From 6e7e902ed6382282843fcaedd8753c325ef713d1 Mon Sep 17 00:00:00 2001 From: Jorge Marey Date: Mon, 1 Apr 2019 18:38:00 +0200 Subject: [PATCH 01/35] Fix approle_secret-id exists return --- vault/resource_approle_auth_backend_role_secret_id.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/resource_approle_auth_backend_role_secret_id.go b/vault/resource_approle_auth_backend_role_secret_id.go index 8309f5350..c3fa51202 100644 --- a/vault/resource_approle_auth_backend_role_secret_id.go +++ b/vault/resource_approle_auth_backend_role_secret_id.go @@ -238,7 +238,7 @@ func approleAuthBackendRoleSecretIDExists(d *schema.ResourceData, meta interface if err != nil { // We need to check if the secret_id has expired if util.IsExpiredTokenErr(err) { - return true, nil + return false, nil } return true, fmt.Errorf("error checking if AppRole auth backend role SecretID %q exists: %s", id, err) } From 1722d640e2dfb4ba0b3826de184d352f056a5af1 Mon Sep 17 00:00:00 2001 From: Cameron Davison Date: Wed, 3 Apr 2019 15:18:37 -0500 Subject: [PATCH 02/35] update documentation import for github auth backend --- website/docs/r/github_auth_backend.html.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/github_auth_backend.html.md b/website/docs/r/github_auth_backend.html.md index 7ebc5d8be..6f29fabf3 100644 --- a/website/docs/r/github_auth_backend.html.md +++ b/website/docs/r/github_auth_backend.html.md @@ -74,5 +74,5 @@ In addition to all arguments above, the following attributes are exported: Github authentication mounts can be imported using the `path`, e.g. ``` -$ terraform import vault_github_auth_backend_role.example auth/github +$ terraform import vault_github_auth_backend.example github ``` From 45221deee3e3d8f6783be3e910d9d6d36a6e9c3d Mon Sep 17 00:00:00 2001 From: Lucy Davinhart Date: Fri, 5 Apr 2019 17:00:18 +0100 Subject: [PATCH 03/35] Allow importing for vault_ldap_auth resources Fixes https://github.com/terraform-providers/terraform-provider-vault/issues/383 ``` terraform import -allow-missing-config vault_ldap_auth_backend_group.foo auth/ldap/groups/foo vault_ldap_auth_backend_group.foo: Importing from ID "auth/ldap/groups/foo"... vault_ldap_auth_backend_group.foo: Import complete! Imported vault_ldap_auth_backend_group (ID: auth/ldap/groups/foo) vault_ldap_auth_backend_group.foo: Refreshing state... (ID: auth/ldap/groups/foo) Import successful! The resources that were imported are shown above. These resources are now in your Terraform state and will henceforth be managed by Terraform. ``` I've not updated any docs yet, and I've only manually tested `vault_ldap_auth_backend_group` by hand so far, so this still needs docs written and tests added. --- vault/resource_ldap_auth_backend.go | 3 +++ vault/resource_ldap_auth_backend_group.go | 3 +++ vault/resource_ldap_auth_backend_user.go | 3 +++ 3 files changed, 9 insertions(+) diff --git a/vault/resource_ldap_auth_backend.go b/vault/resource_ldap_auth_backend.go index a3e98c5c3..33bc7512c 100644 --- a/vault/resource_ldap_auth_backend.go +++ b/vault/resource_ldap_auth_backend.go @@ -21,6 +21,9 @@ func ldapAuthBackendResource() *schema.Resource { Read: ldapAuthBackendRead, Delete: ldapAuthBackendDelete, Exists: ldapAuthBackendExists, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "url": { diff --git a/vault/resource_ldap_auth_backend_group.go b/vault/resource_ldap_auth_backend_group.go index 3fb7f515b..204ca8f5b 100644 --- a/vault/resource_ldap_auth_backend_group.go +++ b/vault/resource_ldap_auth_backend_group.go @@ -19,6 +19,9 @@ func ldapAuthBackendGroupResource() *schema.Resource { Read: ldapAuthBackendGroupResourceRead, Delete: ldapAuthBackendGroupResourceDelete, Exists: ldapAuthBackendGroupResourceExists, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "groupname": { diff --git a/vault/resource_ldap_auth_backend_user.go b/vault/resource_ldap_auth_backend_user.go index d50a62f78..fab4ea46b 100644 --- a/vault/resource_ldap_auth_backend_user.go +++ b/vault/resource_ldap_auth_backend_user.go @@ -19,6 +19,9 @@ func ldapAuthBackendUserResource() *schema.Resource { Read: ldapAuthBackendUserResourceRead, Delete: ldapAuthBackendUserResourceDelete, Exists: ldapAuthBackendUserResourceExists, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "username": { From 151dd46254fdebb73f12e8b30493737feaa9ef14 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Fri, 29 Mar 2019 16:39:11 -0600 Subject: [PATCH 04/35] Add param to configure uri_sans for CSRs --- ...ecret_backend_intermediate_cert_request.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/vault/resource_pki_secret_backend_intermediate_cert_request.go b/vault/resource_pki_secret_backend_intermediate_cert_request.go index 883404ac4..a0238e34b 100644 --- a/vault/resource_pki_secret_backend_intermediate_cert_request.go +++ b/vault/resource_pki_secret_backend_intermediate_cert_request.go @@ -53,6 +53,15 @@ func pkiSecretBackendIntermediateCertRequestResource() *schema.Resource { Type: schema.TypeString, }, }, + "uri_sans": { + Type: schema.TypeList, + Optional: true, + Description: "List of alternative URIs.", + ForceNew: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "other_sans": { Type: schema.TypeList, Optional: true, @@ -181,6 +190,12 @@ func pkiSecretBackendIntermediateCertRequestCreate(d *schema.ResourceData, meta ipSans = append(ipSans, iIpSan.(string)) } + iURISans := d.Get("uri_sans").([]interface{}) + uriSans := make([]string, 0, len(iURISans)) + for _, iUriSan := range iURISans { + uriSans = append(uriSans, iUriSan.(string)) + } + iOtherSans := d.Get("other_sans").([]interface{}) otherSans := make([]string, 0, len(iOtherSans)) for _, iOtherSan := range iOtherSans { @@ -211,6 +226,10 @@ func pkiSecretBackendIntermediateCertRequestCreate(d *schema.ResourceData, meta data["ip_sans"] = strings.Join(ipSans, ",") } + if len(uriSans) > 0 { + data["uri_sans"] = strings.Join(uriSans, ",") + } + if len(otherSans) > 0 { data["other_sans"] = strings.Join(otherSans, ",") } From dd6fab074684f7a7507a78de7636dc7551b0c45f Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Mon, 1 Apr 2019 17:45:23 -0400 Subject: [PATCH 05/35] Add test and docs for uri_sans addition --- ...rce_pki_secret_backend_intermediate_cert_request_test.go | 3 +++ .../r/pki_secret_backend_intermediate_cert_request.html.md | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/vault/resource_pki_secret_backend_intermediate_cert_request_test.go b/vault/resource_pki_secret_backend_intermediate_cert_request_test.go index b413964d5..7ae744bd3 100644 --- a/vault/resource_pki_secret_backend_intermediate_cert_request_test.go +++ b/vault/resource_pki_secret_backend_intermediate_cert_request_test.go @@ -26,6 +26,8 @@ func TestPkiSecretBackendIntermediateCertRequest_basic(t *testing.T) { resource.TestCheckResourceAttr("vault_pki_secret_backend_intermediate_cert_request.test", "backend", path), resource.TestCheckResourceAttr("vault_pki_secret_backend_intermediate_cert_request.test", "type", "internal"), resource.TestCheckResourceAttr("vault_pki_secret_backend_intermediate_cert_request.test", "common_name", "test.my.domain"), + resource.TestCheckResourceAttr("vault_pki_secret_backend_intermediate_cert_request.test", "uri_sans.#", "1"), + resource.TestCheckResourceAttr("vault_pki_secret_backend_intermediate_cert_request.test", "uri_sans.0", "spiffe://test.my.domain"), ), }, }, @@ -69,5 +71,6 @@ resource "vault_pki_secret_backend_intermediate_cert_request" "test" { backend = "${vault_pki_secret_backend.test.path}" type = "internal" common_name = "test.my.domain" + uri_sans = ["spiffe://test.my.domain"] }`, path) } diff --git a/website/docs/r/pki_secret_backend_intermediate_cert_request.html.md b/website/docs/r/pki_secret_backend_intermediate_cert_request.html.md index 5534d1cce..e32821419 100644 --- a/website/docs/r/pki_secret_backend_intermediate_cert_request.html.md +++ b/website/docs/r/pki_secret_backend_intermediate_cert_request.html.md @@ -44,6 +44,8 @@ The following arguments are supported: * `ip_sans` - (Optional) List of alternative IPs +* `uri_sans` - (Optional) List of alternative URIs + * `other_sans` - (Optional) List of other SANs * `format` - (Optional) The format of data @@ -54,8 +56,8 @@ The following arguments are supported: * `key_bits` - (Optional) The number of bits to use -* `exclude_cn_from_sans` - (Optional) Flag to exclude CN from SANs - +* `exclude_cn_from_sans` - (Optional) Flag to exclude CN from SANs + * `ou` - (Optional) The organization unit * `organization` - (Optional) The organization From bd3e43a5f88febaf3eb946908c2999074e0a3805 Mon Sep 17 00:00:00 2001 From: Lucy Davinhart Date: Sat, 6 Apr 2019 17:07:35 +0100 Subject: [PATCH 06/35] Failing tests for LDAP Resource imports Turns out, there's more to it than appeared to be the case from my previous commit. I've not run the full test suite, but only tested the resources I have modified as follows ``` docker run -it --rm -p 8200:8200 vault server -dev -dev-root-token-id="root" VAULT_ADDR=http://0.0.0.0:8200 VAULT_TOKEN=root TF_ACC=1 go test -v --run TestLDAPAuthBackendGroup github.com/terraform-providers/terraform-provider-vault/vault ``` Currently they fail due to, for example: ``` === RUN TestLDAPAuthBackendGroup_import --- FAIL: TestLDAPAuthBackendGroup_import (0.12s) testing.go:538: Step 1 error: ImportStateVerify attributes not equivalent. Difference is shown below. Top is actual, bottom is expected. (map[string]string) { } (map[string]string) (len=2) { (string) (len=7) "backend": (string) (len=39) "tf-test-ldap-backend-392924653340835300", (string) (len=9) "groupname": (string) (len=38) "tf-test-ldap-group-3866433073382041940" } ``` --- .../resource_ldap_auth_backend_group_test.go | 27 ++++++++++++++ vault/resource_ldap_auth_backend_test.go | 21 +++++++++++ vault/resource_ldap_auth_backend_user_test.go | 35 +++++++++++++++++++ 3 files changed, 83 insertions(+) diff --git a/vault/resource_ldap_auth_backend_group_test.go b/vault/resource_ldap_auth_backend_group_test.go index a86a4f6f9..66b4977ed 100644 --- a/vault/resource_ldap_auth_backend_group_test.go +++ b/vault/resource_ldap_auth_backend_group_test.go @@ -14,6 +14,33 @@ import ( "github.com/terraform-providers/terraform-provider-vault/util" ) +func TestLDAPAuthBackendGroup_import(t *testing.T) { + backend := acctest.RandomWithPrefix("tf-test-ldap-backend") + groupname := acctest.RandomWithPrefix("tf-test-ldap-group") + + policies := []string{ + acctest.RandomWithPrefix("policy"), + acctest.RandomWithPrefix("policy"), + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testLDAPAuthBackendGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testLDAPAuthBackendGroupConfig_basic(backend, groupname, policies), + Check: testLDAPAuthBackendGroupCheck_attrs(backend, groupname), + }, + { + ResourceName: "vault_ldap_auth_backend_group.test", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestLDAPAuthBackendGroup_basic(t *testing.T) { backend := acctest.RandomWithPrefix("tf-test-ldap-backend") groupname := acctest.RandomWithPrefix("tf-test-ldap-group") diff --git a/vault/resource_ldap_auth_backend_test.go b/vault/resource_ldap_auth_backend_test.go index 2eaa7c328..3f8c5dfe2 100644 --- a/vault/resource_ldap_auth_backend_test.go +++ b/vault/resource_ldap_auth_backend_test.go @@ -13,6 +13,27 @@ import ( "github.com/hashicorp/vault/api" ) +func TestLDAPAuthBackend_import(t *testing.T) { + path := acctest.RandomWithPrefix("tf-test-ldap-path") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testLDAPAuthBackendDestroy, + Steps: []resource.TestStep{ + { + Config: testLDAPAuthBackendConfig_basic(path), + Check: testLDAPAuthBackendCheck_attrs(path), + }, + { + ResourceName: "vault_ldap_auth_backend.test", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestLDAPAuthBackend_basic(t *testing.T) { path := acctest.RandomWithPrefix("tf-test-ldap-path") diff --git a/vault/resource_ldap_auth_backend_user_test.go b/vault/resource_ldap_auth_backend_user_test.go index 47a558a13..e7adff9c8 100644 --- a/vault/resource_ldap_auth_backend_user_test.go +++ b/vault/resource_ldap_auth_backend_user_test.go @@ -14,6 +14,41 @@ import ( "github.com/terraform-providers/terraform-provider-vault/util" ) +func TestLDAPAuthBackendUser_import(t *testing.T) { + backend := acctest.RandomWithPrefix("tf-test-ldap-backend") + username := acctest.RandomWithPrefix("tf-test-ldap-user") + + policies := []string{ + acctest.RandomWithPrefix("policy"), + acctest.RandomWithPrefix("policy"), + } + + groups := []string{ + acctest.RandomWithPrefix("group"), + acctest.RandomWithPrefix("group"), + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testLDAPAuthBackendUserDestroy, + Steps: []resource.TestStep{ + { + Config: testLDAPAuthBackendUserConfig_basic(backend, username, policies, groups), + Check: resource.ComposeTestCheckFunc( + testLDAPAuthBackendUserCheck_attrs(backend, username), + testLDAPAuthBackendUserCheck_groups(backend, username, groups), + ), + }, + { + ResourceName: "vault_ldap_auth_backend_user.test", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestLDAPAuthBackendUser_basic(t *testing.T) { backend := acctest.RandomWithPrefix("tf-test-ldap-backend") username := acctest.RandomWithPrefix("tf-test-ldap-user") From bc8f3dff1af871ff5d1bce620795cdab8244410f Mon Sep 17 00:00:00 2001 From: Lucy Davinhart Date: Sat, 6 Apr 2019 17:38:23 +0100 Subject: [PATCH 07/35] LDAP Auth resources can now be imported I took inspiration from how AppRoles work, borrowing a lot of the code from there. ``` $ VAULT_ADDR=http://0.0.0.0:8200 VAULT_TOKEN=root TF_ACC=1 go test -v --run TestLDAPAuthBackend github.com/terraform-providers/terraform-provider-vault/vault === RUN TestLDAPAuthBackendGroup_import --- PASS: TestLDAPAuthBackendGroup_import (0.11s) === RUN TestLDAPAuthBackendGroup_basic --- PASS: TestLDAPAuthBackendGroup_basic (0.09s) === RUN TestLDAPAuthBackend_import --- PASS: TestLDAPAuthBackend_import (0.08s) === RUN TestLDAPAuthBackend_basic --- PASS: TestLDAPAuthBackend_basic (0.07s) === RUN TestLDAPAuthBackendUser_import --- PASS: TestLDAPAuthBackendUser_import (0.08s) === RUN TestLDAPAuthBackendUser_basic --- PASS: TestLDAPAuthBackendUser_basic (0.08s) PASS ok github.com/terraform-providers/terraform-provider-vault/vault 0.529s ``` Needed to modify `TestLDAPAuthBackend_import` slightly, as I forgot that `bindpass` isn't returned from the Vault API --- vault/resource_ldap_auth_backend.go | 2 ++ vault/resource_ldap_auth_backend_group.go | 41 +++++++++++++++++++++++ vault/resource_ldap_auth_backend_test.go | 7 ++-- vault/resource_ldap_auth_backend_user.go | 41 +++++++++++++++++++++++ 4 files changed, 88 insertions(+), 3 deletions(-) diff --git a/vault/resource_ldap_auth_backend.go b/vault/resource_ldap_auth_backend.go index 33bc7512c..91c870f36 100644 --- a/vault/resource_ldap_auth_backend.go +++ b/vault/resource_ldap_auth_backend.go @@ -258,6 +258,8 @@ func ldapAuthBackendRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading from Vault: %s", err) } + d.Set("path", path) + authMount := auths[strings.Trim(path, "/")+"/"] if authMount == nil { return fmt.Errorf("auth mount %s not present", path) diff --git a/vault/resource_ldap_auth_backend_group.go b/vault/resource_ldap_auth_backend_group.go index 204ca8f5b..0e50b73d9 100644 --- a/vault/resource_ldap_auth_backend_group.go +++ b/vault/resource_ldap_auth_backend_group.go @@ -3,6 +3,7 @@ package vault import ( "fmt" "log" + "regexp" "strings" "github.com/hashicorp/terraform/helper/schema" @@ -10,6 +11,11 @@ import ( "github.com/hashicorp/vault/api" ) +var ( + ldapAuthBackendGroupBackendFromPathRegex = regexp.MustCompile("^auth/(.+)/groups/.+$") + ldapAuthBackendGroupNameFromPathRegex = regexp.MustCompile("^auth/.+/groups/(.+)$") +) + func ldapAuthBackendGroupResource() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, @@ -84,6 +90,16 @@ func ldapAuthBackendGroupResourceRead(d *schema.ResourceData, meta interface{}) client := meta.(*api.Client) path := d.Id() + backend, err := ldapAuthBackendGroupBackendFromPath(path) + if err != nil { + return fmt.Errorf("invalid path %q for LDAP auth backend group: %s", path, err) + } + + groupname, err := ldapAuthBackendGroupNameFromPath(path) + if err != nil { + return fmt.Errorf("invalid path %q for LDAP auth backend group: %s", path, err) + } + log.Printf("[DEBUG] Reading LDAP group %q", path) resp, err := client.Logical().Read(path) if err != nil { @@ -101,6 +117,9 @@ func ldapAuthBackendGroupResourceRead(d *schema.ResourceData, meta interface{}) schema.NewSet( schema.HashString, resp.Data["policies"].([]interface{}))) + d.Set("backend", backend) + d.Set("groupname", groupname) + return nil } @@ -132,3 +151,25 @@ func ldapAuthBackendGroupResourceExists(d *schema.ResourceData, meta interface{} return resp != nil, nil } + +func ldapAuthBackendGroupNameFromPath(path string) (string, error) { + if !ldapAuthBackendGroupNameFromPathRegex.MatchString(path) { + return "", fmt.Errorf("no group found") + } + res := ldapAuthBackendGroupNameFromPathRegex.FindStringSubmatch(path) + if len(res) != 2 { + return "", fmt.Errorf("unexpected number of matches (%d) for role", len(res)) + } + return res[1], nil +} + +func ldapAuthBackendGroupBackendFromPath(path string) (string, error) { + if !ldapAuthBackendGroupBackendFromPathRegex.MatchString(path) { + return "", fmt.Errorf("no backend found") + } + res := ldapAuthBackendGroupBackendFromPathRegex.FindStringSubmatch(path) + if len(res) != 2 { + return "", fmt.Errorf("unexpected number of matches (%d) for backend", len(res)) + } + return res[1], nil +} diff --git a/vault/resource_ldap_auth_backend_test.go b/vault/resource_ldap_auth_backend_test.go index 3f8c5dfe2..36cbd0beb 100644 --- a/vault/resource_ldap_auth_backend_test.go +++ b/vault/resource_ldap_auth_backend_test.go @@ -26,9 +26,10 @@ func TestLDAPAuthBackend_import(t *testing.T) { Check: testLDAPAuthBackendCheck_attrs(path), }, { - ResourceName: "vault_ldap_auth_backend.test", - ImportState: true, - ImportStateVerify: true, + ResourceName: "vault_ldap_auth_backend.test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"bindpass"}, }, }, }) diff --git a/vault/resource_ldap_auth_backend_user.go b/vault/resource_ldap_auth_backend_user.go index fab4ea46b..093c4bf45 100644 --- a/vault/resource_ldap_auth_backend_user.go +++ b/vault/resource_ldap_auth_backend_user.go @@ -3,6 +3,7 @@ package vault import ( "fmt" "log" + "regexp" "strings" "github.com/hashicorp/terraform/helper/schema" @@ -10,6 +11,11 @@ import ( "github.com/terraform-providers/terraform-provider-vault/util" ) +var ( + ldapAuthBackendUserBackendFromPathRegex = regexp.MustCompile("^auth/(.+)/users/.+$") + ldapAuthBackendUserNameFromPathRegex = regexp.MustCompile("^auth/.+/users/(.+)$") +) + func ldapAuthBackendUserResource() *schema.Resource { return &schema.Resource{ SchemaVersion: 1, @@ -96,6 +102,16 @@ func ldapAuthBackendUserResourceRead(d *schema.ResourceData, meta interface{}) e client := meta.(*api.Client) path := d.Id() + backend, err := ldapAuthBackendUserBackendFromPath(path) + if err != nil { + return fmt.Errorf("invalid path %q for LDAP auth backend user: %s", path, err) + } + + username, err := ldapAuthBackendUserNameFromPath(path) + if err != nil { + return fmt.Errorf("invalid path %q for LDAP auth backend user: %s", path, err) + } + log.Printf("[DEBUG] Reading LDAP user %q", path) resp, err := client.Logical().Read(path) if err != nil { @@ -119,6 +135,9 @@ func ldapAuthBackendUserResourceRead(d *schema.ResourceData, meta interface{}) e } d.Set("groups", groupSet) + d.Set("backend", backend) + d.Set("username", username) + return nil } @@ -150,3 +169,25 @@ func ldapAuthBackendUserResourceExists(d *schema.ResourceData, meta interface{}) return resp != nil, nil } + +func ldapAuthBackendUserNameFromPath(path string) (string, error) { + if !ldapAuthBackendUserNameFromPathRegex.MatchString(path) { + return "", fmt.Errorf("no user found") + } + res := ldapAuthBackendUserNameFromPathRegex.FindStringSubmatch(path) + if len(res) != 2 { + return "", fmt.Errorf("unexpected number of matches (%d) for role", len(res)) + } + return res[1], nil +} + +func ldapAuthBackendUserBackendFromPath(path string) (string, error) { + if !ldapAuthBackendUserBackendFromPathRegex.MatchString(path) { + return "", fmt.Errorf("no backend found") + } + res := ldapAuthBackendUserBackendFromPathRegex.FindStringSubmatch(path) + if len(res) != 2 { + return "", fmt.Errorf("unexpected number of matches (%d) for backend", len(res)) + } + return res[1], nil +} From 612577b0b946961e360c7fd8c9fc3a075a6d0df0 Mon Sep 17 00:00:00 2001 From: Lucy Davinhart Date: Sat, 6 Apr 2019 21:39:04 +0100 Subject: [PATCH 08/35] Update docs for LDAP Auth resource imports --- website/docs/r/ldap_auth_backend.html.md | 8 ++++++++ website/docs/r/ldap_auth_backend_group.html.md | 8 ++++++++ website/docs/r/ldap_auth_backend_user.html.md | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/website/docs/r/ldap_auth_backend.html.md b/website/docs/r/ldap_auth_backend.html.md index 9ce08b54e..eba8f4e88 100644 --- a/website/docs/r/ldap_auth_backend.html.md +++ b/website/docs/r/ldap_auth_backend.html.md @@ -81,3 +81,11 @@ previously stored values. In addition to the fields above, the following attributes are exported: * `accessor` - The accessor for this auth mount. + +## Import + +LDAP authentication backends can be imported using the `path`, e.g. + +``` +$ terraform import vault_ldap_auth_backend.ldap ldap +``` diff --git a/website/docs/r/ldap_auth_backend_group.html.md b/website/docs/r/ldap_auth_backend_group.html.md index 92d5c1724..b675891b5 100644 --- a/website/docs/r/ldap_auth_backend_group.html.md +++ b/website/docs/r/ldap_auth_backend_group.html.md @@ -46,3 +46,11 @@ For more details on the usage of each argument consult the [Vault LDAP API docum ## Attribute Reference No additional attributes are exposed by this resource. + +## Import + +LDAP authentication backend groups can be imported using the `path`, e.g. + +``` +$ terraform import vault_ldap_auth_backend_group.foo auth/ldap/groups/foo +``` diff --git a/website/docs/r/ldap_auth_backend_user.html.md b/website/docs/r/ldap_auth_backend_user.html.md index 53494c0dd..877416593 100644 --- a/website/docs/r/ldap_auth_backend_user.html.md +++ b/website/docs/r/ldap_auth_backend_user.html.md @@ -48,3 +48,11 @@ For more details on the usage of each argument consult the [Vault LDAP API docum ## Attribute Reference No additional attributes are exposed by this resource. + +## Import + +LDAP authentication backend users can be imported using the `path`, e.g. + +``` +$ terraform import vault_ldap_auth_backend_user.foo auth/ldap/users/foo +``` From ad9e5e38328a1588c13d9c884882aa9113c4b46b Mon Sep 17 00:00:00 2001 From: Nick Cabatoff Date: Mon, 8 Apr 2019 15:53:40 -0400 Subject: [PATCH 09/35] Tolerate missing policies in role. Fixes #294. --- vault/resource_jwt_auth_backend_role.go | 5 ++++- vault/resource_jwt_auth_backend_role_test.go | 17 ++--------------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/vault/resource_jwt_auth_backend_role.go b/vault/resource_jwt_auth_backend_role.go index 51e7ed7cf..108684bb5 100644 --- a/vault/resource_jwt_auth_backend_role.go +++ b/vault/resource_jwt_auth_backend_role.go @@ -188,7 +188,10 @@ func jwtAuthBackendRoleRead(d *schema.ResourceData, meta interface{}) error { d.Set("user_claim", resp.Data["user_claim"].(string)) - policies := util.JsonStringArrayToStringArray(resp.Data["policies"].([]interface{})) + policies := make([]string, 0) + if resp.Data["policies"] != nil { + policies = util.JsonStringArrayToStringArray(resp.Data["policies"].([]interface{})) + } err = d.Set("policies", policies) if err != nil { return fmt.Errorf("error setting policies in state: %s", err) diff --git a/vault/resource_jwt_auth_backend_role_test.go b/vault/resource_jwt_auth_backend_role_test.go index 20d8ebea9..57fda8ec8 100644 --- a/vault/resource_jwt_auth_backend_role_test.go +++ b/vault/resource_jwt_auth_backend_role_test.go @@ -85,13 +85,7 @@ func TestAccJWTAuthBackendRole_basic(t *testing.T) { resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", "role_name", role), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.#", "3"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.1971754988", "default"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.232240223", "prod"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.326271447", "dev"), + "policies.#", "0"), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", "ttl", "0"), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", @@ -131,13 +125,7 @@ func TestAccJWTAuthBackendRole_update(t *testing.T) { resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", "role_name", role), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.#", "3"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.1971754988", "default"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.232240223", "prod"), - resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", - "policies.326271447", "dev"), + "policies.#", "0"), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", "ttl", "0"), resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", @@ -368,7 +356,6 @@ resource "vault_jwt_auth_backend_role" "role" { bound_audiences = ["https://myco.test"] user_claim = "https://vault/user" - policies = ["default", "dev", "prod"] }`, backend, role) } From b269941c9b8f71328e529b359abcc6dc7e321b3f Mon Sep 17 00:00:00 2001 From: petems Date: Wed, 10 Apr 2019 15:10:46 +0100 Subject: [PATCH 10/35] Fixes trailing slash issue for namespaces (#390) * Currently the answer from the API returns a trailing slash * Looking in other resources, we validate against having a trailing slash * use `filepath.Clean` to trim trailing slash from API response * Added test to delete resource so test could be run multiple times --- vault/resource_namespace.go | 15 ++++++++++++++- vault/resource_namespace_test.go | 30 +++++++++++++++++++++++++++--- website/docs/r/namespace.html.md | 4 ++-- 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/vault/resource_namespace.go b/vault/resource_namespace.go index 205a12d90..30a659557 100644 --- a/vault/resource_namespace.go +++ b/vault/resource_namespace.go @@ -1,8 +1,11 @@ package vault import ( + "errors" "fmt" "log" + "path/filepath" + "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/vault/api" @@ -23,6 +26,13 @@ func namespaceResource() *schema.Resource { Type: schema.TypeString, Required: true, Description: "Path of the namespace.", + ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { + value := v.(string) + if strings.HasSuffix(value, "/") { + errs = append(errs, errors.New("cannot write to a path ending in '/'")) + } + return + }, }, }, } @@ -70,7 +80,10 @@ func namespaceRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading from Vault: %s", err) } - d.Set("path", resp.Data["path"].(string)) + // remove trailing slash + namespacePath := filepath.Clean(resp.Data["path"].(string)) + + d.Set("path", namespacePath) d.SetId(resp.Data["id"].(string)) return nil diff --git a/vault/resource_namespace_test.go b/vault/resource_namespace_test.go index f349cb392..a27c9c9f9 100644 --- a/vault/resource_namespace_test.go +++ b/vault/resource_namespace_test.go @@ -2,6 +2,7 @@ package vault import ( "fmt" + "regexp" "testing" "os" @@ -9,6 +10,7 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" + "github.com/hashicorp/vault/api" ) func TestNamespace_basic(t *testing.T) { @@ -18,16 +20,22 @@ func TestNamespace_basic(t *testing.T) { t.Skip("TF_ACC_ENTERPRISE is not set, test is applicable only for Enterprise version of Vault") } - namespacePath := acctest.RandomWithPrefix("test-namespace") + "/" + namespacePath := acctest.RandomWithPrefix("test-namespace") resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testProviders, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testNamespaceDestroy(namespacePath), Steps: []resource.TestStep{ { Config: testNamespaceConfig(namespacePath), Check: testNamespaceCheckAttrs(), }, + { + Config: testNamespaceConfig(namespacePath + "/"), + Destroy: false, + ExpectError: regexp.MustCompile("vault_namespace\\.test: cannot write to a path ending in '/'"), + }, }, }) } @@ -48,6 +56,22 @@ func testNamespaceCheckAttrs() resource.TestCheckFunc { } } +func testNamespaceDestroy(path string) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := testProvider.Meta().(*api.Client) + + namespaceRef, err := client.Logical().Read(fmt.Sprintf("/sys/namespaces/%s", path)) + if err != nil { + return fmt.Errorf("error reading back configuration: %s", err) + } + if namespaceRef != nil { + return fmt.Errorf("namespace still exists") + } + + return nil + } +} + func testNamespaceConfig(path string) string { return fmt.Sprintf(` resource "vault_namespace" "test" { diff --git a/website/docs/r/namespace.html.md b/website/docs/r/namespace.html.md index eb6548727..029192e4e 100644 --- a/website/docs/r/namespace.html.md +++ b/website/docs/r/namespace.html.md @@ -16,7 +16,7 @@ Provides a resource to manage [Namespaces](https://www.vaultproject.io/docs/ente ```hcl resource "vault_namespace" "ns1" { - path = "ns1/" + path = "ns1" } ``` @@ -24,7 +24,7 @@ resource "vault_namespace" "ns1" { The following arguments are supported: -* `path` - (Required) The path of the namespace +* `path` - (Required) The path of the namespace. Must not have a trailing `/` ## Attributes Reference From 2c690c5f0468a6f5846d385a7bdabd61cb3b2bec Mon Sep 17 00:00:00 2001 From: petems Date: Wed, 10 Apr 2019 16:24:49 +0100 Subject: [PATCH 11/35] Adds new validator for trailing slashes * new `validateNoTrailingSlash` function * Replaces existing uses * Adds tests for uses --- vault/resource_auth_backend.go | 20 ++++------- vault/resource_jwt_auth_backend.go | 19 ++++------- vault/validators.go | 15 ++++++++ vault/validators_test.go | 55 ++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 27 deletions(-) create mode 100644 vault/validators_test.go diff --git a/vault/resource_auth_backend.go b/vault/resource_auth_backend.go index f8d3e536b..c052ea6d8 100644 --- a/vault/resource_auth_backend.go +++ b/vault/resource_auth_backend.go @@ -1,10 +1,8 @@ package vault import ( - "errors" "fmt" "log" - "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/vault/api" @@ -31,18 +29,12 @@ func authBackendResource() *schema.Resource { }, "path": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - Description: "path to mount the backend. This defaults to the type.", - ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { - value := v.(string) - if strings.HasSuffix(value, "/") { - errs = append(errs, errors.New("cannot write to a path ending in '/'")) - } - return - }, + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + Description: "path to mount the backend. This defaults to the type.", + ValidateFunc: validateNoTrailingSlash, DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return old+"/" == new || new+"/" == old }, diff --git a/vault/resource_jwt_auth_backend.go b/vault/resource_jwt_auth_backend.go index 26f40daf4..24218326a 100644 --- a/vault/resource_jwt_auth_backend.go +++ b/vault/resource_jwt_auth_backend.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "log" - "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/vault/api" @@ -22,18 +21,12 @@ func jwtAuthBackendResource() *schema.Resource { Schema: map[string]*schema.Schema{ "path": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Description: "path to mount the backend", - Default: jwtAuthType, - ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { - value := v.(string) - if strings.HasSuffix(value, "/") { - errs = append(errs, errors.New("cannot write to a path ending in '/'")) - } - return - }, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "path to mount the backend", + Default: jwtAuthType, + ValidateFunc: validateNoTrailingSlash, }, "description": { diff --git a/vault/validators.go b/vault/validators.go index 6dd682822..f918aa873 100644 --- a/vault/validators.go +++ b/vault/validators.go @@ -1,7 +1,9 @@ package vault import ( + "errors" "fmt" + "strings" "time" "github.com/gosimple/slug" @@ -32,3 +34,16 @@ func validateDuration(i interface{}, k string) (s []string, es []error) { } return } + +func validateNoTrailingSlash(i interface{}, k string) (s []string, es []error) { + v, ok := i.(string) + if !ok { + es = append(es, fmt.Errorf("expected type of %s to be string", k)) + return + } + + if strings.HasSuffix(v, "/") { + es = append(es, errors.New("cannot write to a path ending in '/'")) + } + return +} diff --git a/vault/validators_test.go b/vault/validators_test.go new file mode 100644 index 000000000..339de0f85 --- /dev/null +++ b/vault/validators_test.go @@ -0,0 +1,55 @@ +package vault + +import ( + "regexp" + "testing" +) + +func TestValidateNoTrailingSlash(t *testing.T) { + testCases := []struct { + val string + expectedErr *regexp.Regexp + }{ + { + val: "foo", + }, + { + val: "foo/", + expectedErr: regexp.MustCompile(`cannot write to a path ending in '/'`), + }, + { + val: "foo/bar", + }, + { + val: "foo/bar/", + expectedErr: regexp.MustCompile(`cannot write to a path ending in '/'`), + }, + } + + matchErr := func(errs []error, r *regexp.Regexp) bool { + // err must match one provided + for _, err := range errs { + if r.MatchString(err.Error()) { + return true + } + } + + return false + } + + for i, tc := range testCases { + _, errs := validateNoTrailingSlash(tc.val, "test_property") + + if len(errs) == 0 && tc.expectedErr == nil { + continue + } + + if len(errs) != 0 && tc.expectedErr == nil { + t.Fatalf("expected test case %d to produce no errors, got %v", i, errs) + } + + if !matchErr(errs, tc.expectedErr) { + t.Fatalf("expected test case %d to produce error matching \"%s\", got %v", i, tc.expectedErr, errs) + } + } +} From 9da5a50184757b1dde58c837946703da72c2ae3c Mon Sep 17 00:00:00 2001 From: Marcin Wyszynski Date: Fri, 12 Apr 2019 09:16:07 +0200 Subject: [PATCH 12/35] Handle "all policies deleted" corner case --- vault/resource_aws_auth_backend_role.go | 5 ++-- vault/resource_aws_auth_backend_role_test.go | 26 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/vault/resource_aws_auth_backend_role.go b/vault/resource_aws_auth_backend_role.go index 7f3365d51..756353314 100644 --- a/vault/resource_aws_auth_backend_role.go +++ b/vault/resource_aws_auth_backend_role.go @@ -535,9 +535,8 @@ func awsAuthBackendRoleUpdate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("period"); ok { data["period"] = v.(int) } - if len(policies) > 0 { - data["policies"] = policies - } + + data["policies"] = policies if isEc2(authType, inferred) { diff --git a/vault/resource_aws_auth_backend_role_test.go b/vault/resource_aws_auth_backend_role_test.go index 1e0a4839d..d76c4418e 100644 --- a/vault/resource_aws_auth_backend_role_test.go +++ b/vault/resource_aws_auth_backend_role_test.go @@ -181,6 +181,14 @@ func TestAccAWSAuthBackendRole_iamUpdate(t *testing.T) { "policies.1", "dev"), ), }, + { + Config: testAccAWSAuthBackendRoleConfig_DeletePolicies(backend, role), + Check: resource.ComposeTestCheckFunc( + testAccAWSAuthBackendRoleCheck_attrs(backend, role), + resource.TestCheckResourceAttr("vault_aws_auth_backend_role.role", + "policies.#", "0"), + ), + }, }, }) } @@ -412,6 +420,24 @@ resource "vault_aws_auth_backend_role" "role" { }`, backend, role) } +func testAccAWSAuthBackendRoleConfig_DeletePolicies(backend, role string) string { + return fmt.Sprintf(` +resource "vault_auth_backend" "aws" { + type = "aws" + path = "%s" +} +resource "vault_aws_auth_backend_role" "role" { + backend = "${vault_auth_backend.aws.path}" + role = "%s" + auth_type = "iam" + bound_iam_principal_arns = ["arn:aws:iam::123456789012:role/MyRole/*"] + resolve_aws_unique_ids = true + ttl = 30 + max_ttl = 60 + policies = [] +}`, backend, role) +} + func testAccAWSAuthBackendRoleConfig_ec2(backend, role string) string { return fmt.Sprintf(` resource "vault_auth_backend" "aws" { From 005809ddce3ea1d3cb072c7d89b08d7e8425ae0a Mon Sep 17 00:00:00 2001 From: Sergey Trasko Date: Thu, 18 Apr 2019 10:59:19 +0300 Subject: [PATCH 13/35] Support OIDC auth backends --- vault/resource_auth_backend.go | 2 +- vault/resource_jwt_auth_backend.go | 71 +++++++++++++++++--- vault/resource_jwt_auth_backend_role.go | 18 +++++ website/docs/r/jwt_auth_backend.html.md | 49 +++++++++++++- website/docs/r/jwt_auth_backend_role.html.md | 30 ++++++++- 5 files changed, 158 insertions(+), 12 deletions(-) diff --git a/vault/resource_auth_backend.go b/vault/resource_auth_backend.go index f8d3e536b..c69e28746 100644 --- a/vault/resource_auth_backend.go +++ b/vault/resource_auth_backend.go @@ -77,7 +77,7 @@ func authBackendResource() *schema.Resource { Type: schema.TypeString, ForceNew: true, Optional: true, - Description: "Speficies whether to show this mount in the UI-specific listing endpoint", + Description: "Specifies whether to show this mount in the UI-specific listing endpoint", }, "local": { diff --git a/vault/resource_jwt_auth_backend.go b/vault/resource_jwt_auth_backend.go index 26f40daf4..cff4dbffb 100644 --- a/vault/resource_jwt_auth_backend.go +++ b/vault/resource_jwt_auth_backend.go @@ -7,11 +7,10 @@ import ( "strings" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" "github.com/hashicorp/vault/api" ) -var jwtAuthType = "jwt" - func jwtAuthBackendResource() *schema.Resource { return &schema.Resource{ Create: jwtAuthBackendWrite, @@ -26,7 +25,7 @@ func jwtAuthBackendResource() *schema.Resource { Optional: true, ForceNew: true, Description: "path to mount the backend", - Default: jwtAuthType, + Default: "jwt", ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { value := v.(string) if strings.HasSuffix(value, "/") { @@ -36,6 +35,15 @@ func jwtAuthBackendResource() *schema.Resource { }, }, + "type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: "Type of backend. Can be either 'jwt' or 'oidc'", + Default: "jwt", + ValidateFunc: validation.StringInSlice([]string{"jwt", "oidc"}, false), + }, + "description": { Type: schema.TypeString, Required: false, @@ -50,6 +58,19 @@ func jwtAuthBackendResource() *schema.Resource { Description: "The OIDC Discovery URL, without any .well-known component (base path)", }, + "oidc_client_id": { + Type: schema.TypeString, + Optional: true, + Description: "Client ID uses for OIDC", + }, + + "oidc_client_secret": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + Description: "Client Secret uses for OIDC", + }, + "oidc_discovery_ca_pem": { Type: schema.TypeString, Optional: true, @@ -76,11 +97,18 @@ func jwtAuthBackendResource() *schema.Resource { Description: "A list of supported signing algorithms. Defaults to [RS256]", }, + "default_role": { + Type: schema.TypeString, + Optional: true, + Description: "The default role to use if none is provided during login", + }, + "accessor": { Type: schema.TypeString, Computed: true, Description: "The accessor of the JWT auth backend", }, + "tune": authMountTuneSchema(), }, } } @@ -88,7 +116,7 @@ func jwtAuthBackendResource() *schema.Resource { func jwtAuthBackendWrite(d *schema.ResourceData, meta interface{}) error { client := meta.(*api.Client) - authType := jwtAuthType + authType := d.Get("type").(string) desc := d.Get("description").(string) path := getJwtPath(d) @@ -153,7 +181,10 @@ func jwtAuthBackendRead(d *schema.ResourceData, meta interface{}) error { d.Set("accessor", backend.Accessor) d.Set("oidc_discovery_ca_pem", config.Data["oidc_discovery_ca_pem"]) + d.Set("oidc_client_id", config.Data["oidc_client_id"]) + d.Set("oidc_client_secret", config.Data["oidc_client_secret"]) d.Set("bound_issuer", config.Data["bound_issuer"]) + d.Set("default_role", config.Data["default_role"]) d.Set("oidc_discovery_url", config.Data["oidc_discovery_url"]) d.Set("jwt_validation_pubkeys", config.Data["jwt_validation_pubkeys"]) d.Set("jwt_supported_algs", config.Data["jwt_supported_algs"]) @@ -175,7 +206,6 @@ func jwtAuthBackendUpdate(d *schema.ResourceData, meta interface{}) error { oidcDiscoveryUrl, oidcDiscoveryUrlExists := d.GetOk("oidc_discovery_url") jwtValidationPubKeys, jwtValidationPubKeysExists := d.GetOk("jwt_validation_pubkeys") - jwtSupportedAlgs, jwtSupportedAlgsExists := d.GetOk("jwt_supported_algs") if oidcDiscoveryUrlExists == jwtValidationPubKeysExists { return errors.New("exactly one of oidc_discovery_url and jwt_validation_pubkeys should be provided") @@ -189,8 +219,17 @@ func jwtAuthBackendUpdate(d *schema.ResourceData, meta interface{}) error { configuration["jwt_validation_pubkeys"] = jwtValidationPubKeys } - if jwtSupportedAlgsExists { - configuration["jwt_supported_algs"] = jwtSupportedAlgs + if v, ok := d.GetOkExists("jwt_supported_algs"); ok { + configuration["jwt_supported_algs"] = v + } + if v, ok := d.GetOkExists("oidc_client_id"); ok { + configuration["oidc_client_id"] = v.(string) + } + if v, ok := d.GetOkExists("oidc_client_secret"); ok { + configuration["oidc_client_secret"] = v.(string) + } + if v, ok := d.GetOkExists("default_role"); ok { + configuration["default_role"] = v.(string) } _, err := client.Logical().Write(jwtConfigEndpoint(path), configuration) @@ -198,6 +237,22 @@ func jwtAuthBackendUpdate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error updating configuration to Vault for path %s: %s", path, err) } + if d.HasChange("tune") { + log.Printf("[INFO] JWT/OIDC Auth '%q' tune configuration changed", d.Id()) + if raw, ok := d.GetOk("tune"); ok { + backendType := d.Get("type") + log.Printf("[DEBUG] Writing %s auth tune to '%q'", backendType, path) + + err := authMountTune(client, "auth/"+path, raw) + if err != nil { + return nil + } + + log.Printf("[INFO] Written %s auth tune to '%q'", backendType, path) + d.SetPartial("tune") + } + } + return jwtAuthBackendRead(d, meta) } @@ -215,7 +270,7 @@ func getJwtAuthBackendIfPresent(client *api.Client, path string) (*api.AuthMount for authBackendPath, auth := range auths { - if auth.Type == jwtAuthType && authBackendPath == configuredPath { + if authBackendPath == configuredPath { return auth, nil } } diff --git a/vault/resource_jwt_auth_backend_role.go b/vault/resource_jwt_auth_backend_role.go index 51e7ed7cf..e0e756858 100644 --- a/vault/resource_jwt_auth_backend_role.go +++ b/vault/resource_jwt_auth_backend_role.go @@ -63,6 +63,14 @@ func jwtAuthBackendRoleResource() *schema.Resource { }, Description: "Policies to be set on tokens issued using this role.", }, + "allowed_redirect_uris": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Description: "The list of allowed values for redirect_uri during OIDC logins.", + }, "ttl": { Type: schema.TypeInt, Optional: true, @@ -193,6 +201,13 @@ func jwtAuthBackendRoleRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return fmt.Errorf("error setting policies in state: %s", err) } + if resp.Data["allowed_redirect_uris"] != nil { + allowedRedirectUris := util.JsonStringArrayToStringArray(resp.Data["allowed_redirect_uris"].([]interface{})) + err = d.Set("allowed_redirect_uris", allowedRedirectUris) + if err != nil { + return fmt.Errorf("error setting allowed_redirect_uris in state: %s", err) + } + } tokenTTL, err := resp.Data["ttl"].(json.Number).Int64() if err != nil { @@ -340,6 +355,9 @@ func jwtAuthBackendRoleDataToWrite(d *schema.ResourceData) map[string]interface{ if dataList := util.TerraformSetToStringArray(d.Get("policies")); len(dataList) > 0 { data["policies"] = dataList } + if dataList := util.TerraformSetToStringArray(d.Get("allowed_redirect_uris")); len(dataList) > 0 { + data["allowed_redirect_uris"] = dataList + } if v, ok := d.GetOk("role_type"); ok { data["role_type"] = v.(string) diff --git a/website/docs/r/jwt_auth_backend.html.md b/website/docs/r/jwt_auth_backend.html.md index dd3ca07c5..88b37ff05 100644 --- a/website/docs/r/jwt_auth_backend.html.md +++ b/website/docs/r/jwt_auth_backend.html.md @@ -13,6 +13,8 @@ Provides a resource for managing an ## Example Usage +Manage JWT auth backend: + ```hcl resource "vault_jwt_auth_backend" "example" { description = "Demonstration of the Terraform JWT auth backend" @@ -22,16 +24,39 @@ resource "vault_jwt_auth_backend" "example" { } ``` +Manage OIDC auth backend: + +```hcl +resource "vault_jwt_auth_backend" "example" { + description = "Demonstration of the Terraform JWT auth backend" + path = "oidc" + type = "oidc" + oidc_discovery_url = "https://myco.auth0.com/" + oidc_client_id = "1234567890" + oidc_client_secret = "secret123456" + bound_issuer = "https://myco.auth0.com/" + tune = { + listing_visibility = "unauth" + } +} +``` + ## Argument Reference The following arguments are supported: -* `path` - (Required) Path to mount the JWT auth backend +* `path` - (Required) Path to mount the JWT/OIDC auth backend + +* `type` - (Optional) Type of auth backend. Should be one of `jwt` or `oidc`. Default - `jwt` * `description` - (Optional) The description of the auth backend * `oidc_discovery_url` - (Optional) The OIDC Discovery URL, without any .well-known component (base path). Cannot be used in combination with `jwt_validation_pubkeys` +* `oidc_client_id` - (Optional) Client ID used for OIDC backends + +* `oidc_client_secret` - (Optional) Client Secret used for OIDC backends + * `bound_issuer` - (Optional) The value against which to match the iss claim in a JWT * `oidc_discovery_ca_pem` - (Optional) The CA certificate or chain of certificates, in PEM format, to use to validate connections to the OIDC Discovery URL. If not set, system certificates are used @@ -40,6 +65,28 @@ The following arguments are supported: * `jwt_supported_algs` - (Optional) A list of supported signing algorithms. Vault 1.1.0 defaults to [RS256] but future or past versions of Vault may differ +The `tune` block is used to tune the auth backend: + +* `default_lease_ttl` - (Optional) Specifies the default time-to-live. + If set, this overrides the global default. + Must be a valid [duration string](https://golang.org/pkg/time/#ParseDuration) + +* `max_lease_ttl` - (Optional) Specifies the maximum time-to-live. + If set, this overrides the global default. + Must be a valid [duration string](https://golang.org/pkg/time/#ParseDuration) + +* `audit_non_hmac_response_keys` - (Optional) Specifies the list of keys that will + not be HMAC'd by audit devices in the response data object. + +* `audit_non_hmac_request_keys` - (Optional) Specifies the list of keys that will + not be HMAC'd by audit devices in the request data object. + +* `listing_visibility` - (Optional) Specifies whether to show this mount in + the UI-specific listing endpoint. Valid values are "unauth" or "hidden". + +* `passthrough_request_headers` - (Optional) List of headers to whitelist and + pass from the request to the backend. + ## Attributes Reference No additional attributes are exposed by this resource. diff --git a/website/docs/r/jwt_auth_backend_role.html.md b/website/docs/r/jwt_auth_backend_role.html.md index e28c1291a..937e91ed7 100644 --- a/website/docs/r/jwt_auth_backend_role.html.md +++ b/website/docs/r/jwt_auth_backend_role.html.md @@ -3,17 +3,19 @@ layout: "vault" page_title: "Vault: vault_jwt_auth_backend_role resource" sidebar_current: "docs-vault-resource-jwt-auth-backend-role" description: |- - Manages JWT auth backend roles in Vault. + Manages JWT/OIDC auth backend roles in Vault. --- # vault\_jwt\_auth\_backend\_role -Manages an JWT auth backend role in a Vault server. See the [Vault +Manages an JWT/OIDC auth backend role in a Vault server. See the [Vault documentation](https://www.vaultproject.io/docs/auth/jwt.html) for more information. ## Example Usage +Role for JWT backend: + ```hcl resource "vault_jwt_auth_backend" "jwt" { path = "jwt" @@ -26,6 +28,27 @@ resource "vault_jwt_auth_backend_role" "example" { bound_audiences = ["https://myco.test"] user_claim = "https://vault/user" + role_type = "jwt" +} +``` + +Role for OIDC backend: + +```hcl +resource "vault_jwt_auth_backend" "oidc" { + path = "oidc" + default_role = "test-role" +} + +resource "vault_jwt_auth_backend_role" "example" { + backend = "${vault_jwt_auth_backend.oidc.path}" + role_name = "test-role" + policies = ["default", "dev", "prod"] + + bound_audiences = ["https://myco.test"] + user_claim = "https://vault/user" + allowed_redirect_uris = ["http://localhost:8200/ui/vault/auth/oidc/oidc/callback"] + role_type = "oidc" } ``` @@ -84,6 +107,9 @@ The following arguments are supported: * `backend` - (Optional) The unique name of the auth backend to configure. Defaults to `jwt`. +* `allowed_redirect_uris` - (Optional) The list of allowed values for redirect_uri during OIDC logins. + Required for OIDC roles + ## Attributes Reference No additional attributes are exported by this resource. From de666e21eab148079ea8e08485242c3fbc552ab1 Mon Sep 17 00:00:00 2001 From: Jeroen Schepens Date: Tue, 23 Apr 2019 22:59:11 +0200 Subject: [PATCH 14/35] Remove duplicate --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index b5ea10abf..7d192ba02 100644 --- a/.gitignore +++ b/.gitignore @@ -22,7 +22,6 @@ website/node_modules .idea *.iml *.test -*.iml .vscode website/vendor From f3181cd2c0f63dc57d7b5acdc30be24fa6497d5e Mon Sep 17 00:00:00 2001 From: Jeroen Schepens Date: Tue, 23 Apr 2019 22:59:46 +0200 Subject: [PATCH 15/35] Add method --- vault/provider.go | 1 + ...resource_pki_secret_backend_config_urls.go | 137 ++++++++++++++++++ ...rce_pki_secret_backend_config_urls_test.go | 82 +++++++++++ 3 files changed, 220 insertions(+) create mode 100644 vault/resource_pki_secret_backend_config_urls.go create mode 100644 vault/resource_pki_secret_backend_config_urls_test.go diff --git a/vault/provider.go b/vault/provider.go index 800aebda6..248260c53 100644 --- a/vault/provider.go +++ b/vault/provider.go @@ -165,6 +165,7 @@ func Provider() terraform.ResourceProvider { "vault_pki_secret_backend": pkiSecretBackendResource(), "vault_pki_secret_backend_cert": pkiSecretBackendCertResource(), "vault_pki_secret_backend_config_ca": pkiSecretBackendConfigCAResource(), + "vault_pki_secret_backend_config_urls": pkiSecretBackendConfigUrlsResource(), "vault_pki_secret_backend_intermediate_cert_request": pkiSecretBackendIntermediateCertRequestResource(), "vault_pki_secret_backend_intermediate_set_signed": pkiSecretBackendIntermediateSetSignedResource(), "vault_pki_secret_backend_role": pkiSecretBackendRoleResource(), diff --git a/vault/resource_pki_secret_backend_config_urls.go b/vault/resource_pki_secret_backend_config_urls.go new file mode 100644 index 000000000..818949132 --- /dev/null +++ b/vault/resource_pki_secret_backend_config_urls.go @@ -0,0 +1,137 @@ +package vault + +import ( + "fmt" + "log" + "strings" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/vault/api" +) + +func pkiSecretBackendConfigUrlsResource() *schema.Resource { + return &schema.Resource{ + Create: pkiSecretBackendConfigUrlsCreate, + Read: pkiSecretBackendConfigUrlsRead, + Update: pkiSecretBackendConfigUrlsUpdate, + Delete: pkiSecretBackendConfigUrlsDelete, + + Schema: map[string]*schema.Schema{ + "backend": { + Type: schema.TypeString, + Required: true, + Optional: false, + ForceNew: false, + Description: "The path of the PKI secret backend the resource belongs to.", + }, + "issuing_certificates": { + Type: schema.TypeString, + Required: false, + Optional: true, + Description: "Specifies the URL values for the Issuing Certificate field. This can be a comma-separated string list.", + ForceNew: false, + }, + "crl_distribution_points": { + Type: schema.TypeString, + Required: false, + Optional: true, + Description: "Specifies the URL values for the CRL Distribution Points field. This can be a comma-separated string list.", + ForceNew: false, + }, + "ocsp_servers": { + Type: schema.TypeString, + Required: false, + Optional: true, + Description: "Specifies the URL values for the OCSP Servers field. This can be a comma-separated string list.", + ForceNew: false, + }, + }, + } +} + +func pkiSecretBackendConfigUrlsCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + backend := d.Get("backend").(string) + + path := pkiSecretBackendConfigUrlsPath(backend) + + issuingCertificates := d.Get("issuing_certificates").(string) + crlDistributionsPoints := d.Get("crl_distribution_points").(string) + ocspServers := d.Get("ocsp_servers").(string) + + data := map[string]interface{}{ + "issuing_certificates": issuingCertificates, + "crl_distribution_points": crlDistributionsPoints, + "ocsp_servers": ocspServers, + } + + log.Printf("[DEBUG] Creating URL config on PKI secret backend %q", backend) + _, err := client.Logical().Write(path, data) + if err != nil { + return fmt.Errorf("error creating URL config PKI secret backend %q: %s", backend, err) + } + log.Printf("[DEBUG] Created URL config on PKI secret backend %q", backend) + + d.SetId(fmt.Sprintf("%s/config/urls", backend)) + return pkiSecretBackendConfigUrlsRead(d, meta) +} + +func pkiSecretBackendConfigUrlsRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + path := d.Id() + backend := pkiSecretBackendConfigUrlsPath(path) + + log.Printf("[DEBUG] Reading URL config from PKI secret backend %q", backend) + config, err := client.Logical().Read(path) + + if err != nil { + log.Printf("[WARN] Removing path %q its ID is invalid", path) + d.SetId("") + return fmt.Errorf("invalid path ID %q: %s", path, err) + } + + d.Set("issuing_certificates", config.Data["issuing_certificates"]) + d.Set("crl_distribution_points", config.Data["crl_distribution_points"]) + d.Set("ocsp_servers", config.Data["ocsp_servers"]) + + + return nil +} + +func pkiSecretBackendConfigUrlsUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*api.Client) + + backend := d.Id() + + path := pkiSecretBackendConfigUrlsPath(backend) + + issuingCertificates := d.Get("issuing_certificates").(string) + crlDistributionsPoints := d.Get("crl_distribution_points").(string) + ocspServers := d.Get("ocsp_servers").(string) + + data := map[string]interface{}{ + "issuing_certificates": issuingCertificates, + "crl_distribution_points": crlDistributionsPoints, + "ocsp_servers": ocspServers, + } + + log.Printf("[DEBUG] Updating URL config on PKI secret backend %q", backend) + _, err := client.Logical().Write(path, data) + if err != nil { + return fmt.Errorf("error updating URL config for PKI secret backend %q: %s", backend, err) + } + log.Printf("[DEBUG] Updated URL config on PKI secret backend %q", backend) + + return pkiSecretBackendConfigUrlsRead(d, meta) + +} + +func pkiSecretBackendConfigUrlsDelete(d *schema.ResourceData, meta interface{}) error { + return nil +} + +func pkiSecretBackendConfigUrlsPath(backend string) string { + return strings.Trim(backend, "/") + "/config/urls" +} diff --git a/vault/resource_pki_secret_backend_config_urls_test.go b/vault/resource_pki_secret_backend_config_urls_test.go new file mode 100644 index 000000000..f45d8b5b7 --- /dev/null +++ b/vault/resource_pki_secret_backend_config_urls_test.go @@ -0,0 +1,82 @@ +package vault + +import ( + "fmt" + "strconv" + "strings" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/hashicorp/vault/api" +) + +func TestPkiSecretBackendConfigUrls_basic(t *testing.T) { + rootPath := "pki-root-" + strconv.Itoa(acctest.RandInt()) + + issuingCertificates := "http://127.0.0.1:8200/v1/pki/ca" + crlDistributionPoints := "http://127.0.0.1:8200/v1/pki/crl" + ocspServers := "http://127.0.0.1:8200/v1/pki/oscp" + + resource.Test(t, resource.TestCase{ + Providers: testProviders, + PreCheck: func() { testAccPreCheck(t) }, + CheckDestroy: testPkiSecretBackendConfigUrlsDestroy, + Steps: []resource.TestStep{ + { + Config: testPkiSecretBackendCertConfigUrlsConfig_basic(rootPath, issuingCertificates, crlDistributionPoints, ocspServers), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("vault_pki_secret_backend_config_urls.test", "issuing_certificates", issuingCertificates), + resource.TestCheckResourceAttr("vault_pki_secret_backend_config_urls.test", "crl_distribution_points", crlDistributionPoints), + resource.TestCheckResourceAttr("vault_pki_secret_backend_config_urls.test", "ocsp_servers", ocspServers), + ), + }, + }, + }) +} + +func testPkiSecretBackendConfigUrlsDestroy(s *terraform.State) error { + client := testProvider.Meta().(*api.Client) + + mounts, err := client.Sys().ListMounts() + if err != nil { + return err + } + + for _, rs := range s.RootModule().Resources { + if rs.Type != "vault_pki_secret_backend" { + continue + } + for path, mount := range mounts { + path = strings.Trim(path, "/") + rsPath := strings.Trim(rs.Primary.Attributes["path"], "/") + if mount.Type == "pki" && path == rsPath { + return fmt.Errorf("mount %q still exists", path) + } + } + } + return nil +} + +func testPkiSecretBackendCertConfigUrlsConfig_basic(rootPath string, issuingCertificates string, crlDistributionPoints string, ocspServers string) string { + return fmt.Sprintf(` +resource "vault_pki_secret_backend" "test-root" { + path = "%s" + description = "test root" + default_lease_ttl_seconds = "8640000" + max_lease_ttl_seconds = "8640000" +} + +resource "vault_pki_secret_backend_config_urls" "test" { + depends_on = [ "vault_pki_secret_backend.test-root" ] + + backend = "${vault_pki_secret_backend.test-root.path}" + + issuing_certificates = "%s" + crl_distribution_points = "%s" + ocsp_servers = "%s" +} + +`, rootPath, issuingCertificates, crlDistributionPoints, ocspServers) +} From cb57e9880194131a60fe14ff425f9380bf05e146 Mon Sep 17 00:00:00 2001 From: Jeroen Schepens Date: Tue, 23 Apr 2019 23:00:03 +0200 Subject: [PATCH 16/35] Add docs --- .../r/pki_secret_backend_config_urls.html.md | 42 +++++++++++++++++++ website/vault.erb | 4 ++ 2 files changed, 46 insertions(+) create mode 100644 website/docs/r/pki_secret_backend_config_urls.html.md diff --git a/website/docs/r/pki_secret_backend_config_urls.html.md b/website/docs/r/pki_secret_backend_config_urls.html.md new file mode 100644 index 000000000..fce7d4be0 --- /dev/null +++ b/website/docs/r/pki_secret_backend_config_urls.html.md @@ -0,0 +1,42 @@ +--- +layout: "vault" +page_title: "Vault: vault_pki_secret_backend_config_urls resource" +sidebar_current: "docs-vault-resource-pki-secret-backend-config-urls" +description: |- + Sets the config URL's on an PKI Secret Backend for Vault. +--- + +# vault\_pki\_secret\_backend\_config\_urls + +Allows setting the issuing certificate endpoints, CRL distribution points, and OCSP server endpoints that will be encoded into issued certificates. + +## Example Usage + +```hcl +resource "vault_pki_secret_backend" "pki" { + path = "%s" + default_lease_ttl_seconds = 3600 + max_lease_ttl_seconds = 86400 +} + +resource "vault_pki_secret_backend_config_urls" "config_urls" { + backend = "${vault_pki_secret_backend.pki.path}" + issuing_certificates = "http://127.0.0.1:8200/v1/pki/ca" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `backend` - (Required) The path the PKI secret backend is mounted at, with no leading or trailing `/`s. + +* `issuing_certificates` - (Optional) Specifies the URL values for the Issuing Certificate field. Comma-separated string if multiple. + +* `crl_distribution_points` - (Optional) Specifies the URL values for the CRL Distribution Points field. Comma-separated string if multiple. + +* `ocsp_servers` - (Optional) Specifies the URL values for the OCSP Servers field. Comma-separated string if multiple. + +## Attributes Reference + +No additional attributes are exported by this resource. diff --git a/website/vault.erb b/website/vault.erb index f840f8081..d00a8dbdb 100644 --- a/website/vault.erb +++ b/website/vault.erb @@ -223,6 +223,10 @@ vault_pki_secret_backend_config_ca + > + vault_pki_secret_backend_config_urls + + > vault_pki_secret_backend_intermediate_cert_request From 04822f8236ce73084bb40817ecd5cb848b82282c Mon Sep 17 00:00:00 2001 From: Jeroen Schepens Date: Tue, 23 Apr 2019 23:11:34 +0200 Subject: [PATCH 17/35] go fmt error --- vault/resource_pki_secret_backend_config_urls.go | 1 - 1 file changed, 1 deletion(-) diff --git a/vault/resource_pki_secret_backend_config_urls.go b/vault/resource_pki_secret_backend_config_urls.go index 818949132..ab58a0c8e 100644 --- a/vault/resource_pki_secret_backend_config_urls.go +++ b/vault/resource_pki_secret_backend_config_urls.go @@ -96,7 +96,6 @@ func pkiSecretBackendConfigUrlsRead(d *schema.ResourceData, meta interface{}) er d.Set("crl_distribution_points", config.Data["crl_distribution_points"]) d.Set("ocsp_servers", config.Data["ocsp_servers"]) - return nil } From fc042c6de0931e77c684d1bc34ce63ccc5ad80ae Mon Sep 17 00:00:00 2001 From: Becca Petrin Date: Wed, 24 Apr 2019 15:44:09 -0700 Subject: [PATCH 18/35] switch to circleci --- .circleci/config.yml | 14 ++++++++++++++ .travis.yml | 35 ----------------------------------- 2 files changed, 14 insertions(+), 35 deletions(-) create mode 100644 .circleci/config.yml delete mode 100644 .travis.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 000000000..6acd654f1 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,14 @@ +version: 2 +jobs: + build: + docker: + - image: circleci/golang:1.11 + working_directory: /go/src/github.com/terraform-providers/terraform-provider-vault + steps: + - checkout + - run: + name: "Run Tests" + command: go test -v ./... + - run: + name: "Run Build" + command: go build \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b82849874..000000000 --- a/.travis.yml +++ /dev/null @@ -1,35 +0,0 @@ -dist: trusty -sudo: required -services: -- docker -go_import_path: github.com/terraform-providers/terraform-provider-vault -language: go -go: - - "1.11.x" -install: -- bash scripts/gogetcookie.sh -- go get github.com/kardianos/govendor -script: -- docker-compose up -d -- | - until $(curl --output /dev/null --silent --head --fail http://localhost:8200) - do - printf '.' - sleep 1 - done -- source .test-env -- make test -- make testacc -- make vendor-status -- make vet -- make website-test -branches: - only: - - master -matrix: - fast_finish: true - allow_failures: - - go: tip -notifications: - slack: - secure: 3HTR1F2l3Gf+lZgI0p3XYNlu20oZCjK/Q2esv3eFRZe/0l7suuHSovWADGMXflWNGEQe2pHeLpQEELl142bZ2FjYMkZQn2RXfWEuwTOyjMQdlNRzsh0Tm4XiPJqWMYr0NL0cNNXbePQSV+ap3Me8XB6ret5+mkDJGSlI0cStzmmt6pJiVdZ3kq8iu2CnqR11pEgC+v2plGF8OEEca1ixOJF5bRQ2fBQbl6KA81TvE25t1qM5brdT3NzNqZMLtUcHOFoQgsS5Ot5ymQL1HJGatMABAgwmNyUsCcMaBOsdf1qfCAwHC8q8Vpt4RORxY5Rrc0kuWLgKrblHVmJ3uzq+U/XM7rAY3eVKgFm+ZFfyLHQ0Yowpe1jTPGCM3RYVnaDZukf7J39w+958B4xl7NYcK6Sux9q4U1f7k/OTXRHyYmmHSvlZPXjq6+65BEaAEXisy2HvNVqflcXv0n6WqAKwT5vp+xZdd/dc06nCROysc0M9duSm19VOkjIfHlXQLcXlc36tp48S1v8PMNVO2P2Bwh06rRFtPhWXYPYXzeN8g+Fv9dLeHaBj3kEbbtDTsMIYu5cyofQDiphQDCH4/Z/1rjbLhXAVuL/bk8XNwxPsVW90Jh4aZN4B1+tZIT2io3IsxlqUcPvXqtin8B4uVc7850VQSEgK/3HJrPZZrhXmxl0= From fc996171223d7e20433c310705fd889838906f65 Mon Sep 17 00:00:00 2001 From: Sergey Trasko Date: Thu, 25 Apr 2019 11:30:27 +0300 Subject: [PATCH 19/35] Code review fixes (typos) --- vault/resource_jwt_auth_backend.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vault/resource_jwt_auth_backend.go b/vault/resource_jwt_auth_backend.go index cff4dbffb..8185556ee 100644 --- a/vault/resource_jwt_auth_backend.go +++ b/vault/resource_jwt_auth_backend.go @@ -61,14 +61,14 @@ func jwtAuthBackendResource() *schema.Resource { "oidc_client_id": { Type: schema.TypeString, Optional: true, - Description: "Client ID uses for OIDC", + Description: "Client ID used for OIDC", }, "oidc_client_secret": { Type: schema.TypeString, Optional: true, Sensitive: true, - Description: "Client Secret uses for OIDC", + Description: "Client Secret used for OIDC", }, "oidc_discovery_ca_pem": { From 88731ba6dde24fa1cbcc565ba08145bfa5cfbcd6 Mon Sep 17 00:00:00 2001 From: Julien Pivotto Date: Sat, 27 Apr 2019 22:27:52 +0200 Subject: [PATCH 20/35] docs: Add missing GCP resources in menu Signed-off-by: Julien Pivotto --- website/vault.erb | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/website/vault.erb b/website/vault.erb index f840f8081..d49e3cbb1 100644 --- a/website/vault.erb +++ b/website/vault.erb @@ -123,18 +123,26 @@ vault_database_secret_backend_role - > - vault_gcp_auth_backend_role + > + vault_gcp_auth_backend - > - vault_generic_endpoint + > + vault_gcp_auth_backend_role > vault_gcp_secret_backend + > + vault_gcp_secret_roleset + + + > + vault_generic_endpoint + + > vault_generic_secret From afc5d1cff3365441a90a93c690a0808822d4857b Mon Sep 17 00:00:00 2001 From: Sergey Trasko Date: Mon, 29 Apr 2019 16:35:21 +0300 Subject: [PATCH 21/35] Added support for bound_claims, claim_mappings and oidc_scopes --- vault/resource_jwt_auth_backend_role.go | 48 ++++++++ vault/resource_jwt_auth_backend_role_test.go | 116 ++++++++++++++++++- vault/resource_jwt_auth_backend_test.go | 44 +++++++ website/docs/r/jwt_auth_backend_role.html.md | 9 ++ 4 files changed, 215 insertions(+), 2 deletions(-) diff --git a/vault/resource_jwt_auth_backend_role.go b/vault/resource_jwt_auth_backend_role.go index e0e756858..71f807f08 100644 --- a/vault/resource_jwt_auth_backend_role.go +++ b/vault/resource_jwt_auth_backend_role.go @@ -106,6 +106,24 @@ func jwtAuthBackendRoleResource() *schema.Resource { Type: schema.TypeString, }, }, + "oidc_scopes": { + Type: schema.TypeSet, + Optional: true, + Description: "List of OIDC scopes to be used with an OIDC role. The standard scope \"openid\" is automatically included and need not be specified", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "bound_claims": { + Type: schema.TypeMap, + Optional: true, + Description: "Map of claims/values to match against. The expected value may be a single string or a list of strings.", + }, + "claim_mappings": { + Type: schema.TypeMap, + Optional: true, + Description: "Map of claims (keys) to be copied to specified metadata fields (values).", + }, "groups_claim": { Type: schema.TypeString, Optional: true, @@ -246,6 +264,24 @@ func jwtAuthBackendRoleRead(d *schema.ResourceData, meta interface{}) error { d.Set("bound_cidrs", make([]string, 0)) } + if resp.Data["oidc_scopes"] != nil { + cidrs := util.JsonStringArrayToStringArray(resp.Data["oidc_scopes"].([]interface{})) + err = d.Set("oidc_scopes", cidrs) + if err != nil { + return fmt.Errorf("error setting oidc_scopes in state: %s", err) + } + } else { + d.Set("oidc_scopes", make([]string, 0)) + } + + if resp.Data["bound_claims"] != nil { + d.Set("bound_claims", resp.Data["bound_claims"]) + } + + if resp.Data["claim_mappings"] != nil { + d.Set("claim_mappings", resp.Data["claim_mappings"]) + } + d.Set("groups_claim", resp.Data["groups_claim"].(string)) if resp.Data["groups_claim_delimiter_pattern"] != nil { d.Set("groups_claim_delimiter_pattern", resp.Data["groups_claim_delimiter_pattern"].(string)) @@ -383,6 +419,18 @@ func jwtAuthBackendRoleDataToWrite(d *schema.ResourceData) map[string]interface{ data["bound_cidrs"] = dataList } + if dataList := util.TerraformSetToStringArray(d.Get("oidc_scopes")); len(dataList) > 0 { + data["oidc_scopes"] = dataList + } + + if v, ok := d.GetOk("bound_claims"); ok { + data["bound_claims"] = v + } + + if v, ok := d.GetOk("claim_mappings"); ok { + data["claim_mappings"] = v + } + if v, ok := d.GetOkExists("groups_claim"); ok { data["groups_claim"] = v.(string) } diff --git a/vault/resource_jwt_auth_backend_role_test.go b/vault/resource_jwt_auth_backend_role_test.go index 20d8ebea9..7f68bf833 100644 --- a/vault/resource_jwt_auth_backend_role_test.go +++ b/vault/resource_jwt_auth_backend_role_test.go @@ -243,6 +243,76 @@ func TestAccJWTAuthBackendRole_full(t *testing.T) { }) } +func TestAccJWTAuthBackendRoleOIDC_full(t *testing.T) { + backend := acctest.RandomWithPrefix("oidc") + role := acctest.RandomWithPrefix("test-role") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testAccCheckJWTAuthBackendRoleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccJWTAuthBackendRoleConfigOIDC_full(backend, role), + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "backend", backend), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "role_name", role), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "policies.#", "3"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "policies.1971754988", "default"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "policies.232240223", "prod"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "policies.326271447", "dev"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "ttl", "3600"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "max_ttl", "7200"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "num_uses", "12"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "period", "0"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_cidrs.#", "2"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_cidrs.1709552943", "10.148.0.0/20"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_cidrs.838827017", "10.150.0.0/20"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_subject", "sl29dlldsfj3uECzsU3Sbmh0F29Fios1@client"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_audiences.#", "1"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_audiences.2478800941", "https://myco.test"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "user_claim", "https://vault/user"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "groups_claim", "https://vault/groups"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "allowed_redirect_uris.#", "1"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "allowed_redirect_uris.4240710842", "http://localhost:8080"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_claims.%", "2"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_claims.department", "engineering"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "bound_claims.sector", "7g"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "claim_mappings.%", "2"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "claim_mappings.group", "group"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend_role.role", + "claim_mappings.preferred_language", "language"), + ), + }, + }, + }) +} + func TestAccJWTAuthBackendRole_fullUpdate(t *testing.T) { backend := acctest.RandomWithPrefix("jwt") role := acctest.RandomWithPrefix("test-role") @@ -399,8 +469,42 @@ resource "vault_auth_backend" "jwt" { resource "vault_jwt_auth_backend_role" "role" { backend = "${vault_auth_backend.jwt.path}" - role_name = "%s" - role_type = "jwt" + role_name = "%s" + role_type = "jwt" + + bound_subject = "sl29dlldsfj3uECzsU3Sbmh0F29Fios1@client" + bound_cidrs = ["10.148.0.0/20", "10.150.0.0/20"] + bound_audiences = ["https://myco.test"] + user_claim = "https://vault/user" + groups_claim = "https://vault/groups" + policies = ["default", "dev", "prod"] + ttl = 3600 + num_uses = 12 + max_ttl = 7200 +}`, backend, role) +} + +func testAccJWTAuthBackendRoleConfigOIDC_full(backend, role string) string { + return fmt.Sprintf(` +resource "vault_jwt_auth_backend" "jwt" { + type = "oidc" + path = "%s" + oidc_discovery_url = "https://myco.auth0.com/" + oidc_client_id = "client" + oidc_client_secret = "secret" + lifecycle = { + ignore_changes = [ + # Ignore changes to odic_clie_secret inside the tests + "oidc_client_secret" + ] + } +} + +resource "vault_jwt_auth_backend_role" "role" { + backend = "${vault_jwt_auth_backend.jwt.path}" + role_name = "%s" + role_type = "oidc" + allowed_redirect_uris = ["http://localhost:8080"] bound_subject = "sl29dlldsfj3uECzsU3Sbmh0F29Fios1@client" bound_cidrs = ["10.148.0.0/20", "10.150.0.0/20"] @@ -411,6 +515,14 @@ resource "vault_jwt_auth_backend_role" "role" { ttl = 3600 num_uses = 12 max_ttl = 7200 + bound_claims = { + department = "engineering", + sector = "7g" + } + claim_mappings = { + preferred_language = "language", + group = "group" + } }`, backend, role) } diff --git a/vault/resource_jwt_auth_backend_test.go b/vault/resource_jwt_auth_backend_test.go index db2481533..fd043a919 100644 --- a/vault/resource_jwt_auth_backend_test.go +++ b/vault/resource_jwt_auth_backend_test.go @@ -25,6 +25,7 @@ func TestAccJWTAuthBackend(t *testing.T) { resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "path", path), resource.TestCheckResourceAttrSet("vault_jwt_auth_backend.jwt", "accessor"), resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "bound_issuer", ""), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "type", "jwt"), ), }, { @@ -33,6 +34,7 @@ func TestAccJWTAuthBackend(t *testing.T) { resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "oidc_discovery_url", "https://myco.auth0.com/"), resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "bound_issuer", "api://default"), resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "jwt_supported_algs.#", "1"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "type", "jwt"), ), }, { @@ -41,6 +43,27 @@ func TestAccJWTAuthBackend(t *testing.T) { resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "oidc_discovery_url", "https://myco.auth0.com/"), resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "bound_issuer", "api://default"), resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "jwt_supported_algs.#", "2"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.jwt", "type", "jwt"), + ), + }, + }, + }) +} +func TestAccJWTAuthBackend_OIDC(t *testing.T) { + path := acctest.RandomWithPrefix("oidc") + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testProviders, + CheckDestroy: testJWTAuthBackend_Destroyed(path), + Steps: []resource.TestStep{ + { + Config: testAccJWTAuthBackendConfigOIDC(path), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("vault_jwt_auth_backend.oidc", "oidc_discovery_url", "https://myco.auth0.com/"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.oidc", "bound_issuer", "api://default"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.oidc", "oidc_client_id", "client"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.oidc", "type", "oidc"), + resource.TestCheckResourceAttr("vault_jwt_auth_backend.oidc", "default_role", "api"), ), }, }, @@ -90,6 +113,27 @@ resource "vault_jwt_auth_backend" "jwt" { `, oidcDiscoveryUrl, validationPublicKeys, boundIssuer, supportedAlgs, path) } +func testAccJWTAuthBackendConfigOIDC(path string) string { + return fmt.Sprintf(` +resource "vault_jwt_auth_backend" "oidc" { + description = "OIDC backend" + oidc_discovery_url = "https://myco.auth0.com/" + oidc_client_id = "client" + oidc_client_secret = "secret" + bound_issuer = "api://default" + path = "%s" + type = "oidc" + default_role = "api" + lifecycle = { + ignore_changes = [ + # Ignore changes to odic_clie_secret inside the tests + "oidc_client_secret" + ] + } +} +`, path) +} + func testJWTAuthBackend_Destroyed(path string) resource.TestCheckFunc { return func(s *terraform.State) error { diff --git a/website/docs/r/jwt_auth_backend_role.html.md b/website/docs/r/jwt_auth_backend_role.html.md index 937e91ed7..bde5551d6 100644 --- a/website/docs/r/jwt_auth_backend_role.html.md +++ b/website/docs/r/jwt_auth_backend_role.html.md @@ -89,6 +89,15 @@ The following arguments are supported: address for login requests. This value is also encoded into any resulting token. +* `bound_claims` - (Optional) If set, a map of claims/values to match against. + The expected value may be a single string or a list of strings. + +* `claim_mappings` - (Optional) If set, a map of claims (keys) to be copied + to specified metadata fields (values). + +* `oidc_scopes` - (Optional) If set, a list of OIDC scopes to be used with an OIDC role. + The standard scope "openid" is automatically included and need not be specified. + * `groups_claim` - (Optional) The claim to use to uniquely identify the set of groups to which the user belongs; this will be used as the names for the Identity group aliases created due to a successful login. The claim From 35c6291d378ec591a8eceec928f478a541acd230 Mon Sep 17 00:00:00 2001 From: petems Date: Mon, 29 Apr 2019 20:31:25 +0100 Subject: [PATCH 22/35] Refactors namespace to use validateFunc --- vault/resource_namespace.go | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/vault/resource_namespace.go b/vault/resource_namespace.go index 30a659557..30f3365b4 100644 --- a/vault/resource_namespace.go +++ b/vault/resource_namespace.go @@ -1,11 +1,9 @@ package vault import ( - "errors" "fmt" "log" "path/filepath" - "strings" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/vault/api" @@ -23,16 +21,10 @@ func namespaceResource() *schema.Resource { Schema: map[string]*schema.Schema{ "path": { - Type: schema.TypeString, - Required: true, - Description: "Path of the namespace.", - ValidateFunc: func(v interface{}, k string) (ws []string, errs []error) { - value := v.(string) - if strings.HasSuffix(value, "/") { - errs = append(errs, errors.New("cannot write to a path ending in '/'")) - } - return - }, + Type: schema.TypeString, + Required: true, + Description: "Path of the namespace.", + ValidateFunc: validateNoTrailingSlash, }, }, } From 8d2a86cf55a659ce0254d2ff5da38c07d5d35aa6 Mon Sep 17 00:00:00 2001 From: Becca Petrin Date: Tue, 30 Apr 2019 14:33:46 -0700 Subject: [PATCH 23/35] switch to go modules --- go.mod | 82 +++ go.sum | 535 +++++++++++++++ vendor/vendor.json | 1622 -------------------------------------------- 3 files changed, 617 insertions(+), 1622 deletions(-) create mode 100644 go.mod create mode 100644 go.sum delete mode 100644 vendor/vendor.json diff --git a/go.mod b/go.mod new file mode 100644 index 000000000..d7144f1dd --- /dev/null +++ b/go.mod @@ -0,0 +1,82 @@ +module github.com/terraform-providers/terraform-provider-vault + +go 1.12 + +require ( + cloud.google.com/go v0.36.0 + github.com/agext/levenshtein v1.2.2 + github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427 + github.com/apparentlymart/go-rundeck-api v0.0.0-20160826143032-f6af74d34d1e + github.com/apparentlymart/go-textseg v1.0.0 + github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc + github.com/aws/aws-sdk-go v1.16.36 + github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d + github.com/bgentry/speakeasy v0.1.0 + github.com/blang/semver v3.5.1+incompatible + github.com/coreos/etcd v3.3.12+incompatible // indirect + github.com/davecgh/go-spew v1.1.1 + github.com/fatih/structs v1.0.0 + github.com/fsouza/go-dockerclient v0.0.0-20160427172547-1d4f4ae73768 + github.com/go-ini/ini v1.23.1 + github.com/golang/protobuf v1.2.0 + github.com/google/go-cmp v0.2.0 + github.com/googleapis/gax-go v2.0.0+incompatible + github.com/googleapis/gax-go/v2 v2.0.4 // indirect + github.com/gorilla/websocket v1.4.0 // indirect + github.com/gosimple/slug v1.4.1 + github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 // indirect + github.com/grpc-ecosystem/grpc-gateway v1.6.2 // indirect + github.com/hashicorp/errwrap v1.0.0 + github.com/hashicorp/go-cleanhttp v0.5.0 + github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6 + github.com/hashicorp/go-multierror v1.0.0 + github.com/hashicorp/go-plugin v1.0.0 + github.com/hashicorp/go-retryablehttp v0.5.1 + github.com/hashicorp/go-rootcerts v0.0.0-20160503143440-6bb64b370b90 + github.com/hashicorp/go-safetemp v1.0.0 + github.com/hashicorp/go-uuid v1.0.0 + github.com/hashicorp/go-version v1.1.0 + github.com/hashicorp/golang-lru v0.5.1 + github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f + github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260 + github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 + github.com/hashicorp/logutils v0.0.0-20150609070431-0dc08b1671f3 + github.com/hashicorp/terraform v0.0.0-20190329073242-44702fa6c163 + github.com/hashicorp/vault v0.11.1 + github.com/hashicorp/vault-plugin-auth-jwt v0.0.0-20190128234440-a608a5ad1c24 + github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb + github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af + github.com/mattn/go-isatty v0.0.4 + github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5 + github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3 + github.com/mitchellh/go-homedir v1.0.0 + github.com/mitchellh/go-wordwrap v1.0.0 + github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5 + github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49 + github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc + github.com/posener/complete v0.0.0-20171219111128-6bee943216c8 + github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be + github.com/rancher/go-rancher v0.0.0-20170407040943-ec24b7f12fca + github.com/ryanuber/go-glob v1.0.0 // indirect + github.com/spf13/cobra v0.0.3 // indirect + github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect + github.com/ulikunitz/xz v0.5.6 + github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329 + go.opencensus.io v0.19.2 + go.uber.org/atomic v1.3.2 // indirect + go.uber.org/multierr v1.1.0 // indirect + go.uber.org/zap v1.10.0 // indirect + golang.org/x/build v0.0.0-20190314133821-5284462c4bec // indirect + golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 + golang.org/x/exp v0.0.0-20190221220918-438050ddec5e // indirect + golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect + golang.org/x/net v0.0.0-20190328230028-74de082e2cca + golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914 + golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a + golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 + golang.org/x/time v0.0.0-20181108054448-85acf8d2951c + google.golang.org/api v0.3.0 + google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d + google.golang.org/grpc v1.19.0 + k8s.io/kubernetes v1.6.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..c66e546b6 --- /dev/null +++ b/go.sum @@ -0,0 +1,535 @@ +cloud.google.com/go v0.0.0-20190329192448-408b387e95d4/go.mod h1:CazBHdZ5f7eCE/SsNYXk9Ai3Wa8DlFTWAh20R+L0V0k= +cloud.google.com/go v0.15.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.36.0 h1:+aCSj7tOo2LODWVEuZDZeGCckdt6MlSF+X/rB3wUiS8= +cloud.google.com/go v0.36.0/go.mod h1:RUoy9p/M4ge0HzT8L+SDZ8jg+Q6fth0CiBuhFJpSV40= +dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= +dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= +dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= +dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= +git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +git.apache.org/thrift.git v0.12.0/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= +github.com/Azure/azure-sdk-for-go v10.3.0-beta+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/go-autorest v9.10.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-ntlmssp v0.0.0-20170803034930-c92175d54006/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/ChrisTrenkamp/goxpath v0.0.0-20170625215350-4fe035839290/go.mod h1:nuWgzSkT5PnyOd+272uUmV0dnAnAn42Mk7PiQC5VzN4= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/Unknwon/com v0.0.0-20151008135407-28b053d5a292/go.mod h1:KYCjqMOeHpNuTOiFQU6WEcTG7poCJrUs0YgyHNtn1no= +github.com/abdullin/seq v0.0.0-20160510034733-d5467c17e7af/go.mod h1:5Jv4cbFiHJMsVxt52+i0Ha45fjshj6wxYr1r19tB9bw= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= +github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/agl/ed25519 v0.0.0-20150830182803-278e1ec8e8a6/go.mod h1:WPjqKcmVOxf0XSf3YxCJs6N6AOSrOx3obionmG7T0y0= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/antchfx/xpath v0.0.0-20170728053731-b5c552e1acbd/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNYhvtNk= +github.com/antchfx/xquery v0.0.0-20170730121040-eb8c3c172607/go.mod h1:LzD22aAzDP8/dyiCKFp31He4m2GPjl0AFyzDtZzUu9M= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apparentlymart/go-cidr v0.0.0-20170418151526-7e4b007599d4/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= +github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427 h1:2P/DTyNDU+7qJOB6E5KeIpdc3qcT9IYjyA8hZ9HGz50= +github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= +github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= +github.com/apparentlymart/go-rundeck-api v0.0.0-20160826143032-f6af74d34d1e/go.mod h1:U6OjNHcY3edY04ILn+KNrWZm3j15cPzW7PyjtIQOh1Y= +github.com/apparentlymart/go-textseg v0.0.0-20170531203952-b836f5c4d331/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= +github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-radix v0.0.0-20160115234725-4239b77079c7/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc h1:/WQ8Tr5zbclKWAtvafIcAk/njNpW3gtd22TLLouv+6Q= +github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aws/aws-sdk-go v1.8.34/go.mod h1:ZRmQr0FajVIyZ4ZzBYKG5P3ZqPz9IHG41ZoMu1ADI3k= +github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= +github.com/aws/aws-sdk-go v1.16.36 h1:POeH34ZME++pr7GBGh+ZO6Y5kOwSMQpqp5BGUgooJ6k= +github.com/aws/aws-sdk-go v1.16.36/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= +github.com/bgentry/speakeasy v0.0.0-20161015143505-675b82c74c0e/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/blang/semver v0.0.0-20170202183821-4a1e882c79dc/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= +github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= +github.com/bsm/go-vlq v0.0.0-20150828105119-ec6e8d4f5f4e/go.mod h1:N+BjUcTjSxc2mtRGSCPsat1kze3CUtvJN3/jTXlp29k= +github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= +github.com/chzyer/logex v1.1.11-0.20160617073814-96a4d311aa9b/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20161106042343-c914be64f07d/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20160617131543-bea8f082b6fd/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/coreos/bbolt v1.3.1-coreos.1 h1:crb2YOmpHMVsND8Ug24uvqgL8rUmJlQc+UVfUlMHalc= +github.com/coreos/bbolt v1.3.1-coreos.1/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.2.0-rc.1.0.20170908195435-80aa810309d4+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/etcd v3.3.12+incompatible h1:pAWNwdf7QiT1zfaWyqCtNZQWCLByQyA3JrSQyuYAqnQ= +github.com/coreos/etcd v3.3.12+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.2.0 h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20161114122254-48702e0da86b/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d h1:t5Wuyh53qYyg9eqn4BbnlIT+vmhyww0TatL+zT3uWgI= +github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf h1:CAKfRE2YtTUIjjh1bkBtyYFaUT/WmOqsJjgtihT0vMI= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v0.0.0-20160617170158-f0777076321a h1:pzKxqfSfp4kqrm6jfyVYYkWhf+e1hPRt3rX+Yj/3UBU= +github.com/dgrijalva/jwt-go v0.0.0-20160617170158-f0777076321a/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dnaeon/go-vcr v0.0.0-20170218072653-87d4990451a8/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dylanmei/iso8601 v0.1.0/go.mod h1:w9KhXSgIyROl1DefbMYIE7UVSIvELTbMrCfx+QkYnoQ= +github.com/dylanmei/winrmtest v0.0.0-20170819153634-c2fbb09e6c08/go.mod h1:VBVDFSBXCIW8JaHQpI8lldSKfYaLMzP9oyq6IJ4fhzY= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/structs v1.0.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsouza/go-dockerclient v0.0.0-20160427172547-1d4f4ae73768/go.mod h1:KpcjM623fQYE9MZiTGzKhjfxXAV9wbyX2C1cyRHfhl0= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= +github.com/go-ini/ini v1.23.1/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/protobuf v0.0.0-20170307180453-100ba4e88506/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0 h1:xU6/SpYbvkNYiptHJYEDRseDLvYE7wSqhYYNy0QSUzI= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903 h1:LbsanbbD6LieFkXbj9YNNBupiGHJgFeLpO0j0Fza1h8= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v0.0.0-20190318194812-d3c38a4eb497/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.0.0-20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.1.1-0.20171002171727-8ebdfab36c66/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/googleapis/gax-go v0.0.0-20161107002406-da06d194a00e/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= +github.com/googleapis/gax-go v1.0.2/go.mod h1:v2eZhQtr8ifqA4cZIskVgQZ1FwEN4gDW0C++kU5/H7Y= +github.com/googleapis/gax-go v2.0.0+incompatible h1:j0GKcs05QVmm7yesiZq2+9cxHkNK9YM6zKx4D2qucQU= +github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= +github.com/googleapis/gax-go/v2 v2.0.2/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= +github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= +github.com/googleapis/gax-go/v2 v2.0.4 h1:hU4mGcQI4DaAYW+IbTun+2qEZVFxK0ySjQLTbS0VQKc= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/gophercloud/gophercloud v0.0.0-20190208042652-bc37892e1968/go.mod h1:3WdhXV3rUYy9p6AUW8d94kr+HS62Y4VL9mBnFxsD8q4= +github.com/gophercloud/utils v0.0.0-20190128072930-fbb6ab446f01/go.mod h1:wjDF8z83zTeg5eMLml5EBSlAhbF7G8DobyI1YsMuyzw= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gosimple/slug v1.4.1 h1:h29PRcKc8dPN//lJ9Ib6EKP50kG5AmpJ0yRjn7ksY/8= +github.com/gosimple/slug v1.4.1/go.mod h1:ER78kgg1Mv0NQGlXiDe57DpCyfbNywXXZ9mIorhxAf0= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:Iju5GlWwrvL6UBg4zJJt3btmonfrMlCDdsejg4CZE7c= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v0.0.0-20160910222444-6b7015e65d36 h1:cwTrrTEhz13khQS3/UZMLFWwiqlcsdp/2sxFmSjAWeQ= +github.com/grpc-ecosystem/go-grpc-prometheus v0.0.0-20160910222444-6b7015e65d36/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.2.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/grpc-ecosystem/grpc-gateway v1.6.2 h1:8KyC64BiO8ndiGHY5DlFWWdangUPC9QHPakFRre/Ud0= +github.com/grpc-ecosystem/grpc-gateway v1.6.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/hashicorp/atlas-go v0.0.0-20161107204910-1792bd8de119/go.mod h1:ckHDuH0pxfnmXZkq1niVSguIIV0pA65gifQv3so9llw= +github.com/hashicorp/aws-sdk-go-base v0.3.0/go.mod h1:ZIWACGGi0N7a4DZbf15yuE1JQORmWLtBcVM6F5SXNFU= +github.com/hashicorp/consul v0.0.0-20171026175957-610f3c86a089/go.mod h1:mFrjN1mfidgJfYP1xrJCF+AfRhr6Eaqhb2+sfyn/OOI= +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-checkpoint v0.0.0-20171009173528-1545e56e46de/go.mod h1:xIwEieBHERyEvaeKF/TcHh1Hu+lxPM+n2vT1+g9I4m4= +github.com/hashicorp/go-cleanhttp v0.0.0-20170211013415-3573b8b52aa7/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-getter v0.0.0-20180327010114-90bb99a48d86/go.mod h1:6rdJFnhkXnzGOJbvkrdv4t9nLwKcVA+tmbQeUlkIzrU= +github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6 h1:aOgIQP/0Bk+gfS77dy01FVVVSN712E7amhqOFVKGfJM= +github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6/go.mod h1:/O1k/AizTN0QmfEKknCYGvICeyKUDqCYA8vvWtGWDeQ= +github.com/hashicorp/go-hclog v0.0.0-20170716174523-b4e5765d1e5f/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= +github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd h1:rNuUHR+CvK1IS89MMtcF0EpcVMZtjKfPRp4MEmt/aTs= +github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v0.0.0-20150916205742-d30f09973e19/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= +github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= +github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-plugin v0.0.0-20180125190438-e53f54cbf51e/go.mod h1:JSqWYsict+jzcj0+xElxyrBQRPNoiWQuddnxArJ7XHQ= +github.com/hashicorp/go-plugin v1.0.0 h1:/gQ1sNR8/LHpoxKRQq4PmLBuacfZb4tC93e9B30o/7c= +github.com/hashicorp/go-plugin v1.0.0/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= +github.com/hashicorp/go-retryablehttp v0.0.0-20180718195005-e651d75abec6/go.mod h1:fXcdFsQoipQa7mwORhKad5jmDCeSy/RCGzWA08PO0lM= +github.com/hashicorp/go-retryablehttp v0.5.1 h1:Vsx5XKPqPs3M6sM4U4GWyUqFS8aBiL9U5gkgvpkg4SE= +github.com/hashicorp/go-retryablehttp v0.5.1/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +github.com/hashicorp/go-rootcerts v0.0.0-20160503143440-6bb64b370b90 h1:VBj0QYQ0u2MCJzBfeYXGexnAl17GsH1yidnoxCqqD9E= +github.com/hashicorp/go-rootcerts v0.0.0-20160503143440-6bb64b370b90/go.mod h1:o4zcYY1e0GEZI6eSEr+43QDYmuGglw1qSO6qdHUHCgg= +github.com/hashicorp/go-safetemp v0.0.0-20180326211150-b1a1dbde6fdc/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= +github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= +github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= +github.com/hashicorp/go-slug v0.2.0/go.mod h1:+zDycQOzGqOqMW7Kn2fp9vz/NtqpMLQlgb9JUF+0km4= +github.com/hashicorp/go-sockaddr v1.0.0 h1:GeH6tui99pF4NJgfnhp+L6+FfobzVW3Ah46sLo0ICXs= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-tfe v0.3.11/go.mod h1:LHLchj07PCYgQqcyE5Sz+g4zrMNW+nALKbiSNTZedEs= +github.com/hashicorp/go-uuid v0.0.0-20160120003506-36289988d83c/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= +github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= +github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= +github.com/hashicorp/hcl2 v0.0.0-20180308163058-5f8ed954abd8/go.mod h1:xp1eMAxqhQKBxz+yQUTsig9bBMRRWRWw+rK3FJmHf/A= +github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260 h1:C3vhYEXk8ihs+Xvq093axRyYhfLERrZ6Uv5tfRw9yvw= +github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260/go.mod h1:HtEzazM5AZ9fviNEof8QZB4T1Vz9UhHrGhnMPzl//Ek= +github.com/hashicorp/hil v0.0.0-20170512213305-fac2259da677/go.mod h1:KHvg/R2/dPtaePb16oW4qIyzkMxXOL38xjRN64adsts= +github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 h1:fooK5IvDL/KIsi4LxF/JH68nVdrBSiGNPhS2JAQjtjo= +github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250/go.mod h1:KHvg/R2/dPtaePb16oW4qIyzkMxXOL38xjRN64adsts= +github.com/hashicorp/logutils v0.0.0-20150609070431-0dc08b1671f3 h1:oD64EFjELI9RY9yoWlfua58r+etdnoIC871z+rr6lkA= +github.com/hashicorp/logutils v0.0.0-20150609070431-0dc08b1671f3/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/memberlist v0.0.0-20170208211506-23ad4b7d7b38/go.mod h1:ncdBp14cuox2iFOq3kDiquKU6fqsTBc3W6JvZwjxxsE= +github.com/hashicorp/serf v0.8.2-0.20171022020050-c20a0b1b1ea9/go.mod h1:h/Ru6tmZazX7WO/GDmwdpS975F019L4t5ng5IgwbNrE= +github.com/hashicorp/terraform v0.0.0-20190329073242-44702fa6c163 h1:/KPd7xSeTVUKoEU/DQAfM22A+Oo6tQijaTbNeVNSA4Y= +github.com/hashicorp/terraform v0.0.0-20190329073242-44702fa6c163/go.mod h1:4nGneatZDAadikceacKGdKUcO39b835x+9wWqN4OT0w= +github.com/hashicorp/vault v0.0.0-20161029210149-9a60bf2a50e4/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= +github.com/hashicorp/vault v0.11.1 h1:/t8pGnk5cpzRCq13nj6QlEXdu6meBum9NFlGn5Ma2QE= +github.com/hashicorp/vault v0.11.1/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= +github.com/hashicorp/vault-plugin-auth-jwt v0.0.0-20190128234440-a608a5ad1c24/go.mod h1:j6Xmkj3dzuC63mivquwVVTlxjwDndwNxi4cJUku40J8= +github.com/hashicorp/yamux v0.0.0-20160720233140-d1caa6c97c9f/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= +github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/joyent/triton-go v0.0.0-20180313100802-d8f9c0314926/go.mod h1:U+RSyWxWd04xTqnuOQxnai7XGS2PrPY2cfGoDKtMHjA= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kardianos/osext v0.0.0-20160811001526-c2c54e542fb7/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= +github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba/go.mod h1:ghbZscTyKdM07+Fw3KSi0hcJm+AlEUWj8QLlPtijN/M= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= +github.com/lusis/go-artifactory v0.0.0-20160115162124-7e4ce345df82/go.mod h1:y54tfGmO3NKssKveTEFFzH8C/akrSOy/iW9qEAUDV84= +github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/masterzen/azure-sdk-for-go v0.0.0-20161014135628-ee4f0065d00c/go.mod h1:mf8fjOu33zCqxUjuiU3I8S1lJMyEAlH+0F2+M5xl3hE= +github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= +github.com/masterzen/winrm v0.0.0-20180224160350-7e40f93ae939/go.mod h1:CfZSN7zwz5gJiFhZJz49Uzk7mEBHIceWmbFmYx7Hf7E= +github.com/mattn/go-colorable v0.0.0-20160220075935-9cbef7c35391/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.0-20161123143637-30a891c33c7c/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-shellwords v1.0.1/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/cli v0.0.0-20170908181043-65fcae5817c8/go.mod h1:oGumspjLm2kTyiT1QMGpFqRlmxnKHfCvhZEVnx+5UeE= +github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5 h1:OYr3N2fY3e3kP/x/d81CJXlcZrIV2hH8gPnuRLpiME4= +github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5/go.mod h1:oGumspjLm2kTyiT1QMGpFqRlmxnKHfCvhZEVnx+5UeE= +github.com/mitchellh/colorstring v0.0.0-20150917214807-8631ce90f286/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= +github.com/mitchellh/copystructure v0.0.0-20161013195342-5af94aef99f5/go.mod h1:eOsF2yLPlBBJPvD+nhl5QMTBSOBbOph6N7j/IDUw7PY= +github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3 h1:dECZqiJYhKdj9QlLpiQaRDXHDXRTdiyZI3owdDGhlYY= +github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3/go.mod h1:eOsF2yLPlBBJPvD+nhl5QMTBSOBbOph6N7j/IDUw7PY= +github.com/mitchellh/go-homedir v0.0.0-20161203194507-b8bc1bf76747/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-linereader v0.0.0-20141013185533-07bab5fdd958/go.mod h1:OaY7UOoTkkrX3wRwjpYRKafIkkyeD0UtweSHAWWiqQM= +github.com/mitchellh/go-testing-interface v0.0.0-20170730050907-9a441910b168/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= +github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5 h1:h+4fp6yIoLPf/K2egDK3kvYM2zqb28gJIWWMiDzBdKM= +github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= +github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49 h1:kaWdlw4YogwkDl8CG+/VxhXkrL9uz3n1D9QBC2pEGLE= +github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/panicwrap v0.0.0-20161208170302-ba9e1a65e0f7/go.mod h1:QuAqW7/z+iv6aWFJdrA8kCbsF0OOJVKCICqTcYBexuY= +github.com/mitchellh/prefixedio v0.0.0-20151214002211-6e6954073784/go.mod h1:kB1naBgV9ORnkiTVeyJOI1DavaJkG4oNIq0Af6ZVKUo= +github.com/mitchellh/reflectwalk v0.0.0-20161003174516-92573fe8d000/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc h1:gqYjvctjtX4GHzgfutJxZpvZ7XhGwQLGR5BASwhpO2o= +github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= +github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= +github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= +github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= +github.com/openzipkin/zipkin-go v0.1.3/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/packer-community/winrmcp v0.0.0-20180102160824-81144009af58/go.mod h1:f6Izs6JvFTdnRbziASagjZ2vmf55NSIkC/weStxCHqk= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/errors v0.0.0-20170505043639-c605e284fe17/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v0.0.0-20171104095702-dc2bc5a81acc/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v0.0.0-20171219111128-6bee943216c8 h1:lcb1zvdlaZyEbl2OXifN3uOYYyIvllofUbmp9bwbL+0= +github.com/posener/complete v0.0.0-20171219111128-6bee943216c8/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829 h1:D+CiwcpGTW6pL6bv6KI3KbyEyCKyS+1JWS2h8PNDnGA= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_model v0.0.0-20170216185247-6f3806018612/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f h1:BVwpUVJDADN2ufcGik7W992pyps0wZ888b/y9GXcLTU= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.2.0 h1:kUZDBDTdBVBYBj5Tmh2NZLlF60mfjA27rM34b+cVwNU= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1 h1:/K3IL0Z1quvmJ7X0A1AwNEK7CRkVK3YwfOU/QAL4WGg= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ= +github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q= +github.com/rancher/go-rancher v0.0.0-20170407040943-ec24b7f12fca/go.mod h1:7oQvGNiJsGvrUgB+7AH8bmdzuR0uhULfwKb43Ht0hUk= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/ryanuber/columnize v0.0.0-20161220214920-0fbbb3f0e3fb/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= +github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= +github.com/satori/go.uuid v0.0.0-20160927100844-b061729afc07/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/satori/uuid v0.0.0-20160927100844-b061729afc07/go.mod h1:B8HLsPLik/YNn6KKWVMDJ8nzCL8RP5WyfsnmvnAEwIU= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= +github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= +github.com/shurcooL/github_flavored_markdown v0.0.0-20181002035957-2122de532470/go.mod h1:2dOwnU2uBioM+SGy2aZoq1f/Sd1l9OkAeAUvjSyvgU0= +github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= +github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= +github.com/shurcooL/gofontwoff v0.0.0-20180329035133-29b52fc0a18d/go.mod h1:05UtEgK5zq39gLST6uB0cf3NEHjETfB4Fgr3Gx5R9Vw= +github.com/shurcooL/gopherjslib v0.0.0-20160914041154-feb6d3990c2c/go.mod h1:8d3azKNyqcHP1GaQE/c6dDgjkgSx2BZ4IoEi4F1reUI= +github.com/shurcooL/highlight_diff v0.0.0-20170515013008-09bb4053de1b/go.mod h1:ZpfEhSmds4ytuByIcDnOLkTHGUI6KNqRNPDLHDk+mUU= +github.com/shurcooL/highlight_go v0.0.0-20181028180052-98c3abbbae20/go.mod h1:UDKB5a1T23gOMUJrI+uSuH0VRDStOiUVSjBTRDVBVag= +github.com/shurcooL/home v0.0.0-20181020052607-80b7ffcb30f9/go.mod h1:+rgNQw2P9ARFAs37qieuu7ohDNQ3gds9msbT2yn85sg= +github.com/shurcooL/htmlg v0.0.0-20170918183704-d01228ac9e50/go.mod h1:zPn1wHpTIePGnXSHpsVPWEktKXHr6+SS6x/IKRb7cpw= +github.com/shurcooL/httperror v0.0.0-20170206035902-86b7830d14cc/go.mod h1:aYMfkZ6DWSJPJ6c4Wwz3QtW22G7mf/PEgaB9k/ik5+Y= +github.com/shurcooL/httpfs v0.0.0-20171119174359-809beceb2371/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= +github.com/shurcooL/httpgzip v0.0.0-20180522190206-b1c53ac65af9/go.mod h1:919LwcH0M7/W4fcZ0/jy0qGght1GIhqyS/EgWGH2j5Q= +github.com/shurcooL/issues v0.0.0-20181008053335-6292fdc1e191/go.mod h1:e2qWDig5bLteJ4fwvDAc2NHzqFEthkqn7aOZAOpj+PQ= +github.com/shurcooL/issuesapp v0.0.0-20180602232740-048589ce2241/go.mod h1:NPpHK2TI7iSaM0buivtFUc9offApnI0Alt/K8hcHy0I= +github.com/shurcooL/notifications v0.0.0-20181007000457-627ab5aea122/go.mod h1:b5uSkrEVM1jQUspwbixRBhaIjIzL2xazXp6kntxYle0= +github.com/shurcooL/octicon v0.0.0-20181028054416-fa4f57f9efb2/go.mod h1:eWdoE5JD4R5UVWDucdOPg1g2fqQRq78IQa9zlOV1vpQ= +github.com/shurcooL/reactions v0.0.0-20181006231557-f2e0b4ca5b82/go.mod h1:TCR1lToEk4d2s07G3XGfz2QrgHXg4RJBvjrOozvoWfk= +github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= +github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= +github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= +github.com/soheilhy/cmux v0.1.4 h1:0HKaf1o97UwFjHH9o5XsHUOF+tqmdA7KEzXLpiyaw0E= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= +github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= +github.com/spf13/afero v1.0.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v1.0.2 h1:Fy0orTDgHdbnzHcsOgfCN4LtHf0ec3wwtiwJqwvf3Gc= +github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/svanharmelen/jsonapi v0.0.0-20180618144545-0c0828c3f16d/go.mod h1:BSTlc8jOjh0niykqEGVXOLXdi9o0r0kR8tCYiMvjFgw= +github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= +github.com/terraform-providers/terraform-provider-openstack v1.15.0/go.mod h1:2aQ6n/BtChAl1y2S60vebhyJyZXBsuAI5G4+lHrT1Ew= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 h1:LnC5Kc/wtumK+WB441p7ynQJzVuNRJiqddSIE3IlSEQ= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v0.0.0-20170107133203-ded73eae5db7 h1:BPPUhSq7uU6E9lFzyb81vjwVOhiWwMXp0EpKL75NX+8= +github.com/ugorji/go v0.0.0-20170107133203-ded73eae5db7/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/ulikunitz/xz v0.5.4/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= +github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= +github.com/ulikunitz/xz v0.5.6 h1:jGHAfXawEGZQ3blwU5wnWKQJvAraT7Ftq9EXjnXYgt8= +github.com/ulikunitz/xz v0.5.6/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/xanzy/ssh-agent v0.2.0/go.mod h1:0NyE30eGUDliuLEHJgYte/zncp2zdTStcOnWhgSqHD8= +github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18 h1:MPPkRncZLN9Kh4MEFmbnK4h3BD7AUmskWv2+EeZJCCs= +github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xlab/treeprint v0.0.0-20161029104018-1d6e34225557/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= +github.com/zclconf/go-cty v0.0.0-20180302160414-49fa5e03c418/go.mod h1:LnDKxj8gN4aatfXUqmUNooaDjvmDcLPbAN3hYBIVoJE= +github.com/zclconf/go-cty v0.0.0-20190124225737-a385d646c1e9/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= +github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329 h1:ne520NlvoncW5zfBGkmP4EJhyd6ruSaSyhzobv0Vz9w= +github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= +go.opencensus.io v0.0.0-20190327170659-41e54b832491/go.mod h1:NO/8qkisMZLZ1FCsKNqtJPwc8/TaclWyY0B6wcYNg9M= +go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= +go.opencensus.io v0.19.1/go.mod h1:gug0GbSHa8Pafr0d2urOSgoXHZ6x/RUlaiT0d9pqb4A= +go.opencensus.io v0.19.2 h1:ZZpq6xI6kv/LuE/5s5UQvBU5vMjvRnPb8PvJrIntAnc= +go.opencensus.io v0.19.2/go.mod h1:NO/8qkisMZLZ1FCsKNqtJPwc8/TaclWyY0B6wcYNg9M= +go.uber.org/atomic v1.3.2 h1:2Oa65PReHzfn29GpvgsYwloV9AVFHPDk8tYxt2c2tr4= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= +golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= +golang.org/x/build v0.0.0-20190314133821-5284462c4bec/go.mod h1:atTaCNAy0f16Ah5aV1gMSwgiKVHwu/JncqDpuRr7lS4= +golang.org/x/crypto v0.0.0-20170808112155-b176d7def5d7/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180211211603-9de5f2eaf759/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180816225734-aabede6cba87/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190221220918-438050ddec5e/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181029044818-c44066c5c816/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181106065722-10aee1819953/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181129055619-fae4c4e3ad76/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190328230028-74de082e2cca h1:hyA6yiAgbUwuWqtscNvWAI7U1CtlaD1KilQ6iudt1aI= +golang.org/x/net v0.0.0-20190328230028-74de082e2cca/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20170928010508-bb50c06baba3/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914 h1:jIOcLT9BZzyJ9ce+IwwZ+aF9yeCqzrR+NrD68a/SHKw= +golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026144532-2772b66316d2/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181218192612-074acd46bca6/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.0.0-20180911161511-905a57155faa/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c h1:fqgJT0MGcGpPgpWU7VRdRjuArfcOvC4AoJmILihzhDg= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181219222714-6e267b5cc78e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +google.golang.org/api v0.0.0-20171005000305-7a7376eff6a5/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20181220000619-583d854617af/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= +google.golang.org/api v0.0.0-20190329211119-c30064f755a0/go.mod h1:IuvZyQh8jgscv8qWfQ4ABd8m7hEudgBFM/EdhA3BnXw= +google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= +google.golang.org/api v0.2.0/go.mod h1:IfRCZScioGtypHNTlz3gFk67J8uePVW7uDTBzXuIkhU= +google.golang.org/api v0.3.0 h1:UIJY20OEo3+tK5MBlcdx37kmdH6EnRjGkW78mc6+EeA= +google.golang.org/api v0.3.0/go.mod h1:IuvZyQh8jgscv8qWfQ4ABd8m7hEudgBFM/EdhA3BnXw= +google.golang.org/appengine v0.0.0-20150527042145-b667a5000b08/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20171002232614-f676e0f3ac63/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= +google.golang.org/genproto v0.0.0-20181219182458-5a97ab628bfb/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= +google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d h1:XB2jc5XQ9uhizGTS2vWcN01bc4dI6z3C4KY5MQm8SS8= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v0.0.0-20170809211603-7657092a1303/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v0.0.0-20190327231928-f1437f7cc5fa/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= +google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.0.0-20170407172122-cd8b52f8269e/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20180920025451-e3ad64cb4ed3/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= +k8s.io/kubernetes v1.6.1/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= +sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= +sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/vendor/vendor.json b/vendor/vendor.json deleted file mode 100644 index 506aedb38..000000000 --- a/vendor/vendor.json +++ /dev/null @@ -1,1622 +0,0 @@ -{ - "comment": "", - "ignore": "appengine test github.com/hashicorp/nomad/ github.com/hashicorp/terraform/backend", - "package": [ - { - "checksumSHA1": "b1KgRkWqz0RmrEBK6IJ8kOJva6w=", - "path": "cloud.google.com/go/compute/metadata", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "+S/9jBntS1iHZwxkR64vsy97Gh8=", - "path": "cloud.google.com/go/iam", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "JfGXEtr79UaxukcL05IERkjYm/g=", - "path": "cloud.google.com/go/internal", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "wQ4uGuRwMb24vG16pPQDOOCPkFo=", - "path": "cloud.google.com/go/internal/optional", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "wHU/MO9h3gtNmCfK8O7I0/Ml/8Q=", - "path": "cloud.google.com/go/internal/trace", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "FSifvUBJjm4OsSU5rp5s5+bqvN0=", - "path": "cloud.google.com/go/internal/version", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "KQDPVlJX2uH8gZGS3bXti/q/SYg=", - "path": "cloud.google.com/go/storage", - "revision": "408b387e95d4ba708acd3e2361d56b4aaa3b4cf8", - "revisionTime": "2019-03-29T17:51:08Z" - }, - { - "checksumSHA1": "zNspuz2vG1cIkuAk5mN6zW/99mY=", - "path": "github.com/agext/levenshtein", - "revision": "0ded9c86537917af2ff89bc9c78de6bd58477894", - "revisionTime": "2019-02-22T19:05:28Z" - }, - { - "checksumSHA1": "FIL83loX9V9APvGQIjJpbxq53F0=", - "path": "github.com/apparentlymart/go-cidr/cidr", - "revision": "7e4b007599d4e2076d9a81be723b3912852dda2c", - "revisionTime": "2017-04-18T07:21:50Z" - }, - { - "checksumSHA1": "+2yCNqbcf7VcavAptooQReTGiHY=", - "path": "github.com/apparentlymart/go-rundeck-api", - "revision": "f6af74d34d1ef69a511c59173876fc1174c11f0d", - "revisionTime": "2016-08-26T14:30:32Z" - }, - { - "checksumSHA1": "Ffhtm8iHH7l2ynVVOIGJE3eiuLA=", - "path": "github.com/apparentlymart/go-textseg/textseg", - "revision": "fb01f485ebef760e5ee06d55e1b07534dda2d295", - "revisionTime": "2018-08-15T02:43:44Z" - }, - { - "checksumSHA1": "GCTVJ1J/SGZstNZauuLAnTFOhGA=", - "path": "github.com/armon/go-radix", - "revision": "1fca145dffbcaa8fe914309b1ec0cfc67500fe61", - "revisionTime": "2017-07-27T15:54:43Z" - }, - { - "checksumSHA1": "fFU9OeM0pKWGL3D+Fa3PmHSjjLg=", - "path": "github.com/aws/aws-sdk-go/aws", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "Y9W+4GimK4Fuxq+vyIskVYFRnX4=", - "path": "github.com/aws/aws-sdk-go/aws/awserr", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "yyYr41HZ1Aq0hWc3J5ijXwYEcac=", - "path": "github.com/aws/aws-sdk-go/aws/awsutil", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "gcA6wFbLBJLLO/6g+AH9QoQQX1U=", - "path": "github.com/aws/aws-sdk-go/aws/client", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "ieAJ+Cvp/PKv1LpUEnUXpc3OI6E=", - "path": "github.com/aws/aws-sdk-go/aws/client/metadata", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "7/8j/q0TWtOgXyvEcv4B2Dhl00o=", - "path": "github.com/aws/aws-sdk-go/aws/corehandlers", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "Y+cPwQL0dZMyqp3wI+KJWmA9KQ8=", - "path": "github.com/aws/aws-sdk-go/aws/credentials", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "u3GOAJLmdvbuNUeUEcZSEAOeL/0=", - "path": "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "NUJUTWlc1sV8b7WjfiYc4JZbXl0=", - "path": "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "JEYqmF83O5n5bHkupAzA6STm0no=", - "path": "github.com/aws/aws-sdk-go/aws/credentials/stscreds", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "ZdtYh3ZHSgP/WEIaqwJHTEhpkbs=", - "path": "github.com/aws/aws-sdk-go/aws/defaults", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "/EXbk/z2TWjWc1Hvb4QYs3Wmhb8=", - "path": "github.com/aws/aws-sdk-go/aws/ec2metadata", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "vaHB7ND2ZMMwBwrdT0KJUKT1VaM=", - "path": "github.com/aws/aws-sdk-go/aws/endpoints", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "Utpqcq3J2hqoaKEsjI7kDF9bUkg=", - "path": "github.com/aws/aws-sdk-go/aws/request", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "Y20DEtMtbfE9qTtmoi2NYV1x7aA=", - "path": "github.com/aws/aws-sdk-go/aws/session", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "SvIsunO8D9MEKbetMENA4WRnyeE=", - "path": "github.com/aws/aws-sdk-go/aws/signer/v4", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "04ypv4x12l4q0TksA1zEVsmgpvw=", - "path": "github.com/aws/aws-sdk-go/internal/shareddefaults", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "wk7EyvDaHwb5qqoOP/4d3cV0708=", - "path": "github.com/aws/aws-sdk-go/private/protocol", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "ZqY5RWavBLWTo6j9xqdyBEaNFRk=", - "path": "github.com/aws/aws-sdk-go/private/protocol/query", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "Drt1JfLMa0DQEZLWrnMlTWaIcC8=", - "path": "github.com/aws/aws-sdk-go/private/protocol/query/queryutil", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "VCTh+dEaqqhog5ncy/WTt9+/gFM=", - "path": "github.com/aws/aws-sdk-go/private/protocol/rest", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "ODo+ko8D6unAxZuN1jGzMcN4QCc=", - "path": "github.com/aws/aws-sdk-go/private/protocol/restxml", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "0qYPUga28aQVkxZgBR3Z86AbGUQ=", - "path": "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "a+tKLYUEM3ZftY52P2ywtIxlCxE=", - "path": "github.com/aws/aws-sdk-go/service/iam", - "revision": "4c984c1f412ef5c5cdbb1a3f1c6ce5e3155ca9ab", - "revisionTime": "2017-09-22T21:25:34Z" - }, - { - "checksumSHA1": "krqUUMDYRN2ohYcumxZl8BTR5EQ=", - "path": "github.com/aws/aws-sdk-go/service/s3", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "VH5y62f+SDyEIqnTibiPtQ687i8=", - "path": "github.com/aws/aws-sdk-go/service/sts", - "revision": "be4fa13e47938e4801fada8c8ca3d1867ad3dcb3", - "revisionTime": "2017-06-02T18:54:01Z", - "version": "v1.8.34", - "versionExact": "v1.8.34" - }, - { - "checksumSHA1": "nqw2Qn5xUklssHTubS5HDvEL9L4=", - "path": "github.com/bgentry/go-netrc/netrc", - "revision": "9fd32a8b3d3d3f9d43c341bfe098430e07609480", - "revisionTime": "2014-04-22T17:41:19Z" - }, - { - "checksumSHA1": "oTmBS67uxM6OXB/+OJUAG9LK4jw=", - "path": "github.com/bgentry/speakeasy", - "revision": "4aabc24848ce5fd31929f7d1e4ea74d3709c14cd", - "revisionTime": "2017-04-17T20:07:03Z" - }, - { - "checksumSHA1": "OT4XN9z5k69e2RsMSpwW74B+yk4=", - "path": "github.com/blang/semver", - "revision": "2ee87856327ba09384cabd113bc6b5d174e9ec0f", - "revisionTime": "2017-07-27T06:48:18Z" - }, - { - "checksumSHA1": "dvabztWVQX8f6oMLRyv4dLH+TGY=", - "path": "github.com/davecgh/go-spew/spew", - "revision": "346938d642f2ec3594ed81d874461961cd0faa76", - "revisionTime": "2016-10-29T20:57:26Z" - }, - { - "checksumSHA1": "40Ns85VYa4smQPcewZ7SOdfLnKU=", - "path": "github.com/fatih/structs", - "revision": "a720dfa8df582c51dee1b36feabb906bde1588bd", - "revisionTime": "2017-01-03T08:10:50Z" - }, - { - "checksumSHA1": "BCv50o5pDkoSG3vYKOSai1Z8p3w=", - "path": "github.com/fsouza/go-dockerclient", - "revision": "1d4f4ae73768d3ca16a6fb964694f58dc5eba601", - "revisionTime": "2016-04-27T17:25:47Z", - "tree": true - }, - { - "checksumSHA1": "1K+xrZ1PBez190iGt5OnMtGdih4=", - "comment": "v1.8.6", - "path": "github.com/go-ini/ini", - "revision": "766e555c68dc8bda90d197ee8946c37519c19409", - "revisionTime": "2017-01-17T13:00:17Z" - }, - { - "checksumSHA1": "Y2MOwzNZfl4NRNDbLCZa6sgx7O0=", - "path": "github.com/golang/protobuf/proto", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "WOkXetG3AqJnfVVuqTJvdukcHps=", - "path": "github.com/golang/protobuf/protoc-gen-go/descriptor", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "aEiR2m3NGaMGTbUW5P+w5gKFyc8=", - "path": "github.com/golang/protobuf/ptypes", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "2/Xg4L9IVGQRJB8zCELZx7/Z4HU=", - "path": "github.com/golang/protobuf/ptypes/any", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "RE9rLveNHapyMKQC8p10tbkUE9w=", - "path": "github.com/golang/protobuf/ptypes/duration", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "seEwY2xETpK9yHJ9+bHqkLZ0VMU=", - "path": "github.com/golang/protobuf/ptypes/timestamp", - "revision": "d3c38a4eb4970272b87a425ae00ccc4548e2f9bb", - "revisionTime": "2019-03-18T19:48:12Z" - }, - { - "checksumSHA1": "GhVjj03AhsCAzfg27YgS8RA+6wk=", - "path": "github.com/google/go-cmp/cmp", - "revision": "6f77996f0c42f7b84e5a2b252227263f93432e9b", - "revisionTime": "2019-03-12T03:24:27Z" - }, - { - "checksumSHA1": "FUnTgtE5i3f8asIvicGkJSFlrts=", - "path": "github.com/google/go-cmp/cmp/internal/diff", - "revision": "6f77996f0c42f7b84e5a2b252227263f93432e9b", - "revisionTime": "2019-03-12T03:24:27Z" - }, - { - "checksumSHA1": "nR8EJ8i8lqxxmtLPnXI7WlYANiE=", - "path": "github.com/google/go-cmp/cmp/internal/flags", - "revision": "6f77996f0c42f7b84e5a2b252227263f93432e9b", - "revisionTime": "2019-03-12T03:24:27Z" - }, - { - "checksumSHA1": "0pcLJsUQUaBdPXM5LuL9uFeuETs=", - "path": "github.com/google/go-cmp/cmp/internal/function", - "revision": "6f77996f0c42f7b84e5a2b252227263f93432e9b", - "revisionTime": "2019-03-12T03:24:27Z" - }, - { - "checksumSHA1": "ZNN1jJuHnBCpo21lSv25VvkotIM=", - "path": "github.com/google/go-cmp/cmp/internal/value", - "revision": "6f77996f0c42f7b84e5a2b252227263f93432e9b", - "revisionTime": "2019-03-12T03:24:27Z" - }, - { - "checksumSHA1": "Np15I2tN6ZWdS7SNJWW7OO1pAak=", - "path": "github.com/googleapis/gax-go/v2", - "revision": "beaecbbdd8af86aa3acf14180d53828ce69400b2", - "revisionTime": "2019-03-05T15:30:21Z" - }, - { - "checksumSHA1": "wa0Kf+UNMo+htGTATzXGw8n3tEc=", - "path": "github.com/gosimple/slug", - "revision": "d8eda97f6ce6a447aa8ed204694bb5ce84f36b71", - "revisionTime": "2018-11-27T20:15:04Z" - }, - { - "checksumSHA1": "cdOCt0Yb+hdErz8NAQqayxPmRsY=", - "path": "github.com/hashicorp/errwrap", - "revision": "7554cd9344cec97297fa6649b055a8c98c2a1e55" - }, - { - "checksumSHA1": "b8F628srIitj5p7Y130xc9k0QWs=", - "path": "github.com/hashicorp/go-cleanhttp", - "revision": "3573b8b52aa7b37b9358d966a898feb387f62437", - "revisionTime": "2017-02-11T01:34:15Z" - }, - { - "checksumSHA1": "a50Ra65g6qvU0hg1O4NX6FvkITw=", - "path": "github.com/hashicorp/go-getter", - "revision": "69dec094fde6ac8d2659bff743fc0b2096ccb54f", - "revisionTime": "2019-03-26T19:45:18Z" - }, - { - "checksumSHA1": "RPBfCNScCTZ2ov7PsGjeKrEkk3Q=", - "path": "github.com/hashicorp/go-getter/helper/url", - "revision": "69dec094fde6ac8d2659bff743fc0b2096ccb54f", - "revisionTime": "2019-03-26T19:45:18Z" - }, - { - "checksumSHA1": "lrSl49G23l6NhfilxPM0XFs5rZo=", - "path": "github.com/hashicorp/go-multierror", - "revision": "d30f09973e19c1dfcd120b2d9c4f168e68d6b5d5" - }, - { - "checksumSHA1": "gyFqLTk3KDzmkSuXFVEGy9GbS6k=", - "path": "github.com/hashicorp/go-plugin", - "revision": "52e1c4730856c1438ced7597c9b5c585a7bd06a2", - "revisionTime": "2019-03-22T17:27:44Z" - }, - { - "checksumSHA1": "uTvnRQ5UWn/bhRxbW/UCfYFseSc=", - "path": "github.com/hashicorp/go-plugin/internal/plugin", - "revision": "52e1c4730856c1438ced7597c9b5c585a7bd06a2", - "revisionTime": "2019-03-22T17:27:44Z" - }, - { - "checksumSHA1": "/yKfFSspjuDzyOe/bBslrPzyfYM=", - "path": "github.com/hashicorp/go-retryablehttp", - "revision": "e651d75abec6fbd4f2c09508f72ae7af8a8b7171", - "revisionTime": "2018-07-18T19:50:05Z" - }, - { - "checksumSHA1": "A1PcINvF3UiwHRKn8UcgARgvGRs=", - "path": "github.com/hashicorp/go-rootcerts", - "revision": "6bb64b370b90e7ef1fa532be9e591a81c3493e00", - "revisionTime": "2016-05-03T14:34:40Z" - }, - { - "checksumSHA1": "0daDqRBckum49dBVYduwjaoObgU=", - "path": "github.com/hashicorp/go-safetemp", - "revision": "c9a55de4fe06c920a71964b53cfe3dd293a3c743", - "revisionTime": "2018-08-28T16:41:30Z" - }, - { - "checksumSHA1": "85XUnluYJL7F55ptcwdmN8eSOsk=", - "path": "github.com/hashicorp/go-uuid", - "revision": "36289988d83ca270bc07c234c36f364b0dd9c9a7" - }, - { - "checksumSHA1": "5UIub/A8OrLKVMbyXQif7j8ppp4=", - "path": "github.com/hashicorp/go-version", - "revision": "d40cf49b3a77bba84a7afdbd7f1dc295d114efb1", - "revisionTime": "2019-01-07T18:42:39Z" - }, - { - "checksumSHA1": "NvkV52M5EFd0kT4U+9A2Eu/kKr8=", - "path": "github.com/hashicorp/golang-lru/simplelru", - "revision": "7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c", - "revisionTime": "2019-02-27T22:24:58Z" - }, - { - "checksumSHA1": "o3XZZdOnSnwQSpYw215QV75ZDeI=", - "path": "github.com/hashicorp/hcl", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "XQmjDva9JCGGkIecOgwtBEMCJhU=", - "path": "github.com/hashicorp/hcl/hcl/ast", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "teokXoyRXEJ0vZHOWBD11l5YFNI=", - "path": "github.com/hashicorp/hcl/hcl/parser", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "z6wdP4mRw4GVjShkNHDaOWkbxS0=", - "path": "github.com/hashicorp/hcl/hcl/scanner", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "oS3SCN9Wd6D8/LG0Yx1fu84a7gI=", - "path": "github.com/hashicorp/hcl/hcl/strconv", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "c6yprzj06ASwCo18TtbbNNBHljA=", - "path": "github.com/hashicorp/hcl/hcl/token", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "PwlfXt7mFS8UYzWxOK5DOq0yxS0=", - "path": "github.com/hashicorp/hcl/json/parser", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "YdvFsNOMSWMLnY6fcliWQa0O5Fw=", - "path": "github.com/hashicorp/hcl/json/scanner", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "fNlXQCQEnb+B3k5UDL/r15xtSJY=", - "path": "github.com/hashicorp/hcl/json/token", - "revision": "a4b07c25de5ff55ad3b8936cea69a79a3d95a855", - "revisionTime": "2017-05-04T19:02:34Z" - }, - { - "checksumSHA1": "RFEjfMQWPAVILXE2PhL6wDW8Zg4=", - "path": "github.com/hashicorp/hcl2/gohcl", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "bUO4KS1yjAWa6miewgbUUsxYVfo=", - "path": "github.com/hashicorp/hcl2/hcl", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "uMWQk/2xJyIqL6ILq83VYVxkuY8=", - "path": "github.com/hashicorp/hcl2/hcl/hclsyntax", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "Vagtn0ywFboMp7br/xvzeuNUFNc=", - "path": "github.com/hashicorp/hcl2/hcl/json", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "6JRj4T/iQxIe/CoKXHDjPuupmL8=", - "path": "github.com/hashicorp/hcl2/hcldec", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "IzmftuG99BqNhbFGhxZaGwtiMtM=", - "path": "github.com/hashicorp/hcl2/hclparse", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "w2QOKSxuvwC2wp3jTxSz7ZG3l88=", - "path": "github.com/hashicorp/hcl2/hclwrite", - "revision": "3fb4ed0d9260f5c187470d0d879c7b598d5899d1", - "revisionTime": "2019-03-27T22:38:17Z" - }, - { - "checksumSHA1": "M09yxoBoCEtG7EcHR8aEWLzMMJc=", - "path": "github.com/hashicorp/hil", - "revision": "fac2259da677551de1fb92b844c4d020a38d8468", - "revisionTime": "2017-05-12T21:33:05Z" - }, - { - "checksumSHA1": "0S0KeBcfqVFYBPeZkuJ4fhQ5mCA=", - "path": "github.com/hashicorp/hil/ast", - "revision": "fac2259da677551de1fb92b844c4d020a38d8468", - "revisionTime": "2017-05-12T21:33:05Z" - }, - { - "checksumSHA1": "P5PZ3k7SmqWmxgJ8Q0gLzeNpGhE=", - "path": "github.com/hashicorp/hil/parser", - "revision": "fac2259da677551de1fb92b844c4d020a38d8468", - "revisionTime": "2017-05-12T21:33:05Z" - }, - { - "checksumSHA1": "DC1k5kOua4oFqmo+JRt0YzfP44o=", - "path": "github.com/hashicorp/hil/scanner", - "revision": "fac2259da677551de1fb92b844c4d020a38d8468", - "revisionTime": "2017-05-12T21:33:05Z" - }, - { - "checksumSHA1": "vt+P9D2yWDO3gdvdgCzwqunlhxU=", - "path": "github.com/hashicorp/logutils", - "revision": "0dc08b1671f34c4250ce212759ebd880f743d883", - "revisionTime": "2015-06-09T07:04:31Z" - }, - { - "checksumSHA1": "5LAYMNjfAj4wCNBBLkUINsaD8Qc=", - "path": "github.com/hashicorp/terraform/config", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "WzQP2WfiCYlaALKZVqEFsxZsG1o=", - "path": "github.com/hashicorp/terraform/config/configschema", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "3V7300kyZF+AGy/cOKV0+P6M3LY=", - "path": "github.com/hashicorp/terraform/config/hcl2shim", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "IEcv4JzjLVjAJjbxcvcAwziPqNM=", - "path": "github.com/hashicorp/terraform/config/module", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "mPbjVPD2enEey45bP4M83W2AxlY=", - "path": "github.com/hashicorp/terraform/dag", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "P8gNPDuOzmiK4Lz9xG7OBy4Rlm8=", - "path": "github.com/hashicorp/terraform/flatmap", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "zx5DLo5aV0xDqxGTzSibXg7HHAA=", - "path": "github.com/hashicorp/terraform/helper/acctest", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "uT6Q9RdSRAkDjyUgQlJ2XKJRab4=", - "path": "github.com/hashicorp/terraform/helper/config", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "KNvbU1r5jv0CBeQLnEtDoL3dRtc=", - "path": "github.com/hashicorp/terraform/helper/hashcode", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "B267stWNQd0/pBTXHfI/tJsxzfc=", - "path": "github.com/hashicorp/terraform/helper/hilmapstructure", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "j8XqkwLh2W3r3i6wnCRmve07BgI=", - "path": "github.com/hashicorp/terraform/helper/logging", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "ejnz+70aL76+An9FZymcUcg0lUU=", - "path": "github.com/hashicorp/terraform/helper/resource", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "r4SAF/j+gu9sz1SnWotH5Ejn6CQ=", - "path": "github.com/hashicorp/terraform/helper/schema", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "Fzbv+N7hFXOtrR6E7ZcHT3jEE9s=", - "path": "github.com/hashicorp/terraform/helper/structure", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "+JXuXusZkWFE3QgCiOHV/X/omZs=", - "path": "github.com/hashicorp/terraform/helper/validation", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "kD1ayilNruf2cES1LDfNZjYRscQ=", - "path": "github.com/hashicorp/terraform/httpclient", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "yFWmdS6yEJZpRJzUqd/mULqCYGk=", - "path": "github.com/hashicorp/terraform/moduledeps", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "XcILMfUnOq5tCnek9geQAtF599c=", - "path": "github.com/hashicorp/terraform/plugin", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "tx5xrdiUWdAHqoRV5aEfALgT1aU=", - "path": "github.com/hashicorp/terraform/plugin/discovery", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "1K4cl0ZSGST6ZKmquhLQAWJ3SEQ=", - "path": "github.com/hashicorp/terraform/registry", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "cR87P4V5aiEfvF+1qoBi2JQyQS4=", - "path": "github.com/hashicorp/terraform/registry/regsrc", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "y9IXgIJQq9XNy1zIYUV2Kc0KsnA=", - "path": "github.com/hashicorp/terraform/registry/response", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "VXlzRRDVOqeMvnnrbUcR9H64OA4=", - "path": "github.com/hashicorp/terraform/svchost", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "o6CMncmy6Q2F+r13sEOeT6R9GF8=", - "path": "github.com/hashicorp/terraform/svchost/auth", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "aYNEjI1hrEC3wKqftpAxfk7S/Wg=", - "path": "github.com/hashicorp/terraform/svchost/disco", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "nVfmiZMaf6r2swzt14VETeBjue8=", - "path": "github.com/hashicorp/terraform/terraform", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "+K+oz9mMTmQMxIA3KVkGRfjvm9I=", - "path": "github.com/hashicorp/terraform/tfdiags", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "RN8JPQ/+hFU05BtuS1+QWe6MI6k=", - "path": "github.com/hashicorp/terraform/version", - "revision": "44702fa6c163391fe7295b6004a06cefe150daa0", - "revisionTime": "2019-03-29T07:32:42Z", - "version": "=sdk-v0.11-with-go-modules", - "versionExact": "sdk-v0.11-with-go-modules" - }, - { - "checksumSHA1": "Agqmy6rgChDCY8deGHJYANp2Jm4=", - "path": "github.com/hashicorp/vault", - "revision": "8575f8fedcf8f5a6eb2b4701cb527b99574b5286", - "revisionTime": "2018-09-06T17:45:45Z", - "version": "v0.11.1", - "versionExact": "v0.11.1" - }, - { - "checksumSHA1": "6B+p22t7wBR52hepGYd3t1JnDME=", - "path": "github.com/hashicorp/vault-plugin-auth-jwt", - "revision": "a608a5ad1c249797e266cb8fcb4eac336aa72bef", - "revisionTime": "2019-01-28T23:42:21Z" - }, - { - "checksumSHA1": "+B4wuJNerIUKNAVzld7CmMaNW5A=", - "path": "github.com/hashicorp/vault/api", - "revision": "8575f8fedcf8f5a6eb2b4701cb527b99574b5286", - "revisionTime": "2018-09-06T17:45:45Z", - "version": "v0.11.1", - "versionExact": "v0.11.1" - }, - { - "checksumSHA1": "cYsW0ei8JxRNXy1ZHoHjYlBRDIQ=", - "path": "github.com/hashicorp/vault/command/config", - "revision": "95978c208f0b4c0966f3ef2edc1c8ca62cfe3e2e", - "revisionTime": "2018-05-25T23:20:11Z" - }, - { - "checksumSHA1": "NKuji4DOr6kia0RGemhGbnHIb5Y=", - "path": "github.com/hashicorp/vault/command/token", - "revision": "95978c208f0b4c0966f3ef2edc1c8ca62cfe3e2e", - "revisionTime": "2018-05-25T23:20:11Z" - }, - { - "checksumSHA1": "ft77GtqeZEeCXioGpF/s6DlGm/U=", - "path": "github.com/hashicorp/vault/helper/compressutil", - "revision": "9a60bf2a50e4dd1ba4b929a3ccf8072435cbdd0a", - "revisionTime": "2016-10-29T21:01:49Z" - }, - { - "checksumSHA1": "yUiSTPf0QUuL2r/81sjuytqBoeQ=", - "path": "github.com/hashicorp/vault/helper/jsonutil", - "revision": "9a60bf2a50e4dd1ba4b929a3ccf8072435cbdd0a", - "revisionTime": "2016-10-29T21:01:49Z" - }, - { - "checksumSHA1": "ZhK6IO2XN81Y+3RAjTcVm1Ic7oU=", - "path": "github.com/hashicorp/yamux", - "revision": "d1caa6c97c9fc1cc9e83bbe34d0603f9ff0ce8bd", - "revisionTime": "2016-07-20T23:31:40Z" - }, - { - "checksumSHA1": "0ZrwvB6KoGPj2PoDNSEJwxQ6Mog=", - "comment": "0.2.2-2-gc01cf91", - "path": "github.com/jmespath/go-jmespath", - "revision": "bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d", - "revisionTime": "2016-08-03T19:07:31Z" - }, - { - "checksumSHA1": "AZO2VGorXTMDiSVUih3k73vORHY=", - "path": "github.com/mattn/go-isatty", - "revision": "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c", - "revisionTime": "2017-11-07T05:05:31Z" - }, - { - "checksumSHA1": "UIqCj7qI0hhIMpAhS9YYqs2jD48=", - "path": "github.com/mitchellh/cli", - "revision": "65fcae5817c8600da98ada9d7edf26dd1a84837b", - "revisionTime": "2017-09-08T18:10:43Z" - }, - { - "checksumSHA1": "guxbLo8KHHBeM0rzou4OTzzpDNs=", - "path": "github.com/mitchellh/copystructure", - "revision": "5af94aef99f597e6a9e1f6ac6be6ce0f3c96b49d", - "revisionTime": "2016-10-13T19:53:42Z" - }, - { - "checksumSHA1": "V/quM7+em2ByJbWBLOsEwnY3j/Q=", - "path": "github.com/mitchellh/go-homedir", - "revision": "b8bc1bf767474819792c23f32d8286a45736f1c6", - "revisionTime": "2016-12-03T19:45:07Z" - }, - { - "checksumSHA1": "2gW/SeTAbHsmAdoDes4DksvqTj4=", - "path": "github.com/mitchellh/go-wordwrap", - "revision": "9e67c67572bc5dd02aef930e2b0ae3c02a4b5a5c", - "revisionTime": "2018-08-28T14:53:44Z" - }, - { - "checksumSHA1": "xyoJKalfQwTUN1qzZGQKWYAwl0A=", - "path": "github.com/mitchellh/hashstructure", - "revision": "6b17d669fac5e2f71c16658d781ec3fdd3802b69" - }, - { - "checksumSHA1": "MlX15lJuV8DYARX5RJY8rqrSEWQ=", - "path": "github.com/mitchellh/mapstructure", - "revision": "53818660ed4955e899c0bcafa97299a388bd7c8e", - "revisionTime": "2017-03-07T20:11:23Z" - }, - { - "checksumSHA1": "vBpuqNfSTZcAR/0tP8tNYacySGs=", - "path": "github.com/mitchellh/reflectwalk", - "revision": "92573fe8d000a145bfebc03a16bc22b34945867f", - "revisionTime": "2016-10-03T17:45:16Z" - }, - { - "checksumSHA1": "Nt4Ol6ZM2n0XD5zatxjwEYBpQnw=", - "path": "github.com/posener/complete", - "revision": "dc2bc5a81accba8782bebea28628224643a8286a", - "revisionTime": "2017-11-04T09:57:02Z" - }, - { - "checksumSHA1": "NB7uVS0/BJDmNu68vPAlbrq4TME=", - "path": "github.com/posener/complete/cmd", - "revision": "dc2bc5a81accba8782bebea28628224643a8286a", - "revisionTime": "2017-11-04T09:57:02Z" - }, - { - "checksumSHA1": "Hwojin3GxRyKwPAiz5r7UszqkPc=", - "path": "github.com/posener/complete/cmd/install", - "revision": "dc2bc5a81accba8782bebea28628224643a8286a", - "revisionTime": "2017-11-04T09:57:02Z" - }, - { - "checksumSHA1": "DMo94FwJAm9ZCYCiYdJU2+bh4no=", - "path": "github.com/posener/complete/match", - "revision": "dc2bc5a81accba8782bebea28628224643a8286a", - "revisionTime": "2017-11-04T09:57:02Z" - }, - { - "checksumSHA1": "pvg8L4xN+zO9HLJislpVeHPPLjM=", - "path": "github.com/rainycape/unidecode", - "revision": "cb7f23ec59bec0d61b19c56cd88cee3d0cc1870c", - "revisionTime": "2015-09-07T02:38:54Z" - }, - { - "checksumSHA1": "u5s2PZ7fzCOqQX7bVPf9IJ+qNLQ=", - "path": "github.com/rancher/go-rancher", - "revision": "ec24b7f12fca9f78fbfcd62a0ea8bce14ade8792", - "revisionTime": "2017-04-07T04:09:43Z" - }, - { - "checksumSHA1": "feVa3uL7qR2quGvkE7IRtxM0YPQ=", - "path": "github.com/ulikunitz/xz", - "revision": "6f934d456d51e742b4eeab20d925a827ef22320a", - "revisionTime": "2019-02-20T20:51:30Z" - }, - { - "checksumSHA1": "vjnTkzNrMs5Xj6so/fq0mQ6dT1c=", - "path": "github.com/ulikunitz/xz/internal/hash", - "revision": "6f934d456d51e742b4eeab20d925a827ef22320a", - "revisionTime": "2019-02-20T20:51:30Z" - }, - { - "checksumSHA1": "m0pm57ASBK/CTdmC0ppRHO17mBs=", - "path": "github.com/ulikunitz/xz/internal/xlog", - "revision": "6f934d456d51e742b4eeab20d925a827ef22320a", - "revisionTime": "2019-02-20T20:51:30Z" - }, - { - "checksumSHA1": "0ePMTpIfQfr9W6N6Va/qaN7ZFYc=", - "path": "github.com/ulikunitz/xz/lzma", - "revision": "6f934d456d51e742b4eeab20d925a827ef22320a", - "revisionTime": "2019-02-20T20:51:30Z" - }, - { - "checksumSHA1": "22dxGUUO11SbFR65HjpJp47kDqA=", - "path": "github.com/zclconf/go-cty/cty", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "YfO0G0Vo4MDVwifJAjWPFql4Xss=", - "path": "github.com/zclconf/go-cty/cty/convert", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "w2t9tjH/LkWhVHN+KPrjdUrBtjE=", - "path": "github.com/zclconf/go-cty/cty/function", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "u8HY5QZVfCArzRpt5ysoLYuln+U=", - "path": "github.com/zclconf/go-cty/cty/function/stdlib", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "lh3J7K7xRgcs/1tUYo3Nx7nY2Z8=", - "path": "github.com/zclconf/go-cty/cty/gocty", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "Y9Qv0ewA5LJmCLU7DMlr5pikMtE=", - "path": "github.com/zclconf/go-cty/cty/json", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "y5Sk+n6SOspFj8mlyb8swr4DMIs=", - "path": "github.com/zclconf/go-cty/cty/set", - "revision": "fd76348b9329dc6f3bd4b87a45ae9e5fb72bffbc", - "revisionTime": "2019-03-20T22:47:46Z" - }, - { - "checksumSHA1": "zeixbGy5h77jKZN8UJ0C2ZAOxbY=", - "path": "go.opencensus.io", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "KLZy3Nh+8JlI04JmBa/Jc8fxrVQ=", - "path": "go.opencensus.io/internal", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "Dw3rpna1DwTa7TCzijInKcU49g4=", - "path": "go.opencensus.io/internal/tagencoding", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "TxBvrBM2uIz9wGczsexq228U5RM=", - "path": "go.opencensus.io/metric/metricdata", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "kWj13srwY1SH5KgFecPhEfHnzVc=", - "path": "go.opencensus.io/metric/metricproducer", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "m7BfdFek7+xe0ayHLIcXxTQBGmg=", - "path": "go.opencensus.io/plugin/ochttp", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "UZhIoErIy1tKLmVT/5huwlp6KFQ=", - "path": "go.opencensus.io/plugin/ochttp/propagation/b3", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "q+y8X+5nDONIlJlxfkv+OtA18ds=", - "path": "go.opencensus.io/resource", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "mycxlEbkp4ovKoSp96Qp5WkkcaU=", - "path": "go.opencensus.io/stats", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "oIo4NRi6AVCfcwVfHzCXAsoZsdI=", - "path": "go.opencensus.io/stats/internal", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "q6fOuvHaeHcXaOYx5pGjEeMp7IM=", - "path": "go.opencensus.io/stats/view", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "mUKyvyVpJI5rM4NUhJb6wBbYzyE=", - "path": "go.opencensus.io/tag", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "0O3djqX4bcg5O9LZdcinEoYeQKs=", - "path": "go.opencensus.io/trace", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "JkvEb8oMEFjic5K/03Tyr5Lok+w=", - "path": "go.opencensus.io/trace/internal", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "FHJParRi8f1GHO7Cx+lk3bMWBq0=", - "path": "go.opencensus.io/trace/propagation", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "UHbxxaMqpEPsubh8kPwzSlyEwqI=", - "path": "go.opencensus.io/trace/tracestate", - "revision": "41e54b832491efe97a2aafe696f6e7d812f136bb", - "revisionTime": "2019-03-27T17:06:59Z" - }, - { - "checksumSHA1": "vE43s37+4CJ2CDU6TlOUOYE0K9c=", - "path": "golang.org/x/crypto/bcrypt", - "revision": "9477e0b78b9ac3d0b03822fd95422e2fe07627cd", - "revisionTime": "2016-10-31T15:37:30Z" - }, - { - "checksumSHA1": "JsJdKXhz87gWenMwBeejTOeNE7k=", - "path": "golang.org/x/crypto/blowfish", - "revision": "9477e0b78b9ac3d0b03822fd95422e2fe07627cd", - "revisionTime": "2016-10-31T15:37:30Z" - }, - { - "checksumSHA1": "TT1rac6kpQp2vz24m5yDGUNQ/QQ=", - "path": "golang.org/x/crypto/cast5", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "5fWrCoK7RIYvC3bLuins/Y/NZfU=", - "origin": "github.com/hashicorp/terraform/vendor/golang.org/x/crypto/curve25519", - "path": "golang.org/x/crypto/curve25519", - "revision": "b6a464c5214d1378b74cf683c51feb876791e155", - "revisionTime": "2017-08-22T18:47:30Z" - }, - { - "checksumSHA1": "wGb//LjBPNxYHqk+dcLo7BjPXK8=", - "origin": "github.com/hashicorp/terraform/vendor/golang.org/x/crypto/ed25519", - "path": "golang.org/x/crypto/ed25519", - "revision": "b6a464c5214d1378b74cf683c51feb876791e155", - "revisionTime": "2017-08-22T18:47:30Z" - }, - { - "checksumSHA1": "LXFcVx8I587SnWmKycSDEq9yvK8=", - "origin": "github.com/hashicorp/terraform/vendor/golang.org/x/crypto/ed25519/internal/edwards25519", - "path": "golang.org/x/crypto/ed25519/internal/edwards25519", - "revision": "b6a464c5214d1378b74cf683c51feb876791e155", - "revisionTime": "2017-08-22T18:47:30Z" - }, - { - "checksumSHA1": "IIhFTrLlmlc6lEFSitqi4aw2lw0=", - "path": "golang.org/x/crypto/openpgp", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "olOKkhrdkYQHZ0lf1orrFQPQrv4=", - "path": "golang.org/x/crypto/openpgp/armor", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "eo/KtdjieJQXH7Qy+faXFcF70ME=", - "path": "golang.org/x/crypto/openpgp/elgamal", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "rlxVSaGgqdAgwblsErxTxIfuGfg=", - "path": "golang.org/x/crypto/openpgp/errors", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "Pq88+Dgh04UdXWZN6P+bLgYnbRc=", - "path": "golang.org/x/crypto/openpgp/packet", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "s2qT4UwvzBSkzXuiuMkowif1Olw=", - "path": "golang.org/x/crypto/openpgp/s2k", - "revision": "b176d7def5d71bdd214203491f89843ed217f420", - "revisionTime": "2017-07-23T04:49:35Z" - }, - { - "checksumSHA1": "fsrFs762jlaILyqqQImS1GfvIvw=", - "origin": "github.com/hashicorp/terraform/vendor/golang.org/x/crypto/ssh", - "path": "golang.org/x/crypto/ssh", - "revision": "b6a464c5214d1378b74cf683c51feb876791e155", - "revisionTime": "2017-08-22T18:47:30Z" - }, - { - "checksumSHA1": "aFpql3G+Nw8zkzfqLWQJNZC8pu0=", - "path": "golang.org/x/net/context/ctxhttp", - "revision": "74de082e2cca95839e88aa0aeee5aadf6ce7710f", - "revisionTime": "2019-03-26T08:46:22Z" - }, - { - "checksumSHA1": "vqc3a+oTUGX8PmD0TS+qQ7gmN8I=", - "path": "golang.org/x/net/html", - "revision": "1c05540f6879653db88113bc4a2b70aec4bd491f", - "revisionTime": "2017-08-04T00:04:37Z" - }, - { - "checksumSHA1": "z79z5msRzgU48FCZxSuxfU8b4rs=", - "path": "golang.org/x/net/html/atom", - "revision": "1c05540f6879653db88113bc4a2b70aec4bd491f", - "revisionTime": "2017-08-04T00:04:37Z" - }, - { - "checksumSHA1": "pCY4YtdNKVBYRbNvODjx8hj0hIs=", - "path": "golang.org/x/net/http/httpguts", - "revision": "039a4258aec0ad3c79b905677cceeab13b296a77", - "revisionTime": "2018-05-05T01:56:23Z" - }, - { - "checksumSHA1": "leSW9aM30mATlWs/eeqhQQh/3eo=", - "path": "golang.org/x/net/http2/hpack", - "revision": "039a4258aec0ad3c79b905677cceeab13b296a77", - "revisionTime": "2018-05-05T01:56:23Z" - }, - { - "checksumSHA1": "RcrB7tgYS/GMW4QrwVdMOTNqIU8=", - "path": "golang.org/x/net/idna", - "revision": "26e67e76b6c3f6ce91f7c52def5af501b4e0f3a2", - "revisionTime": "2018-09-11T21:37:47Z" - }, - { - "checksumSHA1": "UxahDzW2v4mf/+aFxruuupaoIwo=", - "path": "golang.org/x/net/internal/timeseries", - "revision": "74de082e2cca95839e88aa0aeee5aadf6ce7710f", - "revisionTime": "2019-03-26T08:46:22Z" - }, - { - "checksumSHA1": "HvmG9LfStMLF+hIC7xR4SxegMis=", - "path": "golang.org/x/net/trace", - "revision": "74de082e2cca95839e88aa0aeee5aadf6ce7710f", - "revisionTime": "2019-03-26T08:46:22Z" - }, - { - "checksumSHA1": "/94OVlOstzQP2qidGqEKOXBrzNA=", - "path": "golang.org/x/oauth2", - "revision": "c85d3e98c914e3a33234ad863dcbff5dbc425bb8", - "revisionTime": "2019-03-18T00:32:44Z" - }, - { - "checksumSHA1": "vkOMarzlQnwRlDCnf3eXPyAy+s4=", - "path": "golang.org/x/oauth2/google", - "revision": "c85d3e98c914e3a33234ad863dcbff5dbc425bb8", - "revisionTime": "2019-03-18T00:32:44Z" - }, - { - "checksumSHA1": "+9KSfsjsC3F2CldDDb+Dt+d/H3Q=", - "path": "golang.org/x/oauth2/internal", - "revision": "c85d3e98c914e3a33234ad863dcbff5dbc425bb8", - "revisionTime": "2019-03-18T00:32:44Z" - }, - { - "checksumSHA1": "huVltYnXdRFDJLgp/ZP9IALzG7g=", - "path": "golang.org/x/oauth2/jws", - "revision": "c85d3e98c914e3a33234ad863dcbff5dbc425bb8", - "revisionTime": "2019-03-18T00:32:44Z" - }, - { - "checksumSHA1": "mwzfgZFAlEkfNHK2OYqnhIvbI+g=", - "path": "golang.org/x/oauth2/jwt", - "revision": "c85d3e98c914e3a33234ad863dcbff5dbc425bb8", - "revisionTime": "2019-03-18T00:32:44Z" - }, - { - "checksumSHA1": "4zt1Dz8yMi0tHQKO2aN5rZVshWU=", - "path": "golang.org/x/sys/unix", - "revision": "2772b66316d2c587efeb188dcd5ebc6987656e84", - "revisionTime": "2018-10-17T18:36:36Z" - }, - { - "checksumSHA1": "CbpjEkkOeh0fdM/V8xKDdI0AA88=", - "path": "golang.org/x/text/secure/bidirule", - "revision": "905a57155faa8230500121607930ebb9dd8e139c", - "revisionTime": "2018-09-08T17:02:15Z" - }, - { - "checksumSHA1": "ziMb9+ANGRJSSIuxYdRbA+cDRBQ=", - "path": "golang.org/x/text/transform", - "revision": "905a57155faa8230500121607930ebb9dd8e139c", - "revisionTime": "2018-09-08T17:02:15Z" - }, - { - "checksumSHA1": "Qw4qdlZHCnBurAPPrSt+EKPIngM=", - "path": "golang.org/x/text/unicode/bidi", - "revision": "905a57155faa8230500121607930ebb9dd8e139c", - "revisionTime": "2018-09-08T17:02:15Z" - }, - { - "checksumSHA1": "XJr6+rzzxASewSbC/SCStyGlmuw=", - "path": "golang.org/x/text/unicode/norm", - "revision": "905a57155faa8230500121607930ebb9dd8e139c", - "revisionTime": "2018-09-08T17:02:15Z" - }, - { - "checksumSHA1": "HoCvrd3hEhsFeBOdEw7cbcfyk50=", - "path": "golang.org/x/time/rate", - "revision": "fbb02b2291d28baffd63558aa44b4b56f178d650", - "revisionTime": "2018-04-12T16:56:04Z" - }, - { - "checksumSHA1": "FhzGDPlkW5SaQGtSgKnjQAiYVk0=", - "path": "google.golang.org/api/gensupport", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "YIDE68w/xMptf6Nu9hHiOwXOvho=", - "path": "google.golang.org/api/googleapi", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "1K0JxrUfDqAB3MyRiU1LKjfHyf4=", - "path": "google.golang.org/api/googleapi/internal/uritemplates", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "Mr2fXhMRzlQCgANFm91s536pG7E=", - "path": "google.golang.org/api/googleapi/transport", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "6Tg4dDJKzoSrAA5beVknvnjluOU=", - "path": "google.golang.org/api/internal", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "zh9AcT6oNvhnOqb7w7njY48TkvI=", - "path": "google.golang.org/api/iterator", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "2AyxThTPscWdy49fGsU2tg0Uyw8=", - "path": "google.golang.org/api/option", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "A0kl/7LKBXvL5QBwi0MKWbtYYis=", - "path": "google.golang.org/api/storage/v1", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "WzZfHJ4G6jO/qf3n6DI9a9awJQk=", - "path": "google.golang.org/api/transport/http", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "sJcKCvjPtoysqyelsB2CQzC5oQI=", - "path": "google.golang.org/api/transport/http/internal/propagation", - "revision": "c30064f755a065acb7c5446e8b69067240dcdd39", - "revisionTime": "2019-03-29T21:11:19Z" - }, - { - "checksumSHA1": "OXZcFGFGGyDEzJaVO1FcWw0exIU=", - "path": "google.golang.org/genproto/googleapis/api/annotations", - "revision": "d831d65fe17df2e52bcc4316d4a9f7a418701f43", - "revisionTime": "2019-03-27T12:56:43Z" - }, - { - "checksumSHA1": "EXFa4ydacmVRKISyWiXykmip7SA=", - "path": "google.golang.org/genproto/googleapis/iam/v1", - "revision": "d831d65fe17df2e52bcc4316d4a9f7a418701f43", - "revisionTime": "2019-03-27T12:56:43Z" - }, - { - "checksumSHA1": "QveE+Hm8OYmlqdTu/P15NELHMgI=", - "path": "google.golang.org/genproto/googleapis/rpc/code", - "revision": "d831d65fe17df2e52bcc4316d4a9f7a418701f43", - "revisionTime": "2019-03-27T12:56:43Z" - }, - { - "checksumSHA1": "knF2NGI4m3IQSTWMDkd5HDwFXVY=", - "path": "google.golang.org/genproto/googleapis/rpc/status", - "revision": "d831d65fe17df2e52bcc4316d4a9f7a418701f43", - "revisionTime": "2019-03-27T12:56:43Z" - }, - { - "checksumSHA1": "vZR8rRBYG+rTBXyjuHVK2Y7cpC4=", - "path": "google.golang.org/grpc", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "w7mjaxK+6kK1komm3kvuZb9xstk=", - "path": "google.golang.org/grpc/balancer", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "xohMthvqnNpNM1T1cmuyKUNqsjQ=", - "path": "google.golang.org/grpc/balancer/base", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "cE7mFcyGz0F+EnlTZrzLkhprH/4=", - "path": "google.golang.org/grpc/balancer/roundrobin", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "YyTUFAVju8wgb1s/3azC2CeSbfY=", - "path": "google.golang.org/grpc/binarylog/grpc_binarylog_v1", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "R3tuACGAPyK4lr+oSNt1saUzC0M=", - "path": "google.golang.org/grpc/codes", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "UgxkVy6e/BMqXrmS21WmcHtdcd4=", - "path": "google.golang.org/grpc/connectivity", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "8WFl9b+iDrm/xvKd+vp3Rt+Mwes=", - "path": "google.golang.org/grpc/credentials", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "hj4XY8K4TjmMZwErpAWaSKFrk2c=", - "path": "google.golang.org/grpc/credentials/internal", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "puS+9H2qFMoLKCyXxu9nGACNuQk=", - "path": "google.golang.org/grpc/encoding", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "LKKkn7EYA+Do9Qwb2/SUKLFNxoo=", - "path": "google.golang.org/grpc/encoding/proto", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "3hj3attJzO2iqArJeSNEW8diHqo=", - "path": "google.golang.org/grpc/grpclog", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "wabmZzT67A/Oy1tWQxYWw7UuTnY=", - "path": "google.golang.org/grpc/health", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "KfgIKMqGJ8FdFbWlGDsnmrCY7eE=", - "path": "google.golang.org/grpc/health/grpc_health_v1", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "ljdusD2Cq+jomfGQwL9TyEsRZEA=", - "path": "google.golang.org/grpc/internal", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "uDJA7QK2iGnEwbd9TPqkLaM+xuU=", - "path": "google.golang.org/grpc/internal/backoff", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "Wxgih1pu+wvJRT/rCY9WgSMF4w4=", - "path": "google.golang.org/grpc/internal/binarylog", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "X8zn5E1oU4Ev2qbeiruRbbaTN8Y=", - "path": "google.golang.org/grpc/internal/channelz", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "i4SV6WG1mpU7hw8mtvY5HuXKUCI=", - "path": "google.golang.org/grpc/internal/envconfig", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "70gndc/uHwyAl3D45zqp7vyHWlo=", - "path": "google.golang.org/grpc/internal/grpcrand", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "psHSfNyU2y9L9zRK+s41e7ScTf4=", - "path": "google.golang.org/grpc/internal/grpcsync", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "3LK1XBsYw6P112yilUgf8E8ZZY8=", - "path": "google.golang.org/grpc/internal/syscall", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "tKN4e/kSnh2DCN9zUXQlKS07jAo=", - "path": "google.golang.org/grpc/internal/transport", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "cDYDzrrgfj9Y45GDWcXXCrRofp0=", - "path": "google.golang.org/grpc/keepalive", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "0OoJw+Wc7+1Ox5nBbwjgqWW8Xpw=", - "path": "google.golang.org/grpc/metadata", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "pA4e5yAJjAqCzz1FrutkeNHV5W8=", - "path": "google.golang.org/grpc/naming", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "ltPJN8UyzvWN0H0BvkP2AREujgQ=", - "path": "google.golang.org/grpc/peer", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "6vHMrRHRgTkFCgP1Pp5yTENQoV0=", - "path": "google.golang.org/grpc/resolver", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "jHyoB4k7uV8VIRHJm/Jscyp6EZY=", - "path": "google.golang.org/grpc/resolver/dns", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "voz1mta5+d5bXMGt9SK88Vys2iE=", - "path": "google.golang.org/grpc/resolver/passthrough", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "3ZPGj/HdfLTiK7I3xPdnqELnHdk=", - "path": "google.golang.org/grpc/stats", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "bJSa9mM309wvISy+B6zfc0KAUqs=", - "path": "google.golang.org/grpc/status", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "HGXDrPBB90iBU4NJ7C1N8MJRkI0=", - "path": "google.golang.org/grpc/tap", - "revision": "f1437f7cc5fa7525032e27aa5fdc15e288220c4e", - "revisionTime": "2019-03-27T23:19:28Z" - }, - { - "checksumSHA1": "wICWAGQfZcHD2y0dHesz9R2YSiw=", - "path": "k8s.io/kubernetes/pkg/apimachinery", - "revision": "b0b7a323cc5a4a2019b2e9520c21c7830b7f708e", - "revisionTime": "2017-04-03T20:32:25Z", - "version": "v1.6.1", - "versionExact": "v1.6.1" - } - ], - "rootPath": "github.com/terraform-providers/terraform-provider-vault" -} From fc58866fdff92f77e0bd7291296fcb2f08d11a06 Mon Sep 17 00:00:00 2001 From: Becca Petrin Date: Wed, 1 May 2019 17:07:05 +0300 Subject: [PATCH 24/35] Update vault/resource_jwt_auth_backend_role.go Co-Authored-By: sergeytrasko --- vault/resource_jwt_auth_backend_role.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/resource_jwt_auth_backend_role.go b/vault/resource_jwt_auth_backend_role.go index decd2d463..5794e92ca 100644 --- a/vault/resource_jwt_auth_backend_role.go +++ b/vault/resource_jwt_auth_backend_role.go @@ -109,7 +109,7 @@ func jwtAuthBackendRoleResource() *schema.Resource { "oidc_scopes": { Type: schema.TypeSet, Optional: true, - Description: "List of OIDC scopes to be used with an OIDC role. The standard scope \"openid\" is automatically included and need not be specified", + Description: "List of OIDC scopes to be used with an OIDC role. The standard scope \"openid\" is automatically included and need not be specified.", Elem: &schema.Schema{ Type: schema.TypeString, }, From 44cbc86a1dac49f97fc040fd96ccc2ed8e62bf3f Mon Sep 17 00:00:00 2001 From: Sergey Trasko Date: Wed, 1 May 2019 17:11:55 +0300 Subject: [PATCH 25/35] Fix compilation errors (after merge from master) --- vault/resource_jwt_auth_backend.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/resource_jwt_auth_backend.go b/vault/resource_jwt_auth_backend.go index 83b2dcc1b..39ee766f5 100644 --- a/vault/resource_jwt_auth_backend.go +++ b/vault/resource_jwt_auth_backend.go @@ -24,7 +24,7 @@ func jwtAuthBackendResource() *schema.Resource { Optional: true, ForceNew: true, Description: "path to mount the backend", - Default: jwtAuthType, + Default: "jwt", ValidateFunc: validateNoTrailingSlash, }, From 667e9be08642e171ee28761c2a882c9568139365 Mon Sep 17 00:00:00 2001 From: Brian Williams Date: Tue, 16 Apr 2019 11:26:40 -0500 Subject: [PATCH 26/35] Don't overwrite path with response value. Overwriting the path with the one returned by Vault causes an invalid namespace to be set when using nested namespaces. ex: namespace-b which is inside namespace-a will have the path overwritten with namespace-a/namespace-b/ when the correct value is namespace-b/ --- vault/resource_namespace.go | 1 - 1 file changed, 1 deletion(-) diff --git a/vault/resource_namespace.go b/vault/resource_namespace.go index 30f3365b4..b1a7c539a 100644 --- a/vault/resource_namespace.go +++ b/vault/resource_namespace.go @@ -75,7 +75,6 @@ func namespaceRead(d *schema.ResourceData, meta interface{}) error { // remove trailing slash namespacePath := filepath.Clean(resp.Data["path"].(string)) - d.Set("path", namespacePath) d.SetId(resp.Data["id"].(string)) return nil From a517d886c50675872a8094c9838c9bdab372618c Mon Sep 17 00:00:00 2001 From: Brian Williams Date: Wed, 1 May 2019 16:10:32 -0500 Subject: [PATCH 27/35] Add test case for nested namespaces --- vault/resource_namespace.go | 4 ---- vault/resource_namespace_test.go | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/vault/resource_namespace.go b/vault/resource_namespace.go index b1a7c539a..f5164bb61 100644 --- a/vault/resource_namespace.go +++ b/vault/resource_namespace.go @@ -3,7 +3,6 @@ package vault import ( "fmt" "log" - "path/filepath" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/vault/api" @@ -72,9 +71,6 @@ func namespaceRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error reading from Vault: %s", err) } - // remove trailing slash - namespacePath := filepath.Clean(resp.Data["path"].(string)) - d.SetId(resp.Data["id"].(string)) return nil diff --git a/vault/resource_namespace_test.go b/vault/resource_namespace_test.go index a27c9c9f9..26528d6c3 100644 --- a/vault/resource_namespace_test.go +++ b/vault/resource_namespace_test.go @@ -21,6 +21,7 @@ func TestNamespace_basic(t *testing.T) { } namespacePath := acctest.RandomWithPrefix("test-namespace") + childPath := acctest.RandomWithPrefix("child-namespace") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -36,6 +37,10 @@ func TestNamespace_basic(t *testing.T) { Destroy: false, ExpectError: regexp.MustCompile("vault_namespace\\.test: cannot write to a path ending in '/'"), }, + { + Config: testNestedNamespaceConfig(namespacePath, childPath), + Check: testNestedNamespaceCheckAttrs(childPath), + }, }, }) } @@ -80,3 +85,36 @@ resource "vault_namespace" "test" { `, path) } + +func testNestedNamespaceConfig(parentPath, childPath string) string { + return fmt.Sprintf(` +provider "vault" { + namespace = %q +} + +resource "vault_namespace" "test_child" { + path = %q +} +`, parentPath, childPath) +} + +func testNestedNamespaceCheckAttrs(expectedPath string) resource.TestCheckFunc { + return func(s *terraform.State) error { + resourceState := s.Modules[0].Resources["vault_namespace.test_child"] + if resourceState == nil { + return fmt.Errorf("child namespace resource not found in state") + } + + instanceState := resourceState.Primary + if instanceState == nil { + return fmt.Errorf("child namespace resource has no primary instance") + } + + actualPath := resourceState.Primary.Attributes["path"] + if actualPath != expectedPath { + return fmt.Errorf("expected path to be %s, got %s", expectedPath, actualPath) + } + + return nil + } +} From bff321ecd9dba91841f88f4f1e0783eead0c9747 Mon Sep 17 00:00:00 2001 From: Daniel Meszaros Date: Thu, 2 May 2019 14:29:06 +0200 Subject: [PATCH 28/35] updated `use_token_auth` to `use_token_groups` as per: https://github.com/terraform-providers/terraform-provider-vault/blob/0e404011b45a68275a77111b83aa917f1200c355/vault/resource_ldap_auth_backend.go#L112 --- website/docs/r/ldap_auth_backend.html.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/r/ldap_auth_backend.html.md b/website/docs/r/ldap_auth_backend.html.md index eba8f4e88..c52fb78d7 100644 --- a/website/docs/r/ldap_auth_backend.html.md +++ b/website/docs/r/ldap_auth_backend.html.md @@ -63,7 +63,7 @@ The following arguments are supported: * `groupattr` - (Optional) LDAP attribute to follow on objects returned by groupfilter -* `use_token_auth` - (Optional) Use the Active Directory tokenGroups constructed attribute of the user to find the group memberships +* `use_token_groups` - (Optional) Use the Active Directory tokenGroups constructed attribute of the user to find the group memberships * `path` - (Optional) Path to mount the LDAP auth backend under From 4a250483ee2915079fd62598fb3eb0d5c2ae738e Mon Sep 17 00:00:00 2001 From: Brian Williams Date: Thu, 2 May 2019 08:07:47 -0500 Subject: [PATCH 29/35] Use instanceState instead of resourceState.Primary --- vault/resource_namespace_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/resource_namespace_test.go b/vault/resource_namespace_test.go index 26528d6c3..7004fc0e2 100644 --- a/vault/resource_namespace_test.go +++ b/vault/resource_namespace_test.go @@ -110,7 +110,7 @@ func testNestedNamespaceCheckAttrs(expectedPath string) resource.TestCheckFunc { return fmt.Errorf("child namespace resource has no primary instance") } - actualPath := resourceState.Primary.Attributes["path"] + actualPath := instanceState.Attributes["path"] if actualPath != expectedPath { return fmt.Errorf("expected path to be %s, got %s", expectedPath, actualPath) } From 74fd6fbcb67d1cc6d00c328ea8e596298a75a042 Mon Sep 17 00:00:00 2001 From: Alex Pilon Date: Thu, 2 May 2019 16:32:22 -0400 Subject: [PATCH 30/35] vendor go modules --- go.mod | 96 +- go.sum | 142 +- vendor/cloud.google.com/go/AUTHORS | 15 + vendor/cloud.google.com/go/CONTRIBUTORS | 40 + .../go/internal/version/update_version.sh | 0 vendor/cloud.google.com/go/storage/bucket.go | 5 + vendor/cloud.google.com/go/storage/storage.go | 5 + vendor/github.com/SermoDigital/jose/LICENSE | 22 - .../SermoDigital/jose/crypto/doc.go | 4 - .../SermoDigital/jose/crypto/ecdsa.go | 117 - .../SermoDigital/jose/crypto/ecdsa_utils.go | 48 - .../SermoDigital/jose/crypto/errors.go | 9 - .../SermoDigital/jose/crypto/hmac.go | 81 - .../SermoDigital/jose/crypto/none.go | 72 - .../SermoDigital/jose/crypto/rsa.go | 80 - .../SermoDigital/jose/crypto/rsa_pss.go | 96 - .../SermoDigital/jose/crypto/rsa_utils.go | 70 - .../SermoDigital/jose/crypto/signature.go | 36 - .../jose/crypto/signing_method.go | 24 - .../SermoDigital/jose/jws/claims.go | 190 - .../github.com/SermoDigital/jose/jws/doc.go | 2 - .../SermoDigital/jose/jws/errors.go | 62 - .../github.com/SermoDigital/jose/jws/jws.go | 490 - .../SermoDigital/jose/jws/jws_serialize.go | 132 - .../SermoDigital/jose/jws/jws_validate.go | 203 - .../github.com/SermoDigital/jose/jws/jwt.go | 115 - .../SermoDigital/jose/jws/payload.go | 52 - .../SermoDigital/jose/jws/rawbase64.go | 28 - .../SermoDigital/jose/jws/signing_methods.go | 63 - .../SermoDigital/jose/jwt/claims.go | 274 - .../github.com/SermoDigital/jose/jwt/doc.go | 2 - vendor/github.com/SermoDigital/jose/jwt/eq.go | 47 - .../SermoDigital/jose/jwt/errors.go | 28 - .../github.com/SermoDigital/jose/jwt/jwt.go | 144 - .../github.com/agext/levenshtein/.gitignore | 53 + .../github.com/agext/levenshtein/.travis.yml | 25 + vendor/github.com/agext/levenshtein/test.sh | 0 .../apparentlymart/go-cidr/cidr/cidr.go | 102 +- .../apparentlymart/go-rundeck-api/LICENSE | 21 - .../apparentlymart/go-rundeck-api/README.md | 9 - .../go-textseg/textseg/make_tables.go | 307 + .../go-textseg/textseg/make_test_tables.go | 212 + vendor/github.com/armon/go-metrics/LICENSE | 20 - vendor/github.com/armon/go-metrics/README.md | 91 - .../armon/go-metrics/circonus/circonus.go | 119 - .../github.com/armon/go-metrics/const_unix.go | 12 - .../armon/go-metrics/const_windows.go | 13 - .../armon/go-metrics/datadog/dogstatsd.go | 140 - vendor/github.com/armon/go-metrics/inmem.go | 348 - .../armon/go-metrics/inmem_endpoint.go | 118 - .../armon/go-metrics/inmem_signal.go | 117 - vendor/github.com/armon/go-metrics/metrics.go | 278 - vendor/github.com/armon/go-metrics/sink.go | 115 - vendor/github.com/armon/go-metrics/start.go | 141 - vendor/github.com/armon/go-metrics/statsd.go | 184 - .../github.com/armon/go-metrics/statsite.go | 172 - vendor/github.com/armon/go-radix/.gitignore | 22 + vendor/github.com/armon/go-radix/.travis.yml | 3 + vendor/github.com/armon/go-radix/radix.go | 13 +- .../aws-sdk-go/aws/awsutil/string_value.go | 25 +- .../aws/aws-sdk-go/aws/client/client.go | 10 +- .../aws-sdk-go/aws/client/default_retryer.go | 80 +- .../aws/aws-sdk-go/aws/client/logger.go | 106 +- .../aws/client/metadata/client_info.go | 1 + .../github.com/aws/aws-sdk-go/aws/config.go | 86 +- .../aws/{context.go => context_1_5.go} | 40 +- .../aws/aws-sdk-go/aws/context_1_6.go | 41 - .../aws/aws-sdk-go/aws/context_1_7.go | 9 - .../aws/aws-sdk-go/aws/context_1_9.go | 11 + .../aws-sdk-go/aws/context_background_1_5.go | 56 + .../aws-sdk-go/aws/context_background_1_7.go | 20 + .../aws/aws-sdk-go/aws/context_sleep.go | 24 + .../aws/aws-sdk-go/aws/convert_types.go | 18 + .../aws-sdk-go/aws/corehandlers/handlers.go | 32 +- .../aws-sdk-go/aws/corehandlers/user_agent.go | 37 + .../aws/credentials/chain_provider.go | 4 +- .../aws-sdk-go/aws/credentials/credentials.go | 64 +- .../ec2rolecreds/ec2_role_provider.go | 6 +- .../aws/credentials/endpointcreds/provider.go | 7 + .../aws/credentials/env_provider.go | 4 - .../aws/credentials/processcreds/provider.go | 425 + .../shared_credentials_provider.go | 30 +- .../aws/credentials/static_provider.go | 2 - .../github.com/aws/aws-sdk-go/aws/csm/doc.go | 46 + .../aws/aws-sdk-go/aws/csm/enable.go | 67 + .../aws/aws-sdk-go/aws/csm/metric.go | 109 + .../aws/aws-sdk-go/aws/csm/metric_chan.go | 54 + .../aws-sdk-go/aws/csm/metric_exception.go | 26 + .../aws/aws-sdk-go/aws/csm/reporter.go | 260 + .../aws/aws-sdk-go/aws/defaults/defaults.go | 66 +- .../aws/aws-sdk-go/aws/ec2metadata/api.go | 12 +- .../aws/aws-sdk-go/aws/ec2metadata/service.go | 25 + .../aws/aws-sdk-go/aws/endpoints/decode.go | 59 +- .../aws/aws-sdk-go/aws/endpoints/defaults.go | 3034 +- .../aws/endpoints/dep_service_ids.go | 141 + .../aws/aws-sdk-go/aws/endpoints/doc.go | 4 +- .../aws/aws-sdk-go/aws/endpoints/endpoints.go | 24 +- .../aws/aws-sdk-go/aws/endpoints/v3model.go | 12 +- .../aws/endpoints/v3model_codegen.go | 24 +- .../github.com/aws/aws-sdk-go/aws/errors.go | 4 - .../github.com/aws/aws-sdk-go/aws/logger.go | 10 +- .../aws/aws-sdk-go/aws/request/handlers.go | 21 + .../aws-sdk-go/aws/request/offset_reader.go | 4 +- .../aws/aws-sdk-go/aws/request/request.go | 386 +- .../aws/aws-sdk-go/aws/request/request_1_7.go | 2 +- .../aws/aws-sdk-go/aws/request/request_1_8.go | 2 +- .../aws/request/request_pagination.go | 40 +- .../aws/aws-sdk-go/aws/request/retryer.go | 9 +- .../aws/aws-sdk-go/aws/request/validation.go | 54 +- .../aws/aws-sdk-go/aws/request/waiter.go | 16 +- .../aws/aws-sdk-go/aws/session/doc.go | 6 +- .../aws/aws-sdk-go/aws/session/env_config.go | 54 +- .../aws/aws-sdk-go/aws/session/session.go | 194 +- .../aws-sdk-go/aws/session/shared_config.go | 108 +- .../aws/aws-sdk-go/aws/signer/v4/v4.go | 203 +- vendor/github.com/aws/aws-sdk-go/aws/types.go | 83 + .../github.com/aws/aws-sdk-go/aws/version.go | 2 +- .../aws/aws-sdk-go/internal/ini/ast.go | 120 + .../aws-sdk-go/internal/ini/comma_token.go | 11 + .../aws-sdk-go/internal/ini/comment_token.go | 35 + .../aws/aws-sdk-go/internal/ini/doc.go | 29 + .../aws-sdk-go/internal/ini/empty_token.go | 4 + .../aws/aws-sdk-go/internal/ini/expression.go | 24 + .../aws/aws-sdk-go/internal/ini/fuzz.go | 17 + .../aws/aws-sdk-go/internal/ini/ini.go | 51 + .../aws/aws-sdk-go/internal/ini/ini_lexer.go | 165 + .../aws/aws-sdk-go/internal/ini/ini_parser.go | 347 + .../aws-sdk-go/internal/ini/literal_tokens.go | 324 + .../aws-sdk-go/internal/ini/newline_token.go | 30 + .../aws-sdk-go/internal/ini/number_helper.go | 152 + .../aws/aws-sdk-go/internal/ini/op_tokens.go | 39 + .../aws-sdk-go/internal/ini/parse_error.go | 43 + .../aws-sdk-go/internal/ini/parse_stack.go | 60 + .../aws/aws-sdk-go/internal/ini/sep_tokens.go | 41 + .../aws/aws-sdk-go/internal/ini/skipper.go | 45 + .../aws/aws-sdk-go/internal/ini/statement.go | 35 + .../aws/aws-sdk-go/internal/ini/value_util.go | 284 + .../aws/aws-sdk-go/internal/ini/visitor.go | 166 + .../aws/aws-sdk-go/internal/ini/walker.go | 25 + .../aws/aws-sdk-go/internal/ini/ws_token.go | 24 + .../aws/aws-sdk-go/internal/s3err/error.go | 57 + .../aws/aws-sdk-go/internal/sdkio/io_go1.6.go | 10 + .../aws/aws-sdk-go/internal/sdkio/io_go1.7.go | 12 + .../internal/sdkrand/locked_source.go | 29 + .../aws/aws-sdk-go/internal/sdkuri/path.go | 23 + .../internal/shareddefaults/ecs_container.go | 12 + .../private/protocol/eventstream/debug.go | 144 + .../private/protocol/eventstream/decode.go | 199 + .../private/protocol/eventstream/encode.go | 114 + .../private/protocol/eventstream/error.go | 23 + .../eventstream/eventstreamapi/api.go | 196 + .../eventstream/eventstreamapi/error.go | 24 + .../private/protocol/eventstream/header.go | 166 + .../protocol/eventstream/header_value.go | 501 + .../private/protocol/eventstream/message.go | 103 + .../aws/aws-sdk-go/private/protocol/host.go | 68 + .../private/protocol/host_prefix.go | 54 + .../aws-sdk-go/private/protocol/jsonvalue.go | 76 + .../aws-sdk-go/private/protocol/payload.go | 81 + .../private/protocol/query/build.go | 2 +- .../protocol/query/queryutil/queryutil.go | 11 +- .../private/protocol/query/unmarshal.go | 6 +- .../private/protocol/query/unmarshal_error.go | 14 +- .../aws-sdk-go/private/protocol/rest/build.go | 33 +- .../private/protocol/rest/unmarshal.go | 20 +- .../private/protocol/restxml/restxml.go | 12 +- .../aws-sdk-go/private/protocol/timestamp.go | 72 + .../private/protocol/xml/xmlutil/build.go | 32 +- .../private/protocol/xml/xmlutil/unmarshal.go | 20 +- .../protocol/xml/xmlutil/xml_to_struct.go | 1 + .../dynamodb/dynamodbattribute/converter.go | 443 - .../dynamodb/dynamodbattribute/decode.go | 772 - .../service/dynamodb/dynamodbattribute/doc.go | 101 - .../dynamodb/dynamodbattribute/encode.go | 646 - .../dynamodb/dynamodbattribute/field.go | 273 - .../service/dynamodb/dynamodbattribute/tag.go | 68 - .../aws/aws-sdk-go/service/iam/api.go | 10073 +- .../aws/aws-sdk-go/service/iam/doc.go | 2 +- .../aws/aws-sdk-go/service/iam/errors.go | 12 +- .../aws/aws-sdk-go/service/iam/service.go | 6 +- .../aws/aws-sdk-go/service/s3/api.go | 20494 ++-- .../aws/aws-sdk-go/service/s3/body_hash.go | 249 + .../aws/aws-sdk-go/service/s3/content_md5.go | 36 - .../aws-sdk-go/service/s3/customizations.go | 28 + .../aws/aws-sdk-go/service/s3/doc.go | 64 +- .../aws/aws-sdk-go/service/s3/doc_custom.go | 4 +- .../service/s3/host_style_bucket.go | 13 +- .../aws/aws-sdk-go/service/s3/service.go | 12 +- .../aws/aws-sdk-go/service/s3/sse.go | 18 +- .../aws-sdk-go/service/s3/statusok_error.go | 9 +- .../aws-sdk-go/service/s3/unmarshal_error.go | 52 +- .../aws/aws-sdk-go/service/s3/waiters.go | 8 +- .../aws/aws-sdk-go/service/sts/api.go | 317 +- .../aws/aws-sdk-go/service/sts/doc.go | 64 +- .../aws/aws-sdk-go/service/sts/service.go | 6 +- .../github.com/bgentry/speakeasy/.gitignore | 2 + vendor/github.com/blang/semver/.travis.yml | 21 + vendor/github.com/briankassouf/jose/LICENSE | 22 - .../briankassouf/jose/crypto/doc.go | 4 - .../briankassouf/jose/crypto/ecdsa.go | 138 - .../briankassouf/jose/crypto/ecdsa_utils.go | 48 - .../briankassouf/jose/crypto/errors.go | 9 - .../briankassouf/jose/crypto/hmac.go | 81 - .../briankassouf/jose/crypto/none.go | 72 - .../briankassouf/jose/crypto/rsa.go | 80 - .../briankassouf/jose/crypto/rsa_pss.go | 96 - .../briankassouf/jose/crypto/rsa_utils.go | 70 - .../briankassouf/jose/crypto/signature.go | 36 - .../jose/crypto/signing_method.go | 24 - .../briankassouf/jose/jws/claims.go | 190 - .../github.com/briankassouf/jose/jws/doc.go | 2 - .../briankassouf/jose/jws/errors.go | 62 - .../github.com/briankassouf/jose/jws/jws.go | 490 - .../briankassouf/jose/jws/jws_serialize.go | 132 - .../briankassouf/jose/jws/jws_validate.go | 203 - .../github.com/briankassouf/jose/jws/jwt.go | 115 - .../briankassouf/jose/jws/payload.go | 52 - .../briankassouf/jose/jws/rawbase64.go | 28 - .../briankassouf/jose/jws/signing_methods.go | 63 - .../briankassouf/jose/jwt/claims.go | 274 - .../github.com/briankassouf/jose/jwt/doc.go | 2 - vendor/github.com/briankassouf/jose/jwt/eq.go | 47 - .../briankassouf/jose/jwt/errors.go | 28 - .../github.com/briankassouf/jose/jwt/jwt.go | 144 - .../chrismalek/oktasdk-go/LICENSE.txt | 21 - .../chrismalek/oktasdk-go/okta/apps.go | 315 - .../chrismalek/oktasdk-go/okta/factors.go | 8 - .../chrismalek/oktasdk-go/okta/groups.go | 359 - .../chrismalek/oktasdk-go/okta/sdk.go | 523 - .../chrismalek/oktasdk-go/okta/users.go | 625 - .../cockroachdb/cockroach-go/LICENSE | 202 - .../cockroachdb/cockroach-go/crdb/error.go | 73 - .../cockroachdb/cockroach-go/crdb/tx.go | 133 - vendor/github.com/davecgh/go-spew/LICENSE | 2 +- .../github.com/davecgh/go-spew/spew/bypass.go | 187 +- .../davecgh/go-spew/spew/bypasssafe.go | 2 +- .../github.com/davecgh/go-spew/spew/common.go | 2 +- .../github.com/davecgh/go-spew/spew/dump.go | 10 +- .../github.com/davecgh/go-spew/spew/format.go | 4 +- .../denisenkom/go-mssqldb/LICENSE.txt | 27 - .../denisenkom/go-mssqldb/README.md | 215 - .../denisenkom/go-mssqldb/appveyor.yml | 48 - .../github.com/denisenkom/go-mssqldb/buf.go | 258 - .../denisenkom/go-mssqldb/bulkcopy.go | 554 - .../denisenkom/go-mssqldb/bulkcopy_sql.go | 93 - .../denisenkom/go-mssqldb/convert.go | 306 - .../denisenkom/go-mssqldb/decimal.go | 131 - .../github.com/denisenkom/go-mssqldb/doc.go | 14 - .../github.com/denisenkom/go-mssqldb/error.go | 73 - .../github.com/denisenkom/go-mssqldb/log.go | 30 - .../github.com/denisenkom/go-mssqldb/mssql.go | 962 - .../denisenkom/go-mssqldb/mssql_go110.go | 50 - .../denisenkom/go-mssqldb/mssql_go19.go | 171 - .../denisenkom/go-mssqldb/mssql_go19pre.go | 16 - .../github.com/denisenkom/go-mssqldb/net.go | 103 - .../github.com/denisenkom/go-mssqldb/ntlm.go | 283 - .../denisenkom/go-mssqldb/parser.go | 257 - .../github.com/denisenkom/go-mssqldb/rpc.go | 89 - .../denisenkom/go-mssqldb/sspi_windows.go | 266 - .../github.com/denisenkom/go-mssqldb/tds.go | 1367 - .../github.com/denisenkom/go-mssqldb/token.go | 804 - .../denisenkom/go-mssqldb/token_string.go | 53 - .../github.com/denisenkom/go-mssqldb/tran.go | 110 - .../github.com/denisenkom/go-mssqldb/types.go | 1566 - .../denisenkom/go-mssqldb/uniqueidentifier.go | 74 - vendor/github.com/fatih/color/.travis.yml | 5 + vendor/github.com/fatih/structs/LICENSE | 21 - vendor/github.com/fatih/structs/README.md | 163 - vendor/github.com/fatih/structs/field.go | 141 - vendor/github.com/fatih/structs/structs.go | 586 - vendor/github.com/fatih/structs/tags.go | 32 - .../github.com/fsouza/go-dockerclient/AUTHORS | 136 - .../fsouza/go-dockerclient/DOCKER-LICENSE | 6 - .../github.com/fsouza/go-dockerclient/LICENSE | 22 - .../fsouza/go-dockerclient/Makefile | 57 - .../fsouza/go-dockerclient/README.markdown | 106 - .../github.com/fsouza/go-dockerclient/auth.go | 158 - .../fsouza/go-dockerclient/cancelable.go | 17 - .../fsouza/go-dockerclient/cancelable_go14.go | 19 - .../fsouza/go-dockerclient/change.go | 43 - .../fsouza/go-dockerclient/client.go | 995 - .../fsouza/go-dockerclient/container.go | 1325 - .../github.com/fsouza/go-dockerclient/env.go | 168 - .../fsouza/go-dockerclient/event.go | 379 - .../github.com/fsouza/go-dockerclient/exec.go | 202 - .../github.com/Sirupsen/logrus/CHANGELOG.md | 55 - .../github.com/Sirupsen/logrus/LICENSE | 21 - .../github.com/Sirupsen/logrus/README.md | 365 - .../github.com/Sirupsen/logrus/doc.go | 26 - .../github.com/Sirupsen/logrus/entry.go | 264 - .../github.com/Sirupsen/logrus/exported.go | 193 - .../github.com/Sirupsen/logrus/formatter.go | 48 - .../github.com/Sirupsen/logrus/hooks.go | 34 - .../Sirupsen/logrus/json_formatter.go | 41 - .../github.com/Sirupsen/logrus/logger.go | 212 - .../github.com/Sirupsen/logrus/logrus.go | 98 - .../Sirupsen/logrus/terminal_bsd.go | 9 - .../Sirupsen/logrus/terminal_linux.go | 12 - .../Sirupsen/logrus/terminal_notwindows.go | 21 - .../Sirupsen/logrus/terminal_solaris.go | 15 - .../Sirupsen/logrus/terminal_windows.go | 27 - .../Sirupsen/logrus/text_formatter.go | 161 - .../github.com/Sirupsen/logrus/writer.go | 31 - .../github.com/docker/docker/opts/envfile.go | 67 - .../github.com/docker/docker/opts/hosts.go | 146 - .../docker/docker/opts/hosts_unix.go | 8 - .../docker/docker/opts/hosts_windows.go | 6 - .../github.com/docker/docker/opts/ip.go | 42 - .../github.com/docker/docker/opts/opts.go | 252 - .../docker/docker/opts/opts_unix.go | 6 - .../docker/docker/opts/opts_windows.go | 56 - .../docker/docker/pkg/archive/README.md | 1 - .../docker/docker/pkg/archive/archive.go | 1049 - .../docker/docker/pkg/archive/archive_unix.go | 112 - .../docker/pkg/archive/archive_windows.go | 70 - .../docker/docker/pkg/archive/changes.go | 416 - .../docker/pkg/archive/changes_linux.go | 285 - .../docker/pkg/archive/changes_other.go | 97 - .../docker/docker/pkg/archive/changes_unix.go | 36 - .../docker/pkg/archive/changes_windows.go | 30 - .../docker/docker/pkg/archive/copy.go | 458 - .../docker/docker/pkg/archive/copy_unix.go | 11 - .../docker/docker/pkg/archive/copy_windows.go | 9 - .../docker/docker/pkg/archive/diff.go | 279 - .../docker/docker/pkg/archive/time_linux.go | 16 - .../docker/pkg/archive/time_unsupported.go | 16 - .../docker/docker/pkg/archive/whiteouts.go | 23 - .../docker/docker/pkg/archive/wrap.go | 59 - .../docker/docker/pkg/fileutils/fileutils.go | 279 - .../docker/pkg/fileutils/fileutils_unix.go | 22 - .../docker/pkg/fileutils/fileutils_windows.go | 7 - .../docker/docker/pkg/homedir/homedir.go | 39 - .../docker/docker/pkg/idtools/idtools.go | 195 - .../docker/docker/pkg/idtools/idtools_unix.go | 60 - .../docker/pkg/idtools/idtools_windows.go | 18 - .../docker/pkg/idtools/usergroupadd_linux.go | 155 - .../pkg/idtools/usergroupadd_unsupported.go | 12 - .../docker/docker/pkg/ioutils/bytespipe.go | 152 - .../docker/docker/pkg/ioutils/fmt.go | 22 - .../docker/docker/pkg/ioutils/multireader.go | 226 - .../docker/docker/pkg/ioutils/readers.go | 154 - .../docker/docker/pkg/ioutils/scheduler.go | 6 - .../docker/pkg/ioutils/scheduler_gccgo.go | 13 - .../docker/docker/pkg/ioutils/temp_unix.go | 10 - .../docker/docker/pkg/ioutils/temp_windows.go | 18 - .../docker/docker/pkg/ioutils/writeflusher.go | 92 - .../docker/docker/pkg/ioutils/writers.go | 66 - .../docker/docker/pkg/longpath/longpath.go | 26 - .../docker/docker/pkg/pools/pools.go | 119 - .../docker/docker/pkg/promise/promise.go | 11 - .../docker/docker/pkg/stdcopy/stdcopy.go | 175 - .../docker/docker/pkg/system/chtimes.go | 47 - .../docker/docker/pkg/system/chtimes_unix.go | 14 - .../docker/pkg/system/chtimes_windows.go | 27 - .../docker/docker/pkg/system/errors.go | 10 - .../docker/pkg/system/events_windows.go | 83 - .../docker/docker/pkg/system/filesys.go | 19 - .../docker/pkg/system/filesys_windows.go | 82 - .../docker/docker/pkg/system/lstat.go | 19 - .../docker/docker/pkg/system/lstat_windows.go | 25 - .../docker/docker/pkg/system/meminfo.go | 17 - .../docker/docker/pkg/system/meminfo_linux.go | 66 - .../docker/pkg/system/meminfo_unsupported.go | 8 - .../docker/pkg/system/meminfo_windows.go | 44 - .../docker/docker/pkg/system/mknod.go | 22 - .../docker/docker/pkg/system/mknod_windows.go | 13 - .../docker/docker/pkg/system/path_unix.go | 8 - .../docker/docker/pkg/system/path_windows.go | 7 - .../docker/docker/pkg/system/stat.go | 53 - .../docker/docker/pkg/system/stat_freebsd.go | 27 - .../docker/docker/pkg/system/stat_linux.go | 33 - .../docker/docker/pkg/system/stat_openbsd.go | 15 - .../docker/docker/pkg/system/stat_solaris.go | 17 - .../docker/pkg/system/stat_unsupported.go | 17 - .../docker/docker/pkg/system/stat_windows.go | 43 - .../docker/docker/pkg/system/syscall_unix.go | 11 - .../docker/pkg/system/syscall_windows.go | 36 - .../docker/docker/pkg/system/umask.go | 13 - .../docker/docker/pkg/system/umask_windows.go | 9 - .../docker/docker/pkg/system/utimes_darwin.go | 8 - .../docker/pkg/system/utimes_freebsd.go | 22 - .../docker/docker/pkg/system/utimes_linux.go | 26 - .../docker/pkg/system/utimes_unsupported.go | 10 - .../docker/docker/pkg/system/xattrs_linux.go | 63 - .../docker/pkg/system/xattrs_unsupported.go | 13 - .../docker/go-units/CONTRIBUTING.md | 67 - .../github.com/docker/go-units/LICENSE.code | 191 - .../github.com/docker/go-units/LICENSE.docs | 425 - .../github.com/docker/go-units/MAINTAINERS | 27 - .../github.com/docker/go-units/README.md | 18 - .../github.com/docker/go-units/circle.yml | 11 - .../github.com/docker/go-units/duration.go | 33 - .../github.com/docker/go-units/size.go | 95 - .../github.com/docker/go-units/ulimit.go | 118 - .../github.com/gorilla/context/LICENSE | 27 - .../github.com/gorilla/context/README.md | 7 - .../github.com/gorilla/context/context.go | 143 - .../github.com/gorilla/context/doc.go | 82 - .../external/github.com/gorilla/mux/LICENSE | 27 - .../external/github.com/gorilla/mux/README.md | 240 - .../external/github.com/gorilla/mux/doc.go | 206 - .../external/github.com/gorilla/mux/mux.go | 481 - .../external/github.com/gorilla/mux/regexp.go | 317 - .../external/github.com/gorilla/mux/route.go | 595 - .../github.com/hashicorp/go-cleanhttp/LICENSE | 363 - .../hashicorp/go-cleanhttp/README.md | 30 - .../hashicorp/go-cleanhttp/cleanhttp.go | 40 - .../runc/libcontainer/user/MAINTAINERS | 2 - .../runc/libcontainer/user/lookup.go | 108 - .../runc/libcontainer/user/lookup_unix.go | 30 - .../libcontainer/user/lookup_unsupported.go | 21 - .../runc/libcontainer/user/user.go | 418 - .../golang.org/x/net/context/context.go | 447 - .../external/golang.org/x/sys/unix/asm.s | 10 - .../golang.org/x/sys/unix/asm_darwin_386.s | 29 - .../golang.org/x/sys/unix/asm_darwin_amd64.s | 29 - .../golang.org/x/sys/unix/asm_darwin_arm.s | 30 - .../golang.org/x/sys/unix/asm_dragonfly_386.s | 29 - .../x/sys/unix/asm_dragonfly_amd64.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_386.s | 29 - .../golang.org/x/sys/unix/asm_freebsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_linux_386.s | 35 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 29 - .../golang.org/x/sys/unix/asm_linux_arm.s | 29 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 24 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 28 - .../golang.org/x/sys/unix/asm_netbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_netbsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_netbsd_arm.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_386.s | 29 - .../golang.org/x/sys/unix/asm_openbsd_amd64.s | 29 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 17 - .../golang.org/x/sys/unix/constants.go | 13 - .../golang.org/x/sys/unix/env_unix.go | 27 - .../golang.org/x/sys/unix/env_unset.go | 14 - .../external/golang.org/x/sys/unix/flock.go | 24 - .../x/sys/unix/flock_linux_32bit.go | 13 - .../external/golang.org/x/sys/unix/gccgo.go | 46 - .../external/golang.org/x/sys/unix/gccgo_c.c | 41 - .../x/sys/unix/gccgo_linux_amd64.go | 20 - .../external/golang.org/x/sys/unix/mkall.sh | 274 - .../golang.org/x/sys/unix/mkerrors.sh | 476 - .../golang.org/x/sys/unix/mksyscall.pl | 323 - .../x/sys/unix/mksyscall_solaris.pl | 294 - .../golang.org/x/sys/unix/mksysctl_openbsd.pl | 264 - .../golang.org/x/sys/unix/mksysnum_darwin.pl | 39 - .../x/sys/unix/mksysnum_dragonfly.pl | 50 - .../golang.org/x/sys/unix/mksysnum_freebsd.pl | 63 - .../golang.org/x/sys/unix/mksysnum_linux.pl | 58 - .../golang.org/x/sys/unix/mksysnum_netbsd.pl | 58 - .../golang.org/x/sys/unix/mksysnum_openbsd.pl | 50 - .../external/golang.org/x/sys/unix/race.go | 30 - .../external/golang.org/x/sys/unix/race0.go | 25 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 36 - .../golang.org/x/sys/unix/sockcmsg_unix.go | 103 - .../external/golang.org/x/sys/unix/str.go | 26 - .../external/golang.org/x/sys/unix/syscall.go | 74 - .../golang.org/x/sys/unix/syscall_bsd.go | 628 - .../golang.org/x/sys/unix/syscall_darwin.go | 509 - .../x/sys/unix/syscall_darwin_386.go | 79 - .../x/sys/unix/syscall_darwin_amd64.go | 81 - .../x/sys/unix/syscall_darwin_arm.go | 73 - .../x/sys/unix/syscall_darwin_arm64.go | 79 - .../x/sys/unix/syscall_dragonfly.go | 411 - .../x/sys/unix/syscall_dragonfly_386.go | 63 - .../x/sys/unix/syscall_dragonfly_amd64.go | 63 - .../golang.org/x/sys/unix/syscall_freebsd.go | 682 - .../x/sys/unix/syscall_freebsd_386.go | 63 - .../x/sys/unix/syscall_freebsd_arm.go | 63 - .../golang.org/x/sys/unix/syscall_linux.go | 1086 - .../x/sys/unix/syscall_linux_386.go | 388 - .../x/sys/unix/syscall_linux_amd64.go | 146 - .../x/sys/unix/syscall_linux_arm.go | 233 - .../x/sys/unix/syscall_linux_arm64.go | 150 - .../x/sys/unix/syscall_linux_ppc64x.go | 96 - .../golang.org/x/sys/unix/syscall_netbsd.go | 492 - .../x/sys/unix/syscall_netbsd_386.go | 44 - .../x/sys/unix/syscall_netbsd_amd64.go | 44 - .../x/sys/unix/syscall_netbsd_arm.go | 44 - .../golang.org/x/sys/unix/syscall_no_getwd.go | 11 - .../golang.org/x/sys/unix/syscall_openbsd.go | 303 - .../x/sys/unix/syscall_openbsd_386.go | 44 - .../x/sys/unix/syscall_openbsd_amd64.go | 44 - .../golang.org/x/sys/unix/syscall_solaris.go | 713 - .../x/sys/unix/syscall_solaris_amd64.go | 37 - .../golang.org/x/sys/unix/syscall_unix.go | 297 - .../x/sys/unix/zerrors_darwin_386.go | 1576 - .../x/sys/unix/zerrors_darwin_amd64.go | 1576 - .../x/sys/unix/zerrors_darwin_arm.go | 1293 - .../x/sys/unix/zerrors_darwin_arm64.go | 1576 - .../x/sys/unix/zerrors_dragonfly_386.go | 1530 - .../x/sys/unix/zerrors_dragonfly_amd64.go | 1530 - .../x/sys/unix/zerrors_freebsd_386.go | 1743 - .../x/sys/unix/zerrors_freebsd_amd64.go | 1748 - .../x/sys/unix/zerrors_freebsd_arm.go | 1729 - .../x/sys/unix/zerrors_linux_386.go | 1817 - .../x/sys/unix/zerrors_linux_amd64.go | 1818 - .../x/sys/unix/zerrors_linux_arm.go | 1742 - .../x/sys/unix/zerrors_linux_arm64.go | 1896 - .../x/sys/unix/zerrors_linux_ppc64.go | 1969 - .../x/sys/unix/zerrors_linux_ppc64le.go | 1968 - .../x/sys/unix/zerrors_netbsd_386.go | 1712 - .../x/sys/unix/zerrors_netbsd_arm.go | 1688 - .../x/sys/unix/zerrors_openbsd_386.go | 1584 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1583 - .../x/sys/unix/zerrors_solaris_amd64.go | 1436 - .../x/sys/unix/zsyscall_darwin_arm.go | 1426 - .../x/sys/unix/zsyscall_darwin_arm64.go | 1426 - .../x/sys/unix/zsyscall_dragonfly_386.go | 1412 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1412 - .../x/sys/unix/zsyscall_linux_386.go | 1628 - .../x/sys/unix/zsyscall_linux_amd64.go | 1822 - .../x/sys/unix/zsyscall_linux_arm.go | 1756 - .../x/sys/unix/zsyscall_linux_arm64.go | 1750 - .../x/sys/unix/zsyscall_linux_ppc64.go | 1792 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 1792 - .../x/sys/unix/zsyscall_netbsd_386.go | 1326 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1326 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1326 - .../x/sys/unix/zsyscall_openbsd_386.go | 1386 - .../x/sys/unix/zsyscall_openbsd_amd64.go | 1386 - .../x/sys/unix/zsyscall_solaris_amd64.go | 1559 - .../golang.org/x/sys/unix/zsysctl_openbsd.go | 270 - .../x/sys/unix/zsysnum_darwin_386.go | 398 - .../x/sys/unix/zsysnum_darwin_amd64.go | 398 - .../x/sys/unix/zsysnum_darwin_arm.go | 358 - .../x/sys/unix/zsysnum_darwin_arm64.go | 398 - .../x/sys/unix/zsysnum_dragonfly_386.go | 304 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 304 - .../x/sys/unix/zsysnum_freebsd_386.go | 351 - .../x/sys/unix/zsysnum_freebsd_arm.go | 351 - .../x/sys/unix/zsysnum_linux_386.go | 355 - .../x/sys/unix/zsysnum_linux_amd64.go | 321 - .../x/sys/unix/zsysnum_linux_arm.go | 356 - .../x/sys/unix/zsysnum_linux_arm64.go | 272 - .../x/sys/unix/zsysnum_linux_ppc64.go | 360 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 353 - .../x/sys/unix/zsysnum_netbsd_386.go | 273 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 273 - .../x/sys/unix/zsysnum_openbsd_386.go | 207 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 207 - .../x/sys/unix/zsysnum_solaris_amd64.go | 13 - .../x/sys/unix/ztypes_darwin_386.go | 447 - .../x/sys/unix/ztypes_darwin_amd64.go | 462 - .../x/sys/unix/ztypes_darwin_arm.go | 449 - .../x/sys/unix/ztypes_darwin_arm64.go | 457 - .../x/sys/unix/ztypes_dragonfly_386.go | 437 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 443 - .../x/sys/unix/ztypes_freebsd_386.go | 502 - .../x/sys/unix/ztypes_freebsd_arm.go | 497 - .../golang.org/x/sys/unix/ztypes_linux_386.go | 590 - .../x/sys/unix/ztypes_linux_amd64.go | 608 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 579 - .../x/sys/unix/ztypes_linux_arm64.go | 595 - .../x/sys/unix/ztypes_linux_ppc64.go | 605 - .../x/sys/unix/ztypes_linux_ppc64le.go | 605 - .../x/sys/unix/ztypes_netbsd_386.go | 396 - .../x/sys/unix/ztypes_netbsd_arm.go | 401 - .../x/sys/unix/ztypes_openbsd_386.go | 441 - .../x/sys/unix/ztypes_openbsd_amd64.go | 448 - .../x/sys/unix/ztypes_solaris_amd64.go | 422 - .../fsouza/go-dockerclient/image.go | 642 - .../github.com/fsouza/go-dockerclient/misc.go | 124 - .../fsouza/go-dockerclient/network.go | 273 - .../fsouza/go-dockerclient/signal.go | 49 - .../github.com/fsouza/go-dockerclient/tar.go | 117 - .../go-dockerclient/testing/data/Dockerfile | 15 - .../go-dockerclient/testing/data/barfile | 0 .../go-dockerclient/testing/data/ca.pem | 18 - .../go-dockerclient/testing/data/cert.pem | 18 - .../testing/data/container.tar | Bin 2048 -> 0 bytes .../testing/data/dockerfile.tar | Bin 2560 -> 0 bytes .../go-dockerclient/testing/data/foofile | 0 .../go-dockerclient/testing/data/key.pem | 27 - .../go-dockerclient/testing/data/server.pem | 18 - .../testing/data/serverkey.pem | 27 - .../fsouza/go-dockerclient/testing/server.go | 1334 - .../github.com/fsouza/go-dockerclient/tls.go | 118 - .../travis-scripts/install.bash | 17 - .../travis-scripts/run-tests.bash | 15 - .../fsouza/go-dockerclient/volume.go | 128 - vendor/github.com/ghodss/yaml/LICENSE | 50 - vendor/github.com/ghodss/yaml/README.md | 121 - vendor/github.com/ghodss/yaml/fields.go | 501 - vendor/github.com/ghodss/yaml/yaml.go | 305 - vendor/github.com/ghodss/yaml/yaml_go110.go | 14 - .../github.com/go-errors/errors/LICENSE.MIT | 7 - vendor/github.com/go-errors/errors/README.md | 66 - vendor/github.com/go-errors/errors/cover.out | 89 - vendor/github.com/go-errors/errors/error.go | 224 - .../go-errors/errors/parse_panic.go | 127 - .../github.com/go-errors/errors/stackframe.go | 102 - vendor/github.com/go-ini/ini/LICENSE | 191 - vendor/github.com/go-ini/ini/Makefile | 12 - vendor/github.com/go-ini/ini/README.md | 734 - vendor/github.com/go-ini/ini/README_ZH.md | 721 - vendor/github.com/go-ini/ini/error.go | 32 - vendor/github.com/go-ini/ini/ini.go | 535 - vendor/github.com/go-ini/ini/key.go | 633 - vendor/github.com/go-ini/ini/parser.go | 356 - vendor/github.com/go-ini/ini/section.go | 221 - vendor/github.com/go-ini/ini/struct.go | 431 - vendor/github.com/golang/protobuf/AUTHORS | 3 + .../github.com/golang/protobuf/CONTRIBUTORS | 3 + vendor/github.com/golang/snappy/.gitignore | 16 + vendor/github.com/golang/snappy/AUTHORS | 15 + vendor/github.com/golang/snappy/CONTRIBUTORS | 37 + .../go-github => golang/snappy}/LICENSE | 2 +- vendor/github.com/golang/snappy/README | 107 + vendor/github.com/golang/snappy/decode.go | 237 + .../github.com/golang/snappy/decode_amd64.go | 14 + .../github.com/golang/snappy/decode_amd64.s | 490 + .../github.com/golang/snappy/decode_other.go | 101 + vendor/github.com/golang/snappy/encode.go | 285 + .../github.com/golang/snappy/encode_amd64.go | 29 + .../github.com/golang/snappy/encode_amd64.s | 730 + .../github.com/golang/snappy/encode_other.go | 238 + vendor/github.com/golang/snappy/snappy.go | 98 + .../github.com/google/go-cmp/cmp/compare.go | 557 +- .../go-cmp/cmp/internal/diff/debug_disable.go | 2 +- .../go-cmp/cmp/internal/diff/debug_enable.go | 4 +- .../google/go-cmp/cmp/internal/diff/diff.go | 31 +- .../google/go-cmp/cmp/internal/flags/flags.go | 9 - .../cmp/internal/flags/toolchain_legacy.go | 10 - .../cmp/internal/flags/toolchain_recent.go | 10 - .../go-cmp/cmp/internal/function/func.go | 64 +- .../go-cmp/cmp/internal/value/format.go | 277 + .../cmp/internal/value/pointer_purego.go | 23 - .../cmp/internal/value/pointer_unsafe.go | 26 - .../google/go-cmp/cmp/internal/value/sort.go | 9 +- .../google/go-cmp/cmp/internal/value/zero.go | 45 - .../github.com/google/go-cmp/cmp/options.go | 255 +- vendor/github.com/google/go-cmp/cmp/path.go | 339 +- vendor/github.com/google/go-cmp/cmp/report.go | 51 - .../google/go-cmp/cmp/report_compare.go | 296 - .../google/go-cmp/cmp/report_reflect.go | 279 - .../google/go-cmp/cmp/report_slices.go | 333 - .../google/go-cmp/cmp/report_text.go | 382 - .../google/go-cmp/cmp/report_value.go | 121 - .../github.com/google/go-cmp/cmp/reporter.go | 53 + .../cmp/{export_panic.go => unsafe_panic.go} | 6 +- .../{export_unsafe.go => unsafe_reflect.go} | 8 +- .../google/go-github/github/activity.go | 69 - .../go-github/github/activity_events.go | 328 - .../github/activity_notifications.go | 223 - .../google/go-github/github/activity_star.go | 135 - .../go-github/github/activity_watching.go | 146 - .../google/go-github/github/admin.go | 101 - .../google/go-github/github/admin_stats.go | 171 - .../google/go-github/github/apps.go | 230 - .../go-github/github/apps_installation.go | 101 - .../go-github/github/apps_marketplace.go | 168 - .../google/go-github/github/authorizations.go | 435 - .../google/go-github/github/checks.go | 421 - .../github.com/google/go-github/github/doc.go | 187 - .../google/go-github/github/event_types.go | 787 - .../google/go-github/github/gists.go | 358 - .../google/go-github/github/gists_comments.go | 119 - .../github.com/google/go-github/github/git.go | 12 - .../google/go-github/github/git_blobs.go | 69 - .../google/go-github/github/git_commits.go | 134 - .../google/go-github/github/git_refs.go | 218 - .../google/go-github/github/git_tags.go | 79 - .../google/go-github/github/git_trees.go | 99 - .../go-github/github/github-accessors.go | 11981 -- .../google/go-github/github/github.go | 996 - .../google/go-github/github/gitignore.go | 64 - .../google/go-github/github/issues.go | 347 - .../go-github/github/issues_assignees.go | 85 - .../go-github/github/issues_comments.go | 152 - .../google/go-github/github/issues_events.go | 158 - .../google/go-github/github/issues_labels.go | 261 - .../go-github/github/issues_milestones.go | 148 - .../go-github/github/issues_timeline.go | 149 - .../google/go-github/github/licenses.go | 97 - .../google/go-github/github/messages.go | 247 - .../google/go-github/github/migrations.go | 224 - .../github/migrations_source_import.go | 329 - .../go-github/github/migrations_user.go | 214 - .../google/go-github/github/misc.go | 257 - .../google/go-github/github/orgs.go | 197 - .../google/go-github/github/orgs_hooks.go | 107 - .../google/go-github/github/orgs_members.go | 370 - .../github/orgs_outside_collaborators.go | 81 - .../google/go-github/github/orgs_projects.go | 60 - .../go-github/github/orgs_users_blocking.go | 91 - .../google/go-github/github/projects.go | 462 - .../google/go-github/github/pulls.go | 383 - .../google/go-github/github/pulls_comments.go | 188 - .../go-github/github/pulls_reviewers.go | 79 - .../google/go-github/github/pulls_reviews.go | 236 - .../google/go-github/github/reactions.go | 375 - .../google/go-github/github/repos.go | 1082 - .../go-github/github/repos_collaborators.go | 140 - .../google/go-github/github/repos_comments.go | 161 - .../google/go-github/github/repos_commits.go | 237 - .../github/repos_community_health.go | 59 - .../google/go-github/github/repos_contents.go | 266 - .../go-github/github/repos_deployments.go | 224 - .../google/go-github/github/repos_forks.go | 89 - .../google/go-github/github/repos_hooks.go | 200 - .../go-github/github/repos_invitations.go | 98 - .../google/go-github/github/repos_keys.go | 111 - .../google/go-github/github/repos_merging.go | 38 - .../google/go-github/github/repos_pages.go | 143 - .../github/repos_prereceive_hooks.go | 110 - .../google/go-github/github/repos_projects.go | 69 - .../google/go-github/github/repos_releases.go | 370 - .../google/go-github/github/repos_stats.go | 226 - .../google/go-github/github/repos_statuses.go | 129 - .../google/go-github/github/repos_traffic.go | 141 - .../google/go-github/github/search.go | 261 - .../google/go-github/github/strings.go | 93 - .../google/go-github/github/teams.go | 357 - .../github/teams_discussion_comments.go | 155 - .../go-github/github/teams_discussions.go | 160 - .../google/go-github/github/teams_members.go | 174 - .../google/go-github/github/timestamp.go | 41 - .../google/go-github/github/users.go | 284 - .../go-github/github/users_administration.go | 67 - .../google/go-github/github/users_blocking.go | 91 - .../google/go-github/github/users_emails.go | 71 - .../go-github/github/users_followers.go | 119 - .../google/go-github/github/users_gpg_keys.go | 140 - .../google/go-github/github/users_keys.go | 108 - .../go-github/github/without_appengine.go | 19 - .../googleapis/gax-go/{ => v2}/LICENSE | 0 vendor/github.com/gosimple/slug/.gitignore | 2 + vendor/github.com/gosimple/slug/.travis.yml | 20 + vendor/github.com/hashicorp/consul/LICENSE | 354 - vendor/github.com/hashicorp/consul/NOTICE.md | 3 - .../github.com/hashicorp/consul/api/README.md | 67 - vendor/github.com/hashicorp/consul/api/acl.go | 193 - .../github.com/hashicorp/consul/api/agent.go | 799 - vendor/github.com/hashicorp/consul/api/api.go | 839 - .../hashicorp/consul/api/catalog.go | 219 - .../hashicorp/consul/api/connect.go | 12 - .../hashicorp/consul/api/connect_ca.go | 172 - .../hashicorp/consul/api/connect_intention.go | 302 - .../hashicorp/consul/api/coordinate.go | 106 - .../github.com/hashicorp/consul/api/event.go | 104 - .../github.com/hashicorp/consul/api/health.go | 232 - vendor/github.com/hashicorp/consul/api/kv.go | 420 - .../github.com/hashicorp/consul/api/lock.go | 386 - .../hashicorp/consul/api/operator.go | 11 - .../hashicorp/consul/api/operator_area.go | 194 - .../consul/api/operator_autopilot.go | 219 - .../hashicorp/consul/api/operator_keyring.go | 86 - .../hashicorp/consul/api/operator_raft.go | 89 - .../hashicorp/consul/api/operator_segment.go | 11 - .../hashicorp/consul/api/prepared_query.go | 212 - vendor/github.com/hashicorp/consul/api/raw.go | 24 - .../hashicorp/consul/api/semaphore.go | 514 - .../hashicorp/consul/api/session.go | 224 - .../hashicorp/consul/api/snapshot.go | 47 - .../github.com/hashicorp/consul/api/status.go | 43 - vendor/github.com/hashicorp/errwrap/README.md | 2 +- vendor/github.com/hashicorp/errwrap/go.mod | 1 + .../hashicorp/go-cleanhttp/cleanhttp.go | 1 + .../github.com/hashicorp/go-cleanhttp/go.mod | 1 + .../hashicorp/go-cleanhttp/handlers.go | 48 + .../hashicorp/go-gcp-common/LICENSE | 363 - .../go-gcp-common/gcputil/compute.go | 111 - .../go-gcp-common/gcputil/credentials.go | 178 - .../go-gcp-common/gcputil/iam_admin.go | 51 - .../go-gcp-common/gcputil/resource_name.go | 128 - .../hashicorp/go-getter/.travis.yml | 24 + .../github.com/hashicorp/go-hclog/.gitignore | 1 + .../github.com/hashicorp/go-hclog/README.md | 15 + .../github.com/hashicorp/go-hclog/global.go | 10 +- .../go-hclog/{int.go => intlogger.go} | 310 +- .../hashicorp/go-hclog/{log.go => logger.go} | 39 +- .../hashicorp/go-hclog/nulllogger.go | 7 +- .../hashicorp/go-hclog/stacktrace.go | 9 +- .../github.com/hashicorp/go-hclog/stdlog.go | 20 +- .../github.com/hashicorp/go-hclog/writer.go | 74 + vendor/github.com/hashicorp/go-memdb/LICENSE | 363 - .../github.com/hashicorp/go-memdb/README.md | 98 - .../github.com/hashicorp/go-memdb/filter.go | 33 - vendor/github.com/hashicorp/go-memdb/index.go | 581 - vendor/github.com/hashicorp/go-memdb/memdb.go | 97 - .../github.com/hashicorp/go-memdb/schema.go | 114 - vendor/github.com/hashicorp/go-memdb/txn.go | 644 - vendor/github.com/hashicorp/go-memdb/watch.go | 129 - .../hashicorp/go-memdb/watch_few.go | 117 - .../hashicorp/go-multierror/.travis.yml | 12 + .../hashicorp/go-multierror/Makefile | 31 + .../hashicorp/go-multierror/README.md | 6 + .../hashicorp/go-multierror/append.go | 8 +- .../hashicorp/go-multierror/format.go | 8 +- .../github.com/hashicorp/go-multierror/go.mod | 3 + .../github.com/hashicorp/go-multierror/go.sum | 4 + .../hashicorp/go-multierror/multierror.go | 4 +- .../hashicorp/go-multierror/sort.go | 16 + .../github.com/hashicorp/go-plugin/.gitignore | 1 + .../hashicorp/go-retryablehttp/.gitignore | 3 + .../hashicorp/go-retryablehttp/.travis.yml | 12 + .../hashicorp/go-retryablehttp/client.go | 12 +- .../hashicorp/go-retryablehttp/go.mod | 3 + .../hashicorp/go-retryablehttp/go.sum | 2 + .../hashicorp/go-rootcerts/.travis.yml | 12 + .../hashicorp/go-sockaddr/.gitignore | 26 + .../github.com/hashicorp/go-sockaddr/go.mod | 1 + vendor/github.com/hashicorp/go-syslog/LICENSE | 20 - .../github.com/hashicorp/go-syslog/README.md | 11 - .../github.com/hashicorp/go-syslog/builtin.go | 214 - .../github.com/hashicorp/go-syslog/syslog.go | 27 - vendor/github.com/hashicorp/go-syslog/unix.go | 123 - .../hashicorp/go-syslog/unsupported.go | 17 - .../github.com/hashicorp/go-uuid/.travis.yml | 12 + vendor/github.com/hashicorp/go-uuid/README.md | 4 +- vendor/github.com/hashicorp/go-uuid/go.mod | 1 + vendor/github.com/hashicorp/go-uuid/uuid.go | 38 +- .../hashicorp/go-version/.travis.yml | 13 + vendor/github.com/hashicorp/golang-lru/2q.go | 223 - .../github.com/hashicorp/golang-lru/README.md | 25 - vendor/github.com/hashicorp/golang-lru/arc.go | 257 - vendor/github.com/hashicorp/golang-lru/doc.go | 21 - vendor/github.com/hashicorp/golang-lru/go.mod | 1 - vendor/github.com/hashicorp/golang-lru/lru.go | 110 - vendor/github.com/hashicorp/hcl/.gitignore | 9 + vendor/github.com/hashicorp/hcl/.travis.yml | 13 + vendor/github.com/hashicorp/hcl/decoder.go | 37 +- vendor/github.com/hashicorp/hcl/go.mod | 3 + vendor/github.com/hashicorp/hcl/go.sum | 2 + .../hashicorp/hcl/hcl/parser/parser.go | 20 +- .../hashicorp/hcl/hcl/printer/nodes.go | 789 - .../hashicorp/hcl/hcl/printer/printer.go | 66 - .../hashicorp/hcl/hcl/scanner/scanner.go | 31 +- .../hashicorp/hcl/json/scanner/scanner.go | 2 +- .../hcl2/hcl/hclsyntax/expression_vars.go | 0 .../hcl2/hcl/hclsyntax/expression_vars_gen.go | 99 + vendor/github.com/hashicorp/hil/.gitignore | 3 + vendor/github.com/hashicorp/hil/.travis.yml | 3 + .../hashicorp/hil/scanner/scanner.go | 6 + .../github.com/hashicorp/logutils/.gitignore | 22 + .../vault-plugin-auth-alicloud/Gopkg.lock | 427 - .../vault-plugin-auth-alicloud/Gopkg.toml | 54 - .../vault-plugin-auth-alicloud/LICENSE | 373 - .../vault-plugin-auth-alicloud/Makefile | 55 - .../vault-plugin-auth-alicloud/README.md | 127 - .../vault-plugin-auth-alicloud/arn.go | 94 - .../vault-plugin-auth-alicloud/backend.go | 57 - .../vault-plugin-auth-alicloud/cli.go | 89 - .../vault-plugin-auth-alicloud/path_login.go | 248 - .../vault-plugin-auth-alicloud/path_role.go | 228 - .../vault-plugin-auth-alicloud/role_entry.go | 31 - .../vault-plugin-auth-azure/Gopkg.lock | 484 - .../vault-plugin-auth-azure/Gopkg.toml | 62 - .../hashicorp/vault-plugin-auth-azure/LICENSE | 362 - .../vault-plugin-auth-azure/Makefile | 55 - .../vault-plugin-auth-azure/README.md | 129 - .../vault-plugin-auth-azure/azure.go | 239 - .../vault-plugin-auth-azure/backend.go | 99 - .../vault-plugin-auth-azure/path_config.go | 177 - .../vault-plugin-auth-azure/path_login.go | 309 - .../vault-plugin-auth-azure/path_role.go | 355 - .../hashicorp/vault-plugin-auth-azure/util.go | 57 - .../vault-plugin-auth-centrify/Gopkg.lock | 385 - .../vault-plugin-auth-centrify/Gopkg.toml | 46 - .../vault-plugin-auth-centrify/LICENSE | 363 - .../vault-plugin-auth-centrify/Makefile | 62 - .../vault-plugin-auth-centrify/README.md | 165 - .../vault-plugin-auth-centrify/backend.go | 52 - .../vault-plugin-auth-centrify/cli.go | 66 - .../vault-plugin-auth-centrify/path_config.go | 208 - .../vault-plugin-auth-centrify/path_login.go | 201 - .../hashicorp/vault-plugin-auth-gcp/LICENSE | 364 - .../plugin/authorizer_client_gcp.go | 78 - .../plugin/authorizer_client_stubbed.go | 25 - .../plugin/authorizer_gce.go | 159 - .../vault-plugin-auth-gcp/plugin/backend.go | 190 - .../vault-plugin-auth-gcp/plugin/cli.go | 171 - .../vault-plugin-auth-gcp/plugin/helpers.go | 67 - .../plugin/login_util.go | 27 - .../plugin/path_config.go | 161 - .../plugin/path_login.go | 622 - .../vault-plugin-auth-gcp/plugin/path_role.go | 962 - .../vault-plugin-auth-jwt/Gopkg.lock | 451 - .../vault-plugin-auth-jwt/Gopkg.toml | 66 - .../hashicorp/vault-plugin-auth-jwt/LICENSE | 363 - .../hashicorp/vault-plugin-auth-jwt/Makefile | 55 - .../hashicorp/vault-plugin-auth-jwt/README.md | 123 - .../vault-plugin-auth-jwt/backend.go | 120 - .../vault-plugin-auth-jwt/path_config.go | 217 - .../vault-plugin-auth-jwt/path_login.go | 287 - .../vault-plugin-auth-jwt/path_role.go | 382 - .../vault-plugin-auth-kubernetes/Gopkg.lock | 462 - .../vault-plugin-auth-kubernetes/Gopkg.toml | 74 - .../vault-plugin-auth-kubernetes/LICENSE | 363 - .../vault-plugin-auth-kubernetes/Makefile | 62 - .../vault-plugin-auth-kubernetes/README.md | 131 - .../vault-plugin-auth-kubernetes/backend.go | 118 - .../path_config.go | 175 - .../path_login.go | 343 - .../vault-plugin-auth-kubernetes/path_role.go | 354 - .../token_review.go | 193 - .../hashicorp/vault-plugin-secrets-ad/LICENSE | 373 - .../vault-plugin-secrets-ad/plugin/backend.go | 83 - .../plugin/client/client.go | 172 - .../plugin/client/config.go | 13 - .../plugin/client/entry.go | 41 - .../plugin/client/fieldregistry.go | 113 - .../plugin/client/time.go | 43 - .../plugin/engineconf.go | 10 - .../plugin/passwordconf.go | 17 - .../plugin/path_config.go | 212 - .../plugin/path_creds.go | 213 - .../plugin/path_roles.go | 254 - .../plugin/path_rotate_root_creds.go | 108 - .../vault-plugin-secrets-ad/plugin/role.go | 28 - .../plugin/util/passwords.go | 77 - .../plugin/util/secrets_client.go | 79 - .../vault-plugin-secrets-azure/Gopkg.lock | 438 - .../vault-plugin-secrets-azure/Gopkg.toml | 62 - .../vault-plugin-secrets-azure/LICENSE | 373 - .../vault-plugin-secrets-azure/Makefile | 57 - .../vault-plugin-secrets-azure/README.md | 124 - .../vault-plugin-secrets-azure/backend.go | 83 - .../vault-plugin-secrets-azure/client.go | 298 - .../vault-plugin-secrets-azure/path_config.go | 202 - .../vault-plugin-secrets-azure/path_roles.go | 288 - .../path_service_principal.go | 166 - .../vault-plugin-secrets-azure/provider.go | 190 - .../vault-plugin-secrets-gcp/LICENSE | 363 - .../plugin/backend.go | 115 - .../plugin/path_config.go | 132 - .../plugin/path_role_set.go | 521 - .../plugin/role_set.go | 417 - .../plugin/rollback.go | 277 - .../plugin/secrets_access_token.go | 184 - .../plugin/secrets_service_account_key.go | 237 - .../vault-plugin-secrets-kv/Gopkg.lock | 309 - .../vault-plugin-secrets-kv/Gopkg.toml | 42 - .../hashicorp/vault-plugin-secrets-kv/LICENSE | 373 - .../vault-plugin-secrets-kv/Makefile | 51 - .../vault-plugin-secrets-kv/README.md | 125 - .../vault-plugin-secrets-kv/backend.go | 467 - .../vault-plugin-secrets-kv/passthrough.go | 265 - .../vault-plugin-secrets-kv/path_config.go | 110 - .../vault-plugin-secrets-kv/path_data.go | 428 - .../vault-plugin-secrets-kv/path_delete.go | 156 - .../vault-plugin-secrets-kv/path_destroy.go | 91 - .../vault-plugin-secrets-kv/path_metadata.go | 214 - .../vault-plugin-secrets-kv/types.pb.go | 287 - .../vault-plugin-secrets-kv/types.proto | 81 - .../vault-plugin-secrets-kv/upgrade.go | 216 - .../github.com/hashicorp/vault/CHANGELOG.md | 3312 - .../hashicorp/vault/CONTRIBUTING.md | 72 - vendor/github.com/hashicorp/vault/Makefile | 184 - vendor/github.com/hashicorp/vault/README.md | 134 - .../github.com/hashicorp/vault/audit/audit.go | 63 - .../hashicorp/vault/audit/format.go | 454 - .../hashicorp/vault/audit/format_json.go | 53 - .../hashicorp/vault/audit/format_jsonx.go | 74 - .../hashicorp/vault/audit/formatter.go | 24 - .../hashicorp/vault/audit/hashstructure.go | 319 - .../vault/builtin/audit/file/backend.go | 295 - .../vault/builtin/audit/socket/backend.go | 250 - .../vault/builtin/audit/syslog/backend.go | 171 - .../builtin/credential/app-id/backend.go | 184 - .../builtin/credential/app-id/path_login.go | 230 - .../builtin/credential/approle/backend.go | 176 - .../builtin/credential/approle/path_login.go | 350 - .../builtin/credential/approle/path_role.go | 2562 - .../credential/approle/path_tidy_user_id.go | 246 - .../builtin/credential/approle/validation.go | 390 - .../vault/builtin/credential/aws/backend.go | 311 - .../vault/builtin/credential/aws/cli.go | 164 - .../vault/builtin/credential/aws/client.go | 276 - .../credential/aws/path_config_certificate.go | 447 - .../credential/aws/path_config_client.go | 292 - .../builtin/credential/aws/path_config_sts.go | 249 - .../path_config_tidy_identity_whitelist.go | 152 - .../aws/path_config_tidy_roletag_blacklist.go | 153 - .../credential/aws/path_identity_whitelist.go | 159 - .../builtin/credential/aws/path_login.go | 1688 - .../vault/builtin/credential/aws/path_role.go | 918 - .../builtin/credential/aws/path_role_tag.go | 435 - .../credential/aws/path_roletag_blacklist.go | 252 - .../aws/path_tidy_identity_whitelist.go | 119 - .../aws/path_tidy_roletag_blacklist.go | 119 - .../vault/builtin/credential/cert/backend.go | 72 - .../vault/builtin/credential/cert/cli.go | 61 - .../builtin/credential/cert/path_certs.go | 341 - .../builtin/credential/cert/path_config.go | 63 - .../builtin/credential/cert/path_crls.go | 252 - .../builtin/credential/cert/path_login.go | 519 - .../builtin/credential/github/backend.go | 98 - .../vault/builtin/credential/github/cli.go | 95 - .../builtin/credential/github/path_config.go | 143 - .../builtin/credential/github/path_login.go | 266 - .../vault/builtin/credential/ldap/backend.go | 204 - .../vault/builtin/credential/ldap/cli.go | 111 - .../builtin/credential/ldap/path_config.go | 175 - .../builtin/credential/ldap/path_groups.go | 158 - .../builtin/credential/ldap/path_login.go | 135 - .../builtin/credential/ldap/path_users.go | 174 - .../vault/builtin/credential/okta/backend.go | 315 - .../vault/builtin/credential/okta/cli.go | 89 - .../builtin/credential/okta/path_config.go | 266 - .../builtin/credential/okta/path_groups.go | 183 - .../builtin/credential/okta/path_login.go | 166 - .../builtin/credential/okta/path_users.go | 155 - .../builtin/credential/radius/backend.go | 68 - .../builtin/credential/radius/path_config.go | 221 - .../builtin/credential/radius/path_login.go | 185 - .../builtin/credential/radius/path_users.go | 157 - .../vault/builtin/credential/token/cli.go | 170 - .../builtin/credential/userpass/backend.go | 60 - .../vault/builtin/credential/userpass/cli.go | 105 - .../builtin/credential/userpass/path_login.go | 138 - .../credential/userpass/path_user_password.go | 79 - .../credential/userpass/path_user_policies.go | 57 - .../builtin/credential/userpass/path_users.go | 238 - .../vault/builtin/logical/aws/backend.go | 70 - .../vault/builtin/logical/aws/client.go | 96 - .../builtin/logical/aws/path_config_lease.go | 127 - .../builtin/logical/aws/path_config_root.go | 96 - .../vault/builtin/logical/aws/path_roles.go | 433 - .../vault/builtin/logical/aws/path_user.go | 239 - .../vault/builtin/logical/aws/rollback.go | 27 - .../builtin/logical/aws/secret_access_keys.go | 325 - .../builtin/logical/cassandra/backend.go | 135 - .../cassandra/path_config_connection.go | 244 - .../logical/cassandra/path_creds_create.go | 123 - .../builtin/logical/cassandra/path_roles.go | 196 - .../builtin/logical/cassandra/secret_creds.go | 78 - .../vault/builtin/logical/cassandra/util.go | 96 - .../vault/builtin/logical/consul/backend.go | 45 - .../vault/builtin/logical/consul/client.go | 30 - .../builtin/logical/consul/path_config.go | 102 - .../builtin/logical/consul/path_roles.go | 164 - .../builtin/logical/consul/path_token.go | 85 - .../builtin/logical/consul/secret_token.go | 84 - .../vault/builtin/logical/database/backend.go | 285 - .../database/path_config_connection.go | 381 - .../logical/database/path_creds_create.go | 110 - .../builtin/logical/database/path_roles.go | 284 - .../database/path_rotate_credentials.go | 87 - .../builtin/logical/database/secret_creds.go | 145 - .../vault/builtin/logical/mongodb/backend.go | 144 - .../logical/mongodb/path_config_connection.go | 112 - .../logical/mongodb/path_config_lease.go | 90 - .../logical/mongodb/path_creds_create.go | 119 - .../builtin/logical/mongodb/path_roles.go | 224 - .../builtin/logical/mongodb/secret_creds.go | 84 - .../vault/builtin/logical/mongodb/util.go | 81 - .../vault/builtin/logical/mssql/backend.go | 160 - .../logical/mssql/path_config_connection.go | 127 - .../logical/mssql/path_config_lease.go | 115 - .../logical/mssql/path_creds_create.go | 129 - .../vault/builtin/logical/mssql/path_roles.go | 172 - .../builtin/logical/mssql/secret_creds.go | 181 - .../vault/builtin/logical/mssql/util.go | 28 - .../vault/builtin/logical/mysql/backend.go | 151 - .../logical/mysql/path_config_connection.go | 160 - .../logical/mysql/path_config_lease.go | 102 - .../builtin/logical/mysql/path_role_create.go | 144 - .../vault/builtin/logical/mysql/path_roles.go | 230 - .../builtin/logical/mysql/secret_creds.go | 136 - .../vault/builtin/logical/mysql/util.go | 15 - .../vault/builtin/logical/nomad/backend.go | 73 - .../logical/nomad/path_config_access.go | 129 - .../logical/nomad/path_config_lease.go | 110 - .../logical/nomad/path_creds_create.go | 98 - .../vault/builtin/logical/nomad/path_roles.go | 186 - .../builtin/logical/nomad/secret_token.go | 69 - .../vault/builtin/logical/pki/backend.go | 108 - .../vault/builtin/logical/pki/ca_util.go | 58 - .../vault/builtin/logical/pki/cert_util.go | 1646 - .../vault/builtin/logical/pki/crl_util.go | 238 - .../vault/builtin/logical/pki/fields.go | 232 - .../builtin/logical/pki/path_config_ca.go | 135 - .../builtin/logical/pki/path_config_crl.go | 133 - .../builtin/logical/pki/path_config_urls.go | 162 - .../vault/builtin/logical/pki/path_fetch.go | 276 - .../builtin/logical/pki/path_intermediate.go | 254 - .../builtin/logical/pki/path_issue_sign.go | 364 - .../vault/builtin/logical/pki/path_revoke.go | 96 - .../vault/builtin/logical/pki/path_roles.go | 745 - .../vault/builtin/logical/pki/path_root.go | 485 - .../vault/builtin/logical/pki/path_tidy.go | 229 - .../vault/builtin/logical/pki/secret_certs.go | 52 - .../vault/builtin/logical/pki/util.go | 7 - .../builtin/logical/postgresql/backend.go | 172 - .../postgresql/path_config_connection.go | 168 - .../logical/postgresql/path_config_lease.go | 102 - .../logical/postgresql/path_role_create.go | 149 - .../builtin/logical/postgresql/path_roles.go | 197 - .../vault/builtin/logical/postgresql/query.go | 15 - .../logical/postgresql/secret_creds.go | 269 - .../vault/builtin/logical/rabbitmq/backend.go | 145 - .../rabbitmq/path_config_connection.go | 119 - .../logical/rabbitmq/path_config_lease.go | 84 - .../logical/rabbitmq/path_role_create.go | 126 - .../builtin/logical/rabbitmq/path_roles.go | 181 - .../builtin/logical/rabbitmq/secret_creds.go | 70 - .../vault/builtin/logical/ssh/backend.go | 125 - .../vault/builtin/logical/ssh/communicator.go | 351 - .../logical/ssh/linux_install_script.go | 71 - .../builtin/logical/ssh/path_config_ca.go | 286 - .../logical/ssh/path_config_zeroaddress.go | 184 - .../builtin/logical/ssh/path_creds_create.go | 332 - .../vault/builtin/logical/ssh/path_fetch.go | 41 - .../vault/builtin/logical/ssh/path_keys.go | 110 - .../vault/builtin/logical/ssh/path_lookup.go | 91 - .../vault/builtin/logical/ssh/path_roles.go | 657 - .../vault/builtin/logical/ssh/path_sign.go | 425 - .../vault/builtin/logical/ssh/path_verify.go | 103 - .../builtin/logical/ssh/secret_dynamic_key.go | 71 - .../vault/builtin/logical/ssh/secret_otp.go | 46 - .../vault/builtin/logical/ssh/util.go | 225 - .../vault/builtin/logical/totp/backend.go | 55 - .../vault/builtin/logical/totp/path_code.go | 127 - .../vault/builtin/logical/totp/path_keys.go | 422 - .../vault/builtin/logical/transit/backend.go | 75 - .../builtin/logical/transit/path_backup.go | 43 - .../builtin/logical/transit/path_config.go | 189 - .../builtin/logical/transit/path_datakey.go | 173 - .../builtin/logical/transit/path_decrypt.go | 172 - .../builtin/logical/transit/path_encrypt.go | 314 - .../builtin/logical/transit/path_export.go | 230 - .../builtin/logical/transit/path_hash.go | 116 - .../builtin/logical/transit/path_hmac.go | 247 - .../builtin/logical/transit/path_keys.go | 346 - .../builtin/logical/transit/path_random.go | 97 - .../builtin/logical/transit/path_restore.go | 43 - .../builtin/logical/transit/path_rewrap.go | 198 - .../builtin/logical/transit/path_rotate.go | 61 - .../logical/transit/path_sign_verify.go | 371 - .../hashicorp/vault/builtin/plugin/backend.go | 229 - .../hashicorp/vault/command/agent.go | 393 - .../command/agent/auth/alicloud/alicloud.go | 233 - .../vault/command/agent/auth/auth.go | 216 - .../vault/command/agent/auth/aws/aws.go | 207 - .../vault/command/agent/auth/azure/azure.go | 180 - .../vault/command/agent/auth/gcp/gcp.go | 241 - .../vault/command/agent/auth/jwt/jwt.go | 184 - .../agent/auth/kubernetes/kubernetes.go | 76 - .../vault/command/agent/config/config.go | 239 - .../command/agent/sink/file/file_sink.go | 112 - .../vault/command/agent/sink/sink.go | 242 - .../hashicorp/vault/command/audit.go | 42 - .../hashicorp/vault/command/audit_disable.go | 87 - .../hashicorp/vault/command/audit_enable.go | 154 - .../hashicorp/vault/command/audit_list.go | 166 - .../hashicorp/vault/command/auth.go | 124 - .../hashicorp/vault/command/auth_disable.go | 87 - .../hashicorp/vault/command/auth_enable.go | 274 - .../hashicorp/vault/command/auth_help.go | 123 - .../hashicorp/vault/command/auth_list.go | 173 - .../hashicorp/vault/command/auth_tune.go | 200 - .../hashicorp/vault/command/base.go | 487 - .../hashicorp/vault/command/base_flags.go | 780 - .../hashicorp/vault/command/base_helpers.go | 272 - .../hashicorp/vault/command/base_predict.go | 451 - .../hashicorp/vault/command/commands.go | 992 - .../hashicorp/vault/command/config.go | 54 - .../hashicorp/vault/command/config/config.go | 31 +- .../hashicorp/vault/command/delete.go | 98 - .../hashicorp/vault/command/format.go | 380 - .../github.com/hashicorp/vault/command/kv.go | 52 - .../hashicorp/vault/command/kv_delete.go | 149 - .../hashicorp/vault/command/kv_destroy.go | 132 - .../vault/command/kv_enable_versioning.go | 89 - .../hashicorp/vault/command/kv_get.go | 184 - .../hashicorp/vault/command/kv_helpers.go | 145 - .../hashicorp/vault/command/kv_list.go | 112 - .../hashicorp/vault/command/kv_metadata.go | 48 - .../vault/command/kv_metadata_delete.go | 95 - .../vault/command/kv_metadata_get.go | 140 - .../vault/command/kv_metadata_put.go | 142 - .../hashicorp/vault/command/kv_patch.go | 195 - .../hashicorp/vault/command/kv_put.go | 163 - .../hashicorp/vault/command/kv_rollback.go | 243 - .../hashicorp/vault/command/kv_undelete.go | 127 - .../hashicorp/vault/command/lease.go | 40 - .../hashicorp/vault/command/lease_renew.go | 112 - .../hashicorp/vault/command/lease_revoke.go | 176 - .../hashicorp/vault/command/list.go | 106 - .../hashicorp/vault/command/login.go | 401 - .../hashicorp/vault/command/main.go | 236 - .../hashicorp/vault/command/namespace.go | 51 - .../vault/command/namespace_create.go | 93 - .../vault/command/namespace_delete.go | 98 - .../hashicorp/vault/command/namespace_list.go | 94 - .../vault/command/namespace_lookup.go | 92 - .../hashicorp/vault/command/operator.go | 47 - .../vault/command/operator_generate_root.go | 541 - .../hashicorp/vault/command/operator_init.go | 571 - .../vault/command/operator_key_status.go | 79 - .../hashicorp/vault/command/operator_rekey.go | 807 - .../hashicorp/vault/command/operator_seal.go | 84 - .../vault/command/operator_step_down.go | 80 - .../vault/command/operator_unseal.go | 145 - .../hashicorp/vault/command/path_help.go | 102 - .../hashicorp/vault/command/plugin.go | 46 - .../vault/command/plugin_deregister.go | 86 - .../hashicorp/vault/command/plugin_info.go | 97 - .../hashicorp/vault/command/plugin_list.go | 89 - .../vault/command/plugin_register.go | 135 - .../vault/command/policies_deprecated.go | 57 - .../hashicorp/vault/command/policy.go | 47 - .../hashicorp/vault/command/policy_delete.go | 85 - .../hashicorp/vault/command/policy_fmt.go | 109 - .../hashicorp/vault/command/policy_list.go | 81 - .../hashicorp/vault/command/policy_read.go | 95 - .../hashicorp/vault/command/policy_write.go | 127 - .../hashicorp/vault/command/read.go | 107 - .../hashicorp/vault/command/rotate.go | 101 - .../hashicorp/vault/command/secrets.go | 43 - .../vault/command/secrets_disable.go | 84 - .../hashicorp/vault/command/secrets_enable.go | 294 - .../hashicorp/vault/command/secrets_list.go | 174 - .../hashicorp/vault/command/secrets_move.go | 89 - .../hashicorp/vault/command/secrets_tune.go | 199 - .../hashicorp/vault/command/server.go | 1771 - .../hashicorp/vault/command/server/config.go | 804 - .../vault/command/server/listener.go | 191 - .../vault/command/server/listener_tcp.go | 118 - .../github.com/hashicorp/vault/command/ssh.go | 885 - .../hashicorp/vault/command/status.go | 89 - .../hashicorp/vault/command/token.go | 46 - .../vault/command/token_capabilities.go | 109 - .../hashicorp/vault/command/token_create.go | 252 - .../hashicorp/vault/command/token_lookup.go | 128 - .../hashicorp/vault/command/token_renew.go | 137 - .../hashicorp/vault/command/token_revoke.go | 174 - .../hashicorp/vault/command/unwrap.go | 106 - .../hashicorp/vault/command/util.go | 159 - .../hashicorp/vault/command/version.go | 61 - .../hashicorp/vault/command/write.go | 153 - .../hashicorp/vault/helper/base62/base62.go | 59 - .../vault/helper/builtinplugins/builtin.go | 50 - .../vault/helper/certutil/helpers.go | 301 - .../hashicorp/vault/helper/certutil/types.go | 591 - .../hashicorp/vault/helper/cidrutil/cidr.go | 217 - .../vault/helper/compressutil/compress.go | 47 +- .../hashicorp/vault/helper/dhutil/dhutil.go | 121 - .../hashicorp/vault/helper/errutil/error.go | 20 - .../vault/helper/forwarding/types.pb.go | 343 - .../vault/helper/forwarding/types.proto | 48 - .../hashicorp/vault/helper/forwarding/util.go | 218 - .../vault/helper/gated-writer/writer.go | 43 - .../vault/helper/identity/identity.go | 65 - .../vault/helper/identity/sentinel.go | 125 - .../vault/helper/identity/templating.go | 205 - .../vault/helper/identity/types.pb.go | 505 - .../vault/helper/identity/types.proto | 178 - .../hashicorp/vault/helper/jsonutil/json.go | 5 +- .../vault/helper/kv-builder/builder.go | 132 - .../hashicorp/vault/helper/ldaputil/client.go | 470 - .../hashicorp/vault/helper/ldaputil/config.go | 336 - .../vault/helper/ldaputil/connection.go | 18 - .../hashicorp/vault/helper/ldaputil/ldap.go | 28 - .../hashicorp/vault/helper/locksutil/locks.go | 60 - .../hashicorp/vault/helper/logging/vault.go | 39 - .../hashicorp/vault/helper/mfa/mfa.go | 88 - .../vault/helper/mfa/path_mfa_config.go | 87 - .../hashicorp/vault/helper/mlock/mlock.go | 15 - .../vault/helper/mlock/mlock_unavail.go | 13 - .../vault/helper/mlock/mlock_unix.go | 18 - .../vault/helper/namespace/namespace.go | 107 - .../vault/helper/password/password.go | 64 - .../vault/helper/password/password_solaris.go | 55 - .../vault/helper/password/password_unix.go | 25 - .../vault/helper/password/password_windows.go | 48 - .../vault/helper/pathmanager/pathmanager.go | 136 - .../vault/helper/pgpkeys/encrypt_decrypt.go | 118 - .../hashicorp/vault/helper/pgpkeys/flag.go | 140 - .../hashicorp/vault/helper/pgpkeys/keybase.go | 117 - .../vault/helper/pgpkeys/test_keys.go | 271 - .../hashicorp/vault/helper/pluginutil/env.go | 66 - .../vault/helper/pluginutil/runner.go | 182 - .../hashicorp/vault/helper/pluginutil/tls.go | 241 - .../vault/helper/policyutil/policyutil.go | 131 - .../hashicorp/vault/helper/reload/reload.go | 85 - .../hashicorp/vault/helper/salt/salt.go | 178 - .../helper/storagepacker/storagepacker.go | 355 - .../vault/helper/storagepacker/types.pb.go | 139 - .../vault/helper/storagepacker/types.proto | 17 - .../hashicorp/vault/helper/tlsutil/tlsutil.go | 54 - .../vault/helper/useragent/useragent.go | 47 - .../vault/helper/wrapping/wrapinfo.go | 37 - .../hashicorp/vault/helper/xor/xor.go | 48 - .../github.com/hashicorp/vault/http/cors.go | 67 - .../hashicorp/vault/http/handler.go | 618 - .../github.com/hashicorp/vault/http/help.go | 47 - .../hashicorp/vault/http/logical.go | 329 - .../hashicorp/vault/http/stub_assets.go | 16 - .../hashicorp/vault/http/sys_generate_root.go | 192 - .../hashicorp/vault/http/sys_health.go | 196 - .../hashicorp/vault/http/sys_init.go | 165 - .../hashicorp/vault/http/sys_leader.go | 53 - .../hashicorp/vault/http/sys_rekey.go | 411 - .../hashicorp/vault/http/sys_seal.go | 227 - .../hashicorp/vault/http/testing.go | 67 - .../hashicorp/vault/logical/auth.go | 92 - .../hashicorp/vault/logical/connection.go | 15 - .../hashicorp/vault/logical/error.go | 78 - .../vault/logical/framework/backend.go | 586 - .../vault/logical/framework/field_data.go | 397 - .../vault/logical/framework/field_type.go | 78 - .../vault/logical/framework/lease.go | 106 - .../hashicorp/vault/logical/framework/path.go | 163 - .../vault/logical/framework/path_map.go | 283 - .../vault/logical/framework/path_struct.go | 124 - .../vault/logical/framework/policy_map.go | 65 - .../vault/logical/framework/secret.go | 91 - .../vault/logical/framework/template.go | 42 - .../vault/logical/framework/testing.go | 15 - .../hashicorp/vault/logical/framework/wal.go | 101 - .../hashicorp/vault/logical/identity.pb.go | 183 - .../hashicorp/vault/logical/identity.proto | 34 - .../hashicorp/vault/logical/lease.go | 53 - .../hashicorp/vault/logical/logical.go | 126 - .../hashicorp/vault/logical/plugin.pb.go | 77 - .../hashicorp/vault/logical/plugin.proto | 10 - .../hashicorp/vault/logical/plugin/backend.go | 64 - .../vault/logical/plugin/backend_client.go | 248 - .../vault/logical/plugin/backend_server.go | 148 - .../vault/logical/plugin/grpc_backend.go | 12 - .../logical/plugin/grpc_backend_client.go | 245 - .../logical/plugin/grpc_backend_server.go | 142 - .../vault/logical/plugin/grpc_storage.go | 110 - .../vault/logical/plugin/grpc_system.go | 265 - .../hashicorp/vault/logical/plugin/logger.go | 134 - .../vault/logical/plugin/middleware.go | 91 - .../hashicorp/vault/logical/plugin/plugin.go | 176 - .../hashicorp/vault/logical/plugin/serve.go | 85 - .../hashicorp/vault/logical/plugin/storage.go | 139 - .../hashicorp/vault/logical/plugin/system.go | 345 - .../hashicorp/vault/logical/request.go | 274 - .../hashicorp/vault/logical/response.go | 170 - .../hashicorp/vault/logical/response_util.go | 145 - .../hashicorp/vault/logical/secret.go | 30 - .../hashicorp/vault/logical/storage.go | 121 - .../hashicorp/vault/logical/storage_inmem.go | 67 - .../hashicorp/vault/logical/system_view.go | 130 - .../hashicorp/vault/logical/testing.go | 84 - .../hashicorp/vault/logical/token.go | 119 - .../vault/logical/translate_response.go | 143 - vendor/github.com/hashicorp/vault/main.go | 11 - vendor/github.com/hashicorp/vault/make.bat | 113 - .../vault/physical/alicloudoss/alicloudoss.go | 223 - .../hashicorp/vault/physical/azure/azure.go | 234 - .../hashicorp/vault/physical/cache.go | 220 - .../vault/physical/cassandra/cassandra.go | 341 - .../vault/physical/cockroachdb/cockroachdb.go | 241 - .../hashicorp/vault/physical/consul/consul.go | 880 - .../vault/physical/couchdb/couchdb.go | 310 - .../vault/physical/dynamodb/dynamodb.go | 837 - .../hashicorp/vault/physical/etcd/etcd.go | 146 - .../hashicorp/vault/physical/etcd/etcd2.go | 603 - .../hashicorp/vault/physical/etcd/etcd3.go | 358 - .../hashicorp/vault/physical/file/file.go | 374 - .../vault/physical/foundationdb/README.md | 34 - .../physical/foundationdb/fdb-go-install.sh | 330 - .../physical/foundationdb/foundationdb.go | 836 - .../physical/foundationdb/foundationdbstub.go | 15 - .../hashicorp/vault/physical/gcs/gcs.go | 296 - .../hashicorp/vault/physical/gcs/gcs_ha.go | 419 - .../hashicorp/vault/physical/inmem/inmem.go | 247 - .../vault/physical/inmem/inmem_ha.go | 167 - .../hashicorp/vault/physical/latency.go | 95 - .../hashicorp/vault/physical/manta/manta.go | 264 - .../hashicorp/vault/physical/mssql/mssql.go | 257 - .../hashicorp/vault/physical/mysql/mysql.go | 701 - .../hashicorp/vault/physical/physical.go | 158 - .../vault/physical/physical_access.go | 38 - .../hashicorp/vault/physical/physical_view.go | 98 - .../vault/physical/postgresql/postgresql.go | 215 - .../hashicorp/vault/physical/s3/s3.go | 281 - .../vault/physical/spanner/spanner.go | 347 - .../vault/physical/spanner/spanner_ha.go | 417 - .../hashicorp/vault/physical/swift/swift.go | 248 - .../hashicorp/vault/physical/testing.go | 488 - .../hashicorp/vault/physical/transactions.go | 126 - .../hashicorp/vault/physical/types.pb.go | 85 - .../hashicorp/vault/physical/types.proto | 10 - .../vault/physical/zookeeper/zookeeper.go | 504 - .../hashicorp/vault/shamir/shamir.go | 262 - .../hashicorp/vault/shamir/tables.go | 77 - .../github.com/hashicorp/vault/vault/acl.go | 481 - .../github.com/hashicorp/vault/vault/audit.go | 464 - .../hashicorp/vault/vault/audit_broker.go | 200 - .../hashicorp/vault/vault/audited_headers.go | 162 - .../github.com/hashicorp/vault/vault/auth.go | 627 - .../hashicorp/vault/vault/barrier.go | 183 - .../hashicorp/vault/vault/barrier_access.go | 24 - .../hashicorp/vault/vault/barrier_aes_gcm.go | 936 - .../hashicorp/vault/vault/barrier_view.go | 145 - .../hashicorp/vault/vault/capabilities.go | 58 - .../hashicorp/vault/vault/cluster.go | 458 - .../github.com/hashicorp/vault/vault/core.go | 1490 - .../github.com/hashicorp/vault/vault/cors.go | 161 - .../vault/vault/dynamic_system_view.go | 221 - .../hashicorp/vault/vault/expiration.go | 1492 - .../hashicorp/vault/vault/generate_root.go | 366 - vendor/github.com/hashicorp/vault/vault/ha.go | 871 - .../hashicorp/vault/vault/identity_lookup.go | 329 - .../hashicorp/vault/vault/identity_store.go | 396 - .../vault/vault/identity_store_aliases.go | 465 - .../vault/vault/identity_store_entities.go | 589 - .../vault/identity_store_group_aliases.go | 368 - .../vault/vault/identity_store_groups.go | 463 - .../vault/vault/identity_store_schema.go | 179 - .../vault/vault/identity_store_structs.go | 79 - .../vault/vault/identity_store_upgrade.go | 168 - .../vault/vault/identity_store_util.go | 1675 - .../github.com/hashicorp/vault/vault/init.go | 303 - .../hashicorp/vault/vault/keyring.go | 203 - .../vault/vault/logical_cubbyhole.go | 207 - .../vault/vault/logical_passthrough.go | 247 - .../hashicorp/vault/vault/logical_system.go | 4377 - .../vault/vault/logical_system_helpers.go | 54 - .../github.com/hashicorp/vault/vault/mount.go | 1115 - .../hashicorp/vault/vault/plugin_catalog.go | 189 - .../hashicorp/vault/vault/plugin_reload.go | 143 - .../hashicorp/vault/vault/policy.go | 345 - .../hashicorp/vault/vault/policy_store.go | 567 - .../github.com/hashicorp/vault/vault/rekey.go | 968 - .../vault/vault/request_forwarding.go | 521 - .../vault/request_forwarding_service.pb.go | 274 - .../vault/request_forwarding_service.proto | 28 - .../hashicorp/vault/vault/request_handling.go | 896 - .../hashicorp/vault/vault/rollback.go | 259 - .../hashicorp/vault/vault/router.go | 655 - .../hashicorp/vault/vault/router_access.go | 14 - .../github.com/hashicorp/vault/vault/seal.go | 383 - .../hashicorp/vault/vault/seal_access.go | 63 - .../hashicorp/vault/vault/seal_testing.go | 80 - .../hashicorp/vault/vault/sealunwrapper.go | 183 - .../hashicorp/vault/vault/testing.go | 1416 - .../hashicorp/vault/vault/token_store.go | 2626 - vendor/github.com/hashicorp/vault/vault/ui.go | 217 - .../github.com/hashicorp/vault/vault/util.go | 42 - .../hashicorp/vault/vault/wrapping.go | 349 - .../github.com/hashicorp/vault/version/cgo.go | 7 - .../hashicorp/vault/version/version.go | 87 - .../hashicorp/vault/version/version_base.go | 11 - vendor/github.com/hashicorp/yamux/.gitignore | 23 + vendor/github.com/hashicorp/yamux/go.mod | 1 + vendor/github.com/hashicorp/yamux/mux.go | 13 +- vendor/github.com/hashicorp/yamux/session.go | 72 +- vendor/github.com/hashicorp/yamux/stream.go | 45 +- vendor/github.com/hashicorp/yamux/util.go | 15 + .../jmespath/go-jmespath/.gitignore | 4 + .../jmespath/go-jmespath/.travis.yml | 9 + vendor/github.com/jmespath/go-jmespath/api.go | 2 +- vendor/github.com/keybase/go-crypto/LICENSE | 27 - vendor/github.com/keybase/go-crypto/PATENTS | 22 - .../go-crypto/openpgp/canonical_text.go | 59 - .../keybase/go-crypto/openpgp/keys.go | 917 - .../go-crypto/openpgp/packet/compressed.go | 124 - .../go-crypto/openpgp/packet/config.go | 98 - .../keybase/go-crypto/openpgp/packet/ecdh.go | 104 - .../go-crypto/openpgp/packet/encrypted_key.go | 227 - .../go-crypto/openpgp/packet/literal.go | 89 - .../keybase/go-crypto/openpgp/packet/ocfb.go | 143 - .../openpgp/packet/one_pass_signature.go | 74 - .../go-crypto/openpgp/packet/opaque.go | 162 - .../go-crypto/openpgp/packet/packet.go | 576 - .../go-crypto/openpgp/packet/private_key.go | 557 - .../go-crypto/openpgp/packet/public_key.go | 982 - .../go-crypto/openpgp/packet/public_key_v3.go | 280 - .../go-crypto/openpgp/packet/reader.go | 76 - .../go-crypto/openpgp/packet/signature.go | 892 - .../go-crypto/openpgp/packet/signature_v3.go | 146 - .../openpgp/packet/symmetric_key_encrypted.go | 158 - .../openpgp/packet/symmetrically_encrypted.go | 291 - .../go-crypto/openpgp/packet/userattribute.go | 91 - .../go-crypto/openpgp/packet/userid.go | 160 - .../keybase/go-crypto/openpgp/patch.sh | 7 - .../keybase/go-crypto/openpgp/read.go | 500 - .../keybase/go-crypto/openpgp/sig-v3.patch | 135 - .../keybase/go-crypto/openpgp/write.go | 506 - vendor/github.com/kr/pretty/License | 21 - vendor/github.com/kr/pretty/Readme | 9 - vendor/github.com/kr/pretty/diff.go | 265 - vendor/github.com/kr/pretty/formatter.go | 328 - vendor/github.com/kr/pretty/go.mod | 3 - vendor/github.com/kr/pretty/pretty.go | 108 - vendor/github.com/kr/pretty/zero.go | 41 - vendor/github.com/kr/text/License | 19 - vendor/github.com/kr/text/Readme | 3 - vendor/github.com/kr/text/doc.go | 3 - vendor/github.com/kr/text/go.mod | 3 - vendor/github.com/kr/text/indent.go | 74 - vendor/github.com/kr/text/wrap.go | 86 - vendor/github.com/lib/pq/CONTRIBUTING.md | 29 - vendor/github.com/lib/pq/LICENSE.md | 8 - vendor/github.com/lib/pq/README.md | 95 - vendor/github.com/lib/pq/TESTS.md | 33 - vendor/github.com/lib/pq/array.go | 756 - vendor/github.com/lib/pq/buf.go | 91 - vendor/github.com/lib/pq/conn.go | 1854 - vendor/github.com/lib/pq/conn_go18.go | 131 - vendor/github.com/lib/pq/connector.go | 43 - vendor/github.com/lib/pq/copy.go | 282 - vendor/github.com/lib/pq/doc.go | 245 - vendor/github.com/lib/pq/encode.go | 603 - vendor/github.com/lib/pq/error.go | 515 - vendor/github.com/lib/pq/go.mod | 1 - vendor/github.com/lib/pq/notify.go | 797 - vendor/github.com/lib/pq/rows.go | 93 - vendor/github.com/lib/pq/ssl.go | 169 - vendor/github.com/lib/pq/ssl_go1.7.go | 14 - vendor/github.com/lib/pq/ssl_permissions.go | 20 - vendor/github.com/lib/pq/ssl_renegotiation.go | 8 - vendor/github.com/lib/pq/ssl_windows.go | 9 - vendor/github.com/lib/pq/url.go | 76 - vendor/github.com/lib/pq/user_posix.go | 24 - vendor/github.com/lib/pq/user_windows.go | 27 - vendor/github.com/lib/pq/uuid.go | 23 - .../github.com/mattn/go-colorable/.travis.yml | 9 + .../mattn/go-colorable/colorable_appengine.go | 29 + .../mattn/go-colorable/colorable_windows.go | 208 +- vendor/github.com/mattn/go-isatty/.travis.yml | 13 + .../mattn/go-isatty/isatty_appengine.go | 15 + .../rabbit-hole/CONTRIBUTING.md | 37 - .../michaelklishin/rabbit-hole/ChangeLog.md | 32 - .../michaelklishin/rabbit-hole/LICENSE | 23 - .../michaelklishin/rabbit-hole/Makefile | 26 - .../michaelklishin/rabbit-hole/README.md | 338 - .../michaelklishin/rabbit-hole/bindings.go | 160 - .../michaelklishin/rabbit-hole/channels.go | 84 - .../michaelklishin/rabbit-hole/client.go | 273 - .../michaelklishin/rabbit-hole/cluster.go | 38 - .../michaelklishin/rabbit-hole/common.go | 66 - .../michaelklishin/rabbit-hole/connections.go | 130 - .../michaelklishin/rabbit-hole/doc.go | 186 - .../michaelklishin/rabbit-hole/error.go | 13 - .../michaelklishin/rabbit-hole/exchanges.go | 218 - .../michaelklishin/rabbit-hole/federation.go | 73 - .../michaelklishin/rabbit-hole/misc.go | 83 - .../michaelklishin/rabbit-hole/nodes.go | 300 - .../michaelklishin/rabbit-hole/permissions.go | 125 - .../michaelklishin/rabbit-hole/plugins.go | 31 - .../michaelklishin/rabbit-hole/policies.go | 126 - .../michaelklishin/rabbit-hole/queues.go | 316 - .../michaelklishin/rabbit-hole/shovels.go | 140 - .../michaelklishin/rabbit-hole/users.go | 128 - .../michaelklishin/rabbit-hole/vhosts.go | 159 - vendor/github.com/mitchellh/cli/.travis.yml | 14 + vendor/github.com/mitchellh/cli/cli.go | 29 +- vendor/github.com/mitchellh/cli/go.mod | 12 + vendor/github.com/mitchellh/cli/go.sum | 22 + vendor/github.com/mitchellh/cli/ui_colored.go | 32 +- .../mitchellh/copystructure/.travis.yml | 12 + .../mitchellh/copystructure/copystructure.go | 87 +- .../github.com/mitchellh/copystructure/go.mod | 3 + .../github.com/mitchellh/copystructure/go.sum | 2 + vendor/github.com/mitchellh/go-homedir/go.mod | 1 + .../mitchellh/go-homedir/homedir.go | 56 +- .../go-testing-interface/.travis.yml | 13 + .../mitchellh/mapstructure/.travis.yml | 8 + .../mitchellh/mapstructure/CHANGELOG.md | 21 + .../mitchellh/mapstructure/README.md | 2 +- .../mitchellh/mapstructure/decode_hooks.go | 79 +- .../github.com/mitchellh/mapstructure/go.mod | 1 + .../mitchellh/mapstructure/mapstructure.go | 520 +- .../mitchellh/reflectwalk/.travis.yml | 1 + .../github.com/mitchellh/reflectwalk/go.mod | 1 + .../mitchellh/reflectwalk/location.go | 2 + .../mitchellh/reflectwalk/location_string.go | 8 +- .../mitchellh/reflectwalk/reflectwalk.go | 108 +- vendor/github.com/oklog/run/.gitignore | 14 + vendor/github.com/oklog/run/.travis.yml | 12 + vendor/github.com/oklog/run/README.md | 8 +- .../patrickmn/go-cache/CONTRIBUTORS | 9 - vendor/github.com/patrickmn/go-cache/LICENSE | 19 - .../github.com/patrickmn/go-cache/README.md | 83 - vendor/github.com/patrickmn/go-cache/cache.go | 1161 - .../github.com/patrickmn/go-cache/sharded.go | 192 - vendor/github.com/pkg/errors/LICENSE | 23 - vendor/github.com/pkg/errors/README.md | 52 - vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/errors.go | 269 - vendor/github.com/pkg/errors/stack.go | 147 - vendor/github.com/posener/complete/.gitignore | 2 + .../github.com/posener/complete/.travis.yml | 17 + .../posener/complete/cmd/install/fish.go | 50 + .../posener/complete/cmd/install/install.go | 29 +- .../posener/complete/cmd/install/utils.go | 19 + vendor/github.com/posener/complete/readme.md | 5 +- vendor/github.com/posener/complete/test.sh | 0 .../github.com/rainycape/unidecode/.gitignore | 23 + .../rancher/go-rancher/Dockerfile.dapper | 30 - vendor/github.com/rancher/go-rancher/LICENSE | 177 - vendor/github.com/rancher/go-rancher/Makefile | 23 - .../github.com/rancher/go-rancher/README.md | 55 - vendor/github.com/rancher/go-rancher/main.go | 10 - .../github.com/rancher/go-rancher/trash.conf | 6 - vendor/github.com/ryanuber/columnize/LICENSE | 20 - .../github.com/ryanuber/columnize/README.md | 71 - .../ryanuber/columnize/columnize.go | 191 - .../github.com/ryanuber/go-glob/.travis.yml | 5 + vendor/github.com/ryanuber/go-glob/go.mod | 1 + vendor/github.com/ulikunitz/xz/.gitignore | 25 + vendor/github.com/ulikunitz/xz/example.go | 40 + vendor/github.com/ulikunitz/xz/make-docs | 0 vendor/go.opencensus.io/.gitignore | 9 + vendor/go.opencensus.io/.travis.yml | 17 + vendor/go.opencensus.io/go.mod | 2 +- vendor/go.opencensus.io/opencensus.go | 2 +- vendor/golang.org/x/crypto/AUTHORS | 3 + vendor/golang.org/x/crypto/CONTRIBUTORS | 3 + vendor/golang.org/x/crypto/bcrypt/bcrypt.go | 11 +- vendor/golang.org/x/crypto/blowfish/cipher.go | 10 +- vendor/golang.org/x/crypto/blowfish/const.go | 2 +- vendor/golang.org/x/crypto/cast5/cast5.go | 11 +- .../x/crypto/curve25519/const_amd64.h | 2 +- .../x/crypto/curve25519/const_amd64.s | 2 +- .../x/crypto/curve25519/cswap_amd64.s | 131 +- .../x/crypto/curve25519/curve25519.go | 834 + vendor/golang.org/x/crypto/curve25519/doc.go | 2 +- .../x/crypto/curve25519/freeze_amd64.s | 2 +- .../x/crypto/curve25519/ladderstep_amd64.s | 2 +- .../x/crypto/curve25519/mul_amd64.s | 2 +- .../x/crypto/curve25519/square_amd64.s | 2 +- vendor/golang.org/x/crypto/ed25519/ed25519.go | 66 +- .../internal/edwards25519/edwards25519.go | 22 + .../x/crypto/internal/chacha20/asm_arm64.s | 308 + .../crypto/internal/chacha20/chacha_arm64.go | 31 + .../internal/chacha20/chacha_generic.go | 264 + .../crypto/internal/chacha20/chacha_noasm.go | 16 + .../crypto/internal/chacha20/chacha_s390x.go | 29 + .../x/crypto/internal/chacha20/chacha_s390x.s | 260 + .../x/crypto/internal/chacha20/xor.go | 43 + .../x/crypto/internal/subtle/aliasing.go | 32 + .../internal/subtle/aliasing_appengine.go | 35 + vendor/golang.org/x/crypto/openpgp/keys.go | 168 +- .../x/crypto/openpgp/packet/encrypted_key.go | 9 +- .../x/crypto/openpgp/packet/packet.go | 44 +- .../x/crypto/openpgp/packet/private_key.go | 9 +- .../x/crypto/openpgp/packet/public_key.go | 11 +- .../x/crypto/openpgp/packet/signature.go | 2 +- .../x/crypto/openpgp/packet/userattribute.go | 2 +- vendor/golang.org/x/crypto/openpgp/write.go | 174 +- .../golang.org/x/crypto/poly1305/mac_noasm.go | 11 + .../golang.org/x/crypto/poly1305/poly1305.go | 83 + .../golang.org/x/crypto/poly1305/sum_amd64.go | 68 + .../golang.org/x/crypto/poly1305/sum_amd64.s | 148 + .../golang.org/x/crypto/poly1305/sum_arm.go | 22 + vendor/golang.org/x/crypto/poly1305/sum_arm.s | 427 + .../x/crypto/poly1305/sum_generic.go | 172 + .../golang.org/x/crypto/poly1305/sum_noasm.go | 16 + .../golang.org/x/crypto/poly1305/sum_s390x.go | 42 + .../golang.org/x/crypto/poly1305/sum_s390x.s | 378 + .../x/crypto/poly1305/sum_vmsl_s390x.s | 909 + .../golang.org/x/crypto/ssh/agent/client.go | 683 - .../golang.org/x/crypto/ssh/agent/forward.go | 103 - .../golang.org/x/crypto/ssh/agent/keyring.go | 215 - .../golang.org/x/crypto/ssh/agent/server.go | 523 - vendor/golang.org/x/crypto/ssh/buffer.go | 5 +- vendor/golang.org/x/crypto/ssh/certs.go | 60 +- vendor/golang.org/x/crypto/ssh/channel.go | 142 +- vendor/golang.org/x/crypto/ssh/cipher.go | 251 +- vendor/golang.org/x/crypto/ssh/client.go | 79 +- vendor/golang.org/x/crypto/ssh/client_auth.go | 164 +- vendor/golang.org/x/crypto/ssh/common.go | 34 +- vendor/golang.org/x/crypto/ssh/connection.go | 2 +- vendor/golang.org/x/crypto/ssh/doc.go | 3 + vendor/golang.org/x/crypto/ssh/handshake.go | 59 +- vendor/golang.org/x/crypto/ssh/kex.go | 32 +- vendor/golang.org/x/crypto/ssh/keys.go | 327 +- vendor/golang.org/x/crypto/ssh/messages.go | 38 +- vendor/golang.org/x/crypto/ssh/mux.go | 6 +- vendor/golang.org/x/crypto/ssh/server.go | 141 +- vendor/golang.org/x/crypto/ssh/session.go | 22 +- vendor/golang.org/x/crypto/ssh/streamlocal.go | 116 + vendor/golang.org/x/crypto/ssh/tcpip.go | 207 +- vendor/golang.org/x/crypto/ssh/transport.go | 70 +- vendor/golang.org/x/net/AUTHORS | 3 + vendor/golang.org/x/net/CONTRIBUTORS | 3 + vendor/golang.org/x/net/html/atom/gen.go | 712 + vendor/golang.org/x/net/html/atom/table.go | 1474 +- vendor/golang.org/x/net/html/const.go | 16 +- vendor/golang.org/x/net/html/doc.go | 8 +- vendor/golang.org/x/net/html/entity.go | 4154 +- vendor/golang.org/x/net/html/foreign.go | 6 +- vendor/golang.org/x/net/html/node.go | 33 +- vendor/golang.org/x/net/html/parse.go | 430 +- vendor/golang.org/x/net/html/token.go | 4 +- vendor/golang.org/x/net/http2/.gitignore | 2 + .../x/net/http2/configure_transport.go | 82 - vendor/golang.org/x/net/http2/frame.go | 4 +- vendor/golang.org/x/net/http2/go111.go | 11 +- vendor/golang.org/x/net/http2/go16.go | 16 - vendor/golang.org/x/net/http2/go17.go | 121 - vendor/golang.org/x/net/http2/go17_not18.go | 36 - vendor/golang.org/x/net/http2/go18.go | 56 - vendor/golang.org/x/net/http2/go19.go | 16 - vendor/golang.org/x/net/http2/hpack/hpack.go | 10 +- .../golang.org/x/net/http2/hpack/huffman.go | 20 +- vendor/golang.org/x/net/http2/not_go111.go | 11 +- vendor/golang.org/x/net/http2/not_go16.go | 21 - vendor/golang.org/x/net/http2/not_go17.go | 95 - vendor/golang.org/x/net/http2/not_go18.go | 29 - vendor/golang.org/x/net/http2/not_go19.go | 16 - vendor/golang.org/x/net/http2/server.go | 53 +- vendor/golang.org/x/net/http2/transport.go | 208 +- vendor/golang.org/x/net/http2/write.go | 4 +- vendor/golang.org/x/oauth2/.travis.yml | 13 + .../x/oauth2/google/appengine_gen1.go | 77 + .../x/oauth2/internal/client_appengine.go | 13 + vendor/golang.org/x/sys/AUTHORS | 3 + vendor/golang.org/x/sys/CONTRIBUTORS | 3 + vendor/golang.org/x/sys/cpu/byteorder.go | 30 + vendor/golang.org/x/sys/cpu/cpu.go | 126 + vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go | 30 + vendor/golang.org/x/sys/cpu/cpu_arm.go | 9 + vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go | 21 + vendor/golang.org/x/sys/cpu/cpu_gc_x86.go | 16 + vendor/golang.org/x/sys/cpu/cpu_gccgo.c | 43 + vendor/golang.org/x/sys/cpu/cpu_gccgo.go | 26 + .../golang.org/x/sys/cpu/cpu_gccgo_s390x.go | 22 + vendor/golang.org/x/sys/cpu/cpu_linux.go | 59 + .../golang.org/x/sys/cpu/cpu_linux_arm64.go | 67 + .../golang.org/x/sys/cpu/cpu_linux_ppc64x.go | 33 + .../golang.org/x/sys/cpu/cpu_linux_s390x.go | 161 + vendor/golang.org/x/sys/cpu/cpu_mips64x.go | 11 + vendor/golang.org/x/sys/cpu/cpu_mipsx.go | 11 + .../golang.org/x/sys/cpu/cpu_other_arm64.go | 11 + vendor/golang.org/x/sys/cpu/cpu_s390x.s | 57 + vendor/golang.org/x/sys/cpu/cpu_wasm.go | 15 + vendor/golang.org/x/sys/cpu/cpu_x86.go | 59 + vendor/golang.org/x/sys/cpu/cpu_x86.s | 27 + vendor/golang.org/x/sys/unix/.gitignore | 2 + vendor/golang.org/x/sys/unix/README.md | 20 +- .../x/sys/unix/asm_freebsd_arm64.s} | 4 +- .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 12 - .../x/sys/unix/asm_netbsd_arm64.s} | 5 +- vendor/golang.org/x/sys/unix/fcntl.go | 2 +- vendor/golang.org/x/sys/unix/fcntl_darwin.go | 18 + vendor/golang.org/x/sys/unix/mkall.sh | 82 +- vendor/golang.org/x/sys/unix/mkasm_darwin.go | 61 + vendor/golang.org/x/sys/unix/mkerrors.sh | 41 +- vendor/golang.org/x/sys/unix/mkpost.go | 14 +- vendor/golang.org/x/sys/unix/mksyscall.go | 407 + vendor/golang.org/x/sys/unix/mksyscall.pl | 341 - .../x/sys/unix/mksyscall_aix_ppc.go | 404 + .../x/sys/unix/mksyscall_aix_ppc.pl | 384 - .../x/sys/unix/mksyscall_aix_ppc64.go | 602 + .../x/sys/unix/mksyscall_aix_ppc64.pl | 579 - .../x/sys/unix/mksyscall_solaris.go | 335 + .../x/sys/unix/mksyscall_solaris.pl | 294 - .../golang.org/x/sys/unix/mksysctl_openbsd.pl | 0 vendor/golang.org/x/sys/unix/mksysnum.go | 190 + .../golang.org/x/sys/unix/mksysnum_darwin.pl | 39 - .../x/sys/unix/mksysnum_dragonfly.pl | 50 - .../golang.org/x/sys/unix/mksysnum_freebsd.pl | 50 - .../golang.org/x/sys/unix/mksysnum_netbsd.pl | 58 - .../golang.org/x/sys/unix/mksysnum_openbsd.pl | 50 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 25 +- vendor/golang.org/x/sys/unix/syscall_aix.go | 20 +- .../golang.org/x/sys/unix/syscall_darwin.go | 80 +- .../x/sys/unix/syscall_darwin_386.go | 23 +- .../x/sys/unix/syscall_darwin_amd64.go | 23 +- .../x/sys/unix/syscall_darwin_arm.go | 26 +- .../x/sys/unix/syscall_darwin_arm64.go | 26 +- .../x/sys/unix/syscall_darwin_libSystem.go | 31 + .../x/sys/unix/syscall_dragonfly.go | 16 + .../golang.org/x/sys/unix/syscall_freebsd.go | 7 + .../x/sys/unix/syscall_freebsd_arm64.go} | 23 +- vendor/golang.org/x/sys/unix/syscall_linux.go | 165 +- .../x/sys/unix/syscall_linux_386.go | 1 + .../x/sys/unix/syscall_linux_amd64.go | 19 +- .../x/sys/unix/syscall_linux_arm.go | 15 + .../x/sys/unix/syscall_linux_arm64.go | 14 + .../x/sys/unix/syscall_linux_mips64x.go | 10 +- .../x/sys/unix/syscall_linux_mipsx.go | 1 + .../x/sys/unix/syscall_linux_ppc64x.go | 1 + .../x/sys/unix/syscall_linux_riscv64.go | 17 + .../x/sys/unix/syscall_linux_s390x.go | 1 + .../x/sys/unix/syscall_linux_sparc64.go | 1 + .../golang.org/x/sys/unix/syscall_netbsd.go | 25 + .../x/sys/unix/syscall_netbsd_arm64.go | 33 + .../golang.org/x/sys/unix/syscall_openbsd.go | 44 +- .../golang.org/x/sys/unix/syscall_solaris.go | 7 + vendor/golang.org/x/sys/unix/syscall_unix.go | 63 +- .../golang.org/x/sys/unix/syscall_unix_gc.go | 2 +- .../x/sys/unix/syscall_unix_gc_ppc64x.go | 24 + vendor/golang.org/x/sys/unix/types_darwin.go | 6 + vendor/golang.org/x/sys/unix/types_freebsd.go | 2 +- vendor/golang.org/x/sys/unix/types_netbsd.go | 2 + vendor/golang.org/x/sys/unix/types_openbsd.go | 6 + vendor/golang.org/x/sys/unix/xattr_bsd.go | 15 +- .../x/sys/unix/zerrors_freebsd_arm64.go | 1794 + .../x/sys/unix/zerrors_linux_386.go | 141 +- .../x/sys/unix/zerrors_linux_amd64.go | 141 +- .../x/sys/unix/zerrors_linux_arm.go | 141 +- .../x/sys/unix/zerrors_linux_arm64.go | 141 +- .../x/sys/unix/zerrors_linux_mips.go | 141 +- .../x/sys/unix/zerrors_linux_mips64.go | 141 +- .../x/sys/unix/zerrors_linux_mips64le.go | 141 +- .../x/sys/unix/zerrors_linux_mipsle.go | 141 +- .../x/sys/unix/zerrors_linux_ppc64.go | 143 +- .../x/sys/unix/zerrors_linux_ppc64le.go | 143 +- .../x/sys/unix/zerrors_linux_riscv64.go | 141 +- .../x/sys/unix/zerrors_linux_s390x.go | 141 +- .../x/sys/unix/zerrors_linux_sparc64.go | 4293 +- .../x/sys/unix/zerrors_netbsd_arm64.go} | 324 +- .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 2 +- .../x/sys/unix/zsyscall_aix_ppc64.go | 10 +- .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 12 +- .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 11 +- .../x/sys/unix/zsyscall_darwin_386.1_11.go} | 682 +- .../x/sys/unix/zsyscall_darwin_386.go | 1174 +- .../x/sys/unix/zsyscall_darwin_386.s | 284 + .../x/sys/unix/zsyscall_darwin_amd64.1_11.go} | 680 +- .../x/sys/unix/zsyscall_darwin_amd64.go | 1189 +- .../x/sys/unix/zsyscall_darwin_amd64.s | 286 + .../x/sys/unix/zsyscall_darwin_arm.1_11.go | 1793 + .../x/sys/unix/zsyscall_darwin_arm.go | 1152 +- .../x/sys/unix/zsyscall_darwin_arm.s | 282 + .../x/sys/unix/zsyscall_darwin_arm64.1_11.go} | 845 +- .../x/sys/unix/zsyscall_darwin_arm64.go | 1152 +- .../x/sys/unix/zsyscall_darwin_arm64.s | 282 + .../x/sys/unix/zsyscall_dragonfly_amd64.go | 153 +- .../x/sys/unix/zsyscall_freebsd_386.go | 2 +- .../x/sys/unix/zsyscall_freebsd_amd64.go | 2 +- .../x/sys/unix/zsyscall_freebsd_arm.go | 2 +- .../x/sys/unix/zsyscall_freebsd_arm64.go} | 553 +- .../x/sys/unix/zsyscall_linux_386.go | 80 +- .../x/sys/unix/zsyscall_linux_amd64.go | 97 +- .../x/sys/unix/zsyscall_linux_arm.go | 100 +- .../x/sys/unix/zsyscall_linux_arm64.go | 95 +- .../x/sys/unix/zsyscall_linux_mips.go | 80 +- .../x/sys/unix/zsyscall_linux_mips64.go | 110 +- .../x/sys/unix/zsyscall_linux_mips64le.go | 110 +- .../x/sys/unix/zsyscall_linux_mipsle.go | 80 +- .../x/sys/unix/zsyscall_linux_ppc64.go | 80 +- .../x/sys/unix/zsyscall_linux_ppc64le.go | 80 +- .../x/sys/unix/zsyscall_linux_riscv64.go | 75 +- .../x/sys/unix/zsyscall_linux_s390x.go | 80 +- .../x/sys/unix/zsyscall_linux_sparc64.go | 246 +- .../x/sys/unix/zsyscall_netbsd_386.go | 175 +- .../x/sys/unix/zsyscall_netbsd_amd64.go | 175 +- .../x/sys/unix/zsyscall_netbsd_arm.go | 175 +- .../x/sys/unix/zsyscall_netbsd_arm64.go} | 514 +- .../x/sys/unix/zsyscall_openbsd_386.go | 159 +- .../x/sys/unix/zsyscall_openbsd_amd64.go | 159 +- .../x/sys/unix/zsyscall_openbsd_arm.go | 159 +- .../x/sys/unix/zsyscall_solaris_amd64.go | 2 +- .../x/sys/unix/zsysnum_darwin_386.go | 2 +- .../x/sys/unix/zsysnum_darwin_amd64.go | 6 +- .../x/sys/unix/zsysnum_darwin_arm.go | 2 +- .../x/sys/unix/zsysnum_darwin_arm64.go | 2 +- .../x/sys/unix/zsysnum_dragonfly_amd64.go | 176 +- .../x/sys/unix/zsysnum_freebsd_386.go | 452 +- .../x/sys/unix/zsysnum_freebsd_amd64.go | 452 +- .../x/sys/unix/zsysnum_freebsd_arm.go | 452 +- .../x/sys/unix/zsysnum_freebsd_arm64.go} | 72 +- .../x/sys/unix/zsysnum_linux_386.go | 2 +- .../x/sys/unix/zsysnum_linux_amd64.go | 2 +- .../x/sys/unix/zsysnum_linux_arm.go | 2 +- .../x/sys/unix/zsysnum_linux_arm64.go | 3 +- .../x/sys/unix/zsysnum_linux_mips.go | 2 +- .../x/sys/unix/zsysnum_linux_mips64.go | 2 +- .../x/sys/unix/zsysnum_linux_mips64le.go | 2 +- .../x/sys/unix/zsysnum_linux_mipsle.go | 2 +- .../x/sys/unix/zsysnum_linux_ppc64.go | 2 +- .../x/sys/unix/zsysnum_linux_ppc64le.go | 2 +- .../x/sys/unix/zsysnum_linux_riscv64.go | 3 +- .../x/sys/unix/zsysnum_linux_s390x.go | 2 +- .../x/sys/unix/zsysnum_linux_sparc64.go | 7 +- .../x/sys/unix/zsysnum_netbsd_386.go | 4 +- .../x/sys/unix/zsysnum_netbsd_amd64.go | 4 +- .../x/sys/unix/zsysnum_netbsd_arm.go | 4 +- .../x/sys/unix/zsysnum_netbsd_arm64.go} | 7 +- .../x/sys/unix/zsysnum_openbsd_386.go | 216 +- .../x/sys/unix/zsysnum_openbsd_amd64.go | 216 +- .../x/sys/unix/zsysnum_openbsd_arm.go | 216 +- .../x/sys/unix/ztypes_darwin_386.go | 10 + .../x/sys/unix/ztypes_darwin_amd64.go | 10 + .../x/sys/unix/ztypes_darwin_arm.go | 10 + .../x/sys/unix/ztypes_darwin_arm64.go | 10 + .../x/sys/unix/ztypes_freebsd_386.go | 2 +- .../x/sys/unix/ztypes_freebsd_amd64.go | 2 +- .../x/sys/unix/ztypes_freebsd_arm.go | 2 +- .../x/sys/unix/ztypes_freebsd_arm64.go} | 351 +- .../golang.org/x/sys/unix/ztypes_linux_386.go | 133 +- .../x/sys/unix/ztypes_linux_amd64.go | 140 +- .../golang.org/x/sys/unix/ztypes_linux_arm.go | 134 +- .../x/sys/unix/ztypes_linux_arm64.go | 140 +- .../x/sys/unix/ztypes_linux_mips.go | 131 +- .../x/sys/unix/ztypes_linux_mips64.go | 140 +- .../x/sys/unix/ztypes_linux_mips64le.go | 140 +- .../x/sys/unix/ztypes_linux_mipsle.go | 131 +- .../x/sys/unix/ztypes_linux_ppc64.go | 140 +- .../x/sys/unix/ztypes_linux_ppc64le.go | 140 +- .../x/sys/unix/ztypes_linux_riscv64.go | 142 +- .../x/sys/unix/ztypes_linux_s390x.go | 145 +- .../x/sys/unix/ztypes_linux_sparc64.go | 1586 +- .../x/sys/unix/ztypes_netbsd_386.go | 7 + .../x/sys/unix/ztypes_netbsd_amd64.go | 7 + .../x/sys/unix/ztypes_netbsd_arm.go | 7 + .../x/sys/unix/ztypes_netbsd_arm64.go} | 85 +- .../x/sys/unix/ztypes_openbsd_386.go | 10 + .../x/sys/unix/ztypes_openbsd_amd64.go | 10 + .../x/sys/unix/ztypes_openbsd_arm.go | 112 +- vendor/golang.org/x/text/AUTHORS | 3 + vendor/golang.org/x/text/CONTRIBUTORS | 3 + .../golang.org/x/text/transform/transform.go | 4 +- .../golang.org/x/text/unicode/bidi/bracket.go | 2 +- vendor/golang.org/x/text/unicode/bidi/gen.go | 133 + .../x/text/unicode/bidi/gen_ranges.go | 57 + .../x/text/unicode/bidi/gen_trieval.go | 64 + vendor/golang.org/x/text/unicode/norm/iter.go | 3 +- .../x/text/unicode/norm/maketables.go | 986 + .../x/text/unicode/norm/readwriter.go | 4 +- .../x/text/unicode/norm/transform.go | 10 +- .../golang.org/x/text/unicode/norm/triegen.go | 117 + vendor/golang.org/x/time/AUTHORS | 3 + vendor/golang.org/x/time/CONTRIBUTORS | 3 + vendor/golang.org/x/time/rate/rate.go | 16 +- vendor/golang.org/x/time/rate/rate_go16.go | 21 - vendor/golang.org/x/time/rate/rate_go17.go | 21 - vendor/google.golang.org/api/AUTHORS | 10 + vendor/google.golang.org/api/CONTRIBUTORS | 55 + .../api/compute/v1/compute-api.json | 35286 ------ .../api/compute/v1/compute-gen.go | 97463 ---------------- .../google.golang.org/api/iam/v1/iam-api.json | 1945 - .../google.golang.org/api/iam/v1/iam-gen.go | 6856 -- .../api/transport/http/dial_appengine.go | 30 + .../google.golang.org/appengine/.travis.yml | 20 + .../appengine/CONTRIBUTING.md | 90 + .../appengine}/LICENSE | 0 vendor/google.golang.org/appengine/README.md | 73 + .../google.golang.org/appengine/appengine.go | 137 + .../appengine/appengine_vm.go | 20 + vendor/google.golang.org/appengine/errors.go | 46 + vendor/google.golang.org/appengine/go.mod | 7 + vendor/google.golang.org/appengine/go.sum | 6 + .../google.golang.org/appengine/identity.go | 142 + .../appengine/internal/api.go | 671 + .../appengine/internal/api_classic.go | 169 + .../appengine/internal/api_common.go | 123 + .../appengine/internal/app_id.go | 28 + .../app_identity/app_identity_service.pb.go | 611 + .../app_identity/app_identity_service.proto | 64 + .../appengine/internal/base/api_base.pb.go | 308 + .../appengine/internal/base/api_base.proto | 33 + .../internal/datastore/datastore_v3.pb.go | 4367 + .../internal/datastore/datastore_v3.proto | 551 + .../appengine/internal/identity.go | 55 + .../appengine/internal/identity_classic.go | 61 + .../appengine/internal/identity_flex.go | 11 + .../appengine/internal/identity_vm.go | 134 + .../appengine/internal/internal.go | 110 + .../appengine/internal/log/log_service.pb.go | 1313 + .../appengine/internal/log/log_service.proto | 150 + .../appengine/internal/main.go | 16 + .../appengine/internal/main_common.go | 7 + .../appengine/internal/main_vm.go | 69 + .../appengine/internal/metadata.go | 60 + .../internal/modules/modules_service.pb.go | 786 + .../internal/modules/modules_service.proto | 80 + .../appengine/internal/net.go | 56 + .../appengine/internal/regen.sh | 40 + .../internal/remote_api/remote_api.pb.go | 361 + .../internal/remote_api/remote_api.proto | 44 + .../appengine/internal/transaction.go | 115 + .../internal/urlfetch/urlfetch_service.pb.go | 527 + .../internal/urlfetch/urlfetch_service.proto | 64 + .../google.golang.org/appengine/namespace.go | 25 + vendor/google.golang.org/appengine/timeout.go | 20 + .../appengine/travis_install.sh | 18 + .../appengine/travis_test.sh | 12 + .../appengine/urlfetch/urlfetch.go | 210 + vendor/google.golang.org/grpc/.travis.yml | 39 + .../grpc/balancer/balancer.go | 37 +- .../grpc/balancer/base/balancer.go | 19 +- .../grpc/balancer_conn_wrappers.go | 57 +- vendor/google.golang.org/grpc/clientconn.go | 480 +- vendor/google.golang.org/grpc/codegen.sh | 0 .../internal/syscallconn_appengine.go} | 20 +- vendor/google.golang.org/grpc/dialoptions.go | 19 +- .../grpc/encoding/encoding.go | 6 +- vendor/google.golang.org/grpc/go.mod | 13 +- vendor/google.golang.org/grpc/go.sum | 25 +- .../google.golang.org/grpc/grpclog/grpclog.go | 2 +- .../grpc/health/regenerate.sh | 0 vendor/google.golang.org/grpc/install_gae.sh | 0 .../grpc/internal/binarylog/regenerate.sh | 0 .../grpc/internal/envconfig/envconfig.go | 15 +- .../grpc/internal/transport/handler_server.go | 29 +- .../grpc/internal/transport/http2_client.go | 45 +- .../grpc/internal/transport/http2_server.go | 35 +- .../grpc/internal/transport/http_util.go | 169 +- .../grpc/internal/transport/transport.go | 6 +- .../google.golang.org/grpc/picker_wrapper.go | 5 - .../grpc/resolver/dns/dns_resolver.go | 4 +- .../grpc/resolver/passthrough/passthrough.go | 2 +- .../grpc/resolver/resolver.go | 15 - .../grpc/resolver_conn_wrapper.go | 90 +- vendor/google.golang.org/grpc/server.go | 31 +- .../google.golang.org/grpc/service_config.go | 2 +- vendor/google.golang.org/grpc/stats/stats.go | 5 - vendor/google.golang.org/grpc/stream.go | 41 +- vendor/google.golang.org/grpc/trace.go | 13 - vendor/google.golang.org/grpc/version.go | 2 +- vendor/google.golang.org/grpc/vet.sh | 10 +- .../gopkg.in/square/go-jose.v2/jwt/builder.go | 334 - .../gopkg.in/square/go-jose.v2/jwt/claims.go | 116 - .../gopkg.in/square/go-jose.v2/jwt/errors.go | 50 - vendor/gopkg.in/square/go-jose.v2/jwt/jwt.go | 132 - .../square/go-jose.v2/jwt/validation.go | 89 - vendor/k8s.io/api/LICENSE | 202 - vendor/k8s.io/api/authentication/v1/doc.go | 20 - .../api/authentication/v1/generated.pb.go | 2147 - .../api/authentication/v1/generated.proto | 159 - .../k8s.io/api/authentication/v1/register.go | 52 - vendor/k8s.io/api/authentication/v1/types.go | 168 - .../v1/types_swagger_doc_generated.go | 113 - .../v1/zz_generated.deepcopy.go | 234 - vendor/k8s.io/apimachinery/LICENSE | 202 - .../k8s.io/apimachinery/pkg/api/errors/OWNERS | 24 - .../k8s.io/apimachinery/pkg/api/errors/doc.go | 18 - .../apimachinery/pkg/api/errors/errors.go | 567 - .../apimachinery/pkg/apis/meta/v1/OWNERS | 31 - .../pkg/apis/meta/v1/controller_ref.go | 54 - .../pkg/apis/meta/v1/conversion.go | 319 - .../apimachinery/pkg/apis/meta/v1/doc.go | 22 - .../apimachinery/pkg/apis/meta/v1/duration.go | 50 - .../pkg/apis/meta/v1/generated.pb.go | 8324 -- .../pkg/apis/meta/v1/generated.proto | 879 - .../pkg/apis/meta/v1/group_version.go | 148 - .../apimachinery/pkg/apis/meta/v1/helpers.go | 234 - .../apimachinery/pkg/apis/meta/v1/labels.go | 55 - .../apimachinery/pkg/apis/meta/v1/meta.go | 170 - .../pkg/apis/meta/v1/micro_time.go | 183 - .../pkg/apis/meta/v1/micro_time_proto.go | 72 - .../apimachinery/pkg/apis/meta/v1/register.go | 97 - .../apimachinery/pkg/apis/meta/v1/time.go | 185 - .../pkg/apis/meta/v1/time_proto.go | 92 - .../apimachinery/pkg/apis/meta/v1/types.go | 1005 - .../meta/v1/types_swagger_doc_generated.go | 350 - .../apimachinery/pkg/apis/meta/v1/watch.go | 89 - .../pkg/apis/meta/v1/zz_generated.deepcopy.go | 961 - .../pkg/apis/meta/v1/zz_generated.defaults.go | 32 - .../k8s.io/apimachinery/pkg/runtime/codec.go | 312 - .../apimachinery/pkg/runtime/codec_check.go | 48 - .../apimachinery/pkg/runtime/conversion.go | 113 - .../apimachinery/pkg/runtime/converter.go | 805 - vendor/k8s.io/apimachinery/pkg/runtime/doc.go | 51 - .../apimachinery/pkg/runtime/embedded.go | 142 - .../k8s.io/apimachinery/pkg/runtime/error.go | 122 - .../apimachinery/pkg/runtime/extension.go | 51 - .../apimachinery/pkg/runtime/generated.pb.go | 772 - .../apimachinery/pkg/runtime/generated.proto | 127 - .../k8s.io/apimachinery/pkg/runtime/helper.go | 212 - .../apimachinery/pkg/runtime/interfaces.go | 252 - .../apimachinery/pkg/runtime/register.go | 61 - .../pkg/runtime/schema/generated.pb.go | 64 - .../pkg/runtime/schema/generated.proto | 26 - .../pkg/runtime/schema/group_version.go | 300 - .../pkg/runtime/schema/interfaces.go | 40 - .../k8s.io/apimachinery/pkg/runtime/scheme.go | 754 - .../pkg/runtime/scheme_builder.go | 48 - .../pkg/runtime/swagger_doc_generator.go | 262 - .../k8s.io/apimachinery/pkg/runtime/types.go | 137 - .../apimachinery/pkg/runtime/types_proto.go | 69 - .../pkg/runtime/zz_generated.deepcopy.go | 108 - vendor/modules.txt | 342 + 2068 files changed, 86103 insertions(+), 524611 deletions(-) create mode 100644 vendor/cloud.google.com/go/AUTHORS create mode 100644 vendor/cloud.google.com/go/CONTRIBUTORS mode change 100755 => 100644 vendor/cloud.google.com/go/internal/version/update_version.sh delete mode 100644 vendor/github.com/SermoDigital/jose/LICENSE delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/ecdsa.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/hmac.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/none.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/signature.go delete mode 100644 vendor/github.com/SermoDigital/jose/crypto/signing_method.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/claims.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws_serialize.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jws_validate.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/jwt.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/payload.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/rawbase64.go delete mode 100644 vendor/github.com/SermoDigital/jose/jws/signing_methods.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/claims.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/doc.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/eq.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/errors.go delete mode 100644 vendor/github.com/SermoDigital/jose/jwt/jwt.go create mode 100644 vendor/github.com/agext/levenshtein/.gitignore create mode 100644 vendor/github.com/agext/levenshtein/.travis.yml mode change 100755 => 100644 vendor/github.com/agext/levenshtein/test.sh delete mode 100644 vendor/github.com/apparentlymart/go-rundeck-api/LICENSE delete mode 100644 vendor/github.com/apparentlymart/go-rundeck-api/README.md create mode 100644 vendor/github.com/apparentlymart/go-textseg/textseg/make_tables.go create mode 100644 vendor/github.com/apparentlymart/go-textseg/textseg/make_test_tables.go delete mode 100644 vendor/github.com/armon/go-metrics/LICENSE delete mode 100644 vendor/github.com/armon/go-metrics/README.md delete mode 100644 vendor/github.com/armon/go-metrics/circonus/circonus.go delete mode 100644 vendor/github.com/armon/go-metrics/const_unix.go delete mode 100644 vendor/github.com/armon/go-metrics/const_windows.go delete mode 100644 vendor/github.com/armon/go-metrics/datadog/dogstatsd.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem_endpoint.go delete mode 100644 vendor/github.com/armon/go-metrics/inmem_signal.go delete mode 100644 vendor/github.com/armon/go-metrics/metrics.go delete mode 100644 vendor/github.com/armon/go-metrics/sink.go delete mode 100644 vendor/github.com/armon/go-metrics/start.go delete mode 100644 vendor/github.com/armon/go-metrics/statsd.go delete mode 100644 vendor/github.com/armon/go-metrics/statsite.go create mode 100644 vendor/github.com/armon/go-radix/.gitignore create mode 100644 vendor/github.com/armon/go-radix/.travis.yml rename vendor/github.com/aws/aws-sdk-go/aws/{context.go => context_1_5.go} (58%) delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go create mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/s3err/error.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go create mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/api.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/host.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go create mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/converter.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/decode.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/encode.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/field.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/tag.go create mode 100644 vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go create mode 100644 vendor/github.com/bgentry/speakeasy/.gitignore create mode 100644 vendor/github.com/blang/semver/.travis.yml delete mode 100644 vendor/github.com/briankassouf/jose/LICENSE delete mode 100644 vendor/github.com/briankassouf/jose/crypto/doc.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/ecdsa.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/ecdsa_utils.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/errors.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/hmac.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/none.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/rsa.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/rsa_pss.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/rsa_utils.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/signature.go delete mode 100644 vendor/github.com/briankassouf/jose/crypto/signing_method.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/claims.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/doc.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/errors.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/jws.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/jws_serialize.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/jws_validate.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/jwt.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/payload.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/rawbase64.go delete mode 100644 vendor/github.com/briankassouf/jose/jws/signing_methods.go delete mode 100644 vendor/github.com/briankassouf/jose/jwt/claims.go delete mode 100644 vendor/github.com/briankassouf/jose/jwt/doc.go delete mode 100644 vendor/github.com/briankassouf/jose/jwt/eq.go delete mode 100644 vendor/github.com/briankassouf/jose/jwt/errors.go delete mode 100644 vendor/github.com/briankassouf/jose/jwt/jwt.go delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/LICENSE.txt delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/okta/apps.go delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/okta/factors.go delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/okta/groups.go delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/okta/sdk.go delete mode 100644 vendor/github.com/chrismalek/oktasdk-go/okta/users.go delete mode 100644 vendor/github.com/cockroachdb/cockroach-go/LICENSE delete mode 100644 vendor/github.com/cockroachdb/cockroach-go/crdb/error.go delete mode 100644 vendor/github.com/cockroachdb/cockroach-go/crdb/tx.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/LICENSE.txt delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/README.md delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/appveyor.yml delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/buf.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/bulkcopy.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/bulkcopy_sql.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/convert.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/decimal.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/doc.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/error.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/log.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/mssql.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/mssql_go110.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/mssql_go19.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/mssql_go19pre.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/net.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/ntlm.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/parser.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/rpc.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/sspi_windows.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/tds.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/token.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/token_string.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/tran.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/types.go delete mode 100644 vendor/github.com/denisenkom/go-mssqldb/uniqueidentifier.go create mode 100644 vendor/github.com/fatih/color/.travis.yml delete mode 100644 vendor/github.com/fatih/structs/LICENSE delete mode 100644 vendor/github.com/fatih/structs/README.md delete mode 100644 vendor/github.com/fatih/structs/field.go delete mode 100644 vendor/github.com/fatih/structs/structs.go delete mode 100644 vendor/github.com/fatih/structs/tags.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/AUTHORS delete mode 100644 vendor/github.com/fsouza/go-dockerclient/DOCKER-LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/Makefile delete mode 100644 vendor/github.com/fsouza/go-dockerclient/README.markdown delete mode 100644 vendor/github.com/fsouza/go-dockerclient/auth.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/cancelable.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/cancelable_go14.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/change.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/client.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/container.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/env.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/event.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/exec.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/CHANGELOG.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/doc.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/exported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hooks.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logger.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_bsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_notwindows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_solaris.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/writer.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_other.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/whiteouts.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writeflusher.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise/promise.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/errors.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/events_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_freebsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_openbsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_solaris.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask_windows.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_darwin.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_freebsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/CONTRIBUTING.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.code delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.docs delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/MAINTAINERS delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/circle.yml delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/LICENSE delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/README.md delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/cleanhttp.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_arm.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_arm.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_386.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unset.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock_linux_32bit.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkall.sh delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkerrors.sh delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall_solaris.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysctl_openbsd.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_darwin.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_dragonfly.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_freebsd.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_linux.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_netbsd.pl delete mode 100755 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksysnum_openbsd.pl delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/race.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/str.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_no_getwd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysctl_openbsd.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_solaris_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/image.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/misc.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/network.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/signal.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/tar.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/Dockerfile delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/barfile delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/ca.pem delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/cert.pem delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/container.tar delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/foofile delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/key.pem delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/server.pem delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem delete mode 100644 vendor/github.com/fsouza/go-dockerclient/testing/server.go delete mode 100644 vendor/github.com/fsouza/go-dockerclient/tls.go delete mode 100755 vendor/github.com/fsouza/go-dockerclient/travis-scripts/install.bash delete mode 100755 vendor/github.com/fsouza/go-dockerclient/travis-scripts/run-tests.bash delete mode 100644 vendor/github.com/fsouza/go-dockerclient/volume.go delete mode 100644 vendor/github.com/ghodss/yaml/LICENSE delete mode 100644 vendor/github.com/ghodss/yaml/README.md delete mode 100644 vendor/github.com/ghodss/yaml/fields.go delete mode 100644 vendor/github.com/ghodss/yaml/yaml.go delete mode 100644 vendor/github.com/ghodss/yaml/yaml_go110.go delete mode 100644 vendor/github.com/go-errors/errors/LICENSE.MIT delete mode 100644 vendor/github.com/go-errors/errors/README.md delete mode 100644 vendor/github.com/go-errors/errors/cover.out delete mode 100644 vendor/github.com/go-errors/errors/error.go delete mode 100644 vendor/github.com/go-errors/errors/parse_panic.go delete mode 100644 vendor/github.com/go-errors/errors/stackframe.go delete mode 100644 vendor/github.com/go-ini/ini/LICENSE delete mode 100644 vendor/github.com/go-ini/ini/Makefile delete mode 100644 vendor/github.com/go-ini/ini/README.md delete mode 100644 vendor/github.com/go-ini/ini/README_ZH.md delete mode 100644 vendor/github.com/go-ini/ini/error.go delete mode 100644 vendor/github.com/go-ini/ini/ini.go delete mode 100644 vendor/github.com/go-ini/ini/key.go delete mode 100644 vendor/github.com/go-ini/ini/parser.go delete mode 100644 vendor/github.com/go-ini/ini/section.go delete mode 100644 vendor/github.com/go-ini/ini/struct.go create mode 100644 vendor/github.com/golang/protobuf/AUTHORS create mode 100644 vendor/github.com/golang/protobuf/CONTRIBUTORS create mode 100644 vendor/github.com/golang/snappy/.gitignore create mode 100644 vendor/github.com/golang/snappy/AUTHORS create mode 100644 vendor/github.com/golang/snappy/CONTRIBUTORS rename vendor/github.com/{google/go-github => golang/snappy}/LICENSE (95%) create mode 100644 vendor/github.com/golang/snappy/README create mode 100644 vendor/github.com/golang/snappy/decode.go create mode 100644 vendor/github.com/golang/snappy/decode_amd64.go create mode 100644 vendor/github.com/golang/snappy/decode_amd64.s create mode 100644 vendor/github.com/golang/snappy/decode_other.go create mode 100644 vendor/github.com/golang/snappy/encode.go create mode 100644 vendor/github.com/golang/snappy/encode_amd64.go create mode 100644 vendor/github.com/golang/snappy/encode_amd64.s create mode 100644 vendor/github.com/golang/snappy/encode_other.go create mode 100644 vendor/github.com/golang/snappy/snappy.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_legacy.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_recent.go create mode 100644 vendor/github.com/google/go-cmp/cmp/internal/value/format.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/internal/value/zero.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report_compare.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report_reflect.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report_slices.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report_text.go delete mode 100644 vendor/github.com/google/go-cmp/cmp/report_value.go create mode 100644 vendor/github.com/google/go-cmp/cmp/reporter.go rename vendor/github.com/google/go-cmp/cmp/{export_panic.go => unsafe_panic.go} (60%) rename vendor/github.com/google/go-cmp/cmp/{export_unsafe.go => unsafe_reflect.go} (64%) delete mode 100644 vendor/github.com/google/go-github/github/activity.go delete mode 100644 vendor/github.com/google/go-github/github/activity_events.go delete mode 100644 vendor/github.com/google/go-github/github/activity_notifications.go delete mode 100644 vendor/github.com/google/go-github/github/activity_star.go delete mode 100644 vendor/github.com/google/go-github/github/activity_watching.go delete mode 100644 vendor/github.com/google/go-github/github/admin.go delete mode 100644 vendor/github.com/google/go-github/github/admin_stats.go delete mode 100644 vendor/github.com/google/go-github/github/apps.go delete mode 100644 vendor/github.com/google/go-github/github/apps_installation.go delete mode 100644 vendor/github.com/google/go-github/github/apps_marketplace.go delete mode 100644 vendor/github.com/google/go-github/github/authorizations.go delete mode 100644 vendor/github.com/google/go-github/github/checks.go delete mode 100644 vendor/github.com/google/go-github/github/doc.go delete mode 100644 vendor/github.com/google/go-github/github/event_types.go delete mode 100644 vendor/github.com/google/go-github/github/gists.go delete mode 100644 vendor/github.com/google/go-github/github/gists_comments.go delete mode 100644 vendor/github.com/google/go-github/github/git.go delete mode 100644 vendor/github.com/google/go-github/github/git_blobs.go delete mode 100644 vendor/github.com/google/go-github/github/git_commits.go delete mode 100644 vendor/github.com/google/go-github/github/git_refs.go delete mode 100644 vendor/github.com/google/go-github/github/git_tags.go delete mode 100644 vendor/github.com/google/go-github/github/git_trees.go delete mode 100644 vendor/github.com/google/go-github/github/github-accessors.go delete mode 100644 vendor/github.com/google/go-github/github/github.go delete mode 100644 vendor/github.com/google/go-github/github/gitignore.go delete mode 100644 vendor/github.com/google/go-github/github/issues.go delete mode 100644 vendor/github.com/google/go-github/github/issues_assignees.go delete mode 100644 vendor/github.com/google/go-github/github/issues_comments.go delete mode 100644 vendor/github.com/google/go-github/github/issues_events.go delete mode 100644 vendor/github.com/google/go-github/github/issues_labels.go delete mode 100644 vendor/github.com/google/go-github/github/issues_milestones.go delete mode 100644 vendor/github.com/google/go-github/github/issues_timeline.go delete mode 100644 vendor/github.com/google/go-github/github/licenses.go delete mode 100644 vendor/github.com/google/go-github/github/messages.go delete mode 100644 vendor/github.com/google/go-github/github/migrations.go delete mode 100644 vendor/github.com/google/go-github/github/migrations_source_import.go delete mode 100644 vendor/github.com/google/go-github/github/migrations_user.go delete mode 100644 vendor/github.com/google/go-github/github/misc.go delete mode 100644 vendor/github.com/google/go-github/github/orgs.go delete mode 100644 vendor/github.com/google/go-github/github/orgs_hooks.go delete mode 100644 vendor/github.com/google/go-github/github/orgs_members.go delete mode 100644 vendor/github.com/google/go-github/github/orgs_outside_collaborators.go delete mode 100644 vendor/github.com/google/go-github/github/orgs_projects.go delete mode 100644 vendor/github.com/google/go-github/github/orgs_users_blocking.go delete mode 100644 vendor/github.com/google/go-github/github/projects.go delete mode 100644 vendor/github.com/google/go-github/github/pulls.go delete mode 100644 vendor/github.com/google/go-github/github/pulls_comments.go delete mode 100644 vendor/github.com/google/go-github/github/pulls_reviewers.go delete mode 100644 vendor/github.com/google/go-github/github/pulls_reviews.go delete mode 100644 vendor/github.com/google/go-github/github/reactions.go delete mode 100644 vendor/github.com/google/go-github/github/repos.go delete mode 100644 vendor/github.com/google/go-github/github/repos_collaborators.go delete mode 100644 vendor/github.com/google/go-github/github/repos_comments.go delete mode 100644 vendor/github.com/google/go-github/github/repos_commits.go delete mode 100644 vendor/github.com/google/go-github/github/repos_community_health.go delete mode 100644 vendor/github.com/google/go-github/github/repos_contents.go delete mode 100644 vendor/github.com/google/go-github/github/repos_deployments.go delete mode 100644 vendor/github.com/google/go-github/github/repos_forks.go delete mode 100644 vendor/github.com/google/go-github/github/repos_hooks.go delete mode 100644 vendor/github.com/google/go-github/github/repos_invitations.go delete mode 100644 vendor/github.com/google/go-github/github/repos_keys.go delete mode 100644 vendor/github.com/google/go-github/github/repos_merging.go delete mode 100644 vendor/github.com/google/go-github/github/repos_pages.go delete mode 100644 vendor/github.com/google/go-github/github/repos_prereceive_hooks.go delete mode 100644 vendor/github.com/google/go-github/github/repos_projects.go delete mode 100644 vendor/github.com/google/go-github/github/repos_releases.go delete mode 100644 vendor/github.com/google/go-github/github/repos_stats.go delete mode 100644 vendor/github.com/google/go-github/github/repos_statuses.go delete mode 100644 vendor/github.com/google/go-github/github/repos_traffic.go delete mode 100644 vendor/github.com/google/go-github/github/search.go delete mode 100644 vendor/github.com/google/go-github/github/strings.go delete mode 100644 vendor/github.com/google/go-github/github/teams.go delete mode 100644 vendor/github.com/google/go-github/github/teams_discussion_comments.go delete mode 100644 vendor/github.com/google/go-github/github/teams_discussions.go delete mode 100644 vendor/github.com/google/go-github/github/teams_members.go delete mode 100644 vendor/github.com/google/go-github/github/timestamp.go delete mode 100644 vendor/github.com/google/go-github/github/users.go delete mode 100644 vendor/github.com/google/go-github/github/users_administration.go delete mode 100644 vendor/github.com/google/go-github/github/users_blocking.go delete mode 100644 vendor/github.com/google/go-github/github/users_emails.go delete mode 100644 vendor/github.com/google/go-github/github/users_followers.go delete mode 100644 vendor/github.com/google/go-github/github/users_gpg_keys.go delete mode 100644 vendor/github.com/google/go-github/github/users_keys.go delete mode 100644 vendor/github.com/google/go-github/github/without_appengine.go rename vendor/github.com/googleapis/gax-go/{ => v2}/LICENSE (100%) create mode 100644 vendor/github.com/gosimple/slug/.gitignore create mode 100644 vendor/github.com/gosimple/slug/.travis.yml delete mode 100644 vendor/github.com/hashicorp/consul/LICENSE delete mode 100644 vendor/github.com/hashicorp/consul/NOTICE.md delete mode 100644 vendor/github.com/hashicorp/consul/api/README.md delete mode 100644 vendor/github.com/hashicorp/consul/api/acl.go delete mode 100644 vendor/github.com/hashicorp/consul/api/agent.go delete mode 100644 vendor/github.com/hashicorp/consul/api/api.go delete mode 100644 vendor/github.com/hashicorp/consul/api/catalog.go delete mode 100644 vendor/github.com/hashicorp/consul/api/connect.go delete mode 100644 vendor/github.com/hashicorp/consul/api/connect_ca.go delete mode 100644 vendor/github.com/hashicorp/consul/api/connect_intention.go delete mode 100644 vendor/github.com/hashicorp/consul/api/coordinate.go delete mode 100644 vendor/github.com/hashicorp/consul/api/event.go delete mode 100644 vendor/github.com/hashicorp/consul/api/health.go delete mode 100644 vendor/github.com/hashicorp/consul/api/kv.go delete mode 100644 vendor/github.com/hashicorp/consul/api/lock.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_area.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_autopilot.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_keyring.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_raft.go delete mode 100644 vendor/github.com/hashicorp/consul/api/operator_segment.go delete mode 100644 vendor/github.com/hashicorp/consul/api/prepared_query.go delete mode 100644 vendor/github.com/hashicorp/consul/api/raw.go delete mode 100644 vendor/github.com/hashicorp/consul/api/semaphore.go delete mode 100644 vendor/github.com/hashicorp/consul/api/session.go delete mode 100644 vendor/github.com/hashicorp/consul/api/snapshot.go delete mode 100644 vendor/github.com/hashicorp/consul/api/status.go create mode 100644 vendor/github.com/hashicorp/errwrap/go.mod create mode 100644 vendor/github.com/hashicorp/go-cleanhttp/go.mod create mode 100644 vendor/github.com/hashicorp/go-cleanhttp/handlers.go delete mode 100644 vendor/github.com/hashicorp/go-gcp-common/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-gcp-common/gcputil/compute.go delete mode 100644 vendor/github.com/hashicorp/go-gcp-common/gcputil/credentials.go delete mode 100644 vendor/github.com/hashicorp/go-gcp-common/gcputil/iam_admin.go delete mode 100644 vendor/github.com/hashicorp/go-gcp-common/gcputil/resource_name.go create mode 100644 vendor/github.com/hashicorp/go-getter/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-hclog/.gitignore rename vendor/github.com/hashicorp/go-hclog/{int.go => intlogger.go} (57%) rename vendor/github.com/hashicorp/go-hclog/{log.go => logger.go} (77%) create mode 100644 vendor/github.com/hashicorp/go-hclog/writer.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-memdb/README.md delete mode 100644 vendor/github.com/hashicorp/go-memdb/filter.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/index.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/memdb.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/schema.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/txn.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/watch.go delete mode 100644 vendor/github.com/hashicorp/go-memdb/watch_few.go create mode 100644 vendor/github.com/hashicorp/go-multierror/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-multierror/Makefile create mode 100644 vendor/github.com/hashicorp/go-multierror/go.mod create mode 100644 vendor/github.com/hashicorp/go-multierror/go.sum create mode 100644 vendor/github.com/hashicorp/go-multierror/sort.go create mode 100644 vendor/github.com/hashicorp/go-plugin/.gitignore create mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.gitignore create mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-retryablehttp/go.mod create mode 100644 vendor/github.com/hashicorp/go-retryablehttp/go.sum create mode 100644 vendor/github.com/hashicorp/go-rootcerts/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-sockaddr/.gitignore create mode 100644 vendor/github.com/hashicorp/go-sockaddr/go.mod delete mode 100644 vendor/github.com/hashicorp/go-syslog/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-syslog/README.md delete mode 100644 vendor/github.com/hashicorp/go-syslog/builtin.go delete mode 100644 vendor/github.com/hashicorp/go-syslog/syslog.go delete mode 100644 vendor/github.com/hashicorp/go-syslog/unix.go delete mode 100644 vendor/github.com/hashicorp/go-syslog/unsupported.go create mode 100644 vendor/github.com/hashicorp/go-uuid/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-uuid/go.mod create mode 100644 vendor/github.com/hashicorp/go-version/.travis.yml delete mode 100644 vendor/github.com/hashicorp/golang-lru/2q.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/README.md delete mode 100644 vendor/github.com/hashicorp/golang-lru/arc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/doc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/go.mod delete mode 100644 vendor/github.com/hashicorp/golang-lru/lru.go create mode 100644 vendor/github.com/hashicorp/hcl/.gitignore create mode 100644 vendor/github.com/hashicorp/hcl/.travis.yml create mode 100644 vendor/github.com/hashicorp/hcl/go.mod create mode 100644 vendor/github.com/hashicorp/hcl/go.sum delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go delete mode 100644 vendor/github.com/hashicorp/hcl/hcl/printer/printer.go mode change 100755 => 100644 vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars.go create mode 100644 vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars_gen.go create mode 100644 vendor/github.com/hashicorp/hil/.gitignore create mode 100644 vendor/github.com/hashicorp/hil/.travis.yml create mode 100644 vendor/github.com/hashicorp/logutils/.gitignore delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/arn.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/cli.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-alicloud/role_entry.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/azure.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-azure/util.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/cli.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_gcp.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_stubbed.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_gce.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/cli.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/helpers.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/login_util.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/token_review.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/client.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/entry.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/fieldregistry.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/time.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/engineconf.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/passwordconf.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_creds.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_rotate_root_creds.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/role.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/passwords.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/secrets_client.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/client.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_service_principal.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-azure/provider.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_role_set.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/role_set.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/rollback.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_access_token.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_service_account_key.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.lock delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.toml delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/LICENSE delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/Makefile delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/README.md delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/backend.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/passthrough.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_data.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_delete.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_destroy.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_metadata.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.proto delete mode 100644 vendor/github.com/hashicorp/vault-plugin-secrets-kv/upgrade.go delete mode 100644 vendor/github.com/hashicorp/vault/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/vault/CONTRIBUTING.md delete mode 100644 vendor/github.com/hashicorp/vault/Makefile delete mode 100644 vendor/github.com/hashicorp/vault/README.md delete mode 100644 vendor/github.com/hashicorp/vault/audit/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format_json.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/format_jsonx.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/formatter.go delete mode 100644 vendor/github.com/hashicorp/vault/audit/hashstructure.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/audit/file/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/audit/socket/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/audit/syslog/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/app-id/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/app-id/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/approle/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/approle/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/approle/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/approle/path_tidy_user_id.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/approle/validation.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/client.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_certificate.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_client.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_sts.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_identity_whitelist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_roletag_blacklist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_identity_whitelist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role_tag.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_roletag_blacklist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_identity_whitelist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_roletag_blacklist.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/path_certs.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/path_crls.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/cert/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/github/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/github/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/github/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/github/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_groups.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_users.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/path_groups.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/okta/path_users.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/radius/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/radius/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/radius/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/radius/path_users.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/token/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/cli.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_login.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_password.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_policies.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_users.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/client.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_root.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/path_user.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/rollback.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/aws/secret_access_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/cassandra/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/client.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/path_token.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/consul/secret_token.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/path_rotate_credentials.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/database/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mongodb/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mssql/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_role_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/mysql/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_access.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/nomad/secret_token.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/ca_util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/cert_util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/crl_util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/fields.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_ca.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_crl.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_urls.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_fetch.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_intermediate.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_issue_sign.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_revoke.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_root.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/path_tidy.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/secret_certs.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/pki/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_role_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/query.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/postgresql/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_connection.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_lease.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_role_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/secret_creds.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/communicator.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/linux_install_script.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_ca.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_zeroaddress.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_creds_create.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_fetch.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_lookup.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_roles.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_sign.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_verify.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_dynamic_key.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_otp.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/ssh/util.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/totp/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/totp/path_code.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/totp/path_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_backup.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_config.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_datakey.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_decrypt.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_encrypt.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_export.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hash.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hmac.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_random.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_restore.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rewrap.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rotate.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/logical/transit/path_sign_verify.go delete mode 100644 vendor/github.com/hashicorp/vault/builtin/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/alicloud/alicloud.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/aws/aws.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/azure/azure.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/gcp/gcp.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/jwt/jwt.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/auth/kubernetes/kubernetes.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/config/config.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/sink/file/file_sink.go delete mode 100644 vendor/github.com/hashicorp/vault/command/agent/sink/sink.go delete mode 100644 vendor/github.com/hashicorp/vault/command/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/command/audit_disable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/audit_enable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/audit_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth_disable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth_enable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth_help.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/auth_tune.go delete mode 100644 vendor/github.com/hashicorp/vault/command/base.go delete mode 100644 vendor/github.com/hashicorp/vault/command/base_flags.go delete mode 100644 vendor/github.com/hashicorp/vault/command/base_helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/command/base_predict.go delete mode 100644 vendor/github.com/hashicorp/vault/command/commands.go delete mode 100644 vendor/github.com/hashicorp/vault/command/config.go delete mode 100644 vendor/github.com/hashicorp/vault/command/delete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/format.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_delete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_destroy.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_enable_versioning.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_get.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_metadata.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_metadata_delete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_metadata_get.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_metadata_put.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_patch.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_put.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_rollback.go delete mode 100644 vendor/github.com/hashicorp/vault/command/kv_undelete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/command/lease_renew.go delete mode 100644 vendor/github.com/hashicorp/vault/command/lease_revoke.go delete mode 100644 vendor/github.com/hashicorp/vault/command/list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/login.go delete mode 100644 vendor/github.com/hashicorp/vault/command/main.go delete mode 100644 vendor/github.com/hashicorp/vault/command/namespace.go delete mode 100644 vendor/github.com/hashicorp/vault/command/namespace_create.go delete mode 100644 vendor/github.com/hashicorp/vault/command/namespace_delete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/namespace_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/namespace_lookup.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_init.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_key_status.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_seal.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_step_down.go delete mode 100644 vendor/github.com/hashicorp/vault/command/operator_unseal.go delete mode 100644 vendor/github.com/hashicorp/vault/command/path_help.go delete mode 100644 vendor/github.com/hashicorp/vault/command/plugin.go delete mode 100644 vendor/github.com/hashicorp/vault/command/plugin_deregister.go delete mode 100644 vendor/github.com/hashicorp/vault/command/plugin_info.go delete mode 100644 vendor/github.com/hashicorp/vault/command/plugin_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/plugin_register.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policies_deprecated.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy_delete.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy_fmt.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy_read.go delete mode 100644 vendor/github.com/hashicorp/vault/command/policy_write.go delete mode 100644 vendor/github.com/hashicorp/vault/command/read.go delete mode 100644 vendor/github.com/hashicorp/vault/command/rotate.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets_disable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets_enable.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets_list.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets_move.go delete mode 100644 vendor/github.com/hashicorp/vault/command/secrets_tune.go delete mode 100644 vendor/github.com/hashicorp/vault/command/server.go delete mode 100644 vendor/github.com/hashicorp/vault/command/server/config.go delete mode 100644 vendor/github.com/hashicorp/vault/command/server/listener.go delete mode 100644 vendor/github.com/hashicorp/vault/command/server/listener_tcp.go delete mode 100644 vendor/github.com/hashicorp/vault/command/ssh.go delete mode 100644 vendor/github.com/hashicorp/vault/command/status.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token_capabilities.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token_create.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token_lookup.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token_renew.go delete mode 100644 vendor/github.com/hashicorp/vault/command/token_revoke.go delete mode 100644 vendor/github.com/hashicorp/vault/command/unwrap.go delete mode 100644 vendor/github.com/hashicorp/vault/command/util.go delete mode 100644 vendor/github.com/hashicorp/vault/command/version.go delete mode 100644 vendor/github.com/hashicorp/vault/command/write.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/base62/base62.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/builtinplugins/builtin.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/certutil/helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/certutil/types.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/cidrutil/cidr.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/dhutil/dhutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/errutil/error.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/forwarding/util.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/gated-writer/writer.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/identity.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/sentinel.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/templating.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/identity/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/kv-builder/builder.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/ldaputil/client.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/ldaputil/config.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/ldaputil/connection.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/ldaputil/ldap.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/locksutil/locks.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/logging/vault.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mfa/mfa.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mfa/path_mfa_config.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/namespace/namespace.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/password/password.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/password/password_solaris.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/password/password_unix.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/password/password_windows.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/env.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/reload/reload.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/salt/salt.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/useragent/useragent.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go delete mode 100644 vendor/github.com/hashicorp/vault/helper/xor/xor.go delete mode 100644 vendor/github.com/hashicorp/vault/http/cors.go delete mode 100644 vendor/github.com/hashicorp/vault/http/handler.go delete mode 100644 vendor/github.com/hashicorp/vault/http/help.go delete mode 100644 vendor/github.com/hashicorp/vault/http/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/http/stub_assets.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_health.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_init.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_leader.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/http/sys_seal.go delete mode 100644 vendor/github.com/hashicorp/vault/http/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/connection.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/error.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/field_data.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/field_type.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path_map.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/path_struct.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/policy_map.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/template.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/framework/wal.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/identity.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/identity.proto delete mode 100644 vendor/github.com/hashicorp/vault/logical/lease.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/logical.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin.proto delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/logger.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/middleware.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/plugin.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/serve.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/plugin/system.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/request.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/response.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/response_util.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/secret.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/storage.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/storage_inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/system_view.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/token.go delete mode 100644 vendor/github.com/hashicorp/vault/logical/translate_response.go delete mode 100644 vendor/github.com/hashicorp/vault/main.go delete mode 100644 vendor/github.com/hashicorp/vault/make.bat delete mode 100644 vendor/github.com/hashicorp/vault/physical/alicloudoss/alicloudoss.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/azure/azure.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/cache.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/cassandra/cassandra.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/cockroachdb/cockroachdb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/consul/consul.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/couchdb/couchdb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/dynamodb/dynamodb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/etcd/etcd.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/etcd/etcd2.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/etcd/etcd3.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/file/file.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/foundationdb/README.md delete mode 100755 vendor/github.com/hashicorp/vault/physical/foundationdb/fdb-go-install.sh delete mode 100644 vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdbstub.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/gcs/gcs.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/gcs/gcs_ha.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/inmem/inmem.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/latency.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/manta/manta.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/mssql/mssql.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/mysql/mysql.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical_access.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/physical_view.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/postgresql/postgresql.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/s3/s3.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/spanner/spanner.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/spanner/spanner_ha.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/swift/swift.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/transactions.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/types.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/physical/types.proto delete mode 100644 vendor/github.com/hashicorp/vault/physical/zookeeper/zookeeper.go delete mode 100644 vendor/github.com/hashicorp/vault/shamir/shamir.go delete mode 100644 vendor/github.com/hashicorp/vault/shamir/tables.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/acl.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audit.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audit_broker.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/audited_headers.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/auth.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/barrier_view.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/capabilities.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/cluster.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/core.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/cors.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/expiration.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/generate_root.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/ha.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_lookup.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_entities.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_groups.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_schema.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_structs.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/identity_store_util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/init.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/keyring.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_passthrough.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_system.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/mount.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/plugin_catalog.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/plugin_reload.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/policy_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/rekey.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto delete mode 100644 vendor/github.com/hashicorp/vault/vault/request_handling.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/rollback.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/router.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/router_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_access.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/seal_testing.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/sealunwrapper.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/testing.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/token_store.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/ui.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/util.go delete mode 100644 vendor/github.com/hashicorp/vault/vault/wrapping.go delete mode 100644 vendor/github.com/hashicorp/vault/version/cgo.go delete mode 100644 vendor/github.com/hashicorp/vault/version/version.go delete mode 100644 vendor/github.com/hashicorp/vault/version/version_base.go create mode 100644 vendor/github.com/hashicorp/yamux/.gitignore create mode 100644 vendor/github.com/hashicorp/yamux/go.mod create mode 100644 vendor/github.com/jmespath/go-jmespath/.gitignore create mode 100644 vendor/github.com/jmespath/go-jmespath/.travis.yml delete mode 100644 vendor/github.com/keybase/go-crypto/LICENSE delete mode 100644 vendor/github.com/keybase/go-crypto/PATENTS delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/keys.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/config.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/patch.sh delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/read.go delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch delete mode 100644 vendor/github.com/keybase/go-crypto/openpgp/write.go delete mode 100644 vendor/github.com/kr/pretty/License delete mode 100644 vendor/github.com/kr/pretty/Readme delete mode 100644 vendor/github.com/kr/pretty/diff.go delete mode 100644 vendor/github.com/kr/pretty/formatter.go delete mode 100644 vendor/github.com/kr/pretty/go.mod delete mode 100644 vendor/github.com/kr/pretty/pretty.go delete mode 100644 vendor/github.com/kr/pretty/zero.go delete mode 100644 vendor/github.com/kr/text/License delete mode 100644 vendor/github.com/kr/text/Readme delete mode 100644 vendor/github.com/kr/text/doc.go delete mode 100644 vendor/github.com/kr/text/go.mod delete mode 100644 vendor/github.com/kr/text/indent.go delete mode 100644 vendor/github.com/kr/text/wrap.go delete mode 100644 vendor/github.com/lib/pq/CONTRIBUTING.md delete mode 100644 vendor/github.com/lib/pq/LICENSE.md delete mode 100644 vendor/github.com/lib/pq/README.md delete mode 100644 vendor/github.com/lib/pq/TESTS.md delete mode 100644 vendor/github.com/lib/pq/array.go delete mode 100644 vendor/github.com/lib/pq/buf.go delete mode 100644 vendor/github.com/lib/pq/conn.go delete mode 100644 vendor/github.com/lib/pq/conn_go18.go delete mode 100644 vendor/github.com/lib/pq/connector.go delete mode 100644 vendor/github.com/lib/pq/copy.go delete mode 100644 vendor/github.com/lib/pq/doc.go delete mode 100644 vendor/github.com/lib/pq/encode.go delete mode 100644 vendor/github.com/lib/pq/error.go delete mode 100644 vendor/github.com/lib/pq/go.mod delete mode 100644 vendor/github.com/lib/pq/notify.go delete mode 100644 vendor/github.com/lib/pq/rows.go delete mode 100644 vendor/github.com/lib/pq/ssl.go delete mode 100644 vendor/github.com/lib/pq/ssl_go1.7.go delete mode 100644 vendor/github.com/lib/pq/ssl_permissions.go delete mode 100644 vendor/github.com/lib/pq/ssl_renegotiation.go delete mode 100644 vendor/github.com/lib/pq/ssl_windows.go delete mode 100644 vendor/github.com/lib/pq/url.go delete mode 100644 vendor/github.com/lib/pq/user_posix.go delete mode 100644 vendor/github.com/lib/pq/user_windows.go delete mode 100644 vendor/github.com/lib/pq/uuid.go create mode 100644 vendor/github.com/mattn/go-colorable/.travis.yml create mode 100644 vendor/github.com/mattn/go-colorable/colorable_appengine.go create mode 100644 vendor/github.com/mattn/go-isatty/.travis.yml create mode 100644 vendor/github.com/mattn/go-isatty/isatty_appengine.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/CONTRIBUTING.md delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/ChangeLog.md delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/LICENSE delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/Makefile delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/README.md delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/bindings.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/channels.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/client.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/cluster.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/common.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/connections.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/doc.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/error.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/exchanges.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/federation.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/misc.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/nodes.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/permissions.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/plugins.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/policies.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/queues.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/shovels.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/users.go delete mode 100644 vendor/github.com/michaelklishin/rabbit-hole/vhosts.go create mode 100644 vendor/github.com/mitchellh/cli/.travis.yml create mode 100644 vendor/github.com/mitchellh/cli/go.mod create mode 100644 vendor/github.com/mitchellh/cli/go.sum create mode 100644 vendor/github.com/mitchellh/copystructure/.travis.yml create mode 100644 vendor/github.com/mitchellh/copystructure/go.mod create mode 100644 vendor/github.com/mitchellh/copystructure/go.sum create mode 100644 vendor/github.com/mitchellh/go-homedir/go.mod create mode 100644 vendor/github.com/mitchellh/go-testing-interface/.travis.yml create mode 100644 vendor/github.com/mitchellh/mapstructure/.travis.yml create mode 100644 vendor/github.com/mitchellh/mapstructure/CHANGELOG.md create mode 100644 vendor/github.com/mitchellh/mapstructure/go.mod create mode 100644 vendor/github.com/mitchellh/reflectwalk/.travis.yml create mode 100644 vendor/github.com/mitchellh/reflectwalk/go.mod create mode 100644 vendor/github.com/oklog/run/.gitignore create mode 100644 vendor/github.com/oklog/run/.travis.yml delete mode 100644 vendor/github.com/patrickmn/go-cache/CONTRIBUTORS delete mode 100644 vendor/github.com/patrickmn/go-cache/LICENSE delete mode 100644 vendor/github.com/patrickmn/go-cache/README.md delete mode 100644 vendor/github.com/patrickmn/go-cache/cache.go delete mode 100644 vendor/github.com/patrickmn/go-cache/sharded.go delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/stack.go create mode 100644 vendor/github.com/posener/complete/.gitignore create mode 100644 vendor/github.com/posener/complete/.travis.yml create mode 100644 vendor/github.com/posener/complete/cmd/install/fish.go mode change 100755 => 100644 vendor/github.com/posener/complete/test.sh create mode 100644 vendor/github.com/rainycape/unidecode/.gitignore delete mode 100644 vendor/github.com/rancher/go-rancher/Dockerfile.dapper delete mode 100644 vendor/github.com/rancher/go-rancher/LICENSE delete mode 100644 vendor/github.com/rancher/go-rancher/Makefile delete mode 100644 vendor/github.com/rancher/go-rancher/README.md delete mode 100644 vendor/github.com/rancher/go-rancher/main.go delete mode 100644 vendor/github.com/rancher/go-rancher/trash.conf delete mode 100644 vendor/github.com/ryanuber/columnize/LICENSE delete mode 100644 vendor/github.com/ryanuber/columnize/README.md delete mode 100644 vendor/github.com/ryanuber/columnize/columnize.go create mode 100644 vendor/github.com/ryanuber/go-glob/.travis.yml create mode 100644 vendor/github.com/ryanuber/go-glob/go.mod create mode 100644 vendor/github.com/ulikunitz/xz/.gitignore create mode 100644 vendor/github.com/ulikunitz/xz/example.go mode change 100755 => 100644 vendor/github.com/ulikunitz/xz/make-docs create mode 100644 vendor/go.opencensus.io/.gitignore create mode 100644 vendor/go.opencensus.io/.travis.yml create mode 100644 vendor/golang.org/x/crypto/AUTHORS create mode 100644 vendor/golang.org/x/crypto/CONTRIBUTORS create mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519.go create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s create mode 100644 vendor/golang.org/x/crypto/internal/chacha20/xor.go create mode 100644 vendor/golang.org/x/crypto/internal/subtle/aliasing.go create mode 100644 vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go create mode 100644 vendor/golang.org/x/crypto/poly1305/mac_noasm.go create mode 100644 vendor/golang.org/x/crypto/poly1305/poly1305.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_amd64.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_amd64.s create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_arm.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_arm.s create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_generic.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_noasm.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_s390x.go create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_s390x.s create mode 100644 vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s delete mode 100644 vendor/golang.org/x/crypto/ssh/agent/client.go delete mode 100644 vendor/golang.org/x/crypto/ssh/agent/forward.go delete mode 100644 vendor/golang.org/x/crypto/ssh/agent/keyring.go delete mode 100644 vendor/golang.org/x/crypto/ssh/agent/server.go create mode 100644 vendor/golang.org/x/crypto/ssh/streamlocal.go create mode 100644 vendor/golang.org/x/net/AUTHORS create mode 100644 vendor/golang.org/x/net/CONTRIBUTORS create mode 100644 vendor/golang.org/x/net/html/atom/gen.go create mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/configure_transport.go delete mode 100644 vendor/golang.org/x/net/http2/go16.go delete mode 100644 vendor/golang.org/x/net/http2/go17.go delete mode 100644 vendor/golang.org/x/net/http2/go17_not18.go delete mode 100644 vendor/golang.org/x/net/http2/go18.go delete mode 100644 vendor/golang.org/x/net/http2/go19.go delete mode 100644 vendor/golang.org/x/net/http2/not_go16.go delete mode 100644 vendor/golang.org/x/net/http2/not_go17.go delete mode 100644 vendor/golang.org/x/net/http2/not_go18.go delete mode 100644 vendor/golang.org/x/net/http2/not_go19.go create mode 100644 vendor/golang.org/x/oauth2/.travis.yml create mode 100644 vendor/golang.org/x/oauth2/google/appengine_gen1.go create mode 100644 vendor/golang.org/x/oauth2/internal/client_appengine.go create mode 100644 vendor/golang.org/x/sys/AUTHORS create mode 100644 vendor/golang.org/x/sys/CONTRIBUTORS create mode 100644 vendor/golang.org/x/sys/cpu/byteorder.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_arm.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_gc_x86.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo.c create mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_mips64x.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_mipsx.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_other_arm64.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_s390x.s create mode 100644 vendor/golang.org/x/sys/cpu/cpu_wasm.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_x86.go create mode 100644 vendor/golang.org/x/sys/cpu/cpu_x86.s create mode 100644 vendor/golang.org/x/sys/unix/.gitignore rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_amd64.s => golang.org/x/sys/unix/asm_freebsd_arm64.s} (85%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm64.s => golang.org/x/sys/unix/asm_netbsd_arm64.s} (82%) create mode 100644 vendor/golang.org/x/sys/unix/fcntl_darwin.go mode change 100755 => 100644 vendor/golang.org/x/sys/unix/mkall.sh create mode 100644 vendor/golang.org/x/sys/unix/mkasm_darwin.go mode change 100755 => 100644 vendor/golang.org/x/sys/unix/mkerrors.sh create mode 100644 vendor/golang.org/x/sys/unix/mksyscall.go delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall.pl create mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.pl create mode 100644 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.pl create mode 100644 vendor/golang.org/x/sys/unix/mksyscall_solaris.go delete mode 100755 vendor/golang.org/x/sys/unix/mksyscall_solaris.pl mode change 100755 => 100644 vendor/golang.org/x/sys/unix/mksysctl_openbsd.pl create mode 100644 vendor/golang.org/x/sys/unix/mksysnum.go delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_darwin.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_dragonfly.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_freebsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl delete mode 100755 vendor/golang.org/x/sys/unix/mksysnum_openbsd.pl create mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_amd64.go => golang.org/x/sys/unix/syscall_freebsd_arm64.go} (63%) create mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go create mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go create mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_amd64.go => golang.org/x/sys/unix/zerrors_netbsd_arm64.go} (89%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_386.go => golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go} (74%) create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_386.s rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_amd64.go => golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go} (75%) create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.s rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_arm.go => golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go} (76%) create mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go => golang.org/x/sys/unix/zsyscall_freebsd_arm64.go} (78%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_386.go => golang.org/x/sys/unix/zsyscall_netbsd_arm64.go} (83%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go => golang.org/x/sys/unix/zsysnum_freebsd_arm64.go} (85%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_arm.go => golang.org/x/sys/unix/zsysnum_netbsd_arm64.go} (98%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_amd64.go => golang.org/x/sys/unix/ztypes_freebsd_arm64.go} (60%) rename vendor/{github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_amd64.go => golang.org/x/sys/unix/ztypes_netbsd_arm64.go} (83%) create mode 100644 vendor/golang.org/x/text/AUTHORS create mode 100644 vendor/golang.org/x/text/CONTRIBUTORS create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_ranges.go create mode 100644 vendor/golang.org/x/text/unicode/bidi/gen_trieval.go create mode 100644 vendor/golang.org/x/text/unicode/norm/maketables.go create mode 100644 vendor/golang.org/x/text/unicode/norm/triegen.go create mode 100644 vendor/golang.org/x/time/AUTHORS create mode 100644 vendor/golang.org/x/time/CONTRIBUTORS delete mode 100644 vendor/golang.org/x/time/rate/rate_go16.go delete mode 100644 vendor/golang.org/x/time/rate/rate_go17.go create mode 100644 vendor/google.golang.org/api/AUTHORS create mode 100644 vendor/google.golang.org/api/CONTRIBUTORS delete mode 100644 vendor/google.golang.org/api/compute/v1/compute-api.json delete mode 100644 vendor/google.golang.org/api/compute/v1/compute-gen.go delete mode 100644 vendor/google.golang.org/api/iam/v1/iam-api.json delete mode 100644 vendor/google.golang.org/api/iam/v1/iam-gen.go create mode 100644 vendor/google.golang.org/api/transport/http/dial_appengine.go create mode 100644 vendor/google.golang.org/appengine/.travis.yml create mode 100644 vendor/google.golang.org/appengine/CONTRIBUTING.md rename vendor/{gopkg.in/square/go-jose.v2 => google.golang.org/appengine}/LICENSE (100%) create mode 100644 vendor/google.golang.org/appengine/README.md create mode 100644 vendor/google.golang.org/appengine/appengine.go create mode 100644 vendor/google.golang.org/appengine/appengine_vm.go create mode 100644 vendor/google.golang.org/appengine/errors.go create mode 100644 vendor/google.golang.org/appengine/go.mod create mode 100644 vendor/google.golang.org/appengine/go.sum create mode 100644 vendor/google.golang.org/appengine/identity.go create mode 100644 vendor/google.golang.org/appengine/internal/api.go create mode 100644 vendor/google.golang.org/appengine/internal/api_classic.go create mode 100644 vendor/google.golang.org/appengine/internal/api_common.go create mode 100644 vendor/google.golang.org/appengine/internal/app_id.go create mode 100644 vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/app_identity/app_identity_service.proto create mode 100644 vendor/google.golang.org/appengine/internal/base/api_base.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/base/api_base.proto create mode 100644 vendor/google.golang.org/appengine/internal/datastore/datastore_v3.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/datastore/datastore_v3.proto create mode 100644 vendor/google.golang.org/appengine/internal/identity.go create mode 100644 vendor/google.golang.org/appengine/internal/identity_classic.go create mode 100644 vendor/google.golang.org/appengine/internal/identity_flex.go create mode 100644 vendor/google.golang.org/appengine/internal/identity_vm.go create mode 100644 vendor/google.golang.org/appengine/internal/internal.go create mode 100644 vendor/google.golang.org/appengine/internal/log/log_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/log/log_service.proto create mode 100644 vendor/google.golang.org/appengine/internal/main.go create mode 100644 vendor/google.golang.org/appengine/internal/main_common.go create mode 100644 vendor/google.golang.org/appengine/internal/main_vm.go create mode 100644 vendor/google.golang.org/appengine/internal/metadata.go create mode 100644 vendor/google.golang.org/appengine/internal/modules/modules_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/modules/modules_service.proto create mode 100644 vendor/google.golang.org/appengine/internal/net.go create mode 100644 vendor/google.golang.org/appengine/internal/regen.sh create mode 100644 vendor/google.golang.org/appengine/internal/remote_api/remote_api.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/remote_api/remote_api.proto create mode 100644 vendor/google.golang.org/appengine/internal/transaction.go create mode 100644 vendor/google.golang.org/appengine/internal/urlfetch/urlfetch_service.pb.go create mode 100644 vendor/google.golang.org/appengine/internal/urlfetch/urlfetch_service.proto create mode 100644 vendor/google.golang.org/appengine/namespace.go create mode 100644 vendor/google.golang.org/appengine/timeout.go create mode 100644 vendor/google.golang.org/appengine/travis_install.sh create mode 100644 vendor/google.golang.org/appengine/travis_test.sh create mode 100644 vendor/google.golang.org/appengine/urlfetch/urlfetch.go create mode 100644 vendor/google.golang.org/grpc/.travis.yml mode change 100755 => 100644 vendor/google.golang.org/grpc/codegen.sh rename vendor/{gopkg.in/square/go-jose.v2/jwt/doc.go => google.golang.org/grpc/credentials/internal/syscallconn_appengine.go} (72%) mode change 100755 => 100644 vendor/google.golang.org/grpc/health/regenerate.sh mode change 100755 => 100644 vendor/google.golang.org/grpc/install_gae.sh mode change 100755 => 100644 vendor/google.golang.org/grpc/internal/binarylog/regenerate.sh mode change 100755 => 100644 vendor/google.golang.org/grpc/vet.sh delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/builder.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/claims.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/errors.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/jwt.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/validation.go delete mode 100644 vendor/k8s.io/api/LICENSE delete mode 100644 vendor/k8s.io/api/authentication/v1/doc.go delete mode 100644 vendor/k8s.io/api/authentication/v1/generated.pb.go delete mode 100644 vendor/k8s.io/api/authentication/v1/generated.proto delete mode 100644 vendor/k8s.io/api/authentication/v1/register.go delete mode 100644 vendor/k8s.io/api/authentication/v1/types.go delete mode 100644 vendor/k8s.io/api/authentication/v1/types_swagger_doc_generated.go delete mode 100644 vendor/k8s.io/api/authentication/v1/zz_generated.deepcopy.go delete mode 100644 vendor/k8s.io/apimachinery/LICENSE delete mode 100755 vendor/k8s.io/apimachinery/pkg/api/errors/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/doc.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/errors.go delete mode 100755 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/OWNERS delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/doc.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/meta.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_proto.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/register.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_proto.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_swagger_doc_generated.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/watch.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.deepcopy.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/zz_generated.defaults.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/codec.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/codec_check.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/conversion.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/converter.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/doc.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/embedded.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/error.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/extension.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/generated.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/helper.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/interfaces.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/register.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.pb.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/generated.proto delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/interfaces.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/scheme.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/scheme_builder.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/types.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/types_proto.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/zz_generated.deepcopy.go create mode 100644 vendor/modules.txt diff --git a/go.mod b/go.mod index d7144f1dd..0a2e08c34 100644 --- a/go.mod +++ b/go.mod @@ -3,80 +3,36 @@ module github.com/terraform-providers/terraform-provider-vault go 1.12 require ( - cloud.google.com/go v0.36.0 - github.com/agext/levenshtein v1.2.2 - github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427 - github.com/apparentlymart/go-rundeck-api v0.0.0-20160826143032-f6af74d34d1e - github.com/apparentlymart/go-textseg v1.0.0 - github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc + cloud.google.com/go v0.37.4 // indirect + github.com/agext/levenshtein v1.2.2 // indirect github.com/aws/aws-sdk-go v1.16.36 - github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d - github.com/bgentry/speakeasy v0.1.0 - github.com/blang/semver v3.5.1+incompatible - github.com/coreos/etcd v3.3.12+incompatible // indirect - github.com/davecgh/go-spew v1.1.1 - github.com/fatih/structs v1.0.0 - github.com/fsouza/go-dockerclient v0.0.0-20160427172547-1d4f4ae73768 - github.com/go-ini/ini v1.23.1 - github.com/golang/protobuf v1.2.0 - github.com/google/go-cmp v0.2.0 - github.com/googleapis/gax-go v2.0.0+incompatible - github.com/googleapis/gax-go/v2 v2.0.4 // indirect - github.com/gorilla/websocket v1.4.0 // indirect + github.com/blang/semver v3.5.1+incompatible // indirect + github.com/golang/protobuf v1.3.1 // indirect github.com/gosimple/slug v1.4.1 - github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 // indirect - github.com/grpc-ecosystem/grpc-gateway v1.6.2 // indirect - github.com/hashicorp/errwrap v1.0.0 - github.com/hashicorp/go-cleanhttp v0.5.0 - github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6 - github.com/hashicorp/go-multierror v1.0.0 - github.com/hashicorp/go-plugin v1.0.0 - github.com/hashicorp/go-retryablehttp v0.5.1 - github.com/hashicorp/go-rootcerts v0.0.0-20160503143440-6bb64b370b90 - github.com/hashicorp/go-safetemp v1.0.0 - github.com/hashicorp/go-uuid v1.0.0 - github.com/hashicorp/go-version v1.1.0 - github.com/hashicorp/golang-lru v0.5.1 - github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f - github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260 - github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 - github.com/hashicorp/logutils v0.0.0-20150609070431-0dc08b1671f3 + github.com/hashicorp/go-cleanhttp v0.5.1 + github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6 // indirect + github.com/hashicorp/go-hclog v0.8.0 // indirect + github.com/hashicorp/go-plugin v1.0.0 // indirect + github.com/hashicorp/go-uuid v1.0.1 // indirect + github.com/hashicorp/golang-lru v0.5.1 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260 // indirect github.com/hashicorp/terraform v0.0.0-20190329073242-44702fa6c163 github.com/hashicorp/vault v0.11.1 - github.com/hashicorp/vault-plugin-auth-jwt v0.0.0-20190128234440-a608a5ad1c24 - github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb - github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af - github.com/mattn/go-isatty v0.0.4 - github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5 - github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3 + github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d // indirect + github.com/mitchellh/cli v1.0.0 // indirect + github.com/mitchellh/copystructure v1.0.0 // indirect github.com/mitchellh/go-homedir v1.0.0 - github.com/mitchellh/go-wordwrap v1.0.0 - github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5 - github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49 - github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc - github.com/posener/complete v0.0.0-20171219111128-6bee943216c8 - github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be - github.com/rancher/go-rancher v0.0.0-20170407040943-ec24b7f12fca + github.com/mitchellh/go-wordwrap v1.0.0 // indirect + github.com/mitchellh/mapstructure v1.1.2 // indirect + github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be // indirect github.com/ryanuber/go-glob v1.0.0 // indirect - github.com/spf13/cobra v0.0.3 // indirect - github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect - github.com/ulikunitz/xz v0.5.6 - github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329 - go.opencensus.io v0.19.2 - go.uber.org/atomic v1.3.2 // indirect - go.uber.org/multierr v1.1.0 // indirect - go.uber.org/zap v1.10.0 // indirect - golang.org/x/build v0.0.0-20190314133821-5284462c4bec // indirect - golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 - golang.org/x/exp v0.0.0-20190221220918-438050ddec5e // indirect - golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect - golang.org/x/net v0.0.0-20190328230028-74de082e2cca - golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914 - golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a - golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 - golang.org/x/time v0.0.0-20181108054448-85acf8d2951c - google.golang.org/api v0.3.0 - google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d - google.golang.org/grpc v1.19.0 - k8s.io/kubernetes v1.6.1 + github.com/ulikunitz/xz v0.5.6 // indirect + github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329 // indirect + golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c // indirect + golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 // indirect + golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914 // indirect + golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e // indirect + golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db // indirect + google.golang.org/grpc v1.19.1 // indirect ) diff --git a/go.sum b/go.sum index c66e546b6..0d95aec5e 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +1,16 @@ -cloud.google.com/go v0.0.0-20190329192448-408b387e95d4/go.mod h1:CazBHdZ5f7eCE/SsNYXk9Ai3Wa8DlFTWAh20R+L0V0k= cloud.google.com/go v0.15.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.36.0 h1:+aCSj7tOo2LODWVEuZDZeGCckdt6MlSF+X/rB3wUiS8= cloud.google.com/go v0.36.0/go.mod h1:RUoy9p/M4ge0HzT8L+SDZ8jg+Q6fth0CiBuhFJpSV40= +cloud.google.com/go v0.37.4 h1:glPeL3BQJsbF6aIIYfZizMwc5LTYz250bDMjttbBGAU= +cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw= dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= dmitri.shuralyov.com/service/change v0.0.0-20181023043359-a85b471d5412/go.mod h1:a1inKt/atXimZ4Mv927x+r7UpyzRUf4emIoiiSC2TN4= dmitri.shuralyov.com/state v0.0.0-20180228185332-28bcc343414c/go.mod h1:0PRwlb0D6DFvNNtx+9ybjezNCa8XF0xaYcETyp6rHWU= git.apache.org/thrift.git v0.0.0-20180902110319-2566ecd5d999/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= -git.apache.org/thrift.git v0.12.0/go.mod h1:fPE2ZNJGynbRyZ4dJvy6G277gSllfV2HJqblrnkyeyg= github.com/Azure/azure-sdk-for-go v10.3.0-beta+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-autorest v9.10.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-ntlmssp v0.0.0-20170803034930-c92175d54006/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= @@ -23,6 +23,7 @@ github.com/abdullin/seq v0.0.0-20160510034733-d5467c17e7af/go.mod h1:5Jv4cbFiHJM github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/agl/ed25519 v0.0.0-20150830182803-278e1ec8e8a6 h1:LoeFxdq5zUCBQPhbQKE6zvoGwHMxCBlqwbH9+9kHoHA= github.com/agl/ed25519 v0.0.0-20150830182803-278e1ec8e8a6/go.mod h1:WPjqKcmVOxf0XSf3YxCJs6N6AOSrOx3obionmG7T0y0= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -30,20 +31,19 @@ github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYU github.com/antchfx/xpath v0.0.0-20170728053731-b5c552e1acbd/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNYhvtNk= github.com/antchfx/xquery v0.0.0-20170730121040-eb8c3c172607/go.mod h1:LzD22aAzDP8/dyiCKFp31He4m2GPjl0AFyzDtZzUu9M= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/apparentlymart/go-cidr v0.0.0-20170418151526-7e4b007599d4/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427 h1:2P/DTyNDU+7qJOB6E5KeIpdc3qcT9IYjyA8hZ9HGz50= github.com/apparentlymart/go-cidr v0.0.0-20170616213631-2bd8b58cf427/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= +github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3 h1:ZSTrOEhiM5J5RFxEaFvMZVEAM1KvT1YzbEOwB2EAGjA= github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= -github.com/apparentlymart/go-rundeck-api v0.0.0-20160826143032-f6af74d34d1e/go.mod h1:U6OjNHcY3edY04ILn+KNrWZm3j15cPzW7PyjtIQOh1Y= github.com/apparentlymart/go-textseg v0.0.0-20170531203952-b836f5c4d331/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20160115234725-4239b77079c7/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc h1:/WQ8Tr5zbclKWAtvafIcAk/njNpW3gtd22TLLouv+6Q= -github.com/armon/go-radix v0.0.0-20170727155443-1fca145dffbc/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/aws/aws-sdk-go v1.8.34/go.mod h1:ZRmQr0FajVIyZ4ZzBYKG5P3ZqPz9IHG41ZoMu1ADI3k= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= github.com/aws/aws-sdk-go v1.16.36 h1:POeH34ZME++pr7GBGh+ZO6Y5kOwSMQpqp5BGUgooJ6k= github.com/aws/aws-sdk-go v1.16.36/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= @@ -67,8 +67,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/coreos/bbolt v1.3.1-coreos.1 h1:crb2YOmpHMVsND8Ug24uvqgL8rUmJlQc+UVfUlMHalc= github.com/coreos/bbolt v1.3.1-coreos.1/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.2.0-rc.1.0.20170908195435-80aa810309d4+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/etcd v3.3.12+incompatible h1:pAWNwdf7QiT1zfaWyqCtNZQWCLByQyA3JrSQyuYAqnQ= -github.com/coreos/etcd v3.3.12+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-semver v0.2.0 h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20161114122254-48702e0da86b/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= @@ -88,52 +86,51 @@ github.com/dylanmei/winrmtest v0.0.0-20170819153634-c2fbb09e6c08/go.mod h1:VBVDF github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= -github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/structs v1.0.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsouza/go-dockerclient v0.0.0-20160427172547-1d4f4ae73768/go.mod h1:KpcjM623fQYE9MZiTGzKhjfxXAV9wbyX2C1cyRHfhl0= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-ini/ini v1.23.1/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-test/deep v1.0.1 h1:UQhStjbkDClarlmv0am7OXXO4/GaPdCGiUiMTvi28sg= github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= -github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/gogo/protobuf v0.0.0-20170307180453-100ba4e88506/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.0 h1:xU6/SpYbvkNYiptHJYEDRseDLvYE7wSqhYYNy0QSUzI= github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903 h1:LbsanbbD6LieFkXbj9YNNBupiGHJgFeLpO0j0Fza1h8= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/protobuf v0.0.0-20190318194812-d3c38a4eb497/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.0.0-20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.1.1-0.20171002171727-8ebdfab36c66/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY= github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= +github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/googleapis/gax-go v0.0.0-20161107002406-da06d194a00e/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= -github.com/googleapis/gax-go v1.0.2/go.mod h1:v2eZhQtr8ifqA4cZIskVgQZ1FwEN4gDW0C++kU5/H7Y= github.com/googleapis/gax-go v2.0.0+incompatible h1:j0GKcs05QVmm7yesiZq2+9cxHkNK9YM6zKx4D2qucQU= github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY= -github.com/googleapis/gax-go/v2 v2.0.2/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg= github.com/googleapis/gax-go/v2 v2.0.4 h1:hU4mGcQI4DaAYW+IbTun+2qEZVFxK0ySjQLTbS0VQKc= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= @@ -143,46 +140,41 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORR github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= -github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gosimple/slug v1.4.1 h1:h29PRcKc8dPN//lJ9Ib6EKP50kG5AmpJ0yRjn7ksY/8= github.com/gosimple/slug v1.4.1/go.mod h1:ER78kgg1Mv0NQGlXiDe57DpCyfbNywXXZ9mIorhxAf0= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:Iju5GlWwrvL6UBg4zJJt3btmonfrMlCDdsejg4CZE7c= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v0.0.0-20160910222444-6b7015e65d36 h1:cwTrrTEhz13khQS3/UZMLFWwiqlcsdp/2sxFmSjAWeQ= github.com/grpc-ecosystem/go-grpc-prometheus v0.0.0-20160910222444-6b7015e65d36/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.2.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= -github.com/grpc-ecosystem/grpc-gateway v1.6.2 h1:8KyC64BiO8ndiGHY5DlFWWdangUPC9QHPakFRre/Ud0= -github.com/grpc-ecosystem/grpc-gateway v1.6.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= github.com/hashicorp/atlas-go v0.0.0-20161107204910-1792bd8de119/go.mod h1:ckHDuH0pxfnmXZkq1niVSguIIV0pA65gifQv3so9llw= github.com/hashicorp/aws-sdk-go-base v0.3.0/go.mod h1:ZIWACGGi0N7a4DZbf15yuE1JQORmWLtBcVM6F5SXNFU= github.com/hashicorp/consul v0.0.0-20171026175957-610f3c86a089/go.mod h1:mFrjN1mfidgJfYP1xrJCF+AfRhr6Eaqhb2+sfyn/OOI= -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-checkpoint v0.0.0-20171009173528-1545e56e46de/go.mod h1:xIwEieBHERyEvaeKF/TcHh1Hu+lxPM+n2vT1+g9I4m4= -github.com/hashicorp/go-cleanhttp v0.0.0-20170211013415-3573b8b52aa7/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-getter v0.0.0-20180327010114-90bb99a48d86/go.mod h1:6rdJFnhkXnzGOJbvkrdv4t9nLwKcVA+tmbQeUlkIzrU= github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6 h1:aOgIQP/0Bk+gfS77dy01FVVVSN712E7amhqOFVKGfJM= github.com/hashicorp/go-getter v0.0.0-20190326194518-69dec094fde6/go.mod h1:/O1k/AizTN0QmfEKknCYGvICeyKUDqCYA8vvWtGWDeQ= github.com/hashicorp/go-hclog v0.0.0-20170716174523-b4e5765d1e5f/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd h1:rNuUHR+CvK1IS89MMtcF0EpcVMZtjKfPRp4MEmt/aTs= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= +github.com/hashicorp/go-hclog v0.8.0 h1:z3ollgGRg8RjfJH6UVBaG54R70GFd++QOkvnJH3VSBY= +github.com/hashicorp/go-hclog v0.8.0/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= +github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v0.0.0-20150916205742-d30f09973e19/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-plugin v0.0.0-20180125190438-e53f54cbf51e/go.mod h1:JSqWYsict+jzcj0+xElxyrBQRPNoiWQuddnxArJ7XHQ= github.com/hashicorp/go-plugin v1.0.0 h1:/gQ1sNR8/LHpoxKRQq4PmLBuacfZb4tC93e9B30o/7c= github.com/hashicorp/go-plugin v1.0.0/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= -github.com/hashicorp/go-retryablehttp v0.0.0-20180718195005-e651d75abec6/go.mod h1:fXcdFsQoipQa7mwORhKad5jmDCeSy/RCGzWA08PO0lM= github.com/hashicorp/go-retryablehttp v0.5.1 h1:Vsx5XKPqPs3M6sM4U4GWyUqFS8aBiL9U5gkgvpkg4SE= github.com/hashicorp/go-retryablehttp v0.5.1/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v0.0.0-20160503143440-6bb64b370b90 h1:VBj0QYQ0u2MCJzBfeYXGexnAl17GsH1yidnoxCqqD9E= @@ -194,9 +186,10 @@ github.com/hashicorp/go-slug v0.2.0/go.mod h1:+zDycQOzGqOqMW7Kn2fp9vz/NtqpMLQlgb github.com/hashicorp/go-sockaddr v1.0.0 h1:GeH6tui99pF4NJgfnhp+L6+FfobzVW3Ah46sLo0ICXs= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-tfe v0.3.11/go.mod h1:LHLchj07PCYgQqcyE5Sz+g4zrMNW+nALKbiSNTZedEs= -github.com/hashicorp/go-uuid v0.0.0-20160120003506-36289988d83c/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.0.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= @@ -205,10 +198,11 @@ github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/hcl2 v0.0.0-20180308163058-5f8ed954abd8/go.mod h1:xp1eMAxqhQKBxz+yQUTsig9bBMRRWRWw+rK3FJmHf/A= github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260 h1:C3vhYEXk8ihs+Xvq093axRyYhfLERrZ6Uv5tfRw9yvw= github.com/hashicorp/hcl2 v0.0.0-20190327223817-3fb4ed0d9260/go.mod h1:HtEzazM5AZ9fviNEof8QZB4T1Vz9UhHrGhnMPzl//Ek= -github.com/hashicorp/hil v0.0.0-20170512213305-fac2259da677/go.mod h1:KHvg/R2/dPtaePb16oW4qIyzkMxXOL38xjRN64adsts= github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250 h1:fooK5IvDL/KIsi4LxF/JH68nVdrBSiGNPhS2JAQjtjo= github.com/hashicorp/hil v0.0.0-20170627220502-fa9f258a9250/go.mod h1:KHvg/R2/dPtaePb16oW4qIyzkMxXOL38xjRN64adsts= github.com/hashicorp/logutils v0.0.0-20150609070431-0dc08b1671f3 h1:oD64EFjELI9RY9yoWlfua58r+etdnoIC871z+rr6lkA= @@ -220,15 +214,15 @@ github.com/hashicorp/terraform v0.0.0-20190329073242-44702fa6c163/go.mod h1:4nGn github.com/hashicorp/vault v0.0.0-20161029210149-9a60bf2a50e4/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= github.com/hashicorp/vault v0.11.1 h1:/t8pGnk5cpzRCq13nj6QlEXdu6meBum9NFlGn5Ma2QE= github.com/hashicorp/vault v0.11.1/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= -github.com/hashicorp/vault-plugin-auth-jwt v0.0.0-20190128234440-a608a5ad1c24/go.mod h1:j6Xmkj3dzuC63mivquwVVTlxjwDndwNxi4cJUku40J8= github.com/hashicorp/yamux v0.0.0-20160720233140-d1caa6c97c9f/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= +github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= @@ -238,23 +232,28 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kardianos/osext v0.0.0-20160811001526-c2c54e542fb7/go.mod h1:1NbS8ALrpOvjt0rHPNLyCIeMtbizbir8U//inJ+zuB8= +github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba h1:NARVGAAgEXvoMeNPHhPFt1SBt1VMznA3Gnz9d0qj+co= github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba/go.mod h1:ghbZscTyKdM07+Fw3KSi0hcJm+AlEUWj8QLlPtijN/M= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/lusis/go-artifactory v0.0.0-20160115162124-7e4ce345df82/go.mod h1:y54tfGmO3NKssKveTEFFzH8C/akrSOy/iW9qEAUDV84= -github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/masterzen/azure-sdk-for-go v0.0.0-20161014135628-ee4f0065d00c/go.mod h1:mf8fjOu33zCqxUjuiU3I8S1lJMyEAlH+0F2+M5xl3hE= github.com/masterzen/simplexml v0.0.0-20160608183007-4572e39b1ab9/go.mod h1:kCEbxUJlNDEBNbdQMkPSp6yaKcRXVI6f4ddk8Riv4bc= github.com/masterzen/winrm v0.0.0-20180224160350-7e40f93ae939/go.mod h1:CfZSN7zwz5gJiFhZJz49Uzk7mEBHIceWmbFmYx7Hf7E= github.com/mattn/go-colorable v0.0.0-20160220075935-9cbef7c35391/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.0-20161123143637-30a891c33c7c/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= @@ -263,13 +262,15 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0j github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/mitchellh/cli v0.0.0-20170908181043-65fcae5817c8/go.mod h1:oGumspjLm2kTyiT1QMGpFqRlmxnKHfCvhZEVnx+5UeE= github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5 h1:OYr3N2fY3e3kP/x/d81CJXlcZrIV2hH8gPnuRLpiME4= github.com/mitchellh/cli v0.0.0-20171129193617-33edc47170b5/go.mod h1:oGumspjLm2kTyiT1QMGpFqRlmxnKHfCvhZEVnx+5UeE= +github.com/mitchellh/cli v1.0.0 h1:iGBIsUe3+HZ/AD/Vd7DErOt5sU9fa8Uj7A2s1aggv1Y= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/colorstring v0.0.0-20150917214807-8631ce90f286/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= -github.com/mitchellh/copystructure v0.0.0-20161013195342-5af94aef99f5/go.mod h1:eOsF2yLPlBBJPvD+nhl5QMTBSOBbOph6N7j/IDUw7PY= github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3 h1:dECZqiJYhKdj9QlLpiQaRDXHDXRTdiyZI3owdDGhlYY= github.com/mitchellh/copystructure v0.0.0-20170525013902-d23ffcb85de3/go.mod h1:eOsF2yLPlBBJPvD+nhl5QMTBSOBbOph6N7j/IDUw7PY= +github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/go-homedir v0.0.0-20161203194507-b8bc1bf76747/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -285,11 +286,14 @@ github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5 h1:h+4fp6y github.com/mitchellh/hashstructure v0.0.0-20160209213820-6b17d669fac5/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49 h1:kaWdlw4YogwkDl8CG+/VxhXkrL9uz3n1D9QBC2pEGLE= github.com/mitchellh/mapstructure v0.0.0-20170307201123-53818660ed49/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/panicwrap v0.0.0-20161208170302-ba9e1a65e0f7/go.mod h1:QuAqW7/z+iv6aWFJdrA8kCbsF0OOJVKCICqTcYBexuY= github.com/mitchellh/prefixedio v0.0.0-20151214002211-6e6954073784/go.mod h1:kB1naBgV9ORnkiTVeyJOI1DavaJkG4oNIq0Af6ZVKUo= -github.com/mitchellh/reflectwalk v0.0.0-20161003174516-92573fe8d000/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc h1:gqYjvctjtX4GHzgfutJxZpvZ7XhGwQLGR5BASwhpO2o= github.com/mitchellh/reflectwalk v0.0.0-20170726202117-63d60e9d0dbc/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= @@ -300,17 +304,19 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= -github.com/openzipkin/zipkin-go v0.1.3/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/packer-community/winrmcp v0.0.0-20180102160824-81144009af58/go.mod h1:f6Izs6JvFTdnRbziASagjZ2vmf55NSIkC/weStxCHqk= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c h1:Lgl0gzECD8GnQ5QCWA8o6BtfL6mDH5rQgM4/fX3avOs= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.0.0-20170505043639-c605e284fe17/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v0.0.0-20171104095702-dc2bc5a81acc/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/posener/complete v0.0.0-20171219111128-6bee943216c8 h1:lcb1zvdlaZyEbl2OXifN3uOYYyIvllofUbmp9bwbL+0= github.com/posener/complete v0.0.0-20171219111128-6bee943216c8/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829 h1:D+CiwcpGTW6pL6bv6KI3KbyEyCKyS+1JWS2h8PNDnGA= @@ -330,7 +336,6 @@ github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1 h1:/K3IL0Z1quvmJ github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ= github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q= -github.com/rancher/go-rancher v0.0.0-20170407040943-ec24b7f12fca/go.mod h1:7oQvGNiJsGvrUgB+7AH8bmdzuR0uhULfwKb43Ht0hUk= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/ryanuber/columnize v0.0.0-20161220214920-0fbbb3f0e3fb/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= @@ -339,6 +344,7 @@ github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIH github.com/satori/go.uuid v0.0.0-20160927100844-b061729afc07/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/satori/uuid v0.0.0-20160927100844-b061729afc07/go.mod h1:B8HLsPLik/YNn6KKWVMDJ8nzCL8RP5WyfsnmvnAEwIU= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY= github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM= @@ -371,19 +377,16 @@ github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4k github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE= github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA= github.com/spf13/afero v1.0.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/pflag v1.0.2 h1:Fy0orTDgHdbnzHcsOgfCN4LtHf0ec3wwtiwJqwvf3Gc= github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/svanharmelen/jsonapi v0.0.0-20180618144545-0c0828c3f16d/go.mod h1:BSTlc8jOjh0niykqEGVXOLXdi9o0r0kR8tCYiMvjFgw= github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= github.com/terraform-providers/terraform-provider-openstack v1.15.0/go.mod h1:2aQ6n/BtChAl1y2S60vebhyJyZXBsuAI5G4+lHrT1Ew= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 h1:LnC5Kc/wtumK+WB441p7ynQJzVuNRJiqddSIE3IlSEQ= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v0.0.0-20170107133203-ded73eae5db7 h1:BPPUhSq7uU6E9lFzyb81vjwVOhiWwMXp0EpKL75NX+8= github.com/ugorji/go v0.0.0-20170107133203-ded73eae5db7/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= github.com/ulikunitz/xz v0.5.4/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= @@ -399,35 +402,24 @@ github.com/zclconf/go-cty v0.0.0-20180302160414-49fa5e03c418/go.mod h1:LnDKxj8gN github.com/zclconf/go-cty v0.0.0-20190124225737-a385d646c1e9/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329 h1:ne520NlvoncW5zfBGkmP4EJhyd6ruSaSyhzobv0Vz9w= github.com/zclconf/go-cty v0.0.0-20190320224746-fd76348b9329/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -go.opencensus.io v0.0.0-20190327170659-41e54b832491/go.mod h1:NO/8qkisMZLZ1FCsKNqtJPwc8/TaclWyY0B6wcYNg9M= go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA= -go.opencensus.io v0.19.1/go.mod h1:gug0GbSHa8Pafr0d2urOSgoXHZ6x/RUlaiT0d9pqb4A= -go.opencensus.io v0.19.2 h1:ZZpq6xI6kv/LuE/5s5UQvBU5vMjvRnPb8PvJrIntAnc= -go.opencensus.io v0.19.2/go.mod h1:NO/8qkisMZLZ1FCsKNqtJPwc8/TaclWyY0B6wcYNg9M= -go.uber.org/atomic v1.3.2 h1:2Oa65PReHzfn29GpvgsYwloV9AVFHPDk8tYxt2c2tr4= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.opencensus.io v0.20.1 h1:pMEjRZ1M4ebWGikflH7nQpV6+Zr88KBMA2XJD3sbijw= +go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= -golang.org/x/build v0.0.0-20190314133821-5284462c4bec/go.mod h1:atTaCNAy0f16Ah5aV1gMSwgiKVHwu/JncqDpuRr7lS4= -golang.org/x/crypto v0.0.0-20170808112155-b176d7def5d7/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180211211603-9de5f2eaf759/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180816225734-aabede6cba87/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181030102418-4d3f4d9ffa16/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190221220918-438050ddec5e/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -440,8 +432,8 @@ golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190328230028-74de082e2cca h1:hyA6yiAgbUwuWqtscNvWAI7U1CtlaD1KilQ6iudt1aI= -golang.org/x/net v0.0.0-20190328230028-74de082e2cca/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/oauth2 v0.0.0-20170928010508-bb50c06baba3/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -453,65 +445,65 @@ golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5Tlb golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026144532-2772b66316d2/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181029174526-d69651ed3497/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181218192612-074acd46bca6/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.0.0-20180911161511-905a57155faa/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e h1:nFYrTHrdrAOpShe27kaFHjsqYSEQ0KWqdWLu3xuZJts= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db h1:6/JqlYfC1CCaLnGceQTI+sDGhC9UBSPAsBqI0Gun6kU= +golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c h1:fqgJT0MGcGpPgpWU7VRdRjuArfcOvC4AoJmILihzhDg= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181219222714-6e267b5cc78e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= google.golang.org/api v0.0.0-20171005000305-7a7376eff6a5/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.0.0-20181220000619-583d854617af/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.0.0-20190329211119-c30064f755a0/go.mod h1:IuvZyQh8jgscv8qWfQ4ABd8m7hEudgBFM/EdhA3BnXw= google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y= -google.golang.org/api v0.2.0/go.mod h1:IfRCZScioGtypHNTlz3gFk67J8uePVW7uDTBzXuIkhU= -google.golang.org/api v0.3.0 h1:UIJY20OEo3+tK5MBlcdx37kmdH6EnRjGkW78mc6+EeA= -google.golang.org/api v0.3.0/go.mod h1:IuvZyQh8jgscv8qWfQ4ABd8m7hEudgBFM/EdhA3BnXw= +google.golang.org/api v0.3.1 h1:oJra/lMfmtm13/rgY/8i3MzjFWYXvQIAKjQ3HqofMk8= +google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/appengine v0.0.0-20150527042145-b667a5000b08/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20171002232614-f676e0f3ac63/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= -google.golang.org/genproto v0.0.0-20181219182458-5a97ab628bfb/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg= google.golang.org/genproto v0.0.0-20190201180003-4b09977fb922/go.mod h1:L3J43x8/uS+qIUoksaLKe6OS3nUKxOKuIFz1sl2/jx4= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d h1:XB2jc5XQ9uhizGTS2vWcN01bc4dI6z3C4KY5MQm8SS8= -google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107 h1:xtNn7qFlagY2mQNFHMSRPjT2RkOV4OXM7P5TVy9xATo= +google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/grpc v0.0.0-20170809211603-7657092a1303/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v0.0.0-20190327231928-f1437f7cc5fa/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.19.1 h1:TrBcJ1yqAl1G++wO39nD/qtgpsW9/1+QGrluyMGEYgM= +google.golang.org/grpc v1.19.1/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -526,10 +518,8 @@ gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20180920025451-e3ad64cb4ed3/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= -k8s.io/kubernetes v1.6.1/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/vendor/cloud.google.com/go/AUTHORS b/vendor/cloud.google.com/go/AUTHORS new file mode 100644 index 000000000..c364af1da --- /dev/null +++ b/vendor/cloud.google.com/go/AUTHORS @@ -0,0 +1,15 @@ +# This is the official list of cloud authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. + +Filippo Valsorda +Google Inc. +Ingo Oeser +Palm Stone Games, Inc. +Paweł Knap +Péter Szilágyi +Tyler Treat diff --git a/vendor/cloud.google.com/go/CONTRIBUTORS b/vendor/cloud.google.com/go/CONTRIBUTORS new file mode 100644 index 000000000..3b3cbed98 --- /dev/null +++ b/vendor/cloud.google.com/go/CONTRIBUTORS @@ -0,0 +1,40 @@ +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# Names should be added to this file as: +# Name + +# Keep the list alphabetically sorted. + +Alexis Hunt +Andreas Litt +Andrew Gerrand +Brad Fitzpatrick +Burcu Dogan +Dave Day +David Sansome +David Symonds +Filippo Valsorda +Glenn Lewis +Ingo Oeser +James Hall +Johan Euphrosine +Jonathan Amsterdam +Kunpei Sakai +Luna Duclos +Magnus Hiie +Mario Castro +Michael McGreevy +Omar Jarjur +Paweł Knap +Péter Szilágyi +Sarah Adams +Thanatat Tamtan +Toby Burress +Tuo Shan +Tyler Treat diff --git a/vendor/cloud.google.com/go/internal/version/update_version.sh b/vendor/cloud.google.com/go/internal/version/update_version.sh old mode 100755 new mode 100644 diff --git a/vendor/cloud.google.com/go/storage/bucket.go b/vendor/cloud.google.com/go/storage/bucket.go index 25359da1f..bbfc59b21 100644 --- a/vendor/cloud.google.com/go/storage/bucket.go +++ b/vendor/cloud.google.com/go/storage/bucket.go @@ -313,6 +313,10 @@ type BucketAttrs struct { // The website configuration. Website *BucketWebsite + + // Etag is the HTTP/1.1 Entity tag for the bucket. + // This field is read-only. + Etag string } // BucketPolicyOnly configures access checks to use only bucket-level IAM @@ -501,6 +505,7 @@ func newBucket(b *raw.Bucket) (*BucketAttrs, error) { Logging: toBucketLogging(b.Logging), Website: toBucketWebsite(b.Website), BucketPolicyOnly: toBucketPolicyOnly(b.IamConfiguration), + Etag: b.Etag, }, nil } diff --git a/vendor/cloud.google.com/go/storage/storage.go b/vendor/cloud.google.com/go/storage/storage.go index 70aa7a6df..c29f436a6 100644 --- a/vendor/cloud.google.com/go/storage/storage.go +++ b/vendor/cloud.google.com/go/storage/storage.go @@ -777,6 +777,10 @@ type ObjectAttrs struct { // ObjectIterator.Next. When set, no other fields in ObjectAttrs will be // populated. Prefix string + + // Etag is the HTTP/1.1 Entity tag for the object. + // This field is read-only. + Etag string } // convertTime converts a time in RFC3339 format to time.Time. @@ -829,6 +833,7 @@ func newObject(o *raw.Object) *ObjectAttrs { Created: convertTime(o.TimeCreated), Deleted: convertTime(o.TimeDeleted), Updated: convertTime(o.Updated), + Etag: o.Etag, } } diff --git a/vendor/github.com/SermoDigital/jose/LICENSE b/vendor/github.com/SermoDigital/jose/LICENSE deleted file mode 100644 index d2d35b66c..000000000 --- a/vendor/github.com/SermoDigital/jose/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Sermo Digital LLC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/SermoDigital/jose/crypto/doc.go b/vendor/github.com/SermoDigital/jose/crypto/doc.go deleted file mode 100644 index 16cf476ba..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package crypto implements "SigningMethods" and "EncryptionMethods"; -// that is, ways to sign and encrypt JWS and JWEs, respectively, as well -// as JWTs. -package crypto diff --git a/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go b/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go deleted file mode 100644 index 3ef12ba22..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/ecdsa.go +++ /dev/null @@ -1,117 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "encoding/asn1" - "encoding/json" - "errors" - "math/big" -) - -// ErrECDSAVerification is missing from crypto/ecdsa compared to crypto/rsa -var ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") - -// SigningMethodECDSA implements the ECDSA family of signing methods signing -// methods -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// ECPoint is a marshalling structure for the EC points R and S. -type ECPoint struct { - R *big.Int - S *big.Int -} - -// Specific instances of EC SigningMethods. -var ( - // SigningMethodES256 implements ES256. - SigningMethodES256 = &SigningMethodECDSA{ - Name: "ES256", - Hash: crypto.SHA256, - } - - // SigningMethodES384 implements ES384. - SigningMethodES384 = &SigningMethodECDSA{ - Name: "ES384", - Hash: crypto.SHA384, - } - - // SigningMethodES512 implements ES512. - SigningMethodES512 = &SigningMethodECDSA{ - Name: "ES512", - Hash: crypto.SHA512, - } -) - -// Alg returns the name of the SigningMethodECDSA instance. -func (m *SigningMethodECDSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *ecdsa.PublicKey. -func (m *SigningMethodECDSA) Verify(raw []byte, signature Signature, key interface{}) error { - - ecdsaKey, ok := key.(*ecdsa.PublicKey) - if !ok { - return ErrInvalidKey - } - - // Unmarshal asn1 ECPoint - var ecpoint ECPoint - if _, err := asn1.Unmarshal(signature, &ecpoint); err != nil { - return err - } - - // Verify the signature - if !ecdsa.Verify(ecdsaKey, m.sum(raw), ecpoint.R, ecpoint.S) { - return ErrECDSAVerification - } - return nil -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *ecdsa.PrivateKey. -func (m *SigningMethodECDSA) Sign(data []byte, key interface{}) (Signature, error) { - - ecdsaKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - - r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, m.sum(data)) - if err != nil { - return nil, err - } - - signature, err := asn1.Marshal(ECPoint{R: r, S: s}) - if err != nil { - return nil, err - } - return Signature(signature), nil -} - -func (m *SigningMethodECDSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodECDSA) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON is in case somebody decides to place SigningMethodECDSA -// inside the Header, presumably because they (wrongly) decided it was a good -// idea to use the SigningMethod itself instead of the SigningMethod's Alg -// method. In order to keep things sane, marshalling this will simply -// return the JSON-compatible representation of m.Alg(). -func (m *SigningMethodECDSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodECDSA)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go b/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go deleted file mode 100644 index 4bd75d2e5..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/ecdsa_utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package crypto - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// ECDSA parsing errors. -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// ParseECPrivateKeyFromPEM will parse a PEM encoded EC Private -// Key Structure. -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - return x509.ParseECPrivateKey(block.Bytes) -} - -// ParseECPublicKeyFromPEM will parse a PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - parsedKey = cert.PublicKey - } - - pkey, ok := parsedKey.(*ecdsa.PublicKey) - if !ok { - return nil, ErrNotECPublicKey - } - return pkey, nil -} diff --git a/vendor/github.com/SermoDigital/jose/crypto/errors.go b/vendor/github.com/SermoDigital/jose/crypto/errors.go deleted file mode 100644 index 34fbd25ff..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package crypto - -import "errors" - -var ( - // ErrInvalidKey means the key argument passed to SigningMethod.Verify - // was not the correct type. - ErrInvalidKey = errors.New("key is invalid") -) diff --git a/vendor/github.com/SermoDigital/jose/crypto/hmac.go b/vendor/github.com/SermoDigital/jose/crypto/hmac.go deleted file mode 100644 index 1cb7f6e09..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/hmac.go +++ /dev/null @@ -1,81 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/hmac" - "encoding/json" - "errors" -) - -// SigningMethodHMAC implements the HMAC-SHA family of SigningMethods. -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of HMAC-SHA SigningMethods. -var ( - // SigningMethodHS256 implements HS256. - SigningMethodHS256 = &SigningMethodHMAC{ - Name: "HS256", - Hash: crypto.SHA256, - } - - // SigningMethodHS384 implements HS384. - SigningMethodHS384 = &SigningMethodHMAC{ - Name: "HS384", - Hash: crypto.SHA384, - } - - // SigningMethodHS512 implements HS512. - SigningMethodHS512 = &SigningMethodHMAC{ - Name: "HS512", - Hash: crypto.SHA512, - } - - // ErrSignatureInvalid is returned when the provided signature is found - // to be invalid. - ErrSignatureInvalid = errors.New("signature is invalid") -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodHMAC) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be a []byte. -func (m *SigningMethodHMAC) Verify(raw []byte, signature Signature, key interface{}) error { - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(raw) - if hmac.Equal(signature, hasher.Sum(nil)) { - return nil - } - return ErrSignatureInvalid -} - -// Sign implements the Sign method from SigningMethod for this signing method. -// Key must be a []byte. -func (m *SigningMethodHMAC) Sign(data []byte, key interface{}) (Signature, error) { - keyBytes, ok := key.([]byte) - if !ok { - return nil, ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(data) - return Signature(hasher.Sum(nil)), nil -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodHMAC) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodHMAC) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodHMAC)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/none.go b/vendor/github.com/SermoDigital/jose/crypto/none.go deleted file mode 100644 index db3d139e9..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/none.go +++ /dev/null @@ -1,72 +0,0 @@ -package crypto - -import ( - "crypto" - "encoding/json" - "hash" - "io" -) - -func init() { - crypto.RegisterHash(crypto.Hash(0), h) -} - -// h is passed to crypto.RegisterHash. -func h() hash.Hash { - return &f{Writer: nil} -} - -type f struct{ io.Writer } - -// Sum helps implement the hash.Hash interface. -func (_ *f) Sum(b []byte) []byte { return nil } - -// Reset helps implement the hash.Hash interface. -func (_ *f) Reset() {} - -// Size helps implement the hash.Hash interface. -func (_ *f) Size() int { return -1 } - -// BlockSize helps implement the hash.Hash interface. -func (_ *f) BlockSize() int { return -1 } - -// Unsecured is the default "none" algorithm. -var Unsecured = &SigningMethodNone{ - Name: "none", - Hash: crypto.Hash(0), -} - -// SigningMethodNone is the default "none" algorithm. -type SigningMethodNone struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Verify helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Verify(_ []byte, _ Signature, _ interface{}) error { - return nil -} - -// Sign helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Sign(_ []byte, _ interface{}) (Signature, error) { - return nil, nil -} - -// Alg helps implement the SigningMethod interface. -func (m *SigningMethodNone) Alg() string { - return m.Name -} - -// Hasher helps implement the SigningMethod interface. -func (m *SigningMethodNone) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodNone) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodNone)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa.go b/vendor/github.com/SermoDigital/jose/crypto/rsa.go deleted file mode 100644 index 80596df33..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa.go +++ /dev/null @@ -1,80 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSA implements the RSA family of SigningMethods. -type SigningMethodRSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of RSA SigningMethods. -var ( - // SigningMethodRS256 implements RS256. - SigningMethodRS256 = &SigningMethodRSA{ - Name: "RS256", - Hash: crypto.SHA256, - } - - // SigningMethodRS384 implements RS384. - SigningMethodRS384 = &SigningMethodRSA{ - Name: "RS384", - Hash: crypto.SHA384, - } - - // SigningMethodRS512 implements RS512. - SigningMethodRS512 = &SigningMethodRSA{ - Name: "RS512", - Hash: crypto.SHA512, - } -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodRSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be an *rsa.PublicKey. -func (m *SigningMethodRSA) Verify(raw []byte, sig Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, m.sum(raw), sig) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(data []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, m.sum(data)) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodRSA) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSA)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go b/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go deleted file mode 100644 index 3847ae2d2..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa_pss.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build go1.4 - -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSAPSS implements the RSAPSS family of SigningMethods. -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS SigningMethods. -var ( - // SigningMethodPS256 implements PS256. - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - - // SigningMethodPS384 implements PS384. - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - - // SigningMethodPS512 implements PS512. - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } -) - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *rsa.PublicKey. -func (m *SigningMethodRSAPSS) Verify(raw []byte, signature Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPSS(rsaKey, m.Hash, m.sum(raw), signature, m.Options) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *rsa.PrivateKey. -func (m *SigningMethodRSAPSS) Sign(raw []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, m.sum(raw), m.Options) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSAPSS) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodRSAPSS) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSAPSS) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSAPSS)(nil) diff --git a/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go b/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go deleted file mode 100644 index 43aeff375..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/rsa_utils.go +++ /dev/null @@ -1,70 +0,0 @@ -package crypto - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// Errors specific to rsa_utils. -var ( - ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") -) - -// ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key. -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key. -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/SermoDigital/jose/crypto/signature.go b/vendor/github.com/SermoDigital/jose/crypto/signature.go deleted file mode 100644 index 37571f9de..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/signature.go +++ /dev/null @@ -1,36 +0,0 @@ -package crypto - -import ( - "encoding/json" - - "github.com/SermoDigital/jose" -) - -// Signature is a JWS signature. -type Signature []byte - -// MarshalJSON implements json.Marshaler for a signature. -func (s Signature) MarshalJSON() ([]byte, error) { - return jose.EncodeEscape(s), nil -} - -// Base64 helps implements jose.Encoder for Signature. -func (s Signature) Base64() ([]byte, error) { - return jose.Base64Encode(s), nil -} - -// UnmarshalJSON implements json.Unmarshaler for signature. -func (s *Signature) UnmarshalJSON(b []byte) error { - dec, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - *s = Signature(dec) - return nil -} - -var ( - _ json.Marshaler = (Signature)(nil) - _ json.Unmarshaler = (*Signature)(nil) - _ jose.Encoder = (Signature)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/crypto/signing_method.go b/vendor/github.com/SermoDigital/jose/crypto/signing_method.go deleted file mode 100644 index c8b8874b2..000000000 --- a/vendor/github.com/SermoDigital/jose/crypto/signing_method.go +++ /dev/null @@ -1,24 +0,0 @@ -package crypto - -import "crypto" - -// SigningMethod is an interface that provides a way to sign JWS tokens. -type SigningMethod interface { - // Alg describes the signing algorithm, and is used to uniquely - // describe the specific crypto.SigningMethod. - Alg() string - - // Verify accepts the raw content, the signature, and the key used - // to sign the raw content, and returns any errors found while validating - // the signature and content. - Verify(raw []byte, sig Signature, key interface{}) error - - // Sign returns a Signature for the raw bytes, as well as any errors - // that occurred during the signing. - Sign(raw []byte, key interface{}) (Signature, error) - - // Used to cause quick panics when a crypto.SigningMethod whose form of hashing - // isn't linked in the binary when you register a crypto.SigningMethod. - // To spoof this, see "crypto.SigningMethodNone". - Hasher() crypto.Hash -} diff --git a/vendor/github.com/SermoDigital/jose/jws/claims.go b/vendor/github.com/SermoDigital/jose/jws/claims.go deleted file mode 100644 index 4cc616cfa..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/claims.go +++ /dev/null @@ -1,190 +0,0 @@ -package jws - -import ( - "encoding/json" - "time" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/jwt" -) - -// Claims represents a set of JOSE Claims. -type Claims jwt.Claims - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - return jwt.Claims(c).Get(key) -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - jwt.Claims(c).Set(key, val) -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - jwt.Claims(c).Del(key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - return jwt.Claims(c).Has(key) -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - return jwt.Claims(c).MarshalJSON() -} - -// Base64 implements the Encoder interface. -func (c Claims) Base64() ([]byte, error) { - return jwt.Claims(c).Base64() -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - return jwt.Claims(c).Issuer() -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - return jwt.Claims(c).Subject() -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - return jwt.Claims(c).Audience() -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return jwt.Claims(c).Expiration() -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return jwt.Claims(c).NotBefore() -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return jwt.Claims(c).IssuedAt() -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - return jwt.Claims(c).JWTID() -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { - jwt.Claims(c).Audience() -} - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { - jwt.Claims(c).RemoveExpiration() -} - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { - jwt.Claims(c).NotBefore() -} - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { - jwt.Claims(c).IssuedAt() -} - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { - jwt.Claims(c).RemoveJWTID() -} - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - jwt.Claims(c).SetIssuer(issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - jwt.Claims(c).SetSubject(subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - jwt.Claims(c).SetAudience(audience...) -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - jwt.Claims(c).SetExpiration(expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - jwt.Claims(c).SetNotBefore(notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - jwt.Claims(c).SetIssuedAt(issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - jwt.Claims(c).SetJWTID(uniqueID) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/doc.go b/vendor/github.com/SermoDigital/jose/jws/doc.go deleted file mode 100644 index 165836d57..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jws implements JWSs per RFC 7515 -package jws diff --git a/vendor/github.com/SermoDigital/jose/jws/errors.go b/vendor/github.com/SermoDigital/jose/jws/errors.go deleted file mode 100644 index 0512a0e40..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/errors.go +++ /dev/null @@ -1,62 +0,0 @@ -package jws - -import "errors" - -var ( - - // ErrNotEnoughMethods is returned if New was called _or_ the Flat/Compact - // methods were called with 0 SigningMethods. - ErrNotEnoughMethods = errors.New("not enough methods provided") - - // ErrCouldNotUnmarshal is returned when Parse's json.Unmarshaler - // parameter returns an error. - ErrCouldNotUnmarshal = errors.New("custom unmarshal failed") - - // ErrNotCompact signals that the provided potential JWS is not - // in its compact representation. - ErrNotCompact = errors.New("not a compact JWS") - - // ErrDuplicateHeaderParameter signals that there are duplicate parameters - // in the provided Headers. - ErrDuplicateHeaderParameter = errors.New("duplicate parameters in the JOSE Header") - - // ErrTwoEmptyHeaders is returned if both Headers are empty. - ErrTwoEmptyHeaders = errors.New("both headers cannot be empty") - - // ErrNotEnoughKeys is returned when not enough keys are provided for - // the given SigningMethods. - ErrNotEnoughKeys = errors.New("not enough keys (for given methods)") - - // ErrDidNotValidate means the given JWT did not properly validate - ErrDidNotValidate = errors.New("did not validate") - - // ErrNoAlgorithm means no algorithm ("alg") was found in the Protected - // Header. - ErrNoAlgorithm = errors.New("no algorithm found") - - // ErrAlgorithmDoesntExist means the algorithm asked for cannot be - // found inside the signingMethod cache. - ErrAlgorithmDoesntExist = errors.New("algorithm doesn't exist") - - // ErrMismatchedAlgorithms means the algorithm inside the JWT was - // different than the algorithm the caller wanted to use. - ErrMismatchedAlgorithms = errors.New("mismatched algorithms") - - // ErrCannotValidate means the JWS cannot be validated for various - // reasons. For example, if there aren't any signatures/payloads/headers - // to actually validate. - ErrCannotValidate = errors.New("cannot validate") - - // ErrIsNotJWT means the given JWS is not a JWT. - ErrIsNotJWT = errors.New("JWS is not a JWT") - - // ErrHoldsJWE means the given JWS holds a JWE inside its payload. - ErrHoldsJWE = errors.New("JWS holds JWE") - - // ErrNotEnoughValidSignatures means the JWS did not meet the required - // number of signatures. - ErrNotEnoughValidSignatures = errors.New("not enough valid signatures in the JWS") - - // ErrNoTokenInRequest means there's no token present inside the *http.Request. - ErrNoTokenInRequest = errors.New("no token present in request") -) diff --git a/vendor/github.com/SermoDigital/jose/jws/jws.go b/vendor/github.com/SermoDigital/jose/jws/jws.go deleted file mode 100644 index 49e7b976d..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws.go +++ /dev/null @@ -1,490 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" - "net/http" - "strings" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/crypto" -) - -// JWS implements a JWS per RFC 7515. -type JWS interface { - // Payload Returns the payload. - Payload() interface{} - - // SetPayload sets the payload with the given value. - SetPayload(p interface{}) - - // Protected returns the JWS' Protected Header. - Protected() jose.Protected - - // ProtectedAt returns the JWS' Protected Header. - // i represents the index of the Protected Header. - ProtectedAt(i int) jose.Protected - - // Header returns the JWS' unprotected Header. - Header() jose.Header - - // HeaderAt returns the JWS' unprotected Header. - // i represents the index of the unprotected Header. - HeaderAt(i int) jose.Header - - // Verify validates the current JWS' signature as-is. Refer to - // ValidateMulti for more information. - Verify(key interface{}, method crypto.SigningMethod) error - - // ValidateMulti validates the current JWS' signature as-is. Since it's - // meant to be called after parsing a stream of bytes into a JWS, it - // shouldn't do any internal parsing like the Sign, Flat, Compact, or - // General methods do. - VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error - - // VerifyCallback validates the current JWS' signature as-is. It - // accepts a callback function that can be used to access header - // parameters to lookup needed information. For example, looking - // up the "kid" parameter. - // The return slice must be a slice of keys used in the verification - // of the JWS. - VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error - - // General serializes the JWS into its "general" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.1 - General(keys ...interface{}) ([]byte, error) - - // Flat serializes the JWS to its "flattened" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.2 - Flat(key interface{}) ([]byte, error) - - // Compact serializes the JWS into its "compact" form per - // https://tools.ietf.org/html/rfc7515#section-7.1 - Compact(key interface{}) ([]byte, error) - - // IsJWT returns true if the JWS is a JWT. - IsJWT() bool -} - -// jws represents a specific jws. -type jws struct { - payload *payload - plcache rawBase64 - clean bool - - sb []sigHead - - isJWT bool -} - -// Payload returns the jws' payload. -func (j *jws) Payload() interface{} { - return j.payload.v -} - -// SetPayload sets the jws' raw, unexported payload. -func (j *jws) SetPayload(val interface{}) { - j.payload.v = val -} - -// Protected returns the JWS' Protected Header. -func (j *jws) Protected() jose.Protected { - return j.sb[0].protected -} - -// Protected returns the JWS' Protected Header. -// i represents the index of the Protected Header. -// Left empty, it defaults to 0. -func (j *jws) ProtectedAt(i int) jose.Protected { - return j.sb[i].protected -} - -// Header returns the JWS' unprotected Header. -func (j *jws) Header() jose.Header { - return j.sb[0].unprotected -} - -// HeaderAt returns the JWS' unprotected Header. -// |i| is the index of the unprotected Header. -func (j *jws) HeaderAt(i int) jose.Header { - return j.sb[i].unprotected -} - -// sigHead represents the 'signatures' member of the jws' "general" -// serialization form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// It's embedded inside the "flat" structure in order to properly -// create the "flat" jws. -type sigHead struct { - Protected rawBase64 `json:"protected,omitempty"` - Unprotected rawBase64 `json:"header,omitempty"` - Signature crypto.Signature `json:"signature"` - - protected jose.Protected - unprotected jose.Header - clean bool - - method crypto.SigningMethod -} - -func (s *sigHead) unmarshal() error { - if err := s.protected.UnmarshalJSON(s.Protected); err != nil { - return err - } - return s.unprotected.UnmarshalJSON(s.Unprotected) -} - -// New creates a JWS with the provided crypto.SigningMethods. -func New(content interface{}, methods ...crypto.SigningMethod) JWS { - sb := make([]sigHead, len(methods)) - for i := range methods { - sb[i] = sigHead{ - protected: jose.Protected{ - "alg": methods[i].Alg(), - }, - unprotected: jose.Header{}, - method: methods[i], - } - } - return &jws{ - payload: &payload{v: content}, - sb: sb, - } -} - -func (s *sigHead) assignMethod(p jose.Protected) error { - alg, ok := p.Get("alg").(string) - if !ok { - return ErrNoAlgorithm - } - - sm := GetSigningMethod(alg) - if sm == nil { - return ErrNoAlgorithm - } - s.method = sm - return nil -} - -type generic struct { - Payload rawBase64 `json:"payload"` - sigHead - Signatures []sigHead `json:"signatures,omitempty"` -} - -// Parse parses any of the three serialized jws forms into a physical -// jws per https://tools.ietf.org/html/rfc7515#section-5.2 -// -// It accepts a json.Unmarshaler in order to properly parse -// the payload. In order to keep the caller from having to do extra -// parsing of the payload, a json.Unmarshaler can be passed -// which will be then to unmarshal the payload however the caller -// wishes. Do note that if json.Unmarshal returns an error the -// original payload will be used as if no json.Unmarshaler was -// passed. -// -// Internally, Parse applies some heuristics and then calls either -// ParseGeneral, ParseFlat, or ParseCompact. -// It should only be called if, for whatever reason, you do not -// know which form the serialized JWT is in. -// -// It cannot parse a JWT. -func Parse(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - // Try and unmarshal into a generic struct that'll - // hopefully hold either of the two JSON serialization - // formats. - var g generic - - // Not valid JSON. Let's try compact. - if err := json.Unmarshal(encoded, &g); err != nil { - return ParseCompact(encoded, u...) - } - - if g.Signatures == nil { - return g.parseFlat(u...) - } - return g.parseGeneral(u...) -} - -// ParseGeneral parses a jws serialized into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseGeneral(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseGeneral(u...) -} - -func (g *generic) parseGeneral(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - for i := range g.Signatures { - if err := g.Signatures[i].unmarshal(); err != nil { - return nil, err - } - if err := checkHeaders(jose.Header(g.Signatures[i].protected), g.Signatures[i].unprotected); err != nil { - return nil, err - } - - if err := g.Signatures[i].assignMethod(g.Signatures[i].protected); err != nil { - return nil, err - } - } - - g.clean = len(g.Signatures) != 0 - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: g.Signatures, - }, nil -} - -// ParseFlat parses a jws serialized into its "flat" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseFlat(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseFlat(u...) -} - -func (g *generic) parseFlat(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - if err := g.sigHead.unmarshal(); err != nil { - return nil, err - } - g.sigHead.clean = true - - if err := checkHeaders(jose.Header(g.sigHead.protected), g.sigHead.unprotected); err != nil { - return nil, err - } - - if err := g.sigHead.assignMethod(g.sigHead.protected); err != nil { - return nil, err - } - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: []sigHead{g.sigHead}, - }, nil -} - -// ParseCompact parses a jws serialized into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseCompact(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - return parseCompact(encoded, false, u...) -} - -func parseCompact(encoded []byte, jwt bool, u ...json.Unmarshaler) (*jws, error) { - - // This section loosely follows - // https://tools.ietf.org/html/rfc7519#section-7.2 - // because it's used to parse _both_ jws and JWTs. - - parts := bytes.Split(encoded, []byte{'.'}) - if len(parts) != 3 { - return nil, ErrNotCompact - } - - var p jose.Protected - if err := p.UnmarshalJSON(parts[0]); err != nil { - return nil, err - } - - s := sigHead{ - Protected: parts[0], - protected: p, - Signature: parts[2], - clean: true, - } - - if err := s.assignMethod(p); err != nil { - return nil, err - } - - var pl payload - if len(u) > 0 { - pl.u = u[0] - } - - j := jws{ - payload: &pl, - plcache: parts[1], - sb: []sigHead{s}, - isJWT: jwt, - } - - if err := j.payload.UnmarshalJSON(parts[1]); err != nil { - return nil, err - } - - j.clean = true - - if err := j.sb[0].Signature.UnmarshalJSON(parts[2]); err != nil { - return nil, err - } - - // https://tools.ietf.org/html/rfc7519#section-7.2.8 - cty, ok := p.Get("cty").(string) - if ok && cty == "JWT" { - return &j, ErrHoldsJWE - } - return &j, nil -} - -var ( - // JWSFormKey is the form "key" which should be used inside - // ParseFromRequest if the request is a multipart.Form. - JWSFormKey = "access_token" - - // MaxMemory is maximum amount of memory which should be used - // inside ParseFromRequest while parsing the multipart.Form - // if the request is a multipart.Form. - MaxMemory int64 = 10e6 -) - -// Format specifies which "format" the JWS is in -- Flat, General, -// or compact. Additionally, constants for JWT/Unknown are added. -type Format uint8 - -const ( - // Unknown format. - Unknown Format = iota - - // Flat format. - Flat - - // General format. - General - - // Compact format. - Compact -) - -var parseJumpTable = [...]func([]byte, ...json.Unmarshaler) (JWS, error){ - Unknown: Parse, - Flat: ParseFlat, - General: ParseGeneral, - Compact: ParseCompact, - 1<<8 - 1: Parse, // Max uint8. -} - -func init() { - for i := range parseJumpTable { - if parseJumpTable[i] == nil { - parseJumpTable[i] = Parse - } - } -} - -func fromHeader(req *http.Request) ([]byte, bool) { - if ah := req.Header.Get("Authorization"); len(ah) > 7 && strings.EqualFold(ah[0:7], "BEARER ") { - return []byte(ah[7:]), true - } - return nil, false -} - -func fromForm(req *http.Request) ([]byte, bool) { - if err := req.ParseMultipartForm(MaxMemory); err != nil { - return nil, false - } - if tokStr := req.Form.Get(JWSFormKey); tokStr != "" { - return []byte(tokStr), true - } - return nil, false -} - -// ParseFromHeader tries to find the JWS in an http.Request header. -func ParseFromHeader(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromHeader(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromForm tries to find the JWS in an http.Request form request. -func ParseFromForm(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromForm(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromRequest tries to find the JWS in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseFromRequest(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - token, err := ParseFromHeader(req, format, u...) - if err == nil { - return token, nil - } - - token, err = ParseFromForm(req, format, u...) - if err == nil { - return token, nil - } - - return nil, err -} - -// IgnoreDupes should be set to true if the internal duplicate header key check -// should ignore duplicate Header keys instead of reporting an error when -// duplicate Header keys are found. -// -// Note: -// Duplicate Header keys are defined in -// https://tools.ietf.org/html/rfc7515#section-5.2 -// meaning keys that both the protected and unprotected -// Headers possess. -var IgnoreDupes bool - -// checkHeaders returns an error per the constraints described in -// IgnoreDupes' comment. -func checkHeaders(a, b jose.Header) error { - if len(a)+len(b) == 0 { - return ErrTwoEmptyHeaders - } - for key := range a { - if b.Has(key) && !IgnoreDupes { - return ErrDuplicateHeaderParameter - } - } - return nil -} - -var _ JWS = (*jws)(nil) diff --git a/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go b/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go deleted file mode 100644 index 923fdc224..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws_serialize.go +++ /dev/null @@ -1,132 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" -) - -// Flat serializes the JWS to its "flattened" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -func (j *jws) Flat(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - if err := j.sign(key); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - sigHead - }{ - Payload: j.plcache, - sigHead: j.sb[0], - }) -} - -// General serializes the JWS into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// If only one key is passed it's used for all the provided -// crypto.SigningMethods. Otherwise, len(keys) must equal the number -// of crypto.SigningMethods added. -func (j *jws) General(keys ...interface{}) ([]byte, error) { - if err := j.sign(keys...); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - Signatures []sigHead `json:"signatures"` - }{ - Payload: j.plcache, - Signatures: j.sb, - }) -} - -// Compact serializes the JWS into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -func (j *jws) Compact(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - - if err := j.sign(key); err != nil { - return nil, err - } - - sig, err := j.sb[0].Signature.Base64() - if err != nil { - return nil, err - } - return format( - j.sb[0].Protected, - j.plcache, - sig, - ), nil -} - -// sign signs each index of j's sb member. -func (j *jws) sign(keys ...interface{}) error { - if err := j.cache(); err != nil { - return err - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(j.sb)) - for i := range keys { - keys[i] = k - } - } - - for i := range j.sb { - if err := j.sb[i].cache(); err != nil { - return err - } - - raw := format(j.sb[i].Protected, j.plcache) - sig, err := j.sb[i].method.Sign(raw, keys[i]) - if err != nil { - return err - } - j.sb[i].Signature = sig - } - - return nil -} - -// cache marshals the payload, but only if it's changed since the last cache. -func (j *jws) cache() (err error) { - if !j.clean { - j.plcache, err = j.payload.Base64() - j.clean = err == nil - } - return err -} - -// cache marshals the protected and unprotected headers, but only if -// they've changed since their last cache. -func (s *sigHead) cache() (err error) { - if !s.clean { - s.Protected, err = s.protected.Base64() - if err != nil { - return err - } - s.Unprotected, err = s.unprotected.Base64() - if err != nil { - return err - } - } - s.clean = true - return nil -} - -// format formats a slice of bytes in the order given, joining -// them with a period. -func format(a ...[]byte) []byte { - return bytes.Join(a, []byte{'.'}) -} diff --git a/vendor/github.com/SermoDigital/jose/jws/jws_validate.go b/vendor/github.com/SermoDigital/jose/jws/jws_validate.go deleted file mode 100644 index e5e3abd18..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/jws_validate.go +++ /dev/null @@ -1,203 +0,0 @@ -package jws - -import ( - "fmt" - - "github.com/SermoDigital/jose/crypto" -) - -// VerifyCallback is a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -type VerifyCallback func(JWS) ([]interface{}, error) - -// VerifyCallback validates the current JWS' signature as-is. It -// accepts a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -func (j *jws) VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error { - keys, err := fn(j) - if err != nil { - return err - } - return j.VerifyMulti(keys, methods, o) -} - -// IsMultiError returns true if the given error is type *MultiError. -func IsMultiError(err error) bool { - _, ok := err.(*MultiError) - return ok -} - -// MultiError is a slice of errors. -type MultiError []error - -// Errors implements the error interface. -func (m *MultiError) Error() string { - var s string - var n int - for _, err := range *m { - if err != nil { - if n == 0 { - s = err.Error() - } - n++ - } - } - switch n { - case 0: - return "" - case 1: - return s - case 2: - return s + " and 1 other error" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} - -// Any means any of the JWS signatures need to verify. -// Refer to verifyMulti for more information. -const Any int = 0 - -// VerifyMulti verifies the current JWS as-is. Since it's meant to be -// called after parsing a stream of bytes into a JWS, it doesn't do any -// internal parsing like the Sign, Flat, Compact, or General methods do. -func (j *jws) VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error { - - // Catch a simple mistake. Parameter o is irrelevant in this scenario. - if len(keys) == 1 && - len(methods) == 1 && - len(j.sb) == 1 { - return j.Verify(keys[0], methods[0]) - } - - if len(j.sb) != len(methods) { - return ErrNotEnoughMethods - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - // TODO do this better. - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(methods)) - for i := range keys { - keys[i] = k - } - } - - var o2 SigningOpts - if o == nil { - o = new(SigningOpts) - } - - var m MultiError - for i := range j.sb { - err := j.sb[i].verify(j.plcache, keys[i], methods[i]) - if err != nil { - m = append(m, err) - } else { - o2.Inc() - if o.Needs(i) { - o.ptr++ - o2.Append(i) - } - } - } - - err := o.Validate(&o2) - if err != nil { - m = append(m, err) - } - if len(m) == 0 { - return nil - } - return &m -} - -// SigningOpts is a struct which holds options for validating -// JWS signatures. -// Number represents the cumulative which signatures need to verify -// in order for the JWS to be considered valid. -// Leave 'Number' empty or set it to the constant 'Any' if any number of -// valid signatures (greater than one) should verify the JWS. -// -// Use the indices of the signatures that need to verify in order -// for the JWS to be considered valid if specific signatures need -// to verify in order for the JWS to be considered valid. -// -// Note: -// The JWS spec requires *at least* one -// signature to verify in order for the JWS to be considered valid. -type SigningOpts struct { - // Minimum of signatures which need to verify. - Number int - - // Indices of specific signatures which need to verify. - Indices []int - ptr int - - _ struct{} -} - -// Append appends x to s' Indices member. -func (s *SigningOpts) Append(x int) { - s.Indices = append(s.Indices, x) -} - -// Needs returns true if x resides inside s' Indices member -// for the given index. It's used to match two SigningOpts Indices members. -func (s *SigningOpts) Needs(x int) bool { - return s.ptr < len(s.Indices) && s.Indices[s.ptr] == x -} - -// Inc increments s' Number member by one. -func (s *SigningOpts) Inc() { s.Number++ } - -// Validate returns any errors found while validating the -// provided SigningOpts. The receiver validates |have|. -// It'll return an error if the passed SigningOpts' Number member is less -// than s' or if the passed SigningOpts' Indices slice isn't equal to s'. -func (s *SigningOpts) Validate(have *SigningOpts) error { - if have.Number < s.Number || - (s.Indices != nil && - !eq(s.Indices, have.Indices)) { - return ErrNotEnoughValidSignatures - } - return nil -} - -func eq(a, b []int) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -// Verify verifies the current JWS as-is. Refer to verifyMulti -// for more information. -func (j *jws) Verify(key interface{}, method crypto.SigningMethod) error { - if len(j.sb) < 1 { - return ErrCannotValidate - } - return j.sb[0].verify(j.plcache, key, method) -} - -func (s *sigHead) verify(pl []byte, key interface{}, method crypto.SigningMethod) error { - if s.method.Alg() != method.Alg() || s.method.Hasher() != method.Hasher() { - return ErrMismatchedAlgorithms - } - return method.Verify(format(s.Protected, pl), s.Signature, key) -} diff --git a/vendor/github.com/SermoDigital/jose/jws/jwt.go b/vendor/github.com/SermoDigital/jose/jws/jwt.go deleted file mode 100644 index 53da1fcf7..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/jwt.go +++ /dev/null @@ -1,115 +0,0 @@ -package jws - -import ( - "net/http" - "time" - - "github.com/SermoDigital/jose" - "github.com/SermoDigital/jose/crypto" - "github.com/SermoDigital/jose/jwt" -) - -// NewJWT creates a new JWT with the given claims. -func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT { - j, ok := New(claims, method).(*jws) - if !ok { - panic("jws.NewJWT: runtime panic: New(...).(*jws) != true") - } - j.sb[0].protected.Set("typ", "JWT") - j.isJWT = true - return j -} - -// Serialize helps implements jwt.JWT. -func (j *jws) Serialize(key interface{}) ([]byte, error) { - if j.isJWT { - return j.Compact(key) - } - return nil, ErrIsNotJWT -} - -// Claims helps implements jwt.JWT. -func (j *jws) Claims() jwt.Claims { - if j.isJWT { - if c, ok := j.payload.v.(Claims); ok { - return jwt.Claims(c) - } - } - return nil -} - -// ParseJWTFromRequest tries to find the JWT in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseJWTFromRequest(req *http.Request) (jwt.JWT, error) { - if b, ok := fromHeader(req); ok { - return ParseJWT(b) - } - if b, ok := fromForm(req); ok { - return ParseJWT(b) - } - return nil, ErrNoTokenInRequest -} - -// ParseJWT parses a serialized jwt.JWT into a physical jwt.JWT. -// If its payload isn't a set of claims (or able to be coerced into -// a set of claims) it'll return an error stating the -// JWT isn't a JWT. -func ParseJWT(encoded []byte) (jwt.JWT, error) { - t, err := parseCompact(encoded, true) - if err != nil { - return nil, err - } - c, ok := t.Payload().(map[string]interface{}) - if !ok { - return nil, ErrIsNotJWT - } - t.SetPayload(Claims(c)) - return t, nil -} - -// IsJWT returns true if the JWS is a JWT. -func (j *jws) IsJWT() bool { - return j.isJWT -} - -func (j *jws) Validate(key interface{}, m crypto.SigningMethod, v ...*jwt.Validator) error { - if j.isJWT { - if err := j.Verify(key, m); err != nil { - return err - } - var v1 jwt.Validator - if len(v) > 0 { - v1 = *v[0] - } - c, ok := j.payload.v.(Claims) - if ok { - if err := v1.Validate(j); err != nil { - return err - } - return jwt.Claims(c).Validate(jose.Now(), v1.EXP, v1.NBF) - } - } - return ErrIsNotJWT -} - -// Conv converts a func(Claims) error to type jwt.ValidateFunc. -func Conv(fn func(Claims) error) jwt.ValidateFunc { - if fn == nil { - return nil - } - return func(c jwt.Claims) error { - return fn(Claims(c)) - } -} - -// NewValidator returns a jwt.Validator. -func NewValidator(c Claims, exp, nbf time.Duration, fn func(Claims) error) *jwt.Validator { - return &jwt.Validator{ - Expected: jwt.Claims(c), - EXP: exp, - NBF: nbf, - Fn: Conv(fn), - } -} - -var _ jwt.JWT = (*jws)(nil) diff --git a/vendor/github.com/SermoDigital/jose/jws/payload.go b/vendor/github.com/SermoDigital/jose/jws/payload.go deleted file mode 100644 index 58bfd066f..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/payload.go +++ /dev/null @@ -1,52 +0,0 @@ -package jws - -import ( - "encoding/json" - - "github.com/SermoDigital/jose" -) - -// payload represents the payload of a JWS. -type payload struct { - v interface{} - u json.Unmarshaler - _ struct{} -} - -// MarshalJSON implements json.Marshaler for payload. -func (p *payload) MarshalJSON() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.EncodeEscape(b), nil -} - -// Base64 implements jose.Encoder. -func (p *payload) Base64() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// MarshalJSON implements json.Unmarshaler for payload. -func (p *payload) UnmarshalJSON(b []byte) error { - b2, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - if p.u != nil { - err := p.u.UnmarshalJSON(b2) - p.v = p.u - return err - } - return json.Unmarshal(b2, &p.v) -} - -var ( - _ json.Marshaler = (*payload)(nil) - _ json.Unmarshaler = (*payload)(nil) - _ jose.Encoder = (*payload)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/rawbase64.go b/vendor/github.com/SermoDigital/jose/jws/rawbase64.go deleted file mode 100644 index f2c406048..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/rawbase64.go +++ /dev/null @@ -1,28 +0,0 @@ -package jws - -import "encoding/json" - -type rawBase64 []byte - -// MarshalJSON implements json.Marshaler for rawBase64. -func (r rawBase64) MarshalJSON() ([]byte, error) { - buf := make([]byte, len(r)+2) - buf[0] = '"' - copy(buf[1:], r) - buf[len(buf)-1] = '"' - return buf, nil -} - -// MarshalJSON implements json.Unmarshaler for rawBase64. -func (r *rawBase64) UnmarshalJSON(b []byte) error { - if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' { - b = b[1 : len(b)-1] - } - *r = rawBase64(b) - return nil -} - -var ( - _ json.Marshaler = (rawBase64)(nil) - _ json.Unmarshaler = (*rawBase64)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jws/signing_methods.go b/vendor/github.com/SermoDigital/jose/jws/signing_methods.go deleted file mode 100644 index 525806f4a..000000000 --- a/vendor/github.com/SermoDigital/jose/jws/signing_methods.go +++ /dev/null @@ -1,63 +0,0 @@ -package jws - -import ( - "sync" - - "github.com/SermoDigital/jose/crypto" -) - -var ( - mu sync.RWMutex - - signingMethods = map[string]crypto.SigningMethod{ - crypto.SigningMethodES256.Alg(): crypto.SigningMethodES256, - crypto.SigningMethodES384.Alg(): crypto.SigningMethodES384, - crypto.SigningMethodES512.Alg(): crypto.SigningMethodES512, - - crypto.SigningMethodPS256.Alg(): crypto.SigningMethodPS256, - crypto.SigningMethodPS384.Alg(): crypto.SigningMethodPS384, - crypto.SigningMethodPS512.Alg(): crypto.SigningMethodPS512, - - crypto.SigningMethodRS256.Alg(): crypto.SigningMethodRS256, - crypto.SigningMethodRS384.Alg(): crypto.SigningMethodRS384, - crypto.SigningMethodRS512.Alg(): crypto.SigningMethodRS512, - - crypto.SigningMethodHS256.Alg(): crypto.SigningMethodHS256, - crypto.SigningMethodHS384.Alg(): crypto.SigningMethodHS384, - crypto.SigningMethodHS512.Alg(): crypto.SigningMethodHS512, - - crypto.Unsecured.Alg(): crypto.Unsecured, - } -) - -// RegisterSigningMethod registers the crypto.SigningMethod in the global map. -// This is typically done inside the caller's init function. -func RegisterSigningMethod(sm crypto.SigningMethod) { - alg := sm.Alg() - if GetSigningMethod(alg) != nil { - panic("jose/jws: cannot duplicate signing methods") - } - - if !sm.Hasher().Available() { - panic("jose/jws: specific hash is unavailable") - } - - mu.Lock() - signingMethods[alg] = sm - mu.Unlock() -} - -// RemoveSigningMethod removes the crypto.SigningMethod from the global map. -func RemoveSigningMethod(sm crypto.SigningMethod) { - mu.Lock() - delete(signingMethods, sm.Alg()) - mu.Unlock() -} - -// GetSigningMethod retrieves a crypto.SigningMethod from the global map. -func GetSigningMethod(alg string) (method crypto.SigningMethod) { - mu.RLock() - method = signingMethods[alg] - mu.RUnlock() - return method -} diff --git a/vendor/github.com/SermoDigital/jose/jwt/claims.go b/vendor/github.com/SermoDigital/jose/jwt/claims.go deleted file mode 100644 index d3d93bfb5..000000000 --- a/vendor/github.com/SermoDigital/jose/jwt/claims.go +++ /dev/null @@ -1,274 +0,0 @@ -package jwt - -import ( - "encoding/json" - "time" - - "github.com/SermoDigital/jose" -) - -// Claims implements a set of JOSE Claims with the addition of some helper -// methods, similar to net/url.Values. -type Claims map[string]interface{} - -// Validate validates the Claims per the claims found in -// https://tools.ietf.org/html/rfc7519#section-4.1 -func (c Claims) Validate(now time.Time, expLeeway, nbfLeeway time.Duration) error { - if exp, ok := c.Expiration(); ok { - if now.After(exp.Add(expLeeway)) { - return ErrTokenIsExpired - } - } - - if nbf, ok := c.NotBefore(); ok { - if !now.After(nbf.Add(-nbfLeeway)) { - return ErrTokenNotYetValid - } - } - return nil -} - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - if c == nil { - return nil - } - return c[key] -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - c[key] = val -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - delete(c, key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - _, ok := c[key] - return ok -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - if c == nil || len(c) == 0 { - return nil, nil - } - return json.Marshal(map[string]interface{}(c)) -} - -// Base64 implements the jose.Encoder interface. -func (c Claims) Base64() ([]byte, error) { - b, err := c.MarshalJSON() - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. (Address of unaddressable object and all that...) - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - v, ok := c.Get("iss").(string) - return v, ok -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - v, ok := c.Get("sub").(string) - return v, ok -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - // Audience claim must be stringy. That is, it may be one string - // or multiple strings but it should not be anything else. E.g. an int. - switch t := c.Get("aud").(type) { - case string: - return []string{t}, true - case []string: - return t, true - case []interface{}: - return stringify(t...) - case interface{}: - return stringify(t) - } - return nil, false -} - -func stringify(a ...interface{}) ([]string, bool) { - if len(a) == 0 { - return nil, false - } - - s := make([]string, len(a)) - for i := range a { - str, ok := a[i].(string) - if !ok { - return nil, false - } - s[i] = str - } - return s, true -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return c.GetTime("exp") -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return c.GetTime("nbf") -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return c.GetTime("iat") -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - v, ok := c.Get("jti").(string) - return v, ok -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { c.Del("iss") } - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { c.Del("sub") } - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { c.Del("aud") } - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { c.Del("exp") } - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { c.Del("nbf") } - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { c.Del("iat") } - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { c.Del("jti") } - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - c.Set("iss", issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - c.Set("sub", subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - if len(audience) == 1 { - c.Set("aud", audience[0]) - } else { - c.Set("aud", audience) - } -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - c.SetTime("exp", expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - c.SetTime("nbf", notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - c.SetTime("iat", issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - c.Set("jti", uniqueID) -} - -// GetTime returns a Unix timestamp for the given key. -// -// It converts an int, int32, int64, uint, uint32, uint64 or float64 into a Unix -// timestamp (epoch seconds). float32 does not have sufficient precision to -// store a Unix timestamp. -// -// Numeric values parsed from JSON will always be stored as float64 since -// Claims is a map[string]interface{}. However, the values may be stored directly -// in the claims as a different type. -func (c Claims) GetTime(key string) (time.Time, bool) { - switch t := c.Get(key).(type) { - case int: - return time.Unix(int64(t), 0), true - case int32: - return time.Unix(int64(t), 0), true - case int64: - return time.Unix(int64(t), 0), true - case uint: - return time.Unix(int64(t), 0), true - case uint32: - return time.Unix(int64(t), 0), true - case uint64: - return time.Unix(int64(t), 0), true - case float64: - return time.Unix(int64(t), 0), true - default: - return time.Time{}, false - } -} - -// SetTime stores a UNIX time for the given key. -func (c Claims) SetTime(key string, t time.Time) { - c.Set(key, t.Unix()) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/SermoDigital/jose/jwt/doc.go b/vendor/github.com/SermoDigital/jose/jwt/doc.go deleted file mode 100644 index 6004d0fa9..000000000 --- a/vendor/github.com/SermoDigital/jose/jwt/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jwt implements JWTs per RFC 7519 -package jwt diff --git a/vendor/github.com/SermoDigital/jose/jwt/eq.go b/vendor/github.com/SermoDigital/jose/jwt/eq.go deleted file mode 100644 index 3113269fb..000000000 --- a/vendor/github.com/SermoDigital/jose/jwt/eq.go +++ /dev/null @@ -1,47 +0,0 @@ -package jwt - -func verifyPrincipals(pcpls, auds []string) bool { - // "Each principal intended to process the JWT MUST - // identify itself with a value in the audience claim." - // - https://tools.ietf.org/html/rfc7519#section-4.1.3 - - found := -1 - for i, p := range pcpls { - for _, v := range auds { - if p == v { - found++ - break - } - } - if found != i { - return false - } - } - return true -} - -// ValidAudience returns true iff: -// - a and b are strings and a == b -// - a is string, b is []string and a is in b -// - a is []string, b is []string and all of a is in b -// - a is []string, b is string and len(a) == 1 and a[0] == b -func ValidAudience(a, b interface{}) bool { - s1, ok := a.(string) - if ok { - if s2, ok := b.(string); ok { - return s1 == s2 - } - a2, ok := b.([]string) - return ok && verifyPrincipals([]string{s1}, a2) - } - - a1, ok := a.([]string) - if !ok { - return false - } - if a2, ok := b.([]string); ok { - return verifyPrincipals(a1, a2) - } - s2, ok := b.(string) - return ok && len(a1) == 1 && a1[0] == s2 -} diff --git a/vendor/github.com/SermoDigital/jose/jwt/errors.go b/vendor/github.com/SermoDigital/jose/jwt/errors.go deleted file mode 100644 index 96b240d54..000000000 --- a/vendor/github.com/SermoDigital/jose/jwt/errors.go +++ /dev/null @@ -1,28 +0,0 @@ -package jwt - -import "errors" - -var ( - // ErrTokenIsExpired is return when time.Now().Unix() is after - // the token's "exp" claim. - ErrTokenIsExpired = errors.New("token is expired") - - // ErrTokenNotYetValid is return when time.Now().Unix() is before - // the token's "nbf" claim. - ErrTokenNotYetValid = errors.New("token is not yet valid") - - // ErrInvalidISSClaim means the "iss" claim is invalid. - ErrInvalidISSClaim = errors.New("claim \"iss\" is invalid") - - // ErrInvalidSUBClaim means the "sub" claim is invalid. - ErrInvalidSUBClaim = errors.New("claim \"sub\" is invalid") - - // ErrInvalidIATClaim means the "iat" claim is invalid. - ErrInvalidIATClaim = errors.New("claim \"iat\" is invalid") - - // ErrInvalidJTIClaim means the "jti" claim is invalid. - ErrInvalidJTIClaim = errors.New("claim \"jti\" is invalid") - - // ErrInvalidAUDClaim means the "aud" claim is invalid. - ErrInvalidAUDClaim = errors.New("claim \"aud\" is invalid") -) diff --git a/vendor/github.com/SermoDigital/jose/jwt/jwt.go b/vendor/github.com/SermoDigital/jose/jwt/jwt.go deleted file mode 100644 index feb17126f..000000000 --- a/vendor/github.com/SermoDigital/jose/jwt/jwt.go +++ /dev/null @@ -1,144 +0,0 @@ -package jwt - -import ( - "time" - - "github.com/SermoDigital/jose/crypto" -) - -// JWT represents a JWT per RFC 7519. -// It's described as an interface instead of a physical structure -// because both JWS and JWEs can be JWTs. So, in order to use either, -// import one of those two packages and use their "NewJWT" (and other) -// functions. -type JWT interface { - // Claims returns the set of Claims. - Claims() Claims - - // Validate returns an error describing any issues found while - // validating the JWT. For info on the fn parameter, see the - // comment on ValidateFunc. - Validate(key interface{}, method crypto.SigningMethod, v ...*Validator) error - - // Serialize serializes the JWT into its on-the-wire - // representation. - Serialize(key interface{}) ([]byte, error) -} - -// ValidateFunc is a function that provides access to the JWT -// and allows for custom validation. Keep in mind that the Verify -// methods in the JWS/JWE sibling packages call ValidateFunc *after* -// validating the JWS/JWE, but *before* any validation per the JWT -// RFC. Therefore, the ValidateFunc can be used to short-circuit -// verification, but cannot be used to circumvent the RFC. -// Custom JWT implementations are free to abuse this, but it is -// not recommended. -type ValidateFunc func(Claims) error - -// Validator represents some of the validation options. -type Validator struct { - Expected Claims // If non-nil, these are required to match. - EXP time.Duration // EXPLeeway - NBF time.Duration // NBFLeeway - Fn ValidateFunc // See ValidateFunc for more information. - - _ struct{} // Require explicitly-named struct fields. -} - -// Validate validates the JWT based on the expected claims in v. -// Note: it only validates the registered claims per -// https://tools.ietf.org/html/rfc7519#section-4.1 -// -// Custom claims should be validated using v's Fn member. -func (v *Validator) Validate(j JWT) error { - if iss, ok := v.Expected.Issuer(); ok && - j.Claims().Get("iss") != iss { - return ErrInvalidISSClaim - } - if sub, ok := v.Expected.Subject(); ok && - j.Claims().Get("sub") != sub { - return ErrInvalidSUBClaim - } - if iat, ok := v.Expected.IssuedAt(); ok { - if t, ok := j.Claims().GetTime("iat"); !t.Equal(iat) || !ok { - return ErrInvalidIATClaim - } - } - if jti, ok := v.Expected.JWTID(); ok && - j.Claims().Get("jti") != jti { - return ErrInvalidJTIClaim - } - - if aud, ok := v.Expected.Audience(); ok { - aud2, ok := j.Claims().Audience() - if !ok || !ValidAudience(aud, aud2) { - return ErrInvalidAUDClaim - } - } - - if v.Fn != nil { - return v.Fn(j.Claims()) - } - return nil -} - -// SetClaim sets the claim with the given val. -func (v *Validator) SetClaim(claim string, val interface{}) { - v.expect() - v.Expected.Set(claim, val) -} - -// SetIssuer sets the "iss" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (v *Validator) SetIssuer(iss string) { - v.expect() - v.Expected.Set("iss", iss) -} - -// SetSubject sets the "sub" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (v *Validator) SetSubject(sub string) { - v.expect() - v.Expected.Set("sub", sub) -} - -// SetAudience sets the "aud" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (v *Validator) SetAudience(aud string) { - v.expect() - v.Expected.Set("aud", aud) -} - -// SetExpiration sets the "exp" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (v *Validator) SetExpiration(exp time.Time) { - v.expect() - v.Expected.Set("exp", exp) -} - -// SetNotBefore sets the "nbf" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (v *Validator) SetNotBefore(nbf time.Time) { - v.expect() - v.Expected.Set("nbf", nbf) -} - -// SetIssuedAt sets the "iat" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (v *Validator) SetIssuedAt(iat time.Time) { - v.expect() - v.Expected.Set("iat", iat) -} - -// SetJWTID sets the "jti" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (v *Validator) SetJWTID(jti string) { - v.expect() - v.Expected.Set("jti", jti) -} - -func (v *Validator) expect() { - if v.Expected == nil { - v.Expected = make(Claims) - } -} diff --git a/vendor/github.com/agext/levenshtein/.gitignore b/vendor/github.com/agext/levenshtein/.gitignore new file mode 100644 index 000000000..4473da19b --- /dev/null +++ b/vendor/github.com/agext/levenshtein/.gitignore @@ -0,0 +1,53 @@ +# Ignore docs files +_gh_pages +_site + +# Ignore temporary files +README.html +coverage.out +.tmp + +# Numerous always-ignore extensions +*.diff +*.err +*.log +*.orig +*.rej +*.swo +*.swp +*.vi +*.zip +*~ + +# OS or Editor folders +._* +.cache +.DS_Store +.idea +.project +.settings +.tmproj +*.esproj +*.sublime-project +*.sublime-workspace +nbproject +Thumbs.db + +# Komodo +.komodotools +*.komodoproject + +# SCSS-Lint +scss-lint-report.xml + +# grunt-contrib-sass cache +.sass-cache + +# Jekyll metadata +docs/.jekyll-metadata + +# Folders to ignore +.build +.test +bower_components +node_modules diff --git a/vendor/github.com/agext/levenshtein/.travis.yml b/vendor/github.com/agext/levenshtein/.travis.yml new file mode 100644 index 000000000..a51a14466 --- /dev/null +++ b/vendor/github.com/agext/levenshtein/.travis.yml @@ -0,0 +1,25 @@ +language: go +sudo: false +matrix: + fast_finish: true + include: + - go: 1.11.x + env: TEST_METHOD=goveralls + - go: 1.10.x + - go: tip + - go: 1.9.x + - go: 1.8.x + - go: 1.7.x + - go: 1.6.x + - go: 1.5.x + allow_failures: + - go: tip + - go: 1.9.x + - go: 1.8.x + - go: 1.7.x + - go: 1.6.x + - go: 1.5.x +script: ./test.sh $TEST_METHOD +notifications: + email: + on_success: never diff --git a/vendor/github.com/agext/levenshtein/test.sh b/vendor/github.com/agext/levenshtein/test.sh old mode 100755 new mode 100644 diff --git a/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go b/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go index a31cdec77..753447320 100644 --- a/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go +++ b/vendor/github.com/apparentlymart/go-cidr/cidr/cidr.go @@ -71,8 +71,13 @@ func Host(base *net.IPNet, num int) (net.IP, error) { if numUint64 > maxHostNum { return nil, fmt.Errorf("prefix of %d does not accommodate a host numbered %d", parentLen, num) } - - return insertNumIntoIP(ip, num, 32), nil + var bitlength int + if ip.To4() != nil { + bitlength = 32 + } else { + bitlength = 128 + } + return insertNumIntoIP(ip, num, bitlength), nil } // AddressRange returns the first and last addresses in the given CIDR range. @@ -110,3 +115,96 @@ func AddressCount(network *net.IPNet) uint64 { prefixLen, bits := network.Mask.Size() return 1 << (uint64(bits) - uint64(prefixLen)) } + +//VerifyNoOverlap takes a list subnets and supernet (CIDRBlock) and verifies +//none of the subnets overlap and all subnets are in the supernet +//it returns an error if any of those conditions are not satisfied +func VerifyNoOverlap(subnets []*net.IPNet, CIDRBlock *net.IPNet) error { + firstLastIP := make([][]net.IP, len(subnets)) + for i, s := range subnets { + first, last := AddressRange(s) + firstLastIP[i] = []net.IP{first, last} + } + for i, s := range subnets { + if !CIDRBlock.Contains(firstLastIP[i][0]) || !CIDRBlock.Contains(firstLastIP[i][1]) { + return fmt.Errorf("%s does not fully contain %s", CIDRBlock.String(), s.String()) + } + for j := i + 1; j < len(subnets); j++ { + first := firstLastIP[j][0] + last := firstLastIP[j][1] + if s.Contains(first) || s.Contains(last) { + return fmt.Errorf("%s overlaps with %s", subnets[j].String(), s.String()) + } + } + } + return nil +} + +// PreviousSubnet returns the subnet of the desired mask in the IP space +// just lower than the start of IPNet provided. If the IP space rolls over +// then the second return value is true +func PreviousSubnet(network *net.IPNet, prefixLen int) (*net.IPNet, bool) { + startIP := checkIPv4(network.IP) + previousIP := make(net.IP, len(startIP)) + copy(previousIP, startIP) + cMask := net.CIDRMask(prefixLen, 8*len(previousIP)) + previousIP = Dec(previousIP) + previous := &net.IPNet{IP: previousIP.Mask(cMask), Mask: cMask} + if startIP.Equal(net.IPv4zero) || startIP.Equal(net.IPv6zero) { + return previous, true + } + return previous, false +} + +// NextSubnet returns the next available subnet of the desired mask size +// starting for the maximum IP of the offset subnet +// If the IP exceeds the maxium IP then the second return value is true +func NextSubnet(network *net.IPNet, prefixLen int) (*net.IPNet, bool) { + _, currentLast := AddressRange(network) + mask := net.CIDRMask(prefixLen, 8*len(currentLast)) + currentSubnet := &net.IPNet{IP: currentLast.Mask(mask), Mask: mask} + _, last := AddressRange(currentSubnet) + last = Inc(last) + next := &net.IPNet{IP: last.Mask(mask), Mask: mask} + if last.Equal(net.IPv4zero) || last.Equal(net.IPv6zero) { + return next, true + } + return next, false +} + +//Inc increases the IP by one this returns a new []byte for the IP +func Inc(IP net.IP) net.IP { + IP = checkIPv4(IP) + incIP := make([]byte, len(IP)) + copy(incIP, IP) + for j := len(incIP) - 1; j >= 0; j-- { + incIP[j]++ + if incIP[j] > 0 { + break + } + } + return incIP +} + +//Dec decreases the IP by one this returns a new []byte for the IP +func Dec(IP net.IP) net.IP { + IP = checkIPv4(IP) + decIP := make([]byte, len(IP)) + copy(decIP, IP) + decIP = checkIPv4(decIP) + for j := len(decIP) - 1; j >= 0; j-- { + decIP[j]-- + if decIP[j] < 255 { + break + } + } + return decIP +} + +func checkIPv4(ip net.IP) net.IP { + // Go for some reason allocs IPv6len for IPv4 so we have to correct it + if v4 := ip.To4(); v4 != nil { + return v4 + } + return ip +} diff --git a/vendor/github.com/apparentlymart/go-rundeck-api/LICENSE b/vendor/github.com/apparentlymart/go-rundeck-api/LICENSE deleted file mode 100644 index 35687787e..000000000 --- a/vendor/github.com/apparentlymart/go-rundeck-api/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Martin Atkins - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/apparentlymart/go-rundeck-api/README.md b/vendor/github.com/apparentlymart/go-rundeck-api/README.md deleted file mode 100644 index 18abfb3d3..000000000 --- a/vendor/github.com/apparentlymart/go-rundeck-api/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# go-rundeck-api - -This is a Go client for the Rundeck HTTP API. It was primarily developed to back the Rundeck provider in [Terraform](https://terraform.io), but can be used standalone too. - -It should ``go install`` just like any other Go package: - -* ``go install github.com/apparentlymart/go-rundeck-api/rundeck`` - -For reference documentation, see [godoc](https://godoc.org/github.com/apparentlymart/go-rundeck-api/rundeck). diff --git a/vendor/github.com/apparentlymart/go-textseg/textseg/make_tables.go b/vendor/github.com/apparentlymart/go-textseg/textseg/make_tables.go new file mode 100644 index 000000000..aad3d0506 --- /dev/null +++ b/vendor/github.com/apparentlymart/go-textseg/textseg/make_tables.go @@ -0,0 +1,307 @@ +// Copyright (c) 2014 Couchbase, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file +// except in compliance with the License. You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software distributed under the +// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. See the License for the specific language governing permissions +// and limitations under the License. + +// Modified by Martin Atkins to serve the needs of package textseg. + +// +build ignore + +package main + +import ( + "bufio" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "sort" + "strconv" + "strings" + "unicode" +) + +var url = flag.String("url", + "http://www.unicode.org/Public/"+unicode.Version+"/ucd/auxiliary/", + "URL of Unicode database directory") +var verbose = flag.Bool("verbose", + false, + "write data to stdout as it is parsed") +var localFiles = flag.Bool("local", + false, + "data files have been copied to the current directory; for debugging only") +var outputFile = flag.String("output", + "", + "output file for generated tables; default stdout") + +var output *bufio.Writer + +func main() { + flag.Parse() + setupOutput() + + graphemePropertyRanges := make(map[string]*unicode.RangeTable) + loadUnicodeData("GraphemeBreakProperty.txt", graphemePropertyRanges) + wordPropertyRanges := make(map[string]*unicode.RangeTable) + loadUnicodeData("WordBreakProperty.txt", wordPropertyRanges) + sentencePropertyRanges := make(map[string]*unicode.RangeTable) + loadUnicodeData("SentenceBreakProperty.txt", sentencePropertyRanges) + + fmt.Fprintf(output, fileHeader, *url) + generateTables("Grapheme", graphemePropertyRanges) + generateTables("Word", wordPropertyRanges) + generateTables("Sentence", sentencePropertyRanges) + + flushOutput() +} + +// WordBreakProperty.txt has the form: +// 05F0..05F2 ; Hebrew_Letter # Lo [3] HEBREW LIGATURE YIDDISH DOUBLE VAV..HEBREW LIGATURE YIDDISH DOUBLE YOD +// FB1D ; Hebrew_Letter # Lo HEBREW LETTER YOD WITH HIRIQ +func openReader(file string) (input io.ReadCloser) { + if *localFiles { + f, err := os.Open(file) + if err != nil { + log.Fatal(err) + } + input = f + } else { + path := *url + file + resp, err := http.Get(path) + if err != nil { + log.Fatal(err) + } + if resp.StatusCode != 200 { + log.Fatal("bad GET status for "+file, resp.Status) + } + input = resp.Body + } + return +} + +func loadUnicodeData(filename string, propertyRanges map[string]*unicode.RangeTable) { + f := openReader(filename) + defer f.Close() + bufioReader := bufio.NewReader(f) + line, err := bufioReader.ReadString('\n') + for err == nil { + parseLine(line, propertyRanges) + line, err = bufioReader.ReadString('\n') + } + // if the err was EOF still need to process last value + if err == io.EOF { + parseLine(line, propertyRanges) + } +} + +const comment = "#" +const sep = ";" +const rnge = ".." + +func parseLine(line string, propertyRanges map[string]*unicode.RangeTable) { + if strings.HasPrefix(line, comment) { + return + } + line = strings.TrimSpace(line) + if len(line) == 0 { + return + } + commentStart := strings.Index(line, comment) + if commentStart > 0 { + line = line[0:commentStart] + } + pieces := strings.Split(line, sep) + if len(pieces) != 2 { + log.Printf("unexpected %d pieces in %s", len(pieces), line) + return + } + + propertyName := strings.TrimSpace(pieces[1]) + + rangeTable, ok := propertyRanges[propertyName] + if !ok { + rangeTable = &unicode.RangeTable{ + LatinOffset: 0, + } + propertyRanges[propertyName] = rangeTable + } + + codepointRange := strings.TrimSpace(pieces[0]) + rngeIndex := strings.Index(codepointRange, rnge) + + if rngeIndex < 0 { + // single codepoint, not range + codepointInt, err := strconv.ParseUint(codepointRange, 16, 64) + if err != nil { + log.Printf("error parsing int: %v", err) + return + } + if codepointInt < 0x10000 { + r16 := unicode.Range16{ + Lo: uint16(codepointInt), + Hi: uint16(codepointInt), + Stride: 1, + } + addR16ToTable(rangeTable, r16) + } else { + r32 := unicode.Range32{ + Lo: uint32(codepointInt), + Hi: uint32(codepointInt), + Stride: 1, + } + addR32ToTable(rangeTable, r32) + } + } else { + rngeStart := codepointRange[0:rngeIndex] + rngeEnd := codepointRange[rngeIndex+2:] + rngeStartInt, err := strconv.ParseUint(rngeStart, 16, 64) + if err != nil { + log.Printf("error parsing int: %v", err) + return + } + rngeEndInt, err := strconv.ParseUint(rngeEnd, 16, 64) + if err != nil { + log.Printf("error parsing int: %v", err) + return + } + if rngeStartInt < 0x10000 && rngeEndInt < 0x10000 { + r16 := unicode.Range16{ + Lo: uint16(rngeStartInt), + Hi: uint16(rngeEndInt), + Stride: 1, + } + addR16ToTable(rangeTable, r16) + } else if rngeStartInt >= 0x10000 && rngeEndInt >= 0x10000 { + r32 := unicode.Range32{ + Lo: uint32(rngeStartInt), + Hi: uint32(rngeEndInt), + Stride: 1, + } + addR32ToTable(rangeTable, r32) + } else { + log.Printf("unexpected range") + } + } +} + +func addR16ToTable(r *unicode.RangeTable, r16 unicode.Range16) { + if r.R16 == nil { + r.R16 = make([]unicode.Range16, 0, 1) + } + r.R16 = append(r.R16, r16) + if r16.Hi <= unicode.MaxLatin1 { + r.LatinOffset++ + } +} + +func addR32ToTable(r *unicode.RangeTable, r32 unicode.Range32) { + if r.R32 == nil { + r.R32 = make([]unicode.Range32, 0, 1) + } + r.R32 = append(r.R32, r32) +} + +func generateTables(prefix string, propertyRanges map[string]*unicode.RangeTable) { + prNames := make([]string, 0, len(propertyRanges)) + for k := range propertyRanges { + prNames = append(prNames, k) + } + sort.Strings(prNames) + for _, key := range prNames { + rt := propertyRanges[key] + fmt.Fprintf(output, "var _%s%s = %s\n", prefix, key, generateRangeTable(rt)) + } + fmt.Fprintf(output, "type _%sRuneRange unicode.RangeTable\n", prefix) + + fmt.Fprintf(output, "func _%sRuneType(r rune) *_%sRuneRange {\n", prefix, prefix) + fmt.Fprintf(output, "\tswitch {\n") + for _, key := range prNames { + fmt.Fprintf(output, "\tcase unicode.Is(_%s%s, r):\n\t\treturn (*_%sRuneRange)(_%s%s)\n", prefix, key, prefix, prefix, key) + } + fmt.Fprintf(output, "\tdefault:\n\t\treturn nil\n") + fmt.Fprintf(output, "\t}\n") + fmt.Fprintf(output, "}\n") + + fmt.Fprintf(output, "func (rng *_%sRuneRange) String() string {\n", prefix) + fmt.Fprintf(output, "\tswitch (*unicode.RangeTable)(rng) {\n") + for _, key := range prNames { + fmt.Fprintf(output, "\tcase _%s%s:\n\t\treturn %q\n", prefix, key, key) + } + fmt.Fprintf(output, "\tdefault:\n\t\treturn \"Other\"\n") + fmt.Fprintf(output, "\t}\n") + fmt.Fprintf(output, "}\n") +} + +func generateRangeTable(rt *unicode.RangeTable) string { + rv := "&unicode.RangeTable{\n" + if rt.R16 != nil { + rv += "\tR16: []unicode.Range16{\n" + for _, r16 := range rt.R16 { + rv += fmt.Sprintf("\t\t%#v,\n", r16) + } + rv += "\t},\n" + } + if rt.R32 != nil { + rv += "\tR32: []unicode.Range32{\n" + for _, r32 := range rt.R32 { + rv += fmt.Sprintf("\t\t%#v,\n", r32) + } + rv += "\t},\n" + } + rv += fmt.Sprintf("\t\tLatinOffset: %d,\n", rt.LatinOffset) + rv += "}\n" + return rv +} + +const fileHeader = `// Generated by running +// maketables --url=%s +// DO NOT EDIT + +package textseg + +import( + "unicode" +) +` + +func setupOutput() { + output = bufio.NewWriter(startGofmt()) +} + +// startGofmt connects output to a gofmt process if -output is set. +func startGofmt() io.Writer { + if *outputFile == "" { + return os.Stdout + } + stdout, err := os.Create(*outputFile) + if err != nil { + log.Fatal(err) + } + // Pipe output to gofmt. + gofmt := exec.Command("gofmt") + fd, err := gofmt.StdinPipe() + if err != nil { + log.Fatal(err) + } + gofmt.Stdout = stdout + gofmt.Stderr = os.Stderr + err = gofmt.Start() + if err != nil { + log.Fatal(err) + } + return fd +} + +func flushOutput() { + err := output.Flush() + if err != nil { + log.Fatal(err) + } +} diff --git a/vendor/github.com/apparentlymart/go-textseg/textseg/make_test_tables.go b/vendor/github.com/apparentlymart/go-textseg/textseg/make_test_tables.go new file mode 100644 index 000000000..ac4200260 --- /dev/null +++ b/vendor/github.com/apparentlymart/go-textseg/textseg/make_test_tables.go @@ -0,0 +1,212 @@ +// Copyright (c) 2014 Couchbase, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file +// except in compliance with the License. You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software distributed under the +// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// either express or implied. See the License for the specific language governing permissions +// and limitations under the License. + +// +build ignore + +package main + +import ( + "bufio" + "bytes" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "strconv" + "strings" + "unicode" +) + +var url = flag.String("url", + "http://www.unicode.org/Public/"+unicode.Version+"/ucd/auxiliary/", + "URL of Unicode database directory") +var verbose = flag.Bool("verbose", + false, + "write data to stdout as it is parsed") +var localFiles = flag.Bool("local", + false, + "data files have been copied to the current directory; for debugging only") + +var outputFile = flag.String("output", + "", + "output file for generated tables; default stdout") + +var output *bufio.Writer + +func main() { + flag.Parse() + setupOutput() + + graphemeTests := make([]test, 0) + graphemeTests = loadUnicodeData("GraphemeBreakTest.txt", graphemeTests) + wordTests := make([]test, 0) + wordTests = loadUnicodeData("WordBreakTest.txt", wordTests) + sentenceTests := make([]test, 0) + sentenceTests = loadUnicodeData("SentenceBreakTest.txt", sentenceTests) + + fmt.Fprintf(output, fileHeader, *url) + generateTestTables("Grapheme", graphemeTests) + generateTestTables("Word", wordTests) + generateTestTables("Sentence", sentenceTests) + + flushOutput() +} + +// WordBreakProperty.txt has the form: +// 05F0..05F2 ; Hebrew_Letter # Lo [3] HEBREW LIGATURE YIDDISH DOUBLE VAV..HEBREW LIGATURE YIDDISH DOUBLE YOD +// FB1D ; Hebrew_Letter # Lo HEBREW LETTER YOD WITH HIRIQ +func openReader(file string) (input io.ReadCloser) { + if *localFiles { + f, err := os.Open(file) + if err != nil { + log.Fatal(err) + } + input = f + } else { + path := *url + file + resp, err := http.Get(path) + if err != nil { + log.Fatal(err) + } + if resp.StatusCode != 200 { + log.Fatal("bad GET status for "+file, resp.Status) + } + input = resp.Body + } + return +} + +func loadUnicodeData(filename string, tests []test) []test { + f := openReader(filename) + defer f.Close() + bufioReader := bufio.NewReader(f) + line, err := bufioReader.ReadString('\n') + for err == nil { + tests = parseLine(line, tests) + line, err = bufioReader.ReadString('\n') + } + // if the err was EOF still need to process last value + if err == io.EOF { + tests = parseLine(line, tests) + } + return tests +} + +const comment = "#" +const brk = "÷" +const nbrk = "×" + +type test [][]byte + +func parseLine(line string, tests []test) []test { + if strings.HasPrefix(line, comment) { + return tests + } + line = strings.TrimSpace(line) + if len(line) == 0 { + return tests + } + commentStart := strings.Index(line, comment) + if commentStart > 0 { + line = line[0:commentStart] + } + pieces := strings.Split(line, brk) + t := make(test, 0) + for _, piece := range pieces { + piece = strings.TrimSpace(piece) + if len(piece) > 0 { + codePoints := strings.Split(piece, nbrk) + word := "" + for _, codePoint := range codePoints { + codePoint = strings.TrimSpace(codePoint) + r, err := strconv.ParseInt(codePoint, 16, 64) + if err != nil { + log.Printf("err: %v for '%s'", err, string(r)) + return tests + } + + word += string(r) + } + t = append(t, []byte(word)) + } + } + tests = append(tests, t) + return tests +} + +func generateTestTables(prefix string, tests []test) { + fmt.Fprintf(output, testHeader, prefix) + for _, t := range tests { + fmt.Fprintf(output, "\t\t{\n") + fmt.Fprintf(output, "\t\t\tinput: %#v,\n", bytes.Join(t, []byte{})) + fmt.Fprintf(output, "\t\t\toutput: %s,\n", generateTest(t)) + fmt.Fprintf(output, "\t\t},\n") + } + fmt.Fprintf(output, "}\n") +} + +func generateTest(t test) string { + rv := "[][]byte{" + for _, te := range t { + rv += fmt.Sprintf("%#v,", te) + } + rv += "}" + return rv +} + +const fileHeader = `// Generated by running +// maketesttables --url=%s +// DO NOT EDIT + +package textseg +` + +const testHeader = `var unicode%sTests = []struct { + input []byte + output [][]byte + }{ +` + +func setupOutput() { + output = bufio.NewWriter(startGofmt()) +} + +// startGofmt connects output to a gofmt process if -output is set. +func startGofmt() io.Writer { + if *outputFile == "" { + return os.Stdout + } + stdout, err := os.Create(*outputFile) + if err != nil { + log.Fatal(err) + } + // Pipe output to gofmt. + gofmt := exec.Command("gofmt") + fd, err := gofmt.StdinPipe() + if err != nil { + log.Fatal(err) + } + gofmt.Stdout = stdout + gofmt.Stderr = os.Stderr + err = gofmt.Start() + if err != nil { + log.Fatal(err) + } + return fd +} + +func flushOutput() { + err := output.Flush() + if err != nil { + log.Fatal(err) + } +} diff --git a/vendor/github.com/armon/go-metrics/LICENSE b/vendor/github.com/armon/go-metrics/LICENSE deleted file mode 100644 index 106569e54..000000000 --- a/vendor/github.com/armon/go-metrics/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Armon Dadgar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/armon/go-metrics/README.md b/vendor/github.com/armon/go-metrics/README.md deleted file mode 100644 index aa73348c0..000000000 --- a/vendor/github.com/armon/go-metrics/README.md +++ /dev/null @@ -1,91 +0,0 @@ -go-metrics -========== - -This library provides a `metrics` package which can be used to instrument code, -expose application metrics, and profile runtime performance in a flexible manner. - -Current API: [![GoDoc](https://godoc.org/github.com/armon/go-metrics?status.svg)](https://godoc.org/github.com/armon/go-metrics) - -Sinks ------ - -The `metrics` package makes use of a `MetricSink` interface to support delivery -to any type of backend. Currently the following sinks are provided: - -* StatsiteSink : Sinks to a [statsite](https://github.com/armon/statsite/) instance (TCP) -* StatsdSink: Sinks to a [StatsD](https://github.com/etsy/statsd/) / statsite instance (UDP) -* PrometheusSink: Sinks to a [Prometheus](http://prometheus.io/) metrics endpoint (exposed via HTTP for scrapes) -* InmemSink : Provides in-memory aggregation, can be used to export stats -* FanoutSink : Sinks to multiple sinks. Enables writing to multiple statsite instances for example. -* BlackholeSink : Sinks to nowhere - -In addition to the sinks, the `InmemSignal` can be used to catch a signal, -and dump a formatted output of recent metrics. For example, when a process gets -a SIGUSR1, it can dump to stderr recent performance metrics for debugging. - -Labels ------- - -Most metrics do have an equivalent ending with `WithLabels`, such methods -allow to push metrics with labels and use some features of underlying Sinks -(ex: translated into Prometheus labels). - -Since some of these labels may increase greatly cardinality of metrics, the -library allow to filter labels using a blacklist/whitelist filtering system -which is global to all metrics. - -* If `Config.AllowedLabels` is not nil, then only labels specified in this value will be sent to underlying Sink, otherwise, all labels are sent by default. -* If `Config.BlockedLabels` is not nil, any label specified in this value will not be sent to underlying Sinks. - -By default, both `Config.AllowedLabels` and `Config.BlockedLabels` are nil, meaning that -no tags are filetered at all, but it allow to a user to globally block some tags with high -cardinality at application level. - -Examples --------- - -Here is an example of using the package: - -```go -func SlowMethod() { - // Profiling the runtime of a method - defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now()) -} - -// Configure a statsite sink as the global metrics sink -sink, _ := metrics.NewStatsiteSink("statsite:8125") -metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink) - -// Emit a Key/Value pair -metrics.EmitKey([]string{"questions", "meaning of life"}, 42) -``` - -Here is an example of setting up a signal handler: - -```go -// Setup the inmem sink and signal handler -inm := metrics.NewInmemSink(10*time.Second, time.Minute) -sig := metrics.DefaultInmemSignal(inm) -metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm) - -// Run some code -inm.SetGauge([]string{"foo"}, 42) -inm.EmitKey([]string{"bar"}, 30) - -inm.IncrCounter([]string{"baz"}, 42) -inm.IncrCounter([]string{"baz"}, 1) -inm.IncrCounter([]string{"baz"}, 80) - -inm.AddSample([]string{"method", "wow"}, 42) -inm.AddSample([]string{"method", "wow"}, 100) -inm.AddSample([]string{"method", "wow"}, 22) - -.... -``` - -When a signal comes in, output like the following will be dumped to stderr: - - [2014-01-28 14:57:33.04 -0800 PST][G] 'foo': 42.000 - [2014-01-28 14:57:33.04 -0800 PST][P] 'bar': 30.000 - [2014-01-28 14:57:33.04 -0800 PST][C] 'baz': Count: 3 Min: 1.000 Mean: 41.000 Max: 80.000 Stddev: 39.509 - [2014-01-28 14:57:33.04 -0800 PST][S] 'method.wow': Count: 3 Min: 22.000 Mean: 54.667 Max: 100.000 Stddev: 40.513 \ No newline at end of file diff --git a/vendor/github.com/armon/go-metrics/circonus/circonus.go b/vendor/github.com/armon/go-metrics/circonus/circonus.go deleted file mode 100644 index eb41b9945..000000000 --- a/vendor/github.com/armon/go-metrics/circonus/circonus.go +++ /dev/null @@ -1,119 +0,0 @@ -// Circonus Metrics Sink - -package circonus - -import ( - "strings" - - "github.com/armon/go-metrics" - cgm "github.com/circonus-labs/circonus-gometrics" -) - -// CirconusSink provides an interface to forward metrics to Circonus with -// automatic check creation and metric management -type CirconusSink struct { - metrics *cgm.CirconusMetrics -} - -// Config options for CirconusSink -// See https://github.com/circonus-labs/circonus-gometrics for configuration options -type Config cgm.Config - -// NewCirconusSink - create new metric sink for circonus -// -// one of the following must be supplied: -// - API Token - search for an existing check or create a new check -// - API Token + Check Id - the check identified by check id will be used -// - API Token + Check Submission URL - the check identified by the submission url will be used -// - Check Submission URL - the check identified by the submission url will be used -// metric management will be *disabled* -// -// Note: If submission url is supplied w/o an api token, the public circonus ca cert will be used -// to verify the broker for metrics submission. -func NewCirconusSink(cc *Config) (*CirconusSink, error) { - cfg := cgm.Config{} - if cc != nil { - cfg = cgm.Config(*cc) - } - - metrics, err := cgm.NewCirconusMetrics(&cfg) - if err != nil { - return nil, err - } - - return &CirconusSink{ - metrics: metrics, - }, nil -} - -// Start submitting metrics to Circonus (flush every SubmitInterval) -func (s *CirconusSink) Start() { - s.metrics.Start() -} - -// Flush manually triggers metric submission to Circonus -func (s *CirconusSink) Flush() { - s.metrics.Flush() -} - -// SetGauge sets value for a gauge metric -func (s *CirconusSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.metrics.SetGauge(flatKey, int64(val)) -} - -// SetGaugeWithLabels sets value for a gauge metric with the given labels -func (s *CirconusSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.metrics.SetGauge(flatKey, int64(val)) -} - -// EmitKey is not implemented in circonus -func (s *CirconusSink) EmitKey(key []string, val float32) { - // NOP -} - -// IncrCounter increments a counter metric -func (s *CirconusSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.metrics.IncrementByValue(flatKey, uint64(val)) -} - -// IncrCounterWithLabels increments a counter metric with the given labels -func (s *CirconusSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.metrics.IncrementByValue(flatKey, uint64(val)) -} - -// AddSample adds a sample to a histogram metric -func (s *CirconusSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.metrics.RecordValue(flatKey, float64(val)) -} - -// AddSampleWithLabels adds a sample to a histogram metric with the given labels -func (s *CirconusSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.metrics.RecordValue(flatKey, float64(val)) -} - -// Flattens key to Circonus metric name -func (s *CirconusSink) flattenKey(parts []string) string { - joined := strings.Join(parts, "`") - return strings.Map(func(r rune) rune { - switch r { - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *CirconusSink) flattenKeyLabels(parts []string, labels []metrics.Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} diff --git a/vendor/github.com/armon/go-metrics/const_unix.go b/vendor/github.com/armon/go-metrics/const_unix.go deleted file mode 100644 index 31098dd57..000000000 --- a/vendor/github.com/armon/go-metrics/const_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - DefaultSignal = syscall.SIGUSR1 -) diff --git a/vendor/github.com/armon/go-metrics/const_windows.go b/vendor/github.com/armon/go-metrics/const_windows.go deleted file mode 100644 index 38136af3e..000000000 --- a/vendor/github.com/armon/go-metrics/const_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - // Windows has no SIGUSR1, use SIGBREAK - DefaultSignal = syscall.Signal(21) -) diff --git a/vendor/github.com/armon/go-metrics/datadog/dogstatsd.go b/vendor/github.com/armon/go-metrics/datadog/dogstatsd.go deleted file mode 100644 index fe021d01c..000000000 --- a/vendor/github.com/armon/go-metrics/datadog/dogstatsd.go +++ /dev/null @@ -1,140 +0,0 @@ -package datadog - -import ( - "fmt" - "strings" - - "github.com/DataDog/datadog-go/statsd" - "github.com/armon/go-metrics" -) - -// DogStatsdSink provides a MetricSink that can be used -// with a dogstatsd server. It utilizes the Dogstatsd client at github.com/DataDog/datadog-go/statsd -type DogStatsdSink struct { - client *statsd.Client - hostName string - propagateHostname bool -} - -// NewDogStatsdSink is used to create a new DogStatsdSink with sane defaults -func NewDogStatsdSink(addr string, hostName string) (*DogStatsdSink, error) { - client, err := statsd.New(addr) - if err != nil { - return nil, err - } - sink := &DogStatsdSink{ - client: client, - hostName: hostName, - propagateHostname: false, - } - return sink, nil -} - -// SetTags sets common tags on the Dogstatsd Client that will be sent -// along with all dogstatsd packets. -// Ref: http://docs.datadoghq.com/guides/dogstatsd/#tags -func (s *DogStatsdSink) SetTags(tags []string) { - s.client.Tags = tags -} - -// EnableHostnamePropagation forces a Dogstatsd `host` tag with the value specified by `s.HostName` -// Since the go-metrics package has its own mechanism for attaching a hostname to metrics, -// setting the `propagateHostname` flag ensures that `s.HostName` overrides the host tag naively set by the DogStatsd server -func (s *DogStatsdSink) EnableHostNamePropagation() { - s.propagateHostname = true -} - -func (s *DogStatsdSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(sanitize, joined) -} - -func sanitize(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } -} - -func (s *DogStatsdSink) parseKey(key []string) ([]string, []metrics.Label) { - // Since DogStatsd supports dimensionality via tags on metric keys, this sink's approach is to splice the hostname out of the key in favor of a `host` tag - // The `host` tag is either forced here, or set downstream by the DogStatsd server - - var labels []metrics.Label - hostName := s.hostName - - // Splice the hostname out of the key - for i, el := range key { - if el == hostName { - key = append(key[:i], key[i+1:]...) - break - } - } - - if s.propagateHostname { - labels = append(labels, metrics.Label{"host", hostName}) - } - return key, labels -} - -// Implementation of methods in the MetricSink interface - -func (s *DogStatsdSink) SetGauge(key []string, val float32) { - s.SetGaugeWithLabels(key, val, nil) -} - -func (s *DogStatsdSink) IncrCounter(key []string, val float32) { - s.IncrCounterWithLabels(key, val, nil) -} - -// EmitKey is not implemented since DogStatsd does not provide a metric type that holds an -// arbitrary number of values -func (s *DogStatsdSink) EmitKey(key []string, val float32) { -} - -func (s *DogStatsdSink) AddSample(key []string, val float32) { - s.AddSampleWithLabels(key, val, nil) -} - -// The following ...WithLabels methods correspond to Datadog's Tag extension to Statsd. -// http://docs.datadoghq.com/guides/dogstatsd/#tags -func (s *DogStatsdSink) SetGaugeWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels) - rate := 1.0 - s.client.Gauge(flatKey, float64(val), tags, rate) -} - -func (s *DogStatsdSink) IncrCounterWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels) - rate := 1.0 - s.client.Count(flatKey, int64(val), tags, rate) -} - -func (s *DogStatsdSink) AddSampleWithLabels(key []string, val float32, labels []metrics.Label) { - flatKey, tags := s.getFlatkeyAndCombinedLabels(key, labels) - rate := 1.0 - s.client.TimeInMilliseconds(flatKey, float64(val), tags, rate) -} - -func (s *DogStatsdSink) getFlatkeyAndCombinedLabels(key []string, labels []metrics.Label) (string, []string) { - key, parsedLabels := s.parseKey(key) - flatKey := s.flattenKey(key) - labels = append(labels, parsedLabels...) - - var tags []string - for _, label := range labels { - label.Name = strings.Map(sanitize, label.Name) - label.Value = strings.Map(sanitize, label.Value) - if label.Value != "" { - tags = append(tags, fmt.Sprintf("%s:%s", label.Name, label.Value)) - } else { - tags = append(tags, label.Name) - } - } - - return flatKey, tags -} diff --git a/vendor/github.com/armon/go-metrics/inmem.go b/vendor/github.com/armon/go-metrics/inmem.go deleted file mode 100644 index 4e2d6a709..000000000 --- a/vendor/github.com/armon/go-metrics/inmem.go +++ /dev/null @@ -1,348 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "math" - "net/url" - "strings" - "sync" - "time" -) - -// InmemSink provides a MetricSink that does in-memory aggregation -// without sending metrics over a network. It can be embedded within -// an application to provide profiling information. -type InmemSink struct { - // How long is each aggregation interval - interval time.Duration - - // Retain controls how many metrics interval we keep - retain time.Duration - - // maxIntervals is the maximum length of intervals. - // It is retain / interval. - maxIntervals int - - // intervals is a slice of the retained intervals - intervals []*IntervalMetrics - intervalLock sync.RWMutex - - rateDenom float64 -} - -// IntervalMetrics stores the aggregated metrics -// for a specific interval -type IntervalMetrics struct { - sync.RWMutex - - // The start time of the interval - Interval time.Time - - // Gauges maps the key to the last set value - Gauges map[string]GaugeValue - - // Points maps the string to the list of emitted values - // from EmitKey - Points map[string][]float32 - - // Counters maps the string key to a sum of the counter - // values - Counters map[string]SampledValue - - // Samples maps the key to an AggregateSample, - // which has the rolled up view of a sample - Samples map[string]SampledValue -} - -// NewIntervalMetrics creates a new IntervalMetrics for a given interval -func NewIntervalMetrics(intv time.Time) *IntervalMetrics { - return &IntervalMetrics{ - Interval: intv, - Gauges: make(map[string]GaugeValue), - Points: make(map[string][]float32), - Counters: make(map[string]SampledValue), - Samples: make(map[string]SampledValue), - } -} - -// AggregateSample is used to hold aggregate metrics -// about a sample -type AggregateSample struct { - Count int // The count of emitted pairs - Rate float64 // The values rate per time unit (usually 1 second) - Sum float64 // The sum of values - SumSq float64 `json:"-"` // The sum of squared values - Min float64 // Minimum value - Max float64 // Maximum value - LastUpdated time.Time `json:"-"` // When value was last updated -} - -// Computes a Stddev of the values -func (a *AggregateSample) Stddev() float64 { - num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2) - div := float64(a.Count * (a.Count - 1)) - if div == 0 { - return 0 - } - return math.Sqrt(num / div) -} - -// Computes a mean of the values -func (a *AggregateSample) Mean() float64 { - if a.Count == 0 { - return 0 - } - return a.Sum / float64(a.Count) -} - -// Ingest is used to update a sample -func (a *AggregateSample) Ingest(v float64, rateDenom float64) { - a.Count++ - a.Sum += v - a.SumSq += (v * v) - if v < a.Min || a.Count == 1 { - a.Min = v - } - if v > a.Max || a.Count == 1 { - a.Max = v - } - a.Rate = float64(a.Sum) / rateDenom - a.LastUpdated = time.Now() -} - -func (a *AggregateSample) String() string { - if a.Count == 0 { - return "Count: 0" - } else if a.Stddev() == 0 { - return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated) - } else { - return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s", - a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated) - } -} - -// NewInmemSinkFromURL creates an InmemSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) { - params := u.Query() - - interval, err := time.ParseDuration(params.Get("interval")) - if err != nil { - return nil, fmt.Errorf("Bad 'interval' param: %s", err) - } - - retain, err := time.ParseDuration(params.Get("retain")) - if err != nil { - return nil, fmt.Errorf("Bad 'retain' param: %s", err) - } - - return NewInmemSink(interval, retain), nil -} - -// NewInmemSink is used to construct a new in-memory sink. -// Uses an aggregation interval and maximum retention period. -func NewInmemSink(interval, retain time.Duration) *InmemSink { - rateTimeUnit := time.Second - i := &InmemSink{ - interval: interval, - retain: retain, - maxIntervals: int(retain / interval), - rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()), - } - i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals) - return i -} - -func (i *InmemSink) SetGauge(key []string, val float32) { - i.SetGaugeWithLabels(key, val, nil) -} - -func (i *InmemSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - intv.Gauges[k] = GaugeValue{Name: name, Value: val, Labels: labels} -} - -func (i *InmemSink) EmitKey(key []string, val float32) { - k := i.flattenKey(key) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - vals := intv.Points[k] - intv.Points[k] = append(vals, val) -} - -func (i *InmemSink) IncrCounter(key []string, val float32) { - i.IncrCounterWithLabels(key, val, nil) -} - -func (i *InmemSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Counters[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Counters[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -func (i *InmemSink) AddSample(key []string, val float32) { - i.AddSampleWithLabels(key, val, nil) -} - -func (i *InmemSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Samples[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Samples[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -// Data is used to retrieve all the aggregated metrics -// Intervals may be in use, and a read lock should be acquired -func (i *InmemSink) Data() []*IntervalMetrics { - // Get the current interval, forces creation - i.getInterval() - - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - intervals := make([]*IntervalMetrics, n) - - copy(intervals[:n-1], i.intervals[:n-1]) - current := i.intervals[n-1] - - // make its own copy for current interval - intervals[n-1] = &IntervalMetrics{} - copyCurrent := intervals[n-1] - current.RLock() - *copyCurrent = *current - - copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges)) - for k, v := range current.Gauges { - copyCurrent.Gauges[k] = v - } - // saved values will be not change, just copy its link - copyCurrent.Points = make(map[string][]float32, len(current.Points)) - for k, v := range current.Points { - copyCurrent.Points[k] = v - } - copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters)) - for k, v := range current.Counters { - copyCurrent.Counters[k] = v - } - copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples)) - for k, v := range current.Samples { - copyCurrent.Samples[k] = v - } - current.RUnlock() - - return intervals -} - -func (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - return nil -} - -func (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.Lock() - defer i.intervalLock.Unlock() - - // Check for an existing interval - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - - // Add the current interval - current := NewIntervalMetrics(intv) - i.intervals = append(i.intervals, current) - n++ - - // Truncate the intervals if they are too long - if n >= i.maxIntervals { - copy(i.intervals[0:], i.intervals[n-i.maxIntervals:]) - i.intervals = i.intervals[:i.maxIntervals] - } - return current -} - -// getInterval returns the current interval to write to -func (i *InmemSink) getInterval() *IntervalMetrics { - intv := time.Now().Truncate(i.interval) - if m := i.getExistingInterval(intv); m != nil { - return m - } - return i.createInterval(intv) -} - -// Flattens the key for formatting, removes spaces -func (i *InmemSink) flattenKey(parts []string) string { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - return buf.String() -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSink) flattenKeyLabels(parts []string, labels []Label) (string, string) { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - key := buf.String() - - for _, label := range labels { - replacer.WriteString(buf, fmt.Sprintf(";%s=%s", label.Name, label.Value)) - } - - return buf.String(), key -} diff --git a/vendor/github.com/armon/go-metrics/inmem_endpoint.go b/vendor/github.com/armon/go-metrics/inmem_endpoint.go deleted file mode 100644 index 504f1b374..000000000 --- a/vendor/github.com/armon/go-metrics/inmem_endpoint.go +++ /dev/null @@ -1,118 +0,0 @@ -package metrics - -import ( - "fmt" - "net/http" - "sort" - "time" -) - -// MetricsSummary holds a roll-up of metrics info for a given interval -type MetricsSummary struct { - Timestamp string - Gauges []GaugeValue - Points []PointValue - Counters []SampledValue - Samples []SampledValue -} - -type GaugeValue struct { - Name string - Hash string `json:"-"` - Value float32 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -type PointValue struct { - Name string - Points []float32 -} - -type SampledValue struct { - Name string - Hash string `json:"-"` - *AggregateSample - Mean float64 - Stddev float64 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -// DisplayMetrics returns a summary of the metrics from the most recent finished interval. -func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - data := i.Data() - - var interval *IntervalMetrics - n := len(data) - switch { - case n == 0: - return nil, fmt.Errorf("no metric intervals have been initialized yet") - case n == 1: - // Show the current interval if it's all we have - interval = i.intervals[0] - default: - // Show the most recent finished interval if we have one - interval = i.intervals[n-2] - } - - summary := MetricsSummary{ - Timestamp: interval.Interval.Round(time.Second).UTC().String(), - Gauges: make([]GaugeValue, 0, len(interval.Gauges)), - Points: make([]PointValue, 0, len(interval.Points)), - } - - // Format and sort the output of each metric type, so it gets displayed in a - // deterministic order. - for name, points := range interval.Points { - summary.Points = append(summary.Points, PointValue{name, points}) - } - sort.Slice(summary.Points, func(i, j int) bool { - return summary.Points[i].Name < summary.Points[j].Name - }) - - for hash, value := range interval.Gauges { - value.Hash = hash - value.DisplayLabels = make(map[string]string) - for _, label := range value.Labels { - value.DisplayLabels[label.Name] = label.Value - } - value.Labels = nil - - summary.Gauges = append(summary.Gauges, value) - } - sort.Slice(summary.Gauges, func(i, j int) bool { - return summary.Gauges[i].Hash < summary.Gauges[j].Hash - }) - - summary.Counters = formatSamples(interval.Counters) - summary.Samples = formatSamples(interval.Samples) - - return summary, nil -} - -func formatSamples(source map[string]SampledValue) []SampledValue { - output := make([]SampledValue, 0, len(source)) - for hash, sample := range source { - displayLabels := make(map[string]string) - for _, label := range sample.Labels { - displayLabels[label.Name] = label.Value - } - - output = append(output, SampledValue{ - Name: sample.Name, - Hash: hash, - AggregateSample: sample.AggregateSample, - Mean: sample.AggregateSample.Mean(), - Stddev: sample.AggregateSample.Stddev(), - DisplayLabels: displayLabels, - }) - } - sort.Slice(output, func(i, j int) bool { - return output[i].Hash < output[j].Hash - }) - - return output -} diff --git a/vendor/github.com/armon/go-metrics/inmem_signal.go b/vendor/github.com/armon/go-metrics/inmem_signal.go deleted file mode 100644 index 0937f4aed..000000000 --- a/vendor/github.com/armon/go-metrics/inmem_signal.go +++ /dev/null @@ -1,117 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "io" - "os" - "os/signal" - "strings" - "sync" - "syscall" -) - -// InmemSignal is used to listen for a given signal, and when received, -// to dump the current metrics from the InmemSink to an io.Writer -type InmemSignal struct { - signal syscall.Signal - inm *InmemSink - w io.Writer - sigCh chan os.Signal - - stop bool - stopCh chan struct{} - stopLock sync.Mutex -} - -// NewInmemSignal creates a new InmemSignal which listens for a given signal, -// and dumps the current metrics out to a writer -func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal { - i := &InmemSignal{ - signal: sig, - inm: inmem, - w: w, - sigCh: make(chan os.Signal, 1), - stopCh: make(chan struct{}), - } - signal.Notify(i.sigCh, sig) - go i.run() - return i -} - -// DefaultInmemSignal returns a new InmemSignal that responds to SIGUSR1 -// and writes output to stderr. Windows uses SIGBREAK -func DefaultInmemSignal(inmem *InmemSink) *InmemSignal { - return NewInmemSignal(inmem, DefaultSignal, os.Stderr) -} - -// Stop is used to stop the InmemSignal from listening -func (i *InmemSignal) Stop() { - i.stopLock.Lock() - defer i.stopLock.Unlock() - - if i.stop { - return - } - i.stop = true - close(i.stopCh) - signal.Stop(i.sigCh) -} - -// run is a long running routine that handles signals -func (i *InmemSignal) run() { - for { - select { - case <-i.sigCh: - i.dumpStats() - case <-i.stopCh: - return - } - } -} - -// dumpStats is used to dump the data to output writer -func (i *InmemSignal) dumpStats() { - buf := bytes.NewBuffer(nil) - - data := i.inm.Data() - // Skip the last period which is still being aggregated - for j := 0; j < len(data)-1; j++ { - intv := data[j] - intv.RLock() - for _, val := range intv.Gauges { - name := i.flattenLabels(val.Name, val.Labels) - fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value) - } - for name, vals := range intv.Points { - for _, val := range vals { - fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val) - } - } - for _, agg := range intv.Counters { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - for _, agg := range intv.Samples { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - intv.RUnlock() - } - - // Write out the bytes - i.w.Write(buf.Bytes()) -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSignal) flattenLabels(name string, labels []Label) string { - buf := bytes.NewBufferString(name) - replacer := strings.NewReplacer(" ", "_", ":", "_") - - for _, label := range labels { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, label.Value) - } - - return buf.String() -} diff --git a/vendor/github.com/armon/go-metrics/metrics.go b/vendor/github.com/armon/go-metrics/metrics.go deleted file mode 100644 index cf9def748..000000000 --- a/vendor/github.com/armon/go-metrics/metrics.go +++ /dev/null @@ -1,278 +0,0 @@ -package metrics - -import ( - "runtime" - "strings" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -type Label struct { - Name string - Value string -} - -func (m *Metrics) SetGauge(key []string, val float32) { - m.SetGaugeWithLabels(key, val, nil) -} - -func (m *Metrics) SetGaugeWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" { - if m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } else if m.EnableHostname { - key = insert(0, m.HostName, key) - } - } - if m.EnableTypePrefix { - key = insert(0, "gauge", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.SetGaugeWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) EmitKey(key []string, val float32) { - if m.EnableTypePrefix { - key = insert(0, "kv", key) - } - if m.ServiceName != "" { - key = insert(0, m.ServiceName, key) - } - allowed, _ := m.allowMetric(key, nil) - if !allowed { - return - } - m.sink.EmitKey(key, val) -} - -func (m *Metrics) IncrCounter(key []string, val float32) { - m.IncrCounterWithLabels(key, val, nil) -} - -func (m *Metrics) IncrCounterWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "counter", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.IncrCounterWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) AddSample(key []string, val float32) { - m.AddSampleWithLabels(key, val, nil) -} - -func (m *Metrics) AddSampleWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "sample", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.AddSampleWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) MeasureSince(key []string, start time.Time) { - m.MeasureSinceWithLabels(key, start, nil) -} - -func (m *Metrics) MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "timer", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - now := time.Now() - elapsed := now.Sub(start) - msec := float32(elapsed.Nanoseconds()) / float32(m.TimerGranularity) - m.sink.AddSampleWithLabels(key, msec, labelsFiltered) -} - -// UpdateFilter overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilter(allow, block []string) { - m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels) -} - -// UpdateFilterAndLabels overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - m.filterLock.Lock() - defer m.filterLock.Unlock() - - m.AllowedPrefixes = allow - m.BlockedPrefixes = block - - if allowedLabels == nil { - // Having a white list means we take only elements from it - m.allowedLabels = nil - } else { - m.allowedLabels = make(map[string]bool) - for _, v := range allowedLabels { - m.allowedLabels[v] = true - } - } - m.blockedLabels = make(map[string]bool) - for _, v := range blockedLabels { - m.blockedLabels[v] = true - } - m.AllowedLabels = allowedLabels - m.BlockedLabels = blockedLabels - - m.filter = iradix.New() - for _, prefix := range m.AllowedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), true) - } - for _, prefix := range m.BlockedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), false) - } -} - -// labelIsAllowed return true if a should be included in metric -// the caller should lock m.filterLock while calling this method -func (m *Metrics) labelIsAllowed(label *Label) bool { - labelName := (*label).Name - if m.blockedLabels != nil { - _, ok := m.blockedLabels[labelName] - if ok { - // If present, let's remove this label - return false - } - } - if m.allowedLabels != nil { - _, ok := m.allowedLabels[labelName] - return ok - } - // Allow by default - return true -} - -// filterLabels return only allowed labels -// the caller should lock m.filterLock while calling this method -func (m *Metrics) filterLabels(labels []Label) []Label { - if labels == nil { - return nil - } - toReturn := labels[:0] - for _, label := range labels { - if m.labelIsAllowed(&label) { - toReturn = append(toReturn, label) - } - } - return toReturn -} - -// Returns whether the metric should be allowed based on configured prefix filters -// Also return the applicable labels -func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) { - m.filterLock.RLock() - defer m.filterLock.RUnlock() - - if m.filter == nil || m.filter.Len() == 0 { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - _, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, "."))) - if !ok { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - return allowed.(bool), m.filterLabels(labels) -} - -// Periodically collects runtime stats to publish -func (m *Metrics) collectStats() { - for { - time.Sleep(m.ProfileInterval) - m.emitRuntimeStats() - } -} - -// Emits various runtime statsitics -func (m *Metrics) emitRuntimeStats() { - // Export number of Goroutines - numRoutines := runtime.NumGoroutine() - m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines)) - - // Export memory stats - var stats runtime.MemStats - runtime.ReadMemStats(&stats) - m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc)) - m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys)) - m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs)) - m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees)) - m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects)) - m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs)) - m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC)) - - // Export info about the last few GC runs - num := stats.NumGC - - // Handle wrap around - if num < m.lastNumGC { - m.lastNumGC = 0 - } - - // Ensure we don't scan more than 256 - if num-m.lastNumGC >= 256 { - m.lastNumGC = num - 255 - } - - for i := m.lastNumGC; i < num; i++ { - pause := stats.PauseNs[i%256] - m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause)) - } - m.lastNumGC = num -} - -// Inserts a string value at an index into the slice -func insert(i int, v string, s []string) []string { - s = append(s, "") - copy(s[i+1:], s[i:]) - s[i] = v - return s -} diff --git a/vendor/github.com/armon/go-metrics/sink.go b/vendor/github.com/armon/go-metrics/sink.go deleted file mode 100644 index 0b7d6e4be..000000000 --- a/vendor/github.com/armon/go-metrics/sink.go +++ /dev/null @@ -1,115 +0,0 @@ -package metrics - -import ( - "fmt" - "net/url" -) - -// The MetricSink interface is used to transmit metrics information -// to an external system -type MetricSink interface { - // A Gauge should retain the last value it is set to - SetGauge(key []string, val float32) - SetGaugeWithLabels(key []string, val float32, labels []Label) - - // Should emit a Key/Value pair for each call - EmitKey(key []string, val float32) - - // Counters should accumulate values - IncrCounter(key []string, val float32) - IncrCounterWithLabels(key []string, val float32, labels []Label) - - // Samples are for timing information, where quantiles are used - AddSample(key []string, val float32) - AddSampleWithLabels(key []string, val float32, labels []Label) -} - -// BlackholeSink is used to just blackhole messages -type BlackholeSink struct{} - -func (*BlackholeSink) SetGauge(key []string, val float32) {} -func (*BlackholeSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) EmitKey(key []string, val float32) {} -func (*BlackholeSink) IncrCounter(key []string, val float32) {} -func (*BlackholeSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) AddSample(key []string, val float32) {} -func (*BlackholeSink) AddSampleWithLabels(key []string, val float32, labels []Label) {} - -// FanoutSink is used to sink to fanout values to multiple sinks -type FanoutSink []MetricSink - -func (fh FanoutSink) SetGauge(key []string, val float32) { - fh.SetGaugeWithLabels(key, val, nil) -} - -func (fh FanoutSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.SetGaugeWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) EmitKey(key []string, val float32) { - for _, s := range fh { - s.EmitKey(key, val) - } -} - -func (fh FanoutSink) IncrCounter(key []string, val float32) { - fh.IncrCounterWithLabels(key, val, nil) -} - -func (fh FanoutSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.IncrCounterWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) AddSample(key []string, val float32) { - fh.AddSampleWithLabels(key, val, nil) -} - -func (fh FanoutSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.AddSampleWithLabels(key, val, labels) - } -} - -// sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided -// by each sink type -type sinkURLFactoryFunc func(*url.URL) (MetricSink, error) - -// sinkRegistry supports the generic NewMetricSink function by mapping URL -// schemes to metric sink factory functions -var sinkRegistry = map[string]sinkURLFactoryFunc{ - "statsd": NewStatsdSinkFromURL, - "statsite": NewStatsiteSinkFromURL, - "inmem": NewInmemSinkFromURL, -} - -// NewMetricSinkFromURL allows a generic URL input to configure any of the -// supported sinks. The scheme of the URL identifies the type of the sink, the -// and query parameters are used to set options. -// -// "statsd://" - Initializes a StatsdSink. The host and port are passed through -// as the "addr" of the sink -// -// "statsite://" - Initializes a StatsiteSink. The host and port become the -// "addr" of the sink -// -// "inmem://" - Initializes an InmemSink. The host and port are ignored. The -// "interval" and "duration" query parameters must be specified with valid -// durations, see NewInmemSink for details. -func NewMetricSinkFromURL(urlStr string) (MetricSink, error) { - u, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - sinkURLFactoryFunc := sinkRegistry[u.Scheme] - if sinkURLFactoryFunc == nil { - return nil, fmt.Errorf( - "cannot create metric sink, unrecognized sink name: %q", u.Scheme) - } - - return sinkURLFactoryFunc(u) -} diff --git a/vendor/github.com/armon/go-metrics/start.go b/vendor/github.com/armon/go-metrics/start.go deleted file mode 100644 index 32a28c483..000000000 --- a/vendor/github.com/armon/go-metrics/start.go +++ /dev/null @@ -1,141 +0,0 @@ -package metrics - -import ( - "os" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -// Config is used to configure metrics settings -type Config struct { - ServiceName string // Prefixed with keys to separate services - HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname - EnableHostname bool // Enable prefixing gauge values with hostname - EnableHostnameLabel bool // Enable adding hostname to labels - EnableServiceLabel bool // Enable adding service to labels - EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory) - EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer") - TimerGranularity time.Duration // Granularity of timers. - ProfileInterval time.Duration // Interval to profile runtime metrics - - AllowedPrefixes []string // A list of metric prefixes to allow, with '.' as the separator - BlockedPrefixes []string // A list of metric prefixes to block, with '.' as the separator - AllowedLabels []string // A list of metric labels to allow, with '.' as the separator - BlockedLabels []string // A list of metric labels to block, with '.' as the separator - FilterDefault bool // Whether to allow metrics by default -} - -// Metrics represents an instance of a metrics sink that can -// be used to emit -type Metrics struct { - Config - lastNumGC uint32 - sink MetricSink - filter *iradix.Tree - allowedLabels map[string]bool - blockedLabels map[string]bool - filterLock sync.RWMutex // Lock filters and allowedLabels/blockedLabels access -} - -// Shared global metrics instance -var globalMetrics atomic.Value // *Metrics - -func init() { - // Initialize to a blackhole sink to avoid errors - globalMetrics.Store(&Metrics{sink: &BlackholeSink{}}) -} - -// DefaultConfig provides a sane default configuration -func DefaultConfig(serviceName string) *Config { - c := &Config{ - ServiceName: serviceName, // Use client provided service - HostName: "", - EnableHostname: true, // Enable hostname prefix - EnableRuntimeMetrics: true, // Enable runtime profiling - EnableTypePrefix: false, // Disable type prefix - TimerGranularity: time.Millisecond, // Timers are in milliseconds - ProfileInterval: time.Second, // Poll runtime every second - FilterDefault: true, // Don't filter metrics by default - } - - // Try to get the hostname - name, _ := os.Hostname() - c.HostName = name - return c -} - -// New is used to create a new instance of Metrics -func New(conf *Config, sink MetricSink) (*Metrics, error) { - met := &Metrics{} - met.Config = *conf - met.sink = sink - met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels) - - // Start the runtime collector - if conf.EnableRuntimeMetrics { - go met.collectStats() - } - return met, nil -} - -// NewGlobal is the same as New, but it assigns the metrics object to be -// used globally as well as returning it. -func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) { - metrics, err := New(conf, sink) - if err == nil { - globalMetrics.Store(metrics) - } - return metrics, err -} - -// Proxy all the methods to the globalMetrics instance -func SetGauge(key []string, val float32) { - globalMetrics.Load().(*Metrics).SetGauge(key, val) -} - -func SetGaugeWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).SetGaugeWithLabels(key, val, labels) -} - -func EmitKey(key []string, val float32) { - globalMetrics.Load().(*Metrics).EmitKey(key, val) -} - -func IncrCounter(key []string, val float32) { - globalMetrics.Load().(*Metrics).IncrCounter(key, val) -} - -func IncrCounterWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).IncrCounterWithLabels(key, val, labels) -} - -func AddSample(key []string, val float32) { - globalMetrics.Load().(*Metrics).AddSample(key, val) -} - -func AddSampleWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).AddSampleWithLabels(key, val, labels) -} - -func MeasureSince(key []string, start time.Time) { - globalMetrics.Load().(*Metrics).MeasureSince(key, start) -} - -func MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - globalMetrics.Load().(*Metrics).MeasureSinceWithLabels(key, start, labels) -} - -func UpdateFilter(allow, block []string) { - globalMetrics.Load().(*Metrics).UpdateFilter(allow, block) -} - -// UpdateFilterAndLabels set allow/block prefixes of metrics while allowedLabels -// and blockedLabels - when not nil - allow filtering of labels in order to -// block/allow globally labels (especially useful when having large number of -// values for a given label). See README.md for more information about usage. -func UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - globalMetrics.Load().(*Metrics).UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels) -} diff --git a/vendor/github.com/armon/go-metrics/statsd.go b/vendor/github.com/armon/go-metrics/statsd.go deleted file mode 100644 index 1bfffce46..000000000 --- a/vendor/github.com/armon/go-metrics/statsd.go +++ /dev/null @@ -1,184 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // statsdMaxLen is the maximum size of a packet - // to send to statsd - statsdMaxLen = 1400 -) - -// StatsdSink provides a MetricSink that can be used -// with a statsite or statsd metrics server. It uses -// only UDP packets, while StatsiteSink uses TCP. -type StatsdSink struct { - addr string - metricQueue chan string -} - -// NewStatsdSinkFromURL creates an StatsdSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsdSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsdSink(u.Host) -} - -// NewStatsdSink is used to create a new StatsdSink -func NewStatsdSink(addr string) (*StatsdSink, error) { - s := &StatsdSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsd -func (s *StatsdSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsdSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsdSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsdSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsdSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsdSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsdSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Create a buffer - buf := bytes.NewBuffer(nil) - - // Attempt to connect - sock, err = net.Dial("udp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsd! Err: %s", err) - goto WAIT - } - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Check if this would overflow the packet size - if len(metric)+buf.Len() > statsdMaxLen { - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error writing to statsd! Err: %s", err) - goto WAIT - } - } - - // Append to the buffer - buf.WriteString(metric) - - case <-ticker.C: - if buf.Len() == 0 { - continue - } - - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error flushing to statsd! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/armon/go-metrics/statsite.go b/vendor/github.com/armon/go-metrics/statsite.go deleted file mode 100644 index 6c0d284d2..000000000 --- a/vendor/github.com/armon/go-metrics/statsite.go +++ /dev/null @@ -1,172 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // We force flush the statsite metrics after this period of - // inactivity. Prevents stats from getting stuck in a buffer - // forever. - flushInterval = 100 * time.Millisecond -) - -// NewStatsiteSinkFromURL creates an StatsiteSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsiteSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsiteSink(u.Host) -} - -// StatsiteSink provides a MetricSink that can be used with a -// statsite metrics server -type StatsiteSink struct { - addr string - metricQueue chan string -} - -// NewStatsiteSink is used to create a new StatsiteSink -func NewStatsiteSink(addr string) (*StatsiteSink, error) { - s := &StatsiteSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsite -func (s *StatsiteSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsiteSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsiteSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsiteSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsiteSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsiteSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - var buffered *bufio.Writer - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Attempt to connect - sock, err = net.Dial("tcp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsite! Err: %s", err) - goto WAIT - } - - // Create a buffered writer - buffered = bufio.NewWriter(sock) - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Try to send to statsite - _, err := buffered.Write([]byte(metric)) - if err != nil { - log.Printf("[ERR] Error writing to statsite! Err: %s", err) - goto WAIT - } - case <-ticker.C: - if err := buffered.Flush(); err != nil { - log.Printf("[ERR] Error flushing to statsite! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/armon/go-radix/.gitignore b/vendor/github.com/armon/go-radix/.gitignore new file mode 100644 index 000000000..00268614f --- /dev/null +++ b/vendor/github.com/armon/go-radix/.gitignore @@ -0,0 +1,22 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe diff --git a/vendor/github.com/armon/go-radix/.travis.yml b/vendor/github.com/armon/go-radix/.travis.yml new file mode 100644 index 000000000..1a0bbea6c --- /dev/null +++ b/vendor/github.com/armon/go-radix/.travis.yml @@ -0,0 +1,3 @@ +language: go +go: + - tip diff --git a/vendor/github.com/armon/go-radix/radix.go b/vendor/github.com/armon/go-radix/radix.go index f9655a126..e2bb22eb9 100644 --- a/vendor/github.com/armon/go-radix/radix.go +++ b/vendor/github.com/armon/go-radix/radix.go @@ -44,13 +44,13 @@ func (n *node) addEdge(e edge) { n.edges.Sort() } -func (n *node) replaceEdge(e edge) { +func (n *node) updateEdge(label byte, node *node) { num := len(n.edges) idx := sort.Search(num, func(i int) bool { - return n.edges[i].label >= e.label + return n.edges[i].label >= label }) - if idx < num && n.edges[idx].label == e.label { - n.edges[idx].node = e.node + if idx < num && n.edges[idx].label == label { + n.edges[idx].node = node return } panic("replacing missing edge") @@ -198,10 +198,7 @@ func (t *Tree) Insert(s string, v interface{}) (interface{}, bool) { child := &node{ prefix: search[:commonPrefix], } - parent.replaceEdge(edge{ - label: search[0], - node: child, - }) + parent.updateEdge(search[0], child) // Restore the existing node child.addEdge(edge{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go index b6432f1a1..645df2450 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go @@ -23,28 +23,27 @@ func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { case reflect.Struct: buf.WriteString("{\n") - names := []string{} for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { + ft := v.Type().Field(i) + fv := v.Field(i) + + if ft.Name[0:1] == strings.ToLower(ft.Name[0:1]) { continue // ignore unexported fields } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { + if (fv.Kind() == reflect.Ptr || fv.Kind() == reflect.Slice) && fv.IsNil() { continue // ignore unset fields } - names = append(names, name) - } - for i, n := range names { - val := v.FieldByName(n) buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - stringValue(val, indent+2, buf) + buf.WriteString(ft.Name + ": ") - if i < len(names)-1 { - buf.WriteString(",\n") + if tag := ft.Tag.Get("sensitive"); tag == "true" { + buf.WriteString("") + } else { + stringValue(fv, indent+2, buf) } + + buf.WriteString(",\n") } buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go index 788fe6e27..709605384 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go @@ -15,6 +15,12 @@ type Config struct { Endpoint string SigningRegion string SigningName string + + // States that the signing name did not come from a modeled source but + // was derived based on other data. Used by service client constructors + // to determine if the signin name can be overridden based on metadata the + // service has. + SigningNameDerived bool } // ConfigProvider provides a generic way for a service client to receive @@ -85,6 +91,6 @@ func (c *Client) AddDebugHandlers() { return } - c.Handlers.Send.PushFrontNamed(request.NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) - c.Handlers.Send.PushBackNamed(request.NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) + c.Handlers.Send.PushFrontNamed(LogHTTPRequestHandler) + c.Handlers.Send.PushBackNamed(LogHTTPResponseHandler) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go index 1313478f2..a397b0d04 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go @@ -1,11 +1,11 @@ package client import ( - "math/rand" - "sync" + "strconv" "time" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/sdkrand" ) // DefaultRetryer implements basic retry logic using exponential backoff for @@ -15,11 +15,11 @@ import ( // the MaxRetries method: // // type retryer struct { -// service.DefaultRetryer +// client.DefaultRetryer // } // // // This implementation always has 100 max retries -// func (d retryer) MaxRetries() uint { return 100 } +// func (d retryer) MaxRetries() int { return 100 } type DefaultRetryer struct { NumMaxRetries int } @@ -30,25 +30,27 @@ func (d DefaultRetryer) MaxRetries() int { return d.NumMaxRetries } -var seededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) - // RetryRules returns the delay duration before retrying this request again func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { // Set the upper limit of delay in retrying at ~five minutes minTime := 30 throttle := d.shouldThrottle(r) if throttle { + if delay, ok := getRetryDelay(r); ok { + return delay + } + minTime = 500 } retryCount := r.RetryCount - if retryCount > 13 { - retryCount = 13 - } else if throttle && retryCount > 8 { + if throttle && retryCount > 8 { retryCount = 8 + } else if retryCount > 13 { + retryCount = 13 } - delay := (1 << uint(retryCount)) * (seededRand.Intn(minTime) + minTime) + delay := (1 << uint(retryCount)) * (sdkrand.SeededRand.Intn(minTime) + minTime) return time.Duration(delay) * time.Millisecond } @@ -60,7 +62,7 @@ func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { return *r.Retryable } - if r.HTTPResponse.StatusCode >= 500 { + if r.HTTPResponse.StatusCode >= 500 && r.HTTPResponse.StatusCode != 501 { return true } return r.IsErrorRetryable() || d.shouldThrottle(r) @@ -68,29 +70,47 @@ func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { // ShouldThrottle returns true if the request should be throttled. func (d DefaultRetryer) shouldThrottle(r *request.Request) bool { - if r.HTTPResponse.StatusCode == 502 || - r.HTTPResponse.StatusCode == 503 || - r.HTTPResponse.StatusCode == 504 { - return true + switch r.HTTPResponse.StatusCode { + case 429: + case 502: + case 503: + case 504: + default: + return r.IsErrorThrottle() } - return r.IsErrorThrottle() -} -// lockedSource is a thread-safe implementation of rand.Source -type lockedSource struct { - lk sync.Mutex - src rand.Source + return true } -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() - return +// This will look in the Retry-After header, RFC 7231, for how long +// it will wait before attempting another request +func getRetryDelay(r *request.Request) (time.Duration, bool) { + if !canUseRetryAfterHeader(r) { + return 0, false + } + + delayStr := r.HTTPResponse.Header.Get("Retry-After") + if len(delayStr) == 0 { + return 0, false + } + + delay, err := strconv.Atoi(delayStr) + if err != nil { + return 0, false + } + + return time.Duration(delay) * time.Second, true } -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() +// Will look at the status code to see if the retry header pertains to +// the status code. +func canUseRetryAfterHeader(r *request.Request) bool { + switch r.HTTPResponse.StatusCode { + case 429: + case 503: + default: + return false + } + + return true } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go index 1f39c91f2..ce9fb896d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go @@ -44,22 +44,57 @@ func (reader *teeReaderCloser) Close() error { return reader.Source.Close() } +// LogHTTPRequestHandler is a SDK request handler to log the HTTP request sent +// to a service. Will include the HTTP request body if the LogLevel of the +// request matches LogDebugWithHTTPBody. +var LogHTTPRequestHandler = request.NamedHandler{ + Name: "awssdk.client.LogRequest", + Fn: logRequest, +} + func logRequest(r *request.Request) { logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) + bodySeekable := aws.IsReaderSeekable(r.Body) + + b, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) + r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) return } if logBody { + if !bodySeekable { + r.SetReaderBody(aws.ReadSeekCloser(r.HTTPRequest.Body)) + } // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's // Body as a NoOpCloser and will not be reset after read by the HTTP // client reader. r.ResetBody() } - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody))) + r.Config.Logger.Log(fmt.Sprintf(logReqMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) +} + +// LogHTTPRequestHeaderHandler is a SDK request handler to log the HTTP request sent +// to a service. Will only log the HTTP request's headers. The request payload +// will not be read. +var LogHTTPRequestHeaderHandler = request.NamedHandler{ + Name: "awssdk.client.LogRequestHeader", + Fn: logRequestHeader, +} + +func logRequestHeader(r *request.Request) { + b, err := httputil.DumpRequestOut(r.HTTPRequest, false) + if err != nil { + r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) + return + } + + r.Config.Logger.Log(fmt.Sprintf(logReqMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) } const logRespMsg = `DEBUG: Response %s/%s Details: @@ -72,27 +107,44 @@ const logRespErrMsg = `DEBUG ERROR: Response %s/%s: %s -----------------------------------------------------` +// LogHTTPResponseHandler is a SDK request handler to log the HTTP response +// received from a service. Will include the HTTP response body if the LogLevel +// of the request matches LogDebugWithHTTPBody. +var LogHTTPResponseHandler = request.NamedHandler{ + Name: "awssdk.client.LogResponse", + Fn: logResponse, +} + func logResponse(r *request.Request) { lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, + + logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) + if logBody { + r.HTTPResponse.Body = &teeReaderCloser{ + Reader: io.TeeReader(r.HTTPResponse.Body, lw), + Source: r.HTTPResponse.Body, + } } handlerFn := func(req *request.Request) { - body, err := httputil.DumpResponse(req.HTTPResponse, false) + b, err := httputil.DumpResponse(req.HTTPResponse, false) if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, + req.ClientInfo.ServiceName, req.Operation.Name, err)) return } - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - lw.Logger.Log(fmt.Sprintf(logRespMsg, req.ClientInfo.ServiceName, req.Operation.Name, string(body))) - if req.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { + lw.Logger.Log(fmt.Sprintf(logRespMsg, + req.ClientInfo.ServiceName, req.Operation.Name, string(b))) + + if logBody { + b, err := ioutil.ReadAll(lw.buf) + if err != nil { + lw.Logger.Log(fmt.Sprintf(logRespErrMsg, + req.ClientInfo.ServiceName, req.Operation.Name, err)) + return + } + lw.Logger.Log(string(b)) } } @@ -106,3 +158,27 @@ func logResponse(r *request.Request) { Name: handlerName, Fn: handlerFn, }) } + +// LogHTTPResponseHeaderHandler is a SDK request handler to log the HTTP +// response received from a service. Will only log the HTTP response's headers. +// The response payload will not be read. +var LogHTTPResponseHeaderHandler = request.NamedHandler{ + Name: "awssdk.client.LogResponseHeader", + Fn: logResponseHeader, +} + +func logResponseHeader(r *request.Request) { + if r.Config.Logger == nil { + return + } + + b, err := httputil.DumpResponse(r.HTTPResponse, false) + if err != nil { + r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, + r.ClientInfo.ServiceName, r.Operation.Name, err)) + return + } + + r.Config.Logger.Log(fmt.Sprintf(logRespMsg, + r.ClientInfo.ServiceName, r.Operation.Name, string(b))) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go index 4778056dd..920e9fddf 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go @@ -3,6 +3,7 @@ package metadata // ClientInfo wraps immutable data from the client.Client structure. type ClientInfo struct { ServiceName string + ServiceID string APIVersion string Endpoint string SigningName string diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go index d1f31f1c6..10634d173 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -18,7 +18,7 @@ const UseServiceDefaultRetries = -1 type RequestRetryer interface{} // A Config provides service configuration for service clients. By default, -// all clients will use the defaults.DefaultConfig tructure. +// all clients will use the defaults.DefaultConfig structure. // // // Create Session with MaxRetry configuration to be shared by multiple // // service clients. @@ -45,8 +45,8 @@ type Config struct { // that overrides the default generated endpoint for a client. Set this // to `""` to use the default generated endpoint. // - // @note You must still provide a `Region` value when specifying an - // endpoint for a client. + // Note: You must still provide a `Region` value when specifying an + // endpoint for a client. Endpoint *string // The resolver to use for looking up endpoints for AWS service clients @@ -65,8 +65,8 @@ type Config struct { // noted. A full list of regions is found in the "Regions and Endpoints" // document. // - // @see http://docs.aws.amazon.com/general/latest/gr/rande.html - // AWS Regions and Endpoints + // See http://docs.aws.amazon.com/general/latest/gr/rande.html for AWS + // Regions and Endpoints. Region *string // Set this to `true` to disable SSL when sending requests. Defaults @@ -95,7 +95,7 @@ type Config struct { // recoverable failures. // // When nil or the value does not implement the request.Retryer interface, - // the request.DefaultRetryer will be used. + // the client.DefaultRetryer will be used. // // When both Retryer and MaxRetries are non-nil, the former is used and // the latter ignored. @@ -120,9 +120,10 @@ type Config struct { // will use virtual hosted bucket addressing when possible // (`http://BUCKET.s3.amazonaws.com/KEY`). // - // @note This configuration option is specific to the Amazon S3 service. - // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // Amazon S3: Virtual Hosting of Buckets + // Note: This configuration option is specific to the Amazon S3 service. + // + // See http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html + // for Amazon S3: Virtual Hosting of Buckets S3ForcePathStyle *bool // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` @@ -151,6 +152,15 @@ type Config struct { // with accelerate. S3UseAccelerate *bool + // S3DisableContentMD5Validation config option is temporarily disabled, + // For S3 GetObject API calls, #1837. + // + // Set this to `true` to disable the S3 service client from automatically + // adding the ContentMD5 to S3 Object Put and Upload API calls. This option + // will also disable the SDK from performing object ContentMD5 validation + // on GetObject API calls. + S3DisableContentMD5Validation *bool + // Set this to `true` to disable the EC2Metadata client from overriding the // default http.Client's Timeout. This is helpful if you do not want the // EC2Metadata client to create a new http.Client. This options is only @@ -168,7 +178,7 @@ type Config struct { // EC2MetadataDisableTimeoutOverride *bool - // Instructs the endpiont to be generated for a service client to + // Instructs the endpoint to be generated for a service client to // be the dual stack endpoint. The dual stack endpoint will support // both IPv4 and IPv6 addressing. // @@ -214,6 +224,28 @@ type Config struct { // Key: aws.String("//foo//bar//moo"), // }) DisableRestProtocolURICleaning *bool + + // EnableEndpointDiscovery will allow for endpoint discovery on operations that + // have the definition in its model. By default, endpoint discovery is off. + // + // Example: + // sess := session.Must(session.NewSession(&aws.Config{ + // EnableEndpointDiscovery: aws.Bool(true), + // })) + // + // svc := s3.New(sess) + // out, err := svc.GetObject(&s3.GetObjectInput { + // Bucket: aws.String("bucketname"), + // Key: aws.String("/foo/bar/moo"), + // }) + EnableEndpointDiscovery *bool + + // DisableEndpointHostPrefix will disable the SDK's behavior of prefixing + // request endpoint hosts with modeled information. + // + // Disabling this feature is useful when you want to use local endpoints + // for testing that do not support the modeled host prefix pattern. + DisableEndpointHostPrefix *bool } // NewConfig returns a new Config pointer that can be chained with builder @@ -336,6 +368,15 @@ func (c *Config) WithS3Disable100Continue(disable bool) *Config { func (c *Config) WithS3UseAccelerate(enable bool) *Config { c.S3UseAccelerate = &enable return c + +} + +// WithS3DisableContentMD5Validation sets a config +// S3DisableContentMD5Validation value returning a Config pointer for chaining. +func (c *Config) WithS3DisableContentMD5Validation(enable bool) *Config { + c.S3DisableContentMD5Validation = &enable + return c + } // WithUseDualStack sets a config UseDualStack value returning a Config @@ -359,6 +400,19 @@ func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { return c } +// WithEndpointDiscovery will set whether or not to use endpoint discovery. +func (c *Config) WithEndpointDiscovery(t bool) *Config { + c.EnableEndpointDiscovery = &t + return c +} + +// WithDisableEndpointHostPrefix will set whether or not to use modeled host prefix +// when making requests. +func (c *Config) WithDisableEndpointHostPrefix(t bool) *Config { + c.DisableEndpointHostPrefix = &t + return c +} + // MergeIn merges the passed in configs into the existing config object. func (c *Config) MergeIn(cfgs ...*Config) { for _, other := range cfgs { @@ -435,6 +489,10 @@ func mergeInConfig(dst *Config, other *Config) { dst.S3UseAccelerate = other.S3UseAccelerate } + if other.S3DisableContentMD5Validation != nil { + dst.S3DisableContentMD5Validation = other.S3DisableContentMD5Validation + } + if other.UseDualStack != nil { dst.UseDualStack = other.UseDualStack } @@ -454,6 +512,14 @@ func mergeInConfig(dst *Config, other *Config) { if other.EnforceShouldRetryCheck != nil { dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck } + + if other.EnableEndpointDiscovery != nil { + dst.EnableEndpointDiscovery = other.EnableEndpointDiscovery + } + + if other.DisableEndpointHostPrefix != nil { + dst.DisableEndpointHostPrefix = other.DisableEndpointHostPrefix + } } // Copy will return a shallow copy of the Config object. If any additional diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go similarity index 58% rename from vendor/github.com/aws/aws-sdk-go/aws/context.go rename to vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go index 79f426853..2866f9a7f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/context.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go @@ -1,8 +1,8 @@ +// +build !go1.9 + package aws -import ( - "time" -) +import "time" // Context is an copy of the Go v1.7 stdlib's context.Context interface. // It is represented as a SDK interface to enable you to use the "WithContext" @@ -35,37 +35,3 @@ type Context interface { // functions. Value(key interface{}) interface{} } - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return backgroundCtx -} - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// Expects Context to always return a non-nil error if the Done channel is closed. -func SleepWithContext(ctx Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go deleted file mode 100644 index e8cf93d26..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !go1.7 - -package aws - -import "time" - -// An emptyCtx is a copy of the the Go 1.7 context.emptyCtx type. This -// is copied to provide a 1.6 and 1.5 safe version of context that is compatible -// with Go 1.7's Context. -// -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case backgroundCtx: - return "aws.BackgroundContext" - } - return "unknown empty Context" -} - -var ( - backgroundCtx = new(emptyCtx) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go deleted file mode 100644 index 064f75c92..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.7 - -package aws - -import "context" - -var ( - backgroundCtx = context.Background() -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go new file mode 100644 index 000000000..3718b26e1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go @@ -0,0 +1,11 @@ +// +build go1.9 + +package aws + +import "context" + +// Context is an alias of the Go stdlib's context.Context interface. +// It can be used within the SDK's API operation "WithContext" methods. +// +// See https://golang.org/pkg/context on how to use contexts. +type Context = context.Context diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go new file mode 100644 index 000000000..66c5945db --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go @@ -0,0 +1,56 @@ +// +build !go1.7 + +package aws + +import "time" + +// An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to +// provide a 1.6 and 1.5 safe version of context that is compatible with Go +// 1.7's Context. +// +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (*emptyCtx) Done() <-chan struct{} { + return nil +} + +func (*emptyCtx) Err() error { + return nil +} + +func (*emptyCtx) Value(key interface{}) interface{} { + return nil +} + +func (e *emptyCtx) String() string { + switch e { + case backgroundCtx: + return "aws.BackgroundContext" + } + return "unknown empty Context" +} + +var ( + backgroundCtx = new(emptyCtx) +) + +// BackgroundContext returns a context that will never be canceled, has no +// values, and no deadline. This context is used by the SDK to provide +// backwards compatibility with non-context API operations and functionality. +// +// Go 1.6 and before: +// This context function is equivalent to context.Background in the Go stdlib. +// +// Go 1.7 and later: +// The context returned will be the value returned by context.Background() +// +// See https://golang.org/pkg/context for more information on Contexts. +func BackgroundContext() Context { + return backgroundCtx +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go new file mode 100644 index 000000000..9c29f29af --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go @@ -0,0 +1,20 @@ +// +build go1.7 + +package aws + +import "context" + +// BackgroundContext returns a context that will never be canceled, has no +// values, and no deadline. This context is used by the SDK to provide +// backwards compatibility with non-context API operations and functionality. +// +// Go 1.6 and before: +// This context function is equivalent to context.Background in the Go stdlib. +// +// Go 1.7 and later: +// The context returned will be the value returned by context.Background() +// +// See https://golang.org/pkg/context for more information on Contexts. +func BackgroundContext() Context { + return context.Background() +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go b/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go new file mode 100644 index 000000000..304fd1561 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go @@ -0,0 +1,24 @@ +package aws + +import ( + "time" +) + +// SleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +// +// Expects Context to always return a non-nil error if the Done channel is closed. +func SleepWithContext(ctx Context, dur time.Duration) error { + t := time.NewTimer(dur) + defer t.Stop() + + select { + case <-t.C: + break + case <-ctx.Done(): + return ctx.Err() + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go index 3b73a7da7..ff5d58e06 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go @@ -311,6 +311,24 @@ func TimeValue(v *time.Time) time.Time { return time.Time{} } +// SecondsTimeValue converts an int64 pointer to a time.Time value +// representing seconds since Epoch or time.Time{} if the pointer is nil. +func SecondsTimeValue(v *int64) time.Time { + if v != nil { + return time.Unix((*v / 1000), 0) + } + return time.Time{} +} + +// MillisecondsTimeValue converts an int64 pointer to a time.Time value +// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. +func MillisecondsTimeValue(v *int64) time.Time { + if v != nil { + return time.Unix(0, (*v * 1000000)) + } + return time.Time{} +} + // TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". // The result is undefined if the Unix time cannot be represented by an int64. // Which includes calling TimeUnixMilli on a zero Time is undefined. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go index 495e3ef62..f8853d78a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go @@ -3,12 +3,10 @@ package corehandlers import ( "bytes" "fmt" - "io" "io/ioutil" "net/http" "net/url" "regexp" - "runtime" "strconv" "time" @@ -36,18 +34,13 @@ var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLen if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { length, _ = strconv.ParseInt(slength, 10, 64) } else { - switch body := r.Body.(type) { - case nil: - length = 0 - case lener: - length = int64(body.Len()) - case io.Seeker: - r.BodyStart, _ = body.Seek(0, 1) - end, _ := body.Seek(0, 2) - body.Seek(r.BodyStart, 0) // make sure to seek back to original location - length = end - r.BodyStart - default: - panic("Cannot get length of body, must provide `ContentLength`") + if r.Body != nil { + var err error + length, err = aws.SeekerLen(r.Body) + if err != nil { + r.Error = awserr.New(request.ErrCodeSerialization, "failed to get request body's length", err) + return + } } } @@ -60,13 +53,6 @@ var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLen } }} -// SDKVersionUserAgentHandler is a request handler for adding the SDK Version to the user agent. -var SDKVersionUserAgentHandler = request.NamedHandler{ - Name: "core.SDKVersionUserAgentHandler", - Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, - runtime.Version(), runtime.GOOS, runtime.GOARCH), -} - var reStatusCode = regexp.MustCompile(`^(\d{3})`) // ValidateReqSigHandler is a request handler to ensure that the request's @@ -86,9 +72,9 @@ var ValidateReqSigHandler = request.NamedHandler{ signedTime = r.LastSignedAt } - // 10 minutes to allow for some clock skew/delays in transmission. + // 5 minutes to allow for some clock skew/delays in transmission. // Would be improved with aws/aws-sdk-go#423 - if signedTime.Add(10 * time.Minute).After(time.Now()) { + if signedTime.Add(5 * time.Minute).After(time.Now()) { return } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go new file mode 100644 index 000000000..ab69c7a6f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go @@ -0,0 +1,37 @@ +package corehandlers + +import ( + "os" + "runtime" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// SDKVersionUserAgentHandler is a request handler for adding the SDK Version +// to the user agent. +var SDKVersionUserAgentHandler = request.NamedHandler{ + Name: "core.SDKVersionUserAgentHandler", + Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, + runtime.Version(), runtime.GOOS, runtime.GOARCH), +} + +const execEnvVar = `AWS_EXECUTION_ENV` +const execEnvUAKey = `exec-env` + +// AddHostExecEnvUserAgentHander is a request handler appending the SDK's +// execution environment to the user agent. +// +// If the environment variable AWS_EXECUTION_ENV is set, its value will be +// appended to the user agent string. +var AddHostExecEnvUserAgentHander = request.NamedHandler{ + Name: "core.AddHostExecEnvUserAgentHander", + Fn: func(r *request.Request) { + v := os.Getenv(execEnvVar) + if len(v) == 0 { + return + } + + request.AddToUserAgent(r, execEnvUAKey+"/"+v) + }, +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go index f298d6596..3ad1e798d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go @@ -9,9 +9,7 @@ var ( // providers in the ChainProvider. // // This has been deprecated. For verbose error messaging set - // aws.Config.CredentialsChainVerboseErrors to true - // - // @readonly + // aws.Config.CredentialsChainVerboseErrors to true. ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", `no valid providers in chain. Deprecated. For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go index 42416fc2f..894bbc7f8 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go @@ -49,6 +49,8 @@ package credentials import ( + "fmt" + "github.com/aws/aws-sdk-go/aws/awserr" "sync" "time" ) @@ -64,8 +66,6 @@ import ( // Credentials: credentials.AnonymousCredentials, // }))) // // Access public S3 buckets. -// -// @readonly var AnonymousCredentials = NewStaticCredentials("", "", "") // A Value is the AWS credentials value for individual credential fields. @@ -99,6 +99,14 @@ type Provider interface { IsExpired() bool } +// An Expirer is an interface that Providers can implement to expose the expiration +// time, if known. If the Provider cannot accurately provide this info, +// it should not implement this interface. +type Expirer interface { + // The time at which the credentials are no longer valid + ExpiresAt() time.Time +} + // An ErrorProvider is a stub credentials provider that always returns an error // this is used by the SDK when construction a known provider is not possible // due to an error. @@ -158,13 +166,19 @@ func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { // IsExpired returns if the credentials are expired. func (e *Expiry) IsExpired() bool { - if e.CurrentTime == nil { - e.CurrentTime = time.Now + curTime := e.CurrentTime + if curTime == nil { + curTime = time.Now } - return e.expiration.Before(e.CurrentTime()) + return e.expiration.Before(curTime()) +} + +// ExpiresAt returns the expiration time of the credential +func (e *Expiry) ExpiresAt() time.Time { + return e.expiration } -// A Credentials provides synchronous safe retrieval of AWS credentials Value. +// A Credentials provides concurrency safe retrieval of AWS credentials Value. // Credentials will cache the credentials value until they expire. Once the value // expires the next Get will attempt to retrieve valid credentials. // @@ -178,7 +192,8 @@ func (e *Expiry) IsExpired() bool { type Credentials struct { creds Value forceRefresh bool - m sync.Mutex + + m sync.RWMutex provider Provider } @@ -201,6 +216,17 @@ func NewCredentials(provider Provider) *Credentials { // If Credentials.Expire() was called the credentials Value will be force // expired, and the next call to Get() will cause them to be refreshed. func (c *Credentials) Get() (Value, error) { + // Check the cached credentials first with just the read lock. + c.m.RLock() + if !c.isExpired() { + creds := c.creds + c.m.RUnlock() + return creds, nil + } + c.m.RUnlock() + + // Credentials are expired need to retrieve the credentials taking the full + // lock. c.m.Lock() defer c.m.Unlock() @@ -234,8 +260,8 @@ func (c *Credentials) Expire() { // If the Credentials were forced to be expired with Expire() this will // reflect that override. func (c *Credentials) IsExpired() bool { - c.m.Lock() - defer c.m.Unlock() + c.m.RLock() + defer c.m.RUnlock() return c.isExpired() } @@ -244,3 +270,23 @@ func (c *Credentials) IsExpired() bool { func (c *Credentials) isExpired() bool { return c.forceRefresh || c.provider.IsExpired() } + +// ExpiresAt provides access to the functionality of the Expirer interface of +// the underlying Provider, if it supports that interface. Otherwise, it returns +// an error. +func (c *Credentials) ExpiresAt() (time.Time, error) { + c.m.RLock() + defer c.m.RUnlock() + + expirer, ok := c.provider.(Expirer) + if !ok { + return time.Time{}, awserr.New("ProviderNotExpirer", + fmt.Sprintf("provider %s does not support ExpiresAt()", c.creds.ProviderName), + nil) + } + if c.forceRefresh { + // set expiration time to the distant past + return time.Time{}, nil + } + return expirer.ExpiresAt(), nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go index c39749524..0ed791be6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go @@ -4,7 +4,6 @@ import ( "bufio" "encoding/json" "fmt" - "path" "strings" "time" @@ -12,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/internal/sdkuri" ) // ProviderName provides a name of EC2Role provider @@ -125,7 +125,7 @@ type ec2RoleCredRespBody struct { Message string } -const iamSecurityCredsPath = "/iam/security-credentials" +const iamSecurityCredsPath = "iam/security-credentials/" // requestCredList requests a list of credentials from the EC2 service. // If there are no credentials, or there is an error making or receiving the request @@ -153,7 +153,7 @@ func requestCredList(client *ec2metadata.EC2Metadata) ([]string, error) { // If the credentials cannot be found, or there is an error reading the response // and error will be returned. func requestCred(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName)) + resp, err := client.GetMetadata(sdkuri.PathJoin(iamSecurityCredsPath, credsName)) if err != nil { return ec2RoleCredRespBody{}, awserr.New("EC2RoleRequestError", diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go index a4cec5c55..ace513138 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go @@ -65,6 +65,10 @@ type Provider struct { // // If ExpiryWindow is 0 or less it will be ignored. ExpiryWindow time.Duration + + // Optional authorization token value if set will be used as the value of + // the Authorization header of the endpoint credential request. + AuthorizationToken string } // NewProviderClient returns a credentials Provider for retrieving AWS credentials @@ -152,6 +156,9 @@ func (p *Provider) getCredentials() (*getCredentialsOutput, error) { out := &getCredentialsOutput{} req := p.Client.NewRequest(op, nil, out) req.HTTPRequest.Header.Set("Accept", "application/json") + if authToken := p.AuthorizationToken; len(authToken) != 0 { + req.HTTPRequest.Header.Set("Authorization", authToken) + } return out, req.Send() } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go index c14231a16..54c5cf733 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go @@ -12,14 +12,10 @@ const EnvProviderName = "EnvProvider" var ( // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be // found in the process's environment. - // - // @readonly ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key // can't be found in the process's environment. - // - // @readonly ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) ) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go new file mode 100644 index 000000000..1980c8c14 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go @@ -0,0 +1,425 @@ +/* +Package processcreds is a credential Provider to retrieve `credential_process` +credentials. + +WARNING: The following describes a method of sourcing credentials from an external +process. This can potentially be dangerous, so proceed with caution. Other +credential providers should be preferred if at all possible. If using this +option, you should make sure that the config file is as locked down as possible +using security best practices for your operating system. + +You can use credentials from a `credential_process` in a variety of ways. + +One way is to setup your shared config file, located in the default +location, with the `credential_process` key and the command you want to be +called. You also need to set the AWS_SDK_LOAD_CONFIG environment variable +(e.g., `export AWS_SDK_LOAD_CONFIG=1`) to use the shared config file. + + [default] + credential_process = /command/to/call + +Creating a new session will use the credential process to retrieve credentials. +NOTE: If there are credentials in the profile you are using, the credential +process will not be used. + + // Initialize a session to load credentials. + sess, _ := session.NewSession(&aws.Config{ + Region: aws.String("us-east-1")}, + ) + + // Create S3 service client to use the credentials. + svc := s3.New(sess) + +Another way to use the `credential_process` method is by using +`credentials.NewCredentials()` and providing a command to be executed to +retrieve credentials: + + // Create credentials using the ProcessProvider. + creds := processcreds.NewCredentials("/path/to/command") + + // Create service client value configured for credentials. + svc := s3.New(sess, &aws.Config{Credentials: creds}) + +You can set a non-default timeout for the `credential_process` with another +constructor, `credentials.NewCredentialsTimeout()`, providing the timeout. To +set a one minute timeout: + + // Create credentials using the ProcessProvider. + creds := processcreds.NewCredentialsTimeout( + "/path/to/command", + time.Duration(500) * time.Millisecond) + +If you need more control, you can set any configurable options in the +credentials using one or more option functions. For example, you can set a two +minute timeout, a credential duration of 60 minutes, and a maximum stdout +buffer size of 2k. + + creds := processcreds.NewCredentials( + "/path/to/command", + func(opt *ProcessProvider) { + opt.Timeout = time.Duration(2) * time.Minute + opt.Duration = time.Duration(60) * time.Minute + opt.MaxBufSize = 2048 + }) + +You can also use your own `exec.Cmd`: + + // Create an exec.Cmd + myCommand := exec.Command("/path/to/command") + + // Create credentials using your exec.Cmd and custom timeout + creds := processcreds.NewCredentialsCommand( + myCommand, + func(opt *processcreds.ProcessProvider) { + opt.Timeout = time.Duration(1) * time.Second + }) +*/ +package processcreds + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "os" + "os/exec" + "runtime" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/credentials" +) + +const ( + // ProviderName is the name this credentials provider will label any + // returned credentials Value with. + ProviderName = `ProcessProvider` + + // ErrCodeProcessProviderParse error parsing process output + ErrCodeProcessProviderParse = "ProcessProviderParseError" + + // ErrCodeProcessProviderVersion version error in output + ErrCodeProcessProviderVersion = "ProcessProviderVersionError" + + // ErrCodeProcessProviderRequired required attribute missing in output + ErrCodeProcessProviderRequired = "ProcessProviderRequiredError" + + // ErrCodeProcessProviderExecution execution of command failed + ErrCodeProcessProviderExecution = "ProcessProviderExecutionError" + + // errMsgProcessProviderTimeout process took longer than allowed + errMsgProcessProviderTimeout = "credential process timed out" + + // errMsgProcessProviderProcess process error + errMsgProcessProviderProcess = "error in credential_process" + + // errMsgProcessProviderParse problem parsing output + errMsgProcessProviderParse = "parse failed of credential_process output" + + // errMsgProcessProviderVersion version error in output + errMsgProcessProviderVersion = "wrong version in process output (not 1)" + + // errMsgProcessProviderMissKey missing access key id in output + errMsgProcessProviderMissKey = "missing AccessKeyId in process output" + + // errMsgProcessProviderMissSecret missing secret acess key in output + errMsgProcessProviderMissSecret = "missing SecretAccessKey in process output" + + // errMsgProcessProviderPrepareCmd prepare of command failed + errMsgProcessProviderPrepareCmd = "failed to prepare command" + + // errMsgProcessProviderEmptyCmd command must not be empty + errMsgProcessProviderEmptyCmd = "command must not be empty" + + // errMsgProcessProviderPipe failed to initialize pipe + errMsgProcessProviderPipe = "failed to initialize pipe" + + // DefaultDuration is the default amount of time in minutes that the + // credentials will be valid for. + DefaultDuration = time.Duration(15) * time.Minute + + // DefaultBufSize limits buffer size from growing to an enormous + // amount due to a faulty process. + DefaultBufSize = 1024 + + // DefaultTimeout default limit on time a process can run. + DefaultTimeout = time.Duration(1) * time.Minute +) + +// ProcessProvider satisfies the credentials.Provider interface, and is a +// client to retrieve credentials from a process. +type ProcessProvider struct { + staticCreds bool + credentials.Expiry + originalCommand []string + + // Expiry duration of the credentials. Defaults to 15 minutes if not set. + Duration time.Duration + + // ExpiryWindow will allow the credentials to trigger refreshing prior to + // the credentials actually expiring. This is beneficial so race conditions + // with expiring credentials do not cause request to fail unexpectedly + // due to ExpiredTokenException exceptions. + // + // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true + // 10 seconds before the credentials are actually expired. + // + // If ExpiryWindow is 0 or less it will be ignored. + ExpiryWindow time.Duration + + // A string representing an os command that should return a JSON with + // credential information. + command *exec.Cmd + + // MaxBufSize limits memory usage from growing to an enormous + // amount due to a faulty process. + MaxBufSize int + + // Timeout limits the time a process can run. + Timeout time.Duration +} + +// NewCredentials returns a pointer to a new Credentials object wrapping the +// ProcessProvider. The credentials will expire every 15 minutes by default. +func NewCredentials(command string, options ...func(*ProcessProvider)) *credentials.Credentials { + p := &ProcessProvider{ + command: exec.Command(command), + Duration: DefaultDuration, + Timeout: DefaultTimeout, + MaxBufSize: DefaultBufSize, + } + + for _, option := range options { + option(p) + } + + return credentials.NewCredentials(p) +} + +// NewCredentialsTimeout returns a pointer to a new Credentials object with +// the specified command and timeout, and default duration and max buffer size. +func NewCredentialsTimeout(command string, timeout time.Duration) *credentials.Credentials { + p := NewCredentials(command, func(opt *ProcessProvider) { + opt.Timeout = timeout + }) + + return p +} + +// NewCredentialsCommand returns a pointer to a new Credentials object with +// the specified command, and default timeout, duration and max buffer size. +func NewCredentialsCommand(command *exec.Cmd, options ...func(*ProcessProvider)) *credentials.Credentials { + p := &ProcessProvider{ + command: command, + Duration: DefaultDuration, + Timeout: DefaultTimeout, + MaxBufSize: DefaultBufSize, + } + + for _, option := range options { + option(p) + } + + return credentials.NewCredentials(p) +} + +type credentialProcessResponse struct { + Version int + AccessKeyID string `json:"AccessKeyId"` + SecretAccessKey string + SessionToken string + Expiration *time.Time +} + +// Retrieve executes the 'credential_process' and returns the credentials. +func (p *ProcessProvider) Retrieve() (credentials.Value, error) { + out, err := p.executeCredentialProcess() + if err != nil { + return credentials.Value{ProviderName: ProviderName}, err + } + + // Serialize and validate response + resp := &credentialProcessResponse{} + if err = json.Unmarshal(out, resp); err != nil { + return credentials.Value{ProviderName: ProviderName}, awserr.New( + ErrCodeProcessProviderParse, + fmt.Sprintf("%s: %s", errMsgProcessProviderParse, string(out)), + err) + } + + if resp.Version != 1 { + return credentials.Value{ProviderName: ProviderName}, awserr.New( + ErrCodeProcessProviderVersion, + errMsgProcessProviderVersion, + nil) + } + + if len(resp.AccessKeyID) == 0 { + return credentials.Value{ProviderName: ProviderName}, awserr.New( + ErrCodeProcessProviderRequired, + errMsgProcessProviderMissKey, + nil) + } + + if len(resp.SecretAccessKey) == 0 { + return credentials.Value{ProviderName: ProviderName}, awserr.New( + ErrCodeProcessProviderRequired, + errMsgProcessProviderMissSecret, + nil) + } + + // Handle expiration + p.staticCreds = resp.Expiration == nil + if resp.Expiration != nil { + p.SetExpiration(*resp.Expiration, p.ExpiryWindow) + } + + return credentials.Value{ + ProviderName: ProviderName, + AccessKeyID: resp.AccessKeyID, + SecretAccessKey: resp.SecretAccessKey, + SessionToken: resp.SessionToken, + }, nil +} + +// IsExpired returns true if the credentials retrieved are expired, or not yet +// retrieved. +func (p *ProcessProvider) IsExpired() bool { + if p.staticCreds { + return false + } + return p.Expiry.IsExpired() +} + +// prepareCommand prepares the command to be executed. +func (p *ProcessProvider) prepareCommand() error { + + var cmdArgs []string + if runtime.GOOS == "windows" { + cmdArgs = []string{"cmd.exe", "/C"} + } else { + cmdArgs = []string{"sh", "-c"} + } + + if len(p.originalCommand) == 0 { + p.originalCommand = make([]string, len(p.command.Args)) + copy(p.originalCommand, p.command.Args) + + // check for empty command because it succeeds + if len(strings.TrimSpace(p.originalCommand[0])) < 1 { + return awserr.New( + ErrCodeProcessProviderExecution, + fmt.Sprintf( + "%s: %s", + errMsgProcessProviderPrepareCmd, + errMsgProcessProviderEmptyCmd), + nil) + } + } + + cmdArgs = append(cmdArgs, p.originalCommand...) + p.command = exec.Command(cmdArgs[0], cmdArgs[1:]...) + p.command.Env = os.Environ() + + return nil +} + +// executeCredentialProcess starts the credential process on the OS and +// returns the results or an error. +func (p *ProcessProvider) executeCredentialProcess() ([]byte, error) { + + if err := p.prepareCommand(); err != nil { + return nil, err + } + + // Setup the pipes + outReadPipe, outWritePipe, err := os.Pipe() + if err != nil { + return nil, awserr.New( + ErrCodeProcessProviderExecution, + errMsgProcessProviderPipe, + err) + } + + p.command.Stderr = os.Stderr // display stderr on console for MFA + p.command.Stdout = outWritePipe // get creds json on process's stdout + p.command.Stdin = os.Stdin // enable stdin for MFA + + output := bytes.NewBuffer(make([]byte, 0, p.MaxBufSize)) + + stdoutCh := make(chan error, 1) + go readInput( + io.LimitReader(outReadPipe, int64(p.MaxBufSize)), + output, + stdoutCh) + + execCh := make(chan error, 1) + go executeCommand(*p.command, execCh) + + finished := false + var errors []error + for !finished { + select { + case readError := <-stdoutCh: + errors = appendError(errors, readError) + finished = true + case execError := <-execCh: + err := outWritePipe.Close() + errors = appendError(errors, err) + errors = appendError(errors, execError) + if errors != nil { + return output.Bytes(), awserr.NewBatchError( + ErrCodeProcessProviderExecution, + errMsgProcessProviderProcess, + errors) + } + case <-time.After(p.Timeout): + finished = true + return output.Bytes(), awserr.NewBatchError( + ErrCodeProcessProviderExecution, + errMsgProcessProviderTimeout, + errors) // errors can be nil + } + } + + out := output.Bytes() + + if runtime.GOOS == "windows" { + // windows adds slashes to quotes + out = []byte(strings.Replace(string(out), `\"`, `"`, -1)) + } + + return out, nil +} + +// appendError conveniently checks for nil before appending slice +func appendError(errors []error, err error) []error { + if err != nil { + return append(errors, err) + } + return errors +} + +func executeCommand(cmd exec.Cmd, exec chan error) { + // Start the command + err := cmd.Start() + if err == nil { + err = cmd.Wait() + } + + exec <- err +} + +func readInput(r io.Reader, w io.Writer, read chan error) { + tee := io.TeeReader(r, w) + + _, err := ioutil.ReadAll(tee) + + if err == io.EOF { + err = nil + } + + read <- err // will only arrive here when write end of pipe is closed +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go index 51e21e0f3..e15514958 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go @@ -4,9 +4,8 @@ import ( "fmt" "os" - "github.com/go-ini/ini" - "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/internal/ini" "github.com/aws/aws-sdk-go/internal/shareddefaults" ) @@ -77,36 +76,37 @@ func (p *SharedCredentialsProvider) IsExpired() bool { // The credentials retrieved from the profile will be returned or error. Error will be // returned if it fails to read from the file, or the data is invalid. func loadProfile(filename, profile string) (Value, error) { - config, err := ini.Load(filename) + config, err := ini.OpenFile(filename) if err != nil { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) } - iniProfile, err := config.GetSection(profile) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", err) + + iniProfile, ok := config.GetSection(profile) + if !ok { + return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", nil) } - id, err := iniProfile.GetKey("aws_access_key_id") - if err != nil { + id := iniProfile.String("aws_access_key_id") + if len(id) == 0 { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), - err) + nil) } - secret, err := iniProfile.GetKey("aws_secret_access_key") - if err != nil { + secret := iniProfile.String("aws_secret_access_key") + if len(secret) == 0 { return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), nil) } // Default to empty string if not found - token := iniProfile.Key("aws_session_token") + token := iniProfile.String("aws_session_token") return Value{ - AccessKeyID: id.String(), - SecretAccessKey: secret.String(), - SessionToken: token.String(), + AccessKeyID: id, + SecretAccessKey: secret, + SessionToken: token, ProviderName: SharedCredsProviderName, }, nil } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go index 4f5dab3fc..531139e39 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go @@ -9,8 +9,6 @@ const StaticProviderName = "StaticProvider" var ( // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - // - // @readonly ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) ) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go new file mode 100644 index 000000000..152d785b3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go @@ -0,0 +1,46 @@ +// Package csm provides Client Side Monitoring (CSM) which enables sending metrics +// via UDP connection. Using the Start function will enable the reporting of +// metrics on a given port. If Start is called, with different parameters, again, +// a panic will occur. +// +// Pause can be called to pause any metrics publishing on a given port. Sessions +// that have had their handlers modified via InjectHandlers may still be used. +// However, the handlers will act as a no-op meaning no metrics will be published. +// +// Example: +// r, err := csm.Start("clientID", ":31000") +// if err != nil { +// panic(fmt.Errorf("failed starting CSM: %v", err)) +// } +// +// sess, err := session.NewSession(&aws.Config{}) +// if err != nil { +// panic(fmt.Errorf("failed loading session: %v", err)) +// } +// +// r.InjectHandlers(&sess.Handlers) +// +// client := s3.New(sess) +// resp, err := client.GetObject(&s3.GetObjectInput{ +// Bucket: aws.String("bucket"), +// Key: aws.String("key"), +// }) +// +// // Will pause monitoring +// r.Pause() +// resp, err = client.GetObject(&s3.GetObjectInput{ +// Bucket: aws.String("bucket"), +// Key: aws.String("key"), +// }) +// +// // Resume monitoring +// r.Continue() +// +// Start returns a Reporter that is used to enable or disable monitoring. If +// access to the Reporter is required later, calling Get will return the Reporter +// singleton. +// +// Example: +// r := csm.Get() +// r.Continue() +package csm diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go new file mode 100644 index 000000000..2f0c6eac9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go @@ -0,0 +1,67 @@ +package csm + +import ( + "fmt" + "sync" +) + +var ( + lock sync.Mutex +) + +// Client side metric handler names +const ( + APICallMetricHandlerName = "awscsm.SendAPICallMetric" + APICallAttemptMetricHandlerName = "awscsm.SendAPICallAttemptMetric" +) + +// Start will start the a long running go routine to capture +// client side metrics. Calling start multiple time will only +// start the metric listener once and will panic if a different +// client ID or port is passed in. +// +// Example: +// r, err := csm.Start("clientID", "127.0.0.1:8094") +// if err != nil { +// panic(fmt.Errorf("expected no error, but received %v", err)) +// } +// sess := session.NewSession() +// r.InjectHandlers(sess.Handlers) +// +// svc := s3.New(sess) +// out, err := svc.GetObject(&s3.GetObjectInput{ +// Bucket: aws.String("bucket"), +// Key: aws.String("key"), +// }) +func Start(clientID string, url string) (*Reporter, error) { + lock.Lock() + defer lock.Unlock() + + if sender == nil { + sender = newReporter(clientID, url) + } else { + if sender.clientID != clientID { + panic(fmt.Errorf("inconsistent client IDs. %q was expected, but received %q", sender.clientID, clientID)) + } + + if sender.url != url { + panic(fmt.Errorf("inconsistent URLs. %q was expected, but received %q", sender.url, url)) + } + } + + if err := connect(url); err != nil { + sender = nil + return nil, err + } + + return sender, nil +} + +// Get will return a reporter if one exists, if one does not exist, nil will +// be returned. +func Get() *Reporter { + lock.Lock() + defer lock.Unlock() + + return sender +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go new file mode 100644 index 000000000..5bacc791a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go @@ -0,0 +1,109 @@ +package csm + +import ( + "strconv" + "time" + + "github.com/aws/aws-sdk-go/aws" +) + +type metricTime time.Time + +func (t metricTime) MarshalJSON() ([]byte, error) { + ns := time.Duration(time.Time(t).UnixNano()) + return []byte(strconv.FormatInt(int64(ns/time.Millisecond), 10)), nil +} + +type metric struct { + ClientID *string `json:"ClientId,omitempty"` + API *string `json:"Api,omitempty"` + Service *string `json:"Service,omitempty"` + Timestamp *metricTime `json:"Timestamp,omitempty"` + Type *string `json:"Type,omitempty"` + Version *int `json:"Version,omitempty"` + + AttemptCount *int `json:"AttemptCount,omitempty"` + Latency *int `json:"Latency,omitempty"` + + Fqdn *string `json:"Fqdn,omitempty"` + UserAgent *string `json:"UserAgent,omitempty"` + AttemptLatency *int `json:"AttemptLatency,omitempty"` + + SessionToken *string `json:"SessionToken,omitempty"` + Region *string `json:"Region,omitempty"` + AccessKey *string `json:"AccessKey,omitempty"` + HTTPStatusCode *int `json:"HttpStatusCode,omitempty"` + XAmzID2 *string `json:"XAmzId2,omitempty"` + XAmzRequestID *string `json:"XAmznRequestId,omitempty"` + + AWSException *string `json:"AwsException,omitempty"` + AWSExceptionMessage *string `json:"AwsExceptionMessage,omitempty"` + SDKException *string `json:"SdkException,omitempty"` + SDKExceptionMessage *string `json:"SdkExceptionMessage,omitempty"` + + FinalHTTPStatusCode *int `json:"FinalHttpStatusCode,omitempty"` + FinalAWSException *string `json:"FinalAwsException,omitempty"` + FinalAWSExceptionMessage *string `json:"FinalAwsExceptionMessage,omitempty"` + FinalSDKException *string `json:"FinalSdkException,omitempty"` + FinalSDKExceptionMessage *string `json:"FinalSdkExceptionMessage,omitempty"` + + DestinationIP *string `json:"DestinationIp,omitempty"` + ConnectionReused *int `json:"ConnectionReused,omitempty"` + + AcquireConnectionLatency *int `json:"AcquireConnectionLatency,omitempty"` + ConnectLatency *int `json:"ConnectLatency,omitempty"` + RequestLatency *int `json:"RequestLatency,omitempty"` + DNSLatency *int `json:"DnsLatency,omitempty"` + TCPLatency *int `json:"TcpLatency,omitempty"` + SSLLatency *int `json:"SslLatency,omitempty"` + + MaxRetriesExceeded *int `json:"MaxRetriesExceeded,omitempty"` +} + +func (m *metric) TruncateFields() { + m.ClientID = truncateString(m.ClientID, 255) + m.UserAgent = truncateString(m.UserAgent, 256) + + m.AWSException = truncateString(m.AWSException, 128) + m.AWSExceptionMessage = truncateString(m.AWSExceptionMessage, 512) + + m.SDKException = truncateString(m.SDKException, 128) + m.SDKExceptionMessage = truncateString(m.SDKExceptionMessage, 512) + + m.FinalAWSException = truncateString(m.FinalAWSException, 128) + m.FinalAWSExceptionMessage = truncateString(m.FinalAWSExceptionMessage, 512) + + m.FinalSDKException = truncateString(m.FinalSDKException, 128) + m.FinalSDKExceptionMessage = truncateString(m.FinalSDKExceptionMessage, 512) +} + +func truncateString(v *string, l int) *string { + if v != nil && len(*v) > l { + nv := (*v)[:l] + return &nv + } + + return v +} + +func (m *metric) SetException(e metricException) { + switch te := e.(type) { + case awsException: + m.AWSException = aws.String(te.exception) + m.AWSExceptionMessage = aws.String(te.message) + case sdkException: + m.SDKException = aws.String(te.exception) + m.SDKExceptionMessage = aws.String(te.message) + } +} + +func (m *metric) SetFinalException(e metricException) { + switch te := e.(type) { + case awsException: + m.FinalAWSException = aws.String(te.exception) + m.FinalAWSExceptionMessage = aws.String(te.message) + case sdkException: + m.FinalSDKException = aws.String(te.exception) + m.FinalSDKExceptionMessage = aws.String(te.message) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go new file mode 100644 index 000000000..514fc3739 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go @@ -0,0 +1,54 @@ +package csm + +import ( + "sync/atomic" +) + +const ( + runningEnum = iota + pausedEnum +) + +var ( + // MetricsChannelSize of metrics to hold in the channel + MetricsChannelSize = 100 +) + +type metricChan struct { + ch chan metric + paused int64 +} + +func newMetricChan(size int) metricChan { + return metricChan{ + ch: make(chan metric, size), + } +} + +func (ch *metricChan) Pause() { + atomic.StoreInt64(&ch.paused, pausedEnum) +} + +func (ch *metricChan) Continue() { + atomic.StoreInt64(&ch.paused, runningEnum) +} + +func (ch *metricChan) IsPaused() bool { + v := atomic.LoadInt64(&ch.paused) + return v == pausedEnum +} + +// Push will push metrics to the metric channel if the channel +// is not paused +func (ch *metricChan) Push(m metric) bool { + if ch.IsPaused() { + return false + } + + select { + case ch.ch <- m: + return true + default: + return false + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go new file mode 100644 index 000000000..54a99280c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go @@ -0,0 +1,26 @@ +package csm + +type metricException interface { + Exception() string + Message() string +} + +type requestException struct { + exception string + message string +} + +func (e requestException) Exception() string { + return e.exception +} +func (e requestException) Message() string { + return e.message +} + +type awsException struct { + requestException +} + +type sdkException struct { + requestException +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go new file mode 100644 index 000000000..0b5571acf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go @@ -0,0 +1,260 @@ +package csm + +import ( + "encoding/json" + "net" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +const ( + // DefaultPort is used when no port is specified + DefaultPort = "31000" +) + +// Reporter will gather metrics of API requests made and +// send those metrics to the CSM endpoint. +type Reporter struct { + clientID string + url string + conn net.Conn + metricsCh metricChan + done chan struct{} +} + +var ( + sender *Reporter +) + +func connect(url string) error { + const network = "udp" + if err := sender.connect(network, url); err != nil { + return err + } + + if sender.done == nil { + sender.done = make(chan struct{}) + go sender.start() + } + + return nil +} + +func newReporter(clientID, url string) *Reporter { + return &Reporter{ + clientID: clientID, + url: url, + metricsCh: newMetricChan(MetricsChannelSize), + } +} + +func (rep *Reporter) sendAPICallAttemptMetric(r *request.Request) { + if rep == nil { + return + } + + now := time.Now() + creds, _ := r.Config.Credentials.Get() + + m := metric{ + ClientID: aws.String(rep.clientID), + API: aws.String(r.Operation.Name), + Service: aws.String(r.ClientInfo.ServiceID), + Timestamp: (*metricTime)(&now), + UserAgent: aws.String(r.HTTPRequest.Header.Get("User-Agent")), + Region: r.Config.Region, + Type: aws.String("ApiCallAttempt"), + Version: aws.Int(1), + + XAmzRequestID: aws.String(r.RequestID), + + AttemptCount: aws.Int(r.RetryCount + 1), + AttemptLatency: aws.Int(int(now.Sub(r.AttemptTime).Nanoseconds() / int64(time.Millisecond))), + AccessKey: aws.String(creds.AccessKeyID), + } + + if r.HTTPResponse != nil { + m.HTTPStatusCode = aws.Int(r.HTTPResponse.StatusCode) + } + + if r.Error != nil { + if awserr, ok := r.Error.(awserr.Error); ok { + m.SetException(getMetricException(awserr)) + } + } + + m.TruncateFields() + rep.metricsCh.Push(m) +} + +func getMetricException(err awserr.Error) metricException { + msg := err.Error() + code := err.Code() + + switch code { + case "RequestError", + "SerializationError", + request.CanceledErrorCode: + return sdkException{ + requestException{exception: code, message: msg}, + } + default: + return awsException{ + requestException{exception: code, message: msg}, + } + } +} + +func (rep *Reporter) sendAPICallMetric(r *request.Request) { + if rep == nil { + return + } + + now := time.Now() + m := metric{ + ClientID: aws.String(rep.clientID), + API: aws.String(r.Operation.Name), + Service: aws.String(r.ClientInfo.ServiceID), + Timestamp: (*metricTime)(&now), + UserAgent: aws.String(r.HTTPRequest.Header.Get("User-Agent")), + Type: aws.String("ApiCall"), + AttemptCount: aws.Int(r.RetryCount + 1), + Region: r.Config.Region, + Latency: aws.Int(int(time.Now().Sub(r.Time) / time.Millisecond)), + XAmzRequestID: aws.String(r.RequestID), + MaxRetriesExceeded: aws.Int(boolIntValue(r.RetryCount >= r.MaxRetries())), + } + + if r.HTTPResponse != nil { + m.FinalHTTPStatusCode = aws.Int(r.HTTPResponse.StatusCode) + } + + if r.Error != nil { + if awserr, ok := r.Error.(awserr.Error); ok { + m.SetFinalException(getMetricException(awserr)) + } + } + + m.TruncateFields() + + // TODO: Probably want to figure something out for logging dropped + // metrics + rep.metricsCh.Push(m) +} + +func (rep *Reporter) connect(network, url string) error { + if rep.conn != nil { + rep.conn.Close() + } + + conn, err := net.Dial(network, url) + if err != nil { + return awserr.New("UDPError", "Could not connect", err) + } + + rep.conn = conn + + return nil +} + +func (rep *Reporter) close() { + if rep.done != nil { + close(rep.done) + } + + rep.metricsCh.Pause() +} + +func (rep *Reporter) start() { + defer func() { + rep.metricsCh.Pause() + }() + + for { + select { + case <-rep.done: + rep.done = nil + return + case m := <-rep.metricsCh.ch: + // TODO: What to do with this error? Probably should just log + b, err := json.Marshal(m) + if err != nil { + continue + } + + rep.conn.Write(b) + } + } +} + +// Pause will pause the metric channel preventing any new metrics from +// being added. +func (rep *Reporter) Pause() { + lock.Lock() + defer lock.Unlock() + + if rep == nil { + return + } + + rep.close() +} + +// Continue will reopen the metric channel and allow for monitoring +// to be resumed. +func (rep *Reporter) Continue() { + lock.Lock() + defer lock.Unlock() + if rep == nil { + return + } + + if !rep.metricsCh.IsPaused() { + return + } + + rep.metricsCh.Continue() +} + +// InjectHandlers will will enable client side metrics and inject the proper +// handlers to handle how metrics are sent. +// +// Example: +// // Start must be called in order to inject the correct handlers +// r, err := csm.Start("clientID", "127.0.0.1:8094") +// if err != nil { +// panic(fmt.Errorf("expected no error, but received %v", err)) +// } +// +// sess := session.NewSession() +// r.InjectHandlers(&sess.Handlers) +// +// // create a new service client with our client side metric session +// svc := s3.New(sess) +func (rep *Reporter) InjectHandlers(handlers *request.Handlers) { + if rep == nil { + return + } + + handlers.Complete.PushFrontNamed(request.NamedHandler{ + Name: APICallMetricHandlerName, + Fn: rep.sendAPICallMetric, + }) + + handlers.CompleteAttempt.PushFrontNamed(request.NamedHandler{ + Name: APICallAttemptMetricHandlerName, + Fn: rep.sendAPICallAttemptMetric, + }) +} + +// boolIntValue return 1 for true and 0 for false. +func boolIntValue(b bool) int { + if b { + return 1 + } + + return 0 +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go index 07afe3b8e..23bb639e0 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go @@ -9,6 +9,7 @@ package defaults import ( "fmt" + "net" "net/http" "net/url" "os" @@ -23,6 +24,7 @@ import ( "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/shareddefaults" ) // A Defaults provides a collection of default values for SDK clients. @@ -72,6 +74,7 @@ func Handlers() request.Handlers { handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) handlers.Validate.AfterEachFn = request.HandlerListStopOnError handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) + handlers.Build.PushBackNamed(corehandlers.AddHostExecEnvUserAgentHander) handlers.Build.AfterEachFn = request.HandlerListStopOnError handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler) @@ -90,17 +93,28 @@ func Handlers() request.Handlers { func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { return credentials.NewCredentials(&credentials.ChainProvider{ VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credentials.EnvProvider{}, - &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, - RemoteCredProvider(*cfg, handlers), - }, + Providers: CredProviders(cfg, handlers), }) } +// CredProviders returns the slice of providers used in +// the default credential chain. +// +// For applications that need to use some other provider (for example use +// different environment variables for legacy reasons) but still fall back +// on the default chain of providers. This allows that default chaint to be +// automatically updated +func CredProviders(cfg *aws.Config, handlers request.Handlers) []credentials.Provider { + return []credentials.Provider{ + &credentials.EnvProvider{}, + &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, + RemoteCredProvider(*cfg, handlers), + } +} + const ( - httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - ecsCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" + httpProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" + httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" ) // RemoteCredProvider returns a credentials provider for the default remote @@ -110,22 +124,51 @@ func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.P return localHTTPCredProvider(cfg, handlers, u) } - if uri := os.Getenv(ecsCredsProviderEnvVar); len(uri) > 0 { - u := fmt.Sprintf("http://169.254.170.2%s", uri) + if uri := os.Getenv(shareddefaults.ECSCredsProviderEnvVar); len(uri) > 0 { + u := fmt.Sprintf("%s%s", shareddefaults.ECSContainerCredentialsURI, uri) return httpCredProvider(cfg, handlers, u) } return ec2RoleProvider(cfg, handlers) } +var lookupHostFn = net.LookupHost + +func isLoopbackHost(host string) (bool, error) { + ip := net.ParseIP(host) + if ip != nil { + return ip.IsLoopback(), nil + } + + // Host is not an ip, perform lookup + addrs, err := lookupHostFn(host) + if err != nil { + return false, err + } + for _, addr := range addrs { + if !net.ParseIP(addr).IsLoopback() { + return false, nil + } + } + + return true, nil +} + func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { var errMsg string parsed, err := url.Parse(u) if err != nil { errMsg = fmt.Sprintf("invalid URL, %v", err) - } else if host := aws.URLHostname(parsed); !(host == "localhost" || host == "127.0.0.1") { - errMsg = fmt.Sprintf("invalid host address, %q, only localhost and 127.0.0.1 are valid.", host) + } else { + host := aws.URLHostname(parsed) + if len(host) == 0 { + errMsg = "unable to parse host from local HTTP cred provider URL" + } else if isLoopback, loopbackErr := isLoopbackHost(host); loopbackErr != nil { + errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, loopbackErr) + } else if !isLoopback { + errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback hosts are allowed.", host) + } } if len(errMsg) > 0 { @@ -145,6 +188,7 @@ func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) crede return endpointcreds.NewProviderClient(cfg, handlers, u, func(p *endpointcreds.Provider) { p.ExpiryWindow = 5 * time.Minute + p.AuthorizationToken = os.Getenv(httpProviderAuthorizationEnvVar) }, ) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go index 984407a58..88e2fc707 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go @@ -4,12 +4,12 @@ import ( "encoding/json" "fmt" "net/http" - "path" "strings" "time" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/sdkuri" ) // GetMetadata uses the path provided to request information from the EC2 @@ -19,7 +19,7 @@ func (c *EC2Metadata) GetMetadata(p string) (string, error) { op := &request.Operation{ Name: "GetMetadata", HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", p), + HTTPPath: sdkuri.PathJoin("/meta-data", p), } output := &metadataOutput{} @@ -35,7 +35,7 @@ func (c *EC2Metadata) GetUserData() (string, error) { op := &request.Operation{ Name: "GetUserData", HTTPMethod: "GET", - HTTPPath: path.Join("/", "user-data"), + HTTPPath: "/user-data", } output := &metadataOutput{} @@ -56,7 +56,7 @@ func (c *EC2Metadata) GetDynamicData(p string) (string, error) { op := &request.Operation{ Name: "GetDynamicData", HTTPMethod: "GET", - HTTPPath: path.Join("/", "dynamic", p), + HTTPPath: sdkuri.PathJoin("/dynamic", p), } output := &metadataOutput{} @@ -118,6 +118,10 @@ func (c *EC2Metadata) Region() (string, error) { return "", err } + if len(resp) == 0 { + return "", awserr.New("EC2MetadataError", "invalid Region response", nil) + } + // returns region without the suffix. Eg: us-west-2a becomes us-west-2 return resp[:len(resp)-1], nil } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go index 5b4379dbd..7d1f66e4e 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go @@ -1,5 +1,10 @@ // Package ec2metadata provides the client for making API calls to the // EC2 Metadata service. +// +// This package's client can be disabled completely by setting the environment +// variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to +// true instructs the SDK to disable the EC2 Metadata client. The client cannot +// be used while the environment variable is set to true, (case insensitive). package ec2metadata import ( @@ -7,17 +12,21 @@ import ( "errors" "io" "net/http" + "os" + "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/request" ) // ServiceName is the name of the service. const ServiceName = "ec2metadata" +const disableServiceEnvVar = "AWS_EC2_METADATA_DISABLED" // A EC2Metadata is an EC2 Metadata service Client. type EC2Metadata struct { @@ -63,6 +72,7 @@ func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg, metadata.ClientInfo{ ServiceName: ServiceName, + ServiceID: ServiceName, Endpoint: endpoint, APIVersion: "latest", }, @@ -75,6 +85,21 @@ func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio svc.Handlers.Validate.Clear() svc.Handlers.Validate.PushBack(validateEndpointHandler) + // Disable the EC2 Metadata service if the environment variable is set. + // This shortcirctes the service's functionality to always fail to send + // requests. + if strings.ToLower(os.Getenv(disableServiceEnvVar)) == "true" { + svc.Handlers.Send.SwapNamed(request.NamedHandler{ + Name: corehandlers.SendHandler.Name, + Fn: func(r *request.Request) { + r.Error = awserr.New( + request.CanceledErrorCode, + "EC2 IMDS access disabled via "+disableServiceEnvVar+" env var", + nil) + }, + }) + } + // Add additional options to the service config for _, option := range opts { option(svc.Client) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go index 74f72de07..87b9ff3ff 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go @@ -84,6 +84,8 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol custAddEC2Metadata(p) custAddS3DualStack(p) custRmIotDataService(p) + custFixAppAutoscalingChina(p) + custFixAppAutoscalingUsGov(p) } return ps, nil @@ -94,7 +96,12 @@ func custAddS3DualStack(p *partition) { return } - s, ok := p.Services["s3"] + custAddDualstack(p, "s3") + custAddDualstack(p, "s3-control") +} + +func custAddDualstack(p *partition, svcName string) { + s, ok := p.Services[svcName] if !ok { return } @@ -102,7 +109,7 @@ func custAddS3DualStack(p *partition) { s.Defaults.HasDualStack = boxedTrue s.Defaults.DualStackHostname = "{service}.dualstack.{region}.{dnsSuffix}" - p.Services["s3"] = s + p.Services[svcName] = s } func custAddEC2Metadata(p *partition) { @@ -122,6 +129,54 @@ func custRmIotDataService(p *partition) { delete(p.Services, "data.iot") } +func custFixAppAutoscalingChina(p *partition) { + if p.ID != "aws-cn" { + return + } + + const serviceName = "application-autoscaling" + s, ok := p.Services[serviceName] + if !ok { + return + } + + const expectHostname = `autoscaling.{region}.amazonaws.com` + if e, a := s.Defaults.Hostname, expectHostname; e != a { + fmt.Printf("custFixAppAutoscalingChina: ignoring customization, expected %s, got %s\n", e, a) + return + } + + s.Defaults.Hostname = expectHostname + ".cn" + p.Services[serviceName] = s +} + +func custFixAppAutoscalingUsGov(p *partition) { + if p.ID != "aws-us-gov" { + return + } + + const serviceName = "application-autoscaling" + s, ok := p.Services[serviceName] + if !ok { + return + } + + if a := s.Defaults.CredentialScope.Service; a != "" { + fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty credential scope service, got %s\n", a) + return + } + + if a := s.Defaults.Hostname; a != "" { + fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty hostname, got %s\n", a) + return + } + + s.Defaults.CredentialScope.Service = "application-autoscaling" + s.Defaults.Hostname = "autoscaling.{region}.amazonaws.com" + + p.Services[serviceName] = s +} + type decodeModelError struct { awsError } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index d6d87e446..96ddf8fca 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -22,8 +22,10 @@ const ( ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). CaCentral1RegionID = "ca-central-1" // Canada (Central). EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). + EuNorth1RegionID = "eu-north-1" // EU (Stockholm). EuWest1RegionID = "eu-west-1" // EU (Ireland). EuWest2RegionID = "eu-west-2" // EU (London). + EuWest3RegionID = "eu-west-3" // EU (Paris). SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). UsEast1RegionID = "us-east-1" // US East (N. Virginia). UsEast2RegionID = "us-east-2" // US East (Ohio). @@ -33,116 +35,16 @@ const ( // AWS China partition's regions. const ( - CnNorth1RegionID = "cn-north-1" // China (Beijing). + CnNorth1RegionID = "cn-north-1" // China (Beijing). + CnNorthwest1RegionID = "cn-northwest-1" // China (Ningxia). ) // AWS GovCloud (US) partition's regions. const ( + UsGovEast1RegionID = "us-gov-east-1" // AWS GovCloud (US-East). UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). ) -// Service identifiers -const ( - AcmServiceID = "acm" // Acm. - ApigatewayServiceID = "apigateway" // Apigateway. - ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - Appstream2ServiceID = "appstream2" // Appstream2. - AthenaServiceID = "athena" // Athena. - AutoscalingServiceID = "autoscaling" // Autoscaling. - BatchServiceID = "batch" // Batch. - BudgetsServiceID = "budgets" // Budgets. - ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. - CloudformationServiceID = "cloudformation" // Cloudformation. - CloudfrontServiceID = "cloudfront" // Cloudfront. - CloudhsmServiceID = "cloudhsm" // Cloudhsm. - CloudsearchServiceID = "cloudsearch" // Cloudsearch. - CloudtrailServiceID = "cloudtrail" // Cloudtrail. - CodebuildServiceID = "codebuild" // Codebuild. - CodecommitServiceID = "codecommit" // Codecommit. - CodedeployServiceID = "codedeploy" // Codedeploy. - CodepipelineServiceID = "codepipeline" // Codepipeline. - CodestarServiceID = "codestar" // Codestar. - CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. - CognitoIdpServiceID = "cognito-idp" // CognitoIdp. - CognitoSyncServiceID = "cognito-sync" // CognitoSync. - ConfigServiceID = "config" // Config. - CurServiceID = "cur" // Cur. - DatapipelineServiceID = "datapipeline" // Datapipeline. - DevicefarmServiceID = "devicefarm" // Devicefarm. - DirectconnectServiceID = "directconnect" // Directconnect. - DiscoveryServiceID = "discovery" // Discovery. - DmsServiceID = "dms" // Dms. - DsServiceID = "ds" // Ds. - DynamodbServiceID = "dynamodb" // Dynamodb. - Ec2ServiceID = "ec2" // Ec2. - Ec2metadataServiceID = "ec2metadata" // Ec2metadata. - EcrServiceID = "ecr" // Ecr. - EcsServiceID = "ecs" // Ecs. - ElasticacheServiceID = "elasticache" // Elasticache. - ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. - ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. - ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. - ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. - ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. - EmailServiceID = "email" // Email. - EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. - EsServiceID = "es" // Es. - EventsServiceID = "events" // Events. - FirehoseServiceID = "firehose" // Firehose. - GameliftServiceID = "gamelift" // Gamelift. - GlacierServiceID = "glacier" // Glacier. - HealthServiceID = "health" // Health. - IamServiceID = "iam" // Iam. - ImportexportServiceID = "importexport" // Importexport. - InspectorServiceID = "inspector" // Inspector. - IotServiceID = "iot" // Iot. - KinesisServiceID = "kinesis" // Kinesis. - KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. - KmsServiceID = "kms" // Kms. - LambdaServiceID = "lambda" // Lambda. - LightsailServiceID = "lightsail" // Lightsail. - LogsServiceID = "logs" // Logs. - MachinelearningServiceID = "machinelearning" // Machinelearning. - MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. - MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. - MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. - ModelsLexServiceID = "models.lex" // ModelsLex. - MonitoringServiceID = "monitoring" // Monitoring. - MturkRequesterServiceID = "mturk-requester" // MturkRequester. - OpsworksServiceID = "opsworks" // Opsworks. - OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. - OrganizationsServiceID = "organizations" // Organizations. - PinpointServiceID = "pinpoint" // Pinpoint. - PollyServiceID = "polly" // Polly. - RdsServiceID = "rds" // Rds. - RedshiftServiceID = "redshift" // Redshift. - RekognitionServiceID = "rekognition" // Rekognition. - Route53ServiceID = "route53" // Route53. - Route53domainsServiceID = "route53domains" // Route53domains. - RuntimeLexServiceID = "runtime.lex" // RuntimeLex. - S3ServiceID = "s3" // S3. - SdbServiceID = "sdb" // Sdb. - ServicecatalogServiceID = "servicecatalog" // Servicecatalog. - ShieldServiceID = "shield" // Shield. - SmsServiceID = "sms" // Sms. - SnowballServiceID = "snowball" // Snowball. - SnsServiceID = "sns" // Sns. - SqsServiceID = "sqs" // Sqs. - SsmServiceID = "ssm" // Ssm. - StatesServiceID = "states" // States. - StoragegatewayServiceID = "storagegateway" // Storagegateway. - StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. - StsServiceID = "sts" // Sts. - SupportServiceID = "support" // Support. - SwfServiceID = "swf" // Swf. - TaggingServiceID = "tagging" // Tagging. - WafServiceID = "waf" // Waf. - WafRegionalServiceID = "waf-regional" // WafRegional. - WorkdocsServiceID = "workdocs" // Workdocs. - WorkspacesServiceID = "workspaces" // Workspaces. - XrayServiceID = "xray" // Xray. -) - // DefaultResolver returns an Endpoint resolver that will be able // to resolve endpoints for: AWS Standard, AWS China, and AWS GovCloud (US). // @@ -210,12 +112,18 @@ var awsPartition = partition{ "eu-central-1": region{ Description: "EU (Frankfurt)", }, + "eu-north-1": region{ + Description: "EU (Stockholm)", + }, "eu-west-1": region{ Description: "EU (Ireland)", }, "eu-west-2": region{ Description: "EU (London)", }, + "eu-west-3": region{ + Description: "EU (Paris)", + }, "sa-east-1": region{ Description: "South America (Sao Paulo)", }, @@ -233,6 +141,12 @@ var awsPartition = partition{ }, }, Services: services{ + "a4b": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "acm": service{ Endpoints: endpoints{ @@ -243,8 +157,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -252,74 +168,148 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "apigateway": service{ - + "acm-pca": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", + "api.ecr": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "api.ecr.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + "ap-northeast-2": endpoint{ + Hostname: "api.ecr.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + "ap-south-1": endpoint{ + Hostname: "api.ecr.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + "ap-southeast-1": endpoint{ + Hostname: "api.ecr.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + "ap-southeast-2": endpoint{ + Hostname: "api.ecr.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + "ca-central-1": endpoint{ + Hostname: "api.ecr.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "eu-central-1": endpoint{ + Hostname: "api.ecr.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + "eu-north-1": endpoint{ + Hostname: "api.ecr.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, + "eu-west-1": endpoint{ + Hostname: "api.ecr.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + "eu-west-2": endpoint{ + Hostname: "api.ecr.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + "eu-west-3": endpoint{ + Hostname: "api.ecr.eu-west-3.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + }, + "sa-east-1": endpoint{ + Hostname: "api.ecr.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, + "us-east-1": endpoint{ + Hostname: "api.ecr.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{ + Hostname: "api.ecr.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-1": endpoint{ + Hostname: "api.ecr.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-2": endpoint{ + Hostname: "api.ecr.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, }, }, + }, + "api.mediatailor": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "appstream2": service{ + "api.pricing": service{ Defaults: endpoint{ - Protocols: []string{"https"}, CredentialScope: credentialScope{ - Service: "appstream", + Service: "pricing", }, }, Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, + "ap-south-1": endpoint{}, + "us-east-1": endpoint{}, }, }, - "athena": service{ + "api.sagemaker": service{ - Endpoints: endpoints{ - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -330,47 +320,37 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "batch": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "budgets.amazonaws.com", + "us-east-1-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, }, + "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-1": endpoint{}, + "us-west-1-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, }, }, - "clouddirectory": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudformation": service{ + "apigateway": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -380,8 +360,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -389,37 +371,40 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "cloudfront": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "cloudfront.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, + "application-autoscaling": service{ + Defaults: endpoint{ + Hostname: "autoscaling.{region}.amazonaws.com", + Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Service: "application-autoscaling", }, }, - }, - "cloudhsm": service{ - Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "cloudsearch": service{ - + "appstream2": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Service: "appstream", + }, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -427,13 +412,11 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "cloudtrail": service{ + "appsync": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -441,45 +424,60 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "codebuild": service{ + "athena": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, }, }, - "codecommit": service{ - + "autoscaling": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "codedeploy": service{ - + "autoscaling-plans": service{ + Defaults: endpoint{ + Hostname: "autoscaling.{region}.amazonaws.com", + Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Service: "autoscaling-plans", + }, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -490,73 +488,92 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "codepipeline": service{ + "batch": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "codestar": service{ + "budgets": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-identity": service{ - + "aws-global": endpoint{ + Hostname: "budgets.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, + "ce": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "aws-global": endpoint{ + Hostname: "ce.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, }, }, - "cognito-idp": service{ + "chime": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + Defaults: endpoint{ + SSLCommonName: "service.chime.aws.amazon.com", + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "aws-global": endpoint{ + Hostname: "service.chime.aws.amazon.com", + Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, + "cloud9": service{ Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, + "ap-southeast-1": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, }, }, - "cognito-sync": service{ + "clouddirectory": service{ Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, @@ -565,7 +582,7 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "config": service{ + "cloudformation": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -575,8 +592,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -584,30 +603,41 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "cur": service{ + "cloudfront": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, Endpoints: endpoints{ - "us-east-1": endpoint{}, + "aws-global": endpoint{ + Hostname: "cloudfront.amazonaws.com", + Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, }, }, - "datapipeline": service{ + "cloudhsm": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "devicefarm": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, + "cloudhsmv2": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "cloudhsm", + }, }, - }, - "directconnect": service{ - Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -616,22 +646,32 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, + "eu-west-3": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "discovery": service{ + "cloudsearch": service{ Endpoints: endpoints{ - "us-west-2": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, - "dms": service{ + "cloudtrail": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -641,8 +681,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -650,26 +692,52 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "ds": service{ + "codebuild": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "us-east-1-fips": endpoint{ + Hostname: "codebuild-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "codebuild-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-1": endpoint{}, + "us-west-1-fips": endpoint{ + Hostname: "codebuild-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "codebuild-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, }, }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, + "codecommit": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -680,11 +748,11 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, + "eu-west-3": endpoint{}, + "fips": endpoint{ + Hostname: "codecommit-fips.ca-central-1.amazonaws.com", CredentialScope: credentialScope{ - Region: "us-east-1", + Region: "ca-central-1", }, }, "sa-east-1": endpoint{}, @@ -694,10 +762,8 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, + "codedeploy": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -706,46 +772,66 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, + "us-east-1-fips": endpoint{ + Hostname: "codedeploy-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "codedeploy-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-1": endpoint{}, + "us-west-1-fips": endpoint{ + Hostname: "codedeploy-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "codedeploy-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, }, }, }, - "ecr": service{ + "codepipeline": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "ecs": service{ + "codestar": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, @@ -758,7 +844,7 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "elasticache": service{ + "cognito-identity": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -770,14 +856,12 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "elasticbeanstalk": service{ + "cognito-idp": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -789,27 +873,44 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, - "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "elasticfilesystem": service{ + "cognito-sync": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, }, }, - "elasticloadbalancing": service{ + "comprehend": service{ Defaults: endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, + }, + "config": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -818,8 +919,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -827,75 +930,45 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "elasticmapreduce": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.{service}.{dnsSuffix}", - Protocols: []string{"http", "https"}, + "cur": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, }, + }, + "datapipeline": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, }, }, - "elastictranscoder": service{ + "datasync": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "email": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "entitlement.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "es": service{ + "dax": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -903,7 +976,13 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "events": service{ + "devicefarm": service{ + + Endpoints: endpoints{ + "us-west-2": endpoint{}, + }, + }, + "directconnect": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -913,8 +992,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -922,114 +1003,115 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "firehose": service{ + "discovery": service{ Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "gamelift": service{ + "dms": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "health": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, + "docdb": service{ Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "iam.amazonaws.com", + "eu-west-1": endpoint{ + Hostname: "rds.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + "us-east-1": endpoint{ + Hostname: "rds.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, }, - }, - }, - "importexport": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "importexport.amazonaws.com", - SignatureVersions: []string{"v2", "v4"}, + "us-east-2": endpoint{ + Hostname: "rds.us-east-2.amazonaws.com", CredentialScope: credentialScope{ - Region: "us-east-1", - Service: "IngestionService", + Region: "us-east-2", + }, + }, + "us-west-2": endpoint{ + Hostname: "rds.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", }, }, }, }, - "inspector": service{ + "ds": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "iot": service{ + "dynamodb": service{ Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "local": endpoint{ + Hostname: "localhost:8000", + Protocols: []string{"http"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, - "kinesis": service{ - + "ec2": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1038,8 +1120,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1047,15 +1131,18 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "kinesisanalytics": service{ + "ec2metadata": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, + "aws-global": endpoint{ + Hostname: "169.254.169.254/latest", + Protocols: []string{"http"}, + }, }, }, - "kms": service{ + "ecs": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1065,8 +1152,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1074,7 +1163,34 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "lambda": service{ + "elasticache": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "fips": endpoint{ + Hostname: "elasticache-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "elasticbeanstalk": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1082,20 +1198,24 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "lightsail": service{ + "elasticfilesystem": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, @@ -1103,11 +1223,14 @@ var awsPartition = partition{ "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "logs": service{ - + "elasticloadbalancing": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1116,8 +1239,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1125,24 +1250,10 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "machinelearning": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "marketplacecommerceanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "metering.marketplace": service{ + "elasticmapreduce": service{ Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, + SSLCommonName: "{region}.{service}.{dnsSuffix}", + Protocols: []string{"https"}, }, Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1151,36 +1262,55 @@ var awsPartition = partition{ "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, + "eu-central-1": endpoint{ + SSLCommonName: "{service}.{region}.{dnsSuffix}", + }, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{ + SSLCommonName: "{service}.{region}.{dnsSuffix}", + }, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "elastictranscoder": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, "us-east-1": endpoint{}, - "us-east-2": endpoint{}, "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "mobileanalytics": service{ + "email": service{ Endpoints: endpoints{ + "eu-west-1": endpoint{}, "us-east-1": endpoint{}, + "us-west-2": endpoint{}, }, }, - "models.lex": service{ + "entitlement.marketplace": service{ Defaults: endpoint{ CredentialScope: credentialScope{ - Service: "lex", + Service: "aws-marketplace", }, }, Endpoints: endpoints{ "us-east-1": endpoint{}, }, }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, + "es": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1189,26 +1319,24 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mturk-requester": service{ - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "sandbox": endpoint{ - Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", + "eu-west-3": endpoint{}, + "fips": endpoint{ + Hostname: "es-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, }, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, - "opsworks": service{ + "events": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1216,9 +1344,12 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1226,7 +1357,762 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "opsworks-cm": service{ + "firehose": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "fms": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "fsx": service{ + + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "gamelift": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "glacier": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "glue": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "greengrass": service{ + IsRegionalized: boxedTrue, + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "guardduty": service{ + IsRegionalized: boxedTrue, + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "health": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, + "iam": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-global": endpoint{ + Hostname: "iam.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, + "importexport": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-global": endpoint{ + Hostname: "importexport.amazonaws.com", + SignatureVersions: []string{"v2", "v4"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + Service: "IngestionService", + }, + }, + }, + }, + "inspector": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "iot": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "execute-api", + }, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "iotanalytics": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "kinesis": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "kinesisanalytics": service{ + + Endpoints: endpoints{ + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "kinesisvideo": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "kms": service{ + + Endpoints: endpoints{ + "ProdFips": endpoint{ + Hostname: "kms-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "lambda": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "license-manager": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "lightsail": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "logs": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "machinelearning": service{ + + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + }, + }, + "marketplacecommerceanalytics": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, + "mediaconvert": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "medialive": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "mediapackage": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "mediastore": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "metering.marketplace": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "aws-marketplace", + }, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "mgh": service{ + + Endpoints: endpoints{ + "us-west-2": endpoint{}, + }, + }, + "mobileanalytics": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, + "models.lex": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "lex", + }, + }, + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "monitoring": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "mq": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "mturk-requester": service{ + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "sandbox": endpoint{ + Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", + }, + "us-east-1": endpoint{}, + }, + }, + "neptune": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "rds.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + "ap-southeast-1": endpoint{ + Hostname: "rds.ap-southeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + "ap-southeast-2": endpoint{ + Hostname: "rds.ap-southeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + "eu-central-1": endpoint{ + Hostname: "rds.eu-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + "eu-west-1": endpoint{ + Hostname: "rds.eu-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + "eu-west-2": endpoint{ + Hostname: "rds.eu-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + "us-east-1": endpoint{ + Hostname: "rds.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{ + Hostname: "rds.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-2": endpoint{ + Hostname: "rds.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + }, + }, + "opsworks": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "opsworks-cm": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "organizations": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-global": endpoint{ + Hostname: "organizations.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, + "pinpoint": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "mobiletargeting", + }, + }, + Endpoints: endpoints{ + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "polly": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "rds": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{ + SSLCommonName: "{service}.{dnsSuffix}", + }, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "redshift": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "rekognition": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "resource-groups": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "robomaker": service{ Endpoints: endpoints{ "eu-west-1": endpoint{}, @@ -1234,39 +2120,299 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "organizations": service{ + "route53": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, Endpoints: endpoints{ "aws-global": endpoint{ - Hostname: "organizations.us-east-1.amazonaws.com", + Hostname: "route53.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, + "route53domains": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, + "route53resolver": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "runtime.lex": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "lex", + }, + }, + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "runtime.sagemaker": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "s3": service{ + PartitionEndpoint: "us-east-1", + IsRegionalized: boxedTrue, + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "s3.ap-northeast-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{ + Hostname: "s3.ap-southeast-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "ap-southeast-2": endpoint{ + Hostname: "s3.ap-southeast-2.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{ + Hostname: "s3.eu-west-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "s3-external-1": endpoint{ + Hostname: "s3-external-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "sa-east-1": endpoint{ + Hostname: "s3.sa-east-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "us-east-1": endpoint{ + Hostname: "s3.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "us-east-2": endpoint{}, + "us-west-1": endpoint{ + Hostname: "s3.us-west-1.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + "us-west-2": endpoint{ + Hostname: "s3.us-west-2.amazonaws.com", + SignatureVersions: []string{"s3", "s3v4"}, + }, + }, + }, + "s3-control": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", + }, + Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "s3-control.ap-northeast-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + "ap-northeast-2": endpoint{ + Hostname: "s3-control.ap-northeast-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + "ap-south-1": endpoint{ + Hostname: "s3-control.ap-south-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, + "ap-southeast-1": endpoint{ + Hostname: "s3-control.ap-southeast-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ap-southeast-1", + }, + }, + "ap-southeast-2": endpoint{ + Hostname: "s3-control.ap-southeast-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ap-southeast-2", + }, + }, + "ca-central-1": endpoint{ + Hostname: "s3-control.ca-central-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "eu-central-1": endpoint{ + Hostname: "s3-control.eu-central-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "eu-central-1", + }, + }, + "eu-north-1": endpoint{ + Hostname: "s3-control.eu-north-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, + "eu-west-1": endpoint{ + Hostname: "s3-control.eu-west-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "eu-west-1", + }, + }, + "eu-west-2": endpoint{ + Hostname: "s3-control.eu-west-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "eu-west-2", + }, + }, + "eu-west-3": endpoint{ + Hostname: "s3-control.eu-west-3.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "eu-west-3", + }, + }, + "sa-east-1": endpoint{ + Hostname: "s3-control.sa-east-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, + "us-east-1": endpoint{ + Hostname: "s3-control.us-east-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-1-fips": endpoint{ + Hostname: "s3-control-fips.us-east-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, CredentialScope: credentialScope{ Region: "us-east-1", }, }, + "us-east-2": endpoint{ + Hostname: "s3-control.us-east-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-east-2-fips": endpoint{ + Hostname: "s3-control-fips.us-east-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-1": endpoint{ + Hostname: "s3-control.us-west-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-1-fips": endpoint{ + Hostname: "s3-control-fips.us-west-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "us-west-2": endpoint{ + Hostname: "s3-control.us-west-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-west-2-fips": endpoint{ + Hostname: "s3-control-fips.us-west-2.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, }, }, - "pinpoint": service{ + "sdb": service{ Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, + Protocols: []string{"http", "https"}, + SignatureVersions: []string{"v2"}, }, - }, - "polly": service{ - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{ + Hostname: "sdb.amazonaws.com", + }, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, - "rds": service{ + "secretsmanager": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1278,16 +2424,39 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{dnsSuffix}", + "us-east-1": endpoint{}, + "us-east-1-fips": endpoint{ + Hostname: "secretsmanager-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, }, "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "secretsmanager-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, "us-west-1": endpoint{}, + "us-west-1-fips": endpoint{ + Hostname: "secretsmanager-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "secretsmanager-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, }, }, - "redshift": service{ + "securityhub": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, @@ -1299,6 +2468,7 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1306,138 +2476,124 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "rekognition": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "route53.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "route53domains": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "s3": service{ - PartitionEndpoint: "us-east-1", - IsRegionalized: boxedTrue, + "serverlessrepo": service{ Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", + Protocols: []string{"https"}, }, Endpoints: endpoints{ "ap-northeast-1": endpoint{ - Hostname: "s3-ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, + }, + "ap-northeast-2": endpoint{ + Protocols: []string{"https"}, + }, + "ap-south-1": endpoint{ + Protocols: []string{"https"}, }, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{ - Hostname: "s3-ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, }, "ap-southeast-2": endpoint{ - Hostname: "s3-ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, + }, + "ca-central-1": endpoint{ + Protocols: []string{"https"}, + }, + "eu-central-1": endpoint{ + Protocols: []string{"https"}, }, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, "eu-west-1": endpoint{ - Hostname: "s3-eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, }, - "eu-west-2": endpoint{}, - "s3-external-1": endpoint{ - Hostname: "s3-external-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, + "eu-west-2": endpoint{ + Protocols: []string{"https"}, }, "sa-east-1": endpoint{ - Hostname: "s3-sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, }, "us-east-1": endpoint{ - Hostname: "s3.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, + }, + "us-east-2": endpoint{ + Protocols: []string{"https"}, }, - "us-east-2": endpoint{}, "us-west-1": endpoint{ - Hostname: "s3-us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, }, "us-west-2": endpoint{ - Hostname: "s3-us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, + Protocols: []string{"https"}, }, }, }, - "sdb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v2"}, - }, + "servicecatalog": service{ + Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - Hostname: "sdb.amazonaws.com", + "us-east-1": endpoint{}, + "us-east-1-fips": endpoint{ + Hostname: "servicecatalog-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "servicecatalog-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, }, "us-west-1": endpoint{}, + "us-west-1-fips": endpoint{ + Hostname: "servicecatalog-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "servicecatalog-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, }, }, - "servicecatalog": service{ + "servicediscovery": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, "shield": service{ IsRegionalized: boxedFalse, Defaults: endpoint{ - SSLCommonName: "Shield.us-east-1.amazonaws.com", + SSLCommonName: "shield.us-east-1.amazonaws.com", Protocols: []string{"https"}, }, Endpoints: endpoints{ @@ -1447,19 +2603,36 @@ var awsPartition = partition{ "sms": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "snowball": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -1478,8 +2651,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1500,9 +2675,35 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, + "eu-west-3": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "sqs-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "sqs-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "sqs-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "sqs-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, "us-east-1": endpoint{ SSLCommonName: "queue.{dnsSuffix}", }, @@ -1521,8 +2722,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1534,10 +2737,20 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -1551,8 +2764,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1575,8 +2790,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "local": endpoint{ Hostname: "localhost:8000", Protocols: []string{"http"}, @@ -1613,8 +2830,10 @@ var awsPartition = partition{ "aws-global": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-1-fips": endpoint{ @@ -1662,8 +2881,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1681,8 +2902,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1690,6 +2913,54 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "transfer": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "translate": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-1-fips": endpoint{ + Hostname: "translate-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "us-east-2": endpoint{}, + "us-east-2-fips": endpoint{ + Hostname: "translate-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "us-west-2": endpoint{}, + "us-west-2-fips": endpoint{ + Hostname: "translate-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + }, + }, "waf": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -1707,8 +2978,12 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -1723,14 +2998,28 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "workmail": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "workspaces": service{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, @@ -1745,8 +3034,10 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1781,30 +3072,87 @@ var awscnPartition = partition{ "cn-north-1": region{ Description: "China (Beijing)", }, + "cn-northwest-1": region{ + Description: "China (Ningxia)", + }, }, Services: services{ + "api.ecr": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{ + Hostname: "api.ecr.cn-north-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + "cn-northwest-1": endpoint{ + Hostname: "api.ecr.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "apigateway": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "application-autoscaling": service{ + Defaults: endpoint{ + Hostname: "autoscaling.{region}.amazonaws.com.cn", + Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Service: "application-autoscaling", + }, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "autoscaling": service{ Defaults: endpoint{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "cloudformation": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "cloudtrail": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "codebuild": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "codedeploy": service{ + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "cognito-identity": service{ + Endpoints: endpoints{ "cn-north-1": endpoint{}, }, @@ -1812,13 +3160,29 @@ var awscnPartition = partition{ "config": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "directconnect": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "dms": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "ds": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "dynamodb": service{ @@ -1826,7 +3190,8 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "ec2": service{ @@ -1834,7 +3199,8 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "ec2metadata": service{ @@ -1848,36 +3214,68 @@ var awscnPartition = partition{ }, }, }, + "ecs": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "elasticbeanstalk": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "elasticloadbalancing": service{ Defaults: endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "elasticmapreduce": service{ Defaults: endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "es": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "events": service{ + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "firehose": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "gamelift": service{ + Endpoints: endpoints{ "cn-north-1": endpoint{}, }, @@ -1887,7 +3285,8 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "iam": service{ @@ -1903,16 +3302,35 @@ var awscnPartition = partition{ }, }, }, + "iot": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "execute-api", + }, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + }, + }, "kinesis": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "lambda": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "logs": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "monitoring": service{ @@ -1920,19 +3338,28 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "polly": service{ + + Endpoints: endpoints{ + "cn-northwest-1": endpoint{}, }, }, "rds": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "redshift": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "s3": service{ @@ -1940,6 +3367,42 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, SignatureVersions: []string{"s3v4"}, }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "s3-control": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + SignatureVersions: []string{"s3v4"}, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{ + Hostname: "s3-control.cn-north-1.amazonaws.com.cn", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "cn-north-1", + }, + }, + "cn-northwest-1": endpoint{ + Hostname: "s3-control.cn-northwest-1.amazonaws.com.cn", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "sms": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "snowball": service{ + Endpoints: endpoints{ "cn-north-1": endpoint{}, }, @@ -1949,7 +3412,8 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "sqs": service{ @@ -1958,7 +3422,22 @@ var awscnPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "ssm": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "states": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "storagegateway": service{ @@ -1975,67 +3454,137 @@ var awscnPartition = partition{ }, }, Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, }, }, "sts": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "swf": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + "tagging": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, + }, +} + +// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). +func AwsUsGovPartition() Partition { + return awsusgovPartition.Partition() +} + +var awsusgovPartition = partition{ + ID: "aws-us-gov", + Name: "AWS GovCloud (US)", + DNSSuffix: "amazonaws.com", + RegionRegex: regionRegex{ + Regexp: func() *regexp.Regexp { + reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") + return reg + }(), + }, + Defaults: endpoint{ + Hostname: "{service}.{region}.{dnsSuffix}", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + Regions: regions{ + "us-gov-east-1": region{ + Description: "AWS GovCloud (US-East)", + }, + "us-gov-west-1": region{ + Description: "AWS GovCloud (US)", + }, + }, + Services: services{ + "acm": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "api.ecr": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{ + Hostname: "api.ecr.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "api.ecr.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, + "api.sagemaker": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "apigateway": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "application-autoscaling": service{ + Defaults: endpoint{ + Hostname: "autoscaling.{region}.amazonaws.com", + CredentialScope: credentialScope{ + Service: "application-autoscaling", + }, }, - }, - "swf": service{ - Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, }, }, - "tagging": service{ + "athena": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "us-gov-west-1": endpoint{}, }, }, - }, -} - -// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). -func AwsUsGovPartition() Partition { - return awsusgovPartition.Partition() -} - -var awsusgovPartition = partition{ - ID: "aws-us-gov", - Name: "AWS GovCloud (US)", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", - }, - }, - Services: services{ "autoscaling": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, }, }, + "clouddirectory": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "cloudformation": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, @@ -2045,26 +3594,66 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "cloudhsmv2": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "cloudhsm", + }, + }, + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "cloudtrail": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "codedeploy": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-east-1-fips": endpoint{ + Hostname: "codedeploy-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "codedeploy-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "config": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "directconnect": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "dms": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "ds": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, @@ -2072,12 +3661,20 @@ var awsusgovPartition = partition{ "dynamodb": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "dynamodb.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "ec2": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, @@ -2092,8 +3689,35 @@ var awsusgovPartition = partition{ }, }, }, + "ecs": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "elasticache": service{ + Endpoints: endpoints{ + "fips": endpoint{ + Hostname: "elasticache-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "elasticbeanstalk": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "elasticfilesystem": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, @@ -2101,6 +3725,7 @@ var awsusgovPartition = partition{ "elasticloadbalancing": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, @@ -2109,13 +3734,34 @@ var awsusgovPartition = partition{ "elasticmapreduce": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, + }, + }, + }, + "es": service{ + + Endpoints: endpoints{ + "fips": endpoint{ + Hostname: "es-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, }, }, "events": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "firehose": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, @@ -2123,11 +3769,27 @@ var awsusgovPartition = partition{ "glacier": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, }, }, + "glue": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "guardduty": service{ + IsRegionalized: boxedTrue, + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "iam": service{ PartitionEndpoint: "aws-us-gov-global", IsRegionalized: boxedFalse, @@ -2141,32 +3803,82 @@ var awsusgovPartition = partition{ }, }, }, + "inspector": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "iot": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "execute-api", + }, + }, + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "kinesis": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "kms": service{ Endpoints: endpoints{ + "ProdFips": endpoint{ + Hostname: "kms-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "lambda": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "logs": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "mediaconvert": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "metering.marketplace": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "aws-marketplace", + }, + }, Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, }, "monitoring": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "polly": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, @@ -2174,11 +3886,25 @@ var awsusgovPartition = partition{ "rds": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "redshift": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "rekognition": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "runtime.sagemaker": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, @@ -2194,21 +3920,70 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "us-gov-east-1": endpoint{ + Hostname: "s3.us-gov-east-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, "us-gov-west-1": endpoint{ - Hostname: "s3-us-gov-west-1.amazonaws.com", + Hostname: "s3.us-gov-west-1.amazonaws.com", Protocols: []string{"http", "https"}, }, }, }, + "s3-control": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + SignatureVersions: []string{"s3v4"}, + }, + Endpoints: endpoints{ + "us-gov-east-1": endpoint{ + Hostname: "s3-control.us-gov-east-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-east-1-fips": endpoint{ + Hostname: "s3-control-fips.us-gov-east-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "s3-control.us-gov-west-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1-fips": endpoint{ + Hostname: "s3-control-fips.us-gov-west-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, + "sms": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "snowball": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "sns": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, @@ -2217,12 +3992,33 @@ var awsusgovPartition = partition{ "sqs": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ SSLCommonName: "{region}.queue.{dnsSuffix}", Protocols: []string{"http", "https"}, }, }, }, + "ssm": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "states": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "storagegateway": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "streams.dynamodb": service{ Defaults: endpoint{ CredentialScope: credentialScope{ @@ -2230,17 +4026,53 @@ var awsusgovPartition = partition{ }, }, Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "dynamodb.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "sts": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "swf": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "tagging": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "translate": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "translate-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, + "workspaces": service{ + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go new file mode 100644 index 000000000..000dd79ee --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go @@ -0,0 +1,141 @@ +package endpoints + +// Service identifiers +// +// Deprecated: Use client package's EndpointID value instead of these +// ServiceIDs. These IDs are not maintained, and are out of date. +const ( + A4bServiceID = "a4b" // A4b. + AcmServiceID = "acm" // Acm. + AcmPcaServiceID = "acm-pca" // AcmPca. + ApiMediatailorServiceID = "api.mediatailor" // ApiMediatailor. + ApiPricingServiceID = "api.pricing" // ApiPricing. + ApiSagemakerServiceID = "api.sagemaker" // ApiSagemaker. + ApigatewayServiceID = "apigateway" // Apigateway. + ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. + Appstream2ServiceID = "appstream2" // Appstream2. + AppsyncServiceID = "appsync" // Appsync. + AthenaServiceID = "athena" // Athena. + AutoscalingServiceID = "autoscaling" // Autoscaling. + AutoscalingPlansServiceID = "autoscaling-plans" // AutoscalingPlans. + BatchServiceID = "batch" // Batch. + BudgetsServiceID = "budgets" // Budgets. + CeServiceID = "ce" // Ce. + ChimeServiceID = "chime" // Chime. + Cloud9ServiceID = "cloud9" // Cloud9. + ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. + CloudformationServiceID = "cloudformation" // Cloudformation. + CloudfrontServiceID = "cloudfront" // Cloudfront. + CloudhsmServiceID = "cloudhsm" // Cloudhsm. + Cloudhsmv2ServiceID = "cloudhsmv2" // Cloudhsmv2. + CloudsearchServiceID = "cloudsearch" // Cloudsearch. + CloudtrailServiceID = "cloudtrail" // Cloudtrail. + CodebuildServiceID = "codebuild" // Codebuild. + CodecommitServiceID = "codecommit" // Codecommit. + CodedeployServiceID = "codedeploy" // Codedeploy. + CodepipelineServiceID = "codepipeline" // Codepipeline. + CodestarServiceID = "codestar" // Codestar. + CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. + CognitoIdpServiceID = "cognito-idp" // CognitoIdp. + CognitoSyncServiceID = "cognito-sync" // CognitoSync. + ComprehendServiceID = "comprehend" // Comprehend. + ConfigServiceID = "config" // Config. + CurServiceID = "cur" // Cur. + DatapipelineServiceID = "datapipeline" // Datapipeline. + DaxServiceID = "dax" // Dax. + DevicefarmServiceID = "devicefarm" // Devicefarm. + DirectconnectServiceID = "directconnect" // Directconnect. + DiscoveryServiceID = "discovery" // Discovery. + DmsServiceID = "dms" // Dms. + DsServiceID = "ds" // Ds. + DynamodbServiceID = "dynamodb" // Dynamodb. + Ec2ServiceID = "ec2" // Ec2. + Ec2metadataServiceID = "ec2metadata" // Ec2metadata. + EcrServiceID = "ecr" // Ecr. + EcsServiceID = "ecs" // Ecs. + ElasticacheServiceID = "elasticache" // Elasticache. + ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. + ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. + ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. + ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. + ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. + EmailServiceID = "email" // Email. + EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. + EsServiceID = "es" // Es. + EventsServiceID = "events" // Events. + FirehoseServiceID = "firehose" // Firehose. + FmsServiceID = "fms" // Fms. + GameliftServiceID = "gamelift" // Gamelift. + GlacierServiceID = "glacier" // Glacier. + GlueServiceID = "glue" // Glue. + GreengrassServiceID = "greengrass" // Greengrass. + GuarddutyServiceID = "guardduty" // Guardduty. + HealthServiceID = "health" // Health. + IamServiceID = "iam" // Iam. + ImportexportServiceID = "importexport" // Importexport. + InspectorServiceID = "inspector" // Inspector. + IotServiceID = "iot" // Iot. + IotanalyticsServiceID = "iotanalytics" // Iotanalytics. + KinesisServiceID = "kinesis" // Kinesis. + KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. + KinesisvideoServiceID = "kinesisvideo" // Kinesisvideo. + KmsServiceID = "kms" // Kms. + LambdaServiceID = "lambda" // Lambda. + LightsailServiceID = "lightsail" // Lightsail. + LogsServiceID = "logs" // Logs. + MachinelearningServiceID = "machinelearning" // Machinelearning. + MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. + MediaconvertServiceID = "mediaconvert" // Mediaconvert. + MedialiveServiceID = "medialive" // Medialive. + MediapackageServiceID = "mediapackage" // Mediapackage. + MediastoreServiceID = "mediastore" // Mediastore. + MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. + MghServiceID = "mgh" // Mgh. + MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. + ModelsLexServiceID = "models.lex" // ModelsLex. + MonitoringServiceID = "monitoring" // Monitoring. + MturkRequesterServiceID = "mturk-requester" // MturkRequester. + NeptuneServiceID = "neptune" // Neptune. + OpsworksServiceID = "opsworks" // Opsworks. + OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. + OrganizationsServiceID = "organizations" // Organizations. + PinpointServiceID = "pinpoint" // Pinpoint. + PollyServiceID = "polly" // Polly. + RdsServiceID = "rds" // Rds. + RedshiftServiceID = "redshift" // Redshift. + RekognitionServiceID = "rekognition" // Rekognition. + ResourceGroupsServiceID = "resource-groups" // ResourceGroups. + Route53ServiceID = "route53" // Route53. + Route53domainsServiceID = "route53domains" // Route53domains. + RuntimeLexServiceID = "runtime.lex" // RuntimeLex. + RuntimeSagemakerServiceID = "runtime.sagemaker" // RuntimeSagemaker. + S3ServiceID = "s3" // S3. + S3ControlServiceID = "s3-control" // S3Control. + SagemakerServiceID = "api.sagemaker" // Sagemaker. + SdbServiceID = "sdb" // Sdb. + SecretsmanagerServiceID = "secretsmanager" // Secretsmanager. + ServerlessrepoServiceID = "serverlessrepo" // Serverlessrepo. + ServicecatalogServiceID = "servicecatalog" // Servicecatalog. + ServicediscoveryServiceID = "servicediscovery" // Servicediscovery. + ShieldServiceID = "shield" // Shield. + SmsServiceID = "sms" // Sms. + SnowballServiceID = "snowball" // Snowball. + SnsServiceID = "sns" // Sns. + SqsServiceID = "sqs" // Sqs. + SsmServiceID = "ssm" // Ssm. + StatesServiceID = "states" // States. + StoragegatewayServiceID = "storagegateway" // Storagegateway. + StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. + StsServiceID = "sts" // Sts. + SupportServiceID = "support" // Support. + SwfServiceID = "swf" // Swf. + TaggingServiceID = "tagging" // Tagging. + TransferServiceID = "transfer" // Transfer. + TranslateServiceID = "translate" // Translate. + WafServiceID = "waf" // Waf. + WafRegionalServiceID = "waf-regional" // WafRegional. + WorkdocsServiceID = "workdocs" // Workdocs. + WorkmailServiceID = "workmail" // Workmail. + WorkspacesServiceID = "workspaces" // Workspaces. + XrayServiceID = "xray" // Xray. +) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go index a0e9bc454..84316b92c 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go @@ -21,12 +21,12 @@ // partitions := resolver.(endpoints.EnumPartitions).Partitions() // // for _, p := range partitions { -// fmt.Println("Regions for", p.Name) +// fmt.Println("Regions for", p.ID()) // for id, _ := range p.Regions() { // fmt.Println("*", id) // } // -// fmt.Println("Services for", p.Name) +// fmt.Println("Services for", p.ID()) // for id, _ := range p.Services() { // fmt.Println("*", id) // } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go index 9c3eedb48..f82babf6f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go @@ -35,7 +35,7 @@ type Options struct { // // If resolving an endpoint on the partition list the provided region will // be used to determine which partition's domain name pattern to the service - // endpoint ID with. If both the service and region are unkonwn and resolving + // endpoint ID with. If both the service and region are unknown and resolving // the endpoint on partition list an UnknownEndpointError error will be returned. // // If resolving and endpoint on a partition specific resolver that partition's @@ -206,10 +206,11 @@ func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) ( // enumerating over the regions in a partition. func (p Partition) Regions() map[string]Region { rs := map[string]Region{} - for id := range p.p.Regions { + for id, r := range p.p.Regions { rs[id] = Region{ - id: id, - p: p.p, + id: id, + desc: r.Description, + p: p.p, } } @@ -240,6 +241,10 @@ type Region struct { // ID returns the region's identifier. func (r Region) ID() string { return r.id } +// Description returns the region's description. The region description +// is free text, it can be empty, and it may change between SDK releases. +func (r Region) Description() string { return r.desc } + // ResolveEndpoint resolves an endpoint from the context of the region given // a service. See Partition.EndpointFor for usage and errors that can be returned. func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { @@ -284,10 +289,11 @@ func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (Resolve func (s Service) Regions() map[string]Region { rs := map[string]Region{} for id := range s.p.Services[s.id].Endpoints { - if _, ok := s.p.Regions[id]; ok { + if r, ok := s.p.Regions[id]; ok { rs[id] = Region{ - id: id, - p: s.p, + id: id, + desc: r.Description, + p: s.p, } } } @@ -347,6 +353,10 @@ type ResolvedEndpoint struct { // The service name that should be used for signing requests. SigningName string + // States that the signing name for this endpoint was derived from metadata + // passed in, but was not explicitly modeled. + SigningNameDerived bool + // The signing method that should be used for signing requests. SigningMethod string } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go index 13d968a24..ff6f76db6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go @@ -226,16 +226,20 @@ func (e endpoint) resolve(service, region, dnsSuffix string, defs []endpoint, op if len(signingRegion) == 0 { signingRegion = region } + signingName := e.CredentialScope.Service + var signingNameDerived bool if len(signingName) == 0 { signingName = service + signingNameDerived = true } return ResolvedEndpoint{ - URL: u, - SigningRegion: signingRegion, - SigningName: signingName, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), + URL: u, + SigningRegion: signingRegion, + SigningName: signingName, + SigningNameDerived: signingNameDerived, + SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), } } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go index 05e92df22..0fdfcc56e 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go @@ -16,6 +16,10 @@ import ( type CodeGenOptions struct { // Options for how the model will be decoded. DecodeModelOptions DecodeModelOptions + + // Disables code generation of the service endpoint prefix IDs defined in + // the model. + DisableGenerateServiceIDs bool } // Set combines all of the option functions together @@ -39,8 +43,16 @@ func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGe return err } + v := struct { + Resolver + CodeGenOptions + }{ + Resolver: resolver, + CodeGenOptions: opts, + } + tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl)) - if err := tmpl.ExecuteTemplate(outFile, "defaults", resolver); err != nil { + if err := tmpl.ExecuteTemplate(outFile, "defaults", v); err != nil { return fmt.Errorf("failed to execute template, %v", err) } @@ -166,15 +178,17 @@ import ( "regexp" ) - {{ template "partition consts" . }} + {{ template "partition consts" $.Resolver }} - {{ range $_, $partition := . }} + {{ range $_, $partition := $.Resolver }} {{ template "partition region consts" $partition }} {{ end }} - {{ template "service consts" . }} + {{ if not $.DisableGenerateServiceIDs -}} + {{ template "service consts" $.Resolver }} + {{- end }} - {{ template "endpoint resolvers" . }} + {{ template "endpoint resolvers" $.Resolver }} {{- end }} {{ define "partition consts" }} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/aws/aws-sdk-go/aws/errors.go index 576636168..fa06f7a8f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/errors.go @@ -5,13 +5,9 @@ import "github.com/aws/aws-sdk-go/aws/awserr" var ( // ErrMissingRegion is an error that is returned if region configuration is // not found. - // - // @readonly ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) // ErrMissingEndpoint is an error that is returned if an endpoint cannot be // resolved for a service. - // - // @readonly ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) ) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/logger.go index db87188e2..6ed15b2ec 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/logger.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/logger.go @@ -26,14 +26,14 @@ func (l *LogLevelType) Value() LogLevelType { // Matches returns true if the v LogLevel is enabled by this LogLevel. Should be // used with logging sub levels. Is safe to use on nil value LogLevelTypes. If -// LogLevel is nill, will default to LogOff comparison. +// LogLevel is nil, will default to LogOff comparison. func (l *LogLevelType) Matches(v LogLevelType) bool { c := l.Value() return c&v == v } // AtLeast returns true if this LogLevel is at least high enough to satisfies v. -// Is safe to use on nil value LogLevelTypes. If LogLevel is nill, will default +// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default // to LogOff comparison. func (l *LogLevelType) AtLeast(v LogLevelType) bool { c := l.Value() @@ -71,6 +71,12 @@ const ( // LogDebugWithRequestErrors states the SDK should log when service requests fail // to build, send, validate, or unmarshal. LogDebugWithRequestErrors + + // LogDebugWithEventStreamBody states the SDK should log EventStream + // request and response bodys. This should be used to log the EventStream + // wire unmarshaled message content of requests and responses made while + // using the SDK Will also enable LogDebug. + LogDebugWithEventStreamBody ) // A Logger is a minimalistic interface for the SDK to log messages to. Should diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go index 802ac88ad..8ef8548a9 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go @@ -14,10 +14,12 @@ type Handlers struct { Send HandlerList ValidateResponse HandlerList Unmarshal HandlerList + UnmarshalStream HandlerList UnmarshalMeta HandlerList UnmarshalError HandlerList Retry HandlerList AfterRetry HandlerList + CompleteAttempt HandlerList Complete HandlerList } @@ -30,10 +32,12 @@ func (h *Handlers) Copy() Handlers { Send: h.Send.copy(), ValidateResponse: h.ValidateResponse.copy(), Unmarshal: h.Unmarshal.copy(), + UnmarshalStream: h.UnmarshalStream.copy(), UnmarshalError: h.UnmarshalError.copy(), UnmarshalMeta: h.UnmarshalMeta.copy(), Retry: h.Retry.copy(), AfterRetry: h.AfterRetry.copy(), + CompleteAttempt: h.CompleteAttempt.copy(), Complete: h.Complete.copy(), } } @@ -45,11 +49,13 @@ func (h *Handlers) Clear() { h.Send.Clear() h.Sign.Clear() h.Unmarshal.Clear() + h.UnmarshalStream.Clear() h.UnmarshalMeta.Clear() h.UnmarshalError.Clear() h.ValidateResponse.Clear() h.Retry.Clear() h.AfterRetry.Clear() + h.CompleteAttempt.Clear() h.Complete.Clear() } @@ -172,6 +178,21 @@ func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { return swapped } +// Swap will swap out all handlers matching the name passed in. The matched +// handlers will be swapped in. True is returned if the handlers were swapped. +func (l *HandlerList) Swap(name string, replace NamedHandler) bool { + var swapped bool + + for i := 0; i < len(l.list); i++ { + if l.list[i].Name == name { + l.list[i] = replace + swapped = true + } + } + + return swapped +} + // SetBackNamed will replace the named handler if it exists in the handler list. // If the handler does not exist the handler will be added to the end of the list. func (l *HandlerList) SetBackNamed(n NamedHandler) { diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go index 02f07f4a4..b0c2ef4fe 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go @@ -3,6 +3,8 @@ package request import ( "io" "sync" + + "github.com/aws/aws-sdk-go/internal/sdkio" ) // offsetReader is a thread-safe io.ReadCloser to prevent racing @@ -15,7 +17,7 @@ type offsetReader struct { func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader { reader := &offsetReader{} - buf.Seek(offset, 0) + buf.Seek(offset, sdkio.SeekStart) reader.buf = buf return reader diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go index 299dc379d..8f2eb3e43 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "net" "net/http" "net/url" "reflect" @@ -14,6 +13,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/internal/sdkio" ) const ( @@ -24,10 +24,14 @@ const ( // ErrCodeRead is an error that is returned during HTTP reads. ErrCodeRead = "ReadError" - // ErrCodeResponseTimeout is the connection timeout error that is recieved + // ErrCodeResponseTimeout is the connection timeout error that is received // during body reads. ErrCodeResponseTimeout = "ResponseTimeout" + // ErrCodeInvalidPresignExpire is returned when the expire time provided to + // presign is invalid + ErrCodeInvalidPresignExpire = "InvalidPresignExpireError" + // CanceledErrorCode is the error code that will be returned by an // API request that was canceled. Requests given a aws.Context may // return this error when canceled. @@ -41,8 +45,8 @@ type Request struct { Handlers Handlers Retryer + AttemptTime time.Time Time time.Time - ExpireTime time.Duration Operation *Operation HTTPRequest *http.Request HTTPResponse *http.Response @@ -60,6 +64,11 @@ type Request struct { LastSignedAt time.Time DisableFollowRedirects bool + // A value greater than 0 instructs the request to be signed as Presigned URL + // You should not set this field directly. Instead use Request's + // Presign or PresignRequest methods. + ExpireTime time.Duration + context aws.Context built bool @@ -104,6 +113,8 @@ func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) } + SanitizeHostForHeader(httpReq) + r := &Request{ Config: cfg, ClientInfo: clientInfo, @@ -214,6 +225,9 @@ func (r *Request) SetContext(ctx aws.Context) { // WillRetry returns if the request's can be retried. func (r *Request) WillRetry() bool { + if !aws.IsReaderSeekable(r.Body) && r.HTTPRequest.Body != NoBody { + return false + } return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() } @@ -245,39 +259,74 @@ func (r *Request) SetStringBody(s string) { // SetReaderBody will set the request's body reader. func (r *Request) SetReaderBody(reader io.ReadSeeker) { r.Body = reader + r.BodyStart, _ = reader.Seek(0, sdkio.SeekCurrent) // Get the Bodies current offset. r.ResetBody() } // Presign returns the request's signed URL. Error will be returned -// if the signing fails. -func (r *Request) Presign(expireTime time.Duration) (string, error) { - r.ExpireTime = expireTime +// if the signing fails. The expire parameter is only used for presigned Amazon +// S3 API requests. All other AWS services will use a fixed expiration +// time of 15 minutes. +// +// It is invalid to create a presigned URL with a expire duration 0 or less. An +// error is returned if expire duration is 0 or less. +func (r *Request) Presign(expire time.Duration) (string, error) { + r = r.copy() + + // Presign requires all headers be hoisted. There is no way to retrieve + // the signed headers not hoisted without this. Making the presigned URL + // useless. r.NotHoist = false + u, _, err := getPresignedURL(r, expire) + return u, err +} + +// PresignRequest behaves just like presign, with the addition of returning a +// set of headers that were signed. The expire parameter is only used for +// presigned Amazon S3 API requests. All other AWS services will use a fixed +// expiration time of 15 minutes. +// +// It is invalid to create a presigned URL with a expire duration 0 or less. An +// error is returned if expire duration is 0 or less. +// +// Returns the URL string for the API operation with signature in the query string, +// and the HTTP headers that were included in the signature. These headers must +// be included in any HTTP request made with the presigned URL. +// +// To prevent hoisting any headers to the query string set NotHoist to true on +// this Request value prior to calling PresignRequest. +func (r *Request) PresignRequest(expire time.Duration) (string, http.Header, error) { + r = r.copy() + return getPresignedURL(r, expire) +} + +// IsPresigned returns true if the request represents a presigned API url. +func (r *Request) IsPresigned() bool { + return r.ExpireTime != 0 +} + +func getPresignedURL(r *Request, expire time.Duration) (string, http.Header, error) { + if expire <= 0 { + return "", nil, awserr.New( + ErrCodeInvalidPresignExpire, + "presigned URL requires an expire duration greater than 0", + nil, + ) + } + + r.ExpireTime = expire + if r.Operation.BeforePresignFn != nil { - r = r.copy() - err := r.Operation.BeforePresignFn(r) - if err != nil { - return "", err + if err := r.Operation.BeforePresignFn(r); err != nil { + return "", nil, err } } - r.Sign() - if r.Error != nil { - return "", r.Error + if err := r.Sign(); err != nil { + return "", nil, err } - return r.HTTPRequest.URL.String(), nil -} -// PresignRequest behaves just like presign, but hoists all headers and signs them. -// Also returns the signed hash back to the user -func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error) { - r.ExpireTime = expireTime - r.NotHoist = true - r.Sign() - if r.Error != nil { - return "", nil, r.Error - } return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil } @@ -297,7 +346,7 @@ func debugLogReqError(r *Request, stage string, retrying bool, err error) { // Build will build the request's object so it can be signed and sent // to the service. Build will also validate all the request's parameters. -// Anny additional build Handlers set on this request will be run +// Any additional build Handlers set on this request will be run // in the order they were set. // // The request will only be built once. Multiple calls to build will have @@ -323,9 +372,9 @@ func (r *Request) Build() error { return r.Error } -// Sign will sign the request returning error if errors are encountered. +// Sign will sign the request, returning error if errors are encountered. // -// Send will build the request prior to signing. All Sign Handlers will +// Sign will build the request prior to signing. All Sign Handlers will // be executed in the order they were set. func (r *Request) Sign() error { r.Build() @@ -358,7 +407,7 @@ func (r *Request) getNextRequestBody() (io.ReadCloser, error) { // of the SDK if they used that field. // // Related golang/go#18257 - l, err := computeBodyLength(r.Body) + l, err := aws.SeekerLen(r.Body) if err != nil { return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err) } @@ -376,7 +425,8 @@ func (r *Request) getNextRequestBody() (io.ReadCloser, error) { // Transfer-Encoding: chunked bodies for these methods. // // This would only happen if a aws.ReaderSeekerCloser was used with - // a io.Reader that was not also an io.Seeker. + // a io.Reader that was not also an io.Seeker, or did not implement + // Len() method. switch r.Operation.HTTPMethod { case "GET", "HEAD", "DELETE": body = NoBody @@ -388,49 +438,13 @@ func (r *Request) getNextRequestBody() (io.ReadCloser, error) { return body, nil } -// Attempts to compute the length of the body of the reader using the -// io.Seeker interface. If the value is not seekable because of being -// a ReaderSeekerCloser without an unerlying Seeker -1 will be returned. -// If no error occurs the length of the body will be returned. -func computeBodyLength(r io.ReadSeeker) (int64, error) { - seekable := true - // Determine if the seeker is actually seekable. ReaderSeekerCloser - // hides the fact that a io.Readers might not actually be seekable. - switch v := r.(type) { - case aws.ReaderSeekerCloser: - seekable = v.IsSeeker() - case *aws.ReaderSeekerCloser: - seekable = v.IsSeeker() - } - if !seekable { - return -1, nil - } - - curOffset, err := r.Seek(0, 1) - if err != nil { - return 0, err - } - - endOffset, err := r.Seek(0, 2) - if err != nil { - return 0, err - } - - _, err = r.Seek(curOffset, 0) - if err != nil { - return 0, err - } - - return endOffset - curOffset, nil -} - // GetBody will return an io.ReadSeeker of the Request's underlying // input body with a concurrency safe wrapper. func (r *Request) GetBody() io.ReadSeeker { return r.safeBody } -// Send will send the request returning error if errors are encountered. +// Send will send the request, returning error if errors are encountered. // // Send will sign the request prior to sending. All Send Handlers will // be executed in the order they were set. @@ -450,79 +464,78 @@ func (r *Request) Send() error { r.Handlers.Complete.Run(r) }() - for { - if aws.BoolValue(r.Retryable) { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) - } + if err := r.Error; err != nil { + return err + } - // The previous http.Request will have a reference to the r.Body - // and the HTTP Client's Transport may still be reading from - // the request's body even though the Client's Do returned. - r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) - r.ResetBody() + for { + r.Error = nil + r.AttemptTime = time.Now() - // Closing response body to ensure that no response body is leaked - // between retry attempts. - if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { - r.HTTPResponse.Body.Close() - } + if err := r.Sign(); err != nil { + debugLogReqError(r, "Sign Request", false, err) + return err } - r.Sign() - if r.Error != nil { - return r.Error - } - - r.Retryable = nil - - r.Handlers.Send.Run(r) - if r.Error != nil { - if !shouldRetryCancel(r) { - return r.Error - } - - err := r.Error + if err := r.sendRequest(); err == nil { + return nil + } else if !shouldRetryCancel(r.Error) { + return err + } else { r.Handlers.Retry.Run(r) r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Send Request", false, err) - return r.Error - } - debugLogReqError(r, "Send Request", true, err) - continue - } - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Response", false, err) + if r.Error != nil || !aws.BoolValue(r.Retryable) { return r.Error } - debugLogReqError(r, "Validate Response", true, err) - continue - } - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Unmarshal Response", false, err) - return r.Error - } - debugLogReqError(r, "Unmarshal Response", true, err) + r.prepareRetry() continue } + } +} + +func (r *Request) prepareRetry() { + if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { + r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", + r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) + } + + // The previous http.Request will have a reference to the r.Body + // and the HTTP Client's Transport may still be reading from + // the request's body even though the Client's Do returned. + r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) + r.ResetBody() - break + // Closing response body to ensure that no response body is leaked + // between retry attempts. + if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { + r.HTTPResponse.Body.Close() + } +} + +func (r *Request) sendRequest() (sendErr error) { + defer r.Handlers.CompleteAttempt.Run(r) + + r.Retryable = nil + r.Handlers.Send.Run(r) + if r.Error != nil { + debugLogReqError(r, "Send Request", r.WillRetry(), r.Error) + return r.Error + } + + r.Handlers.UnmarshalMeta.Run(r) + r.Handlers.ValidateResponse.Run(r) + if r.Error != nil { + r.Handlers.UnmarshalError.Run(r) + debugLogReqError(r, "Validate Response", r.WillRetry(), r.Error) + return r.Error + } + + r.Handlers.Unmarshal.Run(r) + if r.Error != nil { + debugLogReqError(r, "Unmarshal Response", r.WillRetry(), r.Error) + return r.Error } return nil @@ -548,28 +561,113 @@ func AddToUserAgent(r *Request, s string) { r.HTTPRequest.Header.Set("User-Agent", s) } -func shouldRetryCancel(r *Request) bool { - awsErr, ok := r.Error.(awserr.Error) - timeoutErr := false - errStr := r.Error.Error() - if ok { - if awsErr.Code() == CanceledErrorCode { +type temporary interface { + Temporary() bool +} + +func shouldRetryCancel(err error) bool { + switch err := err.(type) { + case awserr.Error: + if err.Code() == CanceledErrorCode { return false } - err := awsErr.OrigErr() - netErr, netOK := err.(net.Error) - timeoutErr = netOK && netErr.Temporary() - if urlErr, ok := err.(*url.Error); !timeoutErr && ok { - errStr = urlErr.Err.Error() + return shouldRetryCancel(err.OrigErr()) + case *url.Error: + if strings.Contains(err.Error(), "connection refused") { + // Refused connections should be retried as the service may not yet + // be running on the port. Go TCP dial considers refused + // connections as not temporary. + return true + } + // *url.Error only implements Temporary after golang 1.6 but since + // url.Error only wraps the error: + return shouldRetryCancel(err.Err) + case temporary: + // If the error is temporary, we want to allow continuation of the + // retry process + return err.Temporary() + case nil: + // `awserr.Error.OrigErr()` can be nil, meaning there was an error but + // because we don't know the cause, it is marked as retriable. See + // TestRequest4xxUnretryable for an example. + return true + default: + switch err.Error() { + case "net/http: request canceled", + "net/http: request canceled while waiting for connection": + // known 1.5 error case when an http request is cancelled + return false } + // here we don't know the error; so we allow a retry. + return true + } +} + +// SanitizeHostForHeader removes default port from host and updates request.Host +func SanitizeHostForHeader(r *http.Request) { + host := getHost(r) + port := portOnly(host) + if port != "" && isDefaultPort(r.URL.Scheme, port) { + r.Host = stripPort(host) + } +} + +// Returns host from request +func getHost(r *http.Request) string { + if r.Host != "" { + return r.Host } - // There can be two types of canceled errors here. - // The first being a net.Error and the other being an error. - // If the request was timed out, we want to continue the retry - // process. Otherwise, return the canceled error. - return timeoutErr || - (errStr != "net/http: request canceled" && - errStr != "net/http: request canceled while waiting for connection") + return r.URL.Host +} + +// Hostname returns u.Host, without any port number. +// +// If Host is an IPv6 literal with a port number, Hostname returns the +// IPv6 literal without the square brackets. IPv6 literals may include +// a zone identifier. +// +// Copied from the Go 1.8 standard library (net/url) +func stripPort(hostport string) string { + colon := strings.IndexByte(hostport, ':') + if colon == -1 { + return hostport + } + if i := strings.IndexByte(hostport, ']'); i != -1 { + return strings.TrimPrefix(hostport[:i], "[") + } + return hostport[:colon] +} + +// Port returns the port part of u.Host, without the leading colon. +// If u.Host doesn't contain a port, Port returns an empty string. +// +// Copied from the Go 1.8 standard library (net/url) +func portOnly(hostport string) string { + colon := strings.IndexByte(hostport, ':') + if colon == -1 { + return "" + } + if i := strings.Index(hostport, "]:"); i != -1 { + return hostport[i+len("]:"):] + } + if strings.Contains(hostport, "]") { + return "" + } + return hostport[colon+len(":"):] +} + +// Returns true if the specified URI is using the standard port +// (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs) +func isDefaultPort(scheme, port string) bool { + if port == "" { + return true + } + + lowerCaseScheme := strings.ToLower(scheme) + if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") { + return true + } + return false } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go index 869b97a1a..e36e468b7 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go @@ -21,7 +21,7 @@ func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } var NoBody = noBody{} // ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior +// sets the HTTP Request body reference. When the body is read prior // to being sent in the HTTP request it will need to be rewound. // // ResetBody will automatically be called by the SDK's build handler, but if diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go index c32fc69bc..7c6a8000f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go @@ -11,7 +11,7 @@ import ( var NoBody = http.NoBody // ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior +// sets the HTTP Request body reference. When the body is read prior // to being sent in the HTTP request it will need to be rewound. // // ResetBody will automatically be called by the SDK's build handler, but if diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go index 59de6736b..a633ed5ac 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go @@ -35,8 +35,12 @@ type Pagination struct { // NewRequest should always be built from the same API operations. It is // undefined if different API operations are returned on subsequent calls. NewRequest func() (*Request, error) + // EndPageOnSameToken, when enabled, will allow the paginator to stop on + // token that are the same as its previous tokens. + EndPageOnSameToken bool started bool + prevTokens []interface{} nextTokens []interface{} err error @@ -49,7 +53,15 @@ type Pagination struct { // // Will always return true if Next has not been called yet. func (p *Pagination) HasNextPage() bool { - return !(p.started && len(p.nextTokens) == 0) + if !p.started { + return true + } + + hasNextPage := len(p.nextTokens) != 0 + if p.EndPageOnSameToken { + return hasNextPage && !awsutil.DeepEqual(p.nextTokens, p.prevTokens) + } + return hasNextPage } // Err returns the error Pagination encountered when retrieving the next page. @@ -96,6 +108,7 @@ func (p *Pagination) Next() bool { return false } + p.prevTokens = p.nextTokens p.nextTokens = req.nextPageTokens() p.curPage = req.Data @@ -142,13 +155,28 @@ func (r *Request) nextPageTokens() []interface{} { tokens := []interface{}{} tokenAdded := false for _, outToken := range r.Operation.OutputTokens { - v, _ := awsutil.ValuesAtPath(r.Data, outToken) - if len(v) > 0 { - tokens = append(tokens, v[0]) - tokenAdded = true - } else { + vs, _ := awsutil.ValuesAtPath(r.Data, outToken) + if len(vs) == 0 { tokens = append(tokens, nil) + continue + } + v := vs[0] + + switch tv := v.(type) { + case *string: + if len(aws.StringValue(tv)) == 0 { + tokens = append(tokens, nil) + continue + } + case string: + if len(tv) == 0 { + tokens = append(tokens, nil) + continue + } } + + tokenAdded = true + tokens = append(tokens, v) } if !tokenAdded { return nil diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go index 8d369c1b8..7bc5da782 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go @@ -8,7 +8,7 @@ import ( ) // Retryer is an interface to control retry logic for a given service. -// The default implementation used by most services is the service.DefaultRetryer +// The default implementation used by most services is the client.DefaultRetryer // structure, which contains basic retry logic using exponential backoff. type Retryer interface { RetryRules(*Request) time.Duration @@ -40,6 +40,7 @@ var throttleCodes = map[string]struct{}{ "RequestThrottled": {}, "TooManyRequestsException": {}, // Lambda functions "PriorRequestNotComplete": {}, // Route53 + "TransactionInProgressException": {}, } // credsExpiredCodes is a collection of error codes which signify the credentials @@ -70,8 +71,8 @@ func isCodeExpiredCreds(code string) bool { } var validParentCodes = map[string]struct{}{ - ErrCodeSerialization: struct{}{}, - ErrCodeRead: struct{}{}, + ErrCodeSerialization: {}, + ErrCodeRead: {}, } type temporaryError interface { @@ -97,7 +98,7 @@ func isNestedErrorRetryable(parentErr awserr.Error) bool { } if t, ok := err.(temporaryError); ok { - return t.Temporary() + return t.Temporary() || isErrConnectionReset(err) } return isErrConnectionReset(err) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go index 2520286b7..8630683f3 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go @@ -17,6 +17,12 @@ const ( ParamMinValueErrCode = "ParamMinValueError" // ParamMinLenErrCode is the error code for fields without enough elements. ParamMinLenErrCode = "ParamMinLenError" + // ParamMaxLenErrCode is the error code for value being too long. + ParamMaxLenErrCode = "ParamMaxLenError" + + // ParamFormatErrCode is the error code for a field with invalid + // format or characters. + ParamFormatErrCode = "ParamFormatInvalidError" ) // Validator provides a way for types to perform validation logic on their @@ -220,7 +226,7 @@ type ErrParamMinLen struct { func NewErrParamMinLen(field string, min int) *ErrParamMinLen { return &ErrParamMinLen{ errInvalidParam: errInvalidParam{ - code: ParamMinValueErrCode, + code: ParamMinLenErrCode, field: field, msg: fmt.Sprintf("minimum field size of %v", min), }, @@ -232,3 +238,49 @@ func NewErrParamMinLen(field string, min int) *ErrParamMinLen { func (e *ErrParamMinLen) MinLen() int { return e.min } + +// An ErrParamMaxLen represents a maximum length parameter error. +type ErrParamMaxLen struct { + errInvalidParam + max int +} + +// NewErrParamMaxLen creates a new maximum length parameter error. +func NewErrParamMaxLen(field string, max int, value string) *ErrParamMaxLen { + return &ErrParamMaxLen{ + errInvalidParam: errInvalidParam{ + code: ParamMaxLenErrCode, + field: field, + msg: fmt.Sprintf("maximum size of %v, %v", max, value), + }, + max: max, + } +} + +// MaxLen returns the field's required minimum length. +func (e *ErrParamMaxLen) MaxLen() int { + return e.max +} + +// An ErrParamFormat represents a invalid format parameter error. +type ErrParamFormat struct { + errInvalidParam + format string +} + +// NewErrParamFormat creates a new invalid format parameter error. +func NewErrParamFormat(field string, format, value string) *ErrParamFormat { + return &ErrParamFormat{ + errInvalidParam: errInvalidParam{ + code: ParamFormatErrCode, + field: field, + msg: fmt.Sprintf("format %v, %v", format, value), + }, + format: format, + } +} + +// Format returns the field's required format. +func (e *ErrParamFormat) Format() string { + return e.format +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go index 22d2f8098..4601f883c 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go @@ -79,8 +79,9 @@ type Waiter struct { MaxAttempts int Delay WaiterDelay - RequestOptions []Option - NewRequest func([]Option) (*Request, error) + RequestOptions []Option + NewRequest func([]Option) (*Request, error) + SleepWithContext func(aws.Context, time.Duration) error } // ApplyOptions updates the waiter with the list of waiter options provided. @@ -195,8 +196,15 @@ func (w Waiter) WaitWithContext(ctx aws.Context) error { if sleepFn := req.Config.SleepDelay; sleepFn != nil { // Support SleepDelay for backwards compatibility and testing sleepFn(delay) - } else if err := aws.SleepWithContext(ctx, delay); err != nil { - return awserr.New(CanceledErrorCode, "waiter context canceled", err) + } else { + sleepCtxFn := w.SleepWithContext + if sleepCtxFn == nil { + sleepCtxFn = aws.SleepWithContext + } + + if err := sleepCtxFn(ctx, delay); err != nil { + return awserr.New(CanceledErrorCode, "waiter context canceled", err) + } } } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go index ea7b886f8..38a7b05a6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go @@ -99,7 +99,7 @@ handler logs every request and its payload made by a service client: sess.Handlers.Send.PushFront(func(r *request.Request) { // Log every request made and its payload - logger.Println("Request: %s/%s, Payload: %s", + logger.Printf("Request: %s/%s, Payload: %s", r.ClientInfo.ServiceName, r.Operation, r.Params) }) @@ -128,7 +128,7 @@ read. The Session will be created from configuration values from the shared credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). Credentials are the values the SDK should use for authenticating requests with -AWS Services. They arfrom a configuration file will need to include both +AWS Services. They are from a configuration file will need to include both aws_access_key_id and aws_secret_access_key must be provided together in the same file to be considered valid. The values will be ignored if not a complete group. aws_session_token is an optional field that can be provided if both of @@ -183,7 +183,7 @@ be returned when creating the session. // from assumed role. svc := s3.New(sess) -To setup assume role outside of a session see the stscrds.AssumeRoleProvider +To setup assume role outside of a session see the stscreds.AssumeRoleProvider documentation. Environment Variables diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go index 7357e545a..e3959b959 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go @@ -4,9 +4,14 @@ import ( "os" "strconv" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/defaults" ) +// EnvProviderName provides a name of the provider when config is loaded from environment. +const EnvProviderName = "EnvConfigCredentials" + // envConfig is a collection of environment values the SDK will read // setup config from. All environment values are optional. But some values // such as credentials require multiple values to be complete or the values @@ -75,8 +80,8 @@ type envConfig struct { // AWS_CONFIG_FILE=$HOME/my_shared_config SharedConfigFile string - // Sets the path to a custom Credentials Authroity (CA) Bundle PEM file - // that the SDK will use instead of the the system's root CA bundle. + // Sets the path to a custom Credentials Authority (CA) Bundle PEM file + // that the SDK will use instead of the system's root CA bundle. // Only use this if you want to configure the SDK to use a custom set // of CAs. // @@ -92,9 +97,29 @@ type envConfig struct { // // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle CustomCABundle string + + csmEnabled string + CSMEnabled bool + CSMPort string + CSMClientID string + + enableEndpointDiscovery string + // Enables endpoint discovery via environment variables. + // + // AWS_ENABLE_ENDPOINT_DISCOVERY=true + EnableEndpointDiscovery *bool } var ( + csmEnabledEnvKey = []string{ + "AWS_CSM_ENABLED", + } + csmPortEnvKey = []string{ + "AWS_CSM_PORT", + } + csmClientIDEnvKey = []string{ + "AWS_CSM_CLIENT_ID", + } credAccessEnvKey = []string{ "AWS_ACCESS_KEY_ID", "AWS_ACCESS_KEY", @@ -107,6 +132,10 @@ var ( "AWS_SESSION_TOKEN", } + enableEndpointDiscoveryEnvKey = []string{ + "AWS_ENABLE_ENDPOINT_DISCOVERY", + } + regionEnvKeys = []string{ "AWS_REGION", "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set @@ -153,11 +182,17 @@ func envConfigLoad(enableSharedConfig bool) envConfig { setFromEnvVal(&cfg.Creds.SecretAccessKey, credSecretEnvKey) setFromEnvVal(&cfg.Creds.SessionToken, credSessionEnvKey) + // CSM environment variables + setFromEnvVal(&cfg.csmEnabled, csmEnabledEnvKey) + setFromEnvVal(&cfg.CSMPort, csmPortEnvKey) + setFromEnvVal(&cfg.CSMClientID, csmClientIDEnvKey) + cfg.CSMEnabled = len(cfg.csmEnabled) > 0 + // Require logical grouping of credentials if len(cfg.Creds.AccessKeyID) == 0 || len(cfg.Creds.SecretAccessKey) == 0 { cfg.Creds = credentials.Value{} } else { - cfg.Creds.ProviderName = "EnvConfigCredentials" + cfg.Creds.ProviderName = EnvProviderName } regionKeys := regionEnvKeys @@ -170,9 +205,22 @@ func envConfigLoad(enableSharedConfig bool) envConfig { setFromEnvVal(&cfg.Region, regionKeys) setFromEnvVal(&cfg.Profile, profileKeys) + // endpoint discovery is in reference to it being enabled. + setFromEnvVal(&cfg.enableEndpointDiscovery, enableEndpointDiscoveryEnvKey) + if len(cfg.enableEndpointDiscovery) > 0 { + cfg.EnableEndpointDiscovery = aws.Bool(cfg.enableEndpointDiscovery != "false") + } + setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) + if len(cfg.SharedCredentialsFile) == 0 { + cfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() + } + if len(cfg.SharedConfigFile) == 0 { + cfg.SharedConfigFile = defaults.SharedConfigFilename() + } + cfg.CustomCABundle = os.Getenv("AWS_CA_BUNDLE") return cfg diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go index 9f75d5ac5..9bdbafd65 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go @@ -14,19 +14,39 @@ import ( "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/credentials/processcreds" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" + "github.com/aws/aws-sdk-go/aws/csm" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/shareddefaults" ) +const ( + // ErrCodeSharedConfig represents an error that occurs in the shared + // configuration logic + ErrCodeSharedConfig = "SharedConfigErr" +) + +// ErrSharedConfigSourceCollision will be returned if a section contains both +// source_profile and credential_source +var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only source profile or credential source can be specified, not both", nil) + +// ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment +// variables are empty and Environment was set as the credential source +var ErrSharedConfigECSContainerEnvVarEmpty = awserr.New(ErrCodeSharedConfig, "EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set", nil) + +// ErrSharedConfigInvalidCredSource will be returned if an invalid credential source was provided +var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credential source values must be EcsContainer, Ec2InstanceMetadata, or Environment", nil) + // A Session provides a central location to create service clients from and // store configurations and request handlers for those services. // // Sessions are safe to create service clients concurrently, but it is not safe // to mutate the Session concurrently. // -// The Session satisfies the service client's client.ClientConfigProvider. +// The Session satisfies the service client's client.ConfigProvider. type Session struct { Config *aws.Config Handlers request.Handlers @@ -58,7 +78,12 @@ func New(cfgs ...*aws.Config) *Session { envCfg := loadEnvConfig() if envCfg.EnableSharedConfig { - s, err := newSession(Options{}, envCfg, cfgs...) + var cfg aws.Config + cfg.MergeIn(cfgs...) + s, err := NewSessionWithOptions(Options{ + Config: cfg, + SharedConfigState: SharedConfigEnable, + }) if err != nil { // Old session.New expected all errors to be discovered when // a request is made, and would report the errors then. This @@ -76,10 +101,16 @@ func New(cfgs ...*aws.Config) *Session { r.Error = err }) } + return s } - return deprecatedNewSession(cfgs...) + s := deprecatedNewSession(cfgs...) + if envCfg.CSMEnabled { + enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger) + } + + return s } // NewSession returns a new Session created from SDK defaults, config files, @@ -243,13 +274,6 @@ func NewSessionWithOptions(opts Options) (*Session, error) { envCfg.EnableSharedConfig = true } - if len(envCfg.SharedCredentialsFile) == 0 { - envCfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() - } - if len(envCfg.SharedConfigFile) == 0 { - envCfg.SharedConfigFile = defaults.SharedConfigFilename() - } - // Only use AWS_CA_BUNDLE if session option is not provided. if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil { f, err := os.Open(envCfg.CustomCABundle) @@ -302,10 +326,22 @@ func deprecatedNewSession(cfgs ...*aws.Config) *Session { } initHandlers(s) - return s } +func enableCSM(handlers *request.Handlers, clientID string, port string, logger aws.Logger) { + logger.Log("Enabling CSM") + if len(port) == 0 { + port = csm.DefaultPort + } + + r, err := csm.Start(clientID, "127.0.0.1:"+port) + if err != nil { + return + } + r.InjectHandlers(handlers) +} + func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { cfg := defaults.Config() handlers := defaults.Handlers() @@ -345,6 +381,9 @@ func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, } initHandlers(s) + if envCfg.CSMEnabled { + enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger) + } // Setup HTTP client with custom cert bundle if enabled if opts.CustomCABundle != nil { @@ -414,8 +453,67 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share } } + if cfg.EnableEndpointDiscovery == nil { + if envCfg.EnableEndpointDiscovery != nil { + cfg.WithEndpointDiscovery(*envCfg.EnableEndpointDiscovery) + } else if envCfg.EnableSharedConfig && sharedCfg.EnableEndpointDiscovery != nil { + cfg.WithEndpointDiscovery(*sharedCfg.EnableEndpointDiscovery) + } + } + // Configure credentials if not already set if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { + + // inspect the profile to see if a credential source has been specified. + if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.CredentialSource) > 0 { + + // if both credential_source and source_profile have been set, return an error + // as this is undefined behavior. + if len(sharedCfg.AssumeRole.SourceProfile) > 0 { + return ErrSharedConfigSourceCollision + } + + // valid credential source values + const ( + credSourceEc2Metadata = "Ec2InstanceMetadata" + credSourceEnvironment = "Environment" + credSourceECSContainer = "EcsContainer" + ) + + switch sharedCfg.AssumeRole.CredentialSource { + case credSourceEc2Metadata: + cfgCp := *cfg + p := defaults.RemoteCredProvider(cfgCp, handlers) + cfgCp.Credentials = credentials.NewCredentials(p) + + if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { + // AssumeRole Token provider is required if doing Assume Role + // with MFA. + return AssumeRoleTokenProviderNotSetError{} + } + + cfg.Credentials = assumeRoleCredentials(cfgCp, handlers, sharedCfg, sessOpts) + case credSourceEnvironment: + cfg.Credentials = credentials.NewStaticCredentialsFromCreds( + envCfg.Creds, + ) + case credSourceECSContainer: + if len(os.Getenv(shareddefaults.ECSCredsProviderEnvVar)) == 0 { + return ErrSharedConfigECSContainerEnvVarEmpty + } + + cfgCp := *cfg + p := defaults.RemoteCredProvider(cfgCp, handlers) + creds := credentials.NewCredentials(p) + + cfg.Credentials = creds + default: + return ErrSharedConfigInvalidCredSource + } + + return nil + } + if len(envCfg.Creds.AccessKeyID) > 0 { cfg.Credentials = credentials.NewStaticCredentialsFromCreds( envCfg.Creds, @@ -425,36 +523,22 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( sharedCfg.AssumeRoleSource.Creds, ) + if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { // AssumeRole Token provider is required if doing Assume Role // with MFA. return AssumeRoleTokenProviderNotSetError{} } - cfg.Credentials = stscreds.NewCredentials( - &Session{ - Config: &cfgCp, - Handlers: handlers.Copy(), - }, - sharedCfg.AssumeRole.RoleARN, - func(opt *stscreds.AssumeRoleProvider) { - opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName - - // Assume role with external ID - if len(sharedCfg.AssumeRole.ExternalID) > 0 { - opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.AssumeRole.MFASerial) > 0 { - opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) - opt.TokenProvider = sessOpts.AssumeRoleTokenProvider - } - }, - ) + + cfg.Credentials = assumeRoleCredentials(cfgCp, handlers, sharedCfg, sessOpts) } else if len(sharedCfg.Creds.AccessKeyID) > 0 { cfg.Credentials = credentials.NewStaticCredentialsFromCreds( sharedCfg.Creds, ) + } else if len(sharedCfg.CredentialProcess) > 0 { + cfg.Credentials = processcreds.NewCredentials( + sharedCfg.CredentialProcess, + ) } else { // Fallback to default credentials provider, include mock errors // for the credential chain so user can identify why credentials @@ -473,6 +557,30 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share return nil } +func assumeRoleCredentials(cfg aws.Config, handlers request.Handlers, sharedCfg sharedConfig, sessOpts Options) *credentials.Credentials { + return stscreds.NewCredentials( + &Session{ + Config: &cfg, + Handlers: handlers.Copy(), + }, + sharedCfg.AssumeRole.RoleARN, + func(opt *stscreds.AssumeRoleProvider) { + opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName + + // Assume role with external ID + if len(sharedCfg.AssumeRole.ExternalID) > 0 { + opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) + } + + // Assume role with MFA + if len(sharedCfg.AssumeRole.MFASerial) > 0 { + opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) + opt.TokenProvider = sessOpts.AssumeRoleTokenProvider + } + }, + ) +} + // AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the // MFAToken option is not set when shared config is configured load assume a // role with an MFA token. @@ -573,11 +681,12 @@ func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) ( } return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningName: resolved.SigningName, + Config: s.Config, + Handlers: s.Handlers, + Endpoint: resolved.URL, + SigningRegion: resolved.SigningRegion, + SigningNameDerived: resolved.SigningNameDerived, + SigningName: resolved.SigningName, }, err } @@ -597,10 +706,11 @@ func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Conf } return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningName: resolved.SigningName, + Config: s.Config, + Handlers: s.Handlers, + Endpoint: resolved.URL, + SigningRegion: resolved.SigningRegion, + SigningNameDerived: resolved.SigningNameDerived, + SigningName: resolved.SigningName, } } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go index 09c8e5bc7..7cb44021b 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go @@ -2,11 +2,11 @@ package session import ( "fmt" - "io/ioutil" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" + + "github.com/aws/aws-sdk-go/internal/ini" ) const ( @@ -16,15 +16,21 @@ const ( sessionTokenKey = `aws_session_token` // optional // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional + roleArnKey = `role_arn` // group required + sourceProfileKey = `source_profile` // group required (or credential_source) + credentialSourceKey = `credential_source` // group required (or source_profile) + externalIDKey = `external_id` // optional + mfaSerialKey = `mfa_serial` // optional + roleSessionNameKey = `role_session_name` // optional // Additional Config fields regionKey = `region` + // endpoint discovery group + enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional + // External Credential Process + credentialProcessKey = `credential_process` + // DefaultSharedConfigProfile is the default profile to be used when // loading configuration from the config files if another profile name // is not provided. @@ -32,11 +38,12 @@ const ( ) type assumeRoleConfig struct { - RoleARN string - SourceProfile string - ExternalID string - MFASerial string - RoleSessionName string + RoleARN string + SourceProfile string + CredentialSource string + ExternalID string + MFASerial string + RoleSessionName string } // sharedConfig represents the configuration fields of the SDK config files. @@ -55,16 +62,25 @@ type sharedConfig struct { AssumeRole assumeRoleConfig AssumeRoleSource *sharedConfig + // An external process to request credentials + CredentialProcess string + // Region is the region the SDK should use for looking up AWS service endpoints // and signing requests. // // region Region string + + // EnableEndpointDiscovery can be enabled in the shared config by setting + // endpoint_discovery_enabled to true + // + // endpoint_discovery_enabled = true + EnableEndpointDiscovery *bool } type sharedConfigFile struct { Filename string - IniData *ini.File + IniData ini.Sections } // loadSharedConfig retrieves the configuration from the list of files @@ -105,19 +121,16 @@ func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { files := make([]sharedConfigFile, 0, len(filenames)) for _, filename := range filenames { - b, err := ioutil.ReadFile(filename) - if err != nil { + sections, err := ini.OpenFile(filename) + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == ini.ErrCodeUnableToReadFile { // Skip files which can't be opened and read for whatever reason continue - } - - f, err := ini.Load(b) - if err != nil { + } else if err != nil { return nil, SharedConfigLoadError{Filename: filename, Err: err} } files = append(files, sharedConfigFile{ - Filename: filename, IniData: f, + Filename: filename, IniData: sections, }) } @@ -127,6 +140,13 @@ func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { func (cfg *sharedConfig) setAssumeRoleSource(origProfile string, files []sharedConfigFile) error { var assumeRoleSrc sharedConfig + if len(cfg.AssumeRole.CredentialSource) > 0 { + // setAssumeRoleSource is only called when source_profile is found. + // If both source_profile and credential_source are set, then + // ErrSharedConfigSourceCollision will be returned + return ErrSharedConfigSourceCollision + } + // Multiple level assume role chains are not support if cfg.AssumeRole.SourceProfile == origProfile { assumeRoleSrc = *cfg @@ -171,45 +191,59 @@ func (cfg *sharedConfig) setFromIniFiles(profile string, files []sharedConfigFil // if a config file only includes aws_access_key_id but no aws_secret_access_key // the aws_access_key_id will be ignored. func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile) error { - section, err := file.IniData.GetSection(profile) - if err != nil { + section, ok := file.IniData.GetSection(profile) + if !ok { // Fallback to to alternate profile name: profile - section, err = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) - if err != nil { - return SharedConfigProfileNotExistsError{Profile: profile, Err: err} + section, ok = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) + if !ok { + return SharedConfigProfileNotExistsError{Profile: profile, Err: nil} } } // Shared Credentials - akid := section.Key(accessKeyIDKey).String() - secret := section.Key(secretAccessKey).String() + akid := section.String(accessKeyIDKey) + secret := section.String(secretAccessKey) if len(akid) > 0 && len(secret) > 0 { cfg.Creds = credentials.Value{ AccessKeyID: akid, SecretAccessKey: secret, - SessionToken: section.Key(sessionTokenKey).String(), + SessionToken: section.String(sessionTokenKey), ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), } } // Assume Role - roleArn := section.Key(roleArnKey).String() - srcProfile := section.Key(sourceProfileKey).String() - if len(roleArn) > 0 && len(srcProfile) > 0 { + roleArn := section.String(roleArnKey) + srcProfile := section.String(sourceProfileKey) + credentialSource := section.String(credentialSourceKey) + hasSource := len(srcProfile) > 0 || len(credentialSource) > 0 + if len(roleArn) > 0 && hasSource { cfg.AssumeRole = assumeRoleConfig{ - RoleARN: roleArn, - SourceProfile: srcProfile, - ExternalID: section.Key(externalIDKey).String(), - MFASerial: section.Key(mfaSerialKey).String(), - RoleSessionName: section.Key(roleSessionNameKey).String(), + RoleARN: roleArn, + SourceProfile: srcProfile, + CredentialSource: credentialSource, + ExternalID: section.String(externalIDKey), + MFASerial: section.String(mfaSerialKey), + RoleSessionName: section.String(roleSessionNameKey), } } + // `credential_process` + if credProc := section.String(credentialProcessKey); len(credProc) > 0 { + cfg.CredentialProcess = credProc + } + // Region - if v := section.Key(regionKey).String(); len(v) > 0 { + if v := section.String(regionKey); len(v) > 0 { cfg.Region = v } + // Endpoint discovery + if section.Has(enableEndpointDiscoveryKey) { + v := section.Bool(enableEndpointDiscoveryKey) + cfg.EnableEndpointDiscovery = &v + } + return nil } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go index 434ac872d..523db79f8 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go @@ -45,7 +45,7 @@ // If signing a request intended for HTTP2 server, and you're using Go 1.6.2 // through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the // request URL. https://github.com/golang/go/issues/16847 points to a bug in -// Go pre 1.8 that failes to make HTTP2 requests using absolute URL in the HTTP +// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP // message. URL.Opaque generally will force Go to make requests with absolute URL. // URL.RawPath does not do this, but RawPath must be a valid escaping of Path // or url.EscapedPath will ignore the RawPath escaping. @@ -55,7 +55,6 @@ package v4 import ( - "bytes" "crypto/hmac" "crypto/sha256" "encoding/hex" @@ -72,6 +71,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/sdkio" "github.com/aws/aws-sdk-go/private/protocol/rest" ) @@ -98,25 +98,25 @@ var ignoredHeaders = rules{ var requiredSignedHeaders = rules{ whitelist{ mapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, + "Cache-Control": struct{}{}, + "Content-Disposition": struct{}{}, + "Content-Encoding": struct{}{}, + "Content-Language": struct{}{}, + "Content-Md5": struct{}{}, + "Content-Type": struct{}{}, + "Expires": struct{}{}, + "If-Match": struct{}{}, + "If-Modified-Since": struct{}{}, + "If-None-Match": struct{}{}, + "If-Unmodified-Since": struct{}{}, + "Range": struct{}{}, + "X-Amz-Acl": struct{}{}, + "X-Amz-Copy-Source": struct{}{}, + "X-Amz-Copy-Source-If-Match": struct{}{}, + "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, + "X-Amz-Copy-Source-If-None-Match": struct{}{}, + "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, + "X-Amz-Copy-Source-Range": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, @@ -134,7 +134,9 @@ var requiredSignedHeaders = rules{ "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Storage-Class": struct{}{}, + "X-Amz-Tagging": struct{}{}, "X-Amz-Website-Redirect-Location": struct{}{}, + "X-Amz-Content-Sha256": struct{}{}, }, }, patterns{"X-Amz-Meta-"}, @@ -180,7 +182,7 @@ type Signer struct { // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html DisableURIPathEscaping bool - // Disales the automatical setting of the HTTP request's Body field with the + // Disables the automatical setting of the HTTP request's Body field with the // io.ReadSeeker passed in to the signer. This is useful if you're using a // custom wrapper around the body for the io.ReadSeeker and want to preserve // the Body value on the Request.Body. @@ -269,7 +271,7 @@ type signingCtx struct { // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, 0, signTime) + return v4.signWithBody(r, body, service, region, 0, false, signTime) } // Presign signs AWS v4 requests with the provided body, service name, region @@ -303,10 +305,10 @@ func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region strin // presigned request's signature you can set the "X-Amz-Content-Sha256" // HTTP header and that will be included in the request's signature. func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, exp, signTime) + return v4.signWithBody(r, body, service, region, exp, true, signTime) } -func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { +func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { currentTimeFn := v4.currentTimeFn if currentTimeFn == nil { currentTimeFn = time.Now @@ -318,7 +320,7 @@ func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, regi Query: r.URL.Query(), Time: signTime, ExpireTime: exp, - isPresign: exp != 0, + isPresign: isPresign, ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, @@ -340,8 +342,11 @@ func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, regi return http.Header{}, err } + ctx.sanitizeHostForHeader() ctx.assignAmzQueryValues() - ctx.build(v4.DisableHeaderHoisting) + if err := ctx.build(v4.DisableHeaderHoisting); err != nil { + return nil, err + } // If the request is not presigned the body should be attached to it. This // prevents the confusion of wanting to send a signed request without @@ -364,6 +369,10 @@ func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, regi return ctx.SignedHeaderVals, nil } +func (ctx *signingCtx) sanitizeHostForHeader() { + request.SanitizeHostForHeader(ctx.Request) +} + func (ctx *signingCtx) handlePresignRemoval() { if !ctx.isPresign { return @@ -402,7 +411,7 @@ var SignRequestHandler = request.NamedHandler{ } // SignSDKRequest signs an AWS request with the V4 signature. This -// request handler is bested used only with the SDK's built in service client's +// request handler should only be used with the SDK's built in service client's // API operation requests. // // This function should not be used on its on its own, but in conjunction with @@ -413,7 +422,7 @@ var SignRequestHandler = request.NamedHandler{ // If the credentials of the request's config are set to // credentials.AnonymousCredentials the request will not be signed. func SignSDKRequest(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now) + SignSDKRequestWithCurrentTime(req, time.Now) } // BuildNamedHandler will build a generic handler for signing. @@ -421,12 +430,15 @@ func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler return request.NamedHandler{ Name: name, Fn: func(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now, opts...) + SignSDKRequestWithCurrentTime(req, time.Now, opts...) }, } } -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { +// SignSDKRequestWithCurrentTime will sign the SDK's request using the time +// function passed in. Behaves the same as SignSDKRequest with the exception +// the request is signed with the value returned by the current time function. +func SignSDKRequestWithCurrentTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { @@ -462,13 +474,9 @@ func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time opt(v4) } - signingTime := req.Time - if !req.LastSignedAt.IsZero() { - signingTime = req.LastSignedAt - } - + curTime := curTimeFn() signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), - name, region, req.ExpireTime, signingTime, + name, region, req.ExpireTime, req.ExpireTime > 0, curTime, ) if err != nil { req.Error = err @@ -477,7 +485,7 @@ func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time } req.SignedHeaderVals = signedHeaders - req.LastSignedAt = curTimeFn() + req.LastSignedAt = curTime } const logSignInfoMsg = `DEBUG: Request Signature: @@ -499,10 +507,14 @@ func (v4 *Signer) logSigningInfo(ctx *signingCtx) { v4.Logger.Log(msg) } -func (ctx *signingCtx) build(disableHeaderHoisting bool) { +func (ctx *signingCtx) build(disableHeaderHoisting bool) error { ctx.buildTime() // no depends ctx.buildCredentialString() // no depends + if err := ctx.buildBodyDigest(); err != nil { + return err + } + unsignedHeaders := ctx.Request.Header if ctx.isPresign { if !disableHeaderHoisting { @@ -514,7 +526,6 @@ func (ctx *signingCtx) build(disableHeaderHoisting bool) { } } - ctx.buildBodyDigest() ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) ctx.buildCanonicalString() // depends on canon headers / signed headers ctx.buildStringToSign() // depends on canon string @@ -530,6 +541,8 @@ func (ctx *signingCtx) build(disableHeaderHoisting bool) { } ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) } + + return nil } func (ctx *signingCtx) buildTime() { @@ -604,14 +617,18 @@ func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { headerValues := make([]string, len(headers)) for i, k := range headers { if k == "host" { - headerValues[i] = "host:" + ctx.Request.URL.Host + if ctx.Request.Host != "" { + headerValues[i] = "host:" + ctx.Request.Host + } else { + headerValues[i] = "host:" + ctx.Request.URL.Host + } } else { headerValues[i] = k + ":" + strings.Join(ctx.SignedHeaderVals[k], ",") } } - - ctx.canonicalHeaders = strings.Join(stripExcessSpaces(headerValues), "\n") + stripExcessSpaces(headerValues) + ctx.canonicalHeaders = strings.Join(headerValues, "\n") } func (ctx *signingCtx) buildCanonicalString() { @@ -652,21 +669,34 @@ func (ctx *signingCtx) buildSignature() { ctx.signature = hex.EncodeToString(signature) } -func (ctx *signingCtx) buildBodyDigest() { +func (ctx *signingCtx) buildBodyDigest() error { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { - if ctx.unsignedPayload || (ctx.isPresign && ctx.ServiceName == "s3") { + includeSHA256Header := ctx.unsignedPayload || + ctx.ServiceName == "s3" || + ctx.ServiceName == "glacier" + + s3Presign := ctx.isPresign && ctx.ServiceName == "s3" + + if ctx.unsignedPayload || s3Presign { hash = "UNSIGNED-PAYLOAD" + includeSHA256Header = !s3Presign } else if ctx.Body == nil { hash = emptyStringSHA256 } else { + if !aws.IsReaderSeekable(ctx.Body) { + return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) + } hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) } - if ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { + + if includeSHA256Header { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } ctx.bodyDigest = hash + + return nil } // isRequestSigned returns if the request is currently signed or presigned @@ -706,56 +736,61 @@ func makeSha256(data []byte) []byte { func makeSha256Reader(reader io.ReadSeeker) []byte { hash := sha256.New() - start, _ := reader.Seek(0, 1) - defer reader.Seek(start, 0) + start, _ := reader.Seek(0, sdkio.SeekCurrent) + defer reader.Seek(start, sdkio.SeekStart) + + // Use CopyN to avoid allocating the 32KB buffer in io.Copy for bodies + // smaller than 32KB. Fall back to io.Copy if we fail to determine the size. + size, err := aws.SeekerLen(reader) + if err != nil { + io.Copy(hash, reader) + } else { + io.CopyN(hash, reader, size) + } - io.Copy(hash, reader) return hash.Sum(nil) } -const doubleSpaces = " " - -var doubleSpaceBytes = []byte(doubleSpaces) +const doubleSpace = " " -func stripExcessSpaces(headerVals []string) []string { - vals := make([]string, len(headerVals)) - for i, str := range headerVals { - // Trim leading and trailing spaces - trimmed := strings.TrimSpace(str) +// stripExcessSpaces will rewrite the passed in slice's string values to not +// contain multiple side-by-side spaces. +func stripExcessSpaces(vals []string) { + var j, k, l, m, spaces int + for i, str := range vals { + // Trim trailing spaces + for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { + } - idx := strings.Index(trimmed, doubleSpaces) - var buf []byte - for idx > -1 { - // Multiple adjacent spaces found - if buf == nil { - // first time create the buffer - buf = []byte(trimmed) - } + // Trim leading spaces + for k = 0; k < j && str[k] == ' '; k++ { + } + str = str[k : j+1] - stripToIdx := -1 - for j := idx + 1; j < len(buf); j++ { - if buf[j] != ' ' { - buf = append(buf[:idx+1], buf[j:]...) - stripToIdx = j - break - } - } + // Strip multiple spaces. + j = strings.Index(str, doubleSpace) + if j < 0 { + vals[i] = str + continue + } - if stripToIdx >= 0 { - idx = bytes.Index(buf[stripToIdx:], doubleSpaceBytes) - if idx >= 0 { - idx += stripToIdx + buf := []byte(str) + for k, m, l = j, j, len(buf); k < l; k++ { + if buf[k] == ' ' { + if spaces == 0 { + // First space. + buf[m] = buf[k] + m++ } + spaces++ } else { - idx = -1 + // End of multiple spaces. + spaces = 0 + buf[m] = buf[k] + m++ } } - if buf != nil { - vals[i] = string(buf) - } else { - vals[i] = trimmed - } + vals[i] = string(buf[:m]) } - return vals } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go index 0e2d864e1..8b6f23425 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/types.go @@ -3,6 +3,8 @@ package aws import ( "io" "sync" + + "github.com/aws/aws-sdk-go/internal/sdkio" ) // ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Should @@ -22,6 +24,22 @@ type ReaderSeekerCloser struct { r io.Reader } +// IsReaderSeekable returns if the underlying reader type can be seeked. A +// io.Reader might not actually be seekable if it is the ReaderSeekerCloser +// type. +func IsReaderSeekable(r io.Reader) bool { + switch v := r.(type) { + case ReaderSeekerCloser: + return v.IsSeeker() + case *ReaderSeekerCloser: + return v.IsSeeker() + case io.ReadSeeker: + return true + default: + return false + } +} + // Read reads from the reader up to size of p. The number of bytes read, and // error if it occurred will be returned. // @@ -56,6 +74,71 @@ func (r ReaderSeekerCloser) IsSeeker() bool { return ok } +// HasLen returns the length of the underlying reader if the value implements +// the Len() int method. +func (r ReaderSeekerCloser) HasLen() (int, bool) { + type lenner interface { + Len() int + } + + if lr, ok := r.r.(lenner); ok { + return lr.Len(), true + } + + return 0, false +} + +// GetLen returns the length of the bytes remaining in the underlying reader. +// Checks first for Len(), then io.Seeker to determine the size of the +// underlying reader. +// +// Will return -1 if the length cannot be determined. +func (r ReaderSeekerCloser) GetLen() (int64, error) { + if l, ok := r.HasLen(); ok { + return int64(l), nil + } + + if s, ok := r.r.(io.Seeker); ok { + return seekerLen(s) + } + + return -1, nil +} + +// SeekerLen attempts to get the number of bytes remaining at the seeker's +// current position. Returns the number of bytes remaining or error. +func SeekerLen(s io.Seeker) (int64, error) { + // Determine if the seeker is actually seekable. ReaderSeekerCloser + // hides the fact that a io.Readers might not actually be seekable. + switch v := s.(type) { + case ReaderSeekerCloser: + return v.GetLen() + case *ReaderSeekerCloser: + return v.GetLen() + } + + return seekerLen(s) +} + +func seekerLen(s io.Seeker) (int64, error) { + curOffset, err := s.Seek(0, sdkio.SeekCurrent) + if err != nil { + return 0, err + } + + endOffset, err := s.Seek(0, sdkio.SeekEnd) + if err != nil { + return 0, err + } + + _, err = s.Seek(curOffset, sdkio.SeekStart) + if err != nil { + return 0, err + } + + return endOffset - curOffset, nil +} + // Close closes the ReaderSeekerCloser. // // If the ReaderSeekerCloser is not an io.Closer nothing will be done. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index bbf4c2f12..ab6cee169 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.8.34" +const SDKVersion = "1.16.36" diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go new file mode 100644 index 000000000..e83a99886 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go @@ -0,0 +1,120 @@ +package ini + +// ASTKind represents different states in the parse table +// and the type of AST that is being constructed +type ASTKind int + +// ASTKind* is used in the parse table to transition between +// the different states +const ( + ASTKindNone = ASTKind(iota) + ASTKindStart + ASTKindExpr + ASTKindEqualExpr + ASTKindStatement + ASTKindSkipStatement + ASTKindExprStatement + ASTKindSectionStatement + ASTKindNestedSectionStatement + ASTKindCompletedNestedSectionStatement + ASTKindCommentStatement + ASTKindCompletedSectionStatement +) + +func (k ASTKind) String() string { + switch k { + case ASTKindNone: + return "none" + case ASTKindStart: + return "start" + case ASTKindExpr: + return "expr" + case ASTKindStatement: + return "stmt" + case ASTKindSectionStatement: + return "section_stmt" + case ASTKindExprStatement: + return "expr_stmt" + case ASTKindCommentStatement: + return "comment" + case ASTKindNestedSectionStatement: + return "nested_section_stmt" + case ASTKindCompletedSectionStatement: + return "completed_stmt" + case ASTKindSkipStatement: + return "skip" + default: + return "" + } +} + +// AST interface allows us to determine what kind of node we +// are on and casting may not need to be necessary. +// +// The root is always the first node in Children +type AST struct { + Kind ASTKind + Root Token + RootToken bool + Children []AST +} + +func newAST(kind ASTKind, root AST, children ...AST) AST { + return AST{ + Kind: kind, + Children: append([]AST{root}, children...), + } +} + +func newASTWithRootToken(kind ASTKind, root Token, children ...AST) AST { + return AST{ + Kind: kind, + Root: root, + RootToken: true, + Children: children, + } +} + +// AppendChild will append to the list of children an AST has. +func (a *AST) AppendChild(child AST) { + a.Children = append(a.Children, child) +} + +// GetRoot will return the root AST which can be the first entry +// in the children list or a token. +func (a *AST) GetRoot() AST { + if a.RootToken { + return *a + } + + if len(a.Children) == 0 { + return AST{} + } + + return a.Children[0] +} + +// GetChildren will return the current AST's list of children +func (a *AST) GetChildren() []AST { + if len(a.Children) == 0 { + return []AST{} + } + + if a.RootToken { + return a.Children + } + + return a.Children[1:] +} + +// SetChildren will set and override all children of the AST. +func (a *AST) SetChildren(children []AST) { + if a.RootToken { + a.Children = children + } else { + a.Children = append(a.Children[:1], children...) + } +} + +// Start is used to indicate the starting state of the parse table. +var Start = newAST(ASTKindStart, AST{}) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go new file mode 100644 index 000000000..0895d53cb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go @@ -0,0 +1,11 @@ +package ini + +var commaRunes = []rune(",") + +func isComma(b rune) bool { + return b == ',' +} + +func newCommaToken() Token { + return newToken(TokenComma, commaRunes, NoneType) +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go new file mode 100644 index 000000000..0b76999ba --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go @@ -0,0 +1,35 @@ +package ini + +// isComment will return whether or not the next byte(s) is a +// comment. +func isComment(b []rune) bool { + if len(b) == 0 { + return false + } + + switch b[0] { + case ';': + return true + case '#': + return true + } + + return false +} + +// newCommentToken will create a comment token and +// return how many bytes were read. +func newCommentToken(b []rune) (Token, int, error) { + i := 0 + for ; i < len(b); i++ { + if b[i] == '\n' { + break + } + + if len(b)-i > 2 && b[i] == '\r' && b[i+1] == '\n' { + break + } + } + + return newToken(TokenComment, b[:i], NoneType), i, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go new file mode 100644 index 000000000..25ce0fe13 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go @@ -0,0 +1,29 @@ +// Package ini is an LL(1) parser for configuration files. +// +// Example: +// sections, err := ini.OpenFile("/path/to/file") +// if err != nil { +// panic(err) +// } +// +// profile := "foo" +// section, ok := sections.GetSection(profile) +// if !ok { +// fmt.Printf("section %q could not be found", profile) +// } +// +// Below is the BNF that describes this parser +// Grammar: +// stmt -> value stmt' +// stmt' -> epsilon | op stmt +// value -> number | string | boolean | quoted_string +// +// section -> [ section' +// section' -> value section_close +// section_close -> ] +// +// SkipState will skip (NL WS)+ +// +// comment -> # comment' | ; comment' +// comment' -> epsilon | value +package ini diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go new file mode 100644 index 000000000..04345a54c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go @@ -0,0 +1,4 @@ +package ini + +// emptyToken is used to satisfy the Token interface +var emptyToken = newToken(TokenNone, []rune{}, NoneType) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go new file mode 100644 index 000000000..91ba2a59d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go @@ -0,0 +1,24 @@ +package ini + +// newExpression will return an expression AST. +// Expr represents an expression +// +// grammar: +// expr -> string | number +func newExpression(tok Token) AST { + return newASTWithRootToken(ASTKindExpr, tok) +} + +func newEqualExpr(left AST, tok Token) AST { + return newASTWithRootToken(ASTKindEqualExpr, tok, left) +} + +// EqualExprKey will return a LHS value in the equal expr +func EqualExprKey(ast AST) string { + children := ast.GetChildren() + if len(children) == 0 || ast.Kind != ASTKindEqualExpr { + return "" + } + + return string(children[0].Root.Raw()) +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go new file mode 100644 index 000000000..8d462f77e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go @@ -0,0 +1,17 @@ +// +build gofuzz + +package ini + +import ( + "bytes" +) + +func Fuzz(data []byte) int { + b := bytes.NewReader(data) + + if _, err := Parse(b); err != nil { + return 0 + } + + return 1 +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go new file mode 100644 index 000000000..3b0ca7afe --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go @@ -0,0 +1,51 @@ +package ini + +import ( + "io" + "os" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +// OpenFile takes a path to a given file, and will open and parse +// that file. +func OpenFile(path string) (Sections, error) { + f, err := os.Open(path) + if err != nil { + return Sections{}, awserr.New(ErrCodeUnableToReadFile, "unable to open file", err) + } + defer f.Close() + + return Parse(f) +} + +// Parse will parse the given file using the shared config +// visitor. +func Parse(f io.Reader) (Sections, error) { + tree, err := ParseAST(f) + if err != nil { + return Sections{}, err + } + + v := NewDefaultVisitor() + if err = Walk(tree, v); err != nil { + return Sections{}, err + } + + return v.Sections, nil +} + +// ParseBytes will parse the given bytes and return the parsed sections. +func ParseBytes(b []byte) (Sections, error) { + tree, err := ParseASTBytes(b) + if err != nil { + return Sections{}, err + } + + v := NewDefaultVisitor() + if err = Walk(tree, v); err != nil { + return Sections{}, err + } + + return v.Sections, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go new file mode 100644 index 000000000..582c024ad --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go @@ -0,0 +1,165 @@ +package ini + +import ( + "bytes" + "io" + "io/ioutil" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +const ( + // ErrCodeUnableToReadFile is used when a file is failed to be + // opened or read from. + ErrCodeUnableToReadFile = "FailedRead" +) + +// TokenType represents the various different tokens types +type TokenType int + +func (t TokenType) String() string { + switch t { + case TokenNone: + return "none" + case TokenLit: + return "literal" + case TokenSep: + return "sep" + case TokenOp: + return "op" + case TokenWS: + return "ws" + case TokenNL: + return "newline" + case TokenComment: + return "comment" + case TokenComma: + return "comma" + default: + return "" + } +} + +// TokenType enums +const ( + TokenNone = TokenType(iota) + TokenLit + TokenSep + TokenComma + TokenOp + TokenWS + TokenNL + TokenComment +) + +type iniLexer struct{} + +// Tokenize will return a list of tokens during lexical analysis of the +// io.Reader. +func (l *iniLexer) Tokenize(r io.Reader) ([]Token, error) { + b, err := ioutil.ReadAll(r) + if err != nil { + return nil, awserr.New(ErrCodeUnableToReadFile, "unable to read file", err) + } + + return l.tokenize(b) +} + +func (l *iniLexer) tokenize(b []byte) ([]Token, error) { + runes := bytes.Runes(b) + var err error + n := 0 + tokenAmount := countTokens(runes) + tokens := make([]Token, tokenAmount) + count := 0 + + for len(runes) > 0 && count < tokenAmount { + switch { + case isWhitespace(runes[0]): + tokens[count], n, err = newWSToken(runes) + case isComma(runes[0]): + tokens[count], n = newCommaToken(), 1 + case isComment(runes): + tokens[count], n, err = newCommentToken(runes) + case isNewline(runes): + tokens[count], n, err = newNewlineToken(runes) + case isSep(runes): + tokens[count], n, err = newSepToken(runes) + case isOp(runes): + tokens[count], n, err = newOpToken(runes) + default: + tokens[count], n, err = newLitToken(runes) + } + + if err != nil { + return nil, err + } + + count++ + + runes = runes[n:] + } + + return tokens[:count], nil +} + +func countTokens(runes []rune) int { + count, n := 0, 0 + var err error + + for len(runes) > 0 { + switch { + case isWhitespace(runes[0]): + _, n, err = newWSToken(runes) + case isComma(runes[0]): + _, n = newCommaToken(), 1 + case isComment(runes): + _, n, err = newCommentToken(runes) + case isNewline(runes): + _, n, err = newNewlineToken(runes) + case isSep(runes): + _, n, err = newSepToken(runes) + case isOp(runes): + _, n, err = newOpToken(runes) + default: + _, n, err = newLitToken(runes) + } + + if err != nil { + return 0 + } + + count++ + runes = runes[n:] + } + + return count + 1 +} + +// Token indicates a metadata about a given value. +type Token struct { + t TokenType + ValueType ValueType + base int + raw []rune +} + +var emptyValue = Value{} + +func newToken(t TokenType, raw []rune, v ValueType) Token { + return Token{ + t: t, + raw: raw, + ValueType: v, + } +} + +// Raw return the raw runes that were consumed +func (tok Token) Raw() []rune { + return tok.raw +} + +// Type returns the token type +func (tok Token) Type() TokenType { + return tok.t +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go new file mode 100644 index 000000000..f99703372 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go @@ -0,0 +1,347 @@ +package ini + +import ( + "fmt" + "io" +) + +// State enums for the parse table +const ( + InvalidState = iota + // stmt -> value stmt' + StatementState + // stmt' -> MarkComplete | op stmt + StatementPrimeState + // value -> number | string | boolean | quoted_string + ValueState + // section -> [ section' + OpenScopeState + // section' -> value section_close + SectionState + // section_close -> ] + CloseScopeState + // SkipState will skip (NL WS)+ + SkipState + // SkipTokenState will skip any token and push the previous + // state onto the stack. + SkipTokenState + // comment -> # comment' | ; comment' + // comment' -> MarkComplete | value + CommentState + // MarkComplete state will complete statements and move that + // to the completed AST list + MarkCompleteState + // TerminalState signifies that the tokens have been fully parsed + TerminalState +) + +// parseTable is a state machine to dictate the grammar above. +var parseTable = map[ASTKind]map[TokenType]int{ + ASTKindStart: map[TokenType]int{ + TokenLit: StatementState, + TokenSep: OpenScopeState, + TokenWS: SkipTokenState, + TokenNL: SkipTokenState, + TokenComment: CommentState, + TokenNone: TerminalState, + }, + ASTKindCommentStatement: map[TokenType]int{ + TokenLit: StatementState, + TokenSep: OpenScopeState, + TokenWS: SkipTokenState, + TokenNL: SkipTokenState, + TokenComment: CommentState, + TokenNone: MarkCompleteState, + }, + ASTKindExpr: map[TokenType]int{ + TokenOp: StatementPrimeState, + TokenLit: ValueState, + TokenSep: OpenScopeState, + TokenWS: ValueState, + TokenNL: SkipState, + TokenComment: CommentState, + TokenNone: MarkCompleteState, + }, + ASTKindEqualExpr: map[TokenType]int{ + TokenLit: ValueState, + TokenWS: SkipTokenState, + TokenNL: SkipState, + }, + ASTKindStatement: map[TokenType]int{ + TokenLit: SectionState, + TokenSep: CloseScopeState, + TokenWS: SkipTokenState, + TokenNL: SkipTokenState, + TokenComment: CommentState, + TokenNone: MarkCompleteState, + }, + ASTKindExprStatement: map[TokenType]int{ + TokenLit: ValueState, + TokenSep: OpenScopeState, + TokenOp: ValueState, + TokenWS: ValueState, + TokenNL: MarkCompleteState, + TokenComment: CommentState, + TokenNone: TerminalState, + TokenComma: SkipState, + }, + ASTKindSectionStatement: map[TokenType]int{ + TokenLit: SectionState, + TokenOp: SectionState, + TokenSep: CloseScopeState, + TokenWS: SectionState, + TokenNL: SkipTokenState, + }, + ASTKindCompletedSectionStatement: map[TokenType]int{ + TokenWS: SkipTokenState, + TokenNL: SkipTokenState, + TokenLit: StatementState, + TokenSep: OpenScopeState, + TokenComment: CommentState, + TokenNone: MarkCompleteState, + }, + ASTKindSkipStatement: map[TokenType]int{ + TokenLit: StatementState, + TokenSep: OpenScopeState, + TokenWS: SkipTokenState, + TokenNL: SkipTokenState, + TokenComment: CommentState, + TokenNone: TerminalState, + }, +} + +// ParseAST will parse input from an io.Reader using +// an LL(1) parser. +func ParseAST(r io.Reader) ([]AST, error) { + lexer := iniLexer{} + tokens, err := lexer.Tokenize(r) + if err != nil { + return []AST{}, err + } + + return parse(tokens) +} + +// ParseASTBytes will parse input from a byte slice using +// an LL(1) parser. +func ParseASTBytes(b []byte) ([]AST, error) { + lexer := iniLexer{} + tokens, err := lexer.tokenize(b) + if err != nil { + return []AST{}, err + } + + return parse(tokens) +} + +func parse(tokens []Token) ([]AST, error) { + start := Start + stack := newParseStack(3, len(tokens)) + + stack.Push(start) + s := newSkipper() + +loop: + for stack.Len() > 0 { + k := stack.Pop() + + var tok Token + if len(tokens) == 0 { + // this occurs when all the tokens have been processed + // but reduction of what's left on the stack needs to + // occur. + tok = emptyToken + } else { + tok = tokens[0] + } + + step := parseTable[k.Kind][tok.Type()] + if s.ShouldSkip(tok) { + // being in a skip state with no tokens will break out of + // the parse loop since there is nothing left to process. + if len(tokens) == 0 { + break loop + } + + step = SkipTokenState + } + + switch step { + case TerminalState: + // Finished parsing. Push what should be the last + // statement to the stack. If there is anything left + // on the stack, an error in parsing has occurred. + if k.Kind != ASTKindStart { + stack.MarkComplete(k) + } + break loop + case SkipTokenState: + // When skipping a token, the previous state was popped off the stack. + // To maintain the correct state, the previous state will be pushed + // onto the stack. + stack.Push(k) + case StatementState: + if k.Kind != ASTKindStart { + stack.MarkComplete(k) + } + expr := newExpression(tok) + stack.Push(expr) + case StatementPrimeState: + if tok.Type() != TokenOp { + stack.MarkComplete(k) + continue + } + + if k.Kind != ASTKindExpr { + return nil, NewParseError( + fmt.Sprintf("invalid expression: expected Expr type, but found %T type", k), + ) + } + + k = trimSpaces(k) + expr := newEqualExpr(k, tok) + stack.Push(expr) + case ValueState: + // ValueState requires the previous state to either be an equal expression + // or an expression statement. + // + // This grammar occurs when the RHS is a number, word, or quoted string. + // equal_expr -> lit op equal_expr' + // equal_expr' -> number | string | quoted_string + // quoted_string -> " quoted_string' + // quoted_string' -> string quoted_string_end + // quoted_string_end -> " + // + // otherwise + // expr_stmt -> equal_expr (expr_stmt')* + // expr_stmt' -> ws S | op S | MarkComplete + // S -> equal_expr' expr_stmt' + switch k.Kind { + case ASTKindEqualExpr: + // assiging a value to some key + k.AppendChild(newExpression(tok)) + stack.Push(newExprStatement(k)) + case ASTKindExpr: + k.Root.raw = append(k.Root.raw, tok.Raw()...) + stack.Push(k) + case ASTKindExprStatement: + root := k.GetRoot() + children := root.GetChildren() + if len(children) == 0 { + return nil, NewParseError( + fmt.Sprintf("invalid expression: AST contains no children %s", k.Kind), + ) + } + + rhs := children[len(children)-1] + + if rhs.Root.ValueType != QuotedStringType { + rhs.Root.ValueType = StringType + rhs.Root.raw = append(rhs.Root.raw, tok.Raw()...) + + } + + children[len(children)-1] = rhs + k.SetChildren(children) + + stack.Push(k) + } + case OpenScopeState: + if !runeCompare(tok.Raw(), openBrace) { + return nil, NewParseError("expected '['") + } + + stmt := newStatement() + stack.Push(stmt) + case CloseScopeState: + if !runeCompare(tok.Raw(), closeBrace) { + return nil, NewParseError("expected ']'") + } + + k = trimSpaces(k) + stack.Push(newCompletedSectionStatement(k)) + case SectionState: + var stmt AST + + switch k.Kind { + case ASTKindStatement: + // If there are multiple literals inside of a scope declaration, + // then the current token's raw value will be appended to the Name. + // + // This handles cases like [ profile default ] + // + // k will represent a SectionStatement with the children representing + // the label of the section + stmt = newSectionStatement(tok) + case ASTKindSectionStatement: + k.Root.raw = append(k.Root.raw, tok.Raw()...) + stmt = k + default: + return nil, NewParseError( + fmt.Sprintf("invalid statement: expected statement: %v", k.Kind), + ) + } + + stack.Push(stmt) + case MarkCompleteState: + if k.Kind != ASTKindStart { + stack.MarkComplete(k) + } + + if stack.Len() == 0 { + stack.Push(start) + } + case SkipState: + stack.Push(newSkipStatement(k)) + s.Skip() + case CommentState: + if k.Kind == ASTKindStart { + stack.Push(k) + } else { + stack.MarkComplete(k) + } + + stmt := newCommentStatement(tok) + stack.Push(stmt) + default: + return nil, NewParseError(fmt.Sprintf("invalid state with ASTKind %v and TokenType %v", k, tok)) + } + + if len(tokens) > 0 { + tokens = tokens[1:] + } + } + + // this occurs when a statement has not been completed + if stack.top > 1 { + return nil, NewParseError(fmt.Sprintf("incomplete expression: %v", stack.container)) + } + + // returns a sublist which excludes the start symbol + return stack.List(), nil +} + +// trimSpaces will trim spaces on the left and right hand side of +// the literal. +func trimSpaces(k AST) AST { + // trim left hand side of spaces + for i := 0; i < len(k.Root.raw); i++ { + if !isWhitespace(k.Root.raw[i]) { + break + } + + k.Root.raw = k.Root.raw[1:] + i-- + } + + // trim right hand side of spaces + for i := len(k.Root.raw) - 1; i >= 0; i-- { + if !isWhitespace(k.Root.raw[i]) { + break + } + + k.Root.raw = k.Root.raw[:len(k.Root.raw)-1] + } + + return k +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go new file mode 100644 index 000000000..24df543d3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go @@ -0,0 +1,324 @@ +package ini + +import ( + "fmt" + "strconv" + "strings" +) + +var ( + runesTrue = []rune("true") + runesFalse = []rune("false") +) + +var literalValues = [][]rune{ + runesTrue, + runesFalse, +} + +func isBoolValue(b []rune) bool { + for _, lv := range literalValues { + if isLitValue(lv, b) { + return true + } + } + return false +} + +func isLitValue(want, have []rune) bool { + if len(have) < len(want) { + return false + } + + for i := 0; i < len(want); i++ { + if want[i] != have[i] { + return false + } + } + + return true +} + +// isNumberValue will return whether not the leading characters in +// a byte slice is a number. A number is delimited by whitespace or +// the newline token. +// +// A number is defined to be in a binary, octal, decimal (int | float), hex format, +// or in scientific notation. +func isNumberValue(b []rune) bool { + negativeIndex := 0 + helper := numberHelper{} + needDigit := false + + for i := 0; i < len(b); i++ { + negativeIndex++ + + switch b[i] { + case '-': + if helper.IsNegative() || negativeIndex != 1 { + return false + } + helper.Determine(b[i]) + needDigit = true + continue + case 'e', 'E': + if err := helper.Determine(b[i]); err != nil { + return false + } + negativeIndex = 0 + needDigit = true + continue + case 'b': + if helper.numberFormat == hex { + break + } + fallthrough + case 'o', 'x': + needDigit = true + if i == 0 { + return false + } + + fallthrough + case '.': + if err := helper.Determine(b[i]); err != nil { + return false + } + needDigit = true + continue + } + + if i > 0 && (isNewline(b[i:]) || isWhitespace(b[i])) { + return !needDigit + } + + if !helper.CorrectByte(b[i]) { + return false + } + needDigit = false + } + + return !needDigit +} + +func isValid(b []rune) (bool, int, error) { + if len(b) == 0 { + // TODO: should probably return an error + return false, 0, nil + } + + return isValidRune(b[0]), 1, nil +} + +func isValidRune(r rune) bool { + return r != ':' && r != '=' && r != '[' && r != ']' && r != ' ' && r != '\n' +} + +// ValueType is an enum that will signify what type +// the Value is +type ValueType int + +func (v ValueType) String() string { + switch v { + case NoneType: + return "NONE" + case DecimalType: + return "FLOAT" + case IntegerType: + return "INT" + case StringType: + return "STRING" + case BoolType: + return "BOOL" + } + + return "" +} + +// ValueType enums +const ( + NoneType = ValueType(iota) + DecimalType + IntegerType + StringType + QuotedStringType + BoolType +) + +// Value is a union container +type Value struct { + Type ValueType + raw []rune + + integer int64 + decimal float64 + boolean bool + str string +} + +func newValue(t ValueType, base int, raw []rune) (Value, error) { + v := Value{ + Type: t, + raw: raw, + } + var err error + + switch t { + case DecimalType: + v.decimal, err = strconv.ParseFloat(string(raw), 64) + case IntegerType: + if base != 10 { + raw = raw[2:] + } + + v.integer, err = strconv.ParseInt(string(raw), base, 64) + case StringType: + v.str = string(raw) + case QuotedStringType: + v.str = string(raw[1 : len(raw)-1]) + case BoolType: + v.boolean = runeCompare(v.raw, runesTrue) + } + + // issue 2253 + // + // if the value trying to be parsed is too large, then we will use + // the 'StringType' and raw value instead. + if nerr, ok := err.(*strconv.NumError); ok && nerr.Err == strconv.ErrRange { + v.Type = StringType + v.str = string(raw) + err = nil + } + + return v, err +} + +// Append will append values and change the type to a string +// type. +func (v *Value) Append(tok Token) { + r := tok.Raw() + if v.Type != QuotedStringType { + v.Type = StringType + r = tok.raw[1 : len(tok.raw)-1] + } + if tok.Type() != TokenLit { + v.raw = append(v.raw, tok.Raw()...) + } else { + v.raw = append(v.raw, r...) + } +} + +func (v Value) String() string { + switch v.Type { + case DecimalType: + return fmt.Sprintf("decimal: %f", v.decimal) + case IntegerType: + return fmt.Sprintf("integer: %d", v.integer) + case StringType: + return fmt.Sprintf("string: %s", string(v.raw)) + case QuotedStringType: + return fmt.Sprintf("quoted string: %s", string(v.raw)) + case BoolType: + return fmt.Sprintf("bool: %t", v.boolean) + default: + return "union not set" + } +} + +func newLitToken(b []rune) (Token, int, error) { + n := 0 + var err error + + token := Token{} + if b[0] == '"' { + n, err = getStringValue(b) + if err != nil { + return token, n, err + } + + token = newToken(TokenLit, b[:n], QuotedStringType) + } else if isNumberValue(b) { + var base int + base, n, err = getNumericalValue(b) + if err != nil { + return token, 0, err + } + + value := b[:n] + vType := IntegerType + if contains(value, '.') || hasExponent(value) { + vType = DecimalType + } + token = newToken(TokenLit, value, vType) + token.base = base + } else if isBoolValue(b) { + n, err = getBoolValue(b) + + token = newToken(TokenLit, b[:n], BoolType) + } else { + n, err = getValue(b) + token = newToken(TokenLit, b[:n], StringType) + } + + return token, n, err +} + +// IntValue returns an integer value +func (v Value) IntValue() int64 { + return v.integer +} + +// FloatValue returns a float value +func (v Value) FloatValue() float64 { + return v.decimal +} + +// BoolValue returns a bool value +func (v Value) BoolValue() bool { + return v.boolean +} + +func isTrimmable(r rune) bool { + switch r { + case '\n', ' ': + return true + } + return false +} + +// StringValue returns the string value +func (v Value) StringValue() string { + switch v.Type { + case StringType: + return strings.TrimFunc(string(v.raw), isTrimmable) + case QuotedStringType: + // preserve all characters in the quotes + return string(removeEscapedCharacters(v.raw[1 : len(v.raw)-1])) + default: + return strings.TrimFunc(string(v.raw), isTrimmable) + } +} + +func contains(runes []rune, c rune) bool { + for i := 0; i < len(runes); i++ { + if runes[i] == c { + return true + } + } + + return false +} + +func runeCompare(v1 []rune, v2 []rune) bool { + if len(v1) != len(v2) { + return false + } + + for i := 0; i < len(v1); i++ { + if v1[i] != v2[i] { + return false + } + } + + return true +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go new file mode 100644 index 000000000..e52ac399f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go @@ -0,0 +1,30 @@ +package ini + +func isNewline(b []rune) bool { + if len(b) == 0 { + return false + } + + if b[0] == '\n' { + return true + } + + if len(b) < 2 { + return false + } + + return b[0] == '\r' && b[1] == '\n' +} + +func newNewlineToken(b []rune) (Token, int, error) { + i := 1 + if b[0] == '\r' && isNewline(b[1:]) { + i++ + } + + if !isNewline([]rune(b[:i])) { + return emptyToken, 0, NewParseError("invalid new line token") + } + + return newToken(TokenNL, b[:i], NoneType), i, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go new file mode 100644 index 000000000..a45c0bc56 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go @@ -0,0 +1,152 @@ +package ini + +import ( + "bytes" + "fmt" + "strconv" +) + +const ( + none = numberFormat(iota) + binary + octal + decimal + hex + exponent +) + +type numberFormat int + +// numberHelper is used to dictate what format a number is in +// and what to do for negative values. Since -1e-4 is a valid +// number, we cannot just simply check for duplicate negatives. +type numberHelper struct { + numberFormat numberFormat + + negative bool + negativeExponent bool +} + +func (b numberHelper) Exists() bool { + return b.numberFormat != none +} + +func (b numberHelper) IsNegative() bool { + return b.negative || b.negativeExponent +} + +func (b *numberHelper) Determine(c rune) error { + if b.Exists() { + return NewParseError(fmt.Sprintf("multiple number formats: 0%v", string(c))) + } + + switch c { + case 'b': + b.numberFormat = binary + case 'o': + b.numberFormat = octal + case 'x': + b.numberFormat = hex + case 'e', 'E': + b.numberFormat = exponent + case '-': + if b.numberFormat != exponent { + b.negative = true + } else { + b.negativeExponent = true + } + case '.': + b.numberFormat = decimal + default: + return NewParseError(fmt.Sprintf("invalid number character: %v", string(c))) + } + + return nil +} + +func (b numberHelper) CorrectByte(c rune) bool { + switch { + case b.numberFormat == binary: + if !isBinaryByte(c) { + return false + } + case b.numberFormat == octal: + if !isOctalByte(c) { + return false + } + case b.numberFormat == hex: + if !isHexByte(c) { + return false + } + case b.numberFormat == decimal: + if !isDigit(c) { + return false + } + case b.numberFormat == exponent: + if !isDigit(c) { + return false + } + case b.negativeExponent: + if !isDigit(c) { + return false + } + case b.negative: + if !isDigit(c) { + return false + } + default: + if !isDigit(c) { + return false + } + } + + return true +} + +func (b numberHelper) Base() int { + switch b.numberFormat { + case binary: + return 2 + case octal: + return 8 + case hex: + return 16 + default: + return 10 + } +} + +func (b numberHelper) String() string { + buf := bytes.Buffer{} + i := 0 + + switch b.numberFormat { + case binary: + i++ + buf.WriteString(strconv.Itoa(i) + ": binary format\n") + case octal: + i++ + buf.WriteString(strconv.Itoa(i) + ": octal format\n") + case hex: + i++ + buf.WriteString(strconv.Itoa(i) + ": hex format\n") + case exponent: + i++ + buf.WriteString(strconv.Itoa(i) + ": exponent format\n") + default: + i++ + buf.WriteString(strconv.Itoa(i) + ": integer format\n") + } + + if b.negative { + i++ + buf.WriteString(strconv.Itoa(i) + ": negative format\n") + } + + if b.negativeExponent { + i++ + buf.WriteString(strconv.Itoa(i) + ": negative exponent format\n") + } + + return buf.String() +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go new file mode 100644 index 000000000..8a84c7cbe --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go @@ -0,0 +1,39 @@ +package ini + +import ( + "fmt" +) + +var ( + equalOp = []rune("=") + equalColonOp = []rune(":") +) + +func isOp(b []rune) bool { + if len(b) == 0 { + return false + } + + switch b[0] { + case '=': + return true + case ':': + return true + default: + return false + } +} + +func newOpToken(b []rune) (Token, int, error) { + tok := Token{} + + switch b[0] { + case '=': + tok = newToken(TokenOp, equalOp, NoneType) + case ':': + tok = newToken(TokenOp, equalColonOp, NoneType) + default: + return tok, 0, NewParseError(fmt.Sprintf("unexpected op type, %v", b[0])) + } + return tok, 1, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go new file mode 100644 index 000000000..457287019 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go @@ -0,0 +1,43 @@ +package ini + +import "fmt" + +const ( + // ErrCodeParseError is returned when a parsing error + // has occurred. + ErrCodeParseError = "INIParseError" +) + +// ParseError is an error which is returned during any part of +// the parsing process. +type ParseError struct { + msg string +} + +// NewParseError will return a new ParseError where message +// is the description of the error. +func NewParseError(message string) *ParseError { + return &ParseError{ + msg: message, + } +} + +// Code will return the ErrCodeParseError +func (err *ParseError) Code() string { + return ErrCodeParseError +} + +// Message returns the error's message +func (err *ParseError) Message() string { + return err.msg +} + +// OrigError return nothing since there will never be any +// original error. +func (err *ParseError) OrigError() error { + return nil +} + +func (err *ParseError) Error() string { + return fmt.Sprintf("%s: %s", err.Code(), err.Message()) +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go new file mode 100644 index 000000000..7f01cf7c7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go @@ -0,0 +1,60 @@ +package ini + +import ( + "bytes" + "fmt" +) + +// ParseStack is a stack that contains a container, the stack portion, +// and the list which is the list of ASTs that have been successfully +// parsed. +type ParseStack struct { + top int + container []AST + list []AST + index int +} + +func newParseStack(sizeContainer, sizeList int) ParseStack { + return ParseStack{ + container: make([]AST, sizeContainer), + list: make([]AST, sizeList), + } +} + +// Pop will return and truncate the last container element. +func (s *ParseStack) Pop() AST { + s.top-- + return s.container[s.top] +} + +// Push will add the new AST to the container +func (s *ParseStack) Push(ast AST) { + s.container[s.top] = ast + s.top++ +} + +// MarkComplete will append the AST to the list of completed statements +func (s *ParseStack) MarkComplete(ast AST) { + s.list[s.index] = ast + s.index++ +} + +// List will return the completed statements +func (s ParseStack) List() []AST { + return s.list[:s.index] +} + +// Len will return the length of the container +func (s *ParseStack) Len() int { + return s.top +} + +func (s ParseStack) String() string { + buf := bytes.Buffer{} + for i, node := range s.list { + buf.WriteString(fmt.Sprintf("%d: %v\n", i+1, node)) + } + + return buf.String() +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go new file mode 100644 index 000000000..f82095ba2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go @@ -0,0 +1,41 @@ +package ini + +import ( + "fmt" +) + +var ( + emptyRunes = []rune{} +) + +func isSep(b []rune) bool { + if len(b) == 0 { + return false + } + + switch b[0] { + case '[', ']': + return true + default: + return false + } +} + +var ( + openBrace = []rune("[") + closeBrace = []rune("]") +) + +func newSepToken(b []rune) (Token, int, error) { + tok := Token{} + + switch b[0] { + case '[': + tok = newToken(TokenSep, openBrace, NoneType) + case ']': + tok = newToken(TokenSep, closeBrace, NoneType) + default: + return tok, 0, NewParseError(fmt.Sprintf("unexpected sep type, %v", b[0])) + } + return tok, 1, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go new file mode 100644 index 000000000..6bb696447 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go @@ -0,0 +1,45 @@ +package ini + +// skipper is used to skip certain blocks of an ini file. +// Currently skipper is used to skip nested blocks of ini +// files. See example below +// +// [ foo ] +// nested = ; this section will be skipped +// a=b +// c=d +// bar=baz ; this will be included +type skipper struct { + shouldSkip bool + TokenSet bool + prevTok Token +} + +func newSkipper() skipper { + return skipper{ + prevTok: emptyToken, + } +} + +func (s *skipper) ShouldSkip(tok Token) bool { + if s.shouldSkip && + s.prevTok.Type() == TokenNL && + tok.Type() != TokenWS { + + s.Continue() + return false + } + s.prevTok = tok + + return s.shouldSkip +} + +func (s *skipper) Skip() { + s.shouldSkip = true + s.prevTok = emptyToken +} + +func (s *skipper) Continue() { + s.shouldSkip = false + s.prevTok = emptyToken +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go new file mode 100644 index 000000000..18f3fe893 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go @@ -0,0 +1,35 @@ +package ini + +// Statement is an empty AST mostly used for transitioning states. +func newStatement() AST { + return newAST(ASTKindStatement, AST{}) +} + +// SectionStatement represents a section AST +func newSectionStatement(tok Token) AST { + return newASTWithRootToken(ASTKindSectionStatement, tok) +} + +// ExprStatement represents a completed expression AST +func newExprStatement(ast AST) AST { + return newAST(ASTKindExprStatement, ast) +} + +// CommentStatement represents a comment in the ini definition. +// +// grammar: +// comment -> #comment' | ;comment' +// comment' -> epsilon | value +func newCommentStatement(tok Token) AST { + return newAST(ASTKindCommentStatement, newExpression(tok)) +} + +// CompletedSectionStatement represents a completed section +func newCompletedSectionStatement(ast AST) AST { + return newAST(ASTKindCompletedSectionStatement, ast) +} + +// SkipStatement is used to skip whole statements +func newSkipStatement(ast AST) AST { + return newAST(ASTKindSkipStatement, ast) +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go new file mode 100644 index 000000000..305999d29 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go @@ -0,0 +1,284 @@ +package ini + +import ( + "fmt" +) + +// getStringValue will return a quoted string and the amount +// of bytes read +// +// an error will be returned if the string is not properly formatted +func getStringValue(b []rune) (int, error) { + if b[0] != '"' { + return 0, NewParseError("strings must start with '\"'") + } + + endQuote := false + i := 1 + + for ; i < len(b) && !endQuote; i++ { + if escaped := isEscaped(b[:i], b[i]); b[i] == '"' && !escaped { + endQuote = true + break + } else if escaped { + /*c, err := getEscapedByte(b[i]) + if err != nil { + return 0, err + } + + b[i-1] = c + b = append(b[:i], b[i+1:]...) + i--*/ + + continue + } + } + + if !endQuote { + return 0, NewParseError("missing '\"' in string value") + } + + return i + 1, nil +} + +// getBoolValue will return a boolean and the amount +// of bytes read +// +// an error will be returned if the boolean is not of a correct +// value +func getBoolValue(b []rune) (int, error) { + if len(b) < 4 { + return 0, NewParseError("invalid boolean value") + } + + n := 0 + for _, lv := range literalValues { + if len(lv) > len(b) { + continue + } + + if isLitValue(lv, b) { + n = len(lv) + } + } + + if n == 0 { + return 0, NewParseError("invalid boolean value") + } + + return n, nil +} + +// getNumericalValue will return a numerical string, the amount +// of bytes read, and the base of the number +// +// an error will be returned if the number is not of a correct +// value +func getNumericalValue(b []rune) (int, int, error) { + if !isDigit(b[0]) { + return 0, 0, NewParseError("invalid digit value") + } + + i := 0 + helper := numberHelper{} + +loop: + for negativeIndex := 0; i < len(b); i++ { + negativeIndex++ + + if !isDigit(b[i]) { + switch b[i] { + case '-': + if helper.IsNegative() || negativeIndex != 1 { + return 0, 0, NewParseError("parse error '-'") + } + + n := getNegativeNumber(b[i:]) + i += (n - 1) + helper.Determine(b[i]) + continue + case '.': + if err := helper.Determine(b[i]); err != nil { + return 0, 0, err + } + case 'e', 'E': + if err := helper.Determine(b[i]); err != nil { + return 0, 0, err + } + + negativeIndex = 0 + case 'b': + if helper.numberFormat == hex { + break + } + fallthrough + case 'o', 'x': + if i == 0 && b[i] != '0' { + return 0, 0, NewParseError("incorrect base format, expected leading '0'") + } + + if i != 1 { + return 0, 0, NewParseError(fmt.Sprintf("incorrect base format found %s at %d index", string(b[i]), i)) + } + + if err := helper.Determine(b[i]); err != nil { + return 0, 0, err + } + default: + if isWhitespace(b[i]) { + break loop + } + + if isNewline(b[i:]) { + break loop + } + + if !(helper.numberFormat == hex && isHexByte(b[i])) { + if i+2 < len(b) && !isNewline(b[i:i+2]) { + return 0, 0, NewParseError("invalid numerical character") + } else if !isNewline([]rune{b[i]}) { + return 0, 0, NewParseError("invalid numerical character") + } + + break loop + } + } + } + } + + return helper.Base(), i, nil +} + +// isDigit will return whether or not something is an integer +func isDigit(b rune) bool { + return b >= '0' && b <= '9' +} + +func hasExponent(v []rune) bool { + return contains(v, 'e') || contains(v, 'E') +} + +func isBinaryByte(b rune) bool { + switch b { + case '0', '1': + return true + default: + return false + } +} + +func isOctalByte(b rune) bool { + switch b { + case '0', '1', '2', '3', '4', '5', '6', '7': + return true + default: + return false + } +} + +func isHexByte(b rune) bool { + if isDigit(b) { + return true + } + return (b >= 'A' && b <= 'F') || + (b >= 'a' && b <= 'f') +} + +func getValue(b []rune) (int, error) { + i := 0 + + for i < len(b) { + if isNewline(b[i:]) { + break + } + + if isOp(b[i:]) { + break + } + + valid, n, err := isValid(b[i:]) + if err != nil { + return 0, err + } + + if !valid { + break + } + + i += n + } + + return i, nil +} + +// getNegativeNumber will return a negative number from a +// byte slice. This will iterate through all characters until +// a non-digit has been found. +func getNegativeNumber(b []rune) int { + if b[0] != '-' { + return 0 + } + + i := 1 + for ; i < len(b); i++ { + if !isDigit(b[i]) { + return i + } + } + + return i +} + +// isEscaped will return whether or not the character is an escaped +// character. +func isEscaped(value []rune, b rune) bool { + if len(value) == 0 { + return false + } + + switch b { + case '\'': // single quote + case '"': // quote + case 'n': // newline + case 't': // tab + case '\\': // backslash + default: + return false + } + + return value[len(value)-1] == '\\' +} + +func getEscapedByte(b rune) (rune, error) { + switch b { + case '\'': // single quote + return '\'', nil + case '"': // quote + return '"', nil + case 'n': // newline + return '\n', nil + case 't': // table + return '\t', nil + case '\\': // backslash + return '\\', nil + default: + return b, NewParseError(fmt.Sprintf("invalid escaped character %c", b)) + } +} + +func removeEscapedCharacters(b []rune) []rune { + for i := 0; i < len(b); i++ { + if isEscaped(b[:i], b[i]) { + c, err := getEscapedByte(b[i]) + if err != nil { + return b + } + + b[i-1] = c + b = append(b[:i], b[i+1:]...) + i-- + } + } + + return b +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go new file mode 100644 index 000000000..94841c324 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go @@ -0,0 +1,166 @@ +package ini + +import ( + "fmt" + "sort" +) + +// Visitor is an interface used by walkers that will +// traverse an array of ASTs. +type Visitor interface { + VisitExpr(AST) error + VisitStatement(AST) error +} + +// DefaultVisitor is used to visit statements and expressions +// and ensure that they are both of the correct format. +// In addition, upon visiting this will build sections and populate +// the Sections field which can be used to retrieve profile +// configuration. +type DefaultVisitor struct { + scope string + Sections Sections +} + +// NewDefaultVisitor return a DefaultVisitor +func NewDefaultVisitor() *DefaultVisitor { + return &DefaultVisitor{ + Sections: Sections{ + container: map[string]Section{}, + }, + } +} + +// VisitExpr visits expressions... +func (v *DefaultVisitor) VisitExpr(expr AST) error { + t := v.Sections.container[v.scope] + if t.values == nil { + t.values = values{} + } + + switch expr.Kind { + case ASTKindExprStatement: + opExpr := expr.GetRoot() + switch opExpr.Kind { + case ASTKindEqualExpr: + children := opExpr.GetChildren() + if len(children) <= 1 { + return NewParseError("unexpected token type") + } + + rhs := children[1] + + if rhs.Root.Type() != TokenLit { + return NewParseError("unexpected token type") + } + + key := EqualExprKey(opExpr) + v, err := newValue(rhs.Root.ValueType, rhs.Root.base, rhs.Root.Raw()) + if err != nil { + return err + } + + t.values[key] = v + default: + return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) + } + default: + return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) + } + + v.Sections.container[v.scope] = t + return nil +} + +// VisitStatement visits statements... +func (v *DefaultVisitor) VisitStatement(stmt AST) error { + switch stmt.Kind { + case ASTKindCompletedSectionStatement: + child := stmt.GetRoot() + if child.Kind != ASTKindSectionStatement { + return NewParseError(fmt.Sprintf("unsupported child statement: %T", child)) + } + + name := string(child.Root.Raw()) + v.Sections.container[name] = Section{} + v.scope = name + default: + return NewParseError(fmt.Sprintf("unsupported statement: %s", stmt.Kind)) + } + + return nil +} + +// Sections is a map of Section structures that represent +// a configuration. +type Sections struct { + container map[string]Section +} + +// GetSection will return section p. If section p does not exist, +// false will be returned in the second parameter. +func (t Sections) GetSection(p string) (Section, bool) { + v, ok := t.container[p] + return v, ok +} + +// values represents a map of union values. +type values map[string]Value + +// List will return a list of all sections that were successfully +// parsed. +func (t Sections) List() []string { + keys := make([]string, len(t.container)) + i := 0 + for k := range t.container { + keys[i] = k + i++ + } + + sort.Strings(keys) + return keys +} + +// Section contains a name and values. This represent +// a sectioned entry in a configuration file. +type Section struct { + Name string + values values +} + +// Has will return whether or not an entry exists in a given section +func (t Section) Has(k string) bool { + _, ok := t.values[k] + return ok +} + +// ValueType will returned what type the union is set to. If +// k was not found, the NoneType will be returned. +func (t Section) ValueType(k string) (ValueType, bool) { + v, ok := t.values[k] + return v.Type, ok +} + +// Bool returns a bool value at k +func (t Section) Bool(k string) bool { + return t.values[k].BoolValue() +} + +// Int returns an integer value at k +func (t Section) Int(k string) int64 { + return t.values[k].IntValue() +} + +// Float64 returns a float value at k +func (t Section) Float64(k string) float64 { + return t.values[k].FloatValue() +} + +// String returns the string value at k +func (t Section) String(k string) string { + _, ok := t.values[k] + if !ok { + return "" + } + return t.values[k].StringValue() +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go new file mode 100644 index 000000000..99915f7f7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go @@ -0,0 +1,25 @@ +package ini + +// Walk will traverse the AST using the v, the Visitor. +func Walk(tree []AST, v Visitor) error { + for _, node := range tree { + switch node.Kind { + case ASTKindExpr, + ASTKindExprStatement: + + if err := v.VisitExpr(node); err != nil { + return err + } + case ASTKindStatement, + ASTKindCompletedSectionStatement, + ASTKindNestedSectionStatement, + ASTKindCompletedNestedSectionStatement: + + if err := v.VisitStatement(node); err != nil { + return err + } + } + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go new file mode 100644 index 000000000..7ffb4ae06 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go @@ -0,0 +1,24 @@ +package ini + +import ( + "unicode" +) + +// isWhitespace will return whether or not the character is +// a whitespace character. +// +// Whitespace is defined as a space or tab. +func isWhitespace(c rune) bool { + return unicode.IsSpace(c) && c != '\n' && c != '\r' +} + +func newWSToken(b []rune) (Token, int, error) { + i := 0 + for ; i < len(b); i++ { + if !isWhitespace(b[i]) { + break + } + } + + return newToken(TokenWS, b[:i], NoneType), i, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/s3err/error.go b/vendor/github.com/aws/aws-sdk-go/internal/s3err/error.go new file mode 100644 index 000000000..0b9b0dfce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/s3err/error.go @@ -0,0 +1,57 @@ +package s3err + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +// RequestFailure provides additional S3 specific metadata for the request +// failure. +type RequestFailure struct { + awserr.RequestFailure + + hostID string +} + +// NewRequestFailure returns a request failure error decordated with S3 +// specific metadata. +func NewRequestFailure(err awserr.RequestFailure, hostID string) *RequestFailure { + return &RequestFailure{RequestFailure: err, hostID: hostID} +} + +func (r RequestFailure) Error() string { + extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s", + r.StatusCode(), r.RequestID(), r.hostID) + return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr()) +} +func (r RequestFailure) String() string { + return r.Error() +} + +// HostID returns the HostID request response value. +func (r RequestFailure) HostID() string { + return r.hostID +} + +// RequestFailureWrapperHandler returns a handler to rap an +// awserr.RequestFailure with the S3 request ID 2 from the response. +func RequestFailureWrapperHandler() request.NamedHandler { + return request.NamedHandler{ + Name: "awssdk.s3.errorHandler", + Fn: func(req *request.Request) { + reqErr, ok := req.Error.(awserr.RequestFailure) + if !ok || reqErr == nil { + return + } + + hostID := req.HTTPResponse.Header.Get("X-Amz-Id-2") + if req.Error == nil { + return + } + + req.Error = NewRequestFailure(reqErr, hostID) + }, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go new file mode 100644 index 000000000..5aa9137e0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go @@ -0,0 +1,10 @@ +// +build !go1.7 + +package sdkio + +// Copy of Go 1.7 io package's Seeker constants. +const ( + SeekStart = 0 // seek relative to the origin of the file + SeekCurrent = 1 // seek relative to the current offset + SeekEnd = 2 // seek relative to the end +) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go new file mode 100644 index 000000000..e5f005613 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go @@ -0,0 +1,12 @@ +// +build go1.7 + +package sdkio + +import "io" + +// Alias for Go 1.7 io package Seeker constants +const ( + SeekStart = io.SeekStart // seek relative to the origin of the file + SeekCurrent = io.SeekCurrent // seek relative to the current offset + SeekEnd = io.SeekEnd // seek relative to the end +) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go new file mode 100644 index 000000000..0c9802d87 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go @@ -0,0 +1,29 @@ +package sdkrand + +import ( + "math/rand" + "sync" + "time" +) + +// lockedSource is a thread-safe implementation of rand.Source +type lockedSource struct { + lk sync.Mutex + src rand.Source +} + +func (r *lockedSource) Int63() (n int64) { + r.lk.Lock() + n = r.src.Int63() + r.lk.Unlock() + return +} + +func (r *lockedSource) Seed(seed int64) { + r.lk.Lock() + r.src.Seed(seed) + r.lk.Unlock() +} + +// SeededRand is a new RNG using a thread safe implementation of rand.Source +var SeededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go new file mode 100644 index 000000000..38ea61afe --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go @@ -0,0 +1,23 @@ +package sdkuri + +import ( + "path" + "strings" +) + +// PathJoin will join the elements of the path delimited by the "/" +// character. Similar to path.Join with the exception the trailing "/" +// character is preserved if present. +func PathJoin(elems ...string) string { + if len(elems) == 0 { + return "" + } + + hasTrailing := strings.HasSuffix(elems[len(elems)-1], "/") + str := path.Join(elems...) + if hasTrailing && str != "/" { + str += "/" + } + + return str +} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go new file mode 100644 index 000000000..7da8a49ce --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go @@ -0,0 +1,12 @@ +package shareddefaults + +const ( + // ECSCredsProviderEnvVar is an environmental variable key used to + // determine which path needs to be hit. + ECSCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" +) + +// ECSContainerCredentialsURI is the endpoint to retrieve container +// credentials. This can be overridden to test to ensure the credential process +// is behaving correctly. +var ECSContainerCredentialsURI = "http://169.254.170.2" diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go new file mode 100644 index 000000000..ecc7bf82f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go @@ -0,0 +1,144 @@ +package eventstream + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "strconv" +) + +type decodedMessage struct { + rawMessage + Headers decodedHeaders `json:"headers"` +} +type jsonMessage struct { + Length json.Number `json:"total_length"` + HeadersLen json.Number `json:"headers_length"` + PreludeCRC json.Number `json:"prelude_crc"` + Headers decodedHeaders `json:"headers"` + Payload []byte `json:"payload"` + CRC json.Number `json:"message_crc"` +} + +func (d *decodedMessage) UnmarshalJSON(b []byte) (err error) { + var jsonMsg jsonMessage + if err = json.Unmarshal(b, &jsonMsg); err != nil { + return err + } + + d.Length, err = numAsUint32(jsonMsg.Length) + if err != nil { + return err + } + d.HeadersLen, err = numAsUint32(jsonMsg.HeadersLen) + if err != nil { + return err + } + d.PreludeCRC, err = numAsUint32(jsonMsg.PreludeCRC) + if err != nil { + return err + } + d.Headers = jsonMsg.Headers + d.Payload = jsonMsg.Payload + d.CRC, err = numAsUint32(jsonMsg.CRC) + if err != nil { + return err + } + + return nil +} + +func (d *decodedMessage) MarshalJSON() ([]byte, error) { + jsonMsg := jsonMessage{ + Length: json.Number(strconv.Itoa(int(d.Length))), + HeadersLen: json.Number(strconv.Itoa(int(d.HeadersLen))), + PreludeCRC: json.Number(strconv.Itoa(int(d.PreludeCRC))), + Headers: d.Headers, + Payload: d.Payload, + CRC: json.Number(strconv.Itoa(int(d.CRC))), + } + + return json.Marshal(jsonMsg) +} + +func numAsUint32(n json.Number) (uint32, error) { + v, err := n.Int64() + if err != nil { + return 0, fmt.Errorf("failed to get int64 json number, %v", err) + } + + return uint32(v), nil +} + +func (d decodedMessage) Message() Message { + return Message{ + Headers: Headers(d.Headers), + Payload: d.Payload, + } +} + +type decodedHeaders Headers + +func (hs *decodedHeaders) UnmarshalJSON(b []byte) error { + var jsonHeaders []struct { + Name string `json:"name"` + Type valueType `json:"type"` + Value interface{} `json:"value"` + } + + decoder := json.NewDecoder(bytes.NewReader(b)) + decoder.UseNumber() + if err := decoder.Decode(&jsonHeaders); err != nil { + return err + } + + var headers Headers + for _, h := range jsonHeaders { + value, err := valueFromType(h.Type, h.Value) + if err != nil { + return err + } + headers.Set(h.Name, value) + } + (*hs) = decodedHeaders(headers) + + return nil +} + +func valueFromType(typ valueType, val interface{}) (Value, error) { + switch typ { + case trueValueType: + return BoolValue(true), nil + case falseValueType: + return BoolValue(false), nil + case int8ValueType: + v, err := val.(json.Number).Int64() + return Int8Value(int8(v)), err + case int16ValueType: + v, err := val.(json.Number).Int64() + return Int16Value(int16(v)), err + case int32ValueType: + v, err := val.(json.Number).Int64() + return Int32Value(int32(v)), err + case int64ValueType: + v, err := val.(json.Number).Int64() + return Int64Value(v), err + case bytesValueType: + v, err := base64.StdEncoding.DecodeString(val.(string)) + return BytesValue(v), err + case stringValueType: + v, err := base64.StdEncoding.DecodeString(val.(string)) + return StringValue(string(v)), err + case timestampValueType: + v, err := val.(json.Number).Int64() + return TimestampValue(timeFromEpochMilli(v)), err + case uuidValueType: + v, err := base64.StdEncoding.DecodeString(val.(string)) + var tv UUIDValue + copy(tv[:], v) + return tv, err + default: + panic(fmt.Sprintf("unknown type, %s, %T", typ.String(), val)) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go new file mode 100644 index 000000000..4b972b2d6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go @@ -0,0 +1,199 @@ +package eventstream + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "encoding/json" + "fmt" + "hash" + "hash/crc32" + "io" + + "github.com/aws/aws-sdk-go/aws" +) + +// Decoder provides decoding of an Event Stream messages. +type Decoder struct { + r io.Reader + logger aws.Logger +} + +// NewDecoder initializes and returns a Decoder for decoding event +// stream messages from the reader provided. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + r: r, + } +} + +// Decode attempts to decode a single message from the event stream reader. +// Will return the event stream message, or error if Decode fails to read +// the message from the stream. +func (d *Decoder) Decode(payloadBuf []byte) (m Message, err error) { + reader := d.r + if d.logger != nil { + debugMsgBuf := bytes.NewBuffer(nil) + reader = io.TeeReader(reader, debugMsgBuf) + defer func() { + logMessageDecode(d.logger, debugMsgBuf, m, err) + }() + } + + crc := crc32.New(crc32IEEETable) + hashReader := io.TeeReader(reader, crc) + + prelude, err := decodePrelude(hashReader, crc) + if err != nil { + return Message{}, err + } + + if prelude.HeadersLen > 0 { + lr := io.LimitReader(hashReader, int64(prelude.HeadersLen)) + m.Headers, err = decodeHeaders(lr) + if err != nil { + return Message{}, err + } + } + + if payloadLen := prelude.PayloadLen(); payloadLen > 0 { + buf, err := decodePayload(payloadBuf, io.LimitReader(hashReader, int64(payloadLen))) + if err != nil { + return Message{}, err + } + m.Payload = buf + } + + msgCRC := crc.Sum32() + if err := validateCRC(reader, msgCRC); err != nil { + return Message{}, err + } + + return m, nil +} + +// UseLogger specifies the Logger that that the decoder should use to log the +// message decode to. +func (d *Decoder) UseLogger(logger aws.Logger) { + d.logger = logger +} + +func logMessageDecode(logger aws.Logger, msgBuf *bytes.Buffer, msg Message, decodeErr error) { + w := bytes.NewBuffer(nil) + defer func() { logger.Log(w.String()) }() + + fmt.Fprintf(w, "Raw message:\n%s\n", + hex.Dump(msgBuf.Bytes())) + + if decodeErr != nil { + fmt.Fprintf(w, "Decode error: %v\n", decodeErr) + return + } + + rawMsg, err := msg.rawMessage() + if err != nil { + fmt.Fprintf(w, "failed to create raw message, %v\n", err) + return + } + + decodedMsg := decodedMessage{ + rawMessage: rawMsg, + Headers: decodedHeaders(msg.Headers), + } + + fmt.Fprintf(w, "Decoded message:\n") + encoder := json.NewEncoder(w) + if err := encoder.Encode(decodedMsg); err != nil { + fmt.Fprintf(w, "failed to generate decoded message, %v\n", err) + } +} + +func decodePrelude(r io.Reader, crc hash.Hash32) (messagePrelude, error) { + var p messagePrelude + + var err error + p.Length, err = decodeUint32(r) + if err != nil { + return messagePrelude{}, err + } + + p.HeadersLen, err = decodeUint32(r) + if err != nil { + return messagePrelude{}, err + } + + if err := p.ValidateLens(); err != nil { + return messagePrelude{}, err + } + + preludeCRC := crc.Sum32() + if err := validateCRC(r, preludeCRC); err != nil { + return messagePrelude{}, err + } + + p.PreludeCRC = preludeCRC + + return p, nil +} + +func decodePayload(buf []byte, r io.Reader) ([]byte, error) { + w := bytes.NewBuffer(buf[0:0]) + + _, err := io.Copy(w, r) + return w.Bytes(), err +} + +func decodeUint8(r io.Reader) (uint8, error) { + type byteReader interface { + ReadByte() (byte, error) + } + + if br, ok := r.(byteReader); ok { + v, err := br.ReadByte() + return uint8(v), err + } + + var b [1]byte + _, err := io.ReadFull(r, b[:]) + return uint8(b[0]), err +} +func decodeUint16(r io.Reader) (uint16, error) { + var b [2]byte + bs := b[:] + _, err := io.ReadFull(r, bs) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint16(bs), nil +} +func decodeUint32(r io.Reader) (uint32, error) { + var b [4]byte + bs := b[:] + _, err := io.ReadFull(r, bs) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint32(bs), nil +} +func decodeUint64(r io.Reader) (uint64, error) { + var b [8]byte + bs := b[:] + _, err := io.ReadFull(r, bs) + if err != nil { + return 0, err + } + return binary.BigEndian.Uint64(bs), nil +} + +func validateCRC(r io.Reader, expect uint32) error { + msgCRC, err := decodeUint32(r) + if err != nil { + return err + } + + if msgCRC != expect { + return ChecksumError{} + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go new file mode 100644 index 000000000..150a60981 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go @@ -0,0 +1,114 @@ +package eventstream + +import ( + "bytes" + "encoding/binary" + "hash" + "hash/crc32" + "io" +) + +// Encoder provides EventStream message encoding. +type Encoder struct { + w io.Writer + + headersBuf *bytes.Buffer +} + +// NewEncoder initializes and returns an Encoder to encode Event Stream +// messages to an io.Writer. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + w: w, + headersBuf: bytes.NewBuffer(nil), + } +} + +// Encode encodes a single EventStream message to the io.Writer the Encoder +// was created with. An error is returned if writing the message fails. +func (e *Encoder) Encode(msg Message) error { + e.headersBuf.Reset() + + err := encodeHeaders(e.headersBuf, msg.Headers) + if err != nil { + return err + } + + crc := crc32.New(crc32IEEETable) + hashWriter := io.MultiWriter(e.w, crc) + + headersLen := uint32(e.headersBuf.Len()) + payloadLen := uint32(len(msg.Payload)) + + if err := encodePrelude(hashWriter, crc, headersLen, payloadLen); err != nil { + return err + } + + if headersLen > 0 { + if _, err := io.Copy(hashWriter, e.headersBuf); err != nil { + return err + } + } + + if payloadLen > 0 { + if _, err := hashWriter.Write(msg.Payload); err != nil { + return err + } + } + + msgCRC := crc.Sum32() + return binary.Write(e.w, binary.BigEndian, msgCRC) +} + +func encodePrelude(w io.Writer, crc hash.Hash32, headersLen, payloadLen uint32) error { + p := messagePrelude{ + Length: minMsgLen + headersLen + payloadLen, + HeadersLen: headersLen, + } + if err := p.ValidateLens(); err != nil { + return err + } + + err := binaryWriteFields(w, binary.BigEndian, + p.Length, + p.HeadersLen, + ) + if err != nil { + return err + } + + p.PreludeCRC = crc.Sum32() + err = binary.Write(w, binary.BigEndian, p.PreludeCRC) + if err != nil { + return err + } + + return nil +} + +func encodeHeaders(w io.Writer, headers Headers) error { + for _, h := range headers { + hn := headerName{ + Len: uint8(len(h.Name)), + } + copy(hn.Name[:hn.Len], h.Name) + if err := hn.encode(w); err != nil { + return err + } + + if err := h.Value.encode(w); err != nil { + return err + } + } + + return nil +} + +func binaryWriteFields(w io.Writer, order binary.ByteOrder, vs ...interface{}) error { + for _, v := range vs { + if err := binary.Write(w, order, v); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go new file mode 100644 index 000000000..5481ef307 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go @@ -0,0 +1,23 @@ +package eventstream + +import "fmt" + +// LengthError provides the error for items being larger than a maximum length. +type LengthError struct { + Part string + Want int + Have int + Value interface{} +} + +func (e LengthError) Error() string { + return fmt.Sprintf("%s length invalid, %d/%d, %v", + e.Part, e.Want, e.Have, e.Value) +} + +// ChecksumError provides the error for message checksum invalidation errors. +type ChecksumError struct{} + +func (e ChecksumError) Error() string { + return "message checksum mismatch" +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/api.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/api.go new file mode 100644 index 000000000..97937c8e5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/api.go @@ -0,0 +1,196 @@ +package eventstreamapi + +import ( + "fmt" + "io" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/private/protocol" + "github.com/aws/aws-sdk-go/private/protocol/eventstream" +) + +// Unmarshaler provides the interface for unmarshaling a EventStream +// message into a SDK type. +type Unmarshaler interface { + UnmarshalEvent(protocol.PayloadUnmarshaler, eventstream.Message) error +} + +// EventStream headers with specific meaning to async API functionality. +const ( + MessageTypeHeader = `:message-type` // Identifies type of message. + EventMessageType = `event` + ErrorMessageType = `error` + ExceptionMessageType = `exception` + + // Message Events + EventTypeHeader = `:event-type` // Identifies message event type e.g. "Stats". + + // Message Error + ErrorCodeHeader = `:error-code` + ErrorMessageHeader = `:error-message` + + // Message Exception + ExceptionTypeHeader = `:exception-type` +) + +// EventReader provides reading from the EventStream of an reader. +type EventReader struct { + reader io.ReadCloser + decoder *eventstream.Decoder + + unmarshalerForEventType func(string) (Unmarshaler, error) + payloadUnmarshaler protocol.PayloadUnmarshaler + + payloadBuf []byte +} + +// NewEventReader returns a EventReader built from the reader and unmarshaler +// provided. Use ReadStream method to start reading from the EventStream. +func NewEventReader( + reader io.ReadCloser, + payloadUnmarshaler protocol.PayloadUnmarshaler, + unmarshalerForEventType func(string) (Unmarshaler, error), +) *EventReader { + return &EventReader{ + reader: reader, + decoder: eventstream.NewDecoder(reader), + payloadUnmarshaler: payloadUnmarshaler, + unmarshalerForEventType: unmarshalerForEventType, + payloadBuf: make([]byte, 10*1024), + } +} + +// UseLogger instructs the EventReader to use the logger and log level +// specified. +func (r *EventReader) UseLogger(logger aws.Logger, logLevel aws.LogLevelType) { + if logger != nil && logLevel.Matches(aws.LogDebugWithEventStreamBody) { + r.decoder.UseLogger(logger) + } +} + +// ReadEvent attempts to read a message from the EventStream and return the +// unmarshaled event value that the message is for. +// +// For EventStream API errors check if the returned error satisfies the +// awserr.Error interface to get the error's Code and Message components. +// +// EventUnmarshalers called with EventStream messages must take copies of the +// message's Payload. The payload will is reused between events read. +func (r *EventReader) ReadEvent() (event interface{}, err error) { + msg, err := r.decoder.Decode(r.payloadBuf) + if err != nil { + return nil, err + } + defer func() { + // Reclaim payload buffer for next message read. + r.payloadBuf = msg.Payload[0:0] + }() + + typ, err := GetHeaderString(msg, MessageTypeHeader) + if err != nil { + return nil, err + } + + switch typ { + case EventMessageType: + return r.unmarshalEventMessage(msg) + case ExceptionMessageType: + err = r.unmarshalEventException(msg) + return nil, err + case ErrorMessageType: + return nil, r.unmarshalErrorMessage(msg) + default: + return nil, fmt.Errorf("unknown eventstream message type, %v", typ) + } +} + +func (r *EventReader) unmarshalEventMessage( + msg eventstream.Message, +) (event interface{}, err error) { + eventType, err := GetHeaderString(msg, EventTypeHeader) + if err != nil { + return nil, err + } + + ev, err := r.unmarshalerForEventType(eventType) + if err != nil { + return nil, err + } + + err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg) + if err != nil { + return nil, err + } + + return ev, nil +} + +func (r *EventReader) unmarshalEventException( + msg eventstream.Message, +) (err error) { + eventType, err := GetHeaderString(msg, ExceptionTypeHeader) + if err != nil { + return err + } + + ev, err := r.unmarshalerForEventType(eventType) + if err != nil { + return err + } + + err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg) + if err != nil { + return err + } + + var ok bool + err, ok = ev.(error) + if !ok { + err = messageError{ + code: "SerializationError", + msg: fmt.Sprintf( + "event stream exception %s mapped to non-error %T, %v", + eventType, ev, ev, + ), + } + } + + return err +} + +func (r *EventReader) unmarshalErrorMessage(msg eventstream.Message) (err error) { + var msgErr messageError + + msgErr.code, err = GetHeaderString(msg, ErrorCodeHeader) + if err != nil { + return err + } + + msgErr.msg, err = GetHeaderString(msg, ErrorMessageHeader) + if err != nil { + return err + } + + return msgErr +} + +// Close closes the EventReader's EventStream reader. +func (r *EventReader) Close() error { + return r.reader.Close() +} + +// GetHeaderString returns the value of the header as a string. If the header +// is not set or the value is not a string an error will be returned. +func GetHeaderString(msg eventstream.Message, headerName string) (string, error) { + headerVal := msg.Headers.Get(headerName) + if headerVal == nil { + return "", fmt.Errorf("error header %s not present", headerName) + } + + v, ok := headerVal.Get().(string) + if !ok { + return "", fmt.Errorf("error header value is not a string, %T", headerVal) + } + + return v, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go new file mode 100644 index 000000000..5ea5a988b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go @@ -0,0 +1,24 @@ +package eventstreamapi + +import "fmt" + +type messageError struct { + code string + msg string +} + +func (e messageError) Code() string { + return e.code +} + +func (e messageError) Message() string { + return e.msg +} + +func (e messageError) Error() string { + return fmt.Sprintf("%s: %s", e.code, e.msg) +} + +func (e messageError) OrigErr() error { + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go new file mode 100644 index 000000000..3b44dde2f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go @@ -0,0 +1,166 @@ +package eventstream + +import ( + "encoding/binary" + "fmt" + "io" +) + +// Headers are a collection of EventStream header values. +type Headers []Header + +// Header is a single EventStream Key Value header pair. +type Header struct { + Name string + Value Value +} + +// Set associates the name with a value. If the header name already exists in +// the Headers the value will be replaced with the new one. +func (hs *Headers) Set(name string, value Value) { + var i int + for ; i < len(*hs); i++ { + if (*hs)[i].Name == name { + (*hs)[i].Value = value + return + } + } + + *hs = append(*hs, Header{ + Name: name, Value: value, + }) +} + +// Get returns the Value associated with the header. Nil is returned if the +// value does not exist. +func (hs Headers) Get(name string) Value { + for i := 0; i < len(hs); i++ { + if h := hs[i]; h.Name == name { + return h.Value + } + } + return nil +} + +// Del deletes the value in the Headers if it exists. +func (hs *Headers) Del(name string) { + for i := 0; i < len(*hs); i++ { + if (*hs)[i].Name == name { + copy((*hs)[i:], (*hs)[i+1:]) + (*hs) = (*hs)[:len(*hs)-1] + } + } +} + +func decodeHeaders(r io.Reader) (Headers, error) { + hs := Headers{} + + for { + name, err := decodeHeaderName(r) + if err != nil { + if err == io.EOF { + // EOF while getting header name means no more headers + break + } + return nil, err + } + + value, err := decodeHeaderValue(r) + if err != nil { + return nil, err + } + + hs.Set(name, value) + } + + return hs, nil +} + +func decodeHeaderName(r io.Reader) (string, error) { + var n headerName + + var err error + n.Len, err = decodeUint8(r) + if err != nil { + return "", err + } + + name := n.Name[:n.Len] + if _, err := io.ReadFull(r, name); err != nil { + return "", err + } + + return string(name), nil +} + +func decodeHeaderValue(r io.Reader) (Value, error) { + var raw rawValue + + typ, err := decodeUint8(r) + if err != nil { + return nil, err + } + raw.Type = valueType(typ) + + var v Value + + switch raw.Type { + case trueValueType: + v = BoolValue(true) + case falseValueType: + v = BoolValue(false) + case int8ValueType: + var tv Int8Value + err = tv.decode(r) + v = tv + case int16ValueType: + var tv Int16Value + err = tv.decode(r) + v = tv + case int32ValueType: + var tv Int32Value + err = tv.decode(r) + v = tv + case int64ValueType: + var tv Int64Value + err = tv.decode(r) + v = tv + case bytesValueType: + var tv BytesValue + err = tv.decode(r) + v = tv + case stringValueType: + var tv StringValue + err = tv.decode(r) + v = tv + case timestampValueType: + var tv TimestampValue + err = tv.decode(r) + v = tv + case uuidValueType: + var tv UUIDValue + err = tv.decode(r) + v = tv + default: + panic(fmt.Sprintf("unknown value type %d", raw.Type)) + } + + // Error could be EOF, let caller deal with it + return v, err +} + +const maxHeaderNameLen = 255 + +type headerName struct { + Len uint8 + Name [maxHeaderNameLen]byte +} + +func (v headerName) encode(w io.Writer) error { + if err := binary.Write(w, binary.BigEndian, v.Len); err != nil { + return err + } + + _, err := w.Write(v.Name[:v.Len]) + return err +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go new file mode 100644 index 000000000..e3fc0766a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go @@ -0,0 +1,501 @@ +package eventstream + +import ( + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "strconv" + "time" +) + +const maxHeaderValueLen = 1<<15 - 1 // 2^15-1 or 32KB - 1 + +// valueType is the EventStream header value type. +type valueType uint8 + +// Header value types +const ( + trueValueType valueType = iota + falseValueType + int8ValueType // Byte + int16ValueType // Short + int32ValueType // Integer + int64ValueType // Long + bytesValueType + stringValueType + timestampValueType + uuidValueType +) + +func (t valueType) String() string { + switch t { + case trueValueType: + return "bool" + case falseValueType: + return "bool" + case int8ValueType: + return "int8" + case int16ValueType: + return "int16" + case int32ValueType: + return "int32" + case int64ValueType: + return "int64" + case bytesValueType: + return "byte_array" + case stringValueType: + return "string" + case timestampValueType: + return "timestamp" + case uuidValueType: + return "uuid" + default: + return fmt.Sprintf("unknown value type %d", uint8(t)) + } +} + +type rawValue struct { + Type valueType + Len uint16 // Only set for variable length slices + Value []byte // byte representation of value, BigEndian encoding. +} + +func (r rawValue) encodeScalar(w io.Writer, v interface{}) error { + return binaryWriteFields(w, binary.BigEndian, + r.Type, + v, + ) +} + +func (r rawValue) encodeFixedSlice(w io.Writer, v []byte) error { + binary.Write(w, binary.BigEndian, r.Type) + + _, err := w.Write(v) + return err +} + +func (r rawValue) encodeBytes(w io.Writer, v []byte) error { + if len(v) > maxHeaderValueLen { + return LengthError{ + Part: "header value", + Want: maxHeaderValueLen, Have: len(v), + Value: v, + } + } + r.Len = uint16(len(v)) + + err := binaryWriteFields(w, binary.BigEndian, + r.Type, + r.Len, + ) + if err != nil { + return err + } + + _, err = w.Write(v) + return err +} + +func (r rawValue) encodeString(w io.Writer, v string) error { + if len(v) > maxHeaderValueLen { + return LengthError{ + Part: "header value", + Want: maxHeaderValueLen, Have: len(v), + Value: v, + } + } + r.Len = uint16(len(v)) + + type stringWriter interface { + WriteString(string) (int, error) + } + + err := binaryWriteFields(w, binary.BigEndian, + r.Type, + r.Len, + ) + if err != nil { + return err + } + + if sw, ok := w.(stringWriter); ok { + _, err = sw.WriteString(v) + } else { + _, err = w.Write([]byte(v)) + } + + return err +} + +func decodeFixedBytesValue(r io.Reader, buf []byte) error { + _, err := io.ReadFull(r, buf) + return err +} + +func decodeBytesValue(r io.Reader) ([]byte, error) { + var raw rawValue + var err error + raw.Len, err = decodeUint16(r) + if err != nil { + return nil, err + } + + buf := make([]byte, raw.Len) + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, err + } + + return buf, nil +} + +func decodeStringValue(r io.Reader) (string, error) { + v, err := decodeBytesValue(r) + return string(v), err +} + +// Value represents the abstract header value. +type Value interface { + Get() interface{} + String() string + valueType() valueType + encode(io.Writer) error +} + +// An BoolValue provides eventstream encoding, and representation +// of a Go bool value. +type BoolValue bool + +// Get returns the underlying type +func (v BoolValue) Get() interface{} { + return bool(v) +} + +// valueType returns the EventStream header value type value. +func (v BoolValue) valueType() valueType { + if v { + return trueValueType + } + return falseValueType +} + +func (v BoolValue) String() string { + return strconv.FormatBool(bool(v)) +} + +// encode encodes the BoolValue into an eventstream binary value +// representation. +func (v BoolValue) encode(w io.Writer) error { + return binary.Write(w, binary.BigEndian, v.valueType()) +} + +// An Int8Value provides eventstream encoding, and representation of a Go +// int8 value. +type Int8Value int8 + +// Get returns the underlying value. +func (v Int8Value) Get() interface{} { + return int8(v) +} + +// valueType returns the EventStream header value type value. +func (Int8Value) valueType() valueType { + return int8ValueType +} + +func (v Int8Value) String() string { + return fmt.Sprintf("0x%02x", int8(v)) +} + +// encode encodes the Int8Value into an eventstream binary value +// representation. +func (v Int8Value) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + + return raw.encodeScalar(w, v) +} + +func (v *Int8Value) decode(r io.Reader) error { + n, err := decodeUint8(r) + if err != nil { + return err + } + + *v = Int8Value(n) + return nil +} + +// An Int16Value provides eventstream encoding, and representation of a Go +// int16 value. +type Int16Value int16 + +// Get returns the underlying value. +func (v Int16Value) Get() interface{} { + return int16(v) +} + +// valueType returns the EventStream header value type value. +func (Int16Value) valueType() valueType { + return int16ValueType +} + +func (v Int16Value) String() string { + return fmt.Sprintf("0x%04x", int16(v)) +} + +// encode encodes the Int16Value into an eventstream binary value +// representation. +func (v Int16Value) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + return raw.encodeScalar(w, v) +} + +func (v *Int16Value) decode(r io.Reader) error { + n, err := decodeUint16(r) + if err != nil { + return err + } + + *v = Int16Value(n) + return nil +} + +// An Int32Value provides eventstream encoding, and representation of a Go +// int32 value. +type Int32Value int32 + +// Get returns the underlying value. +func (v Int32Value) Get() interface{} { + return int32(v) +} + +// valueType returns the EventStream header value type value. +func (Int32Value) valueType() valueType { + return int32ValueType +} + +func (v Int32Value) String() string { + return fmt.Sprintf("0x%08x", int32(v)) +} + +// encode encodes the Int32Value into an eventstream binary value +// representation. +func (v Int32Value) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + return raw.encodeScalar(w, v) +} + +func (v *Int32Value) decode(r io.Reader) error { + n, err := decodeUint32(r) + if err != nil { + return err + } + + *v = Int32Value(n) + return nil +} + +// An Int64Value provides eventstream encoding, and representation of a Go +// int64 value. +type Int64Value int64 + +// Get returns the underlying value. +func (v Int64Value) Get() interface{} { + return int64(v) +} + +// valueType returns the EventStream header value type value. +func (Int64Value) valueType() valueType { + return int64ValueType +} + +func (v Int64Value) String() string { + return fmt.Sprintf("0x%016x", int64(v)) +} + +// encode encodes the Int64Value into an eventstream binary value +// representation. +func (v Int64Value) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + return raw.encodeScalar(w, v) +} + +func (v *Int64Value) decode(r io.Reader) error { + n, err := decodeUint64(r) + if err != nil { + return err + } + + *v = Int64Value(n) + return nil +} + +// An BytesValue provides eventstream encoding, and representation of a Go +// byte slice. +type BytesValue []byte + +// Get returns the underlying value. +func (v BytesValue) Get() interface{} { + return []byte(v) +} + +// valueType returns the EventStream header value type value. +func (BytesValue) valueType() valueType { + return bytesValueType +} + +func (v BytesValue) String() string { + return base64.StdEncoding.EncodeToString([]byte(v)) +} + +// encode encodes the BytesValue into an eventstream binary value +// representation. +func (v BytesValue) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + + return raw.encodeBytes(w, []byte(v)) +} + +func (v *BytesValue) decode(r io.Reader) error { + buf, err := decodeBytesValue(r) + if err != nil { + return err + } + + *v = BytesValue(buf) + return nil +} + +// An StringValue provides eventstream encoding, and representation of a Go +// string. +type StringValue string + +// Get returns the underlying value. +func (v StringValue) Get() interface{} { + return string(v) +} + +// valueType returns the EventStream header value type value. +func (StringValue) valueType() valueType { + return stringValueType +} + +func (v StringValue) String() string { + return string(v) +} + +// encode encodes the StringValue into an eventstream binary value +// representation. +func (v StringValue) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + + return raw.encodeString(w, string(v)) +} + +func (v *StringValue) decode(r io.Reader) error { + s, err := decodeStringValue(r) + if err != nil { + return err + } + + *v = StringValue(s) + return nil +} + +// An TimestampValue provides eventstream encoding, and representation of a Go +// timestamp. +type TimestampValue time.Time + +// Get returns the underlying value. +func (v TimestampValue) Get() interface{} { + return time.Time(v) +} + +// valueType returns the EventStream header value type value. +func (TimestampValue) valueType() valueType { + return timestampValueType +} + +func (v TimestampValue) epochMilli() int64 { + nano := time.Time(v).UnixNano() + msec := nano / int64(time.Millisecond) + return msec +} + +func (v TimestampValue) String() string { + msec := v.epochMilli() + return strconv.FormatInt(msec, 10) +} + +// encode encodes the TimestampValue into an eventstream binary value +// representation. +func (v TimestampValue) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + + msec := v.epochMilli() + return raw.encodeScalar(w, msec) +} + +func (v *TimestampValue) decode(r io.Reader) error { + n, err := decodeUint64(r) + if err != nil { + return err + } + + *v = TimestampValue(timeFromEpochMilli(int64(n))) + return nil +} + +func timeFromEpochMilli(t int64) time.Time { + secs := t / 1e3 + msec := t % 1e3 + return time.Unix(secs, msec*int64(time.Millisecond)).UTC() +} + +// An UUIDValue provides eventstream encoding, and representation of a UUID +// value. +type UUIDValue [16]byte + +// Get returns the underlying value. +func (v UUIDValue) Get() interface{} { + return v[:] +} + +// valueType returns the EventStream header value type value. +func (UUIDValue) valueType() valueType { + return uuidValueType +} + +func (v UUIDValue) String() string { + return fmt.Sprintf(`%X-%X-%X-%X-%X`, v[0:4], v[4:6], v[6:8], v[8:10], v[10:]) +} + +// encode encodes the UUIDValue into an eventstream binary value +// representation. +func (v UUIDValue) encode(w io.Writer) error { + raw := rawValue{ + Type: v.valueType(), + } + + return raw.encodeFixedSlice(w, v[:]) +} + +func (v *UUIDValue) decode(r io.Reader) error { + tv := (*v)[:] + return decodeFixedBytesValue(r, tv) +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go new file mode 100644 index 000000000..2dc012a66 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go @@ -0,0 +1,103 @@ +package eventstream + +import ( + "bytes" + "encoding/binary" + "hash/crc32" +) + +const preludeLen = 8 +const preludeCRCLen = 4 +const msgCRCLen = 4 +const minMsgLen = preludeLen + preludeCRCLen + msgCRCLen +const maxPayloadLen = 1024 * 1024 * 16 // 16MB +const maxHeadersLen = 1024 * 128 // 128KB +const maxMsgLen = minMsgLen + maxHeadersLen + maxPayloadLen + +var crc32IEEETable = crc32.MakeTable(crc32.IEEE) + +// A Message provides the eventstream message representation. +type Message struct { + Headers Headers + Payload []byte +} + +func (m *Message) rawMessage() (rawMessage, error) { + var raw rawMessage + + if len(m.Headers) > 0 { + var headers bytes.Buffer + if err := encodeHeaders(&headers, m.Headers); err != nil { + return rawMessage{}, err + } + raw.Headers = headers.Bytes() + raw.HeadersLen = uint32(len(raw.Headers)) + } + + raw.Length = raw.HeadersLen + uint32(len(m.Payload)) + minMsgLen + + hash := crc32.New(crc32IEEETable) + binaryWriteFields(hash, binary.BigEndian, raw.Length, raw.HeadersLen) + raw.PreludeCRC = hash.Sum32() + + binaryWriteFields(hash, binary.BigEndian, raw.PreludeCRC) + + if raw.HeadersLen > 0 { + hash.Write(raw.Headers) + } + + // Read payload bytes and update hash for it as well. + if len(m.Payload) > 0 { + raw.Payload = m.Payload + hash.Write(raw.Payload) + } + + raw.CRC = hash.Sum32() + + return raw, nil +} + +type messagePrelude struct { + Length uint32 + HeadersLen uint32 + PreludeCRC uint32 +} + +func (p messagePrelude) PayloadLen() uint32 { + return p.Length - p.HeadersLen - minMsgLen +} + +func (p messagePrelude) ValidateLens() error { + if p.Length == 0 || p.Length > maxMsgLen { + return LengthError{ + Part: "message prelude", + Want: maxMsgLen, + Have: int(p.Length), + } + } + if p.HeadersLen > maxHeadersLen { + return LengthError{ + Part: "message headers", + Want: maxHeadersLen, + Have: int(p.HeadersLen), + } + } + if payloadLen := p.PayloadLen(); payloadLen > maxPayloadLen { + return LengthError{ + Part: "message payload", + Want: maxPayloadLen, + Have: int(payloadLen), + } + } + + return nil +} + +type rawMessage struct { + messagePrelude + + Headers []byte + Payload []byte + + CRC uint32 +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go new file mode 100644 index 000000000..d7d42db0a --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go @@ -0,0 +1,68 @@ +package protocol + +import ( + "strings" + + "github.com/aws/aws-sdk-go/aws/request" +) + +// ValidateEndpointHostHandler is a request handler that will validate the +// request endpoint's hosts is a valid RFC 3986 host. +var ValidateEndpointHostHandler = request.NamedHandler{ + Name: "awssdk.protocol.ValidateEndpointHostHandler", + Fn: func(r *request.Request) { + err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host) + if err != nil { + r.Error = err + } + }, +} + +// ValidateEndpointHost validates that the host string passed in is a valid RFC +// 3986 host. Returns error if the host is not valid. +func ValidateEndpointHost(opName, host string) error { + paramErrs := request.ErrInvalidParams{Context: opName} + labels := strings.Split(host, ".") + + for i, label := range labels { + if i == len(labels)-1 && len(label) == 0 { + // Allow trailing dot for FQDN hosts. + continue + } + + if !ValidHostLabel(label) { + paramErrs.Add(request.NewErrParamFormat( + "endpoint host label", "[a-zA-Z0-9-]{1,63}", label)) + } + } + + if len(host) > 255 { + paramErrs.Add(request.NewErrParamMaxLen( + "endpoint host", 255, host, + )) + } + + if paramErrs.Len() > 0 { + return paramErrs + } + return nil +} + +// ValidHostLabel returns if the label is a valid RFC 3986 host label. +func ValidHostLabel(label string) bool { + if l := len(label); l == 0 || l > 63 { + return false + } + for _, r := range label { + switch { + case r >= '0' && r <= '9': + case r >= 'A' && r <= 'Z': + case r >= 'a' && r <= 'z': + case r == '-': + default: + return false + } + } + + return true +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go new file mode 100644 index 000000000..915b0fcaf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go @@ -0,0 +1,54 @@ +package protocol + +import ( + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// HostPrefixHandlerName is the handler name for the host prefix request +// handler. +const HostPrefixHandlerName = "awssdk.endpoint.HostPrefixHandler" + +// NewHostPrefixHandler constructs a build handler +func NewHostPrefixHandler(prefix string, labelsFn func() map[string]string) request.NamedHandler { + builder := HostPrefixBuilder{ + Prefix: prefix, + LabelsFn: labelsFn, + } + + return request.NamedHandler{ + Name: HostPrefixHandlerName, + Fn: builder.Build, + } +} + +// HostPrefixBuilder provides the request handler to expand and prepend +// the host prefix into the operation's request endpoint host. +type HostPrefixBuilder struct { + Prefix string + LabelsFn func() map[string]string +} + +// Build updates the passed in Request with the HostPrefix template expanded. +func (h HostPrefixBuilder) Build(r *request.Request) { + if aws.BoolValue(r.Config.DisableEndpointHostPrefix) { + return + } + + var labels map[string]string + if h.LabelsFn != nil { + labels = h.LabelsFn() + } + + prefix := h.Prefix + for name, value := range labels { + prefix = strings.Replace(prefix, "{"+name+"}", value, -1) + } + + r.HTTPRequest.URL.Host = prefix + r.HTTPRequest.URL.Host + if len(r.HTTPRequest.Host) > 0 { + r.HTTPRequest.Host = prefix + r.HTTPRequest.Host + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go new file mode 100644 index 000000000..776d11018 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go @@ -0,0 +1,76 @@ +package protocol + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "strconv" + + "github.com/aws/aws-sdk-go/aws" +) + +// EscapeMode is the mode that should be use for escaping a value +type EscapeMode uint + +// The modes for escaping a value before it is marshaled, and unmarshaled. +const ( + NoEscape EscapeMode = iota + Base64Escape + QuotedEscape +) + +// EncodeJSONValue marshals the value into a JSON string, and optionally base64 +// encodes the string before returning it. +// +// Will panic if the escape mode is unknown. +func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) { + b, err := json.Marshal(v) + if err != nil { + return "", err + } + + switch escape { + case NoEscape: + return string(b), nil + case Base64Escape: + return base64.StdEncoding.EncodeToString(b), nil + case QuotedEscape: + return strconv.Quote(string(b)), nil + } + + panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape)) +} + +// DecodeJSONValue will attempt to decode the string input as a JSONValue. +// Optionally decoding base64 the value first before JSON unmarshaling. +// +// Will panic if the escape mode is unknown. +func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) { + var b []byte + var err error + + switch escape { + case NoEscape: + b = []byte(v) + case Base64Escape: + b, err = base64.StdEncoding.DecodeString(v) + case QuotedEscape: + var u string + u, err = strconv.Unquote(v) + b = []byte(u) + default: + panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape)) + } + + if err != nil { + return nil, err + } + + m := aws.JSONValue{} + err = json.Unmarshal(b, &m) + if err != nil { + return nil, err + } + + return m, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go new file mode 100644 index 000000000..e21614a12 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go @@ -0,0 +1,81 @@ +package protocol + +import ( + "io" + "io/ioutil" + "net/http" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" +) + +// PayloadUnmarshaler provides the interface for unmarshaling a payload's +// reader into a SDK shape. +type PayloadUnmarshaler interface { + UnmarshalPayload(io.Reader, interface{}) error +} + +// HandlerPayloadUnmarshal implements the PayloadUnmarshaler from a +// HandlerList. This provides the support for unmarshaling a payload reader to +// a shape without needing a SDK request first. +type HandlerPayloadUnmarshal struct { + Unmarshalers request.HandlerList +} + +// UnmarshalPayload unmarshals the io.Reader payload into the SDK shape using +// the Unmarshalers HandlerList provided. Returns an error if unable +// unmarshaling fails. +func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error { + req := &request.Request{ + HTTPRequest: &http.Request{}, + HTTPResponse: &http.Response{ + StatusCode: 200, + Header: http.Header{}, + Body: ioutil.NopCloser(r), + }, + Data: v, + } + + h.Unmarshalers.Run(req) + + return req.Error +} + +// PayloadMarshaler provides the interface for marshaling a SDK shape into and +// io.Writer. +type PayloadMarshaler interface { + MarshalPayload(io.Writer, interface{}) error +} + +// HandlerPayloadMarshal implements the PayloadMarshaler from a HandlerList. +// This provides support for marshaling a SDK shape into an io.Writer without +// needing a SDK request first. +type HandlerPayloadMarshal struct { + Marshalers request.HandlerList +} + +// MarshalPayload marshals the SDK shape into the io.Writer using the +// Marshalers HandlerList provided. Returns an error if unable if marshal +// fails. +func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error { + req := request.New( + aws.Config{}, + metadata.ClientInfo{}, + request.Handlers{}, + nil, + &request.Operation{HTTPMethod: "GET"}, + v, + nil, + ) + + h.Marshalers.Run(req) + + if req.Error != nil { + return req.Error + } + + io.Copy(w, req.GetBody()) + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go index 18169f0f8..60e5b09d5 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go @@ -25,7 +25,7 @@ func Build(r *request.Request) { return } - if r.ExpireTime == 0 { + if !r.IsPresigned() { r.HTTPRequest.Method = "POST" r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") r.SetBufferBody([]byte(body.Encode())) diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go index 524ca952a..75866d012 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go @@ -121,6 +121,10 @@ func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string return nil } + if _, ok := value.Interface().([]byte); ok { + return q.parseScalar(v, value, prefix, tag) + } + // check for unflattened list member if !q.isEC2 && tag.Get("flattened") == "" { if listName := tag.Get("locationNameList"); listName == "" { @@ -229,7 +233,12 @@ func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, ta v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) case time.Time: const ISO8601UTC = "2006-01-02T15:04:05Z" - v.Set(name, value.UTC().Format(ISO8601UTC)) + format := tag.Get("timestampFormat") + if len(format) == 0 { + format = protocol.ISO8601TimeFormatName + } + + v.Set(name, protocol.FormatTime(format, value)) default: return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go index e0f4d5a54..3495c7307 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go @@ -23,7 +23,11 @@ func Unmarshal(r *request.Request) { decoder := xml.NewDecoder(r.HTTPResponse.Body) err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") if err != nil { - r.Error = awserr.New("SerializationError", "failed decoding Query response", err) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", "failed decoding Query response", err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go index f21429617..46d354e82 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go @@ -28,7 +28,11 @@ func UnmarshalError(r *request.Request) { bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { - r.Error = awserr.New("SerializationError", "failed to read from query HTTP response body", err) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", "failed to read from query HTTP response body", err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } @@ -61,6 +65,10 @@ func UnmarshalError(r *request.Request) { } // Failed to retrieve any error message from the response body - r.Error = awserr.New("SerializationError", - "failed to decode query XML error response", decodeErr) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", + "failed to decode query XML error response", decodeErr), + r.HTTPResponse.StatusCode, + r.RequestID, + ) } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go index 716183564..b34f5258a 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go @@ -4,7 +4,6 @@ package rest import ( "bytes" "encoding/base64" - "encoding/json" "fmt" "io" "net/http" @@ -18,11 +17,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/protocol" ) -// RFC822 returns an RFC822 formatted timestamp for AWS protocols -const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT" - // Whether the byte value can be sent without escaping in AWS URLs var noEscape [256]bool @@ -252,13 +249,12 @@ func EscapePath(path string, encodeSep bool) string { return buf.String() } -func convertType(v reflect.Value, tag reflect.StructTag) (string, error) { +func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) { v = reflect.Indirect(v) if !v.IsValid() { return "", errValueNotSet } - var str string switch value := v.Interface().(type) { case string: str = value @@ -271,19 +267,28 @@ func convertType(v reflect.Value, tag reflect.StructTag) (string, error) { case float64: str = strconv.FormatFloat(value, 'f', -1, 64) case time.Time: - str = value.UTC().Format(RFC822) + format := tag.Get("timestampFormat") + if len(format) == 0 { + format = protocol.RFC822TimeFormatName + if tag.Get("location") == "querystring" { + format = protocol.ISO8601TimeFormatName + } + } + str = protocol.FormatTime(format, value) case aws.JSONValue: - b, err := json.Marshal(value) - if err != nil { - return "", err + if len(value) == 0 { + return "", errValueNotSet } + escaping := protocol.NoEscape if tag.Get("location") == "header" { - str = base64.StdEncoding.EncodeToString(b) - } else { - str = string(b) + escaping = protocol.Base64Escape + } + str, err = protocol.EncodeJSONValue(value, escaping) + if err != nil { + return "", fmt.Errorf("unable to encode JSONValue, %v", err) } default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) + err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) return "", err } return str, nil diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go index 7a779ee22..33fd53b12 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go @@ -3,7 +3,6 @@ package rest import ( "bytes" "encoding/base64" - "encoding/json" "fmt" "io" "io/ioutil" @@ -16,6 +15,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/protocol" ) // UnmarshalHandler is a named request handler for unmarshaling rest protocol requests @@ -198,23 +198,21 @@ func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) erro } v.Set(reflect.ValueOf(&f)) case *time.Time: - t, err := time.Parse(RFC822, header) + format := tag.Get("timestampFormat") + if len(format) == 0 { + format = protocol.RFC822TimeFormatName + } + t, err := protocol.ParseTime(format, header) if err != nil { return err } v.Set(reflect.ValueOf(&t)) case aws.JSONValue: - b := []byte(header) - var err error + escaping := protocol.NoEscape if tag.Get("location") == "header" { - b, err = base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } + escaping = protocol.Base64Escape } - - m := aws.JSONValue{} - err = json.Unmarshal(b, &m) + m, err := protocol.DecodeJSONValue(header, escaping) if err != nil { return err } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go index 7bdf4c853..b0f4e2456 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go @@ -36,7 +36,11 @@ func Build(r *request.Request) { var buf bytes.Buffer err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) if err != nil { - r.Error = awserr.New("SerializationError", "failed to encode rest XML request", err) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", "failed to encode rest XML request", err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } r.SetBufferBody(buf.Bytes()) @@ -50,7 +54,11 @@ func Unmarshal(r *request.Request) { decoder := xml.NewDecoder(r.HTTPResponse.Body) err := xmlutil.UnmarshalXML(r.Data, decoder, "") if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", "failed to decode REST XML response", err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } } else { diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go new file mode 100644 index 000000000..b7ed6c6f8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go @@ -0,0 +1,72 @@ +package protocol + +import ( + "strconv" + "time" +) + +// Names of time formats supported by the SDK +const ( + RFC822TimeFormatName = "rfc822" + ISO8601TimeFormatName = "iso8601" + UnixTimeFormatName = "unixTimestamp" +) + +// Time formats supported by the SDK +const ( + // RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT + RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT" + + // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z + ISO8601TimeFormat = "2006-01-02T15:04:05Z" +) + +// IsKnownTimestampFormat returns if the timestamp format name +// is know to the SDK's protocols. +func IsKnownTimestampFormat(name string) bool { + switch name { + case RFC822TimeFormatName: + fallthrough + case ISO8601TimeFormatName: + fallthrough + case UnixTimeFormatName: + return true + default: + return false + } +} + +// FormatTime returns a string value of the time. +func FormatTime(name string, t time.Time) string { + t = t.UTC() + + switch name { + case RFC822TimeFormatName: + return t.Format(RFC822TimeFormat) + case ISO8601TimeFormatName: + return t.Format(ISO8601TimeFormat) + case UnixTimeFormatName: + return strconv.FormatInt(t.Unix(), 10) + default: + panic("unknown timestamp format name, " + name) + } +} + +// ParseTime attempts to parse the time given the format. Returns +// the time if it was able to be parsed, and fails otherwise. +func ParseTime(formatName, value string) (time.Time, error) { + switch formatName { + case RFC822TimeFormatName: + return time.Parse(RFC822TimeFormat, value) + case ISO8601TimeFormatName: + return time.Parse(ISO8601TimeFormat, value) + case UnixTimeFormatName: + v, err := strconv.ParseFloat(value, 64) + if err != nil { + return time.Time{}, err + } + return time.Unix(int64(v), 0), nil + default: + panic("unknown timestamp format name, " + formatName) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go index 7091b456d..cf981fe95 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go @@ -13,9 +13,13 @@ import ( "github.com/aws/aws-sdk-go/private/protocol" ) -// BuildXML will serialize params into an xml.Encoder. -// Error will be returned if the serialization of any of the params or nested values fails. +// BuildXML will serialize params into an xml.Encoder. Error will be returned +// if the serialization of any of the params or nested values fails. func BuildXML(params interface{}, e *xml.Encoder) error { + return buildXML(params, e, false) +} + +func buildXML(params interface{}, e *xml.Encoder, sorted bool) error { b := xmlBuilder{encoder: e, namespaces: map[string]string{}} root := NewXMLElement(xml.Name{}) if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { @@ -23,7 +27,7 @@ func BuildXML(params interface{}, e *xml.Encoder) error { } for _, c := range root.Children { for _, v := range c { - return StructToXML(e, v, false) + return StructToXML(e, v, sorted) } } return nil @@ -83,15 +87,13 @@ func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag refle } } -// buildStruct adds a struct and its fields to the current XMLNode. All fields any any nested +// buildStruct adds a struct and its fields to the current XMLNode. All fields and any nested // types are converted to XMLNodes also. func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { if !value.IsValid() { return nil } - fieldAdded := false - // unwrap payloads if payload := tag.Get("payload"); payload != "" { field, _ := value.Type().FieldByName(payload) @@ -119,6 +121,8 @@ func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag refl child.Attr = append(child.Attr, ns) } + var payloadFields, nonPayloadFields int + t := value.Type() for i := 0; i < value.NumField(); i++ { member := elemOf(value.Field(i)) @@ -133,8 +137,10 @@ func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag refl mTag := field.Tag if mTag.Get("location") != "" { // skip non-body members + nonPayloadFields++ continue } + payloadFields++ if protocol.CanSetIdempotencyToken(value.Field(i), field) { token := protocol.GetIdempotencyToken() @@ -149,11 +155,11 @@ func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag refl if err := b.buildValue(member, child, mTag); err != nil { return err } - - fieldAdded = true } - if fieldAdded { // only append this child if we have one ore more valid members + // Only case where the child shape is not added is if the shape only contains + // non-payload fields, e.g headers/query. + if !(payloadFields == 0 && nonPayloadFields > 0) { current.AddChild(child) } @@ -278,8 +284,12 @@ func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag refl case float32: str = strconv.FormatFloat(float64(converted), 'f', -1, 32) case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - str = converted.UTC().Format(ISO8601UTC) + format := tag.Get("timestampFormat") + if len(format) == 0 { + format = protocol.ISO8601TimeFormatName + } + + str = protocol.FormatTime(format, converted) default: return fmt.Errorf("unsupported value for param %s: %v (%s)", tag.Get("locationName"), value.Interface(), value.Type().Name()) diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go index 87584628a..ff1ef6830 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go @@ -9,6 +9,8 @@ import ( "strconv" "strings" "time" + + "github.com/aws/aws-sdk-go/private/protocol" ) // UnmarshalXML deserializes an xml.Decoder into the container v. V @@ -52,9 +54,15 @@ func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { if t == "" { switch rtype.Kind() { case reflect.Struct: - t = "structure" + // also it can't be a time object + if _, ok := r.Interface().(*time.Time); !ok { + t = "structure" + } case reflect.Slice: - t = "list" + // also it can't be a byte slice + if _, ok := r.Interface().([]byte); !ok { + t = "list" + } case reflect.Map: t = "map" } @@ -247,8 +255,12 @@ func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { } r.Set(reflect.ValueOf(&v)) case *time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - t, err := time.Parse(ISO8601UTC, node.Text) + format := tag.Get("timestampFormat") + if len(format) == 0 { + format = protocol.ISO8601TimeFormatName + } + + t, err := protocol.ParseTime(format, node.Text) if err != nil { return err } diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go index 3e970b629..515ce1521 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go @@ -29,6 +29,7 @@ func NewXMLElement(name xml.Name) *XMLNode { // AddChild adds child to the XMLNode. func (n *XMLNode) AddChild(child *XMLNode) { + child.parent = n if _, ok := n.Children[child.Name.Local]; !ok { n.Children[child.Name.Local] = []*XMLNode{} } diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/converter.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/converter.go deleted file mode 100644 index e38e41daf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/converter.go +++ /dev/null @@ -1,443 +0,0 @@ -package dynamodbattribute - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "runtime" - "strconv" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/service/dynamodb" -) - -// ConvertToMap accepts a map[string]interface{} or struct and converts it to a -// map[string]*dynamodb.AttributeValue. -// -// If in contains any structs, it is first JSON encoded/decoded it to convert it -// to a map[string]interface{}, so `json` struct tags are respected. -// -// Deprecated: Use MarshalMap instead -func ConvertToMap(in interface{}) (item map[string]*dynamodb.AttributeValue, err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - if in == nil { - return nil, awserr.New("SerializationError", - "in must be a map[string]interface{} or struct, got ", nil) - } - - v := reflect.ValueOf(in) - if v.Kind() != reflect.Struct && !(v.Kind() == reflect.Map && v.Type().Key().Kind() == reflect.String) { - return nil, awserr.New("SerializationError", - fmt.Sprintf("in must be a map[string]interface{} or struct, got %s", - v.Type().String()), - nil) - } - - if isTyped(reflect.TypeOf(in)) { - var out map[string]interface{} - in = convertToUntyped(in, out) - } - - item = make(map[string]*dynamodb.AttributeValue) - for k, v := range in.(map[string]interface{}) { - item[k] = convertTo(v) - } - - return item, nil -} - -// ConvertFromMap accepts a map[string]*dynamodb.AttributeValue and converts it to a -// map[string]interface{} or struct. -// -// If v points to a struct, the result is first converted it to a -// map[string]interface{}, then JSON encoded/decoded it to convert to a struct, -// so `json` struct tags are respected. -// -// Deprecated: Use UnmarshalMap instead -func ConvertFromMap(item map[string]*dynamodb.AttributeValue, v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to a map[string]interface{} or struct, got %s", - rv.Type()), - nil) - } - if rv.Elem().Kind() != reflect.Struct && !(rv.Elem().Kind() == reflect.Map && rv.Elem().Type().Key().Kind() == reflect.String) { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to a map[string]interface{} or struct, got %s", - rv.Type()), - nil) - } - - m := make(map[string]interface{}) - for k, v := range item { - m[k] = convertFrom(v) - } - - if isTyped(reflect.TypeOf(v)) { - err = convertToTyped(m, v) - } else { - rv.Elem().Set(reflect.ValueOf(m)) - } - - return err -} - -// ConvertToList accepts an array or slice and converts it to a -// []*dynamodb.AttributeValue. -// -// Converting []byte fields to dynamodb.AttributeValue are only currently supported -// if the input is a map[string]interface{} type. []byte within typed structs are not -// converted correctly and are converted into base64 strings. This is a known bug, -// and will be fixed in a later release. -// -// If in contains any structs, it is first JSON encoded/decoded it to convert it -// to a []interface{}, so `json` struct tags are respected. -// -// Deprecated: Use MarshalList instead -func ConvertToList(in interface{}) (item []*dynamodb.AttributeValue, err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - if in == nil { - return nil, awserr.New("SerializationError", - "in must be an array or slice, got ", - nil) - } - - v := reflect.ValueOf(in) - if v.Kind() != reflect.Array && v.Kind() != reflect.Slice { - return nil, awserr.New("SerializationError", - fmt.Sprintf("in must be an array or slice, got %s", - v.Type().String()), - nil) - } - - if isTyped(reflect.TypeOf(in)) { - var out []interface{} - in = convertToUntyped(in, out) - } - - item = make([]*dynamodb.AttributeValue, 0, len(in.([]interface{}))) - for _, v := range in.([]interface{}) { - item = append(item, convertTo(v)) - } - - return item, nil -} - -// ConvertFromList accepts a []*dynamodb.AttributeValue and converts it to an array or -// slice. -// -// If v contains any structs, the result is first converted it to a -// []interface{}, then JSON encoded/decoded it to convert to a typed array or -// slice, so `json` struct tags are respected. -// -// Deprecated: Use UnmarshalList instead -func ConvertFromList(item []*dynamodb.AttributeValue, v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to an array or slice, got %s", - rv.Type()), - nil) - } - if rv.Elem().Kind() != reflect.Array && rv.Elem().Kind() != reflect.Slice { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to an array or slice, got %s", - rv.Type()), - nil) - } - - l := make([]interface{}, 0, len(item)) - for _, v := range item { - l = append(l, convertFrom(v)) - } - - if isTyped(reflect.TypeOf(v)) { - err = convertToTyped(l, v) - } else { - rv.Elem().Set(reflect.ValueOf(l)) - } - - return err -} - -// ConvertTo accepts any interface{} and converts it to a *dynamodb.AttributeValue. -// -// If in contains any structs, it is first JSON encoded/decoded it to convert it -// to a interface{}, so `json` struct tags are respected. -// -// Deprecated: Use Marshal instead -func ConvertTo(in interface{}) (item *dynamodb.AttributeValue, err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - if in != nil && isTyped(reflect.TypeOf(in)) { - var out interface{} - in = convertToUntyped(in, out) - } - - item = convertTo(in) - return item, nil -} - -// ConvertFrom accepts a *dynamodb.AttributeValue and converts it to any interface{}. -// -// If v contains any structs, the result is first converted it to a interface{}, -// then JSON encoded/decoded it to convert to a struct, so `json` struct tags -// are respected. -// -// Deprecated: Use Unmarshal instead -func ConvertFrom(item *dynamodb.AttributeValue, v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if e, ok := r.(runtime.Error); ok { - err = e - } else if s, ok := r.(string); ok { - err = fmt.Errorf(s) - } else { - err = r.(error) - } - item = nil - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to an interface{} or struct, got %s", - rv.Type()), - nil) - } - if rv.Elem().Kind() != reflect.Interface && rv.Elem().Kind() != reflect.Struct { - return awserr.New("SerializationError", - fmt.Sprintf("v must be a non-nil pointer to an interface{} or struct, got %s", - rv.Type()), - nil) - } - - res := convertFrom(item) - - if isTyped(reflect.TypeOf(v)) { - err = convertToTyped(res, v) - } else if res != nil { - rv.Elem().Set(reflect.ValueOf(res)) - } - - return err -} - -func isTyped(v reflect.Type) bool { - switch v.Kind() { - case reflect.Struct: - return true - case reflect.Array, reflect.Slice: - if isTyped(v.Elem()) { - return true - } - case reflect.Map: - if isTyped(v.Key()) { - return true - } - if isTyped(v.Elem()) { - return true - } - case reflect.Ptr: - return isTyped(v.Elem()) - } - return false -} - -func convertToUntyped(in, out interface{}) interface{} { - b, err := json.Marshal(in) - if err != nil { - panic(err) - } - - decoder := json.NewDecoder(bytes.NewReader(b)) - decoder.UseNumber() - err = decoder.Decode(&out) - if err != nil { - panic(err) - } - - return out -} - -func convertToTyped(in, out interface{}) error { - b, err := json.Marshal(in) - if err != nil { - return err - } - - decoder := json.NewDecoder(bytes.NewReader(b)) - return decoder.Decode(&out) -} - -func convertTo(in interface{}) *dynamodb.AttributeValue { - a := &dynamodb.AttributeValue{} - - if in == nil { - a.NULL = new(bool) - *a.NULL = true - return a - } - - if m, ok := in.(map[string]interface{}); ok { - a.M = make(map[string]*dynamodb.AttributeValue) - for k, v := range m { - a.M[k] = convertTo(v) - } - return a - } - - v := reflect.ValueOf(in) - switch v.Kind() { - case reflect.Bool: - a.BOOL = new(bool) - *a.BOOL = v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - a.N = new(string) - *a.N = strconv.FormatInt(v.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - a.N = new(string) - *a.N = strconv.FormatUint(v.Uint(), 10) - case reflect.Float32, reflect.Float64: - a.N = new(string) - *a.N = strconv.FormatFloat(v.Float(), 'f', -1, 64) - case reflect.String: - if n, ok := in.(json.Number); ok { - a.N = new(string) - *a.N = n.String() - } else { - a.S = new(string) - *a.S = v.String() - } - case reflect.Slice: - switch v.Type() { - case reflect.TypeOf(([]byte)(nil)): - a.B = v.Bytes() - default: - a.L = make([]*dynamodb.AttributeValue, v.Len()) - for i := 0; i < v.Len(); i++ { - a.L[i] = convertTo(v.Index(i).Interface()) - } - } - default: - panic(fmt.Sprintf("the type %s is not supported", v.Type().String())) - } - - return a -} - -func convertFrom(a *dynamodb.AttributeValue) interface{} { - if a.S != nil { - return *a.S - } - - if a.N != nil { - // Number is tricky b/c we don't know which numeric type to use. Here we - // simply try the different types from most to least restrictive. - if n, err := strconv.ParseInt(*a.N, 10, 64); err == nil { - return int(n) - } - if n, err := strconv.ParseUint(*a.N, 10, 64); err == nil { - return uint(n) - } - n, err := strconv.ParseFloat(*a.N, 64) - if err != nil { - panic(err) - } - return n - } - - if a.BOOL != nil { - return *a.BOOL - } - - if a.NULL != nil { - return nil - } - - if a.M != nil { - m := make(map[string]interface{}) - for k, v := range a.M { - m[k] = convertFrom(v) - } - return m - } - - if a.L != nil { - l := make([]interface{}, len(a.L)) - for index, v := range a.L { - l[index] = convertFrom(v) - } - return l - } - - if a.B != nil { - return a.B - } - - panic(fmt.Sprintf("%#v is not a supported dynamodb.AttributeValue", a)) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/decode.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/decode.go deleted file mode 100644 index 41b67b3ae..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/decode.go +++ /dev/null @@ -1,772 +0,0 @@ -package dynamodbattribute - -import ( - "encoding/base64" - "fmt" - "reflect" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/service/dynamodb" -) - -// An Unmarshaler is an interface to provide custom unmarshaling of -// AttributeValues. Use this to provide custom logic determining -// how AttributeValues should be unmarshaled. -// type ExampleUnmarshaler struct { -// Value int -// } -// -// func (u *exampleUnmarshaler) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { -// if av.N == nil { -// return nil -// } -// -// n, err := strconv.ParseInt(*av.N, 10, 0) -// if err != nil { -// return err -// } -// -// u.Value = n -// return nil -// } -type Unmarshaler interface { - UnmarshalDynamoDBAttributeValue(*dynamodb.AttributeValue) error -} - -// Unmarshal will unmarshal DynamoDB AttributeValues to Go value types. -// Both generic interface{} and concrete types are valid unmarshal -// destination types. -// -// Unmarshal will allocate maps, slices, and pointers as needed to -// unmarshal the AttributeValue into the provided type value. -// -// When unmarshaling AttributeValues into structs Unmarshal matches -// the field names of the struct to the AttributeValue Map keys. -// Initially it will look for exact field name matching, but will -// fall back to case insensitive if not exact match is found. -// -// With the exception of omitempty, omitemptyelem, binaryset, numberset -// and stringset all struct tags used by Marshal are also used by -// Unmarshal. -// -// When decoding AttributeValues to interfaces Unmarshal will use the -// following types. -// -// []byte, AV Binary (B) -// [][]byte, AV Binary Set (BS) -// bool, AV Boolean (BOOL) -// []interface{}, AV List (L) -// map[string]interface{}, AV Map (M) -// float64, AV Number (N) -// Number, AV Number (N) with UseNumber set -// []float64, AV Number Set (NS) -// []Number, AV Number Set (NS) with UseNumber set -// string, AV String (S) -// []string, AV String Set (SS) -// -// If the Decoder option, UseNumber is set numbers will be unmarshaled -// as Number values instead of float64. Use this to maintain the original -// string formating of the number as it was represented in the AttributeValue. -// In addition provides additional opportunities to parse the number -// string based on individual use cases. -// -// When unmarshaling any error that occurs will halt the unmarshal -// and return the error. -// -// The output value provided must be a non-nil pointer -func Unmarshal(av *dynamodb.AttributeValue, out interface{}) error { - return NewDecoder().Decode(av, out) -} - -// UnmarshalMap is an alias for Unmarshal which unmarshals from -// a map of AttributeValues. -// -// The output value provided must be a non-nil pointer -func UnmarshalMap(m map[string]*dynamodb.AttributeValue, out interface{}) error { - return NewDecoder().Decode(&dynamodb.AttributeValue{M: m}, out) -} - -// UnmarshalList is an alias for Unmarshal func which unmarshals -// a slice of AttributeValues. -// -// The output value provided must be a non-nil pointer -func UnmarshalList(l []*dynamodb.AttributeValue, out interface{}) error { - return NewDecoder().Decode(&dynamodb.AttributeValue{L: l}, out) -} - -// UnmarshalListOfMaps is an alias for Unmarshal func which unmarshals a -// slice of maps of attribute values. -// -// This is useful for when you need to unmarshal the Items from a DynamoDB -// Query API call. -// -// The output value provided must be a non-nil pointer -func UnmarshalListOfMaps(l []map[string]*dynamodb.AttributeValue, out interface{}) error { - items := make([]*dynamodb.AttributeValue, len(l)) - for i, m := range l { - items[i] = &dynamodb.AttributeValue{M: m} - } - - return UnmarshalList(items, out) -} - -// A Decoder provides unmarshaling AttributeValues to Go value types. -type Decoder struct { - MarshalOptions - - // Instructs the decoder to decode AttributeValue Numbers as - // Number type instead of float64 when the destination type - // is interface{}. Similar to encoding/json.Number - UseNumber bool -} - -// NewDecoder creates a new Decoder with default configuration. Use -// the `opts` functional options to override the default configuration. -func NewDecoder(opts ...func(*Decoder)) *Decoder { - d := &Decoder{ - MarshalOptions: MarshalOptions{ - SupportJSONTags: true, - }, - } - for _, o := range opts { - o(d) - } - - return d -} - -// Decode will unmarshal an AttributeValue into a Go value type. An error -// will be return if the decoder is unable to unmarshal the AttributeValue -// to the provide Go value type. -// -// The output value provided must be a non-nil pointer -func (d *Decoder) Decode(av *dynamodb.AttributeValue, out interface{}, opts ...func(*Decoder)) error { - v := reflect.ValueOf(out) - if v.Kind() != reflect.Ptr || v.IsNil() || !v.IsValid() { - return &InvalidUnmarshalError{Type: reflect.TypeOf(out)} - } - - return d.decode(av, v, tag{}) -} - -var stringInterfaceMapType = reflect.TypeOf(map[string]interface{}(nil)) -var byteSliceType = reflect.TypeOf([]byte(nil)) -var byteSliceSlicetype = reflect.TypeOf([][]byte(nil)) -var numberType = reflect.TypeOf(Number("")) -var timeType = reflect.TypeOf(time.Time{}) - -func (d *Decoder) decode(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - var u Unmarshaler - if av == nil || av.NULL != nil { - u, v = indirect(v, true) - if u != nil { - return u.UnmarshalDynamoDBAttributeValue(av) - } - return d.decodeNull(v) - } - - u, v = indirect(v, false) - if u != nil { - return u.UnmarshalDynamoDBAttributeValue(av) - } - - switch { - case len(av.B) != 0: - return d.decodeBinary(av.B, v) - case av.BOOL != nil: - return d.decodeBool(av.BOOL, v) - case len(av.BS) != 0: - return d.decodeBinarySet(av.BS, v) - case len(av.L) != 0: - return d.decodeList(av.L, v) - case len(av.M) != 0: - return d.decodeMap(av.M, v) - case av.N != nil: - return d.decodeNumber(av.N, v, fieldTag) - case len(av.NS) != 0: - return d.decodeNumberSet(av.NS, v) - case av.S != nil: - return d.decodeString(av.S, v, fieldTag) - case len(av.SS) != 0: - return d.decodeStringSet(av.SS, v) - } - - return nil -} - -func (d *Decoder) decodeBinary(b []byte, v reflect.Value) error { - if v.Kind() == reflect.Interface { - buf := make([]byte, len(b)) - copy(buf, b) - v.Set(reflect.ValueOf(buf)) - return nil - } - - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return &UnmarshalTypeError{Value: "binary", Type: v.Type()} - } - - if v.Type() == byteSliceType { - // Optimization for []byte types - if v.IsNil() || v.Cap() < len(b) { - v.Set(reflect.MakeSlice(byteSliceType, len(b), len(b))) - } else if v.Len() != len(b) { - v.SetLen(len(b)) - } - copy(v.Interface().([]byte), b) - return nil - } - - switch v.Type().Elem().Kind() { - case reflect.Uint8: - // Fallback to reflection copy for type aliased of []byte type - if v.Kind() != reflect.Array && (v.IsNil() || v.Cap() < len(b)) { - v.Set(reflect.MakeSlice(v.Type(), len(b), len(b))) - } else if v.Len() != len(b) { - v.SetLen(len(b)) - } - for i := 0; i < len(b); i++ { - v.Index(i).SetUint(uint64(b[i])) - } - default: - if v.Kind() == reflect.Array { - switch v.Type().Elem().Kind() { - case reflect.Uint8: - reflect.Copy(v, reflect.ValueOf(b)) - default: - return &UnmarshalTypeError{Value: "binary", Type: v.Type()} - } - - break - } - - return &UnmarshalTypeError{Value: "binary", Type: v.Type()} - } - - return nil -} - -func (d *Decoder) decodeBool(b *bool, v reflect.Value) error { - switch v.Kind() { - case reflect.Bool, reflect.Interface: - v.Set(reflect.ValueOf(*b).Convert(v.Type())) - default: - return &UnmarshalTypeError{Value: "bool", Type: v.Type()} - } - - return nil -} - -func (d *Decoder) decodeBinarySet(bs [][]byte, v reflect.Value) error { - isArray := false - - switch v.Kind() { - case reflect.Slice: - // Make room for the slice elements if needed - if v.IsNil() || v.Cap() < len(bs) { - // What about if ignoring nil/empty values? - v.Set(reflect.MakeSlice(v.Type(), 0, len(bs))) - } - case reflect.Array: - // Limited to capacity of existing array. - isArray = true - case reflect.Interface: - set := make([][]byte, len(bs)) - for i, b := range bs { - if err := d.decodeBinary(b, reflect.ValueOf(&set[i]).Elem()); err != nil { - return err - } - } - v.Set(reflect.ValueOf(set)) - return nil - default: - return &UnmarshalTypeError{Value: "binary set", Type: v.Type()} - } - - for i := 0; i < v.Cap() && i < len(bs); i++ { - if !isArray { - v.SetLen(i + 1) - } - u, elem := indirect(v.Index(i), false) - if u != nil { - return u.UnmarshalDynamoDBAttributeValue(&dynamodb.AttributeValue{BS: bs}) - } - if err := d.decodeBinary(bs[i], elem); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) decodeNumber(n *string, v reflect.Value, fieldTag tag) error { - switch v.Kind() { - case reflect.Interface: - i, err := d.decodeNumberToInterface(n) - if err != nil { - return err - } - v.Set(reflect.ValueOf(i)) - return nil - case reflect.String: - if v.Type() == numberType { // Support Number value type - v.Set(reflect.ValueOf(Number(*n))) - return nil - } - v.Set(reflect.ValueOf(*n)) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - i, err := strconv.ParseInt(*n, 10, 64) - if err != nil { - return err - } - if v.OverflowInt(i) { - return &UnmarshalTypeError{ - Value: fmt.Sprintf("number overflow, %s", *n), - Type: v.Type(), - } - } - v.SetInt(i) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - i, err := strconv.ParseUint(*n, 10, 64) - if err != nil { - return err - } - if v.OverflowUint(i) { - return &UnmarshalTypeError{ - Value: fmt.Sprintf("number overflow, %s", *n), - Type: v.Type(), - } - } - v.SetUint(i) - case reflect.Float32, reflect.Float64: - i, err := strconv.ParseFloat(*n, 64) - if err != nil { - return err - } - if v.OverflowFloat(i) { - return &UnmarshalTypeError{ - Value: fmt.Sprintf("number overflow, %s", *n), - Type: v.Type(), - } - } - v.SetFloat(i) - default: - if v.Type().ConvertibleTo(timeType) && fieldTag.AsUnixTime { - t, err := decodeUnixTime(*n) - if err != nil { - return err - } - v.Set(reflect.ValueOf(t).Convert(v.Type())) - return nil - } - return &UnmarshalTypeError{Value: "number", Type: v.Type()} - } - - return nil -} - -func (d *Decoder) decodeNumberToInterface(n *string) (interface{}, error) { - if d.UseNumber { - return Number(*n), nil - } - - // Default to float64 for all numbers - return strconv.ParseFloat(*n, 64) -} - -func (d *Decoder) decodeNumberSet(ns []*string, v reflect.Value) error { - isArray := false - - switch v.Kind() { - case reflect.Slice: - // Make room for the slice elements if needed - if v.IsNil() || v.Cap() < len(ns) { - // What about if ignoring nil/empty values? - v.Set(reflect.MakeSlice(v.Type(), 0, len(ns))) - } - case reflect.Array: - // Limited to capacity of existing array. - isArray = true - case reflect.Interface: - if d.UseNumber { - set := make([]Number, len(ns)) - for i, n := range ns { - if err := d.decodeNumber(n, reflect.ValueOf(&set[i]).Elem(), tag{}); err != nil { - return err - } - } - v.Set(reflect.ValueOf(set)) - } else { - set := make([]float64, len(ns)) - for i, n := range ns { - if err := d.decodeNumber(n, reflect.ValueOf(&set[i]).Elem(), tag{}); err != nil { - return err - } - } - v.Set(reflect.ValueOf(set)) - } - return nil - default: - return &UnmarshalTypeError{Value: "number set", Type: v.Type()} - } - - for i := 0; i < v.Cap() && i < len(ns); i++ { - if !isArray { - v.SetLen(i + 1) - } - u, elem := indirect(v.Index(i), false) - if u != nil { - return u.UnmarshalDynamoDBAttributeValue(&dynamodb.AttributeValue{NS: ns}) - } - if err := d.decodeNumber(ns[i], elem, tag{}); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) decodeList(avList []*dynamodb.AttributeValue, v reflect.Value) error { - isArray := false - - switch v.Kind() { - case reflect.Slice: - // Make room for the slice elements if needed - if v.IsNil() || v.Cap() < len(avList) { - // What about if ignoring nil/empty values? - v.Set(reflect.MakeSlice(v.Type(), 0, len(avList))) - } - case reflect.Array: - // Limited to capacity of existing array. - isArray = true - case reflect.Interface: - s := make([]interface{}, len(avList)) - for i, av := range avList { - if err := d.decode(av, reflect.ValueOf(&s[i]).Elem(), tag{}); err != nil { - return err - } - } - v.Set(reflect.ValueOf(s)) - return nil - default: - return &UnmarshalTypeError{Value: "list", Type: v.Type()} - } - - // If v is not a slice, array - for i := 0; i < v.Cap() && i < len(avList); i++ { - if !isArray { - v.SetLen(i + 1) - } - - if err := d.decode(avList[i], v.Index(i), tag{}); err != nil { - return err - } - } - - return nil -} - -func (d *Decoder) decodeMap(avMap map[string]*dynamodb.AttributeValue, v reflect.Value) error { - switch v.Kind() { - case reflect.Map: - t := v.Type() - if t.Key().Kind() != reflect.String { - return &UnmarshalTypeError{Value: "map string key", Type: t.Key()} - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - case reflect.Interface: - v.Set(reflect.MakeMap(stringInterfaceMapType)) - v = v.Elem() - default: - return &UnmarshalTypeError{Value: "map", Type: v.Type()} - } - - if v.Kind() == reflect.Map { - for k, av := range avMap { - key := reflect.ValueOf(k) - elem := reflect.New(v.Type().Elem()).Elem() - if err := d.decode(av, elem, tag{}); err != nil { - return err - } - v.SetMapIndex(key, elem) - } - } else if v.Kind() == reflect.Struct { - fields := unionStructFields(v.Type(), d.MarshalOptions) - for k, av := range avMap { - if f, ok := fieldByName(fields, k); ok { - fv := fieldByIndex(v, f.Index, func(v *reflect.Value) bool { - v.Set(reflect.New(v.Type().Elem())) - return true // to continue the loop. - }) - if err := d.decode(av, fv, f.tag); err != nil { - return err - } - } - } - } - - return nil -} - -func (d *Decoder) decodeNull(v reflect.Value) error { - if v.IsValid() && v.CanSet() { - v.Set(reflect.Zero(v.Type())) - } - - return nil -} - -func (d *Decoder) decodeString(s *string, v reflect.Value, fieldTag tag) error { - if fieldTag.AsString { - return d.decodeNumber(s, v, fieldTag) - } - - // To maintain backwards compatibility with ConvertFrom family of methods which - // converted strings to time.Time structs - if v.Type().ConvertibleTo(timeType) { - t, err := time.Parse(time.RFC3339, *s) - if err != nil { - return err - } - v.Set(reflect.ValueOf(t).Convert(v.Type())) - return nil - } - - switch v.Kind() { - case reflect.String: - v.SetString(*s) - case reflect.Slice: - // To maintain backwards compatibility with the ConvertFrom family of methods - // which converted []byte into base64-encoded strings if the input was typed - if v.Type() == byteSliceType { - decoded, err := base64.StdEncoding.DecodeString(*s) - if err != nil { - return &UnmarshalError{Err: err, Value: "string", Type: v.Type()} - } - v.SetBytes(decoded) - } - case reflect.Interface: - // Ensure type aliasing is handled properly - v.Set(reflect.ValueOf(*s).Convert(v.Type())) - default: - return &UnmarshalTypeError{Value: "string", Type: v.Type()} - } - - return nil -} - -func (d *Decoder) decodeStringSet(ss []*string, v reflect.Value) error { - isArray := false - - switch v.Kind() { - case reflect.Slice: - // Make room for the slice elements if needed - if v.IsNil() || v.Cap() < len(ss) { - v.Set(reflect.MakeSlice(v.Type(), 0, len(ss))) - } - case reflect.Array: - // Limited to capacity of existing array. - isArray = true - case reflect.Interface: - set := make([]string, len(ss)) - for i, s := range ss { - if err := d.decodeString(s, reflect.ValueOf(&set[i]).Elem(), tag{}); err != nil { - return err - } - } - v.Set(reflect.ValueOf(set)) - return nil - default: - return &UnmarshalTypeError{Value: "string set", Type: v.Type()} - } - - for i := 0; i < v.Cap() && i < len(ss); i++ { - if !isArray { - v.SetLen(i + 1) - } - u, elem := indirect(v.Index(i), false) - if u != nil { - return u.UnmarshalDynamoDBAttributeValue(&dynamodb.AttributeValue{SS: ss}) - } - if err := d.decodeString(ss[i], elem, tag{}); err != nil { - return err - } - } - - return nil -} - -func decodeUnixTime(n string) (time.Time, error) { - v, err := strconv.ParseInt(n, 10, 64) - if err != nil { - return time.Time{}, &UnmarshalError{ - Err: err, Value: n, Type: timeType, - } - } - - return time.Unix(v, 0), nil -} - -// indirect will walk a value's interface or pointer value types. Returning -// the final value or the value a unmarshaler is defined on. -// -// Based on the enoding/json type reflect value type indirection in Go Stdlib -// https://golang.org/src/encoding/json/decode.go indirect func. -func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, reflect.Value) { - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - if v.Kind() != reflect.Ptr { - break - } - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, reflect.Value{} - } - } - v = v.Elem() - } - - return nil, v -} - -// A Number represents a Attributevalue number literal. -type Number string - -// Float64 attempts to cast the number ot a float64, returning -// the result of the case or error if the case failed. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 attempts to cast the number ot a int64, returning -// the result of the case or error if the case failed. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -// Uint64 attempts to cast the number ot a uint64, returning -// the result of the case or error if the case failed. -func (n Number) Uint64() (uint64, error) { - return strconv.ParseUint(string(n), 10, 64) -} - -// String returns the raw number represented as a string -func (n Number) String() string { - return string(n) -} - -type emptyOrigError struct{} - -func (e emptyOrigError) OrigErr() error { - return nil -} - -// An UnmarshalTypeError is an error type representing a error -// unmarshaling the AttributeValue's element to a Go value type. -// Includes details about the AttributeValue type and Go value type. -type UnmarshalTypeError struct { - emptyOrigError - Value string - Type reflect.Type -} - -// Error returns the string representation of the error. -// satisfying the error interface -func (e *UnmarshalTypeError) Error() string { - return fmt.Sprintf("%s: %s", e.Code(), e.Message()) -} - -// Code returns the code of the error, satisfying the awserr.Error -// interface. -func (e *UnmarshalTypeError) Code() string { - return "UnmarshalTypeError" -} - -// Message returns the detailed message of the error, satisfying -// the awserr.Error interface. -func (e *UnmarshalTypeError) Message() string { - return "cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() -} - -// An InvalidUnmarshalError is an error type representing an invalid type -// encountered while unmarshaling a AttributeValue to a Go value type. -type InvalidUnmarshalError struct { - emptyOrigError - Type reflect.Type -} - -// Error returns the string representation of the error. -// satisfying the error interface -func (e *InvalidUnmarshalError) Error() string { - return fmt.Sprintf("%s: %s", e.Code(), e.Message()) -} - -// Code returns the code of the error, satisfying the awserr.Error -// interface. -func (e *InvalidUnmarshalError) Code() string { - return "InvalidUnmarshalError" -} - -// Message returns the detailed message of the error, satisfying -// the awserr.Error interface. -func (e *InvalidUnmarshalError) Message() string { - if e.Type == nil { - return "cannot unmarshal to nil value" - } - if e.Type.Kind() != reflect.Ptr { - return "cannot unmarshal to non-pointer value, got " + e.Type.String() - } - return "cannot unmarshal to nil value, " + e.Type.String() -} - -// An UnmarshalError wraps an error that occured while unmarshaling a DynamoDB -// AttributeValue element into a Go type. This is different from UnmarshalTypeError -// in that it wraps the underlying error that occured. -type UnmarshalError struct { - Err error - Value string - Type reflect.Type -} - -// Error returns the string representation of the error. -// satisfying the error interface. -func (e *UnmarshalError) Error() string { - return fmt.Sprintf("%s: %s\ncaused by: %v", e.Code(), e.Message(), e.Err) -} - -// OrigErr returns the original error that caused this issue. -func (e UnmarshalError) OrigErr() error { - return e.Err -} - -// Code returns the code of the error, satisfying the awserr.Error -// interface. -func (e *UnmarshalError) Code() string { - return "UnmarshalError" -} - -// Message returns the detailed message of the error, satisfying -// the awserr.Error interface. -func (e *UnmarshalError) Message() string { - return fmt.Sprintf("cannot unmarshal %q into %s.", - e.Value, e.Type.String()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/doc.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/doc.go deleted file mode 100644 index b83a29c95..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/doc.go +++ /dev/null @@ -1,101 +0,0 @@ -// Package dynamodbattribute provides marshaling and unmarshaling utilities to -// convert between Go types and dynamodb.AttributeValues. -// -// These utilities allow you to marshal slices, maps, structs, and scalar values -// to and from dynamodb.AttributeValue. These are useful when marshaling -// Go value tyes to dynamodb.AttributeValue for DynamoDB requests, or -// unmarshaling the dynamodb.AttributeValue back into a Go value type. -// -// AttributeValue Marshaling -// -// To marshal a Go type to a dynamodbAttributeValue you can use the Marshal -// functions in the dynamodbattribute package. There are specialized versions -// of these functions for collections of Attributevalue, such as maps and lists. -// -// The following example uses MarshalMap to convert the Record Go type to a -// dynamodb.AttributeValue type and use the value to make a PutItem API request. -// -// type Record struct { -// ID string -// URLs []string -// } -// -// //... -// -// r := Record{ -// ID: "ABC123", -// URLs: []string{ -// "https://example.com/first/link", -// "https://example.com/second/url", -// }, -// } -// av, err := dynamodbattribute.MarshalMap(r) -// if err != nil { -// panic(fmt.Sprintf("failed to DynamoDB marshal Record, %v", err)) -// } -// -// _, err = svc.PutItem(&dynamodb.PutItemInput{ -// TableName: aws.String(myTableName), -// Item: av, -// }) -// if err != nil { -// panic(fmt.Sprintf("failed to put Record to DynamoDB, %v", err)) -// } -// -// AttributeValue Unmarshaling -// -// To unmarshal a dynamodb.AttributeValue to a Go type you can use the Unmarshal -// functions in the dynamodbattribute package. There are specialized versions -// of these functions for collections of Attributevalue, such as maps and lists. -// -// The following example will unmarshal the DynamoDB's Scan API operation. The -// Items returned by the operation will be unmarshaled into the slice of Records -// Go type. -// -// type Record struct { -// ID string -// URLs []string -// } -// -// //... -// -// var records []Record -// -// // Use the ScanPages method to perform the scan with pagination. Use -// // just Scan method to make the API call without pagination. -// err := svc.ScanPages(&dynamodb.ScanInput{ -// TableName: aws.String(myTableName), -// }, func(page *dynamodb.ScanOutput, last bool) bool { -// recs := []Record{} -// -// err := dynamodbattribute.UnmarshalListOfMaps(page.Items, &recs) -// if err != nil { -// panic(fmt.Sprintf("failed to unmarshal Dynamodb Scan Items, %v", err)) -// } -// -// records = append(records, recs...) -// -// return true // keep paging -// }) -// -// The ConvertTo, ConvertToList, ConvertToMap, ConvertFrom, ConvertFromMap -// and ConvertFromList methods have been deprecated. The Marshal and Unmarshal -// functions should be used instead. The ConvertTo|From marshallers do not -// support BinarySet, NumberSet, nor StringSets, and will incorrectly marshal -// binary data fields in structs as base64 strings. -// -// The Marshal and Unmarshal functions correct this behavior, and removes -// the reliance on encoding.json. `json` struct tags are still supported. In -// addition support for a new struct tag `dynamodbav` was added. Support for -// the json.Marshaler and json.Unmarshaler interfaces have been removed and -// replaced with have been replaced with dynamodbattribute.Marshaler and -// dynamodbattribute.Unmarshaler interfaces. -// -// The Unmarshal functions are backwards compatible with data marshalled by -// ConvertTo*, but the reverse is not true: objects marshalled using Marshal -// are not necessarily usable by ConvertFrom*. This backward compatibility is -// intended to assist with incremental upgrading of data following a switch -// away from the Convert* family of functions. -// -// `time.Time` is marshaled as RFC3339 format. -package dynamodbattribute diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/encode.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/encode.go deleted file mode 100644 index 15c80785c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/encode.go +++ /dev/null @@ -1,646 +0,0 @@ -package dynamodbattribute - -import ( - "fmt" - "reflect" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/dynamodb" -) - -// An UnixTime provides aliasing of time.Time into a type that when marshaled -// and unmarshaled with DynamoDB AttributeValues it will be done so as number -// instead of string in seconds since January 1, 1970 UTC. -// -// This type is useful as an alternative to the struct tag `unixtime` when you -// want to have your time value marshaled as Unix time in seconds intead of -// the default time.RFC3339. -// -// Important to note that zero value time as unixtime is not 0 seconds -// from January 1, 1970 UTC, but -62135596800. Which is seconds between -// January 1, 0001 UTC, and January 1, 0001 UTC. -type UnixTime time.Time - -// MarshalDynamoDBAttributeValue implements the Marshaler interface so that -// the UnixTime can be marshaled from to a DynamoDB AttributeValue number -// value encoded in the number of seconds since January 1, 1970 UTC. -func (e UnixTime) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { - t := time.Time(e) - s := strconv.FormatInt(t.Unix(), 10) - av.N = &s - - return nil -} - -// UnmarshalDynamoDBAttributeValue implements the Unmarshaler interface so that -// the UnixTime can be unmarshaled from a DynamoDB AttributeValue number representing -// the number of seconds since January 1, 1970 UTC. -// -// If an error parsing the AttributeValue number occurs UnmarshalError will be -// returned. -func (e *UnixTime) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { - t, err := decodeUnixTime(aws.StringValue(av.N)) - if err != nil { - return err - } - - *e = UnixTime(t) - return nil -} - -// A Marshaler is an interface to provide custom marshaling of Go value types -// to AttributeValues. Use this to provide custom logic determining how a -// Go Value type should be marshaled. -// -// type ExampleMarshaler struct { -// Value int -// } -// func (m *ExampleMarshaler) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error { -// n := fmt.Sprintf("%v", m.Value) -// av.N = &n -// return nil -// } -// -type Marshaler interface { - MarshalDynamoDBAttributeValue(*dynamodb.AttributeValue) error -} - -// Marshal will serialize the passed in Go value type into a DynamoDB AttributeValue -// type. This value can be used in DynamoDB API operations to simplify marshaling -// your Go value types into AttributeValues. -// -// Marshal will recursively transverse the passed in value marshaling its -// contents into a AttributeValue. Marshal supports basic scalars -// (int,uint,float,bool,string), maps, slices, and structs. Anonymous -// nested types are flattened based on Go anonymous type visibility. -// -// Marshaling slices to AttributeValue will default to a List for all -// types except for []byte and [][]byte. []byte will be marshaled as -// Binary data (B), and [][]byte will be marshaled as binary data set -// (BS). -// -// `dynamodbav` struct tag can be used to control how the value will be -// marshaled into a AttributeValue. -// -// // Field is ignored -// Field int `dynamodbav:"-"` -// -// // Field AttributeValue map key "myName" -// Field int `dynamodbav:"myName"` -// -// // Field AttributeValue map key "myName", and -// // Field is omitted if it is empty -// Field int `dynamodbav:"myName,omitempty"` -// -// // Field AttributeValue map key "Field", and -// // Field is omitted if it is empty -// Field int `dynamodbav:",omitempty"` -// -// // Field's elems will be omitted if empty -// // only valid for slices, and maps. -// Field []string `dynamodbav:",omitemptyelem"` -// -// // Field will be marshaled as a AttributeValue string -// // only value for number types, (int,uint,float) -// Field int `dynamodbav:",string"` -// -// // Field will be marshaled as a binary set -// Field [][]byte `dynamodbav:",binaryset"` -// -// // Field will be marshaled as a number set -// Field []int `dynamodbav:",numberset"` -// -// // Field will be marshaled as a string set -// Field []string `dynamodbav:",stringset"` -// -// // Field will be marshaled as Unix time number in seconds. -// // This tag is only valid with time.Time typed struct fields. -// // Important to note that zero value time as unixtime is not 0 seconds -// // from January 1, 1970 UTC, but -62135596800. Which is seconds between -// // January 1, 0001 UTC, and January 1, 0001 UTC. -// Field time.Time `dynamodbav:",unixtime"` -// -// The omitempty tag is only used during Marshaling and is ignored for -// Unmarshal. Any zero value or a value when marshaled results in a -// AttributeValue NULL will be added to AttributeValue Maps during struct -// marshal. The omitemptyelem tag works the same as omitempty except it -// applies to maps and slices instead of struct fields, and will not be -// included in the marshaled AttributeValue Map, List, or Set. -// -// For convenience and backwards compatibility with ConvertTo functions -// json struct tags are supported by the Marshal and Unmarshal. If -// both json and dynamodbav struct tags are provided the json tag will -// be ignored in favor of dynamodbav. -// -// All struct fields and with anonymous fields, are marshaled unless the -// any of the following conditions are meet. -// -// - the field is not exported -// - json or dynamodbav field tag is "-" -// - json or dynamodbav field tag specifies "omitempty", and is empty. -// -// Pointer and interfaces values encode as the value pointed to or contained -// in the interface. A nil value encodes as the AttributeValue NULL value. -// -// Channel, complex, and function values are not encoded and will be skipped -// when walking the value to be marshaled. -// -// When marshaling any error that occurs will halt the marshal and return -// the error. -// -// Marshal cannot represent cyclic data structures and will not handle them. -// Passing cyclic structures to Marshal will result in an infinite recursion. -func Marshal(in interface{}) (*dynamodb.AttributeValue, error) { - return NewEncoder().Encode(in) -} - -// MarshalMap is an alias for Marshal func which marshals Go value -// type to a map of AttributeValues. -// -// This is useful for DynamoDB APIs such as PutItem. -func MarshalMap(in interface{}) (map[string]*dynamodb.AttributeValue, error) { - av, err := NewEncoder().Encode(in) - if err != nil || av == nil || av.M == nil { - return map[string]*dynamodb.AttributeValue{}, err - } - - return av.M, nil -} - -// MarshalList is an alias for Marshal func which marshals Go value -// type to a slice of AttributeValues. -func MarshalList(in interface{}) ([]*dynamodb.AttributeValue, error) { - av, err := NewEncoder().Encode(in) - if err != nil || av == nil || av.L == nil { - return []*dynamodb.AttributeValue{}, err - } - - return av.L, nil -} - -// A MarshalOptions is a collection of options shared between marshaling -// and unmarshaling -type MarshalOptions struct { - // States that the encoding/json struct tags should be supported. - // if a `dynamodbav` struct tag is also provided the encoding/json - // tag will be ignored. - // - // Enabled by default. - SupportJSONTags bool - - // Support other custom struct tag keys, such as `yaml` or `toml`. - // Note that values provided with a custom TagKey must also be supported - // by the (un)marshalers in this package. - TagKey string -} - -// An Encoder provides marshaling Go value types to AttributeValues. -type Encoder struct { - MarshalOptions - - // Empty strings, "", will be marked as NULL AttributeValue types. - // Empty strings are not valid values for DynamoDB. Will not apply - // to lists, sets, or maps. Use the struct tag `omitemptyelem` - // to skip empty (zero) values in lists, sets and maps. - // - // Enabled by default. - NullEmptyString bool -} - -// NewEncoder creates a new Encoder with default configuration. Use -// the `opts` functional options to override the default configuration. -func NewEncoder(opts ...func(*Encoder)) *Encoder { - e := &Encoder{ - MarshalOptions: MarshalOptions{ - SupportJSONTags: true, - }, - NullEmptyString: true, - } - for _, o := range opts { - o(e) - } - - return e -} - -// Encode will marshal a Go value type to an AttributeValue. Returning -// the AttributeValue constructed or error. -func (e *Encoder) Encode(in interface{}) (*dynamodb.AttributeValue, error) { - av := &dynamodb.AttributeValue{} - if err := e.encode(av, reflect.ValueOf(in), tag{}); err != nil { - return nil, err - } - - return av, nil -} - -func fieldByIndex(v reflect.Value, index []int, - OnEmbeddedNilStruct func(*reflect.Value) bool) reflect.Value { - fv := v - for i, x := range index { - if i > 0 { - if fv.Kind() == reflect.Ptr && fv.Type().Elem().Kind() == reflect.Struct { - if fv.IsNil() && !OnEmbeddedNilStruct(&fv) { - break - } - fv = fv.Elem() - } - } - fv = fv.Field(x) - } - return fv -} - -func (e *Encoder) encode(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - // We should check for omitted values first before dereferencing. - if fieldTag.OmitEmpty && emptyValue(v) { - encodeNull(av) - return nil - } - - // Handle both pointers and interface conversion into types - v = valueElem(v) - - if v.Kind() != reflect.Invalid { - if used, err := tryMarshaler(av, v); used { - return err - } - } - - switch v.Kind() { - case reflect.Invalid: - encodeNull(av) - case reflect.Struct: - return e.encodeStruct(av, v, fieldTag) - case reflect.Map: - return e.encodeMap(av, v, fieldTag) - case reflect.Slice, reflect.Array: - return e.encodeSlice(av, v, fieldTag) - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - // do nothing for unsupported types - default: - return e.encodeScalar(av, v, fieldTag) - } - - return nil -} - -func (e *Encoder) encodeStruct(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - // To maintain backwards compatibility with ConvertTo family of methods which - // converted time.Time structs to strings - if v.Type().ConvertibleTo(timeType) { - var t time.Time - t = v.Convert(timeType).Interface().(time.Time) - if fieldTag.AsUnixTime { - return UnixTime(t).MarshalDynamoDBAttributeValue(av) - } - s := t.Format(time.RFC3339Nano) - av.S = &s - return nil - } - - av.M = map[string]*dynamodb.AttributeValue{} - fields := unionStructFields(v.Type(), e.MarshalOptions) - for _, f := range fields { - if f.Name == "" { - return &InvalidMarshalError{msg: "map key cannot be empty"} - } - - found := true - fv := fieldByIndex(v, f.Index, func(v *reflect.Value) bool { - found = false - return false // to break the loop. - }) - if !found { - continue - } - elem := &dynamodb.AttributeValue{} - err := e.encode(elem, fv, f.tag) - if err != nil { - return err - } - skip, err := keepOrOmitEmpty(f.OmitEmpty, elem, err) - if err != nil { - return err - } else if skip { - continue - } - - av.M[f.Name] = elem - } - if len(av.M) == 0 { - encodeNull(av) - } - - return nil -} - -func (e *Encoder) encodeMap(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - av.M = map[string]*dynamodb.AttributeValue{} - for _, key := range v.MapKeys() { - keyName := fmt.Sprint(key.Interface()) - if keyName == "" { - return &InvalidMarshalError{msg: "map key cannot be empty"} - } - - elemVal := v.MapIndex(key) - elem := &dynamodb.AttributeValue{} - err := e.encode(elem, elemVal, tag{}) - skip, err := keepOrOmitEmpty(fieldTag.OmitEmptyElem, elem, err) - if err != nil { - return err - } else if skip { - continue - } - - av.M[keyName] = elem - } - if len(av.M) == 0 { - encodeNull(av) - } - - return nil -} - -func (e *Encoder) encodeSlice(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - switch v.Type().Elem().Kind() { - case reflect.Uint8: - slice := reflect.MakeSlice(byteSliceType, v.Len(), v.Len()) - reflect.Copy(slice, v) - - b := slice.Bytes() - if len(b) == 0 { - encodeNull(av) - return nil - } - av.B = append([]byte{}, b...) - default: - var elemFn func(dynamodb.AttributeValue) error - - if fieldTag.AsBinSet || v.Type() == byteSliceSlicetype { // Binary Set - av.BS = make([][]byte, 0, v.Len()) - elemFn = func(elem dynamodb.AttributeValue) error { - if elem.B == nil { - return &InvalidMarshalError{msg: "binary set must only contain non-nil byte slices"} - } - av.BS = append(av.BS, elem.B) - return nil - } - } else if fieldTag.AsNumSet { // Number Set - av.NS = make([]*string, 0, v.Len()) - elemFn = func(elem dynamodb.AttributeValue) error { - if elem.N == nil { - return &InvalidMarshalError{msg: "number set must only contain non-nil string numbers"} - } - av.NS = append(av.NS, elem.N) - return nil - } - } else if fieldTag.AsStrSet { // String Set - av.SS = make([]*string, 0, v.Len()) - elemFn = func(elem dynamodb.AttributeValue) error { - if elem.S == nil { - return &InvalidMarshalError{msg: "string set must only contain non-nil strings"} - } - av.SS = append(av.SS, elem.S) - return nil - } - } else { // List - av.L = make([]*dynamodb.AttributeValue, 0, v.Len()) - elemFn = func(elem dynamodb.AttributeValue) error { - av.L = append(av.L, &elem) - return nil - } - } - - if n, err := e.encodeList(v, fieldTag, elemFn); err != nil { - return err - } else if n == 0 { - encodeNull(av) - } - } - - return nil -} - -func (e *Encoder) encodeList(v reflect.Value, fieldTag tag, elemFn func(dynamodb.AttributeValue) error) (int, error) { - count := 0 - for i := 0; i < v.Len(); i++ { - elem := dynamodb.AttributeValue{} - err := e.encode(&elem, v.Index(i), tag{OmitEmpty: fieldTag.OmitEmptyElem}) - skip, err := keepOrOmitEmpty(fieldTag.OmitEmptyElem, &elem, err) - if err != nil { - return 0, err - } else if skip { - continue - } - - if err := elemFn(elem); err != nil { - return 0, err - } - count++ - } - - return count, nil -} - -func (e *Encoder) encodeScalar(av *dynamodb.AttributeValue, v reflect.Value, fieldTag tag) error { - if v.Type() == numberType { - s := v.String() - if fieldTag.AsString { - av.S = &s - } else { - av.N = &s - } - return nil - } - - switch v.Kind() { - case reflect.Bool: - av.BOOL = new(bool) - *av.BOOL = v.Bool() - case reflect.String: - if err := e.encodeString(av, v); err != nil { - return err - } - default: - // Fallback to encoding numbers, will return invalid type if not supported - if err := e.encodeNumber(av, v); err != nil { - return err - } - if fieldTag.AsString && av.NULL == nil && av.N != nil { - av.S = av.N - av.N = nil - } - } - - return nil -} - -func (e *Encoder) encodeNumber(av *dynamodb.AttributeValue, v reflect.Value) error { - if used, err := tryMarshaler(av, v); used { - return err - } - - var out string - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - out = encodeInt(v.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - out = encodeUint(v.Uint()) - case reflect.Float32, reflect.Float64: - out = encodeFloat(v.Float()) - default: - return &unsupportedMarshalTypeError{Type: v.Type()} - } - - av.N = &out - - return nil -} - -func (e *Encoder) encodeString(av *dynamodb.AttributeValue, v reflect.Value) error { - if used, err := tryMarshaler(av, v); used { - return err - } - - switch v.Kind() { - case reflect.String: - s := v.String() - if len(s) == 0 && e.NullEmptyString { - encodeNull(av) - } else { - av.S = &s - } - default: - return &unsupportedMarshalTypeError{Type: v.Type()} - } - - return nil -} - -func encodeInt(i int64) string { - return strconv.FormatInt(i, 10) -} -func encodeUint(u uint64) string { - return strconv.FormatUint(u, 10) -} -func encodeFloat(f float64) string { - return strconv.FormatFloat(f, 'f', -1, 64) -} -func encodeNull(av *dynamodb.AttributeValue) { - t := true - *av = dynamodb.AttributeValue{NULL: &t} -} - -func valueElem(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Interface, reflect.Ptr: - for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr { - v = v.Elem() - } - } - - return v -} - -func emptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} - -func tryMarshaler(av *dynamodb.AttributeValue, v reflect.Value) (bool, error) { - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - - if v.Type().NumMethod() == 0 { - return false, nil - } - - if m, ok := v.Interface().(Marshaler); ok { - return true, m.MarshalDynamoDBAttributeValue(av) - } - - return false, nil -} - -func keepOrOmitEmpty(omitEmpty bool, av *dynamodb.AttributeValue, err error) (bool, error) { - if err != nil { - if _, ok := err.(*unsupportedMarshalTypeError); ok { - return true, nil - } - return false, err - } - - if av.NULL != nil && omitEmpty { - return true, nil - } - - return false, nil -} - -// An InvalidMarshalError is an error type representing an error -// occurring when marshaling a Go value type to an AttributeValue. -type InvalidMarshalError struct { - emptyOrigError - msg string -} - -// Error returns the string representation of the error. -// satisfying the error interface -func (e *InvalidMarshalError) Error() string { - return fmt.Sprintf("%s: %s", e.Code(), e.Message()) -} - -// Code returns the code of the error, satisfying the awserr.Error -// interface. -func (e *InvalidMarshalError) Code() string { - return "InvalidMarshalError" -} - -// Message returns the detailed message of the error, satisfying -// the awserr.Error interface. -func (e *InvalidMarshalError) Message() string { - return e.msg -} - -// An unsupportedMarshalTypeError represents a Go value type -// which cannot be marshaled into an AttributeValue and should -// be skipped by the marshaler. -type unsupportedMarshalTypeError struct { - emptyOrigError - Type reflect.Type -} - -// Error returns the string representation of the error. -// satisfying the error interface -func (e *unsupportedMarshalTypeError) Error() string { - return fmt.Sprintf("%s: %s", e.Code(), e.Message()) -} - -// Code returns the code of the error, satisfying the awserr.Error -// interface. -func (e *unsupportedMarshalTypeError) Code() string { - return "unsupportedMarshalTypeError" -} - -// Message returns the detailed message of the error, satisfying -// the awserr.Error interface. -func (e *unsupportedMarshalTypeError) Message() string { - return "Go value type " + e.Type.String() + " is not supported" -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/field.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/field.go deleted file mode 100644 index f1c74fec3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/field.go +++ /dev/null @@ -1,273 +0,0 @@ -package dynamodbattribute - -import ( - "reflect" - "sort" - "strings" -) - -type field struct { - tag - - Name string - NameFromTag bool - - Index []int - Type reflect.Type -} - -func fieldByName(fields []field, name string) (field, bool) { - foldExists := false - foldField := field{} - - for _, f := range fields { - if f.Name == name { - return f, true - } - if !foldExists && strings.EqualFold(f.Name, name) { - foldField = f - foldExists = true - } - } - - return foldField, foldExists -} - -func buildField(pIdx []int, i int, sf reflect.StructField, fieldTag tag) field { - f := field{ - Name: sf.Name, - Type: sf.Type, - tag: fieldTag, - } - if len(fieldTag.Name) != 0 { - f.NameFromTag = true - f.Name = fieldTag.Name - } - - f.Index = make([]int, len(pIdx)+1) - copy(f.Index, pIdx) - f.Index[len(pIdx)] = i - - return f -} - -func unionStructFields(t reflect.Type, opts MarshalOptions) []field { - fields := enumFields(t, opts) - - sort.Sort(fieldsByName(fields)) - - fields = visibleFields(fields) - - return fields -} - -// enumFields will recursively iterate through a structure and its nested -// anonymous fields. -// -// Based on the enoding/json struct field enumeration of the Go Stdlib -// https://golang.org/src/encoding/json/encode.go typeField func. -func enumFields(t reflect.Type, opts MarshalOptions) []field { - // Fields to explore - current := []field{} - next := []field{{Type: t}} - - // count of queued names - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - visited := map[reflect.Type]struct{}{} - fields := []field{} - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if _, ok := visited[f.Type]; ok { - continue - } - visited[f.Type] = struct{}{} - - for i := 0; i < f.Type.NumField(); i++ { - sf := f.Type.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { - // Ignore unexported and non-anonymous fields - // unexported but anonymous field may still be used if - // the type has exported nested fields - continue - } - - fieldTag := tag{} - fieldTag.parseAVTag(sf.Tag) - // Because MarshalOptions.TagKey must be explicitly set, use it - // over JSON, which is enabled by default. - if opts.TagKey != "" && fieldTag == (tag{}) { - fieldTag.parseStructTag(opts.TagKey, sf.Tag) - } else if opts.SupportJSONTags && fieldTag == (tag{}) { - fieldTag.parseStructTag("json", sf.Tag) - } - - if fieldTag.Ignore { - continue - } - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - ft = ft.Elem() - } - - structField := buildField(f.Index, i, sf, fieldTag) - structField.Type = ft - - if !sf.Anonymous || ft.Kind() != reflect.Struct { - fields = append(fields, structField) - if count[f.Type] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, structField) - } - continue - } - - // Record new anon struct to explore next round - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, structField) - } - } - } - } - - return fields -} - -// visibleFields will return a slice of fields which are visible based on -// Go's standard visiblity rules with the exception of ties being broken -// by depth and struct tag naming. -// -// Based on the enoding/json field filtering of the Go Stdlib -// https://golang.org/src/encoding/json/encode.go typeField func. -func visibleFields(fields []field) []field { - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.Name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.Name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(fieldsByIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -// -// Based on the enoding/json field filtering of the Go Stdlib -// https://golang.org/src/encoding/json/encode.go dominantField func. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].Index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.Index) > length { - fields = fields[:i] - break - } - if f.NameFromTag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -// fieldsByName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -// -// Based on the enoding/json field filtering of the Go Stdlib -// https://golang.org/src/encoding/json/encode.go fieldsByName type. -type fieldsByName []field - -func (x fieldsByName) Len() int { return len(x) } - -func (x fieldsByName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x fieldsByName) Less(i, j int) bool { - if x[i].Name != x[j].Name { - return x[i].Name < x[j].Name - } - if len(x[i].Index) != len(x[j].Index) { - return len(x[i].Index) < len(x[j].Index) - } - if x[i].NameFromTag != x[j].NameFromTag { - return x[i].NameFromTag - } - return fieldsByIndex(x).Less(i, j) -} - -// fieldsByIndex sorts field by index sequence. -// -// Based on the enoding/json field filtering of the Go Stdlib -// https://golang.org/src/encoding/json/encode.go fieldsByIndex type. -type fieldsByIndex []field - -func (x fieldsByIndex) Len() int { return len(x) } - -func (x fieldsByIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x fieldsByIndex) Less(i, j int) bool { - for k, xik := range x[i].Index { - if k >= len(x[j].Index) { - return false - } - if xik != x[j].Index[k] { - return xik < x[j].Index[k] - } - } - return len(x[i].Index) < len(x[j].Index) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/tag.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/tag.go deleted file mode 100644 index 8b76a7e91..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute/tag.go +++ /dev/null @@ -1,68 +0,0 @@ -package dynamodbattribute - -import ( - "reflect" - "strings" -) - -type tag struct { - Name string - Ignore bool - OmitEmpty bool - OmitEmptyElem bool - AsString bool - AsBinSet, AsNumSet, AsStrSet bool - AsUnixTime bool -} - -func (t *tag) parseAVTag(structTag reflect.StructTag) { - tagStr := structTag.Get("dynamodbav") - if len(tagStr) == 0 { - return - } - - t.parseTagStr(tagStr) -} - -func (t *tag) parseStructTag(tag string, structTag reflect.StructTag) { - tagStr := structTag.Get(tag) - if len(tagStr) == 0 { - return - } - - t.parseTagStr(tagStr) -} - -func (t *tag) parseTagStr(tagStr string) { - parts := strings.Split(tagStr, ",") - if len(parts) == 0 { - return - } - - if name := parts[0]; name == "-" { - t.Name = "" - t.Ignore = true - } else { - t.Name = name - t.Ignore = false - } - - for _, opt := range parts[1:] { - switch opt { - case "omitempty": - t.OmitEmpty = true - case "omitemptyelem": - t.OmitEmptyElem = true - case "string": - t.AsString = true - case "binaryset": - t.AsBinSet = true - case "numberset": - t.AsNumSet = true - case "stringset": - t.AsStrSet = true - case "unixtime": - t.AsUnixTime = true - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go index e667a099d..f91e30b57 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go @@ -17,8 +17,8 @@ const opAddClientIDToOpenIDConnectProvider = "AddClientIDToOpenIDConnectProvider // AddClientIDToOpenIDConnectProviderRequest generates a "aws/request.Request" representing the // client's request for the AddClientIDToOpenIDConnectProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -38,7 +38,7 @@ const opAddClientIDToOpenIDConnectProvider = "AddClientIDToOpenIDConnectProvider // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProvider func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpenIDConnectProviderInput) (req *request.Request, output *AddClientIDToOpenIDConnectProviderOutput) { op := &request.Operation{ Name: opAddClientIDToOpenIDConnectProvider, @@ -52,8 +52,7 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen output = &AddClientIDToOpenIDConnectProviderOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -62,8 +61,8 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // Adds a new client ID (also known as audience) to the list of client IDs already // registered for the specified IAM OpenID Connect (OIDC) provider resource. // -// This action is idempotent; it does not fail or return an error if you add -// an existing client ID to the provider. +// This operation is idempotent; it does not fail or return an error if you +// add an existing client ID to the provider. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -78,8 +77,8 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // for an input parameter. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -89,7 +88,7 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProvider func (c *IAM) AddClientIDToOpenIDConnectProvider(input *AddClientIDToOpenIDConnectProviderInput) (*AddClientIDToOpenIDConnectProviderOutput, error) { req, out := c.AddClientIDToOpenIDConnectProviderRequest(input) return out, req.Send() @@ -115,8 +114,8 @@ const opAddRoleToInstanceProfile = "AddRoleToInstanceProfile" // AddRoleToInstanceProfileRequest generates a "aws/request.Request" representing the // client's request for the AddRoleToInstanceProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -136,7 +135,7 @@ const opAddRoleToInstanceProfile = "AddRoleToInstanceProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfile func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInput) (req *request.Request, output *AddRoleToInstanceProfileOutput) { op := &request.Operation{ Name: opAddRoleToInstanceProfile, @@ -150,18 +149,23 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp output = &AddRoleToInstanceProfileOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // AddRoleToInstanceProfile API operation for AWS Identity and Access Management. // // Adds the specified IAM role to the specified instance profile. An instance -// profile can contain only one role, and this limit cannot be increased. +// profile can contain only one role, and this limit cannot be increased. You +// can remove the existing role and then add a different role to an instance +// profile. You must then wait for the change to appear across all of AWS because +// of eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency). +// To force the change, you must disassociate the instance profile (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html) +// and then associate the instance profile (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html), +// or you can stop your instance and then restart it. // // The caller of this API must be granted the PassRole permission on the IAM -// role by a permission policy. +// role by a permissions policy. // // For more information about roles, go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // For more information about instance profiles, go to About Instance Profiles @@ -176,8 +180,8 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -197,7 +201,7 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfile func (c *IAM) AddRoleToInstanceProfile(input *AddRoleToInstanceProfileInput) (*AddRoleToInstanceProfileOutput, error) { req, out := c.AddRoleToInstanceProfileRequest(input) return out, req.Send() @@ -223,8 +227,8 @@ const opAddUserToGroup = "AddUserToGroup" // AddUserToGroupRequest generates a "aws/request.Request" representing the // client's request for the AddUserToGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -244,7 +248,7 @@ const opAddUserToGroup = "AddUserToGroup" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroup func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Request, output *AddUserToGroupOutput) { op := &request.Operation{ Name: opAddUserToGroup, @@ -258,8 +262,7 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re output = &AddUserToGroupOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -276,8 +279,8 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -287,7 +290,7 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroup func (c *IAM) AddUserToGroup(input *AddUserToGroupInput) (*AddUserToGroupOutput, error) { req, out := c.AddUserToGroupRequest(input) return out, req.Send() @@ -313,8 +316,8 @@ const opAttachGroupPolicy = "AttachGroupPolicy" // AttachGroupPolicyRequest generates a "aws/request.Request" representing the // client's request for the AttachGroupPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -334,7 +337,7 @@ const opAttachGroupPolicy = "AttachGroupPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *request.Request, output *AttachGroupPolicyOutput) { op := &request.Operation{ Name: opAttachGroupPolicy, @@ -348,8 +351,7 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ output = &AttachGroupPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -373,8 +375,8 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -392,7 +394,7 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicy func (c *IAM) AttachGroupPolicy(input *AttachGroupPolicyInput) (*AttachGroupPolicyOutput, error) { req, out := c.AttachGroupPolicyRequest(input) return out, req.Send() @@ -418,8 +420,8 @@ const opAttachRolePolicy = "AttachRolePolicy" // AttachRolePolicyRequest generates a "aws/request.Request" representing the // client's request for the AttachRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -439,7 +441,7 @@ const opAttachRolePolicy = "AttachRolePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicy func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *request.Request, output *AttachRolePolicyOutput) { op := &request.Operation{ Name: opAttachRolePolicy, @@ -453,8 +455,7 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques output = &AttachRolePolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -482,8 +483,8 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -507,7 +508,7 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicy func (c *IAM) AttachRolePolicy(input *AttachRolePolicyInput) (*AttachRolePolicyOutput, error) { req, out := c.AttachRolePolicyRequest(input) return out, req.Send() @@ -533,8 +534,8 @@ const opAttachUserPolicy = "AttachUserPolicy" // AttachUserPolicyRequest generates a "aws/request.Request" representing the // client's request for the AttachUserPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -554,7 +555,7 @@ const opAttachUserPolicy = "AttachUserPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicy func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *request.Request, output *AttachUserPolicyOutput) { op := &request.Operation{ Name: opAttachUserPolicy, @@ -568,8 +569,7 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques output = &AttachUserPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -593,8 +593,8 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -612,7 +612,7 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicy func (c *IAM) AttachUserPolicy(input *AttachUserPolicyInput) (*AttachUserPolicyOutput, error) { req, out := c.AttachUserPolicyRequest(input) return out, req.Send() @@ -638,8 +638,8 @@ const opChangePassword = "ChangePassword" // ChangePasswordRequest generates a "aws/request.Request" representing the // client's request for the ChangePassword operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -659,7 +659,7 @@ const opChangePassword = "ChangePassword" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePassword +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePassword func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Request, output *ChangePasswordOutput) { op := &request.Operation{ Name: opChangePassword, @@ -673,15 +673,14 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re output = &ChangePasswordOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // ChangePassword API operation for AWS Identity and Access Management. // -// Changes the password of the IAM user who is calling this action. The root -// account password is not affected by this action. +// Changes the password of the IAM user who is calling this operation. The AWS +// account root user password is not affected by this operation. // // To change the password for a different user, see UpdateLoginProfile. For // more information about modifying passwords, see Managing Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html) @@ -696,8 +695,8 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidUserTypeException "InvalidUserType" // The request was rejected because the type of user for the transaction was @@ -721,7 +720,7 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePassword +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePassword func (c *IAM) ChangePassword(input *ChangePasswordInput) (*ChangePasswordOutput, error) { req, out := c.ChangePasswordRequest(input) return out, req.Send() @@ -747,8 +746,8 @@ const opCreateAccessKey = "CreateAccessKey" // CreateAccessKeyRequest generates a "aws/request.Request" representing the // client's request for the CreateAccessKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -768,7 +767,7 @@ const opCreateAccessKey = "CreateAccessKey" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKey func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request.Request, output *CreateAccessKeyOutput) { op := &request.Operation{ Name: opCreateAccessKey, @@ -791,9 +790,10 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // the specified user. The default status for new keys is Active. // // If you do not specify a user name, IAM determines the user name implicitly -// based on the AWS access key ID signing the request. Because this action works -// for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// based on the AWS access key ID signing the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials. This is true even if the AWS +// account has no associated users. // // For information about limits on the number of keys you can create, see Limitations // on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) @@ -814,8 +814,8 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -825,7 +825,7 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKey func (c *IAM) CreateAccessKey(input *CreateAccessKeyInput) (*CreateAccessKeyOutput, error) { req, out := c.CreateAccessKeyRequest(input) return out, req.Send() @@ -851,8 +851,8 @@ const opCreateAccountAlias = "CreateAccountAlias" // CreateAccountAliasRequest generates a "aws/request.Request" representing the // client's request for the CreateAccountAlias operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -872,7 +872,7 @@ const opCreateAccountAlias = "CreateAccountAlias" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAlias +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAlias func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *request.Request, output *CreateAccountAliasOutput) { op := &request.Operation{ Name: opCreateAccountAlias, @@ -886,8 +886,7 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *re output = &CreateAccountAliasOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -917,7 +916,7 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAlias +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAlias func (c *IAM) CreateAccountAlias(input *CreateAccountAliasInput) (*CreateAccountAliasOutput, error) { req, out := c.CreateAccountAliasRequest(input) return out, req.Send() @@ -943,8 +942,8 @@ const opCreateGroup = "CreateGroup" // CreateGroupRequest generates a "aws/request.Request" representing the // client's request for the CreateGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -964,7 +963,7 @@ const opCreateGroup = "CreateGroup" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroup func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, output *CreateGroupOutput) { op := &request.Operation{ Name: opCreateGroup, @@ -1006,14 +1005,14 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // exists. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroup func (c *IAM) CreateGroup(input *CreateGroupInput) (*CreateGroupOutput, error) { req, out := c.CreateGroupRequest(input) return out, req.Send() @@ -1039,8 +1038,8 @@ const opCreateInstanceProfile = "CreateInstanceProfile" // CreateInstanceProfileRequest generates a "aws/request.Request" representing the // client's request for the CreateInstanceProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1060,7 +1059,7 @@ const opCreateInstanceProfile = "CreateInstanceProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfile func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (req *request.Request, output *CreateInstanceProfileOutput) { op := &request.Operation{ Name: opCreateInstanceProfile, @@ -1106,7 +1105,7 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfile func (c *IAM) CreateInstanceProfile(input *CreateInstanceProfileInput) (*CreateInstanceProfileOutput, error) { req, out := c.CreateInstanceProfileRequest(input) return out, req.Send() @@ -1132,8 +1131,8 @@ const opCreateLoginProfile = "CreateLoginProfile" // CreateLoginProfileRequest generates a "aws/request.Request" representing the // client's request for the CreateLoginProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1153,7 +1152,7 @@ const opCreateLoginProfile = "CreateLoginProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfile func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *request.Request, output *CreateLoginProfileOutput) { op := &request.Operation{ Name: opCreateLoginProfile, @@ -1190,8 +1189,8 @@ func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *re // exists. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodePasswordPolicyViolationException "PasswordPolicyViolation" // The request was rejected because the provided password did not meet the requirements @@ -1205,7 +1204,7 @@ func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfile func (c *IAM) CreateLoginProfile(input *CreateLoginProfileInput) (*CreateLoginProfileOutput, error) { req, out := c.CreateLoginProfileRequest(input) return out, req.Send() @@ -1231,8 +1230,8 @@ const opCreateOpenIDConnectProvider = "CreateOpenIDConnectProvider" // CreateOpenIDConnectProviderRequest generates a "aws/request.Request" representing the // client's request for the CreateOpenIDConnectProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1252,7 +1251,7 @@ const opCreateOpenIDConnectProvider = "CreateOpenIDConnectProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProvider func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProviderInput) (req *request.Request, output *CreateOpenIDConnectProviderOutput) { op := &request.Operation{ Name: opCreateOpenIDConnectProvider, @@ -1275,19 +1274,24 @@ func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProvi // OpenID Connect (OIDC) (http://openid.net/connect/). // // The OIDC provider that you create with this operation can be used as a principal -// in a role's trust policy to establish a trust relationship between AWS and -// the OIDC provider. +// in a role's trust policy. Such a policy establishes a trust relationship +// between AWS and the OIDC provider. // -// When you create the IAM OIDC provider, you specify the URL of the OIDC identity -// provider (IdP) to trust, a list of client IDs (also known as audiences) that -// identify the application or applications that are allowed to authenticate -// using the OIDC provider, and a list of thumbprints of the server certificate(s) -// that the IdP uses. You get all of this information from the OIDC IdP that -// you want to use for access to AWS. +// When you create the IAM OIDC provider, you specify the following: // -// Because trust for the OIDC provider is ultimately derived from the IAM provider -// that this action creates, it is a best practice to limit access to the CreateOpenIDConnectProvider -// action to highly-privileged users. +// * The URL of the OIDC identity provider (IdP) to trust +// +// * A list of client IDs (also known as audiences) that identify the application +// or applications that are allowed to authenticate using the OIDC provider +// +// * A list of thumbprints of the server certificate(s) that the IdP uses. +// +// You get all of this information from the OIDC IdP that you want to use to +// access AWS. +// +// Because trust for the OIDC provider is derived from the IAM provider that +// this operation creates, it is best to limit access to the CreateOpenIDConnectProvider +// operation to highly privileged users. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1313,7 +1317,7 @@ func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProvi // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProvider func (c *IAM) CreateOpenIDConnectProvider(input *CreateOpenIDConnectProviderInput) (*CreateOpenIDConnectProviderOutput, error) { req, out := c.CreateOpenIDConnectProviderRequest(input) return out, req.Send() @@ -1339,8 +1343,8 @@ const opCreatePolicy = "CreatePolicy" // CreatePolicyRequest generates a "aws/request.Request" representing the // client's request for the CreatePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1360,7 +1364,7 @@ const opCreatePolicy = "CreatePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicy func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Request, output *CreatePolicyOutput) { op := &request.Operation{ Name: opCreatePolicy, @@ -1418,7 +1422,7 @@ func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicy func (c *IAM) CreatePolicy(input *CreatePolicyInput) (*CreatePolicyOutput, error) { req, out := c.CreatePolicyRequest(input) return out, req.Send() @@ -1444,8 +1448,8 @@ const opCreatePolicyVersion = "CreatePolicyVersion" // CreatePolicyVersionRequest generates a "aws/request.Request" representing the // client's request for the CreatePolicyVersion operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1465,7 +1469,7 @@ const opCreatePolicyVersion = "CreatePolicyVersion" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersion func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req *request.Request, output *CreatePolicyVersionOutput) { op := &request.Operation{ Name: opCreatePolicyVersion, @@ -1506,8 +1510,8 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -1525,7 +1529,7 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersion func (c *IAM) CreatePolicyVersion(input *CreatePolicyVersionInput) (*CreatePolicyVersionOutput, error) { req, out := c.CreatePolicyVersionRequest(input) return out, req.Send() @@ -1551,8 +1555,8 @@ const opCreateRole = "CreateRole" // CreateRoleRequest generates a "aws/request.Request" representing the // client's request for the CreateRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1572,7 +1576,7 @@ const opCreateRole = "CreateRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRole func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, output *CreateRoleOutput) { op := &request.Operation{ Name: opCreateRole, @@ -1592,7 +1596,7 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // CreateRole API operation for AWS Identity and Access Management. // // Creates a new role for your AWS account. For more information about roles, -// go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). +// go to IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // For information about limitations on role names and the number of roles you // can create, go to Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) // in the IAM User Guide. @@ -1621,11 +1625,16 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // The request was rejected because the policy document was malformed. The error // message describes the specific error. // +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRole func (c *IAM) CreateRole(input *CreateRoleInput) (*CreateRoleOutput, error) { req, out := c.CreateRoleRequest(input) return out, req.Send() @@ -1651,8 +1660,8 @@ const opCreateSAMLProvider = "CreateSAMLProvider" // CreateSAMLProviderRequest generates a "aws/request.Request" representing the // client's request for the CreateSAMLProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1672,7 +1681,7 @@ const opCreateSAMLProvider = "CreateSAMLProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProvider func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *request.Request, output *CreateSAMLProviderOutput) { op := &request.Operation{ Name: opCreateSAMLProvider, @@ -1695,14 +1704,14 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *re // SAML 2.0. // // The SAML provider resource that you create with this operation can be used -// as a principal in an IAM role's trust policy to enable federated users who -// sign-in using the SAML IdP to assume the role. You can create an IAM role -// that supports Web-based single sign-on (SSO) to the AWS Management Console -// or one that supports API access to AWS. -// -// When you create the SAML provider resource, you upload an a SAML metadata -// document that you get from your IdP and that includes the issuer's name, -// expiration information, and keys that can be used to validate the SAML authentication +// as a principal in an IAM role's trust policy. Such a policy can enable federated +// users who sign-in using the SAML IdP to assume the role. You can create an +// IAM role that supports Web-based single sign-on (SSO) to the AWS Management +// Console or one that supports API access to AWS. +// +// When you create the SAML provider resource, you upload a SAML metadata document +// that you get from your IdP. That document includes the issuer's name, expiration +// information, and keys that can be used to validate the SAML authentication // response (assertions) that the IdP sends. You must generate the metadata // document using the identity management software that is used as your organization's // IdP. @@ -1738,7 +1747,7 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProvider func (c *IAM) CreateSAMLProvider(input *CreateSAMLProviderInput) (*CreateSAMLProviderOutput, error) { req, out := c.CreateSAMLProviderRequest(input) return out, req.Send() @@ -1764,8 +1773,8 @@ const opCreateServiceLinkedRole = "CreateServiceLinkedRole" // CreateServiceLinkedRoleRequest generates a "aws/request.Request" representing the // client's request for the CreateServiceLinkedRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1785,7 +1794,7 @@ const opCreateServiceLinkedRole = "CreateServiceLinkedRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput) (req *request.Request, output *CreateServiceLinkedRoleOutput) { op := &request.Operation{ Name: opCreateServiceLinkedRole, @@ -1809,12 +1818,9 @@ func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput // ensure that the service is not broken by an unexpectedly changed or deleted // role, which could put your AWS resources into an unknown state. Allowing // the service to control the role helps improve service stability and proper -// cleanup when a service and its role are no longer needed. -// -// The name of the role is autogenerated by combining the string that you specify -// for the AWSServiceName parameter with the string that you specify for the -// CustomSuffix parameter. The resulting name must be unique in your account -// or the request fails. +// cleanup when a service and its role are no longer needed. For more information, +// see Using Service-Linked Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html) +// in the IAM User Guide. // // To attach a policy to this service-linked role, you must make the request // using the AWS service that depends on this role. @@ -1836,14 +1842,14 @@ func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRole func (c *IAM) CreateServiceLinkedRole(input *CreateServiceLinkedRoleInput) (*CreateServiceLinkedRoleOutput, error) { req, out := c.CreateServiceLinkedRoleRequest(input) return out, req.Send() @@ -1869,8 +1875,8 @@ const opCreateServiceSpecificCredential = "CreateServiceSpecificCredential" // CreateServiceSpecificCredentialRequest generates a "aws/request.Request" representing the // client's request for the CreateServiceSpecificCredential operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1890,7 +1896,7 @@ const opCreateServiceSpecificCredential = "CreateServiceSpecificCredential" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredential func (c *IAM) CreateServiceSpecificCredentialRequest(input *CreateServiceSpecificCredentialInput) (req *request.Request, output *CreateServiceSpecificCredentialOutput) { op := &request.Operation{ Name: opCreateServiceSpecificCredential, @@ -1937,13 +1943,13 @@ func (c *IAM) CreateServiceSpecificCredentialRequest(input *CreateServiceSpecifi // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceNotSupportedException "NotSupportedService" // The specified service does not support service-specific credentials. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredential func (c *IAM) CreateServiceSpecificCredential(input *CreateServiceSpecificCredentialInput) (*CreateServiceSpecificCredentialOutput, error) { req, out := c.CreateServiceSpecificCredentialRequest(input) return out, req.Send() @@ -1969,8 +1975,8 @@ const opCreateUser = "CreateUser" // CreateUserRequest generates a "aws/request.Request" representing the // client's request for the CreateUser operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -1990,7 +1996,7 @@ const opCreateUser = "CreateUser" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUser func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, output *CreateUserOutput) { op := &request.Operation{ Name: opCreateUser, @@ -2032,14 +2038,23 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // exists. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUser func (c *IAM) CreateUser(input *CreateUserInput) (*CreateUserOutput, error) { req, out := c.CreateUserRequest(input) return out, req.Send() @@ -2065,8 +2080,8 @@ const opCreateVirtualMFADevice = "CreateVirtualMFADevice" // CreateVirtualMFADeviceRequest generates a "aws/request.Request" representing the // client's request for the CreateVirtualMFADevice operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2086,7 +2101,7 @@ const opCreateVirtualMFADevice = "CreateVirtualMFADevice" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADevice func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) (req *request.Request, output *CreateVirtualMFADeviceOutput) { op := &request.Operation{ Name: opCreateVirtualMFADevice, @@ -2140,7 +2155,7 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADevice func (c *IAM) CreateVirtualMFADevice(input *CreateVirtualMFADeviceInput) (*CreateVirtualMFADeviceOutput, error) { req, out := c.CreateVirtualMFADeviceRequest(input) return out, req.Send() @@ -2166,8 +2181,8 @@ const opDeactivateMFADevice = "DeactivateMFADevice" // DeactivateMFADeviceRequest generates a "aws/request.Request" representing the // client's request for the DeactivateMFADevice operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2187,7 +2202,7 @@ const opDeactivateMFADevice = "DeactivateMFADevice" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADevice func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req *request.Request, output *DeactivateMFADeviceOutput) { op := &request.Operation{ Name: opDeactivateMFADevice, @@ -2201,8 +2216,7 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * output = &DeactivateMFADeviceOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2212,7 +2226,7 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // the user name for which it was originally enabled. // // For more information about creating and working with virtual MFA devices, -// go to Using a Virtual MFA Device (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html) +// go to Enabling a Virtual Multi-factor Authentication (MFA) Device (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2230,8 +2244,8 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // waiting several minutes. The error message describes the entity. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2241,7 +2255,7 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADevice func (c *IAM) DeactivateMFADevice(input *DeactivateMFADeviceInput) (*DeactivateMFADeviceOutput, error) { req, out := c.DeactivateMFADeviceRequest(input) return out, req.Send() @@ -2267,8 +2281,8 @@ const opDeleteAccessKey = "DeleteAccessKey" // DeleteAccessKeyRequest generates a "aws/request.Request" representing the // client's request for the DeleteAccessKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2288,7 +2302,7 @@ const opDeleteAccessKey = "DeleteAccessKey" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKey func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request.Request, output *DeleteAccessKeyOutput) { op := &request.Operation{ Name: opDeleteAccessKey, @@ -2302,8 +2316,7 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. output = &DeleteAccessKeyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2312,9 +2325,10 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // Deletes the access key pair associated with the specified IAM user. // // If you do not specify a user name, IAM determines the user name implicitly -// based on the AWS access key ID signing the request. Because this action works -// for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// based on the AWS access key ID signing the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated users. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2325,8 +2339,8 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2336,7 +2350,7 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKey func (c *IAM) DeleteAccessKey(input *DeleteAccessKeyInput) (*DeleteAccessKeyOutput, error) { req, out := c.DeleteAccessKeyRequest(input) return out, req.Send() @@ -2362,8 +2376,8 @@ const opDeleteAccountAlias = "DeleteAccountAlias" // DeleteAccountAliasRequest generates a "aws/request.Request" representing the // client's request for the DeleteAccountAlias operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2383,7 +2397,7 @@ const opDeleteAccountAlias = "DeleteAccountAlias" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAlias +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAlias func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *request.Request, output *DeleteAccountAliasOutput) { op := &request.Operation{ Name: opDeleteAccountAlias, @@ -2397,8 +2411,7 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re output = &DeleteAccountAliasOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2417,8 +2430,8 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2428,7 +2441,7 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAlias +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAlias func (c *IAM) DeleteAccountAlias(input *DeleteAccountAliasInput) (*DeleteAccountAliasOutput, error) { req, out := c.DeleteAccountAliasRequest(input) return out, req.Send() @@ -2454,8 +2467,8 @@ const opDeleteAccountPasswordPolicy = "DeleteAccountPasswordPolicy" // DeleteAccountPasswordPolicyRequest generates a "aws/request.Request" representing the // client's request for the DeleteAccountPasswordPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2475,7 +2488,7 @@ const opDeleteAccountPasswordPolicy = "DeleteAccountPasswordPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicy func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPolicyInput) (req *request.Request, output *DeleteAccountPasswordPolicyOutput) { op := &request.Operation{ Name: opDeleteAccountPasswordPolicy, @@ -2489,8 +2502,7 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol output = &DeleteAccountPasswordPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2507,8 +2519,8 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2518,7 +2530,7 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicy func (c *IAM) DeleteAccountPasswordPolicy(input *DeleteAccountPasswordPolicyInput) (*DeleteAccountPasswordPolicyOutput, error) { req, out := c.DeleteAccountPasswordPolicyRequest(input) return out, req.Send() @@ -2544,8 +2556,8 @@ const opDeleteGroup = "DeleteGroup" // DeleteGroupRequest generates a "aws/request.Request" representing the // client's request for the DeleteGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2565,7 +2577,7 @@ const opDeleteGroup = "DeleteGroup" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroup func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output *DeleteGroupOutput) { op := &request.Operation{ Name: opDeleteGroup, @@ -2579,8 +2591,7 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output = &DeleteGroupOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2598,8 +2609,8 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has @@ -2613,7 +2624,7 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroup func (c *IAM) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { req, out := c.DeleteGroupRequest(input) return out, req.Send() @@ -2639,8 +2650,8 @@ const opDeleteGroupPolicy = "DeleteGroupPolicy" // DeleteGroupPolicyRequest generates a "aws/request.Request" representing the // client's request for the DeleteGroupPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2660,7 +2671,7 @@ const opDeleteGroupPolicy = "DeleteGroupPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicy func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *request.Request, output *DeleteGroupPolicyOutput) { op := &request.Operation{ Name: opDeleteGroupPolicy, @@ -2674,8 +2685,7 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ output = &DeleteGroupPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2698,8 +2708,8 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2709,7 +2719,7 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicy func (c *IAM) DeleteGroupPolicy(input *DeleteGroupPolicyInput) (*DeleteGroupPolicyOutput, error) { req, out := c.DeleteGroupPolicyRequest(input) return out, req.Send() @@ -2735,8 +2745,8 @@ const opDeleteInstanceProfile = "DeleteInstanceProfile" // DeleteInstanceProfileRequest generates a "aws/request.Request" representing the // client's request for the DeleteInstanceProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2756,7 +2766,7 @@ const opDeleteInstanceProfile = "DeleteInstanceProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfile func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (req *request.Request, output *DeleteInstanceProfileOutput) { op := &request.Operation{ Name: opDeleteInstanceProfile, @@ -2770,8 +2780,7 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r output = &DeleteInstanceProfileOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2780,9 +2789,9 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // Deletes the specified instance profile. The instance profile must not have // an associated role. // -// Make sure you do not have any Amazon EC2 instances running with the instance -// profile you are about to delete. Deleting a role or instance profile that -// is associated with a running instance will break any applications running +// Make sure that you do not have any Amazon EC2 instances running with the +// instance profile you are about to delete. Deleting a role or instance profile +// that is associated with a running instance will break any applications running // on the instance. // // For more information about instance profiles, go to About Instance Profiles @@ -2797,8 +2806,8 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has @@ -2812,7 +2821,7 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfile func (c *IAM) DeleteInstanceProfile(input *DeleteInstanceProfileInput) (*DeleteInstanceProfileOutput, error) { req, out := c.DeleteInstanceProfileRequest(input) return out, req.Send() @@ -2838,8 +2847,8 @@ const opDeleteLoginProfile = "DeleteLoginProfile" // DeleteLoginProfileRequest generates a "aws/request.Request" representing the // client's request for the DeleteLoginProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2859,7 +2868,7 @@ const opDeleteLoginProfile = "DeleteLoginProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfile func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *request.Request, output *DeleteLoginProfileOutput) { op := &request.Operation{ Name: opDeleteLoginProfile, @@ -2873,8 +2882,7 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re output = &DeleteLoginProfileOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2884,7 +2892,7 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // ability to access AWS services through the AWS Management Console. // // Deleting a user's password does not prevent a user from accessing AWS through -// the command line interface or the API. To prevent all user access you must +// the command line interface or the API. To prevent all user access, you must // also either make any access keys inactive or delete them. For more information // about making keys inactive or deleting them, see UpdateAccessKey and DeleteAccessKey. // @@ -2903,8 +2911,8 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // waiting several minutes. The error message describes the entity. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -2914,7 +2922,7 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfile func (c *IAM) DeleteLoginProfile(input *DeleteLoginProfileInput) (*DeleteLoginProfileOutput, error) { req, out := c.DeleteLoginProfileRequest(input) return out, req.Send() @@ -2940,8 +2948,8 @@ const opDeleteOpenIDConnectProvider = "DeleteOpenIDConnectProvider" // DeleteOpenIDConnectProviderRequest generates a "aws/request.Request" representing the // client's request for the DeleteOpenIDConnectProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -2961,7 +2969,7 @@ const opDeleteOpenIDConnectProvider = "DeleteOpenIDConnectProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProvider func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProviderInput) (req *request.Request, output *DeleteOpenIDConnectProviderOutput) { op := &request.Operation{ Name: opDeleteOpenIDConnectProvider, @@ -2975,8 +2983,7 @@ func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProvi output = &DeleteOpenIDConnectProviderOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -2988,8 +2995,8 @@ func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProvi // the provider as a principal in their trust policies. Any attempt to assume // a role that references a deleted provider fails. // -// This action is idempotent; it does not fail or return an error if you call -// the action for a provider that does not exist. +// This operation is idempotent; it does not fail or return an error if you +// call the operation for a provider that does not exist. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3004,14 +3011,14 @@ func (c *IAM) DeleteOpenIDConnectProviderRequest(input *DeleteOpenIDConnectProvi // for an input parameter. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProvider func (c *IAM) DeleteOpenIDConnectProvider(input *DeleteOpenIDConnectProviderInput) (*DeleteOpenIDConnectProviderOutput, error) { req, out := c.DeleteOpenIDConnectProviderRequest(input) return out, req.Send() @@ -3037,8 +3044,8 @@ const opDeletePolicy = "DeletePolicy" // DeletePolicyRequest generates a "aws/request.Request" representing the // client's request for the DeletePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3058,7 +3065,7 @@ const opDeletePolicy = "DeletePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicy func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Request, output *DeletePolicyOutput) { op := &request.Operation{ Name: opDeletePolicy, @@ -3072,8 +3079,7 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques output = &DeletePolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3082,14 +3088,14 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // Deletes the specified managed policy. // // Before you can delete a managed policy, you must first detach the policy -// from all users, groups, and roles that it is attached to, and you must delete -// all of the policy's versions. The following steps describe the process for -// deleting a managed policy: +// from all users, groups, and roles that it is attached to. In addition, you +// must delete all the policy's versions. The following steps describe the process +// for deleting a managed policy: // // * Detach the policy from all users, groups, and roles that the policy // is attached to, using the DetachUserPolicy, DetachGroupPolicy, or DetachRolePolicy -// APIs. To list all the users, groups, and roles that a policy is attached -// to, use ListEntitiesForPolicy. +// API operations. To list all the users, groups, and roles that a policy +// is attached to, use ListEntitiesForPolicy. // // * Delete all versions of the policy using DeletePolicyVersion. To list // the policy's versions, use ListPolicyVersions. You cannot use DeletePolicyVersion @@ -3112,8 +3118,8 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -3131,7 +3137,7 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicy func (c *IAM) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error) { req, out := c.DeletePolicyRequest(input) return out, req.Send() @@ -3157,8 +3163,8 @@ const opDeletePolicyVersion = "DeletePolicyVersion" // DeletePolicyVersionRequest generates a "aws/request.Request" representing the // client's request for the DeletePolicyVersion operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3178,7 +3184,7 @@ const opDeletePolicyVersion = "DeletePolicyVersion" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersion func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req *request.Request, output *DeletePolicyVersionOutput) { op := &request.Operation{ Name: opDeletePolicyVersion, @@ -3192,8 +3198,7 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * output = &DeletePolicyVersionOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3218,8 +3223,8 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -3237,7 +3242,7 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersion func (c *IAM) DeletePolicyVersion(input *DeletePolicyVersionInput) (*DeletePolicyVersionOutput, error) { req, out := c.DeletePolicyVersionRequest(input) return out, req.Send() @@ -3263,8 +3268,8 @@ const opDeleteRole = "DeleteRole" // DeleteRoleRequest generates a "aws/request.Request" representing the // client's request for the DeleteRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3284,7 +3289,7 @@ const opDeleteRole = "DeleteRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRole func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, output *DeleteRoleOutput) { op := &request.Operation{ Name: opDeleteRole, @@ -3298,8 +3303,7 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o output = &DeleteRoleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3308,9 +3312,10 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // Deletes the specified role. The role must not have any policies attached. // For more information about roles, go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // -// Make sure you do not have any Amazon EC2 instances running with the role -// you are about to delete. Deleting a role or instance profile that is associated -// with a running instance will break any applications running on the instance. +// Make sure that you do not have any Amazon EC2 instances running with the +// role you are about to delete. Deleting a role or instance profile that is +// associated with a running instance will break any applications running on +// the instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3321,8 +3326,8 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has @@ -3338,11 +3343,16 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // the name of the service that depends on this service-linked role. You must // request the change through that service. // +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRole func (c *IAM) DeleteRole(input *DeleteRoleInput) (*DeleteRoleOutput, error) { req, out := c.DeleteRoleRequest(input) return out, req.Send() @@ -3364,12 +3374,107 @@ func (c *IAM) DeleteRoleWithContext(ctx aws.Context, input *DeleteRoleInput, opt return out, req.Send() } +const opDeleteRolePermissionsBoundary = "DeleteRolePermissionsBoundary" + +// DeleteRolePermissionsBoundaryRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRolePermissionsBoundary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteRolePermissionsBoundary for more information on using the DeleteRolePermissionsBoundary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteRolePermissionsBoundaryRequest method. +// req, resp := client.DeleteRolePermissionsBoundaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePermissionsBoundary +func (c *IAM) DeleteRolePermissionsBoundaryRequest(input *DeleteRolePermissionsBoundaryInput) (req *request.Request, output *DeleteRolePermissionsBoundaryOutput) { + op := &request.Operation{ + Name: opDeleteRolePermissionsBoundary, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteRolePermissionsBoundaryInput{} + } + + output = &DeleteRolePermissionsBoundaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteRolePermissionsBoundary API operation for AWS Identity and Access Management. +// +// Deletes the permissions boundary for the specified IAM role. +// +// Deleting the permissions boundary for a role might increase its permissions +// by allowing anyone who assumes the role to perform all the actions granted +// in its permissions policies. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation DeleteRolePermissionsBoundary for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePermissionsBoundary +func (c *IAM) DeleteRolePermissionsBoundary(input *DeleteRolePermissionsBoundaryInput) (*DeleteRolePermissionsBoundaryOutput, error) { + req, out := c.DeleteRolePermissionsBoundaryRequest(input) + return out, req.Send() +} + +// DeleteRolePermissionsBoundaryWithContext is the same as DeleteRolePermissionsBoundary with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRolePermissionsBoundary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) DeleteRolePermissionsBoundaryWithContext(ctx aws.Context, input *DeleteRolePermissionsBoundaryInput, opts ...request.Option) (*DeleteRolePermissionsBoundaryOutput, error) { + req, out := c.DeleteRolePermissionsBoundaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteRolePolicy = "DeleteRolePolicy" // DeleteRolePolicyRequest generates a "aws/request.Request" representing the // client's request for the DeleteRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3389,7 +3494,7 @@ const opDeleteRolePolicy = "DeleteRolePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicy func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *request.Request, output *DeleteRolePolicyOutput) { op := &request.Operation{ Name: opDeleteRolePolicy, @@ -3403,8 +3508,7 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques output = &DeleteRolePolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3427,8 +3531,8 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -3444,7 +3548,7 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicy func (c *IAM) DeleteRolePolicy(input *DeleteRolePolicyInput) (*DeleteRolePolicyOutput, error) { req, out := c.DeleteRolePolicyRequest(input) return out, req.Send() @@ -3470,8 +3574,8 @@ const opDeleteSAMLProvider = "DeleteSAMLProvider" // DeleteSAMLProviderRequest generates a "aws/request.Request" representing the // client's request for the DeleteSAMLProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3491,7 +3595,7 @@ const opDeleteSAMLProvider = "DeleteSAMLProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProvider func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *request.Request, output *DeleteSAMLProviderOutput) { op := &request.Operation{ Name: opDeleteSAMLProvider, @@ -3505,8 +3609,7 @@ func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *re output = &DeleteSAMLProviderOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3538,14 +3641,14 @@ func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *re // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProvider func (c *IAM) DeleteSAMLProvider(input *DeleteSAMLProviderInput) (*DeleteSAMLProviderOutput, error) { req, out := c.DeleteSAMLProviderRequest(input) return out, req.Send() @@ -3571,8 +3674,8 @@ const opDeleteSSHPublicKey = "DeleteSSHPublicKey" // DeleteSSHPublicKeyRequest generates a "aws/request.Request" representing the // client's request for the DeleteSSHPublicKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3592,7 +3695,7 @@ const opDeleteSSHPublicKey = "DeleteSSHPublicKey" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKey func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *request.Request, output *DeleteSSHPublicKeyOutput) { op := &request.Operation{ Name: opDeleteSSHPublicKey, @@ -3606,8 +3709,7 @@ func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *re output = &DeleteSSHPublicKeyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3615,7 +3717,7 @@ func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *re // // Deletes the specified SSH public key. // -// The SSH public key deleted by this action is used only for authenticating +// The SSH public key deleted by this operation is used only for authenticating // the associated IAM user to an AWS CodeCommit repository. For more information // about using SSH keys to authenticate to an AWS CodeCommit repository, see // Set up AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) @@ -3630,10 +3732,10 @@ func (c *IAM) DeleteSSHPublicKeyRequest(input *DeleteSSHPublicKeyInput) (req *re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKey func (c *IAM) DeleteSSHPublicKey(input *DeleteSSHPublicKeyInput) (*DeleteSSHPublicKeyOutput, error) { req, out := c.DeleteSSHPublicKeyRequest(input) return out, req.Send() @@ -3659,8 +3761,8 @@ const opDeleteServerCertificate = "DeleteServerCertificate" // DeleteServerCertificateRequest generates a "aws/request.Request" representing the // client's request for the DeleteServerCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3680,7 +3782,7 @@ const opDeleteServerCertificate = "DeleteServerCertificate" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificate func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput) (req *request.Request, output *DeleteServerCertificateOutput) { op := &request.Operation{ Name: opDeleteServerCertificate, @@ -3694,8 +3796,7 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput output = &DeleteServerCertificateOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3703,10 +3804,10 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // // Deletes the specified server certificate. // -// For more information about working with server certificates, including a -// list of AWS services that can use the server certificates that you manage -// with IAM, go to Working with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) -// in the IAM User Guide. +// For more information about working with server certificates, see Working +// with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) +// in the IAM User Guide. This topic also includes a list of AWS services that +// can use the server certificates that you manage with IAM. // // If you are using a server certificate with Elastic Load Balancing, deleting // the certificate could have implications for your application. If Elastic @@ -3727,8 +3828,8 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has @@ -3742,7 +3843,7 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificate func (c *IAM) DeleteServerCertificate(input *DeleteServerCertificateInput) (*DeleteServerCertificateOutput, error) { req, out := c.DeleteServerCertificateRequest(input) return out, req.Send() @@ -3768,8 +3869,8 @@ const opDeleteServiceLinkedRole = "DeleteServiceLinkedRole" // DeleteServiceLinkedRoleRequest generates a "aws/request.Request" representing the // client's request for the DeleteServiceLinkedRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3789,7 +3890,7 @@ const opDeleteServiceLinkedRole = "DeleteServiceLinkedRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRole func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput) (req *request.Request, output *DeleteServiceLinkedRoleOutput) { op := &request.Operation{ Name: opDeleteServiceLinkedRole, @@ -3818,8 +3919,8 @@ func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput // If you submit a deletion request for a service-linked role whose linked service // is still accessing a resource, then the deletion task fails. If it fails, // the GetServiceLinkedRoleDeletionStatus API operation returns the reason for -// the failure, including the resources that must be deleted. To delete the -// service-linked role, you must first remove those resources from the linked +// the failure, usually including the resources that must be deleted. To delete +// the service-linked role, you must first remove those resources from the linked // service and then submit the deletion request again. Resources are specific // to the service that is linked to the role. For more information about removing // resources from a service, see the AWS documentation (http://docs.aws.amazon.com/) @@ -3838,8 +3939,8 @@ func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -3849,7 +3950,7 @@ func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRole func (c *IAM) DeleteServiceLinkedRole(input *DeleteServiceLinkedRoleInput) (*DeleteServiceLinkedRoleOutput, error) { req, out := c.DeleteServiceLinkedRoleRequest(input) return out, req.Send() @@ -3875,8 +3976,8 @@ const opDeleteServiceSpecificCredential = "DeleteServiceSpecificCredential" // DeleteServiceSpecificCredentialRequest generates a "aws/request.Request" representing the // client's request for the DeleteServiceSpecificCredential operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3896,7 +3997,7 @@ const opDeleteServiceSpecificCredential = "DeleteServiceSpecificCredential" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredential func (c *IAM) DeleteServiceSpecificCredentialRequest(input *DeleteServiceSpecificCredentialInput) (req *request.Request, output *DeleteServiceSpecificCredentialOutput) { op := &request.Operation{ Name: opDeleteServiceSpecificCredential, @@ -3910,8 +4011,7 @@ func (c *IAM) DeleteServiceSpecificCredentialRequest(input *DeleteServiceSpecifi output = &DeleteServiceSpecificCredentialOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3928,10 +4028,10 @@ func (c *IAM) DeleteServiceSpecificCredentialRequest(input *DeleteServiceSpecifi // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredential func (c *IAM) DeleteServiceSpecificCredential(input *DeleteServiceSpecificCredentialInput) (*DeleteServiceSpecificCredentialOutput, error) { req, out := c.DeleteServiceSpecificCredentialRequest(input) return out, req.Send() @@ -3957,8 +4057,8 @@ const opDeleteSigningCertificate = "DeleteSigningCertificate" // DeleteSigningCertificateRequest generates a "aws/request.Request" representing the // client's request for the DeleteSigningCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -3978,7 +4078,7 @@ const opDeleteSigningCertificate = "DeleteSigningCertificate" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificate func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInput) (req *request.Request, output *DeleteSigningCertificateOutput) { op := &request.Operation{ Name: opDeleteSigningCertificate, @@ -3992,8 +4092,7 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp output = &DeleteSigningCertificateOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4002,9 +4101,10 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // Deletes a signing certificate associated with the specified IAM user. // // If you do not specify a user name, IAM determines the user name implicitly -// based on the AWS access key ID signing the request. Because this action works -// for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated IAM users. +// based on the AWS access key ID signing the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated IAM users. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4015,8 +4115,8 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -4026,7 +4126,7 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificate func (c *IAM) DeleteSigningCertificate(input *DeleteSigningCertificateInput) (*DeleteSigningCertificateOutput, error) { req, out := c.DeleteSigningCertificateRequest(input) return out, req.Send() @@ -4052,8 +4152,8 @@ const opDeleteUser = "DeleteUser" // DeleteUserRequest generates a "aws/request.Request" representing the // client's request for the DeleteUser operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4073,7 +4173,7 @@ const opDeleteUser = "DeleteUser" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUser func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, output *DeleteUserOutput) { op := &request.Operation{ Name: opDeleteUser, @@ -4087,15 +4187,15 @@ func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, o output = &DeleteUserOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // DeleteUser API operation for AWS Identity and Access Management. // // Deletes the specified IAM user. The user must not belong to any groups or -// have any access keys, signing certificates, or attached policies. +// have any access keys, signing certificates, MFA devices enabled for AWS, +// or attached policies. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4110,18 +4210,23 @@ func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, o // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has // attached subordinate entities. The error message describes these entities. // +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUser func (c *IAM) DeleteUser(input *DeleteUserInput) (*DeleteUserOutput, error) { req, out := c.DeleteUserRequest(input) return out, req.Send() @@ -4143,12 +4248,101 @@ func (c *IAM) DeleteUserWithContext(ctx aws.Context, input *DeleteUserInput, opt return out, req.Send() } +const opDeleteUserPermissionsBoundary = "DeleteUserPermissionsBoundary" + +// DeleteUserPermissionsBoundaryRequest generates a "aws/request.Request" representing the +// client's request for the DeleteUserPermissionsBoundary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteUserPermissionsBoundary for more information on using the DeleteUserPermissionsBoundary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteUserPermissionsBoundaryRequest method. +// req, resp := client.DeleteUserPermissionsBoundaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPermissionsBoundary +func (c *IAM) DeleteUserPermissionsBoundaryRequest(input *DeleteUserPermissionsBoundaryInput) (req *request.Request, output *DeleteUserPermissionsBoundaryOutput) { + op := &request.Operation{ + Name: opDeleteUserPermissionsBoundary, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteUserPermissionsBoundaryInput{} + } + + output = &DeleteUserPermissionsBoundaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteUserPermissionsBoundary API operation for AWS Identity and Access Management. +// +// Deletes the permissions boundary for the specified IAM user. +// +// Deleting the permissions boundary for a user might increase its permissions +// by allowing the user to perform all the actions granted in its permissions +// policies. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation DeleteUserPermissionsBoundary for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPermissionsBoundary +func (c *IAM) DeleteUserPermissionsBoundary(input *DeleteUserPermissionsBoundaryInput) (*DeleteUserPermissionsBoundaryOutput, error) { + req, out := c.DeleteUserPermissionsBoundaryRequest(input) + return out, req.Send() +} + +// DeleteUserPermissionsBoundaryWithContext is the same as DeleteUserPermissionsBoundary with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteUserPermissionsBoundary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) DeleteUserPermissionsBoundaryWithContext(ctx aws.Context, input *DeleteUserPermissionsBoundaryInput, opts ...request.Option) (*DeleteUserPermissionsBoundaryOutput, error) { + req, out := c.DeleteUserPermissionsBoundaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteUserPolicy = "DeleteUserPolicy" // DeleteUserPolicyRequest generates a "aws/request.Request" representing the // client's request for the DeleteUserPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4168,7 +4362,7 @@ const opDeleteUserPolicy = "DeleteUserPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicy func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *request.Request, output *DeleteUserPolicyOutput) { op := &request.Operation{ Name: opDeleteUserPolicy, @@ -4182,8 +4376,7 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques output = &DeleteUserPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4206,8 +4399,8 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -4217,7 +4410,7 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicy func (c *IAM) DeleteUserPolicy(input *DeleteUserPolicyInput) (*DeleteUserPolicyOutput, error) { req, out := c.DeleteUserPolicyRequest(input) return out, req.Send() @@ -4243,8 +4436,8 @@ const opDeleteVirtualMFADevice = "DeleteVirtualMFADevice" // DeleteVirtualMFADeviceRequest generates a "aws/request.Request" representing the // client's request for the DeleteVirtualMFADevice operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4264,7 +4457,7 @@ const opDeleteVirtualMFADevice = "DeleteVirtualMFADevice" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADevice func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) (req *request.Request, output *DeleteVirtualMFADeviceOutput) { op := &request.Operation{ Name: opDeleteVirtualMFADevice, @@ -4278,8 +4471,7 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) output = &DeleteVirtualMFADeviceOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4299,8 +4491,8 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeDeleteConflictException "DeleteConflict" // The request was rejected because it attempted to delete a resource that has @@ -4314,7 +4506,7 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADevice func (c *IAM) DeleteVirtualMFADevice(input *DeleteVirtualMFADeviceInput) (*DeleteVirtualMFADeviceOutput, error) { req, out := c.DeleteVirtualMFADeviceRequest(input) return out, req.Send() @@ -4340,8 +4532,8 @@ const opDetachGroupPolicy = "DetachGroupPolicy" // DetachGroupPolicyRequest generates a "aws/request.Request" representing the // client's request for the DetachGroupPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4361,7 +4553,7 @@ const opDetachGroupPolicy = "DetachGroupPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicy func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *request.Request, output *DetachGroupPolicyOutput) { op := &request.Operation{ Name: opDetachGroupPolicy, @@ -4375,8 +4567,7 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ output = &DetachGroupPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4398,8 +4589,8 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -4413,7 +4604,7 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicy func (c *IAM) DetachGroupPolicy(input *DetachGroupPolicyInput) (*DetachGroupPolicyOutput, error) { req, out := c.DetachGroupPolicyRequest(input) return out, req.Send() @@ -4439,8 +4630,8 @@ const opDetachRolePolicy = "DetachRolePolicy" // DetachRolePolicyRequest generates a "aws/request.Request" representing the // client's request for the DetachRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4460,7 +4651,7 @@ const opDetachRolePolicy = "DetachRolePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicy func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *request.Request, output *DetachRolePolicyOutput) { op := &request.Operation{ Name: opDetachRolePolicy, @@ -4474,8 +4665,7 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques output = &DetachRolePolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4497,8 +4687,8 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -4518,7 +4708,7 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicy func (c *IAM) DetachRolePolicy(input *DetachRolePolicyInput) (*DetachRolePolicyOutput, error) { req, out := c.DetachRolePolicyRequest(input) return out, req.Send() @@ -4544,8 +4734,8 @@ const opDetachUserPolicy = "DetachUserPolicy" // DetachUserPolicyRequest generates a "aws/request.Request" representing the // client's request for the DetachUserPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4565,7 +4755,7 @@ const opDetachUserPolicy = "DetachUserPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicy func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *request.Request, output *DetachUserPolicyOutput) { op := &request.Operation{ Name: opDetachUserPolicy, @@ -4579,8 +4769,7 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques output = &DetachUserPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4602,8 +4791,8 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -4617,7 +4806,7 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicy func (c *IAM) DetachUserPolicy(input *DetachUserPolicyInput) (*DetachUserPolicyOutput, error) { req, out := c.DetachUserPolicyRequest(input) return out, req.Send() @@ -4643,8 +4832,8 @@ const opEnableMFADevice = "EnableMFADevice" // EnableMFADeviceRequest generates a "aws/request.Request" representing the // client's request for the EnableMFADevice operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4664,7 +4853,7 @@ const opEnableMFADevice = "EnableMFADevice" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADevice func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request.Request, output *EnableMFADeviceOutput) { op := &request.Operation{ Name: opEnableMFADevice, @@ -4678,8 +4867,7 @@ func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request. output = &EnableMFADeviceOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4716,14 +4904,14 @@ func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request. // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADevice func (c *IAM) EnableMFADevice(input *EnableMFADeviceInput) (*EnableMFADeviceOutput, error) { req, out := c.EnableMFADeviceRequest(input) return out, req.Send() @@ -4749,8 +4937,8 @@ const opGenerateCredentialReport = "GenerateCredentialReport" // GenerateCredentialReportRequest generates a "aws/request.Request" representing the // client's request for the GenerateCredentialReport operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4770,7 +4958,7 @@ const opGenerateCredentialReport = "GenerateCredentialReport" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReport +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReport func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInput) (req *request.Request, output *GenerateCredentialReportOutput) { op := &request.Operation{ Name: opGenerateCredentialReport, @@ -4809,7 +4997,7 @@ func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInp // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReport +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReport func (c *IAM) GenerateCredentialReport(input *GenerateCredentialReportInput) (*GenerateCredentialReportOutput, error) { req, out := c.GenerateCredentialReportRequest(input) return out, req.Send() @@ -4831,12 +5019,145 @@ func (c *IAM) GenerateCredentialReportWithContext(ctx aws.Context, input *Genera return out, req.Send() } +const opGenerateServiceLastAccessedDetails = "GenerateServiceLastAccessedDetails" + +// GenerateServiceLastAccessedDetailsRequest generates a "aws/request.Request" representing the +// client's request for the GenerateServiceLastAccessedDetails operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GenerateServiceLastAccessedDetails for more information on using the GenerateServiceLastAccessedDetails +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GenerateServiceLastAccessedDetailsRequest method. +// req, resp := client.GenerateServiceLastAccessedDetailsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateServiceLastAccessedDetails +func (c *IAM) GenerateServiceLastAccessedDetailsRequest(input *GenerateServiceLastAccessedDetailsInput) (req *request.Request, output *GenerateServiceLastAccessedDetailsOutput) { + op := &request.Operation{ + Name: opGenerateServiceLastAccessedDetails, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GenerateServiceLastAccessedDetailsInput{} + } + + output = &GenerateServiceLastAccessedDetailsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GenerateServiceLastAccessedDetails API operation for AWS Identity and Access Management. +// +// Generates a request for a report that includes details about when an IAM +// resource (user, group, role, or policy) was last used in an attempt to access +// AWS services. Recent activity usually appears within four hours. IAM reports +// activity for the last 365 days, or less if your region began supporting this +// feature within the last year. For more information, see Regions Where Data +// Is Tracked (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#access-advisor_tracking-period). +// +// The service last accessed data includes all attempts to access an AWS API, +// not just the successful ones. This includes all attempts that were made using +// the AWS Management Console, the AWS API through any of the SDKs, or any of +// the command line tools. An unexpected entry in the service last accessed +// data does not mean that your account has been compromised, because the request +// might have been denied. Refer to your CloudTrail logs as the authoritative +// source for information about all API calls and whether they were successful +// or denied access. For more information, see Logging IAM Events with CloudTrail +// (http://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html) +// in the IAM User Guide. +// +// The GenerateServiceLastAccessedDetails operation returns a JobId. Use this +// parameter in the following operations to retrieve the following details from +// your report: +// +// * GetServiceLastAccessedDetails – Use this operation for users, groups, +// roles, or policies to list every AWS service that the resource could access +// using permissions policies. For each service, the response includes information +// about the most recent access attempt. +// +// * GetServiceLastAccessedDetailsWithEntities – Use this operation for groups +// and policies to list information about the associated entities (users +// or roles) that attempted to access a specific AWS service. +// +// To check the status of the GenerateServiceLastAccessedDetails request, use +// the JobId parameter in the same operations and test the JobStatus response +// parameter. +// +// For additional information about the permissions policies that allow an identity +// (user, group, or role) to access specific services, use the ListPoliciesGrantingServiceAccess +// operation. +// +// Service last accessed data does not use other policy types when determining +// whether a resource could access a service. These other policy types include +// resource-based policies, access control lists, AWS Organizations policies, +// IAM permissions boundaries, and AWS STS assume role policies. It only applies +// permissions policy logic. For more about the evaluation of policy types, +// see Evaluating Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics) +// in the IAM User Guide. +// +// For more information about service last accessed data, see Reducing Policy +// Scope by Viewing User Activity (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation GenerateServiceLastAccessedDetails for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateServiceLastAccessedDetails +func (c *IAM) GenerateServiceLastAccessedDetails(input *GenerateServiceLastAccessedDetailsInput) (*GenerateServiceLastAccessedDetailsOutput, error) { + req, out := c.GenerateServiceLastAccessedDetailsRequest(input) + return out, req.Send() +} + +// GenerateServiceLastAccessedDetailsWithContext is the same as GenerateServiceLastAccessedDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateServiceLastAccessedDetails for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) GenerateServiceLastAccessedDetailsWithContext(ctx aws.Context, input *GenerateServiceLastAccessedDetailsInput, opts ...request.Option) (*GenerateServiceLastAccessedDetailsOutput, error) { + req, out := c.GenerateServiceLastAccessedDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetAccessKeyLastUsed = "GetAccessKeyLastUsed" // GetAccessKeyLastUsedRequest generates a "aws/request.Request" representing the // client's request for the GetAccessKeyLastUsed operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4856,7 +5177,7 @@ const opGetAccessKeyLastUsed = "GetAccessKeyLastUsed" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsed +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsed func (c *IAM) GetAccessKeyLastUsedRequest(input *GetAccessKeyLastUsedInput) (req *request.Request, output *GetAccessKeyLastUsedOutput) { op := &request.Operation{ Name: opGetAccessKeyLastUsed, @@ -4889,10 +5210,10 @@ func (c *IAM) GetAccessKeyLastUsedRequest(input *GetAccessKeyLastUsedInput) (req // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsed +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsed func (c *IAM) GetAccessKeyLastUsed(input *GetAccessKeyLastUsedInput) (*GetAccessKeyLastUsedOutput, error) { req, out := c.GetAccessKeyLastUsedRequest(input) return out, req.Send() @@ -4918,8 +5239,8 @@ const opGetAccountAuthorizationDetails = "GetAccountAuthorizationDetails" // GetAccountAuthorizationDetailsRequest generates a "aws/request.Request" representing the // client's request for the GetAccountAuthorizationDetails operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -4939,7 +5260,7 @@ const opGetAccountAuthorizationDetails = "GetAccountAuthorizationDetails" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetails +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetails func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizationDetailsInput) (req *request.Request, output *GetAccountAuthorizationDetailsOutput) { op := &request.Operation{ Name: opGetAccountAuthorizationDetails, @@ -4969,6 +5290,12 @@ func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizati // API to obtain a snapshot of the configuration of IAM permissions (users, // groups, roles, and policies) in your account. // +// Policies returned by this API are URL-encoded compliant with RFC 3986 (https://tools.ietf.org/html/rfc3986). +// You can use a URL decoding method to convert the policy back to plain JSON +// text. For example, if you use Java, you can use the decode method of the +// java.net.URLDecoder utility class in the Java SDK. Other languages and SDKs +// provide similar functionality. +// // You can optionally filter the results using the Filter parameter. You can // paginate the results using the MaxItems and Marker parameters. // @@ -4984,7 +5311,7 @@ func (c *IAM) GetAccountAuthorizationDetailsRequest(input *GetAccountAuthorizati // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetails +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetails func (c *IAM) GetAccountAuthorizationDetails(input *GetAccountAuthorizationDetailsInput) (*GetAccountAuthorizationDetailsOutput, error) { req, out := c.GetAccountAuthorizationDetailsRequest(input) return out, req.Send() @@ -5060,8 +5387,8 @@ const opGetAccountPasswordPolicy = "GetAccountPasswordPolicy" // GetAccountPasswordPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetAccountPasswordPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5081,7 +5408,7 @@ const opGetAccountPasswordPolicy = "GetAccountPasswordPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicy func (c *IAM) GetAccountPasswordPolicyRequest(input *GetAccountPasswordPolicyInput) (req *request.Request, output *GetAccountPasswordPolicyOutput) { op := &request.Operation{ Name: opGetAccountPasswordPolicy, @@ -5112,14 +5439,14 @@ func (c *IAM) GetAccountPasswordPolicyRequest(input *GetAccountPasswordPolicyInp // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicy func (c *IAM) GetAccountPasswordPolicy(input *GetAccountPasswordPolicyInput) (*GetAccountPasswordPolicyOutput, error) { req, out := c.GetAccountPasswordPolicyRequest(input) return out, req.Send() @@ -5145,8 +5472,8 @@ const opGetAccountSummary = "GetAccountSummary" // GetAccountSummaryRequest generates a "aws/request.Request" representing the // client's request for the GetAccountSummary operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5166,7 +5493,7 @@ const opGetAccountSummary = "GetAccountSummary" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummary +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummary func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *request.Request, output *GetAccountSummaryOutput) { op := &request.Operation{ Name: opGetAccountSummary, @@ -5203,7 +5530,7 @@ func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummary +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummary func (c *IAM) GetAccountSummary(input *GetAccountSummaryInput) (*GetAccountSummaryOutput, error) { req, out := c.GetAccountSummaryRequest(input) return out, req.Send() @@ -5229,8 +5556,8 @@ const opGetContextKeysForCustomPolicy = "GetContextKeysForCustomPolicy" // GetContextKeysForCustomPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetContextKeysForCustomPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5250,7 +5577,7 @@ const opGetContextKeysForCustomPolicy = "GetContextKeysForCustomPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicy func (c *IAM) GetContextKeysForCustomPolicyRequest(input *GetContextKeysForCustomPolicyInput) (req *request.Request, output *GetContextKeysForPolicyResponse) { op := &request.Operation{ Name: opGetContextKeysForCustomPolicy, @@ -5274,10 +5601,10 @@ func (c *IAM) GetContextKeysForCustomPolicyRequest(input *GetContextKeysForCusto // keys from policies associated with an IAM user, group, or role, use GetContextKeysForPrincipalPolicy. // // Context keys are variables maintained by AWS and its services that provide -// details about the context of an API query request, and can be evaluated by -// testing against a value specified in an IAM policy. Use GetContextKeysForCustomPolicy +// details about the context of an API query request. Context keys can be evaluated +// by testing against a value specified in an IAM policy. Use GetContextKeysForCustomPolicy // to understand what key names and values you must supply when you call SimulateCustomPolicy. -// Note that all parameters are shown in unencoded form here for clarity, but +// Note that all parameters are shown in unencoded form here for clarity but // must be URL encoded to be included as a part of a real HTML request. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5292,7 +5619,7 @@ func (c *IAM) GetContextKeysForCustomPolicyRequest(input *GetContextKeysForCusto // The request was rejected because an invalid or out-of-range value was supplied // for an input parameter. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicy func (c *IAM) GetContextKeysForCustomPolicy(input *GetContextKeysForCustomPolicyInput) (*GetContextKeysForPolicyResponse, error) { req, out := c.GetContextKeysForCustomPolicyRequest(input) return out, req.Send() @@ -5318,8 +5645,8 @@ const opGetContextKeysForPrincipalPolicy = "GetContextKeysForPrincipalPolicy" // GetContextKeysForPrincipalPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetContextKeysForPrincipalPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5339,7 +5666,7 @@ const opGetContextKeysForPrincipalPolicy = "GetContextKeysForPrincipalPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicy func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPrincipalPolicyInput) (req *request.Request, output *GetContextKeysForPolicyResponse) { op := &request.Operation{ Name: opGetContextKeysForPrincipalPolicy, @@ -5358,10 +5685,10 @@ func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPr // GetContextKeysForPrincipalPolicy API operation for AWS Identity and Access Management. // -// Gets a list of all of the context keys referenced in all of the IAM policies -// attached to the specified IAM entity. The entity can be an IAM user, group, -// or role. If you specify a user, then the request also includes all of the -// policies attached to groups that the user is a member of. +// Gets a list of all of the context keys referenced in all the IAM policies +// that are attached to the specified IAM entity. The entity can be an IAM user, +// group, or role. If you specify a user, then the request also includes all +// of the policies attached to groups that the user is a member of. // // You can optionally include a list of one or more additional policies, specified // as strings. If you want to include only a list of policies by string, use @@ -5372,8 +5699,8 @@ func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPr // allowing them to use GetContextKeysForCustomPolicy instead. // // Context keys are variables maintained by AWS and its services that provide -// details about the context of an API query request, and can be evaluated by -// testing against a value in an IAM policy. Use GetContextKeysForPrincipalPolicy +// details about the context of an API query request. Context keys can be evaluated +// by testing against a value in an IAM policy. Use GetContextKeysForPrincipalPolicy // to understand what key names and values you must supply when you call SimulatePrincipalPolicy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5385,14 +5712,14 @@ func (c *IAM) GetContextKeysForPrincipalPolicyRequest(input *GetContextKeysForPr // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied // for an input parameter. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicy func (c *IAM) GetContextKeysForPrincipalPolicy(input *GetContextKeysForPrincipalPolicyInput) (*GetContextKeysForPolicyResponse, error) { req, out := c.GetContextKeysForPrincipalPolicyRequest(input) return out, req.Send() @@ -5418,8 +5745,8 @@ const opGetCredentialReport = "GetCredentialReport" // GetCredentialReportRequest generates a "aws/request.Request" representing the // client's request for the GetCredentialReport operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5439,7 +5766,7 @@ const opGetCredentialReport = "GetCredentialReport" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReport +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReport func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req *request.Request, output *GetCredentialReportOutput) { op := &request.Operation{ Name: opGetCredentialReport, @@ -5488,7 +5815,7 @@ func (c *IAM) GetCredentialReportRequest(input *GetCredentialReportInput) (req * // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReport +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReport func (c *IAM) GetCredentialReport(input *GetCredentialReportInput) (*GetCredentialReportOutput, error) { req, out := c.GetCredentialReportRequest(input) return out, req.Send() @@ -5514,8 +5841,8 @@ const opGetGroup = "GetGroup" // GetGroupRequest generates a "aws/request.Request" representing the // client's request for the GetGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5535,7 +5862,7 @@ const opGetGroup = "GetGroup" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroup func (c *IAM) GetGroupRequest(input *GetGroupInput) (req *request.Request, output *GetGroupOutput) { op := &request.Operation{ Name: opGetGroup, @@ -5572,14 +5899,14 @@ func (c *IAM) GetGroupRequest(input *GetGroupInput) (req *request.Request, outpu // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroup func (c *IAM) GetGroup(input *GetGroupInput) (*GetGroupOutput, error) { req, out := c.GetGroupRequest(input) return out, req.Send() @@ -5655,8 +5982,8 @@ const opGetGroupPolicy = "GetGroupPolicy" // GetGroupPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetGroupPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5676,7 +6003,7 @@ const opGetGroupPolicy = "GetGroupPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicy func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *request.Request, output *GetGroupPolicyOutput) { op := &request.Operation{ Name: opGetGroupPolicy, @@ -5722,14 +6049,14 @@ func (c *IAM) GetGroupPolicyRequest(input *GetGroupPolicyInput) (req *request.Re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicy func (c *IAM) GetGroupPolicy(input *GetGroupPolicyInput) (*GetGroupPolicyOutput, error) { req, out := c.GetGroupPolicyRequest(input) return out, req.Send() @@ -5755,8 +6082,8 @@ const opGetInstanceProfile = "GetInstanceProfile" // GetInstanceProfileRequest generates a "aws/request.Request" representing the // client's request for the GetInstanceProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5776,7 +6103,7 @@ const opGetInstanceProfile = "GetInstanceProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile func (c *IAM) GetInstanceProfileRequest(input *GetInstanceProfileInput) (req *request.Request, output *GetInstanceProfileOutput) { op := &request.Operation{ Name: opGetInstanceProfile, @@ -5809,14 +6136,14 @@ func (c *IAM) GetInstanceProfileRequest(input *GetInstanceProfileInput) (req *re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile func (c *IAM) GetInstanceProfile(input *GetInstanceProfileInput) (*GetInstanceProfileOutput, error) { req, out := c.GetInstanceProfileRequest(input) return out, req.Send() @@ -5842,8 +6169,8 @@ const opGetLoginProfile = "GetLoginProfile" // GetLoginProfileRequest generates a "aws/request.Request" representing the // client's request for the GetLoginProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5863,7 +6190,7 @@ const opGetLoginProfile = "GetLoginProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfile func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *request.Request, output *GetLoginProfileOutput) { op := &request.Operation{ Name: opGetLoginProfile, @@ -5883,8 +6210,8 @@ func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *request. // GetLoginProfile API operation for AWS Identity and Access Management. // // Retrieves the user name and password-creation date for the specified IAM -// user. If the user has not been assigned a password, the action returns a -// 404 (NoSuchEntity) error. +// user. If the user has not been assigned a password, the operation returns +// a 404 (NoSuchEntity) error. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5895,14 +6222,14 @@ func (c *IAM) GetLoginProfileRequest(input *GetLoginProfileInput) (req *request. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfile func (c *IAM) GetLoginProfile(input *GetLoginProfileInput) (*GetLoginProfileOutput, error) { req, out := c.GetLoginProfileRequest(input) return out, req.Send() @@ -5928,8 +6255,8 @@ const opGetOpenIDConnectProvider = "GetOpenIDConnectProvider" // GetOpenIDConnectProviderRequest generates a "aws/request.Request" representing the // client's request for the GetOpenIDConnectProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -5949,7 +6276,7 @@ const opGetOpenIDConnectProvider = "GetOpenIDConnectProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProvider func (c *IAM) GetOpenIDConnectProviderRequest(input *GetOpenIDConnectProviderInput) (req *request.Request, output *GetOpenIDConnectProviderOutput) { op := &request.Operation{ Name: opGetOpenIDConnectProvider, @@ -5984,14 +6311,14 @@ func (c *IAM) GetOpenIDConnectProviderRequest(input *GetOpenIDConnectProviderInp // for an input parameter. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProvider func (c *IAM) GetOpenIDConnectProvider(input *GetOpenIDConnectProviderInput) (*GetOpenIDConnectProviderOutput, error) { req, out := c.GetOpenIDConnectProviderRequest(input) return out, req.Send() @@ -6017,8 +6344,8 @@ const opGetPolicy = "GetPolicy" // GetPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6038,7 +6365,7 @@ const opGetPolicy = "GetPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicy func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, output *GetPolicyOutput) { op := &request.Operation{ Name: opGetPolicy, @@ -6081,8 +6408,8 @@ func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, out // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -6092,7 +6419,7 @@ func (c *IAM) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, out // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicy func (c *IAM) GetPolicy(input *GetPolicyInput) (*GetPolicyOutput, error) { req, out := c.GetPolicyRequest(input) return out, req.Send() @@ -6118,8 +6445,8 @@ const opGetPolicyVersion = "GetPolicyVersion" // GetPolicyVersionRequest generates a "aws/request.Request" representing the // client's request for the GetPolicyVersion operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6139,7 +6466,7 @@ const opGetPolicyVersion = "GetPolicyVersion" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersion func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *request.Request, output *GetPolicyVersionOutput) { op := &request.Operation{ Name: opGetPolicyVersion, @@ -6190,8 +6517,8 @@ func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -6201,7 +6528,7 @@ func (c *IAM) GetPolicyVersionRequest(input *GetPolicyVersionInput) (req *reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersion func (c *IAM) GetPolicyVersion(input *GetPolicyVersionInput) (*GetPolicyVersionOutput, error) { req, out := c.GetPolicyVersionRequest(input) return out, req.Send() @@ -6227,8 +6554,8 @@ const opGetRole = "GetRole" // GetRoleRequest generates a "aws/request.Request" representing the // client's request for the GetRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6248,7 +6575,7 @@ const opGetRole = "GetRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRole func (c *IAM) GetRoleRequest(input *GetRoleInput) (req *request.Request, output *GetRoleOutput) { op := &request.Operation{ Name: opGetRole, @@ -6286,14 +6613,14 @@ func (c *IAM) GetRoleRequest(input *GetRoleInput) (req *request.Request, output // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRole func (c *IAM) GetRole(input *GetRoleInput) (*GetRoleOutput, error) { req, out := c.GetRoleRequest(input) return out, req.Send() @@ -6319,8 +6646,8 @@ const opGetRolePolicy = "GetRolePolicy" // GetRolePolicyRequest generates a "aws/request.Request" representing the // client's request for the GetRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6340,7 +6667,7 @@ const opGetRolePolicy = "GetRolePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicy func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *request.Request, output *GetRolePolicyOutput) { op := &request.Operation{ Name: opGetRolePolicy, @@ -6389,14 +6716,14 @@ func (c *IAM) GetRolePolicyRequest(input *GetRolePolicyInput) (req *request.Requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicy func (c *IAM) GetRolePolicy(input *GetRolePolicyInput) (*GetRolePolicyOutput, error) { req, out := c.GetRolePolicyRequest(input) return out, req.Send() @@ -6422,8 +6749,8 @@ const opGetSAMLProvider = "GetSAMLProvider" // GetSAMLProviderRequest generates a "aws/request.Request" representing the // client's request for the GetSAMLProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6443,7 +6770,7 @@ const opGetSAMLProvider = "GetSAMLProvider" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProvider func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *request.Request, output *GetSAMLProviderOutput) { op := &request.Operation{ Name: opGetSAMLProvider, @@ -6476,8 +6803,8 @@ func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *request. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -6487,7 +6814,7 @@ func (c *IAM) GetSAMLProviderRequest(input *GetSAMLProviderInput) (req *request. // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProvider func (c *IAM) GetSAMLProvider(input *GetSAMLProviderInput) (*GetSAMLProviderOutput, error) { req, out := c.GetSAMLProviderRequest(input) return out, req.Send() @@ -6513,8 +6840,8 @@ const opGetSSHPublicKey = "GetSSHPublicKey" // GetSSHPublicKeyRequest generates a "aws/request.Request" representing the // client's request for the GetSSHPublicKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6534,7 +6861,7 @@ const opGetSSHPublicKey = "GetSSHPublicKey" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKey func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *request.Request, output *GetSSHPublicKeyOutput) { op := &request.Operation{ Name: opGetSSHPublicKey, @@ -6555,7 +6882,7 @@ func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *request. // // Retrieves the specified SSH public key, including metadata about the key. // -// The SSH public key retrieved by this action is used only for authenticating +// The SSH public key retrieved by this operation is used only for authenticating // the associated IAM user to an AWS CodeCommit repository. For more information // about using SSH keys to authenticate to an AWS CodeCommit repository, see // Set up AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) @@ -6570,14 +6897,14 @@ func (c *IAM) GetSSHPublicKeyRequest(input *GetSSHPublicKeyInput) (req *request. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeUnrecognizedPublicKeyEncodingException "UnrecognizedPublicKeyEncoding" // The request was rejected because the public key encoding format is unsupported // or unrecognized. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKey func (c *IAM) GetSSHPublicKey(input *GetSSHPublicKeyInput) (*GetSSHPublicKeyOutput, error) { req, out := c.GetSSHPublicKeyRequest(input) return out, req.Send() @@ -6603,8 +6930,8 @@ const opGetServerCertificate = "GetServerCertificate" // GetServerCertificateRequest generates a "aws/request.Request" representing the // client's request for the GetServerCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6624,7 +6951,7 @@ const opGetServerCertificate = "GetServerCertificate" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificate func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req *request.Request, output *GetServerCertificateOutput) { op := &request.Operation{ Name: opGetServerCertificate, @@ -6645,10 +6972,10 @@ func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req // // Retrieves information about the specified server certificate stored in IAM. // -// For more information about working with server certificates, including a -// list of AWS services that can use the server certificates that you manage -// with IAM, go to Working with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) -// in the IAM User Guide. +// For more information about working with server certificates, see Working +// with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) +// in the IAM User Guide. This topic includes a list of AWS services that can +// use the server certificates that you manage with IAM. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -6659,14 +6986,14 @@ func (c *IAM) GetServerCertificateRequest(input *GetServerCertificateInput) (req // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificate +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificate func (c *IAM) GetServerCertificate(input *GetServerCertificateInput) (*GetServerCertificateOutput, error) { req, out := c.GetServerCertificateRequest(input) return out, req.Send() @@ -6688,104 +7015,329 @@ func (c *IAM) GetServerCertificateWithContext(ctx aws.Context, input *GetServerC return out, req.Send() } -const opGetServiceLinkedRoleDeletionStatus = "GetServiceLinkedRoleDeletionStatus" +const opGetServiceLastAccessedDetails = "GetServiceLastAccessedDetails" -// GetServiceLinkedRoleDeletionStatusRequest generates a "aws/request.Request" representing the -// client's request for the GetServiceLinkedRoleDeletionStatus operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// GetServiceLastAccessedDetailsRequest generates a "aws/request.Request" representing the +// client's request for the GetServiceLastAccessedDetails operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetServiceLinkedRoleDeletionStatus for more information on using the GetServiceLinkedRoleDeletionStatus +// See GetServiceLastAccessedDetails for more information on using the GetServiceLastAccessedDetails // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetServiceLinkedRoleDeletionStatusRequest method. -// req, resp := client.GetServiceLinkedRoleDeletionStatusRequest(params) +// // Example sending a request using the GetServiceLastAccessedDetailsRequest method. +// req, resp := client.GetServiceLastAccessedDetailsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatus -func (c *IAM) GetServiceLinkedRoleDeletionStatusRequest(input *GetServiceLinkedRoleDeletionStatusInput) (req *request.Request, output *GetServiceLinkedRoleDeletionStatusOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLastAccessedDetails +func (c *IAM) GetServiceLastAccessedDetailsRequest(input *GetServiceLastAccessedDetailsInput) (req *request.Request, output *GetServiceLastAccessedDetailsOutput) { op := &request.Operation{ - Name: opGetServiceLinkedRoleDeletionStatus, + Name: opGetServiceLastAccessedDetails, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetServiceLinkedRoleDeletionStatusInput{} + input = &GetServiceLastAccessedDetailsInput{} } - output = &GetServiceLinkedRoleDeletionStatusOutput{} + output = &GetServiceLastAccessedDetailsOutput{} req = c.newRequest(op, input, output) return } -// GetServiceLinkedRoleDeletionStatus API operation for AWS Identity and Access Management. +// GetServiceLastAccessedDetails API operation for AWS Identity and Access Management. // -// Retrieves the status of your service-linked role deletion. After you use -// the DeleteServiceLinkedRole API operation to submit a service-linked role -// for deletion, you can use the DeletionTaskId parameter in GetServiceLinkedRoleDeletionStatus -// to check the status of the deletion. If the deletion fails, this operation -// returns the reason that it failed. +// After you generate a user, group, role, or policy report using the GenerateServiceLastAccessedDetails +// operation, you can use the JobId parameter in GetServiceLastAccessedDetails. +// This operation retrieves the status of your report job and a list of AWS +// services that the resource (user, group, role, or managed policy) can access. +// +// Service last accessed data does not use other policy types when determining +// whether a resource could access a service. These other policy types include +// resource-based policies, access control lists, AWS Organizations policies, +// IAM permissions boundaries, and AWS STS assume role policies. It only applies +// permissions policy logic. For more about the evaluation of policy types, +// see Evaluating Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics) +// in the IAM User Guide. +// +// For each service that the resource could access using permissions policies, +// the operation returns details about the most recent access attempt. If there +// was no attempt, the service is listed without details about the most recent +// attempt to access the service. If the operation fails, the GetServiceLastAccessedDetails +// operation returns the reason that it failed. +// +// The GetServiceLastAccessedDetails operation returns a list of services that +// includes the number of entities that have attempted to access the service +// and the date and time of the last attempt. It also returns the ARN of the +// following entity, depending on the resource ARN that you used to generate +// the report: +// +// * User – Returns the user ARN that you used to generate the report +// +// * Group – Returns the ARN of the group member (user) that last attempted +// to access the service +// +// * Role – Returns the role ARN that you used to generate the report +// +// * Policy – Returns the ARN of the user or role that last used the policy +// to attempt to access the service +// +// By default, the list is sorted by service namespace. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation GetServiceLinkedRoleDeletionStatus for usage and error information. +// API operation GetServiceLastAccessedDetails for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied // for an input parameter. // -// * ErrCodeServiceFailureException "ServiceFailure" -// The request processing has failed because of an unknown error, exception -// or failure. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatus -func (c *IAM) GetServiceLinkedRoleDeletionStatus(input *GetServiceLinkedRoleDeletionStatusInput) (*GetServiceLinkedRoleDeletionStatusOutput, error) { - req, out := c.GetServiceLinkedRoleDeletionStatusRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLastAccessedDetails +func (c *IAM) GetServiceLastAccessedDetails(input *GetServiceLastAccessedDetailsInput) (*GetServiceLastAccessedDetailsOutput, error) { + req, out := c.GetServiceLastAccessedDetailsRequest(input) return out, req.Send() } -// GetServiceLinkedRoleDeletionStatusWithContext is the same as GetServiceLinkedRoleDeletionStatus with the addition of +// GetServiceLastAccessedDetailsWithContext is the same as GetServiceLastAccessedDetails with the addition of // the ability to pass a context and additional request options. // -// See GetServiceLinkedRoleDeletionStatus for details on how to use this API operation. +// See GetServiceLastAccessedDetails for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) GetServiceLinkedRoleDeletionStatusWithContext(ctx aws.Context, input *GetServiceLinkedRoleDeletionStatusInput, opts ...request.Option) (*GetServiceLinkedRoleDeletionStatusOutput, error) { - req, out := c.GetServiceLinkedRoleDeletionStatusRequest(input) +func (c *IAM) GetServiceLastAccessedDetailsWithContext(ctx aws.Context, input *GetServiceLastAccessedDetailsInput, opts ...request.Option) (*GetServiceLastAccessedDetailsOutput, error) { + req, out := c.GetServiceLastAccessedDetailsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetUser = "GetUser" +const opGetServiceLastAccessedDetailsWithEntities = "GetServiceLastAccessedDetailsWithEntities" -// GetUserRequest generates a "aws/request.Request" representing the +// GetServiceLastAccessedDetailsWithEntitiesRequest generates a "aws/request.Request" representing the +// client's request for the GetServiceLastAccessedDetailsWithEntities operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetServiceLastAccessedDetailsWithEntities for more information on using the GetServiceLastAccessedDetailsWithEntities +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetServiceLastAccessedDetailsWithEntitiesRequest method. +// req, resp := client.GetServiceLastAccessedDetailsWithEntitiesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLastAccessedDetailsWithEntities +func (c *IAM) GetServiceLastAccessedDetailsWithEntitiesRequest(input *GetServiceLastAccessedDetailsWithEntitiesInput) (req *request.Request, output *GetServiceLastAccessedDetailsWithEntitiesOutput) { + op := &request.Operation{ + Name: opGetServiceLastAccessedDetailsWithEntities, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetServiceLastAccessedDetailsWithEntitiesInput{} + } + + output = &GetServiceLastAccessedDetailsWithEntitiesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetServiceLastAccessedDetailsWithEntities API operation for AWS Identity and Access Management. +// +// After you generate a group or policy report using the GenerateServiceLastAccessedDetails +// operation, you can use the JobId parameter in GetServiceLastAccessedDetailsWithEntities. +// This operation retrieves the status of your report job and a list of entities +// that could have used group or policy permissions to access the specified +// service. +// +// * Group – For a group report, this operation returns a list of users in +// the group that could have used the group’s policies in an attempt to access +// the service. +// +// * Policy – For a policy report, this operation returns a list of entities +// (users or roles) that could have used the policy in an attempt to access +// the service. +// +// You can also use this operation for user or role reports to retrieve details +// about those entities. +// +// If the operation fails, the GetServiceLastAccessedDetailsWithEntities operation +// returns the reason that it failed. +// +// By default, the list of associated entities is sorted by date, with the most +// recent access listed first. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation GetServiceLastAccessedDetailsWithEntities for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLastAccessedDetailsWithEntities +func (c *IAM) GetServiceLastAccessedDetailsWithEntities(input *GetServiceLastAccessedDetailsWithEntitiesInput) (*GetServiceLastAccessedDetailsWithEntitiesOutput, error) { + req, out := c.GetServiceLastAccessedDetailsWithEntitiesRequest(input) + return out, req.Send() +} + +// GetServiceLastAccessedDetailsWithEntitiesWithContext is the same as GetServiceLastAccessedDetailsWithEntities with the addition of +// the ability to pass a context and additional request options. +// +// See GetServiceLastAccessedDetailsWithEntities for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) GetServiceLastAccessedDetailsWithEntitiesWithContext(ctx aws.Context, input *GetServiceLastAccessedDetailsWithEntitiesInput, opts ...request.Option) (*GetServiceLastAccessedDetailsWithEntitiesOutput, error) { + req, out := c.GetServiceLastAccessedDetailsWithEntitiesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetServiceLinkedRoleDeletionStatus = "GetServiceLinkedRoleDeletionStatus" + +// GetServiceLinkedRoleDeletionStatusRequest generates a "aws/request.Request" representing the +// client's request for the GetServiceLinkedRoleDeletionStatus operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetServiceLinkedRoleDeletionStatus for more information on using the GetServiceLinkedRoleDeletionStatus +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetServiceLinkedRoleDeletionStatusRequest method. +// req, resp := client.GetServiceLinkedRoleDeletionStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatus +func (c *IAM) GetServiceLinkedRoleDeletionStatusRequest(input *GetServiceLinkedRoleDeletionStatusInput) (req *request.Request, output *GetServiceLinkedRoleDeletionStatusOutput) { + op := &request.Operation{ + Name: opGetServiceLinkedRoleDeletionStatus, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetServiceLinkedRoleDeletionStatusInput{} + } + + output = &GetServiceLinkedRoleDeletionStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetServiceLinkedRoleDeletionStatus API operation for AWS Identity and Access Management. +// +// Retrieves the status of your service-linked role deletion. After you use +// the DeleteServiceLinkedRole API operation to submit a service-linked role +// for deletion, you can use the DeletionTaskId parameter in GetServiceLinkedRoleDeletionStatus +// to check the status of the deletion. If the deletion fails, this operation +// returns the reason that it failed, if that information is returned by the +// service. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation GetServiceLinkedRoleDeletionStatus for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatus +func (c *IAM) GetServiceLinkedRoleDeletionStatus(input *GetServiceLinkedRoleDeletionStatusInput) (*GetServiceLinkedRoleDeletionStatusOutput, error) { + req, out := c.GetServiceLinkedRoleDeletionStatusRequest(input) + return out, req.Send() +} + +// GetServiceLinkedRoleDeletionStatusWithContext is the same as GetServiceLinkedRoleDeletionStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetServiceLinkedRoleDeletionStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) GetServiceLinkedRoleDeletionStatusWithContext(ctx aws.Context, input *GetServiceLinkedRoleDeletionStatusInput, opts ...request.Option) (*GetServiceLinkedRoleDeletionStatusOutput, error) { + req, out := c.GetServiceLinkedRoleDeletionStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetUser = "GetUser" + +// GetUserRequest generates a "aws/request.Request" representing the // client's request for the GetUser operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6805,7 +7357,7 @@ const opGetUser = "GetUser" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUser func (c *IAM) GetUserRequest(input *GetUserInput) (req *request.Request, output *GetUserOutput) { op := &request.Operation{ Name: opGetUser, @@ -6839,14 +7391,14 @@ func (c *IAM) GetUserRequest(input *GetUserInput) (req *request.Request, output // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUser func (c *IAM) GetUser(input *GetUserInput) (*GetUserOutput, error) { req, out := c.GetUserRequest(input) return out, req.Send() @@ -6872,8 +7424,8 @@ const opGetUserPolicy = "GetUserPolicy" // GetUserPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetUserPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6893,7 +7445,7 @@ const opGetUserPolicy = "GetUserPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicy func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *request.Request, output *GetUserPolicyOutput) { op := &request.Operation{ Name: opGetUserPolicy, @@ -6939,14 +7491,14 @@ func (c *IAM) GetUserPolicyRequest(input *GetUserPolicyInput) (req *request.Requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicy func (c *IAM) GetUserPolicy(input *GetUserPolicyInput) (*GetUserPolicyOutput, error) { req, out := c.GetUserPolicyRequest(input) return out, req.Send() @@ -6972,8 +7524,8 @@ const opListAccessKeys = "ListAccessKeys" // ListAccessKeysRequest generates a "aws/request.Request" representing the // client's request for the ListAccessKeys operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -6993,7 +7545,7 @@ const opListAccessKeys = "ListAccessKeys" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeys func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *request.Request, output *ListAccessKeysOutput) { op := &request.Operation{ Name: opListAccessKeys, @@ -7019,15 +7571,16 @@ func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *request.Re // ListAccessKeys API operation for AWS Identity and Access Management. // // Returns information about the access key IDs associated with the specified -// IAM user. If there are none, the action returns an empty list. +// IAM user. If there is none, the operation returns an empty list. // // Although each user is limited to a small number of keys, you can still paginate // the results using the MaxItems and Marker parameters. // -// If the UserName field is not specified, the UserName is determined implicitly -// based on the AWS access key ID used to sign the request. Because this action -// works for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// If the UserName field is not specified, the user name is determined implicitly +// based on the AWS access key ID used to sign the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated users. // // To ensure the security of your AWS account, the secret access key is accessible // only during key and user creation. @@ -7041,14 +7594,14 @@ func (c *IAM) ListAccessKeysRequest(input *ListAccessKeysInput) (req *request.Re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeys func (c *IAM) ListAccessKeys(input *ListAccessKeysInput) (*ListAccessKeysOutput, error) { req, out := c.ListAccessKeysRequest(input) return out, req.Send() @@ -7124,8 +7677,8 @@ const opListAccountAliases = "ListAccountAliases" // ListAccountAliasesRequest generates a "aws/request.Request" representing the // client's request for the ListAccountAliases operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7145,7 +7698,7 @@ const opListAccountAliases = "ListAccountAliases" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliases +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliases func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *request.Request, output *ListAccountAliasesOutput) { op := &request.Operation{ Name: opListAccountAliases, @@ -7187,7 +7740,7 @@ func (c *IAM) ListAccountAliasesRequest(input *ListAccountAliasesInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliases +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliases func (c *IAM) ListAccountAliases(input *ListAccountAliasesInput) (*ListAccountAliasesOutput, error) { req, out := c.ListAccountAliasesRequest(input) return out, req.Send() @@ -7263,8 +7816,8 @@ const opListAttachedGroupPolicies = "ListAttachedGroupPolicies" // ListAttachedGroupPoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListAttachedGroupPolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7284,7 +7837,7 @@ const opListAttachedGroupPolicies = "ListAttachedGroupPolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPolicies func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesInput) (req *request.Request, output *ListAttachedGroupPoliciesOutput) { op := &request.Operation{ Name: opListAttachedGroupPolicies, @@ -7319,7 +7872,7 @@ func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesI // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those // matching the specified path prefix. If there are no policies attached to -// the specified group (or none that match the specified path prefix), the action +// the specified group (or none that match the specified path prefix), the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7331,8 +7884,8 @@ func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesI // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -7342,7 +7895,7 @@ func (c *IAM) ListAttachedGroupPoliciesRequest(input *ListAttachedGroupPoliciesI // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPolicies func (c *IAM) ListAttachedGroupPolicies(input *ListAttachedGroupPoliciesInput) (*ListAttachedGroupPoliciesOutput, error) { req, out := c.ListAttachedGroupPoliciesRequest(input) return out, req.Send() @@ -7418,8 +7971,8 @@ const opListAttachedRolePolicies = "ListAttachedRolePolicies" // ListAttachedRolePoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListAttachedRolePolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7439,7 +7992,7 @@ const opListAttachedRolePolicies = "ListAttachedRolePolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePolicies func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInput) (req *request.Request, output *ListAttachedRolePoliciesOutput) { op := &request.Operation{ Name: opListAttachedRolePolicies, @@ -7474,7 +8027,7 @@ func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInp // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those // matching the specified path prefix. If there are no policies attached to -// the specified role (or none that match the specified path prefix), the action +// the specified role (or none that match the specified path prefix), the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7486,8 +8039,8 @@ func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInp // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -7497,7 +8050,7 @@ func (c *IAM) ListAttachedRolePoliciesRequest(input *ListAttachedRolePoliciesInp // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePolicies func (c *IAM) ListAttachedRolePolicies(input *ListAttachedRolePoliciesInput) (*ListAttachedRolePoliciesOutput, error) { req, out := c.ListAttachedRolePoliciesRequest(input) return out, req.Send() @@ -7573,8 +8126,8 @@ const opListAttachedUserPolicies = "ListAttachedUserPolicies" // ListAttachedUserPoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListAttachedUserPolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7594,7 +8147,7 @@ const opListAttachedUserPolicies = "ListAttachedUserPolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPolicies func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInput) (req *request.Request, output *ListAttachedUserPoliciesOutput) { op := &request.Operation{ Name: opListAttachedUserPolicies, @@ -7629,7 +8182,7 @@ func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInp // You can paginate the results using the MaxItems and Marker parameters. You // can use the PathPrefix parameter to limit the list of policies to only those // matching the specified path prefix. If there are no policies attached to -// the specified group (or none that match the specified path prefix), the action +// the specified group (or none that match the specified path prefix), the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7641,8 +8194,8 @@ func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInp // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -7652,7 +8205,7 @@ func (c *IAM) ListAttachedUserPoliciesRequest(input *ListAttachedUserPoliciesInp // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPolicies func (c *IAM) ListAttachedUserPolicies(input *ListAttachedUserPoliciesInput) (*ListAttachedUserPoliciesOutput, error) { req, out := c.ListAttachedUserPoliciesRequest(input) return out, req.Send() @@ -7728,8 +8281,8 @@ const opListEntitiesForPolicy = "ListEntitiesForPolicy" // ListEntitiesForPolicyRequest generates a "aws/request.Request" representing the // client's request for the ListEntitiesForPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7749,7 +8302,7 @@ const opListEntitiesForPolicy = "ListEntitiesForPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicy func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (req *request.Request, output *ListEntitiesForPolicyOutput) { op := &request.Operation{ Name: opListEntitiesForPolicy, @@ -7793,8 +8346,8 @@ func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (r // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -7804,7 +8357,7 @@ func (c *IAM) ListEntitiesForPolicyRequest(input *ListEntitiesForPolicyInput) (r // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicy func (c *IAM) ListEntitiesForPolicy(input *ListEntitiesForPolicyInput) (*ListEntitiesForPolicyOutput, error) { req, out := c.ListEntitiesForPolicyRequest(input) return out, req.Send() @@ -7880,8 +8433,8 @@ const opListGroupPolicies = "ListGroupPolicies" // ListGroupPoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListGroupPolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -7901,7 +8454,7 @@ const opListGroupPolicies = "ListGroupPolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPolicies func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *request.Request, output *ListGroupPoliciesOutput) { op := &request.Operation{ Name: opListGroupPolicies, @@ -7936,7 +8489,7 @@ func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *requ // in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If -// there are no inline policies embedded with the specified group, the action +// there are no inline policies embedded with the specified group, the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7948,14 +8501,14 @@ func (c *IAM) ListGroupPoliciesRequest(input *ListGroupPoliciesInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPolicies func (c *IAM) ListGroupPolicies(input *ListGroupPoliciesInput) (*ListGroupPoliciesOutput, error) { req, out := c.ListGroupPoliciesRequest(input) return out, req.Send() @@ -8031,8 +8584,8 @@ const opListGroups = "ListGroups" // ListGroupsRequest generates a "aws/request.Request" representing the // client's request for the ListGroups operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8052,7 +8605,7 @@ const opListGroups = "ListGroups" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroups +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroups func (c *IAM) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, output *ListGroupsOutput) { op := &request.Operation{ Name: opListGroups, @@ -8093,7 +8646,7 @@ func (c *IAM) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, o // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroups +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroups func (c *IAM) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { req, out := c.ListGroupsRequest(input) return out, req.Send() @@ -8169,8 +8722,8 @@ const opListGroupsForUser = "ListGroupsForUser" // ListGroupsForUserRequest generates a "aws/request.Request" representing the // client's request for the ListGroupsForUser operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8190,7 +8743,7 @@ const opListGroupsForUser = "ListGroupsForUser" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUser func (c *IAM) ListGroupsForUserRequest(input *ListGroupsForUserInput) (req *request.Request, output *ListGroupsForUserOutput) { op := &request.Operation{ Name: opListGroupsForUser, @@ -8228,14 +8781,14 @@ func (c *IAM) ListGroupsForUserRequest(input *ListGroupsForUserInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUser +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUser func (c *IAM) ListGroupsForUser(input *ListGroupsForUserInput) (*ListGroupsForUserOutput, error) { req, out := c.ListGroupsForUserRequest(input) return out, req.Send() @@ -8311,8 +8864,8 @@ const opListInstanceProfiles = "ListInstanceProfiles" // ListInstanceProfilesRequest generates a "aws/request.Request" representing the // client's request for the ListInstanceProfiles operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8332,7 +8885,7 @@ const opListInstanceProfiles = "ListInstanceProfiles" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfiles +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfiles func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req *request.Request, output *ListInstanceProfilesOutput) { op := &request.Operation{ Name: opListInstanceProfiles, @@ -8358,8 +8911,8 @@ func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req // ListInstanceProfiles API operation for AWS Identity and Access Management. // // Lists the instance profiles that have the specified path prefix. If there -// are none, the action returns an empty list. For more information about instance -// profiles, go to About Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html). +// are none, the operation returns an empty list. For more information about +// instance profiles, go to About Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html). // // You can paginate the results using the MaxItems and Marker parameters. // @@ -8375,7 +8928,7 @@ func (c *IAM) ListInstanceProfilesRequest(input *ListInstanceProfilesInput) (req // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfiles +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfiles func (c *IAM) ListInstanceProfiles(input *ListInstanceProfilesInput) (*ListInstanceProfilesOutput, error) { req, out := c.ListInstanceProfilesRequest(input) return out, req.Send() @@ -8451,8 +9004,8 @@ const opListInstanceProfilesForRole = "ListInstanceProfilesForRole" // ListInstanceProfilesForRoleRequest generates a "aws/request.Request" representing the // client's request for the ListInstanceProfilesForRole operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8472,7 +9025,7 @@ const opListInstanceProfilesForRole = "ListInstanceProfilesForRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRole func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForRoleInput) (req *request.Request, output *ListInstanceProfilesForRoleOutput) { op := &request.Operation{ Name: opListInstanceProfilesForRole, @@ -8498,7 +9051,7 @@ func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForR // ListInstanceProfilesForRole API operation for AWS Identity and Access Management. // // Lists the instance profiles that have the specified associated IAM role. -// If there are none, the action returns an empty list. For more information +// If there are none, the operation returns an empty list. For more information // about instance profiles, go to About Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html). // // You can paginate the results using the MaxItems and Marker parameters. @@ -8512,14 +9065,14 @@ func (c *IAM) ListInstanceProfilesForRoleRequest(input *ListInstanceProfilesForR // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRole func (c *IAM) ListInstanceProfilesForRole(input *ListInstanceProfilesForRoleInput) (*ListInstanceProfilesForRoleOutput, error) { req, out := c.ListInstanceProfilesForRoleRequest(input) return out, req.Send() @@ -8595,8 +9148,8 @@ const opListMFADevices = "ListMFADevices" // ListMFADevicesRequest generates a "aws/request.Request" representing the // client's request for the ListMFADevices operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8616,7 +9169,7 @@ const opListMFADevices = "ListMFADevices" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevices +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevices func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *request.Request, output *ListMFADevicesOutput) { op := &request.Operation{ Name: opListMFADevices, @@ -8642,7 +9195,7 @@ func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *request.Re // ListMFADevices API operation for AWS Identity and Access Management. // // Lists the MFA devices for an IAM user. If the request includes a IAM user -// name, then this action lists all the MFA devices associated with the specified +// name, then this operation lists all the MFA devices associated with the specified // user. If you do not specify a user name, IAM determines the user name implicitly // based on the AWS access key ID signing the request for this API. // @@ -8657,14 +9210,14 @@ func (c *IAM) ListMFADevicesRequest(input *ListMFADevicesInput) (req *request.Re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevices +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevices func (c *IAM) ListMFADevices(input *ListMFADevicesInput) (*ListMFADevicesOutput, error) { req, out := c.ListMFADevicesRequest(input) return out, req.Send() @@ -8740,8 +9293,8 @@ const opListOpenIDConnectProviders = "ListOpenIDConnectProviders" // ListOpenIDConnectProvidersRequest generates a "aws/request.Request" representing the // client's request for the ListOpenIDConnectProviders operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8761,7 +9314,7 @@ const opListOpenIDConnectProviders = "ListOpenIDConnectProviders" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProviders +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProviders func (c *IAM) ListOpenIDConnectProvidersRequest(input *ListOpenIDConnectProvidersInput) (req *request.Request, output *ListOpenIDConnectProvidersOutput) { op := &request.Operation{ Name: opListOpenIDConnectProviders, @@ -8795,7 +9348,7 @@ func (c *IAM) ListOpenIDConnectProvidersRequest(input *ListOpenIDConnectProvider // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProviders +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProviders func (c *IAM) ListOpenIDConnectProviders(input *ListOpenIDConnectProvidersInput) (*ListOpenIDConnectProvidersOutput, error) { req, out := c.ListOpenIDConnectProvidersRequest(input) return out, req.Send() @@ -8821,8 +9374,8 @@ const opListPolicies = "ListPolicies" // ListPoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListPolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8842,7 +9395,7 @@ const opListPolicies = "ListPolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicies func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Request, output *ListPoliciesOutput) { op := &request.Operation{ Name: opListPolicies, @@ -8893,7 +9446,7 @@ func (c *IAM) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Reques // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicies func (c *IAM) ListPolicies(input *ListPoliciesInput) (*ListPoliciesOutput, error) { req, out := c.ListPoliciesRequest(input) return out, req.Send() @@ -8965,12 +9518,130 @@ func (c *IAM) ListPoliciesPagesWithContext(ctx aws.Context, input *ListPoliciesI return p.Err() } +const opListPoliciesGrantingServiceAccess = "ListPoliciesGrantingServiceAccess" + +// ListPoliciesGrantingServiceAccessRequest generates a "aws/request.Request" representing the +// client's request for the ListPoliciesGrantingServiceAccess operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListPoliciesGrantingServiceAccess for more information on using the ListPoliciesGrantingServiceAccess +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListPoliciesGrantingServiceAccessRequest method. +// req, resp := client.ListPoliciesGrantingServiceAccessRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPoliciesGrantingServiceAccess +func (c *IAM) ListPoliciesGrantingServiceAccessRequest(input *ListPoliciesGrantingServiceAccessInput) (req *request.Request, output *ListPoliciesGrantingServiceAccessOutput) { + op := &request.Operation{ + Name: opListPoliciesGrantingServiceAccess, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListPoliciesGrantingServiceAccessInput{} + } + + output = &ListPoliciesGrantingServiceAccessOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListPoliciesGrantingServiceAccess API operation for AWS Identity and Access Management. +// +// Retrieves a list of policies that the IAM identity (user, group, or role) +// can use to access each specified service. +// +// This operation does not use other policy types when determining whether a +// resource could access a service. These other policy types include resource-based +// policies, access control lists, AWS Organizations policies, IAM permissions +// boundaries, and AWS STS assume role policies. It only applies permissions +// policy logic. For more about the evaluation of policy types, see Evaluating +// Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics) +// in the IAM User Guide. +// +// The list of policies returned by the operation depends on the ARN of the +// identity that you provide. +// +// * User – The list of policies includes the managed and inline policies +// that are attached to the user directly. The list also includes any additional +// managed and inline policies that are attached to the group to which the +// user belongs. +// +// * Group – The list of policies includes only the managed and inline policies +// that are attached to the group directly. Policies that are attached to +// the group’s user are not included. +// +// * Role – The list of policies includes only the managed and inline policies +// that are attached to the role. +// +// For each managed policy, this operation returns the ARN and policy name. +// For each inline policy, it returns the policy name and the entity to which +// it is attached. Inline policies do not have an ARN. For more information +// about these policy types, see Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html) +// in the IAM User Guide. +// +// Policies that are attached to users and roles as permissions boundaries are +// not returned. To view which managed policy is currently used to set the permissions +// boundary for a user or role, use the GetUser or GetRole operations. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation ListPoliciesGrantingServiceAccess for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPoliciesGrantingServiceAccess +func (c *IAM) ListPoliciesGrantingServiceAccess(input *ListPoliciesGrantingServiceAccessInput) (*ListPoliciesGrantingServiceAccessOutput, error) { + req, out := c.ListPoliciesGrantingServiceAccessRequest(input) + return out, req.Send() +} + +// ListPoliciesGrantingServiceAccessWithContext is the same as ListPoliciesGrantingServiceAccess with the addition of +// the ability to pass a context and additional request options. +// +// See ListPoliciesGrantingServiceAccess for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) ListPoliciesGrantingServiceAccessWithContext(ctx aws.Context, input *ListPoliciesGrantingServiceAccessInput, opts ...request.Option) (*ListPoliciesGrantingServiceAccessOutput, error) { + req, out := c.ListPoliciesGrantingServiceAccessRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListPolicyVersions = "ListPolicyVersions" // ListPolicyVersionsRequest generates a "aws/request.Request" representing the // client's request for the ListPolicyVersions operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -8990,7 +9661,7 @@ const opListPolicyVersions = "ListPolicyVersions" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersions +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersions func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *request.Request, output *ListPolicyVersionsOutput) { op := &request.Operation{ Name: opListPolicyVersions, @@ -9031,8 +9702,8 @@ func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *re // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -9042,7 +9713,7 @@ func (c *IAM) ListPolicyVersionsRequest(input *ListPolicyVersionsInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersions +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersions func (c *IAM) ListPolicyVersions(input *ListPolicyVersionsInput) (*ListPolicyVersionsOutput, error) { req, out := c.ListPolicyVersionsRequest(input) return out, req.Send() @@ -9118,8 +9789,8 @@ const opListRolePolicies = "ListRolePolicies" // ListRolePoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListRolePolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9139,7 +9810,7 @@ const opListRolePolicies = "ListRolePolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePolicies func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *request.Request, output *ListRolePoliciesOutput) { op := &request.Operation{ Name: opListRolePolicies, @@ -9173,7 +9844,7 @@ func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *reques // in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If -// there are no inline policies embedded with the specified role, the action +// there are no inline policies embedded with the specified role, the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -9185,14 +9856,14 @@ func (c *IAM) ListRolePoliciesRequest(input *ListRolePoliciesInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePolicies func (c *IAM) ListRolePolicies(input *ListRolePoliciesInput) (*ListRolePoliciesOutput, error) { req, out := c.ListRolePoliciesRequest(input) return out, req.Send() @@ -9264,101 +9935,188 @@ func (c *IAM) ListRolePoliciesPagesWithContext(ctx aws.Context, input *ListRoleP return p.Err() } -const opListRoles = "ListRoles" +const opListRoleTags = "ListRoleTags" -// ListRolesRequest generates a "aws/request.Request" representing the -// client's request for the ListRoles operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// ListRoleTagsRequest generates a "aws/request.Request" representing the +// client's request for the ListRoleTags operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListRoles for more information on using the ListRoles +// See ListRoleTags for more information on using the ListRoleTags // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListRolesRequest method. -// req, resp := client.ListRolesRequest(params) +// // Example sending a request using the ListRoleTagsRequest method. +// req, resp := client.ListRoleTagsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoles -func (c *IAM) ListRolesRequest(input *ListRolesInput) (req *request.Request, output *ListRolesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoleTags +func (c *IAM) ListRoleTagsRequest(input *ListRoleTagsInput) (req *request.Request, output *ListRoleTagsOutput) { op := &request.Operation{ - Name: opListRoles, + Name: opListRoleTags, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"Marker"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, } if input == nil { - input = &ListRolesInput{} + input = &ListRoleTagsInput{} } - output = &ListRolesOutput{} + output = &ListRoleTagsOutput{} req = c.newRequest(op, input, output) return } -// ListRoles API operation for AWS Identity and Access Management. -// -// Lists the IAM roles that have the specified path prefix. If there are none, -// the action returns an empty list. For more information about roles, go to -// Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). +// ListRoleTags API operation for AWS Identity and Access Management. // -// You can paginate the results using the MaxItems and Marker parameters. +// Lists the tags that are attached to the specified role. The returned list +// of tags is sorted by tag key. For more information about tagging, see Tagging +// IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) +// in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation ListRoles for usage and error information. +// API operation ListRoleTags for usage and error information. // // Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoles -func (c *IAM) ListRoles(input *ListRolesInput) (*ListRolesOutput, error) { - req, out := c.ListRolesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoleTags +func (c *IAM) ListRoleTags(input *ListRoleTagsInput) (*ListRoleTagsOutput, error) { + req, out := c.ListRoleTagsRequest(input) return out, req.Send() } -// ListRolesWithContext is the same as ListRoles with the addition of +// ListRoleTagsWithContext is the same as ListRoleTags with the addition of // the ability to pass a context and additional request options. // -// See ListRoles for details on how to use this API operation. +// See ListRoleTags for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) ListRolesWithContext(ctx aws.Context, input *ListRolesInput, opts ...request.Option) (*ListRolesOutput, error) { - req, out := c.ListRolesRequest(input) +func (c *IAM) ListRoleTagsWithContext(ctx aws.Context, input *ListRoleTagsInput, opts ...request.Option) (*ListRoleTagsOutput, error) { + req, out := c.ListRoleTagsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListRolesPages iterates over the pages of a ListRoles operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListRoles method for more information on how to use this operation. +const opListRoles = "ListRoles" + +// ListRolesRequest generates a "aws/request.Request" representing the +// client's request for the ListRoles operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListRoles for more information on using the ListRoles +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListRolesRequest method. +// req, resp := client.ListRolesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoles +func (c *IAM) ListRolesRequest(input *ListRolesInput) (req *request.Request, output *ListRolesOutput) { + op := &request.Operation{ + Name: opListRoles, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxItems", + TruncationToken: "IsTruncated", + }, + } + + if input == nil { + input = &ListRolesInput{} + } + + output = &ListRolesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRoles API operation for AWS Identity and Access Management. +// +// Lists the IAM roles that have the specified path prefix. If there are none, +// the operation returns an empty list. For more information about roles, go +// to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). +// +// You can paginate the results using the MaxItems and Marker parameters. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation ListRoles for usage and error information. +// +// Returned Error Codes: +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRoles +func (c *IAM) ListRoles(input *ListRolesInput) (*ListRolesOutput, error) { + req, out := c.ListRolesRequest(input) + return out, req.Send() +} + +// ListRolesWithContext is the same as ListRoles with the addition of +// the ability to pass a context and additional request options. +// +// See ListRoles for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) ListRolesWithContext(ctx aws.Context, input *ListRolesInput, opts ...request.Option) (*ListRolesOutput, error) { + req, out := c.ListRolesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListRolesPages iterates over the pages of a ListRoles operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListRoles method for more information on how to use this operation. // // Note: This operation can generate multiple requests to a service. // @@ -9408,8 +10166,8 @@ const opListSAMLProviders = "ListSAMLProviders" // ListSAMLProvidersRequest generates a "aws/request.Request" representing the // client's request for the ListSAMLProviders operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9429,7 +10187,7 @@ const opListSAMLProviders = "ListSAMLProviders" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProviders +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProviders func (c *IAM) ListSAMLProvidersRequest(input *ListSAMLProvidersInput) (req *request.Request, output *ListSAMLProvidersOutput) { op := &request.Operation{ Name: opListSAMLProviders, @@ -9464,7 +10222,7 @@ func (c *IAM) ListSAMLProvidersRequest(input *ListSAMLProvidersInput) (req *requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProviders +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProviders func (c *IAM) ListSAMLProviders(input *ListSAMLProvidersInput) (*ListSAMLProvidersOutput, error) { req, out := c.ListSAMLProvidersRequest(input) return out, req.Send() @@ -9490,8 +10248,8 @@ const opListSSHPublicKeys = "ListSSHPublicKeys" // ListSSHPublicKeysRequest generates a "aws/request.Request" representing the // client's request for the ListSSHPublicKeys operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9511,7 +10269,7 @@ const opListSSHPublicKeys = "ListSSHPublicKeys" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeys func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *request.Request, output *ListSSHPublicKeysOutput) { op := &request.Operation{ Name: opListSSHPublicKeys, @@ -9537,9 +10295,9 @@ func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *requ // ListSSHPublicKeys API operation for AWS Identity and Access Management. // // Returns information about the SSH public keys associated with the specified -// IAM user. If there are none, the action returns an empty list. +// IAM user. If there none exists, the operation returns an empty list. // -// The SSH public keys returned by this action are used only for authenticating +// The SSH public keys returned by this operation are used only for authenticating // the IAM user to an AWS CodeCommit repository. For more information about // using SSH keys to authenticate to an AWS CodeCommit repository, see Set up // AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) @@ -9557,10 +10315,10 @@ func (c *IAM) ListSSHPublicKeysRequest(input *ListSSHPublicKeysInput) (req *requ // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeys func (c *IAM) ListSSHPublicKeys(input *ListSSHPublicKeysInput) (*ListSSHPublicKeysOutput, error) { req, out := c.ListSSHPublicKeysRequest(input) return out, req.Send() @@ -9636,8 +10394,8 @@ const opListServerCertificates = "ListServerCertificates" // ListServerCertificatesRequest generates a "aws/request.Request" representing the // client's request for the ListServerCertificates operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9657,7 +10415,7 @@ const opListServerCertificates = "ListServerCertificates" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificates +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificates func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) (req *request.Request, output *ListServerCertificatesOutput) { op := &request.Operation{ Name: opListServerCertificates, @@ -9683,14 +10441,14 @@ func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) // ListServerCertificates API operation for AWS Identity and Access Management. // // Lists the server certificates stored in IAM that have the specified path -// prefix. If none exist, the action returns an empty list. +// prefix. If none exist, the operation returns an empty list. // // You can paginate the results using the MaxItems and Marker parameters. // -// For more information about working with server certificates, including a -// list of AWS services that can use the server certificates that you manage -// with IAM, go to Working with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) -// in the IAM User Guide. +// For more information about working with server certificates, see Working +// with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) +// in the IAM User Guide. This topic also includes a list of AWS services that +// can use the server certificates that you manage with IAM. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -9704,7 +10462,7 @@ func (c *IAM) ListServerCertificatesRequest(input *ListServerCertificatesInput) // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificates +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificates func (c *IAM) ListServerCertificates(input *ListServerCertificatesInput) (*ListServerCertificatesOutput, error) { req, out := c.ListServerCertificatesRequest(input) return out, req.Send() @@ -9780,8 +10538,8 @@ const opListServiceSpecificCredentials = "ListServiceSpecificCredentials" // ListServiceSpecificCredentialsRequest generates a "aws/request.Request" representing the // client's request for the ListServiceSpecificCredentials operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9801,7 +10559,7 @@ const opListServiceSpecificCredentials = "ListServiceSpecificCredentials" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentials +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentials func (c *IAM) ListServiceSpecificCredentialsRequest(input *ListServiceSpecificCredentialsInput) (req *request.Request, output *ListServiceSpecificCredentialsOutput) { op := &request.Operation{ Name: opListServiceSpecificCredentials, @@ -9821,11 +10579,11 @@ func (c *IAM) ListServiceSpecificCredentialsRequest(input *ListServiceSpecificCr // ListServiceSpecificCredentials API operation for AWS Identity and Access Management. // // Returns information about the service-specific credentials associated with -// the specified IAM user. If there are none, the action returns an empty list. -// The service-specific credentials returned by this action are used only for -// authenticating the IAM user to a specific service. For more information about -// using service-specific credentials to authenticate to an AWS service, see -// Set Up service-specific credentials (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html) +// the specified IAM user. If none exists, the operation returns an empty list. +// The service-specific credentials returned by this operation are used only +// for authenticating the IAM user to a specific service. For more information +// about using service-specific credentials to authenticate to an AWS service, +// see Set Up service-specific credentials (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html) // in the AWS CodeCommit User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -9837,13 +10595,13 @@ func (c *IAM) ListServiceSpecificCredentialsRequest(input *ListServiceSpecificCr // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceNotSupportedException "NotSupportedService" // The specified service does not support service-specific credentials. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentials +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentials func (c *IAM) ListServiceSpecificCredentials(input *ListServiceSpecificCredentialsInput) (*ListServiceSpecificCredentialsOutput, error) { req, out := c.ListServiceSpecificCredentialsRequest(input) return out, req.Send() @@ -9869,8 +10627,8 @@ const opListSigningCertificates = "ListSigningCertificates" // ListSigningCertificatesRequest generates a "aws/request.Request" representing the // client's request for the ListSigningCertificates operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -9890,7 +10648,7 @@ const opListSigningCertificates = "ListSigningCertificates" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificates +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificates func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput) (req *request.Request, output *ListSigningCertificatesOutput) { op := &request.Operation{ Name: opListSigningCertificates, @@ -9916,16 +10674,16 @@ func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput // ListSigningCertificates API operation for AWS Identity and Access Management. // // Returns information about the signing certificates associated with the specified -// IAM user. If there are none, the action returns an empty list. +// IAM user. If there none exists, the operation returns an empty list. // // Although each user is limited to a small number of signing certificates, // you can still paginate the results using the MaxItems and Marker parameters. // // If the UserName field is not specified, the user name is determined implicitly -// based on the AWS access key ID used to sign the request for this API. Because -// this action works for access keys under the AWS account, you can use this -// action to manage root credentials even if the AWS account has no associated -// users. +// based on the AWS access key ID used to sign the request for this API. This +// operation works for access keys under the AWS account. Consequently, you +// can use this operation to manage AWS account root user credentials even if +// the AWS account has no associated users. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -9936,14 +10694,14 @@ func (c *IAM) ListSigningCertificatesRequest(input *ListSigningCertificatesInput // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificates +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificates func (c *IAM) ListSigningCertificates(input *ListSigningCertificatesInput) (*ListSigningCertificatesOutput, error) { req, out := c.ListSigningCertificatesRequest(input) return out, req.Send() @@ -10019,8 +10777,8 @@ const opListUserPolicies = "ListUserPolicies" // ListUserPoliciesRequest generates a "aws/request.Request" representing the // client's request for the ListUserPolicies operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10040,7 +10798,7 @@ const opListUserPolicies = "ListUserPolicies" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *request.Request, output *ListUserPoliciesOutput) { op := &request.Operation{ Name: opListUserPolicies, @@ -10073,7 +10831,7 @@ func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *reques // in the IAM User Guide. // // You can paginate the results using the MaxItems and Marker parameters. If -// there are no inline policies embedded with the specified user, the action +// there are no inline policies embedded with the specified user, the operation // returns an empty list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10085,14 +10843,14 @@ func (c *IAM) ListUserPoliciesRequest(input *ListUserPoliciesInput) (req *reques // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPolicies func (c *IAM) ListUserPolicies(input *ListUserPoliciesInput) (*ListUserPoliciesOutput, error) { req, out := c.ListUserPoliciesRequest(input) return out, req.Send() @@ -10164,12 +10922,99 @@ func (c *IAM) ListUserPoliciesPagesWithContext(ctx aws.Context, input *ListUserP return p.Err() } +const opListUserTags = "ListUserTags" + +// ListUserTagsRequest generates a "aws/request.Request" representing the +// client's request for the ListUserTags operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListUserTags for more information on using the ListUserTags +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListUserTagsRequest method. +// req, resp := client.ListUserTagsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserTags +func (c *IAM) ListUserTagsRequest(input *ListUserTagsInput) (req *request.Request, output *ListUserTagsOutput) { + op := &request.Operation{ + Name: opListUserTags, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListUserTagsInput{} + } + + output = &ListUserTagsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListUserTags API operation for AWS Identity and Access Management. +// +// Lists the tags that are attached to the specified user. The returned list +// of tags is sorted by tag key. For more information about tagging, see Tagging +// IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation ListUserTags for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserTags +func (c *IAM) ListUserTags(input *ListUserTagsInput) (*ListUserTagsOutput, error) { + req, out := c.ListUserTagsRequest(input) + return out, req.Send() +} + +// ListUserTagsWithContext is the same as ListUserTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListUserTags for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) ListUserTagsWithContext(ctx aws.Context, input *ListUserTagsInput, opts ...request.Option) (*ListUserTagsOutput, error) { + req, out := c.ListUserTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListUsers = "ListUsers" // ListUsersRequest generates a "aws/request.Request" representing the // client's request for the ListUsers operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10189,7 +11034,7 @@ const opListUsers = "ListUsers" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsers +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsers func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *request.Request, output *ListUsersOutput) { op := &request.Operation{ Name: opListUsers, @@ -10215,8 +11060,8 @@ func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *request.Request, out // ListUsers API operation for AWS Identity and Access Management. // // Lists the IAM users that have the specified path prefix. If no path prefix -// is specified, the action returns all users in the AWS account. If there are -// none, the action returns an empty list. +// is specified, the operation returns all users in the AWS account. If there +// are none, the operation returns an empty list. // // You can paginate the results using the MaxItems and Marker parameters. // @@ -10232,7 +11077,7 @@ func (c *IAM) ListUsersRequest(input *ListUsersInput) (req *request.Request, out // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsers +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsers func (c *IAM) ListUsers(input *ListUsersInput) (*ListUsersOutput, error) { req, out := c.ListUsersRequest(input) return out, req.Send() @@ -10308,8 +11153,8 @@ const opListVirtualMFADevices = "ListVirtualMFADevices" // ListVirtualMFADevicesRequest generates a "aws/request.Request" representing the // client's request for the ListVirtualMFADevices operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10329,7 +11174,7 @@ const opListVirtualMFADevices = "ListVirtualMFADevices" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevices +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevices func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (req *request.Request, output *ListVirtualMFADevicesOutput) { op := &request.Operation{ Name: opListVirtualMFADevices, @@ -10355,9 +11200,9 @@ func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (r // ListVirtualMFADevices API operation for AWS Identity and Access Management. // // Lists the virtual MFA devices defined in the AWS account by assignment status. -// If you do not specify an assignment status, the action returns a list of -// all virtual MFA devices. Assignment status can be Assigned, Unassigned, or -// Any. +// If you do not specify an assignment status, the operation returns a list +// of all virtual MFA devices. Assignment status can be Assigned, Unassigned, +// or Any. // // You can paginate the results using the MaxItems and Marker parameters. // @@ -10367,7 +11212,7 @@ func (c *IAM) ListVirtualMFADevicesRequest(input *ListVirtualMFADevicesInput) (r // // See the AWS API reference guide for AWS Identity and Access Management's // API operation ListVirtualMFADevices for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevices +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevices func (c *IAM) ListVirtualMFADevices(input *ListVirtualMFADevicesInput) (*ListVirtualMFADevicesOutput, error) { req, out := c.ListVirtualMFADevicesRequest(input) return out, req.Send() @@ -10443,8 +11288,8 @@ const opPutGroupPolicy = "PutGroupPolicy" // PutGroupPolicyRequest generates a "aws/request.Request" representing the // client's request for the PutGroupPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10464,7 +11309,7 @@ const opPutGroupPolicy = "PutGroupPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicy func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Request, output *PutGroupPolicyOutput) { op := &request.Operation{ Name: opPutGroupPolicy, @@ -10478,8 +11323,7 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Re output = &PutGroupPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -10520,14 +11364,14 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Re // message describes the specific error. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicy func (c *IAM) PutGroupPolicy(input *PutGroupPolicyInput) (*PutGroupPolicyOutput, error) { req, out := c.PutGroupPolicyRequest(input) return out, req.Send() @@ -10549,12 +11393,123 @@ func (c *IAM) PutGroupPolicyWithContext(ctx aws.Context, input *PutGroupPolicyIn return out, req.Send() } +const opPutRolePermissionsBoundary = "PutRolePermissionsBoundary" + +// PutRolePermissionsBoundaryRequest generates a "aws/request.Request" representing the +// client's request for the PutRolePermissionsBoundary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutRolePermissionsBoundary for more information on using the PutRolePermissionsBoundary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutRolePermissionsBoundaryRequest method. +// req, resp := client.PutRolePermissionsBoundaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePermissionsBoundary +func (c *IAM) PutRolePermissionsBoundaryRequest(input *PutRolePermissionsBoundaryInput) (req *request.Request, output *PutRolePermissionsBoundaryOutput) { + op := &request.Operation{ + Name: opPutRolePermissionsBoundary, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutRolePermissionsBoundaryInput{} + } + + output = &PutRolePermissionsBoundaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// PutRolePermissionsBoundary API operation for AWS Identity and Access Management. +// +// Adds or updates the policy that is specified as the IAM role's permissions +// boundary. You can use an AWS managed policy or a customer managed policy +// to set the boundary for a role. Use the boundary to control the maximum permissions +// that the role can have. Setting a permissions boundary is an advanced feature +// that can affect the permissions for the role. +// +// You cannot set the boundary for a service-linked role. +// +// Policies used as permissions boundaries do not provide permissions. You must +// also attach a permissions policy to the role. To learn how the effective +// permissions for a role are evaluated, see IAM JSON Policy Evaluation Logic +// (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation PutRolePermissionsBoundary for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// +// * ErrCodePolicyNotAttachableException "PolicyNotAttachable" +// The request failed because AWS service role policies can only be attached +// to the service-linked role for that service. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePermissionsBoundary +func (c *IAM) PutRolePermissionsBoundary(input *PutRolePermissionsBoundaryInput) (*PutRolePermissionsBoundaryOutput, error) { + req, out := c.PutRolePermissionsBoundaryRequest(input) + return out, req.Send() +} + +// PutRolePermissionsBoundaryWithContext is the same as PutRolePermissionsBoundary with the addition of +// the ability to pass a context and additional request options. +// +// See PutRolePermissionsBoundary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) PutRolePermissionsBoundaryWithContext(ctx aws.Context, input *PutRolePermissionsBoundaryInput, opts ...request.Option) (*PutRolePermissionsBoundaryOutput, error) { + req, out := c.PutRolePermissionsBoundaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPutRolePolicy = "PutRolePolicy" // PutRolePolicyRequest generates a "aws/request.Request" representing the // client's request for the PutRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10574,7 +11529,7 @@ const opPutRolePolicy = "PutRolePolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicy func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Request, output *PutRolePolicyOutput) { op := &request.Operation{ Name: opPutRolePolicy, @@ -10588,8 +11543,7 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ output = &PutRolePolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -10636,8 +11590,8 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // message describes the specific error. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -10649,7 +11603,7 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicy func (c *IAM) PutRolePolicy(input *PutRolePolicyInput) (*PutRolePolicyOutput, error) { req, out := c.PutRolePolicyRequest(input) return out, req.Send() @@ -10671,68 +11625,61 @@ func (c *IAM) PutRolePolicyWithContext(ctx aws.Context, input *PutRolePolicyInpu return out, req.Send() } -const opPutUserPolicy = "PutUserPolicy" +const opPutUserPermissionsBoundary = "PutUserPermissionsBoundary" -// PutUserPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutUserPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// PutUserPermissionsBoundaryRequest generates a "aws/request.Request" representing the +// client's request for the PutUserPermissionsBoundary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See PutUserPolicy for more information on using the PutUserPolicy +// See PutUserPermissionsBoundary for more information on using the PutUserPermissionsBoundary // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the PutUserPolicyRequest method. -// req, resp := client.PutUserPolicyRequest(params) +// // Example sending a request using the PutUserPermissionsBoundaryRequest method. +// req, resp := client.PutUserPermissionsBoundaryRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicy -func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Request, output *PutUserPolicyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPermissionsBoundary +func (c *IAM) PutUserPermissionsBoundaryRequest(input *PutUserPermissionsBoundaryInput) (req *request.Request, output *PutUserPermissionsBoundaryOutput) { op := &request.Operation{ - Name: opPutUserPolicy, + Name: opPutUserPermissionsBoundary, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &PutUserPolicyInput{} + input = &PutUserPermissionsBoundaryInput{} } - output = &PutUserPolicyOutput{} + output = &PutUserPermissionsBoundaryOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// PutUserPolicy API operation for AWS Identity and Access Management. -// -// Adds or updates an inline policy document that is embedded in the specified -// IAM user. -// -// An IAM user can also have a managed policy attached to it. To attach a managed -// policy to a user, use AttachUserPolicy. To create a new managed policy, use -// CreatePolicy. For information about policies, see Managed Policies and Inline -// Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) -// in the IAM User Guide. +// PutUserPermissionsBoundary API operation for AWS Identity and Access Management. // -// For information about limits on the number of inline policies that you can -// embed in a user, see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) -// in the IAM User Guide. +// Adds or updates the policy that is specified as the IAM user's permissions +// boundary. You can use an AWS managed policy or a customer managed policy +// to set the boundary for a user. Use the boundary to control the maximum permissions +// that the user can have. Setting a permissions boundary is an advanced feature +// that can affect the permissions for the user. // -// Because policy documents can be large, you should use POST rather than GET -// when calling PutUserPolicy. For general information about using the Query -// API with IAM, go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) +// Policies that are used as permissions boundaries do not provide permissions. +// You must also attach a permissions policy to the user. To learn how the effective +// permissions for a user are evaluated, see IAM JSON Policy Evaluation Logic +// (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10740,11 +11687,120 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Requ // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation PutUserPolicy for usage and error information. +// API operation PutUserPermissionsBoundary for usage and error information. // // Returned Error Codes: -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodePolicyNotAttachableException "PolicyNotAttachable" +// The request failed because AWS service role policies can only be attached +// to the service-linked role for that service. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPermissionsBoundary +func (c *IAM) PutUserPermissionsBoundary(input *PutUserPermissionsBoundaryInput) (*PutUserPermissionsBoundaryOutput, error) { + req, out := c.PutUserPermissionsBoundaryRequest(input) + return out, req.Send() +} + +// PutUserPermissionsBoundaryWithContext is the same as PutUserPermissionsBoundary with the addition of +// the ability to pass a context and additional request options. +// +// See PutUserPermissionsBoundary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) PutUserPermissionsBoundaryWithContext(ctx aws.Context, input *PutUserPermissionsBoundaryInput, opts ...request.Option) (*PutUserPermissionsBoundaryOutput, error) { + req, out := c.PutUserPermissionsBoundaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opPutUserPolicy = "PutUserPolicy" + +// PutUserPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutUserPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutUserPolicy for more information on using the PutUserPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutUserPolicyRequest method. +// req, resp := client.PutUserPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicy +func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Request, output *PutUserPolicyOutput) { + op := &request.Operation{ + Name: opPutUserPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutUserPolicyInput{} + } + + output = &PutUserPolicyOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// PutUserPolicy API operation for AWS Identity and Access Management. +// +// Adds or updates an inline policy document that is embedded in the specified +// IAM user. +// +// An IAM user can also have a managed policy attached to it. To attach a managed +// policy to a user, use AttachUserPolicy. To create a new managed policy, use +// CreatePolicy. For information about policies, see Managed Policies and Inline +// Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) +// in the IAM User Guide. +// +// For information about limits on the number of inline policies that you can +// embed in a user, see Limitations on IAM Entities (http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// in the IAM User Guide. +// +// Because policy documents can be large, you should use POST rather than GET +// when calling PutUserPolicy. For general information about using the Query +// API with IAM, go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation PutUserPolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" @@ -10752,14 +11808,14 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Requ // message describes the specific error. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicy func (c *IAM) PutUserPolicy(input *PutUserPolicyInput) (*PutUserPolicyOutput, error) { req, out := c.PutUserPolicyRequest(input) return out, req.Send() @@ -10785,8 +11841,8 @@ const opRemoveClientIDFromOpenIDConnectProvider = "RemoveClientIDFromOpenIDConne // RemoveClientIDFromOpenIDConnectProviderRequest generates a "aws/request.Request" representing the // client's request for the RemoveClientIDFromOpenIDConnectProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10806,7 +11862,7 @@ const opRemoveClientIDFromOpenIDConnectProvider = "RemoveClientIDFromOpenIDConne // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProvider func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClientIDFromOpenIDConnectProviderInput) (req *request.Request, output *RemoveClientIDFromOpenIDConnectProviderOutput) { op := &request.Operation{ Name: opRemoveClientIDFromOpenIDConnectProvider, @@ -10820,8 +11876,7 @@ func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClient output = &RemoveClientIDFromOpenIDConnectProviderOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -10831,8 +11886,8 @@ func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClient // client IDs registered for the specified IAM OpenID Connect (OIDC) provider // resource object. // -// This action is idempotent; it does not fail or return an error if you try -// to remove a client ID that does not exist. +// This operation is idempotent; it does not fail or return an error if you +// try to remove a client ID that does not exist. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10847,14 +11902,14 @@ func (c *IAM) RemoveClientIDFromOpenIDConnectProviderRequest(input *RemoveClient // for an input parameter. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProvider +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProvider func (c *IAM) RemoveClientIDFromOpenIDConnectProvider(input *RemoveClientIDFromOpenIDConnectProviderInput) (*RemoveClientIDFromOpenIDConnectProviderOutput, error) { req, out := c.RemoveClientIDFromOpenIDConnectProviderRequest(input) return out, req.Send() @@ -10880,8 +11935,8 @@ const opRemoveRoleFromInstanceProfile = "RemoveRoleFromInstanceProfile" // RemoveRoleFromInstanceProfileRequest generates a "aws/request.Request" representing the // client's request for the RemoveRoleFromInstanceProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -10901,7 +11956,7 @@ const opRemoveRoleFromInstanceProfile = "RemoveRoleFromInstanceProfile" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfile func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstanceProfileInput) (req *request.Request, output *RemoveRoleFromInstanceProfileOutput) { op := &request.Operation{ Name: opRemoveRoleFromInstanceProfile, @@ -10915,8 +11970,7 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance output = &RemoveRoleFromInstanceProfileOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -10924,10 +11978,10 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // // Removes the specified IAM role from the specified EC2 instance profile. // -// Make sure you do not have any Amazon EC2 instances running with the role -// you are about to remove from the instance profile. Removing a role from an -// instance profile that is associated with a running instance might break any -// applications running on the instance. +// Make sure that you do not have any Amazon EC2 instances running with the +// role you are about to remove from the instance profile. Removing a role from +// an instance profile that is associated with a running instance might break +// any applications running on the instance. // // For more information about IAM roles, go to Working with Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). // For more information about instance profiles, go to About Instance Profiles @@ -10942,8 +11996,8 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -10959,7 +12013,7 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfile func (c *IAM) RemoveRoleFromInstanceProfile(input *RemoveRoleFromInstanceProfileInput) (*RemoveRoleFromInstanceProfileOutput, error) { req, out := c.RemoveRoleFromInstanceProfileRequest(input) return out, req.Send() @@ -10985,8 +12039,8 @@ const opRemoveUserFromGroup = "RemoveUserFromGroup" // RemoveUserFromGroupRequest generates a "aws/request.Request" representing the // client's request for the RemoveUserFromGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11006,7 +12060,7 @@ const opRemoveUserFromGroup = "RemoveUserFromGroup" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroup func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req *request.Request, output *RemoveUserFromGroupOutput) { op := &request.Operation{ Name: opRemoveUserFromGroup, @@ -11020,8 +12074,7 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * output = &RemoveUserFromGroupOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -11038,8 +12091,8 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -11049,7 +12102,7 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroup +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroup func (c *IAM) RemoveUserFromGroup(input *RemoveUserFromGroupInput) (*RemoveUserFromGroupOutput, error) { req, out := c.RemoveUserFromGroupRequest(input) return out, req.Send() @@ -11075,8 +12128,8 @@ const opResetServiceSpecificCredential = "ResetServiceSpecificCredential" // ResetServiceSpecificCredentialRequest generates a "aws/request.Request" representing the // client's request for the ResetServiceSpecificCredential operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11096,7 +12149,7 @@ const opResetServiceSpecificCredential = "ResetServiceSpecificCredential" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredential func (c *IAM) ResetServiceSpecificCredentialRequest(input *ResetServiceSpecificCredentialInput) (req *request.Request, output *ResetServiceSpecificCredentialOutput) { op := &request.Operation{ Name: opResetServiceSpecificCredential, @@ -11129,10 +12182,10 @@ func (c *IAM) ResetServiceSpecificCredentialRequest(input *ResetServiceSpecificC // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredential +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredential func (c *IAM) ResetServiceSpecificCredential(input *ResetServiceSpecificCredentialInput) (*ResetServiceSpecificCredentialOutput, error) { req, out := c.ResetServiceSpecificCredentialRequest(input) return out, req.Send() @@ -11158,8 +12211,8 @@ const opResyncMFADevice = "ResyncMFADevice" // ResyncMFADeviceRequest generates a "aws/request.Request" representing the // client's request for the ResyncMFADevice operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11179,7 +12232,7 @@ const opResyncMFADevice = "ResyncMFADevice" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADevice func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request.Request, output *ResyncMFADeviceOutput) { op := &request.Operation{ Name: opResyncMFADevice, @@ -11193,8 +12246,7 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. output = &ResyncMFADeviceOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -11220,8 +12272,8 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. // The error message describes the specific error. // // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -11231,7 +12283,7 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADevice +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADevice func (c *IAM) ResyncMFADevice(input *ResyncMFADeviceInput) (*ResyncMFADeviceOutput, error) { req, out := c.ResyncMFADeviceRequest(input) return out, req.Send() @@ -11257,8 +12309,8 @@ const opSetDefaultPolicyVersion = "SetDefaultPolicyVersion" // SetDefaultPolicyVersionRequest generates a "aws/request.Request" representing the // client's request for the SetDefaultPolicyVersion operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11278,7 +12330,7 @@ const opSetDefaultPolicyVersion = "SetDefaultPolicyVersion" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersion func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput) (req *request.Request, output *SetDefaultPolicyVersionOutput) { op := &request.Operation{ Name: opSetDefaultPolicyVersion, @@ -11292,8 +12344,7 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput output = &SetDefaultPolicyVersionOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -11302,7 +12353,7 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // Sets the specified version of the specified policy as the policy's default // (operative) version. // -// This action affects all users, groups, and roles that the policy is attached +// This operation affects all users, groups, and roles that the policy is attached // to. To list the users, groups, and roles that the policy is attached to, // use the ListEntitiesForPolicy API. // @@ -11319,8 +12370,8 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -11334,7 +12385,7 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersion +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersion func (c *IAM) SetDefaultPolicyVersion(input *SetDefaultPolicyVersionInput) (*SetDefaultPolicyVersionOutput, error) { req, out := c.SetDefaultPolicyVersionRequest(input) return out, req.Send() @@ -11360,8 +12411,8 @@ const opSimulateCustomPolicy = "SimulateCustomPolicy" // SimulateCustomPolicyRequest generates a "aws/request.Request" representing the // client's request for the SimulateCustomPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11381,7 +12432,7 @@ const opSimulateCustomPolicy = "SimulateCustomPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicy func (c *IAM) SimulateCustomPolicyRequest(input *SimulateCustomPolicyInput) (req *request.Request, output *SimulatePolicyResponse) { op := &request.Operation{ Name: opSimulateCustomPolicy, @@ -11407,11 +12458,11 @@ func (c *IAM) SimulateCustomPolicyRequest(input *SimulateCustomPolicyInput) (req // SimulateCustomPolicy API operation for AWS Identity and Access Management. // // Simulate how a set of IAM policies and optionally a resource-based policy -// works with a list of API actions and AWS resources to determine the policies' +// works with a list of API operations and AWS resources to determine the policies' // effective permissions. The policies are provided as strings. // -// The simulation does not perform the API actions; it only checks the authorization -// to determine if the simulated policies allow or deny the actions. +// The simulation does not perform the API operations; it only checks the authorization +// to determine if the simulated policies allow or deny the operations. // // If you want to simulate existing policies attached to an IAM user, group, // or role, use SimulatePrincipalPolicy instead. @@ -11440,7 +12491,7 @@ func (c *IAM) SimulateCustomPolicyRequest(input *SimulateCustomPolicyInput) (req // The request failed because a provided policy could not be successfully evaluated. // An additional detailed message indicates the source of the failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicy func (c *IAM) SimulateCustomPolicy(input *SimulateCustomPolicyInput) (*SimulatePolicyResponse, error) { req, out := c.SimulateCustomPolicyRequest(input) return out, req.Send() @@ -11516,8 +12567,8 @@ const opSimulatePrincipalPolicy = "SimulatePrincipalPolicy" // SimulatePrincipalPolicyRequest generates a "aws/request.Request" representing the // client's request for the SimulatePrincipalPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. @@ -11537,7 +12588,7 @@ const opSimulatePrincipalPolicy = "SimulatePrincipalPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicy func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput) (req *request.Request, output *SimulatePolicyResponse) { op := &request.Operation{ Name: opSimulatePrincipalPolicy, @@ -11563,10 +12614,10 @@ func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput // SimulatePrincipalPolicy API operation for AWS Identity and Access Management. // // Simulate how a set of IAM policies attached to an IAM entity works with a -// list of API actions and AWS resources to determine the policies' effective +// list of API operations and AWS resources to determine the policies' effective // permissions. The entity can be an IAM user, group, or role. If you specify // a user, then the simulation also includes all of the policies that are attached -// to groups that the user belongs to . +// to groups that the user belongs to. // // You can optionally include a list of one or more additional policies specified // as strings to include in the simulation. If you want to simulate only policies @@ -11575,8 +12626,8 @@ func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput // You can also optionally include one resource-based policy to be evaluated // with each of the resources included in the simulation. // -// The simulation does not perform the API actions, it only checks the authorization -// to determine if the simulated policies allow or deny the actions. +// The simulation does not perform the API operations, it only checks the authorization +// to determine if the simulated policies allow or deny the operations. // // Note: This API discloses information about the permissions granted to other // users. If you do not want users to see other user's permissions, then consider @@ -11599,8 +12650,8 @@ func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -11610,7 +12661,7 @@ func (c *IAM) SimulatePrincipalPolicyRequest(input *SimulatePrincipalPolicyInput // The request failed because a provided policy could not be successfully evaluated. // An additional detailed message indicates the source of the failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicy func (c *IAM) SimulatePrincipalPolicy(input *SimulatePrincipalPolicyInput) (*SimulatePolicyResponse, error) { req, out := c.SimulatePrincipalPolicyRequest(input) return out, req.Send() @@ -11682,62 +12733,84 @@ func (c *IAM) SimulatePrincipalPolicyPagesWithContext(ctx aws.Context, input *Si return p.Err() } -const opUpdateAccessKey = "UpdateAccessKey" +const opTagRole = "TagRole" -// UpdateAccessKeyRequest generates a "aws/request.Request" representing the -// client's request for the UpdateAccessKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// TagRoleRequest generates a "aws/request.Request" representing the +// client's request for the TagRole operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateAccessKey for more information on using the UpdateAccessKey +// See TagRole for more information on using the TagRole // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateAccessKeyRequest method. -// req, resp := client.UpdateAccessKeyRequest(params) +// // Example sending a request using the TagRoleRequest method. +// req, resp := client.TagRoleRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKey -func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request.Request, output *UpdateAccessKeyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/TagRole +func (c *IAM) TagRoleRequest(input *TagRoleInput) (req *request.Request, output *TagRoleOutput) { op := &request.Operation{ - Name: opUpdateAccessKey, + Name: opTagRole, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateAccessKeyInput{} + input = &TagRoleInput{} } - output = &UpdateAccessKeyOutput{} + output = &TagRoleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateAccessKey API operation for AWS Identity and Access Management. +// TagRole API operation for AWS Identity and Access Management. // -// Changes the status of the specified access key from Active to Inactive, or -// vice versa. This action can be used to disable a user's key as part of a -// key rotation work flow. +// Adds one or more tags to an IAM role. The role can be a regular role or a +// service-linked role. If a tag with the same key name already exists, then +// that tag is overwritten with the new value. // -// If the UserName field is not specified, the UserName is determined implicitly -// based on the AWS access key ID used to sign the request. Because this action -// works for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// A tag consists of a key name and an associated value. By assigning tags to +// your resources, you can do the following: // -// For information about rotating keys, see Managing Keys and Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html) +// * Administrative grouping and discovery - Attach tags to resources to +// aid in organization and search. For example, you could search for all +// resources with the key name Project and the value MyImportantProject. +// Or search for all resources with the key name Cost Center and the value +// 41200. +// +// * Access control - Reference tags in IAM user-based and resource-based +// policies. You can use tags to restrict access to only an IAM user or role +// that has a specified tag attached. You can also restrict access to only +// those resources that have a certain tag attached. For examples of policies +// that show how to use tags to control access, see Control Access Using +// IAM Tags (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) +// in the IAM User Guide. +// +// * Cost allocation - Use tags to help track which individuals and teams +// are using which AWS resources. +// +// Make sure that you have no invalid tags and that you do not exceed the allowed +// number of tags per role. In either case, the entire request fails and no +// tags are added to the role. +// +// AWS always interprets the tag Value as a single string. If you need to store +// an array, you can store comma-separated values in the string. However, you +// must interpret the value in your code. +// +// For more information about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11745,98 +12818,129 @@ func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request. // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateAccessKey for usage and error information. +// API operation TagRole for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKey -func (c *IAM) UpdateAccessKey(input *UpdateAccessKeyInput) (*UpdateAccessKeyOutput, error) { - req, out := c.UpdateAccessKeyRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/TagRole +func (c *IAM) TagRole(input *TagRoleInput) (*TagRoleOutput, error) { + req, out := c.TagRoleRequest(input) return out, req.Send() } -// UpdateAccessKeyWithContext is the same as UpdateAccessKey with the addition of +// TagRoleWithContext is the same as TagRole with the addition of // the ability to pass a context and additional request options. // -// See UpdateAccessKey for details on how to use this API operation. +// See TagRole for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateAccessKeyWithContext(ctx aws.Context, input *UpdateAccessKeyInput, opts ...request.Option) (*UpdateAccessKeyOutput, error) { - req, out := c.UpdateAccessKeyRequest(input) +func (c *IAM) TagRoleWithContext(ctx aws.Context, input *TagRoleInput, opts ...request.Option) (*TagRoleOutput, error) { + req, out := c.TagRoleRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateAccountPasswordPolicy = "UpdateAccountPasswordPolicy" +const opTagUser = "TagUser" -// UpdateAccountPasswordPolicyRequest generates a "aws/request.Request" representing the -// client's request for the UpdateAccountPasswordPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// TagUserRequest generates a "aws/request.Request" representing the +// client's request for the TagUser operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateAccountPasswordPolicy for more information on using the UpdateAccountPasswordPolicy +// See TagUser for more information on using the TagUser // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateAccountPasswordPolicyRequest method. -// req, resp := client.UpdateAccountPasswordPolicyRequest(params) +// // Example sending a request using the TagUserRequest method. +// req, resp := client.TagUserRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicy -func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPolicyInput) (req *request.Request, output *UpdateAccountPasswordPolicyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/TagUser +func (c *IAM) TagUserRequest(input *TagUserInput) (req *request.Request, output *TagUserOutput) { op := &request.Operation{ - Name: opUpdateAccountPasswordPolicy, + Name: opTagUser, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateAccountPasswordPolicyInput{} + input = &TagUserInput{} } - output = &UpdateAccountPasswordPolicyOutput{} + output = &TagUserOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateAccountPasswordPolicy API operation for AWS Identity and Access Management. +// TagUser API operation for AWS Identity and Access Management. // -// Updates the password policy settings for the AWS account. +// Adds one or more tags to an IAM user. If a tag with the same key name already +// exists, then that tag is overwritten with the new value. // -// This action does not support partial updates. No parameters are required, -// but if you do not specify a parameter, that parameter's value reverts to -// its default value. See the Request Parameters section for each parameter's -// default value. +// A tag consists of a key name and an associated value. By assigning tags to +// your resources, you can do the following: // -// For more information about using a password policy, see Managing an IAM Password -// Policy (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html) +// * Administrative grouping and discovery - Attach tags to resources to +// aid in organization and search. For example, you could search for all +// resources with the key name Project and the value MyImportantProject. +// Or search for all resources with the key name Cost Center and the value +// 41200. +// +// * Access control - Reference tags in IAM user-based and resource-based +// policies. You can use tags to restrict access to only an IAM requesting +// user or to a role that has a specified tag attached. You can also restrict +// access to only those resources that have a certain tag attached. For examples +// of policies that show how to use tags to control access, see Control Access +// Using IAM Tags (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) +// in the IAM User Guide. +// +// * Cost allocation - Use tags to help track which individuals and teams +// are using which AWS resources. +// +// Make sure that you have no invalid tags and that you do not exceed the allowed +// number of tags per role. In either case, the entire request fails and no +// tags are added to the role. +// +// AWS always interprets the tag Value as a single string. If you need to store +// an array, you can store comma-separated values in the string. However, you +// must interpret the value in your code. +// +// For more information about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11844,304 +12948,292 @@ func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPol // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateAccountPasswordPolicy for usage and error information. +// API operation TagUser for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. +// +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicy -func (c *IAM) UpdateAccountPasswordPolicy(input *UpdateAccountPasswordPolicyInput) (*UpdateAccountPasswordPolicyOutput, error) { - req, out := c.UpdateAccountPasswordPolicyRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/TagUser +func (c *IAM) TagUser(input *TagUserInput) (*TagUserOutput, error) { + req, out := c.TagUserRequest(input) return out, req.Send() } -// UpdateAccountPasswordPolicyWithContext is the same as UpdateAccountPasswordPolicy with the addition of +// TagUserWithContext is the same as TagUser with the addition of // the ability to pass a context and additional request options. // -// See UpdateAccountPasswordPolicy for details on how to use this API operation. +// See TagUser for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateAccountPasswordPolicyWithContext(ctx aws.Context, input *UpdateAccountPasswordPolicyInput, opts ...request.Option) (*UpdateAccountPasswordPolicyOutput, error) { - req, out := c.UpdateAccountPasswordPolicyRequest(input) +func (c *IAM) TagUserWithContext(ctx aws.Context, input *TagUserInput, opts ...request.Option) (*TagUserOutput, error) { + req, out := c.TagUserRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateAssumeRolePolicy = "UpdateAssumeRolePolicy" +const opUntagRole = "UntagRole" -// UpdateAssumeRolePolicyRequest generates a "aws/request.Request" representing the -// client's request for the UpdateAssumeRolePolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UntagRoleRequest generates a "aws/request.Request" representing the +// client's request for the UntagRole operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateAssumeRolePolicy for more information on using the UpdateAssumeRolePolicy +// See UntagRole for more information on using the UntagRole // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateAssumeRolePolicyRequest method. -// req, resp := client.UpdateAssumeRolePolicyRequest(params) +// // Example sending a request using the UntagRoleRequest method. +// req, resp := client.UntagRoleRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicy -func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) (req *request.Request, output *UpdateAssumeRolePolicyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UntagRole +func (c *IAM) UntagRoleRequest(input *UntagRoleInput) (req *request.Request, output *UntagRoleOutput) { op := &request.Operation{ - Name: opUpdateAssumeRolePolicy, + Name: opUntagRole, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateAssumeRolePolicyInput{} + input = &UntagRoleInput{} } - output = &UpdateAssumeRolePolicyOutput{} + output = &UntagRoleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateAssumeRolePolicy API operation for AWS Identity and Access Management. +// UntagRole API operation for AWS Identity and Access Management. // -// Updates the policy that grants an IAM entity permission to assume a role. -// This is typically referred to as the "role trust policy". For more information -// about roles, go to Using Roles to Delegate Permissions and Federate Identities -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html). +// Removes the specified tags from the role. For more information about tagging, +// see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) +// in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateAssumeRolePolicy for usage and error information. +// API operation UntagRole for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" -// The request was rejected because only the service that depends on the service-linked -// role can modify or delete the role on your behalf. The error message includes -// the name of the service that depends on this service-linked role. You must -// request the change through that service. +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicy -func (c *IAM) UpdateAssumeRolePolicy(input *UpdateAssumeRolePolicyInput) (*UpdateAssumeRolePolicyOutput, error) { - req, out := c.UpdateAssumeRolePolicyRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UntagRole +func (c *IAM) UntagRole(input *UntagRoleInput) (*UntagRoleOutput, error) { + req, out := c.UntagRoleRequest(input) return out, req.Send() } -// UpdateAssumeRolePolicyWithContext is the same as UpdateAssumeRolePolicy with the addition of +// UntagRoleWithContext is the same as UntagRole with the addition of // the ability to pass a context and additional request options. // -// See UpdateAssumeRolePolicy for details on how to use this API operation. +// See UntagRole for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateAssumeRolePolicyWithContext(ctx aws.Context, input *UpdateAssumeRolePolicyInput, opts ...request.Option) (*UpdateAssumeRolePolicyOutput, error) { - req, out := c.UpdateAssumeRolePolicyRequest(input) +func (c *IAM) UntagRoleWithContext(ctx aws.Context, input *UntagRoleInput, opts ...request.Option) (*UntagRoleOutput, error) { + req, out := c.UntagRoleRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateGroup = "UpdateGroup" +const opUntagUser = "UntagUser" -// UpdateGroupRequest generates a "aws/request.Request" representing the -// client's request for the UpdateGroup operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UntagUserRequest generates a "aws/request.Request" representing the +// client's request for the UntagUser operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateGroup for more information on using the UpdateGroup +// See UntagUser for more information on using the UntagUser // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateGroupRequest method. -// req, resp := client.UpdateGroupRequest(params) +// // Example sending a request using the UntagUserRequest method. +// req, resp := client.UntagUserRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroup -func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UntagUser +func (c *IAM) UntagUserRequest(input *UntagUserInput) (req *request.Request, output *UntagUserOutput) { op := &request.Operation{ - Name: opUpdateGroup, + Name: opUntagUser, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateGroupInput{} + input = &UntagUserInput{} } - output = &UpdateGroupOutput{} + output = &UntagUserOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateGroup API operation for AWS Identity and Access Management. +// UntagUser API operation for AWS Identity and Access Management. // -// Updates the name and/or the path of the specified IAM group. -// -// You should understand the implications of changing a group's path or name. -// For more information, see Renaming Users and Groups (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html) +// Removes the specified tags from the user. For more information about tagging, +// see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) // in the IAM User Guide. // -// To change an IAM group name the requester must have appropriate permissions -// on both the source object and the target object. For example, to change "Managers" -// to "MGRs", the entity making the request must have permission on both "Managers" -// and "MGRs", or must have permission on all (*). For more information about -// permissions, see Permissions and Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PermissionsAndPolicies.html). -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateGroup for usage and error information. +// API operation UntagUser for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" -// The request was rejected because it attempted to create a resource that already -// exists. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroup -func (c *IAM) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { - req, out := c.UpdateGroupRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UntagUser +func (c *IAM) UntagUser(input *UntagUserInput) (*UntagUserOutput, error) { + req, out := c.UntagUserRequest(input) return out, req.Send() } -// UpdateGroupWithContext is the same as UpdateGroup with the addition of +// UntagUserWithContext is the same as UntagUser with the addition of // the ability to pass a context and additional request options. // -// See UpdateGroup for details on how to use this API operation. +// See UntagUser for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateGroupWithContext(ctx aws.Context, input *UpdateGroupInput, opts ...request.Option) (*UpdateGroupOutput, error) { - req, out := c.UpdateGroupRequest(input) +func (c *IAM) UntagUserWithContext(ctx aws.Context, input *UntagUserInput, opts ...request.Option) (*UntagUserOutput, error) { + req, out := c.UntagUserRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateLoginProfile = "UpdateLoginProfile" +const opUpdateAccessKey = "UpdateAccessKey" -// UpdateLoginProfileRequest generates a "aws/request.Request" representing the -// client's request for the UpdateLoginProfile operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateAccessKeyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAccessKey operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateLoginProfile for more information on using the UpdateLoginProfile +// See UpdateAccessKey for more information on using the UpdateAccessKey // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateLoginProfileRequest method. -// req, resp := client.UpdateLoginProfileRequest(params) +// // Example sending a request using the UpdateAccessKeyRequest method. +// req, resp := client.UpdateAccessKeyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfile -func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *request.Request, output *UpdateLoginProfileOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKey +func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request.Request, output *UpdateAccessKeyOutput) { op := &request.Operation{ - Name: opUpdateLoginProfile, + Name: opUpdateAccessKey, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateLoginProfileInput{} + input = &UpdateAccessKeyInput{} } - output = &UpdateLoginProfileOutput{} + output = &UpdateAccessKeyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateLoginProfile API operation for AWS Identity and Access Management. +// UpdateAccessKey API operation for AWS Identity and Access Management. // -// Changes the password for the specified IAM user. +// Changes the status of the specified access key from Active to Inactive, or +// vice versa. This operation can be used to disable a user's key as part of +// a key rotation workflow. // -// IAM users can change their own passwords by calling ChangePassword. For more -// information about modifying passwords, see Managing Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html) +// If the UserName field is not specified, the user name is determined implicitly +// based on the AWS access key ID used to sign the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated users. +// +// For information about rotating keys, see Managing Keys and Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -12149,22 +13241,12 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *re // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateLoginProfile for usage and error information. +// API operation UpdateAccessKey for usage and error information. // // Returned Error Codes: -// * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" -// The request was rejected because it referenced an entity that is temporarily -// unmodifiable, such as a user name that was deleted and then recreated. The -// error indicates that the request is likely to succeed if you try again after -// waiting several minutes. The error message describes the entity. -// // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodePasswordPolicyViolationException "PasswordPolicyViolation" -// The request was rejected because the provided password did not meet the requirements -// imposed by the account password policy. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -12174,189 +13256,201 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfile -func (c *IAM) UpdateLoginProfile(input *UpdateLoginProfileInput) (*UpdateLoginProfileOutput, error) { - req, out := c.UpdateLoginProfileRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKey +func (c *IAM) UpdateAccessKey(input *UpdateAccessKeyInput) (*UpdateAccessKeyOutput, error) { + req, out := c.UpdateAccessKeyRequest(input) return out, req.Send() } -// UpdateLoginProfileWithContext is the same as UpdateLoginProfile with the addition of +// UpdateAccessKeyWithContext is the same as UpdateAccessKey with the addition of // the ability to pass a context and additional request options. // -// See UpdateLoginProfile for details on how to use this API operation. +// See UpdateAccessKey for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateLoginProfileWithContext(ctx aws.Context, input *UpdateLoginProfileInput, opts ...request.Option) (*UpdateLoginProfileOutput, error) { - req, out := c.UpdateLoginProfileRequest(input) +func (c *IAM) UpdateAccessKeyWithContext(ctx aws.Context, input *UpdateAccessKeyInput, opts ...request.Option) (*UpdateAccessKeyOutput, error) { + req, out := c.UpdateAccessKeyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateOpenIDConnectProviderThumbprint = "UpdateOpenIDConnectProviderThumbprint" +const opUpdateAccountPasswordPolicy = "UpdateAccountPasswordPolicy" -// UpdateOpenIDConnectProviderThumbprintRequest generates a "aws/request.Request" representing the -// client's request for the UpdateOpenIDConnectProviderThumbprint operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateAccountPasswordPolicyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAccountPasswordPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateOpenIDConnectProviderThumbprint for more information on using the UpdateOpenIDConnectProviderThumbprint +// See UpdateAccountPasswordPolicy for more information on using the UpdateAccountPasswordPolicy // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateOpenIDConnectProviderThumbprintRequest method. -// req, resp := client.UpdateOpenIDConnectProviderThumbprintRequest(params) +// // Example sending a request using the UpdateAccountPasswordPolicyRequest method. +// req, resp := client.UpdateAccountPasswordPolicyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprint -func (c *IAM) UpdateOpenIDConnectProviderThumbprintRequest(input *UpdateOpenIDConnectProviderThumbprintInput) (req *request.Request, output *UpdateOpenIDConnectProviderThumbprintOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicy +func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPolicyInput) (req *request.Request, output *UpdateAccountPasswordPolicyOutput) { op := &request.Operation{ - Name: opUpdateOpenIDConnectProviderThumbprint, + Name: opUpdateAccountPasswordPolicy, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateOpenIDConnectProviderThumbprintInput{} + input = &UpdateAccountPasswordPolicyInput{} } - output = &UpdateOpenIDConnectProviderThumbprintOutput{} + output = &UpdateAccountPasswordPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateOpenIDConnectProviderThumbprint API operation for AWS Identity and Access Management. -// -// Replaces the existing list of server certificate thumbprints associated with -// an OpenID Connect (OIDC) provider resource object with a new list of thumbprints. +// UpdateAccountPasswordPolicy API operation for AWS Identity and Access Management. // -// The list that you pass with this action completely replaces the existing -// list of thumbprints. (The lists are not merged.) +// Updates the password policy settings for the AWS account. // -// Typically, you need to update a thumbprint only when the identity provider's -// certificate changes, which occurs rarely. However, if the provider's certificate -// does change, any attempt to assume an IAM role that specifies the OIDC provider -// as a principal fails until the certificate thumbprint is updated. +// This operation does not support partial updates. No parameters are required, +// but if you do not specify a parameter, that parameter's value reverts to +// its default value. See the Request Parameters section for each parameter's +// default value. Also note that some parameters do not allow the default parameter +// to be explicitly set. Instead, to invoke the default value, do not include +// that parameter when you invoke the operation. // -// Because trust for the OIDC provider is ultimately derived from the provider's -// certificate and is validated by the thumbprint, it is a best practice to -// limit access to the UpdateOpenIDConnectProviderThumbprint action to highly-privileged -// users. +// For more information about using a password policy, see Managing an IAM Password +// Policy (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html) +// in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateOpenIDConnectProviderThumbprint for usage and error information. +// API operation UpdateAccountPasswordPolicy for usage and error information. // // Returned Error Codes: -// * ErrCodeInvalidInputException "InvalidInput" -// The request was rejected because an invalid or out-of-range value was supplied -// for an input parameter. -// // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" +// The request was rejected because the policy document was malformed. The error +// message describes the specific error. +// +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprint -func (c *IAM) UpdateOpenIDConnectProviderThumbprint(input *UpdateOpenIDConnectProviderThumbprintInput) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { - req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicy +func (c *IAM) UpdateAccountPasswordPolicy(input *UpdateAccountPasswordPolicyInput) (*UpdateAccountPasswordPolicyOutput, error) { + req, out := c.UpdateAccountPasswordPolicyRequest(input) return out, req.Send() } -// UpdateOpenIDConnectProviderThumbprintWithContext is the same as UpdateOpenIDConnectProviderThumbprint with the addition of +// UpdateAccountPasswordPolicyWithContext is the same as UpdateAccountPasswordPolicy with the addition of // the ability to pass a context and additional request options. // -// See UpdateOpenIDConnectProviderThumbprint for details on how to use this API operation. +// See UpdateAccountPasswordPolicy for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateOpenIDConnectProviderThumbprintWithContext(ctx aws.Context, input *UpdateOpenIDConnectProviderThumbprintInput, opts ...request.Option) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { - req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) +func (c *IAM) UpdateAccountPasswordPolicyWithContext(ctx aws.Context, input *UpdateAccountPasswordPolicyInput, opts ...request.Option) (*UpdateAccountPasswordPolicyOutput, error) { + req, out := c.UpdateAccountPasswordPolicyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateRoleDescription = "UpdateRoleDescription" +const opUpdateAssumeRolePolicy = "UpdateAssumeRolePolicy" -// UpdateRoleDescriptionRequest generates a "aws/request.Request" representing the -// client's request for the UpdateRoleDescription operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateAssumeRolePolicyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAssumeRolePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateRoleDescription for more information on using the UpdateRoleDescription +// See UpdateAssumeRolePolicy for more information on using the UpdateAssumeRolePolicy // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateRoleDescriptionRequest method. -// req, resp := client.UpdateRoleDescriptionRequest(params) +// // Example sending a request using the UpdateAssumeRolePolicyRequest method. +// req, resp := client.UpdateAssumeRolePolicyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription -func (c *IAM) UpdateRoleDescriptionRequest(input *UpdateRoleDescriptionInput) (req *request.Request, output *UpdateRoleDescriptionOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicy +func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) (req *request.Request, output *UpdateAssumeRolePolicyOutput) { op := &request.Operation{ - Name: opUpdateRoleDescription, + Name: opUpdateAssumeRolePolicy, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateRoleDescriptionInput{} + input = &UpdateAssumeRolePolicyInput{} } - output = &UpdateRoleDescriptionOutput{} + output = &UpdateAssumeRolePolicyOutput{} req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateRoleDescription API operation for AWS Identity and Access Management. +// UpdateAssumeRolePolicy API operation for AWS Identity and Access Management. // -// Modifies the description of a role. +// Updates the policy that grants an IAM entity permission to assume a role. +// This is typically referred to as the "role trust policy". For more information +// about roles, go to Using Roles to Delegate Permissions and Federate Identities +// (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateRoleDescription for usage and error information. +// API operation UpdateAssumeRolePolicy for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" +// The request was rejected because the policy document was malformed. The error +// message describes the specific error. +// +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -12368,91 +13462,101 @@ func (c *IAM) UpdateRoleDescriptionRequest(input *UpdateRoleDescriptionInput) (r // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription -func (c *IAM) UpdateRoleDescription(input *UpdateRoleDescriptionInput) (*UpdateRoleDescriptionOutput, error) { - req, out := c.UpdateRoleDescriptionRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicy +func (c *IAM) UpdateAssumeRolePolicy(input *UpdateAssumeRolePolicyInput) (*UpdateAssumeRolePolicyOutput, error) { + req, out := c.UpdateAssumeRolePolicyRequest(input) return out, req.Send() } -// UpdateRoleDescriptionWithContext is the same as UpdateRoleDescription with the addition of +// UpdateAssumeRolePolicyWithContext is the same as UpdateAssumeRolePolicy with the addition of // the ability to pass a context and additional request options. // -// See UpdateRoleDescription for details on how to use this API operation. +// See UpdateAssumeRolePolicy for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateRoleDescriptionWithContext(ctx aws.Context, input *UpdateRoleDescriptionInput, opts ...request.Option) (*UpdateRoleDescriptionOutput, error) { - req, out := c.UpdateRoleDescriptionRequest(input) +func (c *IAM) UpdateAssumeRolePolicyWithContext(ctx aws.Context, input *UpdateAssumeRolePolicyInput, opts ...request.Option) (*UpdateAssumeRolePolicyOutput, error) { + req, out := c.UpdateAssumeRolePolicyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateSAMLProvider = "UpdateSAMLProvider" +const opUpdateGroup = "UpdateGroup" -// UpdateSAMLProviderRequest generates a "aws/request.Request" representing the -// client's request for the UpdateSAMLProvider operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateGroupRequest generates a "aws/request.Request" representing the +// client's request for the UpdateGroup operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateSAMLProvider for more information on using the UpdateSAMLProvider +// See UpdateGroup for more information on using the UpdateGroup // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateSAMLProviderRequest method. -// req, resp := client.UpdateSAMLProviderRequest(params) +// // Example sending a request using the UpdateGroupRequest method. +// req, resp := client.UpdateGroupRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProvider -func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *request.Request, output *UpdateSAMLProviderOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroup +func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { op := &request.Operation{ - Name: opUpdateSAMLProvider, + Name: opUpdateGroup, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateSAMLProviderInput{} + input = &UpdateGroupInput{} } - output = &UpdateSAMLProviderOutput{} + output = &UpdateGroupOutput{} req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateSAMLProvider API operation for AWS Identity and Access Management. +// UpdateGroup API operation for AWS Identity and Access Management. // -// Updates the metadata document for an existing SAML provider resource object. +// Updates the name and/or the path of the specified IAM group. // -// This operation requires Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). +// You should understand the implications of changing a group's path or name. +// For more information, see Renaming Users and Groups (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html) +// in the IAM User Guide. +// +// The person making the request (the principal), must have permission to change +// the role group with the old name and the new name. For example, to change +// the group named Managers to MGRs, the principal must have a policy that allows +// them to update both groups. If the principal has permission to update the +// Managers group, but not the MGRs group, then the update fails. For more information +// about permissions, see Access Management (http://docs.aws.amazon.com/IAM/latest/UserGuide/access.html). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateSAMLProvider for usage and error information. +// API operation UpdateGroup for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// * ErrCodeInvalidInputException "InvalidInput" -// The request was rejected because an invalid or out-of-range value was supplied -// for an input parameter. +// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" +// The request was rejected because it attempted to create a resource that already +// exists. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond @@ -12462,571 +13566,563 @@ func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *re // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProvider -func (c *IAM) UpdateSAMLProvider(input *UpdateSAMLProviderInput) (*UpdateSAMLProviderOutput, error) { - req, out := c.UpdateSAMLProviderRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroup +func (c *IAM) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { + req, out := c.UpdateGroupRequest(input) return out, req.Send() } -// UpdateSAMLProviderWithContext is the same as UpdateSAMLProvider with the addition of +// UpdateGroupWithContext is the same as UpdateGroup with the addition of // the ability to pass a context and additional request options. // -// See UpdateSAMLProvider for details on how to use this API operation. +// See UpdateGroup for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateSAMLProviderWithContext(ctx aws.Context, input *UpdateSAMLProviderInput, opts ...request.Option) (*UpdateSAMLProviderOutput, error) { - req, out := c.UpdateSAMLProviderRequest(input) +func (c *IAM) UpdateGroupWithContext(ctx aws.Context, input *UpdateGroupInput, opts ...request.Option) (*UpdateGroupOutput, error) { + req, out := c.UpdateGroupRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateSSHPublicKey = "UpdateSSHPublicKey" +const opUpdateLoginProfile = "UpdateLoginProfile" -// UpdateSSHPublicKeyRequest generates a "aws/request.Request" representing the -// client's request for the UpdateSSHPublicKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateLoginProfileRequest generates a "aws/request.Request" representing the +// client's request for the UpdateLoginProfile operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateSSHPublicKey for more information on using the UpdateSSHPublicKey +// See UpdateLoginProfile for more information on using the UpdateLoginProfile // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateSSHPublicKeyRequest method. -// req, resp := client.UpdateSSHPublicKeyRequest(params) +// // Example sending a request using the UpdateLoginProfileRequest method. +// req, resp := client.UpdateLoginProfileRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey -func (c *IAM) UpdateSSHPublicKeyRequest(input *UpdateSSHPublicKeyInput) (req *request.Request, output *UpdateSSHPublicKeyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfile +func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *request.Request, output *UpdateLoginProfileOutput) { op := &request.Operation{ - Name: opUpdateSSHPublicKey, + Name: opUpdateLoginProfile, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateSSHPublicKeyInput{} + input = &UpdateLoginProfileInput{} } - output = &UpdateSSHPublicKeyOutput{} + output = &UpdateLoginProfileOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateSSHPublicKey API operation for AWS Identity and Access Management. +// UpdateLoginProfile API operation for AWS Identity and Access Management. // -// Sets the status of an IAM user's SSH public key to active or inactive. SSH -// public keys that are inactive cannot be used for authentication. This action -// can be used to disable a user's SSH public key as part of a key rotation -// work flow. +// Changes the password for the specified IAM user. // -// The SSH public key affected by this action is used only for authenticating -// the associated IAM user to an AWS CodeCommit repository. For more information -// about using SSH keys to authenticate to an AWS CodeCommit repository, see -// Set up AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) -// in the AWS CodeCommit User Guide. +// IAM users can change their own passwords by calling ChangePassword. For more +// information about modifying passwords, see Managing Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html) +// in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateSSHPublicKey for usage and error information. +// API operation UpdateLoginProfile for usage and error information. // // Returned Error Codes: +// * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" +// The request was rejected because it referenced an entity that is temporarily +// unmodifiable, such as a user name that was deleted and then recreated. The +// error indicates that the request is likely to succeed if you try again after +// waiting several minutes. The error message describes the entity. +// // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey -func (c *IAM) UpdateSSHPublicKey(input *UpdateSSHPublicKeyInput) (*UpdateSSHPublicKeyOutput, error) { - req, out := c.UpdateSSHPublicKeyRequest(input) +// * ErrCodePasswordPolicyViolationException "PasswordPolicyViolation" +// The request was rejected because the provided password did not meet the requirements +// imposed by the account password policy. +// +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfile +func (c *IAM) UpdateLoginProfile(input *UpdateLoginProfileInput) (*UpdateLoginProfileOutput, error) { + req, out := c.UpdateLoginProfileRequest(input) return out, req.Send() } -// UpdateSSHPublicKeyWithContext is the same as UpdateSSHPublicKey with the addition of +// UpdateLoginProfileWithContext is the same as UpdateLoginProfile with the addition of // the ability to pass a context and additional request options. // -// See UpdateSSHPublicKey for details on how to use this API operation. +// See UpdateLoginProfile for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateSSHPublicKeyWithContext(ctx aws.Context, input *UpdateSSHPublicKeyInput, opts ...request.Option) (*UpdateSSHPublicKeyOutput, error) { - req, out := c.UpdateSSHPublicKeyRequest(input) +func (c *IAM) UpdateLoginProfileWithContext(ctx aws.Context, input *UpdateLoginProfileInput, opts ...request.Option) (*UpdateLoginProfileOutput, error) { + req, out := c.UpdateLoginProfileRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateServerCertificate = "UpdateServerCertificate" +const opUpdateOpenIDConnectProviderThumbprint = "UpdateOpenIDConnectProviderThumbprint" -// UpdateServerCertificateRequest generates a "aws/request.Request" representing the -// client's request for the UpdateServerCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateOpenIDConnectProviderThumbprintRequest generates a "aws/request.Request" representing the +// client's request for the UpdateOpenIDConnectProviderThumbprint operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateServerCertificate for more information on using the UpdateServerCertificate +// See UpdateOpenIDConnectProviderThumbprint for more information on using the UpdateOpenIDConnectProviderThumbprint // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateServerCertificateRequest method. -// req, resp := client.UpdateServerCertificateRequest(params) +// // Example sending a request using the UpdateOpenIDConnectProviderThumbprintRequest method. +// req, resp := client.UpdateOpenIDConnectProviderThumbprintRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificate -func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput) (req *request.Request, output *UpdateServerCertificateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprint +func (c *IAM) UpdateOpenIDConnectProviderThumbprintRequest(input *UpdateOpenIDConnectProviderThumbprintInput) (req *request.Request, output *UpdateOpenIDConnectProviderThumbprintOutput) { op := &request.Operation{ - Name: opUpdateServerCertificate, + Name: opUpdateOpenIDConnectProviderThumbprint, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateServerCertificateInput{} + input = &UpdateOpenIDConnectProviderThumbprintInput{} } - output = &UpdateServerCertificateOutput{} + output = &UpdateOpenIDConnectProviderThumbprintOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateServerCertificate API operation for AWS Identity and Access Management. +// UpdateOpenIDConnectProviderThumbprint API operation for AWS Identity and Access Management. // -// Updates the name and/or the path of the specified server certificate stored -// in IAM. +// Replaces the existing list of server certificate thumbprints associated with +// an OpenID Connect (OIDC) provider resource object with a new list of thumbprints. // -// For more information about working with server certificates, including a -// list of AWS services that can use the server certificates that you manage -// with IAM, go to Working with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) -// in the IAM User Guide. +// The list that you pass with this operation completely replaces the existing +// list of thumbprints. (The lists are not merged.) // -// You should understand the implications of changing a server certificate's -// path or name. For more information, see Renaming a Server Certificate (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs_manage.html#RenamingServerCerts) -// in the IAM User Guide. +// Typically, you need to update a thumbprint only when the identity provider's +// certificate changes, which occurs rarely. However, if the provider's certificate +// does change, any attempt to assume an IAM role that specifies the OIDC provider +// as a principal fails until the certificate thumbprint is updated. // -// To change a server certificate name the requester must have appropriate permissions -// on both the source object and the target object. For example, to change the -// name from "ProductionCert" to "ProdCert", the entity making the request must -// have permission on "ProductionCert" and "ProdCert", or must have permission -// on all (*). For more information about permissions, see Access Management -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/access.html) in the IAM -// User Guide. +// Trust for the OIDC provider is derived from the provider's certificate and +// is validated by the thumbprint. Therefore, it is best to limit access to +// the UpdateOpenIDConnectProviderThumbprint operation to highly privileged +// users. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateServerCertificate for usage and error information. +// API operation UpdateOpenIDConnectProviderThumbprint for usage and error information. // // Returned Error Codes: -// * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" -// The request was rejected because it attempted to create a resource that already -// exists. +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. // -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificate -func (c *IAM) UpdateServerCertificate(input *UpdateServerCertificateInput) (*UpdateServerCertificateOutput, error) { - req, out := c.UpdateServerCertificateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprint +func (c *IAM) UpdateOpenIDConnectProviderThumbprint(input *UpdateOpenIDConnectProviderThumbprintInput) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { + req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) return out, req.Send() } -// UpdateServerCertificateWithContext is the same as UpdateServerCertificate with the addition of +// UpdateOpenIDConnectProviderThumbprintWithContext is the same as UpdateOpenIDConnectProviderThumbprint with the addition of // the ability to pass a context and additional request options. // -// See UpdateServerCertificate for details on how to use this API operation. +// See UpdateOpenIDConnectProviderThumbprint for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateServerCertificateWithContext(ctx aws.Context, input *UpdateServerCertificateInput, opts ...request.Option) (*UpdateServerCertificateOutput, error) { - req, out := c.UpdateServerCertificateRequest(input) +func (c *IAM) UpdateOpenIDConnectProviderThumbprintWithContext(ctx aws.Context, input *UpdateOpenIDConnectProviderThumbprintInput, opts ...request.Option) (*UpdateOpenIDConnectProviderThumbprintOutput, error) { + req, out := c.UpdateOpenIDConnectProviderThumbprintRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateServiceSpecificCredential = "UpdateServiceSpecificCredential" +const opUpdateRole = "UpdateRole" -// UpdateServiceSpecificCredentialRequest generates a "aws/request.Request" representing the -// client's request for the UpdateServiceSpecificCredential operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateRoleRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRole operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateServiceSpecificCredential for more information on using the UpdateServiceSpecificCredential +// See UpdateRole for more information on using the UpdateRole // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateServiceSpecificCredentialRequest method. -// req, resp := client.UpdateServiceSpecificCredentialRequest(params) +// // Example sending a request using the UpdateRoleRequest method. +// req, resp := client.UpdateRoleRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredential -func (c *IAM) UpdateServiceSpecificCredentialRequest(input *UpdateServiceSpecificCredentialInput) (req *request.Request, output *UpdateServiceSpecificCredentialOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRole +func (c *IAM) UpdateRoleRequest(input *UpdateRoleInput) (req *request.Request, output *UpdateRoleOutput) { op := &request.Operation{ - Name: opUpdateServiceSpecificCredential, + Name: opUpdateRole, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateServiceSpecificCredentialInput{} + input = &UpdateRoleInput{} } - output = &UpdateServiceSpecificCredentialOutput{} + output = &UpdateRoleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UpdateServiceSpecificCredential API operation for AWS Identity and Access Management. +// UpdateRole API operation for AWS Identity and Access Management. // -// Sets the status of a service-specific credential to Active or Inactive. Service-specific -// credentials that are inactive cannot be used for authentication to the service. -// This action can be used to disable a user’s service-specific credential as -// part of a credential rotation work flow. +// Updates the description or maximum session duration setting of a role. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateServiceSpecificCredential for usage and error information. +// API operation UpdateRole for usage and error information. // // Returned Error Codes: +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. +// // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredential -func (c *IAM) UpdateServiceSpecificCredential(input *UpdateServiceSpecificCredentialInput) (*UpdateServiceSpecificCredentialOutput, error) { - req, out := c.UpdateServiceSpecificCredentialRequest(input) +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRole +func (c *IAM) UpdateRole(input *UpdateRoleInput) (*UpdateRoleOutput, error) { + req, out := c.UpdateRoleRequest(input) return out, req.Send() } -// UpdateServiceSpecificCredentialWithContext is the same as UpdateServiceSpecificCredential with the addition of +// UpdateRoleWithContext is the same as UpdateRole with the addition of // the ability to pass a context and additional request options. // -// See UpdateServiceSpecificCredential for details on how to use this API operation. +// See UpdateRole for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateServiceSpecificCredentialWithContext(ctx aws.Context, input *UpdateServiceSpecificCredentialInput, opts ...request.Option) (*UpdateServiceSpecificCredentialOutput, error) { - req, out := c.UpdateServiceSpecificCredentialRequest(input) +func (c *IAM) UpdateRoleWithContext(ctx aws.Context, input *UpdateRoleInput, opts ...request.Option) (*UpdateRoleOutput, error) { + req, out := c.UpdateRoleRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateSigningCertificate = "UpdateSigningCertificate" +const opUpdateRoleDescription = "UpdateRoleDescription" -// UpdateSigningCertificateRequest generates a "aws/request.Request" representing the -// client's request for the UpdateSigningCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateRoleDescriptionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRoleDescription operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateSigningCertificate for more information on using the UpdateSigningCertificate +// See UpdateRoleDescription for more information on using the UpdateRoleDescription // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateSigningCertificateRequest method. -// req, resp := client.UpdateSigningCertificateRequest(params) +// // Example sending a request using the UpdateRoleDescriptionRequest method. +// req, resp := client.UpdateRoleDescriptionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificate -func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInput) (req *request.Request, output *UpdateSigningCertificateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription +func (c *IAM) UpdateRoleDescriptionRequest(input *UpdateRoleDescriptionInput) (req *request.Request, output *UpdateRoleDescriptionOutput) { op := &request.Operation{ - Name: opUpdateSigningCertificate, + Name: opUpdateRoleDescription, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateSigningCertificateInput{} + input = &UpdateRoleDescriptionInput{} } - output = &UpdateSigningCertificateOutput{} + output = &UpdateRoleDescriptionOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) return } -// UpdateSigningCertificate API operation for AWS Identity and Access Management. +// UpdateRoleDescription API operation for AWS Identity and Access Management. // -// Changes the status of the specified user signing certificate from active -// to disabled, or vice versa. This action can be used to disable an IAM user's -// signing certificate as part of a certificate rotation work flow. +// Use UpdateRole instead. // -// If the UserName field is not specified, the UserName is determined implicitly -// based on the AWS access key ID used to sign the request. Because this action -// works for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// Modifies only the description of a role. This operation performs the same +// function as the Description parameter in the UpdateRole operation. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateSigningCertificate for usage and error information. +// API operation UpdateRoleDescription for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" +// The request was rejected because only the service that depends on the service-linked +// role can modify or delete the role on your behalf. The error message includes +// the name of the service that depends on this service-linked role. You must +// request the change through that service. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificate -func (c *IAM) UpdateSigningCertificate(input *UpdateSigningCertificateInput) (*UpdateSigningCertificateOutput, error) { - req, out := c.UpdateSigningCertificateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescription +func (c *IAM) UpdateRoleDescription(input *UpdateRoleDescriptionInput) (*UpdateRoleDescriptionOutput, error) { + req, out := c.UpdateRoleDescriptionRequest(input) return out, req.Send() } -// UpdateSigningCertificateWithContext is the same as UpdateSigningCertificate with the addition of +// UpdateRoleDescriptionWithContext is the same as UpdateRoleDescription with the addition of // the ability to pass a context and additional request options. // -// See UpdateSigningCertificate for details on how to use this API operation. +// See UpdateRoleDescription for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateSigningCertificateWithContext(ctx aws.Context, input *UpdateSigningCertificateInput, opts ...request.Option) (*UpdateSigningCertificateOutput, error) { - req, out := c.UpdateSigningCertificateRequest(input) +func (c *IAM) UpdateRoleDescriptionWithContext(ctx aws.Context, input *UpdateRoleDescriptionInput, opts ...request.Option) (*UpdateRoleDescriptionOutput, error) { + req, out := c.UpdateRoleDescriptionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateUser = "UpdateUser" +const opUpdateSAMLProvider = "UpdateSAMLProvider" -// UpdateUserRequest generates a "aws/request.Request" representing the -// client's request for the UpdateUser operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateSAMLProviderRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSAMLProvider operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateUser for more information on using the UpdateUser +// See UpdateSAMLProvider for more information on using the UpdateSAMLProvider // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateUserRequest method. -// req, resp := client.UpdateUserRequest(params) +// // Example sending a request using the UpdateSAMLProviderRequest method. +// req, resp := client.UpdateSAMLProviderRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUser -func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, output *UpdateUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProvider +func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *request.Request, output *UpdateSAMLProviderOutput) { op := &request.Operation{ - Name: opUpdateUser, + Name: opUpdateSAMLProvider, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateUserInput{} + input = &UpdateSAMLProviderInput{} } - output = &UpdateUserOutput{} + output = &UpdateSAMLProviderOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(query.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) return } -// UpdateUser API operation for AWS Identity and Access Management. -// -// Updates the name and/or the path of the specified IAM user. +// UpdateSAMLProvider API operation for AWS Identity and Access Management. // -// You should understand the implications of changing an IAM user's path or -// name. For more information, see Renaming an IAM User (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_renaming) -// and Renaming an IAM Group (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html) -// in the IAM User Guide. +// Updates the metadata document for an existing SAML provider resource object. // -// To change a user name the requester must have appropriate permissions on -// both the source object and the target object. For example, to change Bob -// to Robert, the entity making the request must have permission on Bob and -// Robert, or must have permission on all (*). For more information about permissions, -// see Permissions and Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PermissionsAndPolicies.html). +// This operation requires Signature Version 4 (http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UpdateUser for usage and error information. +// API operation UpdateSAMLProvider for usage and error information. // // Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidInputException "InvalidInput" +// The request was rejected because an invalid or out-of-range value was supplied +// for an input parameter. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond // the current AWS account limits. The error message describes the limit exceeded. // -// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" -// The request was rejected because it attempted to create a resource that already -// exists. -// -// * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" -// The request was rejected because it referenced an entity that is temporarily -// unmodifiable, such as a user name that was deleted and then recreated. The -// error indicates that the request is likely to succeed if you try again after -// waiting several minutes. The error message describes the entity. -// // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUser -func (c *IAM) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { - req, out := c.UpdateUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProvider +func (c *IAM) UpdateSAMLProvider(input *UpdateSAMLProviderInput) (*UpdateSAMLProviderOutput, error) { + req, out := c.UpdateSAMLProviderRequest(input) return out, req.Send() } -// UpdateUserWithContext is the same as UpdateUser with the addition of +// UpdateSAMLProviderWithContext is the same as UpdateSAMLProvider with the addition of // the ability to pass a context and additional request options. // -// See UpdateUser for details on how to use this API operation. +// See UpdateSAMLProvider for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UpdateUserWithContext(ctx aws.Context, input *UpdateUserInput, opts ...request.Option) (*UpdateUserOutput, error) { - req, out := c.UpdateUserRequest(input) +func (c *IAM) UpdateSAMLProviderWithContext(ctx aws.Context, input *UpdateSAMLProviderInput, opts ...request.Option) (*UpdateSAMLProviderOutput, error) { + req, out := c.UpdateSAMLProviderRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUploadSSHPublicKey = "UploadSSHPublicKey" +const opUpdateSSHPublicKey = "UpdateSSHPublicKey" -// UploadSSHPublicKeyRequest generates a "aws/request.Request" representing the -// client's request for the UploadSSHPublicKey operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateSSHPublicKeyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSSHPublicKey operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UploadSSHPublicKey for more information on using the UploadSSHPublicKey +// See UpdateSSHPublicKey for more information on using the UpdateSSHPublicKey // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UploadSSHPublicKeyRequest method. -// req, resp := client.UploadSSHPublicKeyRequest(params) +// // Example sending a request using the UpdateSSHPublicKeyRequest method. +// req, resp := client.UpdateSSHPublicKeyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey -func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *request.Request, output *UploadSSHPublicKeyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey +func (c *IAM) UpdateSSHPublicKeyRequest(input *UpdateSSHPublicKeyInput) (req *request.Request, output *UpdateSSHPublicKeyOutput) { op := &request.Operation{ - Name: opUploadSSHPublicKey, + Name: opUpdateSSHPublicKey, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UploadSSHPublicKeyInput{} + input = &UpdateSSHPublicKeyInput{} } - output = &UploadSSHPublicKeyOutput{} + output = &UpdateSSHPublicKeyOutput{} req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UploadSSHPublicKey API operation for AWS Identity and Access Management. +// UpdateSSHPublicKey API operation for AWS Identity and Access Management. // -// Uploads an SSH public key and associates it with the specified IAM user. +// Sets the status of an IAM user's SSH public key to active or inactive. SSH +// public keys that are inactive cannot be used for authentication. This operation +// can be used to disable a user's SSH public key as part of a key rotation +// work flow. // -// The SSH public key uploaded by this action can be used only for authenticating +// The SSH public key affected by this operation is used only for authenticating // the associated IAM user to an AWS CodeCommit repository. For more information // about using SSH keys to authenticate to an AWS CodeCommit repository, see // Set up AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) @@ -13037,120 +14133,99 @@ func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *re // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UploadSSHPublicKey for usage and error information. +// API operation UpdateSSHPublicKey for usage and error information. // // Returned Error Codes: -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. -// // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. -// -// * ErrCodeInvalidPublicKeyException "InvalidPublicKey" -// The request was rejected because the public key is malformed or otherwise -// invalid. -// -// * ErrCodeDuplicateSSHPublicKeyException "DuplicateSSHPublicKey" -// The request was rejected because the SSH public key is already associated -// with the specified IAM user. -// -// * ErrCodeUnrecognizedPublicKeyEncodingException "UnrecognizedPublicKeyEncoding" -// The request was rejected because the public key encoding format is unsupported -// or unrecognized. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey -func (c *IAM) UploadSSHPublicKey(input *UploadSSHPublicKeyInput) (*UploadSSHPublicKeyOutput, error) { - req, out := c.UploadSSHPublicKeyRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKey +func (c *IAM) UpdateSSHPublicKey(input *UpdateSSHPublicKeyInput) (*UpdateSSHPublicKeyOutput, error) { + req, out := c.UpdateSSHPublicKeyRequest(input) return out, req.Send() } -// UploadSSHPublicKeyWithContext is the same as UploadSSHPublicKey with the addition of +// UpdateSSHPublicKeyWithContext is the same as UpdateSSHPublicKey with the addition of // the ability to pass a context and additional request options. // -// See UploadSSHPublicKey for details on how to use this API operation. +// See UpdateSSHPublicKey for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UploadSSHPublicKeyWithContext(ctx aws.Context, input *UploadSSHPublicKeyInput, opts ...request.Option) (*UploadSSHPublicKeyOutput, error) { - req, out := c.UploadSSHPublicKeyRequest(input) +func (c *IAM) UpdateSSHPublicKeyWithContext(ctx aws.Context, input *UpdateSSHPublicKeyInput, opts ...request.Option) (*UpdateSSHPublicKeyOutput, error) { + req, out := c.UpdateSSHPublicKeyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUploadServerCertificate = "UploadServerCertificate" +const opUpdateServerCertificate = "UpdateServerCertificate" -// UploadServerCertificateRequest generates a "aws/request.Request" representing the -// client's request for the UploadServerCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateServerCertificateRequest generates a "aws/request.Request" representing the +// client's request for the UpdateServerCertificate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UploadServerCertificate for more information on using the UploadServerCertificate +// See UpdateServerCertificate for more information on using the UpdateServerCertificate // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UploadServerCertificateRequest method. -// req, resp := client.UploadServerCertificateRequest(params) +// // Example sending a request using the UpdateServerCertificateRequest method. +// req, resp := client.UpdateServerCertificateRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificate -func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput) (req *request.Request, output *UploadServerCertificateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificate +func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput) (req *request.Request, output *UpdateServerCertificateOutput) { op := &request.Operation{ - Name: opUploadServerCertificate, + Name: opUpdateServerCertificate, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UploadServerCertificateInput{} + input = &UpdateServerCertificateInput{} } - output = &UploadServerCertificateOutput{} + output = &UpdateServerCertificateOutput{} req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UploadServerCertificate API operation for AWS Identity and Access Management. -// -// Uploads a server certificate entity for the AWS account. The server certificate -// entity includes a public key certificate, a private key, and an optional -// certificate chain, which should all be PEM-encoded. +// UpdateServerCertificate API operation for AWS Identity and Access Management. // -// We recommend that you use AWS Certificate Manager (https://aws.amazon.com/certificate-manager/) -// to provision, manage, and deploy your server certificates. With ACM you can -// request a certificate, deploy it to AWS resources, and let ACM handle certificate -// renewals for you. Certificates provided by ACM are free. For more information -// about using ACM, see the AWS Certificate Manager User Guide (http://docs.aws.amazon.com/acm/latest/userguide/). +// Updates the name and/or the path of the specified server certificate stored +// in IAM. // -// For more information about working with server certificates, including a -// list of AWS services that can use the server certificates that you manage -// with IAM, go to Working with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) -// in the IAM User Guide. +// For more information about working with server certificates, see Working +// with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) +// in the IAM User Guide. This topic also includes a list of AWS services that +// can use the server certificates that you manage with IAM. // -// For information about the number of server certificates you can upload, see -// Limitations on IAM Entities and Objects (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html) +// You should understand the implications of changing a server certificate's +// path or name. For more information, see Renaming a Server Certificate (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs_manage.html#RenamingServerCerts) // in the IAM User Guide. // -// Because the body of the public key certificate, private key, and the certificate -// chain can be large, you should use POST rather than GET when calling UploadServerCertificate. -// For information about setting up signatures and authorization through the -// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about using the Query -// API with IAM, go to Calling the API by Making HTTP Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/programming.html) +// The person making the request (the principal), must have permission to change +// the server certificate with the old name and the new name. For example, to +// change the certificate named ProductionCert to ProdCert, the principal must +// have a policy that allows them to update both certificates. If the principal +// has permission to update the ProductionCert group, but not the ProdCert certificate, +// then the update fails. For more information about permissions, see Access +// Management (http://docs.aws.amazon.com/IAM/latest/UserGuide/access.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -13158,198 +14233,713 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UploadServerCertificate for usage and error information. +// API operation UpdateServerCertificate for usage and error information. // // Returned Error Codes: -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already // exists. // -// * ErrCodeMalformedCertificateException "MalformedCertificate" -// The request was rejected because the certificate was malformed or expired. -// The error message describes the specific error. -// -// * ErrCodeKeyPairMismatchException "KeyPairMismatch" -// The request was rejected because the public key certificate and the private -// key do not match. +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificate -func (c *IAM) UploadServerCertificate(input *UploadServerCertificateInput) (*UploadServerCertificateOutput, error) { - req, out := c.UploadServerCertificateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificate +func (c *IAM) UpdateServerCertificate(input *UpdateServerCertificateInput) (*UpdateServerCertificateOutput, error) { + req, out := c.UpdateServerCertificateRequest(input) return out, req.Send() } -// UploadServerCertificateWithContext is the same as UploadServerCertificate with the addition of +// UpdateServerCertificateWithContext is the same as UpdateServerCertificate with the addition of // the ability to pass a context and additional request options. // -// See UploadServerCertificate for details on how to use this API operation. +// See UpdateServerCertificate for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UploadServerCertificateWithContext(ctx aws.Context, input *UploadServerCertificateInput, opts ...request.Option) (*UploadServerCertificateOutput, error) { - req, out := c.UploadServerCertificateRequest(input) +func (c *IAM) UpdateServerCertificateWithContext(ctx aws.Context, input *UpdateServerCertificateInput, opts ...request.Option) (*UpdateServerCertificateOutput, error) { + req, out := c.UpdateServerCertificateRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUploadSigningCertificate = "UploadSigningCertificate" +const opUpdateServiceSpecificCredential = "UpdateServiceSpecificCredential" -// UploadSigningCertificateRequest generates a "aws/request.Request" representing the -// client's request for the UploadSigningCertificate operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. +// UpdateServiceSpecificCredentialRequest generates a "aws/request.Request" representing the +// client's request for the UpdateServiceSpecificCredential operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UploadSigningCertificate for more information on using the UploadSigningCertificate +// See UpdateServiceSpecificCredential for more information on using the UpdateServiceSpecificCredential // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UploadSigningCertificateRequest method. -// req, resp := client.UploadSigningCertificateRequest(params) +// // Example sending a request using the UpdateServiceSpecificCredentialRequest method. +// req, resp := client.UpdateServiceSpecificCredentialRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificate -func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInput) (req *request.Request, output *UploadSigningCertificateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredential +func (c *IAM) UpdateServiceSpecificCredentialRequest(input *UpdateServiceSpecificCredentialInput) (req *request.Request, output *UpdateServiceSpecificCredentialOutput) { op := &request.Operation{ - Name: opUploadSigningCertificate, + Name: opUpdateServiceSpecificCredential, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UploadSigningCertificateInput{} + input = &UpdateServiceSpecificCredentialInput{} } - output = &UploadSigningCertificateOutput{} + output = &UpdateServiceSpecificCredentialOutput{} req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UploadSigningCertificate API operation for AWS Identity and Access Management. -// -// Uploads an X.509 signing certificate and associates it with the specified -// IAM user. Some AWS services use X.509 signing certificates to validate requests -// that are signed with a corresponding private key. When you upload the certificate, -// its default status is Active. -// -// If the UserName field is not specified, the IAM user name is determined implicitly -// based on the AWS access key ID used to sign the request. Because this action -// works for access keys under the AWS account, you can use this action to manage -// root credentials even if the AWS account has no associated users. +// UpdateServiceSpecificCredential API operation for AWS Identity and Access Management. // -// Because the body of a X.509 certificate can be large, you should use POST -// rather than GET when calling UploadSigningCertificate. For information about -// setting up signatures and authorization through the API, go to Signing AWS -// API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about using the Query -// API with IAM, go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in the IAM User Guide. +// Sets the status of a service-specific credential to Active or Inactive. Service-specific +// credentials that are inactive cannot be used for authentication to the service. +// This operation can be used to disable a user's service-specific credential +// as part of a credential rotation work flow. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for AWS Identity and Access Management's -// API operation UploadSigningCertificate for usage and error information. +// API operation UpdateServiceSpecificCredential for usage and error information. // // Returned Error Codes: -// * ErrCodeLimitExceededException "LimitExceeded" -// The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. // -// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" -// The request was rejected because it attempted to create a resource that already -// exists. +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredential +func (c *IAM) UpdateServiceSpecificCredential(input *UpdateServiceSpecificCredentialInput) (*UpdateServiceSpecificCredentialOutput, error) { + req, out := c.UpdateServiceSpecificCredentialRequest(input) + return out, req.Send() +} + +// UpdateServiceSpecificCredentialWithContext is the same as UpdateServiceSpecificCredential with the addition of +// the ability to pass a context and additional request options. // -// * ErrCodeMalformedCertificateException "MalformedCertificate" -// The request was rejected because the certificate was malformed or expired. -// The error message describes the specific error. +// See UpdateServiceSpecificCredential for details on how to use this API operation. // -// * ErrCodeInvalidCertificateException "InvalidCertificate" -// The request was rejected because the certificate is invalid. +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) UpdateServiceSpecificCredentialWithContext(ctx aws.Context, input *UpdateServiceSpecificCredentialInput, opts ...request.Option) (*UpdateServiceSpecificCredentialOutput, error) { + req, out := c.UpdateServiceSpecificCredentialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateSigningCertificate = "UpdateSigningCertificate" + +// UpdateSigningCertificateRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSigningCertificate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// * ErrCodeDuplicateCertificateException "DuplicateCertificate" -// The request was rejected because the same certificate is associated with -// an IAM user in the account. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateSigningCertificate for more information on using the UpdateSigningCertificate +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateSigningCertificateRequest method. +// req, resp := client.UpdateSigningCertificateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificate +func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInput) (req *request.Request, output *UpdateSigningCertificateOutput) { + op := &request.Operation{ + Name: opUpdateSigningCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateSigningCertificateInput{} + } + + output = &UpdateSigningCertificateOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateSigningCertificate API operation for AWS Identity and Access Management. +// +// Changes the status of the specified user signing certificate from active +// to disabled, or vice versa. This operation can be used to disable an IAM +// user's signing certificate as part of a certificate rotation work flow. +// +// If the UserName field is not specified, the user name is determined implicitly +// based on the AWS access key ID used to sign the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated users. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation UpdateSigningCertificate for usage and error information. // +// Returned Error Codes: // * ErrCodeNoSuchEntityException "NoSuchEntity" -// The request was rejected because it referenced an entity that does not exist. -// The error message describes the entity. +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception // or failure. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificate -func (c *IAM) UploadSigningCertificate(input *UploadSigningCertificateInput) (*UploadSigningCertificateOutput, error) { - req, out := c.UploadSigningCertificateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificate +func (c *IAM) UpdateSigningCertificate(input *UpdateSigningCertificateInput) (*UpdateSigningCertificateOutput, error) { + req, out := c.UpdateSigningCertificateRequest(input) return out, req.Send() } -// UploadSigningCertificateWithContext is the same as UploadSigningCertificate with the addition of +// UpdateSigningCertificateWithContext is the same as UpdateSigningCertificate with the addition of // the ability to pass a context and additional request options. // -// See UploadSigningCertificate for details on how to use this API operation. +// See UpdateSigningCertificate for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *IAM) UploadSigningCertificateWithContext(ctx aws.Context, input *UploadSigningCertificateInput, opts ...request.Option) (*UploadSigningCertificateOutput, error) { - req, out := c.UploadSigningCertificateRequest(input) +func (c *IAM) UpdateSigningCertificateWithContext(ctx aws.Context, input *UpdateSigningCertificateInput, opts ...request.Option) (*UpdateSigningCertificateOutput, error) { + req, out := c.UpdateSigningCertificateRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// Contains information about an AWS access key. +const opUpdateUser = "UpdateUser" + +// UpdateUserRequest generates a "aws/request.Request" representing the +// client's request for the UpdateUser operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// This data type is used as a response element in the CreateAccessKey and ListAccessKeys -// actions. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// The SecretAccessKey value is returned only in response to CreateAccessKey. -// You can get a secret access key only when you first create an access key; -// you cannot recover the secret access key later. If you lose a secret access -// key, you must create a new access key. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AccessKey -type AccessKey struct { - _ struct{} `type:"structure"` +// See UpdateUser for more information on using the UpdateUser +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateUserRequest method. +// req, resp := client.UpdateUserRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUser +func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, output *UpdateUserOutput) { + op := &request.Operation{ + Name: opUpdateUser, + HTTPMethod: "POST", + HTTPPath: "/", + } - // The ID for this access key. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` + if input == nil { + input = &UpdateUserInput{} + } - // The date when the access key was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + output = &UpdateUserOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} - // The secret key used to sign requests. - // +// UpdateUser API operation for AWS Identity and Access Management. +// +// Updates the name and/or the path of the specified IAM user. +// +// You should understand the implications of changing an IAM user's path or +// name. For more information, see Renaming an IAM User (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_renaming) +// and Renaming an IAM Group (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html) +// in the IAM User Guide. +// +// To change a user name, the requester must have appropriate permissions on +// both the source object and the target object. For example, to change Bob +// to Robert, the entity making the request must have permission on Bob and +// Robert, or must have permission on all (*). For more information about permissions, +// see Permissions and Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PermissionsAndPolicies.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation UpdateUser for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. +// +// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" +// The request was rejected because it attempted to create a resource that already +// exists. +// +// * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" +// The request was rejected because it referenced an entity that is temporarily +// unmodifiable, such as a user name that was deleted and then recreated. The +// error indicates that the request is likely to succeed if you try again after +// waiting several minutes. The error message describes the entity. +// +// * ErrCodeConcurrentModificationException "ConcurrentModification" +// The request was rejected because multiple requests to change this object +// were submitted simultaneously. Wait a few minutes and submit your request +// again. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUser +func (c *IAM) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { + req, out := c.UpdateUserRequest(input) + return out, req.Send() +} + +// UpdateUserWithContext is the same as UpdateUser with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateUser for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) UpdateUserWithContext(ctx aws.Context, input *UpdateUserInput, opts ...request.Option) (*UpdateUserOutput, error) { + req, out := c.UpdateUserRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUploadSSHPublicKey = "UploadSSHPublicKey" + +// UploadSSHPublicKeyRequest generates a "aws/request.Request" representing the +// client's request for the UploadSSHPublicKey operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UploadSSHPublicKey for more information on using the UploadSSHPublicKey +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UploadSSHPublicKeyRequest method. +// req, resp := client.UploadSSHPublicKeyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey +func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *request.Request, output *UploadSSHPublicKeyOutput) { + op := &request.Operation{ + Name: opUploadSSHPublicKey, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UploadSSHPublicKeyInput{} + } + + output = &UploadSSHPublicKeyOutput{} + req = c.newRequest(op, input, output) + return +} + +// UploadSSHPublicKey API operation for AWS Identity and Access Management. +// +// Uploads an SSH public key and associates it with the specified IAM user. +// +// The SSH public key uploaded by this operation can be used only for authenticating +// the associated IAM user to an AWS CodeCommit repository. For more information +// about using SSH keys to authenticate to an AWS CodeCommit repository, see +// Set up AWS CodeCommit for SSH Connections (http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html) +// in the AWS CodeCommit User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation UploadSSHPublicKey for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. +// +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeInvalidPublicKeyException "InvalidPublicKey" +// The request was rejected because the public key is malformed or otherwise +// invalid. +// +// * ErrCodeDuplicateSSHPublicKeyException "DuplicateSSHPublicKey" +// The request was rejected because the SSH public key is already associated +// with the specified IAM user. +// +// * ErrCodeUnrecognizedPublicKeyEncodingException "UnrecognizedPublicKeyEncoding" +// The request was rejected because the public key encoding format is unsupported +// or unrecognized. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKey +func (c *IAM) UploadSSHPublicKey(input *UploadSSHPublicKeyInput) (*UploadSSHPublicKeyOutput, error) { + req, out := c.UploadSSHPublicKeyRequest(input) + return out, req.Send() +} + +// UploadSSHPublicKeyWithContext is the same as UploadSSHPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See UploadSSHPublicKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) UploadSSHPublicKeyWithContext(ctx aws.Context, input *UploadSSHPublicKeyInput, opts ...request.Option) (*UploadSSHPublicKeyOutput, error) { + req, out := c.UploadSSHPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUploadServerCertificate = "UploadServerCertificate" + +// UploadServerCertificateRequest generates a "aws/request.Request" representing the +// client's request for the UploadServerCertificate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UploadServerCertificate for more information on using the UploadServerCertificate +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UploadServerCertificateRequest method. +// req, resp := client.UploadServerCertificateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificate +func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput) (req *request.Request, output *UploadServerCertificateOutput) { + op := &request.Operation{ + Name: opUploadServerCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UploadServerCertificateInput{} + } + + output = &UploadServerCertificateOutput{} + req = c.newRequest(op, input, output) + return +} + +// UploadServerCertificate API operation for AWS Identity and Access Management. +// +// Uploads a server certificate entity for the AWS account. The server certificate +// entity includes a public key certificate, a private key, and an optional +// certificate chain, which should all be PEM-encoded. +// +// We recommend that you use AWS Certificate Manager (http://docs.aws.amazon.com/certificate-manager/) +// to provision, manage, and deploy your server certificates. With ACM you can +// request a certificate, deploy it to AWS resources, and let ACM handle certificate +// renewals for you. Certificates provided by ACM are free. For more information +// about using ACM, see the AWS Certificate Manager User Guide (http://docs.aws.amazon.com/acm/latest/userguide/). +// +// For more information about working with server certificates, see Working +// with Server Certificates (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) +// in the IAM User Guide. This topic includes a list of AWS services that can +// use the server certificates that you manage with IAM. +// +// For information about the number of server certificates you can upload, see +// Limitations on IAM Entities and Objects (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html) +// in the IAM User Guide. +// +// Because the body of the public key certificate, private key, and the certificate +// chain can be large, you should use POST rather than GET when calling UploadServerCertificate. +// For information about setting up signatures and authorization through the +// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) +// in the AWS General Reference. For general information about using the Query +// API with IAM, go to Calling the API by Making HTTP Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/programming.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation UploadServerCertificate for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. +// +// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" +// The request was rejected because it attempted to create a resource that already +// exists. +// +// * ErrCodeMalformedCertificateException "MalformedCertificate" +// The request was rejected because the certificate was malformed or expired. +// The error message describes the specific error. +// +// * ErrCodeKeyPairMismatchException "KeyPairMismatch" +// The request was rejected because the public key certificate and the private +// key do not match. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificate +func (c *IAM) UploadServerCertificate(input *UploadServerCertificateInput) (*UploadServerCertificateOutput, error) { + req, out := c.UploadServerCertificateRequest(input) + return out, req.Send() +} + +// UploadServerCertificateWithContext is the same as UploadServerCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UploadServerCertificate for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) UploadServerCertificateWithContext(ctx aws.Context, input *UploadServerCertificateInput, opts ...request.Option) (*UploadServerCertificateOutput, error) { + req, out := c.UploadServerCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUploadSigningCertificate = "UploadSigningCertificate" + +// UploadSigningCertificateRequest generates a "aws/request.Request" representing the +// client's request for the UploadSigningCertificate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UploadSigningCertificate for more information on using the UploadSigningCertificate +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UploadSigningCertificateRequest method. +// req, resp := client.UploadSigningCertificateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificate +func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInput) (req *request.Request, output *UploadSigningCertificateOutput) { + op := &request.Operation{ + Name: opUploadSigningCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UploadSigningCertificateInput{} + } + + output = &UploadSigningCertificateOutput{} + req = c.newRequest(op, input, output) + return +} + +// UploadSigningCertificate API operation for AWS Identity and Access Management. +// +// Uploads an X.509 signing certificate and associates it with the specified +// IAM user. Some AWS services use X.509 signing certificates to validate requests +// that are signed with a corresponding private key. When you upload the certificate, +// its default status is Active. +// +// If the UserName field is not specified, the IAM user name is determined implicitly +// based on the AWS access key ID used to sign the request. This operation works +// for access keys under the AWS account. Consequently, you can use this operation +// to manage AWS account root user credentials even if the AWS account has no +// associated users. +// +// Because the body of an X.509 certificate can be large, you should use POST +// rather than GET when calling UploadSigningCertificate. For information about +// setting up signatures and authorization through the API, go to Signing AWS +// API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) +// in the AWS General Reference. For general information about using the Query +// API with IAM, go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) +// in the IAM User Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Identity and Access Management's +// API operation UploadSigningCertificate for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededException "LimitExceeded" +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error message describes the limit exceeded. +// +// * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" +// The request was rejected because it attempted to create a resource that already +// exists. +// +// * ErrCodeMalformedCertificateException "MalformedCertificate" +// The request was rejected because the certificate was malformed or expired. +// The error message describes the specific error. +// +// * ErrCodeInvalidCertificateException "InvalidCertificate" +// The request was rejected because the certificate is invalid. +// +// * ErrCodeDuplicateCertificateException "DuplicateCertificate" +// The request was rejected because the same certificate is associated with +// an IAM user in the account. +// +// * ErrCodeNoSuchEntityException "NoSuchEntity" +// The request was rejected because it referenced a resource entity that does +// not exist. The error message describes the resource. +// +// * ErrCodeServiceFailureException "ServiceFailure" +// The request processing has failed because of an unknown error, exception +// or failure. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificate +func (c *IAM) UploadSigningCertificate(input *UploadSigningCertificateInput) (*UploadSigningCertificateOutput, error) { + req, out := c.UploadSigningCertificateRequest(input) + return out, req.Send() +} + +// UploadSigningCertificateWithContext is the same as UploadSigningCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See UploadSigningCertificate for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IAM) UploadSigningCertificateWithContext(ctx aws.Context, input *UploadSigningCertificateInput, opts ...request.Option) (*UploadSigningCertificateOutput, error) { + req, out := c.UploadSigningCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Contains information about an AWS access key. +// +// This data type is used as a response element in the CreateAccessKey and ListAccessKeys +// operations. +// +// The SecretAccessKey value is returned only in response to CreateAccessKey. +// You can get a secret access key only when you first create an access key; +// you cannot recover the secret access key later. If you lose a secret access +// key, you must create a new access key. +type AccessKey struct { + _ struct{} `type:"structure"` + + // The ID for this access key. + // + // AccessKeyId is a required field + AccessKeyId *string `min:"16" type:"string" required:"true"` + + // The date when the access key was created. + CreateDate *time.Time `type:"timestamp"` + + // The secret key used to sign requests. + // // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` + SecretAccessKey *string `type:"string" required:"true" sensitive:"true"` - // The status of the access key. Active means the key is valid for API calls, - // while Inactive means it is not. + // The status of the access key. Active means that the key is valid for API + // calls, while Inactive means it is not. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` @@ -13400,34 +14990,35 @@ func (s *AccessKey) SetUserName(v string) *AccessKey { return s } -// Contains information about the last time an AWS access key was used. +// Contains information about the last time an AWS access key was used since +// IAM began tracking this information on April 22, 2015. // // This data type is used as a response element in the GetAccessKeyLastUsed -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AccessKeyLastUsed +// operation. type AccessKeyLastUsed struct { _ struct{} `type:"structure"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), - // when the access key was most recently used. This field is null when: + // when the access key was most recently used. This field is null in the following + // situations: // // * The user does not have an access key. // - // * An access key exists but has never been used, at least not since IAM - // started tracking this information on April 22nd, 2015. + // * An access key exists but has not been used since IAM began tracking + // this information. // // * There is no sign-in data associated with the user // // LastUsedDate is a required field - LastUsedDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + LastUsedDate *time.Time `type:"timestamp" required:"true"` - // The AWS region where this access key was most recently used. This field is - // displays "N/A" when: + // The AWS region where this access key was most recently used. The value for + // this field is "N/A" in the following situations: // // * The user does not have an access key. // - // * An access key exists but has never been used, at least not since IAM - // started tracking this information on April 22nd, 2015. + // * An access key exists but has not been used since IAM began tracking + // this information. // // * There is no sign-in data associated with the user // @@ -13438,12 +15029,12 @@ type AccessKeyLastUsed struct { Region *string `type:"string" required:"true"` // The name of the AWS service with which this access key was most recently - // used. This field displays "N/A" when: + // used. The value of this field is "N/A" in the following situations: // // * The user does not have an access key. // - // * An access key exists but has never been used, at least not since IAM - // started tracking this information on April 22nd, 2015. + // * An access key exists but has not been used since IAM started tracking + // this information. // // * There is no sign-in data associated with the user // @@ -13481,8 +15072,7 @@ func (s *AccessKeyLastUsed) SetServiceName(v string) *AccessKeyLastUsed { // Contains information about an AWS access key, without its secret key. // -// This data type is used as a response element in the ListAccessKeys action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AccessKeyMetadata +// This data type is used as a response element in the ListAccessKeys operation. type AccessKeyMetadata struct { _ struct{} `type:"structure"` @@ -13490,10 +15080,10 @@ type AccessKeyMetadata struct { AccessKeyId *string `min:"16" type:"string"` // The date when the access key was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` - // The status of the access key. Active means the key is valid for API calls; - // Inactive means it is not. + // The status of the access key. Active means that the key is valid for API + // calls; Inactive means it is not. Status *string `type:"string" enum:"statusType"` // The name of the IAM user that the key is associated with. @@ -13534,7 +15124,6 @@ func (s *AccessKeyMetadata) SetUserName(v string) *AccessKeyMetadata { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProviderRequest type AddClientIDToOpenIDConnectProviderInput struct { _ struct{} `type:"structure"` @@ -13546,7 +15135,7 @@ type AddClientIDToOpenIDConnectProviderInput struct { // The Amazon Resource Name (ARN) of the IAM OpenID Connect (OIDC) provider // resource to add the client ID to. You can get a list of OIDC provider ARNs - // by using the ListOpenIDConnectProviders action. + // by using the ListOpenIDConnectProviders operation. // // OpenIDConnectProviderArn is a required field OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` @@ -13596,7 +15185,6 @@ func (s *AddClientIDToOpenIDConnectProviderInput) SetOpenIDConnectProviderArn(v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddClientIDToOpenIDConnectProviderOutput type AddClientIDToOpenIDConnectProviderOutput struct { _ struct{} `type:"structure"` } @@ -13611,22 +15199,21 @@ func (s AddClientIDToOpenIDConnectProviderOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfileRequest type AddRoleToInstanceProfileInput struct { _ struct{} `type:"structure"` // The name of the instance profile to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // InstanceProfileName is a required field InstanceProfileName *string `min:"1" type:"string" required:"true"` // The name of the role to add. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -13678,7 +15265,6 @@ func (s *AddRoleToInstanceProfileInput) SetRoleName(v string) *AddRoleToInstance return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddRoleToInstanceProfileOutput type AddRoleToInstanceProfileOutput struct { _ struct{} `type:"structure"` } @@ -13693,24 +15279,23 @@ func (s AddRoleToInstanceProfileOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroupRequest type AddUserToGroupInput struct { _ struct{} `type:"structure"` // The name of the group to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` // The name of the user to add. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -13760,7 +15345,6 @@ func (s *AddUserToGroupInput) SetUserName(v string) *AddUserToGroupInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AddUserToGroupOutput type AddUserToGroupOutput struct { _ struct{} `type:"structure"` } @@ -13775,15 +15359,14 @@ func (s AddUserToGroupOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicyRequest type AttachGroupPolicyInput struct { _ struct{} `type:"structure"` // The name (friendly name, not ARN) of the group to attach the policy to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -13842,7 +15425,6 @@ func (s *AttachGroupPolicyInput) SetPolicyArn(v string) *AttachGroupPolicyInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachGroupPolicyOutput type AttachGroupPolicyOutput struct { _ struct{} `type:"structure"` } @@ -13857,7 +15439,6 @@ func (s AttachGroupPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicyRequest type AttachRolePolicyInput struct { _ struct{} `type:"structure"` @@ -13872,7 +15453,7 @@ type AttachRolePolicyInput struct { // The name (friendly name, not ARN) of the role to attach the policy to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -13924,7 +15505,6 @@ func (s *AttachRolePolicyInput) SetRoleName(v string) *AttachRolePolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachRolePolicyOutput type AttachRolePolicyOutput struct { _ struct{} `type:"structure"` } @@ -13939,7 +15519,6 @@ func (s AttachRolePolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicyRequest type AttachUserPolicyInput struct { _ struct{} `type:"structure"` @@ -13954,9 +15533,9 @@ type AttachUserPolicyInput struct { // The name (friendly name, not ARN) of the IAM user to attach the policy to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -14006,7 +15585,6 @@ func (s *AttachUserPolicyInput) SetUserName(v string) *AttachUserPolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachUserPolicyOutput type AttachUserPolicyOutput struct { _ struct{} `type:"structure"` } @@ -14021,17 +15599,59 @@ func (s AttachUserPolicyOutput) GoString() string { return s.String() } +// Contains information about an attached permissions boundary. +// +// An attached permissions boundary is a managed policy that has been attached +// to a user or role to set the permissions boundary. +// +// For more information about permissions boundaries, see Permissions Boundaries +// for IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) +// in the IAM User Guide. +type AttachedPermissionsBoundary struct { + _ struct{} `type:"structure"` + + // The ARN of the policy used to set the permissions boundary for the user or + // role. + PermissionsBoundaryArn *string `min:"20" type:"string"` + + // The permissions boundary usage type that indicates what type of IAM resource + // is used as the permissions boundary for an entity. This data type can only + // have a value of Policy. + PermissionsBoundaryType *string `type:"string" enum:"PermissionsBoundaryAttachmentType"` +} + +// String returns the string representation +func (s AttachedPermissionsBoundary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachedPermissionsBoundary) GoString() string { + return s.String() +} + +// SetPermissionsBoundaryArn sets the PermissionsBoundaryArn field's value. +func (s *AttachedPermissionsBoundary) SetPermissionsBoundaryArn(v string) *AttachedPermissionsBoundary { + s.PermissionsBoundaryArn = &v + return s +} + +// SetPermissionsBoundaryType sets the PermissionsBoundaryType field's value. +func (s *AttachedPermissionsBoundary) SetPermissionsBoundaryType(v string) *AttachedPermissionsBoundary { + s.PermissionsBoundaryType = &v + return s +} + // Contains information about an attached policy. // // An attached policy is a managed policy that has been attached to a user, // group, or role. This data type is used as a response element in the ListAttachedGroupPolicies, // ListAttachedRolePolicies, ListAttachedUserPolicies, and GetAccountAuthorizationDetails -// actions. +// operations. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/AttachedPolicy type AttachedPolicy struct { _ struct{} `type:"structure"` @@ -14068,29 +15688,28 @@ func (s *AttachedPolicy) SetPolicyName(v string) *AttachedPolicy { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePasswordRequest type ChangePasswordInput struct { _ struct{} `type:"structure"` // The new password. The new password must conform to the AWS account's password // policy, if one exists. // - // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of almost any printable ASCII - // character from the space (\u0020) through the end of the ASCII character - // range (\u00FF). You can also include the tab (\u0009), line feed (\u000A), - // and carriage return (\u000D) characters. Although any of these characters - // are valid in a password, note that many tools, such as the AWS Management - // Console, might restrict the ability to enter certain characters because they - // have special meaning within that tool. + // The regex pattern (http://wikipedia.org/wiki/regex) that is used to validate + // this parameter is a string of characters. That string can include almost + // any printable ASCII character from the space (\u0020) through the end of + // the ASCII character range (\u00FF). You can also include the tab (\u0009), + // line feed (\u000A), and carriage return (\u000D) characters. Any of these + // characters are valid in a password. However, many tools, such as the AWS + // Management Console, might restrict the ability to type certain characters + // because they have special meaning within that tool. // // NewPassword is a required field - NewPassword *string `min:"1" type:"string" required:"true"` + NewPassword *string `min:"1" type:"string" required:"true" sensitive:"true"` // The IAM user's current password. // // OldPassword is a required field - OldPassword *string `min:"1" type:"string" required:"true"` + OldPassword *string `min:"1" type:"string" required:"true" sensitive:"true"` } // String returns the string representation @@ -14137,7 +15756,6 @@ func (s *ChangePasswordInput) SetOldPassword(v string) *ChangePasswordInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ChangePasswordOutput type ChangePasswordOutput struct { _ struct{} `type:"structure"` } @@ -14159,7 +15777,6 @@ func (s ChangePasswordOutput) GoString() string { // // This data type is used as an input parameter to SimulateCustomPolicy and // SimulateCustomPolicy. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ContextEntry type ContextEntry struct { _ struct{} `type:"structure"` @@ -14172,8 +15789,8 @@ type ContextEntry struct { ContextKeyType *string `type:"string" enum:"ContextKeyTypeEnum"` // The value (or values, if the condition context key supports multiple values) - // to provide to the simulation for use when the key is referenced by a Condition - // element in an input policy. + // to provide to the simulation when the key is referenced by a Condition element + // in an input policy. ContextKeyValues []*string `type:"list"` } @@ -14218,15 +15835,14 @@ func (s *ContextEntry) SetContextKeyValues(v []*string) *ContextEntry { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKeyRequest type CreateAccessKeyInput struct { _ struct{} `type:"structure"` // The name of the IAM user that the new key will belong to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -14260,7 +15876,6 @@ func (s *CreateAccessKeyInput) SetUserName(v string) *CreateAccessKeyInput { } // Contains the response to a successful CreateAccessKey request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccessKeyResponse type CreateAccessKeyOutput struct { _ struct{} `type:"structure"` @@ -14286,13 +15901,12 @@ func (s *CreateAccessKeyOutput) SetAccessKey(v *AccessKey) *CreateAccessKeyOutpu return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAliasRequest type CreateAccountAliasInput struct { _ struct{} `type:"structure"` // The account alias to create. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of lowercase letters, digits, and dashes. // You cannot start or finish with a dash, nor can you have two dashes in a // row. @@ -14333,7 +15947,6 @@ func (s *CreateAccountAliasInput) SetAccountAlias(v string) *CreateAccountAliasI return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateAccountAliasOutput type CreateAccountAliasOutput struct { _ struct{} `type:"structure"` } @@ -14348,15 +15961,14 @@ func (s CreateAccountAliasOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroupRequest type CreateGroupInput struct { _ struct{} `type:"structure"` // The name of the group to create. Do not include the path in this value. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-. + // with no spaces. You can also include any of the following characters: _+=,.@-. // The group name must be unique within the account. Group names are not distinguished // by case. For example, you cannot create groups named both "ADMINS" and "admins". // @@ -14370,11 +15982,12 @@ type CreateGroupInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `min:"1" type:"string"` } @@ -14420,7 +16033,6 @@ func (s *CreateGroupInput) SetPath(v string) *CreateGroupInput { } // Contains the response to a successful CreateGroup request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateGroupResponse type CreateGroupOutput struct { _ struct{} `type:"structure"` @@ -14446,15 +16058,14 @@ func (s *CreateGroupOutput) SetGroup(v *Group) *CreateGroupOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfileRequest type CreateInstanceProfileInput struct { _ struct{} `type:"structure"` // The name of the instance profile to create. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // InstanceProfileName is a required field InstanceProfileName *string `min:"1" type:"string" required:"true"` @@ -14466,11 +16077,12 @@ type CreateInstanceProfileInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `min:"1" type:"string"` } @@ -14516,7 +16128,6 @@ func (s *CreateInstanceProfileInput) SetPath(v string) *CreateInstanceProfileInp } // Contains the response to a successful CreateInstanceProfile request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateInstanceProfileResponse type CreateInstanceProfileOutput struct { _ struct{} `type:"structure"` @@ -14542,23 +16153,22 @@ func (s *CreateInstanceProfileOutput) SetInstanceProfile(v *InstanceProfile) *Cr return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfileRequest type CreateLoginProfileInput struct { _ struct{} `type:"structure"` // The new password for the user. // - // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of almost any printable ASCII - // character from the space (\u0020) through the end of the ASCII character - // range (\u00FF). You can also include the tab (\u0009), line feed (\u000A), - // and carriage return (\u000D) characters. Although any of these characters - // are valid in a password, note that many tools, such as the AWS Management - // Console, might restrict the ability to enter certain characters because they - // have special meaning within that tool. + // The regex pattern (http://wikipedia.org/wiki/regex) that is used to validate + // this parameter is a string of characters. That string can include almost + // any printable ASCII character from the space (\u0020) through the end of + // the ASCII character range (\u00FF). You can also include the tab (\u0009), + // line feed (\u000A), and carriage return (\u000D) characters. Any of these + // characters are valid in a password. However, many tools, such as the AWS + // Management Console, might restrict the ability to type certain characters + // because they have special meaning within that tool. // // Password is a required field - Password *string `min:"1" type:"string" required:"true"` + Password *string `min:"1" type:"string" required:"true" sensitive:"true"` // Specifies whether the user is required to set a new password on next sign-in. PasswordResetRequired *bool `type:"boolean"` @@ -14566,9 +16176,9 @@ type CreateLoginProfileInput struct { // The name of the IAM user to create a password for. The user must already // exist. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -14625,7 +16235,6 @@ func (s *CreateLoginProfileInput) SetUserName(v string) *CreateLoginProfileInput } // Contains the response to a successful CreateLoginProfile request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateLoginProfileResponse type CreateLoginProfileOutput struct { _ struct{} `type:"structure"` @@ -14651,7 +16260,6 @@ func (s *CreateLoginProfileOutput) SetLoginProfile(v *LoginProfile) *CreateLogin return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProviderRequest type CreateOpenIDConnectProviderInput struct { _ struct{} `type:"structure"` @@ -14665,11 +16273,11 @@ type CreateOpenIDConnectProviderInput struct { // cannot register more than 100 client IDs with a single IAM OIDC provider. // // There is no defined format for a client ID. The CreateOpenIDConnectProviderRequest - // action accepts client IDs up to 255 characters long. + // operation accepts client IDs up to 255 characters long. ClientIDList []*string `type:"list"` // A list of server certificate thumbprints for the OpenID Connect (OIDC) identity - // provider's server certificate(s). Typically this list includes only one entry. + // provider's server certificates. Typically this list includes only one entry. // However, IAM lets you have up to five thumbprints for an OIDC provider. This // lets you maintain multiple thumbprints if the identity provider is rotating // certificates. @@ -14679,10 +16287,10 @@ type CreateOpenIDConnectProviderInput struct { // makes its keys available. It is always a 40-character string. // // You must provide at least one thumbprint when creating an IAM OIDC provider. - // For example, if the OIDC provider is server.example.com and the provider - // stores its keys at "https://keys.server.example.com/openid-connect", the - // thumbprint string would be the hex-encoded SHA-1 hash value of the certificate - // used by https://keys.server.example.com. + // For example, assume that the OIDC provider is server.example.com and the + // provider stores its keys at https://keys.server.example.com/openid-connect. + // In that case, the thumbprint string would be the hex-encoded SHA-1 hash value + // of the certificate used by https://keys.server.example.com. // // For more information about obtaining the OIDC provider's thumbprint, see // Obtaining the Thumbprint for an OpenID Connect Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html) @@ -14691,11 +16299,11 @@ type CreateOpenIDConnectProviderInput struct { // ThumbprintList is a required field ThumbprintList []*string `type:"list" required:"true"` - // The URL of the identity provider. The URL must begin with "https://" and - // should correspond to the iss claim in the provider's OpenID Connect ID tokens. - // Per the OIDC standard, path components are allowed but query parameters are - // not. Typically the URL consists of only a host name, like "https://server.example.org" - // or "https://example.com". + // The URL of the identity provider. The URL must begin with https:// and should + // correspond to the iss claim in the provider's OpenID Connect ID tokens. Per + // the OIDC standard, path components are allowed but query parameters are not. + // Typically the URL consists of only a hostname, like https://server.example.org + // or https://example.com. // // You cannot register the same provider multiple times in a single AWS account. // If you try to submit a URL that has already been used for an OpenID Connect @@ -14753,7 +16361,6 @@ func (s *CreateOpenIDConnectProviderInput) SetUrl(v string) *CreateOpenIDConnect } // Contains the response to a successful CreateOpenIDConnectProvider request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateOpenIDConnectProviderResponse type CreateOpenIDConnectProviderOutput struct { _ struct{} `type:"structure"` @@ -14778,7 +16385,6 @@ func (s *CreateOpenIDConnectProviderOutput) SetOpenIDConnectProviderArn(v string return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyRequest type CreatePolicyInput struct { _ struct{} `type:"structure"` @@ -14799,31 +16405,37 @@ type CreatePolicyInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `type:"string"` // The JSON policy document that you want to use as the content for the new // policy. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` // The friendly name of the policy. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -14886,7 +16498,6 @@ func (s *CreatePolicyInput) SetPolicyName(v string) *CreatePolicyInput { } // Contains the response to a successful CreatePolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyResponse type CreatePolicyOutput struct { _ struct{} `type:"structure"` @@ -14910,7 +16521,6 @@ func (s *CreatePolicyOutput) SetPolicy(v *Policy) *CreatePolicyOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersionRequest type CreatePolicyVersionInput struct { _ struct{} `type:"structure"` @@ -14928,11 +16538,16 @@ type CreatePolicyVersionInput struct { // version of the policy. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` @@ -14940,8 +16555,8 @@ type CreatePolicyVersionInput struct { // Specifies whether to set this version as the policy's default version. // // When this parameter is true, the new policy version becomes the operative - // version; that is, the version that is in effect for the IAM users, groups, - // and roles that the policy is attached to. + // version. That is, it becomes the version that is in effect for the IAM users, + // groups, and roles that the policy is attached to. // // For more information about managed policy versions, see Versioning for Managed // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) @@ -15000,7 +16615,6 @@ func (s *CreatePolicyVersionInput) SetSetAsDefault(v bool) *CreatePolicyVersionI } // Contains the response to a successful CreatePolicyVersion request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreatePolicyVersionResponse type CreatePolicyVersionOutput struct { _ struct{} `type:"structure"` @@ -15024,7 +16638,6 @@ func (s *CreatePolicyVersionOutput) SetPolicyVersion(v *PolicyVersion) *CreatePo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRoleRequest type CreateRoleInput struct { _ struct{} `type:"structure"` @@ -15032,18 +16645,39 @@ type CreateRoleInput struct { // assume the role. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // AssumeRolePolicyDocument is a required field AssumeRolePolicyDocument *string `min:"1" type:"string" required:"true"` - // A customer-provided description of the role. + // A description of the role. Description *string `type:"string"` + // The maximum session duration (in seconds) that you want to set for the specified + // role. If you do not specify a value for this setting, the default maximum + // of one hour is applied. This setting can have a value from 1 hour to 12 hours. + // + // Anyone who assumes the role from the AWS CLI or API can use the DurationSeconds + // API parameter or the duration-seconds CLI parameter to request a longer session. + // The MaxSessionDuration setting determines the maximum duration that can be + // requested using the DurationSeconds parameter. If users don't specify a value + // for the DurationSeconds parameter, their security credentials are valid for + // one hour by default. This applies when you use the AssumeRole* API operations + // or the assume-role* CLI operations but does not apply when you use those + // operations to create a console URL. For more information, see Using IAM Roles + // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) in the + // IAM User Guide. + MaxSessionDuration *int64 `min:"3600" type:"integer"` + // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the IAM User Guide. @@ -15051,16 +16685,21 @@ type CreateRoleInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `min:"1" type:"string"` + // The ARN of the policy that is used to set the permissions boundary for the + // role. + PermissionsBoundary *string `min:"20" type:"string"` + // The name of the role to create. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -15069,6 +16708,15 @@ type CreateRoleInput struct { // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` + + // A list of tags that you want to attach to the newly created role. Each tag + // consists of a key name and an associated value. For more information about + // tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + // + // If any one of the tags is invalid or if you exceed the allowed number of + // tags per role, then the entire request fails and the role is not created. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -15090,15 +16738,31 @@ func (s *CreateRoleInput) Validate() error { if s.AssumeRolePolicyDocument != nil && len(*s.AssumeRolePolicyDocument) < 1 { invalidParams.Add(request.NewErrParamMinLen("AssumeRolePolicyDocument", 1)) } + if s.MaxSessionDuration != nil && *s.MaxSessionDuration < 3600 { + invalidParams.Add(request.NewErrParamMinValue("MaxSessionDuration", 3600)) + } if s.Path != nil && len(*s.Path) < 1 { invalidParams.Add(request.NewErrParamMinLen("Path", 1)) } + if s.PermissionsBoundary != nil && len(*s.PermissionsBoundary) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PermissionsBoundary", 20)) + } if s.RoleName == nil { invalidParams.Add(request.NewErrParamRequired("RoleName")) } if s.RoleName != nil && len(*s.RoleName) < 1 { invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -15118,20 +16782,37 @@ func (s *CreateRoleInput) SetDescription(v string) *CreateRoleInput { return s } +// SetMaxSessionDuration sets the MaxSessionDuration field's value. +func (s *CreateRoleInput) SetMaxSessionDuration(v int64) *CreateRoleInput { + s.MaxSessionDuration = &v + return s +} + // SetPath sets the Path field's value. func (s *CreateRoleInput) SetPath(v string) *CreateRoleInput { s.Path = &v return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *CreateRoleInput) SetPermissionsBoundary(v string) *CreateRoleInput { + s.PermissionsBoundary = &v + return s +} + // SetRoleName sets the RoleName field's value. func (s *CreateRoleInput) SetRoleName(v string) *CreateRoleInput { s.RoleName = &v return s } +// SetTags sets the Tags field's value. +func (s *CreateRoleInput) SetTags(v []*Tag) *CreateRoleInput { + s.Tags = v + return s +} + // Contains the response to a successful CreateRole request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateRoleResponse type CreateRoleOutput struct { _ struct{} `type:"structure"` @@ -15157,15 +16838,14 @@ func (s *CreateRoleOutput) SetRole(v *Role) *CreateRoleOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProviderRequest type CreateSAMLProviderInput struct { _ struct{} `type:"structure"` // The name of the provider to create. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -15228,7 +16908,6 @@ func (s *CreateSAMLProviderInput) SetSAMLMetadataDocument(v string) *CreateSAMLP } // Contains the response to a successful CreateSAMLProvider request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateSAMLProviderResponse type CreateSAMLProviderOutput struct { _ struct{} `type:"structure"` @@ -15252,21 +16931,29 @@ func (s *CreateSAMLProviderOutput) SetSAMLProviderArn(v string) *CreateSAMLProvi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRoleRequest type CreateServiceLinkedRoleInput struct { _ struct{} `type:"structure"` - // The AWS service to which this role is attached. You use a string similar - // to a URL but without the http:// in front. For example: elasticbeanstalk.amazonaws.com + // The service principal for the AWS service to which this role is attached. + // You use a string similar to a URL but without the http:// in front. For example: + // elasticbeanstalk.amazonaws.com. + // + // Service principals are unique and case-sensitive. To find the exact service + // principal for your service-linked role, see AWS Services That Work with IAM + // (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) + // in the IAM User Guide and look for the services that have Yes in the Service-Linked + // Role column. Choose the Yes link to view the service-linked role documentation + // for that service. // // AWSServiceName is a required field AWSServiceName *string `min:"1" type:"string" required:"true"` - // A string that you provide, which is combined with the service name to form - // the complete role name. If you make multiple requests for the same service, - // then you must supply a different CustomSuffix for each request. Otherwise - // the request fails with a duplicate role name error. For example, you could - // add -1 or -debug to the suffix. + // A string that you provide, which is combined with the service-provided prefix + // to form the complete role name. If you make multiple requests for the same + // service, then you must supply a different CustomSuffixfor each request. Otherwise the request fails with a duplicate role name + // error. For example, you could add -1or -debugto the suffix. + // + // Some services do not support the CustomSuffix CustomSuffix *string `min:"1" type:"string"` // The description of the role. @@ -15320,7 +17007,6 @@ func (s *CreateServiceLinkedRoleInput) SetDescription(v string) *CreateServiceLi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceLinkedRoleResponse type CreateServiceLinkedRoleOutput struct { _ struct{} `type:"structure"` @@ -15344,7 +17030,6 @@ func (s *CreateServiceLinkedRoleOutput) SetRole(v *Role) *CreateServiceLinkedRol return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredentialRequest type CreateServiceSpecificCredentialInput struct { _ struct{} `type:"structure"` @@ -15359,9 +17044,9 @@ type CreateServiceSpecificCredentialInput struct { // new service-specific credentials have the same permissions as the associated // user except that they can be used only to access the specified service. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -15408,7 +17093,6 @@ func (s *CreateServiceSpecificCredentialInput) SetUserName(v string) *CreateServ return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateServiceSpecificCredentialResponse type CreateServiceSpecificCredentialOutput struct { _ struct{} `type:"structure"` @@ -15437,7 +17121,6 @@ func (s *CreateServiceSpecificCredentialOutput) SetServiceSpecificCredential(v * return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUserRequest type CreateUserInput struct { _ struct{} `type:"structure"` @@ -15448,18 +17131,32 @@ type CreateUserInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `min:"1" type:"string"` + // The ARN of the policy that is used to set the permissions boundary for the + // user. + PermissionsBoundary *string `min:"20" type:"string"` + + // A list of tags that you want to attach to the newly created user. Each tag + // consists of a key name and an associated value. For more information about + // tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + // + // If any one of the tags is invalid or if you exceed the allowed number of + // tags per user, then the entire request fails and the user is not created. + Tags []*Tag `type:"list"` + // The name of the user to create. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-. + // with no spaces. You can also include any of the following characters: _+=,.@-. // User names are not distinguished by case. For example, you cannot create // users named both "TESTUSER" and "testuser". // @@ -15483,12 +17180,25 @@ func (s *CreateUserInput) Validate() error { if s.Path != nil && len(*s.Path) < 1 { invalidParams.Add(request.NewErrParamMinLen("Path", 1)) } + if s.PermissionsBoundary != nil && len(*s.PermissionsBoundary) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PermissionsBoundary", 20)) + } if s.UserName == nil { invalidParams.Add(request.NewErrParamRequired("UserName")) } if s.UserName != nil && len(*s.UserName) < 1 { invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -15502,6 +17212,18 @@ func (s *CreateUserInput) SetPath(v string) *CreateUserInput { return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *CreateUserInput) SetPermissionsBoundary(v string) *CreateUserInput { + s.PermissionsBoundary = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateUserInput) SetTags(v []*Tag) *CreateUserInput { + s.Tags = v + return s +} + // SetUserName sets the UserName field's value. func (s *CreateUserInput) SetUserName(v string) *CreateUserInput { s.UserName = &v @@ -15509,7 +17231,6 @@ func (s *CreateUserInput) SetUserName(v string) *CreateUserInput { } // Contains the response to a successful CreateUser request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateUserResponse type CreateUserOutput struct { _ struct{} `type:"structure"` @@ -15533,7 +17254,6 @@ func (s *CreateUserOutput) SetUser(v *User) *CreateUserOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADeviceRequest type CreateVirtualMFADeviceInput struct { _ struct{} `type:"structure"` @@ -15544,19 +17264,20 @@ type CreateVirtualMFADeviceInput struct { // This parameter is optional. If it is not included, it defaults to a slash // (/). // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. Path *string `min:"1" type:"string"` // The name of the virtual MFA device. Use with path to uniquely identify a // virtual MFA device. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // VirtualMFADeviceName is a required field VirtualMFADeviceName *string `min:"1" type:"string" required:"true"` @@ -15604,7 +17325,6 @@ func (s *CreateVirtualMFADeviceInput) SetVirtualMFADeviceName(v string) *CreateV } // Contains the response to a successful CreateVirtualMFADevice request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/CreateVirtualMFADeviceResponse type CreateVirtualMFADeviceOutput struct { _ struct{} `type:"structure"` @@ -15630,14 +17350,13 @@ func (s *CreateVirtualMFADeviceOutput) SetVirtualMFADevice(v *VirtualMFADevice) return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADeviceRequest type DeactivateMFADeviceInput struct { _ struct{} `type:"structure"` // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: =,.@:/- // @@ -15646,9 +17365,9 @@ type DeactivateMFADeviceInput struct { // The name of the user whose MFA device you want to deactivate. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -15698,7 +17417,6 @@ func (s *DeactivateMFADeviceInput) SetUserName(v string) *DeactivateMFADeviceInp return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeactivateMFADeviceOutput type DeactivateMFADeviceOutput struct { _ struct{} `type:"structure"` } @@ -15713,14 +17431,13 @@ func (s DeactivateMFADeviceOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKeyRequest type DeleteAccessKeyInput struct { _ struct{} `type:"structure"` // The access key ID for the access key ID and secret access key you want to // delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -15729,9 +17446,9 @@ type DeleteAccessKeyInput struct { // The name of the user whose access key pair you want to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -15776,7 +17493,6 @@ func (s *DeleteAccessKeyInput) SetUserName(v string) *DeleteAccessKeyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccessKeyOutput type DeleteAccessKeyOutput struct { _ struct{} `type:"structure"` } @@ -15791,13 +17507,12 @@ func (s DeleteAccessKeyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAliasRequest type DeleteAccountAliasInput struct { _ struct{} `type:"structure"` // The name of the account alias to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of lowercase letters, digits, and dashes. // You cannot start or finish with a dash, nor can you have two dashes in a // row. @@ -15838,7 +17553,6 @@ func (s *DeleteAccountAliasInput) SetAccountAlias(v string) *DeleteAccountAliasI return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountAliasOutput type DeleteAccountAliasOutput struct { _ struct{} `type:"structure"` } @@ -15853,7 +17567,6 @@ func (s DeleteAccountAliasOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicyInput type DeleteAccountPasswordPolicyInput struct { _ struct{} `type:"structure"` } @@ -15868,7 +17581,6 @@ func (s DeleteAccountPasswordPolicyInput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteAccountPasswordPolicyOutput type DeleteAccountPasswordPolicyOutput struct { _ struct{} `type:"structure"` } @@ -15883,15 +17595,14 @@ func (s DeleteAccountPasswordPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupRequest type DeleteGroupInput struct { _ struct{} `type:"structure"` // The name of the IAM group to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -15929,7 +17640,6 @@ func (s *DeleteGroupInput) SetGroupName(v string) *DeleteGroupInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupOutput type DeleteGroupOutput struct { _ struct{} `type:"structure"` } @@ -15944,25 +17654,24 @@ func (s DeleteGroupOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicyRequest type DeleteGroupPolicyInput struct { _ struct{} `type:"structure"` // The name (friendly name, not ARN) identifying the group that the policy is // embedded in. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` // The name identifying the policy document to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -16012,7 +17721,6 @@ func (s *DeleteGroupPolicyInput) SetPolicyName(v string) *DeleteGroupPolicyInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteGroupPolicyOutput type DeleteGroupPolicyOutput struct { _ struct{} `type:"structure"` } @@ -16027,15 +17735,14 @@ func (s DeleteGroupPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfileRequest type DeleteInstanceProfileInput struct { _ struct{} `type:"structure"` // The name of the instance profile to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // InstanceProfileName is a required field InstanceProfileName *string `min:"1" type:"string" required:"true"` @@ -16073,7 +17780,6 @@ func (s *DeleteInstanceProfileInput) SetInstanceProfileName(v string) *DeleteIns return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteInstanceProfileOutput type DeleteInstanceProfileOutput struct { _ struct{} `type:"structure"` } @@ -16088,15 +17794,14 @@ func (s DeleteInstanceProfileOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfileRequest type DeleteLoginProfileInput struct { _ struct{} `type:"structure"` // The name of the user whose password you want to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -16134,7 +17839,6 @@ func (s *DeleteLoginProfileInput) SetUserName(v string) *DeleteLoginProfileInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteLoginProfileOutput type DeleteLoginProfileOutput struct { _ struct{} `type:"structure"` } @@ -16149,13 +17853,12 @@ func (s DeleteLoginProfileOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProviderRequest type DeleteOpenIDConnectProviderInput struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of the IAM OpenID Connect provider resource // object to delete. You can get a list of OpenID Connect provider resource - // ARNs by using the ListOpenIDConnectProviders action. + // ARNs by using the ListOpenIDConnectProviders operation. // // OpenIDConnectProviderArn is a required field OpenIDConnectProviderArn *string `min:"20" type:"string" required:"true"` @@ -16193,7 +17896,6 @@ func (s *DeleteOpenIDConnectProviderInput) SetOpenIDConnectProviderArn(v string) return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteOpenIDConnectProviderOutput type DeleteOpenIDConnectProviderOutput struct { _ struct{} `type:"structure"` } @@ -16208,7 +17910,6 @@ func (s DeleteOpenIDConnectProviderOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyRequest type DeletePolicyInput struct { _ struct{} `type:"structure"` @@ -16254,7 +17955,6 @@ func (s *DeletePolicyInput) SetPolicyArn(v string) *DeletePolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyOutput type DeletePolicyOutput struct { _ struct{} `type:"structure"` } @@ -16269,7 +17969,6 @@ func (s DeletePolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersionRequest type DeletePolicyVersionInput struct { _ struct{} `type:"structure"` @@ -16285,7 +17984,7 @@ type DeletePolicyVersionInput struct { // The policy version to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that consists of the lowercase letter 'v' followed // by one or two digits, and optionally followed by a period '.' and a string // of letters and digits. @@ -16339,7 +18038,6 @@ func (s *DeletePolicyVersionInput) SetVersionId(v string) *DeletePolicyVersionIn return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletePolicyVersionOutput type DeletePolicyVersionOutput struct { _ struct{} `type:"structure"` } @@ -16354,13 +18052,12 @@ func (s DeletePolicyVersionOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRoleRequest type DeleteRoleInput struct { _ struct{} `type:"structure"` // The name of the role to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -16400,7 +18097,6 @@ func (s *DeleteRoleInput) SetRoleName(v string) *DeleteRoleInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRoleOutput type DeleteRoleOutput struct { _ struct{} `type:"structure"` } @@ -16415,15 +18111,70 @@ func (s DeleteRoleOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicyRequest +type DeleteRolePermissionsBoundaryInput struct { + _ struct{} `type:"structure"` + + // The name (friendly name, not ARN) of the IAM role from which you want to + // remove the permissions boundary. + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRolePermissionsBoundaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRolePermissionsBoundaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRolePermissionsBoundaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRolePermissionsBoundaryInput"} + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRoleName sets the RoleName field's value. +func (s *DeleteRolePermissionsBoundaryInput) SetRoleName(v string) *DeleteRolePermissionsBoundaryInput { + s.RoleName = &v + return s +} + +type DeleteRolePermissionsBoundaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteRolePermissionsBoundaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRolePermissionsBoundaryOutput) GoString() string { + return s.String() +} + type DeleteRolePolicyInput struct { _ struct{} `type:"structure"` // The name of the inline policy to delete from the specified IAM role. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -16431,7 +18182,7 @@ type DeleteRolePolicyInput struct { // The name (friendly name, not ARN) identifying the role that the policy is // embedded in. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -16483,7 +18234,6 @@ func (s *DeleteRolePolicyInput) SetRoleName(v string) *DeleteRolePolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteRolePolicyOutput type DeleteRolePolicyOutput struct { _ struct{} `type:"structure"` } @@ -16498,7 +18248,6 @@ func (s DeleteRolePolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProviderRequest type DeleteSAMLProviderInput struct { _ struct{} `type:"structure"` @@ -16540,7 +18289,6 @@ func (s *DeleteSAMLProviderInput) SetSAMLProviderArn(v string) *DeleteSAMLProvid return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSAMLProviderOutput type DeleteSAMLProviderOutput struct { _ struct{} `type:"structure"` } @@ -16555,13 +18303,12 @@ func (s DeleteSAMLProviderOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKeyRequest type DeleteSSHPublicKeyInput struct { _ struct{} `type:"structure"` // The unique identifier for the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -16570,9 +18317,9 @@ type DeleteSSHPublicKeyInput struct { // The name of the IAM user associated with the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -16622,7 +18369,6 @@ func (s *DeleteSSHPublicKeyInput) SetUserName(v string) *DeleteSSHPublicKeyInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSSHPublicKeyOutput type DeleteSSHPublicKeyOutput struct { _ struct{} `type:"structure"` } @@ -16637,15 +18383,14 @@ func (s DeleteSSHPublicKeyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificateRequest type DeleteServerCertificateInput struct { _ struct{} `type:"structure"` // The name of the server certificate you want to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // ServerCertificateName is a required field ServerCertificateName *string `min:"1" type:"string" required:"true"` @@ -16683,7 +18428,6 @@ func (s *DeleteServerCertificateInput) SetServerCertificateName(v string) *Delet return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServerCertificateOutput type DeleteServerCertificateOutput struct { _ struct{} `type:"structure"` } @@ -16698,7 +18442,6 @@ func (s DeleteServerCertificateOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRoleRequest type DeleteServiceLinkedRoleInput struct { _ struct{} `type:"structure"` @@ -16740,7 +18483,6 @@ func (s *DeleteServiceLinkedRoleInput) SetRoleName(v string) *DeleteServiceLinke return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceLinkedRoleResponse type DeleteServiceLinkedRoleOutput struct { _ struct{} `type:"structure"` @@ -16767,14 +18509,13 @@ func (s *DeleteServiceLinkedRoleOutput) SetDeletionTaskId(v string) *DeleteServi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredentialRequest type DeleteServiceSpecificCredentialInput struct { _ struct{} `type:"structure"` // The unique identifier of the service-specific credential. You can get this // value by calling ListServiceSpecificCredentials. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -16785,9 +18526,9 @@ type DeleteServiceSpecificCredentialInput struct { // If this value is not specified, then the operation assumes the user whose // credentials are used to call the operation. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -16832,7 +18573,6 @@ func (s *DeleteServiceSpecificCredentialInput) SetUserName(v string) *DeleteServ return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteServiceSpecificCredentialOutput type DeleteServiceSpecificCredentialOutput struct { _ struct{} `type:"structure"` } @@ -16847,7 +18587,6 @@ func (s DeleteServiceSpecificCredentialOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificateRequest type DeleteSigningCertificateInput struct { _ struct{} `type:"structure"` @@ -16862,9 +18601,9 @@ type DeleteSigningCertificateInput struct { // The name of the user the signing certificate belongs to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -16909,7 +18648,6 @@ func (s *DeleteSigningCertificateInput) SetUserName(v string) *DeleteSigningCert return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteSigningCertificateOutput type DeleteSigningCertificateOutput struct { _ struct{} `type:"structure"` } @@ -16924,15 +18662,14 @@ func (s DeleteSigningCertificateOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserRequest type DeleteUserInput struct { _ struct{} `type:"structure"` // The name of the user to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -16970,7 +18707,6 @@ func (s *DeleteUserInput) SetUserName(v string) *DeleteUserInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserOutput type DeleteUserOutput struct { _ struct{} `type:"structure"` } @@ -16985,15 +18721,70 @@ func (s DeleteUserOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicyRequest +type DeleteUserPermissionsBoundaryInput struct { + _ struct{} `type:"structure"` + + // The name (friendly name, not ARN) of the IAM user from which you want to + // remove the permissions boundary. + // + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteUserPermissionsBoundaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteUserPermissionsBoundaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteUserPermissionsBoundaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteUserPermissionsBoundaryInput"} + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetUserName sets the UserName field's value. +func (s *DeleteUserPermissionsBoundaryInput) SetUserName(v string) *DeleteUserPermissionsBoundaryInput { + s.UserName = &v + return s +} + +type DeleteUserPermissionsBoundaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteUserPermissionsBoundaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteUserPermissionsBoundaryOutput) GoString() string { + return s.String() +} + type DeleteUserPolicyInput struct { _ struct{} `type:"structure"` // The name identifying the policy document to delete. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -17001,9 +18792,9 @@ type DeleteUserPolicyInput struct { // The name (friendly name, not ARN) identifying the user that the policy is // embedded in. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -17053,7 +18844,6 @@ func (s *DeleteUserPolicyInput) SetUserName(v string) *DeleteUserPolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteUserPolicyOutput type DeleteUserPolicyOutput struct { _ struct{} `type:"structure"` } @@ -17068,14 +18858,13 @@ func (s DeleteUserPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADeviceRequest type DeleteVirtualMFADeviceInput struct { _ struct{} `type:"structure"` // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the same as the ARN. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: =,.@:/- // @@ -17115,7 +18904,6 @@ func (s *DeleteVirtualMFADeviceInput) SetSerialNumber(v string) *DeleteVirtualMF return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeleteVirtualMFADeviceOutput type DeleteVirtualMFADeviceOutput struct { _ struct{} `type:"structure"` } @@ -17134,7 +18922,6 @@ func (s DeleteVirtualMFADeviceOutput) GoString() string { // // This data type is used as a response element in the GetServiceLinkedRoleDeletionStatus // operation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DeletionTaskFailureReasonType type DeletionTaskFailureReasonType struct { _ struct{} `type:"structure"` @@ -17142,11 +18929,11 @@ type DeletionTaskFailureReasonType struct { Reason *string `type:"string"` // A list of objects that contains details about the service-linked role deletion - // failure. If the service-linked role has active sessions or if any resources - // that were used by the role have not been deleted from the linked service, - // the role can't be deleted. This parameter includes a list of the resources - // that are associated with the role and the region in which the resources are - // being used. + // failure, if that information is returned by the service. If the service-linked + // role has active sessions or if any resources that were used by the role have + // not been deleted from the linked service, the role can't be deleted. This + // parameter includes a list of the resources that are associated with the role + // and the region in which the resources are being used. RoleUsageList []*RoleUsageType `type:"list"` } @@ -17172,15 +18959,14 @@ func (s *DeletionTaskFailureReasonType) SetRoleUsageList(v []*RoleUsageType) *De return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicyRequest type DetachGroupPolicyInput struct { _ struct{} `type:"structure"` // The name (friendly name, not ARN) of the IAM group to detach the policy from. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -17239,7 +19025,6 @@ func (s *DetachGroupPolicyInput) SetPolicyArn(v string) *DetachGroupPolicyInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachGroupPolicyOutput type DetachGroupPolicyOutput struct { _ struct{} `type:"structure"` } @@ -17254,7 +19039,6 @@ func (s DetachGroupPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicyRequest type DetachRolePolicyInput struct { _ struct{} `type:"structure"` @@ -17269,7 +19053,7 @@ type DetachRolePolicyInput struct { // The name (friendly name, not ARN) of the IAM role to detach the policy from. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -17321,7 +19105,6 @@ func (s *DetachRolePolicyInput) SetRoleName(v string) *DetachRolePolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachRolePolicyOutput type DetachRolePolicyOutput struct { _ struct{} `type:"structure"` } @@ -17336,7 +19119,6 @@ func (s DetachRolePolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicyRequest type DetachUserPolicyInput struct { _ struct{} `type:"structure"` @@ -17351,9 +19133,9 @@ type DetachUserPolicyInput struct { // The name (friendly name, not ARN) of the IAM user to detach the policy from. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -17403,7 +19185,6 @@ func (s *DetachUserPolicyInput) SetUserName(v string) *DetachUserPolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/DetachUserPolicyOutput type DetachUserPolicyOutput struct { _ struct{} `type:"structure"` } @@ -17418,13 +19199,12 @@ func (s DetachUserPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADeviceRequest type EnableMFADeviceInput struct { _ struct{} `type:"structure"` // An authentication code emitted by the device. // - // The format for this parameter is a string of 6 digits. + // The format for this parameter is a string of six digits. // // Submit your request immediately after generating the authentication codes. // If you generate the codes and then wait too long to submit the request, the @@ -17438,7 +19218,7 @@ type EnableMFADeviceInput struct { // A subsequent authentication code emitted by the device. // - // The format for this parameter is a string of 6 digits. + // The format for this parameter is a string of six digits. // // Submit your request immediately after generating the authentication codes. // If you generate the codes and then wait too long to submit the request, the @@ -17453,7 +19233,7 @@ type EnableMFADeviceInput struct { // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: =,.@:/- // @@ -17462,9 +19242,9 @@ type EnableMFADeviceInput struct { // The name of the IAM user for whom you want to enable the MFA device. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -17538,7 +19318,6 @@ func (s *EnableMFADeviceInput) SetUserName(v string) *EnableMFADeviceInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EnableMFADeviceOutput type EnableMFADeviceOutput struct { _ struct{} `type:"structure"` } @@ -17553,15 +19332,174 @@ func (s EnableMFADeviceOutput) GoString() string { return s.String() } +// An object that contains details about when the IAM entities (users or roles) +// were last used in an attempt to access the specified AWS service. +// +// This data type is a response element in the GetServiceLastAccessedDetailsWithEntities +// operation. +type EntityDetails struct { + _ struct{} `type:"structure"` + + // The EntityInfo object that contains details about the entity (user or role). + // + // EntityInfo is a required field + EntityInfo *EntityInfo `type:"structure" required:"true"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when the authenticated entity last attempted to access AWS. AWS does not + // report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAuthenticated *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s EntityDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EntityDetails) GoString() string { + return s.String() +} + +// SetEntityInfo sets the EntityInfo field's value. +func (s *EntityDetails) SetEntityInfo(v *EntityInfo) *EntityDetails { + s.EntityInfo = v + return s +} + +// SetLastAuthenticated sets the LastAuthenticated field's value. +func (s *EntityDetails) SetLastAuthenticated(v time.Time) *EntityDetails { + s.LastAuthenticated = &v + return s +} + +// Contains details about the specified entity (user or role). +// +// This data type is an element of the EntityDetails object. +type EntityInfo struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. + // + // For more information about ARNs, go to Amazon Resource Names (ARNs) and AWS + // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + // + // Arn is a required field + Arn *string `min:"20" type:"string" required:"true"` + + // The identifier of the entity (user or role). + // + // Id is a required field + Id *string `min:"16" type:"string" required:"true"` + + // The name of the entity (user or role). + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The path to the entity (user or role). For more information about paths, + // see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) + // in the Using IAM guide. + Path *string `min:"1" type:"string"` + + // The type of entity (user or role). + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"policyOwnerEntityType"` +} + +// String returns the string representation +func (s EntityInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EntityInfo) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *EntityInfo) SetArn(v string) *EntityInfo { + s.Arn = &v + return s +} + +// SetId sets the Id field's value. +func (s *EntityInfo) SetId(v string) *EntityInfo { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *EntityInfo) SetName(v string) *EntityInfo { + s.Name = &v + return s +} + +// SetPath sets the Path field's value. +func (s *EntityInfo) SetPath(v string) *EntityInfo { + s.Path = &v + return s +} + +// SetType sets the Type field's value. +func (s *EntityInfo) SetType(v string) *EntityInfo { + s.Type = &v + return s +} + +// Contains information about the reason that the operation failed. +// +// This data type is used as a response element in the GetServiceLastAccessedDetails +// operation and the GetServiceLastAccessedDetailsWithEntities operation. +type ErrorDetails struct { + _ struct{} `type:"structure"` + + // The error code associated with the operation failure. + // + // Code is a required field + Code *string `type:"string" required:"true"` + + // Detailed information about the reason that the operation failed. + // + // Message is a required field + Message *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ErrorDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ErrorDetails) GoString() string { + return s.String() +} + +// SetCode sets the Code field's value. +func (s *ErrorDetails) SetCode(v string) *ErrorDetails { + s.Code = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *ErrorDetails) SetMessage(v string) *ErrorDetails { + s.Message = &v + return s +} + // Contains the results of a simulation. // // This data type is used by the return parameter of SimulateCustomPolicy and // SimulatePrincipalPolicy. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/EvaluationResult type EvaluationResult struct { _ struct{} `type:"structure"` - // The name of the API action tested on the indicated resource. + // The name of the API operation tested on the indicated resource. // // EvalActionName is a required field EvalActionName *string `min:"3" type:"string" required:"true"` @@ -17579,14 +19517,14 @@ type EvaluationResult struct { // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_compare-resource-policies.html) EvalDecisionDetails map[string]*string `type:"map"` - // The ARN of the resource that the indicated API action was tested on. + // The ARN of the resource that the indicated API operation was tested on. EvalResourceName *string `min:"1" type:"string"` // A list of the statements in the input policies that determine the result - // for this scenario. Remember that even if multiple statements allow the action - // on the resource, if only one statement denies that action, then the explicit - // deny overrides any allow, and the deny statement is the only entry included - // in the result. + // for this scenario. Remember that even if multiple statements allow the operation + // on the resource, if only one statement denies that operation, then the explicit + // deny overrides any allow. Inaddition, the deny statement is the only entry + // included in the result. MatchedStatements []*Statement `type:"list"` // A list of context keys that are required by the included input policies but @@ -17603,8 +19541,8 @@ type EvaluationResult struct { // account is part of an organization. OrganizationsDecisionDetail *OrganizationsDecisionDetail `type:"structure"` - // The individual results of the simulation of the API action specified in EvalActionName - // on each resource. + // The individual results of the simulation of the API operation specified in + // EvalActionName on each resource. ResourceSpecificResults []*ResourceSpecificResult `type:"list"` } @@ -17666,7 +19604,6 @@ func (s *EvaluationResult) SetResourceSpecificResults(v []*ResourceSpecificResul return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReportInput type GenerateCredentialReportInput struct { _ struct{} `type:"structure"` } @@ -17682,7 +19619,6 @@ func (s GenerateCredentialReportInput) GoString() string { } // Contains the response to a successful GenerateCredentialReport request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GenerateCredentialReportResponse type GenerateCredentialReportOutput struct { _ struct{} `type:"structure"` @@ -17715,13 +19651,79 @@ func (s *GenerateCredentialReportOutput) SetState(v string) *GenerateCredentialR return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsedRequest +type GenerateServiceLastAccessedDetailsInput struct { + _ struct{} `type:"structure"` + + // The ARN of the IAM resource (user, group, role, or managed policy) used to + // generate information about when the resource was last used in an attempt + // to access an AWS service. + // + // Arn is a required field + Arn *string `min:"20" type:"string" required:"true"` +} + +// String returns the string representation +func (s GenerateServiceLastAccessedDetailsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GenerateServiceLastAccessedDetailsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GenerateServiceLastAccessedDetailsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GenerateServiceLastAccessedDetailsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 20)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *GenerateServiceLastAccessedDetailsInput) SetArn(v string) *GenerateServiceLastAccessedDetailsInput { + s.Arn = &v + return s +} + +type GenerateServiceLastAccessedDetailsOutput struct { + _ struct{} `type:"structure"` + + // The job ID that you can use in the GetServiceLastAccessedDetails or GetServiceLastAccessedDetailsWithEntities + // operations. + JobId *string `min:"36" type:"string"` +} + +// String returns the string representation +func (s GenerateServiceLastAccessedDetailsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GenerateServiceLastAccessedDetailsOutput) GoString() string { + return s.String() +} + +// SetJobId sets the JobId field's value. +func (s *GenerateServiceLastAccessedDetailsOutput) SetJobId(v string) *GenerateServiceLastAccessedDetailsOutput { + s.JobId = &v + return s +} + type GetAccessKeyLastUsedInput struct { _ struct{} `type:"structure"` // The identifier of an access key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -17764,7 +19766,6 @@ func (s *GetAccessKeyLastUsedInput) SetAccessKeyId(v string) *GetAccessKeyLastUs // Contains the response to a successful GetAccessKeyLastUsed request. It is // also returned as a member of the AccessKeyMetaData structure returned by // the ListAccessKeys action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccessKeyLastUsedResponse type GetAccessKeyLastUsedOutput struct { _ struct{} `type:"structure"` @@ -17797,7 +19798,6 @@ func (s *GetAccessKeyLastUsedOutput) SetUserName(v string) *GetAccessKeyLastUsed return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetailsRequest type GetAccountAuthorizationDetailsInput struct { _ struct{} `type:"structure"` @@ -17816,15 +19816,15 @@ type GetAccountAuthorizationDetailsInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` } @@ -17873,7 +19873,6 @@ func (s *GetAccountAuthorizationDetailsInput) SetMaxItems(v int64) *GetAccountAu } // Contains the response to a successful GetAccountAuthorizationDetails request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountAuthorizationDetailsResponse type GetAccountAuthorizationDetailsOutput struct { _ struct{} `type:"structure"` @@ -17885,7 +19884,7 @@ type GetAccountAuthorizationDetailsOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -17948,7 +19947,6 @@ func (s *GetAccountAuthorizationDetailsOutput) SetUserDetailList(v []*UserDetail return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicyInput type GetAccountPasswordPolicyInput struct { _ struct{} `type:"structure"` } @@ -17964,7 +19962,6 @@ func (s GetAccountPasswordPolicyInput) GoString() string { } // Contains the response to a successful GetAccountPasswordPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountPasswordPolicyResponse type GetAccountPasswordPolicyOutput struct { _ struct{} `type:"structure"` @@ -17990,7 +19987,6 @@ func (s *GetAccountPasswordPolicyOutput) SetPasswordPolicy(v *PasswordPolicy) *G return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummaryInput type GetAccountSummaryInput struct { _ struct{} `type:"structure"` } @@ -18006,11 +20002,10 @@ func (s GetAccountSummaryInput) GoString() string { } // Contains the response to a successful GetAccountSummary request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetAccountSummaryResponse type GetAccountSummaryOutput struct { _ struct{} `type:"structure"` - // A set of key value pairs containing information about IAM entity usage and + // A set of key–value pairs containing information about IAM entity usage and // IAM quotas. SummaryMap map[string]*int64 `type:"map"` } @@ -18031,7 +20026,6 @@ func (s *GetAccountSummaryOutput) SetSummaryMap(v map[string]*int64) *GetAccount return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForCustomPolicyRequest type GetContextKeysForCustomPolicyInput struct { _ struct{} `type:"structure"` @@ -18040,11 +20034,16 @@ type GetContextKeysForCustomPolicyInput struct { // complete, valid JSON text of an IAM policy. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyInputList is a required field PolicyInputList []*string `type:"list" required:"true"` @@ -18081,7 +20080,6 @@ func (s *GetContextKeysForCustomPolicyInput) SetPolicyInputList(v []*string) *Ge // Contains the response to a successful GetContextKeysForPrincipalPolicy or // GetContextKeysForCustomPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPolicyResponse type GetContextKeysForPolicyResponse struct { _ struct{} `type:"structure"` @@ -18105,7 +20103,6 @@ func (s *GetContextKeysForPolicyResponse) SetContextKeyNames(v []*string) *GetCo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetContextKeysForPrincipalPolicyRequest type GetContextKeysForPrincipalPolicyInput struct { _ struct{} `type:"structure"` @@ -18113,20 +20110,26 @@ type GetContextKeysForPrincipalPolicyInput struct { // keys that are referenced. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) PolicyInputList []*string `type:"list"` // The ARN of a user, group, or role whose policies contain the context keys // that you want listed. If you specify a user, the list includes context keys - // that are found in all policies attached to the user as well as to all groups - // that the user is a member of. If you pick a group or a role, then it includes - // only those context keys that are found in policies attached to that entity. - // Note that all parameters are shown in unencoded form here for clarity, but - // must be URL encoded to be included as a part of a real HTML request. + // that are found in all policies that are attached to the user. The list also + // includes all groups that the user is a member of. If you pick a group or + // a role, then it includes only those context keys that are found in policies + // attached to that entity. Note that all parameters are shown in unencoded + // form here for clarity, but must be URL encoded to be included as a part of + // a real HTML request. // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) @@ -18174,7 +20177,6 @@ func (s *GetContextKeysForPrincipalPolicyInput) SetPolicySourceArn(v string) *Ge return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReportInput type GetCredentialReportInput struct { _ struct{} `type:"structure"` } @@ -18190,7 +20192,6 @@ func (s GetCredentialReportInput) GoString() string { } // Contains the response to a successful GetCredentialReport request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetCredentialReportResponse type GetCredentialReportOutput struct { _ struct{} `type:"structure"` @@ -18201,7 +20202,7 @@ type GetCredentialReportOutput struct { // The date and time when the credential report was created, in ISO 8601 date-time // format (http://www.iso.org/iso/iso8601). - GeneratedTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` + GeneratedTime *time.Time `type:"timestamp"` // The format (MIME type) of the credential report. ReportFormat *string `type:"string" enum:"ReportFormatType"` @@ -18235,15 +20236,14 @@ func (s *GetCredentialReportOutput) SetReportFormat(v string) *GetCredentialRepo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupRequest type GetGroupInput struct { _ struct{} `type:"structure"` // The name of the group. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -18254,15 +20254,15 @@ type GetGroupInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` } @@ -18317,7 +20317,6 @@ func (s *GetGroupInput) SetMaxItems(v int64) *GetGroupInput { } // Contains the response to a successful GetGroup request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupResponse type GetGroupOutput struct { _ struct{} `type:"structure"` @@ -18331,7 +20330,7 @@ type GetGroupOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -18378,24 +20377,23 @@ func (s *GetGroupOutput) SetUsers(v []*User) *GetGroupOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicyRequest type GetGroupPolicyInput struct { _ struct{} `type:"structure"` // The name of the group the policy is associated with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` // The name of the policy document to get. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -18446,7 +20444,6 @@ func (s *GetGroupPolicyInput) SetPolicyName(v string) *GetGroupPolicyInput { } // Contains the response to a successful GetGroupPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetGroupPolicyResponse type GetGroupPolicyOutput struct { _ struct{} `type:"structure"` @@ -18494,15 +20491,14 @@ func (s *GetGroupPolicyOutput) SetPolicyName(v string) *GetGroupPolicyOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfileRequest type GetInstanceProfileInput struct { _ struct{} `type:"structure"` // The name of the instance profile to get information about. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // InstanceProfileName is a required field InstanceProfileName *string `min:"1" type:"string" required:"true"` @@ -18541,7 +20537,6 @@ func (s *GetInstanceProfileInput) SetInstanceProfileName(v string) *GetInstanceP } // Contains the response to a successful GetInstanceProfile request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfileResponse type GetInstanceProfileOutput struct { _ struct{} `type:"structure"` @@ -18567,15 +20562,14 @@ func (s *GetInstanceProfileOutput) SetInstanceProfile(v *InstanceProfile) *GetIn return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfileRequest type GetLoginProfileInput struct { _ struct{} `type:"structure"` // The name of the user whose login profile you want to retrieve. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -18614,7 +20608,6 @@ func (s *GetLoginProfileInput) SetUserName(v string) *GetLoginProfileInput { } // Contains the response to a successful GetLoginProfile request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetLoginProfileResponse type GetLoginProfileOutput struct { _ struct{} `type:"structure"` @@ -18640,13 +20633,12 @@ func (s *GetLoginProfileOutput) SetLoginProfile(v *LoginProfile) *GetLoginProfil return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProviderRequest type GetOpenIDConnectProviderInput struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of the OIDC provider resource object in IAM // to get information for. You can get a list of OIDC provider resource ARNs - // by using the ListOpenIDConnectProviders action. + // by using the ListOpenIDConnectProviders operation. // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) @@ -18689,7 +20681,6 @@ func (s *GetOpenIDConnectProviderInput) SetOpenIDConnectProviderArn(v string) *G } // Contains the response to a successful GetOpenIDConnectProvider request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetOpenIDConnectProviderResponse type GetOpenIDConnectProviderOutput struct { _ struct{} `type:"structure"` @@ -18699,7 +20690,7 @@ type GetOpenIDConnectProviderOutput struct { // The date and time when the IAM OIDC provider resource object was created // in the AWS account. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // A list of certificate thumbprints that are associated with the specified // IAM OIDC provider resource object. For more information, see CreateOpenIDConnectProvider. @@ -18744,7 +20735,6 @@ func (s *GetOpenIDConnectProviderOutput) SetUrl(v string) *GetOpenIDConnectProvi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyRequest type GetPolicyInput struct { _ struct{} `type:"structure"` @@ -18792,7 +20782,6 @@ func (s *GetPolicyInput) SetPolicyArn(v string) *GetPolicyInput { } // Contains the response to a successful GetPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyResponse type GetPolicyOutput struct { _ struct{} `type:"structure"` @@ -18816,7 +20805,6 @@ func (s *GetPolicyOutput) SetPolicy(v *Policy) *GetPolicyOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersionRequest type GetPolicyVersionInput struct { _ struct{} `type:"structure"` @@ -18832,7 +20820,7 @@ type GetPolicyVersionInput struct { // Identifies the policy version to retrieve. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that consists of the lowercase letter 'v' followed // by one or two digits, and optionally followed by a period '.' and a string // of letters and digits. @@ -18883,7 +20871,6 @@ func (s *GetPolicyVersionInput) SetVersionId(v string) *GetPolicyVersionInput { } // Contains the response to a successful GetPolicyVersion request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetPolicyVersionResponse type GetPolicyVersionOutput struct { _ struct{} `type:"structure"` @@ -18907,13 +20894,12 @@ func (s *GetPolicyVersionOutput) SetPolicyVersion(v *PolicyVersion) *GetPolicyVe return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRoleRequest type GetRoleInput struct { _ struct{} `type:"structure"` // The name of the IAM role to get information about. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -18954,7 +20940,6 @@ func (s *GetRoleInput) SetRoleName(v string) *GetRoleInput { } // Contains the response to a successful GetRole request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRoleResponse type GetRoleOutput struct { _ struct{} `type:"structure"` @@ -18980,22 +20965,21 @@ func (s *GetRoleOutput) SetRole(v *Role) *GetRoleOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicyRequest type GetRolePolicyInput struct { _ struct{} `type:"structure"` // The name of the policy document to get. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` // The name of the role associated with the policy. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -19048,7 +21032,6 @@ func (s *GetRolePolicyInput) SetRoleName(v string) *GetRolePolicyInput { } // Contains the response to a successful GetRolePolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetRolePolicyResponse type GetRolePolicyOutput struct { _ struct{} `type:"structure"` @@ -19096,7 +21079,6 @@ func (s *GetRolePolicyOutput) SetRoleName(v string) *GetRolePolicyOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProviderRequest type GetSAMLProviderInput struct { _ struct{} `type:"structure"` @@ -19144,18 +21126,17 @@ func (s *GetSAMLProviderInput) SetSAMLProviderArn(v string) *GetSAMLProviderInpu } // Contains the response to a successful GetSAMLProvider request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSAMLProviderResponse type GetSAMLProviderOutput struct { _ struct{} `type:"structure"` // The date and time when the SAML provider was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The XML metadata document that includes information about an identity provider. SAMLMetadataDocument *string `min:"1000" type:"string"` // The expiration date and time for the SAML provider. - ValidUntil *time.Time `type:"timestamp" timestampFormat:"iso8601"` + ValidUntil *time.Time `type:"timestamp"` } // String returns the string representation @@ -19186,7 +21167,6 @@ func (s *GetSAMLProviderOutput) SetValidUntil(v time.Time) *GetSAMLProviderOutpu return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKeyRequest type GetSSHPublicKeyInput struct { _ struct{} `type:"structure"` @@ -19199,7 +21179,7 @@ type GetSSHPublicKeyInput struct { // The unique identifier for the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -19208,9 +21188,9 @@ type GetSSHPublicKeyInput struct { // The name of the IAM user associated with the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -19270,7 +21250,6 @@ func (s *GetSSHPublicKeyInput) SetUserName(v string) *GetSSHPublicKeyInput { } // Contains the response to a successful GetSSHPublicKey request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetSSHPublicKeyResponse type GetSSHPublicKeyOutput struct { _ struct{} `type:"structure"` @@ -19283,91 +21262,458 @@ func (s GetSSHPublicKeyOutput) String() string { return awsutil.Prettify(s) } -// GoString returns the string representation -func (s GetSSHPublicKeyOutput) GoString() string { - return s.String() +// GoString returns the string representation +func (s GetSSHPublicKeyOutput) GoString() string { + return s.String() +} + +// SetSSHPublicKey sets the SSHPublicKey field's value. +func (s *GetSSHPublicKeyOutput) SetSSHPublicKey(v *SSHPublicKey) *GetSSHPublicKeyOutput { + s.SSHPublicKey = v + return s +} + +type GetServerCertificateInput struct { + _ struct{} `type:"structure"` + + // The name of the server certificate you want to retrieve information about. + // + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters consisting of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: _+=,.@- + // + // ServerCertificateName is a required field + ServerCertificateName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetServerCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetServerCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetServerCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetServerCertificateInput"} + if s.ServerCertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("ServerCertificateName")) + } + if s.ServerCertificateName != nil && len(*s.ServerCertificateName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServerCertificateName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetServerCertificateName sets the ServerCertificateName field's value. +func (s *GetServerCertificateInput) SetServerCertificateName(v string) *GetServerCertificateInput { + s.ServerCertificateName = &v + return s +} + +// Contains the response to a successful GetServerCertificate request. +type GetServerCertificateOutput struct { + _ struct{} `type:"structure"` + + // A structure containing details about the server certificate. + // + // ServerCertificate is a required field + ServerCertificate *ServerCertificate `type:"structure" required:"true"` +} + +// String returns the string representation +func (s GetServerCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetServerCertificateOutput) GoString() string { + return s.String() +} + +// SetServerCertificate sets the ServerCertificate field's value. +func (s *GetServerCertificateOutput) SetServerCertificate(v *ServerCertificate) *GetServerCertificateOutput { + s.ServerCertificate = v + return s +} + +type GetServiceLastAccessedDetailsInput struct { + _ struct{} `type:"structure"` + + // The ID of the request generated by the GenerateServiceLastAccessedDetails + // operation. + // + // JobId is a required field + JobId *string `min:"36" type:"string" required:"true"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. + // + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` +} + +// String returns the string representation +func (s GetServiceLastAccessedDetailsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetServiceLastAccessedDetailsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetServiceLastAccessedDetailsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetServiceLastAccessedDetailsInput"} + if s.JobId == nil { + invalidParams.Add(request.NewErrParamRequired("JobId")) + } + if s.JobId != nil && len(*s.JobId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("JobId", 36)) + } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.MaxItems != nil && *s.MaxItems < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetJobId sets the JobId field's value. +func (s *GetServiceLastAccessedDetailsInput) SetJobId(v string) *GetServiceLastAccessedDetailsInput { + s.JobId = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *GetServiceLastAccessedDetailsInput) SetMarker(v string) *GetServiceLastAccessedDetailsInput { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *GetServiceLastAccessedDetailsInput) SetMaxItems(v int64) *GetServiceLastAccessedDetailsInput { + s.MaxItems = &v + return s +} + +type GetServiceLastAccessedDetailsOutput struct { + _ struct{} `type:"structure"` + + // An object that contains details about the reason the operation failed. + Error *ErrorDetails `type:"structure"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Markerrequest parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItemsnumber of results even when there are more results available. We recommend + // that you check IsTruncated + IsTruncated *bool `type:"boolean"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when the generated report job was completed or failed. + // + // This field is null if the job is still in progress, as indicated by a JobStatus + // value of IN_PROGRESS. + // + // JobCompletionDate is a required field + JobCompletionDate *time.Time `type:"timestamp" required:"true"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when the report job was created. + // + // JobCreationDate is a required field + JobCreationDate *time.Time `type:"timestamp" required:"true"` + + // The status of the job. + // + // JobStatus is a required field + JobStatus *string `type:"string" required:"true" enum:"jobStatusType"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` + + // A ServiceLastAccessed object that contains details about the most recent + // attempt to access the service. + // + // ServicesLastAccessed is a required field + ServicesLastAccessed []*ServiceLastAccessed `type:"list" required:"true"` +} + +// String returns the string representation +func (s GetServiceLastAccessedDetailsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetServiceLastAccessedDetailsOutput) GoString() string { + return s.String() +} + +// SetError sets the Error field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetError(v *ErrorDetails) *GetServiceLastAccessedDetailsOutput { + s.Error = v + return s +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetIsTruncated(v bool) *GetServiceLastAccessedDetailsOutput { + s.IsTruncated = &v + return s +} + +// SetJobCompletionDate sets the JobCompletionDate field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetJobCompletionDate(v time.Time) *GetServiceLastAccessedDetailsOutput { + s.JobCompletionDate = &v + return s +} + +// SetJobCreationDate sets the JobCreationDate field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetJobCreationDate(v time.Time) *GetServiceLastAccessedDetailsOutput { + s.JobCreationDate = &v + return s +} + +// SetJobStatus sets the JobStatus field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetJobStatus(v string) *GetServiceLastAccessedDetailsOutput { + s.JobStatus = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetMarker(v string) *GetServiceLastAccessedDetailsOutput { + s.Marker = &v + return s +} + +// SetServicesLastAccessed sets the ServicesLastAccessed field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetServicesLastAccessed(v []*ServiceLastAccessed) *GetServiceLastAccessedDetailsOutput { + s.ServicesLastAccessed = v + return s +} + +type GetServiceLastAccessedDetailsWithEntitiesInput struct { + _ struct{} `type:"structure"` + + // The ID of the request generated by the GenerateServiceLastAccessedDetails + // operation. + // + // JobId is a required field + JobId *string `min:"36" type:"string" required:"true"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. + // + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + + // The service namespace for an AWS service. Provide the service namespace to + // learn when the IAM entity last attempted to access the specified service. + // + // To learn the service namespace for a service, go to Actions, Resources, and + // Condition Keys for AWS Services (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html) + // in the IAM User Guide and choose the name of the service to view details + // for that service. In the first paragraph, find the service prefix. For example, + // (service prefix: a4b). For more information about service namespaces, see + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the AWS General Reference. + // + // ServiceNamespace is a required field + ServiceNamespace *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetServiceLastAccessedDetailsWithEntitiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetServiceLastAccessedDetailsWithEntitiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetServiceLastAccessedDetailsWithEntitiesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetServiceLastAccessedDetailsWithEntitiesInput"} + if s.JobId == nil { + invalidParams.Add(request.NewErrParamRequired("JobId")) + } + if s.JobId != nil && len(*s.JobId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("JobId", 36)) + } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.MaxItems != nil && *s.MaxItems < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + if s.ServiceNamespace != nil && len(*s.ServiceNamespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServiceNamespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetJobId sets the JobId field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesInput) SetJobId(v string) *GetServiceLastAccessedDetailsWithEntitiesInput { + s.JobId = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesInput) SetMarker(v string) *GetServiceLastAccessedDetailsWithEntitiesInput { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesInput) SetMaxItems(v int64) *GetServiceLastAccessedDetailsWithEntitiesInput { + s.MaxItems = &v + return s } -// SetSSHPublicKey sets the SSHPublicKey field's value. -func (s *GetSSHPublicKeyOutput) SetSSHPublicKey(v *SSHPublicKey) *GetSSHPublicKeyOutput { - s.SSHPublicKey = v +// SetServiceNamespace sets the ServiceNamespace field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesInput) SetServiceNamespace(v string) *GetServiceLastAccessedDetailsWithEntitiesInput { + s.ServiceNamespace = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificateRequest -type GetServerCertificateInput struct { +type GetServiceLastAccessedDetailsWithEntitiesOutput struct { _ struct{} `type:"structure"` - // The name of the server certificate you want to retrieve information about. + // An EntityDetailsList object that contains details about when an IAM entity + // (user or role) used group or policy permissions in an attempt to access the + // specified AWS service. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) - // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // EntityDetailsList is a required field + EntityDetailsList []*EntityDetails `type:"list" required:"true"` + + // An object that contains details about the reason the operation failed. + Error *ErrorDetails `type:"structure"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Marker + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all your results. + IsTruncated *bool `type:"boolean"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when the generated report job was completed or failed. // - // ServerCertificateName is a required field - ServerCertificateName *string `min:"1" type:"string" required:"true"` + // JobCompletionDate is a required field + JobCompletionDate *time.Time `type:"timestamp" required:"true"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when the report job was created. + // + // JobCreationDate is a required field + JobCreationDate *time.Time `type:"timestamp" required:"true"` + + // The status of the job. + // + // JobStatus is a required field + JobStatus *string `type:"string" required:"true" enum:"jobStatusType"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` } // String returns the string representation -func (s GetServerCertificateInput) String() string { +func (s GetServiceLastAccessedDetailsWithEntitiesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetServerCertificateInput) GoString() string { +func (s GetServiceLastAccessedDetailsWithEntitiesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetServerCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetServerCertificateInput"} - if s.ServerCertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("ServerCertificateName")) - } - if s.ServerCertificateName != nil && len(*s.ServerCertificateName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ServerCertificateName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetEntityDetailsList sets the EntityDetailsList field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetEntityDetailsList(v []*EntityDetails) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.EntityDetailsList = v + return s } -// SetServerCertificateName sets the ServerCertificateName field's value. -func (s *GetServerCertificateInput) SetServerCertificateName(v string) *GetServerCertificateInput { - s.ServerCertificateName = &v +// SetError sets the Error field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetError(v *ErrorDetails) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.Error = v return s } -// Contains the response to a successful GetServerCertificate request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServerCertificateResponse -type GetServerCertificateOutput struct { - _ struct{} `type:"structure"` +// SetIsTruncated sets the IsTruncated field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetIsTruncated(v bool) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.IsTruncated = &v + return s +} - // A structure containing details about the server certificate. - // - // ServerCertificate is a required field - ServerCertificate *ServerCertificate `type:"structure" required:"true"` +// SetJobCompletionDate sets the JobCompletionDate field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetJobCompletionDate(v time.Time) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.JobCompletionDate = &v + return s } -// String returns the string representation -func (s GetServerCertificateOutput) String() string { - return awsutil.Prettify(s) +// SetJobCreationDate sets the JobCreationDate field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetJobCreationDate(v time.Time) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.JobCreationDate = &v + return s } -// GoString returns the string representation -func (s GetServerCertificateOutput) GoString() string { - return s.String() +// SetJobStatus sets the JobStatus field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetJobStatus(v string) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.JobStatus = &v + return s } -// SetServerCertificate sets the ServerCertificate field's value. -func (s *GetServerCertificateOutput) SetServerCertificate(v *ServerCertificate) *GetServerCertificateOutput { - s.ServerCertificate = v +// SetMarker sets the Marker field's value. +func (s *GetServiceLastAccessedDetailsWithEntitiesOutput) SetMarker(v string) *GetServiceLastAccessedDetailsWithEntitiesOutput { + s.Marker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatusRequest type GetServiceLinkedRoleDeletionStatusInput struct { _ struct{} `type:"structure"` @@ -19410,7 +21756,6 @@ func (s *GetServiceLinkedRoleDeletionStatusInput) SetDeletionTaskId(v string) *G return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetServiceLinkedRoleDeletionStatusResponse type GetServiceLinkedRoleDeletionStatusOutput struct { _ struct{} `type:"structure"` @@ -19445,16 +21790,15 @@ func (s *GetServiceLinkedRoleDeletionStatusOutput) SetStatus(v string) *GetServi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserRequest type GetUserInput struct { _ struct{} `type:"structure"` // The name of the user to get information about. // // This parameter is optional. If it is not included, it defaults to the user - // making the request. This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // making the request. This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -19488,12 +21832,28 @@ func (s *GetUserInput) SetUserName(v string) *GetUserInput { } // Contains the response to a successful GetUser request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserResponse type GetUserOutput struct { _ struct{} `type:"structure"` // A structure containing details about the IAM user. // + // Due to a service issue, password last used data does not include password + // use from May 3, 2018 22:50 PDT to May 23, 2018 14:08 PDT. This affects last + // sign-in (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html) + // dates shown in the IAM console and password last used dates in the IAM credential + // report (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html), + // and returned by this GetUser API. If users signed in during the affected + // time, the password last used date that is returned is the date the user last + // signed in before May 3, 2018. For users that signed in after May 23, 2018 + // 14:08 PDT, the returned password last used date is accurate. + // + // You can use password last used information to identify unused credentials + // for deletion. For example, you might delete users who did not sign in to + // AWS in the last 90 days. In cases like this, we recommend that you adjust + // your evaluation window to include dates after May 23, 2018. Alternatively, + // if your users use access keys to access AWS programmatically you can refer + // to access key last used information because it is accurate for all dates. + // // User is a required field User *User `type:"structure" required:"true"` } @@ -19514,24 +21874,23 @@ func (s *GetUserOutput) SetUser(v *User) *GetUserOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicyRequest type GetUserPolicyInput struct { _ struct{} `type:"structure"` // The name of the policy document to get. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` // The name of the user who the policy is associated with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -19582,7 +21941,6 @@ func (s *GetUserPolicyInput) SetUserName(v string) *GetUserPolicyInput { } // Contains the response to a successful GetUserPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetUserPolicyResponse type GetUserPolicyOutput struct { _ struct{} `type:"structure"` @@ -19632,14 +21990,13 @@ func (s *GetUserPolicyOutput) SetUserName(v string) *GetUserPolicyOutput { // Contains information about an IAM group entity. // -// This data type is used as a response element in the following actions: +// This data type is used as a response element in the following operations: // // * CreateGroup // // * GetGroup // // * ListGroups -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Group type Group struct { _ struct{} `type:"structure"` @@ -19654,7 +22011,7 @@ type Group struct { // when the group was created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // The stable and unique string identifying the group. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -19719,8 +22076,7 @@ func (s *Group) SetPath(v string) *Group { // Contains information about an IAM group, including all of the group's policies. // // This data type is used as a response element in the GetAccountAuthorizationDetails -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GroupDetail +// operation. type GroupDetail struct { _ struct{} `type:"structure"` @@ -19736,7 +22092,7 @@ type GroupDetail struct { // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the group was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The stable and unique string identifying the group. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -19809,7 +22165,7 @@ func (s *GroupDetail) SetPath(v string) *GroupDetail { // Contains information about an instance profile. // -// This data type is used as a response element in the following actions: +// This data type is used as a response element in the following operations: // // * CreateInstanceProfile // @@ -19818,7 +22174,6 @@ func (s *GroupDetail) SetPath(v string) *GroupDetail { // * ListInstanceProfiles // // * ListInstanceProfilesForRole -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/InstanceProfile type InstanceProfile struct { _ struct{} `type:"structure"` @@ -19833,7 +22188,7 @@ type InstanceProfile struct { // The date when the instance profile was created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // The stable and unique string identifying the instance profile. For more information // about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -19906,7 +22261,6 @@ func (s *InstanceProfile) SetRoles(v []*Role) *InstanceProfile { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeysRequest type ListAccessKeysInput struct { _ struct{} `type:"structure"` @@ -19916,22 +22270,22 @@ type ListAccessKeysInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the user. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -19983,7 +22337,6 @@ func (s *ListAccessKeysInput) SetUserName(v string) *ListAccessKeysInput { } // Contains the response to a successful ListAccessKeys request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccessKeysResponse type ListAccessKeysOutput struct { _ struct{} `type:"structure"` @@ -19997,7 +22350,7 @@ type ListAccessKeysOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20033,7 +22386,6 @@ func (s *ListAccessKeysOutput) SetMarker(v string) *ListAccessKeysOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliasesRequest type ListAccountAliasesInput struct { _ struct{} `type:"structure"` @@ -20043,15 +22395,15 @@ type ListAccountAliasesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` } @@ -20094,7 +22446,6 @@ func (s *ListAccountAliasesInput) SetMaxItems(v int64) *ListAccountAliasesInput } // Contains the response to a successful ListAccountAliases request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAccountAliasesResponse type ListAccountAliasesOutput struct { _ struct{} `type:"structure"` @@ -20109,7 +22460,7 @@ type ListAccountAliasesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20145,16 +22496,15 @@ func (s *ListAccountAliasesOutput) SetMarker(v string) *ListAccountAliasesOutput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPoliciesRequest type ListAttachedGroupPoliciesInput struct { _ struct{} `type:"structure"` // The name (friendly name, not ARN) of the group to list attached policies // for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -20165,25 +22515,26 @@ type ListAttachedGroupPoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. PathPrefix *string `type:"string"` } @@ -20244,7 +22595,6 @@ func (s *ListAttachedGroupPoliciesInput) SetPathPrefix(v string) *ListAttachedGr } // Contains the response to a successful ListAttachedGroupPolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedGroupPoliciesResponse type ListAttachedGroupPoliciesOutput struct { _ struct{} `type:"structure"` @@ -20256,7 +22606,7 @@ type ListAttachedGroupPoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20292,7 +22642,6 @@ func (s *ListAttachedGroupPoliciesOutput) SetMarker(v string) *ListAttachedGroup return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePoliciesRequest type ListAttachedRolePoliciesInput struct { _ struct{} `type:"structure"` @@ -20302,30 +22651,31 @@ type ListAttachedRolePoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. PathPrefix *string `type:"string"` // The name (friendly name, not ARN) of the role to list attached policies for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -20390,7 +22740,6 @@ func (s *ListAttachedRolePoliciesInput) SetRoleName(v string) *ListAttachedRoleP } // Contains the response to a successful ListAttachedRolePolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedRolePoliciesResponse type ListAttachedRolePoliciesOutput struct { _ struct{} `type:"structure"` @@ -20402,7 +22751,7 @@ type ListAttachedRolePoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20438,7 +22787,6 @@ func (s *ListAttachedRolePoliciesOutput) SetMarker(v string) *ListAttachedRolePo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPoliciesRequest type ListAttachedUserPoliciesInput struct { _ struct{} `type:"structure"` @@ -20448,32 +22796,33 @@ type ListAttachedUserPoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. PathPrefix *string `type:"string"` // The name (friendly name, not ARN) of the user to list attached policies for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -20536,7 +22885,6 @@ func (s *ListAttachedUserPoliciesInput) SetUserName(v string) *ListAttachedUserP } // Contains the response to a successful ListAttachedUserPolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListAttachedUserPoliciesResponse type ListAttachedUserPoliciesOutput struct { _ struct{} `type:"structure"` @@ -20548,7 +22896,7 @@ type ListAttachedUserPoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20584,7 +22932,6 @@ func (s *ListAttachedUserPoliciesOutput) SetMarker(v string) *ListAttachedUserPo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicyRequest type ListEntitiesForPolicyInput struct { _ struct{} `type:"structure"` @@ -20602,25 +22949,26 @@ type ListEntitiesForPolicyInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all entities. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. PathPrefix *string `min:"1" type:"string"` // The Amazon Resource Name (ARN) of the IAM policy for which you want the versions. @@ -20631,6 +22979,15 @@ type ListEntitiesForPolicyInput struct { // // PolicyArn is a required field PolicyArn *string `min:"20" type:"string" required:"true"` + + // The policy usage method to use for filtering the results. + // + // To list only permissions policies, set PolicyUsageFilter to PermissionsPolicy. + // To list only the policies used to set permissions boundaries, set the value + // to PermissionsBoundary. + // + // This parameter is optional. If it is not included, all policies are returned. + PolicyUsageFilter *string `type:"string" enum:"PolicyUsageType"` } // String returns the string representation @@ -20698,8 +23055,13 @@ func (s *ListEntitiesForPolicyInput) SetPolicyArn(v string) *ListEntitiesForPoli return s } +// SetPolicyUsageFilter sets the PolicyUsageFilter field's value. +func (s *ListEntitiesForPolicyInput) SetPolicyUsageFilter(v string) *ListEntitiesForPolicyInput { + s.PolicyUsageFilter = &v + return s +} + // Contains the response to a successful ListEntitiesForPolicy request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListEntitiesForPolicyResponse type ListEntitiesForPolicyOutput struct { _ struct{} `type:"structure"` @@ -20708,7 +23070,7 @@ type ListEntitiesForPolicyOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20765,15 +23127,14 @@ func (s *ListEntitiesForPolicyOutput) SetPolicyUsers(v []*PolicyUser) *ListEntit return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPoliciesRequest type ListGroupPoliciesInput struct { _ struct{} `type:"structure"` // The name of the group to list policies for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -20784,15 +23145,15 @@ type ListGroupPoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` } @@ -20847,7 +23208,6 @@ func (s *ListGroupPoliciesInput) SetMaxItems(v int64) *ListGroupPoliciesInput { } // Contains the response to a successful ListGroupPolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupPoliciesResponse type ListGroupPoliciesOutput struct { _ struct{} `type:"structure"` @@ -20856,7 +23216,7 @@ type ListGroupPoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -20865,9 +23225,9 @@ type ListGroupPoliciesOutput struct { // A list of policy names. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyNames is a required field PolicyNames []*string `type:"list" required:"true"` @@ -20901,7 +23261,6 @@ func (s *ListGroupPoliciesOutput) SetPolicyNames(v []*string) *ListGroupPolicies return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUserRequest type ListGroupsForUserInput struct { _ struct{} `type:"structure"` @@ -20911,22 +23270,22 @@ type ListGroupsForUserInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the user to list groups for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -20983,7 +23342,6 @@ func (s *ListGroupsForUserInput) SetUserName(v string) *ListGroupsForUserInput { } // Contains the response to a successful ListGroupsForUser request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsForUserResponse type ListGroupsForUserOutput struct { _ struct{} `type:"structure"` @@ -20997,7 +23355,7 @@ type ListGroupsForUserOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21033,7 +23391,6 @@ func (s *ListGroupsForUserOutput) SetMarker(v string) *ListGroupsForUserOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsRequest type ListGroupsInput struct { _ struct{} `type:"structure"` @@ -21043,26 +23400,27 @@ type ListGroupsInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example, the prefix /division_abc/subdivision_xyz/ // gets all groups whose path starts with /division_abc/subdivision_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash - // (/), listing all groups. This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) - // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // (/), listing all groups. This parameter allows (through its regex pattern + // (http://wikipedia.org/wiki/regex)) a string of characters consisting of either + // a forward slash (/) by itself or a string that must begin and end with forward + // slashes. In addition, it can contain any ASCII character from the ! (\u0021) + // through the DEL character (\u007F), including most punctuation characters, + // digits, and upper and lowercased letters. PathPrefix *string `min:"1" type:"string"` } @@ -21114,7 +23472,6 @@ func (s *ListGroupsInput) SetPathPrefix(v string) *ListGroupsInput { } // Contains the response to a successful ListGroups request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListGroupsResponse type ListGroupsOutput struct { _ struct{} `type:"structure"` @@ -21128,7 +23485,7 @@ type ListGroupsOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21164,7 +23521,6 @@ func (s *ListGroupsOutput) SetMarker(v string) *ListGroupsOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRoleRequest type ListInstanceProfilesForRoleInput struct { _ struct{} `type:"structure"` @@ -21174,20 +23530,20 @@ type ListInstanceProfilesForRoleInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the role to list instance profiles for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -21246,7 +23602,6 @@ func (s *ListInstanceProfilesForRoleInput) SetRoleName(v string) *ListInstancePr } // Contains the response to a successful ListInstanceProfilesForRole request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesForRoleResponse type ListInstanceProfilesForRoleOutput struct { _ struct{} `type:"structure"` @@ -21260,7 +23615,7 @@ type ListInstanceProfilesForRoleOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21296,7 +23651,6 @@ func (s *ListInstanceProfilesForRoleOutput) SetMarker(v string) *ListInstancePro return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesRequest type ListInstanceProfilesInput struct { _ struct{} `type:"structure"` @@ -21306,27 +23660,27 @@ type ListInstanceProfilesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example, the prefix /application_abc/component_xyz/ // gets all instance profiles whose path starts with /application_abc/component_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash - // (/), listing all instance profiles. This paramater allows (per its regex + // (/), listing all instance profiles. This parameter allows (through its regex // pattern (http://wikipedia.org/wiki/regex)) a string of characters consisting // of either a forward slash (/) by itself or a string that must begin and end - // with forward slashes, containing any ASCII character from the ! (\u0021) - // thru the DEL character (\u007F), including most punctuation characters, digits, - // and upper and lowercased letters. + // with forward slashes. In addition, it can contain any ASCII character from + // the ! (\u0021) through the DEL character (\u007F), including most punctuation + // characters, digits, and upper and lowercased letters. PathPrefix *string `min:"1" type:"string"` } @@ -21378,7 +23732,6 @@ func (s *ListInstanceProfilesInput) SetPathPrefix(v string) *ListInstanceProfile } // Contains the response to a successful ListInstanceProfiles request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListInstanceProfilesResponse type ListInstanceProfilesOutput struct { _ struct{} `type:"structure"` @@ -21392,7 +23745,7 @@ type ListInstanceProfilesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21428,7 +23781,6 @@ func (s *ListInstanceProfilesOutput) SetMarker(v string) *ListInstanceProfilesOu return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevicesRequest type ListMFADevicesInput struct { _ struct{} `type:"structure"` @@ -21438,22 +23790,22 @@ type ListMFADevicesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the user whose MFA devices you want to list. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -21505,7 +23857,6 @@ func (s *ListMFADevicesInput) SetUserName(v string) *ListMFADevicesInput { } // Contains the response to a successful ListMFADevices request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListMFADevicesResponse type ListMFADevicesOutput struct { _ struct{} `type:"structure"` @@ -21514,7 +23865,7 @@ type ListMFADevicesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // A list of MFA devices. @@ -21555,7 +23906,6 @@ func (s *ListMFADevicesOutput) SetMarker(v string) *ListMFADevicesOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProvidersRequest type ListOpenIDConnectProvidersInput struct { _ struct{} `type:"structure"` } @@ -21571,7 +23921,6 @@ func (s ListOpenIDConnectProvidersInput) GoString() string { } // Contains the response to a successful ListOpenIDConnectProviders request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListOpenIDConnectProvidersResponse type ListOpenIDConnectProvidersOutput struct { _ struct{} `type:"structure"` @@ -21584,18 +23933,194 @@ func (s ListOpenIDConnectProvidersOutput) String() string { return awsutil.Prettify(s) } -// GoString returns the string representation -func (s ListOpenIDConnectProvidersOutput) GoString() string { - return s.String() +// GoString returns the string representation +func (s ListOpenIDConnectProvidersOutput) GoString() string { + return s.String() +} + +// SetOpenIDConnectProviderList sets the OpenIDConnectProviderList field's value. +func (s *ListOpenIDConnectProvidersOutput) SetOpenIDConnectProviderList(v []*OpenIDConnectProviderListEntry) *ListOpenIDConnectProvidersOutput { + s.OpenIDConnectProviderList = v + return s +} + +// Contains details about the permissions policies that are attached to the +// specified identity (user, group, or role). +// +// This data type is used as a response element in the ListPoliciesGrantingServiceAccess +// operation. +type ListPoliciesGrantingServiceAccessEntry struct { + _ struct{} `type:"structure"` + + // The PoliciesGrantingServiceAccess object that contains details about the + // policy. + Policies []*PolicyGrantingServiceAccess `type:"list"` + + // The namespace of the service that was accessed. + // + // To learn the service namespace of a service, go to Actions, Resources, and + // Condition Keys for AWS Services (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html) + // in the IAM User Guide. Choose the name of the service to view details for + // that service. In the first paragraph, find the service prefix. For example, + // (service prefix: a4b). For more information about service namespaces, see + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the AWS General Reference. + ServiceNamespace *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListPoliciesGrantingServiceAccessEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPoliciesGrantingServiceAccessEntry) GoString() string { + return s.String() +} + +// SetPolicies sets the Policies field's value. +func (s *ListPoliciesGrantingServiceAccessEntry) SetPolicies(v []*PolicyGrantingServiceAccess) *ListPoliciesGrantingServiceAccessEntry { + s.Policies = v + return s +} + +// SetServiceNamespace sets the ServiceNamespace field's value. +func (s *ListPoliciesGrantingServiceAccessEntry) SetServiceNamespace(v string) *ListPoliciesGrantingServiceAccessEntry { + s.ServiceNamespace = &v + return s +} + +type ListPoliciesGrantingServiceAccessInput struct { + _ struct{} `type:"structure"` + + // The ARN of the IAM identity (user, group, or role) whose policies you want + // to list. + // + // Arn is a required field + Arn *string `min:"20" type:"string" required:"true"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // The service namespace for the AWS services whose policies you want to list. + // + // To learn the service namespace for a service, go to Actions, Resources, and + // Condition Keys for AWS Services (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html) + // in the IAM User Guide. Choose the name of the service to view details for + // that service. In the first paragraph, find the service prefix. For example, + // (service prefix: a4b). For more information about service namespaces, see + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the AWS General Reference. + // + // ServiceNamespaces is a required field + ServiceNamespaces []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s ListPoliciesGrantingServiceAccessInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPoliciesGrantingServiceAccessInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListPoliciesGrantingServiceAccessInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPoliciesGrantingServiceAccessInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 20)) + } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.ServiceNamespaces == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespaces")) + } + if s.ServiceNamespaces != nil && len(s.ServiceNamespaces) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServiceNamespaces", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *ListPoliciesGrantingServiceAccessInput) SetArn(v string) *ListPoliciesGrantingServiceAccessInput { + s.Arn = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *ListPoliciesGrantingServiceAccessInput) SetMarker(v string) *ListPoliciesGrantingServiceAccessInput { + s.Marker = &v + return s +} + +// SetServiceNamespaces sets the ServiceNamespaces field's value. +func (s *ListPoliciesGrantingServiceAccessInput) SetServiceNamespaces(v []*string) *ListPoliciesGrantingServiceAccessInput { + s.ServiceNamespaces = v + return s +} + +type ListPoliciesGrantingServiceAccessOutput struct { + _ struct{} `type:"structure"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Marker + // request parameter to retrieve more items. We recommend that you check IsTruncated + // after every call to ensure that you receive all your results. + IsTruncated *bool `type:"boolean"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` + + // A ListPoliciesGrantingServiceAccess object that contains details about the + // permissions policies attached to the specified identity (user, group, or + // role). + // + // PoliciesGrantingServiceAccess is a required field + PoliciesGrantingServiceAccess []*ListPoliciesGrantingServiceAccessEntry `type:"list" required:"true"` +} + +// String returns the string representation +func (s ListPoliciesGrantingServiceAccessOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPoliciesGrantingServiceAccessOutput) GoString() string { + return s.String() +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListPoliciesGrantingServiceAccessOutput) SetIsTruncated(v bool) *ListPoliciesGrantingServiceAccessOutput { + s.IsTruncated = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *ListPoliciesGrantingServiceAccessOutput) SetMarker(v string) *ListPoliciesGrantingServiceAccessOutput { + s.Marker = &v + return s } -// SetOpenIDConnectProviderList sets the OpenIDConnectProviderList field's value. -func (s *ListOpenIDConnectProvidersOutput) SetOpenIDConnectProviderList(v []*OpenIDConnectProviderListEntry) *ListOpenIDConnectProvidersOutput { - s.OpenIDConnectProviderList = v +// SetPoliciesGrantingServiceAccess sets the PoliciesGrantingServiceAccess field's value. +func (s *ListPoliciesGrantingServiceAccessOutput) SetPoliciesGrantingServiceAccess(v []*ListPoliciesGrantingServiceAccessEntry) *ListPoliciesGrantingServiceAccessOutput { + s.PoliciesGrantingServiceAccess = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPoliciesRequest type ListPoliciesInput struct { _ struct{} `type:"structure"` @@ -21605,15 +24130,15 @@ type ListPoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // A flag to filter the results to only the attached policies. @@ -21625,13 +24150,23 @@ type ListPoliciesInput struct { // The path prefix for filtering the results. This parameter is optional. If // it is not included, it defaults to a slash (/), listing all policies. This - // paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. PathPrefix *string `type:"string"` + // The policy usage method to use for filtering the results. + // + // To list only permissions policies, set PolicyUsageFilter to PermissionsPolicy. + // To list only the policies used to set permissions boundaries, set the value + // to PermissionsBoundary. + // + // This parameter is optional. If it is not included, all policies are returned. + PolicyUsageFilter *string `type:"string" enum:"PolicyUsageType"` + // The scope to use for filtering the results. // // To list only AWS managed policies, set Scope to AWS. To list only the customer @@ -21692,6 +24227,12 @@ func (s *ListPoliciesInput) SetPathPrefix(v string) *ListPoliciesInput { return s } +// SetPolicyUsageFilter sets the PolicyUsageFilter field's value. +func (s *ListPoliciesInput) SetPolicyUsageFilter(v string) *ListPoliciesInput { + s.PolicyUsageFilter = &v + return s +} + // SetScope sets the Scope field's value. func (s *ListPoliciesInput) SetScope(v string) *ListPoliciesInput { s.Scope = &v @@ -21699,7 +24240,6 @@ func (s *ListPoliciesInput) SetScope(v string) *ListPoliciesInput { } // Contains the response to a successful ListPolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPoliciesResponse type ListPoliciesOutput struct { _ struct{} `type:"structure"` @@ -21708,7 +24248,7 @@ type ListPoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21747,7 +24287,6 @@ func (s *ListPoliciesOutput) SetPolicies(v []*Policy) *ListPoliciesOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersionsRequest type ListPolicyVersionsInput struct { _ struct{} `type:"structure"` @@ -21757,15 +24296,15 @@ type ListPolicyVersionsInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The Amazon Resource Name (ARN) of the IAM policy for which you want the versions. @@ -21829,7 +24368,6 @@ func (s *ListPolicyVersionsInput) SetPolicyArn(v string) *ListPolicyVersionsInpu } // Contains the response to a successful ListPolicyVersions request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListPolicyVersionsResponse type ListPolicyVersionsOutput struct { _ struct{} `type:"structure"` @@ -21838,7 +24376,7 @@ type ListPolicyVersionsOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -21881,7 +24419,6 @@ func (s *ListPolicyVersionsOutput) SetVersions(v []*PolicyVersion) *ListPolicyVe return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePoliciesRequest type ListRolePoliciesInput struct { _ struct{} `type:"structure"` @@ -21891,20 +24428,20 @@ type ListRolePoliciesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the role to list policies for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -21963,7 +24500,6 @@ func (s *ListRolePoliciesInput) SetRoleName(v string) *ListRolePoliciesInput { } // Contains the response to a successful ListRolePolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolePoliciesResponse type ListRolePoliciesOutput struct { _ struct{} `type:"structure"` @@ -21972,7 +24508,7 @@ type ListRolePoliciesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -22013,36 +24549,168 @@ func (s *ListRolePoliciesOutput) SetPolicyNames(v []*string) *ListRolePoliciesOu return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolesRequest -type ListRolesInput struct { +type ListRoleTagsInput struct { _ struct{} `type:"structure"` // Use this parameter only when paginating results and only after you receive // a response indicating that the results are truncated. Set it to the value - // of the Marker element in the response that you received to indicate where - // the next call should start. + // of the Marker element in the response to indicate where the next call should + // start. Marker *string `min:"1" type:"string"` // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // number of items that you want in the response. If additional items exist + // beyond the maximum that you specify, the IsTruncated response element is + // true. // // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue + // return fewer results, even when more results are available. In that case, + // the IsTruncated response element returns true, and Marker contains a value + // to include in the subsequent call that tells the service where to continue // from. MaxItems *int64 `min:"1" type:"integer"` + // The name of the IAM role for which you want to see the list of tags. + // + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: _+=,.@- + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListRoleTagsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRoleTagsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListRoleTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRoleTagsInput"} + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.MaxItems != nil && *s.MaxItems < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) + } + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMarker sets the Marker field's value. +func (s *ListRoleTagsInput) SetMarker(v string) *ListRoleTagsInput { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *ListRoleTagsInput) SetMaxItems(v int64) *ListRoleTagsInput { + s.MaxItems = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *ListRoleTagsInput) SetRoleName(v string) *ListRoleTagsInput { + s.RoleName = &v + return s +} + +type ListRoleTagsOutput struct { + _ struct{} `type:"structure"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can use the Marker request parameter to make a subsequent + // pagination request that retrieves more items. Note that IAM might return + // fewer than the MaxItems number of results even when more results are available. + // Check IsTruncated after every call to ensure that you receive all of your + // results. + IsTruncated *bool `type:"boolean"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` + + // The list of tags currently that is attached to the role. Each tag consists + // of a key name and an associated value. If no tags are attached to the specified + // role, the response contains an empty list. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} + +// String returns the string representation +func (s ListRoleTagsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRoleTagsOutput) GoString() string { + return s.String() +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListRoleTagsOutput) SetIsTruncated(v bool) *ListRoleTagsOutput { + s.IsTruncated = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *ListRoleTagsOutput) SetMarker(v string) *ListRoleTagsOutput { + s.Marker = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ListRoleTagsOutput) SetTags(v []*Tag) *ListRoleTagsOutput { + s.Tags = v + return s +} + +type ListRolesInput struct { + _ struct{} `type:"structure"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. + // + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + // The path prefix for filtering the results. For example, the prefix /application_abc/component_xyz/ // gets all roles whose path starts with /application_abc/component_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash - // (/), listing all roles. This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) - // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // (/), listing all roles. This parameter allows (through its regex pattern + // (http://wikipedia.org/wiki/regex)) a string of characters consisting of either + // a forward slash (/) by itself or a string that must begin and end with forward + // slashes. In addition, it can contain any ASCII character from the ! (\u0021) + // through the DEL character (\u007F), including most punctuation characters, + // digits, and upper and lowercased letters. PathPrefix *string `min:"1" type:"string"` } @@ -22094,7 +24762,6 @@ func (s *ListRolesInput) SetPathPrefix(v string) *ListRolesInput { } // Contains the response to a successful ListRoles request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListRolesResponse type ListRolesOutput struct { _ struct{} `type:"structure"` @@ -22103,7 +24770,7 @@ type ListRolesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -22144,7 +24811,6 @@ func (s *ListRolesOutput) SetRoles(v []*Role) *ListRolesOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProvidersRequest type ListSAMLProvidersInput struct { _ struct{} `type:"structure"` } @@ -22160,7 +24826,6 @@ func (s ListSAMLProvidersInput) GoString() string { } // Contains the response to a successful ListSAMLProviders request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSAMLProvidersResponse type ListSAMLProvidersOutput struct { _ struct{} `type:"structure"` @@ -22184,7 +24849,6 @@ func (s *ListSAMLProvidersOutput) SetSAMLProviderList(v []*SAMLProviderListEntry return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeysRequest type ListSSHPublicKeysInput struct { _ struct{} `type:"structure"` @@ -22194,24 +24858,24 @@ type ListSSHPublicKeysInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the IAM user to list SSH public keys for. If none is specified, // the UserName field is determined implicitly based on the AWS access key used // to sign the request. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -22263,7 +24927,6 @@ func (s *ListSSHPublicKeysInput) SetUserName(v string) *ListSSHPublicKeysInput { } // Contains the response to a successful ListSSHPublicKeys request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSSHPublicKeysResponse type ListSSHPublicKeysOutput struct { _ struct{} `type:"structure"` @@ -22272,7 +24935,7 @@ type ListSSHPublicKeysOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -22311,7 +24974,6 @@ func (s *ListSSHPublicKeysOutput) SetSSHPublicKeys(v []*SSHPublicKeyMetadata) *L return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificatesRequest type ListServerCertificatesInput struct { _ struct{} `type:"structure"` @@ -22321,27 +24983,27 @@ type ListServerCertificatesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example: /company/servercerts // would get all server certificates for which the path starts with /company/servercerts. // // This parameter is optional. If it is not included, it defaults to a slash - // (/), listing all server certificates. This paramater allows (per its regex - // pattern (http://wikipedia.org/wiki/regex)) a string of characters consisting + // (/), listing all server certificates. This parameter allows (through its + // regex pattern (http://wikipedia.org/wiki/regex)) a string of characters consisting // of either a forward slash (/) by itself or a string that must begin and end - // with forward slashes, containing any ASCII character from the ! (\u0021) - // thru the DEL character (\u007F), including most punctuation characters, digits, - // and upper and lowercased letters. + // with forward slashes. In addition, it can contain any ASCII character from + // the ! (\u0021) through the DEL character (\u007F), including most punctuation + // characters, digits, and upper and lowercased letters. PathPrefix *string `min:"1" type:"string"` } @@ -22393,7 +25055,6 @@ func (s *ListServerCertificatesInput) SetPathPrefix(v string) *ListServerCertifi } // Contains the response to a successful ListServerCertificates request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServerCertificatesResponse type ListServerCertificatesOutput struct { _ struct{} `type:"structure"` @@ -22402,7 +25063,7 @@ type ListServerCertificatesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -22443,7 +25104,6 @@ func (s *ListServerCertificatesOutput) SetServerCertificateMetadataList(v []*Ser return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentialsRequest type ListServiceSpecificCredentialsInput struct { _ struct{} `type:"structure"` @@ -22452,12 +25112,12 @@ type ListServiceSpecificCredentialsInput struct { ServiceName *string `type:"string"` // The name of the user whose service-specific credentials you want information - // about. If this value is not specified then the operation assumes the user + // about. If this value is not specified, then the operation assumes the user // whose credentials are used to call the operation. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -22496,7 +25156,6 @@ func (s *ListServiceSpecificCredentialsInput) SetUserName(v string) *ListService return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListServiceSpecificCredentialsResponse type ListServiceSpecificCredentialsOutput struct { _ struct{} `type:"structure"` @@ -22520,7 +25179,6 @@ func (s *ListServiceSpecificCredentialsOutput) SetServiceSpecificCredentials(v [ return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificatesRequest type ListSigningCertificatesInput struct { _ struct{} `type:"structure"` @@ -22530,22 +25188,22 @@ type ListSigningCertificatesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The name of the IAM user whose signing certificates you want to examine. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -22597,7 +25255,6 @@ func (s *ListSigningCertificatesInput) SetUserName(v string) *ListSigningCertifi } // Contains the response to a successful ListSigningCertificates request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListSigningCertificatesResponse type ListSigningCertificatesOutput struct { _ struct{} `type:"structure"` @@ -22611,67 +25268,197 @@ type ListSigningCertificatesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. + IsTruncated *bool `type:"boolean"` + + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListSigningCertificatesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSigningCertificatesOutput) GoString() string { + return s.String() +} + +// SetCertificates sets the Certificates field's value. +func (s *ListSigningCertificatesOutput) SetCertificates(v []*SigningCertificate) *ListSigningCertificatesOutput { + s.Certificates = v + return s +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListSigningCertificatesOutput) SetIsTruncated(v bool) *ListSigningCertificatesOutput { + s.IsTruncated = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *ListSigningCertificatesOutput) SetMarker(v string) *ListSigningCertificatesOutput { + s.Marker = &v + return s +} + +type ListUserPoliciesInput struct { + _ struct{} `type:"structure"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. + // + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + + // The name of the user to list policies for. + // + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters consisting of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: _+=,.@- + // + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListUserPoliciesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListUserPoliciesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListUserPoliciesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUserPoliciesInput"} + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.MaxItems != nil && *s.MaxItems < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMarker sets the Marker field's value. +func (s *ListUserPoliciesInput) SetMarker(v string) *ListUserPoliciesInput { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *ListUserPoliciesInput) SetMaxItems(v int64) *ListUserPoliciesInput { + s.MaxItems = &v + return s +} + +// SetUserName sets the UserName field's value. +func (s *ListUserPoliciesInput) SetUserName(v string) *ListUserPoliciesInput { + s.UserName = &v + return s +} + +// Contains the response to a successful ListUserPolicies request. +type ListUserPoliciesOutput struct { + _ struct{} `type:"structure"` + + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Marker + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. Marker *string `min:"1" type:"string"` + + // A list of policy names. + // + // PolicyNames is a required field + PolicyNames []*string `type:"list" required:"true"` } // String returns the string representation -func (s ListSigningCertificatesOutput) String() string { +func (s ListUserPoliciesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListSigningCertificatesOutput) GoString() string { +func (s ListUserPoliciesOutput) GoString() string { return s.String() } -// SetCertificates sets the Certificates field's value. -func (s *ListSigningCertificatesOutput) SetCertificates(v []*SigningCertificate) *ListSigningCertificatesOutput { - s.Certificates = v - return s -} - // SetIsTruncated sets the IsTruncated field's value. -func (s *ListSigningCertificatesOutput) SetIsTruncated(v bool) *ListSigningCertificatesOutput { +func (s *ListUserPoliciesOutput) SetIsTruncated(v bool) *ListUserPoliciesOutput { s.IsTruncated = &v return s } // SetMarker sets the Marker field's value. -func (s *ListSigningCertificatesOutput) SetMarker(v string) *ListSigningCertificatesOutput { +func (s *ListUserPoliciesOutput) SetMarker(v string) *ListUserPoliciesOutput { s.Marker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPoliciesRequest -type ListUserPoliciesInput struct { +// SetPolicyNames sets the PolicyNames field's value. +func (s *ListUserPoliciesOutput) SetPolicyNames(v []*string) *ListUserPoliciesOutput { + s.PolicyNames = v + return s +} + +type ListUserTagsInput struct { _ struct{} `type:"structure"` // Use this parameter only when paginating results and only after you receive // a response indicating that the results are truncated. Set it to the value - // of the Marker element in the response that you received to indicate where - // the next call should start. + // of the Marker element in the response to indicate where the next call should + // start. Marker *string `min:"1" type:"string"` // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // number of items that you want in the response. If additional items exist + // beyond the maximum that you specify, the IsTruncated response element is + // true. // // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue + // return fewer results, even when more results are available. In that case, + // the IsTruncated response element returns true, and Marker contains a value + // to include in the subsequent call that tells the service where to continue // from. MaxItems *int64 `min:"1" type:"integer"` - // The name of the user to list policies for. + // The name of the IAM user whose tags you want to see. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) - // a string of characters consisting of upper and lowercase alphanumeric characters + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: =,.@- // // UserName is a required field @@ -22679,18 +25466,18 @@ type ListUserPoliciesInput struct { } // String returns the string representation -func (s ListUserPoliciesInput) String() string { +func (s ListUserTagsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUserPoliciesInput) GoString() string { +func (s ListUserTagsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListUserPoliciesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListUserPoliciesInput"} +func (s *ListUserTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUserTagsInput"} if s.Marker != nil && len(*s.Marker) < 1 { invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) } @@ -22711,75 +25498,74 @@ func (s *ListUserPoliciesInput) Validate() error { } // SetMarker sets the Marker field's value. -func (s *ListUserPoliciesInput) SetMarker(v string) *ListUserPoliciesInput { +func (s *ListUserTagsInput) SetMarker(v string) *ListUserTagsInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *ListUserPoliciesInput) SetMaxItems(v int64) *ListUserPoliciesInput { +func (s *ListUserTagsInput) SetMaxItems(v int64) *ListUserTagsInput { s.MaxItems = &v return s } // SetUserName sets the UserName field's value. -func (s *ListUserPoliciesInput) SetUserName(v string) *ListUserPoliciesInput { +func (s *ListUserTagsInput) SetUserName(v string) *ListUserTagsInput { s.UserName = &v return s } -// Contains the response to a successful ListUserPolicies request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUserPoliciesResponse -type ListUserPoliciesOutput struct { +type ListUserTagsOutput struct { _ struct{} `type:"structure"` // A flag that indicates whether there are more items to return. If your results - // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. Note that IAM might return fewer - // than the MaxItems number of results even when there are more results available. - // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // were truncated, you can use the Marker request parameter to make a subsequent + // pagination request that retrieves more items. Note that IAM might return + // fewer than the MaxItems number of results even when more results are available. + // Check IsTruncated after every call to ensure that you receive all of your + // results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. Marker *string `min:"1" type:"string"` - // A list of policy names. + // The list of tags that are currently attached to the user. Each tag consists + // of a key name and an associated value. If no tags are attached to the specified + // user, the response contains an empty list. // - // PolicyNames is a required field - PolicyNames []*string `type:"list" required:"true"` + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` } // String returns the string representation -func (s ListUserPoliciesOutput) String() string { +func (s ListUserTagsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUserPoliciesOutput) GoString() string { +func (s ListUserTagsOutput) GoString() string { return s.String() } // SetIsTruncated sets the IsTruncated field's value. -func (s *ListUserPoliciesOutput) SetIsTruncated(v bool) *ListUserPoliciesOutput { +func (s *ListUserTagsOutput) SetIsTruncated(v bool) *ListUserTagsOutput { s.IsTruncated = &v return s } // SetMarker sets the Marker field's value. -func (s *ListUserPoliciesOutput) SetMarker(v string) *ListUserPoliciesOutput { +func (s *ListUserTagsOutput) SetMarker(v string) *ListUserTagsOutput { s.Marker = &v return s } -// SetPolicyNames sets the PolicyNames field's value. -func (s *ListUserPoliciesOutput) SetPolicyNames(v []*string) *ListUserPoliciesOutput { - s.PolicyNames = v +// SetTags sets the Tags field's value. +func (s *ListUserTagsOutput) SetTags(v []*Tag) *ListUserTagsOutput { + s.Tags = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsersRequest type ListUsersInput struct { _ struct{} `type:"structure"` @@ -22789,27 +25575,27 @@ type ListUsersInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` // The path prefix for filtering the results. For example: /division_abc/subdivision_xyz/, // which would get all user names whose path starts with /division_abc/subdivision_xyz/. // // This parameter is optional. If it is not included, it defaults to a slash - // (/), listing all user names. This paramater allows (per its regex pattern + // (/), listing all user names. This parameter allows (through its regex pattern // (http://wikipedia.org/wiki/regex)) a string of characters consisting of either // a forward slash (/) by itself or a string that must begin and end with forward - // slashes, containing any ASCII character from the ! (\u0021) thru the DEL - // character (\u007F), including most punctuation characters, digits, and upper - // and lowercased letters. + // slashes. In addition, it can contain any ASCII character from the ! (\u0021) + // through the DEL character (\u007F), including most punctuation characters, + // digits, and upper and lowercased letters. PathPrefix *string `min:"1" type:"string"` } @@ -22861,7 +25647,6 @@ func (s *ListUsersInput) SetPathPrefix(v string) *ListUsersInput { } // Contains the response to a successful ListUsers request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListUsersResponse type ListUsersOutput struct { _ struct{} `type:"structure"` @@ -22870,7 +25655,7 @@ type ListUsersOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -22911,13 +25696,12 @@ func (s *ListUsersOutput) SetUsers(v []*User) *ListUsersOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevicesRequest type ListVirtualMFADevicesInput struct { _ struct{} `type:"structure"` // The status (Unassigned or Assigned) of the devices to list. If you do not - // specify an AssignmentStatus, the action defaults to Any which lists both - // assigned and unassigned virtual MFA devices. + // specify an AssignmentStatus, the operation defaults to Any, which lists both + // assigned and unassigned virtual MFA devices., AssignmentStatus *string `type:"string" enum:"assignmentStatusType"` // Use this parameter only when paginating results and only after you receive @@ -22926,15 +25710,15 @@ type ListVirtualMFADevicesInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` } @@ -22983,7 +25767,6 @@ func (s *ListVirtualMFADevicesInput) SetMaxItems(v int64) *ListVirtualMFADevices } // Contains the response to a successful ListVirtualMFADevices request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ListVirtualMFADevicesResponse type ListVirtualMFADevicesOutput struct { _ struct{} `type:"structure"` @@ -22992,7 +25775,7 @@ type ListVirtualMFADevicesOutput struct { // request parameter to retrieve more items. Note that IAM might return fewer // than the MaxItems number of results even when there are more results available. // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. + // receive all your results. IsTruncated *bool `type:"boolean"` // When IsTruncated is true, this element is present and contains the value @@ -23037,15 +25820,14 @@ func (s *ListVirtualMFADevicesOutput) SetVirtualMFADevices(v []*VirtualMFADevice // Contains the user name and password create date for a user. // // This data type is used as a response element in the CreateLoginProfile and -// GetLoginProfile actions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/LoginProfile +// GetLoginProfile operations. type LoginProfile struct { _ struct{} `type:"structure"` // The date when the password for the user was created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // Specifies whether the user is required to set a new password on next sign-in. PasswordResetRequired *bool `type:"boolean"` @@ -23087,15 +25869,14 @@ func (s *LoginProfile) SetUserName(v string) *LoginProfile { // Contains information about an MFA device. // -// This data type is used as a response element in the ListMFADevices action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/MFADevice +// This data type is used as a response element in the ListMFADevices operation. type MFADevice struct { _ struct{} `type:"structure"` // The date when the MFA device was enabled for the user. // // EnableDate is a required field - EnableDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + EnableDate *time.Time `type:"timestamp" required:"true"` // The serial number that uniquely identifies the MFA device. For virtual MFA // devices, the serial number is the device ARN. @@ -23142,12 +25923,11 @@ func (s *MFADevice) SetUserName(v string) *MFADevice { // that the policy is attached to. // // This data type is used as a response element in the GetAccountAuthorizationDetails -// action. +// operation. // // For more information about managed policies, see Managed Policies and Inline // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ManagedPolicyDetail type ManagedPolicyDetail struct { _ struct{} `type:"structure"` @@ -23164,7 +25944,7 @@ type ManagedPolicyDetail struct { // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the policy was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The identifier for the version of the policy that is set as the default (operative) // version. @@ -23186,6 +25966,14 @@ type ManagedPolicyDetail struct { // in the Using IAM guide. Path *string `type:"string"` + // The number of entities (users and roles) for which the policy is used as + // the permissions boundary. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundaryUsageCount *int64 `type:"integer"` + // The stable and unique string identifying the policy. // // For more information about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -23205,7 +25993,7 @@ type ManagedPolicyDetail struct { // when the policy was created. When a policy has more than one version, this // field contains the date and time when the most recent policy version was // created. - UpdateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + UpdateDate *time.Time `type:"timestamp"` } // String returns the string representation @@ -23260,6 +26048,12 @@ func (s *ManagedPolicyDetail) SetPath(v string) *ManagedPolicyDetail { return s } +// SetPermissionsBoundaryUsageCount sets the PermissionsBoundaryUsageCount field's value. +func (s *ManagedPolicyDetail) SetPermissionsBoundaryUsageCount(v int64) *ManagedPolicyDetail { + s.PermissionsBoundaryUsageCount = &v + return s +} + // SetPolicyId sets the PolicyId field's value. func (s *ManagedPolicyDetail) SetPolicyId(v string) *ManagedPolicyDetail { s.PolicyId = &v @@ -23285,7 +26079,6 @@ func (s *ManagedPolicyDetail) SetUpdateDate(v time.Time) *ManagedPolicyDetail { } // Contains the Amazon Resource Name (ARN) for an IAM OpenID Connect provider. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/OpenIDConnectProviderListEntry type OpenIDConnectProviderListEntry struct { _ struct{} `type:"structure"` @@ -23313,12 +26106,11 @@ func (s *OpenIDConnectProviderListEntry) SetArn(v string) *OpenIDConnectProvider return s } -// Contains information about AWS Organizations's affect on a policy simulation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/OrganizationsDecisionDetail +// Contains information about AWS Organizations's effect on a policy simulation. type OrganizationsDecisionDetail struct { _ struct{} `type:"structure"` - // Specifies whether the simulated action is allowed by the AWS Organizations + // Specifies whether the simulated operation is allowed by the AWS Organizations // service control policies that impact the simulated user's account. AllowedByOrganizations *bool `type:"boolean"` } @@ -23342,8 +26134,7 @@ func (s *OrganizationsDecisionDetail) SetAllowedByOrganizations(v bool) *Organiz // Contains information about the account password policy. // // This data type is used as a response element in the GetAccountPasswordPolicy -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PasswordPolicy +// operation. type PasswordPolicy struct { _ struct{} `type:"structure"` @@ -23351,8 +26142,8 @@ type PasswordPolicy struct { AllowUsersToChangePassword *bool `type:"boolean"` // Indicates whether passwords in the account expire. Returns true if MaxPasswordAge - // is contains a value greater than 0. Returns false if MaxPasswordAge is 0 - // or not present. + // contains a value greater than 0. Returns false if MaxPasswordAge is 0 or + // not present. ExpirePasswords *bool `type:"boolean"` // Specifies whether IAM users are prevented from setting a new password after @@ -23455,12 +26246,11 @@ func (s *PasswordPolicy) SetRequireUppercaseCharacters(v bool) *PasswordPolicy { // Contains information about a managed policy. // // This data type is used as a response element in the CreatePolicy, GetPolicy, -// and ListPolicies actions. +// and ListPolicies operations. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Policy type Policy struct { _ struct{} `type:"structure"` @@ -23477,7 +26267,7 @@ type Policy struct { // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the policy was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The identifier for the version of the policy that is set as the default version. DefaultVersionId *string `type:"string"` @@ -23497,6 +26287,14 @@ type Policy struct { // in the Using IAM guide. Path *string `type:"string"` + // The number of entities (users and roles) for which the policy is used to + // set the permissions boundary. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundaryUsageCount *int64 `type:"integer"` + // The stable and unique string identifying the policy. // // For more information about IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -23513,7 +26311,7 @@ type Policy struct { // when the policy was created. When a policy has more than one version, this // field contains the date and time when the most recent policy version was // created. - UpdateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + UpdateDate *time.Time `type:"timestamp"` } // String returns the string representation @@ -23568,6 +26366,12 @@ func (s *Policy) SetPath(v string) *Policy { return s } +// SetPermissionsBoundaryUsageCount sets the PermissionsBoundaryUsageCount field's value. +func (s *Policy) SetPermissionsBoundaryUsageCount(v int64) *Policy { + s.PermissionsBoundaryUsageCount = &v + return s +} + // SetPolicyId sets the PolicyId field's value. func (s *Policy) SetPolicyId(v string) *Policy { s.PolicyId = &v @@ -23589,8 +26393,7 @@ func (s *Policy) SetUpdateDate(v time.Time) *Policy { // Contains information about an IAM policy, including the policy document. // // This data type is used as a response element in the GetAccountAuthorizationDetails -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PolicyDetail +// operation. type PolicyDetail struct { _ struct{} `type:"structure"` @@ -23623,15 +26426,97 @@ func (s *PolicyDetail) SetPolicyName(v string) *PolicyDetail { return s } +// Contains details about the permissions policies that are attached to the +// specified identity (user, group, or role). +// +// This data type is an element of the ListPoliciesGrantingServiceAccessEntry +// object. +type PolicyGrantingServiceAccess struct { + _ struct{} `type:"structure"` + + // The name of the entity (user or role) to which the inline policy is attached. + // + // This field is null for managed policies. For more information about these + // policy types, see Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html) + // in the IAM User Guide. + EntityName *string `min:"1" type:"string"` + + // The type of entity (user or role) that used the policy to access the service + // to which the inline policy is attached. + // + // This field is null for managed policies. For more information about these + // policy types, see Managed Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html) + // in the IAM User Guide. + EntityType *string `type:"string" enum:"policyOwnerEntityType"` + + // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. + // + // For more information about ARNs, go to Amazon Resource Names (ARNs) and AWS + // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + PolicyArn *string `min:"20" type:"string"` + + // The policy name. + // + // PolicyName is a required field + PolicyName *string `min:"1" type:"string" required:"true"` + + // The policy type. For more information about these policy types, see Managed + // Policies and Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html) + // in the IAM User Guide. + // + // PolicyType is a required field + PolicyType *string `type:"string" required:"true" enum:"policyType"` +} + +// String returns the string representation +func (s PolicyGrantingServiceAccess) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PolicyGrantingServiceAccess) GoString() string { + return s.String() +} + +// SetEntityName sets the EntityName field's value. +func (s *PolicyGrantingServiceAccess) SetEntityName(v string) *PolicyGrantingServiceAccess { + s.EntityName = &v + return s +} + +// SetEntityType sets the EntityType field's value. +func (s *PolicyGrantingServiceAccess) SetEntityType(v string) *PolicyGrantingServiceAccess { + s.EntityType = &v + return s +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *PolicyGrantingServiceAccess) SetPolicyArn(v string) *PolicyGrantingServiceAccess { + s.PolicyArn = &v + return s +} + +// SetPolicyName sets the PolicyName field's value. +func (s *PolicyGrantingServiceAccess) SetPolicyName(v string) *PolicyGrantingServiceAccess { + s.PolicyName = &v + return s +} + +// SetPolicyType sets the PolicyType field's value. +func (s *PolicyGrantingServiceAccess) SetPolicyType(v string) *PolicyGrantingServiceAccess { + s.PolicyType = &v + return s +} + // Contains information about a group that a managed policy is attached to. // // This data type is used as a response element in the ListEntitiesForPolicy -// action. +// operation. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PolicyGroup type PolicyGroup struct { _ struct{} `type:"structure"` @@ -23669,12 +26554,11 @@ func (s *PolicyGroup) SetGroupName(v string) *PolicyGroup { // Contains information about a role that a managed policy is attached to. // // This data type is used as a response element in the ListEntitiesForPolicy -// action. +// operation. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PolicyRole type PolicyRole struct { _ struct{} `type:"structure"` @@ -23712,12 +26596,11 @@ func (s *PolicyRole) SetRoleName(v string) *PolicyRole { // Contains information about a user that a managed policy is attached to. // // This data type is used as a response element in the ListEntitiesForPolicy -// action. +// operation. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PolicyUser type PolicyUser struct { _ struct{} `type:"structure"` @@ -23756,24 +26639,29 @@ func (s *PolicyUser) SetUserName(v string) *PolicyUser { // // This data type is used as a response element in the CreatePolicyVersion, // GetPolicyVersion, ListPolicyVersions, and GetAccountAuthorizationDetails -// actions. +// operations. // // For more information about managed policies, refer to Managed Policies and // Inline Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html) // in the Using IAM guide. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PolicyVersion type PolicyVersion struct { _ struct{} `type:"structure"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the policy version was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The policy document. // // The policy document is returned in the response to the GetPolicyVersion and // GetAccountAuthorizationDetails operations. It is not returned in the response // to the CreatePolicyVersion or ListPolicyVersions operations. + // + // The policy document returned in this structure is URL-encoded compliant with + // RFC 3986 (https://tools.ietf.org/html/rfc3986). You can use a URL decoding + // method to convert the policy back to plain JSON text. For example, if you + // use Java, you can use the decode method of the java.net.URLDecoder utility + // class in the Java SDK. Other languages and SDKs provide similar functionality. Document *string `min:"1" type:"string"` // Specifies whether the policy version is set as the policy's default version. @@ -23824,7 +26712,6 @@ func (s *PolicyVersion) SetVersionId(v string) *PolicyVersion { // document. // // This data type is used as a member of the Statement type. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Position type Position struct { _ struct{} `type:"structure"` @@ -23857,15 +26744,14 @@ func (s *Position) SetLine(v int64) *Position { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicyRequest type PutGroupPolicyInput struct { _ struct{} `type:"structure"` // The name of the group to associate the policy with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` @@ -23873,20 +26759,25 @@ type PutGroupPolicyInput struct { // The policy document. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -23948,7 +26839,6 @@ func (s *PutGroupPolicyInput) SetPolicyName(v string) *PutGroupPolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutGroupPolicyOutput type PutGroupPolicyOutput struct { _ struct{} `type:"structure"` } @@ -23963,34 +26853,112 @@ func (s PutGroupPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicyRequest +type PutRolePermissionsBoundaryInput struct { + _ struct{} `type:"structure"` + + // The ARN of the policy that is used to set the permissions boundary for the + // role. + // + // PermissionsBoundary is a required field + PermissionsBoundary *string `min:"20" type:"string" required:"true"` + + // The name (friendly name, not ARN) of the IAM role for which you want to set + // the permissions boundary. + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutRolePermissionsBoundaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRolePermissionsBoundaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutRolePermissionsBoundaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutRolePermissionsBoundaryInput"} + if s.PermissionsBoundary == nil { + invalidParams.Add(request.NewErrParamRequired("PermissionsBoundary")) + } + if s.PermissionsBoundary != nil && len(*s.PermissionsBoundary) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PermissionsBoundary", 20)) + } + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *PutRolePermissionsBoundaryInput) SetPermissionsBoundary(v string) *PutRolePermissionsBoundaryInput { + s.PermissionsBoundary = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *PutRolePermissionsBoundaryInput) SetRoleName(v string) *PutRolePermissionsBoundaryInput { + s.RoleName = &v + return s +} + +type PutRolePermissionsBoundaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s PutRolePermissionsBoundaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRolePermissionsBoundaryOutput) GoString() string { + return s.String() +} + type PutRolePolicyInput struct { _ struct{} `type:"structure"` // The policy document. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` // The name of the role to associate the policy with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -24026,8 +26994,88 @@ func (s *PutRolePolicyInput) Validate() error { if s.RoleName == nil { invalidParams.Add(request.NewErrParamRequired("RoleName")) } - if s.RoleName != nil && len(*s.RoleName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPolicyDocument sets the PolicyDocument field's value. +func (s *PutRolePolicyInput) SetPolicyDocument(v string) *PutRolePolicyInput { + s.PolicyDocument = &v + return s +} + +// SetPolicyName sets the PolicyName field's value. +func (s *PutRolePolicyInput) SetPolicyName(v string) *PutRolePolicyInput { + s.PolicyName = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *PutRolePolicyInput) SetRoleName(v string) *PutRolePolicyInput { + s.RoleName = &v + return s +} + +type PutRolePolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s PutRolePolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRolePolicyOutput) GoString() string { + return s.String() +} + +type PutUserPermissionsBoundaryInput struct { + _ struct{} `type:"structure"` + + // The ARN of the policy that is used to set the permissions boundary for the + // user. + // + // PermissionsBoundary is a required field + PermissionsBoundary *string `min:"20" type:"string" required:"true"` + + // The name (friendly name, not ARN) of the IAM user for which you want to set + // the permissions boundary. + // + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutUserPermissionsBoundaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutUserPermissionsBoundaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutUserPermissionsBoundaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutUserPermissionsBoundaryInput"} + if s.PermissionsBoundary == nil { + invalidParams.Add(request.NewErrParamRequired("PermissionsBoundary")) + } + if s.PermissionsBoundary != nil && len(*s.PermissionsBoundary) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PermissionsBoundary", 20)) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) } if invalidParams.Len() > 0 { @@ -24036,69 +27084,66 @@ func (s *PutRolePolicyInput) Validate() error { return nil } -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *PutRolePolicyInput) SetPolicyDocument(v string) *PutRolePolicyInput { - s.PolicyDocument = &v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *PutRolePolicyInput) SetPolicyName(v string) *PutRolePolicyInput { - s.PolicyName = &v +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *PutUserPermissionsBoundaryInput) SetPermissionsBoundary(v string) *PutUserPermissionsBoundaryInput { + s.PermissionsBoundary = &v return s } -// SetRoleName sets the RoleName field's value. -func (s *PutRolePolicyInput) SetRoleName(v string) *PutRolePolicyInput { - s.RoleName = &v +// SetUserName sets the UserName field's value. +func (s *PutUserPermissionsBoundaryInput) SetUserName(v string) *PutUserPermissionsBoundaryInput { + s.UserName = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutRolePolicyOutput -type PutRolePolicyOutput struct { +type PutUserPermissionsBoundaryOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutRolePolicyOutput) String() string { +func (s PutUserPermissionsBoundaryOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutRolePolicyOutput) GoString() string { +func (s PutUserPermissionsBoundaryOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicyRequest type PutUserPolicyInput struct { _ struct{} `type:"structure"` // The policy document. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the policy document. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@-+ + // with no spaces. You can also include any of the following characters: _+=,.@- // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` // The name of the user to associate the policy with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -24160,7 +27205,6 @@ func (s *PutUserPolicyInput) SetUserName(v string) *PutUserPolicyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/PutUserPolicyOutput type PutUserPolicyOutput struct { _ struct{} `type:"structure"` } @@ -24175,7 +27219,6 @@ func (s PutUserPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProviderRequest type RemoveClientIDFromOpenIDConnectProviderInput struct { _ struct{} `type:"structure"` @@ -24187,7 +27230,7 @@ type RemoveClientIDFromOpenIDConnectProviderInput struct { // The Amazon Resource Name (ARN) of the IAM OIDC provider resource to remove // the client ID from. You can get a list of OIDC provider ARNs by using the - // ListOpenIDConnectProviders action. + // ListOpenIDConnectProviders operation. // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) @@ -24241,7 +27284,6 @@ func (s *RemoveClientIDFromOpenIDConnectProviderInput) SetOpenIDConnectProviderA return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveClientIDFromOpenIDConnectProviderOutput type RemoveClientIDFromOpenIDConnectProviderOutput struct { _ struct{} `type:"structure"` } @@ -24256,22 +27298,21 @@ func (s RemoveClientIDFromOpenIDConnectProviderOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfileRequest type RemoveRoleFromInstanceProfileInput struct { _ struct{} `type:"structure"` // The name of the instance profile to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // InstanceProfileName is a required field InstanceProfileName *string `min:"1" type:"string" required:"true"` // The name of the role to remove. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -24323,7 +27364,6 @@ func (s *RemoveRoleFromInstanceProfileInput) SetRoleName(v string) *RemoveRoleFr return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveRoleFromInstanceProfileOutput type RemoveRoleFromInstanceProfileOutput struct { _ struct{} `type:"structure"` } @@ -24338,24 +27378,23 @@ func (s RemoveRoleFromInstanceProfileOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroupRequest type RemoveUserFromGroupInput struct { _ struct{} `type:"structure"` // The name of the group to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` // The name of the user to remove. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -24405,7 +27444,6 @@ func (s *RemoveUserFromGroupInput) SetUserName(v string) *RemoveUserFromGroupInp return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RemoveUserFromGroupOutput type RemoveUserFromGroupOutput struct { _ struct{} `type:"structure"` } @@ -24420,13 +27458,12 @@ func (s RemoveUserFromGroupOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredentialRequest type ResetServiceSpecificCredentialInput struct { _ struct{} `type:"structure"` // The unique identifier of the service-specific credential. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -24437,9 +27474,9 @@ type ResetServiceSpecificCredentialInput struct { // If this value is not specified, then the operation assumes the user whose // credentials are used to call the operation. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -24484,7 +27521,6 @@ func (s *ResetServiceSpecificCredentialInput) SetUserName(v string) *ResetServic return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResetServiceSpecificCredentialResponse type ResetServiceSpecificCredentialOutput struct { _ struct{} `type:"structure"` @@ -24512,11 +27548,10 @@ func (s *ResetServiceSpecificCredentialOutput) SetServiceSpecificCredential(v *S return s } -// Contains the result of the simulation of a single API action call on a single -// resource. +// Contains the result of the simulation of a single API operation call on a +// single resource. // // This data type is used by a member of the EvaluationResult data type. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResourceSpecificResult type ResourceSpecificResult struct { _ struct{} `type:"structure"` @@ -24527,7 +27562,7 @@ type ResourceSpecificResult struct { // caller's IAM policy must grant access. EvalDecisionDetails map[string]*string `type:"map"` - // The result of the simulation of the simulated API action on the resource + // The result of the simulation of the simulated API operation on the resource // specified in EvalResourceName. // // EvalResourceDecision is a required field @@ -24540,9 +27575,9 @@ type ResourceSpecificResult struct { // A list of the statements in the input policies that determine the result // for this part of the simulation. Remember that even if multiple statements - // allow the action on the resource, if any statement denies that action, then - // the explicit deny overrides any allow, and the deny statement is the only - // entry included in the result. + // allow the operation on the resource, if any statement denies that operation, + // then the explicit deny overrides any allow. In addition, the deny statement + // is the only entry included in the result. MatchedStatements []*Statement `type:"list"` // A list of context keys that are required by the included input policies but @@ -24596,7 +27631,6 @@ func (s *ResourceSpecificResult) SetMissingContextValues(v []*string) *ResourceS return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADeviceRequest type ResyncMFADeviceInput struct { _ struct{} `type:"structure"` @@ -24616,18 +27650,18 @@ type ResyncMFADeviceInput struct { // Serial number that uniquely identifies the MFA device. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // SerialNumber is a required field SerialNumber *string `min:"9" type:"string" required:"true"` // The name of the user whose MFA device you want to resynchronize. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -24701,7 +27735,6 @@ func (s *ResyncMFADeviceInput) SetUserName(v string) *ResyncMFADeviceInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ResyncMFADeviceOutput type ResyncMFADeviceOutput struct { _ struct{} `type:"structure"` } @@ -24717,8 +27750,7 @@ func (s ResyncMFADeviceOutput) GoString() string { } // Contains information about an IAM role. This structure is returned as a response -// element in several APIs that interact with roles. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Role +// element in several API operations that interact with roles. type Role struct { _ struct{} `type:"structure"` @@ -24736,11 +27768,17 @@ type Role struct { // when the role was created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // A description of the role that you provide. Description *string `type:"string"` + // The maximum session duration (in seconds) for the specified role. Anyone + // who uses the AWS CLI, or API to assume the role can specify the duration + // using the optional DurationSeconds API parameter or duration-seconds CLI + // parameter. + MaxSessionDuration *int64 `min:"3600" type:"integer"` + // The path to the role. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -24748,6 +27786,13 @@ type Role struct { // Path is a required field Path *string `min:"1" type:"string" required:"true"` + // The ARN of the policy used to set the permissions boundary for the role. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundary *AttachedPermissionsBoundary `type:"structure"` + // The stable and unique string identifying the role. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -24759,6 +27804,11 @@ type Role struct { // // RoleName is a required field RoleName *string `min:"1" type:"string" required:"true"` + + // A list of tags that are attached to the specified role. For more information + // about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -24795,12 +27845,24 @@ func (s *Role) SetDescription(v string) *Role { return s } +// SetMaxSessionDuration sets the MaxSessionDuration field's value. +func (s *Role) SetMaxSessionDuration(v int64) *Role { + s.MaxSessionDuration = &v + return s +} + // SetPath sets the Path field's value. func (s *Role) SetPath(v string) *Role { s.Path = &v return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *Role) SetPermissionsBoundary(v *AttachedPermissionsBoundary) *Role { + s.PermissionsBoundary = v + return s +} + // SetRoleId sets the RoleId field's value. func (s *Role) SetRoleId(v string) *Role { s.RoleId = &v @@ -24813,11 +27875,16 @@ func (s *Role) SetRoleName(v string) *Role { return s } +// SetTags sets the Tags field's value. +func (s *Role) SetTags(v []*Tag) *Role { + s.Tags = v + return s +} + // Contains information about an IAM role, including all of the role's policies. // // This data type is used as a response element in the GetAccountAuthorizationDetails -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RoleDetail +// operation. type RoleDetail struct { _ struct{} `type:"structure"` @@ -24837,7 +27904,7 @@ type RoleDetail struct { // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the role was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // A list of instance profiles that contain this role. InstanceProfileList []*InstanceProfile `type:"list"` @@ -24847,6 +27914,13 @@ type RoleDetail struct { // in the Using IAM guide. Path *string `min:"1" type:"string"` + // The ARN of the policy used to set the permissions boundary for the role. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundary *AttachedPermissionsBoundary `type:"structure"` + // The stable and unique string identifying the role. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -24858,6 +27932,11 @@ type RoleDetail struct { // A list of inline policies embedded in the role. These policies are the role's // access (permissions) policies. RolePolicyList []*PolicyDetail `type:"list"` + + // A list of tags that are attached to the specified role. For more information + // about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -24906,6 +27985,12 @@ func (s *RoleDetail) SetPath(v string) *RoleDetail { return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *RoleDetail) SetPermissionsBoundary(v *AttachedPermissionsBoundary) *RoleDetail { + s.PermissionsBoundary = v + return s +} + // SetRoleId sets the RoleId field's value. func (s *RoleDetail) SetRoleId(v string) *RoleDetail { s.RoleId = &v @@ -24924,11 +28009,17 @@ func (s *RoleDetail) SetRolePolicyList(v []*PolicyDetail) *RoleDetail { return s } -// An object that contains details about how a service-linked role is used. +// SetTags sets the Tags field's value. +func (s *RoleDetail) SetTags(v []*Tag) *RoleDetail { + s.Tags = v + return s +} + +// An object that contains details about how a service-linked role is used, +// if that information is returned by the service. // // This data type is used as a response element in the GetServiceLinkedRoleDeletionStatus // operation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/RoleUsageType type RoleUsageType struct { _ struct{} `type:"structure"` @@ -24962,7 +28053,6 @@ func (s *RoleUsageType) SetResources(v []*string) *RoleUsageType { } // Contains the list of SAML providers for this account. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SAMLProviderListEntry type SAMLProviderListEntry struct { _ struct{} `type:"structure"` @@ -24970,10 +28060,10 @@ type SAMLProviderListEntry struct { Arn *string `min:"20" type:"string"` // The date and time when the SAML provider was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // The expiration date and time for the SAML provider. - ValidUntil *time.Time `type:"timestamp" timestampFormat:"iso8601"` + ValidUntil *time.Time `type:"timestamp"` } // String returns the string representation @@ -25007,8 +28097,7 @@ func (s *SAMLProviderListEntry) SetValidUntil(v time.Time) *SAMLProviderListEntr // Contains information about an SSH public key. // // This data type is used as a response element in the GetSSHPublicKey and UploadSSHPublicKey -// actions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SSHPublicKey +// operations. type SSHPublicKey struct { _ struct{} `type:"structure"` @@ -25027,15 +28116,16 @@ type SSHPublicKey struct { // SSHPublicKeyId is a required field SSHPublicKeyId *string `min:"20" type:"string" required:"true"` - // The status of the SSH public key. Active means the key can be used for authentication - // with an AWS CodeCommit repository. Inactive means the key cannot be used. + // The status of the SSH public key. Active means that the key can be used for + // authentication with an AWS CodeCommit repository. Inactive means that the + // key cannot be used. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the SSH public key was uploaded. - UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + UploadDate *time.Time `type:"timestamp"` // The name of the IAM user associated with the SSH public key. // @@ -25091,8 +28181,7 @@ func (s *SSHPublicKey) SetUserName(v string) *SSHPublicKey { // Contains information about an SSH public key, without the key's body or fingerprint. // -// This data type is used as a response element in the ListSSHPublicKeys action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SSHPublicKeyMetadata +// This data type is used as a response element in the ListSSHPublicKeys operation. type SSHPublicKeyMetadata struct { _ struct{} `type:"structure"` @@ -25101,8 +28190,9 @@ type SSHPublicKeyMetadata struct { // SSHPublicKeyId is a required field SSHPublicKeyId *string `min:"20" type:"string" required:"true"` - // The status of the SSH public key. Active means the key can be used for authentication - // with an AWS CodeCommit repository. Inactive means the key cannot be used. + // The status of the SSH public key. Active means that the key can be used for + // authentication with an AWS CodeCommit repository. Inactive means that the + // key cannot be used. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` @@ -25111,7 +28201,7 @@ type SSHPublicKeyMetadata struct { // when the SSH public key was uploaded. // // UploadDate is a required field - UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + UploadDate *time.Time `type:"timestamp" required:"true"` // The name of the IAM user associated with the SSH public key. // @@ -25156,8 +28246,7 @@ func (s *SSHPublicKeyMetadata) SetUserName(v string) *SSHPublicKeyMetadata { // Contains information about a server certificate. // // This data type is used as a response element in the GetServerCertificate -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ServerCertificate +// operation. type ServerCertificate struct { _ struct{} `type:"structure"` @@ -25208,8 +28297,7 @@ func (s *ServerCertificate) SetServerCertificateMetadata(v *ServerCertificateMet // certificate chain, and private key. // // This data type is used as a response element in the UploadServerCertificate -// and ListServerCertificates actions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ServerCertificateMetadata +// and ListServerCertificates operations. type ServerCertificateMetadata struct { _ struct{} `type:"structure"` @@ -25222,7 +28310,7 @@ type ServerCertificateMetadata struct { Arn *string `min:"20" type:"string" required:"true"` // The date on which the certificate is set to expire. - Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601"` + Expiration *time.Time `type:"timestamp"` // The path to the server certificate. For more information about paths, see // IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -25244,7 +28332,7 @@ type ServerCertificateMetadata struct { ServerCertificateName *string `min:"1" type:"string" required:"true"` // The date when the server certificate was uploaded. - UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + UploadDate *time.Time `type:"timestamp"` } // String returns the string representation @@ -25293,8 +28381,95 @@ func (s *ServerCertificateMetadata) SetUploadDate(v time.Time) *ServerCertificat return s } -// Contains the details of a service specific credential. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ServiceSpecificCredential +// Contains details about the most recent attempt to access the service. +// +// This data type is used as a response element in the GetServiceLastAccessedDetails +// operation. +type ServiceLastAccessed struct { + _ struct{} `type:"structure"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when an authenticated entity most recently attempted to access the service. + // AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAuthenticated *time.Time `type:"timestamp"` + + // The ARN of the authenticated entity (user or role) that last attempted to + // access the service. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAuthenticatedEntity *string `min:"20" type:"string"` + + // The name of the service in which access was attempted. + // + // ServiceName is a required field + ServiceName *string `type:"string" required:"true"` + + // The namespace of the service in which access was attempted. + // + // To learn the service namespace of a service, go to Actions, Resources, and + // Condition Keys for AWS Services (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html) + // in the IAM User Guide. Choose the name of the service to view details for + // that service. In the first paragraph, find the service prefix. For example, + // (service prefix: a4b). For more information about service namespaces, see + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the AWS General Reference. + // + // ServiceNamespace is a required field + ServiceNamespace *string `min:"1" type:"string" required:"true"` + + // The total number of authenticated entities that have attempted to access + // the service. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + TotalAuthenticatedEntities *int64 `type:"integer"` +} + +// String returns the string representation +func (s ServiceLastAccessed) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceLastAccessed) GoString() string { + return s.String() +} + +// SetLastAuthenticated sets the LastAuthenticated field's value. +func (s *ServiceLastAccessed) SetLastAuthenticated(v time.Time) *ServiceLastAccessed { + s.LastAuthenticated = &v + return s +} + +// SetLastAuthenticatedEntity sets the LastAuthenticatedEntity field's value. +func (s *ServiceLastAccessed) SetLastAuthenticatedEntity(v string) *ServiceLastAccessed { + s.LastAuthenticatedEntity = &v + return s +} + +// SetServiceName sets the ServiceName field's value. +func (s *ServiceLastAccessed) SetServiceName(v string) *ServiceLastAccessed { + s.ServiceName = &v + return s +} + +// SetServiceNamespace sets the ServiceNamespace field's value. +func (s *ServiceLastAccessed) SetServiceNamespace(v string) *ServiceLastAccessed { + s.ServiceNamespace = &v + return s +} + +// SetTotalAuthenticatedEntities sets the TotalAuthenticatedEntities field's value. +func (s *ServiceLastAccessed) SetTotalAuthenticatedEntities(v int64) *ServiceLastAccessed { + s.TotalAuthenticatedEntities = &v + return s +} + +// Contains the details of a service-specific credential. type ServiceSpecificCredential struct { _ struct{} `type:"structure"` @@ -25302,7 +28477,7 @@ type ServiceSpecificCredential struct { // when the service-specific credential were created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // The name of the service associated with the service-specific credential. // @@ -25312,7 +28487,7 @@ type ServiceSpecificCredential struct { // The generated password for the service-specific credential. // // ServicePassword is a required field - ServicePassword *string `type:"string" required:"true"` + ServicePassword *string `type:"string" required:"true" sensitive:"true"` // The unique identifier for the service-specific credential. // @@ -25327,8 +28502,8 @@ type ServiceSpecificCredential struct { // ServiceUserName is a required field ServiceUserName *string `min:"17" type:"string" required:"true"` - // The status of the service-specific credential. Active means the key is valid - // for API calls, while Inactive means it is not. + // The status of the service-specific credential. Active means that the key + // is valid for API calls, while Inactive means it is not. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` @@ -25392,7 +28567,6 @@ func (s *ServiceSpecificCredential) SetUserName(v string) *ServiceSpecificCreden } // Contains additional details about a service-specific credential. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/ServiceSpecificCredentialMetadata type ServiceSpecificCredentialMetadata struct { _ struct{} `type:"structure"` @@ -25400,7 +28574,7 @@ type ServiceSpecificCredentialMetadata struct { // when the service-specific credential were created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // The name of the service associated with the service-specific credential. // @@ -25417,8 +28591,8 @@ type ServiceSpecificCredentialMetadata struct { // ServiceUserName is a required field ServiceUserName *string `min:"17" type:"string" required:"true"` - // The status of the service-specific credential. Active means the key is valid - // for API calls, while Inactive means it is not. + // The status of the service-specific credential. Active means that the key + // is valid for API calls, while Inactive means it is not. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` @@ -25445,81 +28619,390 @@ func (s *ServiceSpecificCredentialMetadata) SetCreateDate(v time.Time) *ServiceS return s } -// SetServiceName sets the ServiceName field's value. -func (s *ServiceSpecificCredentialMetadata) SetServiceName(v string) *ServiceSpecificCredentialMetadata { - s.ServiceName = &v - return s +// SetServiceName sets the ServiceName field's value. +func (s *ServiceSpecificCredentialMetadata) SetServiceName(v string) *ServiceSpecificCredentialMetadata { + s.ServiceName = &v + return s +} + +// SetServiceSpecificCredentialId sets the ServiceSpecificCredentialId field's value. +func (s *ServiceSpecificCredentialMetadata) SetServiceSpecificCredentialId(v string) *ServiceSpecificCredentialMetadata { + s.ServiceSpecificCredentialId = &v + return s +} + +// SetServiceUserName sets the ServiceUserName field's value. +func (s *ServiceSpecificCredentialMetadata) SetServiceUserName(v string) *ServiceSpecificCredentialMetadata { + s.ServiceUserName = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ServiceSpecificCredentialMetadata) SetStatus(v string) *ServiceSpecificCredentialMetadata { + s.Status = &v + return s +} + +// SetUserName sets the UserName field's value. +func (s *ServiceSpecificCredentialMetadata) SetUserName(v string) *ServiceSpecificCredentialMetadata { + s.UserName = &v + return s +} + +type SetDefaultPolicyVersionInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the IAM policy whose default version you + // want to set. + // + // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS + // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + // + // PolicyArn is a required field + PolicyArn *string `min:"20" type:"string" required:"true"` + + // The version of the policy to set as the default (operative) version. + // + // For more information about managed policy versions, see Versioning for Managed + // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) + // in the IAM User Guide. + // + // VersionId is a required field + VersionId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s SetDefaultPolicyVersionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SetDefaultPolicyVersionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *SetDefaultPolicyVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SetDefaultPolicyVersionInput"} + if s.PolicyArn == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyArn")) + } + if s.PolicyArn != nil && len(*s.PolicyArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PolicyArn", 20)) + } + if s.VersionId == nil { + invalidParams.Add(request.NewErrParamRequired("VersionId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *SetDefaultPolicyVersionInput) SetPolicyArn(v string) *SetDefaultPolicyVersionInput { + s.PolicyArn = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *SetDefaultPolicyVersionInput) SetVersionId(v string) *SetDefaultPolicyVersionInput { + s.VersionId = &v + return s +} + +type SetDefaultPolicyVersionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s SetDefaultPolicyVersionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SetDefaultPolicyVersionOutput) GoString() string { + return s.String() +} + +// Contains information about an X.509 signing certificate. +// +// This data type is used as a response element in the UploadSigningCertificate +// and ListSigningCertificates operations. +type SigningCertificate struct { + _ struct{} `type:"structure"` + + // The contents of the signing certificate. + // + // CertificateBody is a required field + CertificateBody *string `min:"1" type:"string" required:"true"` + + // The ID for the signing certificate. + // + // CertificateId is a required field + CertificateId *string `min:"24" type:"string" required:"true"` + + // The status of the signing certificate. Active means that the key is valid + // for API calls, while Inactive means it is not. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"statusType"` + + // The date when the signing certificate was uploaded. + UploadDate *time.Time `type:"timestamp"` + + // The name of the user the signing certificate is associated with. + // + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s SigningCertificate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SigningCertificate) GoString() string { + return s.String() } -// SetServiceSpecificCredentialId sets the ServiceSpecificCredentialId field's value. -func (s *ServiceSpecificCredentialMetadata) SetServiceSpecificCredentialId(v string) *ServiceSpecificCredentialMetadata { - s.ServiceSpecificCredentialId = &v +// SetCertificateBody sets the CertificateBody field's value. +func (s *SigningCertificate) SetCertificateBody(v string) *SigningCertificate { + s.CertificateBody = &v return s } -// SetServiceUserName sets the ServiceUserName field's value. -func (s *ServiceSpecificCredentialMetadata) SetServiceUserName(v string) *ServiceSpecificCredentialMetadata { - s.ServiceUserName = &v +// SetCertificateId sets the CertificateId field's value. +func (s *SigningCertificate) SetCertificateId(v string) *SigningCertificate { + s.CertificateId = &v return s } // SetStatus sets the Status field's value. -func (s *ServiceSpecificCredentialMetadata) SetStatus(v string) *ServiceSpecificCredentialMetadata { +func (s *SigningCertificate) SetStatus(v string) *SigningCertificate { s.Status = &v return s } +// SetUploadDate sets the UploadDate field's value. +func (s *SigningCertificate) SetUploadDate(v time.Time) *SigningCertificate { + s.UploadDate = &v + return s +} + // SetUserName sets the UserName field's value. -func (s *ServiceSpecificCredentialMetadata) SetUserName(v string) *ServiceSpecificCredentialMetadata { +func (s *SigningCertificate) SetUserName(v string) *SigningCertificate { s.UserName = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersionRequest -type SetDefaultPolicyVersionInput struct { +type SimulateCustomPolicyInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the IAM policy whose default version you - // want to set. + // A list of names of API operations to evaluate in the simulation. Each operation + // is evaluated against each resource. Each operation must include the service + // identifier, such as iam:CreateUser. + // + // ActionNames is a required field + ActionNames []*string `type:"list" required:"true"` + + // The ARN of the IAM user that you want to use as the simulated caller of the + // API operations. CallerArn is required if you include a ResourcePolicy so + // that the policy's Principal element has a value to use in evaluating the + // policy. + // + // You can specify only the ARN of an IAM user. You cannot specify the ARN of + // an assumed role, federated user, or a service principal. + CallerArn *string `min:"1" type:"string"` + + // A list of context keys and corresponding values for the simulation to use. + // Whenever a context key is evaluated in one of the simulated IAM permission + // policies, the corresponding value is supplied. + ContextEntries []*ContextEntry `type:"list"` + + // Use this parameter only when paginating results and only after you receive + // a response indicating that the results are truncated. Set it to the value + // of the Marker element in the response that you received to indicate where + // the next call should start. + Marker *string `min:"1" type:"string"` + + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. + // + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. + MaxItems *int64 `min:"1" type:"integer"` + + // A list of policy documents to include in the simulation. Each document is + // specified as a string containing the complete, valid JSON text of an IAM + // policy. Do not include any resource-based policies in this parameter. Any + // resource-based policy must be submitted with the ResourcePolicy parameter. + // The policies cannot be "scope-down" policies, such as you could include in + // a call to GetFederationToken (http://docs.aws.amazon.com/IAM/latest/APIReference/API_GetFederationToken.html) + // or one of the AssumeRole (http://docs.aws.amazon.com/IAM/latest/APIReference/API_AssumeRole.html) + // API operations. In other words, do not use policies designed to restrict + // what a user can do while using the temporary credentials. + // + // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) + // + // PolicyInputList is a required field + PolicyInputList []*string `type:"list" required:"true"` + + // A list of ARNs of AWS resources to include in the simulation. If this parameter + // is not provided, then the value defaults to * (all resources). Each API in + // the ActionNames parameter is evaluated for each resource in this list. The + // simulation determines the access result (allowed or denied) of each combination + // and reports it in the response. + // + // The simulation does not automatically retrieve policies for the specified + // resources. If you want to include a resource policy in the simulation, then + // you must include the policy as a string in the ResourcePolicy parameter. + // + // If you include a ResourcePolicy, then it must be applicable to all of the + // resources included in the simulation or you receive an invalid input error. // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. + ResourceArns []*string `type:"list"` + + // Specifies the type of simulation to run. Different API operations that support + // resource-based policies require different combinations of resources. By specifying + // the type of simulation to run, you enable the policy simulator to enforce + // the presence of the required resources to ensure reliable simulation results. + // If your simulation does not match one of the following scenarios, then you + // can omit this parameter. The following list shows each of the supported scenario + // values and the resources that you must define to run the simulation. // - // PolicyArn is a required field - PolicyArn *string `min:"20" type:"string" required:"true"` + // Each of the EC2 scenarios requires that you specify instance, image, and + // security-group resources. If your scenario includes an EBS volume, then you + // must specify that volume as a resource. If the EC2 scenario includes VPC, + // then you must supply the network-interface resource. If it includes an IP + // subnet, then you must specify the subnet resource. For more information on + // the EC2 scenario options, see Supported Platforms (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html) + // in the Amazon EC2 User Guide. + // + // * EC2-Classic-InstanceStore + // + // instance, image, security-group + // + // * EC2-Classic-EBS + // + // instance, image, security-group, volume + // + // * EC2-VPC-InstanceStore + // + // instance, image, security-group, network-interface + // + // * EC2-VPC-InstanceStore-Subnet + // + // instance, image, security-group, network-interface, subnet + // + // * EC2-VPC-EBS + // + // instance, image, security-group, network-interface, volume + // + // * EC2-VPC-EBS-Subnet + // + // instance, image, security-group, network-interface, subnet, volume + ResourceHandlingOption *string `min:"1" type:"string"` - // The version of the policy to set as the default (operative) version. + // An ARN representing the AWS account ID that specifies the owner of any simulated + // resource that does not identify its owner in the resource ARN, such as an + // S3 bucket or object. If ResourceOwner is specified, it is also used as the + // account owner of any ResourcePolicy included in the simulation. If the ResourceOwner + // parameter is not specified, then the owner of the resources and the resource + // policy defaults to the account of the identity provided in CallerArn. This + // parameter is required only if you specify a resource-based policy and account + // that owns the resource is different from the account that owns the simulated + // calling user CallerArn. + // + // The ARN for an account uses the following syntax: arn:aws:iam::AWS-account-ID:root. + // For example, to represent the account with the 112233445566 ID, use the following + // ARN: arn:aws:iam::112233445566-ID:root. + ResourceOwner *string `min:"1" type:"string"` + + // A resource-based policy to include in the simulation provided as a string. + // Each resource in the simulation is treated as if it had this policy attached. + // You can include only one resource-based policy in a simulation. // - // For more information about managed policy versions, see Versioning for Managed - // Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html) - // in the IAM User Guide. + // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this + // parameter is a string of characters consisting of the following: // - // VersionId is a required field - VersionId *string `type:"string" required:"true"` + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) + ResourcePolicy *string `min:"1" type:"string"` } // String returns the string representation -func (s SetDefaultPolicyVersionInput) String() string { +func (s SimulateCustomPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SetDefaultPolicyVersionInput) GoString() string { +func (s SimulateCustomPolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *SetDefaultPolicyVersionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SetDefaultPolicyVersionInput"} - if s.PolicyArn == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyArn")) +func (s *SimulateCustomPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SimulateCustomPolicyInput"} + if s.ActionNames == nil { + invalidParams.Add(request.NewErrParamRequired("ActionNames")) } - if s.PolicyArn != nil && len(*s.PolicyArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PolicyArn", 20)) + if s.CallerArn != nil && len(*s.CallerArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CallerArn", 1)) } - if s.VersionId == nil { - invalidParams.Add(request.NewErrParamRequired("VersionId")) + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + if s.MaxItems != nil && *s.MaxItems < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) + } + if s.PolicyInputList == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyInputList")) + } + if s.ResourceHandlingOption != nil && len(*s.ResourceHandlingOption) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceHandlingOption", 1)) + } + if s.ResourceOwner != nil && len(*s.ResourceOwner) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceOwner", 1)) + } + if s.ResourcePolicy != nil && len(*s.ResourcePolicy) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourcePolicy", 1)) + } + if s.ContextEntries != nil { + for i, v := range s.ContextEntries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ContextEntries", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -25528,123 +29011,143 @@ func (s *SetDefaultPolicyVersionInput) Validate() error { return nil } -// SetPolicyArn sets the PolicyArn field's value. -func (s *SetDefaultPolicyVersionInput) SetPolicyArn(v string) *SetDefaultPolicyVersionInput { - s.PolicyArn = &v +// SetActionNames sets the ActionNames field's value. +func (s *SimulateCustomPolicyInput) SetActionNames(v []*string) *SimulateCustomPolicyInput { + s.ActionNames = v return s } -// SetVersionId sets the VersionId field's value. -func (s *SetDefaultPolicyVersionInput) SetVersionId(v string) *SetDefaultPolicyVersionInput { - s.VersionId = &v +// SetCallerArn sets the CallerArn field's value. +func (s *SimulateCustomPolicyInput) SetCallerArn(v string) *SimulateCustomPolicyInput { + s.CallerArn = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SetDefaultPolicyVersionOutput -type SetDefaultPolicyVersionOutput struct { - _ struct{} `type:"structure"` +// SetContextEntries sets the ContextEntries field's value. +func (s *SimulateCustomPolicyInput) SetContextEntries(v []*ContextEntry) *SimulateCustomPolicyInput { + s.ContextEntries = v + return s } -// String returns the string representation -func (s SetDefaultPolicyVersionOutput) String() string { - return awsutil.Prettify(s) +// SetMarker sets the Marker field's value. +func (s *SimulateCustomPolicyInput) SetMarker(v string) *SimulateCustomPolicyInput { + s.Marker = &v + return s } -// GoString returns the string representation -func (s SetDefaultPolicyVersionOutput) GoString() string { - return s.String() +// SetMaxItems sets the MaxItems field's value. +func (s *SimulateCustomPolicyInput) SetMaxItems(v int64) *SimulateCustomPolicyInput { + s.MaxItems = &v + return s } -// Contains information about an X.509 signing certificate. -// -// This data type is used as a response element in the UploadSigningCertificate -// and ListSigningCertificates actions. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SigningCertificate -type SigningCertificate struct { - _ struct{} `type:"structure"` +// SetPolicyInputList sets the PolicyInputList field's value. +func (s *SimulateCustomPolicyInput) SetPolicyInputList(v []*string) *SimulateCustomPolicyInput { + s.PolicyInputList = v + return s +} - // The contents of the signing certificate. - // - // CertificateBody is a required field - CertificateBody *string `min:"1" type:"string" required:"true"` +// SetResourceArns sets the ResourceArns field's value. +func (s *SimulateCustomPolicyInput) SetResourceArns(v []*string) *SimulateCustomPolicyInput { + s.ResourceArns = v + return s +} - // The ID for the signing certificate. - // - // CertificateId is a required field - CertificateId *string `min:"24" type:"string" required:"true"` +// SetResourceHandlingOption sets the ResourceHandlingOption field's value. +func (s *SimulateCustomPolicyInput) SetResourceHandlingOption(v string) *SimulateCustomPolicyInput { + s.ResourceHandlingOption = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *SimulateCustomPolicyInput) SetResourceOwner(v string) *SimulateCustomPolicyInput { + s.ResourceOwner = &v + return s +} + +// SetResourcePolicy sets the ResourcePolicy field's value. +func (s *SimulateCustomPolicyInput) SetResourcePolicy(v string) *SimulateCustomPolicyInput { + s.ResourcePolicy = &v + return s +} + +// Contains the response to a successful SimulatePrincipalPolicy or SimulateCustomPolicy +// request. +type SimulatePolicyResponse struct { + _ struct{} `type:"structure"` - // The status of the signing certificate. Active means the key is valid for - // API calls, while Inactive means it is not. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"statusType"` + // The results of the simulation. + EvaluationResults []*EvaluationResult `type:"list"` - // The date when the signing certificate was uploaded. - UploadDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + // A flag that indicates whether there are more items to return. If your results + // were truncated, you can make a subsequent pagination request using the Marker + // request parameter to retrieve more items. Note that IAM might return fewer + // than the MaxItems number of results even when there are more results available. + // We recommend that you check IsTruncated after every call to ensure that you + // receive all your results. + IsTruncated *bool `type:"boolean"` - // The name of the user the signing certificate is associated with. - // - // UserName is a required field - UserName *string `min:"1" type:"string" required:"true"` + // When IsTruncated is true, this element is present and contains the value + // to use for the Marker parameter in a subsequent pagination request. + Marker *string `min:"1" type:"string"` } // String returns the string representation -func (s SigningCertificate) String() string { +func (s SimulatePolicyResponse) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SigningCertificate) GoString() string { +func (s SimulatePolicyResponse) GoString() string { return s.String() } -// SetCertificateBody sets the CertificateBody field's value. -func (s *SigningCertificate) SetCertificateBody(v string) *SigningCertificate { - s.CertificateBody = &v - return s -} - -// SetCertificateId sets the CertificateId field's value. -func (s *SigningCertificate) SetCertificateId(v string) *SigningCertificate { - s.CertificateId = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *SigningCertificate) SetStatus(v string) *SigningCertificate { - s.Status = &v +// SetEvaluationResults sets the EvaluationResults field's value. +func (s *SimulatePolicyResponse) SetEvaluationResults(v []*EvaluationResult) *SimulatePolicyResponse { + s.EvaluationResults = v return s } -// SetUploadDate sets the UploadDate field's value. -func (s *SigningCertificate) SetUploadDate(v time.Time) *SigningCertificate { - s.UploadDate = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *SimulatePolicyResponse) SetIsTruncated(v bool) *SimulatePolicyResponse { + s.IsTruncated = &v return s } -// SetUserName sets the UserName field's value. -func (s *SigningCertificate) SetUserName(v string) *SigningCertificate { - s.UserName = &v +// SetMarker sets the Marker field's value. +func (s *SimulatePolicyResponse) SetMarker(v string) *SimulatePolicyResponse { + s.Marker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulateCustomPolicyRequest -type SimulateCustomPolicyInput struct { +type SimulatePrincipalPolicyInput struct { _ struct{} `type:"structure"` - // A list of names of API actions to evaluate in the simulation. Each action - // is evaluated against each resource. Each action must include the service - // identifier, such as iam:CreateUser. + // A list of names of API operations to evaluate in the simulation. Each operation + // is evaluated for each resource. Each operation must include the service identifier, + // such as iam:CreateUser. // // ActionNames is a required field ActionNames []*string `type:"list" required:"true"` - // The ARN of the IAM user that you want to use as the simulated caller of the - // APIs. CallerArn is required if you include a ResourcePolicy so that the policy's - // Principal element has a value to use in evaluating the policy. + // The ARN of the IAM user that you want to specify as the simulated caller + // of the API operations. If you do not specify a CallerArn, it defaults to + // the ARN of the user that you specify in PolicySourceArn, if you specified + // a user. If you include both a PolicySourceArn (for example, arn:aws:iam::123456789012:user/David) + // and a CallerArn (for example, arn:aws:iam::123456789012:user/Bob), the result + // is that you simulate calling the API operations as Bob, as if Bob had David's + // policies. // // You can specify only the ARN of an IAM user. You cannot specify the ARN of // an assumed role, federated user, or a service principal. + // + // CallerArn is required if you include a ResourcePolicy and the PolicySourceArn + // is not the ARN for an IAM user. This is required so that the resource-based + // policy's Principal element has a value to use in evaluating the policy. + // + // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS + // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. CallerArn *string `min:"1" type:"string"` // A list of context keys and corresponding values for the simulation to use. @@ -25658,38 +29161,49 @@ type SimulateCustomPolicyInput struct { // the next call should start. Marker *string `min:"1" type:"string"` - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. + // Use this only when paginating results to indicate the maximum number of items + // you want in the response. If additional items exist beyond the maximum you + // specify, the IsTruncated response element is true. // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. + // If you do not include this parameter, the number of items defaults to 100. + // Note that IAM might return fewer results, even when there are more results + // available. In that case, the IsTruncated response element returns true, and + // Marker contains a value to include in the subsequent call that tells the + // service where to continue from. MaxItems *int64 `min:"1" type:"integer"` - // A list of policy documents to include in the simulation. Each document is - // specified as a string containing the complete, valid JSON text of an IAM - // policy. Do not include any resource-based policies in this parameter. Any - // resource-based policy must be submitted with the ResourcePolicy parameter. - // The policies cannot be "scope-down" policies, such as you could include in - // a call to GetFederationToken (http://docs.aws.amazon.com/IAM/latest/APIReference/API_GetFederationToken.html) - // or one of the AssumeRole (http://docs.aws.amazon.com/IAM/latest/APIReference/API_AssumeRole.html) - // APIs to restrict what a user can do while using the temporary credentials. + // An optional list of additional policy documents to include in the simulation. + // Each document is specified as a string containing the complete, valid JSON + // text of an IAM policy. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: // - // PolicyInputList is a required field - PolicyInputList []*string `type:"list" required:"true"` + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) + PolicyInputList []*string `type:"list"` + + // The Amazon Resource Name (ARN) of a user, group, or role whose policies you + // want to include in the simulation. If you specify a user, group, or role, + // the simulation includes all policies that are associated with that entity. + // If you specify a user, the simulation also includes all policies that are + // attached to any groups the user belongs to. + // + // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS + // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + // + // PolicySourceArn is a required field + PolicySourceArn *string `min:"20" type:"string" required:"true"` // A list of ARNs of AWS resources to include in the simulation. If this parameter - // is not provided then the value defaults to * (all resources). Each API in + // is not provided, then the value defaults to * (all resources). Each API in // the ActionNames parameter is evaluated for each resource in this list. The // simulation determines the access result (allowed or denied) of each combination // and reports it in the response. @@ -25698,53 +29212,50 @@ type SimulateCustomPolicyInput struct { // resources. If you want to include a resource policy in the simulation, then // you must include the policy as a string in the ResourcePolicy parameter. // - // If you include a ResourcePolicy, then it must be applicable to all of the - // resources included in the simulation or you receive an invalid input error. - // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // in the AWS General Reference. ResourceArns []*string `type:"list"` - // Specifies the type of simulation to run. Different APIs that support resource-based - // policies require different combinations of resources. By specifying the type - // of simulation to run, you enable the policy simulator to enforce the presence - // of the required resources to ensure reliable simulation results. If your - // simulation does not match one of the following scenarios, then you can omit - // this parameter. The following list shows each of the supported scenario values - // and the resources that you must define to run the simulation. + // Specifies the type of simulation to run. Different API operations that support + // resource-based policies require different combinations of resources. By specifying + // the type of simulation to run, you enable the policy simulator to enforce + // the presence of the required resources to ensure reliable simulation results. + // If your simulation does not match one of the following scenarios, then you + // can omit this parameter. The following list shows each of the supported scenario + // values and the resources that you must define to run the simulation. // // Each of the EC2 scenarios requires that you specify instance, image, and - // security-group resources. If your scenario includes an EBS volume, then you + // security group resources. If your scenario includes an EBS volume, then you // must specify that volume as a resource. If the EC2 scenario includes VPC, - // then you must supply the network-interface resource. If it includes an IP + // then you must supply the network interface resource. If it includes an IP // subnet, then you must specify the subnet resource. For more information on // the EC2 scenario options, see Supported Platforms (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html) - // in the AWS EC2 User Guide. + // in the Amazon EC2 User Guide. // // * EC2-Classic-InstanceStore // - // instance, image, security-group + // instance, image, security group // // * EC2-Classic-EBS // - // instance, image, security-group, volume + // instance, image, security group, volume // // * EC2-VPC-InstanceStore // - // instance, image, security-group, network-interface + // instance, image, security group, network interface // // * EC2-VPC-InstanceStore-Subnet // - // instance, image, security-group, network-interface, subnet + // instance, image, security group, network interface, subnet // // * EC2-VPC-EBS // - // instance, image, security-group, network-interface, volume + // instance, image, security group, network interface, volume // // * EC2-VPC-EBS-Subnet // - // instance, image, security-group, network-interface, subnet, volume + // instance, image, security group, network interface, subnet, volume ResourceHandlingOption *string `min:"1" type:"string"` // An AWS account ID that specifies the owner of any simulated resource that @@ -25763,27 +29274,32 @@ type SimulateCustomPolicyInput struct { // You can include only one resource-based policy in a simulation. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) ResourcePolicy *string `min:"1" type:"string"` } // String returns the string representation -func (s SimulateCustomPolicyInput) String() string { +func (s SimulatePrincipalPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SimulateCustomPolicyInput) GoString() string { +func (s SimulatePrincipalPolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *SimulateCustomPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SimulateCustomPolicyInput"} +func (s *SimulatePrincipalPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SimulatePrincipalPolicyInput"} if s.ActionNames == nil { invalidParams.Add(request.NewErrParamRequired("ActionNames")) } @@ -25796,8 +29312,11 @@ func (s *SimulateCustomPolicyInput) Validate() error { if s.MaxItems != nil && *s.MaxItems < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) } - if s.PolicyInputList == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyInputList")) + if s.PolicySourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("PolicySourceArn")) + } + if s.PolicySourceArn != nil && len(*s.PolicySourceArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("PolicySourceArn", 20)) } if s.ResourceHandlingOption != nil && len(*s.ResourceHandlingOption) < 1 { invalidParams.Add(request.NewErrParamMinLen("ResourceHandlingOption", 1)) @@ -25826,319 +29345,326 @@ func (s *SimulateCustomPolicyInput) Validate() error { } // SetActionNames sets the ActionNames field's value. -func (s *SimulateCustomPolicyInput) SetActionNames(v []*string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetActionNames(v []*string) *SimulatePrincipalPolicyInput { s.ActionNames = v return s } // SetCallerArn sets the CallerArn field's value. -func (s *SimulateCustomPolicyInput) SetCallerArn(v string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetCallerArn(v string) *SimulatePrincipalPolicyInput { s.CallerArn = &v return s } // SetContextEntries sets the ContextEntries field's value. -func (s *SimulateCustomPolicyInput) SetContextEntries(v []*ContextEntry) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetContextEntries(v []*ContextEntry) *SimulatePrincipalPolicyInput { s.ContextEntries = v return s } // SetMarker sets the Marker field's value. -func (s *SimulateCustomPolicyInput) SetMarker(v string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetMarker(v string) *SimulatePrincipalPolicyInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *SimulateCustomPolicyInput) SetMaxItems(v int64) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetMaxItems(v int64) *SimulatePrincipalPolicyInput { s.MaxItems = &v return s } // SetPolicyInputList sets the PolicyInputList field's value. -func (s *SimulateCustomPolicyInput) SetPolicyInputList(v []*string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetPolicyInputList(v []*string) *SimulatePrincipalPolicyInput { s.PolicyInputList = v return s } +// SetPolicySourceArn sets the PolicySourceArn field's value. +func (s *SimulatePrincipalPolicyInput) SetPolicySourceArn(v string) *SimulatePrincipalPolicyInput { + s.PolicySourceArn = &v + return s +} + // SetResourceArns sets the ResourceArns field's value. -func (s *SimulateCustomPolicyInput) SetResourceArns(v []*string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetResourceArns(v []*string) *SimulatePrincipalPolicyInput { s.ResourceArns = v return s } // SetResourceHandlingOption sets the ResourceHandlingOption field's value. -func (s *SimulateCustomPolicyInput) SetResourceHandlingOption(v string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetResourceHandlingOption(v string) *SimulatePrincipalPolicyInput { s.ResourceHandlingOption = &v return s } // SetResourceOwner sets the ResourceOwner field's value. -func (s *SimulateCustomPolicyInput) SetResourceOwner(v string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetResourceOwner(v string) *SimulatePrincipalPolicyInput { s.ResourceOwner = &v return s } // SetResourcePolicy sets the ResourcePolicy field's value. -func (s *SimulateCustomPolicyInput) SetResourcePolicy(v string) *SimulateCustomPolicyInput { +func (s *SimulatePrincipalPolicyInput) SetResourcePolicy(v string) *SimulatePrincipalPolicyInput { s.ResourcePolicy = &v return s } -// Contains the response to a successful SimulatePrincipalPolicy or SimulateCustomPolicy -// request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePolicyResponse -type SimulatePolicyResponse struct { +// Contains a reference to a Statement element in a policy document that determines +// the result of the simulation. +// +// This data type is used by the MatchedStatements member of the EvaluationResult +// type. +type Statement struct { _ struct{} `type:"structure"` - // The results of the simulation. - EvaluationResults []*EvaluationResult `type:"list"` + // The row and column of the end of a Statement in an IAM policy. + EndPosition *Position `type:"structure"` - // A flag that indicates whether there are more items to return. If your results - // were truncated, you can make a subsequent pagination request using the Marker - // request parameter to retrieve more items. Note that IAM might return fewer - // than the MaxItems number of results even when there are more results available. - // We recommend that you check IsTruncated after every call to ensure that you - // receive all of your results. - IsTruncated *bool `type:"boolean"` + // The identifier of the policy that was provided as an input. + SourcePolicyId *string `type:"string"` + + // The type of the policy. + SourcePolicyType *string `type:"string" enum:"PolicySourceType"` + + // The row and column of the beginning of the Statement in an IAM policy. + StartPosition *Position `type:"structure"` +} + +// String returns the string representation +func (s Statement) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Statement) GoString() string { + return s.String() +} + +// SetEndPosition sets the EndPosition field's value. +func (s *Statement) SetEndPosition(v *Position) *Statement { + s.EndPosition = v + return s +} + +// SetSourcePolicyId sets the SourcePolicyId field's value. +func (s *Statement) SetSourcePolicyId(v string) *Statement { + s.SourcePolicyId = &v + return s +} + +// SetSourcePolicyType sets the SourcePolicyType field's value. +func (s *Statement) SetSourcePolicyType(v string) *Statement { + s.SourcePolicyType = &v + return s +} + +// SetStartPosition sets the StartPosition field's value. +func (s *Statement) SetStartPosition(v *Position) *Statement { + s.StartPosition = v + return s +} + +// A structure that represents user-provided metadata that can be associated +// with a resource such as an IAM user or role. For more information about tagging, +// see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) +// in the IAM User Guide. +type Tag struct { + _ struct{} `type:"structure"` + + // The key name that can be used to look up or retrieve the associated value. + // For example, Department or Cost Center are common choices. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // The value associated with this tag. For example, tags with a key name of + // Department could have values such as Human Resources, Accounting, and Support. + // Tags with a key name of Cost Center might have values that consist of the + // number associated with the different cost centers in your company. Typically, + // many resources have tags with the same key name but with different values. + // + // AWS always interprets the tag Value as a single string. If you need to store + // an array, you can store comma-separated values in the string. However, you + // must interpret the value in your code. + // + // Value is a required field + Value *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v + return s +} + +type TagRoleInput struct { + _ struct{} `type:"structure"` - // When IsTruncated is true, this element is present and contains the value - // to use for the Marker parameter in a subsequent pagination request. - Marker *string `min:"1" type:"string"` + // The name of the role that you want to add tags to. + // + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: _+=,.@- + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` + + // The list of tags that you want to attach to the role. Each tag consists of + // a key name and an associated value. You can specify this with a JSON string. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` } // String returns the string representation -func (s SimulatePolicyResponse) String() string { +func (s TagRoleInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SimulatePolicyResponse) GoString() string { +func (s TagRoleInput) GoString() string { return s.String() } -// SetEvaluationResults sets the EvaluationResults field's value. -func (s *SimulatePolicyResponse) SetEvaluationResults(v []*EvaluationResult) *SimulatePolicyResponse { - s.EvaluationResults = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagRoleInput"} + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetIsTruncated sets the IsTruncated field's value. -func (s *SimulatePolicyResponse) SetIsTruncated(v bool) *SimulatePolicyResponse { - s.IsTruncated = &v +// SetRoleName sets the RoleName field's value. +func (s *TagRoleInput) SetRoleName(v string) *TagRoleInput { + s.RoleName = &v return s } -// SetMarker sets the Marker field's value. -func (s *SimulatePolicyResponse) SetMarker(v string) *SimulatePolicyResponse { - s.Marker = &v +// SetTags sets the Tags field's value. +func (s *TagRoleInput) SetTags(v []*Tag) *TagRoleInput { + s.Tags = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/SimulatePrincipalPolicyRequest -type SimulatePrincipalPolicyInput struct { +type TagRoleOutput struct { _ struct{} `type:"structure"` +} - // A list of names of API actions to evaluate in the simulation. Each action - // is evaluated for each resource. Each action must include the service identifier, - // such as iam:CreateUser. - // - // ActionNames is a required field - ActionNames []*string `type:"list" required:"true"` - - // The ARN of the IAM user that you want to specify as the simulated caller - // of the APIs. If you do not specify a CallerArn, it defaults to the ARN of - // the user that you specify in PolicySourceArn, if you specified a user. If - // you include both a PolicySourceArn (for example, arn:aws:iam::123456789012:user/David) - // and a CallerArn (for example, arn:aws:iam::123456789012:user/Bob), the result - // is that you simulate calling the APIs as Bob, as if Bob had David's policies. - // - // You can specify only the ARN of an IAM user. You cannot specify the ARN of - // an assumed role, federated user, or a service principal. - // - // CallerArn is required if you include a ResourcePolicy and the PolicySourceArn - // is not the ARN for an IAM user. This is required so that the resource-based - // policy's Principal element has a value to use in evaluating the policy. - // - // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS - // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the AWS General Reference. - CallerArn *string `min:"1" type:"string"` - - // A list of context keys and corresponding values for the simulation to use. - // Whenever a context key is evaluated in one of the simulated IAM permission - // policies, the corresponding value is supplied. - ContextEntries []*ContextEntry `type:"list"` - - // Use this parameter only when paginating results and only after you receive - // a response indicating that the results are truncated. Set it to the value - // of the Marker element in the response that you received to indicate where - // the next call should start. - Marker *string `min:"1" type:"string"` - - // (Optional) Use this only when paginating results to indicate the maximum - // number of items you want in the response. If additional items exist beyond - // the maximum you specify, the IsTruncated response element is true. - // - // If you do not include this parameter, it defaults to 100. Note that IAM might - // return fewer results, even when there are more results available. In that - // case, the IsTruncated response element returns true and Marker contains a - // value to include in the subsequent call that tells the service where to continue - // from. - MaxItems *int64 `min:"1" type:"integer"` +// String returns the string representation +func (s TagRoleOutput) String() string { + return awsutil.Prettify(s) +} - // An optional list of additional policy documents to include in the simulation. - // Each document is specified as a string containing the complete, valid JSON - // text of an IAM policy. - // - // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). - PolicyInputList []*string `type:"list"` +// GoString returns the string representation +func (s TagRoleOutput) GoString() string { + return s.String() +} - // The Amazon Resource Name (ARN) of a user, group, or role whose policies you - // want to include in the simulation. If you specify a user, group, or role, - // the simulation includes all policies that are associated with that entity. - // If you specify a user, the simulation also includes all policies that are - // attached to any groups the user belongs to. - // - // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS - // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the AWS General Reference. - // - // PolicySourceArn is a required field - PolicySourceArn *string `min:"20" type:"string" required:"true"` +type TagUserInput struct { + _ struct{} `type:"structure"` - // A list of ARNs of AWS resources to include in the simulation. If this parameter - // is not provided then the value defaults to * (all resources). Each API in - // the ActionNames parameter is evaluated for each resource in this list. The - // simulation determines the access result (allowed or denied) of each combination - // and reports it in the response. - // - // The simulation does not automatically retrieve policies for the specified - // resources. If you want to include a resource policy in the simulation, then - // you must include the policy as a string in the ResourcePolicy parameter. + // The list of tags that you want to attach to the user. Each tag consists of + // a key name and an associated value. // - // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS - // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the AWS General Reference. - ResourceArns []*string `type:"list"` + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` - // Specifies the type of simulation to run. Different APIs that support resource-based - // policies require different combinations of resources. By specifying the type - // of simulation to run, you enable the policy simulator to enforce the presence - // of the required resources to ensure reliable simulation results. If your - // simulation does not match one of the following scenarios, then you can omit - // this parameter. The following list shows each of the supported scenario values - // and the resources that you must define to run the simulation. - // - // Each of the EC2 scenarios requires that you specify instance, image, and - // security-group resources. If your scenario includes an EBS volume, then you - // must specify that volume as a resource. If the EC2 scenario includes VPC, - // then you must supply the network-interface resource. If it includes an IP - // subnet, then you must specify the subnet resource. For more information on - // the EC2 scenario options, see Supported Platforms (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html) - // in the AWS EC2 User Guide. - // - // * EC2-Classic-InstanceStore + // The name of the user that you want to add tags to. // - // instance, image, security-group - // - // * EC2-Classic-EBS - // - // instance, image, security-group, volume - // - // * EC2-VPC-InstanceStore - // - // instance, image, security-group, network-interface - // - // * EC2-VPC-InstanceStore-Subnet - // - // instance, image, security-group, network-interface, subnet - // - // * EC2-VPC-EBS - // - // instance, image, security-group, network-interface, volume - // - // * EC2-VPC-EBS-Subnet - // - // instance, image, security-group, network-interface, subnet, volume - ResourceHandlingOption *string `min:"1" type:"string"` - - // An AWS account ID that specifies the owner of any simulated resource that - // does not identify its owner in the resource ARN, such as an S3 bucket or - // object. If ResourceOwner is specified, it is also used as the account owner - // of any ResourcePolicy included in the simulation. If the ResourceOwner parameter - // is not specified, then the owner of the resources and the resource policy - // defaults to the account of the identity provided in CallerArn. This parameter - // is required only if you specify a resource-based policy and account that - // owns the resource is different from the account that owns the simulated calling - // user CallerArn. - ResourceOwner *string `min:"1" type:"string"` - - // A resource-based policy to include in the simulation provided as a string. - // Each resource in the simulation is treated as if it had this policy attached. - // You can include only one resource-based policy in a simulation. + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: =,.@- // - // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). - ResourcePolicy *string `min:"1" type:"string"` + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s SimulatePrincipalPolicyInput) String() string { +func (s TagUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SimulatePrincipalPolicyInput) GoString() string { +func (s TagUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *SimulatePrincipalPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SimulatePrincipalPolicyInput"} - if s.ActionNames == nil { - invalidParams.Add(request.NewErrParamRequired("ActionNames")) - } - if s.CallerArn != nil && len(*s.CallerArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerArn", 1)) - } - if s.Marker != nil && len(*s.Marker) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) - } - if s.MaxItems != nil && *s.MaxItems < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) - } - if s.PolicySourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("PolicySourceArn")) - } - if s.PolicySourceArn != nil && len(*s.PolicySourceArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PolicySourceArn", 20)) - } - if s.ResourceHandlingOption != nil && len(*s.ResourceHandlingOption) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceHandlingOption", 1)) +func (s *TagUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagUserInput"} + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) } - if s.ResourceOwner != nil && len(*s.ResourceOwner) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceOwner", 1)) + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) } - if s.ResourcePolicy != nil && len(*s.ResourcePolicy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourcePolicy", 1)) + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) } - if s.ContextEntries != nil { - for i, v := range s.ContextEntries { + if s.Tags != nil { + for i, v := range s.Tags { if v == nil { continue } if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ContextEntries", i), err.(request.ErrInvalidParams)) + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) } } } @@ -26149,153 +29675,204 @@ func (s *SimulatePrincipalPolicyInput) Validate() error { return nil } -// SetActionNames sets the ActionNames field's value. -func (s *SimulatePrincipalPolicyInput) SetActionNames(v []*string) *SimulatePrincipalPolicyInput { - s.ActionNames = v +// SetTags sets the Tags field's value. +func (s *TagUserInput) SetTags(v []*Tag) *TagUserInput { + s.Tags = v return s } -// SetCallerArn sets the CallerArn field's value. -func (s *SimulatePrincipalPolicyInput) SetCallerArn(v string) *SimulatePrincipalPolicyInput { - s.CallerArn = &v +// SetUserName sets the UserName field's value. +func (s *TagUserInput) SetUserName(v string) *TagUserInput { + s.UserName = &v return s } -// SetContextEntries sets the ContextEntries field's value. -func (s *SimulatePrincipalPolicyInput) SetContextEntries(v []*ContextEntry) *SimulatePrincipalPolicyInput { - s.ContextEntries = v - return s +type TagUserOutput struct { + _ struct{} `type:"structure"` } -// SetMarker sets the Marker field's value. -func (s *SimulatePrincipalPolicyInput) SetMarker(v string) *SimulatePrincipalPolicyInput { - s.Marker = &v - return s +// String returns the string representation +func (s TagUserOutput) String() string { + return awsutil.Prettify(s) } -// SetMaxItems sets the MaxItems field's value. -func (s *SimulatePrincipalPolicyInput) SetMaxItems(v int64) *SimulatePrincipalPolicyInput { - s.MaxItems = &v - return s +// GoString returns the string representation +func (s TagUserOutput) GoString() string { + return s.String() +} + +type UntagRoleInput struct { + _ struct{} `type:"structure"` + + // The name of the IAM role from which you want to remove tags. + // + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: _+=,.@- + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` + + // A list of key names as a simple array of strings. The tags with matching + // keys are removed from the specified role. + // + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagRoleInput) GoString() string { + return s.String() } -// SetPolicyInputList sets the PolicyInputList field's value. -func (s *SimulatePrincipalPolicyInput) SetPolicyInputList(v []*string) *SimulatePrincipalPolicyInput { - s.PolicyInputList = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagRoleInput"} + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPolicySourceArn sets the PolicySourceArn field's value. -func (s *SimulatePrincipalPolicyInput) SetPolicySourceArn(v string) *SimulatePrincipalPolicyInput { - s.PolicySourceArn = &v +// SetRoleName sets the RoleName field's value. +func (s *UntagRoleInput) SetRoleName(v string) *UntagRoleInput { + s.RoleName = &v return s } -// SetResourceArns sets the ResourceArns field's value. -func (s *SimulatePrincipalPolicyInput) SetResourceArns(v []*string) *SimulatePrincipalPolicyInput { - s.ResourceArns = v +// SetTagKeys sets the TagKeys field's value. +func (s *UntagRoleInput) SetTagKeys(v []*string) *UntagRoleInput { + s.TagKeys = v return s } -// SetResourceHandlingOption sets the ResourceHandlingOption field's value. -func (s *SimulatePrincipalPolicyInput) SetResourceHandlingOption(v string) *SimulatePrincipalPolicyInput { - s.ResourceHandlingOption = &v - return s +type UntagRoleOutput struct { + _ struct{} `type:"structure"` } -// SetResourceOwner sets the ResourceOwner field's value. -func (s *SimulatePrincipalPolicyInput) SetResourceOwner(v string) *SimulatePrincipalPolicyInput { - s.ResourceOwner = &v - return s +// String returns the string representation +func (s UntagRoleOutput) String() string { + return awsutil.Prettify(s) } -// SetResourcePolicy sets the ResourcePolicy field's value. -func (s *SimulatePrincipalPolicyInput) SetResourcePolicy(v string) *SimulatePrincipalPolicyInput { - s.ResourcePolicy = &v - return s +// GoString returns the string representation +func (s UntagRoleOutput) GoString() string { + return s.String() } -// Contains a reference to a Statement element in a policy document that determines -// the result of the simulation. -// -// This data type is used by the MatchedStatements member of the EvaluationResult -// type. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/Statement -type Statement struct { +type UntagUserInput struct { _ struct{} `type:"structure"` - // The row and column of the end of a Statement in an IAM policy. - EndPosition *Position `type:"structure"` - - // The identifier of the policy that was provided as an input. - SourcePolicyId *string `type:"string"` - - // The type of the policy. - SourcePolicyType *string `type:"string" enum:"PolicySourceType"` + // A list of key names as a simple array of strings. The tags with matching + // keys are removed from the specified user. + // + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` - // The row and column of the beginning of the Statement in an IAM policy. - StartPosition *Position `type:"structure"` + // The name of the IAM user from which you want to remove tags. + // + // This parameter accepts (through its regex pattern (http://wikipedia.org/wiki/regex)) + // a string of characters that consist of upper and lowercase alphanumeric characters + // with no spaces. You can also include any of the following characters: =,.@- + // + // UserName is a required field + UserName *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s Statement) String() string { +func (s UntagUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Statement) GoString() string { +func (s UntagUserInput) GoString() string { return s.String() } -// SetEndPosition sets the EndPosition field's value. -func (s *Statement) SetEndPosition(v *Position) *Statement { - s.EndPosition = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagUserInput"} + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSourcePolicyId sets the SourcePolicyId field's value. -func (s *Statement) SetSourcePolicyId(v string) *Statement { - s.SourcePolicyId = &v +// SetTagKeys sets the TagKeys field's value. +func (s *UntagUserInput) SetTagKeys(v []*string) *UntagUserInput { + s.TagKeys = v return s } -// SetSourcePolicyType sets the SourcePolicyType field's value. -func (s *Statement) SetSourcePolicyType(v string) *Statement { - s.SourcePolicyType = &v +// SetUserName sets the UserName field's value. +func (s *UntagUserInput) SetUserName(v string) *UntagUserInput { + s.UserName = &v return s } -// SetStartPosition sets the StartPosition field's value. -func (s *Statement) SetStartPosition(v *Position) *Statement { - s.StartPosition = v - return s +type UntagUserOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UntagUserOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagUserOutput) GoString() string { + return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKeyRequest type UpdateAccessKeyInput struct { _ struct{} `type:"structure"` // The access key ID of the secret access key you want to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // // AccessKeyId is a required field AccessKeyId *string `min:"16" type:"string" required:"true"` - // The status you want to assign to the secret access key. Active means the - // key can be used for API calls to AWS, while Inactive means the key cannot - // be used. + // The status you want to assign to the secret access key. Active means that + // the key can be used for API calls to AWS, while Inactive means that the key + // cannot be used. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` // The name of the user whose key you want to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -26349,7 +29926,6 @@ func (s *UpdateAccessKeyInput) SetUserName(v string) *UpdateAccessKeyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccessKeyOutput type UpdateAccessKeyOutput struct { _ struct{} `type:"structure"` } @@ -26364,7 +29940,6 @@ func (s UpdateAccessKeyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicyRequest type UpdateAccountPasswordPolicyInput struct { _ struct{} `type:"structure"` @@ -26373,42 +29948,53 @@ type UpdateAccountPasswordPolicyInput struct { // Their Own Passwords (http://docs.aws.amazon.com/IAM/latest/UserGuide/HowToPwdIAMUser.html) // in the IAM User Guide. // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that IAM users in the account do + // not automatically have permissions to change their own password. AllowUsersToChangePassword *bool `type:"boolean"` // Prevents IAM users from setting a new password after their password has expired. + // The IAM user cannot be accessed until an administrator resets the password. // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that IAM users can change their + // passwords after they expire and continue to sign in as the user. HardExpiry *bool `type:"boolean"` - // The number of days that an IAM user password is valid. The default value - // of 0 means IAM user passwords never expire. + // The number of days that an IAM user password is valid. // - // Default value: 0 + // If you do not specify a value for this parameter, then the operation uses + // the default value of 0. The result is that IAM user passwords never expire. MaxPasswordAge *int64 `min:"1" type:"integer"` // The minimum number of characters allowed in an IAM user password. // - // Default value: 6 + // If you do not specify a value for this parameter, then the operation uses + // the default value of 6. MinimumPasswordLength *int64 `min:"6" type:"integer"` // Specifies the number of previous passwords that IAM users are prevented from - // reusing. The default value of 0 means IAM users are not prevented from reusing - // previous passwords. + // reusing. // - // Default value: 0 + // If you do not specify a value for this parameter, then the operation uses + // the default value of 0. The result is that IAM users are not prevented from + // reusing previous passwords. PasswordReusePrevention *int64 `min:"1" type:"integer"` // Specifies whether IAM user passwords must contain at least one lowercase // character from the ISO basic Latin alphabet (a to z). // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that passwords do not require at + // least one lowercase character. RequireLowercaseCharacters *bool `type:"boolean"` // Specifies whether IAM user passwords must contain at least one numeric character // (0 to 9). // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that passwords do not require at + // least one numeric character. RequireNumbers *bool `type:"boolean"` // Specifies whether IAM user passwords must contain at least one of the following @@ -26416,13 +30002,17 @@ type UpdateAccountPasswordPolicyInput struct { // // ! @ # $ % ^ & * ( ) _ + - = [ ] { } | ' // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that passwords do not require at + // least one symbol character. RequireSymbols *bool `type:"boolean"` // Specifies whether IAM user passwords must contain at least one uppercase // character from the ISO basic Latin alphabet (A to Z). // - // Default value: false + // If you do not specify a value for this parameter, then the operation uses + // the default value of false. The result is that passwords do not require at + // least one uppercase character. RequireUppercaseCharacters *bool `type:"boolean"` } @@ -26509,7 +30099,6 @@ func (s *UpdateAccountPasswordPolicyInput) SetRequireUppercaseCharacters(v bool) return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAccountPasswordPolicyOutput type UpdateAccountPasswordPolicyOutput struct { _ struct{} `type:"structure"` } @@ -26524,25 +30113,29 @@ func (s UpdateAccountPasswordPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicyRequest type UpdateAssumeRolePolicyInput struct { _ struct{} `type:"structure"` // The policy that grants an entity permission to assume the role. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PolicyDocument is a required field PolicyDocument *string `min:"1" type:"string" required:"true"` // The name of the role to update with the new policy. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters // with no spaces. You can also include any of the following characters: _+=,.@- // @@ -26594,7 +30187,6 @@ func (s *UpdateAssumeRolePolicyInput) SetRoleName(v string) *UpdateAssumeRolePol return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateAssumeRolePolicyOutput type UpdateAssumeRolePolicyOutput struct { _ struct{} `type:"structure"` } @@ -26609,34 +30201,34 @@ func (s UpdateAssumeRolePolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroupRequest type UpdateGroupInput struct { _ struct{} `type:"structure"` // Name of the IAM group to update. If you're changing the name of the group, // this is the original name. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` // New name for the IAM group. Only include this if changing the group's name. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- NewGroupName *string `min:"1" type:"string"` // New path for the IAM group. Only include this if changing the group's path. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. NewPath *string `min:"1" type:"string"` } @@ -26690,7 +30282,6 @@ func (s *UpdateGroupInput) SetNewPath(v string) *UpdateGroupInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateGroupOutput type UpdateGroupOutput struct { _ struct{} `type:"structure"` } @@ -26705,21 +30296,27 @@ func (s UpdateGroupOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfileRequest type UpdateLoginProfileInput struct { _ struct{} `type:"structure"` // The new password for the specified IAM user. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). However, - // the format can be further restricted by the account administrator by setting - // a password policy on the AWS account. For more information, see UpdateAccountPasswordPolicy. - Password *string `min:"1" type:"string"` + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) + // + // However, the format can be further restricted by the account administrator + // by setting a password policy on the AWS account. For more information, see + // UpdateAccountPasswordPolicy. + Password *string `min:"1" type:"string" sensitive:"true"` // Allows this new password to be used only once by requiring the specified // IAM user to set a new password on next sign-in. @@ -26727,9 +30324,9 @@ type UpdateLoginProfileInput struct { // The name of the user whose password you want to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -26782,7 +30379,6 @@ func (s *UpdateLoginProfileInput) SetUserName(v string) *UpdateLoginProfileInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateLoginProfileOutput type UpdateLoginProfileOutput struct { _ struct{} `type:"structure"` } @@ -26797,13 +30393,12 @@ func (s UpdateLoginProfileOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprintRequest type UpdateOpenIDConnectProviderThumbprintInput struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of the IAM OIDC provider resource object for // which you want to update the thumbprint. You can get a list of OIDC provider - // ARNs by using the ListOpenIDConnectProviders action. + // ARNs by using the ListOpenIDConnectProviders operation. // // For more information about ARNs, see Amazon Resource Names (ARNs) and AWS // Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) @@ -26860,7 +30455,6 @@ func (s *UpdateOpenIDConnectProviderThumbprintInput) SetThumbprintList(v []*stri return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateOpenIDConnectProviderThumbprintOutput type UpdateOpenIDConnectProviderThumbprintOutput struct { _ struct{} `type:"structure"` } @@ -26875,7 +30469,6 @@ func (s UpdateOpenIDConnectProviderThumbprintOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescriptionRequest type UpdateRoleDescriptionInput struct { _ struct{} `type:"structure"` @@ -26931,7 +30524,6 @@ func (s *UpdateRoleDescriptionInput) SetRoleName(v string) *UpdateRoleDescriptio return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateRoleDescriptionResponse type UpdateRoleDescriptionOutput struct { _ struct{} `type:"structure"` @@ -26955,7 +30547,95 @@ func (s *UpdateRoleDescriptionOutput) SetRole(v *Role) *UpdateRoleDescriptionOut return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProviderRequest +type UpdateRoleInput struct { + _ struct{} `type:"structure"` + + // The new description that you want to apply to the specified role. + Description *string `type:"string"` + + // The maximum session duration (in seconds) that you want to set for the specified + // role. If you do not specify a value for this setting, the default maximum + // of one hour is applied. This setting can have a value from 1 hour to 12 hours. + // + // Anyone who assumes the role from the AWS CLI or API can use the DurationSeconds + // API parameter or the duration-seconds CLI parameter to request a longer session. + // The MaxSessionDuration setting determines the maximum duration that can be + // requested using the DurationSeconds parameter. If users don't specify a value + // for the DurationSeconds parameter, their security credentials are valid for + // one hour by default. This applies when you use the AssumeRole* API operations + // or the assume-role* CLI operations but does not apply when you use those + // operations to create a console URL. For more information, see Using IAM Roles + // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) in the + // IAM User Guide. + MaxSessionDuration *int64 `min:"3600" type:"integer"` + + // The name of the role that you want to modify. + // + // RoleName is a required field + RoleName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRoleInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateRoleInput"} + if s.MaxSessionDuration != nil && *s.MaxSessionDuration < 3600 { + invalidParams.Add(request.NewErrParamMinValue("MaxSessionDuration", 3600)) + } + if s.RoleName == nil { + invalidParams.Add(request.NewErrParamRequired("RoleName")) + } + if s.RoleName != nil && len(*s.RoleName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateRoleInput) SetDescription(v string) *UpdateRoleInput { + s.Description = &v + return s +} + +// SetMaxSessionDuration sets the MaxSessionDuration field's value. +func (s *UpdateRoleInput) SetMaxSessionDuration(v int64) *UpdateRoleInput { + s.MaxSessionDuration = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *UpdateRoleInput) SetRoleName(v string) *UpdateRoleInput { + s.RoleName = &v + return s +} + +type UpdateRoleOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateRoleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRoleOutput) GoString() string { + return s.String() +} + type UpdateSAMLProviderInput struct { _ struct{} `type:"structure"` @@ -27023,7 +30703,6 @@ func (s *UpdateSAMLProviderInput) SetSAMLProviderArn(v string) *UpdateSAMLProvid } // Contains the response to a successful UpdateSAMLProvider request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSAMLProviderResponse type UpdateSAMLProviderOutput struct { _ struct{} `type:"structure"` @@ -27047,31 +30726,30 @@ func (s *UpdateSAMLProviderOutput) SetSAMLProviderArn(v string) *UpdateSAMLProvi return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKeyRequest type UpdateSSHPublicKeyInput struct { _ struct{} `type:"structure"` // The unique identifier for the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // // SSHPublicKeyId is a required field SSHPublicKeyId *string `min:"20" type:"string" required:"true"` - // The status to assign to the SSH public key. Active means the key can be used - // for authentication with an AWS CodeCommit repository. Inactive means the - // key cannot be used. + // The status to assign to the SSH public key. Active means that the key can + // be used for authentication with an AWS CodeCommit repository. Inactive means + // that the key cannot be used. // // Status is a required field Status *string `type:"string" required:"true" enum:"statusType"` // The name of the IAM user associated with the SSH public key. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -27130,7 +30808,6 @@ func (s *UpdateSSHPublicKeyInput) SetUserName(v string) *UpdateSSHPublicKeyInput return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSSHPublicKeyOutput type UpdateSSHPublicKeyOutput struct { _ struct{} `type:"structure"` } @@ -27145,34 +30822,34 @@ func (s UpdateSSHPublicKeyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificateRequest type UpdateServerCertificateInput struct { _ struct{} `type:"structure"` // The new path for the server certificate. Include this only if you are updating // the server certificate's path. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. NewPath *string `min:"1" type:"string"` // The new name for the server certificate. Include this only if you are updating // the server certificate's name. The name of the certificate cannot contain // any spaces. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- NewServerCertificateName *string `min:"1" type:"string"` // The name of the server certificate that you want to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // ServerCertificateName is a required field ServerCertificateName *string `min:"1" type:"string" required:"true"` @@ -27228,7 +30905,6 @@ func (s *UpdateServerCertificateInput) SetServerCertificateName(v string) *Updat return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServerCertificateOutput type UpdateServerCertificateOutput struct { _ struct{} `type:"structure"` } @@ -27243,13 +30919,12 @@ func (s UpdateServerCertificateOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredentialRequest type UpdateServiceSpecificCredentialInput struct { _ struct{} `type:"structure"` // The unique identifier of the service-specific credential. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // @@ -27265,9 +30940,9 @@ type UpdateServiceSpecificCredentialInput struct { // If you do not specify this value, then the operation assumes the user whose // credentials are used to call the operation. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -27321,7 +30996,6 @@ func (s *UpdateServiceSpecificCredentialInput) SetUserName(v string) *UpdateServ return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateServiceSpecificCredentialOutput type UpdateServiceSpecificCredentialOutput struct { _ struct{} `type:"structure"` } @@ -27336,21 +31010,20 @@ func (s UpdateServiceSpecificCredentialOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificateRequest type UpdateSigningCertificateInput struct { _ struct{} `type:"structure"` // The ID of the signing certificate you want to update. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters that can consist of any upper or lowercased letter // or digit. // // CertificateId is a required field CertificateId *string `min:"24" type:"string" required:"true"` - // The status you want to assign to the certificate. Active means the certificate - // can be used for API calls to AWS, while Inactive means the certificate cannot + // The status you want to assign to the certificate. Active means that the certificate + // can be used for API calls to AWS Inactive means that the certificate cannot // be used. // // Status is a required field @@ -27358,9 +31031,9 @@ type UpdateSigningCertificateInput struct { // The name of the IAM user the signing certificate belongs to. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -27414,7 +31087,6 @@ func (s *UpdateSigningCertificateInput) SetUserName(v string) *UpdateSigningCert return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateSigningCertificateOutput type UpdateSigningCertificateOutput struct { _ struct{} `type:"structure"` } @@ -27429,34 +31101,34 @@ func (s UpdateSigningCertificateOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUserRequest type UpdateUserInput struct { _ struct{} `type:"structure"` // New path for the IAM user. Include this parameter only if you're changing // the user's path. // - // This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. NewPath *string `min:"1" type:"string"` // New name for the user. Include this parameter only if you're changing the // user's name. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- NewUserName *string `min:"1" type:"string"` // Name of the user to update. If you're changing the name of the user, this // is the original user name. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -27512,7 +31184,6 @@ func (s *UpdateUserInput) SetUserName(v string) *UpdateUserInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UpdateUserOutput type UpdateUserOutput struct { _ struct{} `type:"structure"` } @@ -27527,28 +31198,34 @@ func (s UpdateUserOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKeyRequest type UploadSSHPublicKeyInput struct { _ struct{} `type:"structure"` // The SSH public key. The public key must be encoded in ssh-rsa format or PEM - // format. + // format. The minimum bit-length of the public key is 2048 bits. For example, + // you can generate a 2048-bit key, and the resulting PEM file is 1679 bytes + // long. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // SSHPublicKeyBody is a required field SSHPublicKeyBody *string `min:"1" type:"string" required:"true"` // The name of the IAM user to associate the SSH public key with. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // UserName is a required field UserName *string `min:"1" type:"string" required:"true"` @@ -27599,7 +31276,6 @@ func (s *UploadSSHPublicKeyInput) SetUserName(v string) *UploadSSHPublicKeyInput } // Contains the response to a successful UploadSSHPublicKey request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSSHPublicKeyResponse type UploadSSHPublicKeyOutput struct { _ struct{} `type:"structure"` @@ -27623,18 +31299,22 @@ func (s *UploadSSHPublicKeyOutput) SetSSHPublicKey(v *SSHPublicKey) *UploadSSHPu return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificateRequest type UploadServerCertificateInput struct { _ struct{} `type:"structure"` // The contents of the public key certificate in PEM-encoded format. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // CertificateBody is a required field CertificateBody *string `min:"1" type:"string" required:"true"` @@ -27643,11 +31323,16 @@ type UploadServerCertificateInput struct { // of the PEM-encoded public key certificates of the chain. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) CertificateChain *string `min:"1" type:"string"` // The path for the server certificate. For more information about paths, see @@ -27655,14 +31340,15 @@ type UploadServerCertificateInput struct { // in the IAM User Guide. // // This parameter is optional. If it is not included, it defaults to a slash - // (/). This paramater allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // (/). This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of either a forward slash (/) by itself - // or a string that must begin and end with forward slashes, containing any - // ASCII character from the ! (\u0021) thru the DEL character (\u007F), including - // most punctuation characters, digits, and upper and lowercased letters. + // or a string that must begin and end with forward slashes. In addition, it + // can contain any ASCII character from the ! (\u0021) through the DEL character + // (\u007F), including most punctuation characters, digits, and upper and lowercased + // letters. // // If you are uploading a server certificate specifically for use with Amazon - // CloudFront distributions, you must specify a path using the --path option. + // CloudFront distributions, you must specify a path using the path parameter. // The path must begin with /cloudfront and must include a trailing slash (for // example, /cloudfront/test/). Path *string `min:"1" type:"string"` @@ -27670,21 +31356,26 @@ type UploadServerCertificateInput struct { // The contents of the private key in PEM-encoded format. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // PrivateKey is a required field - PrivateKey *string `min:"1" type:"string" required:"true"` + PrivateKey *string `min:"1" type:"string" required:"true" sensitive:"true"` // The name for the server certificate. Do not include the path in this value. // The name of the certificate cannot contain any spaces. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- // // ServerCertificateName is a required field ServerCertificateName *string `min:"1" type:"string" required:"true"` @@ -27765,7 +31456,6 @@ func (s *UploadServerCertificateInput) SetServerCertificateName(v string) *Uploa } // Contains the response to a successful UploadServerCertificate request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadServerCertificateResponse type UploadServerCertificateOutput struct { _ struct{} `type:"structure"` @@ -27790,27 +31480,31 @@ func (s *UploadServerCertificateOutput) SetServerCertificateMetadata(v *ServerCe return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificateRequest type UploadSigningCertificateInput struct { _ struct{} `type:"structure"` // The contents of the signing certificate. // // The regex pattern (http://wikipedia.org/wiki/regex) used to validate this - // parameter is a string of characters consisting of any printable ASCII character - // ranging from the space character (\u0020) through end of the ASCII character - // range as well as the printable characters in the Basic Latin and Latin-1 - // Supplement character set (through \u00FF). It also includes the special characters - // tab (\u0009), line feed (\u000A), and carriage return (\u000D). + // parameter is a string of characters consisting of the following: + // + // * Any printable ASCII character ranging from the space character (\u0020) + // through the end of the ASCII character range + // + // * The printable characters in the Basic Latin and Latin-1 Supplement character + // set (through \u00FF) + // + // * The special characters tab (\u0009), line feed (\u000A), and carriage + // return (\u000D) // // CertificateBody is a required field CertificateBody *string `min:"1" type:"string" required:"true"` // The name of the user the signing certificate is for. // - // This parameter allows (per its regex pattern (http://wikipedia.org/wiki/regex)) + // This parameter allows (through its regex pattern (http://wikipedia.org/wiki/regex)) // a string of characters consisting of upper and lowercase alphanumeric characters - // with no spaces. You can also include any of the following characters: =,.@- + // with no spaces. You can also include any of the following characters: _+=,.@- UserName *string `min:"1" type:"string"` } @@ -27856,7 +31550,6 @@ func (s *UploadSigningCertificateInput) SetUserName(v string) *UploadSigningCert } // Contains the response to a successful UploadSigningCertificate request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UploadSigningCertificateResponse type UploadSigningCertificateOutput struct { _ struct{} `type:"structure"` @@ -27884,14 +31577,13 @@ func (s *UploadSigningCertificateOutput) SetCertificate(v *SigningCertificate) * // Contains information about an IAM user entity. // -// This data type is used as a response element in the following actions: +// This data type is used as a response element in the following operations: // // * CreateUser // // * GetUser // // * ListUsers -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/User type User struct { _ struct{} `type:"structure"` @@ -27906,7 +31598,7 @@ type User struct { // when the user was created. // // CreateDate is a required field - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + CreateDate *time.Time `type:"timestamp" required:"true"` // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the user's password was last used to sign in to an AWS website. For @@ -27914,20 +31606,20 @@ type User struct { // Reports (http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html) // topic in the Using IAM guide. If a password is used more than once in a five-minute // span, only the first use is returned in this field. If the field is null - // (no value) then it indicates that they never signed in with a password. This - // can be because: + // (no value), then it indicates that they never signed in with a password. + // This can be because: // // * The user never had a password. // // * A password exists but has not been used since IAM started tracking this - // information on October 20th, 2014. + // information on October 20, 2014. // - // A null does not mean that the user never had a password. Also, if the user - // does not currently have a password, but had one in the past, then this field - // contains the date and time the most recent password was used. + // A null valuedoes not mean that the user never had a password. Also, if the + // user does not currently have a password, but had one in the past, then this + // field contains the date and time the most recent password was used. // - // This value is returned only in the GetUser and ListUsers actions. - PasswordLastUsed *time.Time `type:"timestamp" timestampFormat:"iso8601"` + // This value is returned only in the GetUser and ListUsers operations. + PasswordLastUsed *time.Time `type:"timestamp"` // The path to the user. For more information about paths, see IAM Identifiers // (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) @@ -27936,6 +31628,18 @@ type User struct { // Path is a required field Path *string `min:"1" type:"string" required:"true"` + // The ARN of the policy used to set the permissions boundary for the user. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundary *AttachedPermissionsBoundary `type:"structure"` + + // A list of tags that are associated with the specified user. For more information + // about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + Tags []*Tag `type:"list"` + // The stable and unique string identifying the user. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -27983,6 +31687,18 @@ func (s *User) SetPath(v string) *User { return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *User) SetPermissionsBoundary(v *AttachedPermissionsBoundary) *User { + s.PermissionsBoundary = v + return s +} + +// SetTags sets the Tags field's value. +func (s *User) SetTags(v []*Tag) *User { + s.Tags = v + return s +} + // SetUserId sets the UserId field's value. func (s *User) SetUserId(v string) *User { s.UserId = &v @@ -27999,8 +31715,7 @@ func (s *User) SetUserName(v string) *User { // and all the IAM groups the user is in. // // This data type is used as a response element in the GetAccountAuthorizationDetails -// action. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/UserDetail +// operation. type UserDetail struct { _ struct{} `type:"structure"` @@ -28016,7 +31731,7 @@ type UserDetail struct { // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), // when the user was created. - CreateDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + CreateDate *time.Time `type:"timestamp"` // A list of IAM groups that the user is in. GroupList []*string `type:"list"` @@ -28026,6 +31741,18 @@ type UserDetail struct { // in the Using IAM guide. Path *string `min:"1" type:"string"` + // The ARN of the policy used to set the permissions boundary for the user. + // + // For more information about permissions boundaries, see Permissions Boundaries + // for IAM Identities (IAM/latest/UserGuide/access_policies_boundaries.html) + // in the IAM User Guide. + PermissionsBoundary *AttachedPermissionsBoundary `type:"structure"` + + // A list of tags that are associated with the specified user. For more information + // about tagging, see Tagging IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html) + // in the IAM User Guide. + Tags []*Tag `type:"list"` + // The stable and unique string identifying the user. For more information about // IDs, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html) // in the Using IAM guide. @@ -28078,6 +31805,18 @@ func (s *UserDetail) SetPath(v string) *UserDetail { return s } +// SetPermissionsBoundary sets the PermissionsBoundary field's value. +func (s *UserDetail) SetPermissionsBoundary(v *AttachedPermissionsBoundary) *UserDetail { + s.PermissionsBoundary = v + return s +} + +// SetTags sets the Tags field's value. +func (s *UserDetail) SetTags(v []*Tag) *UserDetail { + s.Tags = v + return s +} + // SetUserId sets the UserId field's value. func (s *UserDetail) SetUserId(v string) *UserDetail { s.UserId = &v @@ -28097,26 +31836,25 @@ func (s *UserDetail) SetUserPolicyList(v []*PolicyDetail) *UserDetail { } // Contains information about a virtual MFA device. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/VirtualMFADevice type VirtualMFADevice struct { _ struct{} `type:"structure"` - // The Base32 seed defined as specified in RFC3548 (https://tools.ietf.org/html/rfc3548.txt). - // The Base32StringSeed is Base64-encoded. + // The base32 seed defined as specified in RFC3548 (https://tools.ietf.org/html/rfc3548.txt). + // The Base32StringSeed is base64-encoded. // // Base32StringSeed is automatically base64 encoded/decoded by the SDK. - Base32StringSeed []byte `type:"blob"` + Base32StringSeed []byte `type:"blob" sensitive:"true"` // The date and time on which the virtual MFA device was enabled. - EnableDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + EnableDate *time.Time `type:"timestamp"` // A QR code PNG image that encodes otpauth://totp/$virtualMFADeviceName@$AccountName?secret=$Base32String - // where $virtualMFADeviceName is one of the create call arguments, AccountName + // where $virtualMFADeviceName is one of the create call arguments. AccountName // is the user name if set (otherwise, the account ID otherwise), and Base32String - // is the seed in Base32 format. The Base32String value is Base64-encoded. + // is the seed in base32 format. The Base32String value is base64-encoded. // // QRCodePNG is automatically base64 encoded/decoded by the SDK. - QRCodePNG []byte `type:"blob"` + QRCodePNG []byte `type:"blob" sensitive:"true"` // The serial number associated with VirtualMFADevice. // @@ -28236,6 +31974,11 @@ const ( EntityTypeAwsmanagedPolicy = "AWSManagedPolicy" ) +const ( + // PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy is a PermissionsBoundaryAttachmentType enum value + PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy = "PermissionsBoundaryPolicy" +) + const ( // PolicyEvaluationDecisionTypeAllowed is a PolicyEvaluationDecisionType enum value PolicyEvaluationDecisionTypeAllowed = "allowed" @@ -28270,6 +32013,20 @@ const ( PolicySourceTypeNone = "none" ) +// The policy usage type that indicates whether the policy is used as a permissions +// policy or as the permissions boundary for an entity. +// +// For more information about permissions boundaries, see Permissions Boundaries +// for IAM Identities (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) +// in the IAM User Guide. +const ( + // PolicyUsageTypePermissionsPolicy is a PolicyUsageType enum value + PolicyUsageTypePermissionsPolicy = "PermissionsPolicy" + + // PolicyUsageTypePermissionsBoundary is a PolicyUsageType enum value + PolicyUsageTypePermissionsBoundary = "PermissionsBoundary" +) + const ( // ReportFormatTypeTextCsv is a ReportFormatType enum value ReportFormatTypeTextCsv = "text/csv" @@ -28305,6 +32062,28 @@ const ( EncodingTypePem = "PEM" ) +const ( + // JobStatusTypeInProgress is a jobStatusType enum value + JobStatusTypeInProgress = "IN_PROGRESS" + + // JobStatusTypeCompleted is a jobStatusType enum value + JobStatusTypeCompleted = "COMPLETED" + + // JobStatusTypeFailed is a jobStatusType enum value + JobStatusTypeFailed = "FAILED" +) + +const ( + // PolicyOwnerEntityTypeUser is a policyOwnerEntityType enum value + PolicyOwnerEntityTypeUser = "USER" + + // PolicyOwnerEntityTypeRole is a policyOwnerEntityType enum value + PolicyOwnerEntityTypeRole = "ROLE" + + // PolicyOwnerEntityTypeGroup is a policyOwnerEntityType enum value + PolicyOwnerEntityTypeGroup = "GROUP" +) + const ( // PolicyScopeTypeAll is a policyScopeType enum value PolicyScopeTypeAll = "All" @@ -28316,6 +32095,14 @@ const ( PolicyScopeTypeLocal = "Local" ) +const ( + // PolicyTypeInline is a policyType enum value + PolicyTypeInline = "INLINE" + + // PolicyTypeManaged is a policyType enum value + PolicyTypeManaged = "MANAGED" +) + const ( // StatusTypeActive is a statusType enum value StatusTypeActive = "Active" diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go index a4900f7f4..d8766fbf6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go @@ -64,7 +64,7 @@ // // Using the Client // -// To AWS Identity and Access Management with the SDK use the New function to create +// To contact AWS Identity and Access Management with the SDK use the New function to create // a new service client. With that client you can make API requests to the service. // These clients are safe to use concurrently. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go index 470e19b37..8c1773fcc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go @@ -4,6 +4,14 @@ package iam const ( + // ErrCodeConcurrentModificationException for service response error code + // "ConcurrentModification". + // + // The request was rejected because multiple requests to change this object + // were submitted simultaneously. Wait a few minutes and submit your request + // again. + ErrCodeConcurrentModificationException = "ConcurrentModification" + // ErrCodeCredentialReportExpiredException for service response error code // "ReportExpired". // @@ -129,8 +137,8 @@ const ( // ErrCodeNoSuchEntityException for service response error code // "NoSuchEntity". // - // The request was rejected because it referenced an entity that does not exist. - // The error message describes the entity. + // The request was rejected because it referenced a resource entity that does + // not exist. The error message describes the resource. ErrCodeNoSuchEntityException = "NoSuchEntity" // ErrCodePasswordPolicyViolationException for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/service.go b/vendor/github.com/aws/aws-sdk-go/service/iam/service.go index 4f798c63d..940b4ce32 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/service.go @@ -29,8 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "iam" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. + ServiceName = "iam" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "IAM" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the IAM client with a session. @@ -55,6 +56,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg, metadata.ClientInfo{ ServiceName: ServiceName, + ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go index 52ac02ca9..3b3c2e380 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go @@ -3,14 +3,22 @@ package s3 import ( + "bytes" "fmt" "io" + "sync" + "sync/atomic" "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" + "github.com/aws/aws-sdk-go/private/protocol/eventstream" + "github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi" + "github.com/aws/aws-sdk-go/private/protocol/rest" "github.com/aws/aws-sdk-go/private/protocol/restxml" ) @@ -18,19 +26,18 @@ const opAbortMultipartUpload = "AbortMultipartUpload" // AbortMultipartUploadRequest generates a "aws/request.Request" representing the // client's request for the AbortMultipartUpload operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See AbortMultipartUpload for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AbortMultipartUpload method directly -// instead. +// See AbortMultipartUpload for more information on using the AbortMultipartUpload +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the AbortMultipartUploadRequest method. // req, resp := client.AbortMultipartUploadRequest(params) @@ -40,7 +47,7 @@ const opAbortMultipartUpload = "AbortMultipartUpload" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *request.Request, output *AbortMultipartUploadOutput) { op := &request.Operation{ Name: opAbortMultipartUpload, @@ -76,7 +83,7 @@ func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req // * ErrCodeNoSuchUpload "NoSuchUpload" // The specified multipart upload does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMultipartUploadOutput, error) { req, out := c.AbortMultipartUploadRequest(input) return out, req.Send() @@ -102,19 +109,18 @@ const opCompleteMultipartUpload = "CompleteMultipartUpload" // CompleteMultipartUploadRequest generates a "aws/request.Request" representing the // client's request for the CompleteMultipartUpload operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See CompleteMultipartUpload for usage and error information. +// See CompleteMultipartUpload for more information on using the CompleteMultipartUpload +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the CompleteMultipartUpload method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the CompleteMultipartUploadRequest method. // req, resp := client.CompleteMultipartUploadRequest(params) @@ -124,7 +130,7 @@ const opCompleteMultipartUpload = "CompleteMultipartUpload" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *request.Request, output *CompleteMultipartUploadOutput) { op := &request.Operation{ Name: opCompleteMultipartUpload, @@ -151,7 +157,7 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation CompleteMultipartUpload for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*CompleteMultipartUploadOutput, error) { req, out := c.CompleteMultipartUploadRequest(input) return out, req.Send() @@ -177,19 +183,18 @@ const opCopyObject = "CopyObject" // CopyObjectRequest generates a "aws/request.Request" representing the // client's request for the CopyObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See CopyObject for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the CopyObject method directly -// instead. +// See CopyObject for more information on using the CopyObject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the CopyObjectRequest method. // req, resp := client.CopyObjectRequest(params) @@ -199,7 +204,7 @@ const opCopyObject = "CopyObject" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, output *CopyObjectOutput) { op := &request.Operation{ Name: opCopyObject, @@ -232,7 +237,7 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // The source object of the COPY operation is not in the active tier and is // only stored in Amazon Glacier. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { req, out := c.CopyObjectRequest(input) return out, req.Send() @@ -258,19 +263,18 @@ const opCreateBucket = "CreateBucket" // CreateBucketRequest generates a "aws/request.Request" representing the // client's request for the CreateBucket operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See CreateBucket for usage and error information. +// See CreateBucket for more information on using the CreateBucket +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the CreateBucket method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the CreateBucketRequest method. // req, resp := client.CreateBucketRequest(params) @@ -280,7 +284,7 @@ const opCreateBucket = "CreateBucket" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request, output *CreateBucketOutput) { op := &request.Operation{ Name: opCreateBucket, @@ -315,7 +319,7 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // // * ErrCodeBucketAlreadyOwnedByYou "BucketAlreadyOwnedByYou" // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) { req, out := c.CreateBucketRequest(input) return out, req.Send() @@ -341,19 +345,18 @@ const opCreateMultipartUpload = "CreateMultipartUpload" // CreateMultipartUploadRequest generates a "aws/request.Request" representing the // client's request for the CreateMultipartUpload operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See CreateMultipartUpload for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the CreateMultipartUpload method directly -// instead. +// See CreateMultipartUpload for more information on using the CreateMultipartUpload +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the CreateMultipartUploadRequest method. // req, resp := client.CreateMultipartUploadRequest(params) @@ -363,7 +366,7 @@ const opCreateMultipartUpload = "CreateMultipartUpload" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *request.Request, output *CreateMultipartUploadOutput) { op := &request.Operation{ Name: opCreateMultipartUpload, @@ -396,7 +399,7 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation CreateMultipartUpload for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMultipartUploadOutput, error) { req, out := c.CreateMultipartUploadRequest(input) return out, req.Send() @@ -422,19 +425,18 @@ const opDeleteBucket = "DeleteBucket" // DeleteBucketRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucket operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucket for usage and error information. +// See DeleteBucket for more information on using the DeleteBucket +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucket method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketRequest method. // req, resp := client.DeleteBucketRequest(params) @@ -444,7 +446,7 @@ const opDeleteBucket = "DeleteBucket" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request, output *DeleteBucketOutput) { op := &request.Operation{ Name: opDeleteBucket, @@ -458,8 +460,7 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request output = &DeleteBucketOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -474,7 +475,7 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucket for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) { req, out := c.DeleteBucketRequest(input) return out, req.Send() @@ -500,19 +501,18 @@ const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration // DeleteBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketAnalyticsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteBucketAnalyticsConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketAnalyticsConfiguration method directly -// instead. +// See DeleteBucketAnalyticsConfiguration for more information on using the DeleteBucketAnalyticsConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketAnalyticsConfigurationRequest method. // req, resp := client.DeleteBucketAnalyticsConfigurationRequest(params) @@ -522,7 +522,7 @@ const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyticsConfigurationInput) (req *request.Request, output *DeleteBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketAnalyticsConfiguration, @@ -536,8 +536,7 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt output = &DeleteBucketAnalyticsConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -552,7 +551,7 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration func (c *S3) DeleteBucketAnalyticsConfiguration(input *DeleteBucketAnalyticsConfigurationInput) (*DeleteBucketAnalyticsConfigurationOutput, error) { req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) return out, req.Send() @@ -578,19 +577,18 @@ const opDeleteBucketCors = "DeleteBucketCors" // DeleteBucketCorsRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketCors operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucketCors for usage and error information. +// See DeleteBucketCors for more information on using the DeleteBucketCors +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketCors method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketCorsRequest method. // req, resp := client.DeleteBucketCorsRequest(params) @@ -600,7 +598,7 @@ const opDeleteBucketCors = "DeleteBucketCors" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request.Request, output *DeleteBucketCorsOutput) { op := &request.Operation{ Name: opDeleteBucketCors, @@ -614,14 +612,13 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request output = &DeleteBucketCorsOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // DeleteBucketCors API operation for Amazon Simple Storage Service. // -// Deletes the cors configuration information set for the bucket. +// Deletes the CORS configuration information set for the bucket. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -629,7 +626,7 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors func (c *S3) DeleteBucketCors(input *DeleteBucketCorsInput) (*DeleteBucketCorsOutput, error) { req, out := c.DeleteBucketCorsRequest(input) return out, req.Send() @@ -651,23 +648,97 @@ func (c *S3) DeleteBucketCorsWithContext(ctx aws.Context, input *DeleteBucketCor return out, req.Send() } +const opDeleteBucketEncryption = "DeleteBucketEncryption" + +// DeleteBucketEncryptionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteBucketEncryption operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteBucketEncryption for more information on using the DeleteBucketEncryption +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteBucketEncryptionRequest method. +// req, resp := client.DeleteBucketEncryptionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryption +func (c *S3) DeleteBucketEncryptionRequest(input *DeleteBucketEncryptionInput) (req *request.Request, output *DeleteBucketEncryptionOutput) { + op := &request.Operation{ + Name: opDeleteBucketEncryption, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?encryption", + } + + if input == nil { + input = &DeleteBucketEncryptionInput{} + } + + output = &DeleteBucketEncryptionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteBucketEncryption API operation for Amazon Simple Storage Service. +// +// Deletes the server-side encryption configuration from the bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation DeleteBucketEncryption for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryption +func (c *S3) DeleteBucketEncryption(input *DeleteBucketEncryptionInput) (*DeleteBucketEncryptionOutput, error) { + req, out := c.DeleteBucketEncryptionRequest(input) + return out, req.Send() +} + +// DeleteBucketEncryptionWithContext is the same as DeleteBucketEncryption with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketEncryption for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketEncryptionWithContext(ctx aws.Context, input *DeleteBucketEncryptionInput, opts ...request.Option) (*DeleteBucketEncryptionOutput, error) { + req, out := c.DeleteBucketEncryptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration" // DeleteBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketInventoryConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucketInventoryConfiguration for usage and error information. +// See DeleteBucketInventoryConfiguration for more information on using the DeleteBucketInventoryConfiguration +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketInventoryConfiguration method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketInventoryConfigurationRequest method. // req, resp := client.DeleteBucketInventoryConfigurationRequest(params) @@ -677,7 +748,7 @@ const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInventoryConfigurationInput) (req *request.Request, output *DeleteBucketInventoryConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketInventoryConfiguration, @@ -691,8 +762,7 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent output = &DeleteBucketInventoryConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -707,7 +777,7 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration func (c *S3) DeleteBucketInventoryConfiguration(input *DeleteBucketInventoryConfigurationInput) (*DeleteBucketInventoryConfigurationOutput, error) { req, out := c.DeleteBucketInventoryConfigurationRequest(input) return out, req.Send() @@ -733,19 +803,18 @@ const opDeleteBucketLifecycle = "DeleteBucketLifecycle" // DeleteBucketLifecycleRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketLifecycle operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteBucketLifecycle for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketLifecycle method directly -// instead. +// See DeleteBucketLifecycle for more information on using the DeleteBucketLifecycle +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketLifecycleRequest method. // req, resp := client.DeleteBucketLifecycleRequest(params) @@ -755,7 +824,7 @@ const opDeleteBucketLifecycle = "DeleteBucketLifecycle" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *request.Request, output *DeleteBucketLifecycleOutput) { op := &request.Operation{ Name: opDeleteBucketLifecycle, @@ -769,8 +838,7 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re output = &DeleteBucketLifecycleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -784,7 +852,7 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBucketLifecycleOutput, error) { req, out := c.DeleteBucketLifecycleRequest(input) return out, req.Send() @@ -810,19 +878,18 @@ const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" // DeleteBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketMetricsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucketMetricsConfiguration for usage and error information. +// See DeleteBucketMetricsConfiguration for more information on using the DeleteBucketMetricsConfiguration +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketMetricsConfiguration method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketMetricsConfigurationRequest method. // req, resp := client.DeleteBucketMetricsConfigurationRequest(params) @@ -832,7 +899,7 @@ const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsConfigurationInput) (req *request.Request, output *DeleteBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketMetricsConfiguration, @@ -846,8 +913,7 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC output = &DeleteBucketMetricsConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -862,7 +928,7 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration func (c *S3) DeleteBucketMetricsConfiguration(input *DeleteBucketMetricsConfigurationInput) (*DeleteBucketMetricsConfigurationOutput, error) { req, out := c.DeleteBucketMetricsConfigurationRequest(input) return out, req.Send() @@ -888,19 +954,18 @@ const opDeleteBucketPolicy = "DeleteBucketPolicy" // DeleteBucketPolicyRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketPolicy operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteBucketPolicy for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketPolicy method directly -// instead. +// See DeleteBucketPolicy for more information on using the DeleteBucketPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketPolicyRequest method. // req, resp := client.DeleteBucketPolicyRequest(params) @@ -910,7 +975,7 @@ const opDeleteBucketPolicy = "DeleteBucketPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *request.Request, output *DeleteBucketPolicyOutput) { op := &request.Operation{ Name: opDeleteBucketPolicy, @@ -924,8 +989,7 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req output = &DeleteBucketPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -939,7 +1003,7 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPolicyOutput, error) { req, out := c.DeleteBucketPolicyRequest(input) return out, req.Send() @@ -965,19 +1029,18 @@ const opDeleteBucketReplication = "DeleteBucketReplication" // DeleteBucketReplicationRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketReplication operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucketReplication for usage and error information. +// See DeleteBucketReplication for more information on using the DeleteBucketReplication +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketReplication method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketReplicationRequest method. // req, resp := client.DeleteBucketReplicationRequest(params) @@ -987,7 +1050,7 @@ const opDeleteBucketReplication = "DeleteBucketReplication" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *request.Request, output *DeleteBucketReplicationOutput) { op := &request.Operation{ Name: opDeleteBucketReplication, @@ -1001,14 +1064,15 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) output = &DeleteBucketReplicationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // DeleteBucketReplication API operation for Amazon Simple Storage Service. // -// Deletes the replication configuration from the bucket. +// Deletes the replication configuration from the bucket. For information about +// replication configuration, see Cross-Region Replication (CRR) ( https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) +// in the Amazon S3 Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1016,7 +1080,7 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*DeleteBucketReplicationOutput, error) { req, out := c.DeleteBucketReplicationRequest(input) return out, req.Send() @@ -1042,19 +1106,18 @@ const opDeleteBucketTagging = "DeleteBucketTagging" // DeleteBucketTaggingRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteBucketTagging for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketTagging method directly -// instead. +// See DeleteBucketTagging for more information on using the DeleteBucketTagging +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketTaggingRequest method. // req, resp := client.DeleteBucketTaggingRequest(params) @@ -1064,7 +1127,7 @@ const opDeleteBucketTagging = "DeleteBucketTagging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *request.Request, output *DeleteBucketTaggingOutput) { op := &request.Operation{ Name: opDeleteBucketTagging, @@ -1078,8 +1141,7 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r output = &DeleteBucketTaggingOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -1093,7 +1155,7 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucketTaggingOutput, error) { req, out := c.DeleteBucketTaggingRequest(input) return out, req.Send() @@ -1119,19 +1181,18 @@ const opDeleteBucketWebsite = "DeleteBucketWebsite" // DeleteBucketWebsiteRequest generates a "aws/request.Request" representing the // client's request for the DeleteBucketWebsite operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteBucketWebsite for usage and error information. +// See DeleteBucketWebsite for more information on using the DeleteBucketWebsite +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteBucketWebsite method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteBucketWebsiteRequest method. // req, resp := client.DeleteBucketWebsiteRequest(params) @@ -1141,7 +1202,7 @@ const opDeleteBucketWebsite = "DeleteBucketWebsite" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *request.Request, output *DeleteBucketWebsiteOutput) { op := &request.Operation{ Name: opDeleteBucketWebsite, @@ -1155,8 +1216,7 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r output = &DeleteBucketWebsiteOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -1170,7 +1230,7 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucketWebsiteOutput, error) { req, out := c.DeleteBucketWebsiteRequest(input) return out, req.Send() @@ -1196,19 +1256,18 @@ const opDeleteObject = "DeleteObject" // DeleteObjectRequest generates a "aws/request.Request" representing the // client's request for the DeleteObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteObject for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteObject method directly -// instead. +// See DeleteObject for more information on using the DeleteObject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteObjectRequest method. // req, resp := client.DeleteObjectRequest(params) @@ -1218,7 +1277,7 @@ const opDeleteObject = "DeleteObject" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request, output *DeleteObjectOutput) { op := &request.Operation{ Name: opDeleteObject, @@ -1247,7 +1306,7 @@ func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) { req, out := c.DeleteObjectRequest(input) return out, req.Send() @@ -1273,19 +1332,18 @@ const opDeleteObjectTagging = "DeleteObjectTagging" // DeleteObjectTaggingRequest generates a "aws/request.Request" representing the // client's request for the DeleteObjectTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See DeleteObjectTagging for usage and error information. +// See DeleteObjectTagging for more information on using the DeleteObjectTagging +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteObjectTagging method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteObjectTaggingRequest method. // req, resp := client.DeleteObjectTaggingRequest(params) @@ -1295,7 +1353,7 @@ const opDeleteObjectTagging = "DeleteObjectTagging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *request.Request, output *DeleteObjectTaggingOutput) { op := &request.Operation{ Name: opDeleteObjectTagging, @@ -1322,7 +1380,7 @@ func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging func (c *S3) DeleteObjectTagging(input *DeleteObjectTaggingInput) (*DeleteObjectTaggingOutput, error) { req, out := c.DeleteObjectTaggingRequest(input) return out, req.Send() @@ -1348,19 +1406,18 @@ const opDeleteObjects = "DeleteObjects" // DeleteObjectsRequest generates a "aws/request.Request" representing the // client's request for the DeleteObjects operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DeleteObjects for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DeleteObjects method directly -// instead. +// See DeleteObjects for more information on using the DeleteObjects +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DeleteObjectsRequest method. // req, resp := client.DeleteObjectsRequest(params) @@ -1370,7 +1427,7 @@ const opDeleteObjects = "DeleteObjects" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Request, output *DeleteObjectsOutput) { op := &request.Operation{ Name: opDeleteObjects, @@ -1398,7 +1455,7 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObjects for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, error) { req, out := c.DeleteObjectsRequest(input) return out, req.Send() @@ -1420,23 +1477,97 @@ func (c *S3) DeleteObjectsWithContext(ctx aws.Context, input *DeleteObjectsInput return out, req.Send() } +const opDeletePublicAccessBlock = "DeletePublicAccessBlock" + +// DeletePublicAccessBlockRequest generates a "aws/request.Request" representing the +// client's request for the DeletePublicAccessBlock operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeletePublicAccessBlock for more information on using the DeletePublicAccessBlock +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeletePublicAccessBlockRequest method. +// req, resp := client.DeletePublicAccessBlockRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeletePublicAccessBlock +func (c *S3) DeletePublicAccessBlockRequest(input *DeletePublicAccessBlockInput) (req *request.Request, output *DeletePublicAccessBlockOutput) { + op := &request.Operation{ + Name: opDeletePublicAccessBlock, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?publicAccessBlock", + } + + if input == nil { + input = &DeletePublicAccessBlockInput{} + } + + output = &DeletePublicAccessBlockOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeletePublicAccessBlock API operation for Amazon Simple Storage Service. +// +// Removes the PublicAccessBlock configuration from an Amazon S3 bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation DeletePublicAccessBlock for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeletePublicAccessBlock +func (c *S3) DeletePublicAccessBlock(input *DeletePublicAccessBlockInput) (*DeletePublicAccessBlockOutput, error) { + req, out := c.DeletePublicAccessBlockRequest(input) + return out, req.Send() +} + +// DeletePublicAccessBlockWithContext is the same as DeletePublicAccessBlock with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePublicAccessBlock for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeletePublicAccessBlockWithContext(ctx aws.Context, input *DeletePublicAccessBlockInput, opts ...request.Option) (*DeletePublicAccessBlockOutput, error) { + req, out := c.DeletePublicAccessBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" // GetBucketAccelerateConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketAccelerateConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketAccelerateConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketAccelerateConfiguration method directly -// instead. +// See GetBucketAccelerateConfiguration for more information on using the GetBucketAccelerateConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketAccelerateConfigurationRequest method. // req, resp := client.GetBucketAccelerateConfigurationRequest(params) @@ -1446,7 +1577,7 @@ const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateConfigurationInput) (req *request.Request, output *GetBucketAccelerateConfigurationOutput) { op := &request.Operation{ Name: opGetBucketAccelerateConfiguration, @@ -1473,7 +1604,7 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAccelerateConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration func (c *S3) GetBucketAccelerateConfiguration(input *GetBucketAccelerateConfigurationInput) (*GetBucketAccelerateConfigurationOutput, error) { req, out := c.GetBucketAccelerateConfigurationRequest(input) return out, req.Send() @@ -1499,19 +1630,18 @@ const opGetBucketAcl = "GetBucketAcl" // GetBucketAclRequest generates a "aws/request.Request" representing the // client's request for the GetBucketAcl operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketAcl for usage and error information. +// See GetBucketAcl for more information on using the GetBucketAcl +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketAcl method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketAclRequest method. // req, resp := client.GetBucketAclRequest(params) @@ -1521,7 +1651,7 @@ const opGetBucketAcl = "GetBucketAcl" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request, output *GetBucketAclOutput) { op := &request.Operation{ Name: opGetBucketAcl, @@ -1548,7 +1678,7 @@ func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAcl for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl func (c *S3) GetBucketAcl(input *GetBucketAclInput) (*GetBucketAclOutput, error) { req, out := c.GetBucketAclRequest(input) return out, req.Send() @@ -1574,19 +1704,18 @@ const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" // GetBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketAnalyticsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketAnalyticsConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketAnalyticsConfiguration method directly -// instead. +// See GetBucketAnalyticsConfiguration for more information on using the GetBucketAnalyticsConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketAnalyticsConfigurationRequest method. // req, resp := client.GetBucketAnalyticsConfigurationRequest(params) @@ -1596,7 +1725,7 @@ const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsConfigurationInput) (req *request.Request, output *GetBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opGetBucketAnalyticsConfiguration, @@ -1624,7 +1753,7 @@ func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration func (c *S3) GetBucketAnalyticsConfiguration(input *GetBucketAnalyticsConfigurationInput) (*GetBucketAnalyticsConfigurationOutput, error) { req, out := c.GetBucketAnalyticsConfigurationRequest(input) return out, req.Send() @@ -1650,19 +1779,18 @@ const opGetBucketCors = "GetBucketCors" // GetBucketCorsRequest generates a "aws/request.Request" representing the // client's request for the GetBucketCors operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketCors for usage and error information. +// See GetBucketCors for more information on using the GetBucketCors +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketCors method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketCorsRequest method. // req, resp := client.GetBucketCorsRequest(params) @@ -1672,7 +1800,7 @@ const opGetBucketCors = "GetBucketCors" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Request, output *GetBucketCorsOutput) { op := &request.Operation{ Name: opGetBucketCors, @@ -1691,7 +1819,7 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque // GetBucketCors API operation for Amazon Simple Storage Service. // -// Returns the cors configuration for the bucket. +// Returns the CORS configuration for the bucket. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1699,7 +1827,7 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors func (c *S3) GetBucketCors(input *GetBucketCorsInput) (*GetBucketCorsOutput, error) { req, out := c.GetBucketCorsRequest(input) return out, req.Send() @@ -1721,23 +1849,96 @@ func (c *S3) GetBucketCorsWithContext(ctx aws.Context, input *GetBucketCorsInput return out, req.Send() } +const opGetBucketEncryption = "GetBucketEncryption" + +// GetBucketEncryptionRequest generates a "aws/request.Request" representing the +// client's request for the GetBucketEncryption operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetBucketEncryption for more information on using the GetBucketEncryption +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetBucketEncryptionRequest method. +// req, resp := client.GetBucketEncryptionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryption +func (c *S3) GetBucketEncryptionRequest(input *GetBucketEncryptionInput) (req *request.Request, output *GetBucketEncryptionOutput) { + op := &request.Operation{ + Name: opGetBucketEncryption, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?encryption", + } + + if input == nil { + input = &GetBucketEncryptionInput{} + } + + output = &GetBucketEncryptionOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetBucketEncryption API operation for Amazon Simple Storage Service. +// +// Returns the server-side encryption configuration of a bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetBucketEncryption for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryption +func (c *S3) GetBucketEncryption(input *GetBucketEncryptionInput) (*GetBucketEncryptionOutput, error) { + req, out := c.GetBucketEncryptionRequest(input) + return out, req.Send() +} + +// GetBucketEncryptionWithContext is the same as GetBucketEncryption with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketEncryption for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketEncryptionWithContext(ctx aws.Context, input *GetBucketEncryptionInput, opts ...request.Option) (*GetBucketEncryptionOutput, error) { + req, out := c.GetBucketEncryptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" // GetBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketInventoryConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketInventoryConfiguration for usage and error information. +// See GetBucketInventoryConfiguration for more information on using the GetBucketInventoryConfiguration +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketInventoryConfiguration method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketInventoryConfigurationRequest method. // req, resp := client.GetBucketInventoryConfigurationRequest(params) @@ -1747,7 +1948,7 @@ const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryConfigurationInput) (req *request.Request, output *GetBucketInventoryConfigurationOutput) { op := &request.Operation{ Name: opGetBucketInventoryConfiguration, @@ -1775,7 +1976,7 @@ func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration func (c *S3) GetBucketInventoryConfiguration(input *GetBucketInventoryConfigurationInput) (*GetBucketInventoryConfigurationOutput, error) { req, out := c.GetBucketInventoryConfigurationRequest(input) return out, req.Send() @@ -1801,19 +2002,18 @@ const opGetBucketLifecycle = "GetBucketLifecycle" // GetBucketLifecycleRequest generates a "aws/request.Request" representing the // client's request for the GetBucketLifecycle operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketLifecycle for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketLifecycle method directly -// instead. +// See GetBucketLifecycle for more information on using the GetBucketLifecycle +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketLifecycleRequest method. // req, resp := client.GetBucketLifecycleRequest(params) @@ -1823,7 +2023,9 @@ const opGetBucketLifecycle = "GetBucketLifecycle" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle +// +// Deprecated: GetBucketLifecycle has been deprecated func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *request.Request, output *GetBucketLifecycleOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, GetBucketLifecycle, has been deprecated") @@ -1853,7 +2055,9 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle +// +// Deprecated: GetBucketLifecycle has been deprecated func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifecycleOutput, error) { req, out := c.GetBucketLifecycleRequest(input) return out, req.Send() @@ -1868,6 +2072,8 @@ func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifec // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. +// +// Deprecated: GetBucketLifecycleWithContext has been deprecated func (c *S3) GetBucketLifecycleWithContext(ctx aws.Context, input *GetBucketLifecycleInput, opts ...request.Option) (*GetBucketLifecycleOutput, error) { req, out := c.GetBucketLifecycleRequest(input) req.SetContext(ctx) @@ -1879,19 +2085,18 @@ const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" // GetBucketLifecycleConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketLifecycleConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketLifecycleConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketLifecycleConfiguration method directly -// instead. +// See GetBucketLifecycleConfiguration for more information on using the GetBucketLifecycleConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketLifecycleConfigurationRequest method. // req, resp := client.GetBucketLifecycleConfigurationRequest(params) @@ -1901,7 +2106,7 @@ const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleConfigurationInput) (req *request.Request, output *GetBucketLifecycleConfigurationOutput) { op := &request.Operation{ Name: opGetBucketLifecycleConfiguration, @@ -1928,7 +2133,7 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLifecycleConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration func (c *S3) GetBucketLifecycleConfiguration(input *GetBucketLifecycleConfigurationInput) (*GetBucketLifecycleConfigurationOutput, error) { req, out := c.GetBucketLifecycleConfigurationRequest(input) return out, req.Send() @@ -1954,19 +2159,18 @@ const opGetBucketLocation = "GetBucketLocation" // GetBucketLocationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketLocation operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketLocation for usage and error information. +// See GetBucketLocation for more information on using the GetBucketLocation +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketLocation method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketLocationRequest method. // req, resp := client.GetBucketLocationRequest(params) @@ -1976,7 +2180,7 @@ const opGetBucketLocation = "GetBucketLocation" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *request.Request, output *GetBucketLocationOutput) { op := &request.Operation{ Name: opGetBucketLocation, @@ -2003,7 +2207,7 @@ func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLocation for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocationOutput, error) { req, out := c.GetBucketLocationRequest(input) return out, req.Send() @@ -2029,19 +2233,18 @@ const opGetBucketLogging = "GetBucketLogging" // GetBucketLoggingRequest generates a "aws/request.Request" representing the // client's request for the GetBucketLogging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketLogging for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketLogging method directly -// instead. +// See GetBucketLogging for more information on using the GetBucketLogging +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketLoggingRequest method. // req, resp := client.GetBucketLoggingRequest(params) @@ -2051,7 +2254,7 @@ const opGetBucketLogging = "GetBucketLogging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request.Request, output *GetBucketLoggingOutput) { op := &request.Operation{ Name: opGetBucketLogging, @@ -2079,7 +2282,7 @@ func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLogging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOutput, error) { req, out := c.GetBucketLoggingRequest(input) return out, req.Send() @@ -2105,19 +2308,18 @@ const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" // GetBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketMetricsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketMetricsConfiguration for usage and error information. +// See GetBucketMetricsConfiguration for more information on using the GetBucketMetricsConfiguration +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketMetricsConfiguration method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketMetricsConfigurationRequest method. // req, resp := client.GetBucketMetricsConfigurationRequest(params) @@ -2127,7 +2329,7 @@ const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigurationInput) (req *request.Request, output *GetBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opGetBucketMetricsConfiguration, @@ -2155,7 +2357,7 @@ func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigu // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration func (c *S3) GetBucketMetricsConfiguration(input *GetBucketMetricsConfigurationInput) (*GetBucketMetricsConfigurationOutput, error) { req, out := c.GetBucketMetricsConfigurationRequest(input) return out, req.Send() @@ -2181,19 +2383,18 @@ const opGetBucketNotification = "GetBucketNotification" // GetBucketNotificationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketNotification operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketNotification for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketNotification method directly -// instead. +// See GetBucketNotification for more information on using the GetBucketNotification +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketNotificationRequest method. // req, resp := client.GetBucketNotificationRequest(params) @@ -2203,7 +2404,9 @@ const opGetBucketNotification = "GetBucketNotification" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification +// +// Deprecated: GetBucketNotification has been deprecated func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfigurationDeprecated) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, GetBucketNotification, has been deprecated") @@ -2233,7 +2436,9 @@ func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketNotification for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification +// +// Deprecated: GetBucketNotification has been deprecated func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequest) (*NotificationConfigurationDeprecated, error) { req, out := c.GetBucketNotificationRequest(input) return out, req.Send() @@ -2248,6 +2453,8 @@ func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequ // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. +// +// Deprecated: GetBucketNotificationWithContext has been deprecated func (c *S3) GetBucketNotificationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfigurationDeprecated, error) { req, out := c.GetBucketNotificationRequest(input) req.SetContext(ctx) @@ -2259,19 +2466,18 @@ const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration // GetBucketNotificationConfigurationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketNotificationConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketNotificationConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketNotificationConfiguration method directly -// instead. +// See GetBucketNotificationConfiguration for more information on using the GetBucketNotificationConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketNotificationConfigurationRequest method. // req, resp := client.GetBucketNotificationConfigurationRequest(params) @@ -2281,7 +2487,7 @@ const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfiguration) { op := &request.Operation{ Name: opGetBucketNotificationConfiguration, @@ -2308,7 +2514,7 @@ func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketNotificationConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConfigurationRequest) (*NotificationConfiguration, error) { req, out := c.GetBucketNotificationConfigurationRequest(input) return out, req.Send() @@ -2334,19 +2540,18 @@ const opGetBucketPolicy = "GetBucketPolicy" // GetBucketPolicyRequest generates a "aws/request.Request" representing the // client's request for the GetBucketPolicy operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketPolicy for usage and error information. +// See GetBucketPolicy for more information on using the GetBucketPolicy +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketPolicy method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketPolicyRequest method. // req, resp := client.GetBucketPolicyRequest(params) @@ -2356,7 +2561,7 @@ const opGetBucketPolicy = "GetBucketPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.Request, output *GetBucketPolicyOutput) { op := &request.Operation{ Name: opGetBucketPolicy, @@ -2383,7 +2588,7 @@ func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.R // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutput, error) { req, out := c.GetBucketPolicyRequest(input) return out, req.Send() @@ -2405,23 +2610,97 @@ func (c *S3) GetBucketPolicyWithContext(ctx aws.Context, input *GetBucketPolicyI return out, req.Send() } +const opGetBucketPolicyStatus = "GetBucketPolicyStatus" + +// GetBucketPolicyStatusRequest generates a "aws/request.Request" representing the +// client's request for the GetBucketPolicyStatus operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetBucketPolicyStatus for more information on using the GetBucketPolicyStatus +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetBucketPolicyStatusRequest method. +// req, resp := client.GetBucketPolicyStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyStatus +func (c *S3) GetBucketPolicyStatusRequest(input *GetBucketPolicyStatusInput) (req *request.Request, output *GetBucketPolicyStatusOutput) { + op := &request.Operation{ + Name: opGetBucketPolicyStatus, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?policyStatus", + } + + if input == nil { + input = &GetBucketPolicyStatusInput{} + } + + output = &GetBucketPolicyStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetBucketPolicyStatus API operation for Amazon Simple Storage Service. +// +// Retrieves the policy status for an Amazon S3 bucket, indicating whether the +// bucket is public. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetBucketPolicyStatus for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyStatus +func (c *S3) GetBucketPolicyStatus(input *GetBucketPolicyStatusInput) (*GetBucketPolicyStatusOutput, error) { + req, out := c.GetBucketPolicyStatusRequest(input) + return out, req.Send() +} + +// GetBucketPolicyStatusWithContext is the same as GetBucketPolicyStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketPolicyStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketPolicyStatusWithContext(ctx aws.Context, input *GetBucketPolicyStatusInput, opts ...request.Option) (*GetBucketPolicyStatusOutput, error) { + req, out := c.GetBucketPolicyStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetBucketReplication = "GetBucketReplication" // GetBucketReplicationRequest generates a "aws/request.Request" representing the // client's request for the GetBucketReplication operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketReplication for usage and error information. +// See GetBucketReplication for more information on using the GetBucketReplication +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketReplication method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketReplicationRequest method. // req, resp := client.GetBucketReplicationRequest(params) @@ -2431,7 +2710,7 @@ const opGetBucketReplication = "GetBucketReplication" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *request.Request, output *GetBucketReplicationOutput) { op := &request.Operation{ Name: opGetBucketReplication, @@ -2452,13 +2731,17 @@ func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req // // Returns the replication configuration of a bucket. // +// It can take a while to propagate the put or delete a replication configuration +// to all Amazon S3 systems. Therefore, a get request soon after put or delete +// can return a wrong result. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketReplicationOutput, error) { req, out := c.GetBucketReplicationRequest(input) return out, req.Send() @@ -2484,19 +2767,18 @@ const opGetBucketRequestPayment = "GetBucketRequestPayment" // GetBucketRequestPaymentRequest generates a "aws/request.Request" representing the // client's request for the GetBucketRequestPayment operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketRequestPayment for usage and error information. +// See GetBucketRequestPayment for more information on using the GetBucketRequestPayment +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketRequestPayment method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketRequestPaymentRequest method. // req, resp := client.GetBucketRequestPaymentRequest(params) @@ -2506,7 +2788,7 @@ const opGetBucketRequestPayment = "GetBucketRequestPayment" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *request.Request, output *GetBucketRequestPaymentOutput) { op := &request.Operation{ Name: opGetBucketRequestPayment, @@ -2533,7 +2815,7 @@ func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketRequestPayment for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetBucketRequestPaymentOutput, error) { req, out := c.GetBucketRequestPaymentRequest(input) return out, req.Send() @@ -2559,19 +2841,18 @@ const opGetBucketTagging = "GetBucketTagging" // GetBucketTaggingRequest generates a "aws/request.Request" representing the // client's request for the GetBucketTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketTagging for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketTagging method directly -// instead. +// See GetBucketTagging for more information on using the GetBucketTagging +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketTaggingRequest method. // req, resp := client.GetBucketTaggingRequest(params) @@ -2581,7 +2862,7 @@ const opGetBucketTagging = "GetBucketTagging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request.Request, output *GetBucketTaggingOutput) { op := &request.Operation{ Name: opGetBucketTagging, @@ -2608,7 +2889,7 @@ func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOutput, error) { req, out := c.GetBucketTaggingRequest(input) return out, req.Send() @@ -2634,19 +2915,18 @@ const opGetBucketVersioning = "GetBucketVersioning" // GetBucketVersioningRequest generates a "aws/request.Request" representing the // client's request for the GetBucketVersioning operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetBucketVersioning for usage and error information. +// See GetBucketVersioning for more information on using the GetBucketVersioning +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketVersioning method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketVersioningRequest method. // req, resp := client.GetBucketVersioningRequest(params) @@ -2656,7 +2936,7 @@ const opGetBucketVersioning = "GetBucketVersioning" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *request.Request, output *GetBucketVersioningOutput) { op := &request.Operation{ Name: opGetBucketVersioning, @@ -2683,7 +2963,7 @@ func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketVersioning for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVersioningOutput, error) { req, out := c.GetBucketVersioningRequest(input) return out, req.Send() @@ -2709,19 +2989,18 @@ const opGetBucketWebsite = "GetBucketWebsite" // GetBucketWebsiteRequest generates a "aws/request.Request" representing the // client's request for the GetBucketWebsite operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetBucketWebsite for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetBucketWebsite method directly -// instead. +// See GetBucketWebsite for more information on using the GetBucketWebsite +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetBucketWebsiteRequest method. // req, resp := client.GetBucketWebsiteRequest(params) @@ -2731,7 +3010,7 @@ const opGetBucketWebsite = "GetBucketWebsite" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request.Request, output *GetBucketWebsiteOutput) { op := &request.Operation{ Name: opGetBucketWebsite, @@ -2758,7 +3037,7 @@ func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOutput, error) { req, out := c.GetBucketWebsiteRequest(input) return out, req.Send() @@ -2784,19 +3063,18 @@ const opGetObject = "GetObject" // GetObjectRequest generates a "aws/request.Request" representing the // client's request for the GetObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetObject for usage and error information. +// See GetObject for more information on using the GetObject +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetObject method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetObjectRequest method. // req, resp := client.GetObjectRequest(params) @@ -2806,7 +3084,7 @@ const opGetObject = "GetObject" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, output *GetObjectOutput) { op := &request.Operation{ Name: opGetObject, @@ -2838,7 +3116,7 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { req, out := c.GetObjectRequest(input) return out, req.Send() @@ -2864,19 +3142,18 @@ const opGetObjectAcl = "GetObjectAcl" // GetObjectAclRequest generates a "aws/request.Request" representing the // client's request for the GetObjectAcl operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetObjectAcl for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetObjectAcl method directly -// instead. +// See GetObjectAcl for more information on using the GetObjectAcl +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetObjectAclRequest method. // req, resp := client.GetObjectAclRequest(params) @@ -2886,7 +3163,7 @@ const opGetObjectAcl = "GetObjectAcl" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request, output *GetObjectAclOutput) { op := &request.Operation{ Name: opGetObjectAcl, @@ -2918,7 +3195,7 @@ func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request // * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl func (c *S3) GetObjectAcl(input *GetObjectAclInput) (*GetObjectAclOutput, error) { req, out := c.GetObjectAclRequest(input) return out, req.Send() @@ -2940,120 +3217,342 @@ func (c *S3) GetObjectAclWithContext(ctx aws.Context, input *GetObjectAclInput, return out, req.Send() } -const opGetObjectTagging = "GetObjectTagging" +const opGetObjectLegalHold = "GetObjectLegalHold" -// GetObjectTaggingRequest generates a "aws/request.Request" representing the -// client's request for the GetObjectTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// GetObjectLegalHoldRequest generates a "aws/request.Request" representing the +// client's request for the GetObjectLegalHold operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See GetObjectTagging for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetObjectTagging method directly -// instead. +// See GetObjectLegalHold for more information on using the GetObjectLegalHold +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the GetObjectTaggingRequest method. -// req, resp := client.GetObjectTaggingRequest(params) +// +// // Example sending a request using the GetObjectLegalHoldRequest method. +// req, resp := client.GetObjectLegalHoldRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging -func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request.Request, output *GetObjectTaggingOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectLegalHold +func (c *S3) GetObjectLegalHoldRequest(input *GetObjectLegalHoldInput) (req *request.Request, output *GetObjectLegalHoldOutput) { op := &request.Operation{ - Name: opGetObjectTagging, + Name: opGetObjectLegalHold, HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?tagging", + HTTPPath: "/{Bucket}/{Key+}?legal-hold", } if input == nil { - input = &GetObjectTaggingInput{} + input = &GetObjectLegalHoldInput{} } - output = &GetObjectTaggingOutput{} + output = &GetObjectLegalHoldOutput{} req = c.newRequest(op, input, output) return } -// GetObjectTagging API operation for Amazon Simple Storage Service. +// GetObjectLegalHold API operation for Amazon Simple Storage Service. // -// Returns the tag-set of an object. +// Gets an object's current Legal Hold status. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging -func (c *S3) GetObjectTagging(input *GetObjectTaggingInput) (*GetObjectTaggingOutput, error) { - req, out := c.GetObjectTaggingRequest(input) +// API operation GetObjectLegalHold for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectLegalHold +func (c *S3) GetObjectLegalHold(input *GetObjectLegalHoldInput) (*GetObjectLegalHoldOutput, error) { + req, out := c.GetObjectLegalHoldRequest(input) return out, req.Send() } -// GetObjectTaggingWithContext is the same as GetObjectTagging with the addition of +// GetObjectLegalHoldWithContext is the same as GetObjectLegalHold with the addition of // the ability to pass a context and additional request options. // -// See GetObjectTagging for details on how to use this API operation. +// See GetObjectLegalHold for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) GetObjectTaggingWithContext(ctx aws.Context, input *GetObjectTaggingInput, opts ...request.Option) (*GetObjectTaggingOutput, error) { - req, out := c.GetObjectTaggingRequest(input) +func (c *S3) GetObjectLegalHoldWithContext(ctx aws.Context, input *GetObjectLegalHoldInput, opts ...request.Option) (*GetObjectLegalHoldOutput, error) { + req, out := c.GetObjectLegalHoldRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetObjectTorrent = "GetObjectTorrent" +const opGetObjectLockConfiguration = "GetObjectLockConfiguration" -// GetObjectTorrentRequest generates a "aws/request.Request" representing the -// client's request for the GetObjectTorrent operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// GetObjectLockConfigurationRequest generates a "aws/request.Request" representing the +// client's request for the GetObjectLockConfiguration operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See GetObjectTorrent for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetObjectTorrent method directly -// instead. +// See GetObjectLockConfiguration for more information on using the GetObjectLockConfiguration +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the GetObjectTorrentRequest method. -// req, resp := client.GetObjectTorrentRequest(params) +// +// // Example sending a request using the GetObjectLockConfigurationRequest method. +// req, resp := client.GetObjectLockConfigurationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent -func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request.Request, output *GetObjectTorrentOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectLockConfiguration +func (c *S3) GetObjectLockConfigurationRequest(input *GetObjectLockConfigurationInput) (req *request.Request, output *GetObjectLockConfigurationOutput) { op := &request.Operation{ - Name: opGetObjectTorrent, + Name: opGetObjectLockConfiguration, HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?torrent", + HTTPPath: "/{Bucket}?object-lock", } if input == nil { - input = &GetObjectTorrentInput{} + input = &GetObjectLockConfigurationInput{} } - output = &GetObjectTorrentOutput{} + output = &GetObjectLockConfigurationOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetObjectLockConfiguration API operation for Amazon Simple Storage Service. +// +// Gets the Object Lock configuration for a bucket. The rule specified in the +// Object Lock configuration will be applied by default to every new object +// placed in the specified bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetObjectLockConfiguration for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectLockConfiguration +func (c *S3) GetObjectLockConfiguration(input *GetObjectLockConfigurationInput) (*GetObjectLockConfigurationOutput, error) { + req, out := c.GetObjectLockConfigurationRequest(input) + return out, req.Send() +} + +// GetObjectLockConfigurationWithContext is the same as GetObjectLockConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectLockConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectLockConfigurationWithContext(ctx aws.Context, input *GetObjectLockConfigurationInput, opts ...request.Option) (*GetObjectLockConfigurationOutput, error) { + req, out := c.GetObjectLockConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetObjectRetention = "GetObjectRetention" + +// GetObjectRetentionRequest generates a "aws/request.Request" representing the +// client's request for the GetObjectRetention operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetObjectRetention for more information on using the GetObjectRetention +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetObjectRetentionRequest method. +// req, resp := client.GetObjectRetentionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectRetention +func (c *S3) GetObjectRetentionRequest(input *GetObjectRetentionInput) (req *request.Request, output *GetObjectRetentionOutput) { + op := &request.Operation{ + Name: opGetObjectRetention, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}?retention", + } + + if input == nil { + input = &GetObjectRetentionInput{} + } + + output = &GetObjectRetentionOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetObjectRetention API operation for Amazon Simple Storage Service. +// +// Retrieves an object's retention settings. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetObjectRetention for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectRetention +func (c *S3) GetObjectRetention(input *GetObjectRetentionInput) (*GetObjectRetentionOutput, error) { + req, out := c.GetObjectRetentionRequest(input) + return out, req.Send() +} + +// GetObjectRetentionWithContext is the same as GetObjectRetention with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectRetention for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectRetentionWithContext(ctx aws.Context, input *GetObjectRetentionInput, opts ...request.Option) (*GetObjectRetentionOutput, error) { + req, out := c.GetObjectRetentionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetObjectTagging = "GetObjectTagging" + +// GetObjectTaggingRequest generates a "aws/request.Request" representing the +// client's request for the GetObjectTagging operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetObjectTagging for more information on using the GetObjectTagging +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetObjectTaggingRequest method. +// req, resp := client.GetObjectTaggingRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging +func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request.Request, output *GetObjectTaggingOutput) { + op := &request.Operation{ + Name: opGetObjectTagging, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}?tagging", + } + + if input == nil { + input = &GetObjectTaggingInput{} + } + + output = &GetObjectTaggingOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetObjectTagging API operation for Amazon Simple Storage Service. +// +// Returns the tag-set of an object. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetObjectTagging for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging +func (c *S3) GetObjectTagging(input *GetObjectTaggingInput) (*GetObjectTaggingOutput, error) { + req, out := c.GetObjectTaggingRequest(input) + return out, req.Send() +} + +// GetObjectTaggingWithContext is the same as GetObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectTaggingWithContext(ctx aws.Context, input *GetObjectTaggingInput, opts ...request.Option) (*GetObjectTaggingOutput, error) { + req, out := c.GetObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetObjectTorrent = "GetObjectTorrent" + +// GetObjectTorrentRequest generates a "aws/request.Request" representing the +// client's request for the GetObjectTorrent operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetObjectTorrent for more information on using the GetObjectTorrent +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetObjectTorrentRequest method. +// req, resp := client.GetObjectTorrentRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent +func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request.Request, output *GetObjectTorrentOutput) { + op := &request.Operation{ + Name: opGetObjectTorrent, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}?torrent", + } + + if input == nil { + input = &GetObjectTorrentInput{} + } + + output = &GetObjectTorrentOutput{} req = c.newRequest(op, input, output) return } @@ -3068,7 +3567,7 @@ func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetObjectTorrent for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOutput, error) { req, out := c.GetObjectTorrentRequest(input) return out, req.Send() @@ -3090,23 +3589,96 @@ func (c *S3) GetObjectTorrentWithContext(ctx aws.Context, input *GetObjectTorren return out, req.Send() } +const opGetPublicAccessBlock = "GetPublicAccessBlock" + +// GetPublicAccessBlockRequest generates a "aws/request.Request" representing the +// client's request for the GetPublicAccessBlock operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetPublicAccessBlock for more information on using the GetPublicAccessBlock +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetPublicAccessBlockRequest method. +// req, resp := client.GetPublicAccessBlockRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetPublicAccessBlock +func (c *S3) GetPublicAccessBlockRequest(input *GetPublicAccessBlockInput) (req *request.Request, output *GetPublicAccessBlockOutput) { + op := &request.Operation{ + Name: opGetPublicAccessBlock, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?publicAccessBlock", + } + + if input == nil { + input = &GetPublicAccessBlockInput{} + } + + output = &GetPublicAccessBlockOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetPublicAccessBlock API operation for Amazon Simple Storage Service. +// +// Retrieves the PublicAccessBlock configuration for an Amazon S3 bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation GetPublicAccessBlock for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetPublicAccessBlock +func (c *S3) GetPublicAccessBlock(input *GetPublicAccessBlockInput) (*GetPublicAccessBlockOutput, error) { + req, out := c.GetPublicAccessBlockRequest(input) + return out, req.Send() +} + +// GetPublicAccessBlockWithContext is the same as GetPublicAccessBlock with the addition of +// the ability to pass a context and additional request options. +// +// See GetPublicAccessBlock for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetPublicAccessBlockWithContext(ctx aws.Context, input *GetPublicAccessBlockInput, opts ...request.Option) (*GetPublicAccessBlockOutput, error) { + req, out := c.GetPublicAccessBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opHeadBucket = "HeadBucket" // HeadBucketRequest generates a "aws/request.Request" representing the // client's request for the HeadBucket operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See HeadBucket for usage and error information. +// See HeadBucket for more information on using the HeadBucket +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the HeadBucket method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the HeadBucketRequest method. // req, resp := client.HeadBucketRequest(params) @@ -3116,7 +3688,7 @@ const opHeadBucket = "HeadBucket" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, output *HeadBucketOutput) { op := &request.Operation{ Name: opHeadBucket, @@ -3130,8 +3702,7 @@ func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, ou output = &HeadBucketOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -3151,7 +3722,7 @@ func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, ou // * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { req, out := c.HeadBucketRequest(input) return out, req.Send() @@ -3177,19 +3748,18 @@ const opHeadObject = "HeadObject" // HeadObjectRequest generates a "aws/request.Request" representing the // client's request for the HeadObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See HeadObject for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the HeadObject method directly -// instead. +// See HeadObject for more information on using the HeadObject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the HeadObjectRequest method. // req, resp := client.HeadObjectRequest(params) @@ -3199,7 +3769,7 @@ const opHeadObject = "HeadObject" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, output *HeadObjectOutput) { op := &request.Operation{ Name: opHeadObject, @@ -3231,7 +3801,7 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation HeadObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { req, out := c.HeadObjectRequest(input) return out, req.Send() @@ -3257,19 +3827,18 @@ const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" // ListBucketAnalyticsConfigurationsRequest generates a "aws/request.Request" representing the // client's request for the ListBucketAnalyticsConfigurations operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See ListBucketAnalyticsConfigurations for usage and error information. +// See ListBucketAnalyticsConfigurations for more information on using the ListBucketAnalyticsConfigurations +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListBucketAnalyticsConfigurations method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListBucketAnalyticsConfigurationsRequest method. // req, resp := client.ListBucketAnalyticsConfigurationsRequest(params) @@ -3279,7 +3848,7 @@ const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalyticsConfigurationsInput) (req *request.Request, output *ListBucketAnalyticsConfigurationsOutput) { op := &request.Operation{ Name: opListBucketAnalyticsConfigurations, @@ -3306,7 +3875,7 @@ func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalytics // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketAnalyticsConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations func (c *S3) ListBucketAnalyticsConfigurations(input *ListBucketAnalyticsConfigurationsInput) (*ListBucketAnalyticsConfigurationsOutput, error) { req, out := c.ListBucketAnalyticsConfigurationsRequest(input) return out, req.Send() @@ -3332,19 +3901,18 @@ const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" // ListBucketInventoryConfigurationsRequest generates a "aws/request.Request" representing the // client's request for the ListBucketInventoryConfigurations operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See ListBucketInventoryConfigurations for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListBucketInventoryConfigurations method directly -// instead. +// See ListBucketInventoryConfigurations for more information on using the ListBucketInventoryConfigurations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListBucketInventoryConfigurationsRequest method. // req, resp := client.ListBucketInventoryConfigurationsRequest(params) @@ -3354,7 +3922,7 @@ const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventoryConfigurationsInput) (req *request.Request, output *ListBucketInventoryConfigurationsOutput) { op := &request.Operation{ Name: opListBucketInventoryConfigurations, @@ -3381,7 +3949,7 @@ func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventory // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketInventoryConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations func (c *S3) ListBucketInventoryConfigurations(input *ListBucketInventoryConfigurationsInput) (*ListBucketInventoryConfigurationsOutput, error) { req, out := c.ListBucketInventoryConfigurationsRequest(input) return out, req.Send() @@ -3407,19 +3975,18 @@ const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" // ListBucketMetricsConfigurationsRequest generates a "aws/request.Request" representing the // client's request for the ListBucketMetricsConfigurations operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See ListBucketMetricsConfigurations for usage and error information. +// See ListBucketMetricsConfigurations for more information on using the ListBucketMetricsConfigurations +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListBucketMetricsConfigurations method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListBucketMetricsConfigurationsRequest method. // req, resp := client.ListBucketMetricsConfigurationsRequest(params) @@ -3429,7 +3996,7 @@ const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConfigurationsInput) (req *request.Request, output *ListBucketMetricsConfigurationsOutput) { op := &request.Operation{ Name: opListBucketMetricsConfigurations, @@ -3456,7 +4023,7 @@ func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConf // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketMetricsConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations func (c *S3) ListBucketMetricsConfigurations(input *ListBucketMetricsConfigurationsInput) (*ListBucketMetricsConfigurationsOutput, error) { req, out := c.ListBucketMetricsConfigurationsRequest(input) return out, req.Send() @@ -3482,19 +4049,18 @@ const opListBuckets = "ListBuckets" // ListBucketsRequest generates a "aws/request.Request" representing the // client's request for the ListBuckets operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See ListBuckets for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListBuckets method directly -// instead. +// See ListBuckets for more information on using the ListBuckets +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListBucketsRequest method. // req, resp := client.ListBucketsRequest(params) @@ -3504,7 +4070,7 @@ const opListBuckets = "ListBuckets" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, output *ListBucketsOutput) { op := &request.Operation{ Name: opListBuckets, @@ -3531,7 +4097,7 @@ func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBuckets for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { req, out := c.ListBucketsRequest(input) return out, req.Send() @@ -3557,19 +4123,18 @@ const opListMultipartUploads = "ListMultipartUploads" // ListMultipartUploadsRequest generates a "aws/request.Request" representing the // client's request for the ListMultipartUploads operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See ListMultipartUploads for usage and error information. +// See ListMultipartUploads for more information on using the ListMultipartUploads +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListMultipartUploads method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListMultipartUploadsRequest method. // req, resp := client.ListMultipartUploadsRequest(params) @@ -3579,7 +4144,7 @@ const opListMultipartUploads = "ListMultipartUploads" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *request.Request, output *ListMultipartUploadsOutput) { op := &request.Operation{ Name: opListMultipartUploads, @@ -3612,7 +4177,7 @@ func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListMultipartUploads for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultipartUploadsOutput, error) { req, out := c.ListMultipartUploadsRequest(input) return out, req.Send() @@ -3688,19 +4253,18 @@ const opListObjectVersions = "ListObjectVersions" // ListObjectVersionsRequest generates a "aws/request.Request" representing the // client's request for the ListObjectVersions operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See ListObjectVersions for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListObjectVersions method directly -// instead. +// See ListObjectVersions for more information on using the ListObjectVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListObjectVersionsRequest method. // req, resp := client.ListObjectVersionsRequest(params) @@ -3710,7 +4274,7 @@ const opListObjectVersions = "ListObjectVersions" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *request.Request, output *ListObjectVersionsOutput) { op := &request.Operation{ Name: opListObjectVersions, @@ -3743,7 +4307,7 @@ func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListObjectVersions for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVersionsOutput, error) { req, out := c.ListObjectVersionsRequest(input) return out, req.Send() @@ -3819,19 +4383,18 @@ const opListObjects = "ListObjects" // ListObjectsRequest generates a "aws/request.Request" representing the // client's request for the ListObjects operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See ListObjects for usage and error information. +// See ListObjects for more information on using the ListObjects +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListObjects method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListObjectsRequest method. // req, resp := client.ListObjectsRequest(params) @@ -3841,7 +4404,7 @@ const opListObjects = "ListObjects" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, output *ListObjectsOutput) { op := &request.Operation{ Name: opListObjects, @@ -3881,7 +4444,7 @@ func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, // * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { req, out := c.ListObjectsRequest(input) return out, req.Send() @@ -3957,19 +4520,18 @@ const opListObjectsV2 = "ListObjectsV2" // ListObjectsV2Request generates a "aws/request.Request" representing the // client's request for the ListObjectsV2 operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See ListObjectsV2 for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListObjectsV2 method directly -// instead. +// See ListObjectsV2 for more information on using the ListObjectsV2 +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListObjectsV2Request method. // req, resp := client.ListObjectsV2Request(params) @@ -3979,7 +4541,7 @@ const opListObjectsV2 = "ListObjectsV2" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Request, output *ListObjectsV2Output) { op := &request.Operation{ Name: opListObjectsV2, @@ -4020,7 +4582,7 @@ func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Reque // * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, error) { req, out := c.ListObjectsV2Request(input) return out, req.Send() @@ -4096,19 +4658,18 @@ const opListParts = "ListParts" // ListPartsRequest generates a "aws/request.Request" representing the // client's request for the ListParts operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See ListParts for usage and error information. +// See ListParts for more information on using the ListParts +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the ListParts method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the ListPartsRequest method. // req, resp := client.ListPartsRequest(params) @@ -4118,7 +4679,7 @@ const opListParts = "ListParts" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, output *ListPartsOutput) { op := &request.Operation{ Name: opListParts, @@ -4151,7 +4712,7 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListParts for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { req, out := c.ListPartsRequest(input) return out, req.Send() @@ -4227,19 +4788,18 @@ const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" // PutBucketAccelerateConfigurationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketAccelerateConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketAccelerateConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketAccelerateConfiguration method directly -// instead. +// See PutBucketAccelerateConfiguration for more information on using the PutBucketAccelerateConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketAccelerateConfigurationRequest method. // req, resp := client.PutBucketAccelerateConfigurationRequest(params) @@ -4249,7 +4809,7 @@ const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateConfigurationInput) (req *request.Request, output *PutBucketAccelerateConfigurationOutput) { op := &request.Operation{ Name: opPutBucketAccelerateConfiguration, @@ -4263,8 +4823,7 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC output = &PutBucketAccelerateConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4278,7 +4837,7 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAccelerateConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration func (c *S3) PutBucketAccelerateConfiguration(input *PutBucketAccelerateConfigurationInput) (*PutBucketAccelerateConfigurationOutput, error) { req, out := c.PutBucketAccelerateConfigurationRequest(input) return out, req.Send() @@ -4304,19 +4863,18 @@ const opPutBucketAcl = "PutBucketAcl" // PutBucketAclRequest generates a "aws/request.Request" representing the // client's request for the PutBucketAcl operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketAcl for usage and error information. +// See PutBucketAcl for more information on using the PutBucketAcl +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketAcl method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketAclRequest method. // req, resp := client.PutBucketAclRequest(params) @@ -4326,7 +4884,7 @@ const opPutBucketAcl = "PutBucketAcl" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request, output *PutBucketAclOutput) { op := &request.Operation{ Name: opPutBucketAcl, @@ -4340,8 +4898,7 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request output = &PutBucketAclOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4355,7 +4912,7 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAcl for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl func (c *S3) PutBucketAcl(input *PutBucketAclInput) (*PutBucketAclOutput, error) { req, out := c.PutBucketAclRequest(input) return out, req.Send() @@ -4381,19 +4938,18 @@ const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" // PutBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketAnalyticsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketAnalyticsConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketAnalyticsConfiguration method directly -// instead. +// See PutBucketAnalyticsConfiguration for more information on using the PutBucketAnalyticsConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketAnalyticsConfigurationRequest method. // req, resp := client.PutBucketAnalyticsConfigurationRequest(params) @@ -4403,7 +4959,7 @@ const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsConfigurationInput) (req *request.Request, output *PutBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opPutBucketAnalyticsConfiguration, @@ -4417,8 +4973,7 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon output = &PutBucketAnalyticsConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4433,7 +4988,7 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration func (c *S3) PutBucketAnalyticsConfiguration(input *PutBucketAnalyticsConfigurationInput) (*PutBucketAnalyticsConfigurationOutput, error) { req, out := c.PutBucketAnalyticsConfigurationRequest(input) return out, req.Send() @@ -4459,19 +5014,18 @@ const opPutBucketCors = "PutBucketCors" // PutBucketCorsRequest generates a "aws/request.Request" representing the // client's request for the PutBucketCors operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketCors for usage and error information. +// See PutBucketCors for more information on using the PutBucketCors +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketCors method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketCorsRequest method. // req, resp := client.PutBucketCorsRequest(params) @@ -4481,7 +5035,7 @@ const opPutBucketCors = "PutBucketCors" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Request, output *PutBucketCorsOutput) { op := &request.Operation{ Name: opPutBucketCors, @@ -4495,14 +5049,13 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque output = &PutBucketCorsOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // PutBucketCors API operation for Amazon Simple Storage Service. // -// Sets the cors configuration for a bucket. +// Sets the CORS configuration for a bucket. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4510,7 +5063,7 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors func (c *S3) PutBucketCors(input *PutBucketCorsInput) (*PutBucketCorsOutput, error) { req, out := c.PutBucketCorsRequest(input) return out, req.Send() @@ -4532,111 +5085,186 @@ func (c *S3) PutBucketCorsWithContext(ctx aws.Context, input *PutBucketCorsInput return out, req.Send() } -const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" +const opPutBucketEncryption = "PutBucketEncryption" -// PutBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketInventoryConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutBucketEncryptionRequest generates a "aws/request.Request" representing the +// client's request for the PutBucketEncryption operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketInventoryConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketInventoryConfiguration method directly -// instead. +// See PutBucketEncryption for more information on using the PutBucketEncryption +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the PutBucketInventoryConfigurationRequest method. -// req, resp := client.PutBucketInventoryConfigurationRequest(params) +// +// // Example sending a request using the PutBucketEncryptionRequest method. +// req, resp := client.PutBucketEncryptionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration -func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryConfigurationInput) (req *request.Request, output *PutBucketInventoryConfigurationOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryption +func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *request.Request, output *PutBucketEncryptionOutput) { op := &request.Operation{ - Name: opPutBucketInventoryConfiguration, + Name: opPutBucketEncryption, HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?inventory", + HTTPPath: "/{Bucket}?encryption", } if input == nil { - input = &PutBucketInventoryConfigurationInput{} + input = &PutBucketEncryptionInput{} } - output = &PutBucketInventoryConfigurationOutput{} + output = &PutBucketEncryptionOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// PutBucketInventoryConfiguration API operation for Amazon Simple Storage Service. +// PutBucketEncryption API operation for Amazon Simple Storage Service. // -// Adds an inventory configuration (identified by the inventory ID) from the -// bucket. +// Creates a new server-side encryption configuration (or replaces an existing +// one, if present). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration -func (c *S3) PutBucketInventoryConfiguration(input *PutBucketInventoryConfigurationInput) (*PutBucketInventoryConfigurationOutput, error) { - req, out := c.PutBucketInventoryConfigurationRequest(input) +// API operation PutBucketEncryption for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryption +func (c *S3) PutBucketEncryption(input *PutBucketEncryptionInput) (*PutBucketEncryptionOutput, error) { + req, out := c.PutBucketEncryptionRequest(input) return out, req.Send() } -// PutBucketInventoryConfigurationWithContext is the same as PutBucketInventoryConfiguration with the addition of +// PutBucketEncryptionWithContext is the same as PutBucketEncryption with the addition of // the ability to pass a context and additional request options. // -// See PutBucketInventoryConfiguration for details on how to use this API operation. +// See PutBucketEncryption for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) PutBucketInventoryConfigurationWithContext(ctx aws.Context, input *PutBucketInventoryConfigurationInput, opts ...request.Option) (*PutBucketInventoryConfigurationOutput, error) { - req, out := c.PutBucketInventoryConfigurationRequest(input) +func (c *S3) PutBucketEncryptionWithContext(ctx aws.Context, input *PutBucketEncryptionInput, opts ...request.Option) (*PutBucketEncryptionOutput, error) { + req, out := c.PutBucketEncryptionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opPutBucketLifecycle = "PutBucketLifecycle" +const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" -// PutBucketLifecycleRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketLifecycle operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the +// client's request for the PutBucketInventoryConfiguration operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketLifecycle for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketLifecycle method directly -// instead. +// See PutBucketInventoryConfiguration for more information on using the PutBucketInventoryConfiguration +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the PutBucketLifecycleRequest method. -// req, resp := client.PutBucketLifecycleRequest(params) +// +// // Example sending a request using the PutBucketInventoryConfigurationRequest method. +// req, resp := client.PutBucketInventoryConfigurationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration +func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryConfigurationInput) (req *request.Request, output *PutBucketInventoryConfigurationOutput) { + op := &request.Operation{ + Name: opPutBucketInventoryConfiguration, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?inventory", + } + + if input == nil { + input = &PutBucketInventoryConfigurationInput{} + } + + output = &PutBucketInventoryConfigurationOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// PutBucketInventoryConfiguration API operation for Amazon Simple Storage Service. +// +// Adds an inventory configuration (identified by the inventory ID) from the +// bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation PutBucketInventoryConfiguration for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration +func (c *S3) PutBucketInventoryConfiguration(input *PutBucketInventoryConfigurationInput) (*PutBucketInventoryConfigurationOutput, error) { + req, out := c.PutBucketInventoryConfigurationRequest(input) + return out, req.Send() +} + +// PutBucketInventoryConfigurationWithContext is the same as PutBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketInventoryConfigurationWithContext(ctx aws.Context, input *PutBucketInventoryConfigurationInput, opts ...request.Option) (*PutBucketInventoryConfigurationOutput, error) { + req, out := c.PutBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opPutBucketLifecycle = "PutBucketLifecycle" + +// PutBucketLifecycleRequest generates a "aws/request.Request" representing the +// client's request for the PutBucketLifecycle operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutBucketLifecycle for more information on using the PutBucketLifecycle +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutBucketLifecycleRequest method. +// req, resp := client.PutBucketLifecycleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle +// +// Deprecated: PutBucketLifecycle has been deprecated func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *request.Request, output *PutBucketLifecycleOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, PutBucketLifecycle, has been deprecated") @@ -4653,8 +5281,7 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req output = &PutBucketLifecycleOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4668,7 +5295,9 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle +// +// Deprecated: PutBucketLifecycle has been deprecated func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifecycleOutput, error) { req, out := c.PutBucketLifecycleRequest(input) return out, req.Send() @@ -4683,6 +5312,8 @@ func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifec // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. +// +// Deprecated: PutBucketLifecycleWithContext has been deprecated func (c *S3) PutBucketLifecycleWithContext(ctx aws.Context, input *PutBucketLifecycleInput, opts ...request.Option) (*PutBucketLifecycleOutput, error) { req, out := c.PutBucketLifecycleRequest(input) req.SetContext(ctx) @@ -4694,19 +5325,18 @@ const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" // PutBucketLifecycleConfigurationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketLifecycleConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketLifecycleConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketLifecycleConfiguration method directly -// instead. +// See PutBucketLifecycleConfiguration for more information on using the PutBucketLifecycleConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketLifecycleConfigurationRequest method. // req, resp := client.PutBucketLifecycleConfigurationRequest(params) @@ -4716,7 +5346,7 @@ const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleConfigurationInput) (req *request.Request, output *PutBucketLifecycleConfigurationOutput) { op := &request.Operation{ Name: opPutBucketLifecycleConfiguration, @@ -4730,8 +5360,7 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon output = &PutBucketLifecycleConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4746,7 +5375,7 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLifecycleConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration func (c *S3) PutBucketLifecycleConfiguration(input *PutBucketLifecycleConfigurationInput) (*PutBucketLifecycleConfigurationOutput, error) { req, out := c.PutBucketLifecycleConfigurationRequest(input) return out, req.Send() @@ -4772,19 +5401,18 @@ const opPutBucketLogging = "PutBucketLogging" // PutBucketLoggingRequest generates a "aws/request.Request" representing the // client's request for the PutBucketLogging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketLogging for usage and error information. +// See PutBucketLogging for more information on using the PutBucketLogging +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketLogging method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketLoggingRequest method. // req, resp := client.PutBucketLoggingRequest(params) @@ -4794,7 +5422,7 @@ const opPutBucketLogging = "PutBucketLogging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request.Request, output *PutBucketLoggingOutput) { op := &request.Operation{ Name: opPutBucketLogging, @@ -4808,8 +5436,7 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request output = &PutBucketLoggingOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4825,7 +5452,7 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLogging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOutput, error) { req, out := c.PutBucketLoggingRequest(input) return out, req.Send() @@ -4851,19 +5478,18 @@ const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" // PutBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketMetricsConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketMetricsConfiguration for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketMetricsConfiguration method directly -// instead. +// See PutBucketMetricsConfiguration for more information on using the PutBucketMetricsConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketMetricsConfigurationRequest method. // req, resp := client.PutBucketMetricsConfigurationRequest(params) @@ -4873,7 +5499,7 @@ const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigurationInput) (req *request.Request, output *PutBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opPutBucketMetricsConfiguration, @@ -4887,8 +5513,7 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu output = &PutBucketMetricsConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4903,7 +5528,7 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration func (c *S3) PutBucketMetricsConfiguration(input *PutBucketMetricsConfigurationInput) (*PutBucketMetricsConfigurationOutput, error) { req, out := c.PutBucketMetricsConfigurationRequest(input) return out, req.Send() @@ -4929,19 +5554,18 @@ const opPutBucketNotification = "PutBucketNotification" // PutBucketNotificationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketNotification operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketNotification for usage and error information. +// See PutBucketNotification for more information on using the PutBucketNotification +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketNotification method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketNotificationRequest method. // req, resp := client.PutBucketNotificationRequest(params) @@ -4951,7 +5575,9 @@ const opPutBucketNotification = "PutBucketNotification" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification +// +// Deprecated: PutBucketNotification has been deprecated func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *request.Request, output *PutBucketNotificationOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, PutBucketNotification, has been deprecated") @@ -4968,8 +5594,7 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re output = &PutBucketNotificationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -4983,7 +5608,9 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketNotification for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification +// +// Deprecated: PutBucketNotification has been deprecated func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucketNotificationOutput, error) { req, out := c.PutBucketNotificationRequest(input) return out, req.Send() @@ -4998,6 +5625,8 @@ func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucke // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. +// +// Deprecated: PutBucketNotificationWithContext has been deprecated func (c *S3) PutBucketNotificationWithContext(ctx aws.Context, input *PutBucketNotificationInput, opts ...request.Option) (*PutBucketNotificationOutput, error) { req, out := c.PutBucketNotificationRequest(input) req.SetContext(ctx) @@ -5009,19 +5638,18 @@ const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration // PutBucketNotificationConfigurationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketNotificationConfiguration operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketNotificationConfiguration for usage and error information. +// See PutBucketNotificationConfiguration for more information on using the PutBucketNotificationConfiguration +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketNotificationConfiguration method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketNotificationConfigurationRequest method. // req, resp := client.PutBucketNotificationConfigurationRequest(params) @@ -5031,7 +5659,7 @@ const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *request.Request, output *PutBucketNotificationConfigurationOutput) { op := &request.Operation{ Name: opPutBucketNotificationConfiguration, @@ -5045,8 +5673,7 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat output = &PutBucketNotificationConfigurationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5060,7 +5687,7 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketNotificationConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConfigurationInput) (*PutBucketNotificationConfigurationOutput, error) { req, out := c.PutBucketNotificationConfigurationRequest(input) return out, req.Send() @@ -5086,19 +5713,18 @@ const opPutBucketPolicy = "PutBucketPolicy" // PutBucketPolicyRequest generates a "aws/request.Request" representing the // client's request for the PutBucketPolicy operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketPolicy for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketPolicy method directly -// instead. +// See PutBucketPolicy for more information on using the PutBucketPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketPolicyRequest method. // req, resp := client.PutBucketPolicyRequest(params) @@ -5108,7 +5734,7 @@ const opPutBucketPolicy = "PutBucketPolicy" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.Request, output *PutBucketPolicyOutput) { op := &request.Operation{ Name: opPutBucketPolicy, @@ -5122,8 +5748,7 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R output = &PutBucketPolicyOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5138,7 +5763,7 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutput, error) { req, out := c.PutBucketPolicyRequest(input) return out, req.Send() @@ -5164,19 +5789,18 @@ const opPutBucketReplication = "PutBucketReplication" // PutBucketReplicationRequest generates a "aws/request.Request" representing the // client's request for the PutBucketReplication operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketReplication for usage and error information. +// See PutBucketReplication for more information on using the PutBucketReplication +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketReplication method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketReplicationRequest method. // req, resp := client.PutBucketReplicationRequest(params) @@ -5186,7 +5810,7 @@ const opPutBucketReplication = "PutBucketReplication" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *request.Request, output *PutBucketReplicationOutput) { op := &request.Operation{ Name: opPutBucketReplication, @@ -5200,15 +5824,15 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req output = &PutBucketReplicationOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } // PutBucketReplication API operation for Amazon Simple Storage Service. // -// Creates a new replication configuration (or replaces an existing one, if -// present). +// Creates a replication configuration or replaces an existing one. For more +// information, see Cross-Region Replication (CRR) ( https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) +// in the Amazon S3 Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5216,7 +5840,7 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketReplicationOutput, error) { req, out := c.PutBucketReplicationRequest(input) return out, req.Send() @@ -5242,19 +5866,18 @@ const opPutBucketRequestPayment = "PutBucketRequestPayment" // PutBucketRequestPaymentRequest generates a "aws/request.Request" representing the // client's request for the PutBucketRequestPayment operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketRequestPayment for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketRequestPayment method directly -// instead. +// See PutBucketRequestPayment for more information on using the PutBucketRequestPayment +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketRequestPaymentRequest method. // req, resp := client.PutBucketRequestPaymentRequest(params) @@ -5264,7 +5887,7 @@ const opPutBucketRequestPayment = "PutBucketRequestPayment" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *request.Request, output *PutBucketRequestPaymentOutput) { op := &request.Operation{ Name: opPutBucketRequestPayment, @@ -5278,8 +5901,7 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) output = &PutBucketRequestPaymentOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5297,7 +5919,7 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketRequestPayment for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutBucketRequestPaymentOutput, error) { req, out := c.PutBucketRequestPaymentRequest(input) return out, req.Send() @@ -5323,19 +5945,18 @@ const opPutBucketTagging = "PutBucketTagging" // PutBucketTaggingRequest generates a "aws/request.Request" representing the // client's request for the PutBucketTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketTagging for usage and error information. +// See PutBucketTagging for more information on using the PutBucketTagging +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketTagging method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketTaggingRequest method. // req, resp := client.PutBucketTaggingRequest(params) @@ -5345,7 +5966,7 @@ const opPutBucketTagging = "PutBucketTagging" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request.Request, output *PutBucketTaggingOutput) { op := &request.Operation{ Name: opPutBucketTagging, @@ -5359,8 +5980,7 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request output = &PutBucketTaggingOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5374,7 +5994,7 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOutput, error) { req, out := c.PutBucketTaggingRequest(input) return out, req.Send() @@ -5400,19 +6020,18 @@ const opPutBucketVersioning = "PutBucketVersioning" // PutBucketVersioningRequest generates a "aws/request.Request" representing the // client's request for the PutBucketVersioning operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutBucketVersioning for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketVersioning method directly -// instead. +// See PutBucketVersioning for more information on using the PutBucketVersioning +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketVersioningRequest method. // req, resp := client.PutBucketVersioningRequest(params) @@ -5422,7 +6041,7 @@ const opPutBucketVersioning = "PutBucketVersioning" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *request.Request, output *PutBucketVersioningOutput) { op := &request.Operation{ Name: opPutBucketVersioning, @@ -5436,8 +6055,7 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r output = &PutBucketVersioningOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5452,7 +6070,7 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketVersioning for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVersioningOutput, error) { req, out := c.PutBucketVersioningRequest(input) return out, req.Send() @@ -5478,19 +6096,18 @@ const opPutBucketWebsite = "PutBucketWebsite" // PutBucketWebsiteRequest generates a "aws/request.Request" representing the // client's request for the PutBucketWebsite operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutBucketWebsite for usage and error information. +// See PutBucketWebsite for more information on using the PutBucketWebsite +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutBucketWebsite method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutBucketWebsiteRequest method. // req, resp := client.PutBucketWebsiteRequest(params) @@ -5500,7 +6117,7 @@ const opPutBucketWebsite = "PutBucketWebsite" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request.Request, output *PutBucketWebsiteOutput) { op := &request.Operation{ Name: opPutBucketWebsite, @@ -5514,8 +6131,7 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request output = &PutBucketWebsiteOutput{} req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } @@ -5529,7 +6145,7 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOutput, error) { req, out := c.PutBucketWebsiteRequest(input) return out, req.Send() @@ -5555,19 +6171,18 @@ const opPutObject = "PutObject" // PutObjectRequest generates a "aws/request.Request" representing the // client's request for the PutObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See PutObject for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutObject method directly -// instead. +// See PutObject for more information on using the PutObject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutObjectRequest method. // req, resp := client.PutObjectRequest(params) @@ -5577,7 +6192,7 @@ const opPutObject = "PutObject" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, output *PutObjectOutput) { op := &request.Operation{ Name: opPutObject, @@ -5604,7 +6219,7 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { req, out := c.PutObjectRequest(input) return out, req.Send() @@ -5630,19 +6245,18 @@ const opPutObjectAcl = "PutObjectAcl" // PutObjectAclRequest generates a "aws/request.Request" representing the // client's request for the PutObjectAcl operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See PutObjectAcl for usage and error information. +// See PutObjectAcl for more information on using the PutObjectAcl +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutObjectAcl method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the PutObjectAclRequest method. // req, resp := client.PutObjectAclRequest(params) @@ -5652,7 +6266,7 @@ const opPutObjectAcl = "PutObjectAcl" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request, output *PutObjectAclOutput) { op := &request.Operation{ Name: opPutObjectAcl, @@ -5685,7 +6299,7 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl func (c *S3) PutObjectAcl(input *PutObjectAclInput) (*PutObjectAclOutput, error) { req, out := c.PutObjectAclRequest(input) return out, req.Send() @@ -5707,501 +6321,2691 @@ func (c *S3) PutObjectAclWithContext(ctx aws.Context, input *PutObjectAclInput, return out, req.Send() } -const opPutObjectTagging = "PutObjectTagging" +const opPutObjectLegalHold = "PutObjectLegalHold" -// PutObjectTaggingRequest generates a "aws/request.Request" representing the -// client's request for the PutObjectTagging operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutObjectLegalHoldRequest generates a "aws/request.Request" representing the +// client's request for the PutObjectLegalHold operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See PutObjectTagging for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the PutObjectTagging method directly -// instead. +// See PutObjectLegalHold for more information on using the PutObjectLegalHold +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the PutObjectTaggingRequest method. -// req, resp := client.PutObjectTaggingRequest(params) +// +// // Example sending a request using the PutObjectLegalHoldRequest method. +// req, resp := client.PutObjectLegalHoldRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging -func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request.Request, output *PutObjectTaggingOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectLegalHold +func (c *S3) PutObjectLegalHoldRequest(input *PutObjectLegalHoldInput) (req *request.Request, output *PutObjectLegalHoldOutput) { op := &request.Operation{ - Name: opPutObjectTagging, + Name: opPutObjectLegalHold, HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}?tagging", + HTTPPath: "/{Bucket}/{Key+}?legal-hold", } if input == nil { - input = &PutObjectTaggingInput{} + input = &PutObjectLegalHoldInput{} } - output = &PutObjectTaggingOutput{} + output = &PutObjectLegalHoldOutput{} req = c.newRequest(op, input, output) return } -// PutObjectTagging API operation for Amazon Simple Storage Service. +// PutObjectLegalHold API operation for Amazon Simple Storage Service. // -// Sets the supplied tag-set to an object that already exists in a bucket +// Applies a Legal Hold configuration to the specified object. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging -func (c *S3) PutObjectTagging(input *PutObjectTaggingInput) (*PutObjectTaggingOutput, error) { - req, out := c.PutObjectTaggingRequest(input) +// API operation PutObjectLegalHold for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectLegalHold +func (c *S3) PutObjectLegalHold(input *PutObjectLegalHoldInput) (*PutObjectLegalHoldOutput, error) { + req, out := c.PutObjectLegalHoldRequest(input) return out, req.Send() } -// PutObjectTaggingWithContext is the same as PutObjectTagging with the addition of +// PutObjectLegalHoldWithContext is the same as PutObjectLegalHold with the addition of // the ability to pass a context and additional request options. // -// See PutObjectTagging for details on how to use this API operation. +// See PutObjectLegalHold for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) PutObjectTaggingWithContext(ctx aws.Context, input *PutObjectTaggingInput, opts ...request.Option) (*PutObjectTaggingOutput, error) { - req, out := c.PutObjectTaggingRequest(input) +func (c *S3) PutObjectLegalHoldWithContext(ctx aws.Context, input *PutObjectLegalHoldInput, opts ...request.Option) (*PutObjectLegalHoldOutput, error) { + req, out := c.PutObjectLegalHoldRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opRestoreObject = "RestoreObject" +const opPutObjectLockConfiguration = "PutObjectLockConfiguration" -// RestoreObjectRequest generates a "aws/request.Request" representing the -// client's request for the RestoreObject operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutObjectLockConfigurationRequest generates a "aws/request.Request" representing the +// client's request for the PutObjectLockConfiguration operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See RestoreObject for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the RestoreObject method directly -// instead. +// See PutObjectLockConfiguration for more information on using the PutObjectLockConfiguration +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the RestoreObjectRequest method. -// req, resp := client.RestoreObjectRequest(params) +// +// // Example sending a request using the PutObjectLockConfigurationRequest method. +// req, resp := client.PutObjectLockConfigurationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject -func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Request, output *RestoreObjectOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectLockConfiguration +func (c *S3) PutObjectLockConfigurationRequest(input *PutObjectLockConfigurationInput) (req *request.Request, output *PutObjectLockConfigurationOutput) { op := &request.Operation{ - Name: opRestoreObject, - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?restore", + Name: opPutObjectLockConfiguration, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?object-lock", } if input == nil { - input = &RestoreObjectInput{} + input = &PutObjectLockConfigurationInput{} } - output = &RestoreObjectOutput{} + output = &PutObjectLockConfigurationOutput{} req = c.newRequest(op, input, output) return } -// RestoreObject API operation for Amazon Simple Storage Service. +// PutObjectLockConfiguration API operation for Amazon Simple Storage Service. // -// Restores an archived copy of an object back into Amazon S3 +// Places an Object Lock configuration on the specified bucket. The rule specified +// in the Object Lock configuration will be applied by default to every new +// object placed in the specified bucket. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation RestoreObject for usage and error information. -// -// Returned Error Codes: -// * ErrCodeObjectAlreadyInActiveTierError "ObjectAlreadyInActiveTierError" -// This operation is not allowed against this storage tier -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject -func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, error) { - req, out := c.RestoreObjectRequest(input) +// API operation PutObjectLockConfiguration for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectLockConfiguration +func (c *S3) PutObjectLockConfiguration(input *PutObjectLockConfigurationInput) (*PutObjectLockConfigurationOutput, error) { + req, out := c.PutObjectLockConfigurationRequest(input) return out, req.Send() } -// RestoreObjectWithContext is the same as RestoreObject with the addition of +// PutObjectLockConfigurationWithContext is the same as PutObjectLockConfiguration with the addition of // the ability to pass a context and additional request options. // -// See RestoreObject for details on how to use this API operation. +// See PutObjectLockConfiguration for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) RestoreObjectWithContext(ctx aws.Context, input *RestoreObjectInput, opts ...request.Option) (*RestoreObjectOutput, error) { - req, out := c.RestoreObjectRequest(input) +func (c *S3) PutObjectLockConfigurationWithContext(ctx aws.Context, input *PutObjectLockConfigurationInput, opts ...request.Option) (*PutObjectLockConfigurationOutput, error) { + req, out := c.PutObjectLockConfigurationRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUploadPart = "UploadPart" +const opPutObjectRetention = "PutObjectRetention" -// UploadPartRequest generates a "aws/request.Request" representing the -// client's request for the UploadPart operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutObjectRetentionRequest generates a "aws/request.Request" representing the +// client's request for the PutObjectRetention operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See UploadPart for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the UploadPart method directly -// instead. +// See PutObjectRetention for more information on using the PutObjectRetention +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the UploadPartRequest method. -// req, resp := client.UploadPartRequest(params) +// +// // Example sending a request using the PutObjectRetentionRequest method. +// req, resp := client.PutObjectRetentionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart -func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, output *UploadPartOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectRetention +func (c *S3) PutObjectRetentionRequest(input *PutObjectRetentionInput) (req *request.Request, output *PutObjectRetentionOutput) { op := &request.Operation{ - Name: opUploadPart, + Name: opPutObjectRetention, HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", + HTTPPath: "/{Bucket}/{Key+}?retention", } if input == nil { - input = &UploadPartInput{} + input = &PutObjectRetentionInput{} } - output = &UploadPartOutput{} + output = &PutObjectRetentionOutput{} req = c.newRequest(op, input, output) return } -// UploadPart API operation for Amazon Simple Storage Service. -// -// Uploads a part in a multipart upload. +// PutObjectRetention API operation for Amazon Simple Storage Service. // -// Note: After you initiate multipart upload and upload one or more parts, you -// must either complete or abort multipart upload in order to stop getting charged -// for storage of the uploaded parts. Only after you either complete or abort -// multipart upload, Amazon S3 frees up the parts storage and stops charging -// you for the parts storage. +// Places an Object Retention configuration on an object. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation UploadPart for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart -func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { - req, out := c.UploadPartRequest(input) +// API operation PutObjectRetention for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectRetention +func (c *S3) PutObjectRetention(input *PutObjectRetentionInput) (*PutObjectRetentionOutput, error) { + req, out := c.PutObjectRetentionRequest(input) return out, req.Send() } -// UploadPartWithContext is the same as UploadPart with the addition of +// PutObjectRetentionWithContext is the same as PutObjectRetention with the addition of // the ability to pass a context and additional request options. // -// See UploadPart for details on how to use this API operation. +// See PutObjectRetention for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) UploadPartWithContext(ctx aws.Context, input *UploadPartInput, opts ...request.Option) (*UploadPartOutput, error) { - req, out := c.UploadPartRequest(input) +func (c *S3) PutObjectRetentionWithContext(ctx aws.Context, input *PutObjectRetentionInput, opts ...request.Option) (*PutObjectRetentionOutput, error) { + req, out := c.PutObjectRetentionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUploadPartCopy = "UploadPartCopy" +const opPutObjectTagging = "PutObjectTagging" -// UploadPartCopyRequest generates a "aws/request.Request" representing the -// client's request for the UploadPartCopy operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// PutObjectTaggingRequest generates a "aws/request.Request" representing the +// client's request for the PutObjectTagging operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See UploadPartCopy for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the UploadPartCopy method directly -// instead. +// See PutObjectTagging for more information on using the PutObjectTagging +// API call, and error handling. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// // Example sending a request using the UploadPartCopyRequest method. -// req, resp := client.UploadPartCopyRequest(params) +// +// // Example sending a request using the PutObjectTaggingRequest method. +// req, resp := client.PutObjectTaggingRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy -func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Request, output *UploadPartCopyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging +func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request.Request, output *PutObjectTaggingOutput) { op := &request.Operation{ - Name: opUploadPartCopy, + Name: opPutObjectTagging, HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", + HTTPPath: "/{Bucket}/{Key+}?tagging", } if input == nil { - input = &UploadPartCopyInput{} + input = &PutObjectTaggingInput{} } - output = &UploadPartCopyOutput{} + output = &PutObjectTaggingOutput{} req = c.newRequest(op, input, output) return } -// UploadPartCopy API operation for Amazon Simple Storage Service. +// PutObjectTagging API operation for Amazon Simple Storage Service. // -// Uploads a part by copying data from an existing object as data source. +// Sets the supplied tag-set to an object that already exists in a bucket // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Simple Storage Service's -// API operation UploadPartCopy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy -func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, error) { - req, out := c.UploadPartCopyRequest(input) +// API operation PutObjectTagging for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging +func (c *S3) PutObjectTagging(input *PutObjectTaggingInput) (*PutObjectTaggingOutput, error) { + req, out := c.PutObjectTaggingRequest(input) return out, req.Send() } -// UploadPartCopyWithContext is the same as UploadPartCopy with the addition of +// PutObjectTaggingWithContext is the same as PutObjectTagging with the addition of // the ability to pass a context and additional request options. // -// See UploadPartCopy for details on how to use this API operation. +// See PutObjectTagging for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *S3) UploadPartCopyWithContext(ctx aws.Context, input *UploadPartCopyInput, opts ...request.Option) (*UploadPartCopyOutput, error) { - req, out := c.UploadPartCopyRequest(input) +func (c *S3) PutObjectTaggingWithContext(ctx aws.Context, input *PutObjectTaggingInput, opts ...request.Option) (*PutObjectTaggingOutput, error) { + req, out := c.PutObjectTaggingRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// Specifies the days since the initiation of an Incomplete Multipart Upload -// that Lifecycle will wait before permanently removing all parts of the upload. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortIncompleteMultipartUpload -type AbortIncompleteMultipartUpload struct { - _ struct{} `type:"structure"` +const opPutPublicAccessBlock = "PutPublicAccessBlock" - // Indicates the number of days that must pass since initiation for Lifecycle - // to abort an Incomplete Multipart Upload. - DaysAfterInitiation *int64 `type:"integer"` -} +// PutPublicAccessBlockRequest generates a "aws/request.Request" representing the +// client's request for the PutPublicAccessBlock operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutPublicAccessBlock for more information on using the PutPublicAccessBlock +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutPublicAccessBlockRequest method. +// req, resp := client.PutPublicAccessBlockRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutPublicAccessBlock +func (c *S3) PutPublicAccessBlockRequest(input *PutPublicAccessBlockInput) (req *request.Request, output *PutPublicAccessBlockOutput) { + op := &request.Operation{ + Name: opPutPublicAccessBlock, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?publicAccessBlock", + } -// String returns the string representation -func (s AbortIncompleteMultipartUpload) String() string { - return awsutil.Prettify(s) + if input == nil { + input = &PutPublicAccessBlockInput{} + } + + output = &PutPublicAccessBlockOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return } -// GoString returns the string representation -func (s AbortIncompleteMultipartUpload) GoString() string { - return s.String() +// PutPublicAccessBlock API operation for Amazon Simple Storage Service. +// +// Creates or modifies the PublicAccessBlock configuration for an Amazon S3 +// bucket. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation PutPublicAccessBlock for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutPublicAccessBlock +func (c *S3) PutPublicAccessBlock(input *PutPublicAccessBlockInput) (*PutPublicAccessBlockOutput, error) { + req, out := c.PutPublicAccessBlockRequest(input) + return out, req.Send() } -// SetDaysAfterInitiation sets the DaysAfterInitiation field's value. -func (s *AbortIncompleteMultipartUpload) SetDaysAfterInitiation(v int64) *AbortIncompleteMultipartUpload { - s.DaysAfterInitiation = &v - return s +// PutPublicAccessBlockWithContext is the same as PutPublicAccessBlock with the addition of +// the ability to pass a context and additional request options. +// +// See PutPublicAccessBlock for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutPublicAccessBlockWithContext(ctx aws.Context, input *PutPublicAccessBlockInput, opts ...request.Option) (*PutPublicAccessBlockOutput, error) { + req, out := c.PutPublicAccessBlockRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadRequest -type AbortMultipartUploadInput struct { - _ struct{} `type:"structure"` +const opRestoreObject = "RestoreObject" - // Bucket is a required field +// RestoreObjectRequest generates a "aws/request.Request" representing the +// client's request for the RestoreObject operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RestoreObject for more information on using the RestoreObject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RestoreObjectRequest method. +// req, resp := client.RestoreObjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject +func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Request, output *RestoreObjectOutput) { + op := &request.Operation{ + Name: opRestoreObject, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}/{Key+}?restore", + } + + if input == nil { + input = &RestoreObjectInput{} + } + + output = &RestoreObjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// RestoreObject API operation for Amazon Simple Storage Service. +// +// Restores an archived copy of an object back into Amazon S3 +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation RestoreObject for usage and error information. +// +// Returned Error Codes: +// * ErrCodeObjectAlreadyInActiveTierError "ObjectAlreadyInActiveTierError" +// This operation is not allowed against this storage tier +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject +func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, error) { + req, out := c.RestoreObjectRequest(input) + return out, req.Send() +} + +// RestoreObjectWithContext is the same as RestoreObject with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) RestoreObjectWithContext(ctx aws.Context, input *RestoreObjectInput, opts ...request.Option) (*RestoreObjectOutput, error) { + req, out := c.RestoreObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opSelectObjectContent = "SelectObjectContent" + +// SelectObjectContentRequest generates a "aws/request.Request" representing the +// client's request for the SelectObjectContent operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See SelectObjectContent for more information on using the SelectObjectContent +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the SelectObjectContentRequest method. +// req, resp := client.SelectObjectContentRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SelectObjectContent +func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *request.Request, output *SelectObjectContentOutput) { + op := &request.Operation{ + Name: opSelectObjectContent, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}/{Key+}?select&select-type=2", + } + + if input == nil { + input = &SelectObjectContentInput{} + } + + output = &SelectObjectContentOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, rest.UnmarshalHandler) + req.Handlers.Unmarshal.PushBack(output.runEventStreamLoop) + return +} + +// SelectObjectContent API operation for Amazon Simple Storage Service. +// +// This operation filters the contents of an Amazon S3 object based on a simple +// Structured Query Language (SQL) statement. In the request, along with the +// SQL expression, you must also specify a data serialization format (JSON or +// CSV) of the object. Amazon S3 uses this to parse object data into records, +// and returns only records that match the specified SQL expression. You must +// also specify the data serialization format for the response. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation SelectObjectContent for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SelectObjectContent +func (c *S3) SelectObjectContent(input *SelectObjectContentInput) (*SelectObjectContentOutput, error) { + req, out := c.SelectObjectContentRequest(input) + return out, req.Send() +} + +// SelectObjectContentWithContext is the same as SelectObjectContent with the addition of +// the ability to pass a context and additional request options. +// +// See SelectObjectContent for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) SelectObjectContentWithContext(ctx aws.Context, input *SelectObjectContentInput, opts ...request.Option) (*SelectObjectContentOutput, error) { + req, out := c.SelectObjectContentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUploadPart = "UploadPart" + +// UploadPartRequest generates a "aws/request.Request" representing the +// client's request for the UploadPart operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UploadPart for more information on using the UploadPart +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UploadPartRequest method. +// req, resp := client.UploadPartRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart +func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, output *UploadPartOutput) { + op := &request.Operation{ + Name: opUploadPart, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", + } + + if input == nil { + input = &UploadPartInput{} + } + + output = &UploadPartOutput{} + req = c.newRequest(op, input, output) + return +} + +// UploadPart API operation for Amazon Simple Storage Service. +// +// Uploads a part in a multipart upload. +// +// Note: After you initiate multipart upload and upload one or more parts, you +// must either complete or abort multipart upload in order to stop getting charged +// for storage of the uploaded parts. Only after you either complete or abort +// multipart upload, Amazon S3 frees up the parts storage and stops charging +// you for the parts storage. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation UploadPart for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart +func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { + req, out := c.UploadPartRequest(input) + return out, req.Send() +} + +// UploadPartWithContext is the same as UploadPart with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPart for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartWithContext(ctx aws.Context, input *UploadPartInput, opts ...request.Option) (*UploadPartOutput, error) { + req, out := c.UploadPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUploadPartCopy = "UploadPartCopy" + +// UploadPartCopyRequest generates a "aws/request.Request" representing the +// client's request for the UploadPartCopy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UploadPartCopy for more information on using the UploadPartCopy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UploadPartCopyRequest method. +// req, resp := client.UploadPartCopyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy +func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Request, output *UploadPartCopyOutput) { + op := &request.Operation{ + Name: opUploadPartCopy, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", + } + + if input == nil { + input = &UploadPartCopyInput{} + } + + output = &UploadPartCopyOutput{} + req = c.newRequest(op, input, output) + return +} + +// UploadPartCopy API operation for Amazon Simple Storage Service. +// +// Uploads a part by copying data from an existing object as data source. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Simple Storage Service's +// API operation UploadPartCopy for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy +func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, error) { + req, out := c.UploadPartCopyRequest(input) + return out, req.Send() +} + +// UploadPartCopyWithContext is the same as UploadPartCopy with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPartCopy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartCopyWithContext(ctx aws.Context, input *UploadPartCopyInput, opts ...request.Option) (*UploadPartCopyOutput, error) { + req, out := c.UploadPartCopyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Specifies the days since the initiation of an Incomplete Multipart Upload +// that Lifecycle will wait before permanently removing all parts of the upload. +type AbortIncompleteMultipartUpload struct { + _ struct{} `type:"structure"` + + // Indicates the number of days that must pass since initiation for Lifecycle + // to abort an Incomplete Multipart Upload. + DaysAfterInitiation *int64 `type:"integer"` +} + +// String returns the string representation +func (s AbortIncompleteMultipartUpload) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AbortIncompleteMultipartUpload) GoString() string { + return s.String() +} + +// SetDaysAfterInitiation sets the DaysAfterInitiation field's value. +func (s *AbortIncompleteMultipartUpload) SetDaysAfterInitiation(v int64) *AbortIncompleteMultipartUpload { + s.DaysAfterInitiation = &v + return s +} + +type AbortMultipartUploadInput struct { + _ struct{} `type:"structure"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // UploadId is a required field + UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` +} + +// String returns the string representation +func (s AbortMultipartUploadInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AbortMultipartUploadInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AbortMultipartUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AbortMultipartUploadInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.UploadId == nil { + invalidParams.Add(request.NewErrParamRequired("UploadId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *AbortMultipartUploadInput) SetBucket(v string) *AbortMultipartUploadInput { + s.Bucket = &v + return s +} + +func (s *AbortMultipartUploadInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *AbortMultipartUploadInput) SetKey(v string) *AbortMultipartUploadInput { + s.Key = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *AbortMultipartUploadInput) SetRequestPayer(v string) *AbortMultipartUploadInput { + s.RequestPayer = &v + return s +} + +// SetUploadId sets the UploadId field's value. +func (s *AbortMultipartUploadInput) SetUploadId(v string) *AbortMultipartUploadInput { + s.UploadId = &v + return s +} + +type AbortMultipartUploadOutput struct { + _ struct{} `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` +} + +// String returns the string representation +func (s AbortMultipartUploadOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AbortMultipartUploadOutput) GoString() string { + return s.String() +} + +// SetRequestCharged sets the RequestCharged field's value. +func (s *AbortMultipartUploadOutput) SetRequestCharged(v string) *AbortMultipartUploadOutput { + s.RequestCharged = &v + return s +} + +type AccelerateConfiguration struct { + _ struct{} `type:"structure"` + + // The accelerate configuration of the bucket. + Status *string `type:"string" enum:"BucketAccelerateStatus"` +} + +// String returns the string representation +func (s AccelerateConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccelerateConfiguration) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *AccelerateConfiguration) SetStatus(v string) *AccelerateConfiguration { + s.Status = &v + return s +} + +type AccessControlPolicy struct { + _ struct{} `type:"structure"` + + // A list of grants. + Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` + + Owner *Owner `type:"structure"` +} + +// String returns the string representation +func (s AccessControlPolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessControlPolicy) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AccessControlPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AccessControlPolicy"} + if s.Grants != nil { + for i, v := range s.Grants { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Grants", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGrants sets the Grants field's value. +func (s *AccessControlPolicy) SetGrants(v []*Grant) *AccessControlPolicy { + s.Grants = v + return s +} + +// SetOwner sets the Owner field's value. +func (s *AccessControlPolicy) SetOwner(v *Owner) *AccessControlPolicy { + s.Owner = v + return s +} + +// A container for information about access control for replicas. +type AccessControlTranslation struct { + _ struct{} `type:"structure"` + + // The override value for the owner of the replica object. + // + // Owner is a required field + Owner *string `type:"string" required:"true" enum:"OwnerOverride"` +} + +// String returns the string representation +func (s AccessControlTranslation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessControlTranslation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AccessControlTranslation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AccessControlTranslation"} + if s.Owner == nil { + invalidParams.Add(request.NewErrParamRequired("Owner")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOwner sets the Owner field's value. +func (s *AccessControlTranslation) SetOwner(v string) *AccessControlTranslation { + s.Owner = &v + return s +} + +type AnalyticsAndOperator struct { + _ struct{} `type:"structure"` + + // The prefix to use when evaluating an AND predicate. + Prefix *string `type:"string"` + + // The list of tags to use when evaluating an AND predicate. + Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` +} + +// String returns the string representation +func (s AnalyticsAndOperator) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AnalyticsAndOperator) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AnalyticsAndOperator) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AnalyticsAndOperator"} + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPrefix sets the Prefix field's value. +func (s *AnalyticsAndOperator) SetPrefix(v string) *AnalyticsAndOperator { + s.Prefix = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *AnalyticsAndOperator) SetTags(v []*Tag) *AnalyticsAndOperator { + s.Tags = v + return s +} + +type AnalyticsConfiguration struct { + _ struct{} `type:"structure"` + + // The filter used to describe a set of objects for analyses. A filter must + // have exactly one prefix, one tag, or one conjunction (AnalyticsAndOperator). + // If no filter is provided, all objects will be considered in any analysis. + Filter *AnalyticsFilter `type:"structure"` + + // The identifier used to represent an analytics configuration. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // If present, it indicates that data related to access patterns will be collected + // and made available to analyze the tradeoffs between different storage classes. + // + // StorageClassAnalysis is a required field + StorageClassAnalysis *StorageClassAnalysis `type:"structure" required:"true"` +} + +// String returns the string representation +func (s AnalyticsConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AnalyticsConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AnalyticsConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AnalyticsConfiguration"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.StorageClassAnalysis == nil { + invalidParams.Add(request.NewErrParamRequired("StorageClassAnalysis")) + } + if s.Filter != nil { + if err := s.Filter.Validate(); err != nil { + invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + } + } + if s.StorageClassAnalysis != nil { + if err := s.StorageClassAnalysis.Validate(); err != nil { + invalidParams.AddNested("StorageClassAnalysis", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilter sets the Filter field's value. +func (s *AnalyticsConfiguration) SetFilter(v *AnalyticsFilter) *AnalyticsConfiguration { + s.Filter = v + return s +} + +// SetId sets the Id field's value. +func (s *AnalyticsConfiguration) SetId(v string) *AnalyticsConfiguration { + s.Id = &v + return s +} + +// SetStorageClassAnalysis sets the StorageClassAnalysis field's value. +func (s *AnalyticsConfiguration) SetStorageClassAnalysis(v *StorageClassAnalysis) *AnalyticsConfiguration { + s.StorageClassAnalysis = v + return s +} + +type AnalyticsExportDestination struct { + _ struct{} `type:"structure"` + + // A destination signifying output to an S3 bucket. + // + // S3BucketDestination is a required field + S3BucketDestination *AnalyticsS3BucketDestination `type:"structure" required:"true"` +} + +// String returns the string representation +func (s AnalyticsExportDestination) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AnalyticsExportDestination) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AnalyticsExportDestination) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AnalyticsExportDestination"} + if s.S3BucketDestination == nil { + invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) + } + if s.S3BucketDestination != nil { + if err := s.S3BucketDestination.Validate(); err != nil { + invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetS3BucketDestination sets the S3BucketDestination field's value. +func (s *AnalyticsExportDestination) SetS3BucketDestination(v *AnalyticsS3BucketDestination) *AnalyticsExportDestination { + s.S3BucketDestination = v + return s +} + +type AnalyticsFilter struct { + _ struct{} `type:"structure"` + + // A conjunction (logical AND) of predicates, which is used in evaluating an + // analytics filter. The operator must have at least two predicates. + And *AnalyticsAndOperator `type:"structure"` + + // The prefix to use when evaluating an analytics filter. + Prefix *string `type:"string"` + + // The tag to use when evaluating an analytics filter. + Tag *Tag `type:"structure"` +} + +// String returns the string representation +func (s AnalyticsFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AnalyticsFilter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AnalyticsFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AnalyticsFilter"} + if s.And != nil { + if err := s.And.Validate(); err != nil { + invalidParams.AddNested("And", err.(request.ErrInvalidParams)) + } + } + if s.Tag != nil { + if err := s.Tag.Validate(); err != nil { + invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAnd sets the And field's value. +func (s *AnalyticsFilter) SetAnd(v *AnalyticsAndOperator) *AnalyticsFilter { + s.And = v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *AnalyticsFilter) SetPrefix(v string) *AnalyticsFilter { + s.Prefix = &v + return s +} + +// SetTag sets the Tag field's value. +func (s *AnalyticsFilter) SetTag(v *Tag) *AnalyticsFilter { + s.Tag = v + return s +} + +type AnalyticsS3BucketDestination struct { + _ struct{} `type:"structure"` + + // The Amazon resource name (ARN) of the bucket to which data is exported. + // + // Bucket is a required field + Bucket *string `type:"string" required:"true"` + + // The account ID that owns the destination bucket. If no account ID is provided, + // the owner will not be validated prior to exporting data. + BucketAccountId *string `type:"string"` + + // The file format used when exporting data to Amazon S3. + // + // Format is a required field + Format *string `type:"string" required:"true" enum:"AnalyticsS3ExportFileFormat"` + + // The prefix to use when exporting data. The exported data begins with this + // prefix. + Prefix *string `type:"string"` +} + +// String returns the string representation +func (s AnalyticsS3BucketDestination) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AnalyticsS3BucketDestination) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AnalyticsS3BucketDestination) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AnalyticsS3BucketDestination"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *AnalyticsS3BucketDestination) SetBucket(v string) *AnalyticsS3BucketDestination { + s.Bucket = &v + return s +} + +func (s *AnalyticsS3BucketDestination) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetBucketAccountId sets the BucketAccountId field's value. +func (s *AnalyticsS3BucketDestination) SetBucketAccountId(v string) *AnalyticsS3BucketDestination { + s.BucketAccountId = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *AnalyticsS3BucketDestination) SetFormat(v string) *AnalyticsS3BucketDestination { + s.Format = &v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *AnalyticsS3BucketDestination) SetPrefix(v string) *AnalyticsS3BucketDestination { + s.Prefix = &v + return s +} + +type Bucket struct { + _ struct{} `type:"structure"` + + // Date the bucket was created. + CreationDate *time.Time `type:"timestamp"` + + // The name of the bucket. + Name *string `type:"string"` +} + +// String returns the string representation +func (s Bucket) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Bucket) GoString() string { + return s.String() +} + +// SetCreationDate sets the CreationDate field's value. +func (s *Bucket) SetCreationDate(v time.Time) *Bucket { + s.CreationDate = &v + return s +} + +// SetName sets the Name field's value. +func (s *Bucket) SetName(v string) *Bucket { + s.Name = &v + return s +} + +type BucketLifecycleConfiguration struct { + _ struct{} `type:"structure"` + + // Rules is a required field + Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` +} + +// String returns the string representation +func (s BucketLifecycleConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BucketLifecycleConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BucketLifecycleConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BucketLifecycleConfiguration"} + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) + } + if s.Rules != nil { + for i, v := range s.Rules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRules sets the Rules field's value. +func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifecycleConfiguration { + s.Rules = v + return s +} + +type BucketLoggingStatus struct { + _ struct{} `type:"structure"` + + // Container for logging information. Presence of this element indicates that + // logging is enabled. Parameters TargetBucket and TargetPrefix are required + // in this case. + LoggingEnabled *LoggingEnabled `type:"structure"` +} + +// String returns the string representation +func (s BucketLoggingStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BucketLoggingStatus) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BucketLoggingStatus) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BucketLoggingStatus"} + if s.LoggingEnabled != nil { + if err := s.LoggingEnabled.Validate(); err != nil { + invalidParams.AddNested("LoggingEnabled", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLoggingEnabled sets the LoggingEnabled field's value. +func (s *BucketLoggingStatus) SetLoggingEnabled(v *LoggingEnabled) *BucketLoggingStatus { + s.LoggingEnabled = v + return s +} + +type CORSConfiguration struct { + _ struct{} `type:"structure"` + + // CORSRules is a required field + CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true" required:"true"` +} + +// String returns the string representation +func (s CORSConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CORSConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CORSConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CORSConfiguration"} + if s.CORSRules == nil { + invalidParams.Add(request.NewErrParamRequired("CORSRules")) + } + if s.CORSRules != nil { + for i, v := range s.CORSRules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CORSRules", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCORSRules sets the CORSRules field's value. +func (s *CORSConfiguration) SetCORSRules(v []*CORSRule) *CORSConfiguration { + s.CORSRules = v + return s +} + +type CORSRule struct { + _ struct{} `type:"structure"` + + // Specifies which headers are allowed in a pre-flight OPTIONS request. + AllowedHeaders []*string `locationName:"AllowedHeader" type:"list" flattened:"true"` + + // Identifies HTTP methods that the domain/origin specified in the rule is allowed + // to execute. + // + // AllowedMethods is a required field + AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true" required:"true"` + + // One or more origins you want customers to be able to access the bucket from. + // + // AllowedOrigins is a required field + AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true" required:"true"` + + // One or more headers in the response that you want customers to be able to + // access from their applications (for example, from a JavaScript XMLHttpRequest + // object). + ExposeHeaders []*string `locationName:"ExposeHeader" type:"list" flattened:"true"` + + // The time in seconds that your browser is to cache the preflight response + // for the specified resource. + MaxAgeSeconds *int64 `type:"integer"` +} + +// String returns the string representation +func (s CORSRule) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CORSRule) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CORSRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CORSRule"} + if s.AllowedMethods == nil { + invalidParams.Add(request.NewErrParamRequired("AllowedMethods")) + } + if s.AllowedOrigins == nil { + invalidParams.Add(request.NewErrParamRequired("AllowedOrigins")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowedHeaders sets the AllowedHeaders field's value. +func (s *CORSRule) SetAllowedHeaders(v []*string) *CORSRule { + s.AllowedHeaders = v + return s +} + +// SetAllowedMethods sets the AllowedMethods field's value. +func (s *CORSRule) SetAllowedMethods(v []*string) *CORSRule { + s.AllowedMethods = v + return s +} + +// SetAllowedOrigins sets the AllowedOrigins field's value. +func (s *CORSRule) SetAllowedOrigins(v []*string) *CORSRule { + s.AllowedOrigins = v + return s +} + +// SetExposeHeaders sets the ExposeHeaders field's value. +func (s *CORSRule) SetExposeHeaders(v []*string) *CORSRule { + s.ExposeHeaders = v + return s +} + +// SetMaxAgeSeconds sets the MaxAgeSeconds field's value. +func (s *CORSRule) SetMaxAgeSeconds(v int64) *CORSRule { + s.MaxAgeSeconds = &v + return s +} + +// Describes how a CSV-formatted input object is formatted. +type CSVInput struct { + _ struct{} `type:"structure"` + + // Specifies that CSV field values may contain quoted record delimiters and + // such records should be allowed. Default value is FALSE. Setting this value + // to TRUE may lower performance. + AllowQuotedRecordDelimiter *bool `type:"boolean"` + + // The single character used to indicate a row should be ignored when present + // at the start of a row. + Comments *string `type:"string"` + + // The value used to separate individual fields in a record. + FieldDelimiter *string `type:"string"` + + // Describes the first line of input. Valid values: None, Ignore, Use. + FileHeaderInfo *string `type:"string" enum:"FileHeaderInfo"` + + // Value used for escaping where the field delimiter is part of the value. + QuoteCharacter *string `type:"string"` + + // The single character used for escaping the quote character inside an already + // escaped value. + QuoteEscapeCharacter *string `type:"string"` + + // The value used to separate individual records. + RecordDelimiter *string `type:"string"` +} + +// String returns the string representation +func (s CSVInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CSVInput) GoString() string { + return s.String() +} + +// SetAllowQuotedRecordDelimiter sets the AllowQuotedRecordDelimiter field's value. +func (s *CSVInput) SetAllowQuotedRecordDelimiter(v bool) *CSVInput { + s.AllowQuotedRecordDelimiter = &v + return s +} + +// SetComments sets the Comments field's value. +func (s *CSVInput) SetComments(v string) *CSVInput { + s.Comments = &v + return s +} + +// SetFieldDelimiter sets the FieldDelimiter field's value. +func (s *CSVInput) SetFieldDelimiter(v string) *CSVInput { + s.FieldDelimiter = &v + return s +} + +// SetFileHeaderInfo sets the FileHeaderInfo field's value. +func (s *CSVInput) SetFileHeaderInfo(v string) *CSVInput { + s.FileHeaderInfo = &v + return s +} + +// SetQuoteCharacter sets the QuoteCharacter field's value. +func (s *CSVInput) SetQuoteCharacter(v string) *CSVInput { + s.QuoteCharacter = &v + return s +} + +// SetQuoteEscapeCharacter sets the QuoteEscapeCharacter field's value. +func (s *CSVInput) SetQuoteEscapeCharacter(v string) *CSVInput { + s.QuoteEscapeCharacter = &v + return s +} + +// SetRecordDelimiter sets the RecordDelimiter field's value. +func (s *CSVInput) SetRecordDelimiter(v string) *CSVInput { + s.RecordDelimiter = &v + return s +} + +// Describes how CSV-formatted results are formatted. +type CSVOutput struct { + _ struct{} `type:"structure"` + + // The value used to separate individual fields in a record. + FieldDelimiter *string `type:"string"` + + // The value used for escaping where the field delimiter is part of the value. + QuoteCharacter *string `type:"string"` + + // Th single character used for escaping the quote character inside an already + // escaped value. + QuoteEscapeCharacter *string `type:"string"` + + // Indicates whether or not all output fields should be quoted. + QuoteFields *string `type:"string" enum:"QuoteFields"` + + // The value used to separate individual records. + RecordDelimiter *string `type:"string"` +} + +// String returns the string representation +func (s CSVOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CSVOutput) GoString() string { + return s.String() +} + +// SetFieldDelimiter sets the FieldDelimiter field's value. +func (s *CSVOutput) SetFieldDelimiter(v string) *CSVOutput { + s.FieldDelimiter = &v + return s +} + +// SetQuoteCharacter sets the QuoteCharacter field's value. +func (s *CSVOutput) SetQuoteCharacter(v string) *CSVOutput { + s.QuoteCharacter = &v + return s +} + +// SetQuoteEscapeCharacter sets the QuoteEscapeCharacter field's value. +func (s *CSVOutput) SetQuoteEscapeCharacter(v string) *CSVOutput { + s.QuoteEscapeCharacter = &v + return s +} + +// SetQuoteFields sets the QuoteFields field's value. +func (s *CSVOutput) SetQuoteFields(v string) *CSVOutput { + s.QuoteFields = &v + return s +} + +// SetRecordDelimiter sets the RecordDelimiter field's value. +func (s *CSVOutput) SetRecordDelimiter(v string) *CSVOutput { + s.RecordDelimiter = &v + return s +} + +type CloudFunctionConfiguration struct { + _ struct{} `type:"structure"` + + CloudFunction *string `type:"string"` + + // The bucket event for which to send notifications. + // + // Deprecated: Event has been deprecated + Event *string `deprecated:"true" type:"string" enum:"Event"` + + Events []*string `locationName:"Event" type:"list" flattened:"true"` + + // An optional unique identifier for configurations in a notification configuration. + // If you don't provide one, Amazon S3 will assign an ID. + Id *string `type:"string"` + + InvocationRole *string `type:"string"` +} + +// String returns the string representation +func (s CloudFunctionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudFunctionConfiguration) GoString() string { + return s.String() +} + +// SetCloudFunction sets the CloudFunction field's value. +func (s *CloudFunctionConfiguration) SetCloudFunction(v string) *CloudFunctionConfiguration { + s.CloudFunction = &v + return s +} + +// SetEvent sets the Event field's value. +func (s *CloudFunctionConfiguration) SetEvent(v string) *CloudFunctionConfiguration { + s.Event = &v + return s +} + +// SetEvents sets the Events field's value. +func (s *CloudFunctionConfiguration) SetEvents(v []*string) *CloudFunctionConfiguration { + s.Events = v + return s +} + +// SetId sets the Id field's value. +func (s *CloudFunctionConfiguration) SetId(v string) *CloudFunctionConfiguration { + s.Id = &v + return s +} + +// SetInvocationRole sets the InvocationRole field's value. +func (s *CloudFunctionConfiguration) SetInvocationRole(v string) *CloudFunctionConfiguration { + s.InvocationRole = &v + return s +} + +type CommonPrefix struct { + _ struct{} `type:"structure"` + + Prefix *string `type:"string"` +} + +// String returns the string representation +func (s CommonPrefix) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CommonPrefix) GoString() string { + return s.String() +} + +// SetPrefix sets the Prefix field's value. +func (s *CommonPrefix) SetPrefix(v string) *CommonPrefix { + s.Prefix = &v + return s +} + +type CompleteMultipartUploadInput struct { + _ struct{} `type:"structure" payload:"MultipartUpload"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + MultipartUpload *CompletedMultipartUpload `locationName:"CompleteMultipartUpload" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // UploadId is a required field + UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` +} + +// String returns the string representation +func (s CompleteMultipartUploadInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompleteMultipartUploadInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CompleteMultipartUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CompleteMultipartUploadInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.UploadId == nil { + invalidParams.Add(request.NewErrParamRequired("UploadId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *CompleteMultipartUploadInput) SetBucket(v string) *CompleteMultipartUploadInput { + s.Bucket = &v + return s +} + +func (s *CompleteMultipartUploadInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *CompleteMultipartUploadInput) SetKey(v string) *CompleteMultipartUploadInput { + s.Key = &v + return s +} + +// SetMultipartUpload sets the MultipartUpload field's value. +func (s *CompleteMultipartUploadInput) SetMultipartUpload(v *CompletedMultipartUpload) *CompleteMultipartUploadInput { + s.MultipartUpload = v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *CompleteMultipartUploadInput) SetRequestPayer(v string) *CompleteMultipartUploadInput { + s.RequestPayer = &v + return s +} + +// SetUploadId sets the UploadId field's value. +func (s *CompleteMultipartUploadInput) SetUploadId(v string) *CompleteMultipartUploadInput { + s.UploadId = &v + return s +} + +type CompleteMultipartUploadOutput struct { + _ struct{} `type:"structure"` + + Bucket *string `type:"string"` + + // Entity tag of the object. + ETag *string `type:"string"` + + // If the object expiration is configured, this will contain the expiration + // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. + Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` + + Key *string `min:"1" type:"string"` + + Location *string `type:"string"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // Version of the object. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` +} + +// String returns the string representation +func (s CompleteMultipartUploadOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompleteMultipartUploadOutput) GoString() string { + return s.String() +} + +// SetBucket sets the Bucket field's value. +func (s *CompleteMultipartUploadOutput) SetBucket(v string) *CompleteMultipartUploadOutput { + s.Bucket = &v + return s +} + +func (s *CompleteMultipartUploadOutput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetETag sets the ETag field's value. +func (s *CompleteMultipartUploadOutput) SetETag(v string) *CompleteMultipartUploadOutput { + s.ETag = &v + return s +} + +// SetExpiration sets the Expiration field's value. +func (s *CompleteMultipartUploadOutput) SetExpiration(v string) *CompleteMultipartUploadOutput { + s.Expiration = &v + return s +} + +// SetKey sets the Key field's value. +func (s *CompleteMultipartUploadOutput) SetKey(v string) *CompleteMultipartUploadOutput { + s.Key = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *CompleteMultipartUploadOutput) SetLocation(v string) *CompleteMultipartUploadOutput { + s.Location = &v + return s +} + +// SetRequestCharged sets the RequestCharged field's value. +func (s *CompleteMultipartUploadOutput) SetRequestCharged(v string) *CompleteMultipartUploadOutput { + s.RequestCharged = &v + return s +} + +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *CompleteMultipartUploadOutput) SetSSEKMSKeyId(v string) *CompleteMultipartUploadOutput { + s.SSEKMSKeyId = &v + return s +} + +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *CompleteMultipartUploadOutput) SetServerSideEncryption(v string) *CompleteMultipartUploadOutput { + s.ServerSideEncryption = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *CompleteMultipartUploadOutput) SetVersionId(v string) *CompleteMultipartUploadOutput { + s.VersionId = &v + return s +} + +type CompletedMultipartUpload struct { + _ struct{} `type:"structure"` + + Parts []*CompletedPart `locationName:"Part" type:"list" flattened:"true"` +} + +// String returns the string representation +func (s CompletedMultipartUpload) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompletedMultipartUpload) GoString() string { + return s.String() +} + +// SetParts sets the Parts field's value. +func (s *CompletedMultipartUpload) SetParts(v []*CompletedPart) *CompletedMultipartUpload { + s.Parts = v + return s +} + +type CompletedPart struct { + _ struct{} `type:"structure"` + + // Entity tag returned when the part was uploaded. + ETag *string `type:"string"` + + // Part number that identifies the part. This is a positive integer between + // 1 and 10,000. + PartNumber *int64 `type:"integer"` +} + +// String returns the string representation +func (s CompletedPart) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompletedPart) GoString() string { + return s.String() +} + +// SetETag sets the ETag field's value. +func (s *CompletedPart) SetETag(v string) *CompletedPart { + s.ETag = &v + return s +} + +// SetPartNumber sets the PartNumber field's value. +func (s *CompletedPart) SetPartNumber(v int64) *CompletedPart { + s.PartNumber = &v + return s +} + +type Condition struct { + _ struct{} `type:"structure"` + + // The HTTP error code when the redirect is applied. In the event of an error, + // if the error code equals this value, then the specified redirect is applied. + // Required when parent element Condition is specified and sibling KeyPrefixEquals + // is not specified. If both are specified, then both must be true for the redirect + // to be applied. + HttpErrorCodeReturnedEquals *string `type:"string"` + + // The object key name prefix when the redirect is applied. For example, to + // redirect requests for ExamplePage.html, the key prefix will be ExamplePage.html. + // To redirect request for all pages with the prefix docs/, the key prefix will + // be /docs, which identifies all objects in the docs/ folder. Required when + // the parent element Condition is specified and sibling HttpErrorCodeReturnedEquals + // is not specified. If both conditions are specified, both must be true for + // the redirect to be applied. + KeyPrefixEquals *string `type:"string"` +} + +// String returns the string representation +func (s Condition) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Condition) GoString() string { + return s.String() +} + +// SetHttpErrorCodeReturnedEquals sets the HttpErrorCodeReturnedEquals field's value. +func (s *Condition) SetHttpErrorCodeReturnedEquals(v string) *Condition { + s.HttpErrorCodeReturnedEquals = &v + return s +} + +// SetKeyPrefixEquals sets the KeyPrefixEquals field's value. +func (s *Condition) SetKeyPrefixEquals(v string) *Condition { + s.KeyPrefixEquals = &v + return s +} + +type ContinuationEvent struct { + _ struct{} `locationName:"ContinuationEvent" type:"structure"` +} + +// String returns the string representation +func (s ContinuationEvent) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ContinuationEvent) GoString() string { + return s.String() +} + +// The ContinuationEvent is and event in the SelectObjectContentEventStream group of events. +func (s *ContinuationEvent) eventSelectObjectContentEventStream() {} + +// UnmarshalEvent unmarshals the EventStream Message into the ContinuationEvent value. +// This method is only used internally within the SDK's EventStream handling. +func (s *ContinuationEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + return nil +} + +type CopyObjectInput struct { + _ struct{} `type:"structure"` + + // The canned ACL to apply to the object. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` + + // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Specifies caching behavior along the request/reply chain. + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + + // Specifies presentational information for the object. + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` + + // A standard MIME type describing the format of the object data. + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + + // The name of the source bucket and key name of the source object, separated + // by a slash (/). Must be URL-encoded. + // + // CopySource is a required field + CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` + + // Copies the object if its entity tag (ETag) matches the specified tag. + CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` + + // Copies the object if it has been modified since the specified time. + CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp"` + + // Copies the object if its entity tag (ETag) is different than the specified + // ETag. + CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` + + // Copies the object if it hasn't been modified since the specified time. + CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp"` + + // Specifies the algorithm to use when decrypting the source object (e.g., AES256). + CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt + // the source object. The encryption key provided in this header must be one + // that was used when the source object was created. + CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` + + // The date and time at which the object is no longer cacheable. + Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` + + // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to read the object data and its metadata. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the object ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to write the ACL for the applicable object. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + + // Specifies whether the metadata is copied from the source object or replaced + // with metadata provided in the request. + MetadataDirective *string `location:"header" locationName:"x-amz-metadata-directive" type:"string" enum:"MetadataDirective"` + + // Specifies whether you want to apply a Legal Hold to the copied object. + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` + + // The Object Lock mode that you want to apply to the copied object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // The date and time when you want the copied object's Object Lock to expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // does not store the encryption key. The key must be appropriate for use with + // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT + // requests for an object protected by AWS KMS will fail if not made via SSL + // or using SigV4. Documentation on configuring any of the officially supported + // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // The type of storage to use for the object. Defaults to 'STANDARD'. + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + + // The tag-set for the object destination object this value must be used in + // conjunction with the TaggingDirective. The tag-set must be encoded as URL + // Query parameters + Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` + + // Specifies whether the object tag-set are copied from the source object or + // replaced with tag-set provided in the request. + TaggingDirective *string `location:"header" locationName:"x-amz-tagging-directive" type:"string" enum:"TaggingDirective"` + + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` +} + +// String returns the string representation +func (s CopyObjectInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CopyObjectInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CopyObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CopyObjectInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.CopySource == nil { + invalidParams.Add(request.NewErrParamRequired("CopySource")) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetACL sets the ACL field's value. +func (s *CopyObjectInput) SetACL(v string) *CopyObjectInput { + s.ACL = &v + return s +} + +// SetBucket sets the Bucket field's value. +func (s *CopyObjectInput) SetBucket(v string) *CopyObjectInput { + s.Bucket = &v + return s +} + +func (s *CopyObjectInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetCacheControl sets the CacheControl field's value. +func (s *CopyObjectInput) SetCacheControl(v string) *CopyObjectInput { + s.CacheControl = &v + return s +} + +// SetContentDisposition sets the ContentDisposition field's value. +func (s *CopyObjectInput) SetContentDisposition(v string) *CopyObjectInput { + s.ContentDisposition = &v + return s +} + +// SetContentEncoding sets the ContentEncoding field's value. +func (s *CopyObjectInput) SetContentEncoding(v string) *CopyObjectInput { + s.ContentEncoding = &v + return s +} + +// SetContentLanguage sets the ContentLanguage field's value. +func (s *CopyObjectInput) SetContentLanguage(v string) *CopyObjectInput { + s.ContentLanguage = &v + return s +} + +// SetContentType sets the ContentType field's value. +func (s *CopyObjectInput) SetContentType(v string) *CopyObjectInput { + s.ContentType = &v + return s +} + +// SetCopySource sets the CopySource field's value. +func (s *CopyObjectInput) SetCopySource(v string) *CopyObjectInput { + s.CopySource = &v + return s +} + +// SetCopySourceIfMatch sets the CopySourceIfMatch field's value. +func (s *CopyObjectInput) SetCopySourceIfMatch(v string) *CopyObjectInput { + s.CopySourceIfMatch = &v + return s +} + +// SetCopySourceIfModifiedSince sets the CopySourceIfModifiedSince field's value. +func (s *CopyObjectInput) SetCopySourceIfModifiedSince(v time.Time) *CopyObjectInput { + s.CopySourceIfModifiedSince = &v + return s +} + +// SetCopySourceIfNoneMatch sets the CopySourceIfNoneMatch field's value. +func (s *CopyObjectInput) SetCopySourceIfNoneMatch(v string) *CopyObjectInput { + s.CopySourceIfNoneMatch = &v + return s +} + +// SetCopySourceIfUnmodifiedSince sets the CopySourceIfUnmodifiedSince field's value. +func (s *CopyObjectInput) SetCopySourceIfUnmodifiedSince(v time.Time) *CopyObjectInput { + s.CopySourceIfUnmodifiedSince = &v + return s +} + +// SetCopySourceSSECustomerAlgorithm sets the CopySourceSSECustomerAlgorithm field's value. +func (s *CopyObjectInput) SetCopySourceSSECustomerAlgorithm(v string) *CopyObjectInput { + s.CopySourceSSECustomerAlgorithm = &v + return s +} + +// SetCopySourceSSECustomerKey sets the CopySourceSSECustomerKey field's value. +func (s *CopyObjectInput) SetCopySourceSSECustomerKey(v string) *CopyObjectInput { + s.CopySourceSSECustomerKey = &v + return s +} + +func (s *CopyObjectInput) getCopySourceSSECustomerKey() (v string) { + if s.CopySourceSSECustomerKey == nil { + return v + } + return *s.CopySourceSSECustomerKey +} - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` +// SetCopySourceSSECustomerKeyMD5 sets the CopySourceSSECustomerKeyMD5 field's value. +func (s *CopyObjectInput) SetCopySourceSSECustomerKeyMD5(v string) *CopyObjectInput { + s.CopySourceSSECustomerKeyMD5 = &v + return s +} - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` +// SetExpires sets the Expires field's value. +func (s *CopyObjectInput) SetExpires(v time.Time) *CopyObjectInput { + s.Expires = &v + return s +} + +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *CopyObjectInput) SetGrantFullControl(v string) *CopyObjectInput { + s.GrantFullControl = &v + return s +} + +// SetGrantRead sets the GrantRead field's value. +func (s *CopyObjectInput) SetGrantRead(v string) *CopyObjectInput { + s.GrantRead = &v + return s +} + +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *CopyObjectInput) SetGrantReadACP(v string) *CopyObjectInput { + s.GrantReadACP = &v + return s +} + +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *CopyObjectInput) SetGrantWriteACP(v string) *CopyObjectInput { + s.GrantWriteACP = &v + return s +} + +// SetKey sets the Key field's value. +func (s *CopyObjectInput) SetKey(v string) *CopyObjectInput { + s.Key = &v + return s +} + +// SetMetadata sets the Metadata field's value. +func (s *CopyObjectInput) SetMetadata(v map[string]*string) *CopyObjectInput { + s.Metadata = v + return s +} + +// SetMetadataDirective sets the MetadataDirective field's value. +func (s *CopyObjectInput) SetMetadataDirective(v string) *CopyObjectInput { + s.MetadataDirective = &v + return s +} + +// SetObjectLockLegalHoldStatus sets the ObjectLockLegalHoldStatus field's value. +func (s *CopyObjectInput) SetObjectLockLegalHoldStatus(v string) *CopyObjectInput { + s.ObjectLockLegalHoldStatus = &v + return s +} + +// SetObjectLockMode sets the ObjectLockMode field's value. +func (s *CopyObjectInput) SetObjectLockMode(v string) *CopyObjectInput { + s.ObjectLockMode = &v + return s +} + +// SetObjectLockRetainUntilDate sets the ObjectLockRetainUntilDate field's value. +func (s *CopyObjectInput) SetObjectLockRetainUntilDate(v time.Time) *CopyObjectInput { + s.ObjectLockRetainUntilDate = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *CopyObjectInput) SetRequestPayer(v string) *CopyObjectInput { + s.RequestPayer = &v + return s +} + +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *CopyObjectInput) SetSSECustomerAlgorithm(v string) *CopyObjectInput { + s.SSECustomerAlgorithm = &v + return s +} + +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *CopyObjectInput) SetSSECustomerKey(v string) *CopyObjectInput { + s.SSECustomerKey = &v + return s +} + +func (s *CopyObjectInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey +} + +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *CopyObjectInput) SetSSECustomerKeyMD5(v string) *CopyObjectInput { + s.SSECustomerKeyMD5 = &v + return s +} + +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *CopyObjectInput) SetSSEKMSKeyId(v string) *CopyObjectInput { + s.SSEKMSKeyId = &v + return s +} + +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *CopyObjectInput) SetServerSideEncryption(v string) *CopyObjectInput { + s.ServerSideEncryption = &v + return s +} + +// SetStorageClass sets the StorageClass field's value. +func (s *CopyObjectInput) SetStorageClass(v string) *CopyObjectInput { + s.StorageClass = &v + return s +} + +// SetTagging sets the Tagging field's value. +func (s *CopyObjectInput) SetTagging(v string) *CopyObjectInput { + s.Tagging = &v + return s +} + +// SetTaggingDirective sets the TaggingDirective field's value. +func (s *CopyObjectInput) SetTaggingDirective(v string) *CopyObjectInput { + s.TaggingDirective = &v + return s +} + +// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. +func (s *CopyObjectInput) SetWebsiteRedirectLocation(v string) *CopyObjectInput { + s.WebsiteRedirectLocation = &v + return s +} + +type CopyObjectOutput struct { + _ struct{} `type:"structure" payload:"CopyObjectResult"` + + CopyObjectResult *CopyObjectResult `type:"structure"` + + CopySourceVersionId *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` + + // If the object expiration is configured, the response includes this header. + Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header confirming the encryption algorithm + // used. + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header to provide round trip message integrity + // verification of the customer-provided encryption key. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // Version ID of the newly created copy. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` } // String returns the string representation -func (s AbortMultipartUploadInput) String() string { +func (s CopyObjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AbortMultipartUploadInput) GoString() string { +func (s CopyObjectOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AbortMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AbortMultipartUploadInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } +// SetCopyObjectResult sets the CopyObjectResult field's value. +func (s *CopyObjectOutput) SetCopyObjectResult(v *CopyObjectResult) *CopyObjectOutput { + s.CopyObjectResult = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCopySourceVersionId sets the CopySourceVersionId field's value. +func (s *CopyObjectOutput) SetCopySourceVersionId(v string) *CopyObjectOutput { + s.CopySourceVersionId = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *AbortMultipartUploadInput) SetBucket(v string) *AbortMultipartUploadInput { - s.Bucket = &v +// SetExpiration sets the Expiration field's value. +func (s *CopyObjectOutput) SetExpiration(v string) *CopyObjectOutput { + s.Expiration = &v + return s +} + +// SetRequestCharged sets the RequestCharged field's value. +func (s *CopyObjectOutput) SetRequestCharged(v string) *CopyObjectOutput { + s.RequestCharged = &v + return s +} + +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *CopyObjectOutput) SetSSECustomerAlgorithm(v string) *CopyObjectOutput { + s.SSECustomerAlgorithm = &v + return s +} + +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *CopyObjectOutput) SetSSECustomerKeyMD5(v string) *CopyObjectOutput { + s.SSECustomerKeyMD5 = &v + return s +} + +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *CopyObjectOutput) SetSSEKMSKeyId(v string) *CopyObjectOutput { + s.SSEKMSKeyId = &v + return s +} + +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *CopyObjectOutput) SetServerSideEncryption(v string) *CopyObjectOutput { + s.ServerSideEncryption = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *CopyObjectOutput) SetVersionId(v string) *CopyObjectOutput { + s.VersionId = &v return s } -// SetKey sets the Key field's value. -func (s *AbortMultipartUploadInput) SetKey(v string) *AbortMultipartUploadInput { - s.Key = &v - return s +type CopyObjectResult struct { + _ struct{} `type:"structure"` + + ETag *string `type:"string"` + + LastModified *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s CopyObjectResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CopyObjectResult) GoString() string { + return s.String() } -// SetRequestPayer sets the RequestPayer field's value. -func (s *AbortMultipartUploadInput) SetRequestPayer(v string) *AbortMultipartUploadInput { - s.RequestPayer = &v +// SetETag sets the ETag field's value. +func (s *CopyObjectResult) SetETag(v string) *CopyObjectResult { + s.ETag = &v return s } -// SetUploadId sets the UploadId field's value. -func (s *AbortMultipartUploadInput) SetUploadId(v string) *AbortMultipartUploadInput { - s.UploadId = &v +// SetLastModified sets the LastModified field's value. +func (s *CopyObjectResult) SetLastModified(v time.Time) *CopyObjectResult { + s.LastModified = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadOutput -type AbortMultipartUploadOutput struct { +type CopyPartResult struct { _ struct{} `type:"structure"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // Entity tag of the object. + ETag *string `type:"string"` + + // Date and time at which the object was uploaded. + LastModified *time.Time `type:"timestamp"` } // String returns the string representation -func (s AbortMultipartUploadOutput) String() string { +func (s CopyPartResult) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AbortMultipartUploadOutput) GoString() string { +func (s CopyPartResult) GoString() string { return s.String() } -// SetRequestCharged sets the RequestCharged field's value. -func (s *AbortMultipartUploadOutput) SetRequestCharged(v string) *AbortMultipartUploadOutput { - s.RequestCharged = &v +// SetETag sets the ETag field's value. +func (s *CopyPartResult) SetETag(v string) *CopyPartResult { + s.ETag = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccelerateConfiguration -type AccelerateConfiguration struct { +// SetLastModified sets the LastModified field's value. +func (s *CopyPartResult) SetLastModified(v time.Time) *CopyPartResult { + s.LastModified = &v + return s +} + +type CreateBucketConfiguration struct { _ struct{} `type:"structure"` - // The accelerate configuration of the bucket. - Status *string `type:"string" enum:"BucketAccelerateStatus"` + // Specifies the region where the bucket will be created. If you don't specify + // a region, the bucket will be created in US Standard. + LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` } // String returns the string representation -func (s AccelerateConfiguration) String() string { +func (s CreateBucketConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AccelerateConfiguration) GoString() string { +func (s CreateBucketConfiguration) GoString() string { return s.String() } -// SetStatus sets the Status field's value. -func (s *AccelerateConfiguration) SetStatus(v string) *AccelerateConfiguration { - s.Status = &v +// SetLocationConstraint sets the LocationConstraint field's value. +func (s *CreateBucketConfiguration) SetLocationConstraint(v string) *CreateBucketConfiguration { + s.LocationConstraint = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccessControlPolicy -type AccessControlPolicy struct { - _ struct{} `type:"structure"` +type CreateBucketInput struct { + _ struct{} `type:"structure" payload:"CreateBucketConfiguration"` - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` + // The canned ACL to apply to the bucket. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` - Owner *Owner `type:"structure"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + CreateBucketConfiguration *CreateBucketConfiguration `locationName:"CreateBucketConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // Allows grantee the read, write, read ACP, and write ACP permissions on the + // bucket. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to list the objects in the bucket. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the bucket ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to create, overwrite, and delete any object in the bucket. + GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` + + // Allows grantee to write the ACL for the applicable bucket. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Specifies whether you want S3 Object Lock to be enabled for the new bucket. + ObjectLockEnabledForBucket *bool `location:"header" locationName:"x-amz-bucket-object-lock-enabled" type:"boolean"` } // String returns the string representation -func (s AccessControlPolicy) String() string { +func (s CreateBucketInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AccessControlPolicy) GoString() string { +func (s CreateBucketInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AccessControlPolicy) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AccessControlPolicy"} - if s.Grants != nil { - for i, v := range s.Grants { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Grants", i), err.(request.ErrInvalidParams)) - } - } +func (s *CreateBucketInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateBucketInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -6210,120 +9014,212 @@ func (s *AccessControlPolicy) Validate() error { return nil } -// SetGrants sets the Grants field's value. -func (s *AccessControlPolicy) SetGrants(v []*Grant) *AccessControlPolicy { - s.Grants = v +// SetACL sets the ACL field's value. +func (s *CreateBucketInput) SetACL(v string) *CreateBucketInput { + s.ACL = &v return s } -// SetOwner sets the Owner field's value. -func (s *AccessControlPolicy) SetOwner(v *Owner) *AccessControlPolicy { - s.Owner = v +// SetBucket sets the Bucket field's value. +func (s *CreateBucketInput) SetBucket(v string) *CreateBucketInput { + s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsAndOperator -type AnalyticsAndOperator struct { - _ struct{} `type:"structure"` +func (s *CreateBucketInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // The prefix to use when evaluating an AND predicate. - Prefix *string `type:"string"` +// SetCreateBucketConfiguration sets the CreateBucketConfiguration field's value. +func (s *CreateBucketInput) SetCreateBucketConfiguration(v *CreateBucketConfiguration) *CreateBucketInput { + s.CreateBucketConfiguration = v + return s +} - // The list of tags to use when evaluating an AND predicate. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *CreateBucketInput) SetGrantFullControl(v string) *CreateBucketInput { + s.GrantFullControl = &v + return s +} + +// SetGrantRead sets the GrantRead field's value. +func (s *CreateBucketInput) SetGrantRead(v string) *CreateBucketInput { + s.GrantRead = &v + return s +} + +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *CreateBucketInput) SetGrantReadACP(v string) *CreateBucketInput { + s.GrantReadACP = &v + return s +} + +// SetGrantWrite sets the GrantWrite field's value. +func (s *CreateBucketInput) SetGrantWrite(v string) *CreateBucketInput { + s.GrantWrite = &v + return s +} + +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *CreateBucketInput) SetGrantWriteACP(v string) *CreateBucketInput { + s.GrantWriteACP = &v + return s +} + +// SetObjectLockEnabledForBucket sets the ObjectLockEnabledForBucket field's value. +func (s *CreateBucketInput) SetObjectLockEnabledForBucket(v bool) *CreateBucketInput { + s.ObjectLockEnabledForBucket = &v + return s +} + +type CreateBucketOutput struct { + _ struct{} `type:"structure"` + + Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s AnalyticsAndOperator) String() string { +func (s CreateBucketOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AnalyticsAndOperator) GoString() string { +func (s CreateBucketOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetLocation sets the Location field's value. +func (s *CreateBucketOutput) SetLocation(v string) *CreateBucketOutput { + s.Location = &v + return s } -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsAndOperator) SetPrefix(v string) *AnalyticsAndOperator { - s.Prefix = &v - return s -} +type CreateMultipartUploadInput struct { + _ struct{} `type:"structure"` + + // The canned ACL to apply to the object. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Specifies caching behavior along the request/reply chain. + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + + // Specifies presentational information for the object. + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` + + // A standard MIME type describing the format of the object data. + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + + // The date and time at which the object is no longer cacheable. + Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` + + // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to read the object data and its metadata. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the object ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to write the ACL for the applicable object. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + + // Specifies whether you want to apply a Legal Hold to the uploaded object. + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` + + // Specifies the Object Lock mode that you want to apply to the uploaded object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // Specifies the date and time when you want the Object Lock to expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // does not store the encryption key. The key must be appropriate for use with + // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` -// SetTags sets the Tags field's value. -func (s *AnalyticsAndOperator) SetTags(v []*Tag) *AnalyticsAndOperator { - s.Tags = v - return s -} + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsConfiguration -type AnalyticsConfiguration struct { - _ struct{} `type:"structure"` + // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT + // requests for an object protected by AWS KMS will fail if not made via SSL + // or using SigV4. Documentation on configuring any of the officially supported + // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` - // The filter used to describe a set of objects for analyses. A filter must - // have exactly one prefix, one tag, or one conjunction (AnalyticsAndOperator). - // If no filter is provided, all objects will be considered in any analysis. - Filter *AnalyticsFilter `type:"structure"` + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` + // The type of storage to use for the object. Defaults to 'STANDARD'. + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - // If present, it indicates that data related to access patterns will be collected - // and made available to analyze the tradeoffs between different storage classes. - // - // StorageClassAnalysis is a required field - StorageClassAnalysis *StorageClassAnalysis `type:"structure" required:"true"` + // The tag-set for the object. The tag-set must be encoded as URL Query parameters + Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` + + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` } // String returns the string representation -func (s AnalyticsConfiguration) String() string { +func (s CreateMultipartUploadInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AnalyticsConfiguration) GoString() string { +func (s CreateMultipartUploadInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsConfiguration"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *CreateMultipartUploadInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateMultipartUploadInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.StorageClassAnalysis == nil { - invalidParams.Add(request.NewErrParamRequired("StorageClassAnalysis")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) } - if s.StorageClassAnalysis != nil { - if err := s.StorageClassAnalysis.Validate(); err != nil { - invalidParams.AddNested("StorageClassAnalysis", err.(request.ErrInvalidParams)) - } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -6332,353 +9228,373 @@ func (s *AnalyticsConfiguration) Validate() error { return nil } -// SetFilter sets the Filter field's value. -func (s *AnalyticsConfiguration) SetFilter(v *AnalyticsFilter) *AnalyticsConfiguration { - s.Filter = v +// SetACL sets the ACL field's value. +func (s *CreateMultipartUploadInput) SetACL(v string) *CreateMultipartUploadInput { + s.ACL = &v return s } -// SetId sets the Id field's value. -func (s *AnalyticsConfiguration) SetId(v string) *AnalyticsConfiguration { - s.Id = &v +// SetBucket sets the Bucket field's value. +func (s *CreateMultipartUploadInput) SetBucket(v string) *CreateMultipartUploadInput { + s.Bucket = &v return s } -// SetStorageClassAnalysis sets the StorageClassAnalysis field's value. -func (s *AnalyticsConfiguration) SetStorageClassAnalysis(v *StorageClassAnalysis) *AnalyticsConfiguration { - s.StorageClassAnalysis = v - return s +func (s *CreateMultipartUploadInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsExportDestination -type AnalyticsExportDestination struct { - _ struct{} `type:"structure"` - - // A destination signifying output to an S3 bucket. - // - // S3BucketDestination is a required field - S3BucketDestination *AnalyticsS3BucketDestination `type:"structure" required:"true"` +// SetCacheControl sets the CacheControl field's value. +func (s *CreateMultipartUploadInput) SetCacheControl(v string) *CreateMultipartUploadInput { + s.CacheControl = &v + return s } -// String returns the string representation -func (s AnalyticsExportDestination) String() string { - return awsutil.Prettify(s) +// SetContentDisposition sets the ContentDisposition field's value. +func (s *CreateMultipartUploadInput) SetContentDisposition(v string) *CreateMultipartUploadInput { + s.ContentDisposition = &v + return s } -// GoString returns the string representation -func (s AnalyticsExportDestination) GoString() string { - return s.String() +// SetContentEncoding sets the ContentEncoding field's value. +func (s *CreateMultipartUploadInput) SetContentEncoding(v string) *CreateMultipartUploadInput { + s.ContentEncoding = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsExportDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsExportDestination"} - if s.S3BucketDestination == nil { - invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) - } - if s.S3BucketDestination != nil { - if err := s.S3BucketDestination.Validate(); err != nil { - invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetContentLanguage sets the ContentLanguage field's value. +func (s *CreateMultipartUploadInput) SetContentLanguage(v string) *CreateMultipartUploadInput { + s.ContentLanguage = &v + return s } -// SetS3BucketDestination sets the S3BucketDestination field's value. -func (s *AnalyticsExportDestination) SetS3BucketDestination(v *AnalyticsS3BucketDestination) *AnalyticsExportDestination { - s.S3BucketDestination = v +// SetContentType sets the ContentType field's value. +func (s *CreateMultipartUploadInput) SetContentType(v string) *CreateMultipartUploadInput { + s.ContentType = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsFilter -type AnalyticsFilter struct { - _ struct{} `type:"structure"` - - // A conjunction (logical AND) of predicates, which is used in evaluating an - // analytics filter. The operator must have at least two predicates. - And *AnalyticsAndOperator `type:"structure"` - - // The prefix to use when evaluating an analytics filter. - Prefix *string `type:"string"` - - // The tag to use when evaluating an analytics filter. - Tag *Tag `type:"structure"` +// SetExpires sets the Expires field's value. +func (s *CreateMultipartUploadInput) SetExpires(v time.Time) *CreateMultipartUploadInput { + s.Expires = &v + return s } -// String returns the string representation -func (s AnalyticsFilter) String() string { - return awsutil.Prettify(s) +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *CreateMultipartUploadInput) SetGrantFullControl(v string) *CreateMultipartUploadInput { + s.GrantFullControl = &v + return s } -// GoString returns the string representation -func (s AnalyticsFilter) GoString() string { - return s.String() +// SetGrantRead sets the GrantRead field's value. +func (s *CreateMultipartUploadInput) SetGrantRead(v string) *CreateMultipartUploadInput { + s.GrantRead = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } - } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *CreateMultipartUploadInput) SetGrantReadACP(v string) *CreateMultipartUploadInput { + s.GrantReadACP = &v + return s } -// SetAnd sets the And field's value. -func (s *AnalyticsFilter) SetAnd(v *AnalyticsAndOperator) *AnalyticsFilter { - s.And = v +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *CreateMultipartUploadInput) SetGrantWriteACP(v string) *CreateMultipartUploadInput { + s.GrantWriteACP = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsFilter) SetPrefix(v string) *AnalyticsFilter { - s.Prefix = &v +// SetKey sets the Key field's value. +func (s *CreateMultipartUploadInput) SetKey(v string) *CreateMultipartUploadInput { + s.Key = &v return s } -// SetTag sets the Tag field's value. -func (s *AnalyticsFilter) SetTag(v *Tag) *AnalyticsFilter { - s.Tag = v +// SetMetadata sets the Metadata field's value. +func (s *CreateMultipartUploadInput) SetMetadata(v map[string]*string) *CreateMultipartUploadInput { + s.Metadata = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsS3BucketDestination -type AnalyticsS3BucketDestination struct { - _ struct{} `type:"structure"` - - // The Amazon resource name (ARN) of the bucket to which data is exported. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` +// SetObjectLockLegalHoldStatus sets the ObjectLockLegalHoldStatus field's value. +func (s *CreateMultipartUploadInput) SetObjectLockLegalHoldStatus(v string) *CreateMultipartUploadInput { + s.ObjectLockLegalHoldStatus = &v + return s +} - // The account ID that owns the destination bucket. If no account ID is provided, - // the owner will not be validated prior to exporting data. - BucketAccountId *string `type:"string"` +// SetObjectLockMode sets the ObjectLockMode field's value. +func (s *CreateMultipartUploadInput) SetObjectLockMode(v string) *CreateMultipartUploadInput { + s.ObjectLockMode = &v + return s +} - // The file format used when exporting data to Amazon S3. - // - // Format is a required field - Format *string `type:"string" required:"true" enum:"AnalyticsS3ExportFileFormat"` +// SetObjectLockRetainUntilDate sets the ObjectLockRetainUntilDate field's value. +func (s *CreateMultipartUploadInput) SetObjectLockRetainUntilDate(v time.Time) *CreateMultipartUploadInput { + s.ObjectLockRetainUntilDate = &v + return s +} - // The prefix to use when exporting data. The exported data begins with this - // prefix. - Prefix *string `type:"string"` +// SetRequestPayer sets the RequestPayer field's value. +func (s *CreateMultipartUploadInput) SetRequestPayer(v string) *CreateMultipartUploadInput { + s.RequestPayer = &v + return s } -// String returns the string representation -func (s AnalyticsS3BucketDestination) String() string { - return awsutil.Prettify(s) +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *CreateMultipartUploadInput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadInput { + s.SSECustomerAlgorithm = &v + return s } -// GoString returns the string representation -func (s AnalyticsS3BucketDestination) GoString() string { - return s.String() +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *CreateMultipartUploadInput) SetSSECustomerKey(v string) *CreateMultipartUploadInput { + s.SSECustomerKey = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsS3BucketDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsS3BucketDestination"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Format == nil { - invalidParams.Add(request.NewErrParamRequired("Format")) +func (s *CreateMultipartUploadInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v } + return *s.SSECustomerKey +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *CreateMultipartUploadInput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadInput { + s.SSECustomerKeyMD5 = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *AnalyticsS3BucketDestination) SetBucket(v string) *AnalyticsS3BucketDestination { - s.Bucket = &v +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *CreateMultipartUploadInput) SetSSEKMSKeyId(v string) *CreateMultipartUploadInput { + s.SSEKMSKeyId = &v return s } -// SetBucketAccountId sets the BucketAccountId field's value. -func (s *AnalyticsS3BucketDestination) SetBucketAccountId(v string) *AnalyticsS3BucketDestination { - s.BucketAccountId = &v +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *CreateMultipartUploadInput) SetServerSideEncryption(v string) *CreateMultipartUploadInput { + s.ServerSideEncryption = &v return s } -// SetFormat sets the Format field's value. -func (s *AnalyticsS3BucketDestination) SetFormat(v string) *AnalyticsS3BucketDestination { - s.Format = &v +// SetStorageClass sets the StorageClass field's value. +func (s *CreateMultipartUploadInput) SetStorageClass(v string) *CreateMultipartUploadInput { + s.StorageClass = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsS3BucketDestination) SetPrefix(v string) *AnalyticsS3BucketDestination { - s.Prefix = &v +// SetTagging sets the Tagging field's value. +func (s *CreateMultipartUploadInput) SetTagging(v string) *CreateMultipartUploadInput { + s.Tagging = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Bucket -type Bucket struct { +// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. +func (s *CreateMultipartUploadInput) SetWebsiteRedirectLocation(v string) *CreateMultipartUploadInput { + s.WebsiteRedirectLocation = &v + return s +} + +type CreateMultipartUploadOutput struct { _ struct{} `type:"structure"` - // Date the bucket was created. - CreationDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` + // Date when multipart upload will become eligible for abort operation by lifecycle. + AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp"` - // The name of the bucket. - Name *string `type:"string"` + // Id of the lifecycle rule that makes a multipart upload eligible for abort + // operation. + AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` + + // Name of the bucket to which the multipart upload was initiated. + Bucket *string `locationName:"Bucket" type:"string"` + + // Object key for which the multipart upload was initiated. + Key *string `min:"1" type:"string"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header confirming the encryption algorithm + // used. + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header to provide round trip message integrity + // verification of the customer-provided encryption key. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // ID for the initiated multipart upload. + UploadId *string `type:"string"` } // String returns the string representation -func (s Bucket) String() string { +func (s CreateMultipartUploadOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Bucket) GoString() string { +func (s CreateMultipartUploadOutput) GoString() string { return s.String() } -// SetCreationDate sets the CreationDate field's value. -func (s *Bucket) SetCreationDate(v time.Time) *Bucket { - s.CreationDate = &v +// SetAbortDate sets the AbortDate field's value. +func (s *CreateMultipartUploadOutput) SetAbortDate(v time.Time) *CreateMultipartUploadOutput { + s.AbortDate = &v return s } -// SetName sets the Name field's value. -func (s *Bucket) SetName(v string) *Bucket { - s.Name = &v +// SetAbortRuleId sets the AbortRuleId field's value. +func (s *CreateMultipartUploadOutput) SetAbortRuleId(v string) *CreateMultipartUploadOutput { + s.AbortRuleId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLifecycleConfiguration -type BucketLifecycleConfiguration struct { - _ struct{} `type:"structure"` +// SetBucket sets the Bucket field's value. +func (s *CreateMultipartUploadOutput) SetBucket(v string) *CreateMultipartUploadOutput { + s.Bucket = &v + return s +} - // Rules is a required field - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` +func (s *CreateMultipartUploadOutput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// String returns the string representation -func (s BucketLifecycleConfiguration) String() string { - return awsutil.Prettify(s) +// SetKey sets the Key field's value. +func (s *CreateMultipartUploadOutput) SetKey(v string) *CreateMultipartUploadOutput { + s.Key = &v + return s } -// GoString returns the string representation -func (s BucketLifecycleConfiguration) GoString() string { - return s.String() +// SetRequestCharged sets the RequestCharged field's value. +func (s *CreateMultipartUploadOutput) SetRequestCharged(v string) *CreateMultipartUploadOutput { + s.RequestCharged = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BucketLifecycleConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BucketLifecycleConfiguration"} - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *CreateMultipartUploadOutput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadOutput { + s.SSECustomerAlgorithm = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *CreateMultipartUploadOutput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadOutput { + s.SSECustomerKeyMD5 = &v + return s } -// SetRules sets the Rules field's value. -func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifecycleConfiguration { - s.Rules = v +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *CreateMultipartUploadOutput) SetSSEKMSKeyId(v string) *CreateMultipartUploadOutput { + s.SSEKMSKeyId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLoggingStatus -type BucketLoggingStatus struct { +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *CreateMultipartUploadOutput) SetServerSideEncryption(v string) *CreateMultipartUploadOutput { + s.ServerSideEncryption = &v + return s +} + +// SetUploadId sets the UploadId field's value. +func (s *CreateMultipartUploadOutput) SetUploadId(v string) *CreateMultipartUploadOutput { + s.UploadId = &v + return s +} + +// The container element for specifying the default Object Lock retention settings +// for new objects placed in the specified bucket. +type DefaultRetention struct { _ struct{} `type:"structure"` - LoggingEnabled *LoggingEnabled `type:"structure"` + // The number of days that you want to specify for the default retention period. + Days *int64 `type:"integer"` + + // The default Object Lock retention mode you want to apply to new objects placed + // in the specified bucket. + Mode *string `type:"string" enum:"ObjectLockRetentionMode"` + + // The number of years that you want to specify for the default retention period. + Years *int64 `type:"integer"` } // String returns the string representation -func (s BucketLoggingStatus) String() string { +func (s DefaultRetention) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BucketLoggingStatus) GoString() string { +func (s DefaultRetention) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BucketLoggingStatus) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BucketLoggingStatus"} - if s.LoggingEnabled != nil { - if err := s.LoggingEnabled.Validate(); err != nil { - invalidParams.AddNested("LoggingEnabled", err.(request.ErrInvalidParams)) - } - } +// SetDays sets the Days field's value. +func (s *DefaultRetention) SetDays(v int64) *DefaultRetention { + s.Days = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMode sets the Mode field's value. +func (s *DefaultRetention) SetMode(v string) *DefaultRetention { + s.Mode = &v + return s } -// SetLoggingEnabled sets the LoggingEnabled field's value. -func (s *BucketLoggingStatus) SetLoggingEnabled(v *LoggingEnabled) *BucketLoggingStatus { - s.LoggingEnabled = v +// SetYears sets the Years field's value. +func (s *DefaultRetention) SetYears(v int64) *DefaultRetention { + s.Years = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSConfiguration -type CORSConfiguration struct { +type Delete struct { _ struct{} `type:"structure"` - // CORSRules is a required field - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true" required:"true"` + // Objects is a required field + Objects []*ObjectIdentifier `locationName:"Object" type:"list" flattened:"true" required:"true"` + + // Element to enable quiet mode for the request. When you add this element, + // you must set its value to true. + Quiet *bool `type:"boolean"` } // String returns the string representation -func (s CORSConfiguration) String() string { +func (s Delete) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CORSConfiguration) GoString() string { +func (s Delete) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CORSConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CORSConfiguration"} - if s.CORSRules == nil { - invalidParams.Add(request.NewErrParamRequired("CORSRules")) +func (s *Delete) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Delete"} + if s.Objects == nil { + invalidParams.Add(request.NewErrParamRequired("Objects")) } - if s.CORSRules != nil { - for i, v := range s.CORSRules { + if s.Objects != nil { + for i, v := range s.Objects { if v == nil { continue } if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CORSRules", i), err.(request.ErrInvalidParams)) + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Objects", i), err.(request.ErrInvalidParams)) } } } @@ -6689,58 +9605,53 @@ func (s *CORSConfiguration) Validate() error { return nil } -// SetCORSRules sets the CORSRules field's value. -func (s *CORSConfiguration) SetCORSRules(v []*CORSRule) *CORSConfiguration { - s.CORSRules = v +// SetObjects sets the Objects field's value. +func (s *Delete) SetObjects(v []*ObjectIdentifier) *Delete { + s.Objects = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSRule -type CORSRule struct { - _ struct{} `type:"structure"` - - // Specifies which headers are allowed in a pre-flight OPTIONS request. - AllowedHeaders []*string `locationName:"AllowedHeader" type:"list" flattened:"true"` - - // Identifies HTTP methods that the domain/origin specified in the rule is allowed - // to execute. - // - // AllowedMethods is a required field - AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true" required:"true"` +// SetQuiet sets the Quiet field's value. +func (s *Delete) SetQuiet(v bool) *Delete { + s.Quiet = &v + return s +} - // One or more origins you want customers to be able to access the bucket from. - // - // AllowedOrigins is a required field - AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true" required:"true"` +type DeleteBucketAnalyticsConfigurationInput struct { + _ struct{} `type:"structure"` - // One or more headers in the response that you want customers to be able to - // access from their applications (for example, from a JavaScript XMLHttpRequest - // object). - ExposeHeaders []*string `locationName:"ExposeHeader" type:"list" flattened:"true"` + // The name of the bucket from which an analytics configuration is deleted. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The time in seconds that your browser is to cache the preflight response - // for the specified resource. - MaxAgeSeconds *int64 `type:"integer"` + // The identifier used to represent an analytics configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` } // String returns the string representation -func (s CORSRule) String() string { +func (s DeleteBucketAnalyticsConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CORSRule) GoString() string { +func (s DeleteBucketAnalyticsConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CORSRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CORSRule"} - if s.AllowedMethods == nil { - invalidParams.Add(request.NewErrParamRequired("AllowedMethods")) +func (s *DeleteBucketAnalyticsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketAnalyticsConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.AllowedOrigins == nil { - invalidParams.Add(request.NewErrParamRequired("AllowedOrigins")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } if invalidParams.Len() > 0 { @@ -6749,163 +9660,127 @@ func (s *CORSRule) Validate() error { return nil } -// SetAllowedHeaders sets the AllowedHeaders field's value. -func (s *CORSRule) SetAllowedHeaders(v []*string) *CORSRule { - s.AllowedHeaders = v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketAnalyticsConfigurationInput) SetBucket(v string) *DeleteBucketAnalyticsConfigurationInput { + s.Bucket = &v return s } -// SetAllowedMethods sets the AllowedMethods field's value. -func (s *CORSRule) SetAllowedMethods(v []*string) *CORSRule { - s.AllowedMethods = v - return s +func (s *DeleteBucketAnalyticsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetAllowedOrigins sets the AllowedOrigins field's value. -func (s *CORSRule) SetAllowedOrigins(v []*string) *CORSRule { - s.AllowedOrigins = v +// SetId sets the Id field's value. +func (s *DeleteBucketAnalyticsConfigurationInput) SetId(v string) *DeleteBucketAnalyticsConfigurationInput { + s.Id = &v return s } -// SetExposeHeaders sets the ExposeHeaders field's value. -func (s *CORSRule) SetExposeHeaders(v []*string) *CORSRule { - s.ExposeHeaders = v - return s +type DeleteBucketAnalyticsConfigurationOutput struct { + _ struct{} `type:"structure"` } -// SetMaxAgeSeconds sets the MaxAgeSeconds field's value. -func (s *CORSRule) SetMaxAgeSeconds(v int64) *CORSRule { - s.MaxAgeSeconds = &v - return s +// String returns the string representation +func (s DeleteBucketAnalyticsConfigurationOutput) String() string { + return awsutil.Prettify(s) } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CloudFunctionConfiguration -type CloudFunctionConfiguration struct { - _ struct{} `type:"structure"` - - CloudFunction *string `type:"string"` - - // Bucket event for which to send notifications. - Event *string `deprecated:"true" type:"string" enum:"Event"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` +// GoString returns the string representation +func (s DeleteBucketAnalyticsConfigurationOutput) GoString() string { + return s.String() +} - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` +type DeleteBucketCorsInput struct { + _ struct{} `type:"structure"` - InvocationRole *string `type:"string"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s CloudFunctionConfiguration) String() string { +func (s DeleteBucketCorsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CloudFunctionConfiguration) GoString() string { +func (s DeleteBucketCorsInput) GoString() string { return s.String() } -// SetCloudFunction sets the CloudFunction field's value. -func (s *CloudFunctionConfiguration) SetCloudFunction(v string) *CloudFunctionConfiguration { - s.CloudFunction = &v - return s -} - -// SetEvent sets the Event field's value. -func (s *CloudFunctionConfiguration) SetEvent(v string) *CloudFunctionConfiguration { - s.Event = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketCorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketCorsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } -// SetEvents sets the Events field's value. -func (s *CloudFunctionConfiguration) SetEvents(v []*string) *CloudFunctionConfiguration { - s.Events = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetId sets the Id field's value. -func (s *CloudFunctionConfiguration) SetId(v string) *CloudFunctionConfiguration { - s.Id = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketCorsInput) SetBucket(v string) *DeleteBucketCorsInput { + s.Bucket = &v return s } -// SetInvocationRole sets the InvocationRole field's value. -func (s *CloudFunctionConfiguration) SetInvocationRole(v string) *CloudFunctionConfiguration { - s.InvocationRole = &v - return s +func (s *DeleteBucketCorsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CommonPrefix -type CommonPrefix struct { +type DeleteBucketCorsOutput struct { _ struct{} `type:"structure"` - - Prefix *string `type:"string"` } // String returns the string representation -func (s CommonPrefix) String() string { +func (s DeleteBucketCorsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CommonPrefix) GoString() string { +func (s DeleteBucketCorsOutput) GoString() string { return s.String() } -// SetPrefix sets the Prefix field's value. -func (s *CommonPrefix) SetPrefix(v string) *CommonPrefix { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadRequest -type CompleteMultipartUploadInput struct { - _ struct{} `type:"structure" payload:"MultipartUpload"` +type DeleteBucketEncryptionInput struct { + _ struct{} `type:"structure"` + // The name of the bucket containing the server-side encryption configuration + // to delete. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - MultipartUpload *CompletedMultipartUpload `locationName:"CompleteMultipartUpload" type:"structure"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` } // String returns the string representation -func (s CompleteMultipartUploadInput) String() string { +func (s DeleteBucketEncryptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CompleteMultipartUploadInput) GoString() string { +func (s DeleteBucketEncryptionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CompleteMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CompleteMultipartUploadInput"} +func (s *DeleteBucketEncryptionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketEncryptionInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -6915,389 +9790,394 @@ func (s *CompleteMultipartUploadInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *CompleteMultipartUploadInput) SetBucket(v string) *CompleteMultipartUploadInput { +func (s *DeleteBucketEncryptionInput) SetBucket(v string) *DeleteBucketEncryptionInput { s.Bucket = &v return s } -// SetKey sets the Key field's value. -func (s *CompleteMultipartUploadInput) SetKey(v string) *CompleteMultipartUploadInput { - s.Key = &v - return s +func (s *DeleteBucketEncryptionInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetMultipartUpload sets the MultipartUpload field's value. -func (s *CompleteMultipartUploadInput) SetMultipartUpload(v *CompletedMultipartUpload) *CompleteMultipartUploadInput { - s.MultipartUpload = v - return s +type DeleteBucketEncryptionOutput struct { + _ struct{} `type:"structure"` } -// SetRequestPayer sets the RequestPayer field's value. -func (s *CompleteMultipartUploadInput) SetRequestPayer(v string) *CompleteMultipartUploadInput { - s.RequestPayer = &v - return s +// String returns the string representation +func (s DeleteBucketEncryptionOutput) String() string { + return awsutil.Prettify(s) } -// SetUploadId sets the UploadId field's value. -func (s *CompleteMultipartUploadInput) SetUploadId(v string) *CompleteMultipartUploadInput { - s.UploadId = &v - return s +// GoString returns the string representation +func (s DeleteBucketEncryptionOutput) GoString() string { + return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadOutput -type CompleteMultipartUploadOutput struct { +type DeleteBucketInput struct { _ struct{} `type:"structure"` - Bucket *string `type:"string"` - - // Entity tag of the object. - ETag *string `type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - Key *string `min:"1" type:"string"` - - Location *string `type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s CompleteMultipartUploadOutput) String() string { +func (s DeleteBucketInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CompleteMultipartUploadOutput) GoString() string { +func (s DeleteBucketInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetBucket sets the Bucket field's value. -func (s *CompleteMultipartUploadOutput) SetBucket(v string) *CompleteMultipartUploadOutput { +func (s *DeleteBucketInput) SetBucket(v string) *DeleteBucketInput { s.Bucket = &v return s } -// SetETag sets the ETag field's value. -func (s *CompleteMultipartUploadOutput) SetETag(v string) *CompleteMultipartUploadOutput { - s.ETag = &v - return s +func (s *DeleteBucketInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type DeleteBucketInventoryConfigurationInput struct { + _ struct{} `type:"structure"` + + // The name of the bucket containing the inventory configuration to delete. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The ID used to identify the inventory configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` } -// SetExpiration sets the Expiration field's value. -func (s *CompleteMultipartUploadOutput) SetExpiration(v string) *CompleteMultipartUploadOutput { - s.Expiration = &v - return s +// String returns the string representation +func (s DeleteBucketInventoryConfigurationInput) String() string { + return awsutil.Prettify(s) } -// SetKey sets the Key field's value. -func (s *CompleteMultipartUploadOutput) SetKey(v string) *CompleteMultipartUploadOutput { - s.Key = &v - return s +// GoString returns the string representation +func (s DeleteBucketInventoryConfigurationInput) GoString() string { + return s.String() } -// SetLocation sets the Location field's value. -func (s *CompleteMultipartUploadOutput) SetLocation(v string) *CompleteMultipartUploadOutput { - s.Location = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketInventoryConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInventoryConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } -// SetRequestCharged sets the RequestCharged field's value. -func (s *CompleteMultipartUploadOutput) SetRequestCharged(v string) *CompleteMultipartUploadOutput { - s.RequestCharged = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CompleteMultipartUploadOutput) SetSSEKMSKeyId(v string) *CompleteMultipartUploadOutput { - s.SSEKMSKeyId = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketInventoryConfigurationInput) SetBucket(v string) *DeleteBucketInventoryConfigurationInput { + s.Bucket = &v return s } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CompleteMultipartUploadOutput) SetServerSideEncryption(v string) *CompleteMultipartUploadOutput { - s.ServerSideEncryption = &v - return s +func (s *DeleteBucketInventoryConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetVersionId sets the VersionId field's value. -func (s *CompleteMultipartUploadOutput) SetVersionId(v string) *CompleteMultipartUploadOutput { - s.VersionId = &v +// SetId sets the Id field's value. +func (s *DeleteBucketInventoryConfigurationInput) SetId(v string) *DeleteBucketInventoryConfigurationInput { + s.Id = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedMultipartUpload -type CompletedMultipartUpload struct { +type DeleteBucketInventoryConfigurationOutput struct { _ struct{} `type:"structure"` - - Parts []*CompletedPart `locationName:"Part" type:"list" flattened:"true"` } // String returns the string representation -func (s CompletedMultipartUpload) String() string { +func (s DeleteBucketInventoryConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CompletedMultipartUpload) GoString() string { +func (s DeleteBucketInventoryConfigurationOutput) GoString() string { return s.String() } -// SetParts sets the Parts field's value. -func (s *CompletedMultipartUpload) SetParts(v []*CompletedPart) *CompletedMultipartUpload { - s.Parts = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedPart -type CompletedPart struct { +type DeleteBucketLifecycleInput struct { _ struct{} `type:"structure"` - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` - - // Part number that identifies the part. This is a positive integer between - // 1 and 10,000. - PartNumber *int64 `type:"integer"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s CompletedPart) String() string { +func (s DeleteBucketLifecycleInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CompletedPart) GoString() string { +func (s DeleteBucketLifecycleInput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *CompletedPart) SetETag(v string) *CompletedPart { - s.ETag = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketLifecycleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketLifecycleInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPartNumber sets the PartNumber field's value. -func (s *CompletedPart) SetPartNumber(v int64) *CompletedPart { - s.PartNumber = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketLifecycleInput) SetBucket(v string) *DeleteBucketLifecycleInput { + s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Condition -type Condition struct { - _ struct{} `type:"structure"` - - // The HTTP error code when the redirect is applied. In the event of an error, - // if the error code equals this value, then the specified redirect is applied. - // Required when parent element Condition is specified and sibling KeyPrefixEquals - // is not specified. If both are specified, then both must be true for the redirect - // to be applied. - HttpErrorCodeReturnedEquals *string `type:"string"` +func (s *DeleteBucketLifecycleInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // The object key name prefix when the redirect is applied. For example, to - // redirect requests for ExamplePage.html, the key prefix will be ExamplePage.html. - // To redirect request for all pages with the prefix docs/, the key prefix will - // be /docs, which identifies all objects in the docs/ folder. Required when - // the parent element Condition is specified and sibling HttpErrorCodeReturnedEquals - // is not specified. If both conditions are specified, both must be true for - // the redirect to be applied. - KeyPrefixEquals *string `type:"string"` +type DeleteBucketLifecycleOutput struct { + _ struct{} `type:"structure"` } // String returns the string representation -func (s Condition) String() string { +func (s DeleteBucketLifecycleOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Condition) GoString() string { +func (s DeleteBucketLifecycleOutput) GoString() string { return s.String() } -// SetHttpErrorCodeReturnedEquals sets the HttpErrorCodeReturnedEquals field's value. -func (s *Condition) SetHttpErrorCodeReturnedEquals(v string) *Condition { - s.HttpErrorCodeReturnedEquals = &v - return s -} - -// SetKeyPrefixEquals sets the KeyPrefixEquals field's value. -func (s *Condition) SetKeyPrefixEquals(v string) *Condition { - s.KeyPrefixEquals = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectRequest -type CopyObjectInput struct { +type DeleteBucketMetricsConfigurationInput struct { _ struct{} `type:"structure"` - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - + // The name of the bucket containing the metrics configuration to delete. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. + // The ID used to identify the metrics configuration. // - // CopySource is a required field - CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` +} - // Copies the object if its entity tag (ETag) matches the specified tag. - CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` +// String returns the string representation +func (s DeleteBucketMetricsConfigurationInput) String() string { + return awsutil.Prettify(s) +} - // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` +// GoString returns the string representation +func (s DeleteBucketMetricsConfigurationInput) GoString() string { + return s.String() +} - // Copies the object if its entity tag (ETag) is different than the specified - // ETag. - CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketMetricsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketMetricsConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } - // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Specifies the algorithm to use when decrypting the source object (e.g., AES256). - CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketMetricsConfigurationInput) SetBucket(v string) *DeleteBucketMetricsConfigurationInput { + s.Bucket = &v + return s +} - // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt - // the source object. The encryption key provided in this header must be one - // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` +func (s *DeleteBucketMetricsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` +// SetId sets the Id field's value. +func (s *DeleteBucketMetricsConfigurationInput) SetId(v string) *DeleteBucketMetricsConfigurationInput { + s.Id = &v + return s +} - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` +type DeleteBucketMetricsConfigurationOutput struct { + _ struct{} `type:"structure"` +} - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` +// String returns the string representation +func (s DeleteBucketMetricsConfigurationOutput) String() string { + return awsutil.Prettify(s) +} - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` +// GoString returns the string representation +func (s DeleteBucketMetricsConfigurationOutput) GoString() string { + return s.String() +} - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` +type DeleteBucketOutput struct { + _ struct{} `type:"structure"` +} - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` +// String returns the string representation +func (s DeleteBucketOutput) String() string { + return awsutil.Prettify(s) +} - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` +// GoString returns the string representation +func (s DeleteBucketOutput) GoString() string { + return s.String() +} - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` +type DeleteBucketPolicyInput struct { + _ struct{} `type:"structure"` - // Specifies whether the metadata is copied from the source object or replaced - // with metadata provided in the request. - MetadataDirective *string `location:"header" locationName:"x-amz-metadata-directive" type:"string" enum:"MetadataDirective"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +} - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` +// String returns the string representation +func (s DeleteBucketPolicyInput) String() string { + return awsutil.Prettify(s) +} - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` +// GoString returns the string representation +func (s DeleteBucketPolicyInput) GoString() string { + return s.String() +} - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketPolicyInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketPolicyInput) SetBucket(v string) *DeleteBucketPolicyInput { + s.Bucket = &v + return s +} - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` +func (s *DeleteBucketPolicyInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` +type DeleteBucketPolicyOutput struct { + _ struct{} `type:"structure"` +} - // The tag-set for the object destination object this value must be used in - // conjunction with the TaggingDirective. The tag-set must be encoded as URL - // Query parameters - Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` +// String returns the string representation +func (s DeleteBucketPolicyOutput) String() string { + return awsutil.Prettify(s) +} - // Specifies whether the object tag-set are copied from the source object or - // replaced with tag-set provided in the request. - TaggingDirective *string `location:"header" locationName:"x-amz-tagging-directive" type:"string" enum:"TaggingDirective"` +// GoString returns the string representation +func (s DeleteBucketPolicyOutput) GoString() string { + return s.String() +} - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` +type DeleteBucketReplicationInput struct { + _ struct{} `type:"structure"` + + // The bucket name. + // + // It can take a while to propagate the deletion of a replication configuration + // to all Amazon S3 systems. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s CopyObjectInput) String() string { +func (s DeleteBucketReplicationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CopyObjectInput) GoString() string { +func (s DeleteBucketReplicationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CopyObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CopyObjectInput"} +func (s *DeleteBucketReplicationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketReplicationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.CopySource == nil { - invalidParams.Add(request.NewErrParamRequired("CopySource")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -7306,439 +10186,530 @@ func (s *CopyObjectInput) Validate() error { return nil } -// SetACL sets the ACL field's value. -func (s *CopyObjectInput) SetACL(v string) *CopyObjectInput { - s.ACL = &v - return s -} - // SetBucket sets the Bucket field's value. -func (s *CopyObjectInput) SetBucket(v string) *CopyObjectInput { +func (s *DeleteBucketReplicationInput) SetBucket(v string) *DeleteBucketReplicationInput { s.Bucket = &v return s } -// SetCacheControl sets the CacheControl field's value. -func (s *CopyObjectInput) SetCacheControl(v string) *CopyObjectInput { - s.CacheControl = &v - return s +func (s *DeleteBucketReplicationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetContentDisposition sets the ContentDisposition field's value. -func (s *CopyObjectInput) SetContentDisposition(v string) *CopyObjectInput { - s.ContentDisposition = &v - return s +type DeleteBucketReplicationOutput struct { + _ struct{} `type:"structure"` } -// SetContentEncoding sets the ContentEncoding field's value. -func (s *CopyObjectInput) SetContentEncoding(v string) *CopyObjectInput { - s.ContentEncoding = &v - return s +// String returns the string representation +func (s DeleteBucketReplicationOutput) String() string { + return awsutil.Prettify(s) } -// SetContentLanguage sets the ContentLanguage field's value. -func (s *CopyObjectInput) SetContentLanguage(v string) *CopyObjectInput { - s.ContentLanguage = &v - return s +// GoString returns the string representation +func (s DeleteBucketReplicationOutput) GoString() string { + return s.String() } -// SetContentType sets the ContentType field's value. -func (s *CopyObjectInput) SetContentType(v string) *CopyObjectInput { - s.ContentType = &v - return s +type DeleteBucketTaggingInput struct { + _ struct{} `type:"structure"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } -// SetCopySource sets the CopySource field's value. -func (s *CopyObjectInput) SetCopySource(v string) *CopyObjectInput { - s.CopySource = &v - return s +// String returns the string representation +func (s DeleteBucketTaggingInput) String() string { + return awsutil.Prettify(s) } -// SetCopySourceIfMatch sets the CopySourceIfMatch field's value. -func (s *CopyObjectInput) SetCopySourceIfMatch(v string) *CopyObjectInput { - s.CopySourceIfMatch = &v - return s +// GoString returns the string representation +func (s DeleteBucketTaggingInput) GoString() string { + return s.String() } -// SetCopySourceIfModifiedSince sets the CopySourceIfModifiedSince field's value. -func (s *CopyObjectInput) SetCopySourceIfModifiedSince(v time.Time) *CopyObjectInput { - s.CopySourceIfModifiedSince = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketTaggingInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetCopySourceIfNoneMatch sets the CopySourceIfNoneMatch field's value. -func (s *CopyObjectInput) SetCopySourceIfNoneMatch(v string) *CopyObjectInput { - s.CopySourceIfNoneMatch = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketTaggingInput) SetBucket(v string) *DeleteBucketTaggingInput { + s.Bucket = &v return s } -// SetCopySourceIfUnmodifiedSince sets the CopySourceIfUnmodifiedSince field's value. -func (s *CopyObjectInput) SetCopySourceIfUnmodifiedSince(v time.Time) *CopyObjectInput { - s.CopySourceIfUnmodifiedSince = &v - return s +func (s *DeleteBucketTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetCopySourceSSECustomerAlgorithm sets the CopySourceSSECustomerAlgorithm field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerAlgorithm(v string) *CopyObjectInput { - s.CopySourceSSECustomerAlgorithm = &v - return s +type DeleteBucketTaggingOutput struct { + _ struct{} `type:"structure"` } -// SetCopySourceSSECustomerKey sets the CopySourceSSECustomerKey field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerKey(v string) *CopyObjectInput { - s.CopySourceSSECustomerKey = &v - return s +// String returns the string representation +func (s DeleteBucketTaggingOutput) String() string { + return awsutil.Prettify(s) } -// SetCopySourceSSECustomerKeyMD5 sets the CopySourceSSECustomerKeyMD5 field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerKeyMD5(v string) *CopyObjectInput { - s.CopySourceSSECustomerKeyMD5 = &v - return s +// GoString returns the string representation +func (s DeleteBucketTaggingOutput) GoString() string { + return s.String() +} + +type DeleteBucketWebsiteInput struct { + _ struct{} `type:"structure"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteBucketWebsiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteBucketWebsiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBucketWebsiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBucketWebsiteInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetExpires sets the Expires field's value. -func (s *CopyObjectInput) SetExpires(v time.Time) *CopyObjectInput { - s.Expires = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteBucketWebsiteInput) SetBucket(v string) *DeleteBucketWebsiteInput { + s.Bucket = &v return s } -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CopyObjectInput) SetGrantFullControl(v string) *CopyObjectInput { - s.GrantFullControl = &v - return s +func (s *DeleteBucketWebsiteInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetGrantRead sets the GrantRead field's value. -func (s *CopyObjectInput) SetGrantRead(v string) *CopyObjectInput { - s.GrantRead = &v - return s +type DeleteBucketWebsiteOutput struct { + _ struct{} `type:"structure"` } -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CopyObjectInput) SetGrantReadACP(v string) *CopyObjectInput { - s.GrantReadACP = &v - return s +// String returns the string representation +func (s DeleteBucketWebsiteOutput) String() string { + return awsutil.Prettify(s) } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CopyObjectInput) SetGrantWriteACP(v string) *CopyObjectInput { - s.GrantWriteACP = &v - return s +// GoString returns the string representation +func (s DeleteBucketWebsiteOutput) GoString() string { + return s.String() } -// SetKey sets the Key field's value. -func (s *CopyObjectInput) SetKey(v string) *CopyObjectInput { - s.Key = &v - return s -} +type DeleteMarkerEntry struct { + _ struct{} `type:"structure"` -// SetMetadata sets the Metadata field's value. -func (s *CopyObjectInput) SetMetadata(v map[string]*string) *CopyObjectInput { - s.Metadata = v - return s + // Specifies whether the object is (true) or is not (false) the latest version + // of an object. + IsLatest *bool `type:"boolean"` + + // The object key. + Key *string `min:"1" type:"string"` + + // Date and time the object was last modified. + LastModified *time.Time `type:"timestamp"` + + Owner *Owner `type:"structure"` + + // Version ID of an object. + VersionId *string `type:"string"` } -// SetMetadataDirective sets the MetadataDirective field's value. -func (s *CopyObjectInput) SetMetadataDirective(v string) *CopyObjectInput { - s.MetadataDirective = &v - return s +// String returns the string representation +func (s DeleteMarkerEntry) String() string { + return awsutil.Prettify(s) } -// SetRequestPayer sets the RequestPayer field's value. -func (s *CopyObjectInput) SetRequestPayer(v string) *CopyObjectInput { - s.RequestPayer = &v - return s +// GoString returns the string representation +func (s DeleteMarkerEntry) GoString() string { + return s.String() } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CopyObjectInput) SetSSECustomerAlgorithm(v string) *CopyObjectInput { - s.SSECustomerAlgorithm = &v +// SetIsLatest sets the IsLatest field's value. +func (s *DeleteMarkerEntry) SetIsLatest(v bool) *DeleteMarkerEntry { + s.IsLatest = &v return s } -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *CopyObjectInput) SetSSECustomerKey(v string) *CopyObjectInput { - s.SSECustomerKey = &v +// SetKey sets the Key field's value. +func (s *DeleteMarkerEntry) SetKey(v string) *DeleteMarkerEntry { + s.Key = &v return s } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CopyObjectInput) SetSSECustomerKeyMD5(v string) *CopyObjectInput { - s.SSECustomerKeyMD5 = &v +// SetLastModified sets the LastModified field's value. +func (s *DeleteMarkerEntry) SetLastModified(v time.Time) *DeleteMarkerEntry { + s.LastModified = &v return s } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CopyObjectInput) SetSSEKMSKeyId(v string) *CopyObjectInput { - s.SSEKMSKeyId = &v +// SetOwner sets the Owner field's value. +func (s *DeleteMarkerEntry) SetOwner(v *Owner) *DeleteMarkerEntry { + s.Owner = v return s } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CopyObjectInput) SetServerSideEncryption(v string) *CopyObjectInput { - s.ServerSideEncryption = &v +// SetVersionId sets the VersionId field's value. +func (s *DeleteMarkerEntry) SetVersionId(v string) *DeleteMarkerEntry { + s.VersionId = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *CopyObjectInput) SetStorageClass(v string) *CopyObjectInput { - s.StorageClass = &v - return s +// Specifies whether Amazon S3 should replicate delete makers. +type DeleteMarkerReplication struct { + _ struct{} `type:"structure"` + + // The status of the delete marker replication. + // + // In the current implementation, Amazon S3 doesn't replicate the delete markers. + // The status must be Disabled. + Status *string `type:"string" enum:"DeleteMarkerReplicationStatus"` } -// SetTagging sets the Tagging field's value. -func (s *CopyObjectInput) SetTagging(v string) *CopyObjectInput { - s.Tagging = &v - return s +// String returns the string representation +func (s DeleteMarkerReplication) String() string { + return awsutil.Prettify(s) } -// SetTaggingDirective sets the TaggingDirective field's value. -func (s *CopyObjectInput) SetTaggingDirective(v string) *CopyObjectInput { - s.TaggingDirective = &v - return s +// GoString returns the string representation +func (s DeleteMarkerReplication) GoString() string { + return s.String() } -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *CopyObjectInput) SetWebsiteRedirectLocation(v string) *CopyObjectInput { - s.WebsiteRedirectLocation = &v +// SetStatus sets the Status field's value. +func (s *DeleteMarkerReplication) SetStatus(v string) *DeleteMarkerReplication { + s.Status = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectOutput -type CopyObjectOutput struct { - _ struct{} `type:"structure" payload:"CopyObjectResult"` - - CopyObjectResult *CopyObjectResult `type:"structure"` - - CopySourceVersionId *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` - - // If the object expiration is configured, the response includes this header. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` +type DeleteObjectInput struct { + _ struct{} `type:"structure"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + // Indicates whether S3 Object Lock should bypass Governance-mode restrictions + // to process this operation. + BypassGovernanceRetention *bool `location:"header" locationName:"x-amz-bypass-governance-retention" type:"boolean"` - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` + // The concatenation of the authentication device's serial number, a space, + // and the value that is displayed on your authentication device. + MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - // Version ID of the newly created copy. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // VersionId used to reference a specific version of the object. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s CopyObjectOutput) String() string { +func (s DeleteObjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CopyObjectOutput) GoString() string { +func (s DeleteObjectInput) GoString() string { return s.String() } -// SetCopyObjectResult sets the CopyObjectResult field's value. -func (s *CopyObjectOutput) SetCopyObjectResult(v *CopyObjectResult) *CopyObjectOutput { - s.CopyObjectResult = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteObjectInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *DeleteObjectInput) SetBucket(v string) *DeleteObjectInput { + s.Bucket = &v return s } -// SetCopySourceVersionId sets the CopySourceVersionId field's value. -func (s *CopyObjectOutput) SetCopySourceVersionId(v string) *CopyObjectOutput { - s.CopySourceVersionId = &v +func (s *DeleteObjectInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetBypassGovernanceRetention sets the BypassGovernanceRetention field's value. +func (s *DeleteObjectInput) SetBypassGovernanceRetention(v bool) *DeleteObjectInput { + s.BypassGovernanceRetention = &v return s } -// SetExpiration sets the Expiration field's value. -func (s *CopyObjectOutput) SetExpiration(v string) *CopyObjectOutput { - s.Expiration = &v +// SetKey sets the Key field's value. +func (s *DeleteObjectInput) SetKey(v string) *DeleteObjectInput { + s.Key = &v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *CopyObjectOutput) SetRequestCharged(v string) *CopyObjectOutput { - s.RequestCharged = &v +// SetMFA sets the MFA field's value. +func (s *DeleteObjectInput) SetMFA(v string) *DeleteObjectInput { + s.MFA = &v return s } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CopyObjectOutput) SetSSECustomerAlgorithm(v string) *CopyObjectOutput { - s.SSECustomerAlgorithm = &v +// SetRequestPayer sets the RequestPayer field's value. +func (s *DeleteObjectInput) SetRequestPayer(v string) *DeleteObjectInput { + s.RequestPayer = &v return s } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CopyObjectOutput) SetSSECustomerKeyMD5(v string) *CopyObjectOutput { - s.SSECustomerKeyMD5 = &v +// SetVersionId sets the VersionId field's value. +func (s *DeleteObjectInput) SetVersionId(v string) *DeleteObjectInput { + s.VersionId = &v return s } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CopyObjectOutput) SetSSEKMSKeyId(v string) *CopyObjectOutput { - s.SSEKMSKeyId = &v +type DeleteObjectOutput struct { + _ struct{} `type:"structure"` + + // Specifies whether the versioned object that was permanently deleted was (true) + // or was not (false) a delete marker. + DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // Returns the version ID of the delete marker created as a result of the DELETE + // operation. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` +} + +// String returns the string representation +func (s DeleteObjectOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteObjectOutput) GoString() string { + return s.String() +} + +// SetDeleteMarker sets the DeleteMarker field's value. +func (s *DeleteObjectOutput) SetDeleteMarker(v bool) *DeleteObjectOutput { + s.DeleteMarker = &v return s } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CopyObjectOutput) SetServerSideEncryption(v string) *CopyObjectOutput { - s.ServerSideEncryption = &v +// SetRequestCharged sets the RequestCharged field's value. +func (s *DeleteObjectOutput) SetRequestCharged(v string) *DeleteObjectOutput { + s.RequestCharged = &v return s } // SetVersionId sets the VersionId field's value. -func (s *CopyObjectOutput) SetVersionId(v string) *CopyObjectOutput { +func (s *DeleteObjectOutput) SetVersionId(v string) *DeleteObjectOutput { s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectResult -type CopyObjectResult struct { +type DeleteObjectTaggingInput struct { _ struct{} `type:"structure"` - ETag *string `type:"string"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` + // The versionId of the object that the tag-set will be removed from. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s CopyObjectResult) String() string { +func (s DeleteObjectTaggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CopyObjectResult) GoString() string { +func (s DeleteObjectTaggingInput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *CopyObjectResult) SetETag(v string) *CopyObjectResult { - s.ETag = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *CopyObjectResult) SetLastModified(v time.Time) *CopyObjectResult { - s.LastModified = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyPartResult -type CopyPartResult struct { - _ struct{} `type:"structure"` - - // Entity tag of the object. - ETag *string `type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteObjectTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteObjectTaggingInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } - // Date and time at which the object was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// String returns the string representation -func (s CopyPartResult) String() string { - return awsutil.Prettify(s) +// SetBucket sets the Bucket field's value. +func (s *DeleteObjectTaggingInput) SetBucket(v string) *DeleteObjectTaggingInput { + s.Bucket = &v + return s } -// GoString returns the string representation -func (s CopyPartResult) GoString() string { - return s.String() +func (s *DeleteObjectTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetETag sets the ETag field's value. -func (s *CopyPartResult) SetETag(v string) *CopyPartResult { - s.ETag = &v +// SetKey sets the Key field's value. +func (s *DeleteObjectTaggingInput) SetKey(v string) *DeleteObjectTaggingInput { + s.Key = &v return s } -// SetLastModified sets the LastModified field's value. -func (s *CopyPartResult) SetLastModified(v time.Time) *CopyPartResult { - s.LastModified = &v +// SetVersionId sets the VersionId field's value. +func (s *DeleteObjectTaggingInput) SetVersionId(v string) *DeleteObjectTaggingInput { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketConfiguration -type CreateBucketConfiguration struct { +type DeleteObjectTaggingOutput struct { _ struct{} `type:"structure"` - // Specifies the region where the bucket will be created. If you don't specify - // a region, the bucket will be created in US Standard. - LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` + // The versionId of the object the tag-set was removed from. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` } // String returns the string representation -func (s CreateBucketConfiguration) String() string { +func (s DeleteObjectTaggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateBucketConfiguration) GoString() string { +func (s DeleteObjectTaggingOutput) GoString() string { return s.String() } -// SetLocationConstraint sets the LocationConstraint field's value. -func (s *CreateBucketConfiguration) SetLocationConstraint(v string) *CreateBucketConfiguration { - s.LocationConstraint = &v +// SetVersionId sets the VersionId field's value. +func (s *DeleteObjectTaggingOutput) SetVersionId(v string) *DeleteObjectTaggingOutput { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketRequest -type CreateBucketInput struct { - _ struct{} `type:"structure" payload:"CreateBucketConfiguration"` - - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` +type DeleteObjectsInput struct { + _ struct{} `type:"structure" payload:"Delete"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - CreateBucketConfiguration *CreateBucketConfiguration `locationName:"CreateBucketConfiguration" type:"structure"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + // Specifies whether you want to delete this object even if it has a Governance-type + // Object Lock in place. You must have sufficient permissions to perform this + // operation. + BypassGovernanceRetention *bool `location:"header" locationName:"x-amz-bypass-governance-retention" type:"boolean"` - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + // Delete is a required field + Delete *Delete `locationName:"Delete" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` + // The concatenation of the authentication device's serial number, a space, + // and the value that is displayed on your authentication device. + MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` } // String returns the string representation -func (s CreateBucketInput) String() string { +func (s DeleteObjectsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateBucketInput) GoString() string { +func (s DeleteObjectsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateBucketInput"} +func (s *DeleteObjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteObjectsInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Delete == nil { + invalidParams.Add(request.NewErrParamRequired("Delete")) + } + if s.Delete != nil { + if err := s.Delete.Validate(); err != nil { + invalidParams.AddNested("Delete", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -7746,186 +10717,251 @@ func (s *CreateBucketInput) Validate() error { return nil } -// SetACL sets the ACL field's value. -func (s *CreateBucketInput) SetACL(v string) *CreateBucketInput { - s.ACL = &v +// SetBucket sets the Bucket field's value. +func (s *DeleteObjectsInput) SetBucket(v string) *DeleteObjectsInput { + s.Bucket = &v return s } -// SetBucket sets the Bucket field's value. -func (s *CreateBucketInput) SetBucket(v string) *CreateBucketInput { - s.Bucket = &v +func (s *DeleteObjectsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetBypassGovernanceRetention sets the BypassGovernanceRetention field's value. +func (s *DeleteObjectsInput) SetBypassGovernanceRetention(v bool) *DeleteObjectsInput { + s.BypassGovernanceRetention = &v return s } -// SetCreateBucketConfiguration sets the CreateBucketConfiguration field's value. -func (s *CreateBucketInput) SetCreateBucketConfiguration(v *CreateBucketConfiguration) *CreateBucketInput { - s.CreateBucketConfiguration = v +// SetDelete sets the Delete field's value. +func (s *DeleteObjectsInput) SetDelete(v *Delete) *DeleteObjectsInput { + s.Delete = v return s } -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CreateBucketInput) SetGrantFullControl(v string) *CreateBucketInput { - s.GrantFullControl = &v +// SetMFA sets the MFA field's value. +func (s *DeleteObjectsInput) SetMFA(v string) *DeleteObjectsInput { + s.MFA = &v return s } -// SetGrantRead sets the GrantRead field's value. -func (s *CreateBucketInput) SetGrantRead(v string) *CreateBucketInput { - s.GrantRead = &v +// SetRequestPayer sets the RequestPayer field's value. +func (s *DeleteObjectsInput) SetRequestPayer(v string) *DeleteObjectsInput { + s.RequestPayer = &v return s } -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CreateBucketInput) SetGrantReadACP(v string) *CreateBucketInput { - s.GrantReadACP = &v +type DeleteObjectsOutput struct { + _ struct{} `type:"structure"` + + Deleted []*DeletedObject `type:"list" flattened:"true"` + + Errors []*Error `locationName:"Error" type:"list" flattened:"true"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` +} + +// String returns the string representation +func (s DeleteObjectsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteObjectsOutput) GoString() string { + return s.String() +} + +// SetDeleted sets the Deleted field's value. +func (s *DeleteObjectsOutput) SetDeleted(v []*DeletedObject) *DeleteObjectsOutput { + s.Deleted = v return s } -// SetGrantWrite sets the GrantWrite field's value. -func (s *CreateBucketInput) SetGrantWrite(v string) *CreateBucketInput { - s.GrantWrite = &v +// SetErrors sets the Errors field's value. +func (s *DeleteObjectsOutput) SetErrors(v []*Error) *DeleteObjectsOutput { + s.Errors = v return s } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CreateBucketInput) SetGrantWriteACP(v string) *CreateBucketInput { - s.GrantWriteACP = &v +// SetRequestCharged sets the RequestCharged field's value. +func (s *DeleteObjectsOutput) SetRequestCharged(v string) *DeleteObjectsOutput { + s.RequestCharged = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketOutput -type CreateBucketOutput struct { +type DeletePublicAccessBlockInput struct { _ struct{} `type:"structure"` - Location *string `location:"header" locationName:"Location" type:"string"` + // The Amazon S3 bucket whose PublicAccessBlock configuration you want to delete. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeletePublicAccessBlockInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeletePublicAccessBlockInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeletePublicAccessBlockInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeletePublicAccessBlockInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *DeletePublicAccessBlockInput) SetBucket(v string) *DeletePublicAccessBlockInput { + s.Bucket = &v + return s +} + +func (s *DeletePublicAccessBlockInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type DeletePublicAccessBlockOutput struct { + _ struct{} `type:"structure"` } // String returns the string representation -func (s CreateBucketOutput) String() string { +func (s DeletePublicAccessBlockOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateBucketOutput) GoString() string { +func (s DeletePublicAccessBlockOutput) GoString() string { return s.String() } -// SetLocation sets the Location field's value. -func (s *CreateBucketOutput) SetLocation(v string) *CreateBucketOutput { - s.Location = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadRequest -type CreateMultipartUploadInput struct { +type DeletedObject struct { _ struct{} `type:"structure"` - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + DeleteMarker *bool `type:"boolean"` - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` + DeleteMarkerVersionId *string `type:"string"` - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + Key *string `min:"1" type:"string"` - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + VersionId *string `type:"string"` +} - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` +// String returns the string representation +func (s DeletedObject) String() string { + return awsutil.Prettify(s) +} - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` +// GoString returns the string representation +func (s DeletedObject) GoString() string { + return s.String() +} - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` +// SetDeleteMarker sets the DeleteMarker field's value. +func (s *DeletedObject) SetDeleteMarker(v bool) *DeletedObject { + s.DeleteMarker = &v + return s +} - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` +// SetDeleteMarkerVersionId sets the DeleteMarkerVersionId field's value. +func (s *DeletedObject) SetDeleteMarkerVersionId(v string) *DeletedObject { + s.DeleteMarkerVersionId = &v + return s +} - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` +// SetKey sets the Key field's value. +func (s *DeletedObject) SetKey(v string) *DeletedObject { + s.Key = &v + return s +} - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` +// SetVersionId sets the VersionId field's value. +func (s *DeletedObject) SetVersionId(v string) *DeletedObject { + s.VersionId = &v + return s +} - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` +// A container for information about the replication destination. +type Destination struct { + _ struct{} `type:"structure"` - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // A container for information about access control for replicas. + // + // Use this element only in a cross-account scenario where source and destination + // bucket owners are not the same to change replica ownership to the AWS account + // that owns the destination bucket. If you don't add this element to the replication + // configuration, the replicas are owned by same AWS account that owns the source + // object. + AccessControlTranslation *AccessControlTranslation `type:"structure"` - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` + // The account ID of the destination bucket. Currently, Amazon S3 verifies this + // value only if Access Control Translation is enabled. + // + // In a cross-account scenario, if you change replica ownership to the AWS account + // that owns the destination bucket by adding the AccessControlTranslation element, + // this is the account ID of the owner of the destination bucket. + Account *string `type:"string"` - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + // The Amazon Resource Name (ARN) of the bucket where you want Amazon S3 to + // store replicas of the object identified by the rule. + // + // If there are multiple rules in your replication configuration, all rules + // must specify the same bucket as the destination. A replication configuration + // can replicate objects to only one destination bucket. + // + // Bucket is a required field + Bucket *string `type:"string" required:"true"` - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + // A container that provides information about encryption. If SourceSelectionCriteria + // is specified, you must specify this element. + EncryptionConfiguration *EncryptionConfiguration `type:"structure"` - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` + // The class of storage used to store the object. By default Amazon S3 uses + // storage class of the source object when creating a replica. + StorageClass *string `type:"string" enum:"StorageClass"` } // String returns the string representation -func (s CreateMultipartUploadInput) String() string { +func (s Destination) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateMultipartUploadInput) GoString() string { +func (s Destination) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateMultipartUploadInput"} +func (s *Destination) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Destination"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.AccessControlTranslation != nil { + if err := s.AccessControlTranslation.Validate(); err != nil { + invalidParams.AddNested("AccessControlTranslation", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7934,288 +10970,376 @@ func (s *CreateMultipartUploadInput) Validate() error { return nil } -// SetACL sets the ACL field's value. -func (s *CreateMultipartUploadInput) SetACL(v string) *CreateMultipartUploadInput { - s.ACL = &v +// SetAccessControlTranslation sets the AccessControlTranslation field's value. +func (s *Destination) SetAccessControlTranslation(v *AccessControlTranslation) *Destination { + s.AccessControlTranslation = v + return s +} + +// SetAccount sets the Account field's value. +func (s *Destination) SetAccount(v string) *Destination { + s.Account = &v return s } // SetBucket sets the Bucket field's value. -func (s *CreateMultipartUploadInput) SetBucket(v string) *CreateMultipartUploadInput { +func (s *Destination) SetBucket(v string) *Destination { s.Bucket = &v return s } -// SetCacheControl sets the CacheControl field's value. -func (s *CreateMultipartUploadInput) SetCacheControl(v string) *CreateMultipartUploadInput { - s.CacheControl = &v - return s +func (s *Destination) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetContentDisposition sets the ContentDisposition field's value. -func (s *CreateMultipartUploadInput) SetContentDisposition(v string) *CreateMultipartUploadInput { - s.ContentDisposition = &v +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *Destination) SetEncryptionConfiguration(v *EncryptionConfiguration) *Destination { + s.EncryptionConfiguration = v return s } -// SetContentEncoding sets the ContentEncoding field's value. -func (s *CreateMultipartUploadInput) SetContentEncoding(v string) *CreateMultipartUploadInput { - s.ContentEncoding = &v +// SetStorageClass sets the StorageClass field's value. +func (s *Destination) SetStorageClass(v string) *Destination { + s.StorageClass = &v return s } -// SetContentLanguage sets the ContentLanguage field's value. -func (s *CreateMultipartUploadInput) SetContentLanguage(v string) *CreateMultipartUploadInput { - s.ContentLanguage = &v - return s +// Describes the server-side encryption that will be applied to the restore +// results. +type Encryption struct { + _ struct{} `type:"structure"` + + // The server-side encryption algorithm used when storing job results in Amazon + // S3 (e.g., AES256, aws:kms). + // + // EncryptionType is a required field + EncryptionType *string `type:"string" required:"true" enum:"ServerSideEncryption"` + + // If the encryption type is aws:kms, this optional value can be used to specify + // the encryption context for the restore results. + KMSContext *string `type:"string"` + + // If the encryption type is aws:kms, this optional value specifies the AWS + // KMS key ID to use for encryption of job results. + KMSKeyId *string `type:"string" sensitive:"true"` } -// SetContentType sets the ContentType field's value. -func (s *CreateMultipartUploadInput) SetContentType(v string) *CreateMultipartUploadInput { - s.ContentType = &v - return s +// String returns the string representation +func (s Encryption) String() string { + return awsutil.Prettify(s) } -// SetExpires sets the Expires field's value. -func (s *CreateMultipartUploadInput) SetExpires(v time.Time) *CreateMultipartUploadInput { - s.Expires = &v - return s +// GoString returns the string representation +func (s Encryption) GoString() string { + return s.String() } -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CreateMultipartUploadInput) SetGrantFullControl(v string) *CreateMultipartUploadInput { - s.GrantFullControl = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *Encryption) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Encryption"} + if s.EncryptionType == nil { + invalidParams.Add(request.NewErrParamRequired("EncryptionType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetGrantRead sets the GrantRead field's value. -func (s *CreateMultipartUploadInput) SetGrantRead(v string) *CreateMultipartUploadInput { - s.GrantRead = &v +// SetEncryptionType sets the EncryptionType field's value. +func (s *Encryption) SetEncryptionType(v string) *Encryption { + s.EncryptionType = &v return s } -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CreateMultipartUploadInput) SetGrantReadACP(v string) *CreateMultipartUploadInput { - s.GrantReadACP = &v +// SetKMSContext sets the KMSContext field's value. +func (s *Encryption) SetKMSContext(v string) *Encryption { + s.KMSContext = &v return s } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CreateMultipartUploadInput) SetGrantWriteACP(v string) *CreateMultipartUploadInput { - s.GrantWriteACP = &v +// SetKMSKeyId sets the KMSKeyId field's value. +func (s *Encryption) SetKMSKeyId(v string) *Encryption { + s.KMSKeyId = &v return s } -// SetKey sets the Key field's value. -func (s *CreateMultipartUploadInput) SetKey(v string) *CreateMultipartUploadInput { - s.Key = &v - return s +// A container for information about the encryption-based configuration for +// replicas. +type EncryptionConfiguration struct { + _ struct{} `type:"structure"` + + // The ID of the AWS KMS key for the AWS Region where the destination bucket + // resides. Amazon S3 uses this key to encrypt the replica object. + ReplicaKmsKeyID *string `type:"string"` } -// SetMetadata sets the Metadata field's value. -func (s *CreateMultipartUploadInput) SetMetadata(v map[string]*string) *CreateMultipartUploadInput { - s.Metadata = v - return s +// String returns the string representation +func (s EncryptionConfiguration) String() string { + return awsutil.Prettify(s) } -// SetRequestPayer sets the RequestPayer field's value. -func (s *CreateMultipartUploadInput) SetRequestPayer(v string) *CreateMultipartUploadInput { - s.RequestPayer = &v - return s +// GoString returns the string representation +func (s EncryptionConfiguration) GoString() string { + return s.String() } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadInput { - s.SSECustomerAlgorithm = &v +// SetReplicaKmsKeyID sets the ReplicaKmsKeyID field's value. +func (s *EncryptionConfiguration) SetReplicaKmsKeyID(v string) *EncryptionConfiguration { + s.ReplicaKmsKeyID = &v return s } -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerKey(v string) *CreateMultipartUploadInput { - s.SSECustomerKey = &v - return s +type EndEvent struct { + _ struct{} `locationName:"EndEvent" type:"structure"` } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadInput { - s.SSECustomerKeyMD5 = &v - return s +// String returns the string representation +func (s EndEvent) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EndEvent) GoString() string { + return s.String() +} + +// The EndEvent is and event in the SelectObjectContentEventStream group of events. +func (s *EndEvent) eventSelectObjectContentEventStream() {} + +// UnmarshalEvent unmarshals the EventStream Message into the EndEvent value. +// This method is only used internally within the SDK's EventStream handling. +func (s *EndEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + return nil +} + +type Error struct { + _ struct{} `type:"structure"` + + Code *string `type:"string"` + + Key *string `min:"1" type:"string"` + + Message *string `type:"string"` + + VersionId *string `type:"string"` +} + +// String returns the string representation +func (s Error) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Error) GoString() string { + return s.String() } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CreateMultipartUploadInput) SetSSEKMSKeyId(v string) *CreateMultipartUploadInput { - s.SSEKMSKeyId = &v +// SetCode sets the Code field's value. +func (s *Error) SetCode(v string) *Error { + s.Code = &v return s } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CreateMultipartUploadInput) SetServerSideEncryption(v string) *CreateMultipartUploadInput { - s.ServerSideEncryption = &v +// SetKey sets the Key field's value. +func (s *Error) SetKey(v string) *Error { + s.Key = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *CreateMultipartUploadInput) SetStorageClass(v string) *CreateMultipartUploadInput { - s.StorageClass = &v +// SetMessage sets the Message field's value. +func (s *Error) SetMessage(v string) *Error { + s.Message = &v return s } -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *CreateMultipartUploadInput) SetWebsiteRedirectLocation(v string) *CreateMultipartUploadInput { - s.WebsiteRedirectLocation = &v +// SetVersionId sets the VersionId field's value. +func (s *Error) SetVersionId(v string) *Error { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadOutput -type CreateMultipartUploadOutput struct { +type ErrorDocument struct { _ struct{} `type:"structure"` - // Date when multipart upload will become eligible for abort operation by lifecycle. - AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp" timestampFormat:"rfc822"` - - // Id of the lifecycle rule that makes a multipart upload eligible for abort - // operation. - AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` + // The object key name to use when a 4XX class error occurs. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` +} - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `locationName:"Bucket" type:"string"` +// String returns the string representation +func (s ErrorDocument) String() string { + return awsutil.Prettify(s) +} - // Object key for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` +// GoString returns the string representation +func (s ErrorDocument) GoString() string { + return s.String() +} - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *ErrorDocument) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ErrorDocument"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` +// SetKey sets the Key field's value. +func (s *ErrorDocument) SetKey(v string) *ErrorDocument { + s.Key = &v + return s +} - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` +// A container for a key value pair that defines the criteria for the filter +// rule. +type FilterRule struct { + _ struct{} `type:"structure"` - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + // The object key name prefix or suffix identifying one or more objects to which + // the filtering rule applies. The maximum prefix length is 1,024 characters. + // Overlapping prefixes and suffixes are not supported. For more information, + // see Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Name *string `type:"string" enum:"FilterRuleName"` - // ID for the initiated multipart upload. - UploadId *string `type:"string"` + Value *string `type:"string"` } // String returns the string representation -func (s CreateMultipartUploadOutput) String() string { +func (s FilterRule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateMultipartUploadOutput) GoString() string { +func (s FilterRule) GoString() string { return s.String() } -// SetAbortDate sets the AbortDate field's value. -func (s *CreateMultipartUploadOutput) SetAbortDate(v time.Time) *CreateMultipartUploadOutput { - s.AbortDate = &v +// SetName sets the Name field's value. +func (s *FilterRule) SetName(v string) *FilterRule { + s.Name = &v return s } -// SetAbortRuleId sets the AbortRuleId field's value. -func (s *CreateMultipartUploadOutput) SetAbortRuleId(v string) *CreateMultipartUploadOutput { - s.AbortRuleId = &v +// SetValue sets the Value field's value. +func (s *FilterRule) SetValue(v string) *FilterRule { + s.Value = &v return s } -// SetBucket sets the Bucket field's value. -func (s *CreateMultipartUploadOutput) SetBucket(v string) *CreateMultipartUploadOutput { - s.Bucket = &v - return s +type GetBucketAccelerateConfigurationInput struct { + _ struct{} `type:"structure"` + + // Name of the bucket for which the accelerate configuration is retrieved. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } -// SetKey sets the Key field's value. -func (s *CreateMultipartUploadOutput) SetKey(v string) *CreateMultipartUploadOutput { - s.Key = &v - return s +// String returns the string representation +func (s GetBucketAccelerateConfigurationInput) String() string { + return awsutil.Prettify(s) } -// SetRequestCharged sets the RequestCharged field's value. -func (s *CreateMultipartUploadOutput) SetRequestCharged(v string) *CreateMultipartUploadOutput { - s.RequestCharged = &v - return s +// GoString returns the string representation +func (s GetBucketAccelerateConfigurationInput) GoString() string { + return s.String() } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CreateMultipartUploadOutput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadOutput { - s.SSECustomerAlgorithm = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetBucketAccelerateConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketAccelerateConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CreateMultipartUploadOutput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadOutput { - s.SSECustomerKeyMD5 = &v +// SetBucket sets the Bucket field's value. +func (s *GetBucketAccelerateConfigurationInput) SetBucket(v string) *GetBucketAccelerateConfigurationInput { + s.Bucket = &v return s } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CreateMultipartUploadOutput) SetSSEKMSKeyId(v string) *CreateMultipartUploadOutput { - s.SSEKMSKeyId = &v - return s +func (s *GetBucketAccelerateConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CreateMultipartUploadOutput) SetServerSideEncryption(v string) *CreateMultipartUploadOutput { - s.ServerSideEncryption = &v - return s +type GetBucketAccelerateConfigurationOutput struct { + _ struct{} `type:"structure"` + + // The accelerate configuration of the bucket. + Status *string `type:"string" enum:"BucketAccelerateStatus"` } -// SetUploadId sets the UploadId field's value. -func (s *CreateMultipartUploadOutput) SetUploadId(v string) *CreateMultipartUploadOutput { - s.UploadId = &v +// String returns the string representation +func (s GetBucketAccelerateConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketAccelerateConfigurationOutput) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *GetBucketAccelerateConfigurationOutput) SetStatus(v string) *GetBucketAccelerateConfigurationOutput { + s.Status = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Delete -type Delete struct { +type GetBucketAclInput struct { _ struct{} `type:"structure"` - // Objects is a required field - Objects []*ObjectIdentifier `locationName:"Object" type:"list" flattened:"true" required:"true"` - - // Element to enable quiet mode for the request. When you add this element, - // you must set its value to true. - Quiet *bool `type:"boolean"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s Delete) String() string { +func (s GetBucketAclInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Delete) GoString() string { +func (s GetBucketAclInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Delete) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Delete"} - if s.Objects == nil { - invalidParams.Add(request.NewErrParamRequired("Objects")) +func (s *GetBucketAclInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketAclInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Objects != nil { - for i, v := range s.Objects { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Objects", i), err.(request.ErrInvalidParams)) - } - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -8224,23 +11348,54 @@ func (s *Delete) Validate() error { return nil } -// SetObjects sets the Objects field's value. -func (s *Delete) SetObjects(v []*ObjectIdentifier) *Delete { - s.Objects = v +// SetBucket sets the Bucket field's value. +func (s *GetBucketAclInput) SetBucket(v string) *GetBucketAclInput { + s.Bucket = &v return s } -// SetQuiet sets the Quiet field's value. -func (s *Delete) SetQuiet(v bool) *Delete { - s.Quiet = &v +func (s *GetBucketAclInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketAclOutput struct { + _ struct{} `type:"structure"` + + // A list of grants. + Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` + + Owner *Owner `type:"structure"` +} + +// String returns the string representation +func (s GetBucketAclOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketAclOutput) GoString() string { + return s.String() +} + +// SetGrants sets the Grants field's value. +func (s *GetBucketAclOutput) SetGrants(v []*Grant) *GetBucketAclOutput { + s.Grants = v + return s +} + +// SetOwner sets the Owner field's value. +func (s *GetBucketAclOutput) SetOwner(v *Owner) *GetBucketAclOutput { + s.Owner = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationRequest -type DeleteBucketAnalyticsConfigurationInput struct { +type GetBucketAnalyticsConfigurationInput struct { _ struct{} `type:"structure"` - // The name of the bucket from which an analytics configuration is deleted. + // The name of the bucket from which an analytics configuration is retrieved. // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -8252,21 +11407,24 @@ type DeleteBucketAnalyticsConfigurationInput struct { } // String returns the string representation -func (s DeleteBucketAnalyticsConfigurationInput) String() string { +func (s GetBucketAnalyticsConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketAnalyticsConfigurationInput) GoString() string { +func (s GetBucketAnalyticsConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketAnalyticsConfigurationInput"} +func (s *GetBucketAnalyticsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketAnalyticsConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -8278,34 +11436,48 @@ func (s *DeleteBucketAnalyticsConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketAnalyticsConfigurationInput) SetBucket(v string) *DeleteBucketAnalyticsConfigurationInput { +func (s *GetBucketAnalyticsConfigurationInput) SetBucket(v string) *GetBucketAnalyticsConfigurationInput { s.Bucket = &v return s } +func (s *GetBucketAnalyticsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetId sets the Id field's value. -func (s *DeleteBucketAnalyticsConfigurationInput) SetId(v string) *DeleteBucketAnalyticsConfigurationInput { +func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput { s.Id = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationOutput -type DeleteBucketAnalyticsConfigurationOutput struct { - _ struct{} `type:"structure"` +type GetBucketAnalyticsConfigurationOutput struct { + _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` + + // The configuration and any analyses for the analytics filter. + AnalyticsConfiguration *AnalyticsConfiguration `type:"structure"` } // String returns the string representation -func (s DeleteBucketAnalyticsConfigurationOutput) String() string { +func (s GetBucketAnalyticsConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketAnalyticsConfigurationOutput) GoString() string { +func (s GetBucketAnalyticsConfigurationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsRequest -type DeleteBucketCorsInput struct { +// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. +func (s *GetBucketAnalyticsConfigurationOutput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *GetBucketAnalyticsConfigurationOutput { + s.AnalyticsConfiguration = v + return s +} + +type GetBucketCorsInput struct { _ struct{} `type:"structure"` // Bucket is a required field @@ -8313,21 +11485,24 @@ type DeleteBucketCorsInput struct { } // String returns the string representation -func (s DeleteBucketCorsInput) String() string { +func (s GetBucketCorsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketCorsInput) GoString() string { +func (s GetBucketCorsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketCorsInput"} +func (s *GetBucketCorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketCorsInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8336,50 +11511,69 @@ func (s *DeleteBucketCorsInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketCorsInput) SetBucket(v string) *DeleteBucketCorsInput { +func (s *GetBucketCorsInput) SetBucket(v string) *GetBucketCorsInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsOutput -type DeleteBucketCorsOutput struct { +func (s *GetBucketCorsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketCorsOutput struct { _ struct{} `type:"structure"` + + CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` } // String returns the string representation -func (s DeleteBucketCorsOutput) String() string { +func (s GetBucketCorsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketCorsOutput) GoString() string { +func (s GetBucketCorsOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketRequest -type DeleteBucketInput struct { +// SetCORSRules sets the CORSRules field's value. +func (s *GetBucketCorsOutput) SetCORSRules(v []*CORSRule) *GetBucketCorsOutput { + s.CORSRules = v + return s +} + +type GetBucketEncryptionInput struct { _ struct{} `type:"structure"` + // The name of the bucket from which the server-side encryption configuration + // is retrieved. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s DeleteBucketInput) String() string { +func (s GetBucketEncryptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketInput) GoString() string { +func (s GetBucketEncryptionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInput"} +func (s *GetBucketEncryptionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketEncryptionInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8388,16 +11582,46 @@ func (s *DeleteBucketInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketInput) SetBucket(v string) *DeleteBucketInput { +func (s *GetBucketEncryptionInput) SetBucket(v string) *GetBucketEncryptionInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationRequest -type DeleteBucketInventoryConfigurationInput struct { +func (s *GetBucketEncryptionInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketEncryptionOutput struct { + _ struct{} `type:"structure" payload:"ServerSideEncryptionConfiguration"` + + // Container for server-side encryption configuration rules. Currently S3 supports + // one rule only. + ServerSideEncryptionConfiguration *ServerSideEncryptionConfiguration `type:"structure"` +} + +// String returns the string representation +func (s GetBucketEncryptionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketEncryptionOutput) GoString() string { + return s.String() +} + +// SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value. +func (s *GetBucketEncryptionOutput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *GetBucketEncryptionOutput { + s.ServerSideEncryptionConfiguration = v + return s +} + +type GetBucketInventoryConfigurationInput struct { _ struct{} `type:"structure"` - // The name of the bucket containing the inventory configuration to delete. + // The name of the bucket containing the inventory configuration to retrieve. // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -8409,21 +11633,24 @@ type DeleteBucketInventoryConfigurationInput struct { } // String returns the string representation -func (s DeleteBucketInventoryConfigurationInput) String() string { +func (s GetBucketInventoryConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketInventoryConfigurationInput) GoString() string { +func (s GetBucketInventoryConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInventoryConfigurationInput"} +func (s *GetBucketInventoryConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketInventoryConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -8435,34 +11662,48 @@ func (s *DeleteBucketInventoryConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketInventoryConfigurationInput) SetBucket(v string) *DeleteBucketInventoryConfigurationInput { +func (s *GetBucketInventoryConfigurationInput) SetBucket(v string) *GetBucketInventoryConfigurationInput { s.Bucket = &v return s } +func (s *GetBucketInventoryConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetId sets the Id field's value. -func (s *DeleteBucketInventoryConfigurationInput) SetId(v string) *DeleteBucketInventoryConfigurationInput { +func (s *GetBucketInventoryConfigurationInput) SetId(v string) *GetBucketInventoryConfigurationInput { s.Id = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationOutput -type DeleteBucketInventoryConfigurationOutput struct { - _ struct{} `type:"structure"` +type GetBucketInventoryConfigurationOutput struct { + _ struct{} `type:"structure" payload:"InventoryConfiguration"` + + // Specifies the inventory configuration. + InventoryConfiguration *InventoryConfiguration `type:"structure"` } // String returns the string representation -func (s DeleteBucketInventoryConfigurationOutput) String() string { +func (s GetBucketInventoryConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketInventoryConfigurationOutput) GoString() string { +func (s GetBucketInventoryConfigurationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleRequest -type DeleteBucketLifecycleInput struct { +// SetInventoryConfiguration sets the InventoryConfiguration field's value. +func (s *GetBucketInventoryConfigurationOutput) SetInventoryConfiguration(v *InventoryConfiguration) *GetBucketInventoryConfigurationOutput { + s.InventoryConfiguration = v + return s +} + +type GetBucketLifecycleConfigurationInput struct { _ struct{} `type:"structure"` // Bucket is a required field @@ -8470,21 +11711,24 @@ type DeleteBucketLifecycleInput struct { } // String returns the string representation -func (s DeleteBucketLifecycleInput) String() string { +func (s GetBucketLifecycleConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketLifecycleInput) GoString() string { +func (s GetBucketLifecycleConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketLifecycleInput"} +func (s *GetBucketLifecycleConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8493,59 +11737,65 @@ func (s *DeleteBucketLifecycleInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketLifecycleInput) SetBucket(v string) *DeleteBucketLifecycleInput { +func (s *GetBucketLifecycleConfigurationInput) SetBucket(v string) *GetBucketLifecycleConfigurationInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleOutput -type DeleteBucketLifecycleOutput struct { +func (s *GetBucketLifecycleConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketLifecycleConfigurationOutput struct { _ struct{} `type:"structure"` + + Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` } // String returns the string representation -func (s DeleteBucketLifecycleOutput) String() string { +func (s GetBucketLifecycleConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketLifecycleOutput) GoString() string { +func (s GetBucketLifecycleConfigurationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationRequest -type DeleteBucketMetricsConfigurationInput struct { +// SetRules sets the Rules field's value. +func (s *GetBucketLifecycleConfigurationOutput) SetRules(v []*LifecycleRule) *GetBucketLifecycleConfigurationOutput { + s.Rules = v + return s +} + +type GetBucketLifecycleInput struct { _ struct{} `type:"structure"` - // The name of the bucket containing the metrics configuration to delete. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` } // String returns the string representation -func (s DeleteBucketMetricsConfigurationInput) String() string { +func (s GetBucketLifecycleInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketMetricsConfigurationInput) GoString() string { +func (s GetBucketLifecycleInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketMetricsConfigurationInput"} +func (s *GetBucketLifecycleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -8555,49 +11805,109 @@ func (s *DeleteBucketMetricsConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketMetricsConfigurationInput) SetBucket(v string) *DeleteBucketMetricsConfigurationInput { +func (s *GetBucketLifecycleInput) SetBucket(v string) *GetBucketLifecycleInput { s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *DeleteBucketMetricsConfigurationInput) SetId(v string) *DeleteBucketMetricsConfigurationInput { - s.Id = &v +func (s *GetBucketLifecycleInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketLifecycleOutput struct { + _ struct{} `type:"structure"` + + Rules []*Rule `locationName:"Rule" type:"list" flattened:"true"` +} + +// String returns the string representation +func (s GetBucketLifecycleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketLifecycleOutput) GoString() string { + return s.String() +} + +// SetRules sets the Rules field's value. +func (s *GetBucketLifecycleOutput) SetRules(v []*Rule) *GetBucketLifecycleOutput { + s.Rules = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationOutput -type DeleteBucketMetricsConfigurationOutput struct { +type GetBucketLocationInput struct { _ struct{} `type:"structure"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s DeleteBucketMetricsConfigurationOutput) String() string { +func (s GetBucketLocationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketMetricsConfigurationOutput) GoString() string { +func (s GetBucketLocationInput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketOutput -type DeleteBucketOutput struct { +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetBucketLocationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketLocationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *GetBucketLocationInput) SetBucket(v string) *GetBucketLocationInput { + s.Bucket = &v + return s +} + +func (s *GetBucketLocationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketLocationOutput struct { _ struct{} `type:"structure"` + + LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` } // String returns the string representation -func (s DeleteBucketOutput) String() string { +func (s GetBucketLocationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketOutput) GoString() string { +func (s GetBucketLocationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyRequest -type DeleteBucketPolicyInput struct { +// SetLocationConstraint sets the LocationConstraint field's value. +func (s *GetBucketLocationOutput) SetLocationConstraint(v string) *GetBucketLocationOutput { + s.LocationConstraint = &v + return s +} + +type GetBucketLoggingInput struct { _ struct{} `type:"structure"` // Bucket is a required field @@ -8605,21 +11915,24 @@ type DeleteBucketPolicyInput struct { } // String returns the string representation -func (s DeleteBucketPolicyInput) String() string { +func (s GetBucketLoggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketPolicyInput) GoString() string { +func (s GetBucketLoggingInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketPolicyInput"} +func (s *GetBucketLoggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketLoggingInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8628,50 +11941,79 @@ func (s *DeleteBucketPolicyInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketPolicyInput) SetBucket(v string) *DeleteBucketPolicyInput { +func (s *GetBucketLoggingInput) SetBucket(v string) *GetBucketLoggingInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyOutput -type DeleteBucketPolicyOutput struct { +func (s *GetBucketLoggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketLoggingOutput struct { _ struct{} `type:"structure"` + + // Container for logging information. Presence of this element indicates that + // logging is enabled. Parameters TargetBucket and TargetPrefix are required + // in this case. + LoggingEnabled *LoggingEnabled `type:"structure"` } // String returns the string representation -func (s DeleteBucketPolicyOutput) String() string { +func (s GetBucketLoggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketPolicyOutput) GoString() string { +func (s GetBucketLoggingOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationRequest -type DeleteBucketReplicationInput struct { +// SetLoggingEnabled sets the LoggingEnabled field's value. +func (s *GetBucketLoggingOutput) SetLoggingEnabled(v *LoggingEnabled) *GetBucketLoggingOutput { + s.LoggingEnabled = v + return s +} + +type GetBucketMetricsConfigurationInput struct { _ struct{} `type:"structure"` + // The name of the bucket containing the metrics configuration to retrieve. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The ID used to identify the metrics configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` } // String returns the string representation -func (s DeleteBucketReplicationInput) String() string { +func (s GetBucketMetricsConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketReplicationInput) GoString() string { +func (s GetBucketMetricsConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketReplicationInput"} +func (s *GetBucketMetricsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketMetricsConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } if invalidParams.Len() > 0 { return invalidParams @@ -8680,50 +12022,75 @@ func (s *DeleteBucketReplicationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketReplicationInput) SetBucket(v string) *DeleteBucketReplicationInput { +func (s *GetBucketMetricsConfigurationInput) SetBucket(v string) *GetBucketMetricsConfigurationInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationOutput -type DeleteBucketReplicationOutput struct { - _ struct{} `type:"structure"` +func (s *GetBucketMetricsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetId sets the Id field's value. +func (s *GetBucketMetricsConfigurationInput) SetId(v string) *GetBucketMetricsConfigurationInput { + s.Id = &v + return s +} + +type GetBucketMetricsConfigurationOutput struct { + _ struct{} `type:"structure" payload:"MetricsConfiguration"` + + // Specifies the metrics configuration. + MetricsConfiguration *MetricsConfiguration `type:"structure"` } // String returns the string representation -func (s DeleteBucketReplicationOutput) String() string { +func (s GetBucketMetricsConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketReplicationOutput) GoString() string { +func (s GetBucketMetricsConfigurationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingRequest -type DeleteBucketTaggingInput struct { +// SetMetricsConfiguration sets the MetricsConfiguration field's value. +func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *MetricsConfiguration) *GetBucketMetricsConfigurationOutput { + s.MetricsConfiguration = v + return s +} + +type GetBucketNotificationConfigurationRequest struct { _ struct{} `type:"structure"` + // Name of the bucket to get the notification configuration for. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s DeleteBucketTaggingInput) String() string { +func (s GetBucketNotificationConfigurationRequest) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketTaggingInput) GoString() string { +func (s GetBucketNotificationConfigurationRequest) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketTaggingInput"} +func (s *GetBucketNotificationConfigurationRequest) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketNotificationConfigurationRequest"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8732,28 +12099,19 @@ func (s *DeleteBucketTaggingInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketTaggingInput) SetBucket(v string) *DeleteBucketTaggingInput { +func (s *GetBucketNotificationConfigurationRequest) SetBucket(v string) *GetBucketNotificationConfigurationRequest { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingOutput -type DeleteBucketTaggingOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketTaggingOutput) GoString() string { - return s.String() +func (s *GetBucketNotificationConfigurationRequest) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteRequest -type DeleteBucketWebsiteInput struct { +type GetBucketPolicyInput struct { _ struct{} `type:"structure"` // Bucket is a required field @@ -8761,21 +12119,24 @@ type DeleteBucketWebsiteInput struct { } // String returns the string representation -func (s DeleteBucketWebsiteInput) String() string { +func (s GetBucketPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketWebsiteInput) GoString() string { +func (s GetBucketPolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketWebsiteInput"} +func (s *GetBucketPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketPolicyInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -8784,249 +12145,207 @@ func (s *DeleteBucketWebsiteInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteBucketWebsiteInput) SetBucket(v string) *DeleteBucketWebsiteInput { +func (s *GetBucketPolicyInput) SetBucket(v string) *GetBucketPolicyInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteOutput -type DeleteBucketWebsiteOutput struct { - _ struct{} `type:"structure"` +func (s *GetBucketPolicyInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +type GetBucketPolicyOutput struct { + _ struct{} `type:"structure" payload:"Policy"` + + // The bucket policy as a JSON document. + Policy *string `type:"string"` } // String returns the string representation -func (s DeleteBucketWebsiteOutput) String() string { +func (s GetBucketPolicyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteBucketWebsiteOutput) GoString() string { +func (s GetBucketPolicyOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteMarkerEntry -type DeleteMarkerEntry struct { - _ struct{} `type:"structure"` - - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `min:"1" type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` +// SetPolicy sets the Policy field's value. +func (s *GetBucketPolicyOutput) SetPolicy(v string) *GetBucketPolicyOutput { + s.Policy = &v + return s +} - Owner *Owner `type:"structure"` +type GetBucketPolicyStatusInput struct { + _ struct{} `type:"structure"` - // Version ID of an object. - VersionId *string `type:"string"` + // The name of the Amazon S3 bucket whose policy status you want to retrieve. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s DeleteMarkerEntry) String() string { +func (s GetBucketPolicyStatusInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteMarkerEntry) GoString() string { +func (s GetBucketPolicyStatusInput) GoString() string { return s.String() } -// SetIsLatest sets the IsLatest field's value. -func (s *DeleteMarkerEntry) SetIsLatest(v bool) *DeleteMarkerEntry { - s.IsLatest = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetBucketPolicyStatusInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketPolicyStatusInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetKey sets the Key field's value. -func (s *DeleteMarkerEntry) SetKey(v string) *DeleteMarkerEntry { - s.Key = &v +// SetBucket sets the Bucket field's value. +func (s *GetBucketPolicyStatusInput) SetBucket(v string) *GetBucketPolicyStatusInput { + s.Bucket = &v return s } -// SetLastModified sets the LastModified field's value. -func (s *DeleteMarkerEntry) SetLastModified(v time.Time) *DeleteMarkerEntry { - s.LastModified = &v - return s +func (s *GetBucketPolicyStatusInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetOwner sets the Owner field's value. -func (s *DeleteMarkerEntry) SetOwner(v *Owner) *DeleteMarkerEntry { - s.Owner = v - return s +type GetBucketPolicyStatusOutput struct { + _ struct{} `type:"structure" payload:"PolicyStatus"` + + // The policy status for the specified bucket. + PolicyStatus *PolicyStatus `type:"structure"` } -// SetVersionId sets the VersionId field's value. -func (s *DeleteMarkerEntry) SetVersionId(v string) *DeleteMarkerEntry { - s.VersionId = &v +// String returns the string representation +func (s GetBucketPolicyStatusOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetBucketPolicyStatusOutput) GoString() string { + return s.String() +} + +// SetPolicyStatus sets the PolicyStatus field's value. +func (s *GetBucketPolicyStatusOutput) SetPolicyStatus(v *PolicyStatus) *GetBucketPolicyStatusOutput { + s.PolicyStatus = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectRequest -type DeleteObjectInput struct { +type GetBucketReplicationInput struct { _ struct{} `type:"structure"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s DeleteObjectInput) String() string { +func (s GetBucketReplicationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectInput) GoString() string { +func (s GetBucketReplicationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectInput"} +func (s *GetBucketReplicationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketReplicationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteObjectInput) SetBucket(v string) *DeleteObjectInput { - s.Bucket = &v - return s -} - -// SetKey sets the Key field's value. -func (s *DeleteObjectInput) SetKey(v string) *DeleteObjectInput { - s.Key = &v - return s -} -// SetMFA sets the MFA field's value. -func (s *DeleteObjectInput) SetMFA(v string) *DeleteObjectInput { - s.MFA = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestPayer sets the RequestPayer field's value. -func (s *DeleteObjectInput) SetRequestPayer(v string) *DeleteObjectInput { - s.RequestPayer = &v +// SetBucket sets the Bucket field's value. +func (s *GetBucketReplicationInput) SetBucket(v string) *GetBucketReplicationInput { + s.Bucket = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectInput) SetVersionId(v string) *DeleteObjectInput { - s.VersionId = &v - return s +func (s *GetBucketReplicationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectOutput -type DeleteObjectOutput struct { - _ struct{} `type:"structure"` - - // Specifies whether the versioned object that was permanently deleted was (true) - // or was not (false) a delete marker. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` +type GetBucketReplicationOutput struct { + _ struct{} `type:"structure" payload:"ReplicationConfiguration"` - // Returns the version ID of the delete marker created as a result of the DELETE - // operation. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // A container for replication rules. You can add up to 1,000 rules. The maximum + // size of a replication configuration is 2 MB. + ReplicationConfiguration *ReplicationConfiguration `type:"structure"` } // String returns the string representation -func (s DeleteObjectOutput) String() string { +func (s GetBucketReplicationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectOutput) GoString() string { +func (s GetBucketReplicationOutput) GoString() string { return s.String() } -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *DeleteObjectOutput) SetDeleteMarker(v bool) *DeleteObjectOutput { - s.DeleteMarker = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *DeleteObjectOutput) SetRequestCharged(v string) *DeleteObjectOutput { - s.RequestCharged = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectOutput) SetVersionId(v string) *DeleteObjectOutput { - s.VersionId = &v +// SetReplicationConfiguration sets the ReplicationConfiguration field's value. +func (s *GetBucketReplicationOutput) SetReplicationConfiguration(v *ReplicationConfiguration) *GetBucketReplicationOutput { + s.ReplicationConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingRequest -type DeleteObjectTaggingInput struct { +type GetBucketRequestPaymentInput struct { _ struct{} `type:"structure"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // The versionId of the object that the tag-set will be removed from. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s DeleteObjectTaggingInput) String() string { +func (s GetBucketRequestPaymentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectTaggingInput) GoString() string { +func (s GetBucketRequestPaymentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectTaggingInput"} +func (s *GetBucketRequestPaymentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketRequestPaymentInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -9036,91 +12355,66 @@ func (s *DeleteObjectTaggingInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteObjectTaggingInput) SetBucket(v string) *DeleteObjectTaggingInput { +func (s *GetBucketRequestPaymentInput) SetBucket(v string) *GetBucketRequestPaymentInput { s.Bucket = &v return s } -// SetKey sets the Key field's value. -func (s *DeleteObjectTaggingInput) SetKey(v string) *DeleteObjectTaggingInput { - s.Key = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectTaggingInput) SetVersionId(v string) *DeleteObjectTaggingInput { - s.VersionId = &v - return s +func (s *GetBucketRequestPaymentInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingOutput -type DeleteObjectTaggingOutput struct { +type GetBucketRequestPaymentOutput struct { _ struct{} `type:"structure"` - // The versionId of the object the tag-set was removed from. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Specifies who pays for the download and request fees. + Payer *string `type:"string" enum:"Payer"` } // String returns the string representation -func (s DeleteObjectTaggingOutput) String() string { +func (s GetBucketRequestPaymentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectTaggingOutput) GoString() string { +func (s GetBucketRequestPaymentOutput) GoString() string { return s.String() } -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectTaggingOutput) SetVersionId(v string) *DeleteObjectTaggingOutput { - s.VersionId = &v +// SetPayer sets the Payer field's value. +func (s *GetBucketRequestPaymentOutput) SetPayer(v string) *GetBucketRequestPaymentOutput { + s.Payer = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsRequest -type DeleteObjectsInput struct { - _ struct{} `type:"structure" payload:"Delete"` +type GetBucketTaggingInput struct { + _ struct{} `type:"structure"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Delete is a required field - Delete *Delete `locationName:"Delete" type:"structure" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` } // String returns the string representation -func (s DeleteObjectsInput) String() string { +func (s GetBucketTaggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectsInput) GoString() string { +func (s GetBucketTaggingInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectsInput"} +func (s *GetBucketTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketTaggingInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Delete == nil { - invalidParams.Add(request.NewErrParamRequired("Delete")) - } - if s.Delete != nil { - if err := s.Delete.Validate(); err != nil { - invalidParams.AddNested("Delete", err.(request.ErrInvalidParams)) - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -9130,147 +12424,147 @@ func (s *DeleteObjectsInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *DeleteObjectsInput) SetBucket(v string) *DeleteObjectsInput { +func (s *GetBucketTaggingInput) SetBucket(v string) *GetBucketTaggingInput { s.Bucket = &v return s } -// SetDelete sets the Delete field's value. -func (s *DeleteObjectsInput) SetDelete(v *Delete) *DeleteObjectsInput { - s.Delete = v - return s +func (s *GetBucketTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetMFA sets the MFA field's value. -func (s *DeleteObjectsInput) SetMFA(v string) *DeleteObjectsInput { - s.MFA = &v - return s +type GetBucketTaggingOutput struct { + _ struct{} `type:"structure"` + + // TagSet is a required field + TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` } -// SetRequestPayer sets the RequestPayer field's value. -func (s *DeleteObjectsInput) SetRequestPayer(v string) *DeleteObjectsInput { - s.RequestPayer = &v - return s +// String returns the string representation +func (s GetBucketTaggingOutput) String() string { + return awsutil.Prettify(s) } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsOutput -type DeleteObjectsOutput struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s GetBucketTaggingOutput) GoString() string { + return s.String() +} - Deleted []*DeletedObject `type:"list" flattened:"true"` +// SetTagSet sets the TagSet field's value. +func (s *GetBucketTaggingOutput) SetTagSet(v []*Tag) *GetBucketTaggingOutput { + s.TagSet = v + return s +} - Errors []*Error `locationName:"Error" type:"list" flattened:"true"` +type GetBucketVersioningInput struct { + _ struct{} `type:"structure"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s DeleteObjectsOutput) String() string { +func (s GetBucketVersioningInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteObjectsOutput) GoString() string { +func (s GetBucketVersioningInput) GoString() string { return s.String() } -// SetDeleted sets the Deleted field's value. -func (s *DeleteObjectsOutput) SetDeleted(v []*DeletedObject) *DeleteObjectsOutput { - s.Deleted = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetBucketVersioningInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketVersioningInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetErrors sets the Errors field's value. -func (s *DeleteObjectsOutput) SetErrors(v []*Error) *DeleteObjectsOutput { - s.Errors = v +// SetBucket sets the Bucket field's value. +func (s *GetBucketVersioningInput) SetBucket(v string) *GetBucketVersioningInput { + s.Bucket = &v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *DeleteObjectsOutput) SetRequestCharged(v string) *DeleteObjectsOutput { - s.RequestCharged = &v - return s +func (s *GetBucketVersioningInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeletedObject -type DeletedObject struct { +type GetBucketVersioningOutput struct { _ struct{} `type:"structure"` - DeleteMarker *bool `type:"boolean"` - - DeleteMarkerVersionId *string `type:"string"` - - Key *string `min:"1" type:"string"` + // Specifies whether MFA delete is enabled in the bucket versioning configuration. + // This element is only returned if the bucket has been configured with MFA + // delete. If the bucket has never been so configured, this element is not returned. + MFADelete *string `locationName:"MfaDelete" type:"string" enum:"MFADeleteStatus"` - VersionId *string `type:"string"` + // The versioning state of the bucket. + Status *string `type:"string" enum:"BucketVersioningStatus"` } // String returns the string representation -func (s DeletedObject) String() string { +func (s GetBucketVersioningOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeletedObject) GoString() string { +func (s GetBucketVersioningOutput) GoString() string { return s.String() } -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *DeletedObject) SetDeleteMarker(v bool) *DeletedObject { - s.DeleteMarker = &v - return s -} - -// SetDeleteMarkerVersionId sets the DeleteMarkerVersionId field's value. -func (s *DeletedObject) SetDeleteMarkerVersionId(v string) *DeletedObject { - s.DeleteMarkerVersionId = &v - return s -} - -// SetKey sets the Key field's value. -func (s *DeletedObject) SetKey(v string) *DeletedObject { - s.Key = &v +// SetMFADelete sets the MFADelete field's value. +func (s *GetBucketVersioningOutput) SetMFADelete(v string) *GetBucketVersioningOutput { + s.MFADelete = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *DeletedObject) SetVersionId(v string) *DeletedObject { - s.VersionId = &v +// SetStatus sets the Status field's value. +func (s *GetBucketVersioningOutput) SetStatus(v string) *GetBucketVersioningOutput { + s.Status = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Destination -type Destination struct { +type GetBucketWebsiteInput struct { _ struct{} `type:"structure"` - // Amazon resource name (ARN) of the bucket where you want Amazon S3 to store - // replicas of the object identified by the rule. - // // Bucket is a required field - Bucket *string `type:"string" required:"true"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s Destination) String() string { +func (s GetBucketWebsiteInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Destination) GoString() string { +func (s GetBucketWebsiteInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Destination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Destination"} +func (s *GetBucketWebsiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetBucketWebsiteInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -9279,87 +12573,102 @@ func (s *Destination) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *Destination) SetBucket(v string) *Destination { +func (s *GetBucketWebsiteInput) SetBucket(v string) *GetBucketWebsiteInput { s.Bucket = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *Destination) SetStorageClass(v string) *Destination { - s.StorageClass = &v - return s +func (s *GetBucketWebsiteInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Error -type Error struct { +type GetBucketWebsiteOutput struct { _ struct{} `type:"structure"` - Code *string `type:"string"` + ErrorDocument *ErrorDocument `type:"structure"` - Key *string `min:"1" type:"string"` + IndexDocument *IndexDocument `type:"structure"` - Message *string `type:"string"` + RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - VersionId *string `type:"string"` + RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` } // String returns the string representation -func (s Error) String() string { +func (s GetBucketWebsiteOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Error) GoString() string { +func (s GetBucketWebsiteOutput) GoString() string { return s.String() } -// SetCode sets the Code field's value. -func (s *Error) SetCode(v string) *Error { - s.Code = &v +// SetErrorDocument sets the ErrorDocument field's value. +func (s *GetBucketWebsiteOutput) SetErrorDocument(v *ErrorDocument) *GetBucketWebsiteOutput { + s.ErrorDocument = v return s } -// SetKey sets the Key field's value. -func (s *Error) SetKey(v string) *Error { - s.Key = &v +// SetIndexDocument sets the IndexDocument field's value. +func (s *GetBucketWebsiteOutput) SetIndexDocument(v *IndexDocument) *GetBucketWebsiteOutput { + s.IndexDocument = v return s } -// SetMessage sets the Message field's value. -func (s *Error) SetMessage(v string) *Error { - s.Message = &v +// SetRedirectAllRequestsTo sets the RedirectAllRequestsTo field's value. +func (s *GetBucketWebsiteOutput) SetRedirectAllRequestsTo(v *RedirectAllRequestsTo) *GetBucketWebsiteOutput { + s.RedirectAllRequestsTo = v return s } -// SetVersionId sets the VersionId field's value. -func (s *Error) SetVersionId(v string) *Error { - s.VersionId = &v +// SetRoutingRules sets the RoutingRules field's value. +func (s *GetBucketWebsiteOutput) SetRoutingRules(v []*RoutingRule) *GetBucketWebsiteOutput { + s.RoutingRules = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ErrorDocument -type ErrorDocument struct { +type GetObjectAclInput struct { _ struct{} `type:"structure"` - // The object key name to use when a 4XX class error occurs. - // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Key is a required field - Key *string `min:"1" type:"string" required:"true"` + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // VersionId used to reference a specific version of the object. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s ErrorDocument) String() string { +func (s GetObjectAclInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ErrorDocument) GoString() string { +func (s GetObjectAclInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ErrorDocument) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ErrorDocument"} +func (s *GetObjectAclInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectAclInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Key == nil { invalidParams.Add(request.NewErrParamRequired("Key")) } @@ -9373,74 +12682,180 @@ func (s *ErrorDocument) Validate() error { return nil } +// SetBucket sets the Bucket field's value. +func (s *GetObjectAclInput) SetBucket(v string) *GetObjectAclInput { + s.Bucket = &v + return s +} + +func (s *GetObjectAclInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetKey sets the Key field's value. -func (s *ErrorDocument) SetKey(v string) *ErrorDocument { +func (s *GetObjectAclInput) SetKey(v string) *GetObjectAclInput { s.Key = &v return s } -// Container for key value pair that defines the criteria for the filter rule. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/FilterRule -type FilterRule struct { +// SetRequestPayer sets the RequestPayer field's value. +func (s *GetObjectAclInput) SetRequestPayer(v string) *GetObjectAclInput { + s.RequestPayer = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *GetObjectAclInput) SetVersionId(v string) *GetObjectAclInput { + s.VersionId = &v + return s +} + +type GetObjectAclOutput struct { _ struct{} `type:"structure"` - // Object key name prefix or suffix identifying one or more objects to which - // the filtering rule applies. Maximum prefix length can be up to 1,024 characters. - // Overlapping prefixes and suffixes are not supported. For more information, - // go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Name *string `type:"string" enum:"FilterRuleName"` + // A list of grants. + Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - Value *string `type:"string"` + Owner *Owner `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s FilterRule) String() string { +func (s GetObjectAclOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FilterRule) GoString() string { +func (s GetObjectAclOutput) GoString() string { return s.String() } -// SetName sets the Name field's value. -func (s *FilterRule) SetName(v string) *FilterRule { - s.Name = &v +// SetGrants sets the Grants field's value. +func (s *GetObjectAclOutput) SetGrants(v []*Grant) *GetObjectAclOutput { + s.Grants = v return s } -// SetValue sets the Value field's value. -func (s *FilterRule) SetValue(v string) *FilterRule { - s.Value = &v +// SetOwner sets the Owner field's value. +func (s *GetObjectAclOutput) SetOwner(v *Owner) *GetObjectAclOutput { + s.Owner = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationRequest -type GetBucketAccelerateConfigurationInput struct { +// SetRequestCharged sets the RequestCharged field's value. +func (s *GetObjectAclOutput) SetRequestCharged(v string) *GetObjectAclOutput { + s.RequestCharged = &v + return s +} + +type GetObjectInput struct { _ struct{} `type:"structure"` - // Name of the bucket for which the accelerate configuration is retrieved. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Return the object only if its entity tag (ETag) is the same as the one specified, + // otherwise return a 412 (precondition failed). + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + + // Return the object only if it has been modified since the specified time, + // otherwise return a 304 (not modified). + IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp"` + + // Return the object only if its entity tag (ETag) is different from the one + // specified, otherwise return a 304 (not modified). + IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` + + // Return the object only if it has not been modified since the specified time, + // otherwise return a 412 (precondition failed). + IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Part number of the object being read. This is a positive integer between + // 1 and 10,000. Effectively performs a 'ranged' GET request for the part specified. + // Useful for downloading just a part of an object. + PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` + + // Downloads the specified range bytes of an object. For more information about + // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + Range *string `location:"header" locationName:"Range" type:"string"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Sets the Cache-Control header of the response. + ResponseCacheControl *string `location:"querystring" locationName:"response-cache-control" type:"string"` + + // Sets the Content-Disposition header of the response + ResponseContentDisposition *string `location:"querystring" locationName:"response-content-disposition" type:"string"` + + // Sets the Content-Encoding header of the response. + ResponseContentEncoding *string `location:"querystring" locationName:"response-content-encoding" type:"string"` + + // Sets the Content-Language header of the response. + ResponseContentLanguage *string `location:"querystring" locationName:"response-content-language" type:"string"` + + // Sets the Content-Type header of the response. + ResponseContentType *string `location:"querystring" locationName:"response-content-type" type:"string"` + + // Sets the Expires header of the response. + ResponseExpires *time.Time `location:"querystring" locationName:"response-expires" type:"timestamp"` + + // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // does not store the encryption key. The key must be appropriate for use with + // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // VersionId used to reference a specific version of the object. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s GetBucketAccelerateConfigurationInput) String() string { +func (s GetObjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketAccelerateConfigurationInput) GoString() string { +func (s GetObjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAccelerateConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAccelerateConfigurationInput"} +func (s *GetObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -9449,137 +12864,180 @@ func (s *GetBucketAccelerateConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketAccelerateConfigurationInput) SetBucket(v string) *GetBucketAccelerateConfigurationInput { +func (s *GetObjectInput) SetBucket(v string) *GetObjectInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationOutput -type GetBucketAccelerateConfigurationOutput struct { - _ struct{} `type:"structure"` - - // The accelerate configuration of the bucket. - Status *string `type:"string" enum:"BucketAccelerateStatus"` +func (s *GetObjectInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetIfMatch sets the IfMatch field's value. +func (s *GetObjectInput) SetIfMatch(v string) *GetObjectInput { + s.IfMatch = &v + return s +} + +// SetIfModifiedSince sets the IfModifiedSince field's value. +func (s *GetObjectInput) SetIfModifiedSince(v time.Time) *GetObjectInput { + s.IfModifiedSince = &v + return s +} + +// SetIfNoneMatch sets the IfNoneMatch field's value. +func (s *GetObjectInput) SetIfNoneMatch(v string) *GetObjectInput { + s.IfNoneMatch = &v + return s } -// String returns the string representation -func (s GetBucketAccelerateConfigurationOutput) String() string { - return awsutil.Prettify(s) +// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. +func (s *GetObjectInput) SetIfUnmodifiedSince(v time.Time) *GetObjectInput { + s.IfUnmodifiedSince = &v + return s } -// GoString returns the string representation -func (s GetBucketAccelerateConfigurationOutput) GoString() string { - return s.String() +// SetKey sets the Key field's value. +func (s *GetObjectInput) SetKey(v string) *GetObjectInput { + s.Key = &v + return s } -// SetStatus sets the Status field's value. -func (s *GetBucketAccelerateConfigurationOutput) SetStatus(v string) *GetBucketAccelerateConfigurationOutput { - s.Status = &v +// SetPartNumber sets the PartNumber field's value. +func (s *GetObjectInput) SetPartNumber(v int64) *GetObjectInput { + s.PartNumber = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclRequest -type GetBucketAclInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetRange sets the Range field's value. +func (s *GetObjectInput) SetRange(v string) *GetObjectInput { + s.Range = &v + return s } -// String returns the string representation -func (s GetBucketAclInput) String() string { - return awsutil.Prettify(s) +// SetRequestPayer sets the RequestPayer field's value. +func (s *GetObjectInput) SetRequestPayer(v string) *GetObjectInput { + s.RequestPayer = &v + return s } -// GoString returns the string representation -func (s GetBucketAclInput) GoString() string { - return s.String() +// SetResponseCacheControl sets the ResponseCacheControl field's value. +func (s *GetObjectInput) SetResponseCacheControl(v string) *GetObjectInput { + s.ResponseCacheControl = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } +// SetResponseContentDisposition sets the ResponseContentDisposition field's value. +func (s *GetObjectInput) SetResponseContentDisposition(v string) *GetObjectInput { + s.ResponseContentDisposition = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetResponseContentEncoding sets the ResponseContentEncoding field's value. +func (s *GetObjectInput) SetResponseContentEncoding(v string) *GetObjectInput { + s.ResponseContentEncoding = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetBucketAclInput) SetBucket(v string) *GetBucketAclInput { - s.Bucket = &v +// SetResponseContentLanguage sets the ResponseContentLanguage field's value. +func (s *GetObjectInput) SetResponseContentLanguage(v string) *GetObjectInput { + s.ResponseContentLanguage = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclOutput -type GetBucketAclOutput struct { - _ struct{} `type:"structure"` +// SetResponseContentType sets the ResponseContentType field's value. +func (s *GetObjectInput) SetResponseContentType(v string) *GetObjectInput { + s.ResponseContentType = &v + return s +} - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` +// SetResponseExpires sets the ResponseExpires field's value. +func (s *GetObjectInput) SetResponseExpires(v time.Time) *GetObjectInput { + s.ResponseExpires = &v + return s +} - Owner *Owner `type:"structure"` +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *GetObjectInput) SetSSECustomerAlgorithm(v string) *GetObjectInput { + s.SSECustomerAlgorithm = &v + return s } -// String returns the string representation -func (s GetBucketAclOutput) String() string { - return awsutil.Prettify(s) +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *GetObjectInput) SetSSECustomerKey(v string) *GetObjectInput { + s.SSECustomerKey = &v + return s } -// GoString returns the string representation -func (s GetBucketAclOutput) GoString() string { - return s.String() +func (s *GetObjectInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey } -// SetGrants sets the Grants field's value. -func (s *GetBucketAclOutput) SetGrants(v []*Grant) *GetBucketAclOutput { - s.Grants = v +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *GetObjectInput) SetSSECustomerKeyMD5(v string) *GetObjectInput { + s.SSECustomerKeyMD5 = &v return s } -// SetOwner sets the Owner field's value. -func (s *GetBucketAclOutput) SetOwner(v *Owner) *GetBucketAclOutput { - s.Owner = v +// SetVersionId sets the VersionId field's value. +func (s *GetObjectInput) SetVersionId(v string) *GetObjectInput { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationRequest -type GetBucketAnalyticsConfigurationInput struct { +type GetObjectLegalHoldInput struct { _ struct{} `type:"structure"` - // The name of the bucket from which an analytics configuration is retrieved. + // The bucket containing the object whose Legal Hold status you want to retrieve. // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The identifier used to represent an analytics configuration. + // The key name for the object whose Legal Hold status you want to retrieve. // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // The version ID of the object whose Legal Hold status you want to retrieve. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s GetBucketAnalyticsConfigurationInput) String() string { +func (s GetObjectLegalHoldInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketAnalyticsConfigurationInput) GoString() string { +func (s GetObjectLegalHoldInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAnalyticsConfigurationInput"} +func (s *GetObjectLegalHoldInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectLegalHoldInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -9589,65 +13047,87 @@ func (s *GetBucketAnalyticsConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketAnalyticsConfigurationInput) SetBucket(v string) *GetBucketAnalyticsConfigurationInput { +func (s *GetObjectLegalHoldInput) SetBucket(v string) *GetObjectLegalHoldInput { s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput { - s.Id = &v +func (s *GetObjectLegalHoldInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *GetObjectLegalHoldInput) SetKey(v string) *GetObjectLegalHoldInput { + s.Key = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationOutput -type GetBucketAnalyticsConfigurationOutput struct { - _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` +// SetRequestPayer sets the RequestPayer field's value. +func (s *GetObjectLegalHoldInput) SetRequestPayer(v string) *GetObjectLegalHoldInput { + s.RequestPayer = &v + return s +} - // The configuration and any analyses for the analytics filter. - AnalyticsConfiguration *AnalyticsConfiguration `type:"structure"` +// SetVersionId sets the VersionId field's value. +func (s *GetObjectLegalHoldInput) SetVersionId(v string) *GetObjectLegalHoldInput { + s.VersionId = &v + return s +} + +type GetObjectLegalHoldOutput struct { + _ struct{} `type:"structure" payload:"LegalHold"` + + // The current Legal Hold status for the specified object. + LegalHold *ObjectLockLegalHold `type:"structure"` } // String returns the string representation -func (s GetBucketAnalyticsConfigurationOutput) String() string { +func (s GetObjectLegalHoldOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketAnalyticsConfigurationOutput) GoString() string { +func (s GetObjectLegalHoldOutput) GoString() string { return s.String() } -// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. -func (s *GetBucketAnalyticsConfigurationOutput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *GetBucketAnalyticsConfigurationOutput { - s.AnalyticsConfiguration = v +// SetLegalHold sets the LegalHold field's value. +func (s *GetObjectLegalHoldOutput) SetLegalHold(v *ObjectLockLegalHold) *GetObjectLegalHoldOutput { + s.LegalHold = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsRequest -type GetBucketCorsInput struct { +type GetObjectLockConfigurationInput struct { _ struct{} `type:"structure"` + // The bucket whose Object Lock configuration you want to retrieve. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s GetBucketCorsInput) String() string { +func (s GetObjectLockConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketCorsInput) GoString() string { +func (s GetObjectLockConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketCorsInput"} +func (s *GetObjectLockConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectLockConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -9656,315 +13136,400 @@ func (s *GetBucketCorsInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketCorsInput) SetBucket(v string) *GetBucketCorsInput { +func (s *GetObjectLockConfigurationInput) SetBucket(v string) *GetObjectLockConfigurationInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsOutput -type GetBucketCorsOutput struct { - _ struct{} `type:"structure"` +func (s *GetObjectLockConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` +type GetObjectLockConfigurationOutput struct { + _ struct{} `type:"structure" payload:"ObjectLockConfiguration"` + + // The specified bucket's Object Lock configuration. + ObjectLockConfiguration *ObjectLockConfiguration `type:"structure"` } // String returns the string representation -func (s GetBucketCorsOutput) String() string { +func (s GetObjectLockConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketCorsOutput) GoString() string { +func (s GetObjectLockConfigurationOutput) GoString() string { return s.String() } -// SetCORSRules sets the CORSRules field's value. -func (s *GetBucketCorsOutput) SetCORSRules(v []*CORSRule) *GetBucketCorsOutput { - s.CORSRules = v - return s -} +// SetObjectLockConfiguration sets the ObjectLockConfiguration field's value. +func (s *GetObjectLockConfigurationOutput) SetObjectLockConfiguration(v *ObjectLockConfiguration) *GetObjectLockConfigurationOutput { + s.ObjectLockConfiguration = v + return s +} + +type GetObjectOutput struct { + _ struct{} `type:"structure" payload:"Body"` + + AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` + + // Object data. + Body io.ReadCloser `type:"blob"` + + // Specifies caching behavior along the request/reply chain. + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + + // Specifies presentational information for the object. + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` + + // Size of the body in bytes. + ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` + + // The portion of the object returned in the response. + ContentRange *string `location:"header" locationName:"Content-Range" type:"string"` + + // A standard MIME type describing the format of the object data. + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + + // Specifies whether the object retrieved was (true) or was not (false) a Delete + // Marker. If false, this response header does not appear in the response. + DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` + + // An ETag is an opaque identifier assigned by a web server to a specific version + // of a resource found at a URL + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // If the object expiration is configured (see PUT Bucket lifecycle), the response + // includes this header. It includes the expiry-date and rule-id key value pairs + // providing object expiration information. The value of the rule-id is URL + // encoded. + Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` + + // The date and time at which the object is no longer cacheable. + Expires *string `location:"header" locationName:"Expires" type:"string"` + + // Last modified date of the object + LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp"` + + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + + // This is set to the number of metadata entries not returned in x-amz-meta + // headers. This can happen if you create metadata using an API like SOAP that + // supports more flexible metadata than the REST API. For example, using SOAP, + // you can create metadata whose values are not legal HTTP headers. + MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` + + // Indicates whether this object has an active legal hold. This field is only + // returned if you have permission to view an object's legal hold status. + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` + + // The Object Lock mode currently in place for this object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // The date and time when this object's Object Lock will expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationRequest -type GetBucketInventoryConfigurationInput struct { - _ struct{} `type:"structure"` + // The count of parts this object has. + PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` - // The name of the bucket containing the inventory configuration to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -// String returns the string representation -func (s GetBucketInventoryConfigurationInput) String() string { - return awsutil.Prettify(s) -} + // Provides information about object restoration operation and expiration time + // of the restored object copy. + Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` -// GoString returns the string representation -func (s GetBucketInventoryConfigurationInput) GoString() string { - return s.String() -} + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header confirming the encryption algorithm + // used. + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketInventoryConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header to provide round trip message integrity + // verification of the customer-provided encryption key. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` -// SetBucket sets the Bucket field's value. -func (s *GetBucketInventoryConfigurationInput) SetBucket(v string) *GetBucketInventoryConfigurationInput { - s.Bucket = &v - return s -} + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` -// SetId sets the Id field's value. -func (s *GetBucketInventoryConfigurationInput) SetId(v string) *GetBucketInventoryConfigurationInput { - s.Id = &v - return s -} + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationOutput -type GetBucketInventoryConfigurationOutput struct { - _ struct{} `type:"structure" payload:"InventoryConfiguration"` + // The number of tags, if any, on the object. + TagCount *int64 `location:"header" locationName:"x-amz-tagging-count" type:"integer"` - // Specifies the inventory configuration. - InventoryConfiguration *InventoryConfiguration `type:"structure"` + // Version of the object. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` } // String returns the string representation -func (s GetBucketInventoryConfigurationOutput) String() string { +func (s GetObjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketInventoryConfigurationOutput) GoString() string { +func (s GetObjectOutput) GoString() string { return s.String() } -// SetInventoryConfiguration sets the InventoryConfiguration field's value. -func (s *GetBucketInventoryConfigurationOutput) SetInventoryConfiguration(v *InventoryConfiguration) *GetBucketInventoryConfigurationOutput { - s.InventoryConfiguration = v +// SetAcceptRanges sets the AcceptRanges field's value. +func (s *GetObjectOutput) SetAcceptRanges(v string) *GetObjectOutput { + s.AcceptRanges = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationRequest -type GetBucketLifecycleConfigurationInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetBody sets the Body field's value. +func (s *GetObjectOutput) SetBody(v io.ReadCloser) *GetObjectOutput { + s.Body = v + return s } -// String returns the string representation -func (s GetBucketLifecycleConfigurationInput) String() string { - return awsutil.Prettify(s) +// SetCacheControl sets the CacheControl field's value. +func (s *GetObjectOutput) SetCacheControl(v string) *GetObjectOutput { + s.CacheControl = &v + return s } -// GoString returns the string representation -func (s GetBucketLifecycleConfigurationInput) GoString() string { - return s.String() +// SetContentDisposition sets the ContentDisposition field's value. +func (s *GetObjectOutput) SetContentDisposition(v string) *GetObjectOutput { + s.ContentDisposition = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLifecycleConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetContentEncoding sets the ContentEncoding field's value. +func (s *GetObjectOutput) SetContentEncoding(v string) *GetObjectOutput { + s.ContentEncoding = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetBucketLifecycleConfigurationInput) SetBucket(v string) *GetBucketLifecycleConfigurationInput { - s.Bucket = &v +// SetContentLanguage sets the ContentLanguage field's value. +func (s *GetObjectOutput) SetContentLanguage(v string) *GetObjectOutput { + s.ContentLanguage = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationOutput -type GetBucketLifecycleConfigurationOutput struct { - _ struct{} `type:"structure"` - - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` +// SetContentLength sets the ContentLength field's value. +func (s *GetObjectOutput) SetContentLength(v int64) *GetObjectOutput { + s.ContentLength = &v + return s } -// String returns the string representation -func (s GetBucketLifecycleConfigurationOutput) String() string { - return awsutil.Prettify(s) +// SetContentRange sets the ContentRange field's value. +func (s *GetObjectOutput) SetContentRange(v string) *GetObjectOutput { + s.ContentRange = &v + return s } -// GoString returns the string representation -func (s GetBucketLifecycleConfigurationOutput) GoString() string { - return s.String() +// SetContentType sets the ContentType field's value. +func (s *GetObjectOutput) SetContentType(v string) *GetObjectOutput { + s.ContentType = &v + return s } -// SetRules sets the Rules field's value. -func (s *GetBucketLifecycleConfigurationOutput) SetRules(v []*LifecycleRule) *GetBucketLifecycleConfigurationOutput { - s.Rules = v +// SetDeleteMarker sets the DeleteMarker field's value. +func (s *GetObjectOutput) SetDeleteMarker(v bool) *GetObjectOutput { + s.DeleteMarker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleRequest -type GetBucketLifecycleInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetETag sets the ETag field's value. +func (s *GetObjectOutput) SetETag(v string) *GetObjectOutput { + s.ETag = &v + return s } -// String returns the string representation -func (s GetBucketLifecycleInput) String() string { - return awsutil.Prettify(s) +// SetExpiration sets the Expiration field's value. +func (s *GetObjectOutput) SetExpiration(v string) *GetObjectOutput { + s.Expiration = &v + return s } -// GoString returns the string representation -func (s GetBucketLifecycleInput) GoString() string { - return s.String() +// SetExpires sets the Expires field's value. +func (s *GetObjectOutput) SetExpires(v string) *GetObjectOutput { + s.Expires = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetLastModified sets the LastModified field's value. +func (s *GetObjectOutput) SetLastModified(v time.Time) *GetObjectOutput { + s.LastModified = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetBucketLifecycleInput) SetBucket(v string) *GetBucketLifecycleInput { - s.Bucket = &v +// SetMetadata sets the Metadata field's value. +func (s *GetObjectOutput) SetMetadata(v map[string]*string) *GetObjectOutput { + s.Metadata = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleOutput -type GetBucketLifecycleOutput struct { - _ struct{} `type:"structure"` - - Rules []*Rule `locationName:"Rule" type:"list" flattened:"true"` +// SetMissingMeta sets the MissingMeta field's value. +func (s *GetObjectOutput) SetMissingMeta(v int64) *GetObjectOutput { + s.MissingMeta = &v + return s } -// String returns the string representation -func (s GetBucketLifecycleOutput) String() string { - return awsutil.Prettify(s) +// SetObjectLockLegalHoldStatus sets the ObjectLockLegalHoldStatus field's value. +func (s *GetObjectOutput) SetObjectLockLegalHoldStatus(v string) *GetObjectOutput { + s.ObjectLockLegalHoldStatus = &v + return s } -// GoString returns the string representation -func (s GetBucketLifecycleOutput) GoString() string { - return s.String() +// SetObjectLockMode sets the ObjectLockMode field's value. +func (s *GetObjectOutput) SetObjectLockMode(v string) *GetObjectOutput { + s.ObjectLockMode = &v + return s } -// SetRules sets the Rules field's value. -func (s *GetBucketLifecycleOutput) SetRules(v []*Rule) *GetBucketLifecycleOutput { - s.Rules = v +// SetObjectLockRetainUntilDate sets the ObjectLockRetainUntilDate field's value. +func (s *GetObjectOutput) SetObjectLockRetainUntilDate(v time.Time) *GetObjectOutput { + s.ObjectLockRetainUntilDate = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationRequest -type GetBucketLocationInput struct { - _ struct{} `type:"structure"` +// SetPartsCount sets the PartsCount field's value. +func (s *GetObjectOutput) SetPartsCount(v int64) *GetObjectOutput { + s.PartsCount = &v + return s +} - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetReplicationStatus sets the ReplicationStatus field's value. +func (s *GetObjectOutput) SetReplicationStatus(v string) *GetObjectOutput { + s.ReplicationStatus = &v + return s } -// String returns the string representation -func (s GetBucketLocationInput) String() string { - return awsutil.Prettify(s) +// SetRequestCharged sets the RequestCharged field's value. +func (s *GetObjectOutput) SetRequestCharged(v string) *GetObjectOutput { + s.RequestCharged = &v + return s } -// GoString returns the string representation -func (s GetBucketLocationInput) GoString() string { - return s.String() +// SetRestore sets the Restore field's value. +func (s *GetObjectOutput) SetRestore(v string) *GetObjectOutput { + s.Restore = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLocationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLocationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *GetObjectOutput) SetSSECustomerAlgorithm(v string) *GetObjectOutput { + s.SSECustomerAlgorithm = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *GetObjectOutput) SetSSECustomerKeyMD5(v string) *GetObjectOutput { + s.SSECustomerKeyMD5 = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetBucketLocationInput) SetBucket(v string) *GetBucketLocationInput { - s.Bucket = &v +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *GetObjectOutput) SetSSEKMSKeyId(v string) *GetObjectOutput { + s.SSEKMSKeyId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationOutput -type GetBucketLocationOutput struct { - _ struct{} `type:"structure"` +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *GetObjectOutput) SetServerSideEncryption(v string) *GetObjectOutput { + s.ServerSideEncryption = &v + return s +} - LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` +// SetStorageClass sets the StorageClass field's value. +func (s *GetObjectOutput) SetStorageClass(v string) *GetObjectOutput { + s.StorageClass = &v + return s } -// String returns the string representation -func (s GetBucketLocationOutput) String() string { - return awsutil.Prettify(s) +// SetTagCount sets the TagCount field's value. +func (s *GetObjectOutput) SetTagCount(v int64) *GetObjectOutput { + s.TagCount = &v + return s } -// GoString returns the string representation -func (s GetBucketLocationOutput) GoString() string { - return s.String() +// SetVersionId sets the VersionId field's value. +func (s *GetObjectOutput) SetVersionId(v string) *GetObjectOutput { + s.VersionId = &v + return s } -// SetLocationConstraint sets the LocationConstraint field's value. -func (s *GetBucketLocationOutput) SetLocationConstraint(v string) *GetBucketLocationOutput { - s.LocationConstraint = &v +// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. +func (s *GetObjectOutput) SetWebsiteRedirectLocation(v string) *GetObjectOutput { + s.WebsiteRedirectLocation = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingRequest -type GetBucketLoggingInput struct { +type GetObjectRetentionInput struct { _ struct{} `type:"structure"` + // The bucket containing the object whose retention settings you want to retrieve. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The key name for the object whose retention settings you want to retrieve. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // The version ID for the object whose retention settings you want to retrieve. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s GetBucketLoggingInput) String() string { +func (s GetObjectRetentionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketLoggingInput) GoString() string { +func (s GetObjectRetentionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLoggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLoggingInput"} +func (s *GetObjectRetentionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectRetentionInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -9973,67 +13538,95 @@ func (s *GetBucketLoggingInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketLoggingInput) SetBucket(v string) *GetBucketLoggingInput { +func (s *GetObjectRetentionInput) SetBucket(v string) *GetObjectRetentionInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingOutput -type GetBucketLoggingOutput struct { - _ struct{} `type:"structure"` +func (s *GetObjectRetentionInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - LoggingEnabled *LoggingEnabled `type:"structure"` +// SetKey sets the Key field's value. +func (s *GetObjectRetentionInput) SetKey(v string) *GetObjectRetentionInput { + s.Key = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *GetObjectRetentionInput) SetRequestPayer(v string) *GetObjectRetentionInput { + s.RequestPayer = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *GetObjectRetentionInput) SetVersionId(v string) *GetObjectRetentionInput { + s.VersionId = &v + return s +} + +type GetObjectRetentionOutput struct { + _ struct{} `type:"structure" payload:"Retention"` + + // The container element for an object's retention settings. + Retention *ObjectLockRetention `type:"structure"` } // String returns the string representation -func (s GetBucketLoggingOutput) String() string { +func (s GetObjectRetentionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketLoggingOutput) GoString() string { +func (s GetObjectRetentionOutput) GoString() string { return s.String() } -// SetLoggingEnabled sets the LoggingEnabled field's value. -func (s *GetBucketLoggingOutput) SetLoggingEnabled(v *LoggingEnabled) *GetBucketLoggingOutput { - s.LoggingEnabled = v +// SetRetention sets the Retention field's value. +func (s *GetObjectRetentionOutput) SetRetention(v *ObjectLockRetention) *GetObjectRetentionOutput { + s.Retention = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationRequest -type GetBucketMetricsConfigurationInput struct { +type GetObjectTaggingInput struct { _ struct{} `type:"structure"` - // The name of the bucket containing the metrics configuration to retrieve. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s GetBucketMetricsConfigurationInput) String() string { +func (s GetObjectTaggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketMetricsConfigurationInput) GoString() string { +func (s GetObjectTaggingInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketMetricsConfigurationInput"} +func (s *GetObjectTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectTaggingInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -10043,67 +13636,102 @@ func (s *GetBucketMetricsConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketMetricsConfigurationInput) SetBucket(v string) *GetBucketMetricsConfigurationInput { +func (s *GetObjectTaggingInput) SetBucket(v string) *GetObjectTaggingInput { s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *GetBucketMetricsConfigurationInput) SetId(v string) *GetBucketMetricsConfigurationInput { - s.Id = &v +func (s *GetObjectTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *GetObjectTaggingInput) SetKey(v string) *GetObjectTaggingInput { + s.Key = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationOutput -type GetBucketMetricsConfigurationOutput struct { - _ struct{} `type:"structure" payload:"MetricsConfiguration"` +// SetVersionId sets the VersionId field's value. +func (s *GetObjectTaggingInput) SetVersionId(v string) *GetObjectTaggingInput { + s.VersionId = &v + return s +} - // Specifies the metrics configuration. - MetricsConfiguration *MetricsConfiguration `type:"structure"` +type GetObjectTaggingOutput struct { + _ struct{} `type:"structure"` + + // TagSet is a required field + TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` + + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` } // String returns the string representation -func (s GetBucketMetricsConfigurationOutput) String() string { +func (s GetObjectTaggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketMetricsConfigurationOutput) GoString() string { +func (s GetObjectTaggingOutput) GoString() string { return s.String() } -// SetMetricsConfiguration sets the MetricsConfiguration field's value. -func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *MetricsConfiguration) *GetBucketMetricsConfigurationOutput { - s.MetricsConfiguration = v +// SetTagSet sets the TagSet field's value. +func (s *GetObjectTaggingOutput) SetTagSet(v []*Tag) *GetObjectTaggingOutput { + s.TagSet = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfigurationRequest -type GetBucketNotificationConfigurationRequest struct { +// SetVersionId sets the VersionId field's value. +func (s *GetObjectTaggingOutput) SetVersionId(v string) *GetObjectTaggingOutput { + s.VersionId = &v + return s +} + +type GetObjectTorrentInput struct { _ struct{} `type:"structure"` - // Name of the bucket to get the notification configuration for. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` } // String returns the string representation -func (s GetBucketNotificationConfigurationRequest) String() string { +func (s GetObjectTorrentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketNotificationConfigurationRequest) GoString() string { +func (s GetObjectTorrentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketNotificationConfigurationRequest) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketNotificationConfigurationRequest"} +func (s *GetObjectTorrentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetObjectTorrentInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -10112,96 +13740,91 @@ func (s *GetBucketNotificationConfigurationRequest) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketNotificationConfigurationRequest) SetBucket(v string) *GetBucketNotificationConfigurationRequest { +func (s *GetObjectTorrentInput) SetBucket(v string) *GetObjectTorrentInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyRequest -type GetBucketPolicyInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketPolicyInput"} +func (s *GetObjectTorrentInput) getBucket() (v string) { if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) + return v } + return *s.Bucket +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetKey sets the Key field's value. +func (s *GetObjectTorrentInput) SetKey(v string) *GetObjectTorrentInput { + s.Key = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetBucketPolicyInput) SetBucket(v string) *GetBucketPolicyInput { - s.Bucket = &v +// SetRequestPayer sets the RequestPayer field's value. +func (s *GetObjectTorrentInput) SetRequestPayer(v string) *GetObjectTorrentInput { + s.RequestPayer = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyOutput -type GetBucketPolicyOutput struct { - _ struct{} `type:"structure" payload:"Policy"` +type GetObjectTorrentOutput struct { + _ struct{} `type:"structure" payload:"Body"` - // The bucket policy as a JSON document. - Policy *string `type:"string"` + Body io.ReadCloser `type:"blob"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s GetBucketPolicyOutput) String() string { +func (s GetObjectTorrentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketPolicyOutput) GoString() string { +func (s GetObjectTorrentOutput) GoString() string { return s.String() } -// SetPolicy sets the Policy field's value. -func (s *GetBucketPolicyOutput) SetPolicy(v string) *GetBucketPolicyOutput { - s.Policy = &v +// SetBody sets the Body field's value. +func (s *GetObjectTorrentOutput) SetBody(v io.ReadCloser) *GetObjectTorrentOutput { + s.Body = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationRequest -type GetBucketReplicationInput struct { +// SetRequestCharged sets the RequestCharged field's value. +func (s *GetObjectTorrentOutput) SetRequestCharged(v string) *GetObjectTorrentOutput { + s.RequestCharged = &v + return s +} + +type GetPublicAccessBlockInput struct { _ struct{} `type:"structure"` + // The name of the Amazon S3 bucket whose PublicAccessBlock configuration you + // want to retrieve. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s GetBucketReplicationInput) String() string { +func (s GetPublicAccessBlockInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketReplicationInput) GoString() string { +func (s GetPublicAccessBlockInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketReplicationInput"} +func (s *GetPublicAccessBlockInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetPublicAccessBlockInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -10210,59 +13833,66 @@ func (s *GetBucketReplicationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketReplicationInput) SetBucket(v string) *GetBucketReplicationInput { +func (s *GetPublicAccessBlockInput) SetBucket(v string) *GetPublicAccessBlockInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationOutput -type GetBucketReplicationOutput struct { - _ struct{} `type:"structure" payload:"ReplicationConfiguration"` +func (s *GetPublicAccessBlockInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - ReplicationConfiguration *ReplicationConfiguration `type:"structure"` +type GetPublicAccessBlockOutput struct { + _ struct{} `type:"structure" payload:"PublicAccessBlockConfiguration"` + + // The PublicAccessBlock configuration currently in effect for this Amazon S3 + // bucket. + PublicAccessBlockConfiguration *PublicAccessBlockConfiguration `type:"structure"` } // String returns the string representation -func (s GetBucketReplicationOutput) String() string { +func (s GetPublicAccessBlockOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketReplicationOutput) GoString() string { +func (s GetPublicAccessBlockOutput) GoString() string { return s.String() } -// SetReplicationConfiguration sets the ReplicationConfiguration field's value. -func (s *GetBucketReplicationOutput) SetReplicationConfiguration(v *ReplicationConfiguration) *GetBucketReplicationOutput { - s.ReplicationConfiguration = v +// SetPublicAccessBlockConfiguration sets the PublicAccessBlockConfiguration field's value. +func (s *GetPublicAccessBlockOutput) SetPublicAccessBlockConfiguration(v *PublicAccessBlockConfiguration) *GetPublicAccessBlockOutput { + s.PublicAccessBlockConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentRequest -type GetBucketRequestPaymentInput struct { +type GlacierJobParameters struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Glacier retrieval tier at which the restore will be processed. + // + // Tier is a required field + Tier *string `type:"string" required:"true" enum:"Tier"` } // String returns the string representation -func (s GetBucketRequestPaymentInput) String() string { +func (s GlacierJobParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketRequestPaymentInput) GoString() string { +func (s GlacierJobParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketRequestPaymentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketRequestPaymentInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *GlacierJobParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GlacierJobParameters"} + if s.Tier == nil { + invalidParams.Add(request.NewErrParamRequired("Tier")) } if invalidParams.Len() > 0 { @@ -10271,59 +13901,38 @@ func (s *GetBucketRequestPaymentInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *GetBucketRequestPaymentInput) SetBucket(v string) *GetBucketRequestPaymentInput { - s.Bucket = &v +// SetTier sets the Tier field's value. +func (s *GlacierJobParameters) SetTier(v string) *GlacierJobParameters { + s.Tier = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentOutput -type GetBucketRequestPaymentOutput struct { +type Grant struct { _ struct{} `type:"structure"` - // Specifies who pays for the download and request fees. - Payer *string `type:"string" enum:"Payer"` -} - -// String returns the string representation -func (s GetBucketRequestPaymentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketRequestPaymentOutput) GoString() string { - return s.String() -} - -// SetPayer sets the Payer field's value. -func (s *GetBucketRequestPaymentOutput) SetPayer(v string) *GetBucketRequestPaymentOutput { - s.Payer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingRequest -type GetBucketTaggingInput struct { - _ struct{} `type:"structure"` + Grantee *Grantee `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Specifies the permission given to the grantee. + Permission *string `type:"string" enum:"Permission"` } // String returns the string representation -func (s GetBucketTaggingInput) String() string { +func (s Grant) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketTaggingInput) GoString() string { +func (s Grant) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *Grant) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Grant"} + if s.Grantee != nil { + if err := s.Grantee.Validate(); err != nil { + invalidParams.AddNested("Grantee", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -10332,59 +13941,54 @@ func (s *GetBucketTaggingInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *GetBucketTaggingInput) SetBucket(v string) *GetBucketTaggingInput { - s.Bucket = &v +// SetGrantee sets the Grantee field's value. +func (s *Grant) SetGrantee(v *Grantee) *Grant { + s.Grantee = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingOutput -type GetBucketTaggingOutput struct { - _ struct{} `type:"structure"` - - // TagSet is a required field - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` +// SetPermission sets the Permission field's value. +func (s *Grant) SetPermission(v string) *Grant { + s.Permission = &v + return s } -// String returns the string representation -func (s GetBucketTaggingOutput) String() string { - return awsutil.Prettify(s) -} +type Grantee struct { + _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` -// GoString returns the string representation -func (s GetBucketTaggingOutput) GoString() string { - return s.String() -} + // Screen name of the grantee. + DisplayName *string `type:"string"` -// SetTagSet sets the TagSet field's value. -func (s *GetBucketTaggingOutput) SetTagSet(v []*Tag) *GetBucketTaggingOutput { - s.TagSet = v - return s -} + // Email address of the grantee. + EmailAddress *string `type:"string"` -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningRequest -type GetBucketVersioningInput struct { - _ struct{} `type:"structure"` + // The canonical user ID of the grantee. + ID *string `type:"string"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Type of grantee + // + // Type is a required field + Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true" required:"true" enum:"Type"` + + // URI of the grantee group. + URI *string `type:"string"` } // String returns the string representation -func (s GetBucketVersioningInput) String() string { +func (s Grantee) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketVersioningInput) GoString() string { +func (s Grantee) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketVersioningInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketVersioningInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *Grantee) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Grantee"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) } if invalidParams.Len() > 0 { @@ -10393,49 +13997,37 @@ func (s *GetBucketVersioningInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *GetBucketVersioningInput) SetBucket(v string) *GetBucketVersioningInput { - s.Bucket = &v +// SetDisplayName sets the DisplayName field's value. +func (s *Grantee) SetDisplayName(v string) *Grantee { + s.DisplayName = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningOutput -type GetBucketVersioningOutput struct { - _ struct{} `type:"structure"` - - // Specifies whether MFA delete is enabled in the bucket versioning configuration. - // This element is only returned if the bucket has been configured with MFA - // delete. If the bucket has never been so configured, this element is not returned. - MFADelete *string `locationName:"MfaDelete" type:"string" enum:"MFADeleteStatus"` - - // The versioning state of the bucket. - Status *string `type:"string" enum:"BucketVersioningStatus"` -} - -// String returns the string representation -func (s GetBucketVersioningOutput) String() string { - return awsutil.Prettify(s) +// SetEmailAddress sets the EmailAddress field's value. +func (s *Grantee) SetEmailAddress(v string) *Grantee { + s.EmailAddress = &v + return s } -// GoString returns the string representation -func (s GetBucketVersioningOutput) GoString() string { - return s.String() +// SetID sets the ID field's value. +func (s *Grantee) SetID(v string) *Grantee { + s.ID = &v + return s } -// SetMFADelete sets the MFADelete field's value. -func (s *GetBucketVersioningOutput) SetMFADelete(v string) *GetBucketVersioningOutput { - s.MFADelete = &v +// SetType sets the Type field's value. +func (s *Grantee) SetType(v string) *Grantee { + s.Type = &v return s } -// SetStatus sets the Status field's value. -func (s *GetBucketVersioningOutput) SetStatus(v string) *GetBucketVersioningOutput { - s.Status = &v +// SetURI sets the URI field's value. +func (s *Grantee) SetURI(v string) *Grantee { + s.URI = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteRequest -type GetBucketWebsiteInput struct { +type HeadBucketInput struct { _ struct{} `type:"structure"` // Bucket is a required field @@ -10443,21 +14035,24 @@ type GetBucketWebsiteInput struct { } // String returns the string representation -func (s GetBucketWebsiteInput) String() string { +func (s HeadBucketInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBucketWebsiteInput) GoString() string { +func (s HeadBucketInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketWebsiteInput"} +func (s *HeadBucketInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HeadBucketInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -10466,94 +14061,111 @@ func (s *GetBucketWebsiteInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetBucketWebsiteInput) SetBucket(v string) *GetBucketWebsiteInput { +func (s *HeadBucketInput) SetBucket(v string) *HeadBucketInput { s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteOutput -type GetBucketWebsiteOutput struct { - _ struct{} `type:"structure"` - - ErrorDocument *ErrorDocument `type:"structure"` - - IndexDocument *IndexDocument `type:"structure"` - - RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - - RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` -} - -// String returns the string representation -func (s GetBucketWebsiteOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketWebsiteOutput) GoString() string { - return s.String() -} - -// SetErrorDocument sets the ErrorDocument field's value. -func (s *GetBucketWebsiteOutput) SetErrorDocument(v *ErrorDocument) *GetBucketWebsiteOutput { - s.ErrorDocument = v - return s +func (s *HeadBucketInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetIndexDocument sets the IndexDocument field's value. -func (s *GetBucketWebsiteOutput) SetIndexDocument(v *IndexDocument) *GetBucketWebsiteOutput { - s.IndexDocument = v - return s +type HeadBucketOutput struct { + _ struct{} `type:"structure"` } -// SetRedirectAllRequestsTo sets the RedirectAllRequestsTo field's value. -func (s *GetBucketWebsiteOutput) SetRedirectAllRequestsTo(v *RedirectAllRequestsTo) *GetBucketWebsiteOutput { - s.RedirectAllRequestsTo = v - return s +// String returns the string representation +func (s HeadBucketOutput) String() string { + return awsutil.Prettify(s) } -// SetRoutingRules sets the RoutingRules field's value. -func (s *GetBucketWebsiteOutput) SetRoutingRules(v []*RoutingRule) *GetBucketWebsiteOutput { - s.RoutingRules = v - return s +// GoString returns the string representation +func (s HeadBucketOutput) GoString() string { + return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclRequest -type GetObjectAclInput struct { +type HeadObjectInput struct { _ struct{} `type:"structure"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Return the object only if its entity tag (ETag) is the same as the one specified, + // otherwise return a 412 (precondition failed). + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + + // Return the object only if it has been modified since the specified time, + // otherwise return a 304 (not modified). + IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp"` + + // Return the object only if its entity tag (ETag) is different from the one + // specified, otherwise return a 304 (not modified). + IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` + + // Return the object only if it has not been modified since the specified time, + // otherwise return a 412 (precondition failed). + IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp"` + // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Part number of the object being read. This is a positive integer between + // 1 and 10,000. Effectively performs a 'ranged' HEAD request for the part specified. + // Useful querying about the size of the part and the number of parts in this + // object. + PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` + + // Downloads the specified range bytes of an object. For more information about + // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + Range *string `location:"header" locationName:"Range" type:"string"` + // Confirms that the requester knows that she or he will be charged for the // request. Bucket owners need not specify this parameter in their requests. // Documentation on downloading objects from requester pays buckets can be found // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // does not store the encryption key. The key must be appropriate for use with + // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // VersionId used to reference a specific version of the object. VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s GetObjectAclInput) String() string { +func (s HeadObjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectAclInput) GoString() string { +func (s HeadObjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectAclInput"} +func (s *HeadObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HeadObjectInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Key == nil { invalidParams.Add(request.NewErrParamRequired("Key")) } @@ -10568,610 +14180,813 @@ func (s *GetObjectAclInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *GetObjectAclInput) SetBucket(v string) *GetObjectAclInput { +func (s *HeadObjectInput) SetBucket(v string) *HeadObjectInput { s.Bucket = &v return s } -// SetKey sets the Key field's value. -func (s *GetObjectAclInput) SetKey(v string) *GetObjectAclInput { - s.Key = &v +func (s *HeadObjectInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetIfMatch sets the IfMatch field's value. +func (s *HeadObjectInput) SetIfMatch(v string) *HeadObjectInput { + s.IfMatch = &v return s } -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectAclInput) SetRequestPayer(v string) *GetObjectAclInput { - s.RequestPayer = &v +// SetIfModifiedSince sets the IfModifiedSince field's value. +func (s *HeadObjectInput) SetIfModifiedSince(v time.Time) *HeadObjectInput { + s.IfModifiedSince = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *GetObjectAclInput) SetVersionId(v string) *GetObjectAclInput { - s.VersionId = &v +// SetIfNoneMatch sets the IfNoneMatch field's value. +func (s *HeadObjectInput) SetIfNoneMatch(v string) *HeadObjectInput { + s.IfNoneMatch = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclOutput -type GetObjectAclOutput struct { - _ struct{} `type:"structure"` +// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. +func (s *HeadObjectInput) SetIfUnmodifiedSince(v time.Time) *HeadObjectInput { + s.IfUnmodifiedSince = &v + return s +} - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` +// SetKey sets the Key field's value. +func (s *HeadObjectInput) SetKey(v string) *HeadObjectInput { + s.Key = &v + return s +} - Owner *Owner `type:"structure"` +// SetPartNumber sets the PartNumber field's value. +func (s *HeadObjectInput) SetPartNumber(v int64) *HeadObjectInput { + s.PartNumber = &v + return s +} - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` +// SetRange sets the Range field's value. +func (s *HeadObjectInput) SetRange(v string) *HeadObjectInput { + s.Range = &v + return s } -// String returns the string representation -func (s GetObjectAclOutput) String() string { - return awsutil.Prettify(s) +// SetRequestPayer sets the RequestPayer field's value. +func (s *HeadObjectInput) SetRequestPayer(v string) *HeadObjectInput { + s.RequestPayer = &v + return s } -// GoString returns the string representation -func (s GetObjectAclOutput) GoString() string { - return s.String() +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *HeadObjectInput) SetSSECustomerAlgorithm(v string) *HeadObjectInput { + s.SSECustomerAlgorithm = &v + return s } -// SetGrants sets the Grants field's value. -func (s *GetObjectAclOutput) SetGrants(v []*Grant) *GetObjectAclOutput { - s.Grants = v +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *HeadObjectInput) SetSSECustomerKey(v string) *HeadObjectInput { + s.SSECustomerKey = &v return s } -// SetOwner sets the Owner field's value. -func (s *GetObjectAclOutput) SetOwner(v *Owner) *GetObjectAclOutput { - s.Owner = v +func (s *HeadObjectInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey +} + +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *HeadObjectInput) SetSSECustomerKeyMD5(v string) *HeadObjectInput { + s.SSECustomerKeyMD5 = &v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectAclOutput) SetRequestCharged(v string) *GetObjectAclOutput { - s.RequestCharged = &v +// SetVersionId sets the VersionId field's value. +func (s *HeadObjectInput) SetVersionId(v string) *HeadObjectInput { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectRequest -type GetObjectInput struct { +type HeadObjectOutput struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // Specifies caching behavior along the request/reply chain. + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` + // Specifies presentational information for the object. + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Size of the body in bytes. + ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - // Part number of the object being read. This is a positive integer between - // 1 and 10,000. Effectively performs a 'ranged' GET request for the part specified. - // Useful for downloading just a part of an object. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` + // A standard MIME type describing the format of the object data. + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` + // Specifies whether the object retrieved was (true) or was not (false) a Delete + // Marker. If false, this response header does not appear in the response. + DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + // An ETag is an opaque identifier assigned by a web server to a specific version + // of a resource found at a URL + ETag *string `location:"header" locationName:"ETag" type:"string"` - // Sets the Cache-Control header of the response. - ResponseCacheControl *string `location:"querystring" locationName:"response-cache-control" type:"string"` + // If the object expiration is configured (see PUT Bucket lifecycle), the response + // includes this header. It includes the expiry-date and rule-id key value pairs + // providing object expiration information. The value of the rule-id is URL + // encoded. + Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - // Sets the Content-Disposition header of the response - ResponseContentDisposition *string `location:"querystring" locationName:"response-content-disposition" type:"string"` + // The date and time at which the object is no longer cacheable. + Expires *string `location:"header" locationName:"Expires" type:"string"` - // Sets the Content-Encoding header of the response. - ResponseContentEncoding *string `location:"querystring" locationName:"response-content-encoding" type:"string"` + // Last modified date of the object + LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp"` - // Sets the Content-Language header of the response. - ResponseContentLanguage *string `location:"querystring" locationName:"response-content-language" type:"string"` + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - // Sets the Content-Type header of the response. - ResponseContentType *string `location:"querystring" locationName:"response-content-type" type:"string"` + // This is set to the number of metadata entries not returned in x-amz-meta + // headers. This can happen if you create metadata using an API like SOAP that + // supports more flexible metadata than the REST API. For example, using SOAP, + // you can create metadata whose values are not legal HTTP headers. + MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` - // Sets the Expires header of the response. - ResponseExpires *time.Time `location:"querystring" locationName:"response-expires" type:"timestamp" timestampFormat:"iso8601"` + // The Legal Hold status for the specified object. + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + // The Object Lock mode currently in place for this object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // The date and time when this object's Object Lock will expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` + + // The count of parts this object has. + PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` + + ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // Provides information about object restoration operation and expiration time + // of the restored object copy. + Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header confirming the encryption algorithm + // used. SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header to provide round trip message integrity + // verification of the customer-provided encryption key. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // Version of the object. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` } // String returns the string representation -func (s GetObjectInput) String() string { +func (s HeadObjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectInput) GoString() string { +func (s HeadObjectOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetAcceptRanges sets the AcceptRanges field's value. +func (s *HeadObjectOutput) SetAcceptRanges(v string) *HeadObjectOutput { + s.AcceptRanges = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *GetObjectInput) SetBucket(v string) *GetObjectInput { - s.Bucket = &v +// SetCacheControl sets the CacheControl field's value. +func (s *HeadObjectOutput) SetCacheControl(v string) *HeadObjectOutput { + s.CacheControl = &v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *GetObjectInput) SetIfMatch(v string) *GetObjectInput { - s.IfMatch = &v +// SetContentDisposition sets the ContentDisposition field's value. +func (s *HeadObjectOutput) SetContentDisposition(v string) *HeadObjectOutput { + s.ContentDisposition = &v return s } -// SetIfModifiedSince sets the IfModifiedSince field's value. -func (s *GetObjectInput) SetIfModifiedSince(v time.Time) *GetObjectInput { - s.IfModifiedSince = &v +// SetContentEncoding sets the ContentEncoding field's value. +func (s *HeadObjectOutput) SetContentEncoding(v string) *HeadObjectOutput { + s.ContentEncoding = &v return s } -// SetIfNoneMatch sets the IfNoneMatch field's value. -func (s *GetObjectInput) SetIfNoneMatch(v string) *GetObjectInput { - s.IfNoneMatch = &v +// SetContentLanguage sets the ContentLanguage field's value. +func (s *HeadObjectOutput) SetContentLanguage(v string) *HeadObjectOutput { + s.ContentLanguage = &v return s } -// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. -func (s *GetObjectInput) SetIfUnmodifiedSince(v time.Time) *GetObjectInput { - s.IfUnmodifiedSince = &v +// SetContentLength sets the ContentLength field's value. +func (s *HeadObjectOutput) SetContentLength(v int64) *HeadObjectOutput { + s.ContentLength = &v return s } -// SetKey sets the Key field's value. -func (s *GetObjectInput) SetKey(v string) *GetObjectInput { - s.Key = &v +// SetContentType sets the ContentType field's value. +func (s *HeadObjectOutput) SetContentType(v string) *HeadObjectOutput { + s.ContentType = &v return s } -// SetPartNumber sets the PartNumber field's value. -func (s *GetObjectInput) SetPartNumber(v int64) *GetObjectInput { - s.PartNumber = &v +// SetDeleteMarker sets the DeleteMarker field's value. +func (s *HeadObjectOutput) SetDeleteMarker(v bool) *HeadObjectOutput { + s.DeleteMarker = &v return s } -// SetRange sets the Range field's value. -func (s *GetObjectInput) SetRange(v string) *GetObjectInput { - s.Range = &v +// SetETag sets the ETag field's value. +func (s *HeadObjectOutput) SetETag(v string) *HeadObjectOutput { + s.ETag = &v return s } -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectInput) SetRequestPayer(v string) *GetObjectInput { - s.RequestPayer = &v +// SetExpiration sets the Expiration field's value. +func (s *HeadObjectOutput) SetExpiration(v string) *HeadObjectOutput { + s.Expiration = &v return s } -// SetResponseCacheControl sets the ResponseCacheControl field's value. -func (s *GetObjectInput) SetResponseCacheControl(v string) *GetObjectInput { - s.ResponseCacheControl = &v +// SetExpires sets the Expires field's value. +func (s *HeadObjectOutput) SetExpires(v string) *HeadObjectOutput { + s.Expires = &v return s } -// SetResponseContentDisposition sets the ResponseContentDisposition field's value. -func (s *GetObjectInput) SetResponseContentDisposition(v string) *GetObjectInput { - s.ResponseContentDisposition = &v +// SetLastModified sets the LastModified field's value. +func (s *HeadObjectOutput) SetLastModified(v time.Time) *HeadObjectOutput { + s.LastModified = &v return s } -// SetResponseContentEncoding sets the ResponseContentEncoding field's value. -func (s *GetObjectInput) SetResponseContentEncoding(v string) *GetObjectInput { - s.ResponseContentEncoding = &v +// SetMetadata sets the Metadata field's value. +func (s *HeadObjectOutput) SetMetadata(v map[string]*string) *HeadObjectOutput { + s.Metadata = v return s } -// SetResponseContentLanguage sets the ResponseContentLanguage field's value. -func (s *GetObjectInput) SetResponseContentLanguage(v string) *GetObjectInput { - s.ResponseContentLanguage = &v +// SetMissingMeta sets the MissingMeta field's value. +func (s *HeadObjectOutput) SetMissingMeta(v int64) *HeadObjectOutput { + s.MissingMeta = &v return s } -// SetResponseContentType sets the ResponseContentType field's value. -func (s *GetObjectInput) SetResponseContentType(v string) *GetObjectInput { - s.ResponseContentType = &v +// SetObjectLockLegalHoldStatus sets the ObjectLockLegalHoldStatus field's value. +func (s *HeadObjectOutput) SetObjectLockLegalHoldStatus(v string) *HeadObjectOutput { + s.ObjectLockLegalHoldStatus = &v return s } -// SetResponseExpires sets the ResponseExpires field's value. -func (s *GetObjectInput) SetResponseExpires(v time.Time) *GetObjectInput { - s.ResponseExpires = &v +// SetObjectLockMode sets the ObjectLockMode field's value. +func (s *HeadObjectOutput) SetObjectLockMode(v string) *HeadObjectOutput { + s.ObjectLockMode = &v return s } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *GetObjectInput) SetSSECustomerAlgorithm(v string) *GetObjectInput { - s.SSECustomerAlgorithm = &v +// SetObjectLockRetainUntilDate sets the ObjectLockRetainUntilDate field's value. +func (s *HeadObjectOutput) SetObjectLockRetainUntilDate(v time.Time) *HeadObjectOutput { + s.ObjectLockRetainUntilDate = &v return s } -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *GetObjectInput) SetSSECustomerKey(v string) *GetObjectInput { - s.SSECustomerKey = &v +// SetPartsCount sets the PartsCount field's value. +func (s *HeadObjectOutput) SetPartsCount(v int64) *HeadObjectOutput { + s.PartsCount = &v return s } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *GetObjectInput) SetSSECustomerKeyMD5(v string) *GetObjectInput { - s.SSECustomerKeyMD5 = &v +// SetReplicationStatus sets the ReplicationStatus field's value. +func (s *HeadObjectOutput) SetReplicationStatus(v string) *HeadObjectOutput { + s.ReplicationStatus = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *GetObjectInput) SetVersionId(v string) *GetObjectInput { - s.VersionId = &v +// SetRequestCharged sets the RequestCharged field's value. +func (s *HeadObjectOutput) SetRequestCharged(v string) *HeadObjectOutput { + s.RequestCharged = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectOutput -type GetObjectOutput struct { - _ struct{} `type:"structure" payload:"Body"` - - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - - // Object data. - Body io.ReadCloser `type:"blob"` +// SetRestore sets the Restore field's value. +func (s *HeadObjectOutput) SetRestore(v string) *HeadObjectOutput { + s.Restore = &v + return s +} - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *HeadObjectOutput) SetSSECustomerAlgorithm(v string) *HeadObjectOutput { + s.SSECustomerAlgorithm = &v + return s +} - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *HeadObjectOutput) SetSSECustomerKeyMD5(v string) *HeadObjectOutput { + s.SSECustomerKeyMD5 = &v + return s +} - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *HeadObjectOutput) SetSSEKMSKeyId(v string) *HeadObjectOutput { + s.SSEKMSKeyId = &v + return s +} - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *HeadObjectOutput) SetServerSideEncryption(v string) *HeadObjectOutput { + s.ServerSideEncryption = &v + return s +} - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` +// SetStorageClass sets the StorageClass field's value. +func (s *HeadObjectOutput) SetStorageClass(v string) *HeadObjectOutput { + s.StorageClass = &v + return s +} - // The portion of the object returned in the response. - ContentRange *string `location:"header" locationName:"Content-Range" type:"string"` +// SetVersionId sets the VersionId field's value. +func (s *HeadObjectOutput) SetVersionId(v string) *HeadObjectOutput { + s.VersionId = &v + return s +} - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` +// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. +func (s *HeadObjectOutput) SetWebsiteRedirectLocation(v string) *HeadObjectOutput { + s.WebsiteRedirectLocation = &v + return s +} - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` +type IndexDocument struct { + _ struct{} `type:"structure"` - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` + // A suffix that is appended to a request that is for a directory on the website + // endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ + // the data that is returned will be for the object with the key name images/index.html) + // The suffix must not be empty and must not include a slash character. + // + // Suffix is a required field + Suffix *string `type:"string" required:"true"` +} - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` +// String returns the string representation +func (s IndexDocument) String() string { + return awsutil.Prettify(s) +} - // The date and time at which the object is no longer cacheable. - Expires *string `location:"header" locationName:"Expires" type:"string"` +// GoString returns the string representation +func (s IndexDocument) GoString() string { + return s.String() +} - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *IndexDocument) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "IndexDocument"} + if s.Suffix == nil { + invalidParams.Add(request.NewErrParamRequired("Suffix")) + } - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` +// SetSuffix sets the Suffix field's value. +func (s *IndexDocument) SetSuffix(v string) *IndexDocument { + s.Suffix = &v + return s +} - // The count of parts this object has. - PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` +type Initiator struct { + _ struct{} `type:"structure"` - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` + // Name of the Principal. + DisplayName *string `type:"string"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // If the principal is an AWS account, it provides the Canonical User ID. If + // the principal is an IAM User, it provides a user ARN value. + ID *string `type:"string"` +} - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` +// String returns the string representation +func (s Initiator) String() string { + return awsutil.Prettify(s) +} - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` +// GoString returns the string representation +func (s Initiator) GoString() string { + return s.String() +} - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` +// SetDisplayName sets the DisplayName field's value. +func (s *Initiator) SetDisplayName(v string) *Initiator { + s.DisplayName = &v + return s +} - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` +// SetID sets the ID field's value. +func (s *Initiator) SetID(v string) *Initiator { + s.ID = &v + return s +} - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` +// Describes the serialization format of the object. +type InputSerialization struct { + _ struct{} `type:"structure"` - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + // Describes the serialization of a CSV-encoded object. + CSV *CSVInput `type:"structure"` - // The number of tags, if any, on the object. - TagCount *int64 `location:"header" locationName:"x-amz-tagging-count" type:"integer"` + // Specifies object's compression format. Valid values: NONE, GZIP, BZIP2. Default + // Value: NONE. + CompressionType *string `type:"string" enum:"CompressionType"` - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Specifies JSON as object's input serialization format. + JSON *JSONInput `type:"structure"` - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` + // Specifies Parquet as object's input serialization format. + Parquet *ParquetInput `type:"structure"` } // String returns the string representation -func (s GetObjectOutput) String() string { +func (s InputSerialization) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectOutput) GoString() string { +func (s InputSerialization) GoString() string { return s.String() } -// SetAcceptRanges sets the AcceptRanges field's value. -func (s *GetObjectOutput) SetAcceptRanges(v string) *GetObjectOutput { - s.AcceptRanges = &v +// SetCSV sets the CSV field's value. +func (s *InputSerialization) SetCSV(v *CSVInput) *InputSerialization { + s.CSV = v return s } -// SetBody sets the Body field's value. -func (s *GetObjectOutput) SetBody(v io.ReadCloser) *GetObjectOutput { - s.Body = v +// SetCompressionType sets the CompressionType field's value. +func (s *InputSerialization) SetCompressionType(v string) *InputSerialization { + s.CompressionType = &v return s } -// SetCacheControl sets the CacheControl field's value. -func (s *GetObjectOutput) SetCacheControl(v string) *GetObjectOutput { - s.CacheControl = &v +// SetJSON sets the JSON field's value. +func (s *InputSerialization) SetJSON(v *JSONInput) *InputSerialization { + s.JSON = v return s } -// SetContentDisposition sets the ContentDisposition field's value. -func (s *GetObjectOutput) SetContentDisposition(v string) *GetObjectOutput { - s.ContentDisposition = &v +// SetParquet sets the Parquet field's value. +func (s *InputSerialization) SetParquet(v *ParquetInput) *InputSerialization { + s.Parquet = v return s } -// SetContentEncoding sets the ContentEncoding field's value. -func (s *GetObjectOutput) SetContentEncoding(v string) *GetObjectOutput { - s.ContentEncoding = &v - return s +type InventoryConfiguration struct { + _ struct{} `type:"structure"` + + // Contains information about where to publish the inventory results. + // + // Destination is a required field + Destination *InventoryDestination `type:"structure" required:"true"` + + // Specifies an inventory filter. The inventory only includes objects that meet + // the filter's criteria. + Filter *InventoryFilter `type:"structure"` + + // The ID used to identify the inventory configuration. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // Specifies which object version(s) to included in the inventory results. + // + // IncludedObjectVersions is a required field + IncludedObjectVersions *string `type:"string" required:"true" enum:"InventoryIncludedObjectVersions"` + + // Specifies whether the inventory is enabled or disabled. + // + // IsEnabled is a required field + IsEnabled *bool `type:"boolean" required:"true"` + + // Contains the optional fields that are included in the inventory results. + OptionalFields []*string `locationNameList:"Field" type:"list"` + + // Specifies the schedule for generating inventory results. + // + // Schedule is a required field + Schedule *InventorySchedule `type:"structure" required:"true"` } -// SetContentLanguage sets the ContentLanguage field's value. -func (s *GetObjectOutput) SetContentLanguage(v string) *GetObjectOutput { - s.ContentLanguage = &v - return s +// String returns the string representation +func (s InventoryConfiguration) String() string { + return awsutil.Prettify(s) } -// SetContentLength sets the ContentLength field's value. -func (s *GetObjectOutput) SetContentLength(v int64) *GetObjectOutput { - s.ContentLength = &v - return s +// GoString returns the string representation +func (s InventoryConfiguration) GoString() string { + return s.String() } -// SetContentRange sets the ContentRange field's value. -func (s *GetObjectOutput) SetContentRange(v string) *GetObjectOutput { - s.ContentRange = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *InventoryConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventoryConfiguration"} + if s.Destination == nil { + invalidParams.Add(request.NewErrParamRequired("Destination")) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.IncludedObjectVersions == nil { + invalidParams.Add(request.NewErrParamRequired("IncludedObjectVersions")) + } + if s.IsEnabled == nil { + invalidParams.Add(request.NewErrParamRequired("IsEnabled")) + } + if s.Schedule == nil { + invalidParams.Add(request.NewErrParamRequired("Schedule")) + } + if s.Destination != nil { + if err := s.Destination.Validate(); err != nil { + invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) + } + } + if s.Filter != nil { + if err := s.Filter.Validate(); err != nil { + invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + } + } + if s.Schedule != nil { + if err := s.Schedule.Validate(); err != nil { + invalidParams.AddNested("Schedule", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetContentType sets the ContentType field's value. -func (s *GetObjectOutput) SetContentType(v string) *GetObjectOutput { - s.ContentType = &v +// SetDestination sets the Destination field's value. +func (s *InventoryConfiguration) SetDestination(v *InventoryDestination) *InventoryConfiguration { + s.Destination = v return s } -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *GetObjectOutput) SetDeleteMarker(v bool) *GetObjectOutput { - s.DeleteMarker = &v +// SetFilter sets the Filter field's value. +func (s *InventoryConfiguration) SetFilter(v *InventoryFilter) *InventoryConfiguration { + s.Filter = v return s } -// SetETag sets the ETag field's value. -func (s *GetObjectOutput) SetETag(v string) *GetObjectOutput { - s.ETag = &v +// SetId sets the Id field's value. +func (s *InventoryConfiguration) SetId(v string) *InventoryConfiguration { + s.Id = &v return s } -// SetExpiration sets the Expiration field's value. -func (s *GetObjectOutput) SetExpiration(v string) *GetObjectOutput { - s.Expiration = &v +// SetIncludedObjectVersions sets the IncludedObjectVersions field's value. +func (s *InventoryConfiguration) SetIncludedObjectVersions(v string) *InventoryConfiguration { + s.IncludedObjectVersions = &v return s } -// SetExpires sets the Expires field's value. -func (s *GetObjectOutput) SetExpires(v string) *GetObjectOutput { - s.Expires = &v +// SetIsEnabled sets the IsEnabled field's value. +func (s *InventoryConfiguration) SetIsEnabled(v bool) *InventoryConfiguration { + s.IsEnabled = &v return s } -// SetLastModified sets the LastModified field's value. -func (s *GetObjectOutput) SetLastModified(v time.Time) *GetObjectOutput { - s.LastModified = &v +// SetOptionalFields sets the OptionalFields field's value. +func (s *InventoryConfiguration) SetOptionalFields(v []*string) *InventoryConfiguration { + s.OptionalFields = v return s } -// SetMetadata sets the Metadata field's value. -func (s *GetObjectOutput) SetMetadata(v map[string]*string) *GetObjectOutput { - s.Metadata = v +// SetSchedule sets the Schedule field's value. +func (s *InventoryConfiguration) SetSchedule(v *InventorySchedule) *InventoryConfiguration { + s.Schedule = v return s } -// SetMissingMeta sets the MissingMeta field's value. -func (s *GetObjectOutput) SetMissingMeta(v int64) *GetObjectOutput { - s.MissingMeta = &v - return s +type InventoryDestination struct { + _ struct{} `type:"structure"` + + // Contains the bucket name, file format, bucket owner (optional), and prefix + // (optional) where inventory results are published. + // + // S3BucketDestination is a required field + S3BucketDestination *InventoryS3BucketDestination `type:"structure" required:"true"` +} + +// String returns the string representation +func (s InventoryDestination) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InventoryDestination) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InventoryDestination) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventoryDestination"} + if s.S3BucketDestination == nil { + invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) + } + if s.S3BucketDestination != nil { + if err := s.S3BucketDestination.Validate(); err != nil { + invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPartsCount sets the PartsCount field's value. -func (s *GetObjectOutput) SetPartsCount(v int64) *GetObjectOutput { - s.PartsCount = &v +// SetS3BucketDestination sets the S3BucketDestination field's value. +func (s *InventoryDestination) SetS3BucketDestination(v *InventoryS3BucketDestination) *InventoryDestination { + s.S3BucketDestination = v return s } -// SetReplicationStatus sets the ReplicationStatus field's value. -func (s *GetObjectOutput) SetReplicationStatus(v string) *GetObjectOutput { - s.ReplicationStatus = &v - return s +// Contains the type of server-side encryption used to encrypt the inventory +// results. +type InventoryEncryption struct { + _ struct{} `type:"structure"` + + // Specifies the use of SSE-KMS to encrypt delivered Inventory reports. + SSEKMS *SSEKMS `locationName:"SSE-KMS" type:"structure"` + + // Specifies the use of SSE-S3 to encrypt delivered Inventory reports. + SSES3 *SSES3 `locationName:"SSE-S3" type:"structure"` } -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectOutput) SetRequestCharged(v string) *GetObjectOutput { - s.RequestCharged = &v - return s +// String returns the string representation +func (s InventoryEncryption) String() string { + return awsutil.Prettify(s) } -// SetRestore sets the Restore field's value. -func (s *GetObjectOutput) SetRestore(v string) *GetObjectOutput { - s.Restore = &v - return s +// GoString returns the string representation +func (s InventoryEncryption) GoString() string { + return s.String() } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *GetObjectOutput) SetSSECustomerAlgorithm(v string) *GetObjectOutput { - s.SSECustomerAlgorithm = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *InventoryEncryption) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventoryEncryption"} + if s.SSEKMS != nil { + if err := s.SSEKMS.Validate(); err != nil { + invalidParams.AddNested("SSEKMS", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *GetObjectOutput) SetSSECustomerKeyMD5(v string) *GetObjectOutput { - s.SSECustomerKeyMD5 = &v +// SetSSEKMS sets the SSEKMS field's value. +func (s *InventoryEncryption) SetSSEKMS(v *SSEKMS) *InventoryEncryption { + s.SSEKMS = v return s } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *GetObjectOutput) SetSSEKMSKeyId(v string) *GetObjectOutput { - s.SSEKMSKeyId = &v +// SetSSES3 sets the SSES3 field's value. +func (s *InventoryEncryption) SetSSES3(v *SSES3) *InventoryEncryption { + s.SSES3 = v return s } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *GetObjectOutput) SetServerSideEncryption(v string) *GetObjectOutput { - s.ServerSideEncryption = &v - return s +type InventoryFilter struct { + _ struct{} `type:"structure"` + + // The prefix that an object must have to be included in the inventory results. + // + // Prefix is a required field + Prefix *string `type:"string" required:"true"` } -// SetStorageClass sets the StorageClass field's value. -func (s *GetObjectOutput) SetStorageClass(v string) *GetObjectOutput { - s.StorageClass = &v - return s +// String returns the string representation +func (s InventoryFilter) String() string { + return awsutil.Prettify(s) } -// SetTagCount sets the TagCount field's value. -func (s *GetObjectOutput) SetTagCount(v int64) *GetObjectOutput { - s.TagCount = &v - return s +// GoString returns the string representation +func (s InventoryFilter) GoString() string { + return s.String() } -// SetVersionId sets the VersionId field's value. -func (s *GetObjectOutput) SetVersionId(v string) *GetObjectOutput { - s.VersionId = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *InventoryFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventoryFilter"} + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *GetObjectOutput) SetWebsiteRedirectLocation(v string) *GetObjectOutput { - s.WebsiteRedirectLocation = &v +// SetPrefix sets the Prefix field's value. +func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { + s.Prefix = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingRequest -type GetObjectTaggingInput struct { +type InventoryS3BucketDestination struct { _ struct{} `type:"structure"` + // The ID of the account that owns the destination bucket. + AccountId *string `type:"string"` + + // The Amazon resource name (ARN) of the bucket where inventory results will + // be published. + // // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + Bucket *string `type:"string" required:"true"` - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Contains the type of server-side encryption used to encrypt the inventory + // results. + Encryption *InventoryEncryption `type:"structure"` - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` + // Specifies the output format of the inventory results. + // + // Format is a required field + Format *string `type:"string" required:"true" enum:"InventoryFormat"` + + // The prefix that is prepended to all inventory results. + Prefix *string `type:"string"` } // String returns the string representation -func (s GetObjectTaggingInput) String() string { +func (s InventoryS3BucketDestination) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectTaggingInput) GoString() string { +func (s InventoryS3BucketDestination) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectTaggingInput"} +func (s *InventoryS3BucketDestination) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventoryS3BucketDestination"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Encryption != nil { + if err := s.Encryption.Validate(); err != nil { + invalidParams.AddNested("Encryption", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -11180,178 +14995,257 @@ func (s *GetObjectTaggingInput) Validate() error { return nil } +// SetAccountId sets the AccountId field's value. +func (s *InventoryS3BucketDestination) SetAccountId(v string) *InventoryS3BucketDestination { + s.AccountId = &v + return s +} + // SetBucket sets the Bucket field's value. -func (s *GetObjectTaggingInput) SetBucket(v string) *GetObjectTaggingInput { +func (s *InventoryS3BucketDestination) SetBucket(v string) *InventoryS3BucketDestination { s.Bucket = &v return s } -// SetKey sets the Key field's value. -func (s *GetObjectTaggingInput) SetKey(v string) *GetObjectTaggingInput { - s.Key = &v +func (s *InventoryS3BucketDestination) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetEncryption sets the Encryption field's value. +func (s *InventoryS3BucketDestination) SetEncryption(v *InventoryEncryption) *InventoryS3BucketDestination { + s.Encryption = v return s } -// SetVersionId sets the VersionId field's value. -func (s *GetObjectTaggingInput) SetVersionId(v string) *GetObjectTaggingInput { - s.VersionId = &v +// SetFormat sets the Format field's value. +func (s *InventoryS3BucketDestination) SetFormat(v string) *InventoryS3BucketDestination { + s.Format = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingOutput -type GetObjectTaggingOutput struct { - _ struct{} `type:"structure"` +// SetPrefix sets the Prefix field's value. +func (s *InventoryS3BucketDestination) SetPrefix(v string) *InventoryS3BucketDestination { + s.Prefix = &v + return s +} - // TagSet is a required field - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` +type InventorySchedule struct { + _ struct{} `type:"structure"` - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Specifies how frequently inventory results are produced. + // + // Frequency is a required field + Frequency *string `type:"string" required:"true" enum:"InventoryFrequency"` } // String returns the string representation -func (s GetObjectTaggingOutput) String() string { +func (s InventorySchedule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectTaggingOutput) GoString() string { +func (s InventorySchedule) GoString() string { return s.String() } -// SetTagSet sets the TagSet field's value. -func (s *GetObjectTaggingOutput) SetTagSet(v []*Tag) *GetObjectTaggingOutput { - s.TagSet = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *InventorySchedule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InventorySchedule"} + if s.Frequency == nil { + invalidParams.Add(request.NewErrParamRequired("Frequency")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetVersionId sets the VersionId field's value. -func (s *GetObjectTaggingOutput) SetVersionId(v string) *GetObjectTaggingOutput { - s.VersionId = &v +// SetFrequency sets the Frequency field's value. +func (s *InventorySchedule) SetFrequency(v string) *InventorySchedule { + s.Frequency = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentRequest -type GetObjectTorrentInput struct { +type JSONInput struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The type of JSON. Valid values: Document, Lines. + Type *string `type:"string" enum:"JSONType"` +} - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` +// String returns the string representation +func (s JSONInput) String() string { + return awsutil.Prettify(s) +} - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` +// GoString returns the string representation +func (s JSONInput) GoString() string { + return s.String() +} + +// SetType sets the Type field's value. +func (s *JSONInput) SetType(v string) *JSONInput { + s.Type = &v + return s +} + +type JSONOutput struct { + _ struct{} `type:"structure"` + + // The value used to separate individual records in the output. + RecordDelimiter *string `type:"string"` } // String returns the string representation -func (s GetObjectTorrentInput) String() string { +func (s JSONOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectTorrentInput) GoString() string { +func (s JSONOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectTorrentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectTorrentInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } +// SetRecordDelimiter sets the RecordDelimiter field's value. +func (s *JSONOutput) SetRecordDelimiter(v string) *JSONOutput { + s.RecordDelimiter = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// A container for object key name prefix and suffix filtering rules. +type KeyFilter struct { + _ struct{} `type:"structure"` + + // A list of containers for the key value pair that defines the criteria for + // the filter rule. + FilterRules []*FilterRule `locationName:"FilterRule" type:"list" flattened:"true"` } -// SetBucket sets the Bucket field's value. -func (s *GetObjectTorrentInput) SetBucket(v string) *GetObjectTorrentInput { - s.Bucket = &v - return s +// String returns the string representation +func (s KeyFilter) String() string { + return awsutil.Prettify(s) } -// SetKey sets the Key field's value. -func (s *GetObjectTorrentInput) SetKey(v string) *GetObjectTorrentInput { - s.Key = &v - return s +// GoString returns the string representation +func (s KeyFilter) GoString() string { + return s.String() } -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectTorrentInput) SetRequestPayer(v string) *GetObjectTorrentInput { - s.RequestPayer = &v +// SetFilterRules sets the FilterRules field's value. +func (s *KeyFilter) SetFilterRules(v []*FilterRule) *KeyFilter { + s.FilterRules = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentOutput -type GetObjectTorrentOutput struct { - _ struct{} `type:"structure" payload:"Body"` +// A container for specifying the configuration for AWS Lambda notifications. +type LambdaFunctionConfiguration struct { + _ struct{} `type:"structure"` - Body io.ReadCloser `type:"blob"` + // Events is a required field + Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // A container for object key name filtering rules. For information about key + // name filtering, see Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Filter *NotificationConfigurationFilter `type:"structure"` + + // An optional unique identifier for configurations in a notification configuration. + // If you don't provide one, Amazon S3 will assign an ID. + Id *string `type:"string"` + + // The Amazon Resource Name (ARN) of the Lambda cloud function that Amazon S3 + // can invoke when it detects events of the specified type. + // + // LambdaFunctionArn is a required field + LambdaFunctionArn *string `locationName:"CloudFunction" type:"string" required:"true"` } // String returns the string representation -func (s GetObjectTorrentOutput) String() string { +func (s LambdaFunctionConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetObjectTorrentOutput) GoString() string { +func (s LambdaFunctionConfiguration) GoString() string { return s.String() } -// SetBody sets the Body field's value. -func (s *GetObjectTorrentOutput) SetBody(v io.ReadCloser) *GetObjectTorrentOutput { - s.Body = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *LambdaFunctionConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionConfiguration"} + if s.Events == nil { + invalidParams.Add(request.NewErrParamRequired("Events")) + } + if s.LambdaFunctionArn == nil { + invalidParams.Add(request.NewErrParamRequired("LambdaFunctionArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEvents sets the Events field's value. +func (s *LambdaFunctionConfiguration) SetEvents(v []*string) *LambdaFunctionConfiguration { + s.Events = v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectTorrentOutput) SetRequestCharged(v string) *GetObjectTorrentOutput { - s.RequestCharged = &v +// SetFilter sets the Filter field's value. +func (s *LambdaFunctionConfiguration) SetFilter(v *NotificationConfigurationFilter) *LambdaFunctionConfiguration { + s.Filter = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GlacierJobParameters -type GlacierJobParameters struct { +// SetId sets the Id field's value. +func (s *LambdaFunctionConfiguration) SetId(v string) *LambdaFunctionConfiguration { + s.Id = &v + return s +} + +// SetLambdaFunctionArn sets the LambdaFunctionArn field's value. +func (s *LambdaFunctionConfiguration) SetLambdaFunctionArn(v string) *LambdaFunctionConfiguration { + s.LambdaFunctionArn = &v + return s +} + +type LifecycleConfiguration struct { _ struct{} `type:"structure"` - // Glacier retrieval tier at which the restore will be processed. - // - // Tier is a required field - Tier *string `type:"string" required:"true" enum:"Tier"` + // Rules is a required field + Rules []*Rule `locationName:"Rule" type:"list" flattened:"true" required:"true"` } // String returns the string representation -func (s GlacierJobParameters) String() string { +func (s LifecycleConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GlacierJobParameters) GoString() string { +func (s LifecycleConfiguration) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GlacierJobParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GlacierJobParameters"} - if s.Tier == nil { - invalidParams.Add(request.NewErrParamRequired("Tier")) +func (s *LifecycleConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LifecycleConfiguration"} + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) + } + if s.Rules != nil { + for i, v := range s.Rules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -11360,96 +15254,118 @@ func (s *GlacierJobParameters) Validate() error { return nil } -// SetTier sets the Tier field's value. -func (s *GlacierJobParameters) SetTier(v string) *GlacierJobParameters { - s.Tier = &v +// SetRules sets the Rules field's value. +func (s *LifecycleConfiguration) SetRules(v []*Rule) *LifecycleConfiguration { + s.Rules = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grant -type Grant struct { +type LifecycleExpiration struct { _ struct{} `type:"structure"` - Grantee *Grantee `type:"structure"` + // Indicates at what date the object is to be moved or deleted. Should be in + // GMT ISO 8601 Format. + Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` + + // Indicates the lifetime, in days, of the objects that are subject to the rule. + // The value must be a non-zero positive integer. + Days *int64 `type:"integer"` - // Specifies the permission given to the grantee. - Permission *string `type:"string" enum:"Permission"` + // Indicates whether Amazon S3 will remove a delete marker with no noncurrent + // versions. If set to true, the delete marker will be expired; if set to false + // the policy takes no action. This cannot be specified with Days or Date in + // a Lifecycle Expiration Policy. + ExpiredObjectDeleteMarker *bool `type:"boolean"` } // String returns the string representation -func (s Grant) String() string { +func (s LifecycleExpiration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Grant) GoString() string { +func (s LifecycleExpiration) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *Grant) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Grant"} - if s.Grantee != nil { - if err := s.Grantee.Validate(); err != nil { - invalidParams.AddNested("Grantee", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDate sets the Date field's value. +func (s *LifecycleExpiration) SetDate(v time.Time) *LifecycleExpiration { + s.Date = &v + return s } -// SetGrantee sets the Grantee field's value. -func (s *Grant) SetGrantee(v *Grantee) *Grant { - s.Grantee = v +// SetDays sets the Days field's value. +func (s *LifecycleExpiration) SetDays(v int64) *LifecycleExpiration { + s.Days = &v return s } -// SetPermission sets the Permission field's value. -func (s *Grant) SetPermission(v string) *Grant { - s.Permission = &v +// SetExpiredObjectDeleteMarker sets the ExpiredObjectDeleteMarker field's value. +func (s *LifecycleExpiration) SetExpiredObjectDeleteMarker(v bool) *LifecycleExpiration { + s.ExpiredObjectDeleteMarker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grantee -type Grantee struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` +type LifecycleRule struct { + _ struct{} `type:"structure"` - // Screen name of the grantee. - DisplayName *string `type:"string"` + // Specifies the days since the initiation of an Incomplete Multipart Upload + // that Lifecycle will wait before permanently removing all parts of the upload. + AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` - // Email address of the grantee. - EmailAddress *string `type:"string"` + Expiration *LifecycleExpiration `type:"structure"` - // The canonical user ID of the grantee. + // The Filter is used to identify objects that a Lifecycle Rule applies to. + // A Filter must have exactly one of Prefix, Tag, or And specified. + Filter *LifecycleRuleFilter `type:"structure"` + + // Unique identifier for the rule. The value cannot be longer than 255 characters. ID *string `type:"string"` - // Type of grantee + // Specifies when noncurrent object versions expire. Upon expiration, Amazon + // S3 permanently deletes the noncurrent object versions. You set this lifecycle + // configuration action on a bucket that has versioning enabled (or suspended) + // to request that Amazon S3 delete noncurrent object versions at a specific + // period in the object's lifetime. + NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` + + NoncurrentVersionTransitions []*NoncurrentVersionTransition `locationName:"NoncurrentVersionTransition" type:"list" flattened:"true"` + + // Prefix identifying one or more objects to which the rule applies. This is + // deprecated; use Filter instead. // - // Type is a required field - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true" required:"true" enum:"Type"` + // Deprecated: Prefix has been deprecated + Prefix *string `deprecated:"true" type:"string"` - // URI of the grantee group. - URI *string `type:"string"` + // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule + // is not currently being applied. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"ExpirationStatus"` + + Transitions []*Transition `locationName:"Transition" type:"list" flattened:"true"` } // String returns the string representation -func (s Grantee) String() string { +func (s LifecycleRule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Grantee) GoString() string { +func (s LifecycleRule) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Grantee) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Grantee"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) +func (s *LifecycleRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LifecycleRule"} + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) + } + if s.Filter != nil { + if err := s.Filter.Validate(); err != nil { + invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -11458,59 +15374,95 @@ func (s *Grantee) Validate() error { return nil } -// SetDisplayName sets the DisplayName field's value. -func (s *Grantee) SetDisplayName(v string) *Grantee { - s.DisplayName = &v +// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. +func (s *LifecycleRule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *LifecycleRule { + s.AbortIncompleteMultipartUpload = v return s } -// SetEmailAddress sets the EmailAddress field's value. -func (s *Grantee) SetEmailAddress(v string) *Grantee { - s.EmailAddress = &v +// SetExpiration sets the Expiration field's value. +func (s *LifecycleRule) SetExpiration(v *LifecycleExpiration) *LifecycleRule { + s.Expiration = v + return s +} + +// SetFilter sets the Filter field's value. +func (s *LifecycleRule) SetFilter(v *LifecycleRuleFilter) *LifecycleRule { + s.Filter = v return s } // SetID sets the ID field's value. -func (s *Grantee) SetID(v string) *Grantee { +func (s *LifecycleRule) SetID(v string) *LifecycleRule { s.ID = &v return s } -// SetType sets the Type field's value. -func (s *Grantee) SetType(v string) *Grantee { - s.Type = &v +// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. +func (s *LifecycleRule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *LifecycleRule { + s.NoncurrentVersionExpiration = v return s } -// SetURI sets the URI field's value. -func (s *Grantee) SetURI(v string) *Grantee { - s.URI = &v +// SetNoncurrentVersionTransitions sets the NoncurrentVersionTransitions field's value. +func (s *LifecycleRule) SetNoncurrentVersionTransitions(v []*NoncurrentVersionTransition) *LifecycleRule { + s.NoncurrentVersionTransitions = v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *LifecycleRule) SetPrefix(v string) *LifecycleRule { + s.Prefix = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *LifecycleRule) SetStatus(v string) *LifecycleRule { + s.Status = &v + return s +} + +// SetTransitions sets the Transitions field's value. +func (s *LifecycleRule) SetTransitions(v []*Transition) *LifecycleRule { + s.Transitions = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketRequest -type HeadBucketInput struct { +// This is used in a Lifecycle Rule Filter to apply a logical AND to two or +// more predicates. The Lifecycle Rule will apply to any object matching all +// of the predicates configured inside the And operator. +type LifecycleRuleAndOperator struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + Prefix *string `type:"string"` + + // All of these tags must exist in the object's tag set in order for the rule + // to apply. + Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` } // String returns the string representation -func (s HeadBucketInput) String() string { +func (s LifecycleRuleAndOperator) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HeadBucketInput) GoString() string { +func (s LifecycleRuleAndOperator) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HeadBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HeadBucketInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *LifecycleRuleAndOperator) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleAndOperator"} + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -11519,109 +15471,57 @@ func (s *HeadBucketInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *HeadBucketInput) SetBucket(v string) *HeadBucketInput { - s.Bucket = &v +// SetPrefix sets the Prefix field's value. +func (s *LifecycleRuleAndOperator) SetPrefix(v string) *LifecycleRuleAndOperator { + s.Prefix = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketOutput -type HeadBucketOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s HeadBucketOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HeadBucketOutput) GoString() string { - return s.String() +// SetTags sets the Tags field's value. +func (s *LifecycleRuleAndOperator) SetTags(v []*Tag) *LifecycleRuleAndOperator { + s.Tags = v + return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectRequest -type HeadObjectInput struct { +// The Filter is used to identify objects that a Lifecycle Rule applies to. +// A Filter must have exactly one of Prefix, Tag, or And specified. +type LifecycleRuleFilter struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` - - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` - - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Part number of the object being read. This is a positive integer between - // 1 and 10,000. Effectively performs a 'ranged' HEAD request for the part specified. - // Useful querying about the size of the part and the number of parts in this - // object. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` - - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` + // This is used in a Lifecycle Rule Filter to apply a logical AND to two or + // more predicates. The Lifecycle Rule will apply to any object matching all + // of the predicates configured inside the And operator. + And *LifecycleRuleAndOperator `type:"structure"` - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // Prefix identifying one or more objects to which the rule applies. + Prefix *string `type:"string"` - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` + // This tag must exist in the object's tag set in order for the rule to apply. + Tag *Tag `type:"structure"` } // String returns the string representation -func (s HeadObjectInput) String() string { +func (s LifecycleRuleFilter) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HeadObjectInput) GoString() string { +func (s LifecycleRuleFilter) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HeadObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HeadObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) +func (s *LifecycleRuleFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleFilter"} + if s.And != nil { + if err := s.And.Validate(); err != nil { + invalidParams.AddNested("And", err.(request.ErrInvalidParams)) + } } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Tag != nil { + if err := s.Tag.Validate(); err != nil { + invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -11630,369 +15530,464 @@ func (s *HeadObjectInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *HeadObjectInput) SetBucket(v string) *HeadObjectInput { - s.Bucket = &v +// SetAnd sets the And field's value. +func (s *LifecycleRuleFilter) SetAnd(v *LifecycleRuleAndOperator) *LifecycleRuleFilter { + s.And = v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *HeadObjectInput) SetIfMatch(v string) *HeadObjectInput { - s.IfMatch = &v +// SetPrefix sets the Prefix field's value. +func (s *LifecycleRuleFilter) SetPrefix(v string) *LifecycleRuleFilter { + s.Prefix = &v return s } -// SetIfModifiedSince sets the IfModifiedSince field's value. -func (s *HeadObjectInput) SetIfModifiedSince(v time.Time) *HeadObjectInput { - s.IfModifiedSince = &v +// SetTag sets the Tag field's value. +func (s *LifecycleRuleFilter) SetTag(v *Tag) *LifecycleRuleFilter { + s.Tag = v return s } -// SetIfNoneMatch sets the IfNoneMatch field's value. -func (s *HeadObjectInput) SetIfNoneMatch(v string) *HeadObjectInput { - s.IfNoneMatch = &v - return s -} +type ListBucketAnalyticsConfigurationsInput struct { + _ struct{} `type:"structure"` -// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. -func (s *HeadObjectInput) SetIfUnmodifiedSince(v time.Time) *HeadObjectInput { - s.IfUnmodifiedSince = &v - return s -} + // The name of the bucket from which analytics configurations are retrieved. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -// SetKey sets the Key field's value. -func (s *HeadObjectInput) SetKey(v string) *HeadObjectInput { - s.Key = &v - return s + // The ContinuationToken that represents a placeholder from where this request + // should begin. + ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` } -// SetPartNumber sets the PartNumber field's value. -func (s *HeadObjectInput) SetPartNumber(v int64) *HeadObjectInput { - s.PartNumber = &v - return s +// String returns the string representation +func (s ListBucketAnalyticsConfigurationsInput) String() string { + return awsutil.Prettify(s) } -// SetRange sets the Range field's value. -func (s *HeadObjectInput) SetRange(v string) *HeadObjectInput { - s.Range = &v - return s +// GoString returns the string representation +func (s ListBucketAnalyticsConfigurationsInput) GoString() string { + return s.String() } -// SetRequestPayer sets the RequestPayer field's value. -func (s *HeadObjectInput) SetRequestPayer(v string) *HeadObjectInput { - s.RequestPayer = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListBucketAnalyticsConfigurationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBucketAnalyticsConfigurationsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *HeadObjectInput) SetSSECustomerAlgorithm(v string) *HeadObjectInput { - s.SSECustomerAlgorithm = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *HeadObjectInput) SetSSECustomerKey(v string) *HeadObjectInput { - s.SSECustomerKey = &v +// SetBucket sets the Bucket field's value. +func (s *ListBucketAnalyticsConfigurationsInput) SetBucket(v string) *ListBucketAnalyticsConfigurationsInput { + s.Bucket = &v return s } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *HeadObjectInput) SetSSECustomerKeyMD5(v string) *HeadObjectInput { - s.SSECustomerKeyMD5 = &v - return s +func (s *ListBucketAnalyticsConfigurationsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetVersionId sets the VersionId field's value. -func (s *HeadObjectInput) SetVersionId(v string) *HeadObjectInput { - s.VersionId = &v +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketAnalyticsConfigurationsInput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsInput { + s.ContinuationToken = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectOutput -type HeadObjectOutput struct { +type ListBucketAnalyticsConfigurationsOutput struct { _ struct{} `type:"structure"` - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` + // The list of analytics configurations for a bucket. + AnalyticsConfigurationList []*AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"list" flattened:"true"` - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + // The ContinuationToken that represents where this request began. + ContinuationToken *string `type:"string"` - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + // Indicates whether the returned list of analytics configurations is complete. + // A value of true indicates that the list is not complete and the NextContinuationToken + // will be provided for a subsequent request. + IsTruncated *bool `type:"boolean"` - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + // NextContinuationToken is sent when isTruncated is true, which indicates that + // there are more analytics configurations to list. The next request must include + // this NextContinuationToken. The token is obfuscated and is not a usable value. + NextContinuationToken *string `type:"string"` +} - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` +// String returns the string representation +func (s ListBucketAnalyticsConfigurationsOutput) String() string { + return awsutil.Prettify(s) +} - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` +// GoString returns the string representation +func (s ListBucketAnalyticsConfigurationsOutput) GoString() string { + return s.String() +} - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` +// SetAnalyticsConfigurationList sets the AnalyticsConfigurationList field's value. +func (s *ListBucketAnalyticsConfigurationsOutput) SetAnalyticsConfigurationList(v []*AnalyticsConfiguration) *ListBucketAnalyticsConfigurationsOutput { + s.AnalyticsConfigurationList = v + return s +} - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketAnalyticsConfigurationsOutput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { + s.ContinuationToken = &v + return s +} - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListBucketAnalyticsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketAnalyticsConfigurationsOutput { + s.IsTruncated = &v + return s +} - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` +// SetNextContinuationToken sets the NextContinuationToken field's value. +func (s *ListBucketAnalyticsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { + s.NextContinuationToken = &v + return s +} - // The date and time at which the object is no longer cacheable. - Expires *string `location:"header" locationName:"Expires" type:"string"` +type ListBucketInventoryConfigurationsInput struct { + _ struct{} `type:"structure"` - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` + // The name of the bucket containing the inventory configurations to retrieve. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + // The marker used to continue an inventory configuration listing that has been + // truncated. Use the NextContinuationToken from a previously truncated list + // response to continue the listing. The continuation token is an opaque value + // that Amazon S3 understands. + ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` +} - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` +// String returns the string representation +func (s ListBucketInventoryConfigurationsInput) String() string { + return awsutil.Prettify(s) +} - // The count of parts this object has. - PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` +// GoString returns the string representation +func (s ListBucketInventoryConfigurationsInput) GoString() string { + return s.String() +} - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListBucketInventoryConfigurationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBucketInventoryConfigurationsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` +// SetBucket sets the Bucket field's value. +func (s *ListBucketInventoryConfigurationsInput) SetBucket(v string) *ListBucketInventoryConfigurationsInput { + s.Bucket = &v + return s +} - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` +func (s *ListBucketInventoryConfigurationsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketInventoryConfigurationsInput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsInput { + s.ContinuationToken = &v + return s +} - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` +type ListBucketInventoryConfigurationsOutput struct { + _ struct{} `type:"structure"` - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + // If sent in the request, the marker that is used as a starting point for this + // inventory configuration list response. + ContinuationToken *string `type:"string"` - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + // The list of inventory configurations for a bucket. + InventoryConfigurationList []*InventoryConfiguration `locationName:"InventoryConfiguration" type:"list" flattened:"true"` - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Indicates whether the returned list of inventory configurations is truncated + // in this response. A value of true indicates that the list is truncated. + IsTruncated *bool `type:"boolean"` - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` + // The marker used to continue this inventory configuration listing. Use the + // NextContinuationToken from this response to continue the listing in a subsequent + // request. The continuation token is an opaque value that Amazon S3 understands. + NextContinuationToken *string `type:"string"` } // String returns the string representation -func (s HeadObjectOutput) String() string { +func (s ListBucketInventoryConfigurationsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HeadObjectOutput) GoString() string { +func (s ListBucketInventoryConfigurationsOutput) GoString() string { return s.String() } -// SetAcceptRanges sets the AcceptRanges field's value. -func (s *HeadObjectOutput) SetAcceptRanges(v string) *HeadObjectOutput { - s.AcceptRanges = &v +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketInventoryConfigurationsOutput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { + s.ContinuationToken = &v return s } -// SetCacheControl sets the CacheControl field's value. -func (s *HeadObjectOutput) SetCacheControl(v string) *HeadObjectOutput { - s.CacheControl = &v +// SetInventoryConfigurationList sets the InventoryConfigurationList field's value. +func (s *ListBucketInventoryConfigurationsOutput) SetInventoryConfigurationList(v []*InventoryConfiguration) *ListBucketInventoryConfigurationsOutput { + s.InventoryConfigurationList = v return s } -// SetContentDisposition sets the ContentDisposition field's value. -func (s *HeadObjectOutput) SetContentDisposition(v string) *HeadObjectOutput { - s.ContentDisposition = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListBucketInventoryConfigurationsOutput) SetIsTruncated(v bool) *ListBucketInventoryConfigurationsOutput { + s.IsTruncated = &v return s } -// SetContentEncoding sets the ContentEncoding field's value. -func (s *HeadObjectOutput) SetContentEncoding(v string) *HeadObjectOutput { - s.ContentEncoding = &v +// SetNextContinuationToken sets the NextContinuationToken field's value. +func (s *ListBucketInventoryConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { + s.NextContinuationToken = &v return s } -// SetContentLanguage sets the ContentLanguage field's value. -func (s *HeadObjectOutput) SetContentLanguage(v string) *HeadObjectOutput { - s.ContentLanguage = &v - return s +type ListBucketMetricsConfigurationsInput struct { + _ struct{} `type:"structure"` + + // The name of the bucket containing the metrics configurations to retrieve. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The marker that is used to continue a metrics configuration listing that + // has been truncated. Use the NextContinuationToken from a previously truncated + // list response to continue the listing. The continuation token is an opaque + // value that Amazon S3 understands. + ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` } -// SetContentLength sets the ContentLength field's value. -func (s *HeadObjectOutput) SetContentLength(v int64) *HeadObjectOutput { - s.ContentLength = &v - return s +// String returns the string representation +func (s ListBucketMetricsConfigurationsInput) String() string { + return awsutil.Prettify(s) } -// SetContentType sets the ContentType field's value. -func (s *HeadObjectOutput) SetContentType(v string) *HeadObjectOutput { - s.ContentType = &v - return s +// GoString returns the string representation +func (s ListBucketMetricsConfigurationsInput) GoString() string { + return s.String() } -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *HeadObjectOutput) SetDeleteMarker(v bool) *HeadObjectOutput { - s.DeleteMarker = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListBucketMetricsConfigurationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBucketMetricsConfigurationsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetETag sets the ETag field's value. -func (s *HeadObjectOutput) SetETag(v string) *HeadObjectOutput { - s.ETag = &v +// SetBucket sets the Bucket field's value. +func (s *ListBucketMetricsConfigurationsInput) SetBucket(v string) *ListBucketMetricsConfigurationsInput { + s.Bucket = &v return s } -// SetExpiration sets the Expiration field's value. -func (s *HeadObjectOutput) SetExpiration(v string) *HeadObjectOutput { - s.Expiration = &v +func (s *ListBucketMetricsConfigurationsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketMetricsConfigurationsInput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsInput { + s.ContinuationToken = &v return s } -// SetExpires sets the Expires field's value. -func (s *HeadObjectOutput) SetExpires(v string) *HeadObjectOutput { - s.Expires = &v - return s +type ListBucketMetricsConfigurationsOutput struct { + _ struct{} `type:"structure"` + + // The marker that is used as a starting point for this metrics configuration + // list response. This value is present if it was sent in the request. + ContinuationToken *string `type:"string"` + + // Indicates whether the returned list of metrics configurations is complete. + // A value of true indicates that the list is not complete and the NextContinuationToken + // will be provided for a subsequent request. + IsTruncated *bool `type:"boolean"` + + // The list of metrics configurations for a bucket. + MetricsConfigurationList []*MetricsConfiguration `locationName:"MetricsConfiguration" type:"list" flattened:"true"` + + // The marker used to continue a metrics configuration listing that has been + // truncated. Use the NextContinuationToken from a previously truncated list + // response to continue the listing. The continuation token is an opaque value + // that Amazon S3 understands. + NextContinuationToken *string `type:"string"` +} + +// String returns the string representation +func (s ListBucketMetricsConfigurationsOutput) String() string { + return awsutil.Prettify(s) } -// SetLastModified sets the LastModified field's value. -func (s *HeadObjectOutput) SetLastModified(v time.Time) *HeadObjectOutput { - s.LastModified = &v - return s +// GoString returns the string representation +func (s ListBucketMetricsConfigurationsOutput) GoString() string { + return s.String() } -// SetMetadata sets the Metadata field's value. -func (s *HeadObjectOutput) SetMetadata(v map[string]*string) *HeadObjectOutput { - s.Metadata = v +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListBucketMetricsConfigurationsOutput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { + s.ContinuationToken = &v return s } -// SetMissingMeta sets the MissingMeta field's value. -func (s *HeadObjectOutput) SetMissingMeta(v int64) *HeadObjectOutput { - s.MissingMeta = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListBucketMetricsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketMetricsConfigurationsOutput { + s.IsTruncated = &v return s } -// SetPartsCount sets the PartsCount field's value. -func (s *HeadObjectOutput) SetPartsCount(v int64) *HeadObjectOutput { - s.PartsCount = &v +// SetMetricsConfigurationList sets the MetricsConfigurationList field's value. +func (s *ListBucketMetricsConfigurationsOutput) SetMetricsConfigurationList(v []*MetricsConfiguration) *ListBucketMetricsConfigurationsOutput { + s.MetricsConfigurationList = v return s } -// SetReplicationStatus sets the ReplicationStatus field's value. -func (s *HeadObjectOutput) SetReplicationStatus(v string) *HeadObjectOutput { - s.ReplicationStatus = &v +// SetNextContinuationToken sets the NextContinuationToken field's value. +func (s *ListBucketMetricsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { + s.NextContinuationToken = &v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *HeadObjectOutput) SetRequestCharged(v string) *HeadObjectOutput { - s.RequestCharged = &v - return s +type ListBucketsInput struct { + _ struct{} `type:"structure"` } -// SetRestore sets the Restore field's value. -func (s *HeadObjectOutput) SetRestore(v string) *HeadObjectOutput { - s.Restore = &v - return s +// String returns the string representation +func (s ListBucketsInput) String() string { + return awsutil.Prettify(s) } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *HeadObjectOutput) SetSSECustomerAlgorithm(v string) *HeadObjectOutput { - s.SSECustomerAlgorithm = &v - return s +// GoString returns the string representation +func (s ListBucketsInput) GoString() string { + return s.String() } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *HeadObjectOutput) SetSSECustomerKeyMD5(v string) *HeadObjectOutput { - s.SSECustomerKeyMD5 = &v - return s -} +type ListBucketsOutput struct { + _ struct{} `type:"structure"` -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *HeadObjectOutput) SetSSEKMSKeyId(v string) *HeadObjectOutput { - s.SSEKMSKeyId = &v - return s + Buckets []*Bucket `locationNameList:"Bucket" type:"list"` + + Owner *Owner `type:"structure"` } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *HeadObjectOutput) SetServerSideEncryption(v string) *HeadObjectOutput { - s.ServerSideEncryption = &v - return s +// String returns the string representation +func (s ListBucketsOutput) String() string { + return awsutil.Prettify(s) } -// SetStorageClass sets the StorageClass field's value. -func (s *HeadObjectOutput) SetStorageClass(v string) *HeadObjectOutput { - s.StorageClass = &v - return s +// GoString returns the string representation +func (s ListBucketsOutput) GoString() string { + return s.String() } -// SetVersionId sets the VersionId field's value. -func (s *HeadObjectOutput) SetVersionId(v string) *HeadObjectOutput { - s.VersionId = &v +// SetBuckets sets the Buckets field's value. +func (s *ListBucketsOutput) SetBuckets(v []*Bucket) *ListBucketsOutput { + s.Buckets = v return s } -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *HeadObjectOutput) SetWebsiteRedirectLocation(v string) *HeadObjectOutput { - s.WebsiteRedirectLocation = &v +// SetOwner sets the Owner field's value. +func (s *ListBucketsOutput) SetOwner(v *Owner) *ListBucketsOutput { + s.Owner = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/IndexDocument -type IndexDocument struct { +type ListMultipartUploadsInput struct { _ struct{} `type:"structure"` - // A suffix that is appended to a request that is for a directory on the website - // endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ - // the data that is returned will be for the object with the key name images/index.html) - // The suffix must not be empty and must not include a slash character. - // - // Suffix is a required field - Suffix *string `type:"string" required:"true"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Character you use to group keys. + Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` + + // Requests Amazon S3 to encode the object keys in the response and specifies + // the encoding method to use. An object key may contain any Unicode character; + // however, XML 1.0 parser cannot parse some characters, such as characters + // with an ASCII value from 0 to 10. For characters that are not supported in + // XML 1.0, you can add this parameter to request that Amazon S3 encode the + // keys in the response. + EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + + // Together with upload-id-marker, this parameter specifies the multipart upload + // after which listing should begin. + KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` + + // Sets the maximum number of multipart uploads, from 1 to 1,000, to return + // in the response body. 1,000 is the maximum number of uploads that can be + // returned in a response. + MaxUploads *int64 `location:"querystring" locationName:"max-uploads" type:"integer"` + + // Lists in-progress uploads only for those keys that begin with the specified + // prefix. + Prefix *string `location:"querystring" locationName:"prefix" type:"string"` + + // Together with key-marker, specifies the multipart upload after which listing + // should begin. If key-marker is not specified, the upload-id-marker parameter + // is ignored. + UploadIdMarker *string `location:"querystring" locationName:"upload-id-marker" type:"string"` } // String returns the string representation -func (s IndexDocument) String() string { +func (s ListMultipartUploadsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s IndexDocument) GoString() string { +func (s ListMultipartUploadsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *IndexDocument) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "IndexDocument"} - if s.Suffix == nil { - invalidParams.Add(request.NewErrParamRequired("Suffix")) +func (s *ListMultipartUploadsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListMultipartUploadsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -12001,206 +15996,237 @@ func (s *IndexDocument) Validate() error { return nil } -// SetSuffix sets the Suffix field's value. -func (s *IndexDocument) SetSuffix(v string) *IndexDocument { - s.Suffix = &v +// SetBucket sets the Bucket field's value. +func (s *ListMultipartUploadsInput) SetBucket(v string) *ListMultipartUploadsInput { + s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Initiator -type Initiator struct { - _ struct{} `type:"structure"` +func (s *ListMultipartUploadsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} - // Name of the Principal. - DisplayName *string `type:"string"` +// SetDelimiter sets the Delimiter field's value. +func (s *ListMultipartUploadsInput) SetDelimiter(v string) *ListMultipartUploadsInput { + s.Delimiter = &v + return s +} - // If the principal is an AWS account, it provides the Canonical User ID. If - // the principal is an IAM User, it provides a user ARN value. - ID *string `type:"string"` +// SetEncodingType sets the EncodingType field's value. +func (s *ListMultipartUploadsInput) SetEncodingType(v string) *ListMultipartUploadsInput { + s.EncodingType = &v + return s } -// String returns the string representation -func (s Initiator) String() string { - return awsutil.Prettify(s) +// SetKeyMarker sets the KeyMarker field's value. +func (s *ListMultipartUploadsInput) SetKeyMarker(v string) *ListMultipartUploadsInput { + s.KeyMarker = &v + return s } -// GoString returns the string representation -func (s Initiator) GoString() string { - return s.String() +// SetMaxUploads sets the MaxUploads field's value. +func (s *ListMultipartUploadsInput) SetMaxUploads(v int64) *ListMultipartUploadsInput { + s.MaxUploads = &v + return s } -// SetDisplayName sets the DisplayName field's value. -func (s *Initiator) SetDisplayName(v string) *Initiator { - s.DisplayName = &v +// SetPrefix sets the Prefix field's value. +func (s *ListMultipartUploadsInput) SetPrefix(v string) *ListMultipartUploadsInput { + s.Prefix = &v return s } -// SetID sets the ID field's value. -func (s *Initiator) SetID(v string) *Initiator { - s.ID = &v +// SetUploadIdMarker sets the UploadIdMarker field's value. +func (s *ListMultipartUploadsInput) SetUploadIdMarker(v string) *ListMultipartUploadsInput { + s.UploadIdMarker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryConfiguration -type InventoryConfiguration struct { +type ListMultipartUploadsOutput struct { _ struct{} `type:"structure"` - // Contains information about where to publish the inventory results. - // - // Destination is a required field - Destination *InventoryDestination `type:"structure" required:"true"` + // Name of the bucket to which the multipart upload was initiated. + Bucket *string `type:"string"` - // Specifies an inventory filter. The inventory only includes objects that meet - // the filter's criteria. - Filter *InventoryFilter `type:"structure"` + CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` + Delimiter *string `type:"string"` - // Specifies which object version(s) to included in the inventory results. - // - // IncludedObjectVersions is a required field - IncludedObjectVersions *string `type:"string" required:"true" enum:"InventoryIncludedObjectVersions"` + // Encoding type used by Amazon S3 to encode object keys in the response. + EncodingType *string `type:"string" enum:"EncodingType"` - // Specifies whether the inventory is enabled or disabled. - // - // IsEnabled is a required field - IsEnabled *bool `type:"boolean" required:"true"` + // Indicates whether the returned list of multipart uploads is truncated. A + // value of true indicates that the list was truncated. The list can be truncated + // if the number of multipart uploads exceeds the limit allowed or specified + // by max uploads. + IsTruncated *bool `type:"boolean"` - // Contains the optional fields that are included in the inventory results. - OptionalFields []*string `locationNameList:"Field" type:"list"` + // The key at or after which the listing began. + KeyMarker *string `type:"string"` + + // Maximum number of multipart uploads that could have been included in the + // response. + MaxUploads *int64 `type:"integer"` + + // When a list is truncated, this element specifies the value that should be + // used for the key-marker request parameter in a subsequent request. + NextKeyMarker *string `type:"string"` + + // When a list is truncated, this element specifies the value that should be + // used for the upload-id-marker request parameter in a subsequent request. + NextUploadIdMarker *string `type:"string"` + + // When a prefix is provided in the request, this field contains the specified + // prefix. The result contains only keys starting with the specified prefix. + Prefix *string `type:"string"` + + // Upload ID after which listing began. + UploadIdMarker *string `type:"string"` - // Specifies the schedule for generating inventory results. - // - // Schedule is a required field - Schedule *InventorySchedule `type:"structure" required:"true"` + Uploads []*MultipartUpload `locationName:"Upload" type:"list" flattened:"true"` } // String returns the string representation -func (s InventoryConfiguration) String() string { +func (s ListMultipartUploadsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InventoryConfiguration) GoString() string { +func (s ListMultipartUploadsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryConfiguration"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.IncludedObjectVersions == nil { - invalidParams.Add(request.NewErrParamRequired("IncludedObjectVersions")) - } - if s.IsEnabled == nil { - invalidParams.Add(request.NewErrParamRequired("IsEnabled")) - } - if s.Schedule == nil { - invalidParams.Add(request.NewErrParamRequired("Schedule")) - } - if s.Destination != nil { - if err := s.Destination.Validate(); err != nil { - invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) - } - } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } - } - if s.Schedule != nil { - if err := s.Schedule.Validate(); err != nil { - invalidParams.AddNested("Schedule", err.(request.ErrInvalidParams)) - } - } +// SetBucket sets the Bucket field's value. +func (s *ListMultipartUploadsOutput) SetBucket(v string) *ListMultipartUploadsOutput { + s.Bucket = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams +func (s *ListMultipartUploadsOutput) getBucket() (v string) { + if s.Bucket == nil { + return v } - return nil + return *s.Bucket } -// SetDestination sets the Destination field's value. -func (s *InventoryConfiguration) SetDestination(v *InventoryDestination) *InventoryConfiguration { - s.Destination = v +// SetCommonPrefixes sets the CommonPrefixes field's value. +func (s *ListMultipartUploadsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListMultipartUploadsOutput { + s.CommonPrefixes = v return s } -// SetFilter sets the Filter field's value. -func (s *InventoryConfiguration) SetFilter(v *InventoryFilter) *InventoryConfiguration { - s.Filter = v +// SetDelimiter sets the Delimiter field's value. +func (s *ListMultipartUploadsOutput) SetDelimiter(v string) *ListMultipartUploadsOutput { + s.Delimiter = &v return s } -// SetId sets the Id field's value. -func (s *InventoryConfiguration) SetId(v string) *InventoryConfiguration { - s.Id = &v +// SetEncodingType sets the EncodingType field's value. +func (s *ListMultipartUploadsOutput) SetEncodingType(v string) *ListMultipartUploadsOutput { + s.EncodingType = &v return s } -// SetIncludedObjectVersions sets the IncludedObjectVersions field's value. -func (s *InventoryConfiguration) SetIncludedObjectVersions(v string) *InventoryConfiguration { - s.IncludedObjectVersions = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListMultipartUploadsOutput) SetIsTruncated(v bool) *ListMultipartUploadsOutput { + s.IsTruncated = &v return s } -// SetIsEnabled sets the IsEnabled field's value. -func (s *InventoryConfiguration) SetIsEnabled(v bool) *InventoryConfiguration { - s.IsEnabled = &v +// SetKeyMarker sets the KeyMarker field's value. +func (s *ListMultipartUploadsOutput) SetKeyMarker(v string) *ListMultipartUploadsOutput { + s.KeyMarker = &v return s } -// SetOptionalFields sets the OptionalFields field's value. -func (s *InventoryConfiguration) SetOptionalFields(v []*string) *InventoryConfiguration { - s.OptionalFields = v +// SetMaxUploads sets the MaxUploads field's value. +func (s *ListMultipartUploadsOutput) SetMaxUploads(v int64) *ListMultipartUploadsOutput { + s.MaxUploads = &v return s } -// SetSchedule sets the Schedule field's value. -func (s *InventoryConfiguration) SetSchedule(v *InventorySchedule) *InventoryConfiguration { - s.Schedule = v +// SetNextKeyMarker sets the NextKeyMarker field's value. +func (s *ListMultipartUploadsOutput) SetNextKeyMarker(v string) *ListMultipartUploadsOutput { + s.NextKeyMarker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryDestination -type InventoryDestination struct { +// SetNextUploadIdMarker sets the NextUploadIdMarker field's value. +func (s *ListMultipartUploadsOutput) SetNextUploadIdMarker(v string) *ListMultipartUploadsOutput { + s.NextUploadIdMarker = &v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *ListMultipartUploadsOutput) SetPrefix(v string) *ListMultipartUploadsOutput { + s.Prefix = &v + return s +} + +// SetUploadIdMarker sets the UploadIdMarker field's value. +func (s *ListMultipartUploadsOutput) SetUploadIdMarker(v string) *ListMultipartUploadsOutput { + s.UploadIdMarker = &v + return s +} + +// SetUploads sets the Uploads field's value. +func (s *ListMultipartUploadsOutput) SetUploads(v []*MultipartUpload) *ListMultipartUploadsOutput { + s.Uploads = v + return s +} + +type ListObjectVersionsInput struct { _ struct{} `type:"structure"` - // Contains the bucket name, file format, bucket owner (optional), and prefix - // (optional) where inventory results are published. - // - // S3BucketDestination is a required field - S3BucketDestination *InventoryS3BucketDestination `type:"structure" required:"true"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // A delimiter is a character you use to group keys. + Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` + + // Requests Amazon S3 to encode the object keys in the response and specifies + // the encoding method to use. An object key may contain any Unicode character; + // however, XML 1.0 parser cannot parse some characters, such as characters + // with an ASCII value from 0 to 10. For characters that are not supported in + // XML 1.0, you can add this parameter to request that Amazon S3 encode the + // keys in the response. + EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + + // Specifies the key to start with when listing objects in a bucket. + KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` + + // Sets the maximum number of keys returned in the response. The response might + // contain fewer keys but will never contain more. + MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` + + // Limits the response to keys that begin with the specified prefix. + Prefix *string `location:"querystring" locationName:"prefix" type:"string"` + + // Specifies the object version you want to start listing from. + VersionIdMarker *string `location:"querystring" locationName:"version-id-marker" type:"string"` } // String returns the string representation -func (s InventoryDestination) String() string { +func (s ListObjectVersionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InventoryDestination) GoString() string { +func (s ListObjectVersionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryDestination"} - if s.S3BucketDestination == nil { - invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) +func (s *ListObjectVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListObjectVersionsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.S3BucketDestination != nil { - if err := s.S3BucketDestination.Validate(); err != nil { - invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -12209,229 +16235,233 @@ func (s *InventoryDestination) Validate() error { return nil } -// SetS3BucketDestination sets the S3BucketDestination field's value. -func (s *InventoryDestination) SetS3BucketDestination(v *InventoryS3BucketDestination) *InventoryDestination { - s.S3BucketDestination = v +// SetBucket sets the Bucket field's value. +func (s *ListObjectVersionsInput) SetBucket(v string) *ListObjectVersionsInput { + s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryFilter -type InventoryFilter struct { - _ struct{} `type:"structure"` - - // The prefix that an object must have to be included in the inventory results. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` +func (s *ListObjectVersionsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// String returns the string representation -func (s InventoryFilter) String() string { - return awsutil.Prettify(s) +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectVersionsInput) SetDelimiter(v string) *ListObjectVersionsInput { + s.Delimiter = &v + return s } -// GoString returns the string representation -func (s InventoryFilter) GoString() string { - return s.String() +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectVersionsInput) SetEncodingType(v string) *ListObjectVersionsInput { + s.EncodingType = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryFilter"} - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } +// SetKeyMarker sets the KeyMarker field's value. +func (s *ListObjectVersionsInput) SetKeyMarker(v string) *ListObjectVersionsInput { + s.KeyMarker = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectVersionsInput) SetMaxKeys(v int64) *ListObjectVersionsInput { + s.MaxKeys = &v + return s } // SetPrefix sets the Prefix field's value. -func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { +func (s *ListObjectVersionsInput) SetPrefix(v string) *ListObjectVersionsInput { s.Prefix = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryS3BucketDestination -type InventoryS3BucketDestination struct { +// SetVersionIdMarker sets the VersionIdMarker field's value. +func (s *ListObjectVersionsInput) SetVersionIdMarker(v string) *ListObjectVersionsInput { + s.VersionIdMarker = &v + return s +} + +type ListObjectVersionsOutput struct { _ struct{} `type:"structure"` - // The ID of the account that owns the destination bucket. - AccountId *string `type:"string"` + CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - // The Amazon resource name (ARN) of the bucket where inventory results will - // be published. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` + DeleteMarkers []*DeleteMarkerEntry `locationName:"DeleteMarker" type:"list" flattened:"true"` + + Delimiter *string `type:"string"` + + // Encoding type used by Amazon S3 to encode object keys in the response. + EncodingType *string `type:"string" enum:"EncodingType"` + + // A flag that indicates whether or not Amazon S3 returned all of the results + // that satisfied the search criteria. If your results were truncated, you can + // make a follow-up paginated request using the NextKeyMarker and NextVersionIdMarker + // response parameters as a starting place in another request to return the + // rest of the results. + IsTruncated *bool `type:"boolean"` + + // Marks the last Key returned in a truncated response. + KeyMarker *string `type:"string"` + + MaxKeys *int64 `type:"integer"` + + Name *string `type:"string"` + + // Use this value for the key marker request parameter in a subsequent request. + NextKeyMarker *string `type:"string"` - // Specifies the output format of the inventory results. - // - // Format is a required field - Format *string `type:"string" required:"true" enum:"InventoryFormat"` + // Use this value for the next version id marker parameter in a subsequent request. + NextVersionIdMarker *string `type:"string"` - // The prefix that is prepended to all inventory results. Prefix *string `type:"string"` + + VersionIdMarker *string `type:"string"` + + Versions []*ObjectVersion `locationName:"Version" type:"list" flattened:"true"` } // String returns the string representation -func (s InventoryS3BucketDestination) String() string { +func (s ListObjectVersionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InventoryS3BucketDestination) GoString() string { +func (s ListObjectVersionsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryS3BucketDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryS3BucketDestination"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Format == nil { - invalidParams.Add(request.NewErrParamRequired("Format")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccountId sets the AccountId field's value. -func (s *InventoryS3BucketDestination) SetAccountId(v string) *InventoryS3BucketDestination { - s.AccountId = &v +// SetCommonPrefixes sets the CommonPrefixes field's value. +func (s *ListObjectVersionsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectVersionsOutput { + s.CommonPrefixes = v return s } -// SetBucket sets the Bucket field's value. -func (s *InventoryS3BucketDestination) SetBucket(v string) *InventoryS3BucketDestination { - s.Bucket = &v +// SetDeleteMarkers sets the DeleteMarkers field's value. +func (s *ListObjectVersionsOutput) SetDeleteMarkers(v []*DeleteMarkerEntry) *ListObjectVersionsOutput { + s.DeleteMarkers = v return s } -// SetFormat sets the Format field's value. -func (s *InventoryS3BucketDestination) SetFormat(v string) *InventoryS3BucketDestination { - s.Format = &v +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectVersionsOutput) SetDelimiter(v string) *ListObjectVersionsOutput { + s.Delimiter = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *InventoryS3BucketDestination) SetPrefix(v string) *InventoryS3BucketDestination { - s.Prefix = &v +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectVersionsOutput) SetEncodingType(v string) *ListObjectVersionsOutput { + s.EncodingType = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventorySchedule -type InventorySchedule struct { - _ struct{} `type:"structure"` - - // Specifies how frequently inventory results are produced. - // - // Frequency is a required field - Frequency *string `type:"string" required:"true" enum:"InventoryFrequency"` +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListObjectVersionsOutput) SetIsTruncated(v bool) *ListObjectVersionsOutput { + s.IsTruncated = &v + return s } -// String returns the string representation -func (s InventorySchedule) String() string { - return awsutil.Prettify(s) +// SetKeyMarker sets the KeyMarker field's value. +func (s *ListObjectVersionsOutput) SetKeyMarker(v string) *ListObjectVersionsOutput { + s.KeyMarker = &v + return s } -// GoString returns the string representation -func (s InventorySchedule) GoString() string { - return s.String() +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectVersionsOutput) SetMaxKeys(v int64) *ListObjectVersionsOutput { + s.MaxKeys = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventorySchedule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventorySchedule"} - if s.Frequency == nil { - invalidParams.Add(request.NewErrParamRequired("Frequency")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetName sets the Name field's value. +func (s *ListObjectVersionsOutput) SetName(v string) *ListObjectVersionsOutput { + s.Name = &v + return s } -// SetFrequency sets the Frequency field's value. -func (s *InventorySchedule) SetFrequency(v string) *InventorySchedule { - s.Frequency = &v +// SetNextKeyMarker sets the NextKeyMarker field's value. +func (s *ListObjectVersionsOutput) SetNextKeyMarker(v string) *ListObjectVersionsOutput { + s.NextKeyMarker = &v return s } -// Container for object key name prefix and suffix filtering rules. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/S3KeyFilter -type KeyFilter struct { - _ struct{} `type:"structure"` - - // A list of containers for key value pair that defines the criteria for the - // filter rule. - FilterRules []*FilterRule `locationName:"FilterRule" type:"list" flattened:"true"` +// SetNextVersionIdMarker sets the NextVersionIdMarker field's value. +func (s *ListObjectVersionsOutput) SetNextVersionIdMarker(v string) *ListObjectVersionsOutput { + s.NextVersionIdMarker = &v + return s } -// String returns the string representation -func (s KeyFilter) String() string { - return awsutil.Prettify(s) +// SetPrefix sets the Prefix field's value. +func (s *ListObjectVersionsOutput) SetPrefix(v string) *ListObjectVersionsOutput { + s.Prefix = &v + return s } -// GoString returns the string representation -func (s KeyFilter) GoString() string { - return s.String() +// SetVersionIdMarker sets the VersionIdMarker field's value. +func (s *ListObjectVersionsOutput) SetVersionIdMarker(v string) *ListObjectVersionsOutput { + s.VersionIdMarker = &v + return s } -// SetFilterRules sets the FilterRules field's value. -func (s *KeyFilter) SetFilterRules(v []*FilterRule) *KeyFilter { - s.FilterRules = v +// SetVersions sets the Versions field's value. +func (s *ListObjectVersionsOutput) SetVersions(v []*ObjectVersion) *ListObjectVersionsOutput { + s.Versions = v return s } -// Container for specifying the AWS Lambda notification configuration. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LambdaFunctionConfiguration -type LambdaFunctionConfiguration struct { +type ListObjectsInput struct { _ struct{} `type:"structure"` - // Events is a required field - Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Filter *NotificationConfigurationFilter `type:"structure"` + // A delimiter is a character you use to group keys. + Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` + // Requests Amazon S3 to encode the object keys in the response and specifies + // the encoding method to use. An object key may contain any Unicode character; + // however, XML 1.0 parser cannot parse some characters, such as characters + // with an ASCII value from 0 to 10. For characters that are not supported in + // XML 1.0, you can add this parameter to request that Amazon S3 encode the + // keys in the response. + EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - // Lambda cloud function ARN that Amazon S3 can invoke when it detects events - // of the specified type. - // - // LambdaFunctionArn is a required field - LambdaFunctionArn *string `locationName:"CloudFunction" type:"string" required:"true"` + // Specifies the key to start with when listing objects in a bucket. + Marker *string `location:"querystring" locationName:"marker" type:"string"` + + // Sets the maximum number of keys returned in the response. The response might + // contain fewer keys but will never contain more. + MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` + + // Limits the response to keys that begin with the specified prefix. + Prefix *string `location:"querystring" locationName:"prefix" type:"string"` + + // Confirms that the requester knows that she or he will be charged for the + // list objects request. Bucket owners need not specify this parameter in their + // requests. + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` } // String returns the string representation -func (s LambdaFunctionConfiguration) String() string { +func (s ListObjectsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LambdaFunctionConfiguration) GoString() string { +func (s ListObjectsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LambdaFunctionConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionConfiguration"} - if s.Events == nil { - invalidParams.Add(request.NewErrParamRequired("Events")) +func (s *ListObjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListObjectsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.LambdaFunctionArn == nil { - invalidParams.Add(request.NewErrParamRequired("LambdaFunctionArn")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -12440,183 +16470,218 @@ func (s *LambdaFunctionConfiguration) Validate() error { return nil } -// SetEvents sets the Events field's value. -func (s *LambdaFunctionConfiguration) SetEvents(v []*string) *LambdaFunctionConfiguration { - s.Events = v +// SetBucket sets the Bucket field's value. +func (s *ListObjectsInput) SetBucket(v string) *ListObjectsInput { + s.Bucket = &v return s } -// SetFilter sets the Filter field's value. -func (s *LambdaFunctionConfiguration) SetFilter(v *NotificationConfigurationFilter) *LambdaFunctionConfiguration { - s.Filter = v +func (s *ListObjectsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectsInput) SetDelimiter(v string) *ListObjectsInput { + s.Delimiter = &v return s } -// SetId sets the Id field's value. -func (s *LambdaFunctionConfiguration) SetId(v string) *LambdaFunctionConfiguration { - s.Id = &v +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectsInput) SetEncodingType(v string) *ListObjectsInput { + s.EncodingType = &v return s } -// SetLambdaFunctionArn sets the LambdaFunctionArn field's value. -func (s *LambdaFunctionConfiguration) SetLambdaFunctionArn(v string) *LambdaFunctionConfiguration { - s.LambdaFunctionArn = &v +// SetMarker sets the Marker field's value. +func (s *ListObjectsInput) SetMarker(v string) *ListObjectsInput { + s.Marker = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleConfiguration -type LifecycleConfiguration struct { +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectsInput) SetMaxKeys(v int64) *ListObjectsInput { + s.MaxKeys = &v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *ListObjectsInput) SetPrefix(v string) *ListObjectsInput { + s.Prefix = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *ListObjectsInput) SetRequestPayer(v string) *ListObjectsInput { + s.RequestPayer = &v + return s +} + +type ListObjectsOutput struct { _ struct{} `type:"structure"` - // Rules is a required field - Rules []*Rule `locationName:"Rule" type:"list" flattened:"true" required:"true"` + CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` + + Contents []*Object `type:"list" flattened:"true"` + + Delimiter *string `type:"string"` + + // Encoding type used by Amazon S3 to encode object keys in the response. + EncodingType *string `type:"string" enum:"EncodingType"` + + // A flag that indicates whether or not Amazon S3 returned all of the results + // that satisfied the search criteria. + IsTruncated *bool `type:"boolean"` + + Marker *string `type:"string"` + + MaxKeys *int64 `type:"integer"` + + Name *string `type:"string"` + + // When response is truncated (the IsTruncated element value in the response + // is true), you can use the key name in this field as marker in the subsequent + // request to get next set of objects. Amazon S3 lists objects in alphabetical + // order Note: This element is returned only if you have delimiter request parameter + // specified. If response does not include the NextMaker and it is truncated, + // you can use the value of the last Key in the response as the marker in the + // subsequent request to get the next set of object keys. + NextMarker *string `type:"string"` + + Prefix *string `type:"string"` } // String returns the string representation -func (s LifecycleConfiguration) String() string { +func (s ListObjectsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LifecycleConfiguration) GoString() string { +func (s ListObjectsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleConfiguration"} - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCommonPrefixes sets the CommonPrefixes field's value. +func (s *ListObjectsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsOutput { + s.CommonPrefixes = v + return s } -// SetRules sets the Rules field's value. -func (s *LifecycleConfiguration) SetRules(v []*Rule) *LifecycleConfiguration { - s.Rules = v +// SetContents sets the Contents field's value. +func (s *ListObjectsOutput) SetContents(v []*Object) *ListObjectsOutput { + s.Contents = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleExpiration -type LifecycleExpiration struct { - _ struct{} `type:"structure"` - - // Indicates at what date the object is to be moved or deleted. Should be in - // GMT ISO 8601 Format. - Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectsOutput) SetDelimiter(v string) *ListObjectsOutput { + s.Delimiter = &v + return s +} - // Indicates the lifetime, in days, of the objects that are subject to the rule. - // The value must be a non-zero positive integer. - Days *int64 `type:"integer"` +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectsOutput) SetEncodingType(v string) *ListObjectsOutput { + s.EncodingType = &v + return s +} - // Indicates whether Amazon S3 will remove a delete marker with no noncurrent - // versions. If set to true, the delete marker will be expired; if set to false - // the policy takes no action. This cannot be specified with Days or Date in - // a Lifecycle Expiration Policy. - ExpiredObjectDeleteMarker *bool `type:"boolean"` +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListObjectsOutput) SetIsTruncated(v bool) *ListObjectsOutput { + s.IsTruncated = &v + return s } -// String returns the string representation -func (s LifecycleExpiration) String() string { - return awsutil.Prettify(s) +// SetMarker sets the Marker field's value. +func (s *ListObjectsOutput) SetMarker(v string) *ListObjectsOutput { + s.Marker = &v + return s } -// GoString returns the string representation -func (s LifecycleExpiration) GoString() string { - return s.String() +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectsOutput) SetMaxKeys(v int64) *ListObjectsOutput { + s.MaxKeys = &v + return s } -// SetDate sets the Date field's value. -func (s *LifecycleExpiration) SetDate(v time.Time) *LifecycleExpiration { - s.Date = &v +// SetName sets the Name field's value. +func (s *ListObjectsOutput) SetName(v string) *ListObjectsOutput { + s.Name = &v return s } -// SetDays sets the Days field's value. -func (s *LifecycleExpiration) SetDays(v int64) *LifecycleExpiration { - s.Days = &v +// SetNextMarker sets the NextMarker field's value. +func (s *ListObjectsOutput) SetNextMarker(v string) *ListObjectsOutput { + s.NextMarker = &v return s } -// SetExpiredObjectDeleteMarker sets the ExpiredObjectDeleteMarker field's value. -func (s *LifecycleExpiration) SetExpiredObjectDeleteMarker(v bool) *LifecycleExpiration { - s.ExpiredObjectDeleteMarker = &v +// SetPrefix sets the Prefix field's value. +func (s *ListObjectsOutput) SetPrefix(v string) *ListObjectsOutput { + s.Prefix = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRule -type LifecycleRule struct { +type ListObjectsV2Input struct { _ struct{} `type:"structure"` - // Specifies the days since the initiation of an Incomplete Multipart Upload - // that Lifecycle will wait before permanently removing all parts of the upload. - AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` + // Name of the bucket to list. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Expiration *LifecycleExpiration `type:"structure"` + // ContinuationToken indicates Amazon S3 that the list is being continued on + // this bucket with a token. ContinuationToken is obfuscated and is not a real + // key + ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` - // The Filter is used to identify objects that a Lifecycle Rule applies to. - // A Filter must have exactly one of Prefix, Tag, or And specified. - Filter *LifecycleRuleFilter `type:"structure"` + // A delimiter is a character you use to group keys. + Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` + // Encoding type used by Amazon S3 to encode object keys in the response. + EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - // Specifies when noncurrent object versions expire. Upon expiration, Amazon - // S3 permanently deletes the noncurrent object versions. You set this lifecycle - // configuration action on a bucket that has versioning enabled (or suspended) - // to request that Amazon S3 delete noncurrent object versions at a specific - // period in the object's lifetime. - NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` + // The owner field is not present in listV2 by default, if you want to return + // owner field with each key in the result then set the fetch owner field to + // true + FetchOwner *bool `location:"querystring" locationName:"fetch-owner" type:"boolean"` - NoncurrentVersionTransitions []*NoncurrentVersionTransition `locationName:"NoncurrentVersionTransition" type:"list" flattened:"true"` + // Sets the maximum number of keys returned in the response. The response might + // contain fewer keys but will never contain more. + MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - // Prefix identifying one or more objects to which the rule applies. This is - // deprecated; use Filter instead. - Prefix *string `deprecated:"true" type:"string"` + // Limits the response to keys that begin with the specified prefix. + Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule - // is not currently being applied. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ExpirationStatus"` + // Confirms that the requester knows that she or he will be charged for the + // list objects request in V2 style. Bucket owners need not specify this parameter + // in their requests. + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - Transitions []*Transition `locationName:"Transition" type:"list" flattened:"true"` + // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts + // listing after this specified key. StartAfter can be any key in the bucket + StartAfter *string `location:"querystring" locationName:"start-after" type:"string"` } // String returns the string representation -func (s LifecycleRule) String() string { +func (s ListObjectsV2Input) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LifecycleRule) GoString() string { +func (s ListObjectsV2Input) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRule"} - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) +func (s *ListObjectsV2Input) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListObjectsV2Input"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -12625,212 +16690,256 @@ func (s *LifecycleRule) Validate() error { return nil } -// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. -func (s *LifecycleRule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *LifecycleRule { - s.AbortIncompleteMultipartUpload = v +// SetBucket sets the Bucket field's value. +func (s *ListObjectsV2Input) SetBucket(v string) *ListObjectsV2Input { + s.Bucket = &v return s } -// SetExpiration sets the Expiration field's value. -func (s *LifecycleRule) SetExpiration(v *LifecycleExpiration) *LifecycleRule { - s.Expiration = v +func (s *ListObjectsV2Input) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListObjectsV2Input) SetContinuationToken(v string) *ListObjectsV2Input { + s.ContinuationToken = &v return s } -// SetFilter sets the Filter field's value. -func (s *LifecycleRule) SetFilter(v *LifecycleRuleFilter) *LifecycleRule { - s.Filter = v +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectsV2Input) SetDelimiter(v string) *ListObjectsV2Input { + s.Delimiter = &v return s } -// SetID sets the ID field's value. -func (s *LifecycleRule) SetID(v string) *LifecycleRule { - s.ID = &v +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectsV2Input) SetEncodingType(v string) *ListObjectsV2Input { + s.EncodingType = &v return s } -// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. -func (s *LifecycleRule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *LifecycleRule { - s.NoncurrentVersionExpiration = v +// SetFetchOwner sets the FetchOwner field's value. +func (s *ListObjectsV2Input) SetFetchOwner(v bool) *ListObjectsV2Input { + s.FetchOwner = &v return s } -// SetNoncurrentVersionTransitions sets the NoncurrentVersionTransitions field's value. -func (s *LifecycleRule) SetNoncurrentVersionTransitions(v []*NoncurrentVersionTransition) *LifecycleRule { - s.NoncurrentVersionTransitions = v +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectsV2Input) SetMaxKeys(v int64) *ListObjectsV2Input { + s.MaxKeys = &v return s } // SetPrefix sets the Prefix field's value. -func (s *LifecycleRule) SetPrefix(v string) *LifecycleRule { +func (s *ListObjectsV2Input) SetPrefix(v string) *ListObjectsV2Input { s.Prefix = &v return s } -// SetStatus sets the Status field's value. -func (s *LifecycleRule) SetStatus(v string) *LifecycleRule { - s.Status = &v +// SetRequestPayer sets the RequestPayer field's value. +func (s *ListObjectsV2Input) SetRequestPayer(v string) *ListObjectsV2Input { + s.RequestPayer = &v return s } -// SetTransitions sets the Transitions field's value. -func (s *LifecycleRule) SetTransitions(v []*Transition) *LifecycleRule { - s.Transitions = v +// SetStartAfter sets the StartAfter field's value. +func (s *ListObjectsV2Input) SetStartAfter(v string) *ListObjectsV2Input { + s.StartAfter = &v return s } -// This is used in a Lifecycle Rule Filter to apply a logical AND to two or -// more predicates. The Lifecycle Rule will apply to any object matching all -// of the predicates configured inside the And operator. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleAndOperator -type LifecycleRuleAndOperator struct { - _ struct{} `type:"structure"` +type ListObjectsV2Output struct { + _ struct{} `type:"structure"` + + // CommonPrefixes contains all (if there are any) keys between Prefix and the + // next occurrence of the string specified by delimiter + CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` + + // Metadata about each object returned. + Contents []*Object `type:"list" flattened:"true"` + + // ContinuationToken indicates Amazon S3 that the list is being continued on + // this bucket with a token. ContinuationToken is obfuscated and is not a real + // key + ContinuationToken *string `type:"string"` + + // A delimiter is a character you use to group keys. + Delimiter *string `type:"string"` + + // Encoding type used by Amazon S3 to encode object keys in the response. + EncodingType *string `type:"string" enum:"EncodingType"` + + // A flag that indicates whether or not Amazon S3 returned all of the results + // that satisfied the search criteria. + IsTruncated *bool `type:"boolean"` + + // KeyCount is the number of keys returned with this request. KeyCount will + // always be less than equals to MaxKeys field. Say you ask for 50 keys, your + // result will include less than equals 50 keys + KeyCount *int64 `type:"integer"` + + // Sets the maximum number of keys returned in the response. The response might + // contain fewer keys but will never contain more. + MaxKeys *int64 `type:"integer"` + + // Name of the bucket to list. + Name *string `type:"string"` + + // NextContinuationToken is sent when isTruncated is true which means there + // are more keys in the bucket that can be listed. The next list requests to + // Amazon S3 can be continued with this NextContinuationToken. NextContinuationToken + // is obfuscated and is not a real key + NextContinuationToken *string `type:"string"` + // Limits the response to keys that begin with the specified prefix. Prefix *string `type:"string"` - // All of these tags must exist in the object's tag set in order for the rule - // to apply. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` + // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts + // listing after this specified key. StartAfter can be any key in the bucket + StartAfter *string `type:"string"` } // String returns the string representation -func (s LifecycleRuleAndOperator) String() string { +func (s ListObjectsV2Output) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LifecycleRuleAndOperator) GoString() string { +func (s ListObjectsV2Output) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRuleAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCommonPrefixes sets the CommonPrefixes field's value. +func (s *ListObjectsV2Output) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsV2Output { + s.CommonPrefixes = v + return s } -// SetPrefix sets the Prefix field's value. -func (s *LifecycleRuleAndOperator) SetPrefix(v string) *LifecycleRuleAndOperator { - s.Prefix = &v +// SetContents sets the Contents field's value. +func (s *ListObjectsV2Output) SetContents(v []*Object) *ListObjectsV2Output { + s.Contents = v return s } -// SetTags sets the Tags field's value. -func (s *LifecycleRuleAndOperator) SetTags(v []*Tag) *LifecycleRuleAndOperator { - s.Tags = v +// SetContinuationToken sets the ContinuationToken field's value. +func (s *ListObjectsV2Output) SetContinuationToken(v string) *ListObjectsV2Output { + s.ContinuationToken = &v return s } -// The Filter is used to identify objects that a Lifecycle Rule applies to. -// A Filter must have exactly one of Prefix, Tag, or And specified. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleFilter -type LifecycleRuleFilter struct { - _ struct{} `type:"structure"` - - // This is used in a Lifecycle Rule Filter to apply a logical AND to two or - // more predicates. The Lifecycle Rule will apply to any object matching all - // of the predicates configured inside the And operator. - And *LifecycleRuleAndOperator `type:"structure"` - - // Prefix identifying one or more objects to which the rule applies. - Prefix *string `type:"string"` +// SetDelimiter sets the Delimiter field's value. +func (s *ListObjectsV2Output) SetDelimiter(v string) *ListObjectsV2Output { + s.Delimiter = &v + return s +} - // This tag must exist in the object's tag set in order for the rule to apply. - Tag *Tag `type:"structure"` +// SetEncodingType sets the EncodingType field's value. +func (s *ListObjectsV2Output) SetEncodingType(v string) *ListObjectsV2Output { + s.EncodingType = &v + return s } -// String returns the string representation -func (s LifecycleRuleFilter) String() string { - return awsutil.Prettify(s) +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListObjectsV2Output) SetIsTruncated(v bool) *ListObjectsV2Output { + s.IsTruncated = &v + return s } -// GoString returns the string representation -func (s LifecycleRuleFilter) GoString() string { - return s.String() +// SetKeyCount sets the KeyCount field's value. +func (s *ListObjectsV2Output) SetKeyCount(v int64) *ListObjectsV2Output { + s.KeyCount = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRuleFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } - } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) - } - } +// SetMaxKeys sets the MaxKeys field's value. +func (s *ListObjectsV2Output) SetMaxKeys(v int64) *ListObjectsV2Output { + s.MaxKeys = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetName sets the Name field's value. +func (s *ListObjectsV2Output) SetName(v string) *ListObjectsV2Output { + s.Name = &v + return s } -// SetAnd sets the And field's value. -func (s *LifecycleRuleFilter) SetAnd(v *LifecycleRuleAndOperator) *LifecycleRuleFilter { - s.And = v +// SetNextContinuationToken sets the NextContinuationToken field's value. +func (s *ListObjectsV2Output) SetNextContinuationToken(v string) *ListObjectsV2Output { + s.NextContinuationToken = &v return s } // SetPrefix sets the Prefix field's value. -func (s *LifecycleRuleFilter) SetPrefix(v string) *LifecycleRuleFilter { +func (s *ListObjectsV2Output) SetPrefix(v string) *ListObjectsV2Output { s.Prefix = &v return s } -// SetTag sets the Tag field's value. -func (s *LifecycleRuleFilter) SetTag(v *Tag) *LifecycleRuleFilter { - s.Tag = v +// SetStartAfter sets the StartAfter field's value. +func (s *ListObjectsV2Output) SetStartAfter(v string) *ListObjectsV2Output { + s.StartAfter = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsRequest -type ListBucketAnalyticsConfigurationsInput struct { +type ListPartsInput struct { _ struct{} `type:"structure"` - // The name of the bucket from which analytics configurations are retrieved. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The ContinuationToken that represents a placeholder from where this request - // should begin. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Sets the maximum number of parts to return. + MaxParts *int64 `location:"querystring" locationName:"max-parts" type:"integer"` + + // Specifies the part after which listing should begin. Only parts with higher + // part numbers will be listed. + PartNumberMarker *int64 `location:"querystring" locationName:"part-number-marker" type:"integer"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Upload ID identifying the multipart upload whose parts are being listed. + // + // UploadId is a required field + UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` } // String returns the string representation -func (s ListBucketAnalyticsConfigurationsInput) String() string { +func (s ListPartsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketAnalyticsConfigurationsInput) GoString() string { +func (s ListPartsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketAnalyticsConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketAnalyticsConfigurationsInput"} +func (s *ListPartsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPartsInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.UploadId == nil { + invalidParams.Add(request.NewErrParamRequired("UploadId")) + } if invalidParams.Len() > 0 { return invalidParams @@ -12839,209 +16948,269 @@ func (s *ListBucketAnalyticsConfigurationsInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *ListBucketAnalyticsConfigurationsInput) SetBucket(v string) *ListBucketAnalyticsConfigurationsInput { +func (s *ListPartsInput) SetBucket(v string) *ListPartsInput { s.Bucket = &v return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsInput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsInput { - s.ContinuationToken = &v +func (s *ListPartsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *ListPartsInput) SetKey(v string) *ListPartsInput { + s.Key = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsOutput -type ListBucketAnalyticsConfigurationsOutput struct { +// SetMaxParts sets the MaxParts field's value. +func (s *ListPartsInput) SetMaxParts(v int64) *ListPartsInput { + s.MaxParts = &v + return s +} + +// SetPartNumberMarker sets the PartNumberMarker field's value. +func (s *ListPartsInput) SetPartNumberMarker(v int64) *ListPartsInput { + s.PartNumberMarker = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *ListPartsInput) SetRequestPayer(v string) *ListPartsInput { + s.RequestPayer = &v + return s +} + +// SetUploadId sets the UploadId field's value. +func (s *ListPartsInput) SetUploadId(v string) *ListPartsInput { + s.UploadId = &v + return s +} + +type ListPartsOutput struct { _ struct{} `type:"structure"` - // The list of analytics configurations for a bucket. - AnalyticsConfigurationList []*AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"list" flattened:"true"` + // Date when multipart upload will become eligible for abort operation by lifecycle. + AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp"` - // The ContinuationToken that represents where this request began. - ContinuationToken *string `type:"string"` + // Id of the lifecycle rule that makes a multipart upload eligible for abort + // operation. + AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` + + // Name of the bucket to which the multipart upload was initiated. + Bucket *string `type:"string"` + + // Identifies who initiated the multipart upload. + Initiator *Initiator `type:"structure"` + + // Indicates whether the returned list of parts is truncated. + IsTruncated *bool `type:"boolean"` + + // Object key for which the multipart upload was initiated. + Key *string `min:"1" type:"string"` + + // Maximum number of parts that were allowed in the response. + MaxParts *int64 `type:"integer"` + + // When a list is truncated, this element specifies the last part in the list, + // as well as the value to use for the part-number-marker request parameter + // in a subsequent request. + NextPartNumberMarker *int64 `type:"integer"` + + Owner *Owner `type:"structure"` + + // Part number after which listing begins. + PartNumberMarker *int64 `type:"integer"` + + Parts []*Part `locationName:"Part" type:"list" flattened:"true"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - // Indicates whether the returned list of analytics configurations is complete. - // A value of true indicates that the list is not complete and the NextContinuationToken - // will be provided for a subsequent request. - IsTruncated *bool `type:"boolean"` + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"StorageClass"` - // NextContinuationToken is sent when isTruncated is true, which indicates that - // there are more analytics configurations to list. The next request must include - // this NextContinuationToken. The token is obfuscated and is not a usable value. - NextContinuationToken *string `type:"string"` + // Upload ID identifying the multipart upload whose parts are being listed. + UploadId *string `type:"string"` } // String returns the string representation -func (s ListBucketAnalyticsConfigurationsOutput) String() string { +func (s ListPartsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketAnalyticsConfigurationsOutput) GoString() string { +func (s ListPartsOutput) GoString() string { return s.String() } -// SetAnalyticsConfigurationList sets the AnalyticsConfigurationList field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetAnalyticsConfigurationList(v []*AnalyticsConfiguration) *ListBucketAnalyticsConfigurationsOutput { - s.AnalyticsConfigurationList = v - return s -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { - s.ContinuationToken = &v +// SetAbortDate sets the AbortDate field's value. +func (s *ListPartsOutput) SetAbortDate(v time.Time) *ListPartsOutput { + s.AbortDate = &v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketAnalyticsConfigurationsOutput { - s.IsTruncated = &v +// SetAbortRuleId sets the AbortRuleId field's value. +func (s *ListPartsOutput) SetAbortRuleId(v string) *ListPartsOutput { + s.AbortRuleId = &v return s } -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { - s.NextContinuationToken = &v +// SetBucket sets the Bucket field's value. +func (s *ListPartsOutput) SetBucket(v string) *ListPartsOutput { + s.Bucket = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsRequest -type ListBucketInventoryConfigurationsInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the inventory configurations to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The marker used to continue an inventory configuration listing that has been - // truncated. Use the NextContinuationToken from a previously truncated list - // response to continue the listing. The continuation token is an opaque value - // that Amazon S3 understands. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` -} - -// String returns the string representation -func (s ListBucketInventoryConfigurationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketInventoryConfigurationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketInventoryConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketInventoryConfigurationsInput"} +func (s *ListPartsOutput) getBucket() (v string) { if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams + return v } - return nil + return *s.Bucket } -// SetBucket sets the Bucket field's value. -func (s *ListBucketInventoryConfigurationsInput) SetBucket(v string) *ListBucketInventoryConfigurationsInput { - s.Bucket = &v +// SetInitiator sets the Initiator field's value. +func (s *ListPartsOutput) SetInitiator(v *Initiator) *ListPartsOutput { + s.Initiator = v return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsInput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsInput { - s.ContinuationToken = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *ListPartsOutput) SetIsTruncated(v bool) *ListPartsOutput { + s.IsTruncated = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsOutput -type ListBucketInventoryConfigurationsOutput struct { - _ struct{} `type:"structure"` - - // If sent in the request, the marker that is used as a starting point for this - // inventory configuration list response. - ContinuationToken *string `type:"string"` - - // The list of inventory configurations for a bucket. - InventoryConfigurationList []*InventoryConfiguration `locationName:"InventoryConfiguration" type:"list" flattened:"true"` +// SetKey sets the Key field's value. +func (s *ListPartsOutput) SetKey(v string) *ListPartsOutput { + s.Key = &v + return s +} - // Indicates whether the returned list of inventory configurations is truncated - // in this response. A value of true indicates that the list is truncated. - IsTruncated *bool `type:"boolean"` +// SetMaxParts sets the MaxParts field's value. +func (s *ListPartsOutput) SetMaxParts(v int64) *ListPartsOutput { + s.MaxParts = &v + return s +} - // The marker used to continue this inventory configuration listing. Use the - // NextContinuationToken from this response to continue the listing in a subsequent - // request. The continuation token is an opaque value that Amazon S3 understands. - NextContinuationToken *string `type:"string"` +// SetNextPartNumberMarker sets the NextPartNumberMarker field's value. +func (s *ListPartsOutput) SetNextPartNumberMarker(v int64) *ListPartsOutput { + s.NextPartNumberMarker = &v + return s } -// String returns the string representation -func (s ListBucketInventoryConfigurationsOutput) String() string { - return awsutil.Prettify(s) +// SetOwner sets the Owner field's value. +func (s *ListPartsOutput) SetOwner(v *Owner) *ListPartsOutput { + s.Owner = v + return s } -// GoString returns the string representation -func (s ListBucketInventoryConfigurationsOutput) GoString() string { - return s.String() +// SetPartNumberMarker sets the PartNumberMarker field's value. +func (s *ListPartsOutput) SetPartNumberMarker(v int64) *ListPartsOutput { + s.PartNumberMarker = &v + return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { - s.ContinuationToken = &v +// SetParts sets the Parts field's value. +func (s *ListPartsOutput) SetParts(v []*Part) *ListPartsOutput { + s.Parts = v return s } -// SetInventoryConfigurationList sets the InventoryConfigurationList field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetInventoryConfigurationList(v []*InventoryConfiguration) *ListBucketInventoryConfigurationsOutput { - s.InventoryConfigurationList = v +// SetRequestCharged sets the RequestCharged field's value. +func (s *ListPartsOutput) SetRequestCharged(v string) *ListPartsOutput { + s.RequestCharged = &v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetIsTruncated(v bool) *ListBucketInventoryConfigurationsOutput { - s.IsTruncated = &v +// SetStorageClass sets the StorageClass field's value. +func (s *ListPartsOutput) SetStorageClass(v string) *ListPartsOutput { + s.StorageClass = &v return s } -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { - s.NextContinuationToken = &v +// SetUploadId sets the UploadId field's value. +func (s *ListPartsOutput) SetUploadId(v string) *ListPartsOutput { + s.UploadId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsRequest -type ListBucketMetricsConfigurationsInput struct { +// Describes an S3 location that will receive the results of the restore request. +type Location struct { _ struct{} `type:"structure"` - // The name of the bucket containing the metrics configurations to retrieve. + // A list of grants that control access to the staged results. + AccessControlList []*Grant `locationNameList:"Grant" type:"list"` + + // The name of the bucket where the restore results will be placed. // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // BucketName is a required field + BucketName *string `type:"string" required:"true"` - // The marker that is used to continue a metrics configuration listing that - // has been truncated. Use the NextContinuationToken from a previously truncated - // list response to continue the listing. The continuation token is an opaque - // value that Amazon S3 understands. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + // The canned ACL to apply to the restore results. + CannedACL *string `type:"string" enum:"ObjectCannedACL"` + + // Describes the server-side encryption that will be applied to the restore + // results. + Encryption *Encryption `type:"structure"` + + // The prefix that is prepended to the restore results for this request. + // + // Prefix is a required field + Prefix *string `type:"string" required:"true"` + + // The class of storage used to store the restore results. + StorageClass *string `type:"string" enum:"StorageClass"` + + // The tag-set that is applied to the restore results. + Tagging *Tagging `type:"structure"` + + // A list of metadata to store with the restore results in S3. + UserMetadata []*MetadataEntry `locationNameList:"MetadataEntry" type:"list"` } // String returns the string representation -func (s ListBucketMetricsConfigurationsInput) String() string { +func (s Location) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketMetricsConfigurationsInput) GoString() string { +func (s Location) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketMetricsConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketMetricsConfigurationsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *Location) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Location"} + if s.BucketName == nil { + invalidParams.Add(request.NewErrParamRequired("BucketName")) + } + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) + } + if s.AccessControlList != nil { + for i, v := range s.AccessControlList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AccessControlList", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Encryption != nil { + if err := s.Encryption.Validate(); err != nil { + invalidParams.AddNested("Encryption", err.(request.ErrInvalidParams)) + } + } + if s.Tagging != nil { + if err := s.Tagging.Validate(); err != nil { + invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -13050,173 +17219,250 @@ func (s *ListBucketMetricsConfigurationsInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *ListBucketMetricsConfigurationsInput) SetBucket(v string) *ListBucketMetricsConfigurationsInput { - s.Bucket = &v +// SetAccessControlList sets the AccessControlList field's value. +func (s *Location) SetAccessControlList(v []*Grant) *Location { + s.AccessControlList = v return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsInput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsInput { - s.ContinuationToken = &v +// SetBucketName sets the BucketName field's value. +func (s *Location) SetBucketName(v string) *Location { + s.BucketName = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsOutput -type ListBucketMetricsConfigurationsOutput struct { - _ struct{} `type:"structure"` +// SetCannedACL sets the CannedACL field's value. +func (s *Location) SetCannedACL(v string) *Location { + s.CannedACL = &v + return s +} - // The marker that is used as a starting point for this metrics configuration - // list response. This value is present if it was sent in the request. - ContinuationToken *string `type:"string"` +// SetEncryption sets the Encryption field's value. +func (s *Location) SetEncryption(v *Encryption) *Location { + s.Encryption = v + return s +} - // Indicates whether the returned list of metrics configurations is complete. - // A value of true indicates that the list is not complete and the NextContinuationToken - // will be provided for a subsequent request. - IsTruncated *bool `type:"boolean"` +// SetPrefix sets the Prefix field's value. +func (s *Location) SetPrefix(v string) *Location { + s.Prefix = &v + return s +} - // The list of metrics configurations for a bucket. - MetricsConfigurationList []*MetricsConfiguration `locationName:"MetricsConfiguration" type:"list" flattened:"true"` +// SetStorageClass sets the StorageClass field's value. +func (s *Location) SetStorageClass(v string) *Location { + s.StorageClass = &v + return s +} - // The marker used to continue a metrics configuration listing that has been - // truncated. Use the NextContinuationToken from a previously truncated list - // response to continue the listing. The continuation token is an opaque value - // that Amazon S3 understands. - NextContinuationToken *string `type:"string"` +// SetTagging sets the Tagging field's value. +func (s *Location) SetTagging(v *Tagging) *Location { + s.Tagging = v + return s +} + +// SetUserMetadata sets the UserMetadata field's value. +func (s *Location) SetUserMetadata(v []*MetadataEntry) *Location { + s.UserMetadata = v + return s +} + +// Container for logging information. Presence of this element indicates that +// logging is enabled. Parameters TargetBucket and TargetPrefix are required +// in this case. +type LoggingEnabled struct { + _ struct{} `type:"structure"` + + // Specifies the bucket where you want Amazon S3 to store server access logs. + // You can have your logs delivered to any bucket that you own, including the + // same bucket that is being logged. You can also configure multiple buckets + // to deliver their logs to the same target bucket. In this case you should + // choose a different TargetPrefix for each source bucket so that the delivered + // log files can be distinguished by key. + // + // TargetBucket is a required field + TargetBucket *string `type:"string" required:"true"` + + TargetGrants []*TargetGrant `locationNameList:"Grant" type:"list"` + + // This element lets you specify a prefix for the keys that the log files will + // be stored under. + // + // TargetPrefix is a required field + TargetPrefix *string `type:"string" required:"true"` } // String returns the string representation -func (s ListBucketMetricsConfigurationsOutput) String() string { +func (s LoggingEnabled) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketMetricsConfigurationsOutput) GoString() string { +func (s LoggingEnabled) GoString() string { return s.String() } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { - s.ContinuationToken = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *LoggingEnabled) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LoggingEnabled"} + if s.TargetBucket == nil { + invalidParams.Add(request.NewErrParamRequired("TargetBucket")) + } + if s.TargetPrefix == nil { + invalidParams.Add(request.NewErrParamRequired("TargetPrefix")) + } + if s.TargetGrants != nil { + for i, v := range s.TargetGrants { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TargetGrants", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketMetricsConfigurationsOutput { - s.IsTruncated = &v +// SetTargetBucket sets the TargetBucket field's value. +func (s *LoggingEnabled) SetTargetBucket(v string) *LoggingEnabled { + s.TargetBucket = &v return s } -// SetMetricsConfigurationList sets the MetricsConfigurationList field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetMetricsConfigurationList(v []*MetricsConfiguration) *ListBucketMetricsConfigurationsOutput { - s.MetricsConfigurationList = v +// SetTargetGrants sets the TargetGrants field's value. +func (s *LoggingEnabled) SetTargetGrants(v []*TargetGrant) *LoggingEnabled { + s.TargetGrants = v return s } -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { - s.NextContinuationToken = &v +// SetTargetPrefix sets the TargetPrefix field's value. +func (s *LoggingEnabled) SetTargetPrefix(v string) *LoggingEnabled { + s.TargetPrefix = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsInput -type ListBucketsInput struct { +// A metadata key-value pair to store with an object. +type MetadataEntry struct { _ struct{} `type:"structure"` + + Name *string `type:"string"` + + Value *string `type:"string"` } // String returns the string representation -func (s ListBucketsInput) String() string { +func (s MetadataEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketsInput) GoString() string { +func (s MetadataEntry) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsOutput -type ListBucketsOutput struct { +// SetName sets the Name field's value. +func (s *MetadataEntry) SetName(v string) *MetadataEntry { + s.Name = &v + return s +} + +// SetValue sets the Value field's value. +func (s *MetadataEntry) SetValue(v string) *MetadataEntry { + s.Value = &v + return s +} + +type MetricsAndOperator struct { _ struct{} `type:"structure"` - Buckets []*Bucket `locationNameList:"Bucket" type:"list"` + // The prefix used when evaluating an AND predicate. + Prefix *string `type:"string"` - Owner *Owner `type:"structure"` + // The list of tags used when evaluating an AND predicate. + Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` } // String returns the string representation -func (s ListBucketsOutput) String() string { +func (s MetricsAndOperator) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBucketsOutput) GoString() string { +func (s MetricsAndOperator) GoString() string { return s.String() } -// SetBuckets sets the Buckets field's value. -func (s *ListBucketsOutput) SetBuckets(v []*Bucket) *ListBucketsOutput { - s.Buckets = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *MetricsAndOperator) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MetricsAndOperator"} + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPrefix sets the Prefix field's value. +func (s *MetricsAndOperator) SetPrefix(v string) *MetricsAndOperator { + s.Prefix = &v return s } -// SetOwner sets the Owner field's value. -func (s *ListBucketsOutput) SetOwner(v *Owner) *ListBucketsOutput { - s.Owner = v +// SetTags sets the Tags field's value. +func (s *MetricsAndOperator) SetTags(v []*Tag) *MetricsAndOperator { + s.Tags = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsRequest -type ListMultipartUploadsInput struct { +type MetricsConfiguration struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - - // Together with upload-id-marker, this parameter specifies the multipart upload - // after which listing should begin. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - - // Sets the maximum number of multipart uploads, from 1 to 1,000, to return - // in the response body. 1,000 is the maximum number of uploads that can be - // returned in a response. - MaxUploads *int64 `location:"querystring" locationName:"max-uploads" type:"integer"` - - // Lists in-progress uploads only for those keys that begin with the specified - // prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` + // Specifies a metrics configuration filter. The metrics configuration will + // only include objects that meet the filter's criteria. A filter must be a + // prefix, a tag, or a conjunction (MetricsAndOperator). + Filter *MetricsFilter `type:"structure"` - // Together with key-marker, specifies the multipart upload after which listing - // should begin. If key-marker is not specified, the upload-id-marker parameter - // is ignored. - UploadIdMarker *string `location:"querystring" locationName:"upload-id-marker" type:"string"` + // The ID used to identify the metrics configuration. + // + // Id is a required field + Id *string `type:"string" required:"true"` } // String returns the string representation -func (s ListMultipartUploadsInput) String() string { +func (s MetricsConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListMultipartUploadsInput) GoString() string { +func (s MetricsConfiguration) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListMultipartUploadsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListMultipartUploadsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *MetricsConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MetricsConfiguration"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Filter != nil { + if err := s.Filter.Validate(); err != nil { + invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -13225,222 +17471,276 @@ func (s *ListMultipartUploadsInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *ListMultipartUploadsInput) SetBucket(v string) *ListMultipartUploadsInput { - s.Bucket = &v +// SetFilter sets the Filter field's value. +func (s *MetricsConfiguration) SetFilter(v *MetricsFilter) *MetricsConfiguration { + s.Filter = v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListMultipartUploadsInput) SetDelimiter(v string) *ListMultipartUploadsInput { - s.Delimiter = &v +// SetId sets the Id field's value. +func (s *MetricsConfiguration) SetId(v string) *MetricsConfiguration { + s.Id = &v return s } -// SetEncodingType sets the EncodingType field's value. -func (s *ListMultipartUploadsInput) SetEncodingType(v string) *ListMultipartUploadsInput { - s.EncodingType = &v - return s -} +type MetricsFilter struct { + _ struct{} `type:"structure"` -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListMultipartUploadsInput) SetKeyMarker(v string) *ListMultipartUploadsInput { - s.KeyMarker = &v - return s -} + // A conjunction (logical AND) of predicates, which is used in evaluating a + // metrics filter. The operator must have at least two predicates, and an object + // must match all of the predicates in order for the filter to apply. + And *MetricsAndOperator `type:"structure"` -// SetMaxUploads sets the MaxUploads field's value. -func (s *ListMultipartUploadsInput) SetMaxUploads(v int64) *ListMultipartUploadsInput { - s.MaxUploads = &v - return s -} + // The prefix used when evaluating a metrics filter. + Prefix *string `type:"string"` -// SetPrefix sets the Prefix field's value. -func (s *ListMultipartUploadsInput) SetPrefix(v string) *ListMultipartUploadsInput { - s.Prefix = &v - return s + // The tag used when evaluating a metrics filter. + Tag *Tag `type:"structure"` } -// SetUploadIdMarker sets the UploadIdMarker field's value. -func (s *ListMultipartUploadsInput) SetUploadIdMarker(v string) *ListMultipartUploadsInput { - s.UploadIdMarker = &v - return s +// String returns the string representation +func (s MetricsFilter) String() string { + return awsutil.Prettify(s) } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsOutput -type ListMultipartUploadsOutput struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s MetricsFilter) GoString() string { + return s.String() +} - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *MetricsFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MetricsFilter"} + if s.And != nil { + if err := s.And.Validate(); err != nil { + invalidParams.AddNested("And", err.(request.ErrInvalidParams)) + } + } + if s.Tag != nil { + if err := s.Tag.Validate(); err != nil { + invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) + } + } - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - Delimiter *string `type:"string"` +// SetAnd sets the And field's value. +func (s *MetricsFilter) SetAnd(v *MetricsAndOperator) *MetricsFilter { + s.And = v + return s +} - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` +// SetPrefix sets the Prefix field's value. +func (s *MetricsFilter) SetPrefix(v string) *MetricsFilter { + s.Prefix = &v + return s +} - // Indicates whether the returned list of multipart uploads is truncated. A - // value of true indicates that the list was truncated. The list can be truncated - // if the number of multipart uploads exceeds the limit allowed or specified - // by max uploads. - IsTruncated *bool `type:"boolean"` +// SetTag sets the Tag field's value. +func (s *MetricsFilter) SetTag(v *Tag) *MetricsFilter { + s.Tag = v + return s +} - // The key at or after which the listing began. - KeyMarker *string `type:"string"` +type MultipartUpload struct { + _ struct{} `type:"structure"` - // Maximum number of multipart uploads that could have been included in the - // response. - MaxUploads *int64 `type:"integer"` + // Date and time at which the multipart upload was initiated. + Initiated *time.Time `type:"timestamp"` - // When a list is truncated, this element specifies the value that should be - // used for the key-marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` + // Identifies who initiated the multipart upload. + Initiator *Initiator `type:"structure"` - // When a list is truncated, this element specifies the value that should be - // used for the upload-id-marker request parameter in a subsequent request. - NextUploadIdMarker *string `type:"string"` + // Key of the object for which the multipart upload was initiated. + Key *string `min:"1" type:"string"` - // When a prefix is provided in the request, this field contains the specified - // prefix. The result contains only keys starting with the specified prefix. - Prefix *string `type:"string"` + Owner *Owner `type:"structure"` - // Upload ID after which listing began. - UploadIdMarker *string `type:"string"` + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"StorageClass"` - Uploads []*MultipartUpload `locationName:"Upload" type:"list" flattened:"true"` + // Upload ID that identifies the multipart upload. + UploadId *string `type:"string"` } // String returns the string representation -func (s ListMultipartUploadsOutput) String() string { +func (s MultipartUpload) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListMultipartUploadsOutput) GoString() string { +func (s MultipartUpload) GoString() string { return s.String() } -// SetBucket sets the Bucket field's value. -func (s *ListMultipartUploadsOutput) SetBucket(v string) *ListMultipartUploadsOutput { - s.Bucket = &v +// SetInitiated sets the Initiated field's value. +func (s *MultipartUpload) SetInitiated(v time.Time) *MultipartUpload { + s.Initiated = &v return s } -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListMultipartUploadsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListMultipartUploadsOutput { - s.CommonPrefixes = v +// SetInitiator sets the Initiator field's value. +func (s *MultipartUpload) SetInitiator(v *Initiator) *MultipartUpload { + s.Initiator = v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListMultipartUploadsOutput) SetDelimiter(v string) *ListMultipartUploadsOutput { - s.Delimiter = &v +// SetKey sets the Key field's value. +func (s *MultipartUpload) SetKey(v string) *MultipartUpload { + s.Key = &v return s } -// SetEncodingType sets the EncodingType field's value. -func (s *ListMultipartUploadsOutput) SetEncodingType(v string) *ListMultipartUploadsOutput { - s.EncodingType = &v +// SetOwner sets the Owner field's value. +func (s *MultipartUpload) SetOwner(v *Owner) *MultipartUpload { + s.Owner = v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListMultipartUploadsOutput) SetIsTruncated(v bool) *ListMultipartUploadsOutput { - s.IsTruncated = &v +// SetStorageClass sets the StorageClass field's value. +func (s *MultipartUpload) SetStorageClass(v string) *MultipartUpload { + s.StorageClass = &v return s } -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListMultipartUploadsOutput) SetKeyMarker(v string) *ListMultipartUploadsOutput { - s.KeyMarker = &v +// SetUploadId sets the UploadId field's value. +func (s *MultipartUpload) SetUploadId(v string) *MultipartUpload { + s.UploadId = &v return s } -// SetMaxUploads sets the MaxUploads field's value. -func (s *ListMultipartUploadsOutput) SetMaxUploads(v int64) *ListMultipartUploadsOutput { - s.MaxUploads = &v - return s -} +// Specifies when noncurrent object versions expire. Upon expiration, Amazon +// S3 permanently deletes the noncurrent object versions. You set this lifecycle +// configuration action on a bucket that has versioning enabled (or suspended) +// to request that Amazon S3 delete noncurrent object versions at a specific +// period in the object's lifetime. +type NoncurrentVersionExpiration struct { + _ struct{} `type:"structure"` -// SetNextKeyMarker sets the NextKeyMarker field's value. -func (s *ListMultipartUploadsOutput) SetNextKeyMarker(v string) *ListMultipartUploadsOutput { - s.NextKeyMarker = &v - return s + // Specifies the number of days an object is noncurrent before Amazon S3 can + // perform the associated action. For information about the noncurrent days + // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent + // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) in + // the Amazon Simple Storage Service Developer Guide. + NoncurrentDays *int64 `type:"integer"` } -// SetNextUploadIdMarker sets the NextUploadIdMarker field's value. -func (s *ListMultipartUploadsOutput) SetNextUploadIdMarker(v string) *ListMultipartUploadsOutput { - s.NextUploadIdMarker = &v - return s +// String returns the string representation +func (s NoncurrentVersionExpiration) String() string { + return awsutil.Prettify(s) } -// SetPrefix sets the Prefix field's value. -func (s *ListMultipartUploadsOutput) SetPrefix(v string) *ListMultipartUploadsOutput { - s.Prefix = &v - return s +// GoString returns the string representation +func (s NoncurrentVersionExpiration) GoString() string { + return s.String() } -// SetUploadIdMarker sets the UploadIdMarker field's value. -func (s *ListMultipartUploadsOutput) SetUploadIdMarker(v string) *ListMultipartUploadsOutput { - s.UploadIdMarker = &v +// SetNoncurrentDays sets the NoncurrentDays field's value. +func (s *NoncurrentVersionExpiration) SetNoncurrentDays(v int64) *NoncurrentVersionExpiration { + s.NoncurrentDays = &v return s } -// SetUploads sets the Uploads field's value. -func (s *ListMultipartUploadsOutput) SetUploads(v []*MultipartUpload) *ListMultipartUploadsOutput { - s.Uploads = v - return s +// Container for the transition rule that describes when noncurrent objects +// transition to the STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING or GLACIER +// storage class. If your bucket is versioning-enabled (or versioning is suspended), +// you can set this action to request that Amazon S3 transition noncurrent object +// versions to the STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING or GLACIER storage +// class at a specific period in the object's lifetime. +type NoncurrentVersionTransition struct { + _ struct{} `type:"structure"` + + // Specifies the number of days an object is noncurrent before Amazon S3 can + // perform the associated action. For information about the noncurrent days + // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent + // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) in + // the Amazon Simple Storage Service Developer Guide. + NoncurrentDays *int64 `type:"integer"` + + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"TransitionStorageClass"` } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsRequest -type ListObjectVersionsInput struct { - _ struct{} `type:"structure"` +// String returns the string representation +func (s NoncurrentVersionTransition) String() string { + return awsutil.Prettify(s) +} - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// GoString returns the string representation +func (s NoncurrentVersionTransition) GoString() string { + return s.String() +} - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` +// SetNoncurrentDays sets the NoncurrentDays field's value. +func (s *NoncurrentVersionTransition) SetNoncurrentDays(v int64) *NoncurrentVersionTransition { + s.NoncurrentDays = &v + return s +} - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` +// SetStorageClass sets the StorageClass field's value. +func (s *NoncurrentVersionTransition) SetStorageClass(v string) *NoncurrentVersionTransition { + s.StorageClass = &v + return s +} - // Specifies the key to start with when listing objects in a bucket. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` +// A container for specifying the notification configuration of the bucket. +// If this element is empty, notifications are turned off for the bucket. +type NotificationConfiguration struct { + _ struct{} `type:"structure"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` + LambdaFunctionConfigurations []*LambdaFunctionConfiguration `locationName:"CloudFunctionConfiguration" type:"list" flattened:"true"` - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` + QueueConfigurations []*QueueConfiguration `locationName:"QueueConfiguration" type:"list" flattened:"true"` - // Specifies the object version you want to start listing from. - VersionIdMarker *string `location:"querystring" locationName:"version-id-marker" type:"string"` + TopicConfigurations []*TopicConfiguration `locationName:"TopicConfiguration" type:"list" flattened:"true"` } // String returns the string representation -func (s ListObjectVersionsInput) String() string { +func (s NotificationConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectVersionsInput) GoString() string { +func (s NotificationConfiguration) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectVersionsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *NotificationConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "NotificationConfiguration"} + if s.LambdaFunctionConfigurations != nil { + for i, v := range s.LambdaFunctionConfigurations { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LambdaFunctionConfigurations", i), err.(request.ErrInvalidParams)) + } + } + } + if s.QueueConfigurations != nil { + for i, v := range s.QueueConfigurations { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueueConfigurations", i), err.(request.ErrInvalidParams)) + } + } + } + if s.TopicConfigurations != nil { + for i, v := range s.TopicConfigurations { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TopicConfigurations", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -13449,686 +17749,784 @@ func (s *ListObjectVersionsInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *ListObjectVersionsInput) SetBucket(v string) *ListObjectVersionsInput { - s.Bucket = &v +// SetLambdaFunctionConfigurations sets the LambdaFunctionConfigurations field's value. +func (s *NotificationConfiguration) SetLambdaFunctionConfigurations(v []*LambdaFunctionConfiguration) *NotificationConfiguration { + s.LambdaFunctionConfigurations = v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectVersionsInput) SetDelimiter(v string) *ListObjectVersionsInput { - s.Delimiter = &v +// SetQueueConfigurations sets the QueueConfigurations field's value. +func (s *NotificationConfiguration) SetQueueConfigurations(v []*QueueConfiguration) *NotificationConfiguration { + s.QueueConfigurations = v return s } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectVersionsInput) SetEncodingType(v string) *ListObjectVersionsInput { - s.EncodingType = &v +// SetTopicConfigurations sets the TopicConfigurations field's value. +func (s *NotificationConfiguration) SetTopicConfigurations(v []*TopicConfiguration) *NotificationConfiguration { + s.TopicConfigurations = v return s } -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListObjectVersionsInput) SetKeyMarker(v string) *ListObjectVersionsInput { - s.KeyMarker = &v - return s +type NotificationConfigurationDeprecated struct { + _ struct{} `type:"structure"` + + CloudFunctionConfiguration *CloudFunctionConfiguration `type:"structure"` + + QueueConfiguration *QueueConfigurationDeprecated `type:"structure"` + + TopicConfiguration *TopicConfigurationDeprecated `type:"structure"` } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectVersionsInput) SetMaxKeys(v int64) *ListObjectVersionsInput { - s.MaxKeys = &v +// String returns the string representation +func (s NotificationConfigurationDeprecated) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NotificationConfigurationDeprecated) GoString() string { + return s.String() +} + +// SetCloudFunctionConfiguration sets the CloudFunctionConfiguration field's value. +func (s *NotificationConfigurationDeprecated) SetCloudFunctionConfiguration(v *CloudFunctionConfiguration) *NotificationConfigurationDeprecated { + s.CloudFunctionConfiguration = v return s } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectVersionsInput) SetPrefix(v string) *ListObjectVersionsInput { - s.Prefix = &v +// SetQueueConfiguration sets the QueueConfiguration field's value. +func (s *NotificationConfigurationDeprecated) SetQueueConfiguration(v *QueueConfigurationDeprecated) *NotificationConfigurationDeprecated { + s.QueueConfiguration = v return s } -// SetVersionIdMarker sets the VersionIdMarker field's value. -func (s *ListObjectVersionsInput) SetVersionIdMarker(v string) *ListObjectVersionsInput { - s.VersionIdMarker = &v +// SetTopicConfiguration sets the TopicConfiguration field's value. +func (s *NotificationConfigurationDeprecated) SetTopicConfiguration(v *TopicConfigurationDeprecated) *NotificationConfigurationDeprecated { + s.TopicConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsOutput -type ListObjectVersionsOutput struct { +// A container for object key name filtering rules. For information about key +// name filtering, see Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) +// in the Amazon Simple Storage Service Developer Guide. +type NotificationConfigurationFilter struct { _ struct{} `type:"structure"` - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - DeleteMarkers []*DeleteMarkerEntry `locationName:"DeleteMarker" type:"list" flattened:"true"` - - Delimiter *string `type:"string"` + // A container for object key name prefix and suffix filtering rules. + Key *KeyFilter `locationName:"S3Key" type:"structure"` +} - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` +// String returns the string representation +func (s NotificationConfigurationFilter) String() string { + return awsutil.Prettify(s) +} - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. If your results were truncated, you can - // make a follow-up paginated request using the NextKeyMarker and NextVersionIdMarker - // response parameters as a starting place in another request to return the - // rest of the results. - IsTruncated *bool `type:"boolean"` +// GoString returns the string representation +func (s NotificationConfigurationFilter) GoString() string { + return s.String() +} - // Marks the last Key returned in a truncated response. - KeyMarker *string `type:"string"` +// SetKey sets the Key field's value. +func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConfigurationFilter { + s.Key = v + return s +} - MaxKeys *int64 `type:"integer"` +type Object struct { + _ struct{} `type:"structure"` - Name *string `type:"string"` + ETag *string `type:"string"` - // Use this value for the key marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` + Key *string `min:"1" type:"string"` - // Use this value for the next version id marker parameter in a subsequent request. - NextVersionIdMarker *string `type:"string"` + LastModified *time.Time `type:"timestamp"` - Prefix *string `type:"string"` + Owner *Owner `type:"structure"` - VersionIdMarker *string `type:"string"` + Size *int64 `type:"integer"` - Versions []*ObjectVersion `locationName:"Version" type:"list" flattened:"true"` + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"ObjectStorageClass"` } // String returns the string representation -func (s ListObjectVersionsOutput) String() string { +func (s Object) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectVersionsOutput) GoString() string { +func (s Object) GoString() string { return s.String() } -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectVersionsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectVersionsOutput { - s.CommonPrefixes = v +// SetETag sets the ETag field's value. +func (s *Object) SetETag(v string) *Object { + s.ETag = &v return s } -// SetDeleteMarkers sets the DeleteMarkers field's value. -func (s *ListObjectVersionsOutput) SetDeleteMarkers(v []*DeleteMarkerEntry) *ListObjectVersionsOutput { - s.DeleteMarkers = v +// SetKey sets the Key field's value. +func (s *Object) SetKey(v string) *Object { + s.Key = &v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectVersionsOutput) SetDelimiter(v string) *ListObjectVersionsOutput { - s.Delimiter = &v +// SetLastModified sets the LastModified field's value. +func (s *Object) SetLastModified(v time.Time) *Object { + s.LastModified = &v return s } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectVersionsOutput) SetEncodingType(v string) *ListObjectVersionsOutput { - s.EncodingType = &v +// SetOwner sets the Owner field's value. +func (s *Object) SetOwner(v *Owner) *Object { + s.Owner = v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectVersionsOutput) SetIsTruncated(v bool) *ListObjectVersionsOutput { - s.IsTruncated = &v +// SetSize sets the Size field's value. +func (s *Object) SetSize(v int64) *Object { + s.Size = &v return s } -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListObjectVersionsOutput) SetKeyMarker(v string) *ListObjectVersionsOutput { - s.KeyMarker = &v +// SetStorageClass sets the StorageClass field's value. +func (s *Object) SetStorageClass(v string) *Object { + s.StorageClass = &v return s } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectVersionsOutput) SetMaxKeys(v int64) *ListObjectVersionsOutput { - s.MaxKeys = &v - return s -} +type ObjectIdentifier struct { + _ struct{} `type:"structure"` -// SetName sets the Name field's value. -func (s *ListObjectVersionsOutput) SetName(v string) *ListObjectVersionsOutput { - s.Name = &v - return s + // Key name of the object to delete. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // VersionId for the specific version of the object to delete. + VersionId *string `type:"string"` } -// SetNextKeyMarker sets the NextKeyMarker field's value. -func (s *ListObjectVersionsOutput) SetNextKeyMarker(v string) *ListObjectVersionsOutput { - s.NextKeyMarker = &v - return s +// String returns the string representation +func (s ObjectIdentifier) String() string { + return awsutil.Prettify(s) } -// SetNextVersionIdMarker sets the NextVersionIdMarker field's value. -func (s *ListObjectVersionsOutput) SetNextVersionIdMarker(v string) *ListObjectVersionsOutput { - s.NextVersionIdMarker = &v - return s +// GoString returns the string representation +func (s ObjectIdentifier) GoString() string { + return s.String() } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectVersionsOutput) SetPrefix(v string) *ListObjectVersionsOutput { - s.Prefix = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ObjectIdentifier) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ObjectIdentifier"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetVersionIdMarker sets the VersionIdMarker field's value. -func (s *ListObjectVersionsOutput) SetVersionIdMarker(v string) *ListObjectVersionsOutput { - s.VersionIdMarker = &v +// SetKey sets the Key field's value. +func (s *ObjectIdentifier) SetKey(v string) *ObjectIdentifier { + s.Key = &v return s } -// SetVersions sets the Versions field's value. -func (s *ListObjectVersionsOutput) SetVersions(v []*ObjectVersion) *ListObjectVersionsOutput { - s.Versions = v +// SetVersionId sets the VersionId field's value. +func (s *ObjectIdentifier) SetVersionId(v string) *ObjectIdentifier { + s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsRequest -type ListObjectsInput struct { +// The container element for Object Lock configuration parameters. +type ObjectLockConfiguration struct { _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Indicates whether this bucket has an Object Lock configuration enabled. + ObjectLockEnabled *string `type:"string" enum:"ObjectLockEnabled"` - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` + // The Object Lock rule in place for the specified object. + Rule *ObjectLockRule `type:"structure"` +} - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` +// String returns the string representation +func (s ObjectLockConfiguration) String() string { + return awsutil.Prettify(s) +} - // Specifies the key to start with when listing objects in a bucket. - Marker *string `location:"querystring" locationName:"marker" type:"string"` +// GoString returns the string representation +func (s ObjectLockConfiguration) GoString() string { + return s.String() +} - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` +// SetObjectLockEnabled sets the ObjectLockEnabled field's value. +func (s *ObjectLockConfiguration) SetObjectLockEnabled(v string) *ObjectLockConfiguration { + s.ObjectLockEnabled = &v + return s +} - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` +// SetRule sets the Rule field's value. +func (s *ObjectLockConfiguration) SetRule(v *ObjectLockRule) *ObjectLockConfiguration { + s.Rule = v + return s +} - // Confirms that the requester knows that she or he will be charged for the - // list objects request. Bucket owners need not specify this parameter in their - // requests. - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` +// A Legal Hold configuration for an object. +type ObjectLockLegalHold struct { + _ struct{} `type:"structure"` + + // Indicates whether the specified object has a Legal Hold in place. + Status *string `type:"string" enum:"ObjectLockLegalHoldStatus"` } // String returns the string representation -func (s ListObjectsInput) String() string { +func (s ObjectLockLegalHold) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectsInput) GoString() string { +func (s ObjectLockLegalHold) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } +// SetStatus sets the Status field's value. +func (s *ObjectLockLegalHold) SetStatus(v string) *ObjectLockLegalHold { + s.Status = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// A Retention configuration for an object. +type ObjectLockRetention struct { + _ struct{} `type:"structure"` + + // Indicates the Retention mode for the specified object. + Mode *string `type:"string" enum:"ObjectLockRetentionMode"` + + // The date on which this Object Lock Retention will expire. + RetainUntilDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` } -// SetBucket sets the Bucket field's value. -func (s *ListObjectsInput) SetBucket(v string) *ListObjectsInput { - s.Bucket = &v - return s +// String returns the string representation +func (s ObjectLockRetention) String() string { + return awsutil.Prettify(s) } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsInput) SetDelimiter(v string) *ListObjectsInput { - s.Delimiter = &v - return s +// GoString returns the string representation +func (s ObjectLockRetention) GoString() string { + return s.String() } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsInput) SetEncodingType(v string) *ListObjectsInput { - s.EncodingType = &v +// SetMode sets the Mode field's value. +func (s *ObjectLockRetention) SetMode(v string) *ObjectLockRetention { + s.Mode = &v return s } -// SetMarker sets the Marker field's value. -func (s *ListObjectsInput) SetMarker(v string) *ListObjectsInput { - s.Marker = &v +// SetRetainUntilDate sets the RetainUntilDate field's value. +func (s *ObjectLockRetention) SetRetainUntilDate(v time.Time) *ObjectLockRetention { + s.RetainUntilDate = &v return s } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsInput) SetMaxKeys(v int64) *ListObjectsInput { - s.MaxKeys = &v - return s +// The container element for an Object Lock rule. +type ObjectLockRule struct { + _ struct{} `type:"structure"` + + // The default retention period that you want to apply to new objects placed + // in the specified bucket. + DefaultRetention *DefaultRetention `type:"structure"` } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsInput) SetPrefix(v string) *ListObjectsInput { - s.Prefix = &v - return s +// String returns the string representation +func (s ObjectLockRule) String() string { + return awsutil.Prettify(s) } -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListObjectsInput) SetRequestPayer(v string) *ListObjectsInput { - s.RequestPayer = &v +// GoString returns the string representation +func (s ObjectLockRule) GoString() string { + return s.String() +} + +// SetDefaultRetention sets the DefaultRetention field's value. +func (s *ObjectLockRule) SetDefaultRetention(v *DefaultRetention) *ObjectLockRule { + s.DefaultRetention = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsOutput -type ListObjectsOutput struct { +type ObjectVersion struct { _ struct{} `type:"structure"` - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - Contents []*Object `type:"list" flattened:"true"` - - Delimiter *string `type:"string"` + ETag *string `type:"string"` - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` + // Specifies whether the object is (true) or is not (false) the latest version + // of an object. + IsLatest *bool `type:"boolean"` - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. - IsTruncated *bool `type:"boolean"` + // The object key. + Key *string `min:"1" type:"string"` - Marker *string `type:"string"` + // Date and time the object was last modified. + LastModified *time.Time `type:"timestamp"` - MaxKeys *int64 `type:"integer"` + Owner *Owner `type:"structure"` - Name *string `type:"string"` + // Size in bytes of the object. + Size *int64 `type:"integer"` - // When response is truncated (the IsTruncated element value in the response - // is true), you can use the key name in this field as marker in the subsequent - // request to get next set of objects. Amazon S3 lists objects in alphabetical - // order Note: This element is returned only if you have delimiter request parameter - // specified. If response does not include the NextMaker and it is truncated, - // you can use the value of the last Key in the response as the marker in the - // subsequent request to get the next set of object keys. - NextMarker *string `type:"string"` + // The class of storage used to store the object. + StorageClass *string `type:"string" enum:"ObjectVersionStorageClass"` - Prefix *string `type:"string"` + // Version ID of an object. + VersionId *string `type:"string"` } // String returns the string representation -func (s ListObjectsOutput) String() string { +func (s ObjectVersion) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectsOutput) GoString() string { +func (s ObjectVersion) GoString() string { return s.String() } -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsOutput { - s.CommonPrefixes = v +// SetETag sets the ETag field's value. +func (s *ObjectVersion) SetETag(v string) *ObjectVersion { + s.ETag = &v return s } -// SetContents sets the Contents field's value. -func (s *ListObjectsOutput) SetContents(v []*Object) *ListObjectsOutput { - s.Contents = v +// SetIsLatest sets the IsLatest field's value. +func (s *ObjectVersion) SetIsLatest(v bool) *ObjectVersion { + s.IsLatest = &v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsOutput) SetDelimiter(v string) *ListObjectsOutput { - s.Delimiter = &v +// SetKey sets the Key field's value. +func (s *ObjectVersion) SetKey(v string) *ObjectVersion { + s.Key = &v return s } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsOutput) SetEncodingType(v string) *ListObjectsOutput { - s.EncodingType = &v +// SetLastModified sets the LastModified field's value. +func (s *ObjectVersion) SetLastModified(v time.Time) *ObjectVersion { + s.LastModified = &v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectsOutput) SetIsTruncated(v bool) *ListObjectsOutput { - s.IsTruncated = &v +// SetOwner sets the Owner field's value. +func (s *ObjectVersion) SetOwner(v *Owner) *ObjectVersion { + s.Owner = v return s } -// SetMarker sets the Marker field's value. -func (s *ListObjectsOutput) SetMarker(v string) *ListObjectsOutput { - s.Marker = &v +// SetSize sets the Size field's value. +func (s *ObjectVersion) SetSize(v int64) *ObjectVersion { + s.Size = &v return s } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsOutput) SetMaxKeys(v int64) *ListObjectsOutput { - s.MaxKeys = &v +// SetStorageClass sets the StorageClass field's value. +func (s *ObjectVersion) SetStorageClass(v string) *ObjectVersion { + s.StorageClass = &v return s } -// SetName sets the Name field's value. -func (s *ListObjectsOutput) SetName(v string) *ListObjectsOutput { - s.Name = &v +// SetVersionId sets the VersionId field's value. +func (s *ObjectVersion) SetVersionId(v string) *ObjectVersion { + s.VersionId = &v return s } -// SetNextMarker sets the NextMarker field's value. -func (s *ListObjectsOutput) SetNextMarker(v string) *ListObjectsOutput { - s.NextMarker = &v - return s +// Describes the location where the restore job's output is stored. +type OutputLocation struct { + _ struct{} `type:"structure"` + + // Describes an S3 location that will receive the results of the restore request. + S3 *Location `type:"structure"` } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsOutput) SetPrefix(v string) *ListObjectsOutput { - s.Prefix = &v +// String returns the string representation +func (s OutputLocation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OutputLocation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OutputLocation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OutputLocation"} + if s.S3 != nil { + if err := s.S3.Validate(); err != nil { + invalidParams.AddNested("S3", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetS3 sets the S3 field's value. +func (s *OutputLocation) SetS3(v *Location) *OutputLocation { + s.S3 = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Request -type ListObjectsV2Input struct { +// Describes how results of the Select job are serialized. +type OutputSerialization struct { _ struct{} `type:"structure"` - // Name of the bucket to list. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Describes the serialization of CSV-encoded Select results. + CSV *CSVOutput `type:"structure"` - // ContinuationToken indicates Amazon S3 that the list is being continued on - // this bucket with a token. ContinuationToken is obfuscated and is not a real - // key - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + // Specifies JSON as request's output serialization format. + JSON *JSONOutput `type:"structure"` +} - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` +// String returns the string representation +func (s OutputSerialization) String() string { + return awsutil.Prettify(s) +} - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` +// GoString returns the string representation +func (s OutputSerialization) GoString() string { + return s.String() +} - // The owner field is not present in listV2 by default, if you want to return - // owner field with each key in the result then set the fetch owner field to - // true - FetchOwner *bool `location:"querystring" locationName:"fetch-owner" type:"boolean"` +// SetCSV sets the CSV field's value. +func (s *OutputSerialization) SetCSV(v *CSVOutput) *OutputSerialization { + s.CSV = v + return s +} - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` +// SetJSON sets the JSON field's value. +func (s *OutputSerialization) SetJSON(v *JSONOutput) *OutputSerialization { + s.JSON = v + return s +} - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` +type Owner struct { + _ struct{} `type:"structure"` - // Confirms that the requester knows that she or he will be charged for the - // list objects request in V2 style. Bucket owners need not specify this parameter - // in their requests. - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + DisplayName *string `type:"string"` - // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts - // listing after this specified key. StartAfter can be any key in the bucket - StartAfter *string `location:"querystring" locationName:"start-after" type:"string"` + ID *string `type:"string"` } // String returns the string representation -func (s ListObjectsV2Input) String() string { +func (s Owner) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectsV2Input) GoString() string { +func (s Owner) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectsV2Input) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectsV2Input"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDisplayName sets the DisplayName field's value. +func (s *Owner) SetDisplayName(v string) *Owner { + s.DisplayName = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *ListObjectsV2Input) SetBucket(v string) *ListObjectsV2Input { - s.Bucket = &v +// SetID sets the ID field's value. +func (s *Owner) SetID(v string) *Owner { + s.ID = &v return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListObjectsV2Input) SetContinuationToken(v string) *ListObjectsV2Input { - s.ContinuationToken = &v - return s +type ParquetInput struct { + _ struct{} `type:"structure"` } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsV2Input) SetDelimiter(v string) *ListObjectsV2Input { - s.Delimiter = &v - return s +// String returns the string representation +func (s ParquetInput) String() string { + return awsutil.Prettify(s) } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsV2Input) SetEncodingType(v string) *ListObjectsV2Input { - s.EncodingType = &v - return s +// GoString returns the string representation +func (s ParquetInput) GoString() string { + return s.String() } -// SetFetchOwner sets the FetchOwner field's value. -func (s *ListObjectsV2Input) SetFetchOwner(v bool) *ListObjectsV2Input { - s.FetchOwner = &v - return s +type Part struct { + _ struct{} `type:"structure"` + + // Entity tag returned when the part was uploaded. + ETag *string `type:"string"` + + // Date and time at which the part was uploaded. + LastModified *time.Time `type:"timestamp"` + + // Part number identifying the part. This is a positive integer between 1 and + // 10,000. + PartNumber *int64 `type:"integer"` + + // Size in bytes of the uploaded part data. + Size *int64 `type:"integer"` } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsV2Input) SetMaxKeys(v int64) *ListObjectsV2Input { - s.MaxKeys = &v +// String returns the string representation +func (s Part) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Part) GoString() string { + return s.String() +} + +// SetETag sets the ETag field's value. +func (s *Part) SetETag(v string) *Part { + s.ETag = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsV2Input) SetPrefix(v string) *ListObjectsV2Input { - s.Prefix = &v +// SetLastModified sets the LastModified field's value. +func (s *Part) SetLastModified(v time.Time) *Part { + s.LastModified = &v return s } -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListObjectsV2Input) SetRequestPayer(v string) *ListObjectsV2Input { - s.RequestPayer = &v +// SetPartNumber sets the PartNumber field's value. +func (s *Part) SetPartNumber(v int64) *Part { + s.PartNumber = &v return s } -// SetStartAfter sets the StartAfter field's value. -func (s *ListObjectsV2Input) SetStartAfter(v string) *ListObjectsV2Input { - s.StartAfter = &v +// SetSize sets the Size field's value. +func (s *Part) SetSize(v int64) *Part { + s.Size = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Output -type ListObjectsV2Output struct { +// The container element for a bucket's policy status. +type PolicyStatus struct { _ struct{} `type:"structure"` - // CommonPrefixes contains all (if there are any) keys between Prefix and the - // next occurrence of the string specified by delimiter - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - // Metadata about each object returned. - Contents []*Object `type:"list" flattened:"true"` - - // ContinuationToken indicates Amazon S3 that the list is being continued on - // this bucket with a token. ContinuationToken is obfuscated and is not a real - // key - ContinuationToken *string `type:"string"` - - // A delimiter is a character you use to group keys. - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` + // The policy status for this bucket. TRUE indicates that this bucket is public. + // FALSE indicates that the bucket is not public. + IsPublic *bool `locationName:"IsPublic" type:"boolean"` +} - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. - IsTruncated *bool `type:"boolean"` +// String returns the string representation +func (s PolicyStatus) String() string { + return awsutil.Prettify(s) +} - // KeyCount is the number of keys returned with this request. KeyCount will - // always be less than equals to MaxKeys field. Say you ask for 50 keys, your - // result will include less than equals 50 keys - KeyCount *int64 `type:"integer"` +// GoString returns the string representation +func (s PolicyStatus) GoString() string { + return s.String() +} - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `type:"integer"` +// SetIsPublic sets the IsPublic field's value. +func (s *PolicyStatus) SetIsPublic(v bool) *PolicyStatus { + s.IsPublic = &v + return s +} - // Name of the bucket to list. - Name *string `type:"string"` +type Progress struct { + _ struct{} `type:"structure"` - // NextContinuationToken is sent when isTruncated is true which means there - // are more keys in the bucket that can be listed. The next list requests to - // Amazon S3 can be continued with this NextContinuationToken. NextContinuationToken - // is obfuscated and is not a real key - NextContinuationToken *string `type:"string"` + // The current number of uncompressed object bytes processed. + BytesProcessed *int64 `type:"long"` - // Limits the response to keys that begin with the specified prefix. - Prefix *string `type:"string"` + // The current number of bytes of records payload data returned. + BytesReturned *int64 `type:"long"` - // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts - // listing after this specified key. StartAfter can be any key in the bucket - StartAfter *string `type:"string"` + // The current number of object bytes scanned. + BytesScanned *int64 `type:"long"` } // String returns the string representation -func (s ListObjectsV2Output) String() string { +func (s Progress) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListObjectsV2Output) GoString() string { +func (s Progress) GoString() string { return s.String() } -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectsV2Output) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsV2Output { - s.CommonPrefixes = v +// SetBytesProcessed sets the BytesProcessed field's value. +func (s *Progress) SetBytesProcessed(v int64) *Progress { + s.BytesProcessed = &v return s } -// SetContents sets the Contents field's value. -func (s *ListObjectsV2Output) SetContents(v []*Object) *ListObjectsV2Output { - s.Contents = v +// SetBytesReturned sets the BytesReturned field's value. +func (s *Progress) SetBytesReturned(v int64) *Progress { + s.BytesReturned = &v return s } -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListObjectsV2Output) SetContinuationToken(v string) *ListObjectsV2Output { - s.ContinuationToken = &v +// SetBytesScanned sets the BytesScanned field's value. +func (s *Progress) SetBytesScanned(v int64) *Progress { + s.BytesScanned = &v return s } -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsV2Output) SetDelimiter(v string) *ListObjectsV2Output { - s.Delimiter = &v - return s +type ProgressEvent struct { + _ struct{} `locationName:"ProgressEvent" type:"structure" payload:"Details"` + + // The Progress event details. + Details *Progress `locationName:"Details" type:"structure"` } -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsV2Output) SetEncodingType(v string) *ListObjectsV2Output { - s.EncodingType = &v - return s +// String returns the string representation +func (s ProgressEvent) String() string { + return awsutil.Prettify(s) } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectsV2Output) SetIsTruncated(v bool) *ListObjectsV2Output { - s.IsTruncated = &v - return s +// GoString returns the string representation +func (s ProgressEvent) GoString() string { + return s.String() } -// SetKeyCount sets the KeyCount field's value. -func (s *ListObjectsV2Output) SetKeyCount(v int64) *ListObjectsV2Output { - s.KeyCount = &v +// SetDetails sets the Details field's value. +func (s *ProgressEvent) SetDetails(v *Progress) *ProgressEvent { + s.Details = v return s } -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsV2Output) SetMaxKeys(v int64) *ListObjectsV2Output { - s.MaxKeys = &v - return s +// The ProgressEvent is and event in the SelectObjectContentEventStream group of events. +func (s *ProgressEvent) eventSelectObjectContentEventStream() {} + +// UnmarshalEvent unmarshals the EventStream Message into the ProgressEvent value. +// This method is only used internally within the SDK's EventStream handling. +func (s *ProgressEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + if err := payloadUnmarshaler.UnmarshalPayload( + bytes.NewReader(msg.Payload), s, + ); err != nil { + return err + } + return nil } -// SetName sets the Name field's value. -func (s *ListObjectsV2Output) SetName(v string) *ListObjectsV2Output { - s.Name = &v - return s +type PublicAccessBlockConfiguration struct { + _ struct{} `type:"structure"` + + // Specifies whether Amazon S3 should block public access control lists (ACLs) + // for this bucket and objects in this bucket. Setting this element to TRUE + // causes the following behavior: + // + // * PUT Bucket acl and PUT Object acl calls fail if the specified ACL is + // public. + // + // * PUT Object calls fail if the request includes a public ACL. + // + // Enabling this setting doesn't affect existing policies or ACLs. + BlockPublicAcls *bool `locationName:"BlockPublicAcls" type:"boolean"` + + // Specifies whether Amazon S3 should block public bucket policies for this + // bucket. Setting this element to TRUE causes Amazon S3 to reject calls to + // PUT Bucket policy if the specified bucket policy allows public access. + // + // Enabling this setting doesn't affect existing bucket policies. + BlockPublicPolicy *bool `locationName:"BlockPublicPolicy" type:"boolean"` + + // Specifies whether Amazon S3 should ignore public ACLs for this bucket and + // objects in this bucket. Setting this element to TRUE causes Amazon S3 to + // ignore all public ACLs on this bucket and objects in this bucket. + // + // Enabling this setting doesn't affect the persistence of any existing ACLs + // and doesn't prevent new public ACLs from being set. + IgnorePublicAcls *bool `locationName:"IgnorePublicAcls" type:"boolean"` + + // Specifies whether Amazon S3 should restrict public bucket policies for this + // bucket. Setting this element to TRUE restricts access to this bucket to only + // AWS services and authorized users within this account if the bucket has a + // public policy. + // + // Enabling this setting doesn't affect previously stored bucket policies, except + // that public and cross-account access within any public bucket policy, including + // non-public delegation to specific accounts, is blocked. + RestrictPublicBuckets *bool `locationName:"RestrictPublicBuckets" type:"boolean"` } -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListObjectsV2Output) SetNextContinuationToken(v string) *ListObjectsV2Output { - s.NextContinuationToken = &v - return s +// String returns the string representation +func (s PublicAccessBlockConfiguration) String() string { + return awsutil.Prettify(s) } -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsV2Output) SetPrefix(v string) *ListObjectsV2Output { - s.Prefix = &v - return s +// GoString returns the string representation +func (s PublicAccessBlockConfiguration) GoString() string { + return s.String() } -// SetStartAfter sets the StartAfter field's value. -func (s *ListObjectsV2Output) SetStartAfter(v string) *ListObjectsV2Output { - s.StartAfter = &v +// SetBlockPublicAcls sets the BlockPublicAcls field's value. +func (s *PublicAccessBlockConfiguration) SetBlockPublicAcls(v bool) *PublicAccessBlockConfiguration { + s.BlockPublicAcls = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsRequest -type ListPartsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetBlockPublicPolicy sets the BlockPublicPolicy field's value. +func (s *PublicAccessBlockConfiguration) SetBlockPublicPolicy(v bool) *PublicAccessBlockConfiguration { + s.BlockPublicPolicy = &v + return s +} - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` +// SetIgnorePublicAcls sets the IgnorePublicAcls field's value. +func (s *PublicAccessBlockConfiguration) SetIgnorePublicAcls(v bool) *PublicAccessBlockConfiguration { + s.IgnorePublicAcls = &v + return s +} - // Sets the maximum number of parts to return. - MaxParts *int64 `location:"querystring" locationName:"max-parts" type:"integer"` +// SetRestrictPublicBuckets sets the RestrictPublicBuckets field's value. +func (s *PublicAccessBlockConfiguration) SetRestrictPublicBuckets(v bool) *PublicAccessBlockConfiguration { + s.RestrictPublicBuckets = &v + return s +} - // Specifies the part after which listing should begin. Only parts with higher - // part numbers will be listed. - PartNumberMarker *int64 `location:"querystring" locationName:"part-number-marker" type:"integer"` +type PutBucketAccelerateConfigurationInput struct { + _ struct{} `type:"structure" payload:"AccelerateConfiguration"` - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + // Specifies the Accelerate Configuration you want to set for the bucket. + // + // AccelerateConfiguration is a required field + AccelerateConfiguration *AccelerateConfiguration `locationName:"AccelerateConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - // Upload ID identifying the multipart upload whose parts are being listed. + // Name of the bucket for which the accelerate configuration is set. // - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` } // String returns the string representation -func (s ListPartsInput) String() string { +func (s PutBucketAccelerateConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListPartsInput) GoString() string { +func (s PutBucketAccelerateConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListPartsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListPartsInput"} +func (s *PutBucketAccelerateConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketAccelerateConfigurationInput"} + if s.AccelerateConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("AccelerateConfiguration")) + } if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -14137,225 +18535,214 @@ func (s *ListPartsInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *ListPartsInput) SetBucket(v string) *ListPartsInput { - s.Bucket = &v +// SetAccelerateConfiguration sets the AccelerateConfiguration field's value. +func (s *PutBucketAccelerateConfigurationInput) SetAccelerateConfiguration(v *AccelerateConfiguration) *PutBucketAccelerateConfigurationInput { + s.AccelerateConfiguration = v return s } -// SetKey sets the Key field's value. -func (s *ListPartsInput) SetKey(v string) *ListPartsInput { - s.Key = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketAccelerateConfigurationInput) SetBucket(v string) *PutBucketAccelerateConfigurationInput { + s.Bucket = &v return s } -// SetMaxParts sets the MaxParts field's value. -func (s *ListPartsInput) SetMaxParts(v int64) *ListPartsInput { - s.MaxParts = &v - return s +func (s *PutBucketAccelerateConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetPartNumberMarker sets the PartNumberMarker field's value. -func (s *ListPartsInput) SetPartNumberMarker(v int64) *ListPartsInput { - s.PartNumberMarker = &v - return s +type PutBucketAccelerateConfigurationOutput struct { + _ struct{} `type:"structure"` } -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListPartsInput) SetRequestPayer(v string) *ListPartsInput { - s.RequestPayer = &v - return s +// String returns the string representation +func (s PutBucketAccelerateConfigurationOutput) String() string { + return awsutil.Prettify(s) } -// SetUploadId sets the UploadId field's value. -func (s *ListPartsInput) SetUploadId(v string) *ListPartsInput { - s.UploadId = &v - return s +// GoString returns the string representation +func (s PutBucketAccelerateConfigurationOutput) GoString() string { + return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsOutput -type ListPartsOutput struct { - _ struct{} `type:"structure"` - - // Date when multipart upload will become eligible for abort operation by lifecycle. - AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp" timestampFormat:"rfc822"` - - // Id of the lifecycle rule that makes a multipart upload eligible for abort - // operation. - AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` - - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` - - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` - - // Indicates whether the returned list of parts is truncated. - IsTruncated *bool `type:"boolean"` - - // Object key for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` +type PutBucketAclInput struct { + _ struct{} `type:"structure" payload:"AccessControlPolicy"` - // Maximum number of parts that were allowed in the response. - MaxParts *int64 `type:"integer"` + // The canned ACL to apply to the bucket. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` - // When a list is truncated, this element specifies the last part in the list, - // as well as the value to use for the part-number-marker request parameter - // in a subsequent request. - NextPartNumberMarker *int64 `type:"integer"` + AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - Owner *Owner `type:"structure"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Part number after which listing begins. - PartNumberMarker *int64 `type:"integer"` + // Allows grantee the read, write, read ACP, and write ACP permissions on the + // bucket. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - Parts []*Part `locationName:"Part" type:"list" flattened:"true"` + // Allows grantee to list the objects in the bucket. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // Allows grantee to read the bucket ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` + // Allows grantee to create, overwrite, and delete any object in the bucket. + GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - // Upload ID identifying the multipart upload whose parts are being listed. - UploadId *string `type:"string"` + // Allows grantee to write the ACL for the applicable bucket. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` } // String returns the string representation -func (s ListPartsOutput) String() string { +func (s PutBucketAclInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListPartsOutput) GoString() string { +func (s PutBucketAclInput) GoString() string { return s.String() } -// SetAbortDate sets the AbortDate field's value. -func (s *ListPartsOutput) SetAbortDate(v time.Time) *ListPartsOutput { - s.AbortDate = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketAclInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketAclInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.AccessControlPolicy != nil { + if err := s.AccessControlPolicy.Validate(); err != nil { + invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) + } + } -// SetAbortRuleId sets the AbortRuleId field's value. -func (s *ListPartsOutput) SetAbortRuleId(v string) *ListPartsOutput { - s.AbortRuleId = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetBucket sets the Bucket field's value. -func (s *ListPartsOutput) SetBucket(v string) *ListPartsOutput { - s.Bucket = &v +// SetACL sets the ACL field's value. +func (s *PutBucketAclInput) SetACL(v string) *PutBucketAclInput { + s.ACL = &v return s } -// SetInitiator sets the Initiator field's value. -func (s *ListPartsOutput) SetInitiator(v *Initiator) *ListPartsOutput { - s.Initiator = v +// SetAccessControlPolicy sets the AccessControlPolicy field's value. +func (s *PutBucketAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutBucketAclInput { + s.AccessControlPolicy = v return s } -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListPartsOutput) SetIsTruncated(v bool) *ListPartsOutput { - s.IsTruncated = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketAclInput) SetBucket(v string) *PutBucketAclInput { + s.Bucket = &v return s } -// SetKey sets the Key field's value. -func (s *ListPartsOutput) SetKey(v string) *ListPartsOutput { - s.Key = &v - return s +func (s *PutBucketAclInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetMaxParts sets the MaxParts field's value. -func (s *ListPartsOutput) SetMaxParts(v int64) *ListPartsOutput { - s.MaxParts = &v +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *PutBucketAclInput) SetGrantFullControl(v string) *PutBucketAclInput { + s.GrantFullControl = &v return s } -// SetNextPartNumberMarker sets the NextPartNumberMarker field's value. -func (s *ListPartsOutput) SetNextPartNumberMarker(v int64) *ListPartsOutput { - s.NextPartNumberMarker = &v +// SetGrantRead sets the GrantRead field's value. +func (s *PutBucketAclInput) SetGrantRead(v string) *PutBucketAclInput { + s.GrantRead = &v return s } -// SetOwner sets the Owner field's value. -func (s *ListPartsOutput) SetOwner(v *Owner) *ListPartsOutput { - s.Owner = v +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *PutBucketAclInput) SetGrantReadACP(v string) *PutBucketAclInput { + s.GrantReadACP = &v return s } -// SetPartNumberMarker sets the PartNumberMarker field's value. -func (s *ListPartsOutput) SetPartNumberMarker(v int64) *ListPartsOutput { - s.PartNumberMarker = &v +// SetGrantWrite sets the GrantWrite field's value. +func (s *PutBucketAclInput) SetGrantWrite(v string) *PutBucketAclInput { + s.GrantWrite = &v return s } -// SetParts sets the Parts field's value. -func (s *ListPartsOutput) SetParts(v []*Part) *ListPartsOutput { - s.Parts = v +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *PutBucketAclInput) SetGrantWriteACP(v string) *PutBucketAclInput { + s.GrantWriteACP = &v return s } -// SetRequestCharged sets the RequestCharged field's value. -func (s *ListPartsOutput) SetRequestCharged(v string) *ListPartsOutput { - s.RequestCharged = &v - return s +type PutBucketAclOutput struct { + _ struct{} `type:"structure"` } -// SetStorageClass sets the StorageClass field's value. -func (s *ListPartsOutput) SetStorageClass(v string) *ListPartsOutput { - s.StorageClass = &v - return s +// String returns the string representation +func (s PutBucketAclOutput) String() string { + return awsutil.Prettify(s) } -// SetUploadId sets the UploadId field's value. -func (s *ListPartsOutput) SetUploadId(v string) *ListPartsOutput { - s.UploadId = &v - return s +// GoString returns the string representation +func (s PutBucketAclOutput) GoString() string { + return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LoggingEnabled -type LoggingEnabled struct { - _ struct{} `type:"structure"` +type PutBucketAnalyticsConfigurationInput struct { + _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` - // Specifies the bucket where you want Amazon S3 to store server access logs. - // You can have your logs delivered to any bucket that you own, including the - // same bucket that is being logged. You can also configure multiple buckets - // to deliver their logs to the same target bucket. In this case you should - // choose a different TargetPrefix for each source bucket so that the delivered - // log files can be distinguished by key. - TargetBucket *string `type:"string"` + // The configuration and any analyses for the analytics filter. + // + // AnalyticsConfiguration is a required field + AnalyticsConfiguration *AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - TargetGrants []*TargetGrant `locationNameList:"Grant" type:"list"` + // The name of the bucket to which an analytics configuration is stored. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // This element lets you specify a prefix for the keys that the log files will - // be stored under. - TargetPrefix *string `type:"string"` + // The identifier used to represent an analytics configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` } // String returns the string representation -func (s LoggingEnabled) String() string { +func (s PutBucketAnalyticsConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LoggingEnabled) GoString() string { +func (s PutBucketAnalyticsConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LoggingEnabled) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LoggingEnabled"} - if s.TargetGrants != nil { - for i, v := range s.TargetGrants { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TargetGrants", i), err.(request.ErrInvalidParams)) - } +func (s *PutBucketAnalyticsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketAnalyticsConfigurationInput"} + if s.AnalyticsConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("AnalyticsConfiguration")) + } + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.AnalyticsConfiguration != nil { + if err := s.AnalyticsConfiguration.Validate(); err != nil { + invalidParams.AddNested("AnalyticsConfiguration", err.(request.ErrInvalidParams)) } } @@ -14365,111 +18752,80 @@ func (s *LoggingEnabled) Validate() error { return nil } -// SetTargetBucket sets the TargetBucket field's value. -func (s *LoggingEnabled) SetTargetBucket(v string) *LoggingEnabled { - s.TargetBucket = &v +// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. +func (s *PutBucketAnalyticsConfigurationInput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *PutBucketAnalyticsConfigurationInput { + s.AnalyticsConfiguration = v return s } -// SetTargetGrants sets the TargetGrants field's value. -func (s *LoggingEnabled) SetTargetGrants(v []*TargetGrant) *LoggingEnabled { - s.TargetGrants = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketAnalyticsConfigurationInput) SetBucket(v string) *PutBucketAnalyticsConfigurationInput { + s.Bucket = &v return s } -// SetTargetPrefix sets the TargetPrefix field's value. -func (s *LoggingEnabled) SetTargetPrefix(v string) *LoggingEnabled { - s.TargetPrefix = &v +func (s *PutBucketAnalyticsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetId sets the Id field's value. +func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyticsConfigurationInput { + s.Id = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsAndOperator -type MetricsAndOperator struct { +type PutBucketAnalyticsConfigurationOutput struct { _ struct{} `type:"structure"` - - // The prefix used when evaluating an AND predicate. - Prefix *string `type:"string"` - - // The list of tags used when evaluating an AND predicate. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` } // String returns the string representation -func (s MetricsAndOperator) String() string { +func (s PutBucketAnalyticsConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MetricsAndOperator) GoString() string { +func (s PutBucketAnalyticsConfigurationOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPrefix sets the Prefix field's value. -func (s *MetricsAndOperator) SetPrefix(v string) *MetricsAndOperator { - s.Prefix = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *MetricsAndOperator) SetTags(v []*Tag) *MetricsAndOperator { - s.Tags = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsConfiguration -type MetricsConfiguration struct { - _ struct{} `type:"structure"` +type PutBucketCorsInput struct { + _ struct{} `type:"structure" payload:"CORSConfiguration"` - // Specifies a metrics configuration filter. The metrics configuration will - // only include objects that meet the filter's criteria. A filter must be a - // prefix, a tag, or a conjunction (MetricsAndOperator). - Filter *MetricsFilter `type:"structure"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` + // CORSConfiguration is a required field + CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s MetricsConfiguration) String() string { +func (s PutBucketCorsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MetricsConfiguration) GoString() string { +func (s PutBucketCorsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsConfiguration"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *PutBucketCorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketCorsInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + if s.CORSConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("CORSConfiguration")) + } + if s.CORSConfiguration != nil { + if err := s.CORSConfiguration.Validate(); err != nil { + invalidParams.AddNested("CORSConfiguration", err.(request.ErrInvalidParams)) } } @@ -14479,55 +18835,80 @@ func (s *MetricsConfiguration) Validate() error { return nil } -// SetFilter sets the Filter field's value. -func (s *MetricsConfiguration) SetFilter(v *MetricsFilter) *MetricsConfiguration { - s.Filter = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketCorsInput) SetBucket(v string) *PutBucketCorsInput { + s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *MetricsConfiguration) SetId(v string) *MetricsConfiguration { - s.Id = &v +func (s *PutBucketCorsInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetCORSConfiguration sets the CORSConfiguration field's value. +func (s *PutBucketCorsInput) SetCORSConfiguration(v *CORSConfiguration) *PutBucketCorsInput { + s.CORSConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsFilter -type MetricsFilter struct { +type PutBucketCorsOutput struct { _ struct{} `type:"structure"` +} - // A conjunction (logical AND) of predicates, which is used in evaluating a - // metrics filter. The operator must have at least two predicates, and an object - // must match all of the predicates in order for the filter to apply. - And *MetricsAndOperator `type:"structure"` +// String returns the string representation +func (s PutBucketCorsOutput) String() string { + return awsutil.Prettify(s) +} - // The prefix used when evaluating a metrics filter. - Prefix *string `type:"string"` +// GoString returns the string representation +func (s PutBucketCorsOutput) GoString() string { + return s.String() +} - // The tag used when evaluating a metrics filter. - Tag *Tag `type:"structure"` +type PutBucketEncryptionInput struct { + _ struct{} `type:"structure" payload:"ServerSideEncryptionConfiguration"` + + // The name of the bucket for which the server-side encryption configuration + // is set. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Container for server-side encryption configuration rules. Currently S3 supports + // one rule only. + // + // ServerSideEncryptionConfiguration is a required field + ServerSideEncryptionConfiguration *ServerSideEncryptionConfiguration `locationName:"ServerSideEncryptionConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s MetricsFilter) String() string { +func (s PutBucketEncryptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MetricsFilter) GoString() string { +func (s PutBucketEncryptionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } +func (s *PutBucketEncryptionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketEncryptionInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.ServerSideEncryptionConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("ServerSideEncryptionConfiguration")) + } + if s.ServerSideEncryptionConfiguration != nil { + if err := s.ServerSideEncryptionConfiguration.Validate(); err != nil { + invalidParams.AddNested("ServerSideEncryptionConfiguration", err.(request.ErrInvalidParams)) } } @@ -14537,219 +18918,238 @@ func (s *MetricsFilter) Validate() error { return nil } -// SetAnd sets the And field's value. -func (s *MetricsFilter) SetAnd(v *MetricsAndOperator) *MetricsFilter { - s.And = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketEncryptionInput) SetBucket(v string) *PutBucketEncryptionInput { + s.Bucket = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *MetricsFilter) SetPrefix(v string) *MetricsFilter { - s.Prefix = &v - return s +func (s *PutBucketEncryptionInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetTag sets the Tag field's value. -func (s *MetricsFilter) SetTag(v *Tag) *MetricsFilter { - s.Tag = v +// SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value. +func (s *PutBucketEncryptionInput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *PutBucketEncryptionInput { + s.ServerSideEncryptionConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MultipartUpload -type MultipartUpload struct { +type PutBucketEncryptionOutput struct { _ struct{} `type:"structure"` +} - // Date and time at which the multipart upload was initiated. - Initiated *time.Time `type:"timestamp" timestampFormat:"iso8601"` +// String returns the string representation +func (s PutBucketEncryptionOutput) String() string { + return awsutil.Prettify(s) +} - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` +// GoString returns the string representation +func (s PutBucketEncryptionOutput) GoString() string { + return s.String() +} - // Key of the object for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` +type PutBucketInventoryConfigurationInput struct { + _ struct{} `type:"structure" payload:"InventoryConfiguration"` - Owner *Owner `type:"structure"` + // The name of the bucket where the inventory configuration will be stored. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` + // The ID used to identify the inventory configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - // Upload ID that identifies the multipart upload. - UploadId *string `type:"string"` + // Specifies the inventory configuration. + // + // InventoryConfiguration is a required field + InventoryConfiguration *InventoryConfiguration `locationName:"InventoryConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s MultipartUpload) String() string { +func (s PutBucketInventoryConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MultipartUpload) GoString() string { +func (s PutBucketInventoryConfigurationInput) GoString() string { return s.String() } -// SetInitiated sets the Initiated field's value. -func (s *MultipartUpload) SetInitiated(v time.Time) *MultipartUpload { - s.Initiated = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketInventoryConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketInventoryConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.InventoryConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("InventoryConfiguration")) + } + if s.InventoryConfiguration != nil { + if err := s.InventoryConfiguration.Validate(); err != nil { + invalidParams.AddNested("InventoryConfiguration", err.(request.ErrInvalidParams)) + } + } -// SetInitiator sets the Initiator field's value. -func (s *MultipartUpload) SetInitiator(v *Initiator) *MultipartUpload { - s.Initiator = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetKey sets the Key field's value. -func (s *MultipartUpload) SetKey(v string) *MultipartUpload { - s.Key = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketInventoryConfigurationInput) SetBucket(v string) *PutBucketInventoryConfigurationInput { + s.Bucket = &v return s } -// SetOwner sets the Owner field's value. -func (s *MultipartUpload) SetOwner(v *Owner) *MultipartUpload { - s.Owner = v - return s +func (s *PutBucketInventoryConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetStorageClass sets the StorageClass field's value. -func (s *MultipartUpload) SetStorageClass(v string) *MultipartUpload { - s.StorageClass = &v +// SetId sets the Id field's value. +func (s *PutBucketInventoryConfigurationInput) SetId(v string) *PutBucketInventoryConfigurationInput { + s.Id = &v return s } -// SetUploadId sets the UploadId field's value. -func (s *MultipartUpload) SetUploadId(v string) *MultipartUpload { - s.UploadId = &v +// SetInventoryConfiguration sets the InventoryConfiguration field's value. +func (s *PutBucketInventoryConfigurationInput) SetInventoryConfiguration(v *InventoryConfiguration) *PutBucketInventoryConfigurationInput { + s.InventoryConfiguration = v return s } -// Specifies when noncurrent object versions expire. Upon expiration, Amazon -// S3 permanently deletes the noncurrent object versions. You set this lifecycle -// configuration action on a bucket that has versioning enabled (or suspended) -// to request that Amazon S3 delete noncurrent object versions at a specific -// period in the object's lifetime. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionExpiration -type NoncurrentVersionExpiration struct { +type PutBucketInventoryConfigurationOutput struct { _ struct{} `type:"structure"` - - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) - NoncurrentDays *int64 `type:"integer"` } // String returns the string representation -func (s NoncurrentVersionExpiration) String() string { +func (s PutBucketInventoryConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NoncurrentVersionExpiration) GoString() string { +func (s PutBucketInventoryConfigurationOutput) GoString() string { return s.String() } -// SetNoncurrentDays sets the NoncurrentDays field's value. -func (s *NoncurrentVersionExpiration) SetNoncurrentDays(v int64) *NoncurrentVersionExpiration { - s.NoncurrentDays = &v - return s -} - -// Container for the transition rule that describes when noncurrent objects -// transition to the STANDARD_IA or GLACIER storage class. If your bucket is -// versioning-enabled (or versioning is suspended), you can set this action -// to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA -// or GLACIER storage class at a specific period in the object's lifetime. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionTransition -type NoncurrentVersionTransition struct { - _ struct{} `type:"structure"` +type PutBucketLifecycleConfigurationInput struct { + _ struct{} `type:"structure" payload:"LifecycleConfiguration"` - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) - NoncurrentDays *int64 `type:"integer"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"TransitionStorageClass"` + LifecycleConfiguration *BucketLifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s NoncurrentVersionTransition) String() string { +func (s PutBucketLifecycleConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NoncurrentVersionTransition) GoString() string { +func (s PutBucketLifecycleConfigurationInput) GoString() string { return s.String() } -// SetNoncurrentDays sets the NoncurrentDays field's value. -func (s *NoncurrentVersionTransition) SetNoncurrentDays(v int64) *NoncurrentVersionTransition { - s.NoncurrentDays = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketLifecycleConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.LifecycleConfiguration != nil { + if err := s.LifecycleConfiguration.Validate(); err != nil { + invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *PutBucketLifecycleConfigurationInput) SetBucket(v string) *PutBucketLifecycleConfigurationInput { + s.Bucket = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *NoncurrentVersionTransition) SetStorageClass(v string) *NoncurrentVersionTransition { - s.StorageClass = &v +func (s *PutBucketLifecycleConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. +func (s *PutBucketLifecycleConfigurationInput) SetLifecycleConfiguration(v *BucketLifecycleConfiguration) *PutBucketLifecycleConfigurationInput { + s.LifecycleConfiguration = v return s } -// Container for specifying the notification configuration of the bucket. If -// this element is empty, notifications are turned off on the bucket. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfiguration -type NotificationConfiguration struct { - _ struct{} `type:"structure"` - - LambdaFunctionConfigurations []*LambdaFunctionConfiguration `locationName:"CloudFunctionConfiguration" type:"list" flattened:"true"` +type PutBucketLifecycleConfigurationOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s PutBucketLifecycleConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBucketLifecycleConfigurationOutput) GoString() string { + return s.String() +} + +type PutBucketLifecycleInput struct { + _ struct{} `type:"structure" payload:"LifecycleConfiguration"` - QueueConfigurations []*QueueConfiguration `locationName:"QueueConfiguration" type:"list" flattened:"true"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - TopicConfigurations []*TopicConfiguration `locationName:"TopicConfiguration" type:"list" flattened:"true"` + LifecycleConfiguration *LifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s NotificationConfiguration) String() string { +func (s PutBucketLifecycleInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NotificationConfiguration) GoString() string { +func (s PutBucketLifecycleInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *NotificationConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "NotificationConfiguration"} - if s.LambdaFunctionConfigurations != nil { - for i, v := range s.LambdaFunctionConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LambdaFunctionConfigurations", i), err.(request.ErrInvalidParams)) - } - } +func (s *PutBucketLifecycleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.QueueConfigurations != nil { - for i, v := range s.QueueConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueueConfigurations", i), err.(request.ErrInvalidParams)) - } - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.TopicConfigurations != nil { - for i, v := range s.TopicConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TopicConfigurations", i), err.(request.ErrInvalidParams)) - } + if s.LifecycleConfiguration != nil { + if err := s.LifecycleConfiguration.Validate(); err != nil { + invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) } } @@ -14759,184 +19159,250 @@ func (s *NotificationConfiguration) Validate() error { return nil } -// SetLambdaFunctionConfigurations sets the LambdaFunctionConfigurations field's value. -func (s *NotificationConfiguration) SetLambdaFunctionConfigurations(v []*LambdaFunctionConfiguration) *NotificationConfiguration { - s.LambdaFunctionConfigurations = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketLifecycleInput) SetBucket(v string) *PutBucketLifecycleInput { + s.Bucket = &v return s } -// SetQueueConfigurations sets the QueueConfigurations field's value. -func (s *NotificationConfiguration) SetQueueConfigurations(v []*QueueConfiguration) *NotificationConfiguration { - s.QueueConfigurations = v - return s +func (s *PutBucketLifecycleInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetTopicConfigurations sets the TopicConfigurations field's value. -func (s *NotificationConfiguration) SetTopicConfigurations(v []*TopicConfiguration) *NotificationConfiguration { - s.TopicConfigurations = v +// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. +func (s *PutBucketLifecycleInput) SetLifecycleConfiguration(v *LifecycleConfiguration) *PutBucketLifecycleInput { + s.LifecycleConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationDeprecated -type NotificationConfigurationDeprecated struct { +type PutBucketLifecycleOutput struct { _ struct{} `type:"structure"` +} - CloudFunctionConfiguration *CloudFunctionConfiguration `type:"structure"` +// String returns the string representation +func (s PutBucketLifecycleOutput) String() string { + return awsutil.Prettify(s) +} - QueueConfiguration *QueueConfigurationDeprecated `type:"structure"` +// GoString returns the string representation +func (s PutBucketLifecycleOutput) GoString() string { + return s.String() +} - TopicConfiguration *TopicConfigurationDeprecated `type:"structure"` +type PutBucketLoggingInput struct { + _ struct{} `type:"structure" payload:"BucketLoggingStatus"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // BucketLoggingStatus is a required field + BucketLoggingStatus *BucketLoggingStatus `locationName:"BucketLoggingStatus" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s NotificationConfigurationDeprecated) String() string { +func (s PutBucketLoggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NotificationConfigurationDeprecated) GoString() string { +func (s PutBucketLoggingInput) GoString() string { return s.String() } -// SetCloudFunctionConfiguration sets the CloudFunctionConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetCloudFunctionConfiguration(v *CloudFunctionConfiguration) *NotificationConfigurationDeprecated { - s.CloudFunctionConfiguration = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketLoggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketLoggingInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.BucketLoggingStatus == nil { + invalidParams.Add(request.NewErrParamRequired("BucketLoggingStatus")) + } + if s.BucketLoggingStatus != nil { + if err := s.BucketLoggingStatus.Validate(); err != nil { + invalidParams.AddNested("BucketLoggingStatus", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetQueueConfiguration sets the QueueConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetQueueConfiguration(v *QueueConfigurationDeprecated) *NotificationConfigurationDeprecated { - s.QueueConfiguration = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketLoggingInput) SetBucket(v string) *PutBucketLoggingInput { + s.Bucket = &v return s } -// SetTopicConfiguration sets the TopicConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetTopicConfiguration(v *TopicConfigurationDeprecated) *NotificationConfigurationDeprecated { - s.TopicConfiguration = v +func (s *PutBucketLoggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetBucketLoggingStatus sets the BucketLoggingStatus field's value. +func (s *PutBucketLoggingInput) SetBucketLoggingStatus(v *BucketLoggingStatus) *PutBucketLoggingInput { + s.BucketLoggingStatus = v return s } -// Container for object key name filtering rules. For information about key -// name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationFilter -type NotificationConfigurationFilter struct { +type PutBucketLoggingOutput struct { _ struct{} `type:"structure"` - - // Container for object key name prefix and suffix filtering rules. - Key *KeyFilter `locationName:"S3Key" type:"structure"` } // String returns the string representation -func (s NotificationConfigurationFilter) String() string { +func (s PutBucketLoggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NotificationConfigurationFilter) GoString() string { +func (s PutBucketLoggingOutput) GoString() string { return s.String() } -// SetKey sets the Key field's value. -func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConfigurationFilter { - s.Key = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Object -type Object struct { - _ struct{} `type:"structure"` - - ETag *string `type:"string"` - - Key *string `min:"1" type:"string"` - - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` +type PutBucketMetricsConfigurationInput struct { + _ struct{} `type:"structure" payload:"MetricsConfiguration"` - Owner *Owner `type:"structure"` + // The name of the bucket for which the metrics configuration is set. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - Size *int64 `type:"integer"` + // The ID used to identify the metrics configuration. + // + // Id is a required field + Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"ObjectStorageClass"` + // Specifies the metrics configuration. + // + // MetricsConfiguration is a required field + MetricsConfiguration *MetricsConfiguration `locationName:"MetricsConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s Object) String() string { +func (s PutBucketMetricsConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Object) GoString() string { +func (s PutBucketMetricsConfigurationInput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *Object) SetETag(v string) *Object { - s.ETag = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketMetricsConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketMetricsConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.MetricsConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("MetricsConfiguration")) + } + if s.MetricsConfiguration != nil { + if err := s.MetricsConfiguration.Validate(); err != nil { + invalidParams.AddNested("MetricsConfiguration", err.(request.ErrInvalidParams)) + } + } -// SetKey sets the Key field's value. -func (s *Object) SetKey(v string) *Object { - s.Key = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetLastModified sets the LastModified field's value. -func (s *Object) SetLastModified(v time.Time) *Object { - s.LastModified = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketMetricsConfigurationInput) SetBucket(v string) *PutBucketMetricsConfigurationInput { + s.Bucket = &v return s } -// SetOwner sets the Owner field's value. -func (s *Object) SetOwner(v *Owner) *Object { - s.Owner = v - return s +func (s *PutBucketMetricsConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetSize sets the Size field's value. -func (s *Object) SetSize(v int64) *Object { - s.Size = &v +// SetId sets the Id field's value. +func (s *PutBucketMetricsConfigurationInput) SetId(v string) *PutBucketMetricsConfigurationInput { + s.Id = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *Object) SetStorageClass(v string) *Object { - s.StorageClass = &v +// SetMetricsConfiguration sets the MetricsConfiguration field's value. +func (s *PutBucketMetricsConfigurationInput) SetMetricsConfiguration(v *MetricsConfiguration) *PutBucketMetricsConfigurationInput { + s.MetricsConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectIdentifier -type ObjectIdentifier struct { +type PutBucketMetricsConfigurationOutput struct { _ struct{} `type:"structure"` +} - // Key name of the object to delete. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` +// String returns the string representation +func (s PutBucketMetricsConfigurationOutput) String() string { + return awsutil.Prettify(s) +} - // VersionId for the specific version of the object to delete. - VersionId *string `type:"string"` +// GoString returns the string representation +func (s PutBucketMetricsConfigurationOutput) GoString() string { + return s.String() +} + +type PutBucketNotificationConfigurationInput struct { + _ struct{} `type:"structure" payload:"NotificationConfiguration"` + + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // A container for specifying the notification configuration of the bucket. + // If this element is empty, notifications are turned off for the bucket. + // + // NotificationConfiguration is a required field + NotificationConfiguration *NotificationConfiguration `locationName:"NotificationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s ObjectIdentifier) String() string { +func (s PutBucketNotificationConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ObjectIdentifier) GoString() string { +func (s PutBucketNotificationConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ObjectIdentifier) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ObjectIdentifier"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) +func (s *PutBucketNotificationConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationConfigurationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.NotificationConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) + } + if s.NotificationConfiguration != nil { + if err := s.NotificationConfiguration.Validate(); err != nil { + invalidParams.AddNested("NotificationConfiguration", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -14945,221 +19411,235 @@ func (s *ObjectIdentifier) Validate() error { return nil } -// SetKey sets the Key field's value. -func (s *ObjectIdentifier) SetKey(v string) *ObjectIdentifier { - s.Key = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketNotificationConfigurationInput) SetBucket(v string) *PutBucketNotificationConfigurationInput { + s.Bucket = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *ObjectIdentifier) SetVersionId(v string) *ObjectIdentifier { - s.VersionId = &v +func (s *PutBucketNotificationConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetNotificationConfiguration sets the NotificationConfiguration field's value. +func (s *PutBucketNotificationConfigurationInput) SetNotificationConfiguration(v *NotificationConfiguration) *PutBucketNotificationConfigurationInput { + s.NotificationConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectVersion -type ObjectVersion struct { +type PutBucketNotificationConfigurationOutput struct { _ struct{} `type:"structure"` - - ETag *string `type:"string"` - - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `min:"1" type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - // Size in bytes of the object. - Size *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"ObjectVersionStorageClass"` - - // Version ID of an object. - VersionId *string `type:"string"` } // String returns the string representation -func (s ObjectVersion) String() string { +func (s PutBucketNotificationConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ObjectVersion) GoString() string { +func (s PutBucketNotificationConfigurationOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *ObjectVersion) SetETag(v string) *ObjectVersion { - s.ETag = &v - return s -} +type PutBucketNotificationInput struct { + _ struct{} `type:"structure" payload:"NotificationConfiguration"` -// SetIsLatest sets the IsLatest field's value. -func (s *ObjectVersion) SetIsLatest(v bool) *ObjectVersion { - s.IsLatest = &v - return s + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // NotificationConfiguration is a required field + NotificationConfiguration *NotificationConfigurationDeprecated `locationName:"NotificationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } -// SetKey sets the Key field's value. -func (s *ObjectVersion) SetKey(v string) *ObjectVersion { - s.Key = &v - return s +// String returns the string representation +func (s PutBucketNotificationInput) String() string { + return awsutil.Prettify(s) } -// SetLastModified sets the LastModified field's value. -func (s *ObjectVersion) SetLastModified(v time.Time) *ObjectVersion { - s.LastModified = &v - return s +// GoString returns the string representation +func (s PutBucketNotificationInput) GoString() string { + return s.String() } -// SetOwner sets the Owner field's value. -func (s *ObjectVersion) SetOwner(v *Owner) *ObjectVersion { - s.Owner = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketNotificationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.NotificationConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSize sets the Size field's value. -func (s *ObjectVersion) SetSize(v int64) *ObjectVersion { - s.Size = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketNotificationInput) SetBucket(v string) *PutBucketNotificationInput { + s.Bucket = &v return s } -// SetStorageClass sets the StorageClass field's value. -func (s *ObjectVersion) SetStorageClass(v string) *ObjectVersion { - s.StorageClass = &v - return s +func (s *PutBucketNotificationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetVersionId sets the VersionId field's value. -func (s *ObjectVersion) SetVersionId(v string) *ObjectVersion { - s.VersionId = &v +// SetNotificationConfiguration sets the NotificationConfiguration field's value. +func (s *PutBucketNotificationInput) SetNotificationConfiguration(v *NotificationConfigurationDeprecated) *PutBucketNotificationInput { + s.NotificationConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Owner -type Owner struct { +type PutBucketNotificationOutput struct { _ struct{} `type:"structure"` - - DisplayName *string `type:"string"` - - ID *string `type:"string"` } // String returns the string representation -func (s Owner) String() string { +func (s PutBucketNotificationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Owner) GoString() string { +func (s PutBucketNotificationOutput) GoString() string { return s.String() } -// SetDisplayName sets the DisplayName field's value. -func (s *Owner) SetDisplayName(v string) *Owner { - s.DisplayName = &v - return s -} - -// SetID sets the ID field's value. -func (s *Owner) SetID(v string) *Owner { - s.ID = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Part -type Part struct { - _ struct{} `type:"structure"` - - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` +type PutBucketPolicyInput struct { + _ struct{} `type:"structure" payload:"Policy"` - // Date and time at which the part was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Part number identifying the part. This is a positive integer between 1 and - // 10,000. - PartNumber *int64 `type:"integer"` + // Set this parameter to true to confirm that you want to remove your permissions + // to change this bucket policy in the future. + ConfirmRemoveSelfBucketAccess *bool `location:"header" locationName:"x-amz-confirm-remove-self-bucket-access" type:"boolean"` - // Size of the uploaded part data. - Size *int64 `type:"integer"` + // The bucket policy as a JSON document. + // + // Policy is a required field + Policy *string `type:"string" required:"true"` } // String returns the string representation -func (s Part) String() string { +func (s PutBucketPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Part) GoString() string { +func (s PutBucketPolicyInput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *Part) SetETag(v string) *Part { - s.ETag = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBucketPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketPolicyInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Policy == nil { + invalidParams.Add(request.NewErrParamRequired("Policy")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetLastModified sets the LastModified field's value. -func (s *Part) SetLastModified(v time.Time) *Part { - s.LastModified = &v +// SetBucket sets the Bucket field's value. +func (s *PutBucketPolicyInput) SetBucket(v string) *PutBucketPolicyInput { + s.Bucket = &v return s } -// SetPartNumber sets the PartNumber field's value. -func (s *Part) SetPartNumber(v int64) *Part { - s.PartNumber = &v +func (s *PutBucketPolicyInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetConfirmRemoveSelfBucketAccess sets the ConfirmRemoveSelfBucketAccess field's value. +func (s *PutBucketPolicyInput) SetConfirmRemoveSelfBucketAccess(v bool) *PutBucketPolicyInput { + s.ConfirmRemoveSelfBucketAccess = &v return s } -// SetSize sets the Size field's value. -func (s *Part) SetSize(v int64) *Part { - s.Size = &v +// SetPolicy sets the Policy field's value. +func (s *PutBucketPolicyInput) SetPolicy(v string) *PutBucketPolicyInput { + s.Policy = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationRequest -type PutBucketAccelerateConfigurationInput struct { - _ struct{} `type:"structure" payload:"AccelerateConfiguration"` +type PutBucketPolicyOutput struct { + _ struct{} `type:"structure"` +} - // Specifies the Accelerate Configuration you want to set for the bucket. - // - // AccelerateConfiguration is a required field - AccelerateConfiguration *AccelerateConfiguration `locationName:"AccelerateConfiguration" type:"structure" required:"true"` +// String returns the string representation +func (s PutBucketPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBucketPolicyOutput) GoString() string { + return s.String() +} + +type PutBucketReplicationInput struct { + _ struct{} `type:"structure" payload:"ReplicationConfiguration"` - // Name of the bucket for which the accelerate configuration is set. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // A container for replication rules. You can add up to 1,000 rules. The maximum + // size of a replication configuration is 2 MB. + // + // ReplicationConfiguration is a required field + ReplicationConfiguration *ReplicationConfiguration `locationName:"ReplicationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketAccelerateConfigurationInput) String() string { +func (s PutBucketReplicationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAccelerateConfigurationInput) GoString() string { +func (s PutBucketReplicationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAccelerateConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAccelerateConfigurationInput"} - if s.AccelerateConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("AccelerateConfiguration")) - } +func (s *PutBucketReplicationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketReplicationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.ReplicationConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("ReplicationConfiguration")) + } + if s.ReplicationConfiguration != nil { + if err := s.ReplicationConfiguration.Validate(); err != nil { + invalidParams.AddNested("ReplicationConfiguration", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -15167,81 +19647,74 @@ func (s *PutBucketAccelerateConfigurationInput) Validate() error { return nil } -// SetAccelerateConfiguration sets the AccelerateConfiguration field's value. -func (s *PutBucketAccelerateConfigurationInput) SetAccelerateConfiguration(v *AccelerateConfiguration) *PutBucketAccelerateConfigurationInput { - s.AccelerateConfiguration = v +// SetBucket sets the Bucket field's value. +func (s *PutBucketReplicationInput) SetBucket(v string) *PutBucketReplicationInput { + s.Bucket = &v return s } -// SetBucket sets the Bucket field's value. -func (s *PutBucketAccelerateConfigurationInput) SetBucket(v string) *PutBucketAccelerateConfigurationInput { - s.Bucket = &v +func (s *PutBucketReplicationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetReplicationConfiguration sets the ReplicationConfiguration field's value. +func (s *PutBucketReplicationInput) SetReplicationConfiguration(v *ReplicationConfiguration) *PutBucketReplicationInput { + s.ReplicationConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationOutput -type PutBucketAccelerateConfigurationOutput struct { +type PutBucketReplicationOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketAccelerateConfigurationOutput) String() string { +func (s PutBucketReplicationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAccelerateConfigurationOutput) GoString() string { +func (s PutBucketReplicationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclRequest -type PutBucketAclInput struct { - _ struct{} `type:"structure" payload:"AccessControlPolicy"` - - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure"` +type PutBucketRequestPaymentInput struct { + _ struct{} `type:"structure" payload:"RequestPaymentConfiguration"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + // RequestPaymentConfiguration is a required field + RequestPaymentConfiguration *RequestPaymentConfiguration `locationName:"RequestPaymentConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketAclInput) String() string { +func (s PutBucketRequestPaymentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAclInput) GoString() string { +func (s PutBucketRequestPaymentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAclInput"} +func (s *PutBucketRequestPaymentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketRequestPaymentInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.AccessControlPolicy != nil { - if err := s.AccessControlPolicy.Validate(); err != nil { - invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.RequestPaymentConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("RequestPaymentConfiguration")) + } + if s.RequestPaymentConfiguration != nil { + if err := s.RequestPaymentConfiguration.Validate(); err != nil { + invalidParams.AddNested("RequestPaymentConfiguration", err.(request.ErrInvalidParams)) } } @@ -15251,114 +19724,74 @@ func (s *PutBucketAclInput) Validate() error { return nil } -// SetACL sets the ACL field's value. -func (s *PutBucketAclInput) SetACL(v string) *PutBucketAclInput { - s.ACL = &v - return s -} - -// SetAccessControlPolicy sets the AccessControlPolicy field's value. -func (s *PutBucketAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutBucketAclInput { - s.AccessControlPolicy = v - return s -} - // SetBucket sets the Bucket field's value. -func (s *PutBucketAclInput) SetBucket(v string) *PutBucketAclInput { +func (s *PutBucketRequestPaymentInput) SetBucket(v string) *PutBucketRequestPaymentInput { s.Bucket = &v return s } -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutBucketAclInput) SetGrantFullControl(v string) *PutBucketAclInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *PutBucketAclInput) SetGrantRead(v string) *PutBucketAclInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutBucketAclInput) SetGrantReadACP(v string) *PutBucketAclInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWrite sets the GrantWrite field's value. -func (s *PutBucketAclInput) SetGrantWrite(v string) *PutBucketAclInput { - s.GrantWrite = &v - return s +func (s *PutBucketRequestPaymentInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutBucketAclInput) SetGrantWriteACP(v string) *PutBucketAclInput { - s.GrantWriteACP = &v +// SetRequestPaymentConfiguration sets the RequestPaymentConfiguration field's value. +func (s *PutBucketRequestPaymentInput) SetRequestPaymentConfiguration(v *RequestPaymentConfiguration) *PutBucketRequestPaymentInput { + s.RequestPaymentConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclOutput -type PutBucketAclOutput struct { +type PutBucketRequestPaymentOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketAclOutput) String() string { +func (s PutBucketRequestPaymentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAclOutput) GoString() string { +func (s PutBucketRequestPaymentOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationRequest -type PutBucketAnalyticsConfigurationInput struct { - _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` - - // The configuration and any analyses for the analytics filter. - // - // AnalyticsConfiguration is a required field - AnalyticsConfiguration *AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"structure" required:"true"` +type PutBucketTaggingInput struct { + _ struct{} `type:"structure" payload:"Tagging"` - // The name of the bucket to which an analytics configuration is stored. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` + // Tagging is a required field + Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketAnalyticsConfigurationInput) String() string { +func (s PutBucketTaggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAnalyticsConfigurationInput) GoString() string { +func (s PutBucketTaggingInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAnalyticsConfigurationInput"} - if s.AnalyticsConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("AnalyticsConfiguration")) - } +func (s *PutBucketTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketTaggingInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.AnalyticsConfiguration != nil { - if err := s.AnalyticsConfiguration.Validate(); err != nil { - invalidParams.AddNested("AnalyticsConfiguration", err.(request.ErrInvalidParams)) + if s.Tagging == nil { + invalidParams.Add(request.NewErrParamRequired("Tagging")) + } + if s.Tagging != nil { + if err := s.Tagging.Validate(); err != nil { + invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) } } @@ -15368,73 +19801,74 @@ func (s *PutBucketAnalyticsConfigurationInput) Validate() error { return nil } -// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *PutBucketAnalyticsConfigurationInput { - s.AnalyticsConfiguration = v - return s -} - // SetBucket sets the Bucket field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetBucket(v string) *PutBucketAnalyticsConfigurationInput { +func (s *PutBucketTaggingInput) SetBucket(v string) *PutBucketTaggingInput { s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyticsConfigurationInput { - s.Id = &v +func (s *PutBucketTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetTagging sets the Tagging field's value. +func (s *PutBucketTaggingInput) SetTagging(v *Tagging) *PutBucketTaggingInput { + s.Tagging = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationOutput -type PutBucketAnalyticsConfigurationOutput struct { +type PutBucketTaggingOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketAnalyticsConfigurationOutput) String() string { +func (s PutBucketTaggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketAnalyticsConfigurationOutput) GoString() string { +func (s PutBucketTaggingOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsRequest -type PutBucketCorsInput struct { - _ struct{} `type:"structure" payload:"CORSConfiguration"` +type PutBucketVersioningInput struct { + _ struct{} `type:"structure" payload:"VersioningConfiguration"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // CORSConfiguration is a required field - CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure" required:"true"` + // The concatenation of the authentication device's serial number, a space, + // and the value that is displayed on your authentication device. + MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` + + // VersioningConfiguration is a required field + VersioningConfiguration *VersioningConfiguration `locationName:"VersioningConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketCorsInput) String() string { +func (s PutBucketVersioningInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketCorsInput) GoString() string { +func (s PutBucketVersioningInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketCorsInput"} +func (s *PutBucketVersioningInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketVersioningInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.CORSConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("CORSConfiguration")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.CORSConfiguration != nil { - if err := s.CORSConfiguration.Validate(); err != nil { - invalidParams.AddNested("CORSConfiguration", err.(request.ErrInvalidParams)) - } + if s.VersioningConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("VersioningConfiguration")) } if invalidParams.Len() > 0 { @@ -15444,77 +19878,79 @@ func (s *PutBucketCorsInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketCorsInput) SetBucket(v string) *PutBucketCorsInput { +func (s *PutBucketVersioningInput) SetBucket(v string) *PutBucketVersioningInput { s.Bucket = &v return s } -// SetCORSConfiguration sets the CORSConfiguration field's value. -func (s *PutBucketCorsInput) SetCORSConfiguration(v *CORSConfiguration) *PutBucketCorsInput { - s.CORSConfiguration = v +func (s *PutBucketVersioningInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetMFA sets the MFA field's value. +func (s *PutBucketVersioningInput) SetMFA(v string) *PutBucketVersioningInput { + s.MFA = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsOutput -type PutBucketCorsOutput struct { +// SetVersioningConfiguration sets the VersioningConfiguration field's value. +func (s *PutBucketVersioningInput) SetVersioningConfiguration(v *VersioningConfiguration) *PutBucketVersioningInput { + s.VersioningConfiguration = v + return s +} + +type PutBucketVersioningOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketCorsOutput) String() string { +func (s PutBucketVersioningOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketCorsOutput) GoString() string { +func (s PutBucketVersioningOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationRequest -type PutBucketInventoryConfigurationInput struct { - _ struct{} `type:"structure" payload:"InventoryConfiguration"` +type PutBucketWebsiteInput struct { + _ struct{} `type:"structure" payload:"WebsiteConfiguration"` - // The name of the bucket where the inventory configuration will be stored. - // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // Specifies the inventory configuration. - // - // InventoryConfiguration is a required field - InventoryConfiguration *InventoryConfiguration `locationName:"InventoryConfiguration" type:"structure" required:"true"` + // WebsiteConfiguration is a required field + WebsiteConfiguration *WebsiteConfiguration `locationName:"WebsiteConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketInventoryConfigurationInput) String() string { +func (s PutBucketWebsiteInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketInventoryConfigurationInput) GoString() string { +func (s PutBucketWebsiteInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketInventoryConfigurationInput"} +func (s *PutBucketWebsiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBucketWebsiteInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.InventoryConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("InventoryConfiguration")) + if s.WebsiteConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("WebsiteConfiguration")) } - if s.InventoryConfiguration != nil { - if err := s.InventoryConfiguration.Validate(); err != nil { - invalidParams.AddNested("InventoryConfiguration", err.(request.ErrInvalidParams)) + if s.WebsiteConfiguration != nil { + if err := s.WebsiteConfiguration.Validate(); err != nil { + invalidParams.AddNested("WebsiteConfiguration", err.(request.ErrInvalidParams)) } } @@ -15525,67 +19961,106 @@ func (s *PutBucketInventoryConfigurationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketInventoryConfigurationInput) SetBucket(v string) *PutBucketInventoryConfigurationInput { +func (s *PutBucketWebsiteInput) SetBucket(v string) *PutBucketWebsiteInput { s.Bucket = &v return s } -// SetId sets the Id field's value. -func (s *PutBucketInventoryConfigurationInput) SetId(v string) *PutBucketInventoryConfigurationInput { - s.Id = &v - return s +func (s *PutBucketWebsiteInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetInventoryConfiguration sets the InventoryConfiguration field's value. -func (s *PutBucketInventoryConfigurationInput) SetInventoryConfiguration(v *InventoryConfiguration) *PutBucketInventoryConfigurationInput { - s.InventoryConfiguration = v +// SetWebsiteConfiguration sets the WebsiteConfiguration field's value. +func (s *PutBucketWebsiteInput) SetWebsiteConfiguration(v *WebsiteConfiguration) *PutBucketWebsiteInput { + s.WebsiteConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationOutput -type PutBucketInventoryConfigurationOutput struct { +type PutBucketWebsiteOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketInventoryConfigurationOutput) String() string { +func (s PutBucketWebsiteOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketInventoryConfigurationOutput) GoString() string { +func (s PutBucketWebsiteOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationRequest -type PutBucketLifecycleConfigurationInput struct { - _ struct{} `type:"structure" payload:"LifecycleConfiguration"` +type PutObjectAclInput struct { + _ struct{} `type:"structure" payload:"AccessControlPolicy"` + + // The canned ACL to apply to the object. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` + + AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - LifecycleConfiguration *BucketLifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure"` + // Allows grantee the read, write, read ACP, and write ACP permissions on the + // bucket. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to list the objects in the bucket. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the bucket ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to create, overwrite, and delete any object in the bucket. + GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` + + // Allows grantee to write the ACL for the applicable bucket. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // VersionId used to reference a specific version of the object. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s PutBucketLifecycleConfigurationInput) String() string { +func (s PutObjectAclInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketLifecycleConfigurationInput) GoString() string { +func (s PutObjectAclInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLifecycleConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleConfigurationInput"} +func (s *PutObjectAclInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectAclInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.LifecycleConfiguration != nil { - if err := s.LifecycleConfiguration.Validate(); err != nil { - invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.AccessControlPolicy != nil { + if err := s.AccessControlPolicy.Validate(); err != nil { + invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) } } @@ -15595,63 +20070,241 @@ func (s *PutBucketLifecycleConfigurationInput) Validate() error { return nil } +// SetACL sets the ACL field's value. +func (s *PutObjectAclInput) SetACL(v string) *PutObjectAclInput { + s.ACL = &v + return s +} + +// SetAccessControlPolicy sets the AccessControlPolicy field's value. +func (s *PutObjectAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutObjectAclInput { + s.AccessControlPolicy = v + return s +} + // SetBucket sets the Bucket field's value. -func (s *PutBucketLifecycleConfigurationInput) SetBucket(v string) *PutBucketLifecycleConfigurationInput { +func (s *PutObjectAclInput) SetBucket(v string) *PutObjectAclInput { s.Bucket = &v return s } -// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. -func (s *PutBucketLifecycleConfigurationInput) SetLifecycleConfiguration(v *BucketLifecycleConfiguration) *PutBucketLifecycleConfigurationInput { - s.LifecycleConfiguration = v +func (s *PutObjectAclInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *PutObjectAclInput) SetGrantFullControl(v string) *PutObjectAclInput { + s.GrantFullControl = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationOutput -type PutBucketLifecycleConfigurationOutput struct { +// SetGrantRead sets the GrantRead field's value. +func (s *PutObjectAclInput) SetGrantRead(v string) *PutObjectAclInput { + s.GrantRead = &v + return s +} + +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *PutObjectAclInput) SetGrantReadACP(v string) *PutObjectAclInput { + s.GrantReadACP = &v + return s +} + +// SetGrantWrite sets the GrantWrite field's value. +func (s *PutObjectAclInput) SetGrantWrite(v string) *PutObjectAclInput { + s.GrantWrite = &v + return s +} + +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *PutObjectAclInput) SetGrantWriteACP(v string) *PutObjectAclInput { + s.GrantWriteACP = &v + return s +} + +// SetKey sets the Key field's value. +func (s *PutObjectAclInput) SetKey(v string) *PutObjectAclInput { + s.Key = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *PutObjectAclInput) SetRequestPayer(v string) *PutObjectAclInput { + s.RequestPayer = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *PutObjectAclInput) SetVersionId(v string) *PutObjectAclInput { + s.VersionId = &v + return s +} + +type PutObjectAclOutput struct { _ struct{} `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s PutBucketLifecycleConfigurationOutput) String() string { +func (s PutObjectAclOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketLifecycleConfigurationOutput) GoString() string { +func (s PutObjectAclOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleRequest -type PutBucketLifecycleInput struct { - _ struct{} `type:"structure" payload:"LifecycleConfiguration"` +// SetRequestCharged sets the RequestCharged field's value. +func (s *PutObjectAclOutput) SetRequestCharged(v string) *PutObjectAclOutput { + s.RequestCharged = &v + return s +} + +type PutObjectInput struct { + _ struct{} `type:"structure" payload:"Body"` + + // The canned ACL to apply to the object. + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` + + // Object data. + Body io.ReadSeeker `type:"blob"` + + // Name of the bucket to which the PUT operation was initiated. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Specifies caching behavior along the request/reply chain. + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + + // Specifies presentational information for the object. + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` + + // Size of the body in bytes. This parameter is useful when the size of the + // body cannot be determined automatically. + ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` + + // The base64-encoded 128-bit MD5 digest of the part data. + ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` + + // A standard MIME type describing the format of the object data. + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + + // The date and time at which the object is no longer cacheable. + Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` + + // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to read the object data and its metadata. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the object ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to write the ACL for the applicable object. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Object key for which the PUT operation was initiated. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + + // The Legal Hold status that you want to apply to the specified object. + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` + + // The Object Lock mode that you want to apply to this object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // The date and time when you want this object's Object Lock to expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Specifies the algorithm to use to when encrypting the object (e.g., AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // does not store the encryption key. The key must be appropriate for use with + // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure the encryption + // key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT + // requests for an object protected by AWS KMS will fail if not made via SSL + // or using SigV4. Documentation on configuring any of the officially supported + // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The type of storage to use for the object. Defaults to 'STANDARD'. + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - LifecycleConfiguration *LifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure"` + // The tag-set for the object. The tag-set must be encoded as URL Query parameters. + // (For example, "Key1=Value1") + Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` + + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` } // String returns the string representation -func (s PutBucketLifecycleInput) String() string { +func (s PutObjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketLifecycleInput) GoString() string { +func (s PutObjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleInput"} +func (s *PutObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.LifecycleConfiguration != nil { - if err := s.LifecycleConfiguration.Validate(); err != nil { - invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) - } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -15660,290 +20313,245 @@ func (s *PutBucketLifecycleInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *PutBucketLifecycleInput) SetBucket(v string) *PutBucketLifecycleInput { - s.Bucket = &v +// SetACL sets the ACL field's value. +func (s *PutObjectInput) SetACL(v string) *PutObjectInput { + s.ACL = &v return s } -// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. -func (s *PutBucketLifecycleInput) SetLifecycleConfiguration(v *LifecycleConfiguration) *PutBucketLifecycleInput { - s.LifecycleConfiguration = v +// SetBody sets the Body field's value. +func (s *PutObjectInput) SetBody(v io.ReadSeeker) *PutObjectInput { + s.Body = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleOutput -type PutBucketLifecycleOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketLifecycleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLifecycleOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingRequest -type PutBucketLoggingInput struct { - _ struct{} `type:"structure" payload:"BucketLoggingStatus"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // BucketLoggingStatus is a required field - BucketLoggingStatus *BucketLoggingStatus `locationName:"BucketLoggingStatus" type:"structure" required:"true"` -} - -// String returns the string representation -func (s PutBucketLoggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLoggingInput) GoString() string { - return s.String() +// SetBucket sets the Bucket field's value. +func (s *PutObjectInput) SetBucket(v string) *PutObjectInput { + s.Bucket = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLoggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLoggingInput"} +func (s *PutObjectInput) getBucket() (v string) { if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.BucketLoggingStatus == nil { - invalidParams.Add(request.NewErrParamRequired("BucketLoggingStatus")) - } - if s.BucketLoggingStatus != nil { - if err := s.BucketLoggingStatus.Validate(); err != nil { - invalidParams.AddNested("BucketLoggingStatus", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams + return v } - return nil + return *s.Bucket } -// SetBucket sets the Bucket field's value. -func (s *PutBucketLoggingInput) SetBucket(v string) *PutBucketLoggingInput { - s.Bucket = &v +// SetCacheControl sets the CacheControl field's value. +func (s *PutObjectInput) SetCacheControl(v string) *PutObjectInput { + s.CacheControl = &v return s } -// SetBucketLoggingStatus sets the BucketLoggingStatus field's value. -func (s *PutBucketLoggingInput) SetBucketLoggingStatus(v *BucketLoggingStatus) *PutBucketLoggingInput { - s.BucketLoggingStatus = v +// SetContentDisposition sets the ContentDisposition field's value. +func (s *PutObjectInput) SetContentDisposition(v string) *PutObjectInput { + s.ContentDisposition = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingOutput -type PutBucketLoggingOutput struct { - _ struct{} `type:"structure"` +// SetContentEncoding sets the ContentEncoding field's value. +func (s *PutObjectInput) SetContentEncoding(v string) *PutObjectInput { + s.ContentEncoding = &v + return s } -// String returns the string representation -func (s PutBucketLoggingOutput) String() string { - return awsutil.Prettify(s) +// SetContentLanguage sets the ContentLanguage field's value. +func (s *PutObjectInput) SetContentLanguage(v string) *PutObjectInput { + s.ContentLanguage = &v + return s } -// GoString returns the string representation -func (s PutBucketLoggingOutput) GoString() string { - return s.String() +// SetContentLength sets the ContentLength field's value. +func (s *PutObjectInput) SetContentLength(v int64) *PutObjectInput { + s.ContentLength = &v + return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationRequest -type PutBucketMetricsConfigurationInput struct { - _ struct{} `type:"structure" payload:"MetricsConfiguration"` - - // The name of the bucket for which the metrics configuration is set. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // Specifies the metrics configuration. - // - // MetricsConfiguration is a required field - MetricsConfiguration *MetricsConfiguration `locationName:"MetricsConfiguration" type:"structure" required:"true"` +// SetContentMD5 sets the ContentMD5 field's value. +func (s *PutObjectInput) SetContentMD5(v string) *PutObjectInput { + s.ContentMD5 = &v + return s } -// String returns the string representation -func (s PutBucketMetricsConfigurationInput) String() string { - return awsutil.Prettify(s) +// SetContentType sets the ContentType field's value. +func (s *PutObjectInput) SetContentType(v string) *PutObjectInput { + s.ContentType = &v + return s } -// GoString returns the string representation -func (s PutBucketMetricsConfigurationInput) GoString() string { - return s.String() +// SetExpires sets the Expires field's value. +func (s *PutObjectInput) SetExpires(v time.Time) *PutObjectInput { + s.Expires = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketMetricsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.MetricsConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("MetricsConfiguration")) - } - if s.MetricsConfiguration != nil { - if err := s.MetricsConfiguration.Validate(); err != nil { - invalidParams.AddNested("MetricsConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetGrantFullControl sets the GrantFullControl field's value. +func (s *PutObjectInput) SetGrantFullControl(v string) *PutObjectInput { + s.GrantFullControl = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *PutBucketMetricsConfigurationInput) SetBucket(v string) *PutBucketMetricsConfigurationInput { - s.Bucket = &v +// SetGrantRead sets the GrantRead field's value. +func (s *PutObjectInput) SetGrantRead(v string) *PutObjectInput { + s.GrantRead = &v return s } -// SetId sets the Id field's value. -func (s *PutBucketMetricsConfigurationInput) SetId(v string) *PutBucketMetricsConfigurationInput { - s.Id = &v +// SetGrantReadACP sets the GrantReadACP field's value. +func (s *PutObjectInput) SetGrantReadACP(v string) *PutObjectInput { + s.GrantReadACP = &v return s } -// SetMetricsConfiguration sets the MetricsConfiguration field's value. -func (s *PutBucketMetricsConfigurationInput) SetMetricsConfiguration(v *MetricsConfiguration) *PutBucketMetricsConfigurationInput { - s.MetricsConfiguration = v +// SetGrantWriteACP sets the GrantWriteACP field's value. +func (s *PutObjectInput) SetGrantWriteACP(v string) *PutObjectInput { + s.GrantWriteACP = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationOutput -type PutBucketMetricsConfigurationOutput struct { - _ struct{} `type:"structure"` +// SetKey sets the Key field's value. +func (s *PutObjectInput) SetKey(v string) *PutObjectInput { + s.Key = &v + return s } -// String returns the string representation -func (s PutBucketMetricsConfigurationOutput) String() string { - return awsutil.Prettify(s) +// SetMetadata sets the Metadata field's value. +func (s *PutObjectInput) SetMetadata(v map[string]*string) *PutObjectInput { + s.Metadata = v + return s } -// GoString returns the string representation -func (s PutBucketMetricsConfigurationOutput) GoString() string { - return s.String() +// SetObjectLockLegalHoldStatus sets the ObjectLockLegalHoldStatus field's value. +func (s *PutObjectInput) SetObjectLockLegalHoldStatus(v string) *PutObjectInput { + s.ObjectLockLegalHoldStatus = &v + return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationRequest -type PutBucketNotificationConfigurationInput struct { - _ struct{} `type:"structure" payload:"NotificationConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetObjectLockMode sets the ObjectLockMode field's value. +func (s *PutObjectInput) SetObjectLockMode(v string) *PutObjectInput { + s.ObjectLockMode = &v + return s +} - // Container for specifying the notification configuration of the bucket. If - // this element is empty, notifications are turned off on the bucket. - // - // NotificationConfiguration is a required field - NotificationConfiguration *NotificationConfiguration `locationName:"NotificationConfiguration" type:"structure" required:"true"` +// SetObjectLockRetainUntilDate sets the ObjectLockRetainUntilDate field's value. +func (s *PutObjectInput) SetObjectLockRetainUntilDate(v time.Time) *PutObjectInput { + s.ObjectLockRetainUntilDate = &v + return s } -// String returns the string representation -func (s PutBucketNotificationConfigurationInput) String() string { - return awsutil.Prettify(s) +// SetRequestPayer sets the RequestPayer field's value. +func (s *PutObjectInput) SetRequestPayer(v string) *PutObjectInput { + s.RequestPayer = &v + return s } -// GoString returns the string representation -func (s PutBucketNotificationConfigurationInput) GoString() string { - return s.String() +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *PutObjectInput) SetSSECustomerAlgorithm(v string) *PutObjectInput { + s.SSECustomerAlgorithm = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketNotificationConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.NotificationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) - } - if s.NotificationConfiguration != nil { - if err := s.NotificationConfiguration.Validate(); err != nil { - invalidParams.AddNested("NotificationConfiguration", err.(request.ErrInvalidParams)) - } - } +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *PutObjectInput) SetSSECustomerKey(v string) *PutObjectInput { + s.SSECustomerKey = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams +func (s *PutObjectInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v } - return nil + return *s.SSECustomerKey } -// SetBucket sets the Bucket field's value. -func (s *PutBucketNotificationConfigurationInput) SetBucket(v string) *PutBucketNotificationConfigurationInput { - s.Bucket = &v +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *PutObjectInput) SetSSECustomerKeyMD5(v string) *PutObjectInput { + s.SSECustomerKeyMD5 = &v return s } -// SetNotificationConfiguration sets the NotificationConfiguration field's value. -func (s *PutBucketNotificationConfigurationInput) SetNotificationConfiguration(v *NotificationConfiguration) *PutBucketNotificationConfigurationInput { - s.NotificationConfiguration = v +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *PutObjectInput) SetSSEKMSKeyId(v string) *PutObjectInput { + s.SSEKMSKeyId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationOutput -type PutBucketNotificationConfigurationOutput struct { - _ struct{} `type:"structure"` +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *PutObjectInput) SetServerSideEncryption(v string) *PutObjectInput { + s.ServerSideEncryption = &v + return s } -// String returns the string representation -func (s PutBucketNotificationConfigurationOutput) String() string { - return awsutil.Prettify(s) +// SetStorageClass sets the StorageClass field's value. +func (s *PutObjectInput) SetStorageClass(v string) *PutObjectInput { + s.StorageClass = &v + return s } -// GoString returns the string representation -func (s PutBucketNotificationConfigurationOutput) GoString() string { - return s.String() +// SetTagging sets the Tagging field's value. +func (s *PutObjectInput) SetTagging(v string) *PutObjectInput { + s.Tagging = &v + return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationRequest -type PutBucketNotificationInput struct { - _ struct{} `type:"structure" payload:"NotificationConfiguration"` +// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. +func (s *PutObjectInput) SetWebsiteRedirectLocation(v string) *PutObjectInput { + s.WebsiteRedirectLocation = &v + return s +} + +type PutObjectLegalHoldInput struct { + _ struct{} `type:"structure" payload:"LegalHold"` + // The bucket containing the object that you want to place a Legal Hold on. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // NotificationConfiguration is a required field - NotificationConfiguration *NotificationConfigurationDeprecated `locationName:"NotificationConfiguration" type:"structure" required:"true"` + // The key name for the object that you want to place a Legal Hold on. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Container element for the Legal Hold configuration you want to apply to the + // specified object. + LegalHold *ObjectLockLegalHold `locationName:"LegalHold" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // The version ID of the object that you want to place a Legal Hold on. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s PutBucketNotificationInput) String() string { +func (s PutObjectLegalHoldInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketNotificationInput) GoString() string { +func (s PutObjectLegalHoldInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketNotificationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationInput"} +func (s *PutObjectLegalHoldInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectLegalHoldInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.NotificationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -15953,63 +20561,104 @@ func (s *PutBucketNotificationInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketNotificationInput) SetBucket(v string) *PutBucketNotificationInput { +func (s *PutObjectLegalHoldInput) SetBucket(v string) *PutObjectLegalHoldInput { s.Bucket = &v return s } -// SetNotificationConfiguration sets the NotificationConfiguration field's value. -func (s *PutBucketNotificationInput) SetNotificationConfiguration(v *NotificationConfigurationDeprecated) *PutBucketNotificationInput { - s.NotificationConfiguration = v +func (s *PutObjectLegalHoldInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *PutObjectLegalHoldInput) SetKey(v string) *PutObjectLegalHoldInput { + s.Key = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationOutput -type PutBucketNotificationOutput struct { +// SetLegalHold sets the LegalHold field's value. +func (s *PutObjectLegalHoldInput) SetLegalHold(v *ObjectLockLegalHold) *PutObjectLegalHoldInput { + s.LegalHold = v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *PutObjectLegalHoldInput) SetRequestPayer(v string) *PutObjectLegalHoldInput { + s.RequestPayer = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *PutObjectLegalHoldInput) SetVersionId(v string) *PutObjectLegalHoldInput { + s.VersionId = &v + return s +} + +type PutObjectLegalHoldOutput struct { _ struct{} `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s PutBucketNotificationOutput) String() string { +func (s PutObjectLegalHoldOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketNotificationOutput) GoString() string { +func (s PutObjectLegalHoldOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyRequest -type PutBucketPolicyInput struct { - _ struct{} `type:"structure" payload:"Policy"` +// SetRequestCharged sets the RequestCharged field's value. +func (s *PutObjectLegalHoldOutput) SetRequestCharged(v string) *PutObjectLegalHoldOutput { + s.RequestCharged = &v + return s +} +type PutObjectLockConfigurationInput struct { + _ struct{} `type:"structure" payload:"ObjectLockConfiguration"` + + // The bucket whose Object Lock configuration you want to create or replace. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The bucket policy as a JSON document. - // - // Policy is a required field - Policy *string `type:"string" required:"true"` + // The Object Lock configuration that you want to apply to the specified bucket. + ObjectLockConfiguration *ObjectLockConfiguration `locationName:"ObjectLockConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + Token *string `location:"header" locationName:"x-amz-bucket-object-lock-token" type:"string"` } // String returns the string representation -func (s PutBucketPolicyInput) String() string { +func (s PutObjectLockConfigurationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketPolicyInput) GoString() string { +func (s PutObjectLockConfigurationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketPolicyInput"} +func (s *PutObjectLockConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectLockConfigurationInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Policy == nil { - invalidParams.Add(request.NewErrParamRequired("Policy")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } if invalidParams.Len() > 0 { @@ -16019,138 +20668,210 @@ func (s *PutBucketPolicyInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketPolicyInput) SetBucket(v string) *PutBucketPolicyInput { +func (s *PutObjectLockConfigurationInput) SetBucket(v string) *PutObjectLockConfigurationInput { s.Bucket = &v return s } -// SetPolicy sets the Policy field's value. -func (s *PutBucketPolicyInput) SetPolicy(v string) *PutBucketPolicyInput { - s.Policy = &v +func (s *PutObjectLockConfigurationInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetObjectLockConfiguration sets the ObjectLockConfiguration field's value. +func (s *PutObjectLockConfigurationInput) SetObjectLockConfiguration(v *ObjectLockConfiguration) *PutObjectLockConfigurationInput { + s.ObjectLockConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyOutput -type PutBucketPolicyOutput struct { +// SetRequestPayer sets the RequestPayer field's value. +func (s *PutObjectLockConfigurationInput) SetRequestPayer(v string) *PutObjectLockConfigurationInput { + s.RequestPayer = &v + return s +} + +// SetToken sets the Token field's value. +func (s *PutObjectLockConfigurationInput) SetToken(v string) *PutObjectLockConfigurationInput { + s.Token = &v + return s +} + +type PutObjectLockConfigurationOutput struct { _ struct{} `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s PutBucketPolicyOutput) String() string { +func (s PutObjectLockConfigurationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketPolicyOutput) GoString() string { +func (s PutObjectLockConfigurationOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationRequest -type PutBucketReplicationInput struct { - _ struct{} `type:"structure" payload:"ReplicationConfiguration"` +// SetRequestCharged sets the RequestCharged field's value. +func (s *PutObjectLockConfigurationOutput) SetRequestCharged(v string) *PutObjectLockConfigurationOutput { + s.RequestCharged = &v + return s +} - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +type PutObjectOutput struct { + _ struct{} `type:"structure"` - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - // - // ReplicationConfiguration is a required field - ReplicationConfiguration *ReplicationConfiguration `locationName:"ReplicationConfiguration" type:"structure" required:"true"` + // Entity tag for the uploaded object. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // If the object expiration is configured, this will contain the expiration + // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. + Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header confirming the encryption algorithm + // used. + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // If server-side encryption with a customer-provided encryption key was requested, + // the response will include this header to provide round trip message integrity + // verification of the customer-provided encryption key. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // If present, specifies the ID of the AWS Key Management Service (KMS) master + // encryption key that was used for the object. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The Server-side encryption algorithm used when storing this object in S3 + // (e.g., AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // Version of the object. + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` } // String returns the string representation -func (s PutBucketReplicationInput) String() string { +func (s PutObjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketReplicationInput) GoString() string { +func (s PutObjectOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketReplicationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.ReplicationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("ReplicationConfiguration")) - } - if s.ReplicationConfiguration != nil { - if err := s.ReplicationConfiguration.Validate(); err != nil { - invalidParams.AddNested("ReplicationConfiguration", err.(request.ErrInvalidParams)) - } - } +// SetETag sets the ETag field's value. +func (s *PutObjectOutput) SetETag(v string) *PutObjectOutput { + s.ETag = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetExpiration sets the Expiration field's value. +func (s *PutObjectOutput) SetExpiration(v string) *PutObjectOutput { + s.Expiration = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *PutBucketReplicationInput) SetBucket(v string) *PutBucketReplicationInput { - s.Bucket = &v +// SetRequestCharged sets the RequestCharged field's value. +func (s *PutObjectOutput) SetRequestCharged(v string) *PutObjectOutput { + s.RequestCharged = &v return s } -// SetReplicationConfiguration sets the ReplicationConfiguration field's value. -func (s *PutBucketReplicationInput) SetReplicationConfiguration(v *ReplicationConfiguration) *PutBucketReplicationInput { - s.ReplicationConfiguration = v +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *PutObjectOutput) SetSSECustomerAlgorithm(v string) *PutObjectOutput { + s.SSECustomerAlgorithm = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationOutput -type PutBucketReplicationOutput struct { - _ struct{} `type:"structure"` +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *PutObjectOutput) SetSSECustomerKeyMD5(v string) *PutObjectOutput { + s.SSECustomerKeyMD5 = &v + return s } -// String returns the string representation -func (s PutBucketReplicationOutput) String() string { - return awsutil.Prettify(s) +// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. +func (s *PutObjectOutput) SetSSEKMSKeyId(v string) *PutObjectOutput { + s.SSEKMSKeyId = &v + return s } -// GoString returns the string representation -func (s PutBucketReplicationOutput) GoString() string { - return s.String() +// SetServerSideEncryption sets the ServerSideEncryption field's value. +func (s *PutObjectOutput) SetServerSideEncryption(v string) *PutObjectOutput { + s.ServerSideEncryption = &v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *PutObjectOutput) SetVersionId(v string) *PutObjectOutput { + s.VersionId = &v + return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentRequest -type PutBucketRequestPaymentInput struct { - _ struct{} `type:"structure" payload:"RequestPaymentConfiguration"` +type PutObjectRetentionInput struct { + _ struct{} `type:"structure" payload:"Retention"` + // The bucket that contains the object you want to apply this Object Retention + // configuration to. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // RequestPaymentConfiguration is a required field - RequestPaymentConfiguration *RequestPaymentConfiguration `locationName:"RequestPaymentConfiguration" type:"structure" required:"true"` + // Indicates whether this operation should bypass Governance-mode restrictions.j + BypassGovernanceRetention *bool `location:"header" locationName:"x-amz-bypass-governance-retention" type:"boolean"` + + // The key name for the object that you want to apply this Object Retention + // configuration to. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // The container element for the Object Retention configuration. + Retention *ObjectLockRetention `locationName:"Retention" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // The version ID for the object that you want to apply this Object Retention + // configuration to. + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s PutBucketRequestPaymentInput) String() string { +func (s PutObjectRetentionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketRequestPaymentInput) GoString() string { +func (s PutObjectRetentionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketRequestPaymentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketRequestPaymentInput"} +func (s *PutObjectRetentionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectRetentionInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.RequestPaymentConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("RequestPaymentConfiguration")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.RequestPaymentConfiguration != nil { - if err := s.RequestPaymentConfiguration.Validate(); err != nil { - invalidParams.AddNested("RequestPaymentConfiguration", err.(request.ErrInvalidParams)) - } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -16160,59 +20881,112 @@ func (s *PutBucketRequestPaymentInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketRequestPaymentInput) SetBucket(v string) *PutBucketRequestPaymentInput { +func (s *PutObjectRetentionInput) SetBucket(v string) *PutObjectRetentionInput { s.Bucket = &v return s } -// SetRequestPaymentConfiguration sets the RequestPaymentConfiguration field's value. -func (s *PutBucketRequestPaymentInput) SetRequestPaymentConfiguration(v *RequestPaymentConfiguration) *PutBucketRequestPaymentInput { - s.RequestPaymentConfiguration = v +func (s *PutObjectRetentionInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetBypassGovernanceRetention sets the BypassGovernanceRetention field's value. +func (s *PutObjectRetentionInput) SetBypassGovernanceRetention(v bool) *PutObjectRetentionInput { + s.BypassGovernanceRetention = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentOutput -type PutBucketRequestPaymentOutput struct { +// SetKey sets the Key field's value. +func (s *PutObjectRetentionInput) SetKey(v string) *PutObjectRetentionInput { + s.Key = &v + return s +} + +// SetRequestPayer sets the RequestPayer field's value. +func (s *PutObjectRetentionInput) SetRequestPayer(v string) *PutObjectRetentionInput { + s.RequestPayer = &v + return s +} + +// SetRetention sets the Retention field's value. +func (s *PutObjectRetentionInput) SetRetention(v *ObjectLockRetention) *PutObjectRetentionInput { + s.Retention = v + return s +} + +// SetVersionId sets the VersionId field's value. +func (s *PutObjectRetentionInput) SetVersionId(v string) *PutObjectRetentionInput { + s.VersionId = &v + return s +} + +type PutObjectRetentionOutput struct { _ struct{} `type:"structure"` + + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` } // String returns the string representation -func (s PutBucketRequestPaymentOutput) String() string { +func (s PutObjectRetentionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketRequestPaymentOutput) GoString() string { +func (s PutObjectRetentionOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingRequest -type PutBucketTaggingInput struct { +// SetRequestCharged sets the RequestCharged field's value. +func (s *PutObjectRetentionOutput) SetRequestCharged(v string) *PutObjectRetentionOutput { + s.RequestCharged = &v + return s +} + +type PutObjectTaggingInput struct { _ struct{} `type:"structure" payload:"Tagging"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Tagging is a required field - Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true"` + Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s PutBucketTaggingInput) String() string { +func (s PutObjectTaggingInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketTaggingInput) GoString() string { +func (s PutObjectTaggingInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketTaggingInput"} +func (s *PutObjectTaggingInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutObjectTaggingInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } if s.Tagging == nil { invalidParams.Add(request.NewErrParamRequired("Tagging")) } @@ -16229,65 +21003,98 @@ func (s *PutBucketTaggingInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketTaggingInput) SetBucket(v string) *PutBucketTaggingInput { +func (s *PutObjectTaggingInput) SetBucket(v string) *PutObjectTaggingInput { s.Bucket = &v return s } +func (s *PutObjectTaggingInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetKey sets the Key field's value. +func (s *PutObjectTaggingInput) SetKey(v string) *PutObjectTaggingInput { + s.Key = &v + return s +} + // SetTagging sets the Tagging field's value. -func (s *PutBucketTaggingInput) SetTagging(v *Tagging) *PutBucketTaggingInput { +func (s *PutObjectTaggingInput) SetTagging(v *Tagging) *PutObjectTaggingInput { s.Tagging = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingOutput -type PutBucketTaggingOutput struct { +// SetVersionId sets the VersionId field's value. +func (s *PutObjectTaggingInput) SetVersionId(v string) *PutObjectTaggingInput { + s.VersionId = &v + return s +} + +type PutObjectTaggingOutput struct { _ struct{} `type:"structure"` + + VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` } // String returns the string representation -func (s PutBucketTaggingOutput) String() string { +func (s PutObjectTaggingOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketTaggingOutput) GoString() string { +func (s PutObjectTaggingOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningRequest -type PutBucketVersioningInput struct { - _ struct{} `type:"structure" payload:"VersioningConfiguration"` +// SetVersionId sets the VersionId field's value. +func (s *PutObjectTaggingOutput) SetVersionId(v string) *PutObjectTaggingOutput { + s.VersionId = &v + return s +} +type PutPublicAccessBlockInput struct { + _ struct{} `type:"structure" payload:"PublicAccessBlockConfiguration"` + + // The name of the Amazon S3 bucket whose PublicAccessBlock configuration you + // want to set. + // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // VersioningConfiguration is a required field - VersioningConfiguration *VersioningConfiguration `locationName:"VersioningConfiguration" type:"structure" required:"true"` + // The PublicAccessBlock configuration that you want to apply to this Amazon + // S3 bucket. You can enable the configuration options in any combination. For + // more information about when Amazon S3 considers a bucket or object public, + // see The Meaning of "Public" (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-policy-status) + // in the Amazon Simple Storage Service Developer Guide. + // + // PublicAccessBlockConfiguration is a required field + PublicAccessBlockConfiguration *PublicAccessBlockConfiguration `locationName:"PublicAccessBlockConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } // String returns the string representation -func (s PutBucketVersioningInput) String() string { +func (s PutPublicAccessBlockInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketVersioningInput) GoString() string { +func (s PutPublicAccessBlockInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketVersioningInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketVersioningInput"} +func (s *PutPublicAccessBlockInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutPublicAccessBlockInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.VersioningConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("VersioningConfiguration")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.PublicAccessBlockConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("PublicAccessBlockConfiguration")) } if invalidParams.Len() > 0 { @@ -16297,72 +21104,81 @@ func (s *PutBucketVersioningInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutBucketVersioningInput) SetBucket(v string) *PutBucketVersioningInput { +func (s *PutPublicAccessBlockInput) SetBucket(v string) *PutPublicAccessBlockInput { s.Bucket = &v return s } -// SetMFA sets the MFA field's value. -func (s *PutBucketVersioningInput) SetMFA(v string) *PutBucketVersioningInput { - s.MFA = &v - return s +func (s *PutPublicAccessBlockInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket } -// SetVersioningConfiguration sets the VersioningConfiguration field's value. -func (s *PutBucketVersioningInput) SetVersioningConfiguration(v *VersioningConfiguration) *PutBucketVersioningInput { - s.VersioningConfiguration = v +// SetPublicAccessBlockConfiguration sets the PublicAccessBlockConfiguration field's value. +func (s *PutPublicAccessBlockInput) SetPublicAccessBlockConfiguration(v *PublicAccessBlockConfiguration) *PutPublicAccessBlockInput { + s.PublicAccessBlockConfiguration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningOutput -type PutBucketVersioningOutput struct { +type PutPublicAccessBlockOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s PutBucketVersioningOutput) String() string { +func (s PutPublicAccessBlockOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketVersioningOutput) GoString() string { +func (s PutPublicAccessBlockOutput) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteRequest -type PutBucketWebsiteInput struct { - _ struct{} `type:"structure" payload:"WebsiteConfiguration"` +// A container for specifying the configuration for publication of messages +// to an Amazon Simple Queue Service (Amazon SQS) queue.when Amazon S3 detects +// specified events. +type QueueConfiguration struct { + _ struct{} `type:"structure"` - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // Events is a required field + Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - // WebsiteConfiguration is a required field - WebsiteConfiguration *WebsiteConfiguration `locationName:"WebsiteConfiguration" type:"structure" required:"true"` + // A container for object key name filtering rules. For information about key + // name filtering, see Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. + Filter *NotificationConfigurationFilter `type:"structure"` + + // An optional unique identifier for configurations in a notification configuration. + // If you don't provide one, Amazon S3 will assign an ID. + Id *string `type:"string"` + + // The Amazon Resource Name (ARN) of the Amazon SQS queue to which Amazon S3 + // will publish a message when it detects events of the specified type. + // + // QueueArn is a required field + QueueArn *string `locationName:"Queue" type:"string" required:"true"` } // String returns the string representation -func (s PutBucketWebsiteInput) String() string { +func (s QueueConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketWebsiteInput) GoString() string { +func (s QueueConfiguration) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketWebsiteInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.WebsiteConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("WebsiteConfiguration")) +func (s *QueueConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "QueueConfiguration"} + if s.Events == nil { + invalidParams.Add(request.NewErrParamRequired("Events")) } - if s.WebsiteConfiguration != nil { - if err := s.WebsiteConfiguration.Validate(); err != nil { - invalidParams.AddNested("WebsiteConfiguration", err.(request.ErrInvalidParams)) - } + if s.QueueArn == nil { + invalidParams.Add(request.NewErrParamRequired("QueueArn")) } if invalidParams.Len() > 0 { @@ -16371,322 +21187,391 @@ func (s *PutBucketWebsiteInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *PutBucketWebsiteInput) SetBucket(v string) *PutBucketWebsiteInput { - s.Bucket = &v +// SetEvents sets the Events field's value. +func (s *QueueConfiguration) SetEvents(v []*string) *QueueConfiguration { + s.Events = v + return s +} + +// SetFilter sets the Filter field's value. +func (s *QueueConfiguration) SetFilter(v *NotificationConfigurationFilter) *QueueConfiguration { + s.Filter = v + return s +} + +// SetId sets the Id field's value. +func (s *QueueConfiguration) SetId(v string) *QueueConfiguration { + s.Id = &v + return s +} + +// SetQueueArn sets the QueueArn field's value. +func (s *QueueConfiguration) SetQueueArn(v string) *QueueConfiguration { + s.QueueArn = &v + return s +} + +type QueueConfigurationDeprecated struct { + _ struct{} `type:"structure"` + + // The bucket event for which to send notifications. + // + // Deprecated: Event has been deprecated + Event *string `deprecated:"true" type:"string" enum:"Event"` + + Events []*string `locationName:"Event" type:"list" flattened:"true"` + + // An optional unique identifier for configurations in a notification configuration. + // If you don't provide one, Amazon S3 will assign an ID. + Id *string `type:"string"` + + Queue *string `type:"string"` +} + +// String returns the string representation +func (s QueueConfigurationDeprecated) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s QueueConfigurationDeprecated) GoString() string { + return s.String() +} + +// SetEvent sets the Event field's value. +func (s *QueueConfigurationDeprecated) SetEvent(v string) *QueueConfigurationDeprecated { + s.Event = &v + return s +} + +// SetEvents sets the Events field's value. +func (s *QueueConfigurationDeprecated) SetEvents(v []*string) *QueueConfigurationDeprecated { + s.Events = v + return s +} + +// SetId sets the Id field's value. +func (s *QueueConfigurationDeprecated) SetId(v string) *QueueConfigurationDeprecated { + s.Id = &v return s } -// SetWebsiteConfiguration sets the WebsiteConfiguration field's value. -func (s *PutBucketWebsiteInput) SetWebsiteConfiguration(v *WebsiteConfiguration) *PutBucketWebsiteInput { - s.WebsiteConfiguration = v +// SetQueue sets the Queue field's value. +func (s *QueueConfigurationDeprecated) SetQueue(v string) *QueueConfigurationDeprecated { + s.Queue = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteOutput -type PutBucketWebsiteOutput struct { - _ struct{} `type:"structure"` +type RecordsEvent struct { + _ struct{} `locationName:"RecordsEvent" type:"structure" payload:"Payload"` + + // The byte array of partial, one or more result records. + // + // Payload is automatically base64 encoded/decoded by the SDK. + Payload []byte `type:"blob"` } // String returns the string representation -func (s PutBucketWebsiteOutput) String() string { +func (s RecordsEvent) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutBucketWebsiteOutput) GoString() string { +func (s RecordsEvent) GoString() string { return s.String() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclRequest -type PutObjectAclInput struct { - _ struct{} `type:"structure" payload:"AccessControlPolicy"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// SetPayload sets the Payload field's value. +func (s *RecordsEvent) SetPayload(v []byte) *RecordsEvent { + s.Payload = v + return s +} - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` +// The RecordsEvent is and event in the SelectObjectContentEventStream group of events. +func (s *RecordsEvent) eventSelectObjectContentEventStream() {} - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` +// UnmarshalEvent unmarshals the EventStream Message into the RecordsEvent value. +// This method is only used internally within the SDK's EventStream handling. +func (s *RecordsEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + s.Payload = make([]byte, len(msg.Payload)) + copy(s.Payload, msg.Payload) + return nil +} - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` +type Redirect struct { + _ struct{} `type:"structure"` - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` + // The host name to use in the redirect request. + HostName *string `type:"string"` - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + // The HTTP redirect code to use on the response. Not required if one of the + // siblings is present. + HttpRedirectCode *string `type:"string"` - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // Protocol to use (http, https) when redirecting requests. The default is the + // protocol that is used in the original request. + Protocol *string `type:"string" enum:"Protocol"` - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + // The object key prefix to use in the redirect request. For example, to redirect + // requests for all pages with prefix docs/ (objects in the docs/ folder) to + // documents/, you can set a condition block with KeyPrefixEquals set to docs/ + // and in the Redirect set ReplaceKeyPrefixWith to /documents. Not required + // if one of the siblings is present. Can be present only if ReplaceKeyWith + // is not provided. + ReplaceKeyPrefixWith *string `type:"string"` - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` + // The specific object key to use in the redirect request. For example, redirect + // request to error.html. Not required if one of the sibling is present. Can + // be present only if ReplaceKeyPrefixWith is not provided. + ReplaceKeyWith *string `type:"string"` } // String returns the string representation -func (s PutObjectAclInput) String() string { +func (s Redirect) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectAclInput) GoString() string { +func (s Redirect) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.AccessControlPolicy != nil { - if err := s.AccessControlPolicy.Validate(); err != nil { - invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *PutObjectAclInput) SetACL(v string) *PutObjectAclInput { - s.ACL = &v +// SetHostName sets the HostName field's value. +func (s *Redirect) SetHostName(v string) *Redirect { + s.HostName = &v return s } -// SetAccessControlPolicy sets the AccessControlPolicy field's value. -func (s *PutObjectAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutObjectAclInput { - s.AccessControlPolicy = v +// SetHttpRedirectCode sets the HttpRedirectCode field's value. +func (s *Redirect) SetHttpRedirectCode(v string) *Redirect { + s.HttpRedirectCode = &v return s } -// SetBucket sets the Bucket field's value. -func (s *PutObjectAclInput) SetBucket(v string) *PutObjectAclInput { - s.Bucket = &v +// SetProtocol sets the Protocol field's value. +func (s *Redirect) SetProtocol(v string) *Redirect { + s.Protocol = &v return s } -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutObjectAclInput) SetGrantFullControl(v string) *PutObjectAclInput { - s.GrantFullControl = &v +// SetReplaceKeyPrefixWith sets the ReplaceKeyPrefixWith field's value. +func (s *Redirect) SetReplaceKeyPrefixWith(v string) *Redirect { + s.ReplaceKeyPrefixWith = &v return s } -// SetGrantRead sets the GrantRead field's value. -func (s *PutObjectAclInput) SetGrantRead(v string) *PutObjectAclInput { - s.GrantRead = &v +// SetReplaceKeyWith sets the ReplaceKeyWith field's value. +func (s *Redirect) SetReplaceKeyWith(v string) *Redirect { + s.ReplaceKeyWith = &v return s } -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutObjectAclInput) SetGrantReadACP(v string) *PutObjectAclInput { - s.GrantReadACP = &v - return s +type RedirectAllRequestsTo struct { + _ struct{} `type:"structure"` + + // Name of the host where requests will be redirected. + // + // HostName is a required field + HostName *string `type:"string" required:"true"` + + // Protocol to use (http, https) when redirecting requests. The default is the + // protocol that is used in the original request. + Protocol *string `type:"string" enum:"Protocol"` } -// SetGrantWrite sets the GrantWrite field's value. -func (s *PutObjectAclInput) SetGrantWrite(v string) *PutObjectAclInput { - s.GrantWrite = &v - return s +// String returns the string representation +func (s RedirectAllRequestsTo) String() string { + return awsutil.Prettify(s) } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutObjectAclInput) SetGrantWriteACP(v string) *PutObjectAclInput { - s.GrantWriteACP = &v - return s +// GoString returns the string representation +func (s RedirectAllRequestsTo) GoString() string { + return s.String() } -// SetKey sets the Key field's value. -func (s *PutObjectAclInput) SetKey(v string) *PutObjectAclInput { - s.Key = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *RedirectAllRequestsTo) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RedirectAllRequestsTo"} + if s.HostName == nil { + invalidParams.Add(request.NewErrParamRequired("HostName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestPayer sets the RequestPayer field's value. -func (s *PutObjectAclInput) SetRequestPayer(v string) *PutObjectAclInput { - s.RequestPayer = &v +// SetHostName sets the HostName field's value. +func (s *RedirectAllRequestsTo) SetHostName(v string) *RedirectAllRequestsTo { + s.HostName = &v return s } -// SetVersionId sets the VersionId field's value. -func (s *PutObjectAclInput) SetVersionId(v string) *PutObjectAclInput { - s.VersionId = &v +// SetProtocol sets the Protocol field's value. +func (s *RedirectAllRequestsTo) SetProtocol(v string) *RedirectAllRequestsTo { + s.Protocol = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclOutput -type PutObjectAclOutput struct { +// A container for replication rules. You can add up to 1,000 rules. The maximum +// size of a replication configuration is 2 MB. +type ReplicationConfiguration struct { _ struct{} `type:"structure"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // The Amazon Resource Name (ARN) of the AWS Identity and Access Management + // (IAM) role that Amazon S3 can assume when replicating the objects. + // + // Role is a required field + Role *string `type:"string" required:"true"` + + // A container for one or more replication rules. A replication configuration + // must have at least one rule and can contain a maximum of 1,000 rules. + // + // Rules is a required field + Rules []*ReplicationRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` } // String returns the string representation -func (s PutObjectAclOutput) String() string { +func (s ReplicationConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectAclOutput) GoString() string { +func (s ReplicationConfiguration) GoString() string { return s.String() } -// SetRequestCharged sets the RequestCharged field's value. -func (s *PutObjectAclOutput) SetRequestCharged(v string) *PutObjectAclOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectRequest -type PutObjectInput struct { - _ struct{} `type:"structure" payload:"Body"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - // Object data. - Body io.ReadSeeker `type:"blob"` - - // Name of the bucket to which the PUT operation was initiated. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. This parameter is useful when the size of the - // body cannot be determined automatically. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *ReplicationConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ReplicationConfiguration"} + if s.Role == nil { + invalidParams.Add(request.NewErrParamRequired("Role")) + } + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) + } + if s.Rules != nil { + for i, v := range s.Rules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + } + } + } - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` +// SetRole sets the Role field's value. +func (s *ReplicationConfiguration) SetRole(v string) *ReplicationConfiguration { + s.Role = &v + return s +} - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` +// SetRules sets the Rules field's value. +func (s *ReplicationConfiguration) SetRules(v []*ReplicationRule) *ReplicationConfiguration { + s.Rules = v + return s +} - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` +// A container for information about a specific replication rule. +type ReplicationRule struct { + _ struct{} `type:"structure"` - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + // Specifies whether Amazon S3 should replicate delete makers. + DeleteMarkerReplication *DeleteMarkerReplication `type:"structure"` - // Object key for which the PUT operation was initiated. + // A container for information about the replication destination. // - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + // Destination is a required field + Destination *Destination `type:"structure" required:"true"` - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` + // A filter that identifies the subset of objects to which the replication rule + // applies. A Filter must specify exactly one Prefix, Tag, or an And child element. + Filter *ReplicationRuleFilter `type:"structure"` - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + // A unique identifier for the rule. The maximum value is 255 characters. + ID *string `type:"string"` - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + // An object keyname prefix that identifies the object or objects to which the + // rule applies. The maximum prefix length is 1,024 characters. + // + // Deprecated: Prefix has been deprecated + Prefix *string `deprecated:"true" type:"string"` - // The tag-set for the object. The tag-set must be encoded as URL Query parameters - Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` + // The priority associated with the rule. If you specify multiple rules in a + // replication configuration, Amazon S3 prioritizes the rules to prevent conflicts + // when filtering. If two or more rules identify the same object based on a + // specified filter, the rule with higher priority takes precedence. For example: + // + // * Same object quality prefix based filter criteria If prefixes you specified + // in multiple rules overlap + // + // * Same object qualify tag based filter criteria specified in multiple + // rules + // + // For more information, see Cross-Region Replication (CRR) ( https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) + // in the Amazon S3 Developer Guide. + Priority *int64 `type:"integer"` + + // A container that describes additional filters for identifying the source + // objects that you want to replicate. You can choose to enable or disable the + // replication of these objects. Currently, Amazon S3 supports only the filter + // that you can specify for objects created with server-side encryption using + // an AWS KMS-Managed Key (SSE-KMS). + // + // If you want Amazon S3 to replicate objects created with server-side encryption + // using AWS KMS-Managed Keys. + SourceSelectionCriteria *SourceSelectionCriteria `type:"structure"` - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` + // If status isn't enabled, the rule is ignored. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"ReplicationRuleStatus"` } // String returns the string representation -func (s PutObjectInput) String() string { +func (s ReplicationRule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectInput) GoString() string { +func (s ReplicationRule) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *ReplicationRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ReplicationRule"} + if s.Destination == nil { + invalidParams.Add(request.NewErrParamRequired("Destination")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.Destination != nil { + if err := s.Destination.Validate(); err != nil { + invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) + } + } + if s.Filter != nil { + if err := s.Filter.Validate(); err != nil { + invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) + } + } + if s.SourceSelectionCriteria != nil { + if err := s.SourceSelectionCriteria.Validate(); err != nil { + invalidParams.AddNested("SourceSelectionCriteria", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -16695,254 +21580,242 @@ func (s *PutObjectInput) Validate() error { return nil } -// SetACL sets the ACL field's value. -func (s *PutObjectInput) SetACL(v string) *PutObjectInput { - s.ACL = &v +// SetDeleteMarkerReplication sets the DeleteMarkerReplication field's value. +func (s *ReplicationRule) SetDeleteMarkerReplication(v *DeleteMarkerReplication) *ReplicationRule { + s.DeleteMarkerReplication = v return s } -// SetBody sets the Body field's value. -func (s *PutObjectInput) SetBody(v io.ReadSeeker) *PutObjectInput { - s.Body = v +// SetDestination sets the Destination field's value. +func (s *ReplicationRule) SetDestination(v *Destination) *ReplicationRule { + s.Destination = v return s } -// SetBucket sets the Bucket field's value. -func (s *PutObjectInput) SetBucket(v string) *PutObjectInput { - s.Bucket = &v +// SetFilter sets the Filter field's value. +func (s *ReplicationRule) SetFilter(v *ReplicationRuleFilter) *ReplicationRule { + s.Filter = v return s } -// SetCacheControl sets the CacheControl field's value. -func (s *PutObjectInput) SetCacheControl(v string) *PutObjectInput { - s.CacheControl = &v +// SetID sets the ID field's value. +func (s *ReplicationRule) SetID(v string) *ReplicationRule { + s.ID = &v return s } -// SetContentDisposition sets the ContentDisposition field's value. -func (s *PutObjectInput) SetContentDisposition(v string) *PutObjectInput { - s.ContentDisposition = &v +// SetPrefix sets the Prefix field's value. +func (s *ReplicationRule) SetPrefix(v string) *ReplicationRule { + s.Prefix = &v return s } -// SetContentEncoding sets the ContentEncoding field's value. -func (s *PutObjectInput) SetContentEncoding(v string) *PutObjectInput { - s.ContentEncoding = &v +// SetPriority sets the Priority field's value. +func (s *ReplicationRule) SetPriority(v int64) *ReplicationRule { + s.Priority = &v return s } -// SetContentLanguage sets the ContentLanguage field's value. -func (s *PutObjectInput) SetContentLanguage(v string) *PutObjectInput { - s.ContentLanguage = &v +// SetSourceSelectionCriteria sets the SourceSelectionCriteria field's value. +func (s *ReplicationRule) SetSourceSelectionCriteria(v *SourceSelectionCriteria) *ReplicationRule { + s.SourceSelectionCriteria = v return s } -// SetContentLength sets the ContentLength field's value. -func (s *PutObjectInput) SetContentLength(v int64) *PutObjectInput { - s.ContentLength = &v +// SetStatus sets the Status field's value. +func (s *ReplicationRule) SetStatus(v string) *ReplicationRule { + s.Status = &v return s } -// SetContentType sets the ContentType field's value. -func (s *PutObjectInput) SetContentType(v string) *PutObjectInput { - s.ContentType = &v - return s -} +type ReplicationRuleAndOperator struct { + _ struct{} `type:"structure"` -// SetExpires sets the Expires field's value. -func (s *PutObjectInput) SetExpires(v time.Time) *PutObjectInput { - s.Expires = &v - return s -} + Prefix *string `type:"string"` -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutObjectInput) SetGrantFullControl(v string) *PutObjectInput { - s.GrantFullControl = &v - return s + Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` } -// SetGrantRead sets the GrantRead field's value. -func (s *PutObjectInput) SetGrantRead(v string) *PutObjectInput { - s.GrantRead = &v - return s +// String returns the string representation +func (s ReplicationRuleAndOperator) String() string { + return awsutil.Prettify(s) } -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutObjectInput) SetGrantReadACP(v string) *PutObjectInput { - s.GrantReadACP = &v - return s +// GoString returns the string representation +func (s ReplicationRuleAndOperator) GoString() string { + return s.String() } -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutObjectInput) SetGrantWriteACP(v string) *PutObjectInput { - s.GrantWriteACP = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ReplicationRuleAndOperator) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ReplicationRuleAndOperator"} + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } -// SetKey sets the Key field's value. -func (s *PutObjectInput) SetKey(v string) *PutObjectInput { - s.Key = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetMetadata sets the Metadata field's value. -func (s *PutObjectInput) SetMetadata(v map[string]*string) *PutObjectInput { - s.Metadata = v +// SetPrefix sets the Prefix field's value. +func (s *ReplicationRuleAndOperator) SetPrefix(v string) *ReplicationRuleAndOperator { + s.Prefix = &v return s } -// SetRequestPayer sets the RequestPayer field's value. -func (s *PutObjectInput) SetRequestPayer(v string) *PutObjectInput { - s.RequestPayer = &v +// SetTags sets the Tags field's value. +func (s *ReplicationRuleAndOperator) SetTags(v []*Tag) *ReplicationRuleAndOperator { + s.Tags = v return s } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *PutObjectInput) SetSSECustomerAlgorithm(v string) *PutObjectInput { - s.SSECustomerAlgorithm = &v - return s -} +// A filter that identifies the subset of objects to which the replication rule +// applies. A Filter must specify exactly one Prefix, Tag, or an And child element. +type ReplicationRuleFilter struct { + _ struct{} `type:"structure"` -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *PutObjectInput) SetSSECustomerKey(v string) *PutObjectInput { - s.SSECustomerKey = &v - return s + // A container for specifying rule filters. The filters determine the subset + // of objects to which the rule applies. This element is required only if you + // specify more than one filter. For example: + // + // * If you specify both a Prefix and a Tag filter, wrap these filters in + // an And tag. + // + // * If you specify a filter based on multiple tags, wrap the Tag elements + // in an And tag. + And *ReplicationRuleAndOperator `type:"structure"` + + // An object keyname prefix that identifies the subset of objects to which the + // rule applies. + Prefix *string `type:"string"` + + // A container for specifying a tag key and value. + // + // The rule applies only to objects that have the tag in their tag set. + Tag *Tag `type:"structure"` } -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *PutObjectInput) SetSSECustomerKeyMD5(v string) *PutObjectInput { - s.SSECustomerKeyMD5 = &v - return s +// String returns the string representation +func (s ReplicationRuleFilter) String() string { + return awsutil.Prettify(s) } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *PutObjectInput) SetSSEKMSKeyId(v string) *PutObjectInput { - s.SSEKMSKeyId = &v - return s +// GoString returns the string representation +func (s ReplicationRuleFilter) GoString() string { + return s.String() } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *PutObjectInput) SetServerSideEncryption(v string) *PutObjectInput { - s.ServerSideEncryption = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ReplicationRuleFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ReplicationRuleFilter"} + if s.And != nil { + if err := s.And.Validate(); err != nil { + invalidParams.AddNested("And", err.(request.ErrInvalidParams)) + } + } + if s.Tag != nil { + if err := s.Tag.Validate(); err != nil { + invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetStorageClass sets the StorageClass field's value. -func (s *PutObjectInput) SetStorageClass(v string) *PutObjectInput { - s.StorageClass = &v +// SetAnd sets the And field's value. +func (s *ReplicationRuleFilter) SetAnd(v *ReplicationRuleAndOperator) *ReplicationRuleFilter { + s.And = v return s } -// SetTagging sets the Tagging field's value. -func (s *PutObjectInput) SetTagging(v string) *PutObjectInput { - s.Tagging = &v +// SetPrefix sets the Prefix field's value. +func (s *ReplicationRuleFilter) SetPrefix(v string) *ReplicationRuleFilter { + s.Prefix = &v return s } -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *PutObjectInput) SetWebsiteRedirectLocation(v string) *PutObjectInput { - s.WebsiteRedirectLocation = &v +// SetTag sets the Tag field's value. +func (s *ReplicationRuleFilter) SetTag(v *Tag) *ReplicationRuleFilter { + s.Tag = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectOutput -type PutObjectOutput struct { +type RequestPaymentConfiguration struct { _ struct{} `type:"structure"` - // Entity tag for the uploaded object. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // Specifies who pays for the download and request fees. + // + // Payer is a required field + Payer *string `type:"string" required:"true" enum:"Payer"` } // String returns the string representation -func (s PutObjectOutput) String() string { +func (s RequestPaymentConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectOutput) GoString() string { +func (s RequestPaymentConfiguration) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *PutObjectOutput) SetETag(v string) *PutObjectOutput { - s.ETag = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *RequestPaymentConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RequestPaymentConfiguration"} + if s.Payer == nil { + invalidParams.Add(request.NewErrParamRequired("Payer")) + } -// SetExpiration sets the Expiration field's value. -func (s *PutObjectOutput) SetExpiration(v string) *PutObjectOutput { - s.Expiration = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestCharged sets the RequestCharged field's value. -func (s *PutObjectOutput) SetRequestCharged(v string) *PutObjectOutput { - s.RequestCharged = &v +// SetPayer sets the Payer field's value. +func (s *RequestPaymentConfiguration) SetPayer(v string) *RequestPaymentConfiguration { + s.Payer = &v return s } -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *PutObjectOutput) SetSSECustomerAlgorithm(v string) *PutObjectOutput { - s.SSECustomerAlgorithm = &v - return s -} +type RequestProgress struct { + _ struct{} `type:"structure"` -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *PutObjectOutput) SetSSECustomerKeyMD5(v string) *PutObjectOutput { - s.SSECustomerKeyMD5 = &v - return s + // Specifies whether periodic QueryProgress frames should be sent. Valid values: + // TRUE, FALSE. Default value: FALSE. + Enabled *bool `type:"boolean"` } -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *PutObjectOutput) SetSSEKMSKeyId(v string) *PutObjectOutput { - s.SSEKMSKeyId = &v - return s +// String returns the string representation +func (s RequestProgress) String() string { + return awsutil.Prettify(s) } -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *PutObjectOutput) SetServerSideEncryption(v string) *PutObjectOutput { - s.ServerSideEncryption = &v - return s +// GoString returns the string representation +func (s RequestProgress) GoString() string { + return s.String() } -// SetVersionId sets the VersionId field's value. -func (s *PutObjectOutput) SetVersionId(v string) *PutObjectOutput { - s.VersionId = &v +// SetEnabled sets the Enabled field's value. +func (s *RequestProgress) SetEnabled(v bool) *RequestProgress { + s.Enabled = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingRequest -type PutObjectTaggingInput struct { - _ struct{} `type:"structure" payload:"Tagging"` +type RestoreObjectInput struct { + _ struct{} `type:"structure" payload:"RestoreRequest"` // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -16950,40 +21823,46 @@ type PutObjectTaggingInput struct { // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - // Tagging is a required field - Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true"` + // Confirms that the requester knows that she or he will be charged for the + // request. Bucket owners need not specify this parameter in their requests. + // Documentation on downloading objects from requester pays buckets can be found + // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Container for restore job parameters. + RestoreRequest *RestoreRequest `locationName:"RestoreRequest" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` VersionId *string `location:"querystring" locationName:"versionId" type:"string"` } // String returns the string representation -func (s PutObjectTaggingInput) String() string { +func (s RestoreObjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectTaggingInput) GoString() string { +func (s RestoreObjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectTaggingInput"} +func (s *RestoreObjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RestoreObjectInput"} if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Key == nil { invalidParams.Add(request.NewErrParamRequired("Key")) } if s.Key != nil && len(*s.Key) < 1 { invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } - if s.Tagging == nil { - invalidParams.Add(request.NewErrParamRequired("Tagging")) - } - if s.Tagging != nil { - if err := s.Tagging.Validate(); err != nil { - invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) + if s.RestoreRequest != nil { + if err := s.RestoreRequest.Validate(); err != nil { + invalidParams.AddNested("RestoreRequest", err.(request.ErrInvalidParams)) } } @@ -16994,94 +21873,213 @@ func (s *PutObjectTaggingInput) Validate() error { } // SetBucket sets the Bucket field's value. -func (s *PutObjectTaggingInput) SetBucket(v string) *PutObjectTaggingInput { +func (s *RestoreObjectInput) SetBucket(v string) *RestoreObjectInput { s.Bucket = &v return s } +func (s *RestoreObjectInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetKey sets the Key field's value. -func (s *PutObjectTaggingInput) SetKey(v string) *PutObjectTaggingInput { +func (s *RestoreObjectInput) SetKey(v string) *RestoreObjectInput { s.Key = &v return s } -// SetTagging sets the Tagging field's value. -func (s *PutObjectTaggingInput) SetTagging(v *Tagging) *PutObjectTaggingInput { - s.Tagging = v +// SetRequestPayer sets the RequestPayer field's value. +func (s *RestoreObjectInput) SetRequestPayer(v string) *RestoreObjectInput { + s.RequestPayer = &v + return s +} + +// SetRestoreRequest sets the RestoreRequest field's value. +func (s *RestoreObjectInput) SetRestoreRequest(v *RestoreRequest) *RestoreObjectInput { + s.RestoreRequest = v return s } // SetVersionId sets the VersionId field's value. -func (s *PutObjectTaggingInput) SetVersionId(v string) *PutObjectTaggingInput { +func (s *RestoreObjectInput) SetVersionId(v string) *RestoreObjectInput { s.VersionId = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingOutput -type PutObjectTaggingOutput struct { +type RestoreObjectOutput struct { _ struct{} `type:"structure"` - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` + // If present, indicates that the requester was successfully charged for the + // request. + RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + + // Indicates the path in the provided S3 output location where Select results + // will be restored to. + RestoreOutputPath *string `location:"header" locationName:"x-amz-restore-output-path" type:"string"` } // String returns the string representation -func (s PutObjectTaggingOutput) String() string { +func (s RestoreObjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutObjectTaggingOutput) GoString() string { +func (s RestoreObjectOutput) GoString() string { return s.String() } -// SetVersionId sets the VersionId field's value. -func (s *PutObjectTaggingOutput) SetVersionId(v string) *PutObjectTaggingOutput { - s.VersionId = &v +// SetRequestCharged sets the RequestCharged field's value. +func (s *RestoreObjectOutput) SetRequestCharged(v string) *RestoreObjectOutput { + s.RequestCharged = &v return s } -// Container for specifying an configuration when you want Amazon S3 to publish -// events to an Amazon Simple Queue Service (Amazon SQS) queue. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfiguration -type QueueConfiguration struct { +// SetRestoreOutputPath sets the RestoreOutputPath field's value. +func (s *RestoreObjectOutput) SetRestoreOutputPath(v string) *RestoreObjectOutput { + s.RestoreOutputPath = &v + return s +} + +// Container for restore job parameters. +type RestoreRequest struct { _ struct{} `type:"structure"` - // Events is a required field - Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` + // Lifetime of the active copy in days. Do not use with restores that specify + // OutputLocation. + Days *int64 `type:"integer"` + + // The optional description for the job. + Description *string `type:"string"` + + // Glacier related parameters pertaining to this job. Do not use with restores + // that specify OutputLocation. + GlacierJobParameters *GlacierJobParameters `type:"structure"` + + // Describes the location where the restore job's output is stored. + OutputLocation *OutputLocation `type:"structure"` + + // Describes the parameters for Select job types. + SelectParameters *SelectParameters `type:"structure"` + + // Glacier retrieval tier at which the restore will be processed. + Tier *string `type:"string" enum:"Tier"` + + // Type of restore request. + Type *string `type:"string" enum:"RestoreRequestType"` +} + +// String returns the string representation +func (s RestoreRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreRequest) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RestoreRequest) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RestoreRequest"} + if s.GlacierJobParameters != nil { + if err := s.GlacierJobParameters.Validate(); err != nil { + invalidParams.AddNested("GlacierJobParameters", err.(request.ErrInvalidParams)) + } + } + if s.OutputLocation != nil { + if err := s.OutputLocation.Validate(); err != nil { + invalidParams.AddNested("OutputLocation", err.(request.ErrInvalidParams)) + } + } + if s.SelectParameters != nil { + if err := s.SelectParameters.Validate(); err != nil { + invalidParams.AddNested("SelectParameters", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDays sets the Days field's value. +func (s *RestoreRequest) SetDays(v int64) *RestoreRequest { + s.Days = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *RestoreRequest) SetDescription(v string) *RestoreRequest { + s.Description = &v + return s +} + +// SetGlacierJobParameters sets the GlacierJobParameters field's value. +func (s *RestoreRequest) SetGlacierJobParameters(v *GlacierJobParameters) *RestoreRequest { + s.GlacierJobParameters = v + return s +} + +// SetOutputLocation sets the OutputLocation field's value. +func (s *RestoreRequest) SetOutputLocation(v *OutputLocation) *RestoreRequest { + s.OutputLocation = v + return s +} + +// SetSelectParameters sets the SelectParameters field's value. +func (s *RestoreRequest) SetSelectParameters(v *SelectParameters) *RestoreRequest { + s.SelectParameters = v + return s +} + +// SetTier sets the Tier field's value. +func (s *RestoreRequest) SetTier(v string) *RestoreRequest { + s.Tier = &v + return s +} + +// SetType sets the Type field's value. +func (s *RestoreRequest) SetType(v string) *RestoreRequest { + s.Type = &v + return s +} - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Filter *NotificationConfigurationFilter `type:"structure"` +type RoutingRule struct { + _ struct{} `type:"structure"` - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` + // A container for describing a condition that must be met for the specified + // redirect to apply. For example, 1. If request is for pages in the /docs folder, + // redirect to the /documents folder. 2. If request results in HTTP error 4xx, + // redirect request to another host where you might process the error. + Condition *Condition `type:"structure"` - // Amazon SQS queue ARN to which Amazon S3 will publish a message when it detects - // events of specified type. + // Container for redirect information. You can redirect requests to another + // host, to another page, or with another protocol. In the event of an error, + // you can specify a different error code to return. // - // QueueArn is a required field - QueueArn *string `locationName:"Queue" type:"string" required:"true"` + // Redirect is a required field + Redirect *Redirect `type:"structure" required:"true"` } // String returns the string representation -func (s QueueConfiguration) String() string { +func (s RoutingRule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s QueueConfiguration) GoString() string { +func (s RoutingRule) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *QueueConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "QueueConfiguration"} - if s.Events == nil { - invalidParams.Add(request.NewErrParamRequired("Events")) - } - if s.QueueArn == nil { - invalidParams.Add(request.NewErrParamRequired("QueueArn")) +func (s *RoutingRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RoutingRule"} + if s.Redirect == nil { + invalidParams.Add(request.NewErrParamRequired("Redirect")) } if invalidParams.Len() > 0 { @@ -17090,314 +22088,500 @@ func (s *QueueConfiguration) Validate() error { return nil } -// SetEvents sets the Events field's value. -func (s *QueueConfiguration) SetEvents(v []*string) *QueueConfiguration { - s.Events = v +// SetCondition sets the Condition field's value. +func (s *RoutingRule) SetCondition(v *Condition) *RoutingRule { + s.Condition = v return s } -// SetFilter sets the Filter field's value. -func (s *QueueConfiguration) SetFilter(v *NotificationConfigurationFilter) *QueueConfiguration { - s.Filter = v +// SetRedirect sets the Redirect field's value. +func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { + s.Redirect = v return s } -// SetId sets the Id field's value. -func (s *QueueConfiguration) SetId(v string) *QueueConfiguration { - s.Id = &v - return s -} +type Rule struct { + _ struct{} `type:"structure"` -// SetQueueArn sets the QueueArn field's value. -func (s *QueueConfiguration) SetQueueArn(v string) *QueueConfiguration { - s.QueueArn = &v - return s -} + // Specifies the days since the initiation of an Incomplete Multipart Upload + // that Lifecycle will wait before permanently removing all parts of the upload. + AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfigurationDeprecated -type QueueConfigurationDeprecated struct { - _ struct{} `type:"structure"` + Expiration *LifecycleExpiration `type:"structure"` - // Bucket event for which to send notifications. - Event *string `deprecated:"true" type:"string" enum:"Event"` + // Unique identifier for the rule. The value cannot be longer than 255 characters. + ID *string `type:"string"` - Events []*string `locationName:"Event" type:"list" flattened:"true"` + // Specifies when noncurrent object versions expire. Upon expiration, Amazon + // S3 permanently deletes the noncurrent object versions. You set this lifecycle + // configuration action on a bucket that has versioning enabled (or suspended) + // to request that Amazon S3 delete noncurrent object versions at a specific + // period in the object's lifetime. + NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` + // Container for the transition rule that describes when noncurrent objects + // transition to the STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING or GLACIER + // storage class. If your bucket is versioning-enabled (or versioning is suspended), + // you can set this action to request that Amazon S3 transition noncurrent object + // versions to the STANDARD_IA, ONEZONE_IA, INTELLIGENT_TIERING or GLACIER storage + // class at a specific period in the object's lifetime. + NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` - Queue *string `type:"string"` + // Prefix identifying one or more objects to which the rule applies. + // + // Prefix is a required field + Prefix *string `type:"string" required:"true"` + + // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule + // is not currently being applied. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"ExpirationStatus"` + + Transition *Transition `type:"structure"` } // String returns the string representation -func (s QueueConfigurationDeprecated) String() string { +func (s Rule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s QueueConfigurationDeprecated) GoString() string { +func (s Rule) GoString() string { return s.String() } -// SetEvent sets the Event field's value. -func (s *QueueConfigurationDeprecated) SetEvent(v string) *QueueConfigurationDeprecated { - s.Event = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *Rule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Rule"} + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) + } + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. +func (s *Rule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *Rule { + s.AbortIncompleteMultipartUpload = v return s } -// SetEvents sets the Events field's value. -func (s *QueueConfigurationDeprecated) SetEvents(v []*string) *QueueConfigurationDeprecated { - s.Events = v +// SetExpiration sets the Expiration field's value. +func (s *Rule) SetExpiration(v *LifecycleExpiration) *Rule { + s.Expiration = v return s } -// SetId sets the Id field's value. -func (s *QueueConfigurationDeprecated) SetId(v string) *QueueConfigurationDeprecated { - s.Id = &v +// SetID sets the ID field's value. +func (s *Rule) SetID(v string) *Rule { + s.ID = &v return s } -// SetQueue sets the Queue field's value. -func (s *QueueConfigurationDeprecated) SetQueue(v string) *QueueConfigurationDeprecated { - s.Queue = &v +// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. +func (s *Rule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *Rule { + s.NoncurrentVersionExpiration = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Redirect -type Redirect struct { - _ struct{} `type:"structure"` +// SetNoncurrentVersionTransition sets the NoncurrentVersionTransition field's value. +func (s *Rule) SetNoncurrentVersionTransition(v *NoncurrentVersionTransition) *Rule { + s.NoncurrentVersionTransition = v + return s +} - // The host name to use in the redirect request. - HostName *string `type:"string"` +// SetPrefix sets the Prefix field's value. +func (s *Rule) SetPrefix(v string) *Rule { + s.Prefix = &v + return s +} - // The HTTP redirect code to use on the response. Not required if one of the - // siblings is present. - HttpRedirectCode *string `type:"string"` +// SetStatus sets the Status field's value. +func (s *Rule) SetStatus(v string) *Rule { + s.Status = &v + return s +} - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string" enum:"Protocol"` +// SetTransition sets the Transition field's value. +func (s *Rule) SetTransition(v *Transition) *Rule { + s.Transition = v + return s +} - // The object key prefix to use in the redirect request. For example, to redirect - // requests for all pages with prefix docs/ (objects in the docs/ folder) to - // documents/, you can set a condition block with KeyPrefixEquals set to docs/ - // and in the Redirect set ReplaceKeyPrefixWith to /documents. Not required - // if one of the siblings is present. Can be present only if ReplaceKeyWith - // is not provided. - ReplaceKeyPrefixWith *string `type:"string"` +// Specifies the use of SSE-KMS to encrypt delivered Inventory reports. +type SSEKMS struct { + _ struct{} `locationName:"SSE-KMS" type:"structure"` - // The specific object key to use in the redirect request. For example, redirect - // request to error.html. Not required if one of the sibling is present. Can - // be present only if ReplaceKeyPrefixWith is not provided. - ReplaceKeyWith *string `type:"string"` + // Specifies the ID of the AWS Key Management Service (KMS) master encryption + // key to use for encrypting Inventory reports. + // + // KeyId is a required field + KeyId *string `type:"string" required:"true" sensitive:"true"` } // String returns the string representation -func (s Redirect) String() string { +func (s SSEKMS) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Redirect) GoString() string { +func (s SSEKMS) GoString() string { return s.String() } -// SetHostName sets the HostName field's value. -func (s *Redirect) SetHostName(v string) *Redirect { - s.HostName = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *SSEKMS) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SSEKMS"} + if s.KeyId == nil { + invalidParams.Add(request.NewErrParamRequired("KeyId")) + } -// SetHttpRedirectCode sets the HttpRedirectCode field's value. -func (s *Redirect) SetHttpRedirectCode(v string) *Redirect { - s.HttpRedirectCode = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetProtocol sets the Protocol field's value. -func (s *Redirect) SetProtocol(v string) *Redirect { - s.Protocol = &v +// SetKeyId sets the KeyId field's value. +func (s *SSEKMS) SetKeyId(v string) *SSEKMS { + s.KeyId = &v return s } -// SetReplaceKeyPrefixWith sets the ReplaceKeyPrefixWith field's value. -func (s *Redirect) SetReplaceKeyPrefixWith(v string) *Redirect { - s.ReplaceKeyPrefixWith = &v - return s +// Specifies the use of SSE-S3 to encrypt delivered Inventory reports. +type SSES3 struct { + _ struct{} `locationName:"SSE-S3" type:"structure"` } -// SetReplaceKeyWith sets the ReplaceKeyWith field's value. -func (s *Redirect) SetReplaceKeyWith(v string) *Redirect { - s.ReplaceKeyWith = &v - return s +// String returns the string representation +func (s SSES3) String() string { + return awsutil.Prettify(s) } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RedirectAllRequestsTo -type RedirectAllRequestsTo struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s SSES3) GoString() string { + return s.String() +} - // Name of the host where requests will be redirected. +// SelectObjectContentEventStream provides handling of EventStreams for +// the SelectObjectContent API. +// +// Use this type to receive SelectObjectContentEventStream events. The events +// can be read from the Events channel member. +// +// The events that can be received are: +// +// * ContinuationEvent +// * EndEvent +// * ProgressEvent +// * RecordsEvent +// * StatsEvent +type SelectObjectContentEventStream struct { + // Reader is the EventStream reader for the SelectObjectContentEventStream + // events. This value is automatically set by the SDK when the API call is made + // Use this member when unit testing your code with the SDK to mock out the + // EventStream Reader. // - // HostName is a required field - HostName *string `type:"string" required:"true"` - - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string" enum:"Protocol"` -} + // Must not be nil. + Reader SelectObjectContentEventStreamReader -// String returns the string representation -func (s RedirectAllRequestsTo) String() string { - return awsutil.Prettify(s) + // StreamCloser is the io.Closer for the EventStream connection. For HTTP + // EventStream this is the response Body. The stream will be closed when + // the Close method of the EventStream is called. + StreamCloser io.Closer } -// GoString returns the string representation -func (s RedirectAllRequestsTo) GoString() string { - return s.String() +// Close closes the EventStream. This will also cause the Events channel to be +// closed. You can use the closing of the Events channel to terminate your +// application's read from the API's EventStream. +// +// Will close the underlying EventStream reader. For EventStream over HTTP +// connection this will also close the HTTP connection. +// +// Close must be called when done using the EventStream API. Not calling Close +// may result in resource leaks. +func (es *SelectObjectContentEventStream) Close() (err error) { + es.Reader.Close() + return es.Err() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *RedirectAllRequestsTo) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RedirectAllRequestsTo"} - if s.HostName == nil { - invalidParams.Add(request.NewErrParamRequired("HostName")) +// Err returns any error that occurred while reading EventStream Events from +// the service API's response. Returns nil if there were no errors. +func (es *SelectObjectContentEventStream) Err() error { + if err := es.Reader.Err(); err != nil { + return err } + es.StreamCloser.Close() - if invalidParams.Len() > 0 { - return invalidParams - } return nil } -// SetHostName sets the HostName field's value. -func (s *RedirectAllRequestsTo) SetHostName(v string) *RedirectAllRequestsTo { - s.HostName = &v - return s +// Events returns a channel to read EventStream Events from the +// SelectObjectContent API. +// +// These events are: +// +// * ContinuationEvent +// * EndEvent +// * ProgressEvent +// * RecordsEvent +// * StatsEvent +func (es *SelectObjectContentEventStream) Events() <-chan SelectObjectContentEventStreamEvent { + return es.Reader.Events() +} + +// SelectObjectContentEventStreamEvent groups together all EventStream +// events read from the SelectObjectContent API. +// +// These events are: +// +// * ContinuationEvent +// * EndEvent +// * ProgressEvent +// * RecordsEvent +// * StatsEvent +type SelectObjectContentEventStreamEvent interface { + eventSelectObjectContentEventStream() +} + +// SelectObjectContentEventStreamReader provides the interface for reading EventStream +// Events from the SelectObjectContent API. The +// default implementation for this interface will be SelectObjectContentEventStream. +// +// The reader's Close method must allow multiple concurrent calls. +// +// These events are: +// +// * ContinuationEvent +// * EndEvent +// * ProgressEvent +// * RecordsEvent +// * StatsEvent +type SelectObjectContentEventStreamReader interface { + // Returns a channel of events as they are read from the event stream. + Events() <-chan SelectObjectContentEventStreamEvent + + // Close will close the underlying event stream reader. For event stream over + // HTTP this will also close the HTTP connection. + Close() error + + // Returns any error that has occurred while reading from the event stream. + Err() error } -// SetProtocol sets the Protocol field's value. -func (s *RedirectAllRequestsTo) SetProtocol(v string) *RedirectAllRequestsTo { - s.Protocol = &v - return s +type readSelectObjectContentEventStream struct { + eventReader *eventstreamapi.EventReader + stream chan SelectObjectContentEventStreamEvent + errVal atomic.Value + + done chan struct{} + closeOnce sync.Once } -// Container for replication rules. You can add as many as 1,000 rules. Total -// replication configuration size can be up to 2 MB. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationConfiguration -type ReplicationConfiguration struct { - _ struct{} `type:"structure"` +func newReadSelectObjectContentEventStream( + reader io.ReadCloser, + unmarshalers request.HandlerList, + logger aws.Logger, + logLevel aws.LogLevelType, +) *readSelectObjectContentEventStream { + r := &readSelectObjectContentEventStream{ + stream: make(chan SelectObjectContentEventStreamEvent), + done: make(chan struct{}), + } - // Amazon Resource Name (ARN) of an IAM role for Amazon S3 to assume when replicating - // the objects. - // - // Role is a required field - Role *string `type:"string" required:"true"` + r.eventReader = eventstreamapi.NewEventReader( + reader, + protocol.HandlerPayloadUnmarshal{ + Unmarshalers: unmarshalers, + }, + r.unmarshalerForEventType, + ) + r.eventReader.UseLogger(logger, logLevel) - // Container for information about a particular replication rule. Replication - // configuration must have at least one rule and can contain up to 1,000 rules. - // - // Rules is a required field - Rules []*ReplicationRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` + return r } -// String returns the string representation -func (s ReplicationConfiguration) String() string { - return awsutil.Prettify(s) -} +// Close will close the underlying event stream reader. For EventStream over +// HTTP this will also close the HTTP connection. +func (r *readSelectObjectContentEventStream) Close() error { + r.closeOnce.Do(r.safeClose) -// GoString returns the string representation -func (s ReplicationConfiguration) GoString() string { - return s.String() + return r.Err() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ReplicationConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReplicationConfiguration"} - if s.Role == nil { - invalidParams.Add(request.NewErrParamRequired("Role")) +func (r *readSelectObjectContentEventStream) safeClose() { + close(r.done) + err := r.eventReader.Close() + if err != nil { + r.errVal.Store(err) } - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) +} + +func (r *readSelectObjectContentEventStream) Err() error { + if v := r.errVal.Load(); v != nil { + return v.(error) } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue + + return nil +} + +func (r *readSelectObjectContentEventStream) Events() <-chan SelectObjectContentEventStreamEvent { + return r.stream +} + +func (r *readSelectObjectContentEventStream) readEventStream() { + defer close(r.stream) + + for { + event, err := r.eventReader.ReadEvent() + if err != nil { + if err == io.EOF { + return } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + select { + case <-r.done: + // If closed already ignore the error + return + default: } + r.errVal.Store(err) + return } - } - if invalidParams.Len() > 0 { - return invalidParams + select { + case r.stream <- event.(SelectObjectContentEventStreamEvent): + case <-r.done: + return + } } - return nil } -// SetRole sets the Role field's value. -func (s *ReplicationConfiguration) SetRole(v string) *ReplicationConfiguration { - s.Role = &v - return s -} +func (r *readSelectObjectContentEventStream) unmarshalerForEventType( + eventType string, +) (eventstreamapi.Unmarshaler, error) { + switch eventType { + case "Cont": + return &ContinuationEvent{}, nil -// SetRules sets the Rules field's value. -func (s *ReplicationConfiguration) SetRules(v []*ReplicationRule) *ReplicationConfiguration { - s.Rules = v - return s + case "End": + return &EndEvent{}, nil + + case "Progress": + return &ProgressEvent{}, nil + + case "Records": + return &RecordsEvent{}, nil + + case "Stats": + return &StatsEvent{}, nil + default: + return nil, awserr.New( + request.ErrCodeSerialization, + fmt.Sprintf("unknown event type name, %s, for SelectObjectContentEventStream", eventType), + nil, + ) + } } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationRule -type ReplicationRule struct { - _ struct{} `type:"structure"` +// Request to filter the contents of an Amazon S3 object based on a simple Structured +// Query Language (SQL) statement. In the request, along with the SQL expression, +// you must specify a data serialization format (JSON or CSV) of the object. +// Amazon S3 uses this to parse object data into records. It returns only records +// that match the specified SQL expression. You must also specify the data serialization +// format for the response. For more information, see S3Select API Documentation +// (http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectSELECTContent.html). +type SelectObjectContentInput struct { + _ struct{} `locationName:"SelectObjectContentRequest" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - // Destination is a required field - Destination *Destination `type:"structure" required:"true"` + // The S3 bucket. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` + // The expression that is used to query the object. + // + // Expression is a required field + Expression *string `type:"string" required:"true"` - // Object keyname prefix identifying one or more objects to which the rule applies. - // Maximum prefix length can be up to 1,024 characters. Overlapping prefixes - // are not supported. + // The type of the provided expression (for example., SQL). // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` + // ExpressionType is a required field + ExpressionType *string `type:"string" required:"true" enum:"ExpressionType"` - // The rule is ignored if status is not Enabled. + // Describes the format of the data in the object that is being queried. // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ReplicationRuleStatus"` + // InputSerialization is a required field + InputSerialization *InputSerialization `type:"structure" required:"true"` + + // The object key. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // Describes the format of the data that you want Amazon S3 to return in response. + // + // OutputSerialization is a required field + OutputSerialization *OutputSerialization `type:"structure" required:"true"` + + // Specifies if periodic request progress information should be enabled. + RequestProgress *RequestProgress `type:"structure"` + + // The SSE Algorithm used to encrypt the object. For more information, see + // Server-Side Encryption (Using Customer-Provided Encryption Keys (http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // The SSE Customer Key. For more information, see Server-Side Encryption (Using + // Customer-Provided Encryption Keys (http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html). + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // The SSE Customer Key MD5. For more information, see Server-Side Encryption + // (Using Customer-Provided Encryption Keys (http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html). + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` } // String returns the string representation -func (s ReplicationRule) String() string { +func (s SelectObjectContentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ReplicationRule) GoString() string { +func (s SelectObjectContentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ReplicationRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReplicationRule"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) +func (s *SelectObjectContentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SelectObjectContentInput"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) + if s.Expression == nil { + invalidParams.Add(request.NewErrParamRequired("Expression")) } - if s.Destination != nil { - if err := s.Destination.Validate(); err != nil { - invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) - } + if s.ExpressionType == nil { + invalidParams.Add(request.NewErrParamRequired("ExpressionType")) + } + if s.InputSerialization == nil { + invalidParams.Add(request.NewErrParamRequired("InputSerialization")) + } + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.OutputSerialization == nil { + invalidParams.Add(request.NewErrParamRequired("OutputSerialization")) } if invalidParams.Len() > 0 { @@ -17406,116 +22590,171 @@ func (s *ReplicationRule) Validate() error { return nil } -// SetDestination sets the Destination field's value. -func (s *ReplicationRule) SetDestination(v *Destination) *ReplicationRule { - s.Destination = v +// SetBucket sets the Bucket field's value. +func (s *SelectObjectContentInput) SetBucket(v string) *SelectObjectContentInput { + s.Bucket = &v return s } -// SetID sets the ID field's value. -func (s *ReplicationRule) SetID(v string) *ReplicationRule { - s.ID = &v +func (s *SelectObjectContentInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + +// SetExpression sets the Expression field's value. +func (s *SelectObjectContentInput) SetExpression(v string) *SelectObjectContentInput { + s.Expression = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *ReplicationRule) SetPrefix(v string) *ReplicationRule { - s.Prefix = &v +// SetExpressionType sets the ExpressionType field's value. +func (s *SelectObjectContentInput) SetExpressionType(v string) *SelectObjectContentInput { + s.ExpressionType = &v return s } -// SetStatus sets the Status field's value. -func (s *ReplicationRule) SetStatus(v string) *ReplicationRule { - s.Status = &v +// SetInputSerialization sets the InputSerialization field's value. +func (s *SelectObjectContentInput) SetInputSerialization(v *InputSerialization) *SelectObjectContentInput { + s.InputSerialization = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RequestPaymentConfiguration -type RequestPaymentConfiguration struct { - _ struct{} `type:"structure"` +// SetKey sets the Key field's value. +func (s *SelectObjectContentInput) SetKey(v string) *SelectObjectContentInput { + s.Key = &v + return s +} - // Specifies who pays for the download and request fees. - // - // Payer is a required field - Payer *string `type:"string" required:"true" enum:"Payer"` +// SetOutputSerialization sets the OutputSerialization field's value. +func (s *SelectObjectContentInput) SetOutputSerialization(v *OutputSerialization) *SelectObjectContentInput { + s.OutputSerialization = v + return s +} + +// SetRequestProgress sets the RequestProgress field's value. +func (s *SelectObjectContentInput) SetRequestProgress(v *RequestProgress) *SelectObjectContentInput { + s.RequestProgress = v + return s +} + +// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. +func (s *SelectObjectContentInput) SetSSECustomerAlgorithm(v string) *SelectObjectContentInput { + s.SSECustomerAlgorithm = &v + return s +} + +// SetSSECustomerKey sets the SSECustomerKey field's value. +func (s *SelectObjectContentInput) SetSSECustomerKey(v string) *SelectObjectContentInput { + s.SSECustomerKey = &v + return s +} + +func (s *SelectObjectContentInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey +} + +// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. +func (s *SelectObjectContentInput) SetSSECustomerKeyMD5(v string) *SelectObjectContentInput { + s.SSECustomerKeyMD5 = &v + return s +} + +type SelectObjectContentOutput struct { + _ struct{} `type:"structure" payload:"Payload"` + + // Use EventStream to use the API's stream. + EventStream *SelectObjectContentEventStream `type:"structure"` } // String returns the string representation -func (s RequestPaymentConfiguration) String() string { +func (s SelectObjectContentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RequestPaymentConfiguration) GoString() string { +func (s SelectObjectContentOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *RequestPaymentConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RequestPaymentConfiguration"} - if s.Payer == nil { - invalidParams.Add(request.NewErrParamRequired("Payer")) - } +// SetEventStream sets the EventStream field's value. +func (s *SelectObjectContentOutput) SetEventStream(v *SelectObjectContentEventStream) *SelectObjectContentOutput { + s.EventStream = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams +func (s *SelectObjectContentOutput) runEventStreamLoop(r *request.Request) { + if r.Error != nil { + return } - return nil -} + reader := newReadSelectObjectContentEventStream( + r.HTTPResponse.Body, + r.Handlers.UnmarshalStream, + r.Config.Logger, + r.Config.LogLevel.Value(), + ) + go reader.readEventStream() -// SetPayer sets the Payer field's value. -func (s *RequestPaymentConfiguration) SetPayer(v string) *RequestPaymentConfiguration { - s.Payer = &v - return s + eventStream := &SelectObjectContentEventStream{ + StreamCloser: r.HTTPResponse.Body, + Reader: reader, + } + s.EventStream = eventStream } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectRequest -type RestoreObjectInput struct { - _ struct{} `type:"structure" payload:"RestoreRequest"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` +// Describes the parameters for Select job types. +type SelectParameters struct { + _ struct{} `type:"structure"` - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + // The expression that is used to query the object. + // + // Expression is a required field + Expression *string `type:"string" required:"true"` - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + // The type of the provided expression (e.g., SQL). + // + // ExpressionType is a required field + ExpressionType *string `type:"string" required:"true" enum:"ExpressionType"` - RestoreRequest *RestoreRequest `locationName:"RestoreRequest" type:"structure"` + // Describes the serialization format of the object. + // + // InputSerialization is a required field + InputSerialization *InputSerialization `type:"structure" required:"true"` - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` + // Describes how the results of the Select job are serialized. + // + // OutputSerialization is a required field + OutputSerialization *OutputSerialization `type:"structure" required:"true"` } // String returns the string representation -func (s RestoreObjectInput) String() string { +func (s SelectParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RestoreObjectInput) GoString() string { +func (s SelectParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RestoreObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RestoreObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) +func (s *SelectParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SelectParameters"} + if s.Expression == nil { + invalidParams.Add(request.NewErrParamRequired("Expression")) } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) + if s.ExpressionType == nil { + invalidParams.Add(request.NewErrParamRequired("ExpressionType")) } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.InputSerialization == nil { + invalidParams.Add(request.NewErrParamRequired("InputSerialization")) } - if s.RestoreRequest != nil { - if err := s.RestoreRequest.Validate(); err != nil { - invalidParams.AddNested("RestoreRequest", err.(request.ErrInvalidParams)) - } + if s.OutputSerialization == nil { + invalidParams.Add(request.NewErrParamRequired("OutputSerialization")) } if invalidParams.Len() > 0 { @@ -17524,93 +22763,117 @@ func (s *RestoreObjectInput) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *RestoreObjectInput) SetBucket(v string) *RestoreObjectInput { - s.Bucket = &v - return s -} - -// SetKey sets the Key field's value. -func (s *RestoreObjectInput) SetKey(v string) *RestoreObjectInput { - s.Key = &v +// SetExpression sets the Expression field's value. +func (s *SelectParameters) SetExpression(v string) *SelectParameters { + s.Expression = &v return s } -// SetRequestPayer sets the RequestPayer field's value. -func (s *RestoreObjectInput) SetRequestPayer(v string) *RestoreObjectInput { - s.RequestPayer = &v +// SetExpressionType sets the ExpressionType field's value. +func (s *SelectParameters) SetExpressionType(v string) *SelectParameters { + s.ExpressionType = &v return s } -// SetRestoreRequest sets the RestoreRequest field's value. -func (s *RestoreObjectInput) SetRestoreRequest(v *RestoreRequest) *RestoreObjectInput { - s.RestoreRequest = v +// SetInputSerialization sets the InputSerialization field's value. +func (s *SelectParameters) SetInputSerialization(v *InputSerialization) *SelectParameters { + s.InputSerialization = v return s } -// SetVersionId sets the VersionId field's value. -func (s *RestoreObjectInput) SetVersionId(v string) *RestoreObjectInput { - s.VersionId = &v +// SetOutputSerialization sets the OutputSerialization field's value. +func (s *SelectParameters) SetOutputSerialization(v *OutputSerialization) *SelectParameters { + s.OutputSerialization = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectOutput -type RestoreObjectOutput struct { +// Describes the default server-side encryption to apply to new objects in the +// bucket. If Put Object request does not specify any server-side encryption, +// this default encryption will be applied. +type ServerSideEncryptionByDefault struct { _ struct{} `type:"structure"` - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` + // KMS master key ID to use for the default encryption. This parameter is allowed + // if SSEAlgorithm is aws:kms. + KMSMasterKeyID *string `type:"string" sensitive:"true"` + + // Server-side encryption algorithm to use for the default encryption. + // + // SSEAlgorithm is a required field + SSEAlgorithm *string `type:"string" required:"true" enum:"ServerSideEncryption"` } // String returns the string representation -func (s RestoreObjectOutput) String() string { +func (s ServerSideEncryptionByDefault) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RestoreObjectOutput) GoString() string { +func (s ServerSideEncryptionByDefault) GoString() string { return s.String() } -// SetRequestCharged sets the RequestCharged field's value. -func (s *RestoreObjectOutput) SetRequestCharged(v string) *RestoreObjectOutput { - s.RequestCharged = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *ServerSideEncryptionByDefault) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionByDefault"} + if s.SSEAlgorithm == nil { + invalidParams.Add(request.NewErrParamRequired("SSEAlgorithm")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKMSMasterKeyID sets the KMSMasterKeyID field's value. +func (s *ServerSideEncryptionByDefault) SetKMSMasterKeyID(v string) *ServerSideEncryptionByDefault { + s.KMSMasterKeyID = &v + return s +} + +// SetSSEAlgorithm sets the SSEAlgorithm field's value. +func (s *ServerSideEncryptionByDefault) SetSSEAlgorithm(v string) *ServerSideEncryptionByDefault { + s.SSEAlgorithm = &v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreRequest -type RestoreRequest struct { +// Container for server-side encryption configuration rules. Currently S3 supports +// one rule only. +type ServerSideEncryptionConfiguration struct { _ struct{} `type:"structure"` - // Lifetime of the active copy in days + // Container for information about a particular server-side encryption configuration + // rule. // - // Days is a required field - Days *int64 `type:"integer" required:"true"` - - // Glacier related prameters pertaining to this job. - GlacierJobParameters *GlacierJobParameters `type:"structure"` + // Rules is a required field + Rules []*ServerSideEncryptionRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` } // String returns the string representation -func (s RestoreRequest) String() string { +func (s ServerSideEncryptionConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RestoreRequest) GoString() string { +func (s ServerSideEncryptionConfiguration) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RestoreRequest) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RestoreRequest"} - if s.Days == nil { - invalidParams.Add(request.NewErrParamRequired("Days")) +func (s *ServerSideEncryptionConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionConfiguration"} + if s.Rules == nil { + invalidParams.Add(request.NewErrParamRequired("Rules")) } - if s.GlacierJobParameters != nil { - if err := s.GlacierJobParameters.Validate(); err != nil { - invalidParams.AddNested("GlacierJobParameters", err.(request.ErrInvalidParams)) + if s.Rules != nil { + for i, v := range s.Rules { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) + } } } @@ -17620,51 +22883,40 @@ func (s *RestoreRequest) Validate() error { return nil } -// SetDays sets the Days field's value. -func (s *RestoreRequest) SetDays(v int64) *RestoreRequest { - s.Days = &v - return s -} - -// SetGlacierJobParameters sets the GlacierJobParameters field's value. -func (s *RestoreRequest) SetGlacierJobParameters(v *GlacierJobParameters) *RestoreRequest { - s.GlacierJobParameters = v +// SetRules sets the Rules field's value. +func (s *ServerSideEncryptionConfiguration) SetRules(v []*ServerSideEncryptionRule) *ServerSideEncryptionConfiguration { + s.Rules = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RoutingRule -type RoutingRule struct { +// Container for information about a particular server-side encryption configuration +// rule. +type ServerSideEncryptionRule struct { _ struct{} `type:"structure"` - // A container for describing a condition that must be met for the specified - // redirect to apply. For example, 1. If request is for pages in the /docs folder, - // redirect to the /documents folder. 2. If request results in HTTP error 4xx, - // redirect request to another host where you might process the error. - Condition *Condition `type:"structure"` - - // Container for redirect information. You can redirect requests to another - // host, to another page, or with another protocol. In the event of an error, - // you can can specify a different error code to return. - // - // Redirect is a required field - Redirect *Redirect `type:"structure" required:"true"` + // Describes the default server-side encryption to apply to new objects in the + // bucket. If Put Object request does not specify any server-side encryption, + // this default encryption will be applied. + ApplyServerSideEncryptionByDefault *ServerSideEncryptionByDefault `type:"structure"` } // String returns the string representation -func (s RoutingRule) String() string { +func (s ServerSideEncryptionRule) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RoutingRule) GoString() string { +func (s ServerSideEncryptionRule) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RoutingRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RoutingRule"} - if s.Redirect == nil { - invalidParams.Add(request.NewErrParamRequired("Redirect")) +func (s *ServerSideEncryptionRule) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionRule"} + if s.ApplyServerSideEncryptionByDefault != nil { + if err := s.ApplyServerSideEncryptionByDefault.Validate(); err != nil { + invalidParams.AddNested("ApplyServerSideEncryptionByDefault", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -17673,75 +22925,78 @@ func (s *RoutingRule) Validate() error { return nil } -// SetCondition sets the Condition field's value. -func (s *RoutingRule) SetCondition(v *Condition) *RoutingRule { - s.Condition = v - return s -} - -// SetRedirect sets the Redirect field's value. -func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { - s.Redirect = v +// SetApplyServerSideEncryptionByDefault sets the ApplyServerSideEncryptionByDefault field's value. +func (s *ServerSideEncryptionRule) SetApplyServerSideEncryptionByDefault(v *ServerSideEncryptionByDefault) *ServerSideEncryptionRule { + s.ApplyServerSideEncryptionByDefault = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Rule -type Rule struct { +// A container for filters that define which source objects should be replicated. +type SourceSelectionCriteria struct { _ struct{} `type:"structure"` - // Specifies the days since the initiation of an Incomplete Multipart Upload - // that Lifecycle will wait before permanently removing all parts of the upload. - AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` + // A container for filter information for the selection of S3 objects encrypted + // with AWS KMS. If you include SourceSelectionCriteria in the replication configuration, + // this element is required. + SseKmsEncryptedObjects *SseKmsEncryptedObjects `type:"structure"` +} - Expiration *LifecycleExpiration `type:"structure"` +// String returns the string representation +func (s SourceSelectionCriteria) String() string { + return awsutil.Prettify(s) +} - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` +// GoString returns the string representation +func (s SourceSelectionCriteria) GoString() string { + return s.String() +} - // Specifies when noncurrent object versions expire. Upon expiration, Amazon - // S3 permanently deletes the noncurrent object versions. You set this lifecycle - // configuration action on a bucket that has versioning enabled (or suspended) - // to request that Amazon S3 delete noncurrent object versions at a specific - // period in the object's lifetime. - NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *SourceSelectionCriteria) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SourceSelectionCriteria"} + if s.SseKmsEncryptedObjects != nil { + if err := s.SseKmsEncryptedObjects.Validate(); err != nil { + invalidParams.AddNested("SseKmsEncryptedObjects", err.(request.ErrInvalidParams)) + } + } - // Container for the transition rule that describes when noncurrent objects - // transition to the STANDARD_IA or GLACIER storage class. If your bucket is - // versioning-enabled (or versioning is suspended), you can set this action - // to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA - // or GLACIER storage class at a specific period in the object's lifetime. - NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Prefix identifying one or more objects to which the rule applies. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` +// SetSseKmsEncryptedObjects sets the SseKmsEncryptedObjects field's value. +func (s *SourceSelectionCriteria) SetSseKmsEncryptedObjects(v *SseKmsEncryptedObjects) *SourceSelectionCriteria { + s.SseKmsEncryptedObjects = v + return s +} - // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule - // is not currently being applied. +// A container for filter information for the selection of S3 objects encrypted +// with AWS KMS. +type SseKmsEncryptedObjects struct { + _ struct{} `type:"structure"` + + // If the status is not Enabled, replication for S3 objects encrypted with AWS + // KMS is disabled. // // Status is a required field - Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - - Transition *Transition `type:"structure"` + Status *string `type:"string" required:"true" enum:"SseKmsEncryptedObjectsStatus"` } // String returns the string representation -func (s Rule) String() string { +func (s SseKmsEncryptedObjects) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Rule) GoString() string { +func (s SseKmsEncryptedObjects) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Rule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Rule"} - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } +func (s *SseKmsEncryptedObjects) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SseKmsEncryptedObjects"} if s.Status == nil { invalidParams.Add(request.NewErrParamRequired("Status")) } @@ -17752,55 +23007,93 @@ func (s *Rule) Validate() error { return nil } -// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. -func (s *Rule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *Rule { - s.AbortIncompleteMultipartUpload = v +// SetStatus sets the Status field's value. +func (s *SseKmsEncryptedObjects) SetStatus(v string) *SseKmsEncryptedObjects { + s.Status = &v return s } -// SetExpiration sets the Expiration field's value. -func (s *Rule) SetExpiration(v *LifecycleExpiration) *Rule { - s.Expiration = v - return s +type Stats struct { + _ struct{} `type:"structure"` + + // The total number of uncompressed object bytes processed. + BytesProcessed *int64 `type:"long"` + + // The total number of bytes of records payload data returned. + BytesReturned *int64 `type:"long"` + + // The total number of object bytes scanned. + BytesScanned *int64 `type:"long"` } -// SetID sets the ID field's value. -func (s *Rule) SetID(v string) *Rule { - s.ID = &v - return s +// String returns the string representation +func (s Stats) String() string { + return awsutil.Prettify(s) } -// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. -func (s *Rule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *Rule { - s.NoncurrentVersionExpiration = v - return s +// GoString returns the string representation +func (s Stats) GoString() string { + return s.String() } -// SetNoncurrentVersionTransition sets the NoncurrentVersionTransition field's value. -func (s *Rule) SetNoncurrentVersionTransition(v *NoncurrentVersionTransition) *Rule { - s.NoncurrentVersionTransition = v +// SetBytesProcessed sets the BytesProcessed field's value. +func (s *Stats) SetBytesProcessed(v int64) *Stats { + s.BytesProcessed = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *Rule) SetPrefix(v string) *Rule { - s.Prefix = &v +// SetBytesReturned sets the BytesReturned field's value. +func (s *Stats) SetBytesReturned(v int64) *Stats { + s.BytesReturned = &v return s } -// SetStatus sets the Status field's value. -func (s *Rule) SetStatus(v string) *Rule { - s.Status = &v +// SetBytesScanned sets the BytesScanned field's value. +func (s *Stats) SetBytesScanned(v int64) *Stats { + s.BytesScanned = &v return s } -// SetTransition sets the Transition field's value. -func (s *Rule) SetTransition(v *Transition) *Rule { - s.Transition = v +type StatsEvent struct { + _ struct{} `locationName:"StatsEvent" type:"structure" payload:"Details"` + + // The Stats event details. + Details *Stats `locationName:"Details" type:"structure"` +} + +// String returns the string representation +func (s StatsEvent) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StatsEvent) GoString() string { + return s.String() +} + +// SetDetails sets the Details field's value. +func (s *StatsEvent) SetDetails(v *Stats) *StatsEvent { + s.Details = v return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysis +// The StatsEvent is and event in the SelectObjectContentEventStream group of events. +func (s *StatsEvent) eventSelectObjectContentEventStream() {} + +// UnmarshalEvent unmarshals the EventStream Message into the StatsEvent value. +// This method is only used internally within the SDK's EventStream handling. +func (s *StatsEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + if err := payloadUnmarshaler.UnmarshalPayload( + bytes.NewReader(msg.Payload), s, + ); err != nil { + return err + } + return nil +} + type StorageClassAnalysis struct { _ struct{} `type:"structure"` @@ -17840,7 +23133,6 @@ func (s *StorageClassAnalysis) SetDataExport(v *StorageClassAnalysisDataExport) return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysisDataExport type StorageClassAnalysisDataExport struct { _ struct{} `type:"structure"` @@ -17898,7 +23190,6 @@ func (s *StorageClassAnalysisDataExport) SetOutputSchemaVersion(v string) *Stora return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tag type Tag struct { _ struct{} `type:"structure"` @@ -17954,7 +23245,6 @@ func (s *Tag) SetValue(v string) *Tag { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tagging type Tagging struct { _ struct{} `type:"structure"` @@ -18001,11 +23291,10 @@ func (s *Tagging) SetTagSet(v []*Tag) *Tagging { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TargetGrant type TargetGrant struct { _ struct{} `type:"structure"` - Grantee *Grantee `type:"structure"` + Grantee *Grantee `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` // Logging permissions assigned to the Grantee for the bucket. Permission *string `type:"string" enum:"BucketLogsPermission"` @@ -18048,25 +23337,26 @@ func (s *TargetGrant) SetPermission(v string) *TargetGrant { return s } -// Container for specifying the configuration when you want Amazon S3 to publish -// events to an Amazon Simple Notification Service (Amazon SNS) topic. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfiguration +// A container for specifying the configuration for publication of messages +// to an Amazon Simple Notification Service (Amazon SNS) topic.when Amazon S3 +// detects specified events. type TopicConfiguration struct { _ struct{} `type:"structure"` // Events is a required field Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // A container for object key name filtering rules. For information about key + // name filtering, see Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) + // in the Amazon Simple Storage Service Developer Guide. Filter *NotificationConfigurationFilter `type:"structure"` - // Optional unique identifier for configurations in a notification configuration. + // An optional unique identifier for configurations in a notification configuration. // If you don't provide one, Amazon S3 will assign an ID. Id *string `type:"string"` - // Amazon SNS topic ARN to which Amazon S3 will publish a message when it detects - // events of specified type. + // The Amazon Resource Name (ARN) of the Amazon SNS topic to which Amazon S3 + // will publish a message when it detects events of the specified type. // // TopicArn is a required field TopicArn *string `locationName:"Topic" type:"string" required:"true"` @@ -18122,16 +23412,17 @@ func (s *TopicConfiguration) SetTopicArn(v string) *TopicConfiguration { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfigurationDeprecated type TopicConfigurationDeprecated struct { _ struct{} `type:"structure"` // Bucket event for which to send notifications. + // + // Deprecated: Event has been deprecated Event *string `deprecated:"true" type:"string" enum:"Event"` Events []*string `locationName:"Event" type:"list" flattened:"true"` - // Optional unique identifier for configurations in a notification configuration. + // An optional unique identifier for configurations in a notification configuration. // If you don't provide one, Amazon S3 will assign an ID. Id *string `type:"string"` @@ -18174,7 +23465,6 @@ func (s *TopicConfigurationDeprecated) SetTopic(v string) *TopicConfigurationDep return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Transition type Transition struct { _ struct{} `type:"structure"` @@ -18218,7 +23508,6 @@ func (s *Transition) SetStorageClass(v string) *Transition { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyRequest type UploadPartCopyInput struct { _ struct{} `type:"structure"` @@ -18235,14 +23524,14 @@ type UploadPartCopyInput struct { CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` + CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp"` // Copies the object if its entity tag (ETag) is different than the specified // ETag. CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` + CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp"` // The range of bytes to copy from the source object. The range value must use // the form bytes=first-last, where the first and last are the zero-based byte @@ -18257,7 +23546,7 @@ type UploadPartCopyInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt // the source object. The encryption key provided in this header must be one // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` + CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string" sensitive:"true"` // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. // Amazon S3 uses this header for a message integrity check to ensure the encryption @@ -18288,7 +23577,7 @@ type UploadPartCopyInput struct { // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm // header. This must be the same encryption key specified in the initiate multipart // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. // Amazon S3 uses this header for a message integrity check to ensure the encryption @@ -18317,6 +23606,9 @@ func (s *UploadPartCopyInput) Validate() error { if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.CopySource == nil { invalidParams.Add(request.NewErrParamRequired("CopySource")) } @@ -18345,6 +23637,13 @@ func (s *UploadPartCopyInput) SetBucket(v string) *UploadPartCopyInput { return s } +func (s *UploadPartCopyInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetCopySource sets the CopySource field's value. func (s *UploadPartCopyInput) SetCopySource(v string) *UploadPartCopyInput { s.CopySource = &v @@ -18393,6 +23692,13 @@ func (s *UploadPartCopyInput) SetCopySourceSSECustomerKey(v string) *UploadPartC return s } +func (s *UploadPartCopyInput) getCopySourceSSECustomerKey() (v string) { + if s.CopySourceSSECustomerKey == nil { + return v + } + return *s.CopySourceSSECustomerKey +} + // SetCopySourceSSECustomerKeyMD5 sets the CopySourceSSECustomerKeyMD5 field's value. func (s *UploadPartCopyInput) SetCopySourceSSECustomerKeyMD5(v string) *UploadPartCopyInput { s.CopySourceSSECustomerKeyMD5 = &v @@ -18429,6 +23735,13 @@ func (s *UploadPartCopyInput) SetSSECustomerKey(v string) *UploadPartCopyInput { return s } +func (s *UploadPartCopyInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey +} + // SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. func (s *UploadPartCopyInput) SetSSECustomerKeyMD5(v string) *UploadPartCopyInput { s.SSECustomerKeyMD5 = &v @@ -18441,7 +23754,6 @@ func (s *UploadPartCopyInput) SetUploadId(v string) *UploadPartCopyInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyOutput type UploadPartCopyOutput struct { _ struct{} `type:"structure" payload:"CopyPartResult"` @@ -18467,7 +23779,7 @@ type UploadPartCopyOutput struct { // If present, specifies the ID of the AWS Key Management Service (KMS) master // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` // The Server-side encryption algorithm used when storing this object in S3 // (e.g., AES256, aws:kms). @@ -18526,7 +23838,6 @@ func (s *UploadPartCopyOutput) SetServerSideEncryption(v string) *UploadPartCopy return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartRequest type UploadPartInput struct { _ struct{} `type:"structure" payload:"Body"` @@ -18542,6 +23853,9 @@ type UploadPartInput struct { // body cannot be determined automatically. ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` + // The base64-encoded 128-bit MD5 digest of the part data. + ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` + // Object key for which the multipart upload was initiated. // // Key is a required field @@ -18568,7 +23882,7 @@ type UploadPartInput struct { // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm // header. This must be the same encryption key specified in the initiate multipart // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` + SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. // Amazon S3 uses this header for a message integrity check to ensure the encryption @@ -18597,6 +23911,9 @@ func (s *UploadPartInput) Validate() error { if s.Bucket == nil { invalidParams.Add(request.NewErrParamRequired("Bucket")) } + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } if s.Key == nil { invalidParams.Add(request.NewErrParamRequired("Key")) } @@ -18628,12 +23945,25 @@ func (s *UploadPartInput) SetBucket(v string) *UploadPartInput { return s } +func (s *UploadPartInput) getBucket() (v string) { + if s.Bucket == nil { + return v + } + return *s.Bucket +} + // SetContentLength sets the ContentLength field's value. func (s *UploadPartInput) SetContentLength(v int64) *UploadPartInput { s.ContentLength = &v return s } +// SetContentMD5 sets the ContentMD5 field's value. +func (s *UploadPartInput) SetContentMD5(v string) *UploadPartInput { + s.ContentMD5 = &v + return s +} + // SetKey sets the Key field's value. func (s *UploadPartInput) SetKey(v string) *UploadPartInput { s.Key = &v @@ -18664,6 +23994,13 @@ func (s *UploadPartInput) SetSSECustomerKey(v string) *UploadPartInput { return s } +func (s *UploadPartInput) getSSECustomerKey() (v string) { + if s.SSECustomerKey == nil { + return v + } + return *s.SSECustomerKey +} + // SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. func (s *UploadPartInput) SetSSECustomerKeyMD5(v string) *UploadPartInput { s.SSECustomerKeyMD5 = &v @@ -18676,7 +24013,6 @@ func (s *UploadPartInput) SetUploadId(v string) *UploadPartInput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartOutput type UploadPartOutput struct { _ struct{} `type:"structure"` @@ -18699,7 +24035,7 @@ type UploadPartOutput struct { // If present, specifies the ID of the AWS Key Management Service (KMS) master // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` // The Server-side encryption algorithm used when storing this object in S3 // (e.g., AES256, aws:kms). @@ -18752,7 +24088,6 @@ func (s *UploadPartOutput) SetServerSideEncryption(v string) *UploadPartOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/VersioningConfiguration type VersioningConfiguration struct { _ struct{} `type:"structure"` @@ -18787,7 +24122,6 @@ func (s *VersioningConfiguration) SetStatus(v string) *VersioningConfiguration { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/WebsiteConfiguration type WebsiteConfiguration struct { _ struct{} `type:"structure"` @@ -18950,6 +24284,25 @@ const ( BucketVersioningStatusSuspended = "Suspended" ) +const ( + // CompressionTypeNone is a CompressionType enum value + CompressionTypeNone = "NONE" + + // CompressionTypeGzip is a CompressionType enum value + CompressionTypeGzip = "GZIP" + + // CompressionTypeBzip2 is a CompressionType enum value + CompressionTypeBzip2 = "BZIP2" +) + +const ( + // DeleteMarkerReplicationStatusEnabled is a DeleteMarkerReplicationStatus enum value + DeleteMarkerReplicationStatusEnabled = "Enabled" + + // DeleteMarkerReplicationStatusDisabled is a DeleteMarkerReplicationStatus enum value + DeleteMarkerReplicationStatusDisabled = "Disabled" +) + // Requests Amazon S3 to encode the object keys in the response and specifies // the encoding method to use. An object key may contain any Unicode character; // however, XML 1.0 parser cannot parse some characters, such as characters @@ -18961,7 +24314,7 @@ const ( EncodingTypeUrl = "url" ) -// Bucket event for which to send notifications. +// The bucket event for which to send notifications. const ( // EventS3ReducedRedundancyLostObject is a Event enum value EventS3ReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject" @@ -18989,6 +24342,12 @@ const ( // EventS3ObjectRemovedDeleteMarkerCreated is a Event enum value EventS3ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated" + + // EventS3ObjectRestorePost is a Event enum value + EventS3ObjectRestorePost = "s3:ObjectRestore:Post" + + // EventS3ObjectRestoreCompleted is a Event enum value + EventS3ObjectRestoreCompleted = "s3:ObjectRestore:Completed" ) const ( @@ -18999,6 +24358,22 @@ const ( ExpirationStatusDisabled = "Disabled" ) +const ( + // ExpressionTypeSql is a ExpressionType enum value + ExpressionTypeSql = "SQL" +) + +const ( + // FileHeaderInfoUse is a FileHeaderInfo enum value + FileHeaderInfoUse = "USE" + + // FileHeaderInfoIgnore is a FileHeaderInfo enum value + FileHeaderInfoIgnore = "IGNORE" + + // FileHeaderInfoNone is a FileHeaderInfo enum value + FileHeaderInfoNone = "NONE" +) + const ( // FilterRuleNamePrefix is a FilterRuleName enum value FilterRuleNamePrefix = "prefix" @@ -19010,6 +24385,12 @@ const ( const ( // InventoryFormatCsv is a InventoryFormat enum value InventoryFormatCsv = "CSV" + + // InventoryFormatOrc is a InventoryFormat enum value + InventoryFormatOrc = "ORC" + + // InventoryFormatParquet is a InventoryFormat enum value + InventoryFormatParquet = "Parquet" ) const ( @@ -19046,6 +24427,26 @@ const ( // InventoryOptionalFieldReplicationStatus is a InventoryOptionalField enum value InventoryOptionalFieldReplicationStatus = "ReplicationStatus" + + // InventoryOptionalFieldEncryptionStatus is a InventoryOptionalField enum value + InventoryOptionalFieldEncryptionStatus = "EncryptionStatus" + + // InventoryOptionalFieldObjectLockRetainUntilDate is a InventoryOptionalField enum value + InventoryOptionalFieldObjectLockRetainUntilDate = "ObjectLockRetainUntilDate" + + // InventoryOptionalFieldObjectLockMode is a InventoryOptionalField enum value + InventoryOptionalFieldObjectLockMode = "ObjectLockMode" + + // InventoryOptionalFieldObjectLockLegalHoldStatus is a InventoryOptionalField enum value + InventoryOptionalFieldObjectLockLegalHoldStatus = "ObjectLockLegalHoldStatus" +) + +const ( + // JSONTypeDocument is a JSONType enum value + JSONTypeDocument = "DOCUMENT" + + // JSONTypeLines is a JSONType enum value + JSONTypeLines = "LINES" ) const ( @@ -19095,6 +24496,35 @@ const ( ObjectCannedACLBucketOwnerFullControl = "bucket-owner-full-control" ) +const ( + // ObjectLockEnabledEnabled is a ObjectLockEnabled enum value + ObjectLockEnabledEnabled = "Enabled" +) + +const ( + // ObjectLockLegalHoldStatusOn is a ObjectLockLegalHoldStatus enum value + ObjectLockLegalHoldStatusOn = "ON" + + // ObjectLockLegalHoldStatusOff is a ObjectLockLegalHoldStatus enum value + ObjectLockLegalHoldStatusOff = "OFF" +) + +const ( + // ObjectLockModeGovernance is a ObjectLockMode enum value + ObjectLockModeGovernance = "GOVERNANCE" + + // ObjectLockModeCompliance is a ObjectLockMode enum value + ObjectLockModeCompliance = "COMPLIANCE" +) + +const ( + // ObjectLockRetentionModeGovernance is a ObjectLockRetentionMode enum value + ObjectLockRetentionModeGovernance = "GOVERNANCE" + + // ObjectLockRetentionModeCompliance is a ObjectLockRetentionMode enum value + ObjectLockRetentionModeCompliance = "COMPLIANCE" +) + const ( // ObjectStorageClassStandard is a ObjectStorageClass enum value ObjectStorageClassStandard = "STANDARD" @@ -19104,6 +24534,15 @@ const ( // ObjectStorageClassGlacier is a ObjectStorageClass enum value ObjectStorageClassGlacier = "GLACIER" + + // ObjectStorageClassStandardIa is a ObjectStorageClass enum value + ObjectStorageClassStandardIa = "STANDARD_IA" + + // ObjectStorageClassOnezoneIa is a ObjectStorageClass enum value + ObjectStorageClassOnezoneIa = "ONEZONE_IA" + + // ObjectStorageClassIntelligentTiering is a ObjectStorageClass enum value + ObjectStorageClassIntelligentTiering = "INTELLIGENT_TIERING" ) const ( @@ -19111,6 +24550,11 @@ const ( ObjectVersionStorageClassStandard = "STANDARD" ) +const ( + // OwnerOverrideDestination is a OwnerOverride enum value + OwnerOverrideDestination = "Destination" +) + const ( // PayerRequester is a Payer enum value PayerRequester = "Requester" @@ -19144,6 +24588,14 @@ const ( ProtocolHttps = "https" ) +const ( + // QuoteFieldsAlways is a QuoteFields enum value + QuoteFieldsAlways = "ALWAYS" + + // QuoteFieldsAsneeded is a QuoteFields enum value + QuoteFieldsAsneeded = "ASNEEDED" +) + const ( // ReplicationRuleStatusEnabled is a ReplicationRuleStatus enum value ReplicationRuleStatusEnabled = "Enabled" @@ -19182,6 +24634,11 @@ const ( RequestPayerRequester = "requester" ) +const ( + // RestoreRequestTypeSelect is a RestoreRequestType enum value + RestoreRequestTypeSelect = "SELECT" +) + const ( // ServerSideEncryptionAes256 is a ServerSideEncryption enum value ServerSideEncryptionAes256 = "AES256" @@ -19190,6 +24647,14 @@ const ( ServerSideEncryptionAwsKms = "aws:kms" ) +const ( + // SseKmsEncryptedObjectsStatusEnabled is a SseKmsEncryptedObjectsStatus enum value + SseKmsEncryptedObjectsStatusEnabled = "Enabled" + + // SseKmsEncryptedObjectsStatusDisabled is a SseKmsEncryptedObjectsStatus enum value + SseKmsEncryptedObjectsStatusDisabled = "Disabled" +) + const ( // StorageClassStandard is a StorageClass enum value StorageClassStandard = "STANDARD" @@ -19199,6 +24664,15 @@ const ( // StorageClassStandardIa is a StorageClass enum value StorageClassStandardIa = "STANDARD_IA" + + // StorageClassOnezoneIa is a StorageClass enum value + StorageClassOnezoneIa = "ONEZONE_IA" + + // StorageClassIntelligentTiering is a StorageClass enum value + StorageClassIntelligentTiering = "INTELLIGENT_TIERING" + + // StorageClassGlacier is a StorageClass enum value + StorageClassGlacier = "GLACIER" ) const ( @@ -19231,6 +24705,12 @@ const ( // TransitionStorageClassStandardIa is a TransitionStorageClass enum value TransitionStorageClassStandardIa = "STANDARD_IA" + + // TransitionStorageClassOnezoneIa is a TransitionStorageClass enum value + TransitionStorageClassOnezoneIa = "ONEZONE_IA" + + // TransitionStorageClassIntelligentTiering is a TransitionStorageClass enum value + TransitionStorageClassIntelligentTiering = "INTELLIGENT_TIERING" ) const ( diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go new file mode 100644 index 000000000..5c8ce5cc8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go @@ -0,0 +1,249 @@ +package s3 + +import ( + "bytes" + "crypto/md5" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "fmt" + "hash" + "io" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/sdkio" +) + +const ( + contentMD5Header = "Content-Md5" + contentSha256Header = "X-Amz-Content-Sha256" + amzTeHeader = "X-Amz-Te" + amzTxEncodingHeader = "X-Amz-Transfer-Encoding" + + appendMD5TxEncoding = "append-md5" +) + +// contentMD5 computes and sets the HTTP Content-MD5 header for requests that +// require it. +func contentMD5(r *request.Request) { + h := md5.New() + + if !aws.IsReaderSeekable(r.Body) { + if r.Config.Logger != nil { + r.Config.Logger.Log(fmt.Sprintf( + "Unable to compute Content-MD5 for unseekable body, S3.%s", + r.Operation.Name)) + } + return + } + + if _, err := copySeekableBody(h, r.Body); err != nil { + r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err) + return + } + + // encode the md5 checksum in base64 and set the request header. + v := base64.StdEncoding.EncodeToString(h.Sum(nil)) + r.HTTPRequest.Header.Set(contentMD5Header, v) +} + +// computeBodyHashes will add Content MD5 and Content Sha256 hashes to the +// request. If the body is not seekable or S3DisableContentMD5Validation set +// this handler will be ignored. +func computeBodyHashes(r *request.Request) { + if aws.BoolValue(r.Config.S3DisableContentMD5Validation) { + return + } + if r.IsPresigned() { + return + } + if r.Error != nil || !aws.IsReaderSeekable(r.Body) { + return + } + + var md5Hash, sha256Hash hash.Hash + hashers := make([]io.Writer, 0, 2) + + // Determine upfront which hashes can be set without overriding user + // provide header data. + if v := r.HTTPRequest.Header.Get(contentMD5Header); len(v) == 0 { + md5Hash = md5.New() + hashers = append(hashers, md5Hash) + } + + if v := r.HTTPRequest.Header.Get(contentSha256Header); len(v) == 0 { + sha256Hash = sha256.New() + hashers = append(hashers, sha256Hash) + } + + // Create the destination writer based on the hashes that are not already + // provided by the user. + var dst io.Writer + switch len(hashers) { + case 0: + return + case 1: + dst = hashers[0] + default: + dst = io.MultiWriter(hashers...) + } + + if _, err := copySeekableBody(dst, r.Body); err != nil { + r.Error = awserr.New("BodyHashError", "failed to compute body hashes", err) + return + } + + // For the hashes created, set the associated headers that the user did not + // already provide. + if md5Hash != nil { + sum := make([]byte, md5.Size) + encoded := make([]byte, md5Base64EncLen) + + base64.StdEncoding.Encode(encoded, md5Hash.Sum(sum[0:0])) + r.HTTPRequest.Header[contentMD5Header] = []string{string(encoded)} + } + + if sha256Hash != nil { + encoded := make([]byte, sha256HexEncLen) + sum := make([]byte, sha256.Size) + + hex.Encode(encoded, sha256Hash.Sum(sum[0:0])) + r.HTTPRequest.Header[contentSha256Header] = []string{string(encoded)} + } +} + +const ( + md5Base64EncLen = (md5.Size + 2) / 3 * 4 // base64.StdEncoding.EncodedLen + sha256HexEncLen = sha256.Size * 2 // hex.EncodedLen +) + +func copySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { + curPos, err := src.Seek(0, sdkio.SeekCurrent) + if err != nil { + return 0, err + } + + // hash the body. seek back to the first position after reading to reset + // the body for transmission. copy errors may be assumed to be from the + // body. + n, err := io.Copy(dst, src) + if err != nil { + return n, err + } + + _, err = src.Seek(curPos, sdkio.SeekStart) + if err != nil { + return n, err + } + + return n, nil +} + +// Adds the x-amz-te: append_md5 header to the request. This requests the service +// responds with a trailing MD5 checksum. +// +// Will not ask for append MD5 if disabled, the request is presigned or, +// or the API operation does not support content MD5 validation. +func askForTxEncodingAppendMD5(r *request.Request) { + if aws.BoolValue(r.Config.S3DisableContentMD5Validation) { + return + } + if r.IsPresigned() { + return + } + r.HTTPRequest.Header.Set(amzTeHeader, appendMD5TxEncoding) +} + +func useMD5ValidationReader(r *request.Request) { + if r.Error != nil { + return + } + + if v := r.HTTPResponse.Header.Get(amzTxEncodingHeader); v != appendMD5TxEncoding { + return + } + + var bodyReader *io.ReadCloser + var contentLen int64 + switch tv := r.Data.(type) { + case *GetObjectOutput: + bodyReader = &tv.Body + contentLen = aws.Int64Value(tv.ContentLength) + // Update ContentLength hiden the trailing MD5 checksum. + tv.ContentLength = aws.Int64(contentLen - md5.Size) + tv.ContentRange = aws.String(r.HTTPResponse.Header.Get("X-Amz-Content-Range")) + default: + r.Error = awserr.New("ChecksumValidationError", + fmt.Sprintf("%s: %s header received on unsupported API, %s", + amzTxEncodingHeader, appendMD5TxEncoding, r.Operation.Name, + ), nil) + return + } + + if contentLen < md5.Size { + r.Error = awserr.New("ChecksumValidationError", + fmt.Sprintf("invalid Content-Length %d for %s %s", + contentLen, appendMD5TxEncoding, amzTxEncodingHeader, + ), nil) + return + } + + // Wrap and swap the response body reader with the validation reader. + *bodyReader = newMD5ValidationReader(*bodyReader, contentLen-md5.Size) +} + +type md5ValidationReader struct { + rawReader io.ReadCloser + payload io.Reader + hash hash.Hash + + payloadLen int64 + read int64 +} + +func newMD5ValidationReader(reader io.ReadCloser, payloadLen int64) *md5ValidationReader { + h := md5.New() + return &md5ValidationReader{ + rawReader: reader, + payload: io.TeeReader(&io.LimitedReader{R: reader, N: payloadLen}, h), + hash: h, + payloadLen: payloadLen, + } +} + +func (v *md5ValidationReader) Read(p []byte) (n int, err error) { + n, err = v.payload.Read(p) + if err != nil && err != io.EOF { + return n, err + } + + v.read += int64(n) + + if err == io.EOF { + if v.read != v.payloadLen { + return n, io.ErrUnexpectedEOF + } + expectSum := make([]byte, md5.Size) + actualSum := make([]byte, md5.Size) + if _, sumReadErr := io.ReadFull(v.rawReader, expectSum); sumReadErr != nil { + return n, sumReadErr + } + actualSum = v.hash.Sum(actualSum[0:0]) + if !bytes.Equal(expectSum, actualSum) { + return n, awserr.New("InvalidChecksum", + fmt.Sprintf("expected MD5 checksum %s, got %s", + hex.EncodeToString(expectSum), + hex.EncodeToString(actualSum), + ), + nil) + } + } + + return n, err +} + +func (v *md5ValidationReader) Close() error { + return v.rawReader.Close() +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go b/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go deleted file mode 100644 index 9fc5df94d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go +++ /dev/null @@ -1,36 +0,0 @@ -package s3 - -import ( - "crypto/md5" - "encoding/base64" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// contentMD5 computes and sets the HTTP Content-MD5 header for requests that -// require it. -func contentMD5(r *request.Request) { - h := md5.New() - - // hash the body. seek back to the first position after reading to reset - // the body for transmission. copy errors may be assumed to be from the - // body. - _, err := io.Copy(h, r.Body) - if err != nil { - r.Error = awserr.New("ContentMD5", "failed to read body", err) - return - } - _, err = r.Body.Seek(0, 0) - if err != nil { - r.Error = awserr.New("ContentMD5", "failed to seek body", err) - return - } - - // encode the md5 checksum in base64 and set the request header. - sum := h.Sum(nil) - sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum))) - base64.StdEncoding.Encode(sum64, sum) - r.HTTPRequest.Header.Set("Content-MD5", string(sum64)) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go index 846334723..95f245636 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go @@ -3,6 +3,7 @@ package s3 import ( "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/s3err" ) func init() { @@ -21,6 +22,7 @@ func defaultInitClientFn(c *client.Client) { // S3 uses custom error unmarshaling logic c.Handlers.UnmarshalError.Clear() c.Handlers.UnmarshalError.PushBack(unmarshalError) + c.Handlers.UnmarshalError.PushBackNamed(s3err.RequestFailureWrapperHandler()) } func defaultInitRequestFn(r *request.Request) { @@ -31,6 +33,7 @@ func defaultInitRequestFn(r *request.Request) { switch r.Operation.Name { case opPutBucketCors, opPutBucketLifecycle, opPutBucketPolicy, opPutBucketTagging, opDeleteObjects, opPutBucketLifecycleConfiguration, + opPutObjectLegalHold, opPutObjectRetention, opPutObjectLockConfiguration, opPutBucketReplication: // These S3 operations require Content-MD5 to be set r.Handlers.Build.PushBack(contentMD5) @@ -42,5 +45,30 @@ func defaultInitRequestFn(r *request.Request) { r.Handlers.Validate.PushFront(populateLocationConstraint) case opCopyObject, opUploadPartCopy, opCompleteMultipartUpload: r.Handlers.Unmarshal.PushFront(copyMultipartStatusOKUnmarhsalError) + r.Handlers.Unmarshal.PushBackNamed(s3err.RequestFailureWrapperHandler()) + case opPutObject, opUploadPart: + r.Handlers.Build.PushBack(computeBodyHashes) + // Disabled until #1837 root issue is resolved. + // case opGetObject: + // r.Handlers.Build.PushBack(askForTxEncodingAppendMD5) + // r.Handlers.Unmarshal.PushBack(useMD5ValidationReader) } } + +// bucketGetter is an accessor interface to grab the "Bucket" field from +// an S3 type. +type bucketGetter interface { + getBucket() string +} + +// sseCustomerKeyGetter is an accessor interface to grab the "SSECustomerKey" +// field from an S3 type. +type sseCustomerKeyGetter interface { + getSSECustomerKey() string +} + +// copySourceSSECustomerKeyGetter is an accessor interface to grab the +// "CopySourceSSECustomerKey" field from an S3 type. +type copySourceSSECustomerKeyGetter interface { + getCopySourceSSECustomerKey() string +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go index f045fd0db..0def02255 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go @@ -10,69 +10,17 @@ // // Using the Client // -// To use the client for Amazon Simple Storage Service you will first need -// to create a new instance of it. +// To contact Amazon Simple Storage Service with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. // -// When creating a client for an AWS service you'll first need to have a Session -// already created. The Session provides configuration that can be shared -// between multiple service clients. Additional configuration can be applied to -// the Session and service's client when they are constructed. The aws package's -// Config type contains several fields such as Region for the AWS Region the -// client should make API requests too. The optional Config value can be provided -// as the variadic argument for Sessions and client creation. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// // Create a session to share configuration, and load external configuration. -// sess := session.Must(session.NewSession()) -// -// // Create the service's client with the session. -// svc := s3.New(sess) -// -// See the SDK's documentation for more information on how to use service clients. +// See the SDK's documentation for more information on how to use the SDK. // https://docs.aws.amazon.com/sdk-for-go/api/ // -// See aws package's Config type for more information on configuration options. +// See aws.Config documentation for more information on configuring SDK clients. // https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config // // See the Amazon Simple Storage Service client S3 for more -// information on creating the service's client. +// information on creating client for this service. // https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#New -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. -// -// The API method will document which error codes the service can be returned -// by the operation if the service models the API operation's errors. These -// errors will also be available as const strings prefixed with "ErrCode". -// -// result, err := svc.AbortMultipartUpload(params) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == { -// // Specific error code handling -// } -// return err -// } -// -// fmt.Println("AbortMultipartUpload result:") -// fmt.Println(result) -// -// Using the Client with Context -// -// The service's client also provides methods to make API requests with a Context -// value. This allows you to control the timeout, and cancellation of pending -// requests. These methods also take request Option as variadic parameter to apply -// additional configuration to the API request. -// -// ctx := context.Background() -// -// result, err := svc.AbortMultipartUploadWithContext(ctx, params) -// -// See the request package documentation for more information on using Context pattern -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ package s3 diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go index b794a63ba..39b912c26 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go @@ -35,7 +35,7 @@ // // The s3manager package's Downloader provides concurrently downloading of Objects // from S3. The Downloader will write S3 Object content with an io.WriterAt. -// Once the Downloader instance is created you can call Upload concurrently from +// Once the Downloader instance is created you can call Download concurrently from // multiple goroutines safely. // // // The session the S3 Downloader will use @@ -56,7 +56,7 @@ // Key: aws.String(myString), // }) // if err != nil { -// return fmt.Errorf("failed to upload file, %v", err) +// return fmt.Errorf("failed to download file, %v", err) // } // fmt.Printf("file downloaded, %d bytes\n", n) // diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go b/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go index ec3ffe448..a7fbc2de2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go @@ -8,7 +8,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -113,15 +112,9 @@ func updateEndpointForAccelerate(r *request.Request) { // Attempts to retrieve the bucket name from the request input parameters. // If no bucket is found, or the field is empty "", false will be returned. func bucketNameFromReqParams(params interface{}) (string, bool) { - b, _ := awsutil.ValuesAtPath(params, "Bucket") - if len(b) == 0 { - return "", false - } - - if bucket, ok := b[0].(*string); ok { - if bucketStr := aws.StringValue(bucket); bucketStr != "" { - return bucketStr, true - } + if iface, ok := params.(bucketGetter); ok { + b := iface.getBucket() + return b, len(b) > 0 } return "", false diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go index 614e477d3..d17dcc9da 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go @@ -29,8 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "s3" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. + ServiceName = "s3" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "S3" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the S3 client with a session. @@ -55,6 +56,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg, metadata.ClientInfo{ ServiceName: ServiceName, + ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, @@ -65,12 +67,16 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio } // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Sign.PushBackNamed(v4.BuildNamedHandler(v4.SignRequestHandler.Name, func(s *v4.Signer) { + s.DisableURIPathEscaping = true + })) svc.Handlers.Build.PushBackNamed(restxml.BuildHandler) svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler) svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler) svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler) + svc.Handlers.UnmarshalStream.PushBackNamed(restxml.UnmarshalHandler) + // Run custom client initialization if present if initClient != nil { initClient(svc.Client) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go index 268ea2fb4..8010c4fa1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go @@ -5,17 +5,27 @@ import ( "encoding/base64" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) var errSSERequiresSSL = awserr.New("ConfigError", "cannot send SSE keys over HTTP.", nil) func validateSSERequiresSSL(r *request.Request) { - if r.HTTPRequest.URL.Scheme != "https" { - p, _ := awsutil.ValuesAtPath(r.Params, "SSECustomerKey||CopySourceSSECustomerKey") - if len(p) > 0 { + if r.HTTPRequest.URL.Scheme == "https" { + return + } + + if iface, ok := r.Params.(sseCustomerKeyGetter); ok { + if len(iface.getSSECustomerKey()) > 0 { + r.Error = errSSERequiresSSL + return + } + } + + if iface, ok := r.Params.(copySourceSSECustomerKeyGetter); ok { + if len(iface.getCopySourceSSECustomerKey()) > 0 { r.Error = errSSERequiresSSL + return } } } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go index 5a78fd337..fde3050f9 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go @@ -7,17 +7,22 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/internal/sdkio" ) func copyMultipartStatusOKUnmarhsalError(r *request.Request) { b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { - r.Error = awserr.New("SerializationError", "unable to read response body", err) + r.Error = awserr.NewRequestFailure( + awserr.New("SerializationError", "unable to read response body", err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } body := bytes.NewReader(b) r.HTTPResponse.Body = ioutil.NopCloser(body) - defer body.Seek(0, 0) + defer body.Seek(0, sdkio.SeekStart) if body.Len() == 0 { // If there is no body don't attempt to parse the body. diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go index bcca8627a..12c0612c8 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go @@ -23,22 +23,17 @@ func unmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() defer io.Copy(ioutil.Discard, r.HTTPResponse.Body) - hostID := r.HTTPResponse.Header.Get("X-Amz-Id-2") - // Bucket exists in a different region, and request needs // to be made to the correct region. if r.HTTPResponse.StatusCode == http.StatusMovedPermanently { - r.Error = requestFailure{ - RequestFailure: awserr.NewRequestFailure( - awserr.New("BucketRegionError", - fmt.Sprintf("incorrect region, the bucket is not in '%s' region", - aws.StringValue(r.Config.Region)), - nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ), - hostID: hostID, - } + r.Error = awserr.NewRequestFailure( + awserr.New("BucketRegionError", + fmt.Sprintf("incorrect region, the bucket is not in '%s' region", + aws.StringValue(r.Config.Region)), + nil), + r.HTTPResponse.StatusCode, + r.RequestID, + ) return } @@ -63,14 +58,11 @@ func unmarshalError(r *request.Request) { errMsg = statusText } - r.Error = requestFailure{ - RequestFailure: awserr.NewRequestFailure( - awserr.New(errCode, errMsg, err), - r.HTTPResponse.StatusCode, - r.RequestID, - ), - hostID: hostID, - } + r.Error = awserr.NewRequestFailure( + awserr.New(errCode, errMsg, err), + r.HTTPResponse.StatusCode, + r.RequestID, + ) } // A RequestFailure provides access to the S3 Request ID and Host ID values @@ -83,21 +75,3 @@ type RequestFailure interface { // Host ID is the S3 Host ID needed for debug, and contacting support HostID() string } - -type requestFailure struct { - awserr.RequestFailure - - hostID string -} - -func (r requestFailure) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s", - r.StatusCode(), r.RequestID(), r.hostID) - return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} -func (r requestFailure) String() string { - return r.Error() -} -func (r requestFailure) HostID() string { - return r.hostID -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go index cccfa8c2b..2596c694b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go @@ -11,7 +11,7 @@ import ( // WaitUntilBucketExists uses the Amazon S3 API operation // HeadBucket to wait for a condition to be met before returning. -// If the condition is not meet within the max attempt window an error will +// If the condition is not met within the max attempt window, an error will // be returned. func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { return c.WaitUntilBucketExistsWithContext(aws.BackgroundContext(), input) @@ -72,7 +72,7 @@ func (c *S3) WaitUntilBucketExistsWithContext(ctx aws.Context, input *HeadBucket // WaitUntilBucketNotExists uses the Amazon S3 API operation // HeadBucket to wait for a condition to be met before returning. -// If the condition is not meet within the max attempt window an error will +// If the condition is not met within the max attempt window, an error will // be returned. func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { return c.WaitUntilBucketNotExistsWithContext(aws.BackgroundContext(), input) @@ -118,7 +118,7 @@ func (c *S3) WaitUntilBucketNotExistsWithContext(ctx aws.Context, input *HeadBuc // WaitUntilObjectExists uses the Amazon S3 API operation // HeadObject to wait for a condition to be met before returning. -// If the condition is not meet within the max attempt window an error will +// If the condition is not met within the max attempt window, an error will // be returned. func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { return c.WaitUntilObjectExistsWithContext(aws.BackgroundContext(), input) @@ -169,7 +169,7 @@ func (c *S3) WaitUntilObjectExistsWithContext(ctx aws.Context, input *HeadObject // WaitUntilObjectNotExists uses the Amazon S3 API operation // HeadObject to wait for a condition to be met before returning. -// If the condition is not meet within the max attempt window an error will +// If the condition is not met within the max attempt window, an error will // be returned. func (c *S3) WaitUntilObjectNotExists(input *HeadObjectInput) error { return c.WaitUntilObjectNotExistsWithContext(aws.BackgroundContext(), input) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go index e5c105fed..ee908f916 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -14,19 +14,18 @@ const opAssumeRole = "AssumeRole" // AssumeRoleRequest generates a "aws/request.Request" representing the // client's request for the AssumeRole operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See AssumeRole for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRole method directly -// instead. +// See AssumeRole for more information on using the AssumeRole +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the AssumeRoleRequest method. // req, resp := client.AssumeRoleRequest(params) @@ -36,7 +35,7 @@ const opAssumeRole = "AssumeRole" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) { op := &request.Operation{ Name: opAssumeRole, @@ -89,9 +88,18 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // Scenarios for Temporary Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction) // in the IAM User Guide. // -// The temporary security credentials are valid for the duration that you specified -// when calling AssumeRole, which can be from 900 seconds (15 minutes) to a -// maximum of 3600 seconds (1 hour). The default is 1 hour. +// By default, the temporary security credentials created by AssumeRole last +// for one hour. However, you can use the optional DurationSeconds parameter +// to specify the duration of your session. You can provide a value from 900 +// seconds (15 minutes) up to the maximum session duration setting for the role. +// This setting can have a value from 1 hour to 12 hours. To learn how to view +// the maximum value for your role, see View the Maximum Session Duration Setting +// for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) +// in the IAM User Guide. The maximum session duration limit applies when you +// use the AssumeRole* API operations or the assume-role* CLI operations but +// does not apply when you use those operations to create a console URL. For +// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) +// in the IAM User Guide. // // The temporary security credentials created by AssumeRole can be used to make // API calls to any AWS service with the following exception: you cannot call @@ -122,7 +130,12 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // the user to call AssumeRole on the ARN of the role in the other account. // If the user is in the same account as the role, then you can either attach // a policy to the user (identical to the previous different account user), -// or you can add the user as a principal directly in the role's trust policy +// or you can add the user as a principal directly in the role's trust policy. +// In this case, the trust policy acts as the only resource-based policy in +// IAM, and users in the same account as the role do not need explicit permission +// to assume the role. For more information about trust policies and resource-based +// policies, see IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) +// in the IAM User Guide. // // Using MFA with AssumeRole // @@ -169,7 +182,7 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { req, out := c.AssumeRoleRequest(input) return out, req.Send() @@ -195,19 +208,18 @@ const opAssumeRoleWithSAML = "AssumeRoleWithSAML" // AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the // client's request for the AssumeRoleWithSAML operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See AssumeRoleWithSAML for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRoleWithSAML method directly -// instead. +// See AssumeRoleWithSAML for more information on using the AssumeRoleWithSAML +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the AssumeRoleWithSAMLRequest method. // req, resp := client.AssumeRoleWithSAMLRequest(params) @@ -217,7 +229,7 @@ const opAssumeRoleWithSAML = "AssumeRoleWithSAML" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) { op := &request.Operation{ Name: opAssumeRoleWithSAML, @@ -249,11 +261,20 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re // an access key ID, a secret access key, and a security token. Applications // can use these temporary security credentials to sign calls to AWS services. // -// The temporary security credentials are valid for the duration that you specified -// when calling AssumeRole, or until the time specified in the SAML authentication -// response's SessionNotOnOrAfter value, whichever is shorter. The duration -// can be from 900 seconds (15 minutes) to a maximum of 3600 seconds (1 hour). -// The default is 1 hour. +// By default, the temporary security credentials created by AssumeRoleWithSAML +// last for one hour. However, you can use the optional DurationSeconds parameter +// to specify the duration of your session. Your role session lasts for the +// duration that you specify, or until the time specified in the SAML authentication +// response's SessionNotOnOrAfter value, whichever is shorter. You can provide +// a DurationSeconds value from 900 seconds (15 minutes) up to the maximum session +// duration setting for the role. This setting can have a value from 1 hour +// to 12 hours. To learn how to view the maximum value for your role, see View +// the Maximum Session Duration Setting for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) +// in the IAM User Guide. The maximum session duration limit applies when you +// use the AssumeRole* API operations or the assume-role* CLI operations but +// does not apply when you use those operations to create a console URL. For +// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) +// in the IAM User Guide. // // The temporary security credentials created by AssumeRoleWithSAML can be used // to make API calls to any AWS service with the following exception: you cannot @@ -343,7 +364,7 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { req, out := c.AssumeRoleWithSAMLRequest(input) return out, req.Send() @@ -369,19 +390,18 @@ const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" // AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the // client's request for the AssumeRoleWithWebIdentity operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See AssumeRoleWithWebIdentity for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRoleWithWebIdentity method directly -// instead. +// See AssumeRoleWithWebIdentity for more information on using the AssumeRoleWithWebIdentity +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the AssumeRoleWithWebIdentityRequest method. // req, resp := client.AssumeRoleWithWebIdentityRequest(params) @@ -391,7 +411,7 @@ const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) { op := &request.Operation{ Name: opAssumeRoleWithWebIdentity, @@ -441,9 +461,18 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // key ID, a secret access key, and a security token. Applications can use these // temporary security credentials to sign calls to AWS service APIs. // -// The credentials are valid for the duration that you specified when calling -// AssumeRoleWithWebIdentity, which can be from 900 seconds (15 minutes) to -// a maximum of 3600 seconds (1 hour). The default is 1 hour. +// By default, the temporary security credentials created by AssumeRoleWithWebIdentity +// last for one hour. However, you can use the optional DurationSeconds parameter +// to specify the duration of your session. You can provide a value from 900 +// seconds (15 minutes) up to the maximum session duration setting for the role. +// This setting can have a value from 1 hour to 12 hours. To learn how to view +// the maximum value for your role, see View the Maximum Session Duration Setting +// for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) +// in the IAM User Guide. The maximum session duration limit applies when you +// use the AssumeRole* API operations or the assume-role* CLI operations but +// does not apply when you use those operations to create a console URL. For +// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) +// in the IAM User Guide. // // The temporary security credentials created by AssumeRoleWithWebIdentity can // be used to make API calls to any AWS service with the following exception: @@ -495,7 +524,7 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // the information from these providers to get and use temporary security // credentials. // -// * Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/4617974389850313). +// * Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications). // This article discusses web identity federation and shows an example of // how to use web identity federation to get access to content in Amazon // S3. @@ -546,7 +575,7 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { req, out := c.AssumeRoleWithWebIdentityRequest(input) return out, req.Send() @@ -572,19 +601,18 @@ const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" // DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the // client's request for the DecodeAuthorizationMessage operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See DecodeAuthorizationMessage for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DecodeAuthorizationMessage method directly -// instead. +// See DecodeAuthorizationMessage for more information on using the DecodeAuthorizationMessage +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the DecodeAuthorizationMessageRequest method. // req, resp := client.DecodeAuthorizationMessageRequest(params) @@ -594,7 +622,7 @@ const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) { op := &request.Operation{ Name: opDecodeAuthorizationMessage, @@ -659,7 +687,7 @@ func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessag // invalid. This can happen if the token contains invalid characters, such as // linebreaks. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { req, out := c.DecodeAuthorizationMessageRequest(input) return out, req.Send() @@ -685,19 +713,18 @@ const opGetCallerIdentity = "GetCallerIdentity" // GetCallerIdentityRequest generates a "aws/request.Request" representing the // client's request for the GetCallerIdentity operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetCallerIdentity for usage and error information. +// See GetCallerIdentity for more information on using the GetCallerIdentity +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetCallerIdentity method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetCallerIdentityRequest method. // req, resp := client.GetCallerIdentityRequest(params) @@ -707,7 +734,7 @@ const opGetCallerIdentity = "GetCallerIdentity" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) { op := &request.Operation{ Name: opGetCallerIdentity, @@ -735,7 +762,7 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ // // See the AWS API reference guide for AWS Security Token Service's // API operation GetCallerIdentity for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { req, out := c.GetCallerIdentityRequest(input) return out, req.Send() @@ -761,19 +788,18 @@ const opGetFederationToken = "GetFederationToken" // GetFederationTokenRequest generates a "aws/request.Request" representing the // client's request for the GetFederationToken operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. // -// See GetFederationToken for usage and error information. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetFederationToken method directly -// instead. +// See GetFederationToken for more information on using the GetFederationToken +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetFederationTokenRequest method. // req, resp := client.GetFederationTokenRequest(params) @@ -783,7 +809,7 @@ const opGetFederationToken = "GetFederationToken" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) { op := &request.Operation{ Name: opGetFederationToken, @@ -905,7 +931,7 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { req, out := c.GetFederationTokenRequest(input) return out, req.Send() @@ -931,19 +957,18 @@ const opGetSessionToken = "GetSessionToken" // GetSessionTokenRequest generates a "aws/request.Request" representing the // client's request for the GetSessionToken operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// See GetSessionToken for usage and error information. +// See GetSessionToken for more information on using the GetSessionToken +// API call, and error handling. // -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetSessionToken method directly -// instead. +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. // // // Example sending a request using the GetSessionTokenRequest method. // req, resp := client.GetSessionTokenRequest(params) @@ -953,7 +978,7 @@ const opGetSessionToken = "GetSessionToken" // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) { op := &request.Operation{ Name: opGetSessionToken, @@ -1034,7 +1059,7 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the IAM User Guide. // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken +// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { req, out := c.GetSessionTokenRequest(input) return out, req.Send() @@ -1056,20 +1081,27 @@ func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionToken return out, req.Send() } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleRequest type AssumeRoleInput struct { _ struct{} `type:"structure"` // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. + // seconds (15 minutes) up to the maximum session duration setting for the role. + // This setting can have a value from 1 hour to 12 hours. If you specify a value + // higher than this setting, the operation fails. For example, if you specify + // a session duration of 12 hours, but your administrator set the maximum session + // duration to 6 hours, your operation fails. To learn how to view the maximum + // value for your role, see View the Maximum Session Duration Setting for a + // Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) + // in the IAM User Guide. // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Creating a URL that Enables - // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) + // By default, the value is set to 3600 seconds. + // + // The DurationSeconds parameter is separate from the duration of a console + // session that you might request using the returned credentials. The request + // to the federation endpoint for a console sign-in token takes a SessionDuration + // parameter that specifies the maximum length of the console session. For more + // information, see Creating a URL that Enables Federated Users to Access the + // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) // in the IAM User Guide. DurationSeconds *int64 `min:"900" type:"integer"` @@ -1248,7 +1280,6 @@ func (s *AssumeRoleInput) SetTokenCode(v string) *AssumeRoleInput { // Contains the response to a successful AssumeRole request, including temporary // AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleResponse type AssumeRoleOutput struct { _ struct{} `type:"structure"` @@ -1302,22 +1333,30 @@ func (s *AssumeRoleOutput) SetPackedPolicySize(v int64) *AssumeRoleOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAMLRequest type AssumeRoleWithSAMLInput struct { _ struct{} `type:"structure"` - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. An expiration can also be specified in the SAML authentication - // response's SessionNotOnOrAfter value. The actual expiration time is whichever - // value is shorter. + // The duration, in seconds, of the role session. Your role session lasts for + // the duration that you specify for the DurationSeconds parameter, or until + // the time specified in the SAML authentication response's SessionNotOnOrAfter + // value, whichever is shorter. You can provide a DurationSeconds value from + // 900 seconds (15 minutes) up to the maximum session duration setting for the + // role. This setting can have a value from 1 hour to 12 hours. If you specify + // a value higher than this setting, the operation fails. For example, if you + // specify a session duration of 12 hours, but your administrator set the maximum + // session duration to 6 hours, your operation fails. To learn how to view the + // maximum value for your role, see View the Maximum Session Duration Setting + // for a Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) + // in the IAM User Guide. + // + // By default, the value is set to 3600 seconds. // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Enabling SAML 2.0 Federated - // Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html) + // The DurationSeconds parameter is separate from the duration of a console + // session that you might request using the returned credentials. The request + // to the federation endpoint for a console sign-in token takes a SessionDuration + // parameter that specifies the maximum length of the console session. For more + // information, see Creating a URL that Enables Federated Users to Access the + // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) // in the IAM User Guide. DurationSeconds *int64 `min:"900" type:"integer"` @@ -1443,7 +1482,6 @@ func (s *AssumeRoleWithSAMLInput) SetSAMLAssertion(v string) *AssumeRoleWithSAML // Contains the response to a successful AssumeRoleWithSAML request, including // temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAMLResponse type AssumeRoleWithSAMLOutput struct { _ struct{} `type:"structure"` @@ -1555,20 +1593,27 @@ func (s *AssumeRoleWithSAMLOutput) SetSubjectType(v string) *AssumeRoleWithSAMLO return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentityRequest type AssumeRoleWithWebIdentityInput struct { _ struct{} `type:"structure"` // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. + // seconds (15 minutes) up to the maximum session duration setting for the role. + // This setting can have a value from 1 hour to 12 hours. If you specify a value + // higher than this setting, the operation fails. For example, if you specify + // a session duration of 12 hours, but your administrator set the maximum session + // duration to 6 hours, your operation fails. To learn how to view the maximum + // value for your role, see View the Maximum Session Duration Setting for a + // Role (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) + // in the IAM User Guide. + // + // By default, the value is set to 3600 seconds. // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Creating a URL that Enables - // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) + // The DurationSeconds parameter is separate from the duration of a console + // session that you might request using the returned credentials. The request + // to the federation endpoint for a console sign-in token takes a SessionDuration + // parameter that specifies the maximum length of the console session. For more + // information, see Creating a URL that Enables Federated Users to Access the + // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) // in the IAM User Guide. DurationSeconds *int64 `min:"900" type:"integer"` @@ -1718,7 +1763,6 @@ func (s *AssumeRoleWithWebIdentityInput) SetWebIdentityToken(v string) *AssumeRo // Contains the response to a successful AssumeRoleWithWebIdentity request, // including temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentityResponse type AssumeRoleWithWebIdentityOutput struct { _ struct{} `type:"structure"` @@ -1811,7 +1855,6 @@ func (s *AssumeRoleWithWebIdentityOutput) SetSubjectFromWebIdentityToken(v strin // The identifiers for the temporary security credentials that the operation // returns. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumedRoleUser type AssumedRoleUser struct { _ struct{} `type:"structure"` @@ -1854,7 +1897,6 @@ func (s *AssumedRoleUser) SetAssumedRoleId(v string) *AssumedRoleUser { } // AWS credentials for API authentication. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/Credentials type Credentials struct { _ struct{} `type:"structure"` @@ -1866,7 +1908,7 @@ type Credentials struct { // The date on which the current credentials expire. // // Expiration is a required field - Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` + Expiration *time.Time `type:"timestamp" required:"true"` // The secret access key that can be used to sign requests. // @@ -1913,7 +1955,6 @@ func (s *Credentials) SetSessionToken(v string) *Credentials { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessageRequest type DecodeAuthorizationMessageInput struct { _ struct{} `type:"structure"` @@ -1958,7 +1999,6 @@ func (s *DecodeAuthorizationMessageInput) SetEncodedMessage(v string) *DecodeAut // A document that contains additional information about the authorization status // of a request from an encoded message that is returned in response to an AWS // request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessageResponse type DecodeAuthorizationMessageOutput struct { _ struct{} `type:"structure"` @@ -1983,7 +2023,6 @@ func (s *DecodeAuthorizationMessageOutput) SetDecodedMessage(v string) *DecodeAu } // Identifiers for the federated user that is associated with the credentials. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/FederatedUser type FederatedUser struct { _ struct{} `type:"structure"` @@ -2024,7 +2063,6 @@ func (s *FederatedUser) SetFederatedUserId(v string) *FederatedUser { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentityRequest type GetCallerIdentityInput struct { _ struct{} `type:"structure"` } @@ -2041,7 +2079,6 @@ func (s GetCallerIdentityInput) GoString() string { // Contains the response to a successful GetCallerIdentity request, including // information about the entity making the request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentityResponse type GetCallerIdentityOutput struct { _ struct{} `type:"structure"` @@ -2087,7 +2124,6 @@ func (s *GetCallerIdentityOutput) SetUserId(v string) *GetCallerIdentityOutput { return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationTokenRequest type GetFederationTokenInput struct { _ struct{} `type:"structure"` @@ -2196,7 +2232,6 @@ func (s *GetFederationTokenInput) SetPolicy(v string) *GetFederationTokenInput { // Contains the response to a successful GetFederationToken request, including // temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationTokenResponse type GetFederationTokenOutput struct { _ struct{} `type:"structure"` @@ -2249,7 +2284,6 @@ func (s *GetFederationTokenOutput) SetPackedPolicySize(v int64) *GetFederationTo return s } -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionTokenRequest type GetSessionTokenInput struct { _ struct{} `type:"structure"` @@ -2334,7 +2368,6 @@ func (s *GetSessionTokenInput) SetTokenCode(v string) *GetSessionTokenInput { // Contains the response to a successful GetSessionToken request, including // temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionTokenResponse type GetSessionTokenOutput struct { _ struct{} `type:"structure"` diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go index d2af518cf..ef681ab0c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go @@ -56,69 +56,17 @@ // // Using the Client // -// To use the client for AWS Security Token Service you will first need -// to create a new instance of it. +// To contact AWS Security Token Service with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. // -// When creating a client for an AWS service you'll first need to have a Session -// already created. The Session provides configuration that can be shared -// between multiple service clients. Additional configuration can be applied to -// the Session and service's client when they are constructed. The aws package's -// Config type contains several fields such as Region for the AWS Region the -// client should make API requests too. The optional Config value can be provided -// as the variadic argument for Sessions and client creation. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// // Create a session to share configuration, and load external configuration. -// sess := session.Must(session.NewSession()) -// -// // Create the service's client with the session. -// svc := sts.New(sess) -// -// See the SDK's documentation for more information on how to use service clients. +// See the SDK's documentation for more information on how to use the SDK. // https://docs.aws.amazon.com/sdk-for-go/api/ // -// See aws package's Config type for more information on configuration options. +// See aws.Config documentation for more information on configuring SDK clients. // https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config // // See the AWS Security Token Service client STS for more -// information on creating the service's client. +// information on creating client for this service. // https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. -// -// The API method will document which error codes the service can be returned -// by the operation if the service models the API operation's errors. These -// errors will also be available as const strings prefixed with "ErrCode". -// -// result, err := svc.AssumeRole(params) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == { -// // Specific error code handling -// } -// return err -// } -// -// fmt.Println("AssumeRole result:") -// fmt.Println(result) -// -// Using the Client with Context -// -// The service's client also provides methods to make API requests with a Context -// value. This allows you to control the timeout, and cancellation of pending -// requests. These methods also take request Option as variadic parameter to apply -// additional configuration to the API request. -// -// ctx := context.Background() -// -// result, err := svc.AssumeRoleWithContext(ctx, params) -// -// See the request package documentation for more information on using Context pattern -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go index 1ee5839e0..185c914d1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go @@ -29,8 +29,9 @@ var initRequest func(*request.Request) // Service information constants const ( - ServiceName = "sts" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. + ServiceName = "sts" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "STS" // ServiceID is a unique identifer of a specific service. ) // New creates a new instance of the STS client with a session. @@ -55,6 +56,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg, metadata.ClientInfo{ ServiceName: ServiceName, + ServiceID: ServiceID, SigningName: signingName, SigningRegion: signingRegion, Endpoint: endpoint, diff --git a/vendor/github.com/bgentry/speakeasy/.gitignore b/vendor/github.com/bgentry/speakeasy/.gitignore new file mode 100644 index 000000000..9e1311461 --- /dev/null +++ b/vendor/github.com/bgentry/speakeasy/.gitignore @@ -0,0 +1,2 @@ +example/example +example/example.exe diff --git a/vendor/github.com/blang/semver/.travis.yml b/vendor/github.com/blang/semver/.travis.yml new file mode 100644 index 000000000..102fb9a69 --- /dev/null +++ b/vendor/github.com/blang/semver/.travis.yml @@ -0,0 +1,21 @@ +language: go +matrix: + include: + - go: 1.4.3 + - go: 1.5.4 + - go: 1.6.3 + - go: 1.7 + - go: tip + allow_failures: + - go: tip +install: +- go get golang.org/x/tools/cmd/cover +- go get github.com/mattn/goveralls +script: +- echo "Test and track coverage" ; $HOME/gopath/bin/goveralls -package "." -service=travis-ci + -repotoken $COVERALLS_TOKEN +- echo "Build examples" ; cd examples && go build +- echo "Check if gofmt'd" ; diff -u <(echo -n) <(gofmt -d -s .) +env: + global: + secure: HroGEAUQpVq9zX1b1VIkraLiywhGbzvNnTZq2TMxgK7JHP8xqNplAeF1izrR2i4QLL9nsY+9WtYss4QuPvEtZcVHUobw6XnL6radF7jS1LgfYZ9Y7oF+zogZ2I5QUMRLGA7rcxQ05s7mKq3XZQfeqaNts4bms/eZRefWuaFZbkw= diff --git a/vendor/github.com/briankassouf/jose/LICENSE b/vendor/github.com/briankassouf/jose/LICENSE deleted file mode 100644 index d2d35b66c..000000000 --- a/vendor/github.com/briankassouf/jose/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Sermo Digital LLC - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/briankassouf/jose/crypto/doc.go b/vendor/github.com/briankassouf/jose/crypto/doc.go deleted file mode 100644 index 16cf476ba..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package crypto implements "SigningMethods" and "EncryptionMethods"; -// that is, ways to sign and encrypt JWS and JWEs, respectively, as well -// as JWTs. -package crypto diff --git a/vendor/github.com/briankassouf/jose/crypto/ecdsa.go b/vendor/github.com/briankassouf/jose/crypto/ecdsa.go deleted file mode 100644 index fe9fd5e24..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/ecdsa.go +++ /dev/null @@ -1,138 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "encoding/asn1" - "encoding/json" - "errors" - "math/big" -) - -// ErrECDSAVerification is missing from crypto/ecdsa compared to crypto/rsa -var ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") - -// SigningMethodECDSA implements the ECDSA family of signing methods signing -// methods -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// ECPoint is a marshalling structure for the EC points R and S. -type ECPoint struct { - R *big.Int - S *big.Int -} - -// Specific instances of EC SigningMethods. -var ( - // SigningMethodES256 implements ES256. - SigningMethodES256 = &SigningMethodECDSA{ - Name: "ES256", - Hash: crypto.SHA256, - } - - // SigningMethodES384 implements ES384. - SigningMethodES384 = &SigningMethodECDSA{ - Name: "ES384", - Hash: crypto.SHA384, - } - - // SigningMethodES512 implements ES512. - SigningMethodES512 = &SigningMethodECDSA{ - Name: "ES512", - Hash: crypto.SHA512, - } -) - -// Alg returns the name of the SigningMethodECDSA instance. -func (m *SigningMethodECDSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *ecdsa.PublicKey. -func (m *SigningMethodECDSA) Verify(raw []byte, signature Signature, key interface{}) error { - ecdsaKey, ok := key.(*ecdsa.PublicKey) - if !ok { - return ErrInvalidKey - } - - var keySize int - switch m.Name { - case "ES256": - keySize = 32 - case "ES384": - keySize = 48 - case "ES512": - keySize = 66 - } - - if len(signature) == 2*keySize { - r := big.NewInt(0).SetBytes(signature[:keySize]) - s := big.NewInt(0).SetBytes(signature[keySize:]) - - // If verification succeeds return - if ecdsa.Verify(ecdsaKey, m.sum(raw), r, s) { - return nil - } - } - - // Fall back to the old method - // Unmarshal asn1 ECPoint - var ecpoint ECPoint - if _, err := asn1.Unmarshal(signature, &ecpoint); err != nil { - return err - } - - // Verify the signature - if !ecdsa.Verify(ecdsaKey, m.sum(raw), ecpoint.R, ecpoint.S) { - return ErrECDSAVerification - } - - return nil -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *ecdsa.PrivateKey. -func (m *SigningMethodECDSA) Sign(data []byte, key interface{}) (Signature, error) { - - ecdsaKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - - r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, m.sum(data)) - if err != nil { - return nil, err - } - - signature, err := asn1.Marshal(ECPoint{R: r, S: s}) - if err != nil { - return nil, err - } - return Signature(signature), nil -} - -func (m *SigningMethodECDSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodECDSA) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON is in case somebody decides to place SigningMethodECDSA -// inside the Header, presumably because they (wrongly) decided it was a good -// idea to use the SigningMethod itself instead of the SigningMethod's Alg -// method. In order to keep things sane, marshalling this will simply -// return the JSON-compatible representation of m.Alg(). -func (m *SigningMethodECDSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodECDSA)(nil) diff --git a/vendor/github.com/briankassouf/jose/crypto/ecdsa_utils.go b/vendor/github.com/briankassouf/jose/crypto/ecdsa_utils.go deleted file mode 100644 index 4bd75d2e5..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/ecdsa_utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package crypto - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// ECDSA parsing errors. -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// ParseECPrivateKeyFromPEM will parse a PEM encoded EC Private -// Key Structure. -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - return x509.ParseECPrivateKey(block.Bytes) -} - -// ParseECPublicKeyFromPEM will parse a PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - - block, _ := pem.Decode(key) - if block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - parsedKey = cert.PublicKey - } - - pkey, ok := parsedKey.(*ecdsa.PublicKey) - if !ok { - return nil, ErrNotECPublicKey - } - return pkey, nil -} diff --git a/vendor/github.com/briankassouf/jose/crypto/errors.go b/vendor/github.com/briankassouf/jose/crypto/errors.go deleted file mode 100644 index 34fbd25ff..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package crypto - -import "errors" - -var ( - // ErrInvalidKey means the key argument passed to SigningMethod.Verify - // was not the correct type. - ErrInvalidKey = errors.New("key is invalid") -) diff --git a/vendor/github.com/briankassouf/jose/crypto/hmac.go b/vendor/github.com/briankassouf/jose/crypto/hmac.go deleted file mode 100644 index 1cb7f6e09..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/hmac.go +++ /dev/null @@ -1,81 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/hmac" - "encoding/json" - "errors" -) - -// SigningMethodHMAC implements the HMAC-SHA family of SigningMethods. -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of HMAC-SHA SigningMethods. -var ( - // SigningMethodHS256 implements HS256. - SigningMethodHS256 = &SigningMethodHMAC{ - Name: "HS256", - Hash: crypto.SHA256, - } - - // SigningMethodHS384 implements HS384. - SigningMethodHS384 = &SigningMethodHMAC{ - Name: "HS384", - Hash: crypto.SHA384, - } - - // SigningMethodHS512 implements HS512. - SigningMethodHS512 = &SigningMethodHMAC{ - Name: "HS512", - Hash: crypto.SHA512, - } - - // ErrSignatureInvalid is returned when the provided signature is found - // to be invalid. - ErrSignatureInvalid = errors.New("signature is invalid") -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodHMAC) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be a []byte. -func (m *SigningMethodHMAC) Verify(raw []byte, signature Signature, key interface{}) error { - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(raw) - if hmac.Equal(signature, hasher.Sum(nil)) { - return nil - } - return ErrSignatureInvalid -} - -// Sign implements the Sign method from SigningMethod for this signing method. -// Key must be a []byte. -func (m *SigningMethodHMAC) Sign(data []byte, key interface{}) (Signature, error) { - keyBytes, ok := key.([]byte) - if !ok { - return nil, ErrInvalidKey - } - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write(data) - return Signature(hasher.Sum(nil)), nil -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodHMAC) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodHMAC) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodHMAC)(nil) diff --git a/vendor/github.com/briankassouf/jose/crypto/none.go b/vendor/github.com/briankassouf/jose/crypto/none.go deleted file mode 100644 index db3d139e9..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/none.go +++ /dev/null @@ -1,72 +0,0 @@ -package crypto - -import ( - "crypto" - "encoding/json" - "hash" - "io" -) - -func init() { - crypto.RegisterHash(crypto.Hash(0), h) -} - -// h is passed to crypto.RegisterHash. -func h() hash.Hash { - return &f{Writer: nil} -} - -type f struct{ io.Writer } - -// Sum helps implement the hash.Hash interface. -func (_ *f) Sum(b []byte) []byte { return nil } - -// Reset helps implement the hash.Hash interface. -func (_ *f) Reset() {} - -// Size helps implement the hash.Hash interface. -func (_ *f) Size() int { return -1 } - -// BlockSize helps implement the hash.Hash interface. -func (_ *f) BlockSize() int { return -1 } - -// Unsecured is the default "none" algorithm. -var Unsecured = &SigningMethodNone{ - Name: "none", - Hash: crypto.Hash(0), -} - -// SigningMethodNone is the default "none" algorithm. -type SigningMethodNone struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Verify helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Verify(_ []byte, _ Signature, _ interface{}) error { - return nil -} - -// Sign helps implement the SigningMethod interface. -func (_ *SigningMethodNone) Sign(_ []byte, _ interface{}) (Signature, error) { - return nil, nil -} - -// Alg helps implement the SigningMethod interface. -func (m *SigningMethodNone) Alg() string { - return m.Name -} - -// Hasher helps implement the SigningMethod interface. -func (m *SigningMethodNone) Hasher() crypto.Hash { - return m.Hash -} - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodNone) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodNone)(nil) diff --git a/vendor/github.com/briankassouf/jose/crypto/rsa.go b/vendor/github.com/briankassouf/jose/crypto/rsa.go deleted file mode 100644 index 80596df33..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/rsa.go +++ /dev/null @@ -1,80 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSA implements the RSA family of SigningMethods. -type SigningMethodRSA struct { - Name string - Hash crypto.Hash - _ struct{} -} - -// Specific instances of RSA SigningMethods. -var ( - // SigningMethodRS256 implements RS256. - SigningMethodRS256 = &SigningMethodRSA{ - Name: "RS256", - Hash: crypto.SHA256, - } - - // SigningMethodRS384 implements RS384. - SigningMethodRS384 = &SigningMethodRSA{ - Name: "RS384", - Hash: crypto.SHA384, - } - - // SigningMethodRS512 implements RS512. - SigningMethodRS512 = &SigningMethodRSA{ - Name: "RS512", - Hash: crypto.SHA512, - } -) - -// Alg implements the SigningMethod interface. -func (m *SigningMethodRSA) Alg() string { return m.Name } - -// Verify implements the Verify method from SigningMethod. -// For this signing method, must be an *rsa.PublicKey. -func (m *SigningMethodRSA) Verify(raw []byte, sig Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, m.sum(raw), sig) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(data []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, m.sum(data)) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSA) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the SigningMethod interface. -func (m *SigningMethodRSA) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSA) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSA)(nil) diff --git a/vendor/github.com/briankassouf/jose/crypto/rsa_pss.go b/vendor/github.com/briankassouf/jose/crypto/rsa_pss.go deleted file mode 100644 index 3847ae2d2..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/rsa_pss.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build go1.4 - -package crypto - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "encoding/json" -) - -// SigningMethodRSAPSS implements the RSAPSS family of SigningMethods. -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS SigningMethods. -var ( - // SigningMethodPS256 implements PS256. - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - - // SigningMethodPS384 implements PS384. - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - - // SigningMethodPS512 implements PS512. - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } -) - -// Verify implements the Verify method from SigningMethod. -// For this verify method, key must be an *rsa.PublicKey. -func (m *SigningMethodRSAPSS) Verify(raw []byte, signature Signature, key interface{}) error { - rsaKey, ok := key.(*rsa.PublicKey) - if !ok { - return ErrInvalidKey - } - return rsa.VerifyPSS(rsaKey, m.Hash, m.sum(raw), signature, m.Options) -} - -// Sign implements the Sign method from SigningMethod. -// For this signing method, key must be an *rsa.PrivateKey. -func (m *SigningMethodRSAPSS) Sign(raw []byte, key interface{}) (Signature, error) { - rsaKey, ok := key.(*rsa.PrivateKey) - if !ok { - return nil, ErrInvalidKey - } - sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, m.sum(raw), m.Options) - if err != nil { - return nil, err - } - return Signature(sigBytes), nil -} - -func (m *SigningMethodRSAPSS) sum(b []byte) []byte { - h := m.Hash.New() - h.Write(b) - return h.Sum(nil) -} - -// Hasher implements the Hasher method from SigningMethod. -func (m *SigningMethodRSAPSS) Hasher() crypto.Hash { return m.Hash } - -// MarshalJSON implements json.Marshaler. -// See SigningMethodECDSA.MarshalJSON() for information. -func (m *SigningMethodRSAPSS) MarshalJSON() ([]byte, error) { - return []byte(`"` + m.Alg() + `"`), nil -} - -var _ json.Marshaler = (*SigningMethodRSAPSS)(nil) diff --git a/vendor/github.com/briankassouf/jose/crypto/rsa_utils.go b/vendor/github.com/briankassouf/jose/crypto/rsa_utils.go deleted file mode 100644 index 43aeff375..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/rsa_utils.go +++ /dev/null @@ -1,70 +0,0 @@ -package crypto - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -// Errors specific to rsa_utils. -var ( - ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") -) - -// ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key. -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// ParseRSAPublicKeyFromPEM parses PEM encoded PKCS1 or PKCS8 public key. -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/briankassouf/jose/crypto/signature.go b/vendor/github.com/briankassouf/jose/crypto/signature.go deleted file mode 100644 index 1f79f8611..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/signature.go +++ /dev/null @@ -1,36 +0,0 @@ -package crypto - -import ( - "encoding/json" - - "github.com/briankassouf/jose" -) - -// Signature is a JWS signature. -type Signature []byte - -// MarshalJSON implements json.Marshaler for a signature. -func (s Signature) MarshalJSON() ([]byte, error) { - return jose.EncodeEscape(s), nil -} - -// Base64 helps implements jose.Encoder for Signature. -func (s Signature) Base64() ([]byte, error) { - return jose.Base64Encode(s), nil -} - -// UnmarshalJSON implements json.Unmarshaler for signature. -func (s *Signature) UnmarshalJSON(b []byte) error { - dec, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - *s = Signature(dec) - return nil -} - -var ( - _ json.Marshaler = (Signature)(nil) - _ json.Unmarshaler = (*Signature)(nil) - _ jose.Encoder = (Signature)(nil) -) diff --git a/vendor/github.com/briankassouf/jose/crypto/signing_method.go b/vendor/github.com/briankassouf/jose/crypto/signing_method.go deleted file mode 100644 index c8b8874b2..000000000 --- a/vendor/github.com/briankassouf/jose/crypto/signing_method.go +++ /dev/null @@ -1,24 +0,0 @@ -package crypto - -import "crypto" - -// SigningMethod is an interface that provides a way to sign JWS tokens. -type SigningMethod interface { - // Alg describes the signing algorithm, and is used to uniquely - // describe the specific crypto.SigningMethod. - Alg() string - - // Verify accepts the raw content, the signature, and the key used - // to sign the raw content, and returns any errors found while validating - // the signature and content. - Verify(raw []byte, sig Signature, key interface{}) error - - // Sign returns a Signature for the raw bytes, as well as any errors - // that occurred during the signing. - Sign(raw []byte, key interface{}) (Signature, error) - - // Used to cause quick panics when a crypto.SigningMethod whose form of hashing - // isn't linked in the binary when you register a crypto.SigningMethod. - // To spoof this, see "crypto.SigningMethodNone". - Hasher() crypto.Hash -} diff --git a/vendor/github.com/briankassouf/jose/jws/claims.go b/vendor/github.com/briankassouf/jose/jws/claims.go deleted file mode 100644 index 56a5b91e3..000000000 --- a/vendor/github.com/briankassouf/jose/jws/claims.go +++ /dev/null @@ -1,190 +0,0 @@ -package jws - -import ( - "encoding/json" - "time" - - "github.com/briankassouf/jose" - "github.com/briankassouf/jose/jwt" -) - -// Claims represents a set of JOSE Claims. -type Claims jwt.Claims - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - return jwt.Claims(c).Get(key) -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - jwt.Claims(c).Set(key, val) -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - jwt.Claims(c).Del(key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - return jwt.Claims(c).Has(key) -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - return jwt.Claims(c).MarshalJSON() -} - -// Base64 implements the Encoder interface. -func (c Claims) Base64() ([]byte, error) { - return jwt.Claims(c).Base64() -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - return jwt.Claims(c).Issuer() -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - return jwt.Claims(c).Subject() -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - return jwt.Claims(c).Audience() -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return jwt.Claims(c).Expiration() -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return jwt.Claims(c).NotBefore() -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return jwt.Claims(c).IssuedAt() -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - return jwt.Claims(c).JWTID() -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { - jwt.Claims(c).RemoveIssuer() -} - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { - jwt.Claims(c).Audience() -} - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { - jwt.Claims(c).RemoveExpiration() -} - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { - jwt.Claims(c).NotBefore() -} - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { - jwt.Claims(c).IssuedAt() -} - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { - jwt.Claims(c).RemoveJWTID() -} - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - jwt.Claims(c).SetIssuer(issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - jwt.Claims(c).SetSubject(subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - jwt.Claims(c).SetAudience(audience...) -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - jwt.Claims(c).SetExpiration(expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - jwt.Claims(c).SetNotBefore(notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - jwt.Claims(c).SetIssuedAt(issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - jwt.Claims(c).SetJWTID(uniqueID) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/briankassouf/jose/jws/doc.go b/vendor/github.com/briankassouf/jose/jws/doc.go deleted file mode 100644 index 165836d57..000000000 --- a/vendor/github.com/briankassouf/jose/jws/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jws implements JWSs per RFC 7515 -package jws diff --git a/vendor/github.com/briankassouf/jose/jws/errors.go b/vendor/github.com/briankassouf/jose/jws/errors.go deleted file mode 100644 index 0512a0e40..000000000 --- a/vendor/github.com/briankassouf/jose/jws/errors.go +++ /dev/null @@ -1,62 +0,0 @@ -package jws - -import "errors" - -var ( - - // ErrNotEnoughMethods is returned if New was called _or_ the Flat/Compact - // methods were called with 0 SigningMethods. - ErrNotEnoughMethods = errors.New("not enough methods provided") - - // ErrCouldNotUnmarshal is returned when Parse's json.Unmarshaler - // parameter returns an error. - ErrCouldNotUnmarshal = errors.New("custom unmarshal failed") - - // ErrNotCompact signals that the provided potential JWS is not - // in its compact representation. - ErrNotCompact = errors.New("not a compact JWS") - - // ErrDuplicateHeaderParameter signals that there are duplicate parameters - // in the provided Headers. - ErrDuplicateHeaderParameter = errors.New("duplicate parameters in the JOSE Header") - - // ErrTwoEmptyHeaders is returned if both Headers are empty. - ErrTwoEmptyHeaders = errors.New("both headers cannot be empty") - - // ErrNotEnoughKeys is returned when not enough keys are provided for - // the given SigningMethods. - ErrNotEnoughKeys = errors.New("not enough keys (for given methods)") - - // ErrDidNotValidate means the given JWT did not properly validate - ErrDidNotValidate = errors.New("did not validate") - - // ErrNoAlgorithm means no algorithm ("alg") was found in the Protected - // Header. - ErrNoAlgorithm = errors.New("no algorithm found") - - // ErrAlgorithmDoesntExist means the algorithm asked for cannot be - // found inside the signingMethod cache. - ErrAlgorithmDoesntExist = errors.New("algorithm doesn't exist") - - // ErrMismatchedAlgorithms means the algorithm inside the JWT was - // different than the algorithm the caller wanted to use. - ErrMismatchedAlgorithms = errors.New("mismatched algorithms") - - // ErrCannotValidate means the JWS cannot be validated for various - // reasons. For example, if there aren't any signatures/payloads/headers - // to actually validate. - ErrCannotValidate = errors.New("cannot validate") - - // ErrIsNotJWT means the given JWS is not a JWT. - ErrIsNotJWT = errors.New("JWS is not a JWT") - - // ErrHoldsJWE means the given JWS holds a JWE inside its payload. - ErrHoldsJWE = errors.New("JWS holds JWE") - - // ErrNotEnoughValidSignatures means the JWS did not meet the required - // number of signatures. - ErrNotEnoughValidSignatures = errors.New("not enough valid signatures in the JWS") - - // ErrNoTokenInRequest means there's no token present inside the *http.Request. - ErrNoTokenInRequest = errors.New("no token present in request") -) diff --git a/vendor/github.com/briankassouf/jose/jws/jws.go b/vendor/github.com/briankassouf/jose/jws/jws.go deleted file mode 100644 index 9cf3adff0..000000000 --- a/vendor/github.com/briankassouf/jose/jws/jws.go +++ /dev/null @@ -1,490 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" - "net/http" - "strings" - - "github.com/briankassouf/jose" - "github.com/briankassouf/jose/crypto" -) - -// JWS implements a JWS per RFC 7515. -type JWS interface { - // Payload Returns the payload. - Payload() interface{} - - // SetPayload sets the payload with the given value. - SetPayload(p interface{}) - - // Protected returns the JWS' Protected Header. - Protected() jose.Protected - - // ProtectedAt returns the JWS' Protected Header. - // i represents the index of the Protected Header. - ProtectedAt(i int) jose.Protected - - // Header returns the JWS' unprotected Header. - Header() jose.Header - - // HeaderAt returns the JWS' unprotected Header. - // i represents the index of the unprotected Header. - HeaderAt(i int) jose.Header - - // Verify validates the current JWS' signature as-is. Refer to - // ValidateMulti for more information. - Verify(key interface{}, method crypto.SigningMethod) error - - // ValidateMulti validates the current JWS' signature as-is. Since it's - // meant to be called after parsing a stream of bytes into a JWS, it - // shouldn't do any internal parsing like the Sign, Flat, Compact, or - // General methods do. - VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error - - // VerifyCallback validates the current JWS' signature as-is. It - // accepts a callback function that can be used to access header - // parameters to lookup needed information. For example, looking - // up the "kid" parameter. - // The return slice must be a slice of keys used in the verification - // of the JWS. - VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error - - // General serializes the JWS into its "general" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.1 - General(keys ...interface{}) ([]byte, error) - - // Flat serializes the JWS to its "flattened" form per - // https://tools.ietf.org/html/rfc7515#section-7.2.2 - Flat(key interface{}) ([]byte, error) - - // Compact serializes the JWS into its "compact" form per - // https://tools.ietf.org/html/rfc7515#section-7.1 - Compact(key interface{}) ([]byte, error) - - // IsJWT returns true if the JWS is a JWT. - IsJWT() bool -} - -// jws represents a specific jws. -type jws struct { - payload *payload - plcache rawBase64 - clean bool - - sb []sigHead - - isJWT bool -} - -// Payload returns the jws' payload. -func (j *jws) Payload() interface{} { - return j.payload.v -} - -// SetPayload sets the jws' raw, unexported payload. -func (j *jws) SetPayload(val interface{}) { - j.payload.v = val -} - -// Protected returns the JWS' Protected Header. -func (j *jws) Protected() jose.Protected { - return j.sb[0].protected -} - -// Protected returns the JWS' Protected Header. -// i represents the index of the Protected Header. -// Left empty, it defaults to 0. -func (j *jws) ProtectedAt(i int) jose.Protected { - return j.sb[i].protected -} - -// Header returns the JWS' unprotected Header. -func (j *jws) Header() jose.Header { - return j.sb[0].unprotected -} - -// HeaderAt returns the JWS' unprotected Header. -// |i| is the index of the unprotected Header. -func (j *jws) HeaderAt(i int) jose.Header { - return j.sb[i].unprotected -} - -// sigHead represents the 'signatures' member of the jws' "general" -// serialization form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// It's embedded inside the "flat" structure in order to properly -// create the "flat" jws. -type sigHead struct { - Protected rawBase64 `json:"protected,omitempty"` - Unprotected rawBase64 `json:"header,omitempty"` - Signature crypto.Signature `json:"signature"` - - protected jose.Protected - unprotected jose.Header - clean bool - - method crypto.SigningMethod -} - -func (s *sigHead) unmarshal() error { - if err := s.protected.UnmarshalJSON(s.Protected); err != nil { - return err - } - return s.unprotected.UnmarshalJSON(s.Unprotected) -} - -// New creates a JWS with the provided crypto.SigningMethods. -func New(content interface{}, methods ...crypto.SigningMethod) JWS { - sb := make([]sigHead, len(methods)) - for i := range methods { - sb[i] = sigHead{ - protected: jose.Protected{ - "alg": methods[i].Alg(), - }, - unprotected: jose.Header{}, - method: methods[i], - } - } - return &jws{ - payload: &payload{v: content}, - sb: sb, - } -} - -func (s *sigHead) assignMethod(p jose.Protected) error { - alg, ok := p.Get("alg").(string) - if !ok { - return ErrNoAlgorithm - } - - sm := GetSigningMethod(alg) - if sm == nil { - return ErrNoAlgorithm - } - s.method = sm - return nil -} - -type generic struct { - Payload rawBase64 `json:"payload"` - sigHead - Signatures []sigHead `json:"signatures,omitempty"` -} - -// Parse parses any of the three serialized jws forms into a physical -// jws per https://tools.ietf.org/html/rfc7515#section-5.2 -// -// It accepts a json.Unmarshaler in order to properly parse -// the payload. In order to keep the caller from having to do extra -// parsing of the payload, a json.Unmarshaler can be passed -// which will be then to unmarshal the payload however the caller -// wishes. Do note that if json.Unmarshal returns an error the -// original payload will be used as if no json.Unmarshaler was -// passed. -// -// Internally, Parse applies some heuristics and then calls either -// ParseGeneral, ParseFlat, or ParseCompact. -// It should only be called if, for whatever reason, you do not -// know which form the serialized JWT is in. -// -// It cannot parse a JWT. -func Parse(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - // Try and unmarshal into a generic struct that'll - // hopefully hold either of the two JSON serialization - // formats. - var g generic - - // Not valid JSON. Let's try compact. - if err := json.Unmarshal(encoded, &g); err != nil { - return ParseCompact(encoded, u...) - } - - if g.Signatures == nil { - return g.parseFlat(u...) - } - return g.parseGeneral(u...) -} - -// ParseGeneral parses a jws serialized into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseGeneral(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseGeneral(u...) -} - -func (g *generic) parseGeneral(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - for i := range g.Signatures { - if err := g.Signatures[i].unmarshal(); err != nil { - return nil, err - } - if err := checkHeaders(jose.Header(g.Signatures[i].protected), g.Signatures[i].unprotected); err != nil { - return nil, err - } - - if err := g.Signatures[i].assignMethod(g.Signatures[i].protected); err != nil { - return nil, err - } - } - - g.clean = len(g.Signatures) != 0 - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: g.Signatures, - }, nil -} - -// ParseFlat parses a jws serialized into its "flat" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseFlat(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - var g generic - if err := json.Unmarshal(encoded, &g); err != nil { - return nil, err - } - return g.parseFlat(u...) -} - -func (g *generic) parseFlat(u ...json.Unmarshaler) (JWS, error) { - - var p payload - if len(u) > 0 { - p.u = u[0] - } - - if err := p.UnmarshalJSON(g.Payload); err != nil { - return nil, err - } - - if err := g.sigHead.unmarshal(); err != nil { - return nil, err - } - g.sigHead.clean = true - - if err := checkHeaders(jose.Header(g.sigHead.protected), g.sigHead.unprotected); err != nil { - return nil, err - } - - if err := g.sigHead.assignMethod(g.sigHead.protected); err != nil { - return nil, err - } - - return &jws{ - payload: &p, - plcache: g.Payload, - clean: true, - sb: []sigHead{g.sigHead}, - }, nil -} - -// ParseCompact parses a jws serialized into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -// into a physical jws per -// https://tools.ietf.org/html/rfc7515#section-5.2 -// -// For information on the json.Unmarshaler parameter, see Parse. -func ParseCompact(encoded []byte, u ...json.Unmarshaler) (JWS, error) { - return parseCompact(encoded, false, u...) -} - -func parseCompact(encoded []byte, jwt bool, u ...json.Unmarshaler) (*jws, error) { - - // This section loosely follows - // https://tools.ietf.org/html/rfc7519#section-7.2 - // because it's used to parse _both_ jws and JWTs. - - parts := bytes.Split(encoded, []byte{'.'}) - if len(parts) != 3 { - return nil, ErrNotCompact - } - - var p jose.Protected - if err := p.UnmarshalJSON(parts[0]); err != nil { - return nil, err - } - - s := sigHead{ - Protected: parts[0], - protected: p, - Signature: parts[2], - clean: true, - } - - if err := s.assignMethod(p); err != nil { - return nil, err - } - - var pl payload - if len(u) > 0 { - pl.u = u[0] - } - - j := jws{ - payload: &pl, - plcache: parts[1], - sb: []sigHead{s}, - isJWT: jwt, - } - - if err := j.payload.UnmarshalJSON(parts[1]); err != nil { - return nil, err - } - - j.clean = true - - if err := j.sb[0].Signature.UnmarshalJSON(parts[2]); err != nil { - return nil, err - } - - // https://tools.ietf.org/html/rfc7519#section-7.2.8 - cty, ok := p.Get("cty").(string) - if ok && cty == "JWT" { - return &j, ErrHoldsJWE - } - return &j, nil -} - -var ( - // JWSFormKey is the form "key" which should be used inside - // ParseFromRequest if the request is a multipart.Form. - JWSFormKey = "access_token" - - // MaxMemory is maximum amount of memory which should be used - // inside ParseFromRequest while parsing the multipart.Form - // if the request is a multipart.Form. - MaxMemory int64 = 10e6 -) - -// Format specifies which "format" the JWS is in -- Flat, General, -// or compact. Additionally, constants for JWT/Unknown are added. -type Format uint8 - -const ( - // Unknown format. - Unknown Format = iota - - // Flat format. - Flat - - // General format. - General - - // Compact format. - Compact -) - -var parseJumpTable = [...]func([]byte, ...json.Unmarshaler) (JWS, error){ - Unknown: Parse, - Flat: ParseFlat, - General: ParseGeneral, - Compact: ParseCompact, - 1<<8 - 1: Parse, // Max uint8. -} - -func init() { - for i := range parseJumpTable { - if parseJumpTable[i] == nil { - parseJumpTable[i] = Parse - } - } -} - -func fromHeader(req *http.Request) ([]byte, bool) { - if ah := req.Header.Get("Authorization"); len(ah) > 7 && strings.EqualFold(ah[0:7], "BEARER ") { - return []byte(ah[7:]), true - } - return nil, false -} - -func fromForm(req *http.Request) ([]byte, bool) { - if err := req.ParseMultipartForm(MaxMemory); err != nil { - return nil, false - } - if tokStr := req.Form.Get(JWSFormKey); tokStr != "" { - return []byte(tokStr), true - } - return nil, false -} - -// ParseFromHeader tries to find the JWS in an http.Request header. -func ParseFromHeader(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromHeader(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromForm tries to find the JWS in an http.Request form request. -func ParseFromForm(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - if b, ok := fromForm(req); ok { - return parseJumpTable[format](b, u...) - } - return nil, ErrNoTokenInRequest -} - -// ParseFromRequest tries to find the JWS in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseFromRequest(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error) { - token, err := ParseFromHeader(req, format, u...) - if err == nil { - return token, nil - } - - token, err = ParseFromForm(req, format, u...) - if err == nil { - return token, nil - } - - return nil, err -} - -// IgnoreDupes should be set to true if the internal duplicate header key check -// should ignore duplicate Header keys instead of reporting an error when -// duplicate Header keys are found. -// -// Note: -// Duplicate Header keys are defined in -// https://tools.ietf.org/html/rfc7515#section-5.2 -// meaning keys that both the protected and unprotected -// Headers possess. -var IgnoreDupes bool - -// checkHeaders returns an error per the constraints described in -// IgnoreDupes' comment. -func checkHeaders(a, b jose.Header) error { - if len(a)+len(b) == 0 { - return ErrTwoEmptyHeaders - } - for key := range a { - if b.Has(key) && !IgnoreDupes { - return ErrDuplicateHeaderParameter - } - } - return nil -} - -var _ JWS = (*jws)(nil) diff --git a/vendor/github.com/briankassouf/jose/jws/jws_serialize.go b/vendor/github.com/briankassouf/jose/jws/jws_serialize.go deleted file mode 100644 index 923fdc224..000000000 --- a/vendor/github.com/briankassouf/jose/jws/jws_serialize.go +++ /dev/null @@ -1,132 +0,0 @@ -package jws - -import ( - "bytes" - "encoding/json" -) - -// Flat serializes the JWS to its "flattened" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.2 -func (j *jws) Flat(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - if err := j.sign(key); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - sigHead - }{ - Payload: j.plcache, - sigHead: j.sb[0], - }) -} - -// General serializes the JWS into its "general" form per -// https://tools.ietf.org/html/rfc7515#section-7.2.1 -// -// If only one key is passed it's used for all the provided -// crypto.SigningMethods. Otherwise, len(keys) must equal the number -// of crypto.SigningMethods added. -func (j *jws) General(keys ...interface{}) ([]byte, error) { - if err := j.sign(keys...); err != nil { - return nil, err - } - return json.Marshal(struct { - Payload rawBase64 `json:"payload"` - Signatures []sigHead `json:"signatures"` - }{ - Payload: j.plcache, - Signatures: j.sb, - }) -} - -// Compact serializes the JWS into its "compact" form per -// https://tools.ietf.org/html/rfc7515#section-7.1 -func (j *jws) Compact(key interface{}) ([]byte, error) { - if len(j.sb) < 1 { - return nil, ErrNotEnoughMethods - } - - if err := j.sign(key); err != nil { - return nil, err - } - - sig, err := j.sb[0].Signature.Base64() - if err != nil { - return nil, err - } - return format( - j.sb[0].Protected, - j.plcache, - sig, - ), nil -} - -// sign signs each index of j's sb member. -func (j *jws) sign(keys ...interface{}) error { - if err := j.cache(); err != nil { - return err - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(j.sb)) - for i := range keys { - keys[i] = k - } - } - - for i := range j.sb { - if err := j.sb[i].cache(); err != nil { - return err - } - - raw := format(j.sb[i].Protected, j.plcache) - sig, err := j.sb[i].method.Sign(raw, keys[i]) - if err != nil { - return err - } - j.sb[i].Signature = sig - } - - return nil -} - -// cache marshals the payload, but only if it's changed since the last cache. -func (j *jws) cache() (err error) { - if !j.clean { - j.plcache, err = j.payload.Base64() - j.clean = err == nil - } - return err -} - -// cache marshals the protected and unprotected headers, but only if -// they've changed since their last cache. -func (s *sigHead) cache() (err error) { - if !s.clean { - s.Protected, err = s.protected.Base64() - if err != nil { - return err - } - s.Unprotected, err = s.unprotected.Base64() - if err != nil { - return err - } - } - s.clean = true - return nil -} - -// format formats a slice of bytes in the order given, joining -// them with a period. -func format(a ...[]byte) []byte { - return bytes.Join(a, []byte{'.'}) -} diff --git a/vendor/github.com/briankassouf/jose/jws/jws_validate.go b/vendor/github.com/briankassouf/jose/jws/jws_validate.go deleted file mode 100644 index 290404740..000000000 --- a/vendor/github.com/briankassouf/jose/jws/jws_validate.go +++ /dev/null @@ -1,203 +0,0 @@ -package jws - -import ( - "fmt" - - "github.com/briankassouf/jose/crypto" -) - -// VerifyCallback is a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -type VerifyCallback func(JWS) ([]interface{}, error) - -// VerifyCallback validates the current JWS' signature as-is. It -// accepts a callback function that can be used to access header -// parameters to lookup needed information. For example, looking -// up the "kid" parameter. -// The return slice must be a slice of keys used in the verification -// of the JWS. -func (j *jws) VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error { - keys, err := fn(j) - if err != nil { - return err - } - return j.VerifyMulti(keys, methods, o) -} - -// IsMultiError returns true if the given error is type *MultiError. -func IsMultiError(err error) bool { - _, ok := err.(*MultiError) - return ok -} - -// MultiError is a slice of errors. -type MultiError []error - -// Errors implements the error interface. -func (m *MultiError) Error() string { - var s string - var n int - for _, err := range *m { - if err != nil { - if n == 0 { - s = err.Error() - } - n++ - } - } - switch n { - case 0: - return "" - case 1: - return s - case 2: - return s + " and 1 other error" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} - -// Any means any of the JWS signatures need to verify. -// Refer to verifyMulti for more information. -const Any int = 0 - -// VerifyMulti verifies the current JWS as-is. Since it's meant to be -// called after parsing a stream of bytes into a JWS, it doesn't do any -// internal parsing like the Sign, Flat, Compact, or General methods do. -func (j *jws) VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error { - - // Catch a simple mistake. Parameter o is irrelevant in this scenario. - if len(keys) == 1 && - len(methods) == 1 && - len(j.sb) == 1 { - return j.Verify(keys[0], methods[0]) - } - - if len(j.sb) != len(methods) { - return ErrNotEnoughMethods - } - - if len(keys) < 1 || - len(keys) > 1 && len(keys) != len(j.sb) { - return ErrNotEnoughKeys - } - - // TODO do this better. - if len(keys) == 1 { - k := keys[0] - keys = make([]interface{}, len(methods)) - for i := range keys { - keys[i] = k - } - } - - var o2 SigningOpts - if o == nil { - o = new(SigningOpts) - } - - var m MultiError - for i := range j.sb { - err := j.sb[i].verify(j.plcache, keys[i], methods[i]) - if err != nil { - m = append(m, err) - } else { - o2.Inc() - if o.Needs(i) { - o.ptr++ - o2.Append(i) - } - } - } - - err := o.Validate(&o2) - if err != nil { - m = append(m, err) - } - if len(m) == 0 { - return nil - } - return &m -} - -// SigningOpts is a struct which holds options for validating -// JWS signatures. -// Number represents the cumulative which signatures need to verify -// in order for the JWS to be considered valid. -// Leave 'Number' empty or set it to the constant 'Any' if any number of -// valid signatures (greater than one) should verify the JWS. -// -// Use the indices of the signatures that need to verify in order -// for the JWS to be considered valid if specific signatures need -// to verify in order for the JWS to be considered valid. -// -// Note: -// The JWS spec requires *at least* one -// signature to verify in order for the JWS to be considered valid. -type SigningOpts struct { - // Minimum of signatures which need to verify. - Number int - - // Indices of specific signatures which need to verify. - Indices []int - ptr int - - _ struct{} -} - -// Append appends x to s' Indices member. -func (s *SigningOpts) Append(x int) { - s.Indices = append(s.Indices, x) -} - -// Needs returns true if x resides inside s' Indices member -// for the given index. It's used to match two SigningOpts Indices members. -func (s *SigningOpts) Needs(x int) bool { - return s.ptr < len(s.Indices) && s.Indices[s.ptr] == x -} - -// Inc increments s' Number member by one. -func (s *SigningOpts) Inc() { s.Number++ } - -// Validate returns any errors found while validating the -// provided SigningOpts. The receiver validates |have|. -// It'll return an error if the passed SigningOpts' Number member is less -// than s' or if the passed SigningOpts' Indices slice isn't equal to s'. -func (s *SigningOpts) Validate(have *SigningOpts) error { - if have.Number < s.Number || - (s.Indices != nil && - !eq(s.Indices, have.Indices)) { - return ErrNotEnoughValidSignatures - } - return nil -} - -func eq(a, b []int) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -// Verify verifies the current JWS as-is. Refer to verifyMulti -// for more information. -func (j *jws) Verify(key interface{}, method crypto.SigningMethod) error { - if len(j.sb) < 1 { - return ErrCannotValidate - } - return j.sb[0].verify(j.plcache, key, method) -} - -func (s *sigHead) verify(pl []byte, key interface{}, method crypto.SigningMethod) error { - if s.method.Alg() != method.Alg() || s.method.Hasher() != method.Hasher() { - return ErrMismatchedAlgorithms - } - return method.Verify(format(s.Protected, pl), s.Signature, key) -} diff --git a/vendor/github.com/briankassouf/jose/jws/jwt.go b/vendor/github.com/briankassouf/jose/jws/jwt.go deleted file mode 100644 index c09fb83ea..000000000 --- a/vendor/github.com/briankassouf/jose/jws/jwt.go +++ /dev/null @@ -1,115 +0,0 @@ -package jws - -import ( - "net/http" - "time" - - "github.com/briankassouf/jose" - "github.com/briankassouf/jose/crypto" - "github.com/briankassouf/jose/jwt" -) - -// NewJWT creates a new JWT with the given claims. -func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT { - j, ok := New(claims, method).(*jws) - if !ok { - panic("jws.NewJWT: runtime panic: New(...).(*jws) != true") - } - j.sb[0].protected.Set("typ", "JWT") - j.isJWT = true - return j -} - -// Serialize helps implements jwt.JWT. -func (j *jws) Serialize(key interface{}) ([]byte, error) { - if j.isJWT { - return j.Compact(key) - } - return nil, ErrIsNotJWT -} - -// Claims helps implements jwt.JWT. -func (j *jws) Claims() jwt.Claims { - if j.isJWT { - if c, ok := j.payload.v.(Claims); ok { - return jwt.Claims(c) - } - } - return nil -} - -// ParseJWTFromRequest tries to find the JWT in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -func ParseJWTFromRequest(req *http.Request) (jwt.JWT, error) { - if b, ok := fromHeader(req); ok { - return ParseJWT(b) - } - if b, ok := fromForm(req); ok { - return ParseJWT(b) - } - return nil, ErrNoTokenInRequest -} - -// ParseJWT parses a serialized jwt.JWT into a physical jwt.JWT. -// If its payload isn't a set of claims (or able to be coerced into -// a set of claims) it'll return an error stating the -// JWT isn't a JWT. -func ParseJWT(encoded []byte) (jwt.JWT, error) { - t, err := parseCompact(encoded, true) - if err != nil { - return nil, err - } - c, ok := t.Payload().(map[string]interface{}) - if !ok { - return nil, ErrIsNotJWT - } - t.SetPayload(Claims(c)) - return t, nil -} - -// IsJWT returns true if the JWS is a JWT. -func (j *jws) IsJWT() bool { - return j.isJWT -} - -func (j *jws) Validate(key interface{}, m crypto.SigningMethod, v ...*jwt.Validator) error { - if j.isJWT { - if err := j.Verify(key, m); err != nil { - return err - } - var v1 jwt.Validator - if len(v) > 0 { - v1 = *v[0] - } - c, ok := j.payload.v.(Claims) - if ok { - if err := v1.Validate(j); err != nil { - return err - } - return jwt.Claims(c).Validate(jose.Now(), v1.EXP, v1.NBF) - } - } - return ErrIsNotJWT -} - -// Conv converts a func(Claims) error to type jwt.ValidateFunc. -func Conv(fn func(Claims) error) jwt.ValidateFunc { - if fn == nil { - return nil - } - return func(c jwt.Claims) error { - return fn(Claims(c)) - } -} - -// NewValidator returns a jwt.Validator. -func NewValidator(c Claims, exp, nbf time.Duration, fn func(Claims) error) *jwt.Validator { - return &jwt.Validator{ - Expected: jwt.Claims(c), - EXP: exp, - NBF: nbf, - Fn: Conv(fn), - } -} - -var _ jwt.JWT = (*jws)(nil) diff --git a/vendor/github.com/briankassouf/jose/jws/payload.go b/vendor/github.com/briankassouf/jose/jws/payload.go deleted file mode 100644 index 0a326b5ce..000000000 --- a/vendor/github.com/briankassouf/jose/jws/payload.go +++ /dev/null @@ -1,52 +0,0 @@ -package jws - -import ( - "encoding/json" - - "github.com/briankassouf/jose" -) - -// payload represents the payload of a JWS. -type payload struct { - v interface{} - u json.Unmarshaler - _ struct{} -} - -// MarshalJSON implements json.Marshaler for payload. -func (p *payload) MarshalJSON() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.EncodeEscape(b), nil -} - -// Base64 implements jose.Encoder. -func (p *payload) Base64() ([]byte, error) { - b, err := json.Marshal(p.v) - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// MarshalJSON implements json.Unmarshaler for payload. -func (p *payload) UnmarshalJSON(b []byte) error { - b2, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - if p.u != nil { - err := p.u.UnmarshalJSON(b2) - p.v = p.u - return err - } - return json.Unmarshal(b2, &p.v) -} - -var ( - _ json.Marshaler = (*payload)(nil) - _ json.Unmarshaler = (*payload)(nil) - _ jose.Encoder = (*payload)(nil) -) diff --git a/vendor/github.com/briankassouf/jose/jws/rawbase64.go b/vendor/github.com/briankassouf/jose/jws/rawbase64.go deleted file mode 100644 index f2c406048..000000000 --- a/vendor/github.com/briankassouf/jose/jws/rawbase64.go +++ /dev/null @@ -1,28 +0,0 @@ -package jws - -import "encoding/json" - -type rawBase64 []byte - -// MarshalJSON implements json.Marshaler for rawBase64. -func (r rawBase64) MarshalJSON() ([]byte, error) { - buf := make([]byte, len(r)+2) - buf[0] = '"' - copy(buf[1:], r) - buf[len(buf)-1] = '"' - return buf, nil -} - -// MarshalJSON implements json.Unmarshaler for rawBase64. -func (r *rawBase64) UnmarshalJSON(b []byte) error { - if len(b) > 1 && b[0] == '"' && b[len(b)-1] == '"' { - b = b[1 : len(b)-1] - } - *r = rawBase64(b) - return nil -} - -var ( - _ json.Marshaler = (rawBase64)(nil) - _ json.Unmarshaler = (*rawBase64)(nil) -) diff --git a/vendor/github.com/briankassouf/jose/jws/signing_methods.go b/vendor/github.com/briankassouf/jose/jws/signing_methods.go deleted file mode 100644 index 9fc04c7e9..000000000 --- a/vendor/github.com/briankassouf/jose/jws/signing_methods.go +++ /dev/null @@ -1,63 +0,0 @@ -package jws - -import ( - "sync" - - "github.com/briankassouf/jose/crypto" -) - -var ( - mu sync.RWMutex - - signingMethods = map[string]crypto.SigningMethod{ - crypto.SigningMethodES256.Alg(): crypto.SigningMethodES256, - crypto.SigningMethodES384.Alg(): crypto.SigningMethodES384, - crypto.SigningMethodES512.Alg(): crypto.SigningMethodES512, - - crypto.SigningMethodPS256.Alg(): crypto.SigningMethodPS256, - crypto.SigningMethodPS384.Alg(): crypto.SigningMethodPS384, - crypto.SigningMethodPS512.Alg(): crypto.SigningMethodPS512, - - crypto.SigningMethodRS256.Alg(): crypto.SigningMethodRS256, - crypto.SigningMethodRS384.Alg(): crypto.SigningMethodRS384, - crypto.SigningMethodRS512.Alg(): crypto.SigningMethodRS512, - - crypto.SigningMethodHS256.Alg(): crypto.SigningMethodHS256, - crypto.SigningMethodHS384.Alg(): crypto.SigningMethodHS384, - crypto.SigningMethodHS512.Alg(): crypto.SigningMethodHS512, - - crypto.Unsecured.Alg(): crypto.Unsecured, - } -) - -// RegisterSigningMethod registers the crypto.SigningMethod in the global map. -// This is typically done inside the caller's init function. -func RegisterSigningMethod(sm crypto.SigningMethod) { - alg := sm.Alg() - if GetSigningMethod(alg) != nil { - panic("jose/jws: cannot duplicate signing methods") - } - - if !sm.Hasher().Available() { - panic("jose/jws: specific hash is unavailable") - } - - mu.Lock() - signingMethods[alg] = sm - mu.Unlock() -} - -// RemoveSigningMethod removes the crypto.SigningMethod from the global map. -func RemoveSigningMethod(sm crypto.SigningMethod) { - mu.Lock() - delete(signingMethods, sm.Alg()) - mu.Unlock() -} - -// GetSigningMethod retrieves a crypto.SigningMethod from the global map. -func GetSigningMethod(alg string) (method crypto.SigningMethod) { - mu.RLock() - method = signingMethods[alg] - mu.RUnlock() - return method -} diff --git a/vendor/github.com/briankassouf/jose/jwt/claims.go b/vendor/github.com/briankassouf/jose/jwt/claims.go deleted file mode 100644 index 9a0311305..000000000 --- a/vendor/github.com/briankassouf/jose/jwt/claims.go +++ /dev/null @@ -1,274 +0,0 @@ -package jwt - -import ( - "encoding/json" - "time" - - "github.com/briankassouf/jose" -) - -// Claims implements a set of JOSE Claims with the addition of some helper -// methods, similar to net/url.Values. -type Claims map[string]interface{} - -// Validate validates the Claims per the claims found in -// https://tools.ietf.org/html/rfc7519#section-4.1 -func (c Claims) Validate(now time.Time, expLeeway, nbfLeeway time.Duration) error { - if exp, ok := c.Expiration(); ok { - if now.After(exp.Add(expLeeway)) { - return ErrTokenIsExpired - } - } - - if nbf, ok := c.NotBefore(); ok { - if !now.After(nbf.Add(-nbfLeeway)) { - return ErrTokenNotYetValid - } - } - return nil -} - -// Get retrieves the value corresponding with key from the Claims. -func (c Claims) Get(key string) interface{} { - if c == nil { - return nil - } - return c[key] -} - -// Set sets Claims[key] = val. It'll overwrite without warning. -func (c Claims) Set(key string, val interface{}) { - c[key] = val -} - -// Del removes the value that corresponds with key from the Claims. -func (c Claims) Del(key string) { - delete(c, key) -} - -// Has returns true if a value for the given key exists inside the Claims. -func (c Claims) Has(key string) bool { - _, ok := c[key] - return ok -} - -// MarshalJSON implements json.Marshaler for Claims. -func (c Claims) MarshalJSON() ([]byte, error) { - if c == nil || len(c) == 0 { - return nil, nil - } - return json.Marshal(map[string]interface{}(c)) -} - -// Base64 implements the jose.Encoder interface. -func (c Claims) Base64() ([]byte, error) { - b, err := c.MarshalJSON() - if err != nil { - return nil, err - } - return jose.Base64Encode(b), nil -} - -// UnmarshalJSON implements json.Unmarshaler for Claims. -func (c *Claims) UnmarshalJSON(b []byte) error { - if b == nil { - return nil - } - - b, err := jose.DecodeEscaped(b) - if err != nil { - return err - } - - // Since json.Unmarshal calls UnmarshalJSON, - // calling json.Unmarshal on *p would be infinitely recursive - // A temp variable is needed because &map[string]interface{}(*p) is - // invalid Go. (Address of unaddressable object and all that...) - - tmp := map[string]interface{}(*c) - if err = json.Unmarshal(b, &tmp); err != nil { - return err - } - *c = Claims(tmp) - return nil -} - -// Issuer retrieves claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) Issuer() (string, bool) { - v, ok := c.Get("iss").(string) - return v, ok -} - -// Subject retrieves claim "sub" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) Subject() (string, bool) { - v, ok := c.Get("sub").(string) - return v, ok -} - -// Audience retrieves claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) Audience() ([]string, bool) { - // Audience claim must be stringy. That is, it may be one string - // or multiple strings but it should not be anything else. E.g. an int. - switch t := c.Get("aud").(type) { - case string: - return []string{t}, true - case []string: - return t, true - case []interface{}: - return stringify(t...) - case interface{}: - return stringify(t) - } - return nil, false -} - -func stringify(a ...interface{}) ([]string, bool) { - if len(a) == 0 { - return nil, false - } - - s := make([]string, len(a)) - for i := range a { - str, ok := a[i].(string) - if !ok { - return nil, false - } - s[i] = str - } - return s, true -} - -// Expiration retrieves claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) Expiration() (time.Time, bool) { - return c.GetTime("exp") -} - -// NotBefore retrieves claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) NotBefore() (time.Time, bool) { - return c.GetTime("nbf") -} - -// IssuedAt retrieves claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) IssuedAt() (time.Time, bool) { - return c.GetTime("iat") -} - -// JWTID retrieves claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) JWTID() (string, bool) { - v, ok := c.Get("jti").(string) - return v, ok -} - -// RemoveIssuer deletes claim "iss" from c. -func (c Claims) RemoveIssuer() { c.Del("iss") } - -// RemoveSubject deletes claim "sub" from c. -func (c Claims) RemoveSubject() { c.Del("sub") } - -// RemoveAudience deletes claim "aud" from c. -func (c Claims) RemoveAudience() { c.Del("aud") } - -// RemoveExpiration deletes claim "exp" from c. -func (c Claims) RemoveExpiration() { c.Del("exp") } - -// RemoveNotBefore deletes claim "nbf" from c. -func (c Claims) RemoveNotBefore() { c.Del("nbf") } - -// RemoveIssuedAt deletes claim "iat" from c. -func (c Claims) RemoveIssuedAt() { c.Del("iat") } - -// RemoveJWTID deletes claim "jti" from c. -func (c Claims) RemoveJWTID() { c.Del("jti") } - -// SetIssuer sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (c Claims) SetIssuer(issuer string) { - c.Set("iss", issuer) -} - -// SetSubject sets claim "iss" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (c Claims) SetSubject(subject string) { - c.Set("sub", subject) -} - -// SetAudience sets claim "aud" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (c Claims) SetAudience(audience ...string) { - if len(audience) == 1 { - c.Set("aud", audience[0]) - } else { - c.Set("aud", audience) - } -} - -// SetExpiration sets claim "exp" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (c Claims) SetExpiration(expiration time.Time) { - c.SetTime("exp", expiration) -} - -// SetNotBefore sets claim "nbf" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (c Claims) SetNotBefore(notBefore time.Time) { - c.SetTime("nbf", notBefore) -} - -// SetIssuedAt sets claim "iat" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (c Claims) SetIssuedAt(issuedAt time.Time) { - c.SetTime("iat", issuedAt) -} - -// SetJWTID sets claim "jti" per its type in -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (c Claims) SetJWTID(uniqueID string) { - c.Set("jti", uniqueID) -} - -// GetTime returns a Unix timestamp for the given key. -// -// It converts an int, int32, int64, uint, uint32, uint64 or float64 into a Unix -// timestamp (epoch seconds). float32 does not have sufficient precision to -// store a Unix timestamp. -// -// Numeric values parsed from JSON will always be stored as float64 since -// Claims is a map[string]interface{}. However, the values may be stored directly -// in the claims as a different type. -func (c Claims) GetTime(key string) (time.Time, bool) { - switch t := c.Get(key).(type) { - case int: - return time.Unix(int64(t), 0), true - case int32: - return time.Unix(int64(t), 0), true - case int64: - return time.Unix(int64(t), 0), true - case uint: - return time.Unix(int64(t), 0), true - case uint32: - return time.Unix(int64(t), 0), true - case uint64: - return time.Unix(int64(t), 0), true - case float64: - return time.Unix(int64(t), 0), true - default: - return time.Time{}, false - } -} - -// SetTime stores a UNIX time for the given key. -func (c Claims) SetTime(key string, t time.Time) { - c.Set(key, t.Unix()) -} - -var ( - _ json.Marshaler = (Claims)(nil) - _ json.Unmarshaler = (*Claims)(nil) -) diff --git a/vendor/github.com/briankassouf/jose/jwt/doc.go b/vendor/github.com/briankassouf/jose/jwt/doc.go deleted file mode 100644 index 6004d0fa9..000000000 --- a/vendor/github.com/briankassouf/jose/jwt/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jwt implements JWTs per RFC 7519 -package jwt diff --git a/vendor/github.com/briankassouf/jose/jwt/eq.go b/vendor/github.com/briankassouf/jose/jwt/eq.go deleted file mode 100644 index 3113269fb..000000000 --- a/vendor/github.com/briankassouf/jose/jwt/eq.go +++ /dev/null @@ -1,47 +0,0 @@ -package jwt - -func verifyPrincipals(pcpls, auds []string) bool { - // "Each principal intended to process the JWT MUST - // identify itself with a value in the audience claim." - // - https://tools.ietf.org/html/rfc7519#section-4.1.3 - - found := -1 - for i, p := range pcpls { - for _, v := range auds { - if p == v { - found++ - break - } - } - if found != i { - return false - } - } - return true -} - -// ValidAudience returns true iff: -// - a and b are strings and a == b -// - a is string, b is []string and a is in b -// - a is []string, b is []string and all of a is in b -// - a is []string, b is string and len(a) == 1 and a[0] == b -func ValidAudience(a, b interface{}) bool { - s1, ok := a.(string) - if ok { - if s2, ok := b.(string); ok { - return s1 == s2 - } - a2, ok := b.([]string) - return ok && verifyPrincipals([]string{s1}, a2) - } - - a1, ok := a.([]string) - if !ok { - return false - } - if a2, ok := b.([]string); ok { - return verifyPrincipals(a1, a2) - } - s2, ok := b.(string) - return ok && len(a1) == 1 && a1[0] == s2 -} diff --git a/vendor/github.com/briankassouf/jose/jwt/errors.go b/vendor/github.com/briankassouf/jose/jwt/errors.go deleted file mode 100644 index 96b240d54..000000000 --- a/vendor/github.com/briankassouf/jose/jwt/errors.go +++ /dev/null @@ -1,28 +0,0 @@ -package jwt - -import "errors" - -var ( - // ErrTokenIsExpired is return when time.Now().Unix() is after - // the token's "exp" claim. - ErrTokenIsExpired = errors.New("token is expired") - - // ErrTokenNotYetValid is return when time.Now().Unix() is before - // the token's "nbf" claim. - ErrTokenNotYetValid = errors.New("token is not yet valid") - - // ErrInvalidISSClaim means the "iss" claim is invalid. - ErrInvalidISSClaim = errors.New("claim \"iss\" is invalid") - - // ErrInvalidSUBClaim means the "sub" claim is invalid. - ErrInvalidSUBClaim = errors.New("claim \"sub\" is invalid") - - // ErrInvalidIATClaim means the "iat" claim is invalid. - ErrInvalidIATClaim = errors.New("claim \"iat\" is invalid") - - // ErrInvalidJTIClaim means the "jti" claim is invalid. - ErrInvalidJTIClaim = errors.New("claim \"jti\" is invalid") - - // ErrInvalidAUDClaim means the "aud" claim is invalid. - ErrInvalidAUDClaim = errors.New("claim \"aud\" is invalid") -) diff --git a/vendor/github.com/briankassouf/jose/jwt/jwt.go b/vendor/github.com/briankassouf/jose/jwt/jwt.go deleted file mode 100644 index 691df58ac..000000000 --- a/vendor/github.com/briankassouf/jose/jwt/jwt.go +++ /dev/null @@ -1,144 +0,0 @@ -package jwt - -import ( - "time" - - "github.com/briankassouf/jose/crypto" -) - -// JWT represents a JWT per RFC 7519. -// It's described as an interface instead of a physical structure -// because both JWS and JWEs can be JWTs. So, in order to use either, -// import one of those two packages and use their "NewJWT" (and other) -// functions. -type JWT interface { - // Claims returns the set of Claims. - Claims() Claims - - // Validate returns an error describing any issues found while - // validating the JWT. For info on the fn parameter, see the - // comment on ValidateFunc. - Validate(key interface{}, method crypto.SigningMethod, v ...*Validator) error - - // Serialize serializes the JWT into its on-the-wire - // representation. - Serialize(key interface{}) ([]byte, error) -} - -// ValidateFunc is a function that provides access to the JWT -// and allows for custom validation. Keep in mind that the Verify -// methods in the JWS/JWE sibling packages call ValidateFunc *after* -// validating the JWS/JWE, but *before* any validation per the JWT -// RFC. Therefore, the ValidateFunc can be used to short-circuit -// verification, but cannot be used to circumvent the RFC. -// Custom JWT implementations are free to abuse this, but it is -// not recommended. -type ValidateFunc func(Claims) error - -// Validator represents some of the validation options. -type Validator struct { - Expected Claims // If non-nil, these are required to match. - EXP time.Duration // EXPLeeway - NBF time.Duration // NBFLeeway - Fn ValidateFunc // See ValidateFunc for more information. - - _ struct{} // Require explicitly-named struct fields. -} - -// Validate validates the JWT based on the expected claims in v. -// Note: it only validates the registered claims per -// https://tools.ietf.org/html/rfc7519#section-4.1 -// -// Custom claims should be validated using v's Fn member. -func (v *Validator) Validate(j JWT) error { - if iss, ok := v.Expected.Issuer(); ok && - j.Claims().Get("iss") != iss { - return ErrInvalidISSClaim - } - if sub, ok := v.Expected.Subject(); ok && - j.Claims().Get("sub") != sub { - return ErrInvalidSUBClaim - } - if iat, ok := v.Expected.IssuedAt(); ok { - if t, ok := j.Claims().GetTime("iat"); !t.Equal(iat) || !ok { - return ErrInvalidIATClaim - } - } - if jti, ok := v.Expected.JWTID(); ok && - j.Claims().Get("jti") != jti { - return ErrInvalidJTIClaim - } - - if aud, ok := v.Expected.Audience(); ok { - aud2, ok := j.Claims().Audience() - if !ok || !ValidAudience(aud, aud2) { - return ErrInvalidAUDClaim - } - } - - if v.Fn != nil { - return v.Fn(j.Claims()) - } - return nil -} - -// SetClaim sets the claim with the given val. -func (v *Validator) SetClaim(claim string, val interface{}) { - v.expect() - v.Expected.Set(claim, val) -} - -// SetIssuer sets the "iss" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.1 -func (v *Validator) SetIssuer(iss string) { - v.expect() - v.Expected.Set("iss", iss) -} - -// SetSubject sets the "sub" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.2 -func (v *Validator) SetSubject(sub string) { - v.expect() - v.Expected.Set("sub", sub) -} - -// SetAudience sets the "aud" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.3 -func (v *Validator) SetAudience(aud string) { - v.expect() - v.Expected.Set("aud", aud) -} - -// SetExpiration sets the "exp" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.4 -func (v *Validator) SetExpiration(exp time.Time) { - v.expect() - v.Expected.Set("exp", exp) -} - -// SetNotBefore sets the "nbf" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.5 -func (v *Validator) SetNotBefore(nbf time.Time) { - v.expect() - v.Expected.Set("nbf", nbf) -} - -// SetIssuedAt sets the "iat" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.6 -func (v *Validator) SetIssuedAt(iat time.Time) { - v.expect() - v.Expected.Set("iat", iat) -} - -// SetJWTID sets the "jti" claim per -// https://tools.ietf.org/html/rfc7519#section-4.1.7 -func (v *Validator) SetJWTID(jti string) { - v.expect() - v.Expected.Set("jti", jti) -} - -func (v *Validator) expect() { - if v.Expected == nil { - v.Expected = make(Claims) - } -} diff --git a/vendor/github.com/chrismalek/oktasdk-go/LICENSE.txt b/vendor/github.com/chrismalek/oktasdk-go/LICENSE.txt deleted file mode 100644 index 63b4b681c..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) [year] [fullname] - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/chrismalek/oktasdk-go/okta/apps.go b/vendor/github.com/chrismalek/oktasdk-go/okta/apps.go deleted file mode 100644 index 1fe8007bc..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/okta/apps.go +++ /dev/null @@ -1,315 +0,0 @@ -package okta - -import ( - "fmt" - "net/url" - "time" -) - -// AppsService is a service to retreives applications from OKTA. -type AppsService service - -// AppFilterOptions is used to generate a "Filter" to search for different Apps -// The values here coorelate to API Search paramgters on the group API -type AppFilterOptions struct { - NextURL *url.URL `url:"-"` - GetAllPages bool `url:"-"` - NumberOfPages int `url:"-"` - Limit int `url:"limit,omitempty"` -} - -// App is the Model for an OKTA Application -type App struct { - ID string `json:"id"` - Name string `json:"name"` - Label string `json:"label"` - Status string `json:"status"` - LastUpdated time.Time `json:"lastUpdated"` - Created time.Time `json:"created"` - Accessibility struct { - SelfService bool `json:"selfService"` - ErrorRedirectURL interface{} `json:"errorRedirectUrl"` - LoginRedirectURL interface{} `json:"loginRedirectUrl"` - } `json:"accessibility"` - Visibility struct { - AutoSubmitToolbar bool `json:"autoSubmitToolbar"` - Hide struct { - IOS bool `json:"iOS"` - Web bool `json:"web"` - } `json:"hide"` - AppLinks struct { - TestorgoneCustomsaml20App1Link bool `json:"testorgone_customsaml20app_1_link"` - } `json:"appLinks"` - } `json:"visibility"` - Features []interface{} `json:"features"` - SignOnMode string `json:"signOnMode"` - Credentials struct { - UserNameTemplate struct { - Template string `json:"template"` - Type string `json:"type"` - } `json:"userNameTemplate"` - Signing struct { - } `json:"signing"` - } `json:"credentials"` - Settings struct { - App struct { - } `json:"app"` - Notifications struct { - Vpn struct { - Network struct { - Connection string `json:"connection"` - } `json:"network"` - Message interface{} `json:"message"` - HelpURL interface{} `json:"helpUrl"` - } `json:"vpn"` - } `json:"notifications"` - SignOn struct { - DefaultRelayState string `json:"defaultRelayState"` - SsoAcsURL string `json:"ssoAcsUrl"` - IdpIssuer string `json:"idpIssuer"` - Audience string `json:"audience"` - Recipient string `json:"recipient"` - Destination string `json:"destination"` - SubjectNameIDTemplate string `json:"subjectNameIdTemplate"` - SubjectNameIDFormat string `json:"subjectNameIdFormat"` - ResponseSigned bool `json:"responseSigned"` - AssertionSigned bool `json:"assertionSigned"` - SignatureAlgorithm string `json:"signatureAlgorithm"` - DigestAlgorithm string `json:"digestAlgorithm"` - HonorForceAuthn bool `json:"honorForceAuthn"` - AuthnContextClassRef string `json:"authnContextClassRef"` - SpIssuer interface{} `json:"spIssuer"` - RequestCompressed bool `json:"requestCompressed"` - AttributeStatements []interface{} `json:"attributeStatements"` - } `json:"signOn"` - } `json:"settings"` - Links struct { - Logo []struct { - Name string `json:"name"` - Href string `json:"href"` - Type string `json:"type"` - } `json:"logo"` - AppLinks []struct { - Name string `json:"name"` - Href string `json:"href"` - Type string `json:"type"` - } `json:"appLinks"` - Help struct { - Href string `json:"href"` - Type string `json:"type"` - } `json:"help"` - Users struct { - Href string `json:"href"` - } `json:"users"` - Deactivate struct { - Href string `json:"href"` - } `json:"deactivate"` - Groups struct { - Href string `json:"href"` - } `json:"groups"` - Metadata struct { - Href string `json:"href"` - Type string `json:"type"` - } `json:"metadata"` - } `json:"_links"` -} - -func (a App) String() string { - // return Stringify(g) - return fmt.Sprintf("App:(ID: {%v} - Name: {%v})\n", a.ID, a.Name) -} - -// GetByID gets a group from OKTA by the Gropu ID. An error is returned if the group is not found -func (a *AppsService) GetByID(appID string) (*App, *Response, error) { - - u := fmt.Sprintf("apps/%v", appID) - req, err := a.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, nil, err - } - - app := new(App) - - resp, err := a.client.Do(req, app) - - if err != nil { - return nil, resp, err - } - - return app, resp, err -} - -// AppUser is the model for a user of an OKTA App -type AppUser struct { - ID string `json:"id"` - ExternalID string `json:"externalId"` - Created time.Time `json:"created"` - LastUpdated time.Time `json:"lastUpdated"` - Scope string `json:"scope"` - Status string `json:"status"` - StatusChanged *time.Time `json:"statusChanged"` - PasswordChanged *time.Time `json:"passwordChanged"` - SyncState string `json:"syncState"` - LastSync *time.Time `json:"lastSync"` - Credentials struct { - UserName string `json:"userName"` - Password struct { - } `json:"password"` - } `json:"credentials"` - Profile struct { - SecondEmail interface{} `json:"secondEmail"` - LastName string `json:"lastName"` - MobilePhone interface{} `json:"mobilePhone"` - Email string `json:"email"` - SalesforceGroups []string `json:"salesforceGroups"` - Role string `json:"role"` - FirstName string `json:"firstName"` - Profile string `json:"profile"` - } `json:"profile"` - Links struct { - App struct { - Href string `json:"href"` - } `json:"app"` - User struct { - Href string `json:"href"` - } `json:"user"` - } `json:"_links"` -} - -// GetUsers returns the members in an App -// Pass in an optional AppFilterOptions struct to filter the results -// The Users in the app are returned -func (a *AppsService) GetUsers(appID string, opt *AppFilterOptions) (appUsers []AppUser, resp *Response, err error) { - - pagesRetreived := 0 - var u string - if opt.NextURL != nil { - u = opt.NextURL.String() - } else { - u = fmt.Sprintf("apps/%v/users", appID) - - if opt.Limit == 0 { - opt.Limit = defaultLimit - } - - u, _ = addOptions(u, opt) - } - - req, err := a.client.NewRequest("GET", u, nil) - - if err != nil { - // fmt.Printf("____ERROR HERE\n") - return nil, nil, err - } - resp, err = a.client.Do(req, &appUsers) - - if err != nil { - // fmt.Printf("____ERROR HERE 2\n") - return nil, resp, err - } - - pagesRetreived++ - - if (opt.NumberOfPages > 0 && pagesRetreived < opt.NumberOfPages) || opt.GetAllPages { - - for { - - if pagesRetreived == opt.NumberOfPages { - break - } - if resp.NextURL != nil { - - var userPage []AppUser - pageOpts := new(AppFilterOptions) - pageOpts.NextURL = resp.NextURL - pageOpts.Limit = opt.Limit - pageOpts.NumberOfPages = 1 - - userPage, resp, err = a.GetUsers(appID, pageOpts) - - if err != nil { - return appUsers, resp, err - } - appUsers = append(appUsers, userPage...) - pagesRetreived++ - } else { - break - } - - } - } - - return appUsers, resp, err -} - -// AppGroups - Groups assigned to Application -type AppGroups struct { - ID string `json:"id"` - LastUpdated time.Time `json:"lastUpdated"` - Priority int `json:"priority"` - Links struct { - User struct { - Href string `json:"href"` - } `json:"user"` - } `json:"_links"` -} - -// GetGroups returns groups assigned to the application - Input appID is the Application GUID -func (a *AppsService) GetGroups(appID string) (appGroups []AppGroups, resp *Response, err error) { - - var u string - u = fmt.Sprintf("apps/%v/groups", appID) - - req, err := a.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, nil, err - } - resp, err = a.client.Do(req, &appGroups) - - if err != nil { - return nil, resp, err - } - - for { - - if resp.NextURL != nil { - - var appGroupPage []AppGroups - - appGroupPage, resp, err = a.GetGroups(appID) - - if err != nil { - return appGroups, resp, err - } else { - appGroups = append(appGroups, appGroupPage...) - - } - } else { - break - } - - } - - return appGroups, resp, err -} - -// GetUser returns the AppUser model for one app users -func (a *AppsService) GetUser(appID string, userID string) (appUser AppUser, resp *Response, err error) { - - var u string - u = fmt.Sprintf("apps/%v/users/%v", appID, userID) - - req, err := a.client.NewRequest("GET", u, nil) - - if err != nil { - return appUser, nil, err - } - resp, err = a.client.Do(req, &appUser) - - if err != nil { - return appUser, resp, err - } - return appUser, resp, nil -} diff --git a/vendor/github.com/chrismalek/oktasdk-go/okta/factors.go b/vendor/github.com/chrismalek/oktasdk-go/okta/factors.go deleted file mode 100644 index fc926f91a..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/okta/factors.go +++ /dev/null @@ -1,8 +0,0 @@ -package okta - -const ( - // MFAStatusActive is a constant to represent OKTA User State returned by the API - MFAStatusActive = "ACTIVE" - // MFAStatusPending is a user MFA Status of NOT Active - MFAStatusPending = "PENDING_ACTIVATION" -) diff --git a/vendor/github.com/chrismalek/oktasdk-go/okta/groups.go b/vendor/github.com/chrismalek/oktasdk-go/okta/groups.go deleted file mode 100644 index 34584d6eb..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/okta/groups.go +++ /dev/null @@ -1,359 +0,0 @@ -package okta - -import ( - "errors" - "fmt" - "net/url" - "time" -) - -const ( - // GroupTypeOKTA - group type constant for an OKTA Mastered Group - GroupTypeOKTA = "OKTA_GROUP" - // GroupTypeBuiltIn - group type constant for a Built in OKTA groups - GroupTypeBuiltIn = "BUILT_IN" - // GroupTypeApp -- group type constant for app mastered group - GroupTypeApp = "APP_GROUP" - - groupTypeFilter = "type" - groupNameFilter = "q" - groupLastMembershipUpdatedFilter = "lastMembershipUpdated" - groupLastUpdatedFilter = "lastUpdated" -) - -// GroupsService handles communication with the Groups data related -// methods of the OKTA API. -type GroupsService service - -// Group represents the Group Object from the OKTA API -type Group struct { - ID string `json:"id"` - Created time.Time `json:"created"` - LastUpdated time.Time `json:"lastUpdated"` - LastMembershipUpdated time.Time `json:"lastMembershipUpdated"` - ObjectClass []string `json:"objectClass"` - Type string `json:"type"` - Profile struct { - Name string `json:"name"` - Description string `json:"description"` - SamAccountName string `json:"samAccountName"` - Dn string `json:"dn"` - WindowsDomainQualifiedName string `json:"windowsDomainQualifiedName"` - ExternalID string `json:"externalId"` - } `json:"profile"` - Links struct { - Logo []struct { - Name string `json:"name"` - Href string `json:"href"` - Type string `json:"type"` - } `json:"logo"` - Users struct { - Href string `json:"href"` - } `json:"users"` - Apps struct { - Href string `json:"href"` - } `json:"apps"` - } `json:"_links"` -} - -// GroupFilterOptions is used to generate a "Filter" to search for different groups -// The values here coorelate to API Search paramgters on the group API -type GroupFilterOptions struct { - // This will be built by internal - may not need to export - FilterString string `url:"filter,omitempty"` - NextURL *url.URL `url:"-"` - GetAllPages bool `url:"-"` - NumberOfPages int `url:"-"` - Limit int `url:"limit,omitempty"` - - NameStartsWith string `url:"q,omitempty"` - GroupTypeEqual string `url:"-"` - - LastUpdated dateFilter `url:"-"` - LastMembershipUpdated dateFilter `url:"-"` -} - -func (g Group) String() string { - // return Stringify(g) - return fmt.Sprintf("Group:(ID: {%v} - Type: {%v} - Group Name: {%v})\n", g.ID, g.Type, g.Profile.Name) -} - -// ListWithFilter - Method to list groups with different filter options. -// Pass in a GroupFilterOptions to specify filters. Values in that struct will turn into Query parameters -func (g *GroupsService) ListWithFilter(opt *GroupFilterOptions) ([]Group, *Response, error) { - - var u string - var err error - - pagesRetreived := 0 - if opt.NextURL != nil { - u = opt.NextURL.String() - } else { - if opt.GroupTypeEqual != "" { - opt.FilterString = appendToFilterString(opt.FilterString, groupTypeFilter, FilterEqualOperator, opt.GroupTypeEqual) - } - - // if opt.NameStartsWith != "" { - // opt.FilterString = appendToFilterString(opt.FilterString, groupNameFilter, filterEqualOperator, opt.NameStartsWith) - // } - if (!opt.LastMembershipUpdated.Value.IsZero()) && (opt.LastMembershipUpdated.Operator != "") { - opt.FilterString = appendToFilterString(opt.FilterString, groupLastMembershipUpdatedFilter, opt.LastMembershipUpdated.Operator, opt.LastMembershipUpdated.Value.UTC().Format(oktaFilterTimeFormat)) - } - - if (!opt.LastUpdated.Value.IsZero()) && (opt.LastUpdated.Operator != "") { - opt.FilterString = appendToFilterString(opt.FilterString, groupLastUpdatedFilter, opt.LastUpdated.Operator, opt.LastUpdated.Value.UTC().Format(oktaFilterTimeFormat)) - } - - if opt.Limit == 0 { - opt.Limit = defaultLimit - } - u, err = addOptions("groups", opt) - if err != nil { - return nil, nil, err - } - } - - req, err := g.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - groups := make([]Group, 1) - resp, err := g.client.Do(req, &groups) - if err != nil { - return nil, resp, err - } - pagesRetreived++ - - if (opt.NumberOfPages > 0 && pagesRetreived < opt.NumberOfPages) || opt.GetAllPages { - - for { - - if pagesRetreived == opt.NumberOfPages { - break - } - if resp.NextURL != nil { - var groupPage []Group - pageOption := new(GroupFilterOptions) - pageOption.NextURL = resp.NextURL - pageOption.NumberOfPages = 1 - pageOption.Limit = opt.Limit - - groupPage, resp, err = g.ListWithFilter(pageOption) - if err != nil { - return groups, resp, err - } - groups = append(groups, groupPage...) - pagesRetreived++ - - } else { - break - } - } - } - return groups, resp, err -} - -// GetByID gets a group from OKTA by the Gropu ID. An error is returned if the group is not found -func (g *GroupsService) GetByID(groupID string) (*Group, *Response, error) { - - u := fmt.Sprintf("groups/%v", groupID) - req, err := g.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, nil, err - } - - group := new(Group) - - resp, err := g.client.Do(req, group) - - if err != nil { - return nil, resp, err - } - - return group, resp, err -} - -// GetUsers returns the members in a group -// Pass in an optional GroupFilterOptions struct to filter the results -// The Users in the group are returned -func (g *GroupsService) GetUsers(groupID string, opt *GroupUserFilterOptions) (users []User, resp *Response, err error) { - pagesRetreived := 0 - var u string - if opt.NextURL != nil { - u = opt.NextURL.String() - } else { - u = fmt.Sprintf("groups/%v/users", groupID) - - if opt.Limit == 0 { - opt.Limit = defaultLimit - } - - u, _ = addOptions(u, opt) - } - - req, err := g.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, nil, err - } - resp, err = g.client.Do(req, &users) - - if err != nil { - return nil, resp, err - } - - pagesRetreived++ - if (opt.NumberOfPages > 0 && pagesRetreived < opt.NumberOfPages) || opt.GetAllPages { - - for { - - if pagesRetreived == opt.NumberOfPages { - break - } - if resp.NextURL != nil { - - var userPage []User - pageOpts := new(GroupUserFilterOptions) - pageOpts.NextURL = resp.NextURL - pageOpts.Limit = opt.Limit - pageOpts.NumberOfPages = 1 - - userPage, resp, err = g.GetUsers(groupID, pageOpts) - if err != nil { - return users, resp, err - } - users = append(users, userPage...) - pagesRetreived++ - } else { - break - } - - } - } - - return users, resp, err -} - -// Add - Adds an OKTA Mastered Group with name and description. GroupName is required. -func (g *GroupsService) Add(groupName string, groupDescription string) (*Group, *Response, error) { - - if groupName == "" { - return nil, nil, errors.New("groupName parameter is required for ADD") - } - - newGroup := newGroup{} - newGroup.Profile.Name = groupName - newGroup.Profile.Description = groupDescription - - u := fmt.Sprintf("groups") - - req, err := g.client.NewRequest("POST", u, newGroup) - - if err != nil { - return nil, nil, err - } - - group := new(Group) - - resp, err := g.client.Do(req, group) - - if err != nil { - return nil, resp, err - } - - return group, resp, err -} - -// Delete - Deletes an OKTA Mastered Group with ID -func (g *GroupsService) Delete(groupID string) (*Response, error) { - - if groupID == "" { - return nil, errors.New("groupID parameter is required for Delete") - } - u := fmt.Sprintf("groups/%v", groupID) - - req, err := g.client.NewRequest("DELETE", u, nil) - - if err != nil { - return nil, err - } - - resp, err := g.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// AddUserToGroup - Adds a user to a group. -func (g *GroupsService) AddUserToGroup(groupID string, userID string) (*Response, error) { - - if groupID == "" { - return nil, errors.New("groupID parameter is required for Delete") - } - if userID == "" { - return nil, errors.New("groupID parameter is required for Delete") - } - - u := fmt.Sprintf("groups/%v/users/%v", groupID, userID) - - req, err := g.client.NewRequest("PUT", u, nil) - - if err != nil { - return nil, err - } - - resp, err := g.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// RemoveUserFromGroup - Removes a user to a group. -func (g *GroupsService) RemoveUserFromGroup(groupID string, userID string) (*Response, error) { - - if groupID == "" { - return nil, errors.New("groupID parameter is required for Delete") - } - if userID == "" { - return nil, errors.New("groupID parameter is required for Delete") - } - - u := fmt.Sprintf("groups/%v/users/%v", groupID, userID) - - req, err := g.client.NewRequest("DELETE", u, nil) - - if err != nil { - return nil, err - } - - resp, err := g.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// GroupUserFilterOptions is a struct that you populate which will limit or control group fetches and searches -// The values here will coorelate to the search filtering allowed in the OKTA API. These values are turned into Query Parameters -type GroupUserFilterOptions struct { - Limit int `url:"limit,omitempty"` - NextURL *url.URL `url:"-"` - GetAllPages bool `url:"-"` - NumberOfPages int `url:"-"` -} - -type newGroup struct { - Profile struct { - Name string `json:"name"` - Description string `json:"description"` - } `json:"profile"` -} diff --git a/vendor/github.com/chrismalek/oktasdk-go/okta/sdk.go b/vendor/github.com/chrismalek/oktasdk-go/okta/sdk.go deleted file mode 100644 index d8ec24d6e..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/okta/sdk.go +++ /dev/null @@ -1,523 +0,0 @@ -package okta - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "strconv" - "sync" - "time" - - "github.com/google/go-querystring/query" - - "reflect" -) - -const ( - libraryVersion = "1" - userAgent = "oktasdk-go/" + libraryVersion - productionDomain = "okta.com" - previewDomain = "oktapreview.com" - urlFormat = "https://%s.%s/api/v1/" - headerRateLimit = "X-Rate-Limit-Limit" - headerRateRemaining = "X-Rate-Limit-Remaining" - headerRateReset = "X-Rate-Limit-Reset" - headerOKTARequestID = "X-Okta-Request-Id" - headerAuthorization = "Authorization" - headerAuthorizationFormat = "SSWS %v" - mediaTypeJSON = "application/json" - defaultLimit = 50 - // FilterEqualOperator Filter Operatorid for "equal" - FilterEqualOperator = "eq" - // FilterStartsWithOperator - filter operator for "starts with" - FilterStartsWithOperator = "sw" - // FilterGreaterThanOperator - filter operator for "greater than" - FilterGreaterThanOperator = "gt" - // FilterLessThanOperator - filter operator for "less than" - FilterLessThanOperator = "lt" - - // If the API returns a "X-Rate-Limit-Remaining" header less than this the SDK will either pause - // Or throw RateLimitError depending on the client.PauseOnRateLimit value - defaultRateRemainingFloor = 100 -) - -// A Client manages communication with the API. -type Client struct { - clientMu sync.Mutex // clientMu protects the client during calls that modify the CheckRedirect func. - client *http.Client // HTTP client used to communicate with the API. - - // Base URL for API requests. - // This will be built automatically based on inputs to NewClient - // If needed you can override this if needed (your URL is not *.okta.com or *.oktapreview.com) - BaseURL *url.URL - - // User agent used when communicating with the GitHub API. - UserAgent string - - apiKey string - authorizationHeaderValue string - PauseOnRateLimit bool - - // RateRemainingFloor - If the API returns a "X-Rate-Limit-Remaining" header less than this the SDK will either pause - // Or throw RateLimitError depending on the client.PauseOnRateLimit value. It defaults to 30 - // One client doing too much work can lock out all API Access for every other client - // We are trying to be a "good API User Citizen" - RateRemainingFloor int - - rateMu sync.Mutex - mostRecentRate Rate - - Limit int - // mostRecent rateLimitCategory - - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // Services used for talking to different parts of the API. - // Service for Working with Users - Users *UsersService - - // Service for Working with Groups - Groups *GroupsService - - // Service for Working with Apps - Apps *AppsService -} - -type service struct { - client *Client -} - -// NewClient returns a new OKTA API client. If a nil httpClient is -// provided, http.DefaultClient will be used. -func NewClient(httpClient *http.Client, orgName string, apiToken string, isProduction bool) *Client { - var baseDomain string - if isProduction { - baseDomain = productionDomain - } else { - baseDomain = previewDomain - } - client, _ := NewClientWithDomain(httpClient, orgName, baseDomain, apiToken) - return client -} - -// NewClientWithDomain creates a client based on the organziation name and -// base domain for requests (okta.com, okta-emea.com, oktapreview.com, etc). -func NewClientWithDomain(httpClient *http.Client, orgName string, domain string, apiToken string) (*Client, error) { - baseURL, err := url.Parse(fmt.Sprintf(urlFormat, orgName, domain)) - if err != nil { - return nil, err - } - return NewClientWithBaseURL(httpClient, baseURL, apiToken), nil -} - -// NewClientWithBaseURL creates a client based on the full base URL and api -// token -func NewClientWithBaseURL(httpClient *http.Client, baseURL *url.URL, apiToken string) *Client { - if httpClient == nil { - httpClient = http.DefaultClient - } - - c := &Client{ - client: httpClient, - BaseURL: baseURL, - UserAgent: userAgent, - } - c.PauseOnRateLimit = true // If rate limit found it will block until that time. If false then Error will be returned - c.authorizationHeaderValue = fmt.Sprintf(headerAuthorizationFormat, apiToken) - c.apiKey = apiToken - c.Limit = defaultLimit - c.RateRemainingFloor = defaultRateRemainingFloor - c.common.client = c - - c.Users = (*UsersService)(&c.common) - c.Groups = (*GroupsService)(&c.common) - c.Apps = (*AppsService)(&c.common) - return c -} - -// Rate represents the rate limit for the current client. -type Rate struct { - // The number of requests per minute the client is currently limited to. - RatePerMinuteLimit int - - // The number of remaining requests the client can make this minute - Remaining int - - // The time at which the current rate limit will reset. - ResetTime time.Time -} - -// Response is a OKTA API response. This wraps the standard http.Response -// returned from OKTA and provides convenient access to things like -// pagination links. -type Response struct { - *http.Response - - // These fields provide the page values for paginating through a set of - // results. - - NextURL *url.URL - // PrevURL *url.URL - SelfURL *url.URL - OKTARequestID string - Rate -} - -// newResponse creates a new Response for the provided http.Response. -func newResponse(r *http.Response) *Response { - response := &Response{Response: r} - - response.OKTARequestID = r.Header.Get(headerOKTARequestID) - - response.populatePaginationURLS() - response.Rate = parseRate(r) - return response -} - -// populatePageValues parses the HTTP Link response headers and populates the -// various pagination link values in the Response. - -// OKTA LINK Header takes this form: -// Link: ; rel="next", -// ; rel="self" - -func (r *Response) populatePaginationURLS() { - - for k, v := range r.Header { - - if k == "Link" { - nextRegex := regexp.MustCompile(`<(.*?)>; rel="next"`) - // prevRegex := regexp.MustCompile(`<(.*?)>; rel="prev"`) - selfRegex := regexp.MustCompile(`<(.*?)>; rel="self"`) - - for _, linkValue := range v { - nextLinkMatch := nextRegex.FindStringSubmatch(linkValue) - if len(nextLinkMatch) != 0 { - r.NextURL, _ = url.Parse(nextLinkMatch[1]) - } - selfLinkMatch := selfRegex.FindStringSubmatch(linkValue) - if len(selfLinkMatch) != 0 { - r.SelfURL, _ = url.Parse(selfLinkMatch[1]) - } - // prevLinkMatch := prevRegex.FindStringSubmatch(linkValue) - // if len(prevLinkMatch) != 0 { - // r.PrevURL, _ = url.Parse(prevLinkMatch[1]) - // } - } - } - } - -} - -// parseRate parses the rate related headers. -func parseRate(r *http.Response) Rate { - var rate Rate - - if limit := r.Header.Get(headerRateLimit); limit != "" { - rate.RatePerMinuteLimit, _ = strconv.Atoi(limit) - } - if remaining := r.Header.Get(headerRateRemaining); remaining != "" { - rate.Remaining, _ = strconv.Atoi(remaining) - } - if reset := r.Header.Get(headerRateReset); reset != "" { - if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { - rate.ResetTime = time.Unix(v, 0) - } - } - return rate -} - -// Do sends an API request and returns the API response. The API response is -// JSON decoded and stored in the value pointed to by v, or returned as an -// error if an API error has occurred. If v implements the io.Writer -// interface, the raw response body will be written to v, without attempting to -// first decode it. If rate limit is exceeded and reset time is in the future, -// Do returns rate immediately without making a network API call. -func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) { - - // If we've hit rate limit, don't make further requests before Reset time. - if err := c.checkRateLimitBeforeDo(req); err != nil { - return nil, err - } - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - - defer func() { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(ioutil.Discard, resp.Body, 512) - resp.Body.Close() - }() - - response := newResponse(resp) - - c.rateMu.Lock() - c.mostRecentRate.RatePerMinuteLimit = response.Rate.RatePerMinuteLimit - c.mostRecentRate.Remaining = response.Rate.Remaining - c.mostRecentRate.ResetTime = response.Rate.ResetTime - c.rateMu.Unlock() - - err = CheckResponse(resp) - if err != nil { - // even though there was an error, we still return the response - // in case the caller wants to inspect it further - // fmt.Printf("Error after sdk.Do return\n") - - return response, err - } - - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(v) - if err == io.EOF { - err = nil // ignore EOF errors caused by empty response body - } - } - } - - return response, err -} - -// checkRateLimitBeforeDo does not make any network calls, but uses existing knowledge from -// current client state in order to quickly check if *RateLimitError can be immediately returned -// from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. -// Otherwise it returns nil, and Client.Do should proceed normally. -// http://developer.okta.com/docs/api/getting_started/design_principles.html#rate-limiting -func (c *Client) checkRateLimitBeforeDo(req *http.Request) error { - - c.rateMu.Lock() - mostRecentRate := c.mostRecentRate - c.rateMu.Unlock() - // fmt.Printf("checkRateLimitBeforeDo: \t Remaining = %d, \t ResetTime = %s\n", mostRecentRate.Remaining, mostRecentRate.ResetTime.String()) - if !mostRecentRate.ResetTime.IsZero() && mostRecentRate.Remaining < c.RateRemainingFloor && time.Now().Before(mostRecentRate.ResetTime) { - - if c.PauseOnRateLimit { - // If rate limit is hitting threshold then pause until the rate limit resets - // This behavior is controlled by the client PauseOnRateLimit value - // fmt.Printf("checkRateLimitBeforeDo: \t ***pause**** \t Time Now = %s \tPause After = %s\n", time.Now().String(), mostRecentRate.ResetTime.Sub(time.Now().Add(2*time.Second)).String()) - <-time.After(mostRecentRate.ResetTime.Sub(time.Now().Add(2 * time.Second))) - } else { - // fmt.Printf("checkRateLimitBeforeDo: \t ***error****\n") - - return &RateLimitError{ - Rate: mostRecentRate, - } - } - - } - - return nil -} - -// CheckResponse checks the API response for errors, and returns them if -// present. A response is considered an error if it has a status code outside -// the 200 range. API error responses are expected to have either no response -// body, or a JSON response body that maps to ErrorResponse. Any other -// response body will be silently ignored. -// -// The error type will be *RateLimitError for rate limit exceeded errors, -// and *TwoFactorAuthError for two-factor authentication errors. -// TODO - check un-authorized -func CheckResponse(r *http.Response) error { - if c := r.StatusCode; 200 <= c && c <= 299 { - return nil - } - - errorResp := &errorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) - if err == nil && data != nil { - json.Unmarshal(data, &errorResp.ErrorDetail) - } - switch { - case r.StatusCode == http.StatusTooManyRequests: - - return &RateLimitError{ - Rate: parseRate(r), - Response: r, - ErrorDetail: errorResp.ErrorDetail} - - default: - return errorResp - } - -} - -type apiError struct { - ErrorCode string `json:"errorCode"` - ErrorSummary string `json:"errorSummary"` - ErrorLink string `json:"errorLink"` - ErrorID string `json:"errorId"` - ErrorCauses []struct { - ErrorSummary string `json:"errorSummary"` - } `json:"errorCauses"` -} - -type errorResponse struct { - Response *http.Response // - ErrorDetail apiError -} - -func (r *errorResponse) Error() string { - return fmt.Sprintf("HTTP Method: %v - URL: %v: - HTTP Status Code: %d, OKTA Error Code: %v, OKTA Error Summary: %v, OKTA Error Causes: %v", - r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.ErrorDetail.ErrorCode, r.ErrorDetail.ErrorSummary, r.ErrorDetail.ErrorCauses) -} - -// RateLimitError occurs when OKTA returns 429 "Too Many Requests" response with a rate limit -// remaining value of 0, and error message starts with "API rate limit exceeded for ". -type RateLimitError struct { - Rate Rate // Rate specifies last known rate limit for the client - ErrorDetail apiError - Response *http.Response // -} - -func (r *RateLimitError) Error() string { - - return fmt.Sprintf("rate reset in %v", r.Rate.ResetTime.Sub(time.Now())) - -} - -// Code stolen from Github api libary -// Stringify attempts to create a reasonable string representation of types in -// the library. It does things like resolve pointers to their values -// and omits struct fields with nil values. -func stringify(message interface{}) string { - var buf bytes.Buffer - v := reflect.ValueOf(message) - stringifyValue(&buf, v) - return buf.String() -} - -// stringifyValue was heavily inspired by the goprotobuf library. - -func stringifyValue(w io.Writer, val reflect.Value) { - if val.Kind() == reflect.Ptr && val.IsNil() { - w.Write([]byte("")) - return - } - - v := reflect.Indirect(val) - - switch v.Kind() { - case reflect.String: - fmt.Fprintf(w, `"%s"`, v) - case reflect.Slice: - w.Write([]byte{'['}) - for i := 0; i < v.Len(); i++ { - if i > 0 { - w.Write([]byte{' '}) - } - - stringifyValue(w, v.Index(i)) - } - - w.Write([]byte{']'}) - return - case reflect.Struct: - if v.Type().Name() != "" { - w.Write([]byte(v.Type().String())) - } - w.Write([]byte{'{'}) - - var sep bool - for i := 0; i < v.NumField(); i++ { - fv := v.Field(i) - if fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - continue - } - - if sep { - w.Write([]byte(", ")) - } else { - sep = true - } - - w.Write([]byte(v.Type().Field(i).Name)) - w.Write([]byte{':'}) - stringifyValue(w, fv) - } - - w.Write([]byte{'}'}) - default: - if v.CanInterface() { - fmt.Fprint(w, v.Interface()) - } - } -} - -// NewRequest creates an API request. A relative URL can be provided in urlStr, -// in which case it is resolved relative to the BaseURL of the Client. -// Relative URLs should always be specified without a preceding slash. If -// specified, the value pointed to by body is JSON encoded and included as the -// request body. -func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { - rel, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - u := c.BaseURL.ResolveReference(rel) - - var buf io.ReadWriter - if body != nil { - buf = new(bytes.Buffer) - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, u.String(), buf) - if err != nil { - return nil, err - } - - req.Header.Set(headerAuthorization, fmt.Sprintf(headerAuthorizationFormat, c.apiKey)) - - if body != nil { - req.Header.Set("Content-Type", mediaTypeJSON) - } - - if c.UserAgent != "" { - req.Header.Set("User-Agent", c.UserAgent) - } - return req, nil -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) - if v.Kind() == reflect.Ptr && v.IsNil() { - return s, nil - } - - u, err := url.Parse(s) - if err != nil { - return s, err - } - - qs, err := query.Values(opt) - if err != nil { - return s, err - } - - u.RawQuery = qs.Encode() - return u.String(), nil -} - -type dateFilter struct { - Value time.Time - Operator string -} diff --git a/vendor/github.com/chrismalek/oktasdk-go/okta/users.go b/vendor/github.com/chrismalek/oktasdk-go/okta/users.go deleted file mode 100644 index 8102a819e..000000000 --- a/vendor/github.com/chrismalek/oktasdk-go/okta/users.go +++ /dev/null @@ -1,625 +0,0 @@ -package okta - -import ( - "errors" - "fmt" - "net/url" - "time" -) - -const ( - profileEmailFilter = "profile.email" - profileLoginFilter = "profile.login" - profileStatusFilter = "status" - profileIDFilter = "id" - profileFirstNameFilter = "profile.firstName" - profileLastNameFilter = "profile.lastName" - profileLastUpdatedFilter = "lastUpdated" - // UserStatusActive is a constant to represent OKTA User State returned by the API - UserStatusActive = "ACTIVE" - // UserStatusStaged is a constant to represent OKTA User State returned by the API - UserStatusStaged = "STAGED" - // UserStatusProvisioned is a constant to represent OKTA User State returned by the API - UserStatusProvisioned = "PROVISIONED" - // UserStatusRecovery is a constant to represent OKTA User State returned by the API - UserStatusRecovery = "RECOVERY" - // UserStatusLockedOut is a constant to represent OKTA User State returned by the API - UserStatusLockedOut = "LOCKED_OUT" - // UserStatusPasswordExpired is a constant to represent OKTA User State returned by the API - UserStatusPasswordExpired = "PASSWORD_EXPIRED" - // UserStatusSuspended is a constant to represent OKTA User State returned by the API - UserStatusSuspended = "SUSPENDED" - // UserStatusDeprovisioned is a constant to represent OKTA User State returned by the API - UserStatusDeprovisioned = "DEPROVISIONED" - - oktaFilterTimeFormat = "2006-01-02T15:05:05.000Z" -) - -// UsersService handles communication with the User data related -// methods of the OKTA API. -type UsersService service - -// ActivationResponse - Response coming back from a user activation -type ActivationResponse struct { - ActivationURL string `json:"activationUrl"` -} - -type provider struct { - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` -} - -type recoveryQuestion struct { - Question string `json:"question,omitempty"` - Answer string `json:"answer,omitempty"` -} - -type passwordValue struct { - Value string `json:"value,omitempty"` -} -type credentials struct { - Password *passwordValue `json:"password,omitempty"` - Provider *provider `json:"provider,omitempty"` - RecoveryQuestion *recoveryQuestion `json:"recovery_question,omitempty"` -} - -type userProfile struct { - Email string `json:"email"` - FirstName string `json:"firstName"` - LastName string `json:"lastName"` - Login string `json:"login"` - MobilePhone string `json:"mobilePhone,omitempty"` - SecondEmail string `json:"secondEmail,omitempty"` - PsEmplid string `json:"psEmplid,omitempty"` - NickName string `json:"nickname,omitempty"` - DisplayName string `json:"displayName,omitempty"` - - ProfileURL string `json:"profileUrl,omitempty"` - PreferredLanguage string `json:"preferredLanguage,omitempty"` - UserType string `json:"userType,omitempty"` - Organization string `json:"organization,omitempty"` - Title string `json:"title,omitempty"` - Division string `json:"division,omitempty"` - Department string `json:"department,omitempty"` - CostCenter string `json:"costCenter,omitempty"` - EmployeeNumber string `json:"employeeNumber,omitempty"` - PrimaryPhone string `json:"primaryPhone,omitempty"` - StreetAddress string `json:"streetAddress,omitempty"` - City string `json:"city,omitempty"` - State string `json:"state,omitempty"` - ZipCode string `json:"zipCode,omitempty"` - CountryCode string `json:"countryCode,omitempty"` -} - -type userLinks struct { - ChangePassword struct { - Href string `json:"href"` - } `json:"changePassword"` - ChangeRecoveryQuestion struct { - Href string `json:"href"` - } `json:"changeRecoveryQuestion"` - Deactivate struct { - Href string `json:"href"` - } `json:"deactivate"` - ExpirePassword struct { - Href string `json:"href"` - } `json:"expirePassword"` - ForgotPassword struct { - Href string `json:"href"` - } `json:"forgotPassword"` - ResetFactors struct { - Href string `json:"href"` - } `json:"resetFactors"` - ResetPassword struct { - Href string `json:"href"` - } `json:"resetPassword"` -} - -// User is a struct that represents a user object from OKTA. -type User struct { - Activated string `json:"activated,omitempty"` - Created string `json:"created,omitempty"` - Credentials credentials `json:"credentials,omitempty"` - ID string `json:"id,omitempty"` - LastLogin string `json:"lastLogin,omitempty"` - LastUpdated string `json:"lastUpdated,omitempty"` - PasswordChanged string `json:"passwordChanged,omitempty"` - Profile userProfile `json:"profile"` - Status string `json:"status,omitempty"` - StatusChanged string `json:"statusChanged,omitempty"` - Links userLinks `json:"_links,omitempty"` - MFAFactors []userMFAFactor `json:"-,"` - Groups []Group `json:"-"` -} - -type userMFAFactor struct { - ID string `json:"id,omitempty"` - FactorType string `json:"factorType,omitempty"` - Provider string `json:"provider,omitempty"` - VendorName string `json:"vendorName,omitempty"` - Status string `json:"status,omitempty"` - Created time.Time `json:"created,omitempty"` - LastUpdated time.Time `json:"lastUpdated,omitempty"` - Profile struct { - CredentialID string `json:"credentialId,omitempty"` - } `json:"profile,omitempty"` -} - -// NewUser object to create user objects in OKTA -type NewUser struct { - Profile userProfile `json:"profile"` - Credentials *credentials `json:"credentials,omitempty"` -} - -type newPasswordSet struct { - Credentials credentials `json:"credentials"` -} - -// ResetPasswordResponse struct that returns data about the password reset -type ResetPasswordResponse struct { - ResetPasswordURL string `json:"resetPasswordUrl"` -} - -// NewUser - Returns a new user object. This is used to create users in OKTA. It only has the properties that -// OKTA will take as input. The "User" object has more feilds that are OKTA returned like the ID, etc -func (s *UsersService) NewUser() NewUser { - return NewUser{} -} - -// SetPassword Adds a specified password to the new User -func (u *NewUser) SetPassword(passwordIn string) { - - if passwordIn != "" { - - pass := new(passwordValue) - pass.Value = passwordIn - - var cred *credentials - if u.Credentials == nil { - cred = new(credentials) - } else { - cred = u.Credentials - } - - cred.Password = pass - u.Credentials = cred - - } -} - -// SetRecoveryQuestion - Sets a custom security question and answer on a user object -func (u *NewUser) SetRecoveryQuestion(questionIn string, answerIn string) { - - if questionIn != "" && answerIn != "" { - recovery := new(recoveryQuestion) - - recovery.Question = questionIn - recovery.Answer = answerIn - - var cred *credentials - if u.Credentials == nil { - cred = new(credentials) - } else { - cred = u.Credentials - } - cred.RecoveryQuestion = recovery - u.Credentials = cred - - } -} - -func (u User) String() string { - return stringify(u) - // return fmt.Sprintf("ID: %v \tLogin: %v", u.ID, u.Profile.Login) -} - -// GetByID returns a user object for a specific OKTA ID. -// Generally the id input string is the cryptic OKTA key value from User.ID. However, the OKTA API may accept other values like "me", or login shortname -func (s *UsersService) GetByID(id string) (*User, *Response, error) { - u := fmt.Sprintf("users/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - user := new(User) - resp, err := s.client.Do(req, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} - -// UserListFilterOptions is a struct that you can populate which will "filter" user searches -// the exported struct fields should allow you to do different filters based on what is allowed in the OKTA API. -// The filter OKTA API is limited in the fields it can search -// NOTE: In the current form you can't add parenthesis and ordering -// OKTA API Supports only a limited number of properties: -// status, lastUpdated, id, profile.login, profile.email, profile.firstName, and profile.lastName. -// http://developer.okta.com/docs/api/resources/users.html#list-users-with-a-filter -type UserListFilterOptions struct { - Limit int `url:"limit,omitempty"` - EmailEqualTo string `url:"-"` - LoginEqualTo string `url:"-"` - StatusEqualTo string `url:"-"` - IDEqualTo string `url:"-"` - - FirstNameEqualTo string `url:"-"` - LastNameEqualTo string `url:"-"` - // API documenation says you can search with "starts with" but these don't work - - // FirstNameStartsWith string `url:"-"` - // LastNameStartsWith string `url:"-"` - - // This will be built by internal - may not need to export - FilterString string `url:"filter,omitempty"` - NextURL *url.URL `url:"-"` - GetAllPages bool `url:"-"` - NumberOfPages int `url:"-"` - LastUpdated dateFilter `url:"-"` -} - -// PopulateGroups will populate the groups a user is a member of. You pass in a pointer to an existing users -func (s *UsersService) PopulateGroups(user *User) (*Response, error) { - u := fmt.Sprintf("users/%v/groups", user.ID) - req, err := s.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, err - } - // Get first page of users. - resp, err := s.client.Do(req, &user.Groups) - if err != nil { - return resp, err - } - // Look for any remaining user group pages. - var nextURL string - if resp.NextURL != nil { - nextURL = resp.NextURL.String() - } - for { - - if nextURL != "" { - req, err := s.client.NewRequest("GET", nextURL, nil) - userGroupsPages := []Group{} - - resp, err := s.client.Do(req, &userGroupsPages) - nextURL = "" - if err != nil { - return resp, err - } - user.Groups = append(user.Groups, userGroupsPages...) - if resp.NextURL != nil { - nextURL = resp.NextURL.String() - } - - } else { - return resp, err - } - - } - -} - -// PopulateEnrolledFactors will populate the Enrolled MFA Factors a user is a member of. -// You pass in a pointer to an existing users -// http://developer.okta.com/docs/api/resources/factors.html#list-enrolled-factors -func (s *UsersService) PopulateEnrolledFactors(user *User) (*Response, error) { - u := fmt.Sprintf("users/%v/factors", user.ID) - req, err := s.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, err - } - // TODO: If user has more than 200 groups this will only return those first 200 - resp, err := s.client.Do(req, &user.MFAFactors) - if err != nil { - return resp, err - } - - return resp, err -} - -// List users with status of LOCKED_OUT -// filter=status eq "LOCKED_OUT" -// List users updated after 06/01/2013 but before 01/01/2014 -// filter=lastUpdated gt "2013-06-01T00:00:00.000Z" and lastUpdated lt "2014-01-01T00:00:00.000Z" -// List users updated after 06/01/2013 but before 01/01/2014 with a status of ACTIVE -// filter=lastUpdated gt "2013-06-01T00:00:00.000Z" and lastUpdated lt "2014-01-01T00:00:00.000Z" and status eq "ACTIVE" -// TODO - Currently no way to do parenthesis -// List users updated after 06/01/2013 but with a status of LOCKED_OUT or RECOVERY -// filter=lastUpdated gt "2013-06-01T00:00:00.000Z" and (status eq "LOCKED_OUT" or status eq "RECOVERY") - -// OTKA API docs: http://developer.okta.com/docs/api/resources/users.html#list-users-with-a-filter - -func appendToFilterString(currFilterString string, appendFilterKey string, appendFilterOperator string, appendFilterValue string) (rs string) { - if currFilterString != "" { - rs = fmt.Sprintf("%v and %v %v \"%v\"", currFilterString, appendFilterKey, appendFilterOperator, appendFilterValue) - } else { - rs = fmt.Sprintf("%v %v \"%v\"", appendFilterKey, appendFilterOperator, appendFilterValue) - } - - return rs -} - -// ListWithFilter will use the input UserListFilterOptions to find users and return a paged result set -func (s *UsersService) ListWithFilter(opt *UserListFilterOptions) ([]User, *Response, error) { - var u string - var err error - - pagesRetreived := 0 - - if opt.NextURL != nil { - u = opt.NextURL.String() - } else { - if opt.EmailEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileEmailFilter, FilterEqualOperator, opt.EmailEqualTo) - } - if opt.LoginEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileLoginFilter, FilterEqualOperator, opt.LoginEqualTo) - } - - if opt.StatusEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileStatusFilter, FilterEqualOperator, opt.StatusEqualTo) - } - - if opt.IDEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileIDFilter, FilterEqualOperator, opt.IDEqualTo) - } - - if opt.FirstNameEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileFirstNameFilter, FilterEqualOperator, opt.FirstNameEqualTo) - } - - if opt.LastNameEqualTo != "" { - opt.FilterString = appendToFilterString(opt.FilterString, profileLastNameFilter, FilterEqualOperator, opt.LastNameEqualTo) - } - - // API documenation says you can search with "starts with" but these don't work - // if opt.FirstNameStartsWith != "" { - // opt.FilterString = appendToFilterString(opt.FilterString, profileFirstNameFilter, filterStartsWithOperator, opt.FirstNameStartsWith) - // } - - // if opt.LastNameStartsWith != "" { - // opt.FilterString = appendToFilterString(opt.FilterString, profileLastNameFilter, filterStartsWithOperator, opt.LastNameStartsWith) - // } - - if !opt.LastUpdated.Value.IsZero() { - opt.FilterString = appendToFilterString(opt.FilterString, profileLastUpdatedFilter, opt.LastUpdated.Operator, opt.LastUpdated.Value.UTC().Format(oktaFilterTimeFormat)) - } - - if opt.Limit == 0 { - opt.Limit = defaultLimit - } - - u, err = addOptions("users", opt) - - } - - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - users := make([]User, 1) - resp, err := s.client.Do(req, &users) - if err != nil { - return nil, resp, err - } - - pagesRetreived++ - - if (opt.NumberOfPages > 0 && pagesRetreived < opt.NumberOfPages) || opt.GetAllPages { - - for { - - if pagesRetreived == opt.NumberOfPages { - break - } - if resp.NextURL != nil { - var userPage []User - pageOption := new(UserListFilterOptions) - pageOption.NextURL = resp.NextURL - pageOption.NumberOfPages = 1 - pageOption.Limit = opt.Limit - - userPage, resp, err = s.ListWithFilter(pageOption) - if err != nil { - return users, resp, err - } - users = append(users, userPage...) - pagesRetreived++ - } else { - break - } - } - } - return users, resp, err -} - -// Create - Creates a new user. You must pass in a "newUser" object created from Users.NewUser() -// There are many differnt reasons that OKTA may reject the request so you have to check the error messages -func (s *UsersService) Create(userIn NewUser, createAsActive bool) (*User, *Response, error) { - - u := fmt.Sprintf("users?activate=%v", createAsActive) - - req, err := s.client.NewRequest("POST", u, userIn) - - if err != nil { - return nil, nil, err - } - - newUser := new(User) - resp, err := s.client.Do(req, newUser) - if err != nil { - return nil, resp, err - } - - return newUser, resp, err -} - -// Activate Activates a user. You can have OKTA send an email by including a "sendEmail=true" -// If you pass in sendEmail=false, then activationResponse.ActivationURL will have a string URL that -// can be sent to the end user. You can discard response if sendEmail=true -func (s *UsersService) Activate(id string, sendEmail bool) (*ActivationResponse, *Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/activate?sendEmail=%v", id, sendEmail) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - activationInfo := new(ActivationResponse) - resp, err := s.client.Do(req, activationInfo) - - if err != nil { - return nil, resp, err - } - - return activationInfo, resp, err -} - -// Deactivate - Deactivates a user -func (s *UsersService) Deactivate(id string) (*Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/deactivate", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - resp, err := s.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// Suspend - Suspends a user - If user is NOT active an Error will come back based on OKTA API: -// http://developer.okta.com/docs/api/resources/users.html#suspend-user -func (s *UsersService) Suspend(id string) (*Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/suspend", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - resp, err := s.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// Unsuspend - Unsuspends a user - If user is NOT SUSPENDED, an Error will come back based on OKTA API: -// http://developer.okta.com/docs/api/resources/users.html#unsuspend-user -func (s *UsersService) Unsuspend(id string) (*Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/unsuspend", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - resp, err := s.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// Unlock - Unlocks a user - Per docs, only for OKTA Mastered Account -// http://developer.okta.com/docs/api/resources/users.html#unlock-user -func (s *UsersService) Unlock(id string) (*Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/unlock", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - resp, err := s.client.Do(req, nil) - - if err != nil { - return resp, err - } - - return resp, err -} - -// SetPassword - Sets a user password to an Admin provided String -func (s *UsersService) SetPassword(id string, newPassword string) (*User, *Response, error) { - - if id == "" || newPassword == "" { - return nil, nil, errors.New("please provide a User ID and Password") - } - - passwordUpdate := new(newPasswordSet) - - pass := new(passwordValue) - pass.Value = newPassword - - passwordUpdate.Credentials.Password = pass - - u := fmt.Sprintf("users/%v", id) - req, err := s.client.NewRequest("POST", u, passwordUpdate) - if err != nil { - return nil, nil, err - } - - user := new(User) - resp, err := s.client.Do(req, user) - if err != nil { - return nil, resp, err - } - - return user, resp, err -} - -// ResetPassword - Generates a one-time token (OTT) that can be used to reset a user’s password. -// The OTT link can be automatically emailed to the user or returned to the API caller and distributed using a custom flow. -// http://developer.okta.com/docs/api/resources/users.html#reset-password -// If you pass in sendEmail=false, then resetPasswordResponse.resetPasswordUrl will have a string URL that -// can be sent to the end user. You can discard response if sendEmail=true -func (s *UsersService) ResetPassword(id string, sendEmail bool) (*ResetPasswordResponse, *Response, error) { - u := fmt.Sprintf("users/%v/lifecycle/reset_password?sendEmail=%v", id, sendEmail) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - resetInfo := new(ResetPasswordResponse) - resp, err := s.client.Do(req, resetInfo) - - if err != nil { - return nil, resp, err - } - - return resetInfo, resp, err -} - -// PopulateMFAFactors will populate the MFA Factors a user is a member of. You pass in a pointer to an existing users -func (s *UsersService) PopulateMFAFactors(user *User) (*Response, error) { - u := fmt.Sprintf("users/%v/factors", user.ID) - - req, err := s.client.NewRequest("GET", u, nil) - - if err != nil { - return nil, err - } - - resp, err := s.client.Do(req, &user.MFAFactors) - if err != nil { - return resp, err - } - - return resp, err -} diff --git a/vendor/github.com/cockroachdb/cockroach-go/LICENSE b/vendor/github.com/cockroachdb/cockroach-go/LICENSE deleted file mode 100644 index 829ea336d..000000000 --- a/vendor/github.com/cockroachdb/cockroach-go/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/vendor/github.com/cockroachdb/cockroach-go/crdb/error.go b/vendor/github.com/cockroachdb/cockroach-go/crdb/error.go deleted file mode 100644 index 32e10017a..000000000 --- a/vendor/github.com/cockroachdb/cockroach-go/crdb/error.go +++ /dev/null @@ -1,73 +0,0 @@ -package crdb - -import "fmt" - -// ErrorCauser is the type implemented by an error that remembers its cause. -// -// ErrorCauser is intentionally equivalent to the causer interface used by -// the github.com/pkg/errors package. -type ErrorCauser interface { - // Cause returns the proximate cause of this error. - Cause() error -} - -// errorCause returns the original cause of the error, if possible. An error has -// a proximate cause if it implements ErrorCauser; the original cause is the -// first error in the cause chain that does not implement ErrorCauser. -// -// errorCause is intentionally equivalent to pkg/errors.Cause. -func errorCause(err error) error { - for err != nil { - cause, ok := err.(ErrorCauser) - if !ok { - break - } - err = cause.Cause() - } - return err -} - -type txError struct { - cause error -} - -// Error implements the error interface. -func (e *txError) Error() string { return e.cause.Error() } - -// Cause implements the ErrorCauser interface. -func (e *txError) Cause() error { return e.cause } - -// AmbiguousCommitError represents an error that left a transaction in an -// ambiguous state: unclear if it committed or not. -type AmbiguousCommitError struct { - txError -} - -func newAmbiguousCommitError(err error) *AmbiguousCommitError { - return &AmbiguousCommitError{txError{cause: err}} -} - -// TxnRestartError represents an error when restarting a transaction. `cause` is -// the error from restarting the txn and `retryCause` is the original error which -// triggered the restart. -type TxnRestartError struct { - txError - retryCause error - msg string -} - -func newTxnRestartError(err error, retryErr error) *TxnRestartError { - const msgPattern = "restarting txn failed. ROLLBACK TO SAVEPOINT " + - "encountered error: %s. Original error: %s." - return &TxnRestartError{ - txError: txError{cause: err}, - retryCause: retryErr, - msg: fmt.Sprintf(msgPattern, err, retryErr), - } -} - -// Error implements the error interface. -func (e *TxnRestartError) Error() string { return e.msg } - -// RetryCause returns the error that caused the transaction to be restarted. -func (e *TxnRestartError) RetryCause() error { return e.retryCause } diff --git a/vendor/github.com/cockroachdb/cockroach-go/crdb/tx.go b/vendor/github.com/cockroachdb/cockroach-go/crdb/tx.go deleted file mode 100644 index c2ad7b9ce..000000000 --- a/vendor/github.com/cockroachdb/cockroach-go/crdb/tx.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2016 The Cockroach Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -// implied. See the License for the specific language governing -// permissions and limitations under the License. - -// Package crdb provides helpers for using CockroachDB in client -// applications. -package crdb - -import ( - "context" - "database/sql" - - "github.com/lib/pq" -) - -// ExecuteTx runs fn inside a transaction and retries it as needed. -// On non-retryable failures, the transaction is aborted and rolled -// back; on success, the transaction is committed. -// There are cases where the state of a transaction is inherently ambiguous: if -// we err on RELEASE with a communication error it's unclear if the transaction -// has been committed or not (similar to erroring on COMMIT in other databases). -// In that case, we return AmbiguousCommitError. -// There are cases when restarting a transaction fails: we err on ROLLBACK -// to the SAVEPOINT. In that case, we return a TxnRestartError. -// -// For more information about CockroachDB's transaction model see -// https://cockroachlabs.com/docs/stable/transactions.html. -// -// NOTE: the supplied fn closure should not have external side -// effects beyond changes to the database. -// -// fn must take care when wrapping errors returned from the database driver with -// additional context. For example, if the UPDATE statement fails in the -// following snippet, the original retryable error will be masked by the call to -// fmt.Errorf, and the transaction will not be automatically retried. -// -// crdb.ExecuteTx(ctx, db, txopts, func (tx *sql.Tx) error { -// if err := tx.ExecContext(ctx, "UPDATE..."); err != nil { -// return fmt.Errorf("updating record: %s", err) -// } -// return nil -// }) -// -// Instead, add context by returning an error that implements the ErrorCauser -// interface. Either create a custom error type that implements ErrorCauser or -// use a helper function that does so automatically, like pkg/errors.Wrap: -// -// import "github.com/pkg/errors" -// -// crdb.ExecuteTx(ctx, db, txopts, func (tx *sql.Tx) error { -// if err := tx.ExecContext(ctx, "UPDATE..."); err != nil { -// return errors.Wrap(err, "updating record") -// } -// return nil -// }) -// -func ExecuteTx(ctx context.Context, db *sql.DB, txopts *sql.TxOptions, fn func(*sql.Tx) error) error { - // Start a transaction. - tx, err := db.BeginTx(ctx, txopts) - if err != nil { - return err - } - return ExecuteInTx(ctx, tx, func() error { return fn(tx) }) -} - -// Tx is used to permit clients to implement custom transaction logic. -type Tx interface { - ExecContext(context.Context, string, ...interface{}) (sql.Result, error) - Commit() error - Rollback() error -} - -// ExecuteInTx runs fn inside tx which should already have begun. -// *WARNING*: Do not execute any statements on the supplied tx before calling this function. -// ExecuteInTx will only retry statements that are performed within the supplied -// closure (fn). Any statements performed on the tx before ExecuteInTx is invoked will *not* -// be re-run if the transaction needs to be retried. -// -// fn is subject to the same restrictions as the fn passed to ExecuteTx. -func ExecuteInTx(ctx context.Context, tx Tx, fn func() error) (err error) { - defer func() { - if err == nil { - // Ignore commit errors. The tx has already been committed by RELEASE. - _ = tx.Commit() - } else { - // We always need to execute a Rollback() so sql.DB releases the - // connection. - _ = tx.Rollback() - } - }() - // Specify that we intend to retry this txn in case of CockroachDB retryable - // errors. - if _, err = tx.ExecContext(ctx, "SAVEPOINT cockroach_restart"); err != nil { - return err - } - - for { - released := false - err = fn() - if err == nil { - // RELEASE acts like COMMIT in CockroachDB. We use it since it gives us an - // opportunity to react to retryable errors, whereas tx.Commit() doesn't. - released = true - if _, err = tx.ExecContext(ctx, "RELEASE SAVEPOINT cockroach_restart"); err == nil { - return nil - } - } - // We got an error; let's see if it's a retryable one and, if so, restart. We look - // for either the standard PG errcode SerializationFailureError:40001 or the Cockroach extension - // errcode RetriableError:CR000. The Cockroach extension has been removed server-side, but support - // for it has been left here for now to maintain backwards compatibility. - pqErr, ok := errorCause(err).(*pq.Error) - if retryable := ok && (pqErr.Code == "CR000" || pqErr.Code == "40001"); !retryable { - if released { - err = newAmbiguousCommitError(err) - } - return err - } - if _, retryErr := tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT cockroach_restart"); retryErr != nil { - return newTxnRestartError(retryErr, err) - } - } -} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE index c83641619..bc52e96f2 100644 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ b/vendor/github.com/davecgh/go-spew/LICENSE @@ -2,7 +2,7 @@ ISC License Copyright (c) 2012-2016 Dave Collins -Permission to use, copy, modify, and distribute this software for any +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go index 8a4a6589a..792994785 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -16,7 +16,9 @@ // when the code is not running on Google App Engine, compiled by GopherJS, and // "-tags safe" is not added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe +// Go versions prior to 1.4 are disabled because they use a different layout +// for interfaces which make the implementation of unsafeReflectValue more complex. +// +build !js,!appengine,!safe,!disableunsafe,go1.4 package spew @@ -34,80 +36,49 @@ const ( ptrSize = unsafe.Sizeof((*byte)(nil)) ) +type flag uintptr + var ( - // offsetPtr, offsetScalar, and offsetFlag are the offsets for the - // internal reflect.Value fields. These values are valid before golang - // commit ecccf07e7f9d which changed the format. The are also valid - // after commit 82f48826c6c7 which changed the format again to mirror - // the original format. Code in the init function updates these offsets - // as necessary. - offsetPtr = uintptr(ptrSize) - offsetScalar = uintptr(0) - offsetFlag = uintptr(ptrSize * 2) - - // flagKindWidth and flagKindShift indicate various bits that the - // reflect package uses internally to track kind information. - // - // flagRO indicates whether or not the value field of a reflect.Value is - // read-only. - // - // flagIndir indicates whether the value field of a reflect.Value is - // the actual data or a pointer to the data. - // - // These values are valid before golang commit 90a7c3c86944 which - // changed their positions. Code in the init function updates these - // flags as necessary. - flagKindWidth = uintptr(5) - flagKindShift = uintptr(flagKindWidth - 1) - flagRO = uintptr(1 << 0) - flagIndir = uintptr(1 << 1) + // flagRO indicates whether the value field of a reflect.Value + // is read-only. + flagRO flag + + // flagAddr indicates whether the address of the reflect.Value's + // value may be taken. + flagAddr flag ) -func init() { - // Older versions of reflect.Value stored small integers directly in the - // ptr field (which is named val in the older versions). Versions - // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named - // scalar for this purpose which unfortunately came before the flag - // field, so the offset of the flag field is different for those - // versions. - // - // This code constructs a new reflect.Value from a known small integer - // and checks if the size of the reflect.Value struct indicates it has - // the scalar field. When it does, the offsets are updated accordingly. - vv := reflect.ValueOf(0xf00) - if unsafe.Sizeof(vv) == (ptrSize * 4) { - offsetScalar = ptrSize * 2 - offsetFlag = ptrSize * 3 - } +// flagKindMask holds the bits that make up the kind +// part of the flags field. In all the supported versions, +// it is in the lower 5 bits. +const flagKindMask = flag(0x1f) - // Commit 90a7c3c86944 changed the flag positions such that the low - // order bits are the kind. This code extracts the kind from the flags - // field and ensures it's the correct type. When it's not, the flag - // order has been changed to the newer format, so the flags are updated - // accordingly. - upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) - upfv := *(*uintptr)(upf) - flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { - flagKindShift = 0 - flagRO = 1 << 5 - flagIndir = 1 << 6 - - // Commit adf9b30e5594 modified the flags to separate the - // flagRO flag into two bits which specifies whether or not the - // field is embedded. This causes flagIndir to move over a bit - // and means that flagRO is the combination of either of the - // original flagRO bit and the new bit. - // - // This code detects the change by extracting what used to be - // the indirect bit to ensure it's set. When it's not, the flag - // order has been changed to the newer format, so the flags are - // updated accordingly. - if upfv&flagIndir == 0 { - flagRO = 3 << 5 - flagIndir = 1 << 7 - } +// Different versions of Go have used different +// bit layouts for the flags type. This table +// records the known combinations. +var okFlags = []struct { + ro, addr flag +}{{ + // From Go 1.4 to 1.5 + ro: 1 << 5, + addr: 1 << 7, +}, { + // Up to Go tip. + ro: 1<<5 | 1<<6, + addr: 1 << 8, +}} + +var flagValOffset = func() uintptr { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") } + return field.Offset +}() + +// flagField returns a pointer to the flag field of a reflect.Value. +func flagField(v *reflect.Value) *flag { + return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses @@ -119,34 +90,56 @@ func init() { // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. -func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { - indirects := 1 - vt := v.Type() - upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) - rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) - if rvf&flagIndir != 0 { - vt = reflect.PtrTo(v.Type()) - indirects++ - } else if offsetScalar != 0 { - // The value is in the scalar field when it's not one of the - // reference types. - switch vt.Kind() { - case reflect.Uintptr: - case reflect.Chan: - case reflect.Func: - case reflect.Map: - case reflect.Ptr: - case reflect.UnsafePointer: - default: - upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + - offsetScalar) - } +func unsafeReflectValue(v reflect.Value) reflect.Value { + if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { + return v } + flagFieldPtr := flagField(&v) + *flagFieldPtr &^= flagRO + *flagFieldPtr |= flagAddr + return v +} - pv := reflect.NewAt(vt, upv) - rv = pv - for i := 0; i < indirects; i++ { - rv = rv.Elem() +// Sanity checks against future reflect package changes +// to the type or semantics of the Value.flag field. +func init() { + field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") + if !ok { + panic("reflect.Value has no flag field") + } + if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { + panic("reflect.Value flag field has changed kind") + } + type t0 int + var t struct { + A t0 + // t0 will have flagEmbedRO set. + t0 + // a will have flagStickyRO set + a t0 + } + vA := reflect.ValueOf(t).FieldByName("A") + va := reflect.ValueOf(t).FieldByName("a") + vt0 := reflect.ValueOf(t).FieldByName("t0") + + // Infer flagRO from the difference between the flags + // for the (otherwise identical) fields in t. + flagPublic := *flagField(&vA) + flagWithRO := *flagField(&va) | *flagField(&vt0) + flagRO = flagPublic ^ flagWithRO + + // Infer flagAddr from the difference between a value + // taken from a pointer and not. + vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") + flagNoPtr := *flagField(&vA) + flagPtr := *flagField(&vPtrA) + flagAddr = flagNoPtr ^ flagPtr + + // Check that the inferred flags tally with one of the known versions. + for _, f := range okFlags { + if flagRO == f.ro && flagAddr == f.addr { + return + } } - return rv + panic("reflect.Value read-only flag has changed semantics") } diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go index 1fe3cf3d5..205c28d68 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -16,7 +16,7 @@ // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe +// +build js appengine safe disableunsafe !go1.4 package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go index 7c519ff47..1be8ce945 100644 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ b/vendor/github.com/davecgh/go-spew/spew/common.go @@ -180,7 +180,7 @@ func printComplex(w io.Writer, c complex128, floatPrecision int) { w.Write(closeParenBytes) } -// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' +// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go index df1d582a7..f78d89fc1 100644 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ b/vendor/github.com/davecgh/go-spew/spew/dump.go @@ -35,16 +35,16 @@ var ( // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") + cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. - cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") + cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") + cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) ) // dumpState contains information about the state of a dump operation. @@ -143,10 +143,10 @@ func (d *dumpState) dumpPtr(v reflect.Value) { // Display dereferenced value. d.w.Write(openParenBytes) switch { - case nilFound == true: + case nilFound: d.w.Write(nilAngleBytes) - case cycleFound == true: + case cycleFound: d.w.Write(circularBytes) default: diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go index c49875bac..b04edb7d7 100644 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ b/vendor/github.com/davecgh/go-spew/spew/format.go @@ -182,10 +182,10 @@ func (f *formatState) formatPtr(v reflect.Value) { // Display dereferenced value. switch { - case nilFound == true: + case nilFound: f.fs.Write(nilAngleBytes) - case cycleFound == true: + case cycleFound: f.fs.Write(circularShortBytes) default: diff --git a/vendor/github.com/denisenkom/go-mssqldb/LICENSE.txt b/vendor/github.com/denisenkom/go-mssqldb/LICENSE.txt deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/denisenkom/go-mssqldb/README.md b/vendor/github.com/denisenkom/go-mssqldb/README.md deleted file mode 100644 index ea06b900a..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/README.md +++ /dev/null @@ -1,215 +0,0 @@ -# A pure Go MSSQL driver for Go's database/sql package - -[![GoDoc](https://godoc.org/github.com/denisenkom/go-mssqldb?status.svg)](http://godoc.org/github.com/denisenkom/go-mssqldb) -[![Build status](https://ci.appveyor.com/api/projects/status/jrln8cs62wj9i0a2?svg=true)](https://ci.appveyor.com/project/denisenkom/go-mssqldb) -[![codecov](https://codecov.io/gh/denisenkom/go-mssqldb/branch/master/graph/badge.svg)](https://codecov.io/gh/denisenkom/go-mssqldb) - -## Install - -Requires Go 1.8 or above. - -Install with `go get github.com/denisenkom/go-mssqldb` . - -## Connection Parameters and DSN - -The recommended connection string uses a URL format: -`sqlserver://username:password@host/instance?param1=value¶m2=value` -Other supported formats are listed below. - -### Common parameters: - -* `user id` - enter the SQL Server Authentication user id or the Windows Authentication user id in the DOMAIN\User format. On Windows, if user id is empty or missing Single-Sign-On is used. -* `password` -* `database` -* `connection timeout` - in seconds (default is 0 for no timeout), set to 0 for no timeout. Recommended to set to 0 and use context to manage query and connection timeouts. -* `dial timeout` - in seconds (default is 15), set to 0 for no timeout -* `encrypt` - * `disable` - Data send between client and server is not encrypted. - * `false` - Data sent between client and server is not encrypted beyond the login packet. (Default) - * `true` - Data sent between client and server is encrypted. -* `app name` - The application name (default is go-mssqldb) - -### Connection parameters for ODBC and ADO style connection strings: - -* `server` - host or host\instance (default localhost) -* `port` - used only when there is no instance in server (default 1433) - -### Less common parameters: - -* `keepAlive` - in seconds; 0 to disable (default is 30) -* `failoverpartner` - host or host\instance (default is no partner). -* `failoverport` - used only when there is no instance in failoverpartner (default 1433) -* `packet size` - in bytes; 512 to 32767 (default is 4096) - * Encrypted connections have a maximum packet size of 16383 bytes - * Further information on usage: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option -* `log` - logging flags (default 0/no logging, 63 for full logging) - * 1 log errors - * 2 log messages - * 4 log rows affected - * 8 trace sql statements - * 16 log statement parameters - * 32 log transaction begin/end -* `TrustServerCertificate` - * false - Server certificate is checked. Default is false if encypt is specified. - * true - Server certificate is not checked. Default is true if encrypt is not specified. If trust server certificate is true, driver accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to man-in-the-middle attacks. This should be used only for testing. -* `certificate` - The file that contains the public key certificate of the CA that signed the SQL Server certificate. The specified certificate overrides the go platform specific CA certificates. -* `hostNameInCertificate` - Specifies the Common Name (CN) in the server certificate. Default value is the server host. -* `ServerSPN` - The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port. -* `Workstation ID` - The workstation name (default is the host name) -* `ApplicationIntent` - Can be given the value `ReadOnly` to initiate a read-only connection to an Availability Group listener. - -### The connection string can be specified in one of three formats: - - -1. URL: with `sqlserver` scheme. username and password appears before the host. Any instance appears as - the first segment in the path. All other options are query parameters. Examples: - - * `sqlserver://username:password@host/instance?param1=value¶m2=value` - * `sqlserver://username:password@host:port?param1=value¶m2=value` - * `sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30` // `SQLExpress instance. - * `sqlserver://sa:mypass@localhost?database=master&connection+timeout=30` // username=sa, password=mypass. - * `sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30` // port 1234 on localhost. - * `sqlserver://sa:my%7Bpass@somehost?connection+timeout=30` // password is "my{pass" - - A string of this format can be constructed using the `URL` type in the `net/url` package. - -```go - query := url.Values{} - query.Add("app name", "MyAppName") - - u := &url.URL{ - Scheme: "sqlserver", - User: url.UserPassword(username, password), - Host: fmt.Sprintf("%s:%d", hostname, port), - // Path: instance, // if connecting to an instance instead of a port - RawQuery: query.Encode(), - } - db, err := sql.Open("sqlserver", u.String()) -``` - -2. ADO: `key=value` pairs separated by `;`. Values may not contain `;`, leading and trailing whitespace is ignored. - Examples: - - * `server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName` - * `server=localhost;user id=sa;database=master;app name=MyAppName` - -3. ODBC: Prefix with `odbc`, `key=value` pairs separated by `;`. Allow `;` by wrapping - values in `{}`. Examples: - - * `odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName` - * `odbc:server=localhost;user id=sa;database=master;app name=MyAppName` - * `odbc:server=localhost;user id=sa;password={foo;bar}` // Value marked with `{}`, password is "foo;bar" - * `odbc:server=localhost;user id=sa;password={foo{bar}` // Value marked with `{}`, password is "foo{bar" - * `odbc:server=localhost;user id=sa;password={foobar }` // Value marked with `{}`, password is "foobar " - * `odbc:server=localhost;user id=sa;password=foo{bar` // Literal `{`, password is "foo{bar" - * `odbc:server=localhost;user id=sa;password=foo}bar` // Literal `}`, password is "foo}bar" - * `odbc:server=localhost;user id=sa;password={foo{bar}` // Literal `{`, password is "foo{bar" - * `odbc:server=localhost;user id=sa;password={foo}}bar}` // Escaped `} with `}}`, password is "foo}bar" - -## Executing Stored Procedures - -To run a stored procedure, set the query text to the procedure name: -```go -var account = "abc" -_, err := db.ExecContext(ctx, "sp_RunMe", - sql.Named("ID", 123), - sql.Named("Account", sql.Out{Dest: &account}), -) -``` - -## Return Status - -To get the procedure return status, pass into the parameters a -`*mssql.ReturnStatus`. For example: -``` -var rs mssql.ReturnStatus -_, err := db.ExecContext(ctx, "theproc", &rs) -log.Printf("status=%d", rs) -``` - -## Parameters - -The `sqlserver` driver uses normal MS SQL Server syntax and expects parameters in -the sql query to be in the form of either `@Name` or `@p1` to `@pN` (ordinal position). - -```go -db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob") -``` - -### Parameter Types - -To pass specific types to the query parameters, say `varchar` or `date` types, -you must convert the types to the type before passing in. The following types -are supported: - - * string -> nvarchar - * mssql.VarChar -> varchar - * time.Time -> datetimeoffset or datetime (TDS version dependent) - * mssql.DateTime1 -> datetime - * mssql.DateTimeOffset -> datetimeoffset - * "cloud.google.com/go/civil".Date -> date - * "cloud.google.com/go/civil".DateTime -> datetime2 - * "cloud.google.com/go/civil".Time -> time - -## Important Notes - - * [LastInsertId](https://golang.org/pkg/database/sql/#Result.LastInsertId) should - not be used with this driver (or SQL Server) due to how the TDS protocol - works. Please use the [OUTPUT Clause](https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql) - or add a `select ID = convert(bigint, SCOPE_IDENTITY());` to the end of your - query (ref [SCOPE_IDENTITY](https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql)). - This will ensure you are getting the correct ID and will prevent a network round trip. - * [NewConnector](https://godoc.org/github.com/denisenkom/go-mssqldb#NewConnector) - may be used with [OpenDB](https://golang.org/pkg/database/sql/#OpenDB). - * [Connector.SessionInitSQL](https://godoc.org/github.com/denisenkom/go-mssqldb#Connector.SessionInitSQL) - may be set to set any driver specific session settings after the session - has been reset. If empty the session will still be reset but use the database - defaults in Go1.10+. - -## Features - -* Can be used with SQL Server 2005 or newer -* Can be used with Microsoft Azure SQL Database -* Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows) -* Supports new date/time types: date, time, datetime2, datetimeoffset -* Supports string parameters longer than 8000 characters -* Supports encryption using SSL/TLS -* Supports SQL Server and Windows Authentication -* Supports Single-Sign-On on Windows -* Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas. -* Supports query notifications - -## Tests - -`go test` is used for testing. A running instance of MSSQL server is required. -Environment variables are used to pass login information. - -Example: - - env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test - -## Deprecated - -These features still exist in the driver, but they are are deprecated. - -### Query Parameter Token Replace (driver "mssql") - -If you use the driver name "mssql" (rather then "sqlserver") the SQL text -will be loosly parsed and an attempt to extract identifiers using one of - -* ? -* ?nnn -* :nnn -* $nnn - -will be used. This is not recommended with SQL Server. -There is at least one existing `won't fix` issue with the query parsing. - -Use the native "@Name" parameters instead with the "sqlserver" driver name. - -## Known Issues - -* SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled. -To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2. -To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3. -More information: http://support.microsoft.com/kb/2653857 diff --git a/vendor/github.com/denisenkom/go-mssqldb/appveyor.yml b/vendor/github.com/denisenkom/go-mssqldb/appveyor.yml deleted file mode 100644 index 2ae5456d5..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/appveyor.yml +++ /dev/null @@ -1,48 +0,0 @@ -version: 1.0.{build} - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\denisenkom\go-mssqldb - -environment: - GOPATH: c:\gopath - HOST: localhost - SQLUSER: sa - SQLPASSWORD: Password12! - DATABASE: test - GOVERSION: 110 - matrix: - - GOVERSION: 18 - SQLINSTANCE: SQL2016 - - GOVERSION: 19 - SQLINSTANCE: SQL2016 - - GOVERSION: 110 - SQLINSTANCE: SQL2016 - - SQLINSTANCE: SQL2014 - - SQLINSTANCE: SQL2012SP1 - - SQLINSTANCE: SQL2008R2SP2 - -install: - - set GOROOT=c:\go%GOVERSION% - - set PATH=%GOPATH%\bin;%GOROOT%\bin;%PATH% - - go version - - go env - - go get -u cloud.google.com/go/civil - -build_script: - - go build - -before_test: - # setup SQL Server - - ps: | - $instanceName = $env:SQLINSTANCE - Start-Service "MSSQL`$$instanceName" - Start-Service "SQLBrowser" - - sqlcmd -S "(local)\%SQLINSTANCE%" -Q "Use [master]; CREATE DATABASE test;" - - sqlcmd -S "(local)\%SQLINSTANCE%" -h -1 -Q "set nocount on; Select @@version" - - pip install codecov - - -test_script: - - go test -race -cpu 4 -coverprofile=coverage.txt -covermode=atomic - - codecov -f coverage.txt diff --git a/vendor/github.com/denisenkom/go-mssqldb/buf.go b/vendor/github.com/denisenkom/go-mssqldb/buf.go deleted file mode 100644 index 927d75d1b..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/buf.go +++ /dev/null @@ -1,258 +0,0 @@ -package mssql - -import ( - "encoding/binary" - "errors" - "io" -) - -type packetType uint8 - -type header struct { - PacketType packetType - Status uint8 - Size uint16 - Spid uint16 - PacketNo uint8 - Pad uint8 -} - -// tdsBuffer reads and writes TDS packets of data to the transport. -// The write and read buffers are separate to make sending attn signals -// possible without locks. Currently attn signals are only sent during -// reads, not writes. -type tdsBuffer struct { - transport io.ReadWriteCloser - - packetSize int - - // Write fields. - wbuf []byte - wpos int - wPacketSeq byte - wPacketType packetType - - // Read fields. - rbuf []byte - rpos int - rsize int - final bool - rPacketType packetType - - // afterFirst is assigned to right after tdsBuffer is created and - // before the first use. It is executed after the first packet is - // written and then removed. - afterFirst func() -} - -func newTdsBuffer(bufsize uint16, transport io.ReadWriteCloser) *tdsBuffer { - return &tdsBuffer{ - packetSize: int(bufsize), - wbuf: make([]byte, 1<<16), - rbuf: make([]byte, 1<<16), - rpos: 8, - transport: transport, - } -} - -func (rw *tdsBuffer) ResizeBuffer(packetSize int) { - rw.packetSize = packetSize -} - -func (w *tdsBuffer) PackageSize() int { - return w.packetSize -} - -func (w *tdsBuffer) flush() (err error) { - // Write packet size. - w.wbuf[0] = byte(w.wPacketType) - binary.BigEndian.PutUint16(w.wbuf[2:], uint16(w.wpos)) - w.wbuf[6] = w.wPacketSeq - - // Write packet into underlying transport. - if _, err = w.transport.Write(w.wbuf[:w.wpos]); err != nil { - return err - } - // It is possible to create a whole new buffer after a flush. - // Useful for debugging. Normally reuse the buffer. - // w.wbuf = make([]byte, 1<<16) - - // Execute afterFirst hook if it is set. - if w.afterFirst != nil { - w.afterFirst() - w.afterFirst = nil - } - - w.wpos = 8 - w.wPacketSeq++ - return nil -} - -func (w *tdsBuffer) Write(p []byte) (total int, err error) { - for { - copied := copy(w.wbuf[w.wpos:w.packetSize], p) - w.wpos += copied - total += copied - if copied == len(p) { - return - } - if err = w.flush(); err != nil { - return - } - p = p[copied:] - } -} - -func (w *tdsBuffer) WriteByte(b byte) error { - if int(w.wpos) == len(w.wbuf) || w.wpos == w.packetSize { - if err := w.flush(); err != nil { - return err - } - } - w.wbuf[w.wpos] = b - w.wpos += 1 - return nil -} - -func (w *tdsBuffer) BeginPacket(packetType packetType, resetSession bool) { - status := byte(0) - if resetSession { - switch packetType { - // Reset session can only be set on the following packet types. - case packSQLBatch, packRPCRequest, packTransMgrReq: - status = 0x8 - } - } - w.wbuf[1] = status // Packet is incomplete. This byte is set again in FinishPacket. - w.wpos = 8 - w.wPacketSeq = 1 - w.wPacketType = packetType -} - -func (w *tdsBuffer) FinishPacket() error { - w.wbuf[1] |= 1 // Mark this as the last packet in the message. - return w.flush() -} - -var headerSize = binary.Size(header{}) - -func (r *tdsBuffer) readNextPacket() error { - h := header{} - var err error - err = binary.Read(r.transport, binary.BigEndian, &h) - if err != nil { - return err - } - if int(h.Size) > r.packetSize { - return errors.New("Invalid packet size, it is longer than buffer size") - } - if headerSize > int(h.Size) { - return errors.New("Invalid packet size, it is shorter than header size") - } - _, err = io.ReadFull(r.transport, r.rbuf[headerSize:h.Size]) - if err != nil { - return err - } - r.rpos = headerSize - r.rsize = int(h.Size) - r.final = h.Status != 0 - r.rPacketType = h.PacketType - return nil -} - -func (r *tdsBuffer) BeginRead() (packetType, error) { - err := r.readNextPacket() - if err != nil { - return 0, err - } - return r.rPacketType, nil -} - -func (r *tdsBuffer) ReadByte() (res byte, err error) { - if r.rpos == r.rsize { - if r.final { - return 0, io.EOF - } - err = r.readNextPacket() - if err != nil { - return 0, err - } - } - res = r.rbuf[r.rpos] - r.rpos++ - return res, nil -} - -func (r *tdsBuffer) byte() byte { - b, err := r.ReadByte() - if err != nil { - badStreamPanic(err) - } - return b -} - -func (r *tdsBuffer) ReadFull(buf []byte) { - _, err := io.ReadFull(r, buf[:]) - if err != nil { - badStreamPanic(err) - } -} - -func (r *tdsBuffer) uint64() uint64 { - var buf [8]byte - r.ReadFull(buf[:]) - return binary.LittleEndian.Uint64(buf[:]) -} - -func (r *tdsBuffer) int32() int32 { - return int32(r.uint32()) -} - -func (r *tdsBuffer) uint32() uint32 { - var buf [4]byte - r.ReadFull(buf[:]) - return binary.LittleEndian.Uint32(buf[:]) -} - -func (r *tdsBuffer) uint16() uint16 { - var buf [2]byte - r.ReadFull(buf[:]) - return binary.LittleEndian.Uint16(buf[:]) -} - -func (r *tdsBuffer) BVarChar() string { - l := int(r.byte()) - return r.readUcs2(l) -} - -func (r *tdsBuffer) UsVarChar() string { - l := int(r.uint16()) - return r.readUcs2(l) -} - -func (r *tdsBuffer) readUcs2(numchars int) string { - b := make([]byte, numchars*2) - r.ReadFull(b) - res, err := ucs22str(b) - if err != nil { - badStreamPanic(err) - } - return res -} - -func (r *tdsBuffer) Read(buf []byte) (copied int, err error) { - copied = 0 - err = nil - if r.rpos == r.rsize { - if r.final { - return 0, io.EOF - } - err = r.readNextPacket() - if err != nil { - return - } - } - copied = copy(buf, r.rbuf[r.rpos:r.rsize]) - r.rpos += copied - return -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/bulkcopy.go b/vendor/github.com/denisenkom/go-mssqldb/bulkcopy.go deleted file mode 100644 index 3b319af89..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/bulkcopy.go +++ /dev/null @@ -1,554 +0,0 @@ -package mssql - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "math" - "reflect" - "strconv" - "strings" - "time" -) - -type Bulk struct { - // ctx is used only for AddRow and Done methods. - // This could be removed if AddRow and Done accepted - // a ctx field as well, which is available with the - // database/sql call. - ctx context.Context - - cn *Conn - metadata []columnStruct - bulkColumns []columnStruct - columnsName []string - tablename string - numRows int - - headerSent bool - Options BulkOptions - Debug bool -} -type BulkOptions struct { - CheckConstraints bool - FireTriggers bool - KeepNulls bool - KilobytesPerBatch int - RowsPerBatch int - Order []string - Tablock bool -} - -type DataValue interface{} - -func (cn *Conn) CreateBulk(table string, columns []string) (_ *Bulk) { - b := Bulk{ctx: context.Background(), cn: cn, tablename: table, headerSent: false, columnsName: columns} - b.Debug = false - return &b -} - -func (cn *Conn) CreateBulkContext(ctx context.Context, table string, columns []string) (_ *Bulk) { - b := Bulk{ctx: ctx, cn: cn, tablename: table, headerSent: false, columnsName: columns} - b.Debug = false - return &b -} - -func (b *Bulk) sendBulkCommand(ctx context.Context) (err error) { - //get table columns info - err = b.getMetadata(ctx) - if err != nil { - return err - } - - //match the columns - for _, colname := range b.columnsName { - var bulkCol *columnStruct - - for _, m := range b.metadata { - if m.ColName == colname { - bulkCol = &m - break - } - } - if bulkCol != nil { - - if bulkCol.ti.TypeId == typeUdt { - //send udt as binary - bulkCol.ti.TypeId = typeBigVarBin - } - b.bulkColumns = append(b.bulkColumns, *bulkCol) - b.dlogf("Adding column %s %s %#x", colname, bulkCol.ColName, bulkCol.ti.TypeId) - } else { - return fmt.Errorf("Column %s does not exist in destination table %s", colname, b.tablename) - } - } - - //create the bulk command - - //columns definitions - var col_defs bytes.Buffer - for i, col := range b.bulkColumns { - if i != 0 { - col_defs.WriteString(", ") - } - col_defs.WriteString("[" + col.ColName + "] " + makeDecl(col.ti)) - } - - //options - var with_opts []string - - if b.Options.CheckConstraints { - with_opts = append(with_opts, "CHECK_CONSTRAINTS") - } - if b.Options.FireTriggers { - with_opts = append(with_opts, "FIRE_TRIGGERS") - } - if b.Options.KeepNulls { - with_opts = append(with_opts, "KEEP_NULLS") - } - if b.Options.KilobytesPerBatch > 0 { - with_opts = append(with_opts, fmt.Sprintf("KILOBYTES_PER_BATCH = %d", b.Options.KilobytesPerBatch)) - } - if b.Options.RowsPerBatch > 0 { - with_opts = append(with_opts, fmt.Sprintf("ROWS_PER_BATCH = %d", b.Options.RowsPerBatch)) - } - if len(b.Options.Order) > 0 { - with_opts = append(with_opts, fmt.Sprintf("ORDER(%s)", strings.Join(b.Options.Order, ","))) - } - if b.Options.Tablock { - with_opts = append(with_opts, "TABLOCK") - } - var with_part string - if len(with_opts) > 0 { - with_part = fmt.Sprintf("WITH (%s)", strings.Join(with_opts, ",")) - } - - query := fmt.Sprintf("INSERT BULK %s (%s) %s", b.tablename, col_defs.String(), with_part) - - stmt, err := b.cn.PrepareContext(ctx, query) - if err != nil { - return fmt.Errorf("Prepare failed: %s", err.Error()) - } - b.dlogf(query) - - _, err = stmt.(*Stmt).ExecContext(ctx, nil) - if err != nil { - return err - } - - b.headerSent = true - - var buf = b.cn.sess.buf - buf.BeginPacket(packBulkLoadBCP, false) - - // Send the columns metadata. - columnMetadata := b.createColMetadata() - _, err = buf.Write(columnMetadata) - - return -} - -// AddRow immediately writes the row to the destination table. -// The arguments are the row values in the order they were specified. -func (b *Bulk) AddRow(row []interface{}) (err error) { - if !b.headerSent { - err = b.sendBulkCommand(b.ctx) - if err != nil { - return - } - } - - if len(row) != len(b.bulkColumns) { - return fmt.Errorf("Row does not have the same number of columns than the destination table %d %d", - len(row), len(b.bulkColumns)) - } - - bytes, err := b.makeRowData(row) - if err != nil { - return - } - - _, err = b.cn.sess.buf.Write(bytes) - if err != nil { - return - } - - b.numRows = b.numRows + 1 - return -} - -func (b *Bulk) makeRowData(row []interface{}) ([]byte, error) { - buf := new(bytes.Buffer) - buf.WriteByte(byte(tokenRow)) - - var logcol bytes.Buffer - for i, col := range b.bulkColumns { - - if b.Debug { - logcol.WriteString(fmt.Sprintf(" col[%d]='%v' ", i, row[i])) - } - param, err := b.makeParam(row[i], col) - if err != nil { - return nil, fmt.Errorf("bulkcopy: %s", err.Error()) - } - - if col.ti.Writer == nil { - return nil, fmt.Errorf("no writer for column: %s, TypeId: %#x", - col.ColName, col.ti.TypeId) - } - err = col.ti.Writer(buf, param.ti, param.buffer) - if err != nil { - return nil, fmt.Errorf("bulkcopy: %s", err.Error()) - } - } - - b.dlogf("row[%d] %s\n", b.numRows, logcol.String()) - - return buf.Bytes(), nil -} - -func (b *Bulk) Done() (rowcount int64, err error) { - if b.headerSent == false { - //no rows had been sent - return 0, nil - } - var buf = b.cn.sess.buf - buf.WriteByte(byte(tokenDone)) - - binary.Write(buf, binary.LittleEndian, uint16(doneFinal)) - binary.Write(buf, binary.LittleEndian, uint16(0)) // curcmd - - if b.cn.sess.loginAck.TDSVersion >= verTDS72 { - binary.Write(buf, binary.LittleEndian, uint64(0)) //rowcount 0 - } else { - binary.Write(buf, binary.LittleEndian, uint32(0)) //rowcount 0 - } - - buf.FinishPacket() - - tokchan := make(chan tokenStruct, 5) - go processResponse(b.ctx, b.cn.sess, tokchan, nil) - - var rowCount int64 - for token := range tokchan { - switch token := token.(type) { - case doneStruct: - if token.Status&doneCount != 0 { - rowCount = int64(token.RowCount) - } - if token.isError() { - return 0, token.getError() - } - case error: - return 0, b.cn.checkBadConn(token) - } - } - return rowCount, nil -} - -func (b *Bulk) createColMetadata() []byte { - buf := new(bytes.Buffer) - buf.WriteByte(byte(tokenColMetadata)) // token - binary.Write(buf, binary.LittleEndian, uint16(len(b.bulkColumns))) // column count - - for i, col := range b.bulkColumns { - - if b.cn.sess.loginAck.TDSVersion >= verTDS72 { - binary.Write(buf, binary.LittleEndian, uint32(col.UserType)) // usertype, always 0? - } else { - binary.Write(buf, binary.LittleEndian, uint16(col.UserType)) - } - binary.Write(buf, binary.LittleEndian, uint16(col.Flags)) - - writeTypeInfo(buf, &b.bulkColumns[i].ti) - - if col.ti.TypeId == typeNText || - col.ti.TypeId == typeText || - col.ti.TypeId == typeImage { - - tablename_ucs2 := str2ucs2(b.tablename) - binary.Write(buf, binary.LittleEndian, uint16(len(tablename_ucs2)/2)) - buf.Write(tablename_ucs2) - } - colname_ucs2 := str2ucs2(col.ColName) - buf.WriteByte(uint8(len(colname_ucs2) / 2)) - buf.Write(colname_ucs2) - } - - return buf.Bytes() -} - -func (b *Bulk) getMetadata(ctx context.Context) (err error) { - stmt, err := b.cn.prepareContext(ctx, "SET FMTONLY ON") - if err != nil { - return - } - - _, err = stmt.ExecContext(ctx, nil) - if err != nil { - return - } - - // Get columns info. - stmt, err = b.cn.prepareContext(ctx, fmt.Sprintf("select * from %s SET FMTONLY OFF", b.tablename)) - if err != nil { - return - } - rows, err := stmt.QueryContext(ctx, nil) - if err != nil { - return fmt.Errorf("get columns info failed: %v", err) - } - b.metadata = rows.(*Rows).cols - - if b.Debug { - for _, col := range b.metadata { - b.dlogf("col: %s typeId: %#x size: %d scale: %d prec: %d flags: %d lcid: %#x\n", - col.ColName, col.ti.TypeId, col.ti.Size, col.ti.Scale, col.ti.Prec, - col.Flags, col.ti.Collation.LcidAndFlags) - } - } - - return rows.Close() -} - -func (b *Bulk) makeParam(val DataValue, col columnStruct) (res param, err error) { - res.ti.Size = col.ti.Size - res.ti.TypeId = col.ti.TypeId - - if val == nil { - res.ti.Size = 0 - return - } - - switch col.ti.TypeId { - - case typeInt1, typeInt2, typeInt4, typeInt8, typeIntN: - var intvalue int64 - - switch val := val.(type) { - case int: - intvalue = int64(val) - case int32: - intvalue = int64(val) - case int64: - intvalue = val - default: - err = fmt.Errorf("mssql: invalid type for int column") - return - } - - res.buffer = make([]byte, res.ti.Size) - if col.ti.Size == 1 { - res.buffer[0] = byte(intvalue) - } else if col.ti.Size == 2 { - binary.LittleEndian.PutUint16(res.buffer, uint16(intvalue)) - } else if col.ti.Size == 4 { - binary.LittleEndian.PutUint32(res.buffer, uint32(intvalue)) - } else if col.ti.Size == 8 { - binary.LittleEndian.PutUint64(res.buffer, uint64(intvalue)) - } - case typeFlt4, typeFlt8, typeFltN: - var floatvalue float64 - - switch val := val.(type) { - case float32: - floatvalue = float64(val) - case float64: - floatvalue = val - case int: - floatvalue = float64(val) - case int64: - floatvalue = float64(val) - default: - err = fmt.Errorf("mssql: invalid type for float column: %s", val) - return - } - - if col.ti.Size == 4 { - res.buffer = make([]byte, 4) - binary.LittleEndian.PutUint32(res.buffer, math.Float32bits(float32(floatvalue))) - } else if col.ti.Size == 8 { - res.buffer = make([]byte, 8) - binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(floatvalue)) - } - case typeNVarChar, typeNText, typeNChar: - - switch val := val.(type) { - case string: - res.buffer = str2ucs2(val) - case []byte: - res.buffer = val - default: - err = fmt.Errorf("mssql: invalid type for nvarchar column: %s", val) - return - } - res.ti.Size = len(res.buffer) - - case typeVarChar, typeBigVarChar, typeText, typeChar, typeBigChar: - switch val := val.(type) { - case string: - res.buffer = []byte(val) - case []byte: - res.buffer = val - default: - err = fmt.Errorf("mssql: invalid type for varchar column: %s", val) - return - } - res.ti.Size = len(res.buffer) - - case typeBit, typeBitN: - if reflect.TypeOf(val).Kind() != reflect.Bool { - err = fmt.Errorf("mssql: invalid type for bit column: %s", val) - return - } - res.ti.TypeId = typeBitN - res.ti.Size = 1 - res.buffer = make([]byte, 1) - if val.(bool) { - res.buffer[0] = 1 - } - case typeDateTime2N: - switch val := val.(type) { - case time.Time: - res.buffer = encodeDateTime2(val, int(col.ti.Scale)) - res.ti.Size = len(res.buffer) - default: - err = fmt.Errorf("mssql: invalid type for datetime2 column: %s", val) - return - } - case typeDateTimeOffsetN: - switch val := val.(type) { - case time.Time: - res.buffer = encodeDateTimeOffset(val, int(res.ti.Scale)) - res.ti.Size = len(res.buffer) - - default: - err = fmt.Errorf("mssql: invalid type for datetimeoffset column: %s", val) - return - } - case typeDateN: - switch val := val.(type) { - case time.Time: - res.buffer = encodeDate(val) - res.ti.Size = len(res.buffer) - default: - err = fmt.Errorf("mssql: invalid type for date column: %s", val) - return - } - case typeDateTime, typeDateTimeN, typeDateTim4: - switch val := val.(type) { - case time.Time: - if col.ti.Size == 4 { - res.buffer = encodeDateTim4(val) - res.ti.Size = len(res.buffer) - } else if col.ti.Size == 8 { - res.buffer = encodeDateTime(val) - res.ti.Size = len(res.buffer) - } else { - err = fmt.Errorf("mssql: invalid size of column") - } - - default: - err = fmt.Errorf("mssql: invalid type for datetime column: %s", val) - } - - // case typeMoney, typeMoney4, typeMoneyN: - case typeDecimal, typeDecimalN, typeNumeric, typeNumericN: - var value float64 - switch v := val.(type) { - case int: - value = float64(v) - case int8: - value = float64(v) - case int16: - value = float64(v) - case int32: - value = float64(v) - case int64: - value = float64(v) - case float32: - value = float64(v) - case float64: - value = v - case string: - if value, err = strconv.ParseFloat(v, 64); err != nil { - return res, fmt.Errorf("bulk: unable to convert string to float: %v", err) - } - default: - return res, fmt.Errorf("unknown value for decimal: %#v", v) - } - - perc := col.ti.Prec - scale := col.ti.Scale - var dec Decimal - dec, err = Float64ToDecimalScale(value, scale) - if err != nil { - return res, err - } - dec.prec = perc - - var length byte - switch { - case perc <= 9: - length = 4 - case perc <= 19: - length = 8 - case perc <= 28: - length = 12 - default: - length = 16 - } - - buf := make([]byte, length+1) - // first byte length written by typeInfo.writer - res.ti.Size = int(length) + 1 - // second byte sign - if value < 0 { - buf[0] = 0 - } else { - buf[0] = 1 - } - - ub := dec.UnscaledBytes() - l := len(ub) - if l > int(length) { - err = fmt.Errorf("decimal out of range: %s", dec) - return res, err - } - // reverse the bytes - for i, j := 1, l-1; j >= 0; i, j = i+1, j-1 { - buf[i] = ub[j] - } - res.buffer = buf - case typeBigVarBin, typeBigBinary: - switch val := val.(type) { - case []byte: - res.ti.Size = len(val) - res.buffer = val - default: - err = fmt.Errorf("mssql: invalid type for Binary column: %s", val) - return - } - case typeGuid: - switch val := val.(type) { - case []byte: - res.ti.Size = len(val) - res.buffer = val - default: - err = fmt.Errorf("mssql: invalid type for Guid column: %s", val) - return - } - - default: - err = fmt.Errorf("mssql: type %x not implemented", col.ti.TypeId) - } - return - -} - -func (b *Bulk) dlogf(format string, v ...interface{}) { - if b.Debug { - b.cn.sess.log.Printf(format, v...) - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/bulkcopy_sql.go b/vendor/github.com/denisenkom/go-mssqldb/bulkcopy_sql.go deleted file mode 100644 index 4824df9ad..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/bulkcopy_sql.go +++ /dev/null @@ -1,93 +0,0 @@ -package mssql - -import ( - "context" - "database/sql/driver" - "encoding/json" - "errors" -) - -type copyin struct { - cn *Conn - bulkcopy *Bulk - closed bool -} - -type serializableBulkConfig struct { - TableName string - ColumnsName []string - Options BulkOptions -} - -func (d *Driver) OpenConnection(dsn string) (*Conn, error) { - return d.open(context.Background(), dsn) -} - -func (c *Conn) prepareCopyIn(ctx context.Context, query string) (_ driver.Stmt, err error) { - config_json := query[11:] - - bulkconfig := serializableBulkConfig{} - err = json.Unmarshal([]byte(config_json), &bulkconfig) - if err != nil { - return - } - - bulkcopy := c.CreateBulkContext(ctx, bulkconfig.TableName, bulkconfig.ColumnsName) - bulkcopy.Options = bulkconfig.Options - - ci := ©in{ - cn: c, - bulkcopy: bulkcopy, - } - - return ci, nil -} - -func CopyIn(table string, options BulkOptions, columns ...string) string { - bulkconfig := &serializableBulkConfig{TableName: table, Options: options, ColumnsName: columns} - - config_json, err := json.Marshal(bulkconfig) - if err != nil { - panic(err) - } - - stmt := "INSERTBULK " + string(config_json) - - return stmt -} - -func (ci *copyin) NumInput() int { - return -1 -} - -func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { - panic("should never be called") -} - -func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { - if ci.closed { - return nil, errors.New("errCopyInClosed") - } - - if len(v) == 0 { - rowCount, err := ci.bulkcopy.Done() - ci.closed = true - return driver.RowsAffected(rowCount), err - } - - t := make([]interface{}, len(v)) - for i, val := range v { - t[i] = val - } - - err = ci.bulkcopy.AddRow(t) - if err != nil { - return - } - - return driver.RowsAffected(0), nil -} - -func (ci *copyin) Close() (err error) { - return nil -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/convert.go b/vendor/github.com/denisenkom/go-mssqldb/convert.go deleted file mode 100644 index 51bd4ee3a..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/convert.go +++ /dev/null @@ -1,306 +0,0 @@ -package mssql - -import "errors" - -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Type conversions for Scan. - -// This file was imported from database.sql.convert for go 1.10.3 with minor modifications to get -// convertAssign function -// This function is used internally by sql to convert values during call to Scan, we need same -// logic to return values for OUTPUT parameters. -// TODO: sql library should instead expose function defaultCheckNamedValue to be callable by drivers - -import ( - "database/sql" - "database/sql/driver" - "fmt" - "reflect" - "strconv" - "time" -) - -var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error - -// convertAssign copies to dest the value in src, converting it if possible. -// An error is returned if the copy would result in loss of information. -// dest should be a pointer type. -func convertAssign(dest, src interface{}) error { - // Common cases, without reflect. - switch s := src.(type) { - case string: - switch d := dest.(type) { - case *string: - if d == nil { - return errNilPtr - } - *d = s - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = []byte(s) - return nil - case *sql.RawBytes: - if d == nil { - return errNilPtr - } - *d = append((*d)[:0], s...) - return nil - } - case []byte: - switch d := dest.(type) { - case *string: - if d == nil { - return errNilPtr - } - *d = string(s) - return nil - case *interface{}: - if d == nil { - return errNilPtr - } - *d = cloneBytes(s) - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = cloneBytes(s) - return nil - case *sql.RawBytes: - if d == nil { - return errNilPtr - } - *d = s - return nil - } - case time.Time: - switch d := dest.(type) { - case *time.Time: - *d = s - return nil - case *string: - *d = s.Format(time.RFC3339Nano) - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = []byte(s.Format(time.RFC3339Nano)) - return nil - case *sql.RawBytes: - if d == nil { - return errNilPtr - } - *d = s.AppendFormat((*d)[:0], time.RFC3339Nano) - return nil - } - case nil: - switch d := dest.(type) { - case *interface{}: - if d == nil { - return errNilPtr - } - *d = nil - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = nil - return nil - case *sql.RawBytes: - if d == nil { - return errNilPtr - } - *d = nil - return nil - } - } - - var sv reflect.Value - - switch d := dest.(type) { - case *string: - sv = reflect.ValueOf(src) - switch sv.Kind() { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - *d = asString(src) - return nil - } - case *[]byte: - sv = reflect.ValueOf(src) - if b, ok := asBytes(nil, sv); ok { - *d = b - return nil - } - case *sql.RawBytes: - sv = reflect.ValueOf(src) - if b, ok := asBytes([]byte(*d)[:0], sv); ok { - *d = sql.RawBytes(b) - return nil - } - case *bool: - bv, err := driver.Bool.ConvertValue(src) - if err == nil { - *d = bv.(bool) - } - return err - case *interface{}: - *d = src - return nil - } - - if scanner, ok := dest.(sql.Scanner); ok { - return scanner.Scan(src) - } - - dpv := reflect.ValueOf(dest) - if dpv.Kind() != reflect.Ptr { - return errors.New("destination not a pointer") - } - if dpv.IsNil() { - return errNilPtr - } - - if !sv.IsValid() { - sv = reflect.ValueOf(src) - } - - dv := reflect.Indirect(dpv) - if sv.IsValid() && sv.Type().AssignableTo(dv.Type()) { - switch b := src.(type) { - case []byte: - dv.Set(reflect.ValueOf(cloneBytes(b))) - default: - dv.Set(sv) - } - return nil - } - - if dv.Kind() == sv.Kind() && sv.Type().ConvertibleTo(dv.Type()) { - dv.Set(sv.Convert(dv.Type())) - return nil - } - - // The following conversions use a string value as an intermediate representation - // to convert between various numeric types. - // - // This also allows scanning into user defined types such as "type Int int64". - // For symmetry, also check for string destination types. - switch dv.Kind() { - case reflect.Ptr: - if src == nil { - dv.Set(reflect.Zero(dv.Type())) - return nil - } else { - dv.Set(reflect.New(dv.Type().Elem())) - return convertAssign(dv.Interface(), src) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - s := asString(src) - i64, err := strconv.ParseInt(s, 10, dv.Type().Bits()) - if err != nil { - err = strconvErr(err) - return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err) - } - dv.SetInt(i64) - return nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - s := asString(src) - u64, err := strconv.ParseUint(s, 10, dv.Type().Bits()) - if err != nil { - err = strconvErr(err) - return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err) - } - dv.SetUint(u64) - return nil - case reflect.Float32, reflect.Float64: - s := asString(src) - f64, err := strconv.ParseFloat(s, dv.Type().Bits()) - if err != nil { - err = strconvErr(err) - return fmt.Errorf("converting driver.Value type %T (%q) to a %s: %v", src, s, dv.Kind(), err) - } - dv.SetFloat(f64) - return nil - case reflect.String: - switch v := src.(type) { - case string: - dv.SetString(v) - return nil - case []byte: - dv.SetString(string(v)) - return nil - } - } - - return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, dest) -} - -func strconvErr(err error) error { - if ne, ok := err.(*strconv.NumError); ok { - return ne.Err - } - return err -} - -func cloneBytes(b []byte) []byte { - if b == nil { - return nil - } else { - c := make([]byte, len(b)) - copy(c, b) - return c - } -} - -func asString(src interface{}) string { - switch v := src.(type) { - case string: - return v - case []byte: - return string(v) - } - rv := reflect.ValueOf(src) - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.FormatInt(rv.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return strconv.FormatUint(rv.Uint(), 10) - case reflect.Float64: - return strconv.FormatFloat(rv.Float(), 'g', -1, 64) - case reflect.Float32: - return strconv.FormatFloat(rv.Float(), 'g', -1, 32) - case reflect.Bool: - return strconv.FormatBool(rv.Bool()) - } - return fmt.Sprintf("%v", src) -} - -func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.AppendInt(buf, rv.Int(), 10), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return strconv.AppendUint(buf, rv.Uint(), 10), true - case reflect.Float32: - return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true - case reflect.Float64: - return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true - case reflect.Bool: - return strconv.AppendBool(buf, rv.Bool()), true - case reflect.String: - s := rv.String() - return append(buf, s...), true - } - return -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/decimal.go b/vendor/github.com/denisenkom/go-mssqldb/decimal.go deleted file mode 100644 index 372f64b4e..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/decimal.go +++ /dev/null @@ -1,131 +0,0 @@ -package mssql - -import ( - "encoding/binary" - "errors" - "math" - "math/big" -) - -// http://msdn.microsoft.com/en-us/library/ee780893.aspx -type Decimal struct { - integer [4]uint32 - positive bool - prec uint8 - scale uint8 -} - -var scaletblflt64 [39]float64 - -func (d Decimal) ToFloat64() float64 { - val := float64(0) - for i := 3; i >= 0; i-- { - val *= 0x100000000 - val += float64(d.integer[i]) - } - if !d.positive { - val = -val - } - if d.scale != 0 { - val /= scaletblflt64[d.scale] - } - return val -} - -const autoScale = 100 - -func Float64ToDecimal(f float64) (Decimal, error) { - return Float64ToDecimalScale(f, autoScale) -} - -func Float64ToDecimalScale(f float64, scale uint8) (Decimal, error) { - var dec Decimal - if math.IsNaN(f) { - return dec, errors.New("NaN") - } - if math.IsInf(f, 0) { - return dec, errors.New("Infinity can't be converted to decimal") - } - dec.positive = f >= 0 - if !dec.positive { - f = math.Abs(f) - } - if f > 3.402823669209385e+38 { - return dec, errors.New("Float value is out of range") - } - dec.prec = 20 - var integer float64 - for dec.scale = 0; dec.scale <= scale; dec.scale++ { - integer = f * scaletblflt64[dec.scale] - _, frac := math.Modf(integer) - if frac == 0 && scale == autoScale { - break - } - } - for i := 0; i < 4; i++ { - mod := math.Mod(integer, 0x100000000) - integer -= mod - integer /= 0x100000000 - dec.integer[i] = uint32(mod) - } - return dec, nil -} - -func init() { - var acc float64 = 1 - for i := 0; i <= 38; i++ { - scaletblflt64[i] = acc - acc *= 10 - } -} - -func (d Decimal) BigInt() big.Int { - bytes := make([]byte, 16) - binary.BigEndian.PutUint32(bytes[0:4], d.integer[3]) - binary.BigEndian.PutUint32(bytes[4:8], d.integer[2]) - binary.BigEndian.PutUint32(bytes[8:12], d.integer[1]) - binary.BigEndian.PutUint32(bytes[12:16], d.integer[0]) - var x big.Int - x.SetBytes(bytes) - if !d.positive { - x.Neg(&x) - } - return x -} - -func (d Decimal) Bytes() []byte { - x := d.BigInt() - return scaleBytes(x.String(), d.scale) -} - -func (d Decimal) UnscaledBytes() []byte { - x := d.BigInt() - return x.Bytes() -} - -func scaleBytes(s string, scale uint8) []byte { - z := make([]byte, 0, len(s)+1) - if s[0] == '-' || s[0] == '+' { - z = append(z, byte(s[0])) - s = s[1:] - } - pos := len(s) - int(scale) - if pos <= 0 { - z = append(z, byte('0')) - } else if pos > 0 { - z = append(z, []byte(s[:pos])...) - } - if scale > 0 { - z = append(z, byte('.')) - for pos < 0 { - z = append(z, byte('0')) - pos++ - } - z = append(z, []byte(s[pos:])...) - } - return z -} - -func (d Decimal) String() string { - return string(d.Bytes()) -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/doc.go b/vendor/github.com/denisenkom/go-mssqldb/doc.go deleted file mode 100644 index 2e54929c5..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/doc.go +++ /dev/null @@ -1,14 +0,0 @@ -// package mssql implements the TDS protocol used to connect to MS SQL Server (sqlserver) -// database servers. -// -// This package registers the driver: -// sqlserver: uses native "@" parameter placeholder names and does no pre-processing. -// -// If the ordinal position is used for query parameters, identifiers will be named -// "@p1", "@p2", ... "@pN". -// -// Please refer to the README for the format of the DSN. There are multiple DSN -// formats accepted: ADO style, ODBC style, and URL style. The following is an -// example of a URL style DSN: -// sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30 -package mssql diff --git a/vendor/github.com/denisenkom/go-mssqldb/error.go b/vendor/github.com/denisenkom/go-mssqldb/error.go deleted file mode 100644 index 2e5baceec..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/error.go +++ /dev/null @@ -1,73 +0,0 @@ -package mssql - -import ( - "fmt" -) - -// Error represents an SQL Server error. This -// type includes methods for reading the contents -// of the struct, which allows calling programs -// to check for specific error conditions without -// having to import this package directly. -type Error struct { - Number int32 - State uint8 - Class uint8 - Message string - ServerName string - ProcName string - LineNo int32 -} - -func (e Error) Error() string { - return "mssql: " + e.Message -} - -// SQLErrorNumber returns the SQL Server error number. -func (e Error) SQLErrorNumber() int32 { - return e.Number -} - -func (e Error) SQLErrorState() uint8 { - return e.State -} - -func (e Error) SQLErrorClass() uint8 { - return e.Class -} - -func (e Error) SQLErrorMessage() string { - return e.Message -} - -func (e Error) SQLErrorServerName() string { - return e.ServerName -} - -func (e Error) SQLErrorProcName() string { - return e.ProcName -} - -func (e Error) SQLErrorLineNo() int32 { - return e.LineNo -} - -type StreamError struct { - Message string -} - -func (e StreamError) Error() string { - return e.Message -} - -func streamErrorf(format string, v ...interface{}) StreamError { - return StreamError{"Invalid TDS stream: " + fmt.Sprintf(format, v...)} -} - -func badStreamPanic(err error) { - panic(err) -} - -func badStreamPanicf(format string, v ...interface{}) { - panic(streamErrorf(format, v...)) -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/log.go b/vendor/github.com/denisenkom/go-mssqldb/log.go deleted file mode 100644 index 9b8c551e8..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/log.go +++ /dev/null @@ -1,30 +0,0 @@ -package mssql - -import ( - "log" -) - -type Logger interface { - Printf(format string, v ...interface{}) - Println(v ...interface{}) -} - -type optionalLogger struct { - logger Logger -} - -func (o optionalLogger) Printf(format string, v ...interface{}) { - if o.logger != nil { - o.logger.Printf(format, v...) - } else { - log.Printf(format, v...) - } -} - -func (o optionalLogger) Println(v ...interface{}) { - if o.logger != nil { - o.logger.Println(v...) - } else { - log.Println(v...) - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/mssql.go b/vendor/github.com/denisenkom/go-mssqldb/mssql.go deleted file mode 100644 index aa173b3ed..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/mssql.go +++ /dev/null @@ -1,962 +0,0 @@ -package mssql - -import ( - "context" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "net" - "reflect" - "strings" - "time" - "unicode" -) - -// ReturnStatus may be used to return the return value from a proc. -// -// var rs mssql.ReturnStatus -// _, err := db.Exec("theproc", &rs) -// log.Printf("return status = %d", rs) -type ReturnStatus int32 - -var driverInstance = &Driver{processQueryText: true} -var driverInstanceNoProcess = &Driver{processQueryText: false} - -func init() { - sql.Register("mssql", driverInstance) - sql.Register("sqlserver", driverInstanceNoProcess) - createDialer = func(p *connectParams) dialer { - return tcpDialer{&net.Dialer{KeepAlive: p.keepAlive}} - } -} - -// Abstract the dialer for testing and for non-TCP based connections. -type dialer interface { - Dial(ctx context.Context, addr string) (net.Conn, error) -} - -var createDialer func(p *connectParams) dialer - -type tcpDialer struct { - nd *net.Dialer -} - -func (d tcpDialer) Dial(ctx context.Context, addr string) (net.Conn, error) { - return d.nd.DialContext(ctx, "tcp", addr) -} - -type Driver struct { - log optionalLogger - - processQueryText bool -} - -// OpenConnector opens a new connector. Useful to dial with a context. -func (d *Driver) OpenConnector(dsn string) (*Connector, error) { - params, err := parseConnectParams(dsn) - if err != nil { - return nil, err - } - return &Connector{ - params: params, - driver: d, - }, nil -} - -func (d *Driver) Open(dsn string) (driver.Conn, error) { - return d.open(context.Background(), dsn) -} - -func SetLogger(logger Logger) { - driverInstance.SetLogger(logger) - driverInstanceNoProcess.SetLogger(logger) -} - -func (d *Driver) SetLogger(logger Logger) { - d.log = optionalLogger{logger} -} - -// NewConnector creates a new connector from a DSN. -// The returned connector may be used with sql.OpenDB. -func NewConnector(dsn string) (*Connector, error) { - params, err := parseConnectParams(dsn) - if err != nil { - return nil, err - } - c := &Connector{ - params: params, - driver: driverInstanceNoProcess, - } - return c, nil -} - -// Connector holds the parsed DSN and is ready to make a new connection -// at any time. -// -// In the future, settings that cannot be passed through a string DSN -// may be set directly on the connector. -type Connector struct { - params connectParams - driver *Driver - - // SessionInitSQL is executed after marking a given session to be reset. - // When not present, the next query will still reset the session to the - // database defaults. - // - // When present the connection will immediately mark the session to - // be reset, then execute the SessionInitSQL text to setup the session - // that may be different from the base database defaults. - // - // For Example, the application relies on the following defaults - // but is not allowed to set them at the database system level. - // - // SET XACT_ABORT ON; - // SET TEXTSIZE -1; - // SET ANSI_NULLS ON; - // SET LOCK_TIMEOUT 10000; - // - // SessionInitSQL should not attempt to manually call sp_reset_connection. - // This will happen at the TDS layer. - // - // SessionInitSQL is optional. The session will be reset even if - // SessionInitSQL is empty. - SessionInitSQL string -} - -type Conn struct { - connector *Connector - sess *tdsSession - transactionCtx context.Context - resetSession bool - - processQueryText bool - connectionGood bool - - outs map[string]interface{} - returnStatus *ReturnStatus -} - -func (c *Conn) setReturnStatus(s ReturnStatus) { - if c.returnStatus == nil { - return - } - *c.returnStatus = s -} - -func (c *Conn) checkBadConn(err error) error { - // this is a hack to address Issue #275 - // we set connectionGood flag to false if - // error indicates that connection is not usable - // but we return actual error instead of ErrBadConn - // this will cause connection to stay in a pool - // but next request to this connection will return ErrBadConn - - // it might be possible to revise this hack after - // https://github.com/golang/go/issues/20807 - // is implemented - switch err { - case nil: - return nil - case io.EOF: - c.connectionGood = false - return driver.ErrBadConn - case driver.ErrBadConn: - // It is an internal programming error if driver.ErrBadConn - // is ever passed to this function. driver.ErrBadConn should - // only ever be returned in response to a *mssql.Conn.connectionGood == false - // check in the external facing API. - panic("driver.ErrBadConn in checkBadConn. This should not happen.") - } - - switch err.(type) { - case net.Error: - c.connectionGood = false - return err - case StreamError: - c.connectionGood = false - return err - default: - return err - } -} - -func (c *Conn) clearOuts() { - c.outs = nil -} - -func (c *Conn) simpleProcessResp(ctx context.Context) error { - tokchan := make(chan tokenStruct, 5) - go processResponse(ctx, c.sess, tokchan, c.outs) - c.clearOuts() - for tok := range tokchan { - switch token := tok.(type) { - case doneStruct: - if token.isError() { - return c.checkBadConn(token.getError()) - } - case error: - return c.checkBadConn(token) - } - } - return nil -} - -func (c *Conn) Commit() error { - if !c.connectionGood { - return driver.ErrBadConn - } - if err := c.sendCommitRequest(); err != nil { - return c.checkBadConn(err) - } - return c.simpleProcessResp(c.transactionCtx) -} - -func (c *Conn) sendCommitRequest() error { - headers := []headerStruct{ - {hdrtype: dataStmHdrTransDescr, - data: transDescrHdr{c.sess.tranid, 1}.pack()}, - } - reset := c.resetSession - c.resetSession = false - if err := sendCommitXact(c.sess.buf, headers, "", 0, 0, "", reset); err != nil { - if c.sess.logFlags&logErrors != 0 { - c.sess.log.Printf("Failed to send CommitXact with %v", err) - } - c.connectionGood = false - return fmt.Errorf("Faild to send CommitXact: %v", err) - } - return nil -} - -func (c *Conn) Rollback() error { - if !c.connectionGood { - return driver.ErrBadConn - } - if err := c.sendRollbackRequest(); err != nil { - return c.checkBadConn(err) - } - return c.simpleProcessResp(c.transactionCtx) -} - -func (c *Conn) sendRollbackRequest() error { - headers := []headerStruct{ - {hdrtype: dataStmHdrTransDescr, - data: transDescrHdr{c.sess.tranid, 1}.pack()}, - } - reset := c.resetSession - c.resetSession = false - if err := sendRollbackXact(c.sess.buf, headers, "", 0, 0, "", reset); err != nil { - if c.sess.logFlags&logErrors != 0 { - c.sess.log.Printf("Failed to send RollbackXact with %v", err) - } - c.connectionGood = false - return fmt.Errorf("Failed to send RollbackXact: %v", err) - } - return nil -} - -func (c *Conn) Begin() (driver.Tx, error) { - return c.begin(context.Background(), isolationUseCurrent) -} - -func (c *Conn) begin(ctx context.Context, tdsIsolation isoLevel) (tx driver.Tx, err error) { - if !c.connectionGood { - return nil, driver.ErrBadConn - } - err = c.sendBeginRequest(ctx, tdsIsolation) - if err != nil { - return nil, c.checkBadConn(err) - } - tx, err = c.processBeginResponse(ctx) - if err != nil { - return nil, c.checkBadConn(err) - } - return -} - -func (c *Conn) sendBeginRequest(ctx context.Context, tdsIsolation isoLevel) error { - c.transactionCtx = ctx - headers := []headerStruct{ - {hdrtype: dataStmHdrTransDescr, - data: transDescrHdr{0, 1}.pack()}, - } - reset := c.resetSession - c.resetSession = false - if err := sendBeginXact(c.sess.buf, headers, tdsIsolation, "", reset); err != nil { - if c.sess.logFlags&logErrors != 0 { - c.sess.log.Printf("Failed to send BeginXact with %v", err) - } - c.connectionGood = false - return fmt.Errorf("Failed to send BeginXact: %v", err) - } - return nil -} - -func (c *Conn) processBeginResponse(ctx context.Context) (driver.Tx, error) { - if err := c.simpleProcessResp(ctx); err != nil { - return nil, err - } - // successful BEGINXACT request will return sess.tranid - // for started transaction - return c, nil -} - -func (d *Driver) open(ctx context.Context, dsn string) (*Conn, error) { - params, err := parseConnectParams(dsn) - if err != nil { - return nil, err - } - return d.connect(ctx, params) -} - -// connect to the server, using the provided context for dialing only. -func (d *Driver) connect(ctx context.Context, params connectParams) (*Conn, error) { - sess, err := connect(ctx, d.log, params) - if err != nil { - // main server failed, try fail-over partner - if params.failOverPartner == "" { - return nil, err - } - - params.host = params.failOverPartner - if params.failOverPort != 0 { - params.port = params.failOverPort - } - - sess, err = connect(ctx, d.log, params) - if err != nil { - // fail-over partner also failed, now fail - return nil, err - } - } - - conn := &Conn{ - sess: sess, - transactionCtx: context.Background(), - processQueryText: d.processQueryText, - connectionGood: true, - } - conn.sess.log = d.log - - return conn, nil -} - -func (c *Conn) Close() error { - return c.sess.buf.transport.Close() -} - -type Stmt struct { - c *Conn - query string - paramCount int - notifSub *queryNotifSub -} - -type queryNotifSub struct { - msgText string - options string - timeout uint32 -} - -func (c *Conn) Prepare(query string) (driver.Stmt, error) { - if !c.connectionGood { - return nil, driver.ErrBadConn - } - if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") { - return c.prepareCopyIn(context.Background(), query) - } - return c.prepareContext(context.Background(), query) -} - -func (c *Conn) prepareContext(ctx context.Context, query string) (*Stmt, error) { - paramCount := -1 - if c.processQueryText { - query, paramCount = parseParams(query) - } - return &Stmt{c, query, paramCount, nil}, nil -} - -func (s *Stmt) Close() error { - return nil -} - -func (s *Stmt) SetQueryNotification(id, options string, timeout time.Duration) { - to := uint32(timeout / time.Second) - if to < 1 { - to = 1 - } - s.notifSub = &queryNotifSub{id, options, to} -} - -func (s *Stmt) NumInput() int { - return s.paramCount -} - -func (s *Stmt) sendQuery(args []namedValue) (err error) { - headers := []headerStruct{ - {hdrtype: dataStmHdrTransDescr, - data: transDescrHdr{s.c.sess.tranid, 1}.pack()}, - } - - if s.notifSub != nil { - headers = append(headers, - headerStruct{ - hdrtype: dataStmHdrQueryNotif, - data: queryNotifHdr{ - s.notifSub.msgText, - s.notifSub.options, - s.notifSub.timeout, - }.pack(), - }) - } - - conn := s.c - - // no need to check number of parameters here, it is checked by database/sql - if conn.sess.logFlags&logSQL != 0 { - conn.sess.log.Println(s.query) - } - if conn.sess.logFlags&logParams != 0 && len(args) > 0 { - for i := 0; i < len(args); i++ { - if len(args[i].Name) > 0 { - s.c.sess.log.Printf("\t@%s\t%v\n", args[i].Name, args[i].Value) - } else { - s.c.sess.log.Printf("\t@p%d\t%v\n", i+1, args[i].Value) - } - } - } - - reset := conn.resetSession - conn.resetSession = false - if len(args) == 0 { - if err = sendSqlBatch72(conn.sess.buf, s.query, headers, reset); err != nil { - if conn.sess.logFlags&logErrors != 0 { - conn.sess.log.Printf("Failed to send SqlBatch with %v", err) - } - conn.connectionGood = false - return fmt.Errorf("failed to send SQL Batch: %v", err) - } - } else { - proc := sp_ExecuteSql - var params []param - if isProc(s.query) { - proc.name = s.query - params, _, err = s.makeRPCParams(args, 0) - if err != nil { - return - } - } else { - var decls []string - params, decls, err = s.makeRPCParams(args, 2) - if err != nil { - return - } - params[0] = makeStrParam(s.query) - params[1] = makeStrParam(strings.Join(decls, ",")) - } - if err = sendRpc(conn.sess.buf, headers, proc, 0, params, reset); err != nil { - if conn.sess.logFlags&logErrors != 0 { - conn.sess.log.Printf("Failed to send Rpc with %v", err) - } - conn.connectionGood = false - return fmt.Errorf("Failed to send RPC: %v", err) - } - } - return -} - -// isProc takes the query text in s and determines if it is a stored proc name -// or SQL text. -func isProc(s string) bool { - if len(s) == 0 { - return false - } - const ( - outside = iota - text - escaped - ) - st := outside - var rn1, rPrev rune - for _, r := range s { - rPrev = rn1 - rn1 = r - switch r { - // No newlines or string sequences. - case '\n', '\r', '\'', ';': - return false - } - switch st { - case outside: - switch { - case unicode.IsSpace(r): - return false - case r == '[': - st = escaped - continue - case r == ']' && rPrev == ']': - st = escaped - continue - case unicode.IsLetter(r): - st = text - } - case text: - switch { - case r == '.': - st = outside - continue - case unicode.IsSpace(r): - return false - } - case escaped: - switch { - case r == ']': - st = outside - continue - } - } - } - return true -} - -func (s *Stmt) makeRPCParams(args []namedValue, offset int) ([]param, []string, error) { - var err error - params := make([]param, len(args)+offset) - decls := make([]string, len(args)) - for i, val := range args { - params[i+offset], err = s.makeParam(val.Value) - if err != nil { - return nil, nil, err - } - var name string - if len(val.Name) > 0 { - name = "@" + val.Name - } else { - name = fmt.Sprintf("@p%d", val.Ordinal) - } - params[i+offset].Name = name - decls[i] = fmt.Sprintf("%s %s", name, makeDecl(params[i+offset].ti)) - } - return params, decls, nil -} - -type namedValue struct { - Name string - Ordinal int - Value driver.Value -} - -func convertOldArgs(args []driver.Value) []namedValue { - list := make([]namedValue, len(args)) - for i, v := range args { - list[i] = namedValue{ - Ordinal: i + 1, - Value: v, - } - } - return list -} - -func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) { - return s.queryContext(context.Background(), convertOldArgs(args)) -} - -func (s *Stmt) queryContext(ctx context.Context, args []namedValue) (rows driver.Rows, err error) { - if !s.c.connectionGood { - return nil, driver.ErrBadConn - } - if err = s.sendQuery(args); err != nil { - return nil, s.c.checkBadConn(err) - } - return s.processQueryResponse(ctx) -} - -func (s *Stmt) processQueryResponse(ctx context.Context) (res driver.Rows, err error) { - tokchan := make(chan tokenStruct, 5) - ctx, cancel := context.WithCancel(ctx) - go processResponse(ctx, s.c.sess, tokchan, s.c.outs) - s.c.clearOuts() - // process metadata - var cols []columnStruct -loop: - for tok := range tokchan { - switch token := tok.(type) { - // By ignoring DONE token we effectively - // skip empty result-sets. - // This improves results in queries like that: - // set nocount on; select 1 - // see TestIgnoreEmptyResults test - //case doneStruct: - //break loop - case []columnStruct: - cols = token - break loop - case doneStruct: - if token.isError() { - return nil, s.c.checkBadConn(token.getError()) - } - case ReturnStatus: - s.c.setReturnStatus(token) - case error: - return nil, s.c.checkBadConn(token) - } - } - res = &Rows{stmt: s, tokchan: tokchan, cols: cols, cancel: cancel} - return -} - -func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) { - return s.exec(context.Background(), convertOldArgs(args)) -} - -func (s *Stmt) exec(ctx context.Context, args []namedValue) (res driver.Result, err error) { - if !s.c.connectionGood { - return nil, driver.ErrBadConn - } - if err = s.sendQuery(args); err != nil { - return nil, s.c.checkBadConn(err) - } - if res, err = s.processExec(ctx); err != nil { - return nil, s.c.checkBadConn(err) - } - return -} - -func (s *Stmt) processExec(ctx context.Context) (res driver.Result, err error) { - tokchan := make(chan tokenStruct, 5) - go processResponse(ctx, s.c.sess, tokchan, s.c.outs) - s.c.clearOuts() - var rowCount int64 - for token := range tokchan { - switch token := token.(type) { - case doneInProcStruct: - if token.Status&doneCount != 0 { - rowCount += int64(token.RowCount) - } - case doneStruct: - if token.Status&doneCount != 0 { - rowCount += int64(token.RowCount) - } - if token.isError() { - return nil, token.getError() - } - case ReturnStatus: - s.c.setReturnStatus(token) - case error: - return nil, token - } - } - return &Result{s.c, rowCount}, nil -} - -type Rows struct { - stmt *Stmt - cols []columnStruct - tokchan chan tokenStruct - - nextCols []columnStruct - - cancel func() -} - -func (rc *Rows) Close() error { - rc.cancel() - for _ = range rc.tokchan { - } - rc.tokchan = nil - return nil -} - -func (rc *Rows) Columns() (res []string) { - res = make([]string, len(rc.cols)) - for i, col := range rc.cols { - res[i] = col.ColName - } - return -} - -func (rc *Rows) Next(dest []driver.Value) error { - if !rc.stmt.c.connectionGood { - return driver.ErrBadConn - } - if rc.nextCols != nil { - return io.EOF - } - for tok := range rc.tokchan { - switch tokdata := tok.(type) { - case []columnStruct: - rc.nextCols = tokdata - return io.EOF - case []interface{}: - for i := range dest { - dest[i] = tokdata[i] - } - return nil - case doneStruct: - if tokdata.isError() { - return rc.stmt.c.checkBadConn(tokdata.getError()) - } - case error: - return rc.stmt.c.checkBadConn(tokdata) - } - } - return io.EOF -} - -func (rc *Rows) HasNextResultSet() bool { - return rc.nextCols != nil -} - -func (rc *Rows) NextResultSet() error { - rc.cols = rc.nextCols - rc.nextCols = nil - if rc.cols == nil { - return io.EOF - } - return nil -} - -// It should return -// the value type that can be used to scan types into. For example, the database -// column type "bigint" this should return "reflect.TypeOf(int64(0))". -func (r *Rows) ColumnTypeScanType(index int) reflect.Type { - return makeGoLangScanType(r.cols[index].ti) -} - -// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the -// database system type name without the length. Type names should be uppercase. -// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", -// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", -// "TIMESTAMP". -func (r *Rows) ColumnTypeDatabaseTypeName(index int) string { - return makeGoLangTypeName(r.cols[index].ti) -} - -// RowsColumnTypeLength may be implemented by Rows. It should return the length -// of the column type if the column is a variable length type. If the column is -// not a variable length type ok should return false. -// If length is not limited other than system limits, it should return math.MaxInt64. -// The following are examples of returned values for various types: -// TEXT (math.MaxInt64, true) -// varchar(10) (10, true) -// nvarchar(10) (10, true) -// decimal (0, false) -// int (0, false) -// bytea(30) (30, true) -func (r *Rows) ColumnTypeLength(index int) (int64, bool) { - return makeGoLangTypeLength(r.cols[index].ti) -} - -// It should return -// the precision and scale for decimal types. If not applicable, ok should be false. -// The following are examples of returned values for various types: -// decimal(38, 4) (38, 4, true) -// int (0, 0, false) -// decimal (math.MaxInt64, math.MaxInt64, true) -func (r *Rows) ColumnTypePrecisionScale(index int) (int64, int64, bool) { - return makeGoLangTypePrecisionScale(r.cols[index].ti) -} - -// The nullable value should -// be true if it is known the column may be null, or false if the column is known -// to be not nullable. -// If the column nullability is unknown, ok should be false. -func (r *Rows) ColumnTypeNullable(index int) (nullable, ok bool) { - nullable = r.cols[index].Flags&colFlagNullable != 0 - ok = true - return -} - -func makeStrParam(val string) (res param) { - res.ti.TypeId = typeNVarChar - res.buffer = str2ucs2(val) - res.ti.Size = len(res.buffer) - return -} - -func (s *Stmt) makeParam(val driver.Value) (res param, err error) { - if val == nil { - res.ti.TypeId = typeNull - res.buffer = nil - res.ti.Size = 0 - return - } - switch val := val.(type) { - case int64: - res.ti.TypeId = typeIntN - res.buffer = make([]byte, 8) - res.ti.Size = 8 - binary.LittleEndian.PutUint64(res.buffer, uint64(val)) - case sql.NullInt64: - // only null values should be getting here - res.ti.TypeId = typeIntN - res.ti.Size = 8 - res.buffer = []byte{} - - case float64: - res.ti.TypeId = typeFltN - res.ti.Size = 8 - res.buffer = make([]byte, 8) - binary.LittleEndian.PutUint64(res.buffer, math.Float64bits(val)) - case sql.NullFloat64: - // only null values should be getting here - res.ti.TypeId = typeFltN - res.ti.Size = 8 - res.buffer = []byte{} - - case []byte: - res.ti.TypeId = typeBigVarBin - res.ti.Size = len(val) - res.buffer = val - case string: - res = makeStrParam(val) - case sql.NullString: - // only null values should be getting here - res.ti.TypeId = typeNVarChar - res.buffer = nil - res.ti.Size = 8000 - case bool: - res.ti.TypeId = typeBitN - res.ti.Size = 1 - res.buffer = make([]byte, 1) - if val { - res.buffer[0] = 1 - } - case sql.NullBool: - // only null values should be getting here - res.ti.TypeId = typeBitN - res.ti.Size = 1 - res.buffer = []byte{} - - case time.Time: - if s.c.sess.loginAck.TDSVersion >= verTDS73 { - res.ti.TypeId = typeDateTimeOffsetN - res.ti.Scale = 7 - res.buffer = encodeDateTimeOffset(val, int(res.ti.Scale)) - res.ti.Size = len(res.buffer) - } else { - res.ti.TypeId = typeDateTimeN - res.buffer = encodeDateTime(val) - res.ti.Size = len(res.buffer) - } - default: - return s.makeParamExtra(val) - } - return -} - -type Result struct { - c *Conn - rowsAffected int64 -} - -func (r *Result) RowsAffected() (int64, error) { - return r.rowsAffected, nil -} - -func (r *Result) LastInsertId() (int64, error) { - s, err := r.c.Prepare("select cast(@@identity as bigint)") - if err != nil { - return 0, err - } - defer s.Close() - rows, err := s.Query(nil) - if err != nil { - return 0, err - } - defer rows.Close() - dest := make([]driver.Value, 1) - err = rows.Next(dest) - if err != nil { - return 0, err - } - if dest[0] == nil { - return -1, errors.New("There is no generated identity value") - } - lastInsertId := dest[0].(int64) - return lastInsertId, nil -} - -var _ driver.Pinger = &Conn{} - -// Ping is used to check if the remote server is available and satisfies the Pinger interface. -func (c *Conn) Ping(ctx context.Context) error { - if !c.connectionGood { - return driver.ErrBadConn - } - stmt := &Stmt{c, `select 1;`, 0, nil} - _, err := stmt.ExecContext(ctx, nil) - return err -} - -var _ driver.ConnBeginTx = &Conn{} - -// BeginTx satisfies ConnBeginTx. -func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if !c.connectionGood { - return nil, driver.ErrBadConn - } - if opts.ReadOnly { - return nil, errors.New("Read-only transactions are not supported") - } - - var tdsIsolation isoLevel - switch sql.IsolationLevel(opts.Isolation) { - case sql.LevelDefault: - tdsIsolation = isolationUseCurrent - case sql.LevelReadUncommitted: - tdsIsolation = isolationReadUncommited - case sql.LevelReadCommitted: - tdsIsolation = isolationReadCommited - case sql.LevelWriteCommitted: - return nil, errors.New("LevelWriteCommitted isolation level is not supported") - case sql.LevelRepeatableRead: - tdsIsolation = isolationRepeatableRead - case sql.LevelSnapshot: - tdsIsolation = isolationSnapshot - case sql.LevelSerializable: - tdsIsolation = isolationSerializable - case sql.LevelLinearizable: - return nil, errors.New("LevelLinearizable isolation level is not supported") - default: - return nil, errors.New("Isolation level is not supported or unknown") - } - return c.begin(ctx, tdsIsolation) -} - -func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - if !c.connectionGood { - return nil, driver.ErrBadConn - } - if len(query) > 10 && strings.EqualFold(query[:10], "INSERTBULK") { - return c.prepareCopyIn(ctx, query) - } - - return c.prepareContext(ctx, query) -} - -func (s *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - if !s.c.connectionGood { - return nil, driver.ErrBadConn - } - list := make([]namedValue, len(args)) - for i, nv := range args { - list[i] = namedValue(nv) - } - return s.queryContext(ctx, list) -} - -func (s *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { - if !s.c.connectionGood { - return nil, driver.ErrBadConn - } - list := make([]namedValue, len(args)) - for i, nv := range args { - list[i] = namedValue(nv) - } - return s.exec(ctx, list) -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/mssql_go110.go b/vendor/github.com/denisenkom/go-mssqldb/mssql_go110.go deleted file mode 100644 index 3d5ab57a5..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/mssql_go110.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build go1.10 - -package mssql - -import ( - "context" - "database/sql/driver" -) - -var _ driver.Connector = &Connector{} -var _ driver.SessionResetter = &Conn{} - -func (c *Conn) ResetSession(ctx context.Context) error { - if !c.connectionGood { - return driver.ErrBadConn - } - c.resetSession = true - - if c.connector == nil || len(c.connector.SessionInitSQL) == 0 { - return nil - } - - s, err := c.prepareContext(ctx, c.connector.SessionInitSQL) - if err != nil { - return driver.ErrBadConn - } - _, err = s.exec(ctx, nil) - if err != nil { - return driver.ErrBadConn - } - - return nil -} - -// Connect to the server and return a TDS connection. -func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { - conn, err := c.driver.connect(ctx, c.params) - if conn != nil { - conn.connector = c - } - if err == nil { - err = conn.ResetSession(ctx) - } - return conn, err -} - -// Driver underlying the Connector. -func (c *Connector) Driver() driver.Driver { - return c.driver -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/mssql_go19.go b/vendor/github.com/denisenkom/go-mssqldb/mssql_go19.go deleted file mode 100644 index 65a11720d..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/mssql_go19.go +++ /dev/null @@ -1,171 +0,0 @@ -// +build go1.9 - -package mssql - -import ( - "database/sql" - "database/sql/driver" - "errors" - "fmt" - "reflect" - "time" - - // "github.com/cockroachdb/apd" - "cloud.google.com/go/civil" -) - -// Type alias provided for compatibility. - -type MssqlDriver = Driver // Deprecated: users should transition to the new name when possible. -type MssqlBulk = Bulk // Deprecated: users should transition to the new name when possible. -type MssqlBulkOptions = BulkOptions // Deprecated: users should transition to the new name when possible. -type MssqlConn = Conn // Deprecated: users should transition to the new name when possible. -type MssqlResult = Result // Deprecated: users should transition to the new name when possible. -type MssqlRows = Rows // Deprecated: users should transition to the new name when possible. -type MssqlStmt = Stmt // Deprecated: users should transition to the new name when possible. - -var _ driver.NamedValueChecker = &Conn{} - -// VarChar parameter types. -type VarChar string - -type NVarCharMax string -type VarCharMax string - -// DateTime1 encodes parameters to original DateTime SQL types. -type DateTime1 time.Time - -// DateTimeOffset encodes parameters to DateTimeOffset, preserving the UTC offset. -type DateTimeOffset time.Time - -func convertInputParameter(val interface{}) (interface{}, error) { - switch v := val.(type) { - case VarChar: - return val, nil - case NVarCharMax: - return val, nil - case VarCharMax: - return val, nil - case DateTime1: - return val, nil - case DateTimeOffset: - return val, nil - case civil.Date: - return val, nil - case civil.DateTime: - return val, nil - case civil.Time: - return val, nil - // case *apd.Decimal: - // return nil - default: - return driver.DefaultParameterConverter.ConvertValue(v) - } -} - -func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error { - switch v := nv.Value.(type) { - case sql.Out: - if c.outs == nil { - c.outs = make(map[string]interface{}) - } - c.outs[nv.Name] = v.Dest - - if v.Dest == nil { - return errors.New("destination is a nil pointer") - } - - dest_info := reflect.ValueOf(v.Dest) - if dest_info.Kind() != reflect.Ptr { - return errors.New("destination not a pointer") - } - - if dest_info.IsNil() { - return errors.New("destination is a nil pointer") - } - - pointed_value := reflect.Indirect(dest_info) - - // don't allow pointer to a pointer, only pointer to a value can be handled - // correctly - if pointed_value.Kind() == reflect.Ptr { - return errors.New("destination is a pointer to a pointer") - } - - // Unwrap the Out value and check the inner value. - val := pointed_value.Interface() - if val == nil { - return errors.New("MSSQL does not allow NULL value without type for OUTPUT parameters") - } - conv, err := convertInputParameter(val) - if err != nil { - return err - } - if conv == nil { - // if we replace with nil we would lose type information - nv.Value = sql.Out{Dest: val} - } else { - nv.Value = sql.Out{Dest: conv} - } - return nil - case *ReturnStatus: - *v = 0 // By default the return value should be zero. - c.returnStatus = v - return driver.ErrRemoveArgument - default: - var err error - nv.Value, err = convertInputParameter(nv.Value) - return err - } -} - -func (s *Stmt) makeParamExtra(val driver.Value) (res param, err error) { - switch val := val.(type) { - case VarChar: - res.ti.TypeId = typeBigVarChar - res.buffer = []byte(val) - res.ti.Size = len(res.buffer) - case VarCharMax: - res.ti.TypeId = typeBigVarChar - res.buffer = []byte(val) - res.ti.Size = 0 // currently zero forces varchar(max) - case NVarCharMax: - res.ti.TypeId = typeNVarChar - res.buffer = str2ucs2(string(val)) - res.ti.Size = 0 // currently zero forces nvarchar(max) - case DateTime1: - t := time.Time(val) - res.ti.TypeId = typeDateTimeN - res.buffer = encodeDateTime(t) - res.ti.Size = len(res.buffer) - case DateTimeOffset: - res.ti.TypeId = typeDateTimeOffsetN - res.ti.Scale = 7 - res.buffer = encodeDateTimeOffset(time.Time(val), int(res.ti.Scale)) - res.ti.Size = len(res.buffer) - case civil.Date: - res.ti.TypeId = typeDateN - res.buffer = encodeDate(val.In(time.UTC)) - res.ti.Size = len(res.buffer) - case civil.DateTime: - res.ti.TypeId = typeDateTime2N - res.ti.Scale = 7 - res.buffer = encodeDateTime2(val.In(time.UTC), int(res.ti.Scale)) - res.ti.Size = len(res.buffer) - case civil.Time: - res.ti.TypeId = typeTimeN - res.ti.Scale = 7 - res.buffer = encodeTime(val.Hour, val.Minute, val.Second, val.Nanosecond, int(res.ti.Scale)) - res.ti.Size = len(res.buffer) - case sql.Out: - res, err = s.makeParam(val.Dest) - res.Flags = fByRevValue - default: - err = fmt.Errorf("mssql: unknown type for %T", val) - } - return -} - -func scanIntoOut(name string, fromServer, scanInto interface{}) error { - return convertAssign(scanInto, fromServer) -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/mssql_go19pre.go b/vendor/github.com/denisenkom/go-mssqldb/mssql_go19pre.go deleted file mode 100644 index 9680f5107..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/mssql_go19pre.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !go1.9 - -package mssql - -import ( - "database/sql/driver" - "fmt" -) - -func (s *Stmt) makeParamExtra(val driver.Value) (param, error) { - return param{}, fmt.Errorf("mssql: unknown type for %T", val) -} - -func scanIntoOut(name string, fromServer, scanInto interface{}) error { - return fmt.Errorf("mssql: unsupported OUTPUT type, use a newer Go version") -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/net.go b/vendor/github.com/denisenkom/go-mssqldb/net.go deleted file mode 100644 index e3864d1a2..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/net.go +++ /dev/null @@ -1,103 +0,0 @@ -package mssql - -import ( - "fmt" - "net" - "time" -) - -type timeoutConn struct { - c net.Conn - timeout time.Duration - buf *tdsBuffer - packetPending bool - continueRead bool -} - -func newTimeoutConn(conn net.Conn, timeout time.Duration) *timeoutConn { - return &timeoutConn{ - c: conn, - timeout: timeout, - } -} - -func (c *timeoutConn) Read(b []byte) (n int, err error) { - if c.buf != nil { - if c.packetPending { - c.packetPending = false - err = c.buf.FinishPacket() - if err != nil { - err = fmt.Errorf("Cannot send handshake packet: %s", err.Error()) - return - } - c.continueRead = false - } - if !c.continueRead { - var packet packetType - packet, err = c.buf.BeginRead() - if err != nil { - err = fmt.Errorf("Cannot read handshake packet: %s", err.Error()) - return - } - if packet != packPrelogin { - err = fmt.Errorf("unexpected packet %d, expecting prelogin", packet) - return - } - c.continueRead = true - } - n, err = c.buf.Read(b) - return - } - if c.timeout > 0 { - err = c.c.SetDeadline(time.Now().Add(c.timeout)) - if err != nil { - return - } - } - return c.c.Read(b) -} - -func (c *timeoutConn) Write(b []byte) (n int, err error) { - if c.buf != nil { - if !c.packetPending { - c.buf.BeginPacket(packPrelogin, false) - c.packetPending = true - } - n, err = c.buf.Write(b) - if err != nil { - return - } - return - } - if c.timeout > 0 { - err = c.c.SetDeadline(time.Now().Add(c.timeout)) - if err != nil { - return - } - } - return c.c.Write(b) -} - -func (c timeoutConn) Close() error { - return c.c.Close() -} - -func (c timeoutConn) LocalAddr() net.Addr { - return c.c.LocalAddr() -} - -func (c timeoutConn) RemoteAddr() net.Addr { - return c.c.RemoteAddr() -} - -func (c timeoutConn) SetDeadline(t time.Time) error { - panic("Not implemented") -} - -func (c timeoutConn) SetReadDeadline(t time.Time) error { - panic("Not implemented") -} - -func (c timeoutConn) SetWriteDeadline(t time.Time) error { - panic("Not implemented") -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/ntlm.go b/vendor/github.com/denisenkom/go-mssqldb/ntlm.go deleted file mode 100644 index 7c0cc4f78..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/ntlm.go +++ /dev/null @@ -1,283 +0,0 @@ -// +build !windows - -package mssql - -import ( - "crypto/des" - "crypto/md5" - "crypto/rand" - "encoding/binary" - "errors" - "strings" - "unicode/utf16" - - "golang.org/x/crypto/md4" -) - -const ( - _NEGOTIATE_MESSAGE = 1 - _CHALLENGE_MESSAGE = 2 - _AUTHENTICATE_MESSAGE = 3 -) - -const ( - _NEGOTIATE_UNICODE = 0x00000001 - _NEGOTIATE_OEM = 0x00000002 - _NEGOTIATE_TARGET = 0x00000004 - _NEGOTIATE_SIGN = 0x00000010 - _NEGOTIATE_SEAL = 0x00000020 - _NEGOTIATE_DATAGRAM = 0x00000040 - _NEGOTIATE_LMKEY = 0x00000080 - _NEGOTIATE_NTLM = 0x00000200 - _NEGOTIATE_ANONYMOUS = 0x00000800 - _NEGOTIATE_OEM_DOMAIN_SUPPLIED = 0x00001000 - _NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000 - _NEGOTIATE_ALWAYS_SIGN = 0x00008000 - _NEGOTIATE_TARGET_TYPE_DOMAIN = 0x00010000 - _NEGOTIATE_TARGET_TYPE_SERVER = 0x00020000 - _NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000 - _NEGOTIATE_IDENTIFY = 0x00100000 - _REQUEST_NON_NT_SESSION_KEY = 0x00400000 - _NEGOTIATE_TARGET_INFO = 0x00800000 - _NEGOTIATE_VERSION = 0x02000000 - _NEGOTIATE_128 = 0x20000000 - _NEGOTIATE_KEY_EXCH = 0x40000000 - _NEGOTIATE_56 = 0x80000000 -) - -const _NEGOTIATE_FLAGS = _NEGOTIATE_UNICODE | - _NEGOTIATE_NTLM | - _NEGOTIATE_OEM_DOMAIN_SUPPLIED | - _NEGOTIATE_OEM_WORKSTATION_SUPPLIED | - _NEGOTIATE_ALWAYS_SIGN | - _NEGOTIATE_EXTENDED_SESSIONSECURITY - -type ntlmAuth struct { - Domain string - UserName string - Password string - Workstation string -} - -func getAuth(user, password, service, workstation string) (auth, bool) { - if !strings.ContainsRune(user, '\\') { - return nil, false - } - domain_user := strings.SplitN(user, "\\", 2) - return &ntlmAuth{ - Domain: domain_user[0], - UserName: domain_user[1], - Password: password, - Workstation: workstation, - }, true -} - -func utf16le(val string) []byte { - var v []byte - for _, r := range val { - if utf16.IsSurrogate(r) { - r1, r2 := utf16.EncodeRune(r) - v = append(v, byte(r1), byte(r1>>8)) - v = append(v, byte(r2), byte(r2>>8)) - } else { - v = append(v, byte(r), byte(r>>8)) - } - } - return v -} - -func (auth *ntlmAuth) InitialBytes() ([]byte, error) { - domain_len := len(auth.Domain) - workstation_len := len(auth.Workstation) - msg := make([]byte, 40+domain_len+workstation_len) - copy(msg, []byte("NTLMSSP\x00")) - binary.LittleEndian.PutUint32(msg[8:], _NEGOTIATE_MESSAGE) - binary.LittleEndian.PutUint32(msg[12:], _NEGOTIATE_FLAGS) - // Domain Name Fields - binary.LittleEndian.PutUint16(msg[16:], uint16(domain_len)) - binary.LittleEndian.PutUint16(msg[18:], uint16(domain_len)) - binary.LittleEndian.PutUint32(msg[20:], 40) - // Workstation Fields - binary.LittleEndian.PutUint16(msg[24:], uint16(workstation_len)) - binary.LittleEndian.PutUint16(msg[26:], uint16(workstation_len)) - binary.LittleEndian.PutUint32(msg[28:], uint32(40+domain_len)) - // Version - binary.LittleEndian.PutUint32(msg[32:], 0) - binary.LittleEndian.PutUint32(msg[36:], 0) - // Payload - copy(msg[40:], auth.Domain) - copy(msg[40+domain_len:], auth.Workstation) - return msg, nil -} - -var errorNTLM = errors.New("NTLM protocol error") - -func createDesKey(bytes, material []byte) { - material[0] = bytes[0] - material[1] = (byte)(bytes[0]<<7 | (bytes[1]&0xff)>>1) - material[2] = (byte)(bytes[1]<<6 | (bytes[2]&0xff)>>2) - material[3] = (byte)(bytes[2]<<5 | (bytes[3]&0xff)>>3) - material[4] = (byte)(bytes[3]<<4 | (bytes[4]&0xff)>>4) - material[5] = (byte)(bytes[4]<<3 | (bytes[5]&0xff)>>5) - material[6] = (byte)(bytes[5]<<2 | (bytes[6]&0xff)>>6) - material[7] = (byte)(bytes[6] << 1) -} - -func oddParity(bytes []byte) { - for i := 0; i < len(bytes); i++ { - b := bytes[i] - needsParity := (((b >> 7) ^ (b >> 6) ^ (b >> 5) ^ (b >> 4) ^ (b >> 3) ^ (b >> 2) ^ (b >> 1)) & 0x01) == 0 - if needsParity { - bytes[i] = bytes[i] | byte(0x01) - } else { - bytes[i] = bytes[i] & byte(0xfe) - } - } -} - -func encryptDes(key []byte, cleartext []byte, ciphertext []byte) { - var desKey [8]byte - createDesKey(key, desKey[:]) - cipher, err := des.NewCipher(desKey[:]) - if err != nil { - panic(err) - } - cipher.Encrypt(ciphertext, cleartext) -} - -func response(challenge [8]byte, hash [21]byte) (ret [24]byte) { - encryptDes(hash[:7], challenge[:], ret[:8]) - encryptDes(hash[7:14], challenge[:], ret[8:16]) - encryptDes(hash[14:], challenge[:], ret[16:]) - return -} - -func lmHash(password string) (hash [21]byte) { - var lmpass [14]byte - copy(lmpass[:14], []byte(strings.ToUpper(password))) - magic := []byte("KGS!@#$%") - encryptDes(lmpass[:7], magic, hash[:8]) - encryptDes(lmpass[7:], magic, hash[8:]) - return -} - -func lmResponse(challenge [8]byte, password string) [24]byte { - hash := lmHash(password) - return response(challenge, hash) -} - -func ntlmHash(password string) (hash [21]byte) { - h := md4.New() - h.Write(utf16le(password)) - h.Sum(hash[:0]) - return -} - -func ntResponse(challenge [8]byte, password string) [24]byte { - hash := ntlmHash(password) - return response(challenge, hash) -} - -func clientChallenge() (nonce [8]byte) { - _, err := rand.Read(nonce[:]) - if err != nil { - panic(err) - } - return -} - -func ntlmSessionResponse(clientNonce [8]byte, serverChallenge [8]byte, password string) [24]byte { - var sessionHash [16]byte - h := md5.New() - h.Write(serverChallenge[:]) - h.Write(clientNonce[:]) - h.Sum(sessionHash[:0]) - var hash [8]byte - copy(hash[:], sessionHash[:8]) - passwordHash := ntlmHash(password) - return response(hash, passwordHash) -} - -func (auth *ntlmAuth) NextBytes(bytes []byte) ([]byte, error) { - if string(bytes[0:8]) != "NTLMSSP\x00" { - return nil, errorNTLM - } - if binary.LittleEndian.Uint32(bytes[8:12]) != _CHALLENGE_MESSAGE { - return nil, errorNTLM - } - flags := binary.LittleEndian.Uint32(bytes[20:24]) - var challenge [8]byte - copy(challenge[:], bytes[24:32]) - - var lm, nt []byte - if (flags & _NEGOTIATE_EXTENDED_SESSIONSECURITY) != 0 { - nonce := clientChallenge() - var lm_bytes [24]byte - copy(lm_bytes[:8], nonce[:]) - lm = lm_bytes[:] - nt_bytes := ntlmSessionResponse(nonce, challenge, auth.Password) - nt = nt_bytes[:] - } else { - lm_bytes := lmResponse(challenge, auth.Password) - lm = lm_bytes[:] - nt_bytes := ntResponse(challenge, auth.Password) - nt = nt_bytes[:] - } - lm_len := len(lm) - nt_len := len(nt) - - domain16 := utf16le(auth.Domain) - domain_len := len(domain16) - user16 := utf16le(auth.UserName) - user_len := len(user16) - workstation16 := utf16le(auth.Workstation) - workstation_len := len(workstation16) - - msg := make([]byte, 88+lm_len+nt_len+domain_len+user_len+workstation_len) - copy(msg, []byte("NTLMSSP\x00")) - binary.LittleEndian.PutUint32(msg[8:], _AUTHENTICATE_MESSAGE) - // Lm Challenge Response Fields - binary.LittleEndian.PutUint16(msg[12:], uint16(lm_len)) - binary.LittleEndian.PutUint16(msg[14:], uint16(lm_len)) - binary.LittleEndian.PutUint32(msg[16:], 88) - // Nt Challenge Response Fields - binary.LittleEndian.PutUint16(msg[20:], uint16(nt_len)) - binary.LittleEndian.PutUint16(msg[22:], uint16(nt_len)) - binary.LittleEndian.PutUint32(msg[24:], uint32(88+lm_len)) - // Domain Name Fields - binary.LittleEndian.PutUint16(msg[28:], uint16(domain_len)) - binary.LittleEndian.PutUint16(msg[30:], uint16(domain_len)) - binary.LittleEndian.PutUint32(msg[32:], uint32(88+lm_len+nt_len)) - // User Name Fields - binary.LittleEndian.PutUint16(msg[36:], uint16(user_len)) - binary.LittleEndian.PutUint16(msg[38:], uint16(user_len)) - binary.LittleEndian.PutUint32(msg[40:], uint32(88+lm_len+nt_len+domain_len)) - // Workstation Fields - binary.LittleEndian.PutUint16(msg[44:], uint16(workstation_len)) - binary.LittleEndian.PutUint16(msg[46:], uint16(workstation_len)) - binary.LittleEndian.PutUint32(msg[48:], uint32(88+lm_len+nt_len+domain_len+user_len)) - // Encrypted Random Session Key Fields - binary.LittleEndian.PutUint16(msg[52:], 0) - binary.LittleEndian.PutUint16(msg[54:], 0) - binary.LittleEndian.PutUint32(msg[56:], uint32(88+lm_len+nt_len+domain_len+user_len+workstation_len)) - // Negotiate Flags - binary.LittleEndian.PutUint32(msg[60:], flags) - // Version - binary.LittleEndian.PutUint32(msg[64:], 0) - binary.LittleEndian.PutUint32(msg[68:], 0) - // MIC - binary.LittleEndian.PutUint32(msg[72:], 0) - binary.LittleEndian.PutUint32(msg[76:], 0) - binary.LittleEndian.PutUint32(msg[88:], 0) - binary.LittleEndian.PutUint32(msg[84:], 0) - // Payload - copy(msg[88:], lm) - copy(msg[88+lm_len:], nt) - copy(msg[88+lm_len+nt_len:], domain16) - copy(msg[88+lm_len+nt_len+domain_len:], user16) - copy(msg[88+lm_len+nt_len+domain_len+user_len:], workstation16) - return msg, nil -} - -func (auth *ntlmAuth) Free() { -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/parser.go b/vendor/github.com/denisenkom/go-mssqldb/parser.go deleted file mode 100644 index 8021ca603..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/parser.go +++ /dev/null @@ -1,257 +0,0 @@ -package mssql - -import ( - "bytes" - "io" - "strconv" -) - -type parser struct { - r *bytes.Reader - w bytes.Buffer - paramCount int - paramMax int - - // using map as a set - namedParams map[string]bool -} - -func (p *parser) next() (rune, bool) { - ch, _, err := p.r.ReadRune() - if err != nil { - if err != io.EOF { - panic(err) - } - return 0, false - } - return ch, true -} - -func (p *parser) unread() { - err := p.r.UnreadRune() - if err != nil { - panic(err) - } -} - -func (p *parser) write(ch rune) { - p.w.WriteRune(ch) -} - -type stateFunc func(*parser) stateFunc - -func parseParams(query string) (string, int) { - p := &parser{ - r: bytes.NewReader([]byte(query)), - namedParams: map[string]bool{}, - } - state := parseNormal - for state != nil { - state = state(p) - } - return p.w.String(), p.paramMax + len(p.namedParams) -} - -func parseNormal(p *parser) stateFunc { - for { - ch, ok := p.next() - if !ok { - return nil - } - if ch == '?' { - return parseOrdinalParameter - } else if ch == '$' || ch == ':' { - ch2, ok := p.next() - if !ok { - p.write(ch) - return nil - } - p.unread() - if ch2 >= '0' && ch2 <= '9' { - return parseOrdinalParameter - } else if 'a' <= ch2 && ch2 <= 'z' || 'A' <= ch2 && ch2 <= 'Z' { - return parseNamedParameter - } - } - p.write(ch) - switch ch { - case '\'': - return parseQuote - case '"': - return parseDoubleQuote - case '[': - return parseBracket - case '-': - return parseLineComment - case '/': - return parseComment - } - } -} - -func parseOrdinalParameter(p *parser) stateFunc { - var paramN int - var ok bool - for { - var ch rune - ch, ok = p.next() - if ok && ch >= '0' && ch <= '9' { - paramN = paramN*10 + int(ch-'0') - } else { - break - } - } - if ok { - p.unread() - } - if paramN == 0 { - p.paramCount++ - paramN = p.paramCount - } - if paramN > p.paramMax { - p.paramMax = paramN - } - p.w.WriteString("@p") - p.w.WriteString(strconv.Itoa(paramN)) - if !ok { - return nil - } - return parseNormal -} - -func parseNamedParameter(p *parser) stateFunc { - var paramName string - var ok bool - for { - var ch rune - ch, ok = p.next() - if ok && (ch >= '0' && ch <= '9' || 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z') { - paramName = paramName + string(ch) - } else { - break - } - } - if ok { - p.unread() - } - p.namedParams[paramName] = true - p.w.WriteString("@") - p.w.WriteString(paramName) - if !ok { - return nil - } - return parseNormal -} - -func parseQuote(p *parser) stateFunc { - for { - ch, ok := p.next() - if !ok { - return nil - } - p.write(ch) - if ch == '\'' { - return parseNormal - } - } -} - -func parseDoubleQuote(p *parser) stateFunc { - for { - ch, ok := p.next() - if !ok { - return nil - } - p.write(ch) - if ch == '"' { - return parseNormal - } - } -} - -func parseBracket(p *parser) stateFunc { - for { - ch, ok := p.next() - if !ok { - return nil - } - p.write(ch) - if ch == ']' { - ch, ok = p.next() - if !ok { - return nil - } - if ch != ']' { - p.unread() - return parseNormal - } - p.write(ch) - } - } -} - -func parseLineComment(p *parser) stateFunc { - ch, ok := p.next() - if !ok { - return nil - } - if ch != '-' { - p.unread() - return parseNormal - } - p.write(ch) - for { - ch, ok = p.next() - if !ok { - return nil - } - p.write(ch) - if ch == '\n' { - return parseNormal - } - } -} - -func parseComment(p *parser) stateFunc { - var nested int - ch, ok := p.next() - if !ok { - return nil - } - if ch != '*' { - p.unread() - return parseNormal - } - p.write(ch) - for { - ch, ok = p.next() - if !ok { - return nil - } - p.write(ch) - for ch == '*' { - ch, ok = p.next() - if !ok { - return nil - } - p.write(ch) - if ch == '/' { - if nested == 0 { - return parseNormal - } else { - nested-- - } - } - } - for ch == '/' { - ch, ok = p.next() - if !ok { - return nil - } - p.write(ch) - if ch == '*' { - nested++ - } - } - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/rpc.go b/vendor/github.com/denisenkom/go-mssqldb/rpc.go deleted file mode 100644 index 4ca22578f..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/rpc.go +++ /dev/null @@ -1,89 +0,0 @@ -package mssql - -import ( - "encoding/binary" -) - -type procId struct { - id uint16 - name string -} - -// parameter flags -const ( - fByRevValue = 1 - fDefaultValue = 2 -) - -type param struct { - Name string - Flags uint8 - ti typeInfo - buffer []byte -} - -const ( - fWithRecomp = 1 - fNoMetaData = 2 - fReuseMetaData = 4 -) - -var ( - sp_Cursor = procId{1, ""} - sp_CursorOpen = procId{2, ""} - sp_CursorPrepare = procId{3, ""} - sp_CursorExecute = procId{4, ""} - sp_CursorPrepExec = procId{5, ""} - sp_CursorUnprepare = procId{6, ""} - sp_CursorFetch = procId{7, ""} - sp_CursorOption = procId{8, ""} - sp_CursorClose = procId{9, ""} - sp_ExecuteSql = procId{10, ""} - sp_Prepare = procId{11, ""} - sp_PrepExec = procId{13, ""} - sp_PrepExecRpc = procId{14, ""} - sp_Unprepare = procId{15, ""} -) - -// http://msdn.microsoft.com/en-us/library/dd357576.aspx -func sendRpc(buf *tdsBuffer, headers []headerStruct, proc procId, flags uint16, params []param, resetSession bool) (err error) { - buf.BeginPacket(packRPCRequest, resetSession) - writeAllHeaders(buf, headers) - if len(proc.name) == 0 { - var idswitch uint16 = 0xffff - err = binary.Write(buf, binary.LittleEndian, &idswitch) - if err != nil { - return - } - err = binary.Write(buf, binary.LittleEndian, &proc.id) - if err != nil { - return - } - } else { - err = writeUsVarChar(buf, proc.name) - if err != nil { - return - } - } - err = binary.Write(buf, binary.LittleEndian, &flags) - if err != nil { - return - } - for _, param := range params { - if err = writeBVarChar(buf, param.Name); err != nil { - return - } - if err = binary.Write(buf, binary.LittleEndian, param.Flags); err != nil { - return - } - err = writeTypeInfo(buf, ¶m.ti) - if err != nil { - return - } - err = param.ti.Writer(buf, param.ti, param.buffer) - if err != nil { - return - } - } - return buf.FinishPacket() -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/sspi_windows.go b/vendor/github.com/denisenkom/go-mssqldb/sspi_windows.go deleted file mode 100644 index 9b5bc6893..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/sspi_windows.go +++ /dev/null @@ -1,266 +0,0 @@ -package mssql - -import ( - "fmt" - "strings" - "syscall" - "unsafe" -) - -var ( - secur32_dll = syscall.NewLazyDLL("secur32.dll") - initSecurityInterface = secur32_dll.NewProc("InitSecurityInterfaceW") - sec_fn *SecurityFunctionTable -) - -func init() { - ptr, _, _ := initSecurityInterface.Call() - sec_fn = (*SecurityFunctionTable)(unsafe.Pointer(ptr)) -} - -const ( - SEC_E_OK = 0 - SECPKG_CRED_OUTBOUND = 2 - SEC_WINNT_AUTH_IDENTITY_UNICODE = 2 - ISC_REQ_DELEGATE = 0x00000001 - ISC_REQ_REPLAY_DETECT = 0x00000004 - ISC_REQ_SEQUENCE_DETECT = 0x00000008 - ISC_REQ_CONFIDENTIALITY = 0x00000010 - ISC_REQ_CONNECTION = 0x00000800 - SECURITY_NETWORK_DREP = 0 - SEC_I_CONTINUE_NEEDED = 0x00090312 - SEC_I_COMPLETE_NEEDED = 0x00090313 - SEC_I_COMPLETE_AND_CONTINUE = 0x00090314 - SECBUFFER_VERSION = 0 - SECBUFFER_TOKEN = 2 - NTLMBUF_LEN = 12000 -) - -const ISC_REQ = ISC_REQ_CONFIDENTIALITY | - ISC_REQ_REPLAY_DETECT | - ISC_REQ_SEQUENCE_DETECT | - ISC_REQ_CONNECTION | - ISC_REQ_DELEGATE - -type SecurityFunctionTable struct { - dwVersion uint32 - EnumerateSecurityPackages uintptr - QueryCredentialsAttributes uintptr - AcquireCredentialsHandle uintptr - FreeCredentialsHandle uintptr - Reserved2 uintptr - InitializeSecurityContext uintptr - AcceptSecurityContext uintptr - CompleteAuthToken uintptr - DeleteSecurityContext uintptr - ApplyControlToken uintptr - QueryContextAttributes uintptr - ImpersonateSecurityContext uintptr - RevertSecurityContext uintptr - MakeSignature uintptr - VerifySignature uintptr - FreeContextBuffer uintptr - QuerySecurityPackageInfo uintptr - Reserved3 uintptr - Reserved4 uintptr - Reserved5 uintptr - Reserved6 uintptr - Reserved7 uintptr - Reserved8 uintptr - QuerySecurityContextToken uintptr - EncryptMessage uintptr - DecryptMessage uintptr -} - -type SEC_WINNT_AUTH_IDENTITY struct { - User *uint16 - UserLength uint32 - Domain *uint16 - DomainLength uint32 - Password *uint16 - PasswordLength uint32 - Flags uint32 -} - -type TimeStamp struct { - LowPart uint32 - HighPart int32 -} - -type SecHandle struct { - dwLower uintptr - dwUpper uintptr -} - -type SecBuffer struct { - cbBuffer uint32 - BufferType uint32 - pvBuffer *byte -} - -type SecBufferDesc struct { - ulVersion uint32 - cBuffers uint32 - pBuffers *SecBuffer -} - -type SSPIAuth struct { - Domain string - UserName string - Password string - Service string - cred SecHandle - ctxt SecHandle -} - -func getAuth(user, password, service, workstation string) (auth, bool) { - if user == "" { - return &SSPIAuth{Service: service}, true - } - if !strings.ContainsRune(user, '\\') { - return nil, false - } - domain_user := strings.SplitN(user, "\\", 2) - return &SSPIAuth{ - Domain: domain_user[0], - UserName: domain_user[1], - Password: password, - Service: service, - }, true -} - -func (auth *SSPIAuth) InitialBytes() ([]byte, error) { - var identity *SEC_WINNT_AUTH_IDENTITY - if auth.UserName != "" { - identity = &SEC_WINNT_AUTH_IDENTITY{ - Flags: SEC_WINNT_AUTH_IDENTITY_UNICODE, - Password: syscall.StringToUTF16Ptr(auth.Password), - PasswordLength: uint32(len(auth.Password)), - Domain: syscall.StringToUTF16Ptr(auth.Domain), - DomainLength: uint32(len(auth.Domain)), - User: syscall.StringToUTF16Ptr(auth.UserName), - UserLength: uint32(len(auth.UserName)), - } - } - var ts TimeStamp - sec_ok, _, _ := syscall.Syscall9(sec_fn.AcquireCredentialsHandle, - 9, - 0, - uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Negotiate"))), - SECPKG_CRED_OUTBOUND, - 0, - uintptr(unsafe.Pointer(identity)), - 0, - 0, - uintptr(unsafe.Pointer(&auth.cred)), - uintptr(unsafe.Pointer(&ts))) - if sec_ok != SEC_E_OK { - return nil, fmt.Errorf("AcquireCredentialsHandle failed %x", sec_ok) - } - - var buf SecBuffer - var desc SecBufferDesc - desc.ulVersion = SECBUFFER_VERSION - desc.cBuffers = 1 - desc.pBuffers = &buf - - outbuf := make([]byte, NTLMBUF_LEN) - buf.cbBuffer = NTLMBUF_LEN - buf.BufferType = SECBUFFER_TOKEN - buf.pvBuffer = &outbuf[0] - - var attrs uint32 - sec_ok, _, _ = syscall.Syscall12(sec_fn.InitializeSecurityContext, - 12, - uintptr(unsafe.Pointer(&auth.cred)), - 0, - uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))), - ISC_REQ, - 0, - SECURITY_NETWORK_DREP, - 0, - 0, - uintptr(unsafe.Pointer(&auth.ctxt)), - uintptr(unsafe.Pointer(&desc)), - uintptr(unsafe.Pointer(&attrs)), - uintptr(unsafe.Pointer(&ts))) - if sec_ok == SEC_I_COMPLETE_AND_CONTINUE || - sec_ok == SEC_I_COMPLETE_NEEDED { - syscall.Syscall6(sec_fn.CompleteAuthToken, - 2, - uintptr(unsafe.Pointer(&auth.ctxt)), - uintptr(unsafe.Pointer(&desc)), - 0, 0, 0, 0) - } else if sec_ok != SEC_E_OK && - sec_ok != SEC_I_CONTINUE_NEEDED { - syscall.Syscall6(sec_fn.FreeCredentialsHandle, - 1, - uintptr(unsafe.Pointer(&auth.cred)), - 0, 0, 0, 0, 0) - return nil, fmt.Errorf("InitialBytes InitializeSecurityContext failed %x", sec_ok) - } - return outbuf[:buf.cbBuffer], nil -} - -func (auth *SSPIAuth) NextBytes(bytes []byte) ([]byte, error) { - var in_buf, out_buf SecBuffer - var in_desc, out_desc SecBufferDesc - - in_desc.ulVersion = SECBUFFER_VERSION - in_desc.cBuffers = 1 - in_desc.pBuffers = &in_buf - - out_desc.ulVersion = SECBUFFER_VERSION - out_desc.cBuffers = 1 - out_desc.pBuffers = &out_buf - - in_buf.BufferType = SECBUFFER_TOKEN - in_buf.pvBuffer = &bytes[0] - in_buf.cbBuffer = uint32(len(bytes)) - - outbuf := make([]byte, NTLMBUF_LEN) - out_buf.BufferType = SECBUFFER_TOKEN - out_buf.pvBuffer = &outbuf[0] - out_buf.cbBuffer = NTLMBUF_LEN - - var attrs uint32 - var ts TimeStamp - sec_ok, _, _ := syscall.Syscall12(sec_fn.InitializeSecurityContext, - 12, - uintptr(unsafe.Pointer(&auth.cred)), - uintptr(unsafe.Pointer(&auth.ctxt)), - uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(auth.Service))), - ISC_REQ, - 0, - SECURITY_NETWORK_DREP, - uintptr(unsafe.Pointer(&in_desc)), - 0, - uintptr(unsafe.Pointer(&auth.ctxt)), - uintptr(unsafe.Pointer(&out_desc)), - uintptr(unsafe.Pointer(&attrs)), - uintptr(unsafe.Pointer(&ts))) - if sec_ok == SEC_I_COMPLETE_AND_CONTINUE || - sec_ok == SEC_I_COMPLETE_NEEDED { - syscall.Syscall6(sec_fn.CompleteAuthToken, - 2, - uintptr(unsafe.Pointer(&auth.ctxt)), - uintptr(unsafe.Pointer(&out_desc)), - 0, 0, 0, 0) - } else if sec_ok != SEC_E_OK && - sec_ok != SEC_I_CONTINUE_NEEDED { - return nil, fmt.Errorf("NextBytes InitializeSecurityContext failed %x", sec_ok) - } - - return outbuf[:out_buf.cbBuffer], nil -} - -func (auth *SSPIAuth) Free() { - syscall.Syscall6(sec_fn.DeleteSecurityContext, - 1, - uintptr(unsafe.Pointer(&auth.ctxt)), - 0, 0, 0, 0, 0) - syscall.Syscall6(sec_fn.FreeCredentialsHandle, - 1, - uintptr(unsafe.Pointer(&auth.cred)), - 0, 0, 0, 0, 0) -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/tds.go b/vendor/github.com/denisenkom/go-mssqldb/tds.go deleted file mode 100644 index a45711d55..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/tds.go +++ /dev/null @@ -1,1367 +0,0 @@ -package mssql - -import ( - "context" - "crypto/tls" - "crypto/x509" - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/url" - "os" - "sort" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -func parseInstances(msg []byte) map[string]map[string]string { - results := map[string]map[string]string{} - if len(msg) > 3 && msg[0] == 5 { - out_s := string(msg[3:]) - tokens := strings.Split(out_s, ";") - instdict := map[string]string{} - got_name := false - var name string - for _, token := range tokens { - if got_name { - instdict[name] = token - got_name = false - } else { - name = token - if len(name) == 0 { - if len(instdict) == 0 { - break - } - results[strings.ToUpper(instdict["InstanceName"])] = instdict - instdict = map[string]string{} - continue - } - got_name = true - } - } - } - return results -} - -func getInstances(ctx context.Context, address string) (map[string]map[string]string, error) { - maxTime := 5 * time.Second - dialer := &net.Dialer{ - Timeout: maxTime, - } - conn, err := dialer.DialContext(ctx, "udp", address+":1434") - if err != nil { - return nil, err - } - defer conn.Close() - conn.SetDeadline(time.Now().Add(maxTime)) - _, err = conn.Write([]byte{3}) - if err != nil { - return nil, err - } - var resp = make([]byte, 16*1024-1) - read, err := conn.Read(resp) - if err != nil { - return nil, err - } - return parseInstances(resp[:read]), nil -} - -// tds versions -const ( - verTDS70 = 0x70000000 - verTDS71 = 0x71000000 - verTDS71rev1 = 0x71000001 - verTDS72 = 0x72090002 - verTDS73A = 0x730A0003 - verTDS73 = verTDS73A - verTDS73B = 0x730B0003 - verTDS74 = 0x74000004 -) - -// packet types -// https://msdn.microsoft.com/en-us/library/dd304214.aspx -const ( - packSQLBatch packetType = 1 - packRPCRequest = 3 - packReply = 4 - - // 2.2.1.7 Attention: https://msdn.microsoft.com/en-us/library/dd341449.aspx - // 4.19.2 Out-of-Band Attention Signal: https://msdn.microsoft.com/en-us/library/dd305167.aspx - packAttention = 6 - - packBulkLoadBCP = 7 - packTransMgrReq = 14 - packNormal = 15 - packLogin7 = 16 - packSSPIMessage = 17 - packPrelogin = 18 -) - -// prelogin fields -// http://msdn.microsoft.com/en-us/library/dd357559.aspx -const ( - preloginVERSION = 0 - preloginENCRYPTION = 1 - preloginINSTOPT = 2 - preloginTHREADID = 3 - preloginMARS = 4 - preloginTRACEID = 5 - preloginTERMINATOR = 0xff -) - -const ( - encryptOff = 0 // Encryption is available but off. - encryptOn = 1 // Encryption is available and on. - encryptNotSup = 2 // Encryption is not available. - encryptReq = 3 // Encryption is required. -) - -type tdsSession struct { - buf *tdsBuffer - loginAck loginAckStruct - database string - partner string - columns []columnStruct - tranid uint64 - logFlags uint64 - log optionalLogger - routedServer string - routedPort uint16 -} - -const ( - logErrors = 1 - logMessages = 2 - logRows = 4 - logSQL = 8 - logParams = 16 - logTransaction = 32 - logDebug = 64 -) - -type columnStruct struct { - UserType uint32 - Flags uint16 - ColName string - ti typeInfo -} - -type keySlice []uint8 - -func (p keySlice) Len() int { return len(p) } -func (p keySlice) Less(i, j int) bool { return p[i] < p[j] } -func (p keySlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// http://msdn.microsoft.com/en-us/library/dd357559.aspx -func writePrelogin(w *tdsBuffer, fields map[uint8][]byte) error { - var err error - - w.BeginPacket(packPrelogin, false) - offset := uint16(5*len(fields) + 1) - keys := make(keySlice, 0, len(fields)) - for k, _ := range fields { - keys = append(keys, k) - } - sort.Sort(keys) - // writing header - for _, k := range keys { - err = w.WriteByte(k) - if err != nil { - return err - } - err = binary.Write(w, binary.BigEndian, offset) - if err != nil { - return err - } - v := fields[k] - size := uint16(len(v)) - err = binary.Write(w, binary.BigEndian, size) - if err != nil { - return err - } - offset += size - } - err = w.WriteByte(preloginTERMINATOR) - if err != nil { - return err - } - // writing values - for _, k := range keys { - v := fields[k] - written, err := w.Write(v) - if err != nil { - return err - } - if written != len(v) { - return errors.New("Write method didn't write the whole value") - } - } - return w.FinishPacket() -} - -func readPrelogin(r *tdsBuffer) (map[uint8][]byte, error) { - packet_type, err := r.BeginRead() - if err != nil { - return nil, err - } - struct_buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - if packet_type != 4 { - return nil, errors.New("Invalid respones, expected packet type 4, PRELOGIN RESPONSE") - } - offset := 0 - results := map[uint8][]byte{} - for true { - rec_type := struct_buf[offset] - if rec_type == preloginTERMINATOR { - break - } - - rec_offset := binary.BigEndian.Uint16(struct_buf[offset+1:]) - rec_len := binary.BigEndian.Uint16(struct_buf[offset+3:]) - value := struct_buf[rec_offset : rec_offset+rec_len] - results[rec_type] = value - offset += 5 - } - return results, nil -} - -// OptionFlags2 -// http://msdn.microsoft.com/en-us/library/dd304019.aspx -const ( - fLanguageFatal = 1 - fODBC = 2 - fTransBoundary = 4 - fCacheConnect = 8 - fIntSecurity = 0x80 -) - -// TypeFlags -const ( - // 4 bits for fSQLType - // 1 bit for fOLEDB - fReadOnlyIntent = 32 -) - -type login struct { - TDSVersion uint32 - PacketSize uint32 - ClientProgVer uint32 - ClientPID uint32 - ConnectionID uint32 - OptionFlags1 uint8 - OptionFlags2 uint8 - TypeFlags uint8 - OptionFlags3 uint8 - ClientTimeZone int32 - ClientLCID uint32 - HostName string - UserName string - Password string - AppName string - ServerName string - CtlIntName string - Language string - Database string - ClientID [6]byte - SSPI []byte - AtchDBFile string - ChangePassword string -} - -type loginHeader struct { - Length uint32 - TDSVersion uint32 - PacketSize uint32 - ClientProgVer uint32 - ClientPID uint32 - ConnectionID uint32 - OptionFlags1 uint8 - OptionFlags2 uint8 - TypeFlags uint8 - OptionFlags3 uint8 - ClientTimeZone int32 - ClientLCID uint32 - HostNameOffset uint16 - HostNameLength uint16 - UserNameOffset uint16 - UserNameLength uint16 - PasswordOffset uint16 - PasswordLength uint16 - AppNameOffset uint16 - AppNameLength uint16 - ServerNameOffset uint16 - ServerNameLength uint16 - ExtensionOffset uint16 - ExtensionLenght uint16 - CtlIntNameOffset uint16 - CtlIntNameLength uint16 - LanguageOffset uint16 - LanguageLength uint16 - DatabaseOffset uint16 - DatabaseLength uint16 - ClientID [6]byte - SSPIOffset uint16 - SSPILength uint16 - AtchDBFileOffset uint16 - AtchDBFileLength uint16 - ChangePasswordOffset uint16 - ChangePasswordLength uint16 - SSPILongLength uint32 -} - -// convert Go string to UTF-16 encoded []byte (littleEndian) -// done manually rather than using bytes and binary packages -// for performance reasons -func str2ucs2(s string) []byte { - res := utf16.Encode([]rune(s)) - ucs2 := make([]byte, 2*len(res)) - for i := 0; i < len(res); i++ { - ucs2[2*i] = byte(res[i]) - ucs2[2*i+1] = byte(res[i] >> 8) - } - return ucs2 -} - -func ucs22str(s []byte) (string, error) { - if len(s)%2 != 0 { - return "", fmt.Errorf("Illegal UCS2 string length: %d", len(s)) - } - buf := make([]uint16, len(s)/2) - for i := 0; i < len(s); i += 2 { - buf[i/2] = binary.LittleEndian.Uint16(s[i:]) - } - return string(utf16.Decode(buf)), nil -} - -func manglePassword(password string) []byte { - var ucs2password []byte = str2ucs2(password) - for i, ch := range ucs2password { - ucs2password[i] = ((ch<<4)&0xff | (ch >> 4)) ^ 0xA5 - } - return ucs2password -} - -// http://msdn.microsoft.com/en-us/library/dd304019.aspx -func sendLogin(w *tdsBuffer, login login) error { - w.BeginPacket(packLogin7, false) - hostname := str2ucs2(login.HostName) - username := str2ucs2(login.UserName) - password := manglePassword(login.Password) - appname := str2ucs2(login.AppName) - servername := str2ucs2(login.ServerName) - ctlintname := str2ucs2(login.CtlIntName) - language := str2ucs2(login.Language) - database := str2ucs2(login.Database) - atchdbfile := str2ucs2(login.AtchDBFile) - changepassword := str2ucs2(login.ChangePassword) - hdr := loginHeader{ - TDSVersion: login.TDSVersion, - PacketSize: login.PacketSize, - ClientProgVer: login.ClientProgVer, - ClientPID: login.ClientPID, - ConnectionID: login.ConnectionID, - OptionFlags1: login.OptionFlags1, - OptionFlags2: login.OptionFlags2, - TypeFlags: login.TypeFlags, - OptionFlags3: login.OptionFlags3, - ClientTimeZone: login.ClientTimeZone, - ClientLCID: login.ClientLCID, - HostNameLength: uint16(utf8.RuneCountInString(login.HostName)), - UserNameLength: uint16(utf8.RuneCountInString(login.UserName)), - PasswordLength: uint16(utf8.RuneCountInString(login.Password)), - AppNameLength: uint16(utf8.RuneCountInString(login.AppName)), - ServerNameLength: uint16(utf8.RuneCountInString(login.ServerName)), - CtlIntNameLength: uint16(utf8.RuneCountInString(login.CtlIntName)), - LanguageLength: uint16(utf8.RuneCountInString(login.Language)), - DatabaseLength: uint16(utf8.RuneCountInString(login.Database)), - ClientID: login.ClientID, - SSPILength: uint16(len(login.SSPI)), - AtchDBFileLength: uint16(utf8.RuneCountInString(login.AtchDBFile)), - ChangePasswordLength: uint16(utf8.RuneCountInString(login.ChangePassword)), - } - offset := uint16(binary.Size(hdr)) - hdr.HostNameOffset = offset - offset += uint16(len(hostname)) - hdr.UserNameOffset = offset - offset += uint16(len(username)) - hdr.PasswordOffset = offset - offset += uint16(len(password)) - hdr.AppNameOffset = offset - offset += uint16(len(appname)) - hdr.ServerNameOffset = offset - offset += uint16(len(servername)) - hdr.CtlIntNameOffset = offset - offset += uint16(len(ctlintname)) - hdr.LanguageOffset = offset - offset += uint16(len(language)) - hdr.DatabaseOffset = offset - offset += uint16(len(database)) - hdr.SSPIOffset = offset - offset += uint16(len(login.SSPI)) - hdr.AtchDBFileOffset = offset - offset += uint16(len(atchdbfile)) - hdr.ChangePasswordOffset = offset - offset += uint16(len(changepassword)) - hdr.Length = uint32(offset) - var err error - err = binary.Write(w, binary.LittleEndian, &hdr) - if err != nil { - return err - } - _, err = w.Write(hostname) - if err != nil { - return err - } - _, err = w.Write(username) - if err != nil { - return err - } - _, err = w.Write(password) - if err != nil { - return err - } - _, err = w.Write(appname) - if err != nil { - return err - } - _, err = w.Write(servername) - if err != nil { - return err - } - _, err = w.Write(ctlintname) - if err != nil { - return err - } - _, err = w.Write(language) - if err != nil { - return err - } - _, err = w.Write(database) - if err != nil { - return err - } - _, err = w.Write(login.SSPI) - if err != nil { - return err - } - _, err = w.Write(atchdbfile) - if err != nil { - return err - } - _, err = w.Write(changepassword) - if err != nil { - return err - } - return w.FinishPacket() -} - -func readUcs2(r io.Reader, numchars int) (res string, err error) { - buf := make([]byte, numchars*2) - _, err = io.ReadFull(r, buf) - if err != nil { - return "", err - } - return ucs22str(buf) -} - -func readUsVarChar(r io.Reader) (res string, err error) { - var numchars uint16 - err = binary.Read(r, binary.LittleEndian, &numchars) - if err != nil { - return "", err - } - return readUcs2(r, int(numchars)) -} - -func writeUsVarChar(w io.Writer, s string) (err error) { - buf := str2ucs2(s) - var numchars int = len(buf) / 2 - if numchars > 0xffff { - panic("invalid size for US_VARCHAR") - } - err = binary.Write(w, binary.LittleEndian, uint16(numchars)) - if err != nil { - return - } - _, err = w.Write(buf) - return -} - -func readBVarChar(r io.Reader) (res string, err error) { - var numchars uint8 - err = binary.Read(r, binary.LittleEndian, &numchars) - if err != nil { - return "", err - } - - // A zero length could be returned, return an empty string - if numchars == 0 { - return "", nil - } - return readUcs2(r, int(numchars)) -} - -func writeBVarChar(w io.Writer, s string) (err error) { - buf := str2ucs2(s) - var numchars int = len(buf) / 2 - if numchars > 0xff { - panic("invalid size for B_VARCHAR") - } - err = binary.Write(w, binary.LittleEndian, uint8(numchars)) - if err != nil { - return - } - _, err = w.Write(buf) - return -} - -func readBVarByte(r io.Reader) (res []byte, err error) { - var length uint8 - err = binary.Read(r, binary.LittleEndian, &length) - if err != nil { - return - } - res = make([]byte, length) - _, err = io.ReadFull(r, res) - return -} - -func readUshort(r io.Reader) (res uint16, err error) { - err = binary.Read(r, binary.LittleEndian, &res) - return -} - -func readByte(r io.Reader) (res byte, err error) { - var b [1]byte - _, err = r.Read(b[:]) - res = b[0] - return -} - -// Packet Data Stream Headers -// http://msdn.microsoft.com/en-us/library/dd304953.aspx -type headerStruct struct { - hdrtype uint16 - data []byte -} - -const ( - dataStmHdrQueryNotif = 1 // query notifications - dataStmHdrTransDescr = 2 // MARS transaction descriptor (required) - dataStmHdrTraceActivity = 3 -) - -// Query Notifications Header -// http://msdn.microsoft.com/en-us/library/dd304949.aspx -type queryNotifHdr struct { - notifyId string - ssbDeployment string - notifyTimeout uint32 -} - -func (hdr queryNotifHdr) pack() (res []byte) { - notifyId := str2ucs2(hdr.notifyId) - ssbDeployment := str2ucs2(hdr.ssbDeployment) - - res = make([]byte, 2+len(notifyId)+2+len(ssbDeployment)+4) - b := res - - binary.LittleEndian.PutUint16(b, uint16(len(notifyId))) - b = b[2:] - copy(b, notifyId) - b = b[len(notifyId):] - - binary.LittleEndian.PutUint16(b, uint16(len(ssbDeployment))) - b = b[2:] - copy(b, ssbDeployment) - b = b[len(ssbDeployment):] - - binary.LittleEndian.PutUint32(b, hdr.notifyTimeout) - - return res -} - -// MARS Transaction Descriptor Header -// http://msdn.microsoft.com/en-us/library/dd340515.aspx -type transDescrHdr struct { - transDescr uint64 // transaction descriptor returned from ENVCHANGE - outstandingReqCnt uint32 // outstanding request count -} - -func (hdr transDescrHdr) pack() (res []byte) { - res = make([]byte, 8+4) - binary.LittleEndian.PutUint64(res, hdr.transDescr) - binary.LittleEndian.PutUint32(res[8:], hdr.outstandingReqCnt) - return res -} - -func writeAllHeaders(w io.Writer, headers []headerStruct) (err error) { - // Calculating total length. - var totallen uint32 = 4 - for _, hdr := range headers { - totallen += 4 + 2 + uint32(len(hdr.data)) - } - // writing - err = binary.Write(w, binary.LittleEndian, totallen) - if err != nil { - return err - } - for _, hdr := range headers { - var headerlen uint32 = 4 + 2 + uint32(len(hdr.data)) - err = binary.Write(w, binary.LittleEndian, headerlen) - if err != nil { - return err - } - err = binary.Write(w, binary.LittleEndian, hdr.hdrtype) - if err != nil { - return err - } - _, err = w.Write(hdr.data) - if err != nil { - return err - } - } - return nil -} - -func sendSqlBatch72(buf *tdsBuffer, sqltext string, headers []headerStruct, resetSession bool) (err error) { - buf.BeginPacket(packSQLBatch, resetSession) - - if err = writeAllHeaders(buf, headers); err != nil { - return - } - - _, err = buf.Write(str2ucs2(sqltext)) - if err != nil { - return - } - return buf.FinishPacket() -} - -// 2.2.1.7 Attention: https://msdn.microsoft.com/en-us/library/dd341449.aspx -// 4.19.2 Out-of-Band Attention Signal: https://msdn.microsoft.com/en-us/library/dd305167.aspx -func sendAttention(buf *tdsBuffer) error { - buf.BeginPacket(packAttention, false) - return buf.FinishPacket() -} - -type connectParams struct { - logFlags uint64 - port uint64 - host string - instance string - database string - user string - password string - dial_timeout time.Duration - conn_timeout time.Duration - keepAlive time.Duration - encrypt bool - disableEncryption bool - trustServerCertificate bool - certificate string - hostInCertificate string - serverSPN string - workstation string - appname string - typeFlags uint8 - failOverPartner string - failOverPort uint64 - packetSize uint16 -} - -func splitConnectionString(dsn string) (res map[string]string) { - res = map[string]string{} - parts := strings.Split(dsn, ";") - for _, part := range parts { - if len(part) == 0 { - continue - } - lst := strings.SplitN(part, "=", 2) - name := strings.TrimSpace(strings.ToLower(lst[0])) - if len(name) == 0 { - continue - } - var value string = "" - if len(lst) > 1 { - value = strings.TrimSpace(lst[1]) - } - res[name] = value - } - return res -} - -// Splits a URL in the ODBC format -func splitConnectionStringOdbc(dsn string) (map[string]string, error) { - res := map[string]string{} - - type parserState int - const ( - // Before the start of a key - parserStateBeforeKey parserState = iota - - // Inside a key - parserStateKey - - // Beginning of a value. May be bare or braced - parserStateBeginValue - - // Inside a bare value - parserStateBareValue - - // Inside a braced value - parserStateBracedValue - - // A closing brace inside a braced value. - // May be the end of the value or an escaped closing brace, depending on the next character - parserStateBracedValueClosingBrace - - // After a value. Next character should be a semicolon or whitespace. - parserStateEndValue - ) - - var state = parserStateBeforeKey - - var key string - var value string - - for i, c := range dsn { - switch state { - case parserStateBeforeKey: - switch { - case c == '=': - return res, fmt.Errorf("Unexpected character = at index %d. Expected start of key or semi-colon or whitespace.", i) - case !unicode.IsSpace(c) && c != ';': - state = parserStateKey - key += string(c) - } - - case parserStateKey: - switch c { - case '=': - key = normalizeOdbcKey(key) - if len(key) == 0 { - return res, fmt.Errorf("Unexpected end of key at index %d.", i) - } - - state = parserStateBeginValue - - case ';': - // Key without value - key = normalizeOdbcKey(key) - if len(key) == 0 { - return res, fmt.Errorf("Unexpected end of key at index %d.", i) - } - - res[key] = value - key = "" - value = "" - state = parserStateBeforeKey - - default: - key += string(c) - } - - case parserStateBeginValue: - switch { - case c == '{': - state = parserStateBracedValue - case c == ';': - // Empty value - res[key] = value - key = "" - state = parserStateBeforeKey - case unicode.IsSpace(c): - // Ignore whitespace - default: - state = parserStateBareValue - value += string(c) - } - - case parserStateBareValue: - if c == ';' { - res[key] = strings.TrimRightFunc(value, unicode.IsSpace) - key = "" - value = "" - state = parserStateBeforeKey - } else { - value += string(c) - } - - case parserStateBracedValue: - if c == '}' { - state = parserStateBracedValueClosingBrace - } else { - value += string(c) - } - - case parserStateBracedValueClosingBrace: - if c == '}' { - // Escaped closing brace - value += string(c) - state = parserStateBracedValue - continue - } - - // End of braced value - res[key] = value - key = "" - value = "" - - // This character is the first character past the end, - // so it needs to be parsed like the parserStateEndValue state. - state = parserStateEndValue - switch { - case c == ';': - state = parserStateBeforeKey - case unicode.IsSpace(c): - // Ignore whitespace - default: - return res, fmt.Errorf("Unexpected character %c at index %d. Expected semi-colon or whitespace.", c, i) - } - - case parserStateEndValue: - switch { - case c == ';': - state = parserStateBeforeKey - case unicode.IsSpace(c): - // Ignore whitespace - default: - return res, fmt.Errorf("Unexpected character %c at index %d. Expected semi-colon or whitespace.", c, i) - } - } - } - - switch state { - case parserStateBeforeKey: // Okay - case parserStateKey: // Unfinished key. Treat as key without value. - key = normalizeOdbcKey(key) - if len(key) == 0 { - return res, fmt.Errorf("Unexpected end of key at index %d.", len(dsn)) - } - res[key] = value - case parserStateBeginValue: // Empty value - res[key] = value - case parserStateBareValue: - res[key] = strings.TrimRightFunc(value, unicode.IsSpace) - case parserStateBracedValue: - return res, fmt.Errorf("Unexpected end of braced value at index %d.", len(dsn)) - case parserStateBracedValueClosingBrace: // End of braced value - res[key] = value - case parserStateEndValue: // Okay - } - - return res, nil -} - -// Normalizes the given string as an ODBC-format key -func normalizeOdbcKey(s string) string { - return strings.ToLower(strings.TrimRightFunc(s, unicode.IsSpace)) -} - -// Splits a URL of the form sqlserver://username:password@host/instance?param1=value¶m2=value -func splitConnectionStringURL(dsn string) (map[string]string, error) { - res := map[string]string{} - - u, err := url.Parse(dsn) - if err != nil { - return res, err - } - - if u.Scheme != "sqlserver" { - return res, fmt.Errorf("scheme %s is not recognized", u.Scheme) - } - - if u.User != nil { - res["user id"] = u.User.Username() - p, exists := u.User.Password() - if exists { - res["password"] = p - } - } - - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - host = u.Host - } - - if len(u.Path) > 0 { - res["server"] = host + "\\" + u.Path[1:] - } else { - res["server"] = host - } - - if len(port) > 0 { - res["port"] = port - } - - query := u.Query() - for k, v := range query { - if len(v) > 1 { - return res, fmt.Errorf("key %s provided more than once", k) - } - res[strings.ToLower(k)] = v[0] - } - - return res, nil -} - -func parseConnectParams(dsn string) (connectParams, error) { - var p connectParams - - var params map[string]string - if strings.HasPrefix(dsn, "odbc:") { - parameters, err := splitConnectionStringOdbc(dsn[len("odbc:"):]) - if err != nil { - return p, err - } - params = parameters - } else if strings.HasPrefix(dsn, "sqlserver://") { - parameters, err := splitConnectionStringURL(dsn) - if err != nil { - return p, err - } - params = parameters - } else { - params = splitConnectionString(dsn) - } - - strlog, ok := params["log"] - if ok { - var err error - p.logFlags, err = strconv.ParseUint(strlog, 10, 64) - if err != nil { - return p, fmt.Errorf("Invalid log parameter '%s': %s", strlog, err.Error()) - } - } - server := params["server"] - parts := strings.SplitN(server, `\`, 2) - p.host = parts[0] - if p.host == "." || strings.ToUpper(p.host) == "(LOCAL)" || p.host == "" { - p.host = "localhost" - } - if len(parts) > 1 { - p.instance = parts[1] - } - p.database = params["database"] - p.user = params["user id"] - p.password = params["password"] - - p.port = 1433 - strport, ok := params["port"] - if ok { - var err error - p.port, err = strconv.ParseUint(strport, 10, 16) - if err != nil { - f := "Invalid tcp port '%v': %v" - return p, fmt.Errorf(f, strport, err.Error()) - } - } - - // https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option - // Default packet size remains at 4096 bytes - p.packetSize = 4096 - strpsize, ok := params["packet size"] - if ok { - var err error - psize, err := strconv.ParseUint(strpsize, 0, 16) - if err != nil { - f := "Invalid packet size '%v': %v" - return p, fmt.Errorf(f, strpsize, err.Error()) - } - - // Ensure packet size falls within the TDS protocol range of 512 to 32767 bytes - // NOTE: Encrypted connections have a maximum size of 16383 bytes. If you request - // a higher packet size, the server will respond with an ENVCHANGE request to - // alter the packet size to 16383 bytes. - p.packetSize = uint16(psize) - if p.packetSize < 512 { - p.packetSize = 512 - } else if p.packetSize > 32767 { - p.packetSize = 32767 - } - } - - // https://msdn.microsoft.com/en-us/library/dd341108.aspx - // - // Do not set a connection timeout. Use Context to manage such things. - // Default to zero, but still allow it to be set. - if strconntimeout, ok := params["connection timeout"]; ok { - timeout, err := strconv.ParseUint(strconntimeout, 10, 64) - if err != nil { - f := "Invalid connection timeout '%v': %v" - return p, fmt.Errorf(f, strconntimeout, err.Error()) - } - p.conn_timeout = time.Duration(timeout) * time.Second - } - p.dial_timeout = 15 * time.Second - if strdialtimeout, ok := params["dial timeout"]; ok { - timeout, err := strconv.ParseUint(strdialtimeout, 10, 64) - if err != nil { - f := "Invalid dial timeout '%v': %v" - return p, fmt.Errorf(f, strdialtimeout, err.Error()) - } - p.dial_timeout = time.Duration(timeout) * time.Second - } - - // default keep alive should be 30 seconds according to spec: - // https://msdn.microsoft.com/en-us/library/dd341108.aspx - p.keepAlive = 30 * time.Second - if keepAlive, ok := params["keepalive"]; ok { - timeout, err := strconv.ParseUint(keepAlive, 10, 64) - if err != nil { - f := "Invalid keepAlive value '%s': %s" - return p, fmt.Errorf(f, keepAlive, err.Error()) - } - p.keepAlive = time.Duration(timeout) * time.Second - } - encrypt, ok := params["encrypt"] - if ok { - if strings.EqualFold(encrypt, "DISABLE") { - p.disableEncryption = true - } else { - var err error - p.encrypt, err = strconv.ParseBool(encrypt) - if err != nil { - f := "Invalid encrypt '%s': %s" - return p, fmt.Errorf(f, encrypt, err.Error()) - } - } - } else { - p.trustServerCertificate = true - } - trust, ok := params["trustservercertificate"] - if ok { - var err error - p.trustServerCertificate, err = strconv.ParseBool(trust) - if err != nil { - f := "Invalid trust server certificate '%s': %s" - return p, fmt.Errorf(f, trust, err.Error()) - } - } - p.certificate = params["certificate"] - p.hostInCertificate, ok = params["hostnameincertificate"] - if !ok { - p.hostInCertificate = p.host - } - - serverSPN, ok := params["serverspn"] - if ok { - p.serverSPN = serverSPN - } else { - p.serverSPN = fmt.Sprintf("MSSQLSvc/%s:%d", p.host, p.port) - } - - workstation, ok := params["workstation id"] - if ok { - p.workstation = workstation - } else { - workstation, err := os.Hostname() - if err == nil { - p.workstation = workstation - } - } - - appname, ok := params["app name"] - if !ok { - appname = "go-mssqldb" - } - p.appname = appname - - appintent, ok := params["applicationintent"] - if ok { - if appintent == "ReadOnly" { - p.typeFlags |= fReadOnlyIntent - } - } - - failOverPartner, ok := params["failoverpartner"] - if ok { - p.failOverPartner = failOverPartner - } - - failOverPort, ok := params["failoverport"] - if ok { - var err error - p.failOverPort, err = strconv.ParseUint(failOverPort, 0, 16) - if err != nil { - f := "Invalid tcp port '%v': %v" - return p, fmt.Errorf(f, failOverPort, err.Error()) - } - } - - return p, nil -} - -type auth interface { - InitialBytes() ([]byte, error) - NextBytes([]byte) ([]byte, error) - Free() -} - -// SQL Server AlwaysOn Availability Group Listeners are bound by DNS to a -// list of IP addresses. So if there is more than one, try them all and -// use the first one that allows a connection. -func dialConnection(ctx context.Context, p connectParams) (conn net.Conn, err error) { - var ips []net.IP - ips, err = net.LookupIP(p.host) - if err != nil { - ip := net.ParseIP(p.host) - if ip == nil { - return nil, err - } - ips = []net.IP{ip} - } - if len(ips) == 1 { - d := createDialer(&p) - addr := net.JoinHostPort(ips[0].String(), strconv.Itoa(int(p.port))) - conn, err = d.Dial(ctx, addr) - - } else { - //Try Dials in parallel to avoid waiting for timeouts. - connChan := make(chan net.Conn, len(ips)) - errChan := make(chan error, len(ips)) - portStr := strconv.Itoa(int(p.port)) - for _, ip := range ips { - go func(ip net.IP) { - d := createDialer(&p) - addr := net.JoinHostPort(ip.String(), portStr) - conn, err := d.Dial(ctx, addr) - if err == nil { - connChan <- conn - } else { - errChan <- err - } - }(ip) - } - // Wait for either the *first* successful connection, or all the errors - wait_loop: - for i, _ := range ips { - select { - case conn = <-connChan: - // Got a connection to use, close any others - go func(n int) { - for i := 0; i < n; i++ { - select { - case conn := <-connChan: - conn.Close() - case <-errChan: - } - } - }(len(ips) - i - 1) - // Remove any earlier errors we may have collected - err = nil - break wait_loop - case err = <-errChan: - } - } - } - // Can't do the usual err != nil check, as it is possible to have gotten an error before a successful connection - if conn == nil { - f := "Unable to open tcp connection with host '%v:%v': %v" - return nil, fmt.Errorf(f, p.host, p.port, err.Error()) - } - return conn, err -} - -func connect(ctx context.Context, log optionalLogger, p connectParams) (res *tdsSession, err error) { - dialCtx := ctx - if p.dial_timeout > 0 { - var cancel func() - dialCtx, cancel = context.WithTimeout(ctx, p.dial_timeout) - defer cancel() - } - // if instance is specified use instance resolution service - if p.instance != "" { - p.instance = strings.ToUpper(p.instance) - instances, err := getInstances(dialCtx, p.host) - if err != nil { - f := "Unable to get instances from Sql Server Browser on host %v: %v" - return nil, fmt.Errorf(f, p.host, err.Error()) - } - strport, ok := instances[p.instance]["tcp"] - if !ok { - f := "No instance matching '%v' returned from host '%v'" - return nil, fmt.Errorf(f, p.instance, p.host) - } - p.port, err = strconv.ParseUint(strport, 0, 16) - if err != nil { - f := "Invalid tcp port returned from Sql Server Browser '%v': %v" - return nil, fmt.Errorf(f, strport, err.Error()) - } - } - -initiate_connection: - conn, err := dialConnection(dialCtx, p) - if err != nil { - return nil, err - } - - toconn := newTimeoutConn(conn, p.conn_timeout) - - outbuf := newTdsBuffer(p.packetSize, toconn) - sess := tdsSession{ - buf: outbuf, - log: log, - logFlags: p.logFlags, - } - - instance_buf := []byte(p.instance) - instance_buf = append(instance_buf, 0) // zero terminate instance name - var encrypt byte - if p.disableEncryption { - encrypt = encryptNotSup - } else if p.encrypt { - encrypt = encryptOn - } else { - encrypt = encryptOff - } - fields := map[uint8][]byte{ - preloginVERSION: {0, 0, 0, 0, 0, 0}, - preloginENCRYPTION: {encrypt}, - preloginINSTOPT: instance_buf, - preloginTHREADID: {0, 0, 0, 0}, - preloginMARS: {0}, // MARS disabled - } - - err = writePrelogin(outbuf, fields) - if err != nil { - return nil, err - } - - fields, err = readPrelogin(outbuf) - if err != nil { - return nil, err - } - - encryptBytes, ok := fields[preloginENCRYPTION] - if !ok { - return nil, fmt.Errorf("Encrypt negotiation failed") - } - encrypt = encryptBytes[0] - if p.encrypt && (encrypt == encryptNotSup || encrypt == encryptOff) { - return nil, fmt.Errorf("Server does not support encryption") - } - - if encrypt != encryptNotSup { - var config tls.Config - if p.certificate != "" { - pem, err := ioutil.ReadFile(p.certificate) - if err != nil { - return nil, fmt.Errorf("Cannot read certificate %q: %v", p.certificate, err) - } - certs := x509.NewCertPool() - certs.AppendCertsFromPEM(pem) - config.RootCAs = certs - } - if p.trustServerCertificate { - config.InsecureSkipVerify = true - } - config.ServerName = p.hostInCertificate - // fix for https://github.com/denisenkom/go-mssqldb/issues/166 - // Go implementation of TLS payload size heuristic algorithm splits single TDS package to multiple TCP segments, - // while SQL Server seems to expect one TCP segment per encrypted TDS package. - // Setting DynamicRecordSizingDisabled to true disables that algorithm and uses 16384 bytes per TLS package - config.DynamicRecordSizingDisabled = true - outbuf.transport = conn - toconn.buf = outbuf - tlsConn := tls.Client(toconn, &config) - err = tlsConn.Handshake() - - toconn.buf = nil - outbuf.transport = tlsConn - if err != nil { - return nil, fmt.Errorf("TLS Handshake failed: %v", err) - } - if encrypt == encryptOff { - outbuf.afterFirst = func() { - outbuf.transport = toconn - } - } - } - - login := login{ - TDSVersion: verTDS74, - PacketSize: uint32(outbuf.PackageSize()), - Database: p.database, - OptionFlags2: fODBC, // to get unlimited TEXTSIZE - HostName: p.workstation, - ServerName: p.host, - AppName: p.appname, - TypeFlags: p.typeFlags, - } - auth, auth_ok := getAuth(p.user, p.password, p.serverSPN, p.workstation) - if auth_ok { - login.SSPI, err = auth.InitialBytes() - if err != nil { - return nil, err - } - login.OptionFlags2 |= fIntSecurity - defer auth.Free() - } else { - login.UserName = p.user - login.Password = p.password - } - err = sendLogin(outbuf, login) - if err != nil { - return nil, err - } - - // processing login response - var sspi_msg []byte -continue_login: - tokchan := make(chan tokenStruct, 5) - go processResponse(context.Background(), &sess, tokchan, nil) - success := false - for tok := range tokchan { - switch token := tok.(type) { - case sspiMsg: - sspi_msg, err = auth.NextBytes(token) - if err != nil { - return nil, err - } - case loginAckStruct: - success = true - sess.loginAck = token - case error: - return nil, fmt.Errorf("Login error: %s", token.Error()) - case doneStruct: - if token.isError() { - return nil, fmt.Errorf("Login error: %s", token.getError()) - } - } - } - if sspi_msg != nil { - outbuf.BeginPacket(packSSPIMessage, false) - _, err = outbuf.Write(sspi_msg) - if err != nil { - return nil, err - } - err = outbuf.FinishPacket() - if err != nil { - return nil, err - } - sspi_msg = nil - goto continue_login - } - if !success { - return nil, fmt.Errorf("Login failed") - } - if sess.routedServer != "" { - toconn.Close() - p.host = sess.routedServer - p.port = uint64(sess.routedPort) - goto initiate_connection - } - return &sess, nil -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/token.go b/vendor/github.com/denisenkom/go-mssqldb/token.go deleted file mode 100644 index 1acac8a5d..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/token.go +++ /dev/null @@ -1,804 +0,0 @@ -package mssql - -import ( - "context" - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "strconv" - "strings" -) - -//go:generate stringer -type token - -type token byte - -// token ids -const ( - tokenReturnStatus token = 121 // 0x79 - tokenColMetadata token = 129 // 0x81 - tokenOrder token = 169 // 0xA9 - tokenError token = 170 // 0xAA - tokenInfo token = 171 // 0xAB - tokenReturnValue token = 0xAC - tokenLoginAck token = 173 // 0xad - tokenRow token = 209 // 0xd1 - tokenNbcRow token = 210 // 0xd2 - tokenEnvChange token = 227 // 0xE3 - tokenSSPI token = 237 // 0xED - tokenDone token = 253 // 0xFD - tokenDoneProc token = 254 - tokenDoneInProc token = 255 -) - -// done flags -// https://msdn.microsoft.com/en-us/library/dd340421.aspx -const ( - doneFinal = 0 - doneMore = 1 - doneError = 2 - doneInxact = 4 - doneCount = 0x10 - doneAttn = 0x20 - doneSrvError = 0x100 -) - -// ENVCHANGE types -// http://msdn.microsoft.com/en-us/library/dd303449.aspx -const ( - envTypDatabase = 1 - envTypLanguage = 2 - envTypCharset = 3 - envTypPacketSize = 4 - envSortId = 5 - envSortFlags = 6 - envSqlCollation = 7 - envTypBeginTran = 8 - envTypCommitTran = 9 - envTypRollbackTran = 10 - envEnlistDTC = 11 - envDefectTran = 12 - envDatabaseMirrorPartner = 13 - envPromoteTran = 15 - envTranMgrAddr = 16 - envTranEnded = 17 - envResetConnAck = 18 - envStartedInstanceName = 19 - envRouting = 20 -) - -// COLMETADATA flags -// https://msdn.microsoft.com/en-us/library/dd357363.aspx -const ( - colFlagNullable = 1 - // TODO implement more flags -) - -// interface for all tokens -type tokenStruct interface{} - -type orderStruct struct { - ColIds []uint16 -} - -type doneStruct struct { - Status uint16 - CurCmd uint16 - RowCount uint64 - errors []Error -} - -func (d doneStruct) isError() bool { - return d.Status&doneError != 0 || len(d.errors) > 0 -} - -func (d doneStruct) getError() Error { - if len(d.errors) > 0 { - return d.errors[len(d.errors)-1] - } else { - return Error{Message: "Request failed but didn't provide reason"} - } -} - -type doneInProcStruct doneStruct - -var doneFlags2str = map[uint16]string{ - doneFinal: "final", - doneMore: "more", - doneError: "error", - doneInxact: "inxact", - doneCount: "count", - doneAttn: "attn", - doneSrvError: "srverror", -} - -func doneFlags2Str(flags uint16) string { - strs := make([]string, 0, len(doneFlags2str)) - for flag, tag := range doneFlags2str { - if flags&flag != 0 { - strs = append(strs, tag) - } - } - return strings.Join(strs, "|") -} - -// ENVCHANGE stream -// http://msdn.microsoft.com/en-us/library/dd303449.aspx -func processEnvChg(sess *tdsSession) { - size := sess.buf.uint16() - r := &io.LimitedReader{R: sess.buf, N: int64(size)} - for { - var err error - var envtype uint8 - err = binary.Read(r, binary.LittleEndian, &envtype) - if err == io.EOF { - return - } - if err != nil { - badStreamPanic(err) - } - switch envtype { - case envTypDatabase: - sess.database, err = readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - _, err = readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - case envTypLanguage: - // currently ignored - // new value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envTypCharset: - // currently ignored - // new value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envTypPacketSize: - packetsize, err := readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - _, err = readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - packetsizei, err := strconv.Atoi(packetsize) - if err != nil { - badStreamPanicf("Invalid Packet size value returned from server (%s): %s", packetsize, err.Error()) - } - sess.buf.ResizeBuffer(packetsizei) - case envSortId: - // currently ignored - // new value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envSortFlags: - // currently ignored - // new value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envSqlCollation: - // currently ignored - var collationSize uint8 - err = binary.Read(r, binary.LittleEndian, &collationSize) - if err != nil { - badStreamPanic(err) - } - - // SQL Collation data should contain 5 bytes in length - if collationSize != 5 { - badStreamPanicf("Invalid SQL Collation size value returned from server: %d", collationSize) - } - - // 4 bytes, contains: LCID ColFlags Version - var info uint32 - err = binary.Read(r, binary.LittleEndian, &info) - if err != nil { - badStreamPanic(err) - } - - // 1 byte, contains: sortID - var sortID uint8 - err = binary.Read(r, binary.LittleEndian, &sortID) - if err != nil { - badStreamPanic(err) - } - - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envTypBeginTran: - tranid, err := readBVarByte(r) - if len(tranid) != 8 { - badStreamPanicf("invalid size of transaction identifier: %d", len(tranid)) - } - sess.tranid = binary.LittleEndian.Uint64(tranid) - if err != nil { - badStreamPanic(err) - } - if sess.logFlags&logTransaction != 0 { - sess.log.Printf("BEGIN TRANSACTION %x\n", sess.tranid) - } - _, err = readBVarByte(r) - if err != nil { - badStreamPanic(err) - } - case envTypCommitTran, envTypRollbackTran: - _, err = readBVarByte(r) - if err != nil { - badStreamPanic(err) - } - _, err = readBVarByte(r) - if err != nil { - badStreamPanic(err) - } - if sess.logFlags&logTransaction != 0 { - if envtype == envTypCommitTran { - sess.log.Printf("COMMIT TRANSACTION %x\n", sess.tranid) - } else { - sess.log.Printf("ROLLBACK TRANSACTION %x\n", sess.tranid) - } - } - sess.tranid = 0 - case envEnlistDTC: - // currently ignored - // new value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envDefectTran: - // currently ignored - // new value - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envDatabaseMirrorPartner: - sess.partner, err = readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - _, err = readBVarChar(r) - if err != nil { - badStreamPanic(err) - } - case envPromoteTran: - // currently ignored - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // dtc token - // spec says it should be L_VARBYTE, so this code might be wrong - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envTranMgrAddr: - // currently ignored - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // XACT_MANAGER_ADDRESS = B_VARBYTE - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envTranEnded: - // currently ignored - // old value, B_VARBYTE - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envResetConnAck: - // currently ignored - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envStartedInstanceName: - // currently ignored - // old value, should be 0 - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - // instance name - if _, err = readBVarChar(r); err != nil { - badStreamPanic(err) - } - case envRouting: - // RoutingData message is: - // ValueLength USHORT - // Protocol (TCP = 0) BYTE - // ProtocolProperty (new port) USHORT - // AlternateServer US_VARCHAR - _, err := readUshort(r) - if err != nil { - badStreamPanic(err) - } - protocol, err := readByte(r) - if err != nil || protocol != 0 { - badStreamPanic(err) - } - newPort, err := readUshort(r) - if err != nil { - badStreamPanic(err) - } - newServer, err := readUsVarChar(r) - if err != nil { - badStreamPanic(err) - } - // consume the OLDVALUE = %x00 %x00 - _, err = readUshort(r) - if err != nil { - badStreamPanic(err) - } - sess.routedServer = newServer - sess.routedPort = newPort - default: - // ignore rest of records because we don't know how to skip those - sess.log.Printf("WARN: Unknown ENVCHANGE record detected with type id = %d\n", envtype) - break - } - - } -} - -// http://msdn.microsoft.com/en-us/library/dd358180.aspx -func parseReturnStatus(r *tdsBuffer) ReturnStatus { - return ReturnStatus(r.int32()) -} - -func parseOrder(r *tdsBuffer) (res orderStruct) { - len := int(r.uint16()) - res.ColIds = make([]uint16, len/2) - for i := 0; i < len/2; i++ { - res.ColIds[i] = r.uint16() - } - return res -} - -// https://msdn.microsoft.com/en-us/library/dd340421.aspx -func parseDone(r *tdsBuffer) (res doneStruct) { - res.Status = r.uint16() - res.CurCmd = r.uint16() - res.RowCount = r.uint64() - return res -} - -// https://msdn.microsoft.com/en-us/library/dd340553.aspx -func parseDoneInProc(r *tdsBuffer) (res doneInProcStruct) { - res.Status = r.uint16() - res.CurCmd = r.uint16() - res.RowCount = r.uint64() - return res -} - -type sspiMsg []byte - -func parseSSPIMsg(r *tdsBuffer) sspiMsg { - size := r.uint16() - buf := make([]byte, size) - r.ReadFull(buf) - return sspiMsg(buf) -} - -type loginAckStruct struct { - Interface uint8 - TDSVersion uint32 - ProgName string - ProgVer uint32 -} - -func parseLoginAck(r *tdsBuffer) loginAckStruct { - size := r.uint16() - buf := make([]byte, size) - r.ReadFull(buf) - var res loginAckStruct - res.Interface = buf[0] - res.TDSVersion = binary.BigEndian.Uint32(buf[1:]) - prognamelen := buf[1+4] - var err error - if res.ProgName, err = ucs22str(buf[1+4+1 : 1+4+1+prognamelen*2]); err != nil { - badStreamPanic(err) - } - res.ProgVer = binary.BigEndian.Uint32(buf[size-4:]) - return res -} - -// http://msdn.microsoft.com/en-us/library/dd357363.aspx -func parseColMetadata72(r *tdsBuffer) (columns []columnStruct) { - count := r.uint16() - if count == 0xffff { - // no metadata is sent - return nil - } - columns = make([]columnStruct, count) - for i := range columns { - column := &columns[i] - column.UserType = r.uint32() - column.Flags = r.uint16() - - // parsing TYPE_INFO structure - column.ti = readTypeInfo(r) - column.ColName = r.BVarChar() - } - return columns -} - -// http://msdn.microsoft.com/en-us/library/dd357254.aspx -func parseRow(r *tdsBuffer, columns []columnStruct, row []interface{}) { - for i, column := range columns { - row[i] = column.ti.Reader(&column.ti, r) - } -} - -// http://msdn.microsoft.com/en-us/library/dd304783.aspx -func parseNbcRow(r *tdsBuffer, columns []columnStruct, row []interface{}) { - bitlen := (len(columns) + 7) / 8 - pres := make([]byte, bitlen) - r.ReadFull(pres) - for i, col := range columns { - if pres[i/8]&(1<<(uint(i)%8)) != 0 { - row[i] = nil - continue - } - row[i] = col.ti.Reader(&col.ti, r) - } -} - -// http://msdn.microsoft.com/en-us/library/dd304156.aspx -func parseError72(r *tdsBuffer) (res Error) { - length := r.uint16() - _ = length // ignore length - res.Number = r.int32() - res.State = r.byte() - res.Class = r.byte() - res.Message = r.UsVarChar() - res.ServerName = r.BVarChar() - res.ProcName = r.BVarChar() - res.LineNo = r.int32() - return -} - -// http://msdn.microsoft.com/en-us/library/dd304156.aspx -func parseInfo(r *tdsBuffer) (res Error) { - length := r.uint16() - _ = length // ignore length - res.Number = r.int32() - res.State = r.byte() - res.Class = r.byte() - res.Message = r.UsVarChar() - res.ServerName = r.BVarChar() - res.ProcName = r.BVarChar() - res.LineNo = r.int32() - return -} - -// https://msdn.microsoft.com/en-us/library/dd303881.aspx -func parseReturnValue(r *tdsBuffer) (nv namedValue) { - /* - ParamOrdinal - ParamName - Status - UserType - Flags - TypeInfo - CryptoMetadata - Value - */ - r.uint16() - nv.Name = r.BVarChar() - r.byte() - r.uint32() // UserType (uint16 prior to 7.2) - r.uint16() - ti := readTypeInfo(r) - nv.Value = ti.Reader(&ti, r) - return -} - -func processSingleResponse(sess *tdsSession, ch chan tokenStruct, outs map[string]interface{}) { - defer func() { - if err := recover(); err != nil { - if sess.logFlags&logErrors != 0 { - sess.log.Printf("ERROR: Intercepted panic %v", err) - } - ch <- err - } - close(ch) - }() - - packet_type, err := sess.buf.BeginRead() - if err != nil { - if sess.logFlags&logErrors != 0 { - sess.log.Printf("ERROR: BeginRead failed %v", err) - } - ch <- err - return - } - if packet_type != packReply { - badStreamPanic(fmt.Errorf("unexpected packet type in reply: got %v, expected %v", packet_type, packReply)) - } - var columns []columnStruct - errs := make([]Error, 0, 5) - for { - token := token(sess.buf.byte()) - if sess.logFlags&logDebug != 0 { - sess.log.Printf("got token %v", token) - } - switch token { - case tokenSSPI: - ch <- parseSSPIMsg(sess.buf) - return - case tokenReturnStatus: - returnStatus := parseReturnStatus(sess.buf) - ch <- returnStatus - case tokenLoginAck: - loginAck := parseLoginAck(sess.buf) - ch <- loginAck - case tokenOrder: - order := parseOrder(sess.buf) - ch <- order - case tokenDoneInProc: - done := parseDoneInProc(sess.buf) - if sess.logFlags&logRows != 0 && done.Status&doneCount != 0 { - sess.log.Printf("(%d row(s) affected)\n", done.RowCount) - } - ch <- done - case tokenDone, tokenDoneProc: - done := parseDone(sess.buf) - done.errors = errs - if sess.logFlags&logDebug != 0 { - sess.log.Printf("got DONE or DONEPROC status=%d", done.Status) - } - if done.Status&doneSrvError != 0 { - ch <- errors.New("SQL Server had internal error") - return - } - if sess.logFlags&logRows != 0 && done.Status&doneCount != 0 { - sess.log.Printf("(%d row(s) affected)\n", done.RowCount) - } - ch <- done - if done.Status&doneMore == 0 { - return - } - case tokenColMetadata: - columns = parseColMetadata72(sess.buf) - ch <- columns - case tokenRow: - row := make([]interface{}, len(columns)) - parseRow(sess.buf, columns, row) - ch <- row - case tokenNbcRow: - row := make([]interface{}, len(columns)) - parseNbcRow(sess.buf, columns, row) - ch <- row - case tokenEnvChange: - processEnvChg(sess) - case tokenError: - err := parseError72(sess.buf) - if sess.logFlags&logDebug != 0 { - sess.log.Printf("got ERROR %d %s", err.Number, err.Message) - } - errs = append(errs, err) - if sess.logFlags&logErrors != 0 { - sess.log.Println(err.Message) - } - case tokenInfo: - info := parseInfo(sess.buf) - if sess.logFlags&logDebug != 0 { - sess.log.Printf("got INFO %d %s", info.Number, info.Message) - } - if sess.logFlags&logMessages != 0 { - sess.log.Println(info.Message) - } - case tokenReturnValue: - nv := parseReturnValue(sess.buf) - if len(nv.Name) > 0 { - name := nv.Name[1:] // Remove the leading "@". - if ov, has := outs[name]; has { - err = scanIntoOut(name, nv.Value, ov) - if err != nil { - fmt.Println("scan error", err) - ch <- err - } - } - } - default: - badStreamPanic(fmt.Errorf("unknown token type returned: %v", token)) - } - } -} - -type parseRespIter byte - -const ( - parseRespIterContinue parseRespIter = iota // Continue parsing current token. - parseRespIterNext // Fetch the next token. - parseRespIterDone // Done with parsing the response. -) - -type parseRespState byte - -const ( - parseRespStateNormal parseRespState = iota // Normal response state. - parseRespStateCancel // Query is canceled, wait for server to confirm. - parseRespStateClosing // Waiting for tokens to come through. -) - -type parseResp struct { - sess *tdsSession - ctxDone <-chan struct{} - state parseRespState - cancelError error -} - -func (ts *parseResp) sendAttention(ch chan tokenStruct) parseRespIter { - if err := sendAttention(ts.sess.buf); err != nil { - ts.dlogf("failed to send attention signal %v", err) - ch <- err - return parseRespIterDone - } - ts.state = parseRespStateCancel - return parseRespIterContinue -} - -func (ts *parseResp) dlog(msg string) { - if ts.sess.logFlags&logDebug != 0 { - ts.sess.log.Println(msg) - } -} -func (ts *parseResp) dlogf(f string, v ...interface{}) { - if ts.sess.logFlags&logDebug != 0 { - ts.sess.log.Printf(f, v...) - } -} - -func (ts *parseResp) iter(ctx context.Context, ch chan tokenStruct, tokChan chan tokenStruct) parseRespIter { - switch ts.state { - default: - panic("unknown state") - case parseRespStateNormal: - select { - case tok, ok := <-tokChan: - if !ok { - ts.dlog("response finished") - return parseRespIterDone - } - if err, ok := tok.(net.Error); ok && err.Timeout() { - ts.cancelError = err - ts.dlog("got timeout error, sending attention signal to server") - return ts.sendAttention(ch) - } - // Pass the token along. - ch <- tok - return parseRespIterContinue - - case <-ts.ctxDone: - ts.ctxDone = nil - ts.dlog("got cancel message, sending attention signal to server") - return ts.sendAttention(ch) - } - case parseRespStateCancel: // Read all responses until a DONE or error is received.Auth - select { - case tok, ok := <-tokChan: - if !ok { - ts.dlog("response finished but waiting for attention ack") - return parseRespIterNext - } - switch tok := tok.(type) { - default: - // Ignore all other tokens while waiting. - // The TDS spec says other tokens may arrive after an attention - // signal is sent. Ignore these tokens and continue looking for - // a DONE with attention confirm mark. - case doneStruct: - if tok.Status&doneAttn != 0 { - ts.dlog("got cancellation confirmation from server") - if ts.cancelError != nil { - ch <- ts.cancelError - ts.cancelError = nil - } else { - ch <- ctx.Err() - } - return parseRespIterDone - } - - // If an error happens during cancel, pass it along and just stop. - // We are uncertain to receive more tokens. - case error: - ch <- tok - ts.state = parseRespStateClosing - } - return parseRespIterContinue - case <-ts.ctxDone: - ts.ctxDone = nil - ts.state = parseRespStateClosing - return parseRespIterContinue - } - case parseRespStateClosing: // Wait for current token chan to close. - if _, ok := <-tokChan; !ok { - ts.dlog("response finished") - return parseRespIterDone - } - return parseRespIterContinue - } -} - -func processResponse(ctx context.Context, sess *tdsSession, ch chan tokenStruct, outs map[string]interface{}) { - ts := &parseResp{ - sess: sess, - ctxDone: ctx.Done(), - } - defer func() { - // Ensure any remaining error is piped through - // or the query may look like it executed when it actually failed. - if ts.cancelError != nil { - ch <- ts.cancelError - ts.cancelError = nil - } - close(ch) - }() - - // Loop over multiple responses. - for { - ts.dlog("initiating response reading") - - tokChan := make(chan tokenStruct) - go processSingleResponse(sess, tokChan, outs) - - // Loop over multiple tokens in response. - tokensLoop: - for { - switch ts.iter(ctx, ch, tokChan) { - case parseRespIterContinue: - // Nothing, continue to next token. - case parseRespIterNext: - break tokensLoop - case parseRespIterDone: - return - } - } - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/token_string.go b/vendor/github.com/denisenkom/go-mssqldb/token_string.go deleted file mode 100644 index c075b23be..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/token_string.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by "stringer -type token"; DO NOT EDIT - -package mssql - -import "fmt" - -const ( - _token_name_0 = "tokenReturnStatus" - _token_name_1 = "tokenColMetadata" - _token_name_2 = "tokenOrdertokenErrortokenInfo" - _token_name_3 = "tokenLoginAck" - _token_name_4 = "tokenRowtokenNbcRow" - _token_name_5 = "tokenEnvChange" - _token_name_6 = "tokenSSPI" - _token_name_7 = "tokenDonetokenDoneProctokenDoneInProc" -) - -var ( - _token_index_0 = [...]uint8{0, 17} - _token_index_1 = [...]uint8{0, 16} - _token_index_2 = [...]uint8{0, 10, 20, 29} - _token_index_3 = [...]uint8{0, 13} - _token_index_4 = [...]uint8{0, 8, 19} - _token_index_5 = [...]uint8{0, 14} - _token_index_6 = [...]uint8{0, 9} - _token_index_7 = [...]uint8{0, 9, 22, 37} -) - -func (i token) String() string { - switch { - case i == 121: - return _token_name_0 - case i == 129: - return _token_name_1 - case 169 <= i && i <= 171: - i -= 169 - return _token_name_2[_token_index_2[i]:_token_index_2[i+1]] - case i == 173: - return _token_name_3 - case 209 <= i && i <= 210: - i -= 209 - return _token_name_4[_token_index_4[i]:_token_index_4[i+1]] - case i == 227: - return _token_name_5 - case i == 237: - return _token_name_6 - case 253 <= i && i <= 255: - i -= 253 - return _token_name_7[_token_index_7[i]:_token_index_7[i+1]] - default: - return fmt.Sprintf("token(%d)", i) - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/tran.go b/vendor/github.com/denisenkom/go-mssqldb/tran.go deleted file mode 100644 index cb6436816..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/tran.go +++ /dev/null @@ -1,110 +0,0 @@ -package mssql - -// Transaction Manager requests -// http://msdn.microsoft.com/en-us/library/dd339887.aspx - -import ( - "encoding/binary" -) - -const ( - tmGetDtcAddr = 0 - tmPropagateXact = 1 - tmBeginXact = 5 - tmPromoteXact = 6 - tmCommitXact = 7 - tmRollbackXact = 8 - tmSaveXact = 9 -) - -type isoLevel uint8 - -const ( - isolationUseCurrent isoLevel = 0 - isolationReadUncommited = 1 - isolationReadCommited = 2 - isolationRepeatableRead = 3 - isolationSerializable = 4 - isolationSnapshot = 5 -) - -func sendBeginXact(buf *tdsBuffer, headers []headerStruct, isolation isoLevel, name string, resetSession bool) (err error) { - buf.BeginPacket(packTransMgrReq, resetSession) - writeAllHeaders(buf, headers) - var rqtype uint16 = tmBeginXact - err = binary.Write(buf, binary.LittleEndian, &rqtype) - if err != nil { - return - } - err = binary.Write(buf, binary.LittleEndian, &isolation) - if err != nil { - return - } - err = writeBVarChar(buf, name) - if err != nil { - return - } - return buf.FinishPacket() -} - -const ( - fBeginXact = 1 -) - -func sendCommitXact(buf *tdsBuffer, headers []headerStruct, name string, flags uint8, isolation uint8, newname string, resetSession bool) error { - buf.BeginPacket(packTransMgrReq, resetSession) - writeAllHeaders(buf, headers) - var rqtype uint16 = tmCommitXact - err := binary.Write(buf, binary.LittleEndian, &rqtype) - if err != nil { - return err - } - err = writeBVarChar(buf, name) - if err != nil { - return err - } - err = binary.Write(buf, binary.LittleEndian, &flags) - if err != nil { - return err - } - if flags&fBeginXact != 0 { - err = binary.Write(buf, binary.LittleEndian, &isolation) - if err != nil { - return err - } - err = writeBVarChar(buf, name) - if err != nil { - return err - } - } - return buf.FinishPacket() -} - -func sendRollbackXact(buf *tdsBuffer, headers []headerStruct, name string, flags uint8, isolation uint8, newname string, resetSession bool) error { - buf.BeginPacket(packTransMgrReq, resetSession) - writeAllHeaders(buf, headers) - var rqtype uint16 = tmRollbackXact - err := binary.Write(buf, binary.LittleEndian, &rqtype) - if err != nil { - return err - } - err = writeBVarChar(buf, name) - if err != nil { - return err - } - err = binary.Write(buf, binary.LittleEndian, &flags) - if err != nil { - return err - } - if flags&fBeginXact != 0 { - err = binary.Write(buf, binary.LittleEndian, &isolation) - if err != nil { - return err - } - err = writeBVarChar(buf, name) - if err != nil { - return err - } - } - return buf.FinishPacket() -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/types.go b/vendor/github.com/denisenkom/go-mssqldb/types.go deleted file mode 100644 index 3bad788b9..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/types.go +++ /dev/null @@ -1,1566 +0,0 @@ -package mssql - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "math" - "reflect" - "strconv" - "time" - - "github.com/denisenkom/go-mssqldb/internal/cp" -) - -// fixed-length data types -// http://msdn.microsoft.com/en-us/library/dd341171.aspx -const ( - typeNull = 0x1f - typeInt1 = 0x30 - typeBit = 0x32 - typeInt2 = 0x34 - typeInt4 = 0x38 - typeDateTim4 = 0x3a - typeFlt4 = 0x3b - typeMoney = 0x3c - typeDateTime = 0x3d - typeFlt8 = 0x3e - typeMoney4 = 0x7a - typeInt8 = 0x7f -) - -// variable-length data types -// http://msdn.microsoft.com/en-us/library/dd358341.aspx -const ( - // byte len types - typeGuid = 0x24 - typeIntN = 0x26 - typeDecimal = 0x37 // legacy - typeNumeric = 0x3f // legacy - typeBitN = 0x68 - typeDecimalN = 0x6a - typeNumericN = 0x6c - typeFltN = 0x6d - typeMoneyN = 0x6e - typeDateTimeN = 0x6f - typeDateN = 0x28 - typeTimeN = 0x29 - typeDateTime2N = 0x2a - typeDateTimeOffsetN = 0x2b - typeChar = 0x2f // legacy - typeVarChar = 0x27 // legacy - typeBinary = 0x2d // legacy - typeVarBinary = 0x25 // legacy - - // short length types - typeBigVarBin = 0xa5 - typeBigVarChar = 0xa7 - typeBigBinary = 0xad - typeBigChar = 0xaf - typeNVarChar = 0xe7 - typeNChar = 0xef - typeXml = 0xf1 - typeUdt = 0xf0 - - // long length types - typeText = 0x23 - typeImage = 0x22 - typeNText = 0x63 - typeVariant = 0x62 -) -const _PLP_NULL = 0xFFFFFFFFFFFFFFFF -const _UNKNOWN_PLP_LEN = 0xFFFFFFFFFFFFFFFE -const _PLP_TERMINATOR = 0x00000000 - -// TYPE_INFO rule -// http://msdn.microsoft.com/en-us/library/dd358284.aspx -type typeInfo struct { - TypeId uint8 - Size int - Scale uint8 - Prec uint8 - Buffer []byte - Collation cp.Collation - UdtInfo udtInfo - XmlInfo xmlInfo - Reader func(ti *typeInfo, r *tdsBuffer) (res interface{}) - Writer func(w io.Writer, ti typeInfo, buf []byte) (err error) -} - -// Common Language Runtime (CLR) Instances -// http://msdn.microsoft.com/en-us/library/dd357962.aspx -type udtInfo struct { - //MaxByteSize uint32 - DBName string - SchemaName string - TypeName string - AssemblyQualifiedName string -} - -// XML Values -// http://msdn.microsoft.com/en-us/library/dd304764.aspx -type xmlInfo struct { - SchemaPresent uint8 - DBName string - OwningSchema string - XmlSchemaCollection string -} - -func readTypeInfo(r *tdsBuffer) (res typeInfo) { - res.TypeId = r.byte() - switch res.TypeId { - case typeNull, typeInt1, typeBit, typeInt2, typeInt4, typeDateTim4, - typeFlt4, typeMoney, typeDateTime, typeFlt8, typeMoney4, typeInt8: - // those are fixed length types - switch res.TypeId { - case typeNull: - res.Size = 0 - case typeInt1, typeBit: - res.Size = 1 - case typeInt2: - res.Size = 2 - case typeInt4, typeDateTim4, typeFlt4, typeMoney4: - res.Size = 4 - case typeMoney, typeDateTime, typeFlt8, typeInt8: - res.Size = 8 - } - res.Reader = readFixedType - res.Buffer = make([]byte, res.Size) - default: // all others are VARLENTYPE - readVarLen(&res, r) - } - return -} - -// https://msdn.microsoft.com/en-us/library/dd358284.aspx -func writeTypeInfo(w io.Writer, ti *typeInfo) (err error) { - err = binary.Write(w, binary.LittleEndian, ti.TypeId) - if err != nil { - return - } - switch ti.TypeId { - case typeNull, typeInt1, typeBit, typeInt2, typeInt4, typeDateTim4, - typeFlt4, typeMoney, typeDateTime, typeFlt8, typeMoney4, typeInt8: - // those are fixed length - // https://msdn.microsoft.com/en-us/library/dd341171.aspx - ti.Writer = writeFixedType - default: // all others are VARLENTYPE - err = writeVarLen(w, ti) - if err != nil { - return - } - } - return -} - -func writeFixedType(w io.Writer, ti typeInfo, buf []byte) (err error) { - _, err = w.Write(buf) - return -} - -// https://msdn.microsoft.com/en-us/library/dd358341.aspx -func writeVarLen(w io.Writer, ti *typeInfo) (err error) { - switch ti.TypeId { - case typeDateN: - ti.Writer = writeByteLenType - case typeTimeN, typeDateTime2N, typeDateTimeOffsetN: - if err = binary.Write(w, binary.LittleEndian, ti.Scale); err != nil { - return - } - ti.Writer = writeByteLenType - case typeIntN, typeDecimal, typeNumeric, - typeBitN, typeDecimalN, typeNumericN, typeFltN, - typeMoneyN, typeDateTimeN, typeChar, - typeVarChar, typeBinary, typeVarBinary: - - // byle len types - if ti.Size > 0xff { - panic("Invalid size for BYLELEN_TYPE") - } - if err = binary.Write(w, binary.LittleEndian, uint8(ti.Size)); err != nil { - return - } - switch ti.TypeId { - case typeDecimal, typeNumeric, typeDecimalN, typeNumericN: - err = binary.Write(w, binary.LittleEndian, ti.Prec) - if err != nil { - return - } - err = binary.Write(w, binary.LittleEndian, ti.Scale) - if err != nil { - return - } - } - ti.Writer = writeByteLenType - case typeGuid: - if !(ti.Size == 0x10 || ti.Size == 0x00) { - panic("Invalid size for BYLELEN_TYPE") - } - if err = binary.Write(w, binary.LittleEndian, uint8(ti.Size)); err != nil { - return - } - ti.Writer = writeByteLenType - case typeBigVarBin, typeBigVarChar, typeBigBinary, typeBigChar, - typeNVarChar, typeNChar, typeXml, typeUdt: - // short len types - if ti.Size > 8000 || ti.Size == 0 { - if err = binary.Write(w, binary.LittleEndian, uint16(0xffff)); err != nil { - return - } - ti.Writer = writePLPType - } else { - if err = binary.Write(w, binary.LittleEndian, uint16(ti.Size)); err != nil { - return - } - ti.Writer = writeShortLenType - } - switch ti.TypeId { - case typeBigVarChar, typeBigChar, typeNVarChar, typeNChar: - if err = writeCollation(w, ti.Collation); err != nil { - return - } - case typeXml: - if err = binary.Write(w, binary.LittleEndian, ti.XmlInfo.SchemaPresent); err != nil { - return - } - } - case typeText, typeImage, typeNText, typeVariant: - // LONGLEN_TYPE - if err = binary.Write(w, binary.LittleEndian, uint32(ti.Size)); err != nil { - return - } - if err = writeCollation(w, ti.Collation); err != nil { - return - } - ti.Writer = writeLongLenType - default: - panic("Invalid type") - } - return -} - -// http://msdn.microsoft.com/en-us/library/ee780895.aspx -func decodeDateTim4(buf []byte) time.Time { - days := binary.LittleEndian.Uint16(buf) - mins := binary.LittleEndian.Uint16(buf[2:]) - return time.Date(1900, 1, 1+int(days), - 0, int(mins), 0, 0, time.UTC) -} - -func encodeDateTim4(val time.Time) (buf []byte) { - buf = make([]byte, 4) - - ref := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) - dur := val.Sub(ref) - days := dur / (24 * time.Hour) - mins := val.Hour()*60 + val.Minute() - if days < 0 { - days = 0 - mins = 0 - } - - binary.LittleEndian.PutUint16(buf[:2], uint16(days)) - binary.LittleEndian.PutUint16(buf[2:], uint16(mins)) - return -} - -// encodes datetime value -// type identifier is typeDateTimeN -func encodeDateTime(t time.Time) (res []byte) { - // base date in days since Jan 1st 1900 - basedays := gregorianDays(1900, 1) - // days since Jan 1st 1900 (same TZ as t) - days := gregorianDays(t.Year(), t.YearDay()) - basedays - tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9 - // minimum and maximum possible - mindays := gregorianDays(1753, 1) - basedays - maxdays := gregorianDays(9999, 365) - basedays - if days < mindays { - days = mindays - tm = 0 - } - if days > maxdays { - days = maxdays - tm = (23*60*60+59*60+59)*300 + 299 - } - res = make([]byte, 8) - binary.LittleEndian.PutUint32(res[0:4], uint32(days)) - binary.LittleEndian.PutUint32(res[4:8], uint32(tm)) - return -} - -func decodeDateTime(buf []byte) time.Time { - days := int32(binary.LittleEndian.Uint32(buf)) - tm := binary.LittleEndian.Uint32(buf[4:]) - ns := int(math.Trunc(float64(tm%300)/0.3+0.5)) * 1000000 - secs := int(tm / 300) - return time.Date(1900, 1, 1+int(days), - 0, 0, secs, ns, time.UTC) -} - -func readFixedType(ti *typeInfo, r *tdsBuffer) interface{} { - r.ReadFull(ti.Buffer) - buf := ti.Buffer - switch ti.TypeId { - case typeNull: - return nil - case typeInt1: - return int64(buf[0]) - case typeBit: - return buf[0] != 0 - case typeInt2: - return int64(int16(binary.LittleEndian.Uint16(buf))) - case typeInt4: - return int64(int32(binary.LittleEndian.Uint32(buf))) - case typeDateTim4: - return decodeDateTim4(buf) - case typeFlt4: - return math.Float32frombits(binary.LittleEndian.Uint32(buf)) - case typeMoney4: - return decodeMoney4(buf) - case typeMoney: - return decodeMoney(buf) - case typeDateTime: - return decodeDateTime(buf) - case typeFlt8: - return math.Float64frombits(binary.LittleEndian.Uint64(buf)) - case typeInt8: - return int64(binary.LittleEndian.Uint64(buf)) - default: - badStreamPanicf("Invalid typeid") - } - panic("shoulnd't get here") -} - -func readByteLenType(ti *typeInfo, r *tdsBuffer) interface{} { - size := r.byte() - if size == 0 { - return nil - } - r.ReadFull(ti.Buffer[:size]) - buf := ti.Buffer[:size] - switch ti.TypeId { - case typeDateN: - if len(buf) != 3 { - badStreamPanicf("Invalid size for DATENTYPE") - } - return decodeDate(buf) - case typeTimeN: - return decodeTime(ti.Scale, buf) - case typeDateTime2N: - return decodeDateTime2(ti.Scale, buf) - case typeDateTimeOffsetN: - return decodeDateTimeOffset(ti.Scale, buf) - case typeGuid: - return decodeGuid(buf) - case typeIntN: - switch len(buf) { - case 1: - return int64(buf[0]) - case 2: - return int64(int16((binary.LittleEndian.Uint16(buf)))) - case 4: - return int64(int32(binary.LittleEndian.Uint32(buf))) - case 8: - return int64(binary.LittleEndian.Uint64(buf)) - default: - badStreamPanicf("Invalid size for INTNTYPE: %d", len(buf)) - } - case typeDecimal, typeNumeric, typeDecimalN, typeNumericN: - return decodeDecimal(ti.Prec, ti.Scale, buf) - case typeBitN: - if len(buf) != 1 { - badStreamPanicf("Invalid size for BITNTYPE") - } - return buf[0] != 0 - case typeFltN: - switch len(buf) { - case 4: - return float64(math.Float32frombits(binary.LittleEndian.Uint32(buf))) - case 8: - return math.Float64frombits(binary.LittleEndian.Uint64(buf)) - default: - badStreamPanicf("Invalid size for FLTNTYPE") - } - case typeMoneyN: - switch len(buf) { - case 4: - return decodeMoney4(buf) - case 8: - return decodeMoney(buf) - default: - badStreamPanicf("Invalid size for MONEYNTYPE") - } - case typeDateTim4: - return decodeDateTim4(buf) - case typeDateTime: - return decodeDateTime(buf) - case typeDateTimeN: - switch len(buf) { - case 4: - return decodeDateTim4(buf) - case 8: - return decodeDateTime(buf) - default: - badStreamPanicf("Invalid size for DATETIMENTYPE") - } - case typeChar, typeVarChar: - return decodeChar(ti.Collation, buf) - case typeBinary, typeVarBinary: - // a copy, because the backing array for ti.Buffer is reused - // and can be overwritten by the next row while this row waits - // in a buffered chan - cpy := make([]byte, len(buf)) - copy(cpy, buf) - return cpy - default: - badStreamPanicf("Invalid typeid") - } - panic("shoulnd't get here") -} - -func writeByteLenType(w io.Writer, ti typeInfo, buf []byte) (err error) { - if ti.Size > 0xff { - panic("Invalid size for BYTELEN_TYPE") - } - err = binary.Write(w, binary.LittleEndian, uint8(len(buf))) - if err != nil { - return - } - _, err = w.Write(buf) - return -} - -func readShortLenType(ti *typeInfo, r *tdsBuffer) interface{} { - size := r.uint16() - if size == 0xffff { - return nil - } - r.ReadFull(ti.Buffer[:size]) - buf := ti.Buffer[:size] - switch ti.TypeId { - case typeBigVarChar, typeBigChar: - return decodeChar(ti.Collation, buf) - case typeBigVarBin, typeBigBinary: - // a copy, because the backing array for ti.Buffer is reused - // and can be overwritten by the next row while this row waits - // in a buffered chan - cpy := make([]byte, len(buf)) - copy(cpy, buf) - return cpy - case typeNVarChar, typeNChar: - return decodeNChar(buf) - case typeUdt: - return decodeUdt(*ti, buf) - default: - badStreamPanicf("Invalid typeid") - } - panic("shoulnd't get here") -} - -func writeShortLenType(w io.Writer, ti typeInfo, buf []byte) (err error) { - if buf == nil { - err = binary.Write(w, binary.LittleEndian, uint16(0xffff)) - return - } - if ti.Size > 0xfffe { - panic("Invalid size for USHORTLEN_TYPE") - } - err = binary.Write(w, binary.LittleEndian, uint16(ti.Size)) - if err != nil { - return - } - _, err = w.Write(buf) - return -} - -func readLongLenType(ti *typeInfo, r *tdsBuffer) interface{} { - // information about this format can be found here: - // http://msdn.microsoft.com/en-us/library/dd304783.aspx - // and here: - // http://msdn.microsoft.com/en-us/library/dd357254.aspx - textptrsize := int(r.byte()) - if textptrsize == 0 { - return nil - } - textptr := make([]byte, textptrsize) - r.ReadFull(textptr) - timestamp := r.uint64() - _ = timestamp // ignore timestamp - size := r.int32() - if size == -1 { - return nil - } - buf := make([]byte, size) - r.ReadFull(buf) - switch ti.TypeId { - case typeText: - return decodeChar(ti.Collation, buf) - case typeImage: - return buf - case typeNText: - return decodeNChar(buf) - default: - badStreamPanicf("Invalid typeid") - } - panic("shoulnd't get here") -} -func writeLongLenType(w io.Writer, ti typeInfo, buf []byte) (err error) { - //textptr - err = binary.Write(w, binary.LittleEndian, byte(0x10)) - if err != nil { - return - } - err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF)) - if err != nil { - return - } - err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF)) - if err != nil { - return - } - //timestamp? - err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF)) - if err != nil { - return - } - - err = binary.Write(w, binary.LittleEndian, uint32(ti.Size)) - if err != nil { - return - } - _, err = w.Write(buf) - return -} - -func readCollation(r *tdsBuffer) (res cp.Collation) { - res.LcidAndFlags = r.uint32() - res.SortId = r.byte() - return -} - -func writeCollation(w io.Writer, col cp.Collation) (err error) { - if err = binary.Write(w, binary.LittleEndian, col.LcidAndFlags); err != nil { - return - } - err = binary.Write(w, binary.LittleEndian, col.SortId) - return -} - -// reads variant value -// http://msdn.microsoft.com/en-us/library/dd303302.aspx -func readVariantType(ti *typeInfo, r *tdsBuffer) interface{} { - size := r.int32() - if size == 0 { - return nil - } - vartype := r.byte() - propbytes := int32(r.byte()) - switch vartype { - case typeGuid: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return buf - case typeBit: - return r.byte() != 0 - case typeInt1: - return int64(r.byte()) - case typeInt2: - return int64(int16(r.uint16())) - case typeInt4: - return int64(r.int32()) - case typeInt8: - return int64(r.uint64()) - case typeDateTime: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDateTime(buf) - case typeDateTim4: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDateTim4(buf) - case typeFlt4: - return float64(math.Float32frombits(r.uint32())) - case typeFlt8: - return math.Float64frombits(r.uint64()) - case typeMoney4: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeMoney4(buf) - case typeMoney: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeMoney(buf) - case typeDateN: - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDate(buf) - case typeTimeN: - scale := r.byte() - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeTime(scale, buf) - case typeDateTime2N: - scale := r.byte() - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDateTime2(scale, buf) - case typeDateTimeOffsetN: - scale := r.byte() - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDateTimeOffset(scale, buf) - case typeBigVarBin, typeBigBinary: - r.uint16() // max length, ignoring - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return buf - case typeDecimalN, typeNumericN: - prec := r.byte() - scale := r.byte() - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeDecimal(prec, scale, buf) - case typeBigVarChar, typeBigChar: - col := readCollation(r) - r.uint16() // max length, ignoring - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeChar(col, buf) - case typeNVarChar, typeNChar: - _ = readCollation(r) - r.uint16() // max length, ignoring - buf := make([]byte, size-2-propbytes) - r.ReadFull(buf) - return decodeNChar(buf) - default: - badStreamPanicf("Invalid variant typeid") - } - panic("shoulnd't get here") -} - -// partially length prefixed stream -// http://msdn.microsoft.com/en-us/library/dd340469.aspx -func readPLPType(ti *typeInfo, r *tdsBuffer) interface{} { - size := r.uint64() - var buf *bytes.Buffer - switch size { - case _PLP_NULL: - // null - return nil - case _UNKNOWN_PLP_LEN: - // size unknown - buf = bytes.NewBuffer(make([]byte, 0, 1000)) - default: - buf = bytes.NewBuffer(make([]byte, 0, size)) - } - for true { - chunksize := r.uint32() - if chunksize == 0 { - break - } - if _, err := io.CopyN(buf, r, int64(chunksize)); err != nil { - badStreamPanicf("Reading PLP type failed: %s", err.Error()) - } - } - switch ti.TypeId { - case typeXml: - return decodeXml(*ti, buf.Bytes()) - case typeBigVarChar, typeBigChar, typeText: - return decodeChar(ti.Collation, buf.Bytes()) - case typeBigVarBin, typeBigBinary, typeImage: - return buf.Bytes() - case typeNVarChar, typeNChar, typeNText: - return decodeNChar(buf.Bytes()) - case typeUdt: - return decodeUdt(*ti, buf.Bytes()) - } - panic("shoulnd't get here") -} - -func writePLPType(w io.Writer, ti typeInfo, buf []byte) (err error) { - if err = binary.Write(w, binary.LittleEndian, uint64(_UNKNOWN_PLP_LEN)); err != nil { - return - } - for { - chunksize := uint32(len(buf)) - if chunksize == 0 { - err = binary.Write(w, binary.LittleEndian, uint32(_PLP_TERMINATOR)) - return - } - if err = binary.Write(w, binary.LittleEndian, chunksize); err != nil { - return - } - if _, err = w.Write(buf[:chunksize]); err != nil { - return - } - buf = buf[chunksize:] - } -} - -func readVarLen(ti *typeInfo, r *tdsBuffer) { - switch ti.TypeId { - case typeDateN: - ti.Size = 3 - ti.Reader = readByteLenType - ti.Buffer = make([]byte, ti.Size) - case typeTimeN, typeDateTime2N, typeDateTimeOffsetN: - ti.Scale = r.byte() - switch ti.Scale { - case 0, 1, 2: - ti.Size = 3 - case 3, 4: - ti.Size = 4 - case 5, 6, 7: - ti.Size = 5 - default: - badStreamPanicf("Invalid scale for TIME/DATETIME2/DATETIMEOFFSET type") - } - switch ti.TypeId { - case typeDateTime2N: - ti.Size += 3 - case typeDateTimeOffsetN: - ti.Size += 5 - } - ti.Reader = readByteLenType - ti.Buffer = make([]byte, ti.Size) - case typeGuid, typeIntN, typeDecimal, typeNumeric, - typeBitN, typeDecimalN, typeNumericN, typeFltN, - typeMoneyN, typeDateTimeN, typeChar, - typeVarChar, typeBinary, typeVarBinary: - // byle len types - ti.Size = int(r.byte()) - ti.Buffer = make([]byte, ti.Size) - switch ti.TypeId { - case typeDecimal, typeNumeric, typeDecimalN, typeNumericN: - ti.Prec = r.byte() - ti.Scale = r.byte() - } - ti.Reader = readByteLenType - case typeXml: - ti.XmlInfo.SchemaPresent = r.byte() - if ti.XmlInfo.SchemaPresent != 0 { - // dbname - ti.XmlInfo.DBName = r.BVarChar() - // owning schema - ti.XmlInfo.OwningSchema = r.BVarChar() - // xml schema collection - ti.XmlInfo.XmlSchemaCollection = r.UsVarChar() - } - ti.Reader = readPLPType - case typeUdt: - ti.Size = int(r.uint16()) - ti.UdtInfo.DBName = r.BVarChar() - ti.UdtInfo.SchemaName = r.BVarChar() - ti.UdtInfo.TypeName = r.BVarChar() - ti.UdtInfo.AssemblyQualifiedName = r.UsVarChar() - - ti.Buffer = make([]byte, ti.Size) - ti.Reader = readPLPType - case typeBigVarBin, typeBigVarChar, typeBigBinary, typeBigChar, - typeNVarChar, typeNChar: - // short len types - ti.Size = int(r.uint16()) - switch ti.TypeId { - case typeBigVarChar, typeBigChar, typeNVarChar, typeNChar: - ti.Collation = readCollation(r) - } - if ti.Size == 0xffff { - ti.Reader = readPLPType - } else { - ti.Buffer = make([]byte, ti.Size) - ti.Reader = readShortLenType - } - case typeText, typeImage, typeNText, typeVariant: - // LONGLEN_TYPE - ti.Size = int(r.int32()) - switch ti.TypeId { - case typeText, typeNText: - ti.Collation = readCollation(r) - // ignore tablenames - numparts := int(r.byte()) - for i := 0; i < numparts; i++ { - r.UsVarChar() - } - ti.Reader = readLongLenType - case typeImage: - // ignore tablenames - numparts := int(r.byte()) - for i := 0; i < numparts; i++ { - r.UsVarChar() - } - ti.Reader = readLongLenType - case typeVariant: - ti.Reader = readVariantType - } - default: - badStreamPanicf("Invalid type %d", ti.TypeId) - } - return -} - -func decodeMoney(buf []byte) []byte { - money := int64(uint64(buf[4]) | - uint64(buf[5])<<8 | - uint64(buf[6])<<16 | - uint64(buf[7])<<24 | - uint64(buf[0])<<32 | - uint64(buf[1])<<40 | - uint64(buf[2])<<48 | - uint64(buf[3])<<56) - return scaleBytes(strconv.FormatInt(money, 10), 4) -} - -func decodeMoney4(buf []byte) []byte { - money := int32(binary.LittleEndian.Uint32(buf[0:4])) - return scaleBytes(strconv.FormatInt(int64(money), 10), 4) -} - -func decodeGuid(buf []byte) []byte { - res := make([]byte, 16) - copy(res, buf) - return res -} - -func decodeDecimal(prec uint8, scale uint8, buf []byte) []byte { - var sign uint8 - sign = buf[0] - dec := Decimal{ - positive: sign != 0, - prec: prec, - scale: scale, - } - buf = buf[1:] - l := len(buf) / 4 - for i := 0; i < l; i++ { - dec.integer[i] = binary.LittleEndian.Uint32(buf[0:4]) - buf = buf[4:] - } - return dec.Bytes() -} - -// http://msdn.microsoft.com/en-us/library/ee780895.aspx -func decodeDateInt(buf []byte) (days int) { - days = int(buf[0]) + int(buf[1])*256 + int(buf[2])*256*256 - return -} - -func decodeDate(buf []byte) time.Time { - return time.Date(1, 1, 1+decodeDateInt(buf), 0, 0, 0, 0, time.UTC) -} - -func encodeDate(val time.Time) (buf []byte) { - days, _, _ := dateTime2(val) - buf = make([]byte, 3) - buf[0] = byte(days) - buf[1] = byte(days >> 8) - buf[2] = byte(days >> 16) - return -} - -func decodeTimeInt(scale uint8, buf []byte) (sec int, ns int) { - var acc uint64 = 0 - for i := len(buf) - 1; i >= 0; i-- { - acc <<= 8 - acc |= uint64(buf[i]) - } - for i := 0; i < 7-int(scale); i++ { - acc *= 10 - } - nsbig := acc * 100 - sec = int(nsbig / 1000000000) - ns = int(nsbig % 1000000000) - return -} - -// calculate size of time field in bytes -func calcTimeSize(scale int) int { - if scale <= 2 { - return 3 - } else if scale <= 4 { - return 4 - } else { - return 5 - } -} - -// writes time value into a field buffer -// buffer should be at least calcTimeSize long -func encodeTimeInt(seconds, ns, scale int, buf []byte) { - ns_total := int64(seconds)*1000*1000*1000 + int64(ns) - t := ns_total / int64(math.Pow10(int(scale)*-1)*1e9) - buf[0] = byte(t) - buf[1] = byte(t >> 8) - buf[2] = byte(t >> 16) - buf[3] = byte(t >> 24) - buf[4] = byte(t >> 32) -} - -func decodeTime(scale uint8, buf []byte) time.Time { - sec, ns := decodeTimeInt(scale, buf) - return time.Date(1, 1, 1, 0, 0, sec, ns, time.UTC) -} - -func encodeTime(hour, minute, second, ns, scale int) (buf []byte) { - seconds := hour*3600 + minute*60 + second - buf = make([]byte, calcTimeSize(scale)) - encodeTimeInt(seconds, ns, scale, buf) - return -} - -func decodeDateTime2(scale uint8, buf []byte) time.Time { - timesize := len(buf) - 3 - sec, ns := decodeTimeInt(scale, buf[:timesize]) - days := decodeDateInt(buf[timesize:]) - return time.Date(1, 1, 1+days, 0, 0, sec, ns, time.UTC) -} - -func encodeDateTime2(val time.Time, scale int) (buf []byte) { - days, seconds, ns := dateTime2(val) - timesize := calcTimeSize(scale) - buf = make([]byte, 3+timesize) - encodeTimeInt(seconds, ns, scale, buf) - buf[timesize] = byte(days) - buf[timesize+1] = byte(days >> 8) - buf[timesize+2] = byte(days >> 16) - return -} - -func decodeDateTimeOffset(scale uint8, buf []byte) time.Time { - timesize := len(buf) - 3 - 2 - sec, ns := decodeTimeInt(scale, buf[:timesize]) - buf = buf[timesize:] - days := decodeDateInt(buf[:3]) - buf = buf[3:] - offset := int(int16(binary.LittleEndian.Uint16(buf))) // in mins - return time.Date(1, 1, 1+days, 0, 0, sec+offset*60, ns, - time.FixedZone("", offset*60)) -} - -func encodeDateTimeOffset(val time.Time, scale int) (buf []byte) { - timesize := calcTimeSize(scale) - buf = make([]byte, timesize+2+3) - days, seconds, ns := dateTime2(val.In(time.UTC)) - encodeTimeInt(seconds, ns, scale, buf) - buf[timesize] = byte(days) - buf[timesize+1] = byte(days >> 8) - buf[timesize+2] = byte(days >> 16) - _, offset := val.Zone() - offset /= 60 - buf[timesize+3] = byte(offset) - buf[timesize+4] = byte(offset >> 8) - return -} - -// returns days since Jan 1st 0001 in Gregorian calendar -func gregorianDays(year, yearday int) int { - year0 := year - 1 - return year0*365 + year0/4 - year0/100 + year0/400 + yearday - 1 -} - -func dateTime2(t time.Time) (days int, seconds int, ns int) { - // days since Jan 1 1 (in same TZ as t) - days = gregorianDays(t.Year(), t.YearDay()) - seconds = t.Second() + t.Minute()*60 + t.Hour()*60*60 - ns = t.Nanosecond() - if days < 0 { - days = 0 - seconds = 0 - ns = 0 - } - max := gregorianDays(9999, 365) - if days > max { - days = max - seconds = 59 + 59*60 + 23*60*60 - ns = 999999900 - } - return -} - -func decodeChar(col cp.Collation, buf []byte) string { - return cp.CharsetToUTF8(col, buf) -} - -func decodeUcs2(buf []byte) string { - res, err := ucs22str(buf) - if err != nil { - badStreamPanicf("Invalid UCS2 encoding: %s", err.Error()) - } - return res -} - -func decodeNChar(buf []byte) string { - return decodeUcs2(buf) -} - -func decodeXml(ti typeInfo, buf []byte) string { - return decodeUcs2(buf) -} - -func decodeUdt(ti typeInfo, buf []byte) []byte { - return buf -} - -// makes go/sql type instance as described below -// It should return -// the value type that can be used to scan types into. For example, the database -// column type "bigint" this should return "reflect.TypeOf(int64(0))". -func makeGoLangScanType(ti typeInfo) reflect.Type { - switch ti.TypeId { - case typeInt1: - return reflect.TypeOf(int64(0)) - case typeInt2: - return reflect.TypeOf(int64(0)) - case typeInt4: - return reflect.TypeOf(int64(0)) - case typeInt8: - return reflect.TypeOf(int64(0)) - case typeFlt4: - return reflect.TypeOf(float64(0)) - case typeIntN: - switch ti.Size { - case 1: - return reflect.TypeOf(int64(0)) - case 2: - return reflect.TypeOf(int64(0)) - case 4: - return reflect.TypeOf(int64(0)) - case 8: - return reflect.TypeOf(int64(0)) - default: - panic("invalid size of INTNTYPE") - } - case typeFlt8: - return reflect.TypeOf(float64(0)) - case typeFltN: - switch ti.Size { - case 4: - return reflect.TypeOf(float64(0)) - case 8: - return reflect.TypeOf(float64(0)) - default: - panic("invalid size of FLNNTYPE") - } - case typeBigVarBin: - return reflect.TypeOf([]byte{}) - case typeVarChar: - return reflect.TypeOf("") - case typeNVarChar: - return reflect.TypeOf("") - case typeBit, typeBitN: - return reflect.TypeOf(true) - case typeDecimalN, typeNumericN: - return reflect.TypeOf([]byte{}) - case typeMoney, typeMoney4, typeMoneyN: - switch ti.Size { - case 4: - return reflect.TypeOf([]byte{}) - case 8: - return reflect.TypeOf([]byte{}) - default: - panic("invalid size of MONEYN") - } - case typeDateTim4: - return reflect.TypeOf(time.Time{}) - case typeDateTime: - return reflect.TypeOf(time.Time{}) - case typeDateTimeN: - switch ti.Size { - case 4: - return reflect.TypeOf(time.Time{}) - case 8: - return reflect.TypeOf(time.Time{}) - default: - panic("invalid size of DATETIMEN") - } - case typeDateTime2N: - return reflect.TypeOf(time.Time{}) - case typeDateN: - return reflect.TypeOf(time.Time{}) - case typeTimeN: - return reflect.TypeOf(time.Time{}) - case typeDateTimeOffsetN: - return reflect.TypeOf(time.Time{}) - case typeBigVarChar: - return reflect.TypeOf("") - case typeBigChar: - return reflect.TypeOf("") - case typeNChar: - return reflect.TypeOf("") - case typeGuid: - return reflect.TypeOf([]byte{}) - case typeXml: - return reflect.TypeOf("") - case typeText: - return reflect.TypeOf("") - case typeNText: - return reflect.TypeOf("") - case typeImage: - return reflect.TypeOf([]byte{}) - case typeBigBinary: - return reflect.TypeOf([]byte{}) - case typeVariant: - return reflect.TypeOf(nil) - default: - panic(fmt.Sprintf("not implemented makeGoLangScanType for type %d", ti.TypeId)) - } -} - -func makeDecl(ti typeInfo) string { - switch ti.TypeId { - case typeNull: - // maybe we should use something else here - // this is tested in TestNull - return "nvarchar(1)" - case typeInt1: - return "tinyint" - case typeBigBinary: - return fmt.Sprintf("binary(%d)", ti.Size) - case typeInt2: - return "smallint" - case typeInt4: - return "int" - case typeInt8: - return "bigint" - case typeFlt4: - return "real" - case typeIntN: - switch ti.Size { - case 1: - return "tinyint" - case 2: - return "smallint" - case 4: - return "int" - case 8: - return "bigint" - default: - panic("invalid size of INTNTYPE") - } - case typeFlt8: - return "float" - case typeFltN: - switch ti.Size { - case 4: - return "real" - case 8: - return "float" - default: - panic("invalid size of FLNNTYPE") - } - case typeDecimal, typeDecimalN: - return fmt.Sprintf("decimal(%d, %d)", ti.Prec, ti.Scale) - case typeNumeric, typeNumericN: - return fmt.Sprintf("numeric(%d, %d)", ti.Prec, ti.Scale) - case typeMoney4: - return "smallmoney" - case typeMoney: - return "money" - case typeMoneyN: - switch ti.Size { - case 4: - return "smallmoney" - case 8: - return "money" - default: - panic("invalid size of MONEYNTYPE") - } - case typeBigVarBin: - if ti.Size > 8000 || ti.Size == 0 { - return "varbinary(max)" - } else { - return fmt.Sprintf("varbinary(%d)", ti.Size) - } - case typeNChar: - return fmt.Sprintf("nchar(%d)", ti.Size/2) - case typeBigChar, typeChar: - return fmt.Sprintf("char(%d)", ti.Size) - case typeBigVarChar, typeVarChar: - if ti.Size > 4000 || ti.Size == 0 { - return fmt.Sprintf("varchar(max)") - } else { - return fmt.Sprintf("varchar(%d)", ti.Size) - } - case typeNVarChar: - if ti.Size > 8000 || ti.Size == 0 { - return "nvarchar(max)" - } else { - return fmt.Sprintf("nvarchar(%d)", ti.Size/2) - } - case typeBit, typeBitN: - return "bit" - case typeDateN: - return "date" - case typeDateTim4: - return "smalldatetime" - case typeDateTime: - return "datetime" - case typeDateTimeN: - switch ti.Size { - case 4: - return "smalldatetime" - case 8: - return "datetime" - default: - panic("invalid size of DATETIMNTYPE") - } - case typeTimeN: - return "time" - case typeDateTime2N: - return fmt.Sprintf("datetime2(%d)", ti.Scale) - case typeDateTimeOffsetN: - return fmt.Sprintf("datetimeoffset(%d)", ti.Scale) - case typeText: - return "text" - case typeNText: - return "ntext" - case typeUdt: - return ti.UdtInfo.TypeName - case typeGuid: - return "uniqueidentifier" - default: - panic(fmt.Sprintf("not implemented makeDecl for type %#x", ti.TypeId)) - } -} - -// makes go/sql type name as described below -// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the -// database system type name without the length. Type names should be uppercase. -// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", -// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", -// "TIMESTAMP". -func makeGoLangTypeName(ti typeInfo) string { - switch ti.TypeId { - case typeInt1: - return "TINYINT" - case typeInt2: - return "SMALLINT" - case typeInt4: - return "INT" - case typeInt8: - return "BIGINT" - case typeFlt4: - return "REAL" - case typeIntN: - switch ti.Size { - case 1: - return "TINYINT" - case 2: - return "SMALLINT" - case 4: - return "INT" - case 8: - return "BIGINT" - default: - panic("invalid size of INTNTYPE") - } - case typeFlt8: - return "FLOAT" - case typeFltN: - switch ti.Size { - case 4: - return "REAL" - case 8: - return "FLOAT" - default: - panic("invalid size of FLNNTYPE") - } - case typeBigVarBin: - return "VARBINARY" - case typeVarChar: - return "VARCHAR" - case typeNVarChar: - return "NVARCHAR" - case typeBit, typeBitN: - return "BIT" - case typeDecimalN, typeNumericN: - return "DECIMAL" - case typeMoney, typeMoney4, typeMoneyN: - switch ti.Size { - case 4: - return "SMALLMONEY" - case 8: - return "MONEY" - default: - panic("invalid size of MONEYN") - } - case typeDateTim4: - return "SMALLDATETIME" - case typeDateTime: - return "DATETIME" - case typeDateTimeN: - switch ti.Size { - case 4: - return "SMALLDATETIME" - case 8: - return "DATETIME" - default: - panic("invalid size of DATETIMEN") - } - case typeDateTime2N: - return "DATETIME2" - case typeDateN: - return "DATE" - case typeTimeN: - return "TIME" - case typeDateTimeOffsetN: - return "DATETIMEOFFSET" - case typeBigVarChar: - return "VARCHAR" - case typeBigChar: - return "CHAR" - case typeNChar: - return "NCHAR" - case typeGuid: - return "UNIQUEIDENTIFIER" - case typeXml: - return "XML" - case typeText: - return "TEXT" - case typeNText: - return "NTEXT" - case typeImage: - return "IMAGE" - case typeVariant: - return "SQL_VARIANT" - case typeBigBinary: - return "BINARY" - default: - panic(fmt.Sprintf("not implemented makeGoLangTypeName for type %d", ti.TypeId)) - } -} - -// makes go/sql type length as described below -// It should return the length -// of the column type if the column is a variable length type. If the column is -// not a variable length type ok should return false. -// If length is not limited other than system limits, it should return math.MaxInt64. -// The following are examples of returned values for various types: -// TEXT (math.MaxInt64, true) -// varchar(10) (10, true) -// nvarchar(10) (10, true) -// decimal (0, false) -// int (0, false) -// bytea(30) (30, true) -func makeGoLangTypeLength(ti typeInfo) (int64, bool) { - switch ti.TypeId { - case typeInt1: - return 0, false - case typeInt2: - return 0, false - case typeInt4: - return 0, false - case typeInt8: - return 0, false - case typeFlt4: - return 0, false - case typeIntN: - switch ti.Size { - case 1: - return 0, false - case 2: - return 0, false - case 4: - return 0, false - case 8: - return 0, false - default: - panic("invalid size of INTNTYPE") - } - case typeFlt8: - return 0, false - case typeFltN: - switch ti.Size { - case 4: - return 0, false - case 8: - return 0, false - default: - panic("invalid size of FLNNTYPE") - } - case typeBit, typeBitN: - return 0, false - case typeDecimalN, typeNumericN: - return 0, false - case typeMoney, typeMoney4, typeMoneyN: - switch ti.Size { - case 4: - return 0, false - case 8: - return 0, false - default: - panic("invalid size of MONEYN") - } - case typeDateTim4, typeDateTime: - return 0, false - case typeDateTimeN: - switch ti.Size { - case 4: - return 0, false - case 8: - return 0, false - default: - panic("invalid size of DATETIMEN") - } - case typeDateTime2N: - return 0, false - case typeDateN: - return 0, false - case typeTimeN: - return 0, false - case typeDateTimeOffsetN: - return 0, false - case typeBigVarBin: - if ti.Size == 0xffff { - return 2147483645, true - } else { - return int64(ti.Size), true - } - case typeVarChar: - return int64(ti.Size), true - case typeBigVarChar: - if ti.Size == 0xffff { - return 2147483645, true - } else { - return int64(ti.Size), true - } - case typeBigChar: - return int64(ti.Size), true - case typeNVarChar: - if ti.Size == 0xffff { - return 2147483645 / 2, true - } else { - return int64(ti.Size) / 2, true - } - case typeNChar: - return int64(ti.Size) / 2, true - case typeGuid: - return 0, false - case typeXml: - return 1073741822, true - case typeText: - return 2147483647, true - case typeNText: - return 1073741823, true - case typeImage: - return 2147483647, true - case typeVariant: - return 0, false - case typeBigBinary: - return 0, false - default: - panic(fmt.Sprintf("not implemented makeGoLangTypeLength for type %d", ti.TypeId)) - } -} - -// makes go/sql type precision and scale as described below -// It should return the length -// of the column type if the column is a variable length type. If the column is -// not a variable length type ok should return false. -// If length is not limited other than system limits, it should return math.MaxInt64. -// The following are examples of returned values for various types: -// TEXT (math.MaxInt64, true) -// varchar(10) (10, true) -// nvarchar(10) (10, true) -// decimal (0, false) -// int (0, false) -// bytea(30) (30, true) -func makeGoLangTypePrecisionScale(ti typeInfo) (int64, int64, bool) { - switch ti.TypeId { - case typeInt1: - return 0, 0, false - case typeInt2: - return 0, 0, false - case typeInt4: - return 0, 0, false - case typeInt8: - return 0, 0, false - case typeFlt4: - return 0, 0, false - case typeIntN: - switch ti.Size { - case 1: - return 0, 0, false - case 2: - return 0, 0, false - case 4: - return 0, 0, false - case 8: - return 0, 0, false - default: - panic("invalid size of INTNTYPE") - } - case typeFlt8: - return 0, 0, false - case typeFltN: - switch ti.Size { - case 4: - return 0, 0, false - case 8: - return 0, 0, false - default: - panic("invalid size of FLNNTYPE") - } - case typeBit, typeBitN: - return 0, 0, false - case typeDecimalN, typeNumericN: - return int64(ti.Prec), int64(ti.Scale), true - case typeMoney, typeMoney4, typeMoneyN: - switch ti.Size { - case 4: - return 0, 0, false - case 8: - return 0, 0, false - default: - panic("invalid size of MONEYN") - } - case typeDateTim4, typeDateTime: - return 0, 0, false - case typeDateTimeN: - switch ti.Size { - case 4: - return 0, 0, false - case 8: - return 0, 0, false - default: - panic("invalid size of DATETIMEN") - } - case typeDateTime2N: - return 0, 0, false - case typeDateN: - return 0, 0, false - case typeTimeN: - return 0, 0, false - case typeDateTimeOffsetN: - return 0, 0, false - case typeBigVarBin: - return 0, 0, false - case typeVarChar: - return 0, 0, false - case typeBigVarChar: - return 0, 0, false - case typeBigChar: - return 0, 0, false - case typeNVarChar: - return 0, 0, false - case typeNChar: - return 0, 0, false - case typeGuid: - return 0, 0, false - case typeXml: - return 0, 0, false - case typeText: - return 0, 0, false - case typeNText: - return 0, 0, false - case typeImage: - return 0, 0, false - case typeVariant: - return 0, 0, false - case typeBigBinary: - return 0, 0, false - default: - panic(fmt.Sprintf("not implemented makeGoLangTypePrecisionScale for type %d", ti.TypeId)) - } -} diff --git a/vendor/github.com/denisenkom/go-mssqldb/uniqueidentifier.go b/vendor/github.com/denisenkom/go-mssqldb/uniqueidentifier.go deleted file mode 100644 index c8ef3149b..000000000 --- a/vendor/github.com/denisenkom/go-mssqldb/uniqueidentifier.go +++ /dev/null @@ -1,74 +0,0 @@ -package mssql - -import ( - "database/sql/driver" - "encoding/hex" - "errors" - "fmt" -) - -type UniqueIdentifier [16]byte - -func (u *UniqueIdentifier) Scan(v interface{}) error { - reverse := func(b []byte) { - for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { - b[i], b[j] = b[j], b[i] - } - } - - switch vt := v.(type) { - case []byte: - if len(vt) != 16 { - return errors.New("mssql: invalid UniqueIdentifier length") - } - - var raw UniqueIdentifier - - copy(raw[:], vt) - - reverse(raw[0:4]) - reverse(raw[4:6]) - reverse(raw[6:8]) - *u = raw - - return nil - case string: - if len(vt) != 36 { - return errors.New("mssql: invalid UniqueIdentifier string length") - } - - b := []byte(vt) - for i, c := range b { - switch c { - case '-': - b = append(b[:i], b[i+1:]...) - } - } - - _, err := hex.Decode(u[:], []byte(b)) - return err - default: - return fmt.Errorf("mssql: cannot convert %T to UniqueIdentifier", v) - } -} - -func (u UniqueIdentifier) Value() (driver.Value, error) { - reverse := func(b []byte) { - for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { - b[i], b[j] = b[j], b[i] - } - } - - raw := make([]byte, len(u)) - copy(raw, u[:]) - - reverse(raw[0:4]) - reverse(raw[4:6]) - reverse(raw[6:8]) - - return raw, nil -} - -func (u UniqueIdentifier) String() string { - return fmt.Sprintf("%X-%X-%X-%X-%X", u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) -} diff --git a/vendor/github.com/fatih/color/.travis.yml b/vendor/github.com/fatih/color/.travis.yml new file mode 100644 index 000000000..95f8a1ff5 --- /dev/null +++ b/vendor/github.com/fatih/color/.travis.yml @@ -0,0 +1,5 @@ +language: go +go: + - 1.8.x + - tip + diff --git a/vendor/github.com/fatih/structs/LICENSE b/vendor/github.com/fatih/structs/LICENSE deleted file mode 100644 index 34504e4b3..000000000 --- a/vendor/github.com/fatih/structs/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Fatih Arslan - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/fatih/structs/README.md b/vendor/github.com/fatih/structs/README.md deleted file mode 100644 index 44e01006e..000000000 --- a/vendor/github.com/fatih/structs/README.md +++ /dev/null @@ -1,163 +0,0 @@ -# Structs [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/structs) [![Build Status](http://img.shields.io/travis/fatih/structs.svg?style=flat-square)](https://travis-ci.org/fatih/structs) [![Coverage Status](http://img.shields.io/coveralls/fatih/structs.svg?style=flat-square)](https://coveralls.io/r/fatih/structs) - -Structs contains various utilities to work with Go (Golang) structs. It was -initially used by me to convert a struct into a `map[string]interface{}`. With -time I've added other utilities for structs. It's basically a high level -package based on primitives from the reflect package. Feel free to add new -functions or improve the existing code. - -## Install - -```bash -go get github.com/fatih/structs -``` - -## Usage and Examples - -Just like the standard lib `strings`, `bytes` and co packages, `structs` has -many global functions to manipulate or organize your struct data. Lets define -and declare a struct: - -```go -type Server struct { - Name string `json:"name,omitempty"` - ID int - Enabled bool - users []string // not exported - http.Server // embedded -} - -server := &Server{ - Name: "gopher", - ID: 123456, - Enabled: true, -} -``` - -```go -// Convert a struct to a map[string]interface{} -// => {"Name":"gopher", "ID":123456, "Enabled":true} -m := structs.Map(server) - -// Convert the values of a struct to a []interface{} -// => ["gopher", 123456, true] -v := structs.Values(server) - -// Convert the names of a struct to a []string -// (see "Names methods" for more info about fields) -n := structs.Names(server) - -// Convert the values of a struct to a []*Field -// (see "Field methods" for more info about fields) -f := structs.Fields(server) - -// Return the struct name => "Server" -n := structs.Name(server) - -// Check if any field of a struct is initialized or not. -h := structs.HasZero(server) - -// Check if all fields of a struct is initialized or not. -z := structs.IsZero(server) - -// Check if server is a struct or a pointer to struct -i := structs.IsStruct(server) -``` - -### Struct methods - -The structs functions can be also used as independent methods by creating a new -`*structs.Struct`. This is handy if you want to have more control over the -structs (such as retrieving a single Field). - -```go -// Create a new struct type: -s := structs.New(server) - -m := s.Map() // Get a map[string]interface{} -v := s.Values() // Get a []interface{} -f := s.Fields() // Get a []*Field -n := s.Names() // Get a []string -f := s.Field(name) // Get a *Field based on the given field name -f, ok := s.FieldOk(name) // Get a *Field based on the given field name -n := s.Name() // Get the struct name -h := s.HasZero() // Check if any field is initialized -z := s.IsZero() // Check if all fields are initialized -``` - -### Field methods - -We can easily examine a single Field for more detail. Below you can see how we -get and interact with various field methods: - - -```go -s := structs.New(server) - -// Get the Field struct for the "Name" field -name := s.Field("Name") - -// Get the underlying value, value => "gopher" -value := name.Value().(string) - -// Set the field's value -name.Set("another gopher") - -// Get the field's kind, kind => "string" -name.Kind() - -// Check if the field is exported or not -if name.IsExported() { - fmt.Println("Name field is exported") -} - -// Check if the value is a zero value, such as "" for string, 0 for int -if !name.IsZero() { - fmt.Println("Name is initialized") -} - -// Check if the field is an anonymous (embedded) field -if !name.IsEmbedded() { - fmt.Println("Name is not an embedded field") -} - -// Get the Field's tag value for tag name "json", tag value => "name,omitempty" -tagValue := name.Tag("json") -``` - -Nested structs are supported too: - -```go -addrField := s.Field("Server").Field("Addr") - -// Get the value for addr -a := addrField.Value().(string) - -// Or get all fields -httpServer := s.Field("Server").Fields() -``` - -We can also get a slice of Fields from the Struct type to iterate over all -fields. This is handy if you wish to examine all fields: - -```go -s := structs.New(server) - -for _, f := range s.Fields() { - fmt.Printf("field name: %+v\n", f.Name()) - - if f.IsExported() { - fmt.Printf("value : %+v\n", f.Value()) - fmt.Printf("is zero : %+v\n", f.IsZero()) - } -} -``` - -## Credits - - * [Fatih Arslan](https://github.com/fatih) - * [Cihangir Savas](https://github.com/cihangir) - -## License - -The MIT License (MIT) - see LICENSE.md for more details diff --git a/vendor/github.com/fatih/structs/field.go b/vendor/github.com/fatih/structs/field.go deleted file mode 100644 index e69783230..000000000 --- a/vendor/github.com/fatih/structs/field.go +++ /dev/null @@ -1,141 +0,0 @@ -package structs - -import ( - "errors" - "fmt" - "reflect" -) - -var ( - errNotExported = errors.New("field is not exported") - errNotSettable = errors.New("field is not settable") -) - -// Field represents a single struct field that encapsulates high level -// functions around the field. -type Field struct { - value reflect.Value - field reflect.StructField - defaultTag string -} - -// Tag returns the value associated with key in the tag string. If there is no -// such key in the tag, Tag returns the empty string. -func (f *Field) Tag(key string) string { - return f.field.Tag.Get(key) -} - -// Value returns the underlying value of the field. It panics if the field -// is not exported. -func (f *Field) Value() interface{} { - return f.value.Interface() -} - -// IsEmbedded returns true if the given field is an anonymous field (embedded) -func (f *Field) IsEmbedded() bool { - return f.field.Anonymous -} - -// IsExported returns true if the given field is exported. -func (f *Field) IsExported() bool { - return f.field.PkgPath == "" -} - -// IsZero returns true if the given field is not initialized (has a zero value). -// It panics if the field is not exported. -func (f *Field) IsZero() bool { - zero := reflect.Zero(f.value.Type()).Interface() - current := f.Value() - - return reflect.DeepEqual(current, zero) -} - -// Name returns the name of the given field -func (f *Field) Name() string { - return f.field.Name -} - -// Kind returns the fields kind, such as "string", "map", "bool", etc .. -func (f *Field) Kind() reflect.Kind { - return f.value.Kind() -} - -// Set sets the field to given value v. It returns an error if the field is not -// settable (not addressable or not exported) or if the given value's type -// doesn't match the fields type. -func (f *Field) Set(val interface{}) error { - // we can't set unexported fields, so be sure this field is exported - if !f.IsExported() { - return errNotExported - } - - // do we get here? not sure... - if !f.value.CanSet() { - return errNotSettable - } - - given := reflect.ValueOf(val) - - if f.value.Kind() != given.Kind() { - return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind()) - } - - f.value.Set(given) - return nil -} - -// Zero sets the field to its zero value. It returns an error if the field is not -// settable (not addressable or not exported). -func (f *Field) Zero() error { - zero := reflect.Zero(f.value.Type()).Interface() - return f.Set(zero) -} - -// Fields returns a slice of Fields. This is particular handy to get the fields -// of a nested struct . A struct tag with the content of "-" ignores the -// checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field *http.Request `structs:"-"` -// -// It panics if field is not exported or if field's kind is not struct -func (f *Field) Fields() []*Field { - return getFields(f.value, f.defaultTag) -} - -// Field returns the field from a nested struct. It panics if the nested struct -// is not exported or if the field was not found. -func (f *Field) Field(name string) *Field { - field, ok := f.FieldOk(name) - if !ok { - panic("field not found") - } - - return field -} - -// FieldOk returns the field from a nested struct. The boolean returns whether -// the field was found (true) or not (false). -func (f *Field) FieldOk(name string) (*Field, bool) { - value := &f.value - // value must be settable so we need to make sure it holds the address of the - // variable and not a copy, so we can pass the pointer to strctVal instead of a - // copy (which is not assigned to any variable, hence not settable). - // see "https://blog.golang.org/laws-of-reflection#TOC_8." - if f.value.Kind() != reflect.Ptr { - a := f.value.Addr() - value = &a - } - v := strctVal(value.Interface()) - t := v.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: v.FieldByName(name), - }, true -} diff --git a/vendor/github.com/fatih/structs/structs.go b/vendor/github.com/fatih/structs/structs.go deleted file mode 100644 index be3816abc..000000000 --- a/vendor/github.com/fatih/structs/structs.go +++ /dev/null @@ -1,586 +0,0 @@ -// Package structs contains various utilities functions to work with structs. -package structs - -import ( - "fmt" - - "reflect" -) - -var ( - // DefaultTagName is the default tag name for struct fields which provides - // a more granular to tweak certain structs. Lookup the necessary functions - // for more info. - DefaultTagName = "structs" // struct's field default tag name -) - -// Struct encapsulates a struct type to provide several high level functions -// around the struct. -type Struct struct { - raw interface{} - value reflect.Value - TagName string -} - -// New returns a new *Struct with the struct s. It panics if the s's kind is -// not struct. -func New(s interface{}) *Struct { - return &Struct{ - raw: s, - value: strctVal(s), - TagName: DefaultTagName, - } -} - -// Map converts the given struct to a map[string]interface{}, where the keys -// of the map are the field names and the values of the map the associated -// values of the fields. The default key string is the struct field name but -// can be changed in the struct field's tag value. The "structs" key in the -// struct's field tag value is the key name. Example: -// -// // Field appears in map as key "myName". -// Name string `structs:"myName"` -// -// A tag value with the content of "-" ignores that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A tag value with the content of "string" uses the stringer to get the value. Example: -// -// // The value will be output of Animal's String() func. -// // Map will panic if Animal does not implement String(). -// Field *Animal `structs:"field,string"` -// -// A tag value with the option of "flatten" used in a struct field is to flatten its fields -// in the output map. Example: -// -// // The FieldStruct's fields will be flattened into the output map. -// FieldStruct time.Time `structs:",flatten"` -// -// A tag value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field if -// the field value is empty. Example: -// -// // Field appears in map as key "myName", but the field is -// // skipped if empty. -// Field string `structs:"myName,omitempty"` -// -// // Field appears in map as key "Field" (the default), but -// // the field is skipped if empty. -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Map() map[string]interface{} { - out := make(map[string]interface{}) - s.FillMap(out) - return out -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func (s *Struct) FillMap(out map[string]interface{}) { - if out == nil { - return - } - - fields := s.structFields() - - for _, field := range fields { - name := field.Name - val := s.value.FieldByName(name) - isSubStruct := false - var finalVal interface{} - - tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) - if tagName != "" { - name = tagName - } - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if !tagOpts.Has("omitnested") { - finalVal = s.nested(val) - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Map, reflect.Struct: - isSubStruct = true - } - } else { - finalVal = val.Interface() - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - out[name] = s.String() - } - continue - } - - if isSubStruct && (tagOpts.Has("flatten")) { - for k := range finalVal.(map[string]interface{}) { - out[k] = finalVal.(map[string]interface{})[k] - } - } else { - out[name] = finalVal - } - } -} - -// Values converts the given s struct's field values to a []interface{}. A -// struct tag with the content of "-" ignores the that particular field. -// Example: -// -// // Field is ignored by this package. -// Field int `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Fields is not processed further by this package. -// Field time.Time `structs:",omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field and -// is not added to the values if the field value is empty. Example: -// -// // Field is skipped if empty -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Values() []interface{} { - fields := s.structFields() - - var t []interface{} - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - t = append(t, s.String()) - } - continue - } - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - // look out for embedded structs, and convert them to a - // []interface{} to be added to the final values slice - for _, embeddedVal := range Values(val.Interface()) { - t = append(t, embeddedVal) - } - } else { - t = append(t, val.Interface()) - } - } - - return t -} - -// Fields returns a slice of Fields. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Fields() []*Field { - return getFields(s.value, s.TagName) -} - -// Names returns a slice of field names. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Names() []string { - fields := getFields(s.value, s.TagName) - - names := make([]string, len(fields)) - - for i, field := range fields { - names[i] = field.Name() - } - - return names -} - -func getFields(v reflect.Value, tagName string) []*Field { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - t := v.Type() - - var fields []*Field - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - - if tag := field.Tag.Get(tagName); tag == "-" { - continue - } - - f := &Field{ - field: field, - value: v.FieldByName(field.Name), - } - - fields = append(fields, f) - - } - - return fields -} - -// Field returns a new Field struct that provides several high level functions -// around a single struct field entity. It panics if the field is not found. -func (s *Struct) Field(name string) *Field { - f, ok := s.FieldOk(name) - if !ok { - panic("field not found") - } - - return f -} - -// FieldOk returns a new Field struct that provides several high level functions -// around a single struct field entity. The boolean returns true if the field -// was found. -func (s *Struct) FieldOk(name string) (*Field, bool) { - t := s.value.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: s.value.FieldByName(name), - defaultTag: s.TagName, - }, true -} - -// IsZero returns true if all fields in a struct is a zero value (not -// initialized) A struct tag with the content of "-" ignores the checking of -// that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) IsZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := IsZero(val.Interface()) - if !ok { - return false - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if !reflect.DeepEqual(current, zero) { - return false - } - } - - return true -} - -// HasZero returns true if a field in a struct is not initialized (zero value). -// A struct tag with the content of "-" ignores the checking of that particular -// field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) HasZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := HasZero(val.Interface()) - if ok { - return true - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - return true - } - } - - return false -} - -// Name returns the structs's type name within its package. For more info refer -// to Name() function. -func (s *Struct) Name() string { - return s.value.Type().Name() -} - -// structFields returns the exported struct fields for a given s struct. This -// is a convenient helper method to avoid duplicate code in some of the -// functions. -func (s *Struct) structFields() []reflect.StructField { - t := s.value.Type() - - var f []reflect.StructField - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - // we can't access the value of unexported fields - if field.PkgPath != "" { - continue - } - - // don't check if it's omitted - if tag := field.Tag.Get(s.TagName); tag == "-" { - continue - } - - f = append(f, field) - } - - return f -} - -func strctVal(s interface{}) reflect.Value { - v := reflect.ValueOf(s) - - // if pointer get the underlying element≤ - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - if v.Kind() != reflect.Struct { - panic("not struct") - } - - return v -} - -// Map converts the given struct to a map[string]interface{}. For more info -// refer to Struct types Map() method. It panics if s's kind is not struct. -func Map(s interface{}) map[string]interface{} { - return New(s).Map() -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func FillMap(s interface{}, out map[string]interface{}) { - New(s).FillMap(out) -} - -// Values converts the given struct to a []interface{}. For more info refer to -// Struct types Values() method. It panics if s's kind is not struct. -func Values(s interface{}) []interface{} { - return New(s).Values() -} - -// Fields returns a slice of *Field. For more info refer to Struct types -// Fields() method. It panics if s's kind is not struct. -func Fields(s interface{}) []*Field { - return New(s).Fields() -} - -// Names returns a slice of field names. For more info refer to Struct types -// Names() method. It panics if s's kind is not struct. -func Names(s interface{}) []string { - return New(s).Names() -} - -// IsZero returns true if all fields is equal to a zero value. For more info -// refer to Struct types IsZero() method. It panics if s's kind is not struct. -func IsZero(s interface{}) bool { - return New(s).IsZero() -} - -// HasZero returns true if any field is equal to a zero value. For more info -// refer to Struct types HasZero() method. It panics if s's kind is not struct. -func HasZero(s interface{}) bool { - return New(s).HasZero() -} - -// IsStruct returns true if the given variable is a struct or a pointer to -// struct. -func IsStruct(s interface{}) bool { - v := reflect.ValueOf(s) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - // uninitialized zero value of a struct - if v.Kind() == reflect.Invalid { - return false - } - - return v.Kind() == reflect.Struct -} - -// Name returns the structs's type name within its package. It returns an -// empty string for unnamed types. It panics if s's kind is not struct. -func Name(s interface{}) string { - return New(s).Name() -} - -// nested retrieves recursively all types for the given value and returns the -// nested value. -func (s *Struct) nested(val reflect.Value) interface{} { - var finalVal interface{} - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - n := New(val.Interface()) - n.TagName = s.TagName - m := n.Map() - - // do not add the converted value if there are no exported fields, ie: - // time.Time - if len(m) == 0 { - finalVal = val.Interface() - } else { - finalVal = m - } - case reflect.Map: - // get the element type of the map - mapElem := val.Type() - switch val.Type().Kind() { - case reflect.Ptr, reflect.Array, reflect.Map, - reflect.Slice, reflect.Chan: - mapElem = val.Type().Elem() - if mapElem.Kind() == reflect.Ptr { - mapElem = mapElem.Elem() - } - } - - // only iterate over struct types, ie: map[string]StructType, - // map[string][]StructType, - if mapElem.Kind() == reflect.Struct || - (mapElem.Kind() == reflect.Slice && - mapElem.Elem().Kind() == reflect.Struct) { - m := make(map[string]interface{}, val.Len()) - for _, k := range val.MapKeys() { - m[k.String()] = s.nested(val.MapIndex(k)) - } - finalVal = m - break - } - - // TODO(arslan): should this be optional? - finalVal = val.Interface() - case reflect.Slice, reflect.Array: - if val.Type().Kind() == reflect.Interface { - finalVal = val.Interface() - break - } - - // TODO(arslan): should this be optional? - // do not iterate of non struct types, just pass the value. Ie: []int, - // []string, co... We only iterate further if it's a struct. - // i.e []foo or []*foo - if val.Type().Elem().Kind() != reflect.Struct && - !(val.Type().Elem().Kind() == reflect.Ptr && - val.Type().Elem().Elem().Kind() == reflect.Struct) { - finalVal = val.Interface() - break - } - - slices := make([]interface{}, val.Len(), val.Len()) - for x := 0; x < val.Len(); x++ { - slices[x] = s.nested(val.Index(x)) - } - finalVal = slices - default: - finalVal = val.Interface() - } - - return finalVal -} diff --git a/vendor/github.com/fatih/structs/tags.go b/vendor/github.com/fatih/structs/tags.go deleted file mode 100644 index 8859341c1..000000000 --- a/vendor/github.com/fatih/structs/tags.go +++ /dev/null @@ -1,32 +0,0 @@ -package structs - -import "strings" - -// tagOptions contains a slice of tag options -type tagOptions []string - -// Has returns true if the given optiton is available in tagOptions -func (t tagOptions) Has(opt string) bool { - for _, tagOpt := range t { - if tagOpt == opt { - return true - } - } - - return false -} - -// parseTag splits a struct field's tag into its name and a list of options -// which comes after a name. A tag is in the form of: "name,option1,option2". -// The name can be neglectected. -func parseTag(tag string) (string, tagOptions) { - // tag is one of followings: - // "" - // "name" - // "name,opt" - // "name,opt,opt2" - // ",opt" - - res := strings.Split(tag, ",") - return res[0], res[1:] -} diff --git a/vendor/github.com/fsouza/go-dockerclient/AUTHORS b/vendor/github.com/fsouza/go-dockerclient/AUTHORS deleted file mode 100644 index d27226e58..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/AUTHORS +++ /dev/null @@ -1,136 +0,0 @@ -# This is the official list of go-dockerclient authors for copyright purposes. - -Abhishek Chanda -Adam Bell-Hanssen -Adrien Kohlbecker -Aldrin Leal -Andreas Jaekle -Andrews Medina -Andrey Sibiryov -Andy Goldstein -Antonio Murdaca -Artem Sidorenko -Ben Marini -Ben McCann -Ben Parees -Benno van den Berg -Bradley Cicenas -Brendan Fosberry -Brian Lalor -Brian P. Hamachek -Brian Palmer -Bryan Boreham -Burke Libbey -Carlos Diaz-Padron -Cesar Wong -Cezar Sa Espinola -Cheah Chu Yeow -cheneydeng -Chris Bednarski -CMGS -Colin Hebert -Craig Jellick -Dan Williams -Daniel, Dao Quang Minh -Daniel Garcia -Daniel Hiltgen -Darren Shepherd -Dave Choi -David Huie -Dawn Chen -Dinesh Subhraveti -Drew Wells -Ed -Elias G. Schneevoigt -Erez Horev -Eric Anderson -Ewout Prangsma -Fabio Rehm -Fatih Arslan -Flavia Missi -Francisco Souza -Frank Groeneveld -George Moura -Grégoire Delattre -Guillermo Álvarez Fernández -Harry Zhang -He Simei -Ivan Mikushin -James Bardin -James Nugent -Jari Kolehmainen -Jason Wilder -Jawher Moussa -Jean-Baptiste Dalido -Jeff Mitchell -Jeffrey Hulten -Jen Andre -Jérôme Laurens -Johan Euphrosine -John Hughes -Kamil Domanski -Karan Misra -Ken Herner -Kim, Hirokuni -Kyle Allan -Liron Levin -Lior Yankovich -Liu Peng -Lorenz Leutgeb -Lucas Clemente -Lucas Weiblen -Lyon Hill -Mantas Matelis -Martin Sweeney -Máximo Cuadros Ortiz -Michael Schmatz -Michal Fojtik -Mike Dillon -Mrunal Patel -Nate Jones -Nguyen Sy Thanh Son -Nicholas Van Wiggeren -Nick Ethier -Omeid Matten -Orivej Desh -Paul Bellamy -Paul Morie -Paul Weil -Peter Edge -Peter Jihoon Kim -Phil Lu -Philippe Lafoucrière -Rafe Colton -Raphaël Pinson -Rob Miller -Robbert Klarenbeek -Robert Williamson -Roman Khlystik -Salvador Gironès -Sam Rijs -Sami Wagiaalla -Samuel Archambault -Samuel Karp -Seth Jennings -Silas Sewell -Simon Eskildsen -Simon Menke -Skolos -Soulou -Sridhar Ratnakumar -Summer Mousa -Sunjin Lee -Tarsis Azevedo -Tim Schindler -Timothy St. Clair -Tobi Knaup -Tom Wilkie -Tonic -ttyh061 -Victor Marmol -Vincenzo Prignano -Vlad Alexandru Ionescu -Wiliam Souza -Ye Yin -Yu, Zou -Yuriy Bogdanov diff --git a/vendor/github.com/fsouza/go-dockerclient/DOCKER-LICENSE b/vendor/github.com/fsouza/go-dockerclient/DOCKER-LICENSE deleted file mode 100644 index 706634474..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/DOCKER-LICENSE +++ /dev/null @@ -1,6 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -You can find the Docker license at the following link: -https://raw.githubusercontent.com/docker/docker/master/LICENSE diff --git a/vendor/github.com/fsouza/go-dockerclient/LICENSE b/vendor/github.com/fsouza/go-dockerclient/LICENSE deleted file mode 100644 index b1cdd4cd2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016, go-dockerclient authors -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsouza/go-dockerclient/Makefile b/vendor/github.com/fsouza/go-dockerclient/Makefile deleted file mode 100644 index 2d6a5cf89..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -.PHONY: \ - all \ - vendor \ - lint \ - vet \ - fmt \ - fmtcheck \ - pretest \ - test \ - integration \ - cov \ - clean - -PKGS = . ./testing - -all: test - -vendor: - @ go get -v github.com/mjibson/party - party -d external -c -u - -lint: - @ go get -v github.com/golang/lint/golint - @for file in $$(git ls-files '*.go' | grep -v 'external/'); do \ - export output="$$(golint $${file} | grep -v 'type name will be used as docker.DockerInfo')"; \ - [ -n "$${output}" ] && echo "$${output}" && export status=1; \ - done; \ - exit $${status:-0} - -vet: - go vet $(PKGS) - -fmt: - gofmt -s -w $(PKGS) - -fmtcheck: - @ export output=$$(gofmt -s -d $(PKGS)); \ - [ -n "$${output}" ] && echo "$${output}" && export status=1; \ - exit $${status:-0} - -pretest: lint vet fmtcheck - -gotest: - go test $(GO_TEST_FLAGS) $(PKGS) - -test: pretest gotest - -integration: - go test -tags docker_integration -run TestIntegration -v - -cov: - @ go get -v github.com/axw/gocov/gocov - @ go get golang.org/x/tools/cmd/cover - gocov test | gocov report - -clean: - go clean $(PKGS) diff --git a/vendor/github.com/fsouza/go-dockerclient/README.markdown b/vendor/github.com/fsouza/go-dockerclient/README.markdown deleted file mode 100644 index 234b9e49e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/README.markdown +++ /dev/null @@ -1,106 +0,0 @@ -# go-dockerclient - -[![Travis](https://img.shields.io/travis/fsouza/go-dockerclient/master.svg?style=flat-square)](https://travis-ci.org/fsouza/go-dockerclient) -[![GoDoc](https://img.shields.io/badge/api-Godoc-blue.svg?style=flat-square)](https://godoc.org/github.com/fsouza/go-dockerclient) - -This package presents a client for the Docker remote API. It also provides -support for the extensions in the [Swarm API](https://docs.docker.com/swarm/swarm-api/). -It currently supports the Docker API up to version 1.23. - -This package also provides support for docker's network API, which is a simple -passthrough to the libnetwork remote API. Note that docker's network API is -only available in docker 1.8 and above, and only enabled in docker if -DOCKER_EXPERIMENTAL is defined during the docker build process. - -For more details, check the [remote API documentation](http://docs.docker.com/engine/reference/api/docker_remote_api/). - -## Vendoring - -If you are having issues with Go 1.5 and have `GO15VENDOREXPERIMENT` set with an application that has go-dockerclient vendored, -please update your vendoring of go-dockerclient :) We recently moved the `vendor` directory to `external` so that go-dockerclient -is compatible with this configuration. See [338](https://github.com/fsouza/go-dockerclient/issues/338) and [339](https://github.com/fsouza/go-dockerclient/pull/339) -for details. - -## Example - -```go -package main - -import ( - "fmt" - - "github.com/fsouza/go-dockerclient" -) - -func main() { - endpoint := "unix:///var/run/docker.sock" - client, _ := docker.NewClient(endpoint) - imgs, _ := client.ListImages(docker.ListImagesOptions{All: false}) - for _, img := range imgs { - fmt.Println("ID: ", img.ID) - fmt.Println("RepoTags: ", img.RepoTags) - fmt.Println("Created: ", img.Created) - fmt.Println("Size: ", img.Size) - fmt.Println("VirtualSize: ", img.VirtualSize) - fmt.Println("ParentId: ", img.ParentID) - } -} -``` - -## Using with TLS - -In order to instantiate the client for a TLS-enabled daemon, you should use NewTLSClient, passing the endpoint and path for key and certificates as parameters. - -```go -package main - -import ( - "fmt" - - "github.com/fsouza/go-dockerclient" -) - -func main() { - endpoint := "tcp://[ip]:[port]" - path := os.Getenv("DOCKER_CERT_PATH") - ca := fmt.Sprintf("%s/ca.pem", path) - cert := fmt.Sprintf("%s/cert.pem", path) - key := fmt.Sprintf("%s/key.pem", path) - client, _ := docker.NewTLSClient(endpoint, cert, key, ca) - // use client -} -``` - -If using [docker-machine](https://docs.docker.com/machine/), or another application that exports environment variables -`DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH`, you can use NewClientFromEnv. - - -```go -package main - -import ( - "fmt" - - "github.com/fsouza/go-dockerclient" -) - -func main() { - client, _ := docker.NewClientFromEnv() - // use client -} -``` - -See the documentation for more details. - -## Developing - -All development commands can be seen in the [Makefile](Makefile). - -Commited code must pass: - -* [golint](https://github.com/golang/lint) -* [go vet](https://godoc.org/golang.org/x/tools/cmd/vet) -* [gofmt](https://golang.org/cmd/gofmt) -* [go test](https://golang.org/cmd/go/#hdr-Test_packages) - -Running `make test` will check all of these. If your editor does not automatically call gofmt, `make fmt` will format all go files in this repository. diff --git a/vendor/github.com/fsouza/go-dockerclient/auth.go b/vendor/github.com/fsouza/go-dockerclient/auth.go deleted file mode 100644 index 95596d782..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/auth.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path" - "strings" -) - -// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed. -var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg") - -// AuthConfiguration represents authentication options to use in the PushImage -// method. It represents the authentication in the Docker index server. -type AuthConfiguration struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Email string `json:"email,omitempty"` - ServerAddress string `json:"serveraddress,omitempty"` -} - -// AuthConfigurations represents authentication options to use for the -// PushImage method accommodating the new X-Registry-Config header -type AuthConfigurations struct { - Configs map[string]AuthConfiguration `json:"configs"` -} - -// AuthConfigurations119 is used to serialize a set of AuthConfigurations -// for Docker API >= 1.19. -type AuthConfigurations119 map[string]AuthConfiguration - -// dockerConfig represents a registry authentation configuration from the -// .dockercfg file. -type dockerConfig struct { - Auth string `json:"auth"` - Email string `json:"email"` -} - -// NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from the -// ~/.dockercfg file. -func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) { - var r io.Reader - var err error - p := path.Join(os.Getenv("HOME"), ".docker", "config.json") - r, err = os.Open(p) - if err != nil { - p := path.Join(os.Getenv("HOME"), ".dockercfg") - r, err = os.Open(p) - if err != nil { - return nil, err - } - } - return NewAuthConfigurations(r) -} - -// NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the -// same format as the .dockercfg file. -func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) { - var auth *AuthConfigurations - confs, err := parseDockerConfig(r) - if err != nil { - return nil, err - } - auth, err = authConfigs(confs) - if err != nil { - return nil, err - } - return auth, nil -} - -func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) { - buf := new(bytes.Buffer) - buf.ReadFrom(r) - byteData := buf.Bytes() - - confsWrapper := struct { - Auths map[string]dockerConfig `json:"auths"` - }{} - if err := json.Unmarshal(byteData, &confsWrapper); err == nil { - if len(confsWrapper.Auths) > 0 { - return confsWrapper.Auths, nil - } - } - - var confs map[string]dockerConfig - if err := json.Unmarshal(byteData, &confs); err != nil { - return nil, err - } - return confs, nil -} - -// authConfigs converts a dockerConfigs map to a AuthConfigurations object. -func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) { - c := &AuthConfigurations{ - Configs: make(map[string]AuthConfiguration), - } - for reg, conf := range confs { - data, err := base64.StdEncoding.DecodeString(conf.Auth) - if err != nil { - return nil, err - } - userpass := strings.SplitN(string(data), ":", 2) - if len(userpass) != 2 { - return nil, ErrCannotParseDockercfg - } - c.Configs[reg] = AuthConfiguration{ - Email: conf.Email, - Username: userpass[0], - Password: userpass[1], - ServerAddress: reg, - } - } - return c, nil -} - -// AuthStatus returns the authentication status for Docker API versions >= 1.23. -type AuthStatus struct { - Status string `json:"Status,omitempty" yaml:"Status,omitempty"` - IdentityToken string `json:"IdentityToken,omitempty" yaml:"IdentityToken,omitempty"` -} - -// AuthCheck validates the given credentials. It returns nil if successful. -// -// For Docker API versions >= 1.23, the AuthStatus struct will be populated, otherwise it will be empty.` -// -// See https://goo.gl/6nsZkH for more details. -func (c *Client) AuthCheck(conf *AuthConfiguration) (AuthStatus, error) { - var authStatus AuthStatus - if conf == nil { - return authStatus, fmt.Errorf("conf is nil") - } - resp, err := c.do("POST", "/auth", doOptions{data: conf}) - if err != nil { - return authStatus, err - } - defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return authStatus, err - } - if len(data) == 0 { - return authStatus, nil - } - if err := json.Unmarshal(data, &authStatus); err != nil { - return authStatus, err - } - return authStatus, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/cancelable.go b/vendor/github.com/fsouza/go-dockerclient/cancelable.go deleted file mode 100644 index 375fbd15c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/cancelable.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package docker - -import "net/http" - -func cancelable(client *http.Client, req *http.Request) func() { - ch := make(chan struct{}) - req.Cancel = ch - return func() { - close(ch) - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/cancelable_go14.go b/vendor/github.com/fsouza/go-dockerclient/cancelable_go14.go deleted file mode 100644 index 3c203986f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/cancelable_go14.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2016 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package docker - -import "net/http" - -func cancelable(client *http.Client, req *http.Request) func() { - return func() { - if rc, ok := client.Transport.(interface { - CancelRequest(*http.Request) - }); ok { - rc.CancelRequest(req) - } - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/change.go b/vendor/github.com/fsouza/go-dockerclient/change.go deleted file mode 100644 index d133594d4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/change.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import "fmt" - -// ChangeType is a type for constants indicating the type of change -// in a container -type ChangeType int - -const ( - // ChangeModify is the ChangeType for container modifications - ChangeModify ChangeType = iota - - // ChangeAdd is the ChangeType for additions to a container - ChangeAdd - - // ChangeDelete is the ChangeType for deletions from a container - ChangeDelete -) - -// Change represents a change in a container. -// -// See https://goo.gl/9GsTIF for more details. -type Change struct { - Path string - Kind ChangeType -} - -func (change *Change) String() string { - var kind string - switch change.Kind { - case ChangeModify: - kind = "C" - case ChangeAdd: - kind = "A" - case ChangeDelete: - kind = "D" - } - return fmt.Sprintf("%s %s", kind, change.Path) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/client.go b/vendor/github.com/fsouza/go-dockerclient/client.go deleted file mode 100644 index a3f09cd8b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/client.go +++ /dev/null @@ -1,995 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package docker provides a client for the Docker remote API. -// -// See https://goo.gl/G3plxW for more details on the remote API. -package docker - -import ( - "bufio" - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httputil" - "net/url" - "os" - "path/filepath" - "reflect" - "runtime" - "strconv" - "strings" - "sync/atomic" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy" - "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" -) - -const userAgent = "go-dockerclient" - -var ( - // ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL. - ErrInvalidEndpoint = errors.New("invalid endpoint") - - // ErrConnectionRefused is returned when the client cannot connect to the given endpoint. - ErrConnectionRefused = errors.New("cannot connect to Docker endpoint") - - // ErrInactivityTimeout is returned when a streamable call has been inactive for some time. - ErrInactivityTimeout = errors.New("inactivity time exceeded timeout") - - apiVersion112, _ = NewAPIVersion("1.12") - - apiVersion119, _ = NewAPIVersion("1.19") -) - -// APIVersion is an internal representation of a version of the Remote API. -type APIVersion []int - -// NewAPIVersion returns an instance of APIVersion for the given string. -// -// The given string must be in the form .., where , -// and are integer numbers. -func NewAPIVersion(input string) (APIVersion, error) { - if !strings.Contains(input, ".") { - return nil, fmt.Errorf("Unable to parse version %q", input) - } - raw := strings.Split(input, "-") - arr := strings.Split(raw[0], ".") - ret := make(APIVersion, len(arr)) - var err error - for i, val := range arr { - ret[i], err = strconv.Atoi(val) - if err != nil { - return nil, fmt.Errorf("Unable to parse version %q: %q is not an integer", input, val) - } - } - return ret, nil -} - -func (version APIVersion) String() string { - var str string - for i, val := range version { - str += strconv.Itoa(val) - if i < len(version)-1 { - str += "." - } - } - return str -} - -// LessThan is a function for comparing APIVersion structs -func (version APIVersion) LessThan(other APIVersion) bool { - return version.compare(other) < 0 -} - -// LessThanOrEqualTo is a function for comparing APIVersion structs -func (version APIVersion) LessThanOrEqualTo(other APIVersion) bool { - return version.compare(other) <= 0 -} - -// GreaterThan is a function for comparing APIVersion structs -func (version APIVersion) GreaterThan(other APIVersion) bool { - return version.compare(other) > 0 -} - -// GreaterThanOrEqualTo is a function for comparing APIVersion structs -func (version APIVersion) GreaterThanOrEqualTo(other APIVersion) bool { - return version.compare(other) >= 0 -} - -func (version APIVersion) compare(other APIVersion) int { - for i, v := range version { - if i <= len(other)-1 { - otherVersion := other[i] - - if v < otherVersion { - return -1 - } else if v > otherVersion { - return 1 - } - } - } - if len(version) > len(other) { - return 1 - } - if len(version) < len(other) { - return -1 - } - return 0 -} - -// Client is the basic type of this package. It provides methods for -// interaction with the API. -type Client struct { - SkipServerVersionCheck bool - HTTPClient *http.Client - TLSConfig *tls.Config - Dialer *net.Dialer - - endpoint string - endpointURL *url.URL - eventMonitor *eventMonitoringState - requestedAPIVersion APIVersion - serverAPIVersion APIVersion - expectedAPIVersion APIVersion - unixHTTPClient *http.Client -} - -// NewClient returns a Client instance ready for communication with the given -// server endpoint. It will use the latest remote API version available in the -// server. -func NewClient(endpoint string) (*Client, error) { - client, err := NewVersionedClient(endpoint, "") - if err != nil { - return nil, err - } - client.SkipServerVersionCheck = true - return client, nil -} - -// NewTLSClient returns a Client instance ready for TLS communications with the givens -// server endpoint, key and certificates . It will use the latest remote API version -// available in the server. -func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) { - client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "") - if err != nil { - return nil, err - } - client.SkipServerVersionCheck = true - return client, nil -} - -// NewTLSClientFromBytes returns a Client instance ready for TLS communications with the givens -// server endpoint, key and certificates (passed inline to the function as opposed to being -// read from a local file). It will use the latest remote API version available in the server. -func NewTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte) (*Client, error) { - client, err := NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, "") - if err != nil { - return nil, err - } - client.SkipServerVersionCheck = true - return client, nil -} - -// NewVersionedClient returns a Client instance ready for communication with -// the given server endpoint, using a specific remote API version. -func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) { - u, err := parseEndpoint(endpoint, false) - if err != nil { - return nil, err - } - var requestedAPIVersion APIVersion - if strings.Contains(apiVersionString, ".") { - requestedAPIVersion, err = NewAPIVersion(apiVersionString) - if err != nil { - return nil, err - } - } - return &Client{ - HTTPClient: cleanhttp.DefaultClient(), - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - eventMonitor: new(eventMonitoringState), - requestedAPIVersion: requestedAPIVersion, - }, nil -} - -// NewVersionnedTLSClient has been DEPRECATED, please use NewVersionedTLSClient. -func NewVersionnedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { - return NewVersionedTLSClient(endpoint, cert, key, ca, apiVersionString) -} - -// NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens -// server endpoint, key and certificates, using a specific remote API version. -func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { - certPEMBlock, err := ioutil.ReadFile(cert) - if err != nil { - return nil, err - } - keyPEMBlock, err := ioutil.ReadFile(key) - if err != nil { - return nil, err - } - caPEMCert, err := ioutil.ReadFile(ca) - if err != nil { - return nil, err - } - return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString) -} - -// NewClientFromEnv returns a Client instance ready for communication created from -// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH. -// -// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. -// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. -func NewClientFromEnv() (*Client, error) { - client, err := NewVersionedClientFromEnv("") - if err != nil { - return nil, err - } - client.SkipServerVersionCheck = true - return client, nil -} - -// NewVersionedClientFromEnv returns a Client instance ready for TLS communications created from -// Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH, -// and using a specific remote API version. -// -// See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. -// See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. -func NewVersionedClientFromEnv(apiVersionString string) (*Client, error) { - dockerEnv, err := getDockerEnv() - if err != nil { - return nil, err - } - dockerHost := dockerEnv.dockerHost - if dockerEnv.dockerTLSVerify { - parts := strings.SplitN(dockerEnv.dockerHost, "://", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("could not split %s into two parts by ://", dockerHost) - } - cert := filepath.Join(dockerEnv.dockerCertPath, "cert.pem") - key := filepath.Join(dockerEnv.dockerCertPath, "key.pem") - ca := filepath.Join(dockerEnv.dockerCertPath, "ca.pem") - return NewVersionedTLSClient(dockerEnv.dockerHost, cert, key, ca, apiVersionString) - } - return NewVersionedClient(dockerEnv.dockerHost, apiVersionString) -} - -// NewVersionedTLSClientFromBytes returns a Client instance ready for TLS communications with the givens -// server endpoint, key and certificates (passed inline to the function as opposed to being -// read from a local file), using a specific remote API version. -func NewVersionedTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte, apiVersionString string) (*Client, error) { - u, err := parseEndpoint(endpoint, true) - if err != nil { - return nil, err - } - var requestedAPIVersion APIVersion - if strings.Contains(apiVersionString, ".") { - requestedAPIVersion, err = NewAPIVersion(apiVersionString) - if err != nil { - return nil, err - } - } - if certPEMBlock == nil || keyPEMBlock == nil { - return nil, errors.New("Both cert and key are required") - } - tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) - if err != nil { - return nil, err - } - tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}} - if caPEMCert == nil { - tlsConfig.InsecureSkipVerify = true - } else { - caPool := x509.NewCertPool() - if !caPool.AppendCertsFromPEM(caPEMCert) { - return nil, errors.New("Could not add RootCA pem") - } - tlsConfig.RootCAs = caPool - } - tr := cleanhttp.DefaultTransport() - tr.TLSClientConfig = tlsConfig - if err != nil { - return nil, err - } - return &Client{ - HTTPClient: &http.Client{Transport: tr}, - TLSConfig: tlsConfig, - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - eventMonitor: new(eventMonitoringState), - requestedAPIVersion: requestedAPIVersion, - }, nil -} - -func (c *Client) checkAPIVersion() error { - serverAPIVersionString, err := c.getServerAPIVersionString() - if err != nil { - return err - } - c.serverAPIVersion, err = NewAPIVersion(serverAPIVersionString) - if err != nil { - return err - } - if c.requestedAPIVersion == nil { - c.expectedAPIVersion = c.serverAPIVersion - } else { - c.expectedAPIVersion = c.requestedAPIVersion - } - return nil -} - -// Endpoint returns the current endpoint. It's useful for getting the endpoint -// when using functions that get this data from the environment (like -// NewClientFromEnv. -func (c *Client) Endpoint() string { - return c.endpoint -} - -// Ping pings the docker server -// -// See https://goo.gl/kQCfJj for more details. -func (c *Client) Ping() error { - path := "/_ping" - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return newError(resp) - } - resp.Body.Close() - return nil -} - -func (c *Client) getServerAPIVersionString() (version string, err error) { - resp, err := c.do("GET", "/version", doOptions{}) - if err != nil { - return "", err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("Received unexpected status %d while trying to retrieve the server version", resp.StatusCode) - } - var versionResponse map[string]interface{} - if err := json.NewDecoder(resp.Body).Decode(&versionResponse); err != nil { - return "", err - } - if version, ok := (versionResponse["ApiVersion"]).(string); ok { - return version, nil - } - return "", nil -} - -type doOptions struct { - data interface{} - forceJSON bool - headers map[string]string -} - -func (c *Client) do(method, path string, doOptions doOptions) (*http.Response, error) { - var params io.Reader - if doOptions.data != nil || doOptions.forceJSON { - buf, err := json.Marshal(doOptions.data) - if err != nil { - return nil, err - } - params = bytes.NewBuffer(buf) - } - if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { - err := c.checkAPIVersion() - if err != nil { - return nil, err - } - } - httpClient := c.HTTPClient - protocol := c.endpointURL.Scheme - var u string - if protocol == "unix" { - httpClient = c.unixClient() - u = c.getFakeUnixURL(path) - } else { - u = c.getURL(path) - } - req, err := http.NewRequest(method, u, params) - if err != nil { - return nil, err - } - req.Header.Set("User-Agent", userAgent) - if doOptions.data != nil { - req.Header.Set("Content-Type", "application/json") - } else if method == "POST" { - req.Header.Set("Content-Type", "plain/text") - } - - for k, v := range doOptions.headers { - req.Header.Set(k, v) - } - resp, err := httpClient.Do(req) - if err != nil { - if strings.Contains(err.Error(), "connection refused") { - return nil, ErrConnectionRefused - } - return nil, err - } - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - return nil, newError(resp) - } - return resp, nil -} - -type streamOptions struct { - setRawTerminal bool - rawJSONStream bool - useJSONDecoder bool - headers map[string]string - in io.Reader - stdout io.Writer - stderr io.Writer - // timeout is the initial connection timeout - timeout time.Duration - // Timeout with no data is received, it's reset every time new data - // arrives - inactivityTimeout time.Duration -} - -func (c *Client) stream(method, path string, streamOptions streamOptions) error { - if (method == "POST" || method == "PUT") && streamOptions.in == nil { - streamOptions.in = bytes.NewReader(nil) - } - if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { - err := c.checkAPIVersion() - if err != nil { - return err - } - } - req, err := http.NewRequest(method, c.getURL(path), streamOptions.in) - if err != nil { - return err - } - req.Header.Set("User-Agent", userAgent) - if method == "POST" { - req.Header.Set("Content-Type", "plain/text") - } - for key, val := range streamOptions.headers { - req.Header.Set(key, val) - } - var resp *http.Response - protocol := c.endpointURL.Scheme - address := c.endpointURL.Path - if streamOptions.stdout == nil { - streamOptions.stdout = ioutil.Discard - } - if streamOptions.stderr == nil { - streamOptions.stderr = ioutil.Discard - } - cancelRequest := cancelable(c.HTTPClient, req) - if protocol == "unix" { - dial, err := c.Dialer.Dial(protocol, address) - if err != nil { - return err - } - cancelRequest = func() { dial.Close() } - defer dial.Close() - breader := bufio.NewReader(dial) - err = req.Write(dial) - if err != nil { - return err - } - - // ReadResponse may hang if server does not replay - if streamOptions.timeout > 0 { - dial.SetDeadline(time.Now().Add(streamOptions.timeout)) - } - - if resp, err = http.ReadResponse(breader, req); err != nil { - // Cancel timeout for future I/O operations - if streamOptions.timeout > 0 { - dial.SetDeadline(time.Time{}) - } - if strings.Contains(err.Error(), "connection refused") { - return ErrConnectionRefused - } - return err - } - } else { - if resp, err = c.HTTPClient.Do(req); err != nil { - if strings.Contains(err.Error(), "connection refused") { - return ErrConnectionRefused - } - return err - } - } - defer resp.Body.Close() - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - return newError(resp) - } - var canceled uint32 - if streamOptions.inactivityTimeout > 0 { - ch := handleInactivityTimeout(&streamOptions, cancelRequest, &canceled) - defer close(ch) - } - err = handleStreamResponse(resp, &streamOptions) - if err != nil { - if atomic.LoadUint32(&canceled) != 0 { - return ErrInactivityTimeout - } - return err - } - return nil -} - -func handleStreamResponse(resp *http.Response, streamOptions *streamOptions) error { - var err error - if !streamOptions.useJSONDecoder && resp.Header.Get("Content-Type") != "application/json" { - if streamOptions.setRawTerminal { - _, err = io.Copy(streamOptions.stdout, resp.Body) - } else { - _, err = stdcopy.StdCopy(streamOptions.stdout, streamOptions.stderr, resp.Body) - } - return err - } - // if we want to get raw json stream, just copy it back to output - // without decoding it - if streamOptions.rawJSONStream { - _, err = io.Copy(streamOptions.stdout, resp.Body) - return err - } - dec := json.NewDecoder(resp.Body) - for { - var m jsonMessage - if err := dec.Decode(&m); err == io.EOF { - break - } else if err != nil { - return err - } - if m.Stream != "" { - fmt.Fprint(streamOptions.stdout, m.Stream) - } else if m.Progress != "" { - fmt.Fprintf(streamOptions.stdout, "%s %s\r", m.Status, m.Progress) - } else if m.Error != "" { - return errors.New(m.Error) - } - if m.Status != "" { - fmt.Fprintln(streamOptions.stdout, m.Status) - } - } - return nil -} - -type proxyWriter struct { - io.Writer - calls uint64 -} - -func (p *proxyWriter) callCount() uint64 { - return atomic.LoadUint64(&p.calls) -} - -func (p *proxyWriter) Write(data []byte) (int, error) { - atomic.AddUint64(&p.calls, 1) - return p.Writer.Write(data) -} - -func handleInactivityTimeout(options *streamOptions, cancelRequest func(), canceled *uint32) chan<- struct{} { - done := make(chan struct{}) - proxyStdout := &proxyWriter{Writer: options.stdout} - proxyStderr := &proxyWriter{Writer: options.stderr} - options.stdout = proxyStdout - options.stderr = proxyStderr - go func() { - var lastCallCount uint64 - for { - select { - case <-time.After(options.inactivityTimeout): - case <-done: - return - } - curCallCount := proxyStdout.callCount() + proxyStderr.callCount() - if curCallCount == lastCallCount { - atomic.AddUint32(canceled, 1) - cancelRequest() - return - } - lastCallCount = curCallCount - } - }() - return done -} - -type hijackOptions struct { - success chan struct{} - setRawTerminal bool - in io.Reader - stdout io.Writer - stderr io.Writer - data interface{} -} - -// CloseWaiter is an interface with methods for closing the underlying resource -// and then waiting for it to finish processing. -type CloseWaiter interface { - io.Closer - Wait() error -} - -type waiterFunc func() error - -func (w waiterFunc) Wait() error { return w() } - -type closerFunc func() error - -func (c closerFunc) Close() error { return c() } - -func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (CloseWaiter, error) { - if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { - err := c.checkAPIVersion() - if err != nil { - return nil, err - } - } - var params io.Reader - if hijackOptions.data != nil { - buf, err := json.Marshal(hijackOptions.data) - if err != nil { - return nil, err - } - params = bytes.NewBuffer(buf) - } - req, err := http.NewRequest(method, c.getURL(path), params) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "tcp") - protocol := c.endpointURL.Scheme - address := c.endpointURL.Path - if protocol != "unix" { - protocol = "tcp" - address = c.endpointURL.Host - } - var dial net.Conn - if c.TLSConfig != nil && protocol != "unix" { - dial, err = tlsDialWithDialer(c.Dialer, protocol, address, c.TLSConfig) - if err != nil { - return nil, err - } - } else { - dial, err = c.Dialer.Dial(protocol, address) - if err != nil { - return nil, err - } - } - - errs := make(chan error) - quit := make(chan struct{}) - go func() { - clientconn := httputil.NewClientConn(dial, nil) - defer clientconn.Close() - clientconn.Do(req) - if hijackOptions.success != nil { - hijackOptions.success <- struct{}{} - <-hijackOptions.success - } - rwc, br := clientconn.Hijack() - defer rwc.Close() - - errChanOut := make(chan error, 1) - errChanIn := make(chan error, 1) - if hijackOptions.stdout == nil && hijackOptions.stderr == nil { - close(errChanOut) - } else { - // Only copy if hijackOptions.stdout and/or hijackOptions.stderr is actually set. - // Otherwise, if the only stream you care about is stdin, your attach session - // will "hang" until the container terminates, even though you're not reading - // stdout/stderr - if hijackOptions.stdout == nil { - hijackOptions.stdout = ioutil.Discard - } - if hijackOptions.stderr == nil { - hijackOptions.stderr = ioutil.Discard - } - - go func() { - defer func() { - if hijackOptions.in != nil { - if closer, ok := hijackOptions.in.(io.Closer); ok { - closer.Close() - } - errChanIn <- nil - } - }() - - var err error - if hijackOptions.setRawTerminal { - _, err = io.Copy(hijackOptions.stdout, br) - } else { - _, err = stdcopy.StdCopy(hijackOptions.stdout, hijackOptions.stderr, br) - } - errChanOut <- err - }() - } - - go func() { - var err error - if hijackOptions.in != nil { - _, err = io.Copy(rwc, hijackOptions.in) - } - errChanIn <- err - rwc.(interface { - CloseWrite() error - }).CloseWrite() - }() - - var errIn error - select { - case errIn = <-errChanIn: - case <-quit: - return - } - - var errOut error - select { - case errOut = <-errChanOut: - case <-quit: - return - } - - if errIn != nil { - errs <- errIn - } else { - errs <- errOut - } - }() - - return struct { - closerFunc - waiterFunc - }{ - closerFunc(func() error { close(quit); return nil }), - waiterFunc(func() error { return <-errs }), - }, nil -} - -func (c *Client) getURL(path string) string { - urlStr := strings.TrimRight(c.endpointURL.String(), "/") - if c.endpointURL.Scheme == "unix" { - urlStr = "" - } - if c.requestedAPIVersion != nil { - return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) - } - return fmt.Sprintf("%s%s", urlStr, path) -} - -// getFakeUnixURL returns the URL needed to make an HTTP request over a UNIX -// domain socket to the given path. -func (c *Client) getFakeUnixURL(path string) string { - u := *c.endpointURL // Copy. - - // Override URL so that net/http will not complain. - u.Scheme = "http" - u.Host = "unix.sock" // Doesn't matter what this is - it's not used. - u.Path = "" - urlStr := strings.TrimRight(u.String(), "/") - if c.requestedAPIVersion != nil { - return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) - } - return fmt.Sprintf("%s%s", urlStr, path) -} - -func (c *Client) unixClient() *http.Client { - if c.unixHTTPClient != nil { - return c.unixHTTPClient - } - socketPath := c.endpointURL.Path - tr := &http.Transport{ - Dial: func(network, addr string) (net.Conn, error) { - return c.Dialer.Dial("unix", socketPath) - }, - } - cleanhttp.SetTransportFinalizer(tr) - c.unixHTTPClient = &http.Client{Transport: tr} - return c.unixHTTPClient -} - -type jsonMessage struct { - Status string `json:"status,omitempty"` - Progress string `json:"progress,omitempty"` - Error string `json:"error,omitempty"` - Stream string `json:"stream,omitempty"` -} - -func queryString(opts interface{}) string { - if opts == nil { - return "" - } - value := reflect.ValueOf(opts) - if value.Kind() == reflect.Ptr { - value = value.Elem() - } - if value.Kind() != reflect.Struct { - return "" - } - items := url.Values(map[string][]string{}) - for i := 0; i < value.NumField(); i++ { - field := value.Type().Field(i) - if field.PkgPath != "" { - continue - } - key := field.Tag.Get("qs") - if key == "" { - key = strings.ToLower(field.Name) - } else if key == "-" { - continue - } - addQueryStringValue(items, key, value.Field(i)) - } - return items.Encode() -} - -func addQueryStringValue(items url.Values, key string, v reflect.Value) { - switch v.Kind() { - case reflect.Bool: - if v.Bool() { - items.Add(key, "1") - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if v.Int() > 0 { - items.Add(key, strconv.FormatInt(v.Int(), 10)) - } - case reflect.Float32, reflect.Float64: - if v.Float() > 0 { - items.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64)) - } - case reflect.String: - if v.String() != "" { - items.Add(key, v.String()) - } - case reflect.Ptr: - if !v.IsNil() { - if b, err := json.Marshal(v.Interface()); err == nil { - items.Add(key, string(b)) - } - } - case reflect.Map: - if len(v.MapKeys()) > 0 { - if b, err := json.Marshal(v.Interface()); err == nil { - items.Add(key, string(b)) - } - } - case reflect.Array, reflect.Slice: - vLen := v.Len() - if vLen > 0 { - for i := 0; i < vLen; i++ { - addQueryStringValue(items, key, v.Index(i)) - } - } - } -} - -// Error represents failures in the API. It represents a failure from the API. -type Error struct { - Status int - Message string -} - -func newError(resp *http.Response) *Error { - defer resp.Body.Close() - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return &Error{Status: resp.StatusCode, Message: fmt.Sprintf("cannot read body, err: %v", err)} - } - return &Error{Status: resp.StatusCode, Message: string(data)} -} - -func (e *Error) Error() string { - return fmt.Sprintf("API error (%d): %s", e.Status, e.Message) -} - -func parseEndpoint(endpoint string, tls bool) (*url.URL, error) { - if endpoint != "" && !strings.Contains(endpoint, "://") { - endpoint = "tcp://" + endpoint - } - u, err := url.Parse(endpoint) - if err != nil { - return nil, ErrInvalidEndpoint - } - if tls { - u.Scheme = "https" - } - switch u.Scheme { - case "unix": - return u, nil - case "http", "https", "tcp": - _, port, err := net.SplitHostPort(u.Host) - if err != nil { - if e, ok := err.(*net.AddrError); ok { - if e.Err == "missing port in address" { - return u, nil - } - } - return nil, ErrInvalidEndpoint - } - number, err := strconv.ParseInt(port, 10, 64) - if err == nil && number > 0 && number < 65536 { - if u.Scheme == "tcp" { - if tls { - u.Scheme = "https" - } else { - u.Scheme = "http" - } - } - return u, nil - } - return nil, ErrInvalidEndpoint - default: - return nil, ErrInvalidEndpoint - } -} - -type dockerEnv struct { - dockerHost string - dockerTLSVerify bool - dockerCertPath string -} - -func getDockerEnv() (*dockerEnv, error) { - dockerHost := os.Getenv("DOCKER_HOST") - var err error - if dockerHost == "" { - dockerHost, err = DefaultDockerHost() - if err != nil { - return nil, err - } - } - dockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY") != "" - var dockerCertPath string - if dockerTLSVerify { - dockerCertPath = os.Getenv("DOCKER_CERT_PATH") - if dockerCertPath == "" { - home := homedir.Get() - if home == "" { - return nil, errors.New("environment variable HOME must be set if DOCKER_CERT_PATH is not set") - } - dockerCertPath = filepath.Join(home, ".docker") - dockerCertPath, err = filepath.Abs(dockerCertPath) - if err != nil { - return nil, err - } - } - } - return &dockerEnv{ - dockerHost: dockerHost, - dockerTLSVerify: dockerTLSVerify, - dockerCertPath: dockerCertPath, - }, nil -} - -// DefaultDockerHost returns the default docker socket for the current OS -func DefaultDockerHost() (string, error) { - var defaultHost string - if runtime.GOOS == "windows" { - // If we do not have a host, default to TCP socket on Windows - defaultHost = fmt.Sprintf("tcp://%s:%d", opts.DefaultHTTPHost, opts.DefaultHTTPPort) - } else { - // If we do not have a host, default to unix socket - defaultHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket) - } - return opts.ValidateHost(defaultHost) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/container.go b/vendor/github.com/fsouza/go-dockerclient/container.go deleted file mode 100644 index f7ed5f574..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/container.go +++ /dev/null @@ -1,1325 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units" -) - -// ErrContainerAlreadyExists is the error returned by CreateContainer when the -// container already exists. -var ErrContainerAlreadyExists = errors.New("container already exists") - -// ListContainersOptions specify parameters to the ListContainers function. -// -// See https://goo.gl/47a6tO for more details. -type ListContainersOptions struct { - All bool - Size bool - Limit int - Since string - Before string - Filters map[string][]string -} - -// APIPort is a type that represents a port mapping returned by the Docker API -type APIPort struct { - PrivatePort int64 `json:"PrivatePort,omitempty" yaml:"PrivatePort,omitempty"` - PublicPort int64 `json:"PublicPort,omitempty" yaml:"PublicPort,omitempty"` - Type string `json:"Type,omitempty" yaml:"Type,omitempty"` - IP string `json:"IP,omitempty" yaml:"IP,omitempty"` -} - -// APIMount represents a mount point for a container. -type APIMount struct { - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - Source string `json:"Source,omitempty" yaml:"Source,omitempty"` - Destination string `json:"Destination,omitempty" yaml:"Destination,omitempty"` - Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty"` - Mode string `json:"Mode,omitempty" yaml:"Mode,omitempty"` - RW bool `json:"RW,omitempty" yaml:"RW,omitempty"` - Propogation string `json:"Propogation,omitempty" yaml:"Propogation,omitempty"` -} - -// APIContainers represents each container in the list returned by -// ListContainers. -type APIContainers struct { - ID string `json:"Id" yaml:"Id"` - Image string `json:"Image,omitempty" yaml:"Image,omitempty"` - Command string `json:"Command,omitempty" yaml:"Command,omitempty"` - Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` - State string `json:"State,omitempty" yaml:"State,omitempty"` - Status string `json:"Status,omitempty" yaml:"Status,omitempty"` - Ports []APIPort `json:"Ports,omitempty" yaml:"Ports,omitempty"` - SizeRw int64 `json:"SizeRw,omitempty" yaml:"SizeRw,omitempty"` - SizeRootFs int64 `json:"SizeRootFs,omitempty" yaml:"SizeRootFs,omitempty"` - Names []string `json:"Names,omitempty" yaml:"Names,omitempty"` - Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` - Networks NetworkList `json:"NetworkSettings,omitempty" yaml:"NetworkSettings,omitempty"` - Mounts []APIMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty"` -} - -// NetworkList encapsulates a map of networks, as returned by the Docker API in -// ListContainers. -type NetworkList struct { - Networks map[string]ContainerNetwork `json:"Networks" yaml:"Networks,omitempty"` -} - -// ListContainers returns a slice of containers matching the given criteria. -// -// See https://goo.gl/47a6tO for more details. -func (c *Client) ListContainers(opts ListContainersOptions) ([]APIContainers, error) { - path := "/containers/json?" + queryString(opts) - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var containers []APIContainers - if err := json.NewDecoder(resp.Body).Decode(&containers); err != nil { - return nil, err - } - return containers, nil -} - -// Port represents the port number and the protocol, in the form -// /. For example: 80/tcp. -type Port string - -// Port returns the number of the port. -func (p Port) Port() string { - return strings.Split(string(p), "/")[0] -} - -// Proto returns the name of the protocol. -func (p Port) Proto() string { - parts := strings.Split(string(p), "/") - if len(parts) == 1 { - return "tcp" - } - return parts[1] -} - -// State represents the state of a container. -type State struct { - Status string `json:"Status,omitempty" yaml:"Status,omitempty"` - Running bool `json:"Running,omitempty" yaml:"Running,omitempty"` - Paused bool `json:"Paused,omitempty" yaml:"Paused,omitempty"` - Restarting bool `json:"Restarting,omitempty" yaml:"Restarting,omitempty"` - OOMKilled bool `json:"OOMKilled,omitempty" yaml:"OOMKilled,omitempty"` - RemovalInProgress bool `json:"RemovalInProgress,omitempty" yaml:"RemovalInProgress,omitempty"` - Dead bool `json:"Dead,omitempty" yaml:"Dead,omitempty"` - Pid int `json:"Pid,omitempty" yaml:"Pid,omitempty"` - ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty"` - Error string `json:"Error,omitempty" yaml:"Error,omitempty"` - StartedAt time.Time `json:"StartedAt,omitempty" yaml:"StartedAt,omitempty"` - FinishedAt time.Time `json:"FinishedAt,omitempty" yaml:"FinishedAt,omitempty"` -} - -// String returns a human-readable description of the state -func (s *State) String() string { - if s.Running { - if s.Paused { - return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) - } - if s.Restarting { - return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) - } - - return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) - } - - if s.RemovalInProgress { - return "Removal In Progress" - } - - if s.Dead { - return "Dead" - } - - if s.StartedAt.IsZero() { - return "Created" - } - - if s.FinishedAt.IsZero() { - return "" - } - - return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) -} - -// StateString returns a single string to describe state -func (s *State) StateString() string { - if s.Running { - if s.Paused { - return "paused" - } - if s.Restarting { - return "restarting" - } - return "running" - } - - if s.Dead { - return "dead" - } - - if s.StartedAt.IsZero() { - return "created" - } - - return "exited" -} - -// PortBinding represents the host/container port mapping as returned in the -// `docker inspect` json -type PortBinding struct { - HostIP string `json:"HostIP,omitempty" yaml:"HostIP,omitempty"` - HostPort string `json:"HostPort,omitempty" yaml:"HostPort,omitempty"` -} - -// PortMapping represents a deprecated field in the `docker inspect` output, -// and its value as found in NetworkSettings should always be nil -type PortMapping map[string]string - -// ContainerNetwork represents the networking settings of a container per network. -type ContainerNetwork struct { - MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` - GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty"` - GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty"` - IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty"` - IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty"` - IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty"` - Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty"` - EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty"` - NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty"` -} - -// NetworkSettings contains network-related information about a container -type NetworkSettings struct { - Networks map[string]ContainerNetwork `json:"Networks,omitempty" yaml:"Networks,omitempty"` - IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty"` - IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty"` - MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` - Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty"` - Bridge string `json:"Bridge,omitempty" yaml:"Bridge,omitempty"` - PortMapping map[string]PortMapping `json:"PortMapping,omitempty" yaml:"PortMapping,omitempty"` - Ports map[Port][]PortBinding `json:"Ports,omitempty" yaml:"Ports,omitempty"` - NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty"` - EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty"` - SandboxKey string `json:"SandboxKey,omitempty" yaml:"SandboxKey,omitempty"` - GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty"` - GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty"` - IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty"` - LinkLocalIPv6Address string `json:"LinkLocalIPv6Address,omitempty" yaml:"LinkLocalIPv6Address,omitempty"` - LinkLocalIPv6PrefixLen int `json:"LinkLocalIPv6PrefixLen,omitempty" yaml:"LinkLocalIPv6PrefixLen,omitempty"` - SecondaryIPAddresses []string `json:"SecondaryIPAddresses,omitempty" yaml:"SecondaryIPAddresses,omitempty"` - SecondaryIPv6Addresses []string `json:"SecondaryIPv6Addresses,omitempty" yaml:"SecondaryIPv6Addresses,omitempty"` -} - -// PortMappingAPI translates the port mappings as contained in NetworkSettings -// into the format in which they would appear when returned by the API -func (settings *NetworkSettings) PortMappingAPI() []APIPort { - var mapping []APIPort - for port, bindings := range settings.Ports { - p, _ := parsePort(port.Port()) - if len(bindings) == 0 { - mapping = append(mapping, APIPort{ - PrivatePort: int64(p), - Type: port.Proto(), - }) - continue - } - for _, binding := range bindings { - p, _ := parsePort(port.Port()) - h, _ := parsePort(binding.HostPort) - mapping = append(mapping, APIPort{ - PrivatePort: int64(p), - PublicPort: int64(h), - Type: port.Proto(), - IP: binding.HostIP, - }) - } - } - return mapping -} - -func parsePort(rawPort string) (int, error) { - port, err := strconv.ParseUint(rawPort, 10, 16) - if err != nil { - return 0, err - } - return int(port), nil -} - -// Config is the list of configuration options used when creating a container. -// Config does not contain the options that are specific to starting a container on a -// given host. Those are contained in HostConfig -type Config struct { - Hostname string `json:"Hostname,omitempty" yaml:"Hostname,omitempty"` - Domainname string `json:"Domainname,omitempty" yaml:"Domainname,omitempty"` - User string `json:"User,omitempty" yaml:"User,omitempty"` - Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` - MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty"` - MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty"` - KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty"` - PidsLimit int64 `json:"PidsLimit,omitempty" yaml:"PidsLimit,omitempty"` - CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty"` - CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty"` - AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty"` - AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty"` - AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty"` - PortSpecs []string `json:"PortSpecs,omitempty" yaml:"PortSpecs,omitempty"` - ExposedPorts map[Port]struct{} `json:"ExposedPorts,omitempty" yaml:"ExposedPorts,omitempty"` - StopSignal string `json:"StopSignal,omitempty" yaml:"StopSignal,omitempty"` - Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` - OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty"` - StdinOnce bool `json:"StdinOnce,omitempty" yaml:"StdinOnce,omitempty"` - Env []string `json:"Env,omitempty" yaml:"Env,omitempty"` - Cmd []string `json:"Cmd" yaml:"Cmd"` - DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty"` // For Docker API v1.9 and below only - Image string `json:"Image,omitempty" yaml:"Image,omitempty"` - Volumes map[string]struct{} `json:"Volumes,omitempty" yaml:"Volumes,omitempty"` - VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty"` - VolumesFrom string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty"` - WorkingDir string `json:"WorkingDir,omitempty" yaml:"WorkingDir,omitempty"` - MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` - Entrypoint []string `json:"Entrypoint" yaml:"Entrypoint"` - NetworkDisabled bool `json:"NetworkDisabled,omitempty" yaml:"NetworkDisabled,omitempty"` - SecurityOpts []string `json:"SecurityOpts,omitempty" yaml:"SecurityOpts,omitempty"` - OnBuild []string `json:"OnBuild,omitempty" yaml:"OnBuild,omitempty"` - Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty"` - Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` -} - -// Mount represents a mount point in the container. -// -// It has been added in the version 1.20 of the Docker API, available since -// Docker 1.8. -type Mount struct { - Name string - Source string - Destination string - Driver string - Mode string - RW bool -} - -// LogConfig defines the log driver type and the configuration for it. -type LogConfig struct { - Type string `json:"Type,omitempty" yaml:"Type,omitempty"` - Config map[string]string `json:"Config,omitempty" yaml:"Config,omitempty"` -} - -// ULimit defines system-wide resource limitations -// This can help a lot in system administration, e.g. when a user starts too many processes and therefore makes the system unresponsive for other users. -type ULimit struct { - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - Soft int64 `json:"Soft,omitempty" yaml:"Soft,omitempty"` - Hard int64 `json:"Hard,omitempty" yaml:"Hard,omitempty"` -} - -// SwarmNode containers information about which Swarm node the container is on -type SwarmNode struct { - ID string `json:"ID,omitempty" yaml:"ID,omitempty"` - IP string `json:"IP,omitempty" yaml:"IP,omitempty"` - Addr string `json:"Addr,omitempty" yaml:"Addr,omitempty"` - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - CPUs int64 `json:"CPUs,omitempty" yaml:"CPUs,omitempty"` - Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` - Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` -} - -// GraphDriver contains information about the GraphDriver used by the container -type GraphDriver struct { - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - Data map[string]string `json:"Data,omitempty" yaml:"Data,omitempty"` -} - -// Container is the type encompasing everything about a container - its config, -// hostconfig, etc. -type Container struct { - ID string `json:"Id" yaml:"Id"` - - Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty"` - - Path string `json:"Path,omitempty" yaml:"Path,omitempty"` - Args []string `json:"Args,omitempty" yaml:"Args,omitempty"` - - Config *Config `json:"Config,omitempty" yaml:"Config,omitempty"` - State State `json:"State,omitempty" yaml:"State,omitempty"` - Image string `json:"Image,omitempty" yaml:"Image,omitempty"` - - Node *SwarmNode `json:"Node,omitempty" yaml:"Node,omitempty"` - - NetworkSettings *NetworkSettings `json:"NetworkSettings,omitempty" yaml:"NetworkSettings,omitempty"` - - SysInitPath string `json:"SysInitPath,omitempty" yaml:"SysInitPath,omitempty"` - ResolvConfPath string `json:"ResolvConfPath,omitempty" yaml:"ResolvConfPath,omitempty"` - HostnamePath string `json:"HostnamePath,omitempty" yaml:"HostnamePath,omitempty"` - HostsPath string `json:"HostsPath,omitempty" yaml:"HostsPath,omitempty"` - LogPath string `json:"LogPath,omitempty" yaml:"LogPath,omitempty"` - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty"` - Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty"` - - Volumes map[string]string `json:"Volumes,omitempty" yaml:"Volumes,omitempty"` - VolumesRW map[string]bool `json:"VolumesRW,omitempty" yaml:"VolumesRW,omitempty"` - HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty"` - ExecIDs []string `json:"ExecIDs,omitempty" yaml:"ExecIDs,omitempty"` - GraphDriver *GraphDriver `json:"GraphDriver,omitempty" yaml:"GraphDriver,omitempty"` - - RestartCount int `json:"RestartCount,omitempty" yaml:"RestartCount,omitempty"` - - AppArmorProfile string `json:"AppArmorProfile,omitempty" yaml:"AppArmorProfile,omitempty"` -} - -// UpdateContainerOptions specify parameters to the UpdateContainer function. -// -// See https://goo.gl/Y6fXUy for more details. -type UpdateContainerOptions struct { - BlkioWeight int `json:"BlkioWeight"` - CPUShares int `json:"CpuShares"` - CPUPeriod int `json:"CpuPeriod"` - CPUQuota int `json:"CpuQuota"` - CpusetCpus string `json:"CpusetCpus"` - CpusetMems string `json:"CpusetMems"` - Memory int `json:"Memory"` - MemorySwap int `json:"MemorySwap"` - MemoryReservation int `json:"MemoryReservation"` - KernelMemory int `json:"KernelMemory"` - RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty"` -} - -// UpdateContainer updates the container at ID with the options -// -// See https://goo.gl/Y6fXUy for more details. -func (c *Client) UpdateContainer(id string, opts UpdateContainerOptions) error { - resp, err := c.do("POST", fmt.Sprintf("/containers/"+id+"/update"), doOptions{data: opts, forceJSON: true}) - if err != nil { - return err - } - defer resp.Body.Close() - return nil -} - -// RenameContainerOptions specify parameters to the RenameContainer function. -// -// See https://goo.gl/laSOIy for more details. -type RenameContainerOptions struct { - // ID of container to rename - ID string `qs:"-"` - - // New name - Name string `json:"name,omitempty" yaml:"name,omitempty"` -} - -// RenameContainer updates and existing containers name -// -// See https://goo.gl/laSOIy for more details. -func (c *Client) RenameContainer(opts RenameContainerOptions) error { - resp, err := c.do("POST", fmt.Sprintf("/containers/"+opts.ID+"/rename?%s", queryString(opts)), doOptions{}) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// InspectContainer returns information about a container by its ID. -// -// See https://goo.gl/RdIq0b for more details. -func (c *Client) InspectContainer(id string) (*Container, error) { - path := "/containers/" + id + "/json" - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchContainer{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var container Container - if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { - return nil, err - } - return &container, nil -} - -// ContainerChanges returns changes in the filesystem of the given container. -// -// See https://goo.gl/9GsTIF for more details. -func (c *Client) ContainerChanges(id string) ([]Change, error) { - path := "/containers/" + id + "/changes" - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchContainer{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var changes []Change - if err := json.NewDecoder(resp.Body).Decode(&changes); err != nil { - return nil, err - } - return changes, nil -} - -// CreateContainerOptions specify parameters to the CreateContainer function. -// -// See https://goo.gl/WxQzrr for more details. -type CreateContainerOptions struct { - Name string - Config *Config `qs:"-"` - HostConfig *HostConfig `qs:"-"` -} - -// CreateContainer creates a new container, returning the container instance, -// or an error in case of failure. -// -// See https://goo.gl/WxQzrr for more details. -func (c *Client) CreateContainer(opts CreateContainerOptions) (*Container, error) { - path := "/containers/create?" + queryString(opts) - resp, err := c.do( - "POST", - path, - doOptions{ - data: struct { - *Config - HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty"` - }{ - opts.Config, - opts.HostConfig, - }, - }, - ) - - if e, ok := err.(*Error); ok { - if e.Status == http.StatusNotFound { - return nil, ErrNoSuchImage - } - if e.Status == http.StatusConflict { - return nil, ErrContainerAlreadyExists - } - } - - if err != nil { - return nil, err - } - defer resp.Body.Close() - var container Container - if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { - return nil, err - } - - container.Name = opts.Name - - return &container, nil -} - -// KeyValuePair is a type for generic key/value pairs as used in the Lxc -// configuration -type KeyValuePair struct { - Key string `json:"Key,omitempty" yaml:"Key,omitempty"` - Value string `json:"Value,omitempty" yaml:"Value,omitempty"` -} - -// RestartPolicy represents the policy for automatically restarting a container. -// -// Possible values are: -// -// - always: the docker daemon will always restart the container -// - on-failure: the docker daemon will restart the container on failures, at -// most MaximumRetryCount times -// - no: the docker daemon will not restart the container automatically -type RestartPolicy struct { - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - MaximumRetryCount int `json:"MaximumRetryCount,omitempty" yaml:"MaximumRetryCount,omitempty"` -} - -// AlwaysRestart returns a restart policy that tells the Docker daemon to -// always restart the container. -func AlwaysRestart() RestartPolicy { - return RestartPolicy{Name: "always"} -} - -// RestartOnFailure returns a restart policy that tells the Docker daemon to -// restart the container on failures, trying at most maxRetry times. -func RestartOnFailure(maxRetry int) RestartPolicy { - return RestartPolicy{Name: "on-failure", MaximumRetryCount: maxRetry} -} - -// NeverRestart returns a restart policy that tells the Docker daemon to never -// restart the container on failures. -func NeverRestart() RestartPolicy { - return RestartPolicy{Name: "no"} -} - -// Device represents a device mapping between the Docker host and the -// container. -type Device struct { - PathOnHost string `json:"PathOnHost,omitempty" yaml:"PathOnHost,omitempty"` - PathInContainer string `json:"PathInContainer,omitempty" yaml:"PathInContainer,omitempty"` - CgroupPermissions string `json:"CgroupPermissions,omitempty" yaml:"CgroupPermissions,omitempty"` -} - -// BlockWeight represents a relative device weight for an individual device inside -// of a container -// -// See https://goo.gl/FSdP0H for more details. -type BlockWeight struct { - Path string `json:"Path,omitempty"` - Weight string `json:"Weight,omitempty"` -} - -// BlockLimit represents a read/write limit in IOPS or Bandwidth for a device -// inside of a container -// -// See https://goo.gl/FSdP0H for more details. -type BlockLimit struct { - Path string `json:"Path,omitempty"` - Rate string `json:"Rate,omitempty"` -} - -// HostConfig contains the container options related to starting a container on -// a given host -type HostConfig struct { - Binds []string `json:"Binds,omitempty" yaml:"Binds,omitempty"` - CapAdd []string `json:"CapAdd,omitempty" yaml:"CapAdd,omitempty"` - CapDrop []string `json:"CapDrop,omitempty" yaml:"CapDrop,omitempty"` - GroupAdd []string `json:"GroupAdd,omitempty" yaml:"GroupAdd,omitempty"` - ContainerIDFile string `json:"ContainerIDFile,omitempty" yaml:"ContainerIDFile,omitempty"` - LxcConf []KeyValuePair `json:"LxcConf,omitempty" yaml:"LxcConf,omitempty"` - Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty"` - PortBindings map[Port][]PortBinding `json:"PortBindings,omitempty" yaml:"PortBindings,omitempty"` - Links []string `json:"Links,omitempty" yaml:"Links,omitempty"` - PublishAllPorts bool `json:"PublishAllPorts,omitempty" yaml:"PublishAllPorts,omitempty"` - DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty"` // For Docker API v1.10 and above only - DNSOptions []string `json:"DnsOptions,omitempty" yaml:"DnsOptions,omitempty"` - DNSSearch []string `json:"DnsSearch,omitempty" yaml:"DnsSearch,omitempty"` - ExtraHosts []string `json:"ExtraHosts,omitempty" yaml:"ExtraHosts,omitempty"` - VolumesFrom []string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty"` - UsernsMode string `json:"UsernsMode,omitempty" yaml:"UsernsMode,omitempty"` - NetworkMode string `json:"NetworkMode,omitempty" yaml:"NetworkMode,omitempty"` - IpcMode string `json:"IpcMode,omitempty" yaml:"IpcMode,omitempty"` - PidMode string `json:"PidMode,omitempty" yaml:"PidMode,omitempty"` - UTSMode string `json:"UTSMode,omitempty" yaml:"UTSMode,omitempty"` - RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty" yaml:"RestartPolicy,omitempty"` - Devices []Device `json:"Devices,omitempty" yaml:"Devices,omitempty"` - LogConfig LogConfig `json:"LogConfig,omitempty" yaml:"LogConfig,omitempty"` - ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty" yaml:"ReadonlyRootfs,omitempty"` - SecurityOpt []string `json:"SecurityOpt,omitempty" yaml:"SecurityOpt,omitempty"` - CgroupParent string `json:"CgroupParent,omitempty" yaml:"CgroupParent,omitempty"` - Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` - MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty"` - MemorySwappiness int64 `json:"MemorySwappiness,omitempty" yaml:"MemorySwappiness,omitempty"` - OOMKillDisable bool `json:"OomKillDisable,omitempty" yaml:"OomKillDisable"` - CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty"` - CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty"` - CPUSetCPUs string `json:"CpusetCpus,omitempty" yaml:"CpusetCpus,omitempty"` - CPUSetMEMs string `json:"CpusetMems,omitempty" yaml:"CpusetMems,omitempty"` - CPUQuota int64 `json:"CpuQuota,omitempty" yaml:"CpuQuota,omitempty"` - CPUPeriod int64 `json:"CpuPeriod,omitempty" yaml:"CpuPeriod,omitempty"` - BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight"` - BlkioWeightDevice []BlockWeight `json:"BlkioWeightDevice,omitempty" yaml:"BlkioWeightDevice"` - BlkioDeviceReadBps []BlockLimit `json:"BlkioDeviceReadBps,omitempty" yaml:"BlkioDeviceReadBps"` - BlkioDeviceReadIOps []BlockLimit `json:"BlkioDeviceReadIOps,omitempty" yaml:"BlkioDeviceReadIOps"` - BlkioDeviceWriteBps []BlockLimit `json:"BlkioDeviceWriteBps,omitempty" yaml:"BlkioDeviceWriteBps"` - BlkioDeviceWriteIOps []BlockLimit `json:"BlkioDeviceWriteIOps,omitempty" yaml:"BlkioDeviceWriteIOps"` - Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty"` - VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty"` - OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty"` - ShmSize int64 `json:"ShmSize,omitempty" yaml:"ShmSize,omitempty"` -} - -// StartContainer starts a container, returning an error in case of failure. -// -// See https://goo.gl/MrBAJv for more details. -func (c *Client) StartContainer(id string, hostConfig *HostConfig) error { - path := "/containers/" + id + "/start" - resp, err := c.do("POST", path, doOptions{data: hostConfig, forceJSON: true}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: id, Err: err} - } - return err - } - if resp.StatusCode == http.StatusNotModified { - return &ContainerAlreadyRunning{ID: id} - } - resp.Body.Close() - return nil -} - -// StopContainer stops a container, killing it after the given timeout (in -// seconds). -// -// See https://goo.gl/USqsFt for more details. -func (c *Client) StopContainer(id string, timeout uint) error { - path := fmt.Sprintf("/containers/%s/stop?t=%d", id, timeout) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: id} - } - return err - } - if resp.StatusCode == http.StatusNotModified { - return &ContainerNotRunning{ID: id} - } - resp.Body.Close() - return nil -} - -// RestartContainer stops a container, killing it after the given timeout (in -// seconds), during the stop process. -// -// See https://goo.gl/QzsDnz for more details. -func (c *Client) RestartContainer(id string, timeout uint) error { - path := fmt.Sprintf("/containers/%s/restart?t=%d", id, timeout) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: id} - } - return err - } - resp.Body.Close() - return nil -} - -// PauseContainer pauses the given container. -// -// See https://goo.gl/OF7W9X for more details. -func (c *Client) PauseContainer(id string) error { - path := fmt.Sprintf("/containers/%s/pause", id) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: id} - } - return err - } - resp.Body.Close() - return nil -} - -// UnpauseContainer unpauses the given container. -// -// See https://goo.gl/7dwyPA for more details. -func (c *Client) UnpauseContainer(id string) error { - path := fmt.Sprintf("/containers/%s/unpause", id) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: id} - } - return err - } - resp.Body.Close() - return nil -} - -// TopResult represents the list of processes running in a container, as -// returned by /containers//top. -// -// See https://goo.gl/Rb46aY for more details. -type TopResult struct { - Titles []string - Processes [][]string -} - -// TopContainer returns processes running inside a container -// -// See https://goo.gl/Rb46aY for more details. -func (c *Client) TopContainer(id string, psArgs string) (TopResult, error) { - var args string - var result TopResult - if psArgs != "" { - args = fmt.Sprintf("?ps_args=%s", psArgs) - } - path := fmt.Sprintf("/containers/%s/top%s", id, args) - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return result, &NoSuchContainer{ID: id} - } - return result, err - } - defer resp.Body.Close() - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return result, err - } - return result, nil -} - -// Stats represents container statistics, returned by /containers//stats. -// -// See https://goo.gl/GNmLHb for more details. -type Stats struct { - Read time.Time `json:"read,omitempty" yaml:"read,omitempty"` - PidsStats struct { - Current uint64 `json:"current,omitempty" yaml:"current,omitempty"` - } `json:"pids_stats,omitempty" yaml:"pids_stats,omitempty"` - Network NetworkStats `json:"network,omitempty" yaml:"network,omitempty"` - Networks map[string]NetworkStats `json:"networks,omitempty" yaml:"networks,omitempty"` - MemoryStats struct { - Stats struct { - TotalPgmafault uint64 `json:"total_pgmafault,omitempty" yaml:"total_pgmafault,omitempty"` - Cache uint64 `json:"cache,omitempty" yaml:"cache,omitempty"` - MappedFile uint64 `json:"mapped_file,omitempty" yaml:"mapped_file,omitempty"` - TotalInactiveFile uint64 `json:"total_inactive_file,omitempty" yaml:"total_inactive_file,omitempty"` - Pgpgout uint64 `json:"pgpgout,omitempty" yaml:"pgpgout,omitempty"` - Rss uint64 `json:"rss,omitempty" yaml:"rss,omitempty"` - TotalMappedFile uint64 `json:"total_mapped_file,omitempty" yaml:"total_mapped_file,omitempty"` - Writeback uint64 `json:"writeback,omitempty" yaml:"writeback,omitempty"` - Unevictable uint64 `json:"unevictable,omitempty" yaml:"unevictable,omitempty"` - Pgpgin uint64 `json:"pgpgin,omitempty" yaml:"pgpgin,omitempty"` - TotalUnevictable uint64 `json:"total_unevictable,omitempty" yaml:"total_unevictable,omitempty"` - Pgmajfault uint64 `json:"pgmajfault,omitempty" yaml:"pgmajfault,omitempty"` - TotalRss uint64 `json:"total_rss,omitempty" yaml:"total_rss,omitempty"` - TotalRssHuge uint64 `json:"total_rss_huge,omitempty" yaml:"total_rss_huge,omitempty"` - TotalWriteback uint64 `json:"total_writeback,omitempty" yaml:"total_writeback,omitempty"` - TotalInactiveAnon uint64 `json:"total_inactive_anon,omitempty" yaml:"total_inactive_anon,omitempty"` - RssHuge uint64 `json:"rss_huge,omitempty" yaml:"rss_huge,omitempty"` - HierarchicalMemoryLimit uint64 `json:"hierarchical_memory_limit,omitempty" yaml:"hierarchical_memory_limit,omitempty"` - TotalPgfault uint64 `json:"total_pgfault,omitempty" yaml:"total_pgfault,omitempty"` - TotalActiveFile uint64 `json:"total_active_file,omitempty" yaml:"total_active_file,omitempty"` - ActiveAnon uint64 `json:"active_anon,omitempty" yaml:"active_anon,omitempty"` - TotalActiveAnon uint64 `json:"total_active_anon,omitempty" yaml:"total_active_anon,omitempty"` - TotalPgpgout uint64 `json:"total_pgpgout,omitempty" yaml:"total_pgpgout,omitempty"` - TotalCache uint64 `json:"total_cache,omitempty" yaml:"total_cache,omitempty"` - InactiveAnon uint64 `json:"inactive_anon,omitempty" yaml:"inactive_anon,omitempty"` - ActiveFile uint64 `json:"active_file,omitempty" yaml:"active_file,omitempty"` - Pgfault uint64 `json:"pgfault,omitempty" yaml:"pgfault,omitempty"` - InactiveFile uint64 `json:"inactive_file,omitempty" yaml:"inactive_file,omitempty"` - TotalPgpgin uint64 `json:"total_pgpgin,omitempty" yaml:"total_pgpgin,omitempty"` - HierarchicalMemswLimit uint64 `json:"hierarchical_memsw_limit,omitempty" yaml:"hierarchical_memsw_limit,omitempty"` - Swap uint64 `json:"swap,omitempty" yaml:"swap,omitempty"` - } `json:"stats,omitempty" yaml:"stats,omitempty"` - MaxUsage uint64 `json:"max_usage,omitempty" yaml:"max_usage,omitempty"` - Usage uint64 `json:"usage,omitempty" yaml:"usage,omitempty"` - Failcnt uint64 `json:"failcnt,omitempty" yaml:"failcnt,omitempty"` - Limit uint64 `json:"limit,omitempty" yaml:"limit,omitempty"` - } `json:"memory_stats,omitempty" yaml:"memory_stats,omitempty"` - BlkioStats struct { - IOServiceBytesRecursive []BlkioStatsEntry `json:"io_service_bytes_recursive,omitempty" yaml:"io_service_bytes_recursive,omitempty"` - IOServicedRecursive []BlkioStatsEntry `json:"io_serviced_recursive,omitempty" yaml:"io_serviced_recursive,omitempty"` - IOQueueRecursive []BlkioStatsEntry `json:"io_queue_recursive,omitempty" yaml:"io_queue_recursive,omitempty"` - IOServiceTimeRecursive []BlkioStatsEntry `json:"io_service_time_recursive,omitempty" yaml:"io_service_time_recursive,omitempty"` - IOWaitTimeRecursive []BlkioStatsEntry `json:"io_wait_time_recursive,omitempty" yaml:"io_wait_time_recursive,omitempty"` - IOMergedRecursive []BlkioStatsEntry `json:"io_merged_recursive,omitempty" yaml:"io_merged_recursive,omitempty"` - IOTimeRecursive []BlkioStatsEntry `json:"io_time_recursive,omitempty" yaml:"io_time_recursive,omitempty"` - SectorsRecursive []BlkioStatsEntry `json:"sectors_recursive,omitempty" yaml:"sectors_recursive,omitempty"` - } `json:"blkio_stats,omitempty" yaml:"blkio_stats,omitempty"` - CPUStats CPUStats `json:"cpu_stats,omitempty" yaml:"cpu_stats,omitempty"` - PreCPUStats CPUStats `json:"precpu_stats,omitempty"` -} - -// NetworkStats is a stats entry for network stats -type NetworkStats struct { - RxDropped uint64 `json:"rx_dropped,omitempty" yaml:"rx_dropped,omitempty"` - RxBytes uint64 `json:"rx_bytes,omitempty" yaml:"rx_bytes,omitempty"` - RxErrors uint64 `json:"rx_errors,omitempty" yaml:"rx_errors,omitempty"` - TxPackets uint64 `json:"tx_packets,omitempty" yaml:"tx_packets,omitempty"` - TxDropped uint64 `json:"tx_dropped,omitempty" yaml:"tx_dropped,omitempty"` - RxPackets uint64 `json:"rx_packets,omitempty" yaml:"rx_packets,omitempty"` - TxErrors uint64 `json:"tx_errors,omitempty" yaml:"tx_errors,omitempty"` - TxBytes uint64 `json:"tx_bytes,omitempty" yaml:"tx_bytes,omitempty"` -} - -// CPUStats is a stats entry for cpu stats -type CPUStats struct { - CPUUsage struct { - PercpuUsage []uint64 `json:"percpu_usage,omitempty" yaml:"percpu_usage,omitempty"` - UsageInUsermode uint64 `json:"usage_in_usermode,omitempty" yaml:"usage_in_usermode,omitempty"` - TotalUsage uint64 `json:"total_usage,omitempty" yaml:"total_usage,omitempty"` - UsageInKernelmode uint64 `json:"usage_in_kernelmode,omitempty" yaml:"usage_in_kernelmode,omitempty"` - } `json:"cpu_usage,omitempty" yaml:"cpu_usage,omitempty"` - SystemCPUUsage uint64 `json:"system_cpu_usage,omitempty" yaml:"system_cpu_usage,omitempty"` - ThrottlingData struct { - Periods uint64 `json:"periods,omitempty"` - ThrottledPeriods uint64 `json:"throttled_periods,omitempty"` - ThrottledTime uint64 `json:"throttled_time,omitempty"` - } `json:"throttling_data,omitempty" yaml:"throttling_data,omitempty"` -} - -// BlkioStatsEntry is a stats entry for blkio_stats -type BlkioStatsEntry struct { - Major uint64 `json:"major,omitempty" yaml:"major,omitempty"` - Minor uint64 `json:"minor,omitempty" yaml:"minor,omitempty"` - Op string `json:"op,omitempty" yaml:"op,omitempty"` - Value uint64 `json:"value,omitempty" yaml:"value,omitempty"` -} - -// StatsOptions specify parameters to the Stats function. -// -// See https://goo.gl/GNmLHb for more details. -type StatsOptions struct { - ID string - Stats chan<- *Stats - Stream bool - // A flag that enables stopping the stats operation - Done <-chan bool - // Initial connection timeout - Timeout time.Duration - // Timeout with no data is received, it's reset every time new data - // arrives - InactivityTimeout time.Duration `qs:"-"` -} - -// Stats sends container statistics for the given container to the given channel. -// -// This function is blocking, similar to a streaming call for logs, and should be run -// on a separate goroutine from the caller. Note that this function will block until -// the given container is removed, not just exited. When finished, this function -// will close the given channel. Alternatively, function can be stopped by -// signaling on the Done channel. -// -// See https://goo.gl/GNmLHb for more details. -func (c *Client) Stats(opts StatsOptions) (retErr error) { - errC := make(chan error, 1) - readCloser, writeCloser := io.Pipe() - - defer func() { - close(opts.Stats) - - select { - case err := <-errC: - if err != nil && retErr == nil { - retErr = err - } - default: - // No errors - } - - if err := readCloser.Close(); err != nil && retErr == nil { - retErr = err - } - }() - - go func() { - err := c.stream("GET", fmt.Sprintf("/containers/%s/stats?stream=%v", opts.ID, opts.Stream), streamOptions{ - rawJSONStream: true, - useJSONDecoder: true, - stdout: writeCloser, - timeout: opts.Timeout, - inactivityTimeout: opts.InactivityTimeout, - }) - if err != nil { - dockerError, ok := err.(*Error) - if ok { - if dockerError.Status == http.StatusNotFound { - err = &NoSuchContainer{ID: opts.ID} - } - } - } - if closeErr := writeCloser.Close(); closeErr != nil && err == nil { - err = closeErr - } - errC <- err - close(errC) - }() - - quit := make(chan struct{}) - defer close(quit) - go func() { - // block here waiting for the signal to stop function - select { - case <-opts.Done: - readCloser.Close() - case <-quit: - return - } - }() - - decoder := json.NewDecoder(readCloser) - stats := new(Stats) - for err := decoder.Decode(stats); err != io.EOF; err = decoder.Decode(stats) { - if err != nil { - return err - } - opts.Stats <- stats - stats = new(Stats) - } - return nil -} - -// KillContainerOptions represents the set of options that can be used in a -// call to KillContainer. -// -// See https://goo.gl/hkS9i8 for more details. -type KillContainerOptions struct { - // The ID of the container. - ID string `qs:"-"` - - // The signal to send to the container. When omitted, Docker server - // will assume SIGKILL. - Signal Signal -} - -// KillContainer sends a signal to a container, returning an error in case of -// failure. -// -// See https://goo.gl/hkS9i8 for more details. -func (c *Client) KillContainer(opts KillContainerOptions) error { - path := "/containers/" + opts.ID + "/kill" + "?" + queryString(opts) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} - -// RemoveContainerOptions encapsulates options to remove a container. -// -// See https://goo.gl/RQyX62 for more details. -type RemoveContainerOptions struct { - // The ID of the container. - ID string `qs:"-"` - - // A flag that indicates whether Docker should remove the volumes - // associated to the container. - RemoveVolumes bool `qs:"v"` - - // A flag that indicates whether Docker should remove the container - // even if it is currently running. - Force bool -} - -// RemoveContainer removes a container, returning an error in case of failure. -// -// See https://goo.gl/RQyX62 for more details. -func (c *Client) RemoveContainer(opts RemoveContainerOptions) error { - path := "/containers/" + opts.ID + "?" + queryString(opts) - resp, err := c.do("DELETE", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: opts.ID} - } - return err - } - resp.Body.Close() - return nil -} - -// UploadToContainerOptions is the set of options that can be used when -// uploading an archive into a container. -// -// See https://goo.gl/Ss97HW for more details. -type UploadToContainerOptions struct { - InputStream io.Reader `json:"-" qs:"-"` - Path string `qs:"path"` - NoOverwriteDirNonDir bool `qs:"noOverwriteDirNonDir"` -} - -// UploadToContainer uploads a tar archive to be extracted to a path in the -// filesystem of the container. -// -// See https://goo.gl/Ss97HW for more details. -func (c *Client) UploadToContainer(id string, opts UploadToContainerOptions) error { - url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) - - return c.stream("PUT", url, streamOptions{ - in: opts.InputStream, - }) -} - -// DownloadFromContainerOptions is the set of options that can be used when -// downloading resources from a container. -// -// See https://goo.gl/KnZJDX for more details. -type DownloadFromContainerOptions struct { - OutputStream io.Writer `json:"-" qs:"-"` - Path string `qs:"path"` - InactivityTimeout time.Duration `qs:"-"` -} - -// DownloadFromContainer downloads a tar archive of files or folders in a container. -// -// See https://goo.gl/KnZJDX for more details. -func (c *Client) DownloadFromContainer(id string, opts DownloadFromContainerOptions) error { - url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) - - return c.stream("GET", url, streamOptions{ - setRawTerminal: true, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// CopyFromContainerOptions has been DEPRECATED, please use DownloadFromContainerOptions along with DownloadFromContainer. -// -// See https://goo.gl/R2jevW for more details. -type CopyFromContainerOptions struct { - OutputStream io.Writer `json:"-"` - Container string `json:"-"` - Resource string -} - -// CopyFromContainer has been DEPRECATED, please use DownloadFromContainerOptions along with DownloadFromContainer. -// -// See https://goo.gl/R2jevW for more details. -func (c *Client) CopyFromContainer(opts CopyFromContainerOptions) error { - if opts.Container == "" { - return &NoSuchContainer{ID: opts.Container} - } - url := fmt.Sprintf("/containers/%s/copy", opts.Container) - resp, err := c.do("POST", url, doOptions{data: opts}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchContainer{ID: opts.Container} - } - return err - } - defer resp.Body.Close() - _, err = io.Copy(opts.OutputStream, resp.Body) - return err -} - -// WaitContainer blocks until the given container stops, return the exit code -// of the container status. -// -// See https://goo.gl/Gc1rge for more details. -func (c *Client) WaitContainer(id string) (int, error) { - resp, err := c.do("POST", "/containers/"+id+"/wait", doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return 0, &NoSuchContainer{ID: id} - } - return 0, err - } - defer resp.Body.Close() - var r struct{ StatusCode int } - if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { - return 0, err - } - return r.StatusCode, nil -} - -// CommitContainerOptions aggregates parameters to the CommitContainer method. -// -// See https://goo.gl/mqfoCw for more details. -type CommitContainerOptions struct { - Container string - Repository string `qs:"repo"` - Tag string - Message string `qs:"comment"` - Author string - Run *Config `qs:"-"` -} - -// CommitContainer creates a new image from a container's changes. -// -// See https://goo.gl/mqfoCw for more details. -func (c *Client) CommitContainer(opts CommitContainerOptions) (*Image, error) { - path := "/commit?" + queryString(opts) - resp, err := c.do("POST", path, doOptions{data: opts.Run}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchContainer{ID: opts.Container} - } - return nil, err - } - defer resp.Body.Close() - var image Image - if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { - return nil, err - } - return &image, nil -} - -// AttachToContainerOptions is the set of options that can be used when -// attaching to a container. -// -// See https://goo.gl/NKpkFk for more details. -type AttachToContainerOptions struct { - Container string `qs:"-"` - InputStream io.Reader `qs:"-"` - OutputStream io.Writer `qs:"-"` - ErrorStream io.Writer `qs:"-"` - - // Get container logs, sending it to OutputStream. - Logs bool - - // Stream the response? - Stream bool - - // Attach to stdin, and use InputStream. - Stdin bool - - // Attach to stdout, and use OutputStream. - Stdout bool - - // Attach to stderr, and use ErrorStream. - Stderr bool - - // If set, after a successful connect, a sentinel will be sent and then the - // client will block on receive before continuing. - // - // It must be an unbuffered channel. Using a buffered channel can lead - // to unexpected behavior. - Success chan struct{} - - // Use raw terminal? Usually true when the container contains a TTY. - RawTerminal bool `qs:"-"` -} - -// AttachToContainer attaches to a container, using the given options. -// -// See https://goo.gl/NKpkFk for more details. -func (c *Client) AttachToContainer(opts AttachToContainerOptions) error { - cw, err := c.AttachToContainerNonBlocking(opts) - if err != nil { - return err - } - return cw.Wait() -} - -// AttachToContainerNonBlocking attaches to a container, using the given options. -// This function does not block. -// -// See https://goo.gl/NKpkFk for more details. -func (c *Client) AttachToContainerNonBlocking(opts AttachToContainerOptions) (CloseWaiter, error) { - if opts.Container == "" { - return nil, &NoSuchContainer{ID: opts.Container} - } - path := "/containers/" + opts.Container + "/attach?" + queryString(opts) - return c.hijack("POST", path, hijackOptions{ - success: opts.Success, - setRawTerminal: opts.RawTerminal, - in: opts.InputStream, - stdout: opts.OutputStream, - stderr: opts.ErrorStream, - }) -} - -// LogsOptions represents the set of options used when getting logs from a -// container. -// -// See https://goo.gl/yl8PGm for more details. -type LogsOptions struct { - Container string `qs:"-"` - OutputStream io.Writer `qs:"-"` - ErrorStream io.Writer `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` - Follow bool - Stdout bool - Stderr bool - Since int64 - Timestamps bool - Tail string - - // Use raw terminal? Usually true when the container contains a TTY. - RawTerminal bool `qs:"-"` -} - -// Logs gets stdout and stderr logs from the specified container. -// -// See https://goo.gl/yl8PGm for more details. -func (c *Client) Logs(opts LogsOptions) error { - if opts.Container == "" { - return &NoSuchContainer{ID: opts.Container} - } - if opts.Tail == "" { - opts.Tail = "all" - } - path := "/containers/" + opts.Container + "/logs?" + queryString(opts) - return c.stream("GET", path, streamOptions{ - setRawTerminal: opts.RawTerminal, - stdout: opts.OutputStream, - stderr: opts.ErrorStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// ResizeContainerTTY resizes the terminal to the given height and width. -// -// See https://goo.gl/xERhCc for more details. -func (c *Client) ResizeContainerTTY(id string, height, width int) error { - params := make(url.Values) - params.Set("h", strconv.Itoa(height)) - params.Set("w", strconv.Itoa(width)) - resp, err := c.do("POST", "/containers/"+id+"/resize?"+params.Encode(), doOptions{}) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// ExportContainerOptions is the set of parameters to the ExportContainer -// method. -// -// See https://goo.gl/dOkTyk for more details. -type ExportContainerOptions struct { - ID string - OutputStream io.Writer - InactivityTimeout time.Duration `qs:"-"` -} - -// ExportContainer export the contents of container id as tar archive -// and prints the exported contents to stdout. -// -// See https://goo.gl/dOkTyk for more details. -func (c *Client) ExportContainer(opts ExportContainerOptions) error { - if opts.ID == "" { - return &NoSuchContainer{ID: opts.ID} - } - url := fmt.Sprintf("/containers/%s/export", opts.ID) - return c.stream("GET", url, streamOptions{ - setRawTerminal: true, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// NoSuchContainer is the error returned when a given container does not exist. -type NoSuchContainer struct { - ID string - Err error -} - -func (err *NoSuchContainer) Error() string { - if err.Err != nil { - return err.Err.Error() - } - return "No such container: " + err.ID -} - -// ContainerAlreadyRunning is the error returned when a given container is -// already running. -type ContainerAlreadyRunning struct { - ID string -} - -func (err *ContainerAlreadyRunning) Error() string { - return "Container already running: " + err.ID -} - -// ContainerNotRunning is the error returned when a given container is not -// running. -type ContainerNotRunning struct { - ID string -} - -func (err *ContainerNotRunning) Error() string { - return "Container not running: " + err.ID -} diff --git a/vendor/github.com/fsouza/go-dockerclient/env.go b/vendor/github.com/fsouza/go-dockerclient/env.go deleted file mode 100644 index c54b0b0e8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/env.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2014 Docker authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the DOCKER-LICENSE file. - -package docker - -import ( - "encoding/json" - "fmt" - "io" - "strconv" - "strings" -) - -// Env represents a list of key-pair represented in the form KEY=VALUE. -type Env []string - -// Get returns the string value of the given key. -func (env *Env) Get(key string) (value string) { - return env.Map()[key] -} - -// Exists checks whether the given key is defined in the internal Env -// representation. -func (env *Env) Exists(key string) bool { - _, exists := env.Map()[key] - return exists -} - -// GetBool returns a boolean representation of the given key. The key is false -// whenever its value if 0, no, false, none or an empty string. Any other value -// will be interpreted as true. -func (env *Env) GetBool(key string) (value bool) { - s := strings.ToLower(strings.Trim(env.Get(key), " \t")) - if s == "" || s == "0" || s == "no" || s == "false" || s == "none" { - return false - } - return true -} - -// SetBool defines a boolean value to the given key. -func (env *Env) SetBool(key string, value bool) { - if value { - env.Set(key, "1") - } else { - env.Set(key, "0") - } -} - -// GetInt returns the value of the provided key, converted to int. -// -// It the value cannot be represented as an integer, it returns -1. -func (env *Env) GetInt(key string) int { - return int(env.GetInt64(key)) -} - -// SetInt defines an integer value to the given key. -func (env *Env) SetInt(key string, value int) { - env.Set(key, strconv.Itoa(value)) -} - -// GetInt64 returns the value of the provided key, converted to int64. -// -// It the value cannot be represented as an integer, it returns -1. -func (env *Env) GetInt64(key string) int64 { - s := strings.Trim(env.Get(key), " \t") - val, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return -1 - } - return val -} - -// SetInt64 defines an integer (64-bit wide) value to the given key. -func (env *Env) SetInt64(key string, value int64) { - env.Set(key, strconv.FormatInt(value, 10)) -} - -// GetJSON unmarshals the value of the provided key in the provided iface. -// -// iface is a value that can be provided to the json.Unmarshal function. -func (env *Env) GetJSON(key string, iface interface{}) error { - sval := env.Get(key) - if sval == "" { - return nil - } - return json.Unmarshal([]byte(sval), iface) -} - -// SetJSON marshals the given value to JSON format and stores it using the -// provided key. -func (env *Env) SetJSON(key string, value interface{}) error { - sval, err := json.Marshal(value) - if err != nil { - return err - } - env.Set(key, string(sval)) - return nil -} - -// GetList returns a list of strings matching the provided key. It handles the -// list as a JSON representation of a list of strings. -// -// If the given key matches to a single string, it will return a list -// containing only the value that matches the key. -func (env *Env) GetList(key string) []string { - sval := env.Get(key) - if sval == "" { - return nil - } - var l []string - if err := json.Unmarshal([]byte(sval), &l); err != nil { - l = append(l, sval) - } - return l -} - -// SetList stores the given list in the provided key, after serializing it to -// JSON format. -func (env *Env) SetList(key string, value []string) error { - return env.SetJSON(key, value) -} - -// Set defines the value of a key to the given string. -func (env *Env) Set(key, value string) { - *env = append(*env, key+"="+value) -} - -// Decode decodes `src` as a json dictionary, and adds each decoded key-value -// pair to the environment. -// -// If `src` cannot be decoded as a json dictionary, an error is returned. -func (env *Env) Decode(src io.Reader) error { - m := make(map[string]interface{}) - if err := json.NewDecoder(src).Decode(&m); err != nil { - return err - } - for k, v := range m { - env.SetAuto(k, v) - } - return nil -} - -// SetAuto will try to define the Set* method to call based on the given value. -func (env *Env) SetAuto(key string, value interface{}) { - if fval, ok := value.(float64); ok { - env.SetInt64(key, int64(fval)) - } else if sval, ok := value.(string); ok { - env.Set(key, sval) - } else if val, err := json.Marshal(value); err == nil { - env.Set(key, string(val)) - } else { - env.Set(key, fmt.Sprintf("%v", value)) - } -} - -// Map returns the map representation of the env. -func (env *Env) Map() map[string]string { - if len(*env) == 0 { - return nil - } - m := make(map[string]string) - for _, kv := range *env { - parts := strings.SplitN(kv, "=", 2) - m[parts[0]] = parts[1] - } - return m -} diff --git a/vendor/github.com/fsouza/go-dockerclient/event.go b/vendor/github.com/fsouza/go-dockerclient/event.go deleted file mode 100644 index 120cdc9bf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/event.go +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "math" - "net" - "net/http" - "net/http/httputil" - "sync" - "sync/atomic" - "time" -) - -// APIEvents represents events coming from the Docker API -// The fields in the Docker API changed in API version 1.22, and -// events for more than images and containers are now fired off. -// To maintain forward and backward compatibility, go-dockerclient -// replicates the event in both the new and old format as faithfully as possible. -// -// For events that only exist in 1.22 in later, `Status` is filled in as -// `"Type:Action"` instead of just `Action` to allow for older clients to -// differentiate and not break if they rely on the pre-1.22 Status types. -// -// The transformEvent method can be consulted for more information about how -// events are translated from new/old API formats -type APIEvents struct { - // New API Fields in 1.22 - Action string `json:"action,omitempty"` - Type string `json:"type,omitempty"` - Actor APIActor `json:"actor,omitempty"` - - // Old API fields for < 1.22 - Status string `json:"status,omitempty"` - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - - // Fields in both - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` -} - -// APIActor represents an actor that accomplishes something for an event -type APIActor struct { - ID string `json:"id,omitempty"` - Attributes map[string]string `json:"attributes,omitempty"` -} - -type eventMonitoringState struct { - sync.RWMutex - sync.WaitGroup - enabled bool - lastSeen int64 - C chan *APIEvents - errC chan error - listeners []chan<- *APIEvents -} - -const ( - maxMonitorConnRetries = 5 - retryInitialWaitTime = 10. -) - -var ( - // ErrNoListeners is the error returned when no listeners are available - // to receive an event. - ErrNoListeners = errors.New("no listeners present to receive event") - - // ErrListenerAlreadyExists is the error returned when the listerner already - // exists. - ErrListenerAlreadyExists = errors.New("listener already exists for docker events") - - // EOFEvent is sent when the event listener receives an EOF error. - EOFEvent = &APIEvents{ - Type: "EOF", - Status: "EOF", - } -) - -// AddEventListener adds a new listener to container events in the Docker API. -// -// The parameter is a channel through which events will be sent. -func (c *Client) AddEventListener(listener chan<- *APIEvents) error { - var err error - if !c.eventMonitor.isEnabled() { - err = c.eventMonitor.enableEventMonitoring(c) - if err != nil { - return err - } - } - err = c.eventMonitor.addListener(listener) - if err != nil { - return err - } - return nil -} - -// RemoveEventListener removes a listener from the monitor. -func (c *Client) RemoveEventListener(listener chan *APIEvents) error { - err := c.eventMonitor.removeListener(listener) - if err != nil { - return err - } - if len(c.eventMonitor.listeners) == 0 { - c.eventMonitor.disableEventMonitoring() - } - return nil -} - -func (eventState *eventMonitoringState) addListener(listener chan<- *APIEvents) error { - eventState.Lock() - defer eventState.Unlock() - if listenerExists(listener, &eventState.listeners) { - return ErrListenerAlreadyExists - } - eventState.Add(1) - eventState.listeners = append(eventState.listeners, listener) - return nil -} - -func (eventState *eventMonitoringState) removeListener(listener chan<- *APIEvents) error { - eventState.Lock() - defer eventState.Unlock() - if listenerExists(listener, &eventState.listeners) { - var newListeners []chan<- *APIEvents - for _, l := range eventState.listeners { - if l != listener { - newListeners = append(newListeners, l) - } - } - eventState.listeners = newListeners - eventState.Add(-1) - } - return nil -} - -func (eventState *eventMonitoringState) closeListeners() { - for _, l := range eventState.listeners { - close(l) - eventState.Add(-1) - } - eventState.listeners = nil -} - -func listenerExists(a chan<- *APIEvents, list *[]chan<- *APIEvents) bool { - for _, b := range *list { - if b == a { - return true - } - } - return false -} - -func (eventState *eventMonitoringState) enableEventMonitoring(c *Client) error { - eventState.Lock() - defer eventState.Unlock() - if !eventState.enabled { - eventState.enabled = true - atomic.StoreInt64(&eventState.lastSeen, 0) - eventState.C = make(chan *APIEvents, 100) - eventState.errC = make(chan error, 1) - go eventState.monitorEvents(c) - } - return nil -} - -func (eventState *eventMonitoringState) disableEventMonitoring() error { - eventState.Lock() - defer eventState.Unlock() - - eventState.closeListeners() - - eventState.Wait() - - if eventState.enabled { - eventState.enabled = false - close(eventState.C) - close(eventState.errC) - } - return nil -} - -func (eventState *eventMonitoringState) monitorEvents(c *Client) { - var err error - for eventState.noListeners() { - time.Sleep(10 * time.Millisecond) - } - if err = eventState.connectWithRetry(c); err != nil { - // terminate if connect failed - eventState.disableEventMonitoring() - return - } - for eventState.isEnabled() { - timeout := time.After(100 * time.Millisecond) - select { - case ev, ok := <-eventState.C: - if !ok { - return - } - if ev == EOFEvent { - eventState.disableEventMonitoring() - return - } - eventState.updateLastSeen(ev) - go eventState.sendEvent(ev) - case err = <-eventState.errC: - if err == ErrNoListeners { - eventState.disableEventMonitoring() - return - } else if err != nil { - defer func() { go eventState.monitorEvents(c) }() - return - } - case <-timeout: - continue - } - } -} - -func (eventState *eventMonitoringState) connectWithRetry(c *Client) error { - var retries int - eventState.RLock() - eventChan := eventState.C - errChan := eventState.errC - eventState.RUnlock() - err := c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan) - for ; err != nil && retries < maxMonitorConnRetries; retries++ { - waitTime := int64(retryInitialWaitTime * math.Pow(2, float64(retries))) - time.Sleep(time.Duration(waitTime) * time.Millisecond) - eventState.RLock() - eventChan = eventState.C - errChan = eventState.errC - eventState.RUnlock() - err = c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan) - } - return err -} - -func (eventState *eventMonitoringState) noListeners() bool { - eventState.RLock() - defer eventState.RUnlock() - return len(eventState.listeners) == 0 -} - -func (eventState *eventMonitoringState) isEnabled() bool { - eventState.RLock() - defer eventState.RUnlock() - return eventState.enabled -} - -func (eventState *eventMonitoringState) sendEvent(event *APIEvents) { - eventState.RLock() - defer eventState.RUnlock() - eventState.Add(1) - defer eventState.Done() - if eventState.enabled { - if len(eventState.listeners) == 0 { - eventState.errC <- ErrNoListeners - return - } - - for _, listener := range eventState.listeners { - listener <- event - } - } -} - -func (eventState *eventMonitoringState) updateLastSeen(e *APIEvents) { - eventState.Lock() - defer eventState.Unlock() - if atomic.LoadInt64(&eventState.lastSeen) < e.Time { - atomic.StoreInt64(&eventState.lastSeen, e.Time) - } -} - -func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan chan error) error { - uri := "/events" - if startTime != 0 { - uri += fmt.Sprintf("?since=%d", startTime) - } - protocol := c.endpointURL.Scheme - address := c.endpointURL.Path - if protocol != "unix" { - protocol = "tcp" - address = c.endpointURL.Host - } - var dial net.Conn - var err error - if c.TLSConfig == nil { - dial, err = c.Dialer.Dial(protocol, address) - } else { - dial, err = tlsDialWithDialer(c.Dialer, protocol, address, c.TLSConfig) - } - if err != nil { - return err - } - conn := httputil.NewClientConn(dial, nil) - req, err := http.NewRequest("GET", uri, nil) - if err != nil { - return err - } - res, err := conn.Do(req) - if err != nil { - return err - } - go func(res *http.Response, conn *httputil.ClientConn) { - defer conn.Close() - defer res.Body.Close() - decoder := json.NewDecoder(res.Body) - for { - var event APIEvents - if err = decoder.Decode(&event); err != nil { - if err == io.EOF || err == io.ErrUnexpectedEOF { - c.eventMonitor.RLock() - if c.eventMonitor.enabled && c.eventMonitor.C == eventChan { - // Signal that we're exiting. - eventChan <- EOFEvent - } - c.eventMonitor.RUnlock() - break - } - errChan <- err - } - if event.Time == 0 { - continue - } - if !c.eventMonitor.isEnabled() || c.eventMonitor.C != eventChan { - return - } - transformEvent(&event) - eventChan <- &event - } - }(res, conn) - return nil -} - -// transformEvent takes an event and determines what version it is from -// then populates both versions of the event -func transformEvent(event *APIEvents) { - // if event version is <= 1.21 there will be no Action and no Type - if event.Action == "" && event.Type == "" { - event.Action = event.Status - event.Actor.ID = event.ID - event.Actor.Attributes = map[string]string{} - switch event.Status { - case "delete", "import", "pull", "push", "tag", "untag": - event.Type = "image" - default: - event.Type = "container" - if event.From != "" { - event.Actor.Attributes["image"] = event.From - } - } - } else { - if event.Status == "" { - if event.Type == "image" || event.Type == "container" { - event.Status = event.Action - } else { - // Because just the Status has been overloaded with different Types - // if an event is not for an image or a container, we prepend the type - // to avoid problems for people relying on actions being only for - // images and containers - event.Status = event.Type + ":" + event.Action - } - } - if event.ID == "" { - event.ID = event.Actor.ID - } - if event.From == "" { - event.From = event.Actor.Attributes["image"] - } - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/exec.go b/vendor/github.com/fsouza/go-dockerclient/exec.go deleted file mode 100644 index 1a16da9d6..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/exec.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strconv" -) - -// Exec is the type representing a `docker exec` instance and containing the -// instance ID -type Exec struct { - ID string `json:"Id,omitempty" yaml:"Id,omitempty"` -} - -// CreateExecOptions specify parameters to the CreateExecContainer function. -// -// See https://goo.gl/1KSIb7 for more details -type CreateExecOptions struct { - AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty"` - AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty"` - AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty"` - Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` - Cmd []string `json:"Cmd,omitempty" yaml:"Cmd,omitempty"` - Container string `json:"Container,omitempty" yaml:"Container,omitempty"` - User string `json:"User,omitempty" yaml:"User,omitempty"` -} - -// CreateExec sets up an exec instance in a running container `id`, returning the exec -// instance, or an error in case of failure. -// -// See https://goo.gl/1KSIb7 for more details -func (c *Client) CreateExec(opts CreateExecOptions) (*Exec, error) { - path := fmt.Sprintf("/containers/%s/exec", opts.Container) - resp, err := c.do("POST", path, doOptions{data: opts}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchContainer{ID: opts.Container} - } - return nil, err - } - defer resp.Body.Close() - var exec Exec - if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { - return nil, err - } - - return &exec, nil -} - -// StartExecOptions specify parameters to the StartExecContainer function. -// -// See https://goo.gl/iQCnto for more details -type StartExecOptions struct { - Detach bool `json:"Detach,omitempty" yaml:"Detach,omitempty"` - - Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` - - InputStream io.Reader `qs:"-"` - OutputStream io.Writer `qs:"-"` - ErrorStream io.Writer `qs:"-"` - - // Use raw terminal? Usually true when the container contains a TTY. - RawTerminal bool `qs:"-"` - - // If set, after a successful connect, a sentinel will be sent and then the - // client will block on receive before continuing. - // - // It must be an unbuffered channel. Using a buffered channel can lead - // to unexpected behavior. - Success chan struct{} `json:"-"` -} - -// StartExec starts a previously set up exec instance id. If opts.Detach is -// true, it returns after starting the exec command. Otherwise, it sets up an -// interactive session with the exec command. -// -// See https://goo.gl/iQCnto for more details -func (c *Client) StartExec(id string, opts StartExecOptions) error { - cw, err := c.StartExecNonBlocking(id, opts) - if err != nil { - return err - } - if cw != nil { - return cw.Wait() - } - return nil -} - -// StartExecNonBlocking starts a previously set up exec instance id. If opts.Detach is -// true, it returns after starting the exec command. Otherwise, it sets up an -// interactive session with the exec command. -// -// See https://goo.gl/iQCnto for more details -func (c *Client) StartExecNonBlocking(id string, opts StartExecOptions) (CloseWaiter, error) { - if id == "" { - return nil, &NoSuchExec{ID: id} - } - - path := fmt.Sprintf("/exec/%s/start", id) - - if opts.Detach { - resp, err := c.do("POST", path, doOptions{data: opts}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchExec{ID: id} - } - return nil, err - } - defer resp.Body.Close() - return nil, nil - } - - return c.hijack("POST", path, hijackOptions{ - success: opts.Success, - setRawTerminal: opts.RawTerminal, - in: opts.InputStream, - stdout: opts.OutputStream, - stderr: opts.ErrorStream, - data: opts, - }) -} - -// ResizeExecTTY resizes the tty session used by the exec command id. This API -// is valid only if Tty was specified as part of creating and starting the exec -// command. -// -// See https://goo.gl/e1JpsA for more details -func (c *Client) ResizeExecTTY(id string, height, width int) error { - params := make(url.Values) - params.Set("h", strconv.Itoa(height)) - params.Set("w", strconv.Itoa(width)) - - path := fmt.Sprintf("/exec/%s/resize?%s", id, params.Encode()) - resp, err := c.do("POST", path, doOptions{}) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// ExecProcessConfig is a type describing the command associated to a Exec -// instance. It's used in the ExecInspect type. -type ExecProcessConfig struct { - Privileged bool `json:"privileged,omitempty" yaml:"privileged,omitempty"` - User string `json:"user,omitempty" yaml:"user,omitempty"` - Tty bool `json:"tty,omitempty" yaml:"tty,omitempty"` - EntryPoint string `json:"entrypoint,omitempty" yaml:"entrypoint,omitempty"` - Arguments []string `json:"arguments,omitempty" yaml:"arguments,omitempty"` -} - -// ExecInspect is a type with details about a exec instance, including the -// exit code if the command has finished running. It's returned by a api -// call to /exec/(id)/json -// -// See https://goo.gl/gPtX9R for more details -type ExecInspect struct { - ID string `json:"ID,omitempty" yaml:"ID,omitempty"` - Running bool `json:"Running,omitempty" yaml:"Running,omitempty"` - ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty"` - OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty"` - OpenStderr bool `json:"OpenStderr,omitempty" yaml:"OpenStderr,omitempty"` - OpenStdout bool `json:"OpenStdout,omitempty" yaml:"OpenStdout,omitempty"` - ProcessConfig ExecProcessConfig `json:"ProcessConfig,omitempty" yaml:"ProcessConfig,omitempty"` - Container Container `json:"Container,omitempty" yaml:"Container,omitempty"` -} - -// InspectExec returns low-level information about the exec command id. -// -// See https://goo.gl/gPtX9R for more details -func (c *Client) InspectExec(id string) (*ExecInspect, error) { - path := fmt.Sprintf("/exec/%s/json", id) - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchExec{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var exec ExecInspect - if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { - return nil, err - } - return &exec, nil -} - -// NoSuchExec is the error returned when a given exec instance does not exist. -type NoSuchExec struct { - ID string -} - -func (err *NoSuchExec) Error() string { - return "No such exec instance: " + err.ID -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/CHANGELOG.md deleted file mode 100644 index ecc843272..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/CHANGELOG.md +++ /dev/null @@ -1,55 +0,0 @@ -# 0.9.0 (Unreleased) - -* logrus/text_formatter: don't emit empty msg -* logrus/hooks/airbrake: move out of main repository -* logrus/hooks/sentry: move out of main repository -* logrus/hooks/papertrail: move out of main repository -* logrus/hooks/bugsnag: move out of main repository - -# 0.8.7 - -* logrus/core: fix possible race (#216) -* logrus/doc: small typo fixes and doc improvements - - -# 0.8.6 - -* hooks/raven: allow passing an initialized client - -# 0.8.5 - -* logrus/core: revert #208 - -# 0.8.4 - -* formatter/text: fix data race (#218) - -# 0.8.3 - -* logrus/core: fix entry log level (#208) -* logrus/core: improve performance of text formatter by 40% -* logrus/core: expose `LevelHooks` type -* logrus/core: add support for DragonflyBSD and NetBSD -* formatter/text: print structs more verbosely - -# 0.8.2 - -* logrus: fix more Fatal family functions - -# 0.8.1 - -* logrus: fix not exiting on `Fatalf` and `Fatalln` - -# 0.8.0 - -* logrus: defaults to stderr instead of stdout -* hooks/sentry: add special field for `*http.Request` -* formatter/text: ignore Windows for colors - -# 0.7.3 - -* formatter/\*: allow configuration of timestamp layout - -# 0.7.2 - -* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/LICENSE deleted file mode 100644 index f090cb42f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Simon Eskildsen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md deleted file mode 100644 index 55d3a8d5f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md +++ /dev/null @@ -1,365 +0,0 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc] - -Logrus is a structured logger for Go (golang), completely API compatible with -the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not -yet stable (pre 1.0). Logrus itself is completely stable and has been used in -many large deployments. The core API is unlikely to change much but please -version control your Logrus to make sure you aren't fetching latest `master` on -every build.** - -Nicely color-coded in development (when a TTY is attached, otherwise just -plain text): - -![Colored](http://i.imgur.com/PY7qMwd.png) - -With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash -or Splunk: - -```json -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} -``` - -With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not -attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: - -```text -time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 -time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 -time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true -time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 -time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true -exit status 1 -``` - -#### Example - -The simplest way to use Logrus is simply the package-level exported logger: - -```go -package main - -import ( - log "github.com/Sirupsen/logrus" -) - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - }).Info("A walrus appears") -} -``` - -Note that it's completely api-compatible with the stdlib logger, so you can -replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` -and you'll now have the flexibility of Logrus. You can customize it all you -want: - -```go -package main - -import ( - "os" - log "github.com/Sirupsen/logrus" -) - -func init() { - // Log as JSON instead of the default ASCII formatter. - log.SetFormatter(&log.JSONFormatter{}) - - // Output to stderr instead of stdout, could also be a file. - log.SetOutput(os.Stderr) - - // Only log the warning severity or above. - log.SetLevel(log.WarnLevel) -} - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(log.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(log.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") - - // A common pattern is to re-use fields between logging statements by re-using - // the logrus.Entry returned from WithFields() - contextLogger := log.WithFields(log.Fields{ - "common": "this is a common field", - "other": "I also should be logged always", - }) - - contextLogger.Info("I'll be logged with common and other field") - contextLogger.Info("Me too") -} -``` - -For more advanced usage such as logging to multiple locations from the same -application, you can also create an instance of the `logrus` Logger: - -```go -package main - -import ( - "github.com/Sirupsen/logrus" -) - -// Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() - -func main() { - // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stderr - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") -} -``` - -#### Fields - -Logrus encourages careful, structured logging though logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed -to send event %s to topic %s with key %d")`, you should log the much more -discoverable: - -```go -log.WithFields(log.Fields{ - "event": event, - "topic": topic, - "key": key, -}).Fatal("Failed to send event") -``` - -We've found this API forces you to think about logging in a way that produces -much more useful logging messages. We've been in countless situations where just -a single added field to a log statement that was already there would've saved us -hours. The `WithFields` call is optional. - -In general, with Logrus using any of the `printf`-family functions should be -seen as a hint you should add a field, however, you can still use the -`printf`-family functions with Logrus. - -#### Hooks - -You can add hooks for logging levels. For example to send errors to an exception -tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to -multiple places simultaneously, e.g. syslog. - -Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in -`init`: - -```go -import ( - log "github.com/Sirupsen/logrus" - "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake" - logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" - "log/syslog" -) - -func init() { - - // Use the Airbrake hook to report errors that have Error severity or above to - // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook(123, "xyz", "production")) - - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - if err != nil { - log.Error("Unable to connect to local syslog daemon") - } else { - log.AddHook(hook) - } -} -``` -Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). - -| Hook | Description | -| ----- | ----------- | -| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. | -| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | -| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. | -| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | -| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | -| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. | -| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | -| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | -| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | -| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | -| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) | -| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | -| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | -| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | -| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | -| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | -| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | -| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | -| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | -| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | -| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | - -#### Level logging - -Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. - -```go -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") -// Calls os.Exit(1) after logging -log.Fatal("Bye.") -// Calls panic() after logging -log.Panic("I'm bailing.") -``` - -You can set the logging level on a `Logger`, then it will only log entries with -that severity or anything above it: - -```go -// Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) -``` - -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose -environment if your application has that. - -#### Entries - -Besides the fields added with `WithField` or `WithFields` some fields are -automatically added to all logging events: - -1. `time`. The timestamp when the entry was created. -2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after - the `AddFields` call. E.g. `Failed to send event.` -3. `level`. The logging level. E.g. `info`. - -#### Environments - -Logrus has no notion of environment. - -If you wish for hooks and formatters to only be used in specific environments, -you should handle that yourself. For example, if your application has a global -variable `Environment`, which is a string representation of the environment you -could do: - -```go -import ( - log "github.com/Sirupsen/logrus" -) - -init() { - // do something here to set environment depending on an environment variable - // or command-line flag - if Environment == "production" { - log.SetFormatter(&log.JSONFormatter{}) - } else { - // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) - } -} -``` - -This configuration is how `logrus` was intended to be used, but JSON in -production is mostly only useful if you do log aggregation with tools like -Splunk or Logstash. - -#### Formatters - -The built-in logging formatters are: - -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` - field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true` -* `logrus.JSONFormatter`. Logs fields as JSON. -* `logrus/formatters/logstash.LogstashFormatter`. Logs fields as [Logstash](http://logstash.net) Events. - - ```go - logrus.SetFormatter(&logstash.LogstashFormatter{Type: "application_name"}) - ``` - -Third party logging formatters: - -* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. -* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. - -You can define your formatter by implementing the `Formatter` interface, -requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the -default ones (see Entries section above): - -```go -type MyJSONFormatter struct { -} - -log.SetFormatter(new(MyJSONFormatter)) - -func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { - // Note this doesn't include Time, Level and Message which are available on - // the Entry. Consult `godoc` on information about those fields or read the - // source of the official loggers. - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} -``` - -#### Logger as an `io.Writer` - -Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. - -```go -w := logger.Writer() -defer w.Close() - -srv := http.Server{ - // create a stdlib log.Logger that writes to - // logrus.Logger. - ErrorLog: log.New(w, "", 0), -} -``` - -Each line written to that writer will be printed the usual way, using formatters -and hooks. The level for those entries is `info`. - -#### Rotation - -Log rotation is not provided with Logrus. Log rotation should be done by an -external program (like `logrotate(8)`) that can compress and delete old log -entries. It should not be a feature of the application-level logger. - -#### Tools - -| Tool | Description | -| ---- | ----------- | -|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| - -[godoc]: https://godoc.org/github.com/Sirupsen/logrus diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/doc.go deleted file mode 100644 index dddd5f877..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - - -The simplest way to use Logrus is simply the package-level exported logger: - - package main - - import ( - log "github.com/Sirupsen/logrus" - ) - - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } - -Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 - -For a full guide visit https://github.com/Sirupsen/logrus -*/ -package logrus diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry.go deleted file mode 100644 index 9ae900bc5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry.go +++ /dev/null @@ -1,264 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "io" - "os" - "time" -) - -// Defines the key when adding errors using WithError. -var ErrorKey = "error" - -// An entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Debug, Info, -// Warn, Error, Fatal or Panic is called on it. These objects can be reused and -// passed around as much as you wish to avoid field duplication. -type Entry struct { - Logger *Logger - - // Contains all the fields set by the user. - Data Fields - - // Time at which the log entry was created - Time time.Time - - // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic - Level Level - - // Message passed to Debug, Info, Warn, Error, Fatal or Panic - Message string -} - -func NewEntry(logger *Logger) *Entry { - return &Entry{ - Logger: logger, - // Default is three fields, give a little extra room - Data: make(Fields, 5), - } -} - -// Returns a reader for the entry, which is a proxy to the formatter. -func (entry *Entry) Reader() (*bytes.Buffer, error) { - serialized, err := entry.Logger.Formatter.Format(entry) - return bytes.NewBuffer(serialized), err -} - -// Returns the string representation from the reader and ultimately the -// formatter. -func (entry *Entry) String() (string, error) { - reader, err := entry.Reader() - if err != nil { - return "", err - } - - return reader.String(), err -} - -// Add an error as single field (using the key defined in ErrorKey) to the Entry. -func (entry *Entry) WithError(err error) *Entry { - return entry.WithField(ErrorKey, err) -} - -// Add a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) -} - -// Add a map of fields to the Entry. -func (entry *Entry) WithFields(fields Fields) *Entry { - data := Fields{} - for k, v := range entry.Data { - data[k] = v - } - for k, v := range fields { - data[k] = v - } - return &Entry{Logger: entry.Logger, Data: data} -} - -// This function is not declared with a pointer value because otherwise -// race conditions will occur when using multiple goroutines -func (entry Entry) log(level Level, msg string) { - entry.Time = time.Now() - entry.Level = level - entry.Message = msg - - if err := entry.Logger.Hooks.Fire(level, &entry); err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) - entry.Logger.mu.Unlock() - } - - reader, err := entry.Reader() - if err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - entry.Logger.mu.Unlock() - } - - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - - _, err = io.Copy(entry.Logger.Out, reader) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } - - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { - panic(&entry) - } -} - -func (entry *Entry) Debug(args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.log(DebugLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Print(args ...interface{}) { - entry.Info(args...) -} - -func (entry *Entry) Info(args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.log(InfoLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warn(args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.log(WarnLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warning(args ...interface{}) { - entry.Warn(args...) -} - -func (entry *Entry) Error(args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.log(ErrorLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Fatal(args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.log(FatalLevel, fmt.Sprint(args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panic(args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.log(PanicLevel, fmt.Sprint(args...)) - } - panic(fmt.Sprint(args...)) -} - -// Entry Printf family functions - -func (entry *Entry) Debugf(format string, args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.Debug(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Infof(format string, args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.Info(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Printf(format string, args ...interface{}) { - entry.Infof(format, args...) -} - -func (entry *Entry) Warnf(format string, args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.Warn(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Warningf(format string, args ...interface{}) { - entry.Warnf(format, args...) -} - -func (entry *Entry) Errorf(format string, args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.Error(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Fatalf(format string, args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.Fatal(fmt.Sprintf(format, args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panicf(format string, args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.Panic(fmt.Sprintf(format, args...)) - } -} - -// Entry Println family functions - -func (entry *Entry) Debugln(args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.Debug(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Infoln(args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.Info(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Println(args ...interface{}) { - entry.Infoln(args...) -} - -func (entry *Entry) Warnln(args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.Warn(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Warningln(args ...interface{}) { - entry.Warnln(args...) -} - -func (entry *Entry) Errorln(args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.Error(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Fatalln(args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.Fatal(entry.sprintlnn(args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panicln(args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.Panic(entry.sprintlnn(args...)) - } -} - -// Sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/exported.go deleted file mode 100644 index 9a0120ac1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/exported.go +++ /dev/null @@ -1,193 +0,0 @@ -package logrus - -import ( - "io" -) - -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) - -func StandardLogger() *Logger { - return std -} - -// SetOutput sets the standard logger output. -func SetOutput(out io.Writer) { - std.mu.Lock() - defer std.mu.Unlock() - std.Out = out -} - -// SetFormatter sets the standard logger formatter. -func SetFormatter(formatter Formatter) { - std.mu.Lock() - defer std.mu.Unlock() - std.Formatter = formatter -} - -// SetLevel sets the standard logger level. -func SetLevel(level Level) { - std.mu.Lock() - defer std.mu.Unlock() - std.Level = level -} - -// GetLevel returns the standard logger level. -func GetLevel() Level { - std.mu.Lock() - defer std.mu.Unlock() - return std.Level -} - -// AddHook adds a hook to the standard logger hooks. -func AddHook(hook Hook) { - std.mu.Lock() - defer std.mu.Unlock() - std.Hooks.Add(hook) -} - -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. -func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) -} - -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { - return std.WithField(key, value) -} - -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithFields(fields Fields) *Entry { - return std.WithFields(fields) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - std.Debug(args...) -} - -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { - std.Print(args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - std.Info(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - std.Warn(args...) -} - -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { - std.Warning(args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - std.Error(args...) -} - -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { - std.Panic(args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func Fatal(args ...interface{}) { - std.Fatal(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) -} - -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { - std.Printf(format, args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - std.Infof(format, args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - std.Warnf(format, args...) -} - -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { - std.Warningf(format, args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) -} - -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { - std.Panicf(format, args...) -} - -// Fatalf logs a message at level Fatal on the standard logger. -func Fatalf(format string, args ...interface{}) { - std.Fatalf(format, args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - std.Debugln(args...) -} - -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { - std.Println(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - std.Infoln(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - std.Warnln(args...) -} - -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { - std.Warningln(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - std.Errorln(args...) -} - -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { - std.Panicln(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger. -func Fatalln(args ...interface{}) { - std.Fatalln(args...) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter.go deleted file mode 100644 index 104d689f1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter.go +++ /dev/null @@ -1,48 +0,0 @@ -package logrus - -import "time" - -const DefaultTimestampFormat = time.RFC3339 - -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: -// -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. -// -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. -type Formatter interface { - Format(*Entry) ([]byte, error) -} - -// This is to not silently overwrite `time`, `msg` and `level` fields when -// dumping it. If this code wasn't there doing: -// -// logrus.WithField("level", 1).Info("hello") -// -// Would just silently drop the user provided level. Instead with this code -// it'll logged as: -// -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} -// -// It's not exported because it's still using Data in an opinionated way. It's to -// avoid code duplication between the two default formatters. -func prefixFieldClashes(data Fields) { - _, ok := data["time"] - if ok { - data["fields.time"] = data["time"] - } - - _, ok = data["msg"] - if ok { - data["fields.msg"] = data["msg"] - } - - _, ok = data["level"] - if ok { - data["fields.level"] = data["level"] - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hooks.go deleted file mode 100644 index 3f151cdc3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package logrus - -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not -// fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for -// the logging calls for levels returned from `Levels()` to block. -type Hook interface { - Levels() []Level - Fire(*Entry) error -} - -// Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook - -// Add a hook to an instance of logger. This is called with -// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { - for _, level := range hook.Levels() { - hooks[level] = append(hooks[level], hook) - } -} - -// Fire all the hooks for the passed level. Used by `entry.log` to fire -// appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { - for _, hook := range hooks[level] { - if err := hook.Fire(entry); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter.go deleted file mode 100644 index 2ad6dc5cf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter.go +++ /dev/null @@ -1,41 +0,0 @@ -package logrus - -import ( - "encoding/json" - "fmt" -) - -type JSONFormatter struct { - // TimestampFormat sets the format used for marshaling timestamps. - TimestampFormat string -} - -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+3) - for k, v := range entry.Data { - switch v := v.(type) { - case error: - // Otherwise errors are ignored by `encoding/json` - // https://github.com/Sirupsen/logrus/issues/137 - data[k] = v.Error() - default: - data[k] = v - } - } - prefixFieldClashes(data) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat - } - - data["time"] = entry.Time.Format(timestampFormat) - data["msg"] = entry.Message - data["level"] = entry.Level.String() - - serialized, err := json.Marshal(data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logger.go deleted file mode 100644 index 2fdb23176..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logger.go +++ /dev/null @@ -1,212 +0,0 @@ -package logrus - -import ( - "io" - "os" - "sync" -) - -type Logger struct { - // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stderr`. You can also set this to - // something more adventorous, such as logging to Kafka. - Out io.Writer - // Hooks for the logger instance. These allow firing events based on logging - // levels and log entries. For example, to send errors to an error tracking - // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks - // All log entries pass through the formatter before logged to Out. The - // included formatters are `TextFormatter` and `JSONFormatter` for which - // TextFormatter is the default. In development (when a TTY is attached) it - // logs with colors, but to a file it wouldn't. You can easily implement your - // own that implements the `Formatter` interface, see the `README` or included - // formatters for examples. - Formatter Formatter - // The logging level the logger should log at. This is typically (and defaults - // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be - // logged. `logrus.Debug` is useful in - Level Level - // Used to sync writing to the log. - mu sync.Mutex -} - -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just -// instantiate your own: -// -// var log = &Logger{ -// Out: os.Stderr, -// Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), -// Level: logrus.DebugLevel, -// } -// -// It's recommended to make this a global instance called `log`. -func New() *Logger { - return &Logger{ - Out: os.Stderr, - Formatter: new(TextFormatter), - Hooks: make(LevelHooks), - Level: InfoLevel, - } -} - -// Adds a field to the log entry, note that you it doesn't log until you call -// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. -// If you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { - return NewEntry(logger).WithField(key, value) -} - -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. -func (logger *Logger) WithFields(fields Fields) *Entry { - return NewEntry(logger).WithFields(fields) -} - -// Add an error as single field to the log entry. All it does is call -// `WithError` for the given `error`. -func (logger *Logger) WithError(err error) *Entry { - return NewEntry(logger).WithError(err) -} - -func (logger *Logger) Debugf(format string, args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debugf(format, args...) - } -} - -func (logger *Logger) Infof(format string, args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Infof(format, args...) - } -} - -func (logger *Logger) Printf(format string, args ...interface{}) { - NewEntry(logger).Printf(format, args...) -} - -func (logger *Logger) Warnf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnf(format, args...) - } -} - -func (logger *Logger) Warningf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnf(format, args...) - } -} - -func (logger *Logger) Errorf(format string, args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Errorf(format, args...) - } -} - -func (logger *Logger) Fatalf(format string, args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatalf(format, args...) - } - os.Exit(1) -} - -func (logger *Logger) Panicf(format string, args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panicf(format, args...) - } -} - -func (logger *Logger) Debug(args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debug(args...) - } -} - -func (logger *Logger) Info(args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Info(args...) - } -} - -func (logger *Logger) Print(args ...interface{}) { - NewEntry(logger).Info(args...) -} - -func (logger *Logger) Warn(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warn(args...) - } -} - -func (logger *Logger) Warning(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warn(args...) - } -} - -func (logger *Logger) Error(args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Error(args...) - } -} - -func (logger *Logger) Fatal(args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatal(args...) - } - os.Exit(1) -} - -func (logger *Logger) Panic(args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panic(args...) - } -} - -func (logger *Logger) Debugln(args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debugln(args...) - } -} - -func (logger *Logger) Infoln(args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Infoln(args...) - } -} - -func (logger *Logger) Println(args ...interface{}) { - NewEntry(logger).Println(args...) -} - -func (logger *Logger) Warnln(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnln(args...) - } -} - -func (logger *Logger) Warningln(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnln(args...) - } -} - -func (logger *Logger) Errorln(args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Errorln(args...) - } -} - -func (logger *Logger) Fatalln(args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatalln(args...) - } - os.Exit(1) -} - -func (logger *Logger) Panicln(args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panicln(args...) - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus.go deleted file mode 100644 index 0c09fbc26..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus.go +++ /dev/null @@ -1,98 +0,0 @@ -package logrus - -import ( - "fmt" - "log" -) - -// Fields type, used to pass to `WithFields`. -type Fields map[string]interface{} - -// Level type -type Level uint8 - -// Convert the Level to a string. E.g. PanicLevel becomes "panic". -func (level Level) String() string { - switch level { - case DebugLevel: - return "debug" - case InfoLevel: - return "info" - case WarnLevel: - return "warning" - case ErrorLevel: - return "error" - case FatalLevel: - return "fatal" - case PanicLevel: - return "panic" - } - - return "unknown" -} - -// ParseLevel takes a string level and returns the Logrus log level constant. -func ParseLevel(lvl string) (Level, error) { - switch lvl { - case "panic": - return PanicLevel, nil - case "fatal": - return FatalLevel, nil - case "error": - return ErrorLevel, nil - case "warn", "warning": - return WarnLevel, nil - case "info": - return InfoLevel, nil - case "debug": - return DebugLevel, nil - } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) -} - -// These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. -const ( - // PanicLevel level, highest level of severity. Logs and then calls panic with the - // message passed to Debug, Info, ... - PanicLevel Level = iota - // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the - // logging level is set to Panic. - FatalLevel - // ErrorLevel level. Logs. Used for errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel - // InfoLevel level. General operational entries about what's going on inside the - // application. - InfoLevel - // DebugLevel level. Usually only enabled when debugging. Very verbose logging. - DebugLevel -) - -// Won't compile if StdLogger can't be realized by a log.Logger -var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} -) - -// StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. -type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) - - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) - - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_bsd.go deleted file mode 100644 index 71f8d67a5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_bsd.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TIOCGETA - -type Termios syscall.Termios diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_linux.go deleted file mode 100644 index a2c0b40db..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_linux.go +++ /dev/null @@ -1,12 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TCGETS - -type Termios syscall.Termios diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_notwindows.go deleted file mode 100644 index b343b3a37..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_notwindows.go +++ /dev/null @@ -1,21 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux darwin freebsd openbsd netbsd dragonfly - -package logrus - -import ( - "syscall" - "unsafe" -) - -// IsTerminal returns true if stderr's file descriptor is a terminal. -func IsTerminal() bool { - fd := syscall.Stderr - var termios Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_solaris.go deleted file mode 100644 index 743df457f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_solaris.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build solaris - -package logrus - -import ( - "os" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal() bool { - _, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA) - return err == nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_windows.go deleted file mode 100644 index 0146845d1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package logrus - -import ( - "syscall" - "unsafe" -) - -var kernel32 = syscall.NewLazyDLL("kernel32.dll") - -var ( - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") -) - -// IsTerminal returns true if stderr's file descriptor is a terminal. -func IsTerminal() bool { - fd := syscall.Stderr - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter.go deleted file mode 100644 index 06ef20233..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter.go +++ /dev/null @@ -1,161 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "runtime" - "sort" - "strings" - "time" -) - -const ( - nocolor = 0 - red = 31 - green = 32 - yellow = 33 - blue = 34 - gray = 37 -) - -var ( - baseTimestamp time.Time - isTerminal bool -) - -func init() { - baseTimestamp = time.Now() - isTerminal = IsTerminal() -} - -func miniTS() int { - return int(time.Since(baseTimestamp) / time.Second) -} - -type TextFormatter struct { - // Set to true to bypass checking for a TTY before outputting colors. - ForceColors bool - - // Force disabling colors. - DisableColors bool - - // Disable timestamp logging. useful when output is redirected to logging - // system that already adds timestamps. - DisableTimestamp bool - - // Enable logging the full timestamp when a TTY is attached instead of just - // the time passed since beginning of execution. - FullTimestamp bool - - // TimestampFormat to use for display when a full timestamp is printed - TimestampFormat string - - // The fields are sorted by default for a consistent output. For applications - // that log extremely frequently and don't use the JSON formatter this may not - // be desired. - DisableSorting bool -} - -func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - var keys []string = make([]string, 0, len(entry.Data)) - for k := range entry.Data { - keys = append(keys, k) - } - - if !f.DisableSorting { - sort.Strings(keys) - } - - b := &bytes.Buffer{} - - prefixFieldClashes(entry.Data) - - isColorTerminal := isTerminal && (runtime.GOOS != "windows") - isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat - } - if isColored { - f.printColored(b, entry, keys, timestampFormat) - } else { - if !f.DisableTimestamp { - f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) - } - f.appendKeyValue(b, "level", entry.Level.String()) - if entry.Message != "" { - f.appendKeyValue(b, "msg", entry.Message) - } - for _, key := range keys { - f.appendKeyValue(b, key, entry.Data[key]) - } - } - - b.WriteByte('\n') - return b.Bytes(), nil -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { - var levelColor int - switch entry.Level { - case DebugLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String())[0:4] - - if !f.FullTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) - } else { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) - } - for _, k := range keys { - v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) - } -} - -func needsQuoting(text string) bool { - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.') { - return false - } - } - return true -} - -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - - b.WriteString(key) - b.WriteByte('=') - - switch value := value.(type) { - case string: - if needsQuoting(value) { - b.WriteString(value) - } else { - fmt.Fprintf(b, "%q", value) - } - case error: - errmsg := value.Error() - if needsQuoting(errmsg) { - b.WriteString(errmsg) - } else { - fmt.Fprintf(b, "%q", value) - } - default: - fmt.Fprint(b, value) - } - - b.WriteByte(' ') -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/writer.go deleted file mode 100644 index 1e30b1c75..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/writer.go +++ /dev/null @@ -1,31 +0,0 @@ -package logrus - -import ( - "bufio" - "io" - "runtime" -) - -func (logger *Logger) Writer() *io.PipeWriter { - reader, writer := io.Pipe() - - go logger.writerScanner(reader) - runtime.SetFinalizer(writer, writerFinalizer) - - return writer -} - -func (logger *Logger) writerScanner(reader *io.PipeReader) { - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - logger.Print(scanner.Text()) - } - if err := scanner.Err(); err != nil { - logger.Errorf("Error while reading from Writer: %s", err) - } - reader.Close() -} - -func writerFinalizer(writer *io.PipeWriter) { - writer.Close() -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile.go deleted file mode 100644 index ba8b4f201..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile.go +++ /dev/null @@ -1,67 +0,0 @@ -package opts - -import ( - "bufio" - "fmt" - "os" - "strings" -) - -// ParseEnvFile reads a file with environment variables enumerated by lines -// -// ``Environment variable names used by the utilities in the Shell and -// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase -// letters, digits, and the '_' (underscore) from the characters defined in -// Portable Character Set and do not begin with a digit. *But*, other -// characters may be permitted by an implementation; applications shall -// tolerate the presence of such names.'' -// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html -// -// As of #16585, it's up to application inside docker to validate or not -// environment variables, that's why we just strip leading whitespace and -// nothing more. -func ParseEnvFile(filename string) ([]string, error) { - fh, err := os.Open(filename) - if err != nil { - return []string{}, err - } - defer fh.Close() - - lines := []string{} - scanner := bufio.NewScanner(fh) - for scanner.Scan() { - // trim the line from all leading whitespace first - line := strings.TrimLeft(scanner.Text(), whiteSpaces) - // line is not empty, and not starting with '#' - if len(line) > 0 && !strings.HasPrefix(line, "#") { - data := strings.SplitN(line, "=", 2) - - // trim the front of a variable, but nothing else - variable := strings.TrimLeft(data[0], whiteSpaces) - if strings.ContainsAny(variable, whiteSpaces) { - return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)} - } - - if len(data) > 1 { - - // pass the value through, no trimming - lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1])) - } else { - // if only a pass-through variable is given, clean it up. - lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line))) - } - } - } - return lines, scanner.Err() -} - -var whiteSpaces = " \t" - -// ErrBadEnvVariable typed error for bad environment variable -type ErrBadEnvVariable struct { - msg string -} - -func (e ErrBadEnvVariable) Error() string { - return fmt.Sprintf("poorly formatted environment: %s", e.msg) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts.go deleted file mode 100644 index d1b698541..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts.go +++ /dev/null @@ -1,146 +0,0 @@ -package opts - -import ( - "fmt" - "net" - "net/url" - "runtime" - "strconv" - "strings" -) - -var ( - // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. docker daemon -H tcp:// - // TODO Windows. DefaultHTTPPort is only used on Windows if a -H parameter - // is not supplied. A better longer term solution would be to use a named - // pipe as the default on the Windows daemon. - // These are the IANA registered port numbers for use with Docker - // see http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml?search=docker - DefaultHTTPPort = 2375 // Default HTTP Port - // DefaultTLSHTTPPort Default HTTP Port used when TLS enabled - DefaultTLSHTTPPort = 2376 // Default TLS encrypted HTTP Port - // DefaultUnixSocket Path for the unix socket. - // Docker daemon by default always listens on the default unix socket - DefaultUnixSocket = "/var/run/docker.sock" - // DefaultTCPHost constant defines the default host string used by docker on Windows - DefaultTCPHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort) - // DefaultTLSHost constant defines the default host string used by docker for TLS sockets - DefaultTLSHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultTLSHTTPPort) -) - -// ValidateHost validates that the specified string is a valid host and returns it. -func ValidateHost(val string) (string, error) { - _, err := parseDockerDaemonHost(DefaultTCPHost, DefaultTLSHost, DefaultUnixSocket, "", val) - if err != nil { - return val, err - } - // Note: unlike most flag validators, we don't return the mutated value here - // we need to know what the user entered later (using ParseHost) to adjust for tls - return val, nil -} - -// ParseHost and set defaults for a Daemon host string -func ParseHost(defaultHost, val string) (string, error) { - host, err := parseDockerDaemonHost(DefaultTCPHost, DefaultTLSHost, DefaultUnixSocket, defaultHost, val) - if err != nil { - return val, err - } - return host, nil -} - -// parseDockerDaemonHost parses the specified address and returns an address that will be used as the host. -// Depending of the address specified, will use the defaultTCPAddr or defaultUnixAddr -// defaultUnixAddr must be a absolute file path (no `unix://` prefix) -// defaultTCPAddr must be the full `tcp://host:port` form -func parseDockerDaemonHost(defaultTCPAddr, defaultTLSHost, defaultUnixAddr, defaultAddr, addr string) (string, error) { - addr = strings.TrimSpace(addr) - if addr == "" { - if defaultAddr == defaultTLSHost { - return defaultTLSHost, nil - } - if runtime.GOOS != "windows" { - return fmt.Sprintf("unix://%s", defaultUnixAddr), nil - } - return defaultTCPAddr, nil - } - addrParts := strings.Split(addr, "://") - if len(addrParts) == 1 { - addrParts = []string{"tcp", addrParts[0]} - } - - switch addrParts[0] { - case "tcp": - return parseTCPAddr(addrParts[1], defaultTCPAddr) - case "unix": - return parseUnixAddr(addrParts[1], defaultUnixAddr) - case "fd": - return addr, nil - default: - return "", fmt.Errorf("Invalid bind address format: %s", addr) - } -} - -// parseUnixAddr parses and validates that the specified address is a valid UNIX -// socket address. It returns a formatted UNIX socket address, either using the -// address parsed from addr, or the contents of defaultAddr if addr is a blank -// string. -func parseUnixAddr(addr string, defaultAddr string) (string, error) { - addr = strings.TrimPrefix(addr, "unix://") - if strings.Contains(addr, "://") { - return "", fmt.Errorf("Invalid proto, expected unix: %s", addr) - } - if addr == "" { - addr = defaultAddr - } - return fmt.Sprintf("unix://%s", addr), nil -} - -// parseTCPAddr parses and validates that the specified address is a valid TCP -// address. It returns a formatted TCP address, either using the address parsed -// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string. -// tryAddr is expected to have already been Trim()'d -// defaultAddr must be in the full `tcp://host:port` form -func parseTCPAddr(tryAddr string, defaultAddr string) (string, error) { - if tryAddr == "" || tryAddr == "tcp://" { - return defaultAddr, nil - } - addr := strings.TrimPrefix(tryAddr, "tcp://") - if strings.Contains(addr, "://") || addr == "" { - return "", fmt.Errorf("Invalid proto, expected tcp: %s", tryAddr) - } - - defaultAddr = strings.TrimPrefix(defaultAddr, "tcp://") - defaultHost, defaultPort, err := net.SplitHostPort(defaultAddr) - if err != nil { - return "", err - } - // url.Parse fails for trailing colon on IPv6 brackets on Go 1.5, but - // not 1.4. See https://github.com/golang/go/issues/12200 and - // https://github.com/golang/go/issues/6530. - if strings.HasSuffix(addr, "]:") { - addr += defaultPort - } - - u, err := url.Parse("tcp://" + addr) - if err != nil { - return "", err - } - - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - return "", fmt.Errorf("Invalid bind address format: %s", tryAddr) - } - - if host == "" { - host = defaultHost - } - if port == "" { - port = defaultPort - } - p, err := strconv.Atoi(port) - if err != nil && p == 0 { - return "", fmt.Errorf("Invalid bind address format: %s", tryAddr) - } - - return fmt.Sprintf("tcp://%s%s", net.JoinHostPort(host, port), u.Path), nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_unix.go deleted file mode 100644 index 611407a9d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows - -package opts - -import "fmt" - -// DefaultHost constant defines the default host string used by docker on other hosts than Windows -var DefaultHost = fmt.Sprintf("unix://%s", DefaultUnixSocket) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_windows.go deleted file mode 100644 index ec52e9a70..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build windows - -package opts - -// DefaultHost constant defines the default host string used by docker on Windows -var DefaultHost = DefaultTCPHost diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip.go deleted file mode 100644 index c7b0dc994..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip.go +++ /dev/null @@ -1,42 +0,0 @@ -package opts - -import ( - "fmt" - "net" -) - -// IPOpt holds an IP. It is used to store values from CLI flags. -type IPOpt struct { - *net.IP -} - -// NewIPOpt creates a new IPOpt from a reference net.IP and a -// string representation of an IP. If the string is not a valid -// IP it will fallback to the specified reference. -func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt { - o := &IPOpt{ - IP: ref, - } - o.Set(defaultVal) - return o -} - -// Set sets an IPv4 or IPv6 address from a given string. If the given -// string is not parseable as an IP address it returns an error. -func (o *IPOpt) Set(val string) error { - ip := net.ParseIP(val) - if ip == nil { - return fmt.Errorf("%s is not an ip address", val) - } - *o.IP = ip - return nil -} - -// String returns the IP address stored in the IPOpt. If stored IP is a -// nil pointer, it returns an empty string. -func (o *IPOpt) String() string { - if *o.IP == nil { - return "" - } - return o.IP.String() -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts.go deleted file mode 100644 index b244f5a3a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts.go +++ /dev/null @@ -1,252 +0,0 @@ -package opts - -import ( - "fmt" - "net" - "os" - "regexp" - "strings" -) - -var ( - alphaRegexp = regexp.MustCompile(`[a-zA-Z]`) - domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`) -) - -// ListOpts holds a list of values and a validation function. -type ListOpts struct { - values *[]string - validator ValidatorFctType -} - -// NewListOpts creates a new ListOpts with the specified validator. -func NewListOpts(validator ValidatorFctType) ListOpts { - var values []string - return *NewListOptsRef(&values, validator) -} - -// NewListOptsRef creates a new ListOpts with the specified values and validator. -func NewListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts { - return &ListOpts{ - values: values, - validator: validator, - } -} - -func (opts *ListOpts) String() string { - return fmt.Sprintf("%v", []string((*opts.values))) -} - -// Set validates if needed the input value and add it to the -// internal slice. -func (opts *ListOpts) Set(value string) error { - if opts.validator != nil { - v, err := opts.validator(value) - if err != nil { - return err - } - value = v - } - (*opts.values) = append((*opts.values), value) - return nil -} - -// Delete removes the specified element from the slice. -func (opts *ListOpts) Delete(key string) { - for i, k := range *opts.values { - if k == key { - (*opts.values) = append((*opts.values)[:i], (*opts.values)[i+1:]...) - return - } - } -} - -// GetMap returns the content of values in a map in order to avoid -// duplicates. -func (opts *ListOpts) GetMap() map[string]struct{} { - ret := make(map[string]struct{}) - for _, k := range *opts.values { - ret[k] = struct{}{} - } - return ret -} - -// GetAll returns the values of slice. -func (opts *ListOpts) GetAll() []string { - return (*opts.values) -} - -// GetAllOrEmpty returns the values of the slice -// or an empty slice when there are no values. -func (opts *ListOpts) GetAllOrEmpty() []string { - v := *opts.values - if v == nil { - return make([]string, 0) - } - return v -} - -// Get checks the existence of the specified key. -func (opts *ListOpts) Get(key string) bool { - for _, k := range *opts.values { - if k == key { - return true - } - } - return false -} - -// Len returns the amount of element in the slice. -func (opts *ListOpts) Len() int { - return len((*opts.values)) -} - -//MapOpts holds a map of values and a validation function. -type MapOpts struct { - values map[string]string - validator ValidatorFctType -} - -// Set validates if needed the input value and add it to the -// internal map, by splitting on '='. -func (opts *MapOpts) Set(value string) error { - if opts.validator != nil { - v, err := opts.validator(value) - if err != nil { - return err - } - value = v - } - vals := strings.SplitN(value, "=", 2) - if len(vals) == 1 { - (opts.values)[vals[0]] = "" - } else { - (opts.values)[vals[0]] = vals[1] - } - return nil -} - -// GetAll returns the values of MapOpts as a map. -func (opts *MapOpts) GetAll() map[string]string { - return opts.values -} - -func (opts *MapOpts) String() string { - return fmt.Sprintf("%v", map[string]string((opts.values))) -} - -// NewMapOpts creates a new MapOpts with the specified map of values and a validator. -func NewMapOpts(values map[string]string, validator ValidatorFctType) *MapOpts { - if values == nil { - values = make(map[string]string) - } - return &MapOpts{ - values: values, - validator: validator, - } -} - -// ValidatorFctType defines a validator function that returns a validated string and/or an error. -type ValidatorFctType func(val string) (string, error) - -// ValidatorFctListType defines a validator function that returns a validated list of string and/or an error -type ValidatorFctListType func(val string) ([]string, error) - -// ValidateAttach validates that the specified string is a valid attach option. -func ValidateAttach(val string) (string, error) { - s := strings.ToLower(val) - for _, str := range []string{"stdin", "stdout", "stderr"} { - if s == str { - return s, nil - } - } - return val, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR") -} - -// ValidateEnv validates an environment variable and returns it. -// If no value is specified, it returns the current value using os.Getenv. -// -// As on ParseEnvFile and related to #16585, environment variable names -// are not validate what so ever, it's up to application inside docker -// to validate them or not. -func ValidateEnv(val string) (string, error) { - arr := strings.Split(val, "=") - if len(arr) > 1 { - return val, nil - } - if !doesEnvExist(val) { - return val, nil - } - return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil -} - -// ValidateIPAddress validates an Ip address. -func ValidateIPAddress(val string) (string, error) { - var ip = net.ParseIP(strings.TrimSpace(val)) - if ip != nil { - return ip.String(), nil - } - return "", fmt.Errorf("%s is not an ip address", val) -} - -// ValidateMACAddress validates a MAC address. -func ValidateMACAddress(val string) (string, error) { - _, err := net.ParseMAC(strings.TrimSpace(val)) - if err != nil { - return "", err - } - return val, nil -} - -// ValidateDNSSearch validates domain for resolvconf search configuration. -// A zero length domain is represented by a dot (.). -func ValidateDNSSearch(val string) (string, error) { - if val = strings.Trim(val, " "); val == "." { - return val, nil - } - return validateDomain(val) -} - -func validateDomain(val string) (string, error) { - if alphaRegexp.FindString(val) == "" { - return "", fmt.Errorf("%s is not a valid domain", val) - } - ns := domainRegexp.FindSubmatch([]byte(val)) - if len(ns) > 0 && len(ns[1]) < 255 { - return string(ns[1]), nil - } - return "", fmt.Errorf("%s is not a valid domain", val) -} - -// ValidateExtraHost validates that the specified string is a valid extrahost and returns it. -// ExtraHost are in the form of name:ip where the ip has to be a valid ip (ipv4 or ipv6). -func ValidateExtraHost(val string) (string, error) { - // allow for IPv6 addresses in extra hosts by only splitting on first ":" - arr := strings.SplitN(val, ":", 2) - if len(arr) != 2 || len(arr[0]) == 0 { - return "", fmt.Errorf("bad format for add-host: %q", val) - } - if _, err := ValidateIPAddress(arr[1]); err != nil { - return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1]) - } - return val, nil -} - -// ValidateLabel validates that the specified string is a valid label, and returns it. -// Labels are in the form on key=value. -func ValidateLabel(val string) (string, error) { - if strings.Count(val, "=") < 1 { - return "", fmt.Errorf("bad attribute format: %s", val) - } - return val, nil -} - -func doesEnvExist(name string) bool { - for _, entry := range os.Environ() { - parts := strings.SplitN(entry, "=", 2) - if parts[0] == name { - return true - } - } - return false -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_unix.go deleted file mode 100644 index f1ce844a8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !windows - -package opts - -// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker daemon -H tcp://:8080 -const DefaultHTTPHost = "localhost" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_windows.go deleted file mode 100644 index 2a9e2be74..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_windows.go +++ /dev/null @@ -1,56 +0,0 @@ -package opts - -// TODO Windows. Identify bug in GOLang 1.5.1 and/or Windows Server 2016 TP4. -// @jhowardmsft, @swernli. -// -// On Windows, this mitigates a problem with the default options of running -// a docker client against a local docker daemon on TP4. -// -// What was found that if the default host is "localhost", even if the client -// (and daemon as this is local) is not physically on a network, and the DNS -// cache is flushed (ipconfig /flushdns), then the client will pause for -// exactly one second when connecting to the daemon for calls. For example -// using docker run windowsservercore cmd, the CLI will send a create followed -// by an attach. You see the delay between the attach finishing and the attach -// being seen by the daemon. -// -// Here's some daemon debug logs with additional debug spew put in. The -// AfterWriteJSON log is the very last thing the daemon does as part of the -// create call. The POST /attach is the second CLI call. Notice the second -// time gap. -// -// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs" -// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig" -// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...." -// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking.... -// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...." -// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...." -// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func" -// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create" -// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2" -// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate" -// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON" -// ... 1 second gap here.... -// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach" -// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1" -// -// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change -// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows TP4. In theory, -// the Windows networking stack is supposed to resolve "localhost" internally, -// without hitting DNS, or even reading the hosts file (which is why localhost -// is commented out in the hosts file on Windows). -// -// We have validated that working around this using the actual IPv4 localhost -// address does not cause the delay. -// -// This does not occur with the docker client built with 1.4.3 on the same -// Windows TP4 build, regardless of whether the daemon is built using 1.5.1 -// or 1.4.3. It does not occur on Linux. We also verified we see the same thing -// on a cross-compiled Windows binary (from Linux). -// -// Final note: This is a mitigation, not a 'real' fix. It is still susceptible -// to the delay in TP4 if a user were to do 'docker run -H=tcp://localhost:2375...' -// explicitly. - -// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker daemon -H tcp://:8080 -const DefaultHTTPHost = "127.0.0.1" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/README.md deleted file mode 100644 index 7307d9694..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/README.md +++ /dev/null @@ -1 +0,0 @@ -This code provides helper functions for dealing with archive files. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go deleted file mode 100644 index ce84347d3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go +++ /dev/null @@ -1,1049 +0,0 @@ -package archive - -import ( - "archive/tar" - "bufio" - "bytes" - "compress/bzip2" - "compress/gzip" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "syscall" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -type ( - // Archive is a type of io.ReadCloser which has two interfaces Read and Closer. - Archive io.ReadCloser - // Reader is a type of io.Reader. - Reader io.Reader - // Compression is the state represents if compressed or not. - Compression int - // TarChownOptions wraps the chown options UID and GID. - TarChownOptions struct { - UID, GID int - } - // TarOptions wraps the tar options. - TarOptions struct { - IncludeFiles []string - ExcludePatterns []string - Compression Compression - NoLchown bool - UIDMaps []idtools.IDMap - GIDMaps []idtools.IDMap - ChownOpts *TarChownOptions - IncludeSourceDir bool - // When unpacking, specifies whether overwriting a directory with a - // non-directory is allowed and vice versa. - NoOverwriteDirNonDir bool - // For each include when creating an archive, the included name will be - // replaced with the matching name from this map. - RebaseNames map[string]string - } - - // Archiver allows the reuse of most utility functions of this package - // with a pluggable Untar function. Also, to facilitate the passing of - // specific id mappings for untar, an archiver can be created with maps - // which will then be passed to Untar operations - Archiver struct { - Untar func(io.Reader, string, *TarOptions) error - UIDMaps []idtools.IDMap - GIDMaps []idtools.IDMap - } - - // breakoutError is used to differentiate errors related to breaking out - // When testing archive breakout in the unit tests, this error is expected - // in order for the test to pass. - breakoutError error -) - -var ( - // ErrNotImplemented is the error message of function not implemented. - ErrNotImplemented = errors.New("Function not implemented") - defaultArchiver = &Archiver{Untar: Untar, UIDMaps: nil, GIDMaps: nil} -) - -const ( - // HeaderSize is the size in bytes of a tar header - HeaderSize = 512 -) - -const ( - // Uncompressed represents the uncompressed. - Uncompressed Compression = iota - // Bzip2 is bzip2 compression algorithm. - Bzip2 - // Gzip is gzip compression algorithm. - Gzip - // Xz is xz compression algorithm. - Xz -) - -// IsArchive checks for the magic bytes of a tar or any supported compression -// algorithm. -func IsArchive(header []byte) bool { - compression := DetectCompression(header) - if compression != Uncompressed { - return true - } - r := tar.NewReader(bytes.NewBuffer(header)) - _, err := r.Next() - return err == nil -} - -// IsArchivePath checks if the (possibly compressed) file at the given path -// starts with a tar file header. -func IsArchivePath(path string) bool { - file, err := os.Open(path) - if err != nil { - return false - } - defer file.Close() - rdr, err := DecompressStream(file) - if err != nil { - return false - } - r := tar.NewReader(rdr) - _, err = r.Next() - return err == nil -} - -// DetectCompression detects the compression algorithm of the source. -func DetectCompression(source []byte) Compression { - for compression, m := range map[Compression][]byte{ - Bzip2: {0x42, 0x5A, 0x68}, - Gzip: {0x1F, 0x8B, 0x08}, - Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, - } { - if len(source) < len(m) { - logrus.Debugf("Len too short") - continue - } - if bytes.Compare(m, source[:len(m)]) == 0 { - return compression - } - } - return Uncompressed -} - -func xzDecompress(archive io.Reader) (io.ReadCloser, <-chan struct{}, error) { - args := []string{"xz", "-d", "-c", "-q"} - - return cmdStream(exec.Command(args[0], args[1:]...), archive) -} - -// DecompressStream decompress the archive and returns a ReaderCloser with the decompressed archive. -func DecompressStream(archive io.Reader) (io.ReadCloser, error) { - p := pools.BufioReader32KPool - buf := p.Get(archive) - bs, err := buf.Peek(10) - if err != nil && err != io.EOF { - // Note: we'll ignore any io.EOF error because there are some odd - // cases where the layer.tar file will be empty (zero bytes) and - // that results in an io.EOF from the Peek() call. So, in those - // cases we'll just treat it as a non-compressed stream and - // that means just create an empty layer. - // See Issue 18170 - return nil, err - } - - compression := DetectCompression(bs) - switch compression { - case Uncompressed: - readBufWrapper := p.NewReadCloserWrapper(buf, buf) - return readBufWrapper, nil - case Gzip: - gzReader, err := gzip.NewReader(buf) - if err != nil { - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) - return readBufWrapper, nil - case Bzip2: - bz2Reader := bzip2.NewReader(buf) - readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) - return readBufWrapper, nil - case Xz: - xzReader, chdone, err := xzDecompress(buf) - if err != nil { - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) - return ioutils.NewReadCloserWrapper(readBufWrapper, func() error { - <-chdone - return readBufWrapper.Close() - }), nil - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// CompressStream compresses the dest with specified compression algorithm. -func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) { - p := pools.BufioWriter32KPool - buf := p.Get(dest) - switch compression { - case Uncompressed: - writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) - return writeBufWrapper, nil - case Gzip: - gzWriter := gzip.NewWriter(dest) - writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) - return writeBufWrapper, nil - case Bzip2, Xz: - // archive/bzip2 does not support writing, and there is no xz support at all - // However, this is not a problem as docker only currently generates gzipped tars - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// Extension returns the extension of a file that uses the specified compression algorithm. -func (compression *Compression) Extension() string { - switch *compression { - case Uncompressed: - return "tar" - case Bzip2: - return "tar.bz2" - case Gzip: - return "tar.gz" - case Xz: - return "tar.xz" - } - return "" -} - -type tarAppender struct { - TarWriter *tar.Writer - Buffer *bufio.Writer - - // for hardlink mapping - SeenFiles map[uint64]string - UIDMaps []idtools.IDMap - GIDMaps []idtools.IDMap -} - -// canonicalTarName provides a platform-independent and consistent posix-style -//path for files and directories to be archived regardless of the platform. -func canonicalTarName(name string, isDir bool) (string, error) { - name, err := CanonicalTarNameForPath(name) - if err != nil { - return "", err - } - - // suffix with '/' for directories - if isDir && !strings.HasSuffix(name, "/") { - name += "/" - } - return name, nil -} - -func (ta *tarAppender) addTarFile(path, name string) error { - fi, err := os.Lstat(path) - if err != nil { - return err - } - - link := "" - if fi.Mode()&os.ModeSymlink != 0 { - if link, err = os.Readlink(path); err != nil { - return err - } - } - - hdr, err := tar.FileInfoHeader(fi, link) - if err != nil { - return err - } - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) - - name, err = canonicalTarName(name, fi.IsDir()) - if err != nil { - return fmt.Errorf("tar: cannot canonicalize path: %v", err) - } - hdr.Name = name - - inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys()) - if err != nil { - return err - } - - // if it's not a directory and has more than 1 link, - // it's hardlinked, so set the type flag accordingly - if !fi.IsDir() && hasHardlinks(fi) { - // a link should have a name that it links too - // and that linked name should be first in the tar archive - if oldpath, ok := ta.SeenFiles[inode]; ok { - hdr.Typeflag = tar.TypeLink - hdr.Linkname = oldpath - hdr.Size = 0 // This Must be here for the writer math to add up! - } else { - ta.SeenFiles[inode] = name - } - } - - capability, _ := system.Lgetxattr(path, "security.capability") - if capability != nil { - hdr.Xattrs = make(map[string]string) - hdr.Xattrs["security.capability"] = string(capability) - } - - //handle re-mapping container ID mappings back to host ID mappings before - //writing tar headers/files. We skip whiteout files because they were written - //by the kernel and already have proper ownership relative to the host - if !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && (ta.UIDMaps != nil || ta.GIDMaps != nil) { - uid, gid, err := getFileUIDGID(fi.Sys()) - if err != nil { - return err - } - xUID, err := idtools.ToContainer(uid, ta.UIDMaps) - if err != nil { - return err - } - xGID, err := idtools.ToContainer(gid, ta.GIDMaps) - if err != nil { - return err - } - hdr.Uid = xUID - hdr.Gid = xGID - } - - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - return err - } - - if hdr.Typeflag == tar.TypeReg { - file, err := os.Open(path) - if err != nil { - return err - } - - ta.Buffer.Reset(ta.TarWriter) - defer ta.Buffer.Reset(nil) - _, err = io.Copy(ta.Buffer, file) - file.Close() - if err != nil { - return err - } - err = ta.Buffer.Flush() - if err != nil { - return err - } - } - - return nil -} - -func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions) error { - // hdr.Mode is in linux format, which we can use for sycalls, - // but for os.Foo() calls we need the mode converted to os.FileMode, - // so use hdrInfo.Mode() (they differ for e.g. setuid bits) - hdrInfo := hdr.FileInfo() - - switch hdr.Typeflag { - case tar.TypeDir: - // Create directory unless it exists as a directory already. - // In that case we just want to merge the two - if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { - if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { - return err - } - } - - case tar.TypeReg, tar.TypeRegA: - // Source is regular file - file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) - if err != nil { - return err - } - if _, err := io.Copy(file, reader); err != nil { - file.Close() - return err - } - file.Close() - - case tar.TypeBlock, tar.TypeChar, tar.TypeFifo: - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { - return err - } - - case tar.TypeLink: - targetPath := filepath.Join(extractDir, hdr.Linkname) - // check for hardlink breakout - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) - } - if err := os.Link(targetPath, path); err != nil { - return err - } - - case tar.TypeSymlink: - // path -> hdr.Linkname = targetPath - // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file - targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) - - // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because - // that symlink would first have to be created, which would be caught earlier, at this very check: - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) - } - if err := os.Symlink(hdr.Linkname, path); err != nil { - return err - } - - case tar.TypeXGlobalHeader: - logrus.Debugf("PAX Global Extended Headers found and ignored") - return nil - - default: - return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag) - } - - // Lchown is not supported on Windows. - if Lchown && runtime.GOOS != "windows" { - if chownOpts == nil { - chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid} - } - if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { - return err - } - } - - for key, value := range hdr.Xattrs { - if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { - return err - } - } - - // There is no LChmod, so ignore mode for symlink. Also, this - // must happen after chown, as that can modify the file mode - if err := handleLChmod(hdr, path, hdrInfo); err != nil { - return err - } - - aTime := hdr.AccessTime - if aTime.Before(hdr.ModTime) { - // Last access time should never be before last modified time. - aTime = hdr.ModTime - } - - // system.Chtimes doesn't support a NOFOLLOW flag atm - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } else { - ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)} - if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { - return err - } - } - return nil -} - -// Tar creates an archive from the directory at `path`, and returns it as a -// stream of bytes. -func Tar(path string, compression Compression) (io.ReadCloser, error) { - return TarWithOptions(path, &TarOptions{Compression: compression}) -} - -// TarWithOptions creates an archive from the directory at `path`, only including files whose relative -// paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. -func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { - - // Fix the source path to work with long path names. This is a no-op - // on platforms other than Windows. - srcPath = fixVolumePathPrefix(srcPath) - - patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns) - - if err != nil { - return nil, err - } - - pipeReader, pipeWriter := io.Pipe() - - compressWriter, err := CompressStream(pipeWriter, options.Compression) - if err != nil { - return nil, err - } - - go func() { - ta := &tarAppender{ - TarWriter: tar.NewWriter(compressWriter), - Buffer: pools.BufioWriter32KPool.Get(nil), - SeenFiles: make(map[uint64]string), - UIDMaps: options.UIDMaps, - GIDMaps: options.GIDMaps, - } - - defer func() { - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Debugf("Can't close tar writer: %s", err) - } - if err := compressWriter.Close(); err != nil { - logrus.Debugf("Can't close compress writer: %s", err) - } - if err := pipeWriter.Close(); err != nil { - logrus.Debugf("Can't close pipe writer: %s", err) - } - }() - - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - - stat, err := os.Lstat(srcPath) - if err != nil { - return - } - - if !stat.IsDir() { - // We can't later join a non-dir with any includes because the - // 'walk' will error if "file/." is stat-ed and "file" is not a - // directory. So, we must split the source path and use the - // basename as the include. - if len(options.IncludeFiles) > 0 { - logrus.Warn("Tar: Can't archive a file with includes") - } - - dir, base := SplitPathDirEntry(srcPath) - srcPath = dir - options.IncludeFiles = []string{base} - } - - if len(options.IncludeFiles) == 0 { - options.IncludeFiles = []string{"."} - } - - seen := make(map[string]bool) - - for _, include := range options.IncludeFiles { - rebaseName := options.RebaseNames[include] - - walkRoot := getWalkRoot(srcPath, include) - filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { - if err != nil { - logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) - return nil - } - - relFilePath, err := filepath.Rel(srcPath, filePath) - if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { - // Error getting relative path OR we are looking - // at the source directory path. Skip in both situations. - return nil - } - - if options.IncludeSourceDir && include == "." && relFilePath != "." { - relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) - } - - skip := false - - // If "include" is an exact match for the current file - // then even if there's an "excludePatterns" pattern that - // matches it, don't skip it. IOW, assume an explicit 'include' - // is asking for that file no matter what - which is true - // for some files, like .dockerignore and Dockerfile (sometimes) - if include != relFilePath { - skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs) - if err != nil { - logrus.Debugf("Error matching %s: %v", relFilePath, err) - return err - } - } - - if skip { - if !exceptions && f.IsDir() { - return filepath.SkipDir - } - return nil - } - - if seen[relFilePath] { - return nil - } - seen[relFilePath] = true - - // Rename the base resource. - if rebaseName != "" { - var replacement string - if rebaseName != string(filepath.Separator) { - // Special case the root directory to replace with an - // empty string instead so that we don't end up with - // double slashes in the paths. - replacement = rebaseName - } - - relFilePath = strings.Replace(relFilePath, include, replacement, 1) - } - - if err := ta.addTarFile(filePath, relFilePath); err != nil { - logrus.Debugf("Can't add file %s to tar: %s", filePath, err) - } - return nil - }) - } - }() - - return pipeReader, nil -} - -// Unpack unpacks the decompressedArchive to dest with options. -func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { - tr := tar.NewReader(decompressedArchive) - trBuf := pools.BufioReader32KPool.Get(nil) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps) - if err != nil { - return err - } - - // Iterate through the files in the archive. -loop: - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return err - } - - // Normalize name, for safety and for a simple is-root check - // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: - // This keeps "..\" as-is, but normalizes "\..\" to "\". - hdr.Name = filepath.Clean(hdr.Name) - - for _, exclude := range options.ExcludePatterns { - if strings.HasPrefix(hdr.Name, exclude) { - continue loop - } - } - - // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in - // the filepath format for the OS on which the daemon is running. Hence - // the check for a slash-suffix MUST be done in an OS-agnostic way. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = system.MkdirAll(parentPath, 0777) - if err != nil { - return err - } - } - } - - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return err - } - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - - // If path exits we almost always just want to remove and replace it - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing directory with a non-directory from the archive. - return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) - } - - if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing non-directory with a directory from the archive. - return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) - } - - if fi.IsDir() && hdr.Name == "." { - continue - } - - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return err - } - } - } - trBuf.Reset(tr) - - // if the options contain a uid & gid maps, convert header uid/gid - // entries using the maps such that lchown sets the proper mapped - // uid/gid after writing the file. We only perform this mapping if - // the file isn't already owned by the remapped root UID or GID, as - // that specific uid/gid has no mapping from container -> host, and - // those files already have the proper ownership for inside the - // container. - if hdr.Uid != remappedRootUID { - xUID, err := idtools.ToHost(hdr.Uid, options.UIDMaps) - if err != nil { - return err - } - hdr.Uid = xUID - } - if hdr.Gid != remappedRootGID { - xGID, err := idtools.ToHost(hdr.Gid, options.GIDMaps) - if err != nil { - return err - } - hdr.Gid = xGID - } - - if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts); err != nil { - return err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - } - - for _, hdr := range dirs { - path := filepath.Join(dest, hdr.Name) - - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return err - } - } - return nil -} - -// Untar reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive may be compressed with one of the following algorithms: -// identity (uncompressed), gzip, bzip2, xz. -// FIXME: specify behavior when target path exists vs. doesn't exist. -func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, true) -} - -// UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive must be an uncompressed stream. -func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, false) -} - -// Handler for teasing out the automatic decompression -func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { - if tarArchive == nil { - return fmt.Errorf("Empty archive") - } - dest = filepath.Clean(dest) - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - - r := tarArchive - if decompress { - decompressedArchive, err := DecompressStream(tarArchive) - if err != nil { - return err - } - defer decompressedArchive.Close() - r = decompressedArchive - } - - return Unpack(r, dest, options) -} - -// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. -// If either Tar or Untar fails, TarUntar aborts and returns the error. -func (archiver *Archiver) TarUntar(src, dst string) error { - logrus.Debugf("TarUntar(%s %s)", src, dst) - archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) - if err != nil { - return err - } - defer archive.Close() - - var options *TarOptions - if archiver.UIDMaps != nil || archiver.GIDMaps != nil { - options = &TarOptions{ - UIDMaps: archiver.UIDMaps, - GIDMaps: archiver.GIDMaps, - } - } - return archiver.Untar(archive, dst, options) -} - -// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. -// If either Tar or Untar fails, TarUntar aborts and returns the error. -func TarUntar(src, dst string) error { - return defaultArchiver.TarUntar(src, dst) -} - -// UntarPath untar a file from path to a destination, src is the source tar file path. -func (archiver *Archiver) UntarPath(src, dst string) error { - archive, err := os.Open(src) - if err != nil { - return err - } - defer archive.Close() - var options *TarOptions - if archiver.UIDMaps != nil || archiver.GIDMaps != nil { - options = &TarOptions{ - UIDMaps: archiver.UIDMaps, - GIDMaps: archiver.GIDMaps, - } - } - return archiver.Untar(archive, dst, options) -} - -// UntarPath is a convenience function which looks for an archive -// at filesystem path `src`, and unpacks it at `dst`. -func UntarPath(src, dst string) error { - return defaultArchiver.UntarPath(src, dst) -} - -// CopyWithTar creates a tar archive of filesystem path `src`, and -// unpacks it at filesystem path `dst`. -// The archive is streamed directly with fixed buffering and no -// intermediary disk IO. -func (archiver *Archiver) CopyWithTar(src, dst string) error { - srcSt, err := os.Stat(src) - if err != nil { - return err - } - if !srcSt.IsDir() { - return archiver.CopyFileWithTar(src, dst) - } - // Create dst, copy src's content into it - logrus.Debugf("Creating dest directory: %s", dst) - if err := system.MkdirAll(dst, 0755); err != nil { - return err - } - logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) - return archiver.TarUntar(src, dst) -} - -// CopyWithTar creates a tar archive of filesystem path `src`, and -// unpacks it at filesystem path `dst`. -// The archive is streamed directly with fixed buffering and no -// intermediary disk IO. -func CopyWithTar(src, dst string) error { - return defaultArchiver.CopyWithTar(src, dst) -} - -// CopyFileWithTar emulates the behavior of the 'cp' command-line -// for a single file. It copies a regular file from path `src` to -// path `dst`, and preserves all its metadata. -func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { - logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) - srcSt, err := os.Stat(src) - if err != nil { - return err - } - - if srcSt.IsDir() { - return fmt.Errorf("Can't copy a directory") - } - - // Clean up the trailing slash. This must be done in an operating - // system specific manner. - if dst[len(dst)-1] == os.PathSeparator { - dst = filepath.Join(dst, filepath.Base(src)) - } - // Create the holding directory if necessary - if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil { - return err - } - - r, w := io.Pipe() - errC := promise.Go(func() error { - defer w.Close() - - srcF, err := os.Open(src) - if err != nil { - return err - } - defer srcF.Close() - - hdr, err := tar.FileInfoHeader(srcSt, "") - if err != nil { - return err - } - hdr.Name = filepath.Base(dst) - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) - - remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(archiver.UIDMaps, archiver.GIDMaps) - if err != nil { - return err - } - - // only perform mapping if the file being copied isn't already owned by the - // uid or gid of the remapped root in the container - if remappedRootUID != hdr.Uid { - xUID, err := idtools.ToHost(hdr.Uid, archiver.UIDMaps) - if err != nil { - return err - } - hdr.Uid = xUID - } - if remappedRootGID != hdr.Gid { - xGID, err := idtools.ToHost(hdr.Gid, archiver.GIDMaps) - if err != nil { - return err - } - hdr.Gid = xGID - } - - tw := tar.NewWriter(w) - defer tw.Close() - if err := tw.WriteHeader(hdr); err != nil { - return err - } - if _, err := io.Copy(tw, srcF); err != nil { - return err - } - return nil - }) - defer func() { - if er := <-errC; err != nil { - err = er - } - }() - - err = archiver.Untar(r, filepath.Dir(dst), nil) - if err != nil { - r.CloseWithError(err) - } - return err -} - -// CopyFileWithTar emulates the behavior of the 'cp' command-line -// for a single file. It copies a regular file from path `src` to -// path `dst`, and preserves all its metadata. -// -// Destination handling is in an operating specific manner depending -// where the daemon is running. If `dst` ends with a trailing slash -// the final destination path will be `dst/base(src)` (Linux) or -// `dst\base(src)` (Windows). -func CopyFileWithTar(src, dst string) (err error) { - return defaultArchiver.CopyFileWithTar(src, dst) -} - -// cmdStream executes a command, and returns its stdout as a stream. -// If the command fails to run or doesn't complete successfully, an error -// will be returned, including anything written on stderr. -func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, <-chan struct{}, error) { - chdone := make(chan struct{}) - cmd.Stdin = input - pipeR, pipeW := io.Pipe() - cmd.Stdout = pipeW - var errBuf bytes.Buffer - cmd.Stderr = &errBuf - - // Run the command and return the pipe - if err := cmd.Start(); err != nil { - return nil, nil, err - } - - // Copy stdout to the returned pipe - go func() { - if err := cmd.Wait(); err != nil { - pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) - } else { - pipeW.Close() - } - close(chdone) - }() - - return pipeR, chdone, nil -} - -// NewTempArchive reads the content of src into a temporary file, and returns the contents -// of that file as an archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -func NewTempArchive(src Archive, dir string) (*TempArchive, error) { - f, err := ioutil.TempFile(dir, "") - if err != nil { - return nil, err - } - if _, err := io.Copy(f, src); err != nil { - return nil, err - } - if _, err := f.Seek(0, 0); err != nil { - return nil, err - } - st, err := f.Stat() - if err != nil { - return nil, err - } - size := st.Size() - return &TempArchive{File: f, Size: size}, nil -} - -// TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -type TempArchive struct { - *os.File - Size int64 // Pre-computed from Stat().Size() as a convenience - read int64 - closed bool -} - -// Close closes the underlying file if it's still open, or does a no-op -// to allow callers to try to close the TempArchive multiple times safely. -func (archive *TempArchive) Close() error { - if archive.closed { - return nil - } - - archive.closed = true - - return archive.File.Close() -} - -func (archive *TempArchive) Read(data []byte) (int, error) { - n, err := archive.File.Read(data) - archive.read += int64(n) - if err != nil || archive.read == archive.Size { - archive.Close() - os.Remove(archive.File.Name()) - } - return n, err -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix.go deleted file mode 100644 index 86c688825..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build !windows - -package archive - -import ( - "archive/tar" - "errors" - "os" - "path/filepath" - "syscall" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return srcPath -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. On Linux, we -// can't use filepath.Join(srcPath,include) because this will clean away -// a trailing "." or "/" which may be important. -func getWalkRoot(srcPath string, include string) string { - return srcPath + string(filepath.Separator) + include -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) (string, error) { - return p, nil // already unix-style -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. - -func chmodTarEntry(perm os.FileMode) os.FileMode { - return perm // noop for unix as golang APIs provide perm bits correctly -} - -func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (inode uint64, err error) { - s, ok := stat.(*syscall.Stat_t) - - if !ok { - err = errors.New("cannot convert stat value to syscall.Stat_t") - return - } - - inode = uint64(s.Ino) - - // Currently go does not fill in the major/minors - if s.Mode&syscall.S_IFBLK != 0 || - s.Mode&syscall.S_IFCHR != 0 { - hdr.Devmajor = int64(major(uint64(s.Rdev))) - hdr.Devminor = int64(minor(uint64(s.Rdev))) - } - - return -} - -func getFileUIDGID(stat interface{}) (int, int, error) { - s, ok := stat.(*syscall.Stat_t) - - if !ok { - return -1, -1, errors.New("cannot convert stat value to syscall.Stat_t") - } - return int(s.Uid), int(s.Gid), nil -} - -func major(device uint64) uint64 { - return (device >> 8) & 0xfff -} - -func minor(device uint64) uint64 { - return (device & 0xff) | ((device >> 12) & 0xfff00) -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - mode := uint32(hdr.Mode & 07777) - switch hdr.Typeflag { - case tar.TypeBlock: - mode |= syscall.S_IFBLK - case tar.TypeChar: - mode |= syscall.S_IFCHR - case tar.TypeFifo: - mode |= syscall.S_IFIFO - } - - if err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))); err != nil { - return err - } - return nil -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows.go deleted file mode 100644 index 23d60aa41..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build windows - -package archive - -import ( - "archive/tar" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath" -) - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return longpath.AddPrefix(srcPath) -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. -func getWalkRoot(srcPath string, include string) string { - return filepath.Join(srcPath, include) -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) (string, error) { - // windows: convert windows style relative path with backslashes - // into forward slashes. Since windows does not allow '/' or '\' - // in file names, it is mostly safe to replace however we must - // check just in case - if strings.Contains(p, "/") { - return "", fmt.Errorf("Windows path contains forward slash: %s", p) - } - return strings.Replace(p, string(os.PathSeparator), "/", -1), nil - -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { - perm &= 0755 - // Add the x bit: make everything +x from windows - perm |= 0111 - - return perm -} - -func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (inode uint64, err error) { - // do nothing. no notion of Rdev, Inode, Nlink in stat on Windows - return -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - return nil -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - return nil -} - -func getFileUIDGID(stat interface{}) (int, int, error) { - // no notion of file ownership mapping yet on Windows - return 0, 0, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes.go deleted file mode 100644 index a2a1dc36e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes.go +++ /dev/null @@ -1,416 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - "syscall" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// ChangeType represents the change type. -type ChangeType int - -const ( - // ChangeModify represents the modify operation. - ChangeModify = iota - // ChangeAdd represents the add operation. - ChangeAdd - // ChangeDelete represents the delete operation. - ChangeDelete -) - -func (c ChangeType) String() string { - switch c { - case ChangeModify: - return "C" - case ChangeAdd: - return "A" - case ChangeDelete: - return "D" - } - return "" -} - -// Change represents a change, it wraps the change type and path. -// It describes changes of the files in the path respect to the -// parent layers. The change could be modify, add, delete. -// This is used for layer diff. -type Change struct { - Path string - Kind ChangeType -} - -func (change *Change) String() string { - return fmt.Sprintf("%s %s", change.Kind, change.Path) -} - -// for sort.Sort -type changesByPath []Change - -func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } -func (c changesByPath) Len() int { return len(c) } -func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } - -// Gnu tar and the go tar writer don't have sub-second mtime -// precision, which is problematic when we apply changes via tar -// files, we handle this by comparing for exact times, *or* same -// second count and either a or b having exactly 0 nanoseconds -func sameFsTime(a, b time.Time) bool { - return a == b || - (a.Unix() == b.Unix() && - (a.Nanosecond() == 0 || b.Nanosecond() == 0)) -} - -func sameFsTimeSpec(a, b syscall.Timespec) bool { - return a.Sec == b.Sec && - (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) -} - -// Changes walks the path rw and determines changes for the files in the path, -// with respect to the parent layers -func Changes(layers []string, rw string) ([]Change, error) { - var ( - changes []Change - changedDirs = make(map[string]struct{}) - ) - - err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(rw, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - // Skip AUFS metadata - if matched, err := filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path); err != nil || matched { - return err - } - - change := Change{ - Path: path, - } - - // Find out what kind of modification happened - file := filepath.Base(path) - // If there is a whiteout, then the file was removed - if strings.HasPrefix(file, WhiteoutPrefix) { - originalFile := file[len(WhiteoutPrefix):] - change.Path = filepath.Join(filepath.Dir(path), originalFile) - change.Kind = ChangeDelete - } else { - // Otherwise, the file was added - change.Kind = ChangeAdd - - // ...Unless it already existed in a top layer, in which case, it's a modification - for _, layer := range layers { - stat, err := os.Stat(filepath.Join(layer, path)) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil { - // The file existed in the top layer, so that's a modification - - // However, if it's a directory, maybe it wasn't actually modified. - // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar - if stat.IsDir() && f.IsDir() { - if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { - // Both directories are the same, don't record the change - return nil - } - } - change.Kind = ChangeModify - break - } - } - } - - // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. - // This block is here to ensure the change is recorded even if the - // modify time, mode and size of the parent directory in the rw and ro layers are all equal. - // Check https://github.com/docker/docker/pull/13590 for details. - if f.IsDir() { - changedDirs[path] = struct{}{} - } - if change.Kind == ChangeAdd || change.Kind == ChangeDelete { - parent := filepath.Dir(path) - if _, ok := changedDirs[parent]; !ok && parent != "/" { - changes = append(changes, Change{Path: parent, Kind: ChangeModify}) - changedDirs[parent] = struct{}{} - } - } - - // Record change - changes = append(changes, change) - return nil - }) - if err != nil && !os.IsNotExist(err) { - return nil, err - } - return changes, nil -} - -// FileInfo describes the information of a file. -type FileInfo struct { - parent *FileInfo - name string - stat *system.StatT - children map[string]*FileInfo - capability []byte - added bool -} - -// LookUp looks up the file information of a file. -func (info *FileInfo) LookUp(path string) *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - parent := info - if path == string(os.PathSeparator) { - return info - } - - pathElements := strings.Split(path, string(os.PathSeparator)) - for _, elem := range pathElements { - if elem != "" { - child := parent.children[elem] - if child == nil { - return nil - } - parent = child - } - } - return parent -} - -func (info *FileInfo) path() string { - if info.parent == nil { - // As this runs on the daemon side, file paths are OS specific. - return string(os.PathSeparator) - } - return filepath.Join(info.parent.path(), info.name) -} - -func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { - - sizeAtEntry := len(*changes) - - if oldInfo == nil { - // add - change := Change{ - Path: info.path(), - Kind: ChangeAdd, - } - *changes = append(*changes, change) - info.added = true - } - - // We make a copy so we can modify it to detect additions - // also, we only recurse on the old dir if the new info is a directory - // otherwise any previous delete/change is considered recursive - oldChildren := make(map[string]*FileInfo) - if oldInfo != nil && info.isDir() { - for k, v := range oldInfo.children { - oldChildren[k] = v - } - } - - for name, newChild := range info.children { - oldChild, _ := oldChildren[name] - if oldChild != nil { - // change? - oldStat := oldChild.stat - newStat := newChild.stat - // Note: We can't compare inode or ctime or blocksize here, because these change - // when copying a file into a container. However, that is not generally a problem - // because any content change will change mtime, and any status change should - // be visible when actually comparing the stat fields. The only time this - // breaks down is if some code intentionally hides a change by setting - // back mtime - if statDifferent(oldStat, newStat) || - bytes.Compare(oldChild.capability, newChild.capability) != 0 { - change := Change{ - Path: newChild.path(), - Kind: ChangeModify, - } - *changes = append(*changes, change) - newChild.added = true - } - - // Remove from copy so we can detect deletions - delete(oldChildren, name) - } - - newChild.addChanges(oldChild, changes) - } - for _, oldChild := range oldChildren { - // delete - change := Change{ - Path: oldChild.path(), - Kind: ChangeDelete, - } - *changes = append(*changes, change) - } - - // If there were changes inside this directory, we need to add it, even if the directory - // itself wasn't changed. This is needed to properly save and restore filesystem permissions. - // As this runs on the daemon side, file paths are OS specific. - if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { - change := Change{ - Path: info.path(), - Kind: ChangeModify, - } - // Let's insert the directory entry before the recently added entries located inside this dir - *changes = append(*changes, change) // just to resize the slice, will be overwritten - copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) - (*changes)[sizeAtEntry] = change - } - -} - -// Changes add changes to file information. -func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { - var changes []Change - - info.addChanges(oldInfo, &changes) - - return changes -} - -func newRootFileInfo() *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - root := &FileInfo{ - name: string(os.PathSeparator), - children: make(map[string]*FileInfo), - } - return root -} - -// ChangesDirs compares two directories and generates an array of Change objects describing the changes. -// If oldDir is "", then all files in newDir will be Add-Changes. -func ChangesDirs(newDir, oldDir string) ([]Change, error) { - var ( - oldRoot, newRoot *FileInfo - ) - if oldDir == "" { - emptyDir, err := ioutil.TempDir("", "empty") - if err != nil { - return nil, err - } - defer os.Remove(emptyDir) - oldDir = emptyDir - } - oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) - if err != nil { - return nil, err - } - - return newRoot.Changes(oldRoot), nil -} - -// ChangesSize calculates the size in bytes of the provided changes, based on newDir. -func ChangesSize(newDir string, changes []Change) int64 { - var ( - size int64 - sf = make(map[uint64]struct{}) - ) - for _, change := range changes { - if change.Kind == ChangeModify || change.Kind == ChangeAdd { - file := filepath.Join(newDir, change.Path) - fileInfo, err := os.Lstat(file) - if err != nil { - logrus.Errorf("Can not stat %q: %s", file, err) - continue - } - - if fileInfo != nil && !fileInfo.IsDir() { - if hasHardlinks(fileInfo) { - inode := getIno(fileInfo) - if _, ok := sf[inode]; !ok { - size += fileInfo.Size() - sf[inode] = struct{}{} - } - } else { - size += fileInfo.Size() - } - } - } - } - return size -} - -// ExportChanges produces an Archive from the provided changes, relative to dir. -func ExportChanges(dir string, changes []Change, uidMaps, gidMaps []idtools.IDMap) (Archive, error) { - reader, writer := io.Pipe() - go func() { - ta := &tarAppender{ - TarWriter: tar.NewWriter(writer), - Buffer: pools.BufioWriter32KPool.Get(nil), - SeenFiles: make(map[uint64]string), - UIDMaps: uidMaps, - GIDMaps: gidMaps, - } - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - sort.Sort(changesByPath(changes)) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - for _, change := range changes { - if change.Kind == ChangeDelete { - whiteOutDir := filepath.Dir(change.Path) - whiteOutBase := filepath.Base(change.Path) - whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) - timestamp := time.Now() - hdr := &tar.Header{ - Name: whiteOut[1:], - Size: 0, - ModTime: timestamp, - AccessTime: timestamp, - ChangeTime: timestamp, - } - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - logrus.Debugf("Can't write whiteout header: %s", err) - } - } else { - path := filepath.Join(dir, change.Path) - if err := ta.addTarFile(path, change.Path[1:]); err != nil { - logrus.Debugf("Can't add file %s to tar: %s", path, err) - } - } - } - - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Debugf("Can't close layer: %s", err) - } - if err := writer.Close(); err != nil { - logrus.Debugf("failed close Changes writer: %s", err) - } - }() - return reader, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_linux.go deleted file mode 100644 index 378cc09c8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_linux.go +++ /dev/null @@ -1,285 +0,0 @@ -package archive - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "sort" - "syscall" - "unsafe" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// walker is used to implement collectFileInfoForChanges on linux. Where this -// method in general returns the entire contents of two directory trees, we -// optimize some FS calls out on linux. In particular, we take advantage of the -// fact that getdents(2) returns the inode of each file in the directory being -// walked, which, when walking two trees in parallel to generate a list of -// changes, can be used to prune subtrees without ever having to lstat(2) them -// directly. Eliminating stat calls in this way can save up to seconds on large -// images. -type walker struct { - dir1 string - dir2 string - root1 *FileInfo - root2 *FileInfo -} - -// collectFileInfoForChanges returns a complete representation of the trees -// rooted at dir1 and dir2, with one important exception: any subtree or -// leaf where the inode and device numbers are an exact match between dir1 -// and dir2 will be pruned from the results. This method is *only* to be used -// to generating a list of changes between the two directories, as it does not -// reflect the full contents. -func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { - w := &walker{ - dir1: dir1, - dir2: dir2, - root1: newRootFileInfo(), - root2: newRootFileInfo(), - } - - i1, err := os.Lstat(w.dir1) - if err != nil { - return nil, nil, err - } - i2, err := os.Lstat(w.dir2) - if err != nil { - return nil, nil, err - } - - if err := w.walk("/", i1, i2); err != nil { - return nil, nil, err - } - - return w.root1, w.root2, nil -} - -// Given a FileInfo, its path info, and a reference to the root of the tree -// being constructed, register this file with the tree. -func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { - if fi == nil { - return nil - } - parent := root.LookUp(filepath.Dir(path)) - if parent == nil { - return fmt.Errorf("collectFileInfoForChanges: Unexpectedly no parent for %s", path) - } - info := &FileInfo{ - name: filepath.Base(path), - children: make(map[string]*FileInfo), - parent: parent, - } - cpath := filepath.Join(dir, path) - stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) - if err != nil { - return err - } - info.stat = stat - info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access - parent.children[info.name] = info - return nil -} - -// Walk a subtree rooted at the same path in both trees being iterated. For -// example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d -func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { - // Register these nodes with the return trees, unless we're still at the - // (already-created) roots: - if path != "/" { - if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { - return err - } - if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { - return err - } - } - - is1Dir := i1 != nil && i1.IsDir() - is2Dir := i2 != nil && i2.IsDir() - - sameDevice := false - if i1 != nil && i2 != nil { - si1 := i1.Sys().(*syscall.Stat_t) - si2 := i2.Sys().(*syscall.Stat_t) - if si1.Dev == si2.Dev { - sameDevice = true - } - } - - // If these files are both non-existent, or leaves (non-dirs), we are done. - if !is1Dir && !is2Dir { - return nil - } - - // Fetch the names of all the files contained in both directories being walked: - var names1, names2 []nameIno - if is1Dir { - names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access - if err != nil { - return err - } - } - if is2Dir { - names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access - if err != nil { - return err - } - } - - // We have lists of the files contained in both parallel directories, sorted - // in the same order. Walk them in parallel, generating a unique merged list - // of all items present in either or both directories. - var names []string - ix1 := 0 - ix2 := 0 - - for { - if ix1 >= len(names1) { - break - } - if ix2 >= len(names2) { - break - } - - ni1 := names1[ix1] - ni2 := names2[ix2] - - switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { - case -1: // ni1 < ni2 -- advance ni1 - // we will not encounter ni1 in names2 - names = append(names, ni1.name) - ix1++ - case 0: // ni1 == ni2 - if ni1.ino != ni2.ino || !sameDevice { - names = append(names, ni1.name) - } - ix1++ - ix2++ - case 1: // ni1 > ni2 -- advance ni2 - // we will not encounter ni2 in names1 - names = append(names, ni2.name) - ix2++ - } - } - for ix1 < len(names1) { - names = append(names, names1[ix1].name) - ix1++ - } - for ix2 < len(names2) { - names = append(names, names2[ix2].name) - ix2++ - } - - // For each of the names present in either or both of the directories being - // iterated, stat the name under each root, and recurse the pair of them: - for _, name := range names { - fname := filepath.Join(path, name) - var cInfo1, cInfo2 os.FileInfo - if is1Dir { - cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if is2Dir { - cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if err = w.walk(fname, cInfo1, cInfo2); err != nil { - return err - } - } - return nil -} - -// {name,inode} pairs used to support the early-pruning logic of the walker type -type nameIno struct { - name string - ino uint64 -} - -type nameInoSlice []nameIno - -func (s nameInoSlice) Len() int { return len(s) } -func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } - -// readdirnames is a hacked-apart version of the Go stdlib code, exposing inode -// numbers further up the stack when reading directory contents. Unlike -// os.Readdirnames, which returns a list of filenames, this function returns a -// list of {filename,inode} pairs. -func readdirnames(dirname string) (names []nameIno, err error) { - var ( - size = 100 - buf = make([]byte, 4096) - nbuf int - bufp int - nb int - ) - - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - defer f.Close() - - names = make([]nameIno, 0, size) // Empty with room to grow. - for { - // Refill the buffer if necessary - if bufp >= nbuf { - bufp = 0 - nbuf, err = syscall.ReadDirent(int(f.Fd()), buf) // getdents on linux - if nbuf < 0 { - nbuf = 0 - } - if err != nil { - return nil, os.NewSyscallError("readdirent", err) - } - if nbuf <= 0 { - break // EOF - } - } - - // Drain the buffer - nb, names = parseDirent(buf[bufp:nbuf], names) - bufp += nb - } - - sl := nameInoSlice(names) - sort.Sort(sl) - return sl, nil -} - -// parseDirent is a minor modification of syscall.ParseDirent (linux version) -// which returns {name,inode} pairs instead of just names. -func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { - origlen := len(buf) - for len(buf) > 0 { - dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[0])) - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:clen(bytes[:])]) - if name == "." || name == ".." { // Useless names - continue - } - names = append(names, nameIno{name, dirent.Ino}) - } - return origlen - len(buf), names -} - -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_other.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_other.go deleted file mode 100644 index 35832f087..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_other.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build !linux - -package archive - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { - var ( - oldRoot, newRoot *FileInfo - err1, err2 error - errs = make(chan error, 2) - ) - go func() { - oldRoot, err1 = collectFileInfo(oldDir) - errs <- err1 - }() - go func() { - newRoot, err2 = collectFileInfo(newDir) - errs <- err2 - }() - - // block until both routines have returned - for i := 0; i < 2; i++ { - if err := <-errs; err != nil { - return nil, nil, err - } - } - - return oldRoot, newRoot, nil -} - -func collectFileInfo(sourceDir string) (*FileInfo, error) { - root := newRootFileInfo() - - err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - relPath, err := filepath.Rel(sourceDir, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - relPath = filepath.Join(string(os.PathSeparator), relPath) - - // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. - // Temporary workaround. If the returned path starts with two backslashes, - // trim it down to a single backslash. Only relevant on Windows. - if runtime.GOOS == "windows" { - if strings.HasPrefix(relPath, `\\`) { - relPath = relPath[1:] - } - } - - if relPath == string(os.PathSeparator) { - return nil - } - - parent := root.LookUp(filepath.Dir(relPath)) - if parent == nil { - return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) - } - - info := &FileInfo{ - name: filepath.Base(relPath), - children: make(map[string]*FileInfo), - parent: parent, - } - - s, err := system.Lstat(path) - if err != nil { - return err - } - info.stat = s - - info.capability, _ = system.Lgetxattr(path, "security.capability") - - parent.children[info.name] = info - - return nil - }) - if err != nil { - return nil, err - } - return root, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_unix.go deleted file mode 100644 index 6646b4dfd..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_unix.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build !windows - -package archive - -import ( - "os" - "syscall" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - // Don't look at size for dirs, its not a good measure of change - if oldStat.Mode() != newStat.Mode() || - oldStat.UID() != newStat.UID() || - oldStat.GID() != newStat.GID() || - oldStat.Rdev() != newStat.Rdev() || - // Don't look at size for dirs, its not a good measure of change - (oldStat.Mode()&syscall.S_IFDIR != syscall.S_IFDIR && - (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.Mode()&syscall.S_IFDIR != 0 -} - -func getIno(fi os.FileInfo) uint64 { - return uint64(fi.Sys().(*syscall.Stat_t).Ino) -} - -func hasHardlinks(fi os.FileInfo) bool { - return fi.Sys().(*syscall.Stat_t).Nlink > 1 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_windows.go deleted file mode 100644 index 2d8708d0a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_windows.go +++ /dev/null @@ -1,30 +0,0 @@ -package archive - -import ( - "os" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - - // Don't look at size for dirs, its not a good measure of change - if oldStat.ModTime() != newStat.ModTime() || - oldStat.Mode() != newStat.Mode() || - oldStat.Size() != newStat.Size() && !oldStat.IsDir() { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.IsDir() -} - -func getIno(fi os.FileInfo) (inode uint64) { - return -} - -func hasHardlinks(fi os.FileInfo) bool { - return false -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy.go deleted file mode 100644 index e95091264..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy.go +++ /dev/null @@ -1,458 +0,0 @@ -package archive - -import ( - "archive/tar" - "errors" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// Errors used or returned by this file. -var ( - ErrNotDirectory = errors.New("not a directory") - ErrDirNotExists = errors.New("no such directory") - ErrCannotCopyDir = errors.New("cannot copy directory") - ErrInvalidCopySource = errors.New("invalid copy source content") -) - -// PreserveTrailingDotOrSeparator returns the given cleaned path (after -// processing using any utility functions from the path or filepath stdlib -// packages) and appends a trailing `/.` or `/` if its corresponding original -// path (from before being processed by utility functions from the path or -// filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned -// path already ends in a `.` path segment, then another is not added. If the -// clean path already ends in a path separator, then another is not added. -func PreserveTrailingDotOrSeparator(cleanedPath, originalPath string) string { - // Ensure paths are in platform semantics - cleanedPath = normalizePath(cleanedPath) - originalPath = normalizePath(originalPath) - - if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { - if !hasTrailingPathSeparator(cleanedPath) { - // Add a separator if it doesn't already end with one (a cleaned - // path would only end in a separator if it is the root). - cleanedPath += string(filepath.Separator) - } - cleanedPath += "." - } - - if !hasTrailingPathSeparator(cleanedPath) && hasTrailingPathSeparator(originalPath) { - cleanedPath += string(filepath.Separator) - } - - return cleanedPath -} - -// assertsDirectory returns whether the given path is -// asserted to be a directory, i.e., the path ends with -// a trailing '/' or `/.`, assuming a path separator of `/`. -func assertsDirectory(path string) bool { - return hasTrailingPathSeparator(path) || specifiesCurrentDir(path) -} - -// hasTrailingPathSeparator returns whether the given -// path ends with the system's path separator character. -func hasTrailingPathSeparator(path string) bool { - return len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) -} - -// specifiesCurrentDir returns whether the given path specifies -// a "current directory", i.e., the last path segment is `.`. -func specifiesCurrentDir(path string) bool { - return filepath.Base(path) == "." -} - -// SplitPathDirEntry splits the given path between its directory name and its -// basename by first cleaning the path but preserves a trailing "." if the -// original path specified the current directory. -func SplitPathDirEntry(path string) (dir, base string) { - cleanedPath := filepath.Clean(normalizePath(path)) - - if specifiesCurrentDir(path) { - cleanedPath += string(filepath.Separator) + "." - } - - return filepath.Dir(cleanedPath), filepath.Base(cleanedPath) -} - -// TarResource archives the resource described by the given CopyInfo to a Tar -// archive. A non-nil error is returned if sourcePath does not exist or is -// asserted to be a directory but exists as another type of file. -// -// This function acts as a convenient wrapper around TarWithOptions, which -// requires a directory as the source path. TarResource accepts either a -// directory or a file path and correctly sets the Tar options. -func TarResource(sourceInfo CopyInfo) (content Archive, err error) { - return TarResourceRebase(sourceInfo.Path, sourceInfo.RebaseName) -} - -// TarResourceRebase is like TarResource but renames the first path element of -// items in the resulting tar archive to match the given rebaseName if not "". -func TarResourceRebase(sourcePath, rebaseName string) (content Archive, err error) { - sourcePath = normalizePath(sourcePath) - if _, err = os.Lstat(sourcePath); err != nil { - // Catches the case where the source does not exist or is not a - // directory if asserted to be a directory, as this also causes an - // error. - return - } - - // Separate the source path between it's directory and - // the entry in that directory which we are archiving. - sourceDir, sourceBase := SplitPathDirEntry(sourcePath) - - filter := []string{sourceBase} - - logrus.Debugf("copying %q from %q", sourceBase, sourceDir) - - return TarWithOptions(sourceDir, &TarOptions{ - Compression: Uncompressed, - IncludeFiles: filter, - IncludeSourceDir: true, - RebaseNames: map[string]string{ - sourceBase: rebaseName, - }, - }) -} - -// CopyInfo holds basic info about the source -// or destination path of a copy operation. -type CopyInfo struct { - Path string - Exists bool - IsDir bool - RebaseName string -} - -// CopyInfoSourcePath stats the given path to create a CopyInfo -// struct representing that resource for the source of an archive copy -// operation. The given path should be an absolute local path. A source path -// has all symlinks evaluated that appear before the last path separator ("/" -// on Unix). As it is to be a copy source, the path must exist. -func CopyInfoSourcePath(path string, followLink bool) (CopyInfo, error) { - // normalize the file path and then evaluate the symbol link - // we will use the target file instead of the symbol link if - // followLink is set - path = normalizePath(path) - - resolvedPath, rebaseName, err := ResolveHostSourcePath(path, followLink) - if err != nil { - return CopyInfo{}, err - } - - stat, err := os.Lstat(resolvedPath) - if err != nil { - return CopyInfo{}, err - } - - return CopyInfo{ - Path: resolvedPath, - Exists: true, - IsDir: stat.IsDir(), - RebaseName: rebaseName, - }, nil -} - -// CopyInfoDestinationPath stats the given path to create a CopyInfo -// struct representing that resource for the destination of an archive copy -// operation. The given path should be an absolute local path. -func CopyInfoDestinationPath(path string) (info CopyInfo, err error) { - maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot. - path = normalizePath(path) - originalPath := path - - stat, err := os.Lstat(path) - - if err == nil && stat.Mode()&os.ModeSymlink == 0 { - // The path exists and is not a symlink. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil - } - - // While the path is a symlink. - for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ { - if n > maxSymlinkIter { - // Don't follow symlinks more than this arbitrary number of times. - return CopyInfo{}, errors.New("too many symlinks in " + originalPath) - } - - // The path is a symbolic link. We need to evaluate it so that the - // destination of the copy operation is the link target and not the - // link itself. This is notably different than CopyInfoSourcePath which - // only evaluates symlinks before the last appearing path separator. - // Also note that it is okay if the last path element is a broken - // symlink as the copy operation should create the target. - var linkTarget string - - linkTarget, err = os.Readlink(path) - if err != nil { - return CopyInfo{}, err - } - - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - dstParent, _ := SplitPathDirEntry(path) - linkTarget = filepath.Join(dstParent, linkTarget) - } - - path = linkTarget - stat, err = os.Lstat(path) - } - - if err != nil { - // It's okay if the destination path doesn't exist. We can still - // continue the copy operation if the parent directory exists. - if !os.IsNotExist(err) { - return CopyInfo{}, err - } - - // Ensure destination parent dir exists. - dstParent, _ := SplitPathDirEntry(path) - - parentDirStat, err := os.Lstat(dstParent) - if err != nil { - return CopyInfo{}, err - } - if !parentDirStat.IsDir() { - return CopyInfo{}, ErrNotDirectory - } - - return CopyInfo{Path: path}, nil - } - - // The path exists after resolving symlinks. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil -} - -// PrepareArchiveCopy prepares the given srcContent archive, which should -// contain the archived resource described by srcInfo, to the destination -// described by dstInfo. Returns the possibly modified content archive along -// with the path to the destination directory which it should be extracted to. -func PrepareArchiveCopy(srcContent Reader, srcInfo, dstInfo CopyInfo) (dstDir string, content Archive, err error) { - // Ensure in platform semantics - srcInfo.Path = normalizePath(srcInfo.Path) - dstInfo.Path = normalizePath(dstInfo.Path) - - // Separate the destination path between its directory and base - // components in case the source archive contents need to be rebased. - dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) - _, srcBase := SplitPathDirEntry(srcInfo.Path) - - switch { - case dstInfo.Exists && dstInfo.IsDir: - // The destination exists as a directory. No alteration - // to srcContent is needed as its contents can be - // simply extracted to the destination directory. - return dstInfo.Path, ioutil.NopCloser(srcContent), nil - case dstInfo.Exists && srcInfo.IsDir: - // The destination exists as some type of file and the source - // content is a directory. This is an error condition since - // you cannot copy a directory to an existing file location. - return "", nil, ErrCannotCopyDir - case dstInfo.Exists: - // The destination exists as some type of file and the source content - // is also a file. The source content entry will have to be renamed to - // have a basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case srcInfo.IsDir: - // The destination does not exist and the source content is an archive - // of a directory. The archive should be extracted to the parent of - // the destination path instead, and when it is, the directory that is - // created as a result should take the name of the destination path. - // The source content entries will have to be renamed to have a - // basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case assertsDirectory(dstInfo.Path): - // The destination does not exist and is asserted to be created as a - // directory, but the source content is not a directory. This is an - // error condition since you cannot create a directory from a file - // source. - return "", nil, ErrDirNotExists - default: - // The last remaining case is when the destination does not exist, is - // not asserted to be a directory, and the source content is not an - // archive of a directory. It this case, the destination file will need - // to be created when the archive is extracted and the source content - // entry will have to be renamed to have a basename which matches the - // destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - } - -} - -// RebaseArchiveEntries rewrites the given srcContent archive replacing -// an occurrence of oldBase with newBase at the beginning of entry names. -func RebaseArchiveEntries(srcContent Reader, oldBase, newBase string) Archive { - if oldBase == string(os.PathSeparator) { - // If oldBase specifies the root directory, use an empty string as - // oldBase instead so that newBase doesn't replace the path separator - // that all paths will start with. - oldBase = "" - } - - rebased, w := io.Pipe() - - go func() { - srcTar := tar.NewReader(srcContent) - rebasedTar := tar.NewWriter(w) - - for { - hdr, err := srcTar.Next() - if err == io.EOF { - // Signals end of archive. - rebasedTar.Close() - w.Close() - return - } - if err != nil { - w.CloseWithError(err) - return - } - - hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) - - if err = rebasedTar.WriteHeader(hdr); err != nil { - w.CloseWithError(err) - return - } - - if _, err = io.Copy(rebasedTar, srcTar); err != nil { - w.CloseWithError(err) - return - } - } - }() - - return rebased -} - -// CopyResource performs an archive copy from the given source path to the -// given destination path. The source path MUST exist and the destination -// path's parent directory must exist. -func CopyResource(srcPath, dstPath string, followLink bool) error { - var ( - srcInfo CopyInfo - err error - ) - - // Ensure in platform semantics - srcPath = normalizePath(srcPath) - dstPath = normalizePath(dstPath) - - // Clean the source and destination paths. - srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath) - dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath) - - if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { - return err - } - - content, err := TarResource(srcInfo) - if err != nil { - return err - } - defer content.Close() - - return CopyTo(content, srcInfo, dstPath) -} - -// CopyTo handles extracting the given content whose -// entries should be sourced from srcInfo to dstPath. -func CopyTo(content Reader, srcInfo CopyInfo, dstPath string) error { - // The destination path need not exist, but CopyInfoDestinationPath will - // ensure that at least the parent directory exists. - dstInfo, err := CopyInfoDestinationPath(normalizePath(dstPath)) - if err != nil { - return err - } - - dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) - if err != nil { - return err - } - defer copyArchive.Close() - - options := &TarOptions{ - NoLchown: true, - NoOverwriteDirNonDir: true, - } - - return Untar(copyArchive, dstDir, options) -} - -// ResolveHostSourcePath decides real path need to be copied with parameters such as -// whether to follow symbol link or not, if followLink is true, resolvedPath will return -// link target of any symbol link file, else it will only resolve symlink of directory -// but return symbol link file itself without resolving. -func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) { - if followLink { - resolvedPath, err = filepath.EvalSymlinks(path) - if err != nil { - return - } - - resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) - } else { - dirPath, basePath := filepath.Split(path) - - // if not follow symbol link, then resolve symbol link of parent dir - var resolvedDirPath string - resolvedDirPath, err = filepath.EvalSymlinks(dirPath) - if err != nil { - return - } - // resolvedDirPath will have been cleaned (no trailing path separators) so - // we can manually join it with the base path element. - resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath - if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) { - rebaseName = filepath.Base(path) - } - } - return resolvedPath, rebaseName, nil -} - -// GetRebaseName normalizes and compares path and resolvedPath, -// return completed resolved path and rebased file name -func GetRebaseName(path, resolvedPath string) (string, string) { - // linkTarget will have been cleaned (no trailing path separators and dot) so - // we can manually join it with them - var rebaseName string - if specifiesCurrentDir(path) && !specifiesCurrentDir(resolvedPath) { - resolvedPath += string(filepath.Separator) + "." - } - - if hasTrailingPathSeparator(path) && !hasTrailingPathSeparator(resolvedPath) { - resolvedPath += string(filepath.Separator) - } - - if filepath.Base(path) != filepath.Base(resolvedPath) { - // In the case where the path had a trailing separator and a symlink - // evaluation has changed the last path component, we will need to - // rebase the name in the archive that is being copied to match the - // originally requested name. - rebaseName = filepath.Base(path) - } - return resolvedPath, rebaseName -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_unix.go deleted file mode 100644 index e305b5e4a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !windows - -package archive - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.ToSlash(path) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_windows.go deleted file mode 100644 index 2b775b45c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -package archive - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.FromSlash(path) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff.go deleted file mode 100644 index 887dd54cc..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff.go +++ /dev/null @@ -1,279 +0,0 @@ -package archive - -import ( - "archive/tar" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func UnpackLayer(dest string, layer Reader, options *TarOptions) (size int64, err error) { - tr := tar.NewReader(layer) - trBuf := pools.BufioReader32KPool.Get(tr) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - unpackedPaths := make(map[string]struct{}) - - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps) - if err != nil { - return 0, err - } - - aufsTempdir := "" - aufsHardlinks := make(map[string]*tar.Header) - - if options == nil { - options = &TarOptions{} - } - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return 0, err - } - - size += hdr.Size - - // Normalize name, for safety and for a simple is-root check - hdr.Name = filepath.Clean(hdr.Name) - - // Windows does not support filenames with colons in them. Ignore - // these files. This is not a problem though (although it might - // appear that it is). Let's suppose a client is running docker pull. - // The daemon it points to is Windows. Would it make sense for the - // client to be doing a docker pull Ubuntu for example (which has files - // with colons in the name under /usr/share/man/man3)? No, absolutely - // not as it would really only make sense that they were pulling a - // Windows image. However, for development, it is necessary to be able - // to pull Linux images which are in the repository. - // - // TODO Windows. Once the registry is aware of what images are Windows- - // specific or Linux-specific, this warning should be changed to an error - // to cater for the situation where someone does manage to upload a Linux - // image but have it tagged as Windows inadvertently. - if runtime.GOOS == "windows" { - if strings.Contains(hdr.Name, ":") { - logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) - continue - } - } - - // Note as these operations are platform specific, so must the slash be. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists. - // This happened in some tests where an image had a tarfile without any - // parent directories. - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = system.MkdirAll(parentPath, 0600) - if err != nil { - return 0, err - } - } - } - - // Skip AUFS metadata dirs - if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) { - // Regular files inside /.wh..wh.plnk can be used as hardlink targets - // We don't want this directory, but we need the files in them so that - // such hardlinks can be resolved. - if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { - basename := filepath.Base(hdr.Name) - aufsHardlinks[basename] = hdr - if aufsTempdir == "" { - if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil { - return 0, err - } - defer os.RemoveAll(aufsTempdir) - } - if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil); err != nil { - return 0, err - } - } - - if hdr.Name != WhiteoutOpaqueDir { - continue - } - } - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return 0, err - } - - // Note as these operations are platform specific, so must the slash be. - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - base := filepath.Base(path) - - if strings.HasPrefix(base, WhiteoutPrefix) { - dir := filepath.Dir(path) - if base == WhiteoutOpaqueDir { - _, err := os.Lstat(dir) - if err != nil { - return 0, err - } - err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - if err != nil { - if os.IsNotExist(err) { - err = nil // parent was deleted - } - return err - } - if path == dir { - return nil - } - if _, exists := unpackedPaths[path]; !exists { - err := os.RemoveAll(path) - return err - } - return nil - }) - if err != nil { - return 0, err - } - } else { - originalBase := base[len(WhiteoutPrefix):] - originalPath := filepath.Join(dir, originalBase) - if err := os.RemoveAll(originalPath); err != nil { - return 0, err - } - } - } else { - // If path exits we almost always just want to remove and replace it. - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return 0, err - } - } - } - - trBuf.Reset(tr) - srcData := io.Reader(trBuf) - srcHdr := hdr - - // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so - // we manually retarget these into the temporary files we extracted them into - if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { - linkBasename := filepath.Base(hdr.Linkname) - srcHdr = aufsHardlinks[linkBasename] - if srcHdr == nil { - return 0, fmt.Errorf("Invalid aufs hardlink") - } - tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) - if err != nil { - return 0, err - } - defer tmpFile.Close() - srcData = tmpFile - } - - // if the options contain a uid & gid maps, convert header uid/gid - // entries using the maps such that lchown sets the proper mapped - // uid/gid after writing the file. We only perform this mapping if - // the file isn't already owned by the remapped root UID or GID, as - // that specific uid/gid has no mapping from container -> host, and - // those files already have the proper ownership for inside the - // container. - if srcHdr.Uid != remappedRootUID { - xUID, err := idtools.ToHost(srcHdr.Uid, options.UIDMaps) - if err != nil { - return 0, err - } - srcHdr.Uid = xUID - } - if srcHdr.Gid != remappedRootGID { - xGID, err := idtools.ToHost(srcHdr.Gid, options.GIDMaps) - if err != nil { - return 0, err - } - srcHdr.Gid = xGID - } - if err := createTarFile(path, dest, srcHdr, srcData, true, nil); err != nil { - return 0, err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - unpackedPaths[path] = struct{}{} - } - } - - for _, hdr := range dirs { - path := filepath.Join(dest, hdr.Name) - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return 0, err - } - } - - return size, nil -} - -// ApplyLayer parses a diff in the standard layer format from `layer`, -// and applies it to the directory `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyLayer(dest string, layer Reader) (int64, error) { - return applyLayerHandler(dest, layer, &TarOptions{}, true) -} - -// ApplyUncompressedLayer parses a diff in the standard layer format from -// `layer`, and applies it to the directory `dest`. The stream `layer` -// can only be uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyUncompressedLayer(dest string, layer Reader, options *TarOptions) (int64, error) { - return applyLayerHandler(dest, layer, options, false) -} - -// do the bulk load of ApplyLayer, but allow for not calling DecompressStream -func applyLayerHandler(dest string, layer Reader, options *TarOptions, decompress bool) (int64, error) { - dest = filepath.Clean(dest) - - // We need to be able to set any perms - oldmask, err := system.Umask(0) - if err != nil { - return 0, err - } - defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform - - if decompress { - layer, err = DecompressStream(layer) - if err != nil { - return 0, err - } - } - return UnpackLayer(dest, layer, options) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_linux.go deleted file mode 100644 index 3448569b1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -package archive - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - if time.IsZero() { - // Return UTIME_OMIT special value - ts.Sec = 0 - ts.Nsec = ((1 << 30) - 2) - return - } - return syscall.NsecToTimespec(time.UnixNano()) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_unsupported.go deleted file mode 100644 index e85aac054..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_unsupported.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !linux - -package archive - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - nsec := int64(0) - if !time.IsZero() { - nsec = time.UnixNano() - } - return syscall.NsecToTimespec(nsec) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/whiteouts.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/whiteouts.go deleted file mode 100644 index d20478a10..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/whiteouts.go +++ /dev/null @@ -1,23 +0,0 @@ -package archive - -// Whiteouts are files with a special meaning for the layered filesystem. -// Docker uses AUFS whiteout files inside exported archives. In other -// filesystems these files are generated/handled on tar creation/extraction. - -// WhiteoutPrefix prefix means file is a whiteout. If this is followed by a -// filename this means that file has been removed from the base layer. -const WhiteoutPrefix = ".wh." - -// WhiteoutMetaPrefix prefix means whiteout has a special meaning and is not -// for removing an actual file. Normally these files are excluded from exported -// archives. -const WhiteoutMetaPrefix = WhiteoutPrefix + WhiteoutPrefix - -// WhiteoutLinkDir is a directory AUFS uses for storing hardlink links to other -// layers. Normally these should not go into exported archives and all changed -// hardlinks should be copied to the top layer. -const WhiteoutLinkDir = WhiteoutMetaPrefix + "plnk" - -// WhiteoutOpaqueDir file means directory has been made opaque - meaning -// readdir calls to this directory do not follow to lower layers. -const WhiteoutOpaqueDir = WhiteoutMetaPrefix + ".opq" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap.go deleted file mode 100644 index dfb335c0b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap.go +++ /dev/null @@ -1,59 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "io/ioutil" -) - -// Generate generates a new archive from the content provided -// as input. -// -// `files` is a sequence of path/content pairs. A new file is -// added to the archive for each pair. -// If the last pair is incomplete, the file is created with an -// empty content. For example: -// -// Generate("foo.txt", "hello world", "emptyfile") -// -// The above call will return an archive with 2 files: -// * ./foo.txt with content "hello world" -// * ./empty with empty content -// -// FIXME: stream content instead of buffering -// FIXME: specify permissions and other archive metadata -func Generate(input ...string) (Archive, error) { - files := parseStringPairs(input...) - buf := new(bytes.Buffer) - tw := tar.NewWriter(buf) - for _, file := range files { - name, content := file[0], file[1] - hdr := &tar.Header{ - Name: name, - Size: int64(len(content)), - } - if err := tw.WriteHeader(hdr); err != nil { - return nil, err - } - if _, err := tw.Write([]byte(content)); err != nil { - return nil, err - } - } - if err := tw.Close(); err != nil { - return nil, err - } - return ioutil.NopCloser(buf), nil -} - -func parseStringPairs(input ...string) (output [][2]string) { - output = make([][2]string, 0, len(input)/2+1) - for i := 0; i < len(input); i += 2 { - var pair [2]string - pair[0] = input[i] - if i+1 < len(input) { - pair[1] = input[i+1] - } - output = append(output, pair) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils.go deleted file mode 100644 index a15cf4bc5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils.go +++ /dev/null @@ -1,279 +0,0 @@ -package fileutils - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "regexp" - "strings" - "text/scanner" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" -) - -// exclusion return true if the specified pattern is an exclusion -func exclusion(pattern string) bool { - return pattern[0] == '!' -} - -// empty return true if the specified pattern is empty -func empty(pattern string) bool { - return pattern == "" -} - -// CleanPatterns takes a slice of patterns returns a new -// slice of patterns cleaned with filepath.Clean, stripped -// of any empty patterns and lets the caller know whether the -// slice contains any exception patterns (prefixed with !). -func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) { - // Loop over exclusion patterns and: - // 1. Clean them up. - // 2. Indicate whether we are dealing with any exception rules. - // 3. Error if we see a single exclusion marker on it's own (!). - cleanedPatterns := []string{} - patternDirs := [][]string{} - exceptions := false - for _, pattern := range patterns { - // Eliminate leading and trailing whitespace. - pattern = strings.TrimSpace(pattern) - if empty(pattern) { - continue - } - if exclusion(pattern) { - if len(pattern) == 1 { - return nil, nil, false, errors.New("Illegal exclusion pattern: !") - } - exceptions = true - } - pattern = filepath.Clean(pattern) - cleanedPatterns = append(cleanedPatterns, pattern) - if exclusion(pattern) { - pattern = pattern[1:] - } - patternDirs = append(patternDirs, strings.Split(pattern, "/")) - } - - return cleanedPatterns, patternDirs, exceptions, nil -} - -// Matches returns true if file matches any of the patterns -// and isn't excluded by any of the subsequent patterns. -func Matches(file string, patterns []string) (bool, error) { - file = filepath.Clean(file) - - if file == "." { - // Don't let them exclude everything, kind of silly. - return false, nil - } - - patterns, patDirs, _, err := CleanPatterns(patterns) - if err != nil { - return false, err - } - - return OptimizedMatches(file, patterns, patDirs) -} - -// OptimizedMatches is basically the same as fileutils.Matches() but optimized for archive.go. -// It will assume that the inputs have been preprocessed and therefore the function -// doesn't need to do as much error checking and clean-up. This was done to avoid -// repeating these steps on each file being checked during the archive process. -// The more generic fileutils.Matches() can't make these assumptions. -func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) { - matched := false - parentPath := filepath.Dir(file) - parentPathDirs := strings.Split(parentPath, "/") - - for i, pattern := range patterns { - negative := false - - if exclusion(pattern) { - negative = true - pattern = pattern[1:] - } - - match, err := regexpMatch(pattern, file) - if err != nil { - return false, fmt.Errorf("Error in pattern (%s): %s", pattern, err) - } - - if !match && parentPath != "." { - // Check to see if the pattern matches one of our parent dirs. - if len(patDirs[i]) <= len(parentPathDirs) { - match, _ = regexpMatch(strings.Join(patDirs[i], "/"), - strings.Join(parentPathDirs[:len(patDirs[i])], "/")) - } - } - - if match { - matched = !negative - } - } - - if matched { - logrus.Debugf("Skipping excluded path: %s", file) - } - - return matched, nil -} - -// regexpMatch tries to match the logic of filepath.Match but -// does so using regexp logic. We do this so that we can expand the -// wildcard set to include other things, like "**" to mean any number -// of directories. This means that we should be backwards compatible -// with filepath.Match(). We'll end up supporting more stuff, due to -// the fact that we're using regexp, but that's ok - it does no harm. -func regexpMatch(pattern, path string) (bool, error) { - regStr := "^" - - // Do some syntax checking on the pattern. - // filepath's Match() has some really weird rules that are inconsistent - // so instead of trying to dup their logic, just call Match() for its - // error state and if there is an error in the pattern return it. - // If this becomes an issue we can remove this since its really only - // needed in the error (syntax) case - which isn't really critical. - if _, err := filepath.Match(pattern, path); err != nil { - return false, err - } - - // Go through the pattern and convert it to a regexp. - // We use a scanner so we can support utf-8 chars. - var scan scanner.Scanner - scan.Init(strings.NewReader(pattern)) - - sl := string(os.PathSeparator) - escSL := sl - if sl == `\` { - escSL += `\` - } - - for scan.Peek() != scanner.EOF { - ch := scan.Next() - - if ch == '*' { - if scan.Peek() == '*' { - // is some flavor of "**" - scan.Next() - - if scan.Peek() == scanner.EOF { - // is "**EOF" - to align with .gitignore just accept all - regStr += ".*" - } else { - // is "**" - regStr += "((.*" + escSL + ")|([^" + escSL + "]*))" - } - - // Treat **/ as ** so eat the "/" - if string(scan.Peek()) == sl { - scan.Next() - } - } else { - // is "*" so map it to anything but "/" - regStr += "[^" + escSL + "]*" - } - } else if ch == '?' { - // "?" is any char except "/" - regStr += "[^" + escSL + "]" - } else if strings.Index(".$", string(ch)) != -1 { - // Escape some regexp special chars that have no meaning - // in golang's filepath.Match - regStr += `\` + string(ch) - } else if ch == '\\' { - // escape next char. Note that a trailing \ in the pattern - // will be left alone (but need to escape it) - if sl == `\` { - // On windows map "\" to "\\", meaning an escaped backslash, - // and then just continue because filepath.Match on - // Windows doesn't allow escaping at all - regStr += escSL - continue - } - if scan.Peek() != scanner.EOF { - regStr += `\` + string(scan.Next()) - } else { - regStr += `\` - } - } else { - regStr += string(ch) - } - } - - regStr += "$" - - res, err := regexp.MatchString(regStr, path) - - // Map regexp's error to filepath's so no one knows we're not using filepath - if err != nil { - err = filepath.ErrBadPattern - } - - return res, err -} - -// CopyFile copies from src to dst until either EOF is reached -// on src or an error occurs. It verifies src exists and remove -// the dst if it exists. -func CopyFile(src, dst string) (int64, error) { - cleanSrc := filepath.Clean(src) - cleanDst := filepath.Clean(dst) - if cleanSrc == cleanDst { - return 0, nil - } - sf, err := os.Open(cleanSrc) - if err != nil { - return 0, err - } - defer sf.Close() - if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { - return 0, err - } - df, err := os.Create(cleanDst) - if err != nil { - return 0, err - } - defer df.Close() - return io.Copy(df, sf) -} - -// ReadSymlinkedDirectory returns the target directory of a symlink. -// The target of the symbolic link may not be a file. -func ReadSymlinkedDirectory(path string) (string, error) { - var realPath string - var err error - if realPath, err = filepath.Abs(path); err != nil { - return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) - } - if realPath, err = filepath.EvalSymlinks(realPath); err != nil { - return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) - } - realPathInfo, err := os.Stat(realPath) - if err != nil { - return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) - } - if !realPathInfo.Mode().IsDir() { - return "", fmt.Errorf("canonical path points to a file '%s'", realPath) - } - return realPath, nil -} - -// CreateIfNotExists creates a file or a directory only if it does not already exist. -func CreateIfNotExists(path string, isDir bool) error { - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - if isDir { - return os.MkdirAll(path, 0755) - } - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { - return err - } - f, err := os.OpenFile(path, os.O_CREATE, 0755) - if err != nil { - return err - } - f.Close() - } - } - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_unix.go deleted file mode 100644 index 7e00802c1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build linux freebsd - -package fileutils - -import ( - "fmt" - "io/ioutil" - "os" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" -) - -// GetTotalUsedFds Returns the number of used File Descriptors by -// reading it via /proc filesystem. -func GetTotalUsedFds() int { - if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { - logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) - } else { - return len(fds) - } - return -1 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_windows.go deleted file mode 100644 index 5ec21cace..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package fileutils - -// GetTotalUsedFds Returns the number of used File Descriptors. Not supported -// on Windows. -func GetTotalUsedFds() int { - return -1 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir.go deleted file mode 100644 index dcae17882..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir.go +++ /dev/null @@ -1,39 +0,0 @@ -package homedir - -import ( - "os" - "runtime" - - "github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user" -) - -// Key returns the env var name for the user's home dir based on -// the platform being run on -func Key() string { - if runtime.GOOS == "windows" { - return "USERPROFILE" - } - return "HOME" -} - -// Get returns the home directory of the current user with the help of -// environment variables depending on the target operating system. -// Returned path should be used with "path/filepath" to form new paths. -func Get() string { - home := os.Getenv(Key()) - if home == "" && runtime.GOOS != "windows" { - if u, err := user.CurrentUser(); err == nil { - return u.Home - } - } - return home -} - -// GetShortcutString returns the string that is shortcut to user's home directory -// in the native shell of the platform running on. -func GetShortcutString() string { - if runtime.GOOS == "windows" { - return "%USERPROFILE%" // be careful while using in format functions - } - return "~" -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools.go deleted file mode 100644 index a1301ee97..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools.go +++ /dev/null @@ -1,195 +0,0 @@ -package idtools - -import ( - "bufio" - "fmt" - "os" - "sort" - "strconv" - "strings" -) - -// IDMap contains a single entry for user namespace range remapping. An array -// of IDMap entries represents the structure that will be provided to the Linux -// kernel for creating a user namespace. -type IDMap struct { - ContainerID int `json:"container_id"` - HostID int `json:"host_id"` - Size int `json:"size"` -} - -type subIDRange struct { - Start int - Length int -} - -type ranges []subIDRange - -func (e ranges) Len() int { return len(e) } -func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } -func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } - -const ( - subuidFileName string = "/etc/subuid" - subgidFileName string = "/etc/subgid" -) - -// MkdirAllAs creates a directory (include any along the path) and then modifies -// ownership to the requested uid/gid. If the directory already exists, this -// function will still change ownership to the requested uid/gid pair. -func MkdirAllAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { - return mkdirAs(path, mode, ownerUID, ownerGID, true, true) -} - -// MkdirAllNewAs creates a directory (include any along the path) and then modifies -// ownership ONLY of newly created directories to the requested uid/gid. If the -// directories along the path exist, no change of ownership will be performed -func MkdirAllNewAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { - return mkdirAs(path, mode, ownerUID, ownerGID, true, false) -} - -// MkdirAs creates a directory and then modifies ownership to the requested uid/gid. -// If the directory already exists, this function still changes ownership -func MkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { - return mkdirAs(path, mode, ownerUID, ownerGID, false, true) -} - -// GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. -// If the maps are empty, then the root uid/gid will default to "real" 0/0 -func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { - var uid, gid int - - if uidMap != nil { - xUID, err := ToHost(0, uidMap) - if err != nil { - return -1, -1, err - } - uid = xUID - } - if gidMap != nil { - xGID, err := ToHost(0, gidMap) - if err != nil { - return -1, -1, err - } - gid = xGID - } - return uid, gid, nil -} - -// ToContainer takes an id mapping, and uses it to translate a -// host ID to the remapped ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id -func ToContainer(hostID int, idMap []IDMap) (int, error) { - if idMap == nil { - return hostID, nil - } - for _, m := range idMap { - if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { - contID := m.ContainerID + (hostID - m.HostID) - return contID, nil - } - } - return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) -} - -// ToHost takes an id mapping and a remapped ID, and translates the -// ID to the mapped host ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id # -func ToHost(contID int, idMap []IDMap) (int, error) { - if idMap == nil { - return contID, nil - } - for _, m := range idMap { - if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { - hostID := m.HostID + (contID - m.ContainerID) - return hostID, nil - } - } - return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) -} - -// CreateIDMappings takes a requested user and group name and -// using the data from /etc/sub{uid,gid} ranges, creates the -// proper uid and gid remapping ranges for that user/group pair -func CreateIDMappings(username, groupname string) ([]IDMap, []IDMap, error) { - subuidRanges, err := parseSubuid(username) - if err != nil { - return nil, nil, err - } - subgidRanges, err := parseSubgid(groupname) - if err != nil { - return nil, nil, err - } - if len(subuidRanges) == 0 { - return nil, nil, fmt.Errorf("No subuid ranges found for user %q", username) - } - if len(subgidRanges) == 0 { - return nil, nil, fmt.Errorf("No subgid ranges found for group %q", groupname) - } - - return createIDMap(subuidRanges), createIDMap(subgidRanges), nil -} - -func createIDMap(subidRanges ranges) []IDMap { - idMap := []IDMap{} - - // sort the ranges by lowest ID first - sort.Sort(subidRanges) - containerID := 0 - for _, idrange := range subidRanges { - idMap = append(idMap, IDMap{ - ContainerID: containerID, - HostID: idrange.Start, - Size: idrange.Length, - }) - containerID = containerID + idrange.Length - } - return idMap -} - -func parseSubuid(username string) (ranges, error) { - return parseSubidFile(subuidFileName, username) -} - -func parseSubgid(username string) (ranges, error) { - return parseSubidFile(subgidFileName, username) -} - -func parseSubidFile(path, username string) (ranges, error) { - var rangeList ranges - - subidFile, err := os.Open(path) - if err != nil { - return rangeList, err - } - defer subidFile.Close() - - s := bufio.NewScanner(subidFile) - for s.Scan() { - if err := s.Err(); err != nil { - return rangeList, err - } - - text := strings.TrimSpace(s.Text()) - if text == "" { - continue - } - parts := strings.Split(text, ":") - if len(parts) != 3 { - return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) - } - if parts[0] == username { - // return the first entry for a user; ignores potential for multiple ranges per user - startid, err := strconv.Atoi(parts[1]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - length, err := strconv.Atoi(parts[2]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - rangeList = append(rangeList, subIDRange{startid, length}) - } - } - return rangeList, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix.go deleted file mode 100644 index 0444307d2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build !windows - -package idtools - -import ( - "os" - "path/filepath" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error { - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If chownExisting is false, we won't - // chown the full directory path if it exists - var paths []string - if _, err := os.Stat(path); err != nil && os.IsNotExist(err) { - paths = []string{path} - } else if err == nil && chownExisting { - if err := os.Chown(path, ownerUID, ownerGID); err != nil { - return err - } - // short-circuit--we were called with an existing directory and chown was requested - return nil - } else if err == nil { - // nothing to do; directory path fully exists already and chown was NOT requested - return nil - } - - if mkAll { - // walk back to "/" looking for directories which do not exist - // and add them to the paths array for chown after creation - dirPath := path - for { - dirPath = filepath.Dir(dirPath) - if dirPath == "/" { - break - } - if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) { - paths = append(paths, dirPath) - } - } - if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) { - return err - } - } else { - if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) { - return err - } - } - // even if it existed, we will chown the requested path + any subpaths that - // didn't exist when we called MkdirAll - for _, pathComponent := range paths { - if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_windows.go deleted file mode 100644 index d5ec992db..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build windows - -package idtools - -import ( - "os" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -// Platforms such as Windows do not support the UID/GID concept. So make this -// just a wrapper around system.MkdirAll. -func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error { - if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) { - return err - } - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go deleted file mode 100644 index c1eedff10..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go +++ /dev/null @@ -1,155 +0,0 @@ -package idtools - -import ( - "fmt" - "os/exec" - "path/filepath" - "strings" - "syscall" -) - -// add a user and/or group to Linux /etc/passwd, /etc/group using standard -// Linux distribution commands: -// adduser --uid --shell /bin/login --no-create-home --disabled-login --ingroup -// useradd -M -u -s /bin/nologin -N -g -// addgroup --gid -// groupadd -g - -const baseUID int = 10000 -const baseGID int = 10000 -const idMAX int = 65534 - -var ( - userCommand string - groupCommand string - - cmdTemplates = map[string]string{ - "adduser": "--uid %d --shell /bin/false --no-create-home --disabled-login --ingroup %s %s", - "useradd": "-M -u %d -s /bin/false -N -g %s %s", - "addgroup": "--gid %d %s", - "groupadd": "-g %d %s", - } -) - -func init() { - // set up which commands are used for adding users/groups dependent on distro - if _, err := resolveBinary("adduser"); err == nil { - userCommand = "adduser" - } else if _, err := resolveBinary("useradd"); err == nil { - userCommand = "useradd" - } - if _, err := resolveBinary("addgroup"); err == nil { - groupCommand = "addgroup" - } else if _, err := resolveBinary("groupadd"); err == nil { - groupCommand = "groupadd" - } -} - -func resolveBinary(binname string) (string, error) { - binaryPath, err := exec.LookPath(binname) - if err != nil { - return "", err - } - resolvedPath, err := filepath.EvalSymlinks(binaryPath) - if err != nil { - return "", err - } - //only return no error if the final resolved binary basename - //matches what was searched for - if filepath.Base(resolvedPath) == binname { - return resolvedPath, nil - } - return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) -} - -// AddNamespaceRangesUser takes a name and finds an unused uid, gid pair -// and calls the appropriate helper function to add the group and then -// the user to the group in /etc/group and /etc/passwd respectively. -// This new user's /etc/sub{uid,gid} ranges will be used for user namespace -// mapping ranges in containers. -func AddNamespaceRangesUser(name string) (int, int, error) { - // Find unused uid, gid pair - uid, err := findUnusedUID(baseUID) - if err != nil { - return -1, -1, fmt.Errorf("Unable to find unused UID: %v", err) - } - gid, err := findUnusedGID(baseGID) - if err != nil { - return -1, -1, fmt.Errorf("Unable to find unused GID: %v", err) - } - - // First add the group that we will use - if err := addGroup(name, gid); err != nil { - return -1, -1, fmt.Errorf("Error adding group %q: %v", name, err) - } - // Add the user as a member of the group - if err := addUser(name, uid, name); err != nil { - return -1, -1, fmt.Errorf("Error adding user %q: %v", name, err) - } - return uid, gid, nil -} - -func addUser(userName string, uid int, groupName string) error { - - if userCommand == "" { - return fmt.Errorf("Cannot add user; no useradd/adduser binary found") - } - args := fmt.Sprintf(cmdTemplates[userCommand], uid, groupName, userName) - return execAddCmd(userCommand, args) -} - -func addGroup(groupName string, gid int) error { - - if groupCommand == "" { - return fmt.Errorf("Cannot add group; no groupadd/addgroup binary found") - } - args := fmt.Sprintf(cmdTemplates[groupCommand], gid, groupName) - // only error out if the error isn't that the group already exists - // if the group exists then our needs are already met - if err := execAddCmd(groupCommand, args); err != nil && !strings.Contains(err.Error(), "already exists") { - return err - } - return nil -} - -func execAddCmd(cmd, args string) error { - execCmd := exec.Command(cmd, strings.Split(args, " ")...) - out, err := execCmd.CombinedOutput() - if err != nil { - return fmt.Errorf("Failed to add user/group with error: %v; output: %q", err, string(out)) - } - return nil -} - -func findUnusedUID(startUID int) (int, error) { - return findUnused("passwd", startUID) -} - -func findUnusedGID(startGID int) (int, error) { - return findUnused("group", startGID) -} - -func findUnused(file string, id int) (int, error) { - for { - cmdStr := fmt.Sprintf("cat /etc/%s | cut -d: -f3 | grep '^%d$'", file, id) - cmd := exec.Command("sh", "-c", cmdStr) - if err := cmd.Run(); err != nil { - // if a non-zero return code occurs, then we know the ID was not found - // and is usable - if exiterr, ok := err.(*exec.ExitError); ok { - // The program has exited with an exit code != 0 - if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { - if status.ExitStatus() == 1 { - //no match, we can use this ID - return id, nil - } - } - } - return -1, fmt.Errorf("Error looking in /etc/%s for unused ID: %v", file, err) - } - id++ - if id > idMAX { - return -1, fmt.Errorf("Maximum id in %q reached with finding unused numeric ID", file) - } - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go deleted file mode 100644 index d98b354cb..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !linux - -package idtools - -import "fmt" - -// AddNamespaceRangesUser takes a name and finds an unused uid, gid pair -// and calls the appropriate helper function to add the group and then -// the user to the group in /etc/group and /etc/passwd respectively. -func AddNamespaceRangesUser(name string) (int, int, error) { - return -1, -1, fmt.Errorf("No support for adding users or groups on this OS") -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe.go deleted file mode 100644 index e263c284f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ /dev/null @@ -1,152 +0,0 @@ -package ioutils - -import ( - "errors" - "io" - "sync" -) - -// maxCap is the highest capacity to use in byte slices that buffer data. -const maxCap = 1e6 - -// blockThreshold is the minimum number of bytes in the buffer which will cause -// a write to BytesPipe to block when allocating a new slice. -const blockThreshold = 1e6 - -// ErrClosed is returned when Write is called on a closed BytesPipe. -var ErrClosed = errors.New("write to closed BytesPipe") - -// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). -// All written data may be read at most once. Also, BytesPipe allocates -// and releases new byte slices to adjust to current needs, so the buffer -// won't be overgrown after peak loads. -type BytesPipe struct { - mu sync.Mutex - wait *sync.Cond - buf [][]byte // slice of byte-slices of buffered data - lastRead int // index in the first slice to a read point - bufLen int // length of data buffered over the slices - closeErr error // error to return from next Read. set to nil if not closed. -} - -// NewBytesPipe creates new BytesPipe, initialized by specified slice. -// If buf is nil, then it will be initialized with slice which cap is 64. -// buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). -func NewBytesPipe(buf []byte) *BytesPipe { - if cap(buf) == 0 { - buf = make([]byte, 0, 64) - } - bp := &BytesPipe{ - buf: [][]byte{buf[:0]}, - } - bp.wait = sync.NewCond(&bp.mu) - return bp -} - -// Write writes p to BytesPipe. -// It can allocate new []byte slices in a process of writing. -func (bp *BytesPipe) Write(p []byte) (int, error) { - bp.mu.Lock() - defer bp.mu.Unlock() - written := 0 - for { - if bp.closeErr != nil { - return written, ErrClosed - } - // write data to the last buffer - b := bp.buf[len(bp.buf)-1] - // copy data to the current empty allocated area - n := copy(b[len(b):cap(b)], p) - // increment buffered data length - bp.bufLen += n - // include written data in last buffer - bp.buf[len(bp.buf)-1] = b[:len(b)+n] - - written += n - - // if there was enough room to write all then break - if len(p) == n { - break - } - - // more data: write to the next slice - p = p[n:] - - // block if too much data is still in the buffer - for bp.bufLen >= blockThreshold { - bp.wait.Wait() - } - - // allocate slice that has twice the size of the last unless maximum reached - nextCap := 2 * cap(bp.buf[len(bp.buf)-1]) - if nextCap > maxCap { - nextCap = maxCap - } - // add new byte slice to the buffers slice and continue writing - bp.buf = append(bp.buf, make([]byte, 0, nextCap)) - } - bp.wait.Broadcast() - return written, nil -} - -// CloseWithError causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) CloseWithError(err error) error { - bp.mu.Lock() - if err != nil { - bp.closeErr = err - } else { - bp.closeErr = io.EOF - } - bp.wait.Broadcast() - bp.mu.Unlock() - return nil -} - -// Close causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) Close() error { - return bp.CloseWithError(nil) -} - -func (bp *BytesPipe) len() int { - return bp.bufLen - bp.lastRead -} - -// Read reads bytes from BytesPipe. -// Data could be read only once. -func (bp *BytesPipe) Read(p []byte) (n int, err error) { - bp.mu.Lock() - defer bp.mu.Unlock() - if bp.len() == 0 { - if bp.closeErr != nil { - return 0, bp.closeErr - } - bp.wait.Wait() - if bp.len() == 0 && bp.closeErr != nil { - return 0, bp.closeErr - } - } - for { - read := copy(p, bp.buf[0][bp.lastRead:]) - n += read - bp.lastRead += read - if bp.len() == 0 { - // we have read everything. reset to the beginning. - bp.lastRead = 0 - bp.bufLen -= len(bp.buf[0]) - bp.buf[0] = bp.buf[0][:0] - break - } - // break if everything was read - if len(p) == read { - break - } - // more buffered data and more asked. read from next slice. - p = p[read:] - bp.lastRead = 0 - bp.bufLen -= len(bp.buf[0]) - bp.buf[0] = nil // throw away old slice - bp.buf = bp.buf[1:] // switch to next - } - bp.wait.Broadcast() - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt.go deleted file mode 100644 index 0b04b0ba3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt.go +++ /dev/null @@ -1,22 +0,0 @@ -package ioutils - -import ( - "fmt" - "io" -) - -// FprintfIfNotEmpty prints the string value if it's not empty -func FprintfIfNotEmpty(w io.Writer, format, value string) (int, error) { - if value != "" { - return fmt.Fprintf(w, format, value) - } - return 0, nil -} - -// FprintfIfTrue prints the boolean value if it's true -func FprintfIfTrue(w io.Writer, format string, ok bool) (int, error) { - if ok { - return fmt.Fprintf(w, format, ok) - } - return 0, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader.go deleted file mode 100644 index 0d2d76b47..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader.go +++ /dev/null @@ -1,226 +0,0 @@ -package ioutils - -import ( - "bytes" - "fmt" - "io" - "os" -) - -type pos struct { - idx int - offset int64 -} - -type multiReadSeeker struct { - readers []io.ReadSeeker - pos *pos - posIdx map[io.ReadSeeker]int -} - -func (r *multiReadSeeker) Seek(offset int64, whence int) (int64, error) { - var tmpOffset int64 - switch whence { - case os.SEEK_SET: - for i, rdr := range r.readers { - // get size of the current reader - s, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - - if offset > tmpOffset+s { - if i == len(r.readers)-1 { - rdrOffset := s + (offset - tmpOffset) - if _, err := rdr.Seek(rdrOffset, os.SEEK_SET); err != nil { - return -1, err - } - r.pos = &pos{i, rdrOffset} - return offset, nil - } - - tmpOffset += s - continue - } - - rdrOffset := offset - tmpOffset - idx := i - - rdr.Seek(rdrOffset, os.SEEK_SET) - // make sure all following readers are at 0 - for _, rdr := range r.readers[i+1:] { - rdr.Seek(0, os.SEEK_SET) - } - - if rdrOffset == s && i != len(r.readers)-1 { - idx++ - rdrOffset = 0 - } - r.pos = &pos{idx, rdrOffset} - return offset, nil - } - case os.SEEK_END: - for _, rdr := range r.readers { - s, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - tmpOffset += s - } - r.Seek(tmpOffset+offset, os.SEEK_SET) - return tmpOffset + offset, nil - case os.SEEK_CUR: - if r.pos == nil { - return r.Seek(offset, os.SEEK_SET) - } - // Just return the current offset - if offset == 0 { - return r.getCurOffset() - } - - curOffset, err := r.getCurOffset() - if err != nil { - return -1, err - } - rdr, rdrOffset, err := r.getReaderForOffset(curOffset + offset) - if err != nil { - return -1, err - } - - r.pos = &pos{r.posIdx[rdr], rdrOffset} - return curOffset + offset, nil - default: - return -1, fmt.Errorf("Invalid whence: %d", whence) - } - - return -1, fmt.Errorf("Error seeking for whence: %d, offset: %d", whence, offset) -} - -func (r *multiReadSeeker) getReaderForOffset(offset int64) (io.ReadSeeker, int64, error) { - var rdr io.ReadSeeker - var rdrOffset int64 - - for i, rdr := range r.readers { - offsetTo, err := r.getOffsetToReader(rdr) - if err != nil { - return nil, -1, err - } - if offsetTo > offset { - rdr = r.readers[i-1] - rdrOffset = offsetTo - offset - break - } - - if rdr == r.readers[len(r.readers)-1] { - rdrOffset = offsetTo + offset - break - } - } - - return rdr, rdrOffset, nil -} - -func (r *multiReadSeeker) getCurOffset() (int64, error) { - var totalSize int64 - for _, rdr := range r.readers[:r.pos.idx+1] { - if r.posIdx[rdr] == r.pos.idx { - totalSize += r.pos.offset - break - } - - size, err := getReadSeekerSize(rdr) - if err != nil { - return -1, fmt.Errorf("error getting seeker size: %v", err) - } - totalSize += size - } - return totalSize, nil -} - -func (r *multiReadSeeker) getOffsetToReader(rdr io.ReadSeeker) (int64, error) { - var offset int64 - for _, r := range r.readers { - if r == rdr { - break - } - - size, err := getReadSeekerSize(rdr) - if err != nil { - return -1, err - } - offset += size - } - return offset, nil -} - -func (r *multiReadSeeker) Read(b []byte) (int, error) { - if r.pos == nil { - r.pos = &pos{0, 0} - } - - bCap := int64(cap(b)) - buf := bytes.NewBuffer(nil) - var rdr io.ReadSeeker - - for _, rdr = range r.readers[r.pos.idx:] { - readBytes, err := io.CopyN(buf, rdr, bCap) - if err != nil && err != io.EOF { - return -1, err - } - bCap -= readBytes - - if bCap == 0 { - break - } - } - - rdrPos, err := rdr.Seek(0, os.SEEK_CUR) - if err != nil { - return -1, err - } - r.pos = &pos{r.posIdx[rdr], rdrPos} - return buf.Read(b) -} - -func getReadSeekerSize(rdr io.ReadSeeker) (int64, error) { - // save the current position - pos, err := rdr.Seek(0, os.SEEK_CUR) - if err != nil { - return -1, err - } - - // get the size - size, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - - // reset the position - if _, err := rdr.Seek(pos, os.SEEK_SET); err != nil { - return -1, err - } - return size, nil -} - -// MultiReadSeeker returns a ReadSeeker that's the logical concatenation of the provided -// input readseekers. After calling this method the initial position is set to the -// beginning of the first ReadSeeker. At the end of a ReadSeeker, Read always advances -// to the beginning of the next ReadSeeker and returns EOF at the end of the last ReadSeeker. -// Seek can be used over the sum of lengths of all readseekers. -// -// When a MultiReadSeeker is used, no Read and Seek operations should be made on -// its ReadSeeker components. Also, users should make no assumption on the state -// of individual readseekers while the MultiReadSeeker is used. -func MultiReadSeeker(readers ...io.ReadSeeker) io.ReadSeeker { - if len(readers) == 1 { - return readers[0] - } - idx := make(map[io.ReadSeeker]int) - for i, rdr := range readers { - idx[rdr] = i - } - return &multiReadSeeker{ - readers: readers, - posIdx: idx, - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers.go deleted file mode 100644 index a891955ac..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers.go +++ /dev/null @@ -1,154 +0,0 @@ -package ioutils - -import ( - "crypto/sha256" - "encoding/hex" - "io" - - "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" -) - -type readCloserWrapper struct { - io.Reader - closer func() error -} - -func (r *readCloserWrapper) Close() error { - return r.closer() -} - -// NewReadCloserWrapper returns a new io.ReadCloser. -func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { - return &readCloserWrapper{ - Reader: r, - closer: closer, - } -} - -type readerErrWrapper struct { - reader io.Reader - closer func() -} - -func (r *readerErrWrapper) Read(p []byte) (int, error) { - n, err := r.reader.Read(p) - if err != nil { - r.closer() - } - return n, err -} - -// NewReaderErrWrapper returns a new io.Reader. -func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { - return &readerErrWrapper{ - reader: r, - closer: closer, - } -} - -// HashData returns the sha256 sum of src. -func HashData(src io.Reader) (string, error) { - h := sha256.New() - if _, err := io.Copy(h, src); err != nil { - return "", err - } - return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil -} - -// OnEOFReader wraps a io.ReadCloser and a function -// the function will run at the end of file or close the file. -type OnEOFReader struct { - Rc io.ReadCloser - Fn func() -} - -func (r *OnEOFReader) Read(p []byte) (n int, err error) { - n, err = r.Rc.Read(p) - if err == io.EOF { - r.runFunc() - } - return -} - -// Close closes the file and run the function. -func (r *OnEOFReader) Close() error { - err := r.Rc.Close() - r.runFunc() - return err -} - -func (r *OnEOFReader) runFunc() { - if fn := r.Fn; fn != nil { - fn() - r.Fn = nil - } -} - -// cancelReadCloser wraps an io.ReadCloser with a context for cancelling read -// operations. -type cancelReadCloser struct { - cancel func() - pR *io.PipeReader // Stream to read from - pW *io.PipeWriter -} - -// NewCancelReadCloser creates a wrapper that closes the ReadCloser when the -// context is cancelled. The returned io.ReadCloser must be closed when it is -// no longer needed. -func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { - pR, pW := io.Pipe() - - // Create a context used to signal when the pipe is closed - doneCtx, cancel := context.WithCancel(context.Background()) - - p := &cancelReadCloser{ - cancel: cancel, - pR: pR, - pW: pW, - } - - go func() { - _, err := io.Copy(pW, in) - select { - case <-ctx.Done(): - // If the context was closed, p.closeWithError - // was already called. Calling it again would - // change the error that Read returns. - default: - p.closeWithError(err) - } - in.Close() - }() - go func() { - for { - select { - case <-ctx.Done(): - p.closeWithError(ctx.Err()) - case <-doneCtx.Done(): - return - } - } - }() - - return p -} - -// Read wraps the Read method of the pipe that provides data from the wrapped -// ReadCloser. -func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { - return p.pR.Read(buf) -} - -// closeWithError closes the wrapper and its underlying reader. It will -// cause future calls to Read to return err. -func (p *cancelReadCloser) closeWithError(err error) { - p.pW.CloseWithError(err) - p.cancel() -} - -// Close closes the wrapper its underlying reader. It will cause -// future calls to Read to return io.EOF. -func (p *cancelReadCloser) Close() error { - p.closeWithError(io.EOF) - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler.go deleted file mode 100644 index 3c88f29e3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !gccgo - -package ioutils - -func callSchedulerIfNecessary() { -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go deleted file mode 100644 index c11d02b94..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build gccgo - -package ioutils - -import ( - "runtime" -) - -func callSchedulerIfNecessary() { - //allow or force Go scheduler to switch context, without explicitly - //forcing this will make it hang when using gccgo implementation - runtime.Gosched() -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_unix.go deleted file mode 100644 index 1539ad21b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package ioutils - -import "io/ioutil" - -// TempDir on Unix systems is equivalent to ioutil.TempDir. -func TempDir(dir, prefix string) (string, error) { - return ioutil.TempDir(dir, prefix) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_windows.go deleted file mode 100644 index 72c0bc597..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build windows - -package ioutils - -import ( - "io/ioutil" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath" -) - -// TempDir is the equivalent of ioutil.TempDir, except that the result is in Windows longpath format. -func TempDir(dir, prefix string) (string, error) { - tempDir, err := ioutil.TempDir(dir, prefix) - if err != nil { - return "", err - } - return longpath.AddPrefix(tempDir), nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writeflusher.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writeflusher.go deleted file mode 100644 index 2b35a2666..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writeflusher.go +++ /dev/null @@ -1,92 +0,0 @@ -package ioutils - -import ( - "errors" - "io" - "net/http" - "sync" -) - -// WriteFlusher wraps the Write and Flush operation ensuring that every write -// is a flush. In addition, the Close method can be called to intercept -// Read/Write calls if the targets lifecycle has already ended. -type WriteFlusher struct { - mu sync.Mutex - w io.Writer - flusher http.Flusher - flushed bool - closed error - - // TODO(stevvooe): Use channel for closed instead, remove mutex. Using a - // channel will allow one to properly order the operations. -} - -var errWriteFlusherClosed = errors.New("writeflusher: closed") - -func (wf *WriteFlusher) Write(b []byte) (n int, err error) { - wf.mu.Lock() - defer wf.mu.Unlock() - if wf.closed != nil { - return 0, wf.closed - } - - n, err = wf.w.Write(b) - wf.flush() // every write is a flush. - return n, err -} - -// Flush the stream immediately. -func (wf *WriteFlusher) Flush() { - wf.mu.Lock() - defer wf.mu.Unlock() - - wf.flush() -} - -// flush the stream immediately without taking a lock. Used internally. -func (wf *WriteFlusher) flush() { - if wf.closed != nil { - return - } - - wf.flushed = true - wf.flusher.Flush() -} - -// Flushed returns the state of flushed. -// If it's flushed, return true, or else it return false. -func (wf *WriteFlusher) Flushed() bool { - // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to - // be used to detect whether or a response code has been issued or not. - // Another hook should be used instead. - wf.mu.Lock() - defer wf.mu.Unlock() - - return wf.flushed -} - -// Close closes the write flusher, disallowing any further writes to the -// target. After the flusher is closed, all calls to write or flush will -// result in an error. -func (wf *WriteFlusher) Close() error { - wf.mu.Lock() - defer wf.mu.Unlock() - - if wf.closed != nil { - return wf.closed - } - - wf.closed = errWriteFlusherClosed - return nil -} - -// NewWriteFlusher returns a new WriteFlusher. -func NewWriteFlusher(w io.Writer) *WriteFlusher { - var flusher http.Flusher - if f, ok := w.(http.Flusher); ok { - flusher = f - } else { - flusher = &NopFlusher{} - } - return &WriteFlusher{w: w, flusher: flusher} -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers.go deleted file mode 100644 index ccc7f9c23..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers.go +++ /dev/null @@ -1,66 +0,0 @@ -package ioutils - -import "io" - -// NopWriter represents a type which write operation is nop. -type NopWriter struct{} - -func (*NopWriter) Write(buf []byte) (int, error) { - return len(buf), nil -} - -type nopWriteCloser struct { - io.Writer -} - -func (w *nopWriteCloser) Close() error { return nil } - -// NopWriteCloser returns a nopWriteCloser. -func NopWriteCloser(w io.Writer) io.WriteCloser { - return &nopWriteCloser{w} -} - -// NopFlusher represents a type which flush operation is nop. -type NopFlusher struct{} - -// Flush is a nop operation. -func (f *NopFlusher) Flush() {} - -type writeCloserWrapper struct { - io.Writer - closer func() error -} - -func (r *writeCloserWrapper) Close() error { - return r.closer() -} - -// NewWriteCloserWrapper returns a new io.WriteCloser. -func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { - return &writeCloserWrapper{ - Writer: r, - closer: closer, - } -} - -// WriteCounter wraps a concrete io.Writer and hold a count of the number -// of bytes written to the writer during a "session". -// This can be convenient when write return is masked -// (e.g., json.Encoder.Encode()) -type WriteCounter struct { - Count int64 - Writer io.Writer -} - -// NewWriteCounter returns a new WriteCounter. -func NewWriteCounter(w io.Writer) *WriteCounter { - return &WriteCounter{ - Writer: w, - } -} - -func (wc *WriteCounter) Write(p []byte) (count int, err error) { - count, err = wc.Writer.Write(p) - wc.Count += int64(count) - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath.go deleted file mode 100644 index 9b15bfff4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,26 +0,0 @@ -// longpath introduces some constants and helper functions for handling long paths -// in Windows, which are expected to be prepended with `\\?\` and followed by either -// a drive letter, a UNC server\share, or a volume identifier. - -package longpath - -import ( - "strings" -) - -// Prefix is the longpath prefix for Windows file paths. -const Prefix = `\\?\` - -// AddPrefix will add the Windows long path prefix to the path provided if -// it does not already have it. -func AddPrefix(path string) string { - if !strings.HasPrefix(path, Prefix) { - if strings.HasPrefix(path, `\\`) { - // This is a UNC path, so we need to add 'UNC' to the path as well. - path = Prefix + `UNC` + path[1:] - } else { - path = Prefix + path - } - } - return path -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools.go deleted file mode 100644 index 515fb4d05..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools.go +++ /dev/null @@ -1,119 +0,0 @@ -// Package pools provides a collection of pools which provide various -// data types with buffers. These can be used to lower the number of -// memory allocations and reuse buffers. -// -// New pools should be added to this package to allow them to be -// shared across packages. -// -// Utility functions which operate on pools should be added to this -// package to allow them to be reused. -package pools - -import ( - "bufio" - "io" - "sync" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" -) - -var ( - // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer. - BufioReader32KPool *BufioReaderPool - // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer. - BufioWriter32KPool *BufioWriterPool -) - -const buffer32K = 32 * 1024 - -// BufioReaderPool is a bufio reader that uses sync.Pool. -type BufioReaderPool struct { - pool sync.Pool -} - -func init() { - BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) - BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) -} - -// newBufioReaderPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioReaderPoolWithSize(size int) *BufioReaderPool { - pool := sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, size) }, - } - return &BufioReaderPool{pool: pool} -} - -// Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. -func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { - buf := bufPool.pool.Get().(*bufio.Reader) - buf.Reset(r) - return buf -} - -// Put puts the bufio.Reader back into the pool. -func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -// Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. -func Copy(dst io.Writer, src io.Reader) (written int64, err error) { - buf := BufioReader32KPool.Get(src) - written, err = io.Copy(dst, buf) - BufioReader32KPool.Put(buf) - return -} - -// NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back -// into the pool and closes the reader if it's an io.ReadCloser. -func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { - return ioutils.NewReadCloserWrapper(r, func() error { - if readCloser, ok := r.(io.ReadCloser); ok { - readCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} - -// BufioWriterPool is a bufio writer that uses sync.Pool. -type BufioWriterPool struct { - pool sync.Pool -} - -// newBufioWriterPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioWriterPoolWithSize(size int) *BufioWriterPool { - pool := sync.Pool{ - New: func() interface{} { return bufio.NewWriterSize(nil, size) }, - } - return &BufioWriterPool{pool: pool} -} - -// Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. -func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { - buf := bufPool.pool.Get().(*bufio.Writer) - buf.Reset(w) - return buf -} - -// Put puts the bufio.Writer back into the pool. -func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -// NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back -// into the pool and closes the writer if it's an io.Writecloser. -func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { - return ioutils.NewWriteCloserWrapper(w, func() error { - buf.Flush() - if writeCloser, ok := w.(io.WriteCloser); ok { - writeCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise/promise.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise/promise.go deleted file mode 100644 index dd52b9082..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise/promise.go +++ /dev/null @@ -1,11 +0,0 @@ -package promise - -// Go is a basic promise implementation: it wraps calls a function in a goroutine, -// and returns a channel which will later return the function's return value. -func Go(f func() error) chan error { - ch := make(chan error, 1) - go func() { - ch <- f() - }() - return ch -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy.go deleted file mode 100644 index b2c60046a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy.go +++ /dev/null @@ -1,175 +0,0 @@ -package stdcopy - -import ( - "encoding/binary" - "errors" - "io" - - "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" -) - -const ( - stdWriterPrefixLen = 8 - stdWriterFdIndex = 0 - stdWriterSizeIndex = 4 - - startingBufLen = 32*1024 + stdWriterPrefixLen + 1 -) - -// StdType prefixes type and length to standard stream. -type StdType [stdWriterPrefixLen]byte - -var ( - // Stdin represents standard input stream type. - Stdin = StdType{0: 0} - // Stdout represents standard output stream type. - Stdout = StdType{0: 1} - // Stderr represents standard error steam type. - Stderr = StdType{0: 2} -) - -// StdWriter is wrapper of io.Writer with extra customized info. -type StdWriter struct { - io.Writer - prefix StdType - sizeBuf []byte -} - -func (w *StdWriter) Write(buf []byte) (n int, err error) { - var n1, n2 int - if w == nil || w.Writer == nil { - return 0, errors.New("Writer not instantiated") - } - binary.BigEndian.PutUint32(w.prefix[4:], uint32(len(buf))) - n1, err = w.Writer.Write(w.prefix[:]) - if err != nil { - n = n1 - stdWriterPrefixLen - } else { - n2, err = w.Writer.Write(buf) - n = n1 + n2 - stdWriterPrefixLen - } - if n < 0 { - n = 0 - } - return -} - -// NewStdWriter instantiates a new Writer. -// Everything written to it will be encapsulated using a custom format, -// and written to the underlying `w` stream. -// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. -// `t` indicates the id of the stream to encapsulate. -// It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. -func NewStdWriter(w io.Writer, t StdType) *StdWriter { - return &StdWriter{ - Writer: w, - prefix: t, - sizeBuf: make([]byte, 4), - } -} - -var errInvalidStdHeader = errors.New("Unrecognized input header") - -// StdCopy is a modified version of io.Copy. -// -// StdCopy will demultiplex `src`, assuming that it contains two streams, -// previously multiplexed together using a StdWriter instance. -// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. -// -// StdCopy will read until it hits EOF on `src`. It will then return a nil error. -// In other words: if `err` is non nil, it indicates a real underlying error. -// -// `written` will hold the total number of bytes written to `dstout` and `dsterr`. -func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { - var ( - buf = make([]byte, startingBufLen) - bufLen = len(buf) - nr, nw int - er, ew error - out io.Writer - frameSize int - ) - - for { - // Make sure we have at least a full header - for nr < stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < stdWriterPrefixLen { - logrus.Debugf("Corrupted prefix: %v", buf[:nr]) - return written, nil - } - break - } - if er != nil { - logrus.Debugf("Error reading header: %s", er) - return 0, er - } - } - - // Check the first byte to know where to write - switch buf[stdWriterFdIndex] { - case 0: - fallthrough - case 1: - // Write on stdout - out = dstout - case 2: - // Write on stderr - out = dsterr - default: - logrus.Debugf("Error selecting output fd: (%d)", buf[stdWriterFdIndex]) - return 0, errInvalidStdHeader - } - - // Retrieve the size of the frame - frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) - logrus.Debugf("framesize: %d", frameSize) - - // Check if the buffer is big enough to read the frame. - // Extend it if necessary. - if frameSize+stdWriterPrefixLen > bufLen { - logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+stdWriterPrefixLen-bufLen+1, len(buf)) - buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) - bufLen = len(buf) - } - - // While the amount of bytes read is less than the size of the frame + header, we keep reading - for nr < frameSize+stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < frameSize+stdWriterPrefixLen { - logrus.Debugf("Corrupted frame: %v", buf[stdWriterPrefixLen:nr]) - return written, nil - } - break - } - if er != nil { - logrus.Debugf("Error reading frame: %s", er) - return 0, er - } - } - - // Write the retrieved frame (without header) - nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) - if ew != nil { - logrus.Debugf("Error writing frame: %s", ew) - return 0, ew - } - // If the frame has not been fully written: error - if nw != frameSize { - logrus.Debugf("Error Short Write: (%d on %d)", nw, frameSize) - return 0, io.ErrShortWrite - } - written += int64(nw) - - // Move the rest of the buffer to the beginning - copy(buf, buf[frameSize+stdWriterPrefixLen:]) - // Move the index - nr -= frameSize + stdWriterPrefixLen - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes.go deleted file mode 100644 index acf3f566f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes.go +++ /dev/null @@ -1,47 +0,0 @@ -package system - -import ( - "os" - "syscall" - "time" - "unsafe" -) - -var ( - maxTime time.Time -) - -func init() { - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - maxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - maxTime = time.Unix(1<<31-1, 0) - } -} - -// Chtimes changes the access time and modified time of a file at the given path -func Chtimes(name string, atime time.Time, mtime time.Time) error { - unixMinTime := time.Unix(0, 0) - unixMaxTime := maxTime - - // If the modified time is prior to the Unix Epoch, or after the - // end of Unix Time, os.Chtimes has undefined behavior - // default to Unix Epoch in this case, just in case - - if atime.Before(unixMinTime) || atime.After(unixMaxTime) { - atime = unixMinTime - } - - if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { - mtime = unixMinTime - } - - if err := os.Chtimes(name, atime, mtime); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix.go deleted file mode 100644 index 09d58bcbf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !windows - -package system - -import ( - "time" -) - -//setCTime will set the create time on a file. On Unix, the create -//time is updated as a side effect of setting the modified time, so -//no action is required. -func setCTime(path string, ctime time.Time) error { - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows.go deleted file mode 100644 index 294586846..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build windows - -package system - -import ( - "syscall" - "time" -) - -//setCTime will set the create time on a file. On Windows, this requires -//calling SetFileTime and explicitly including the create time. -func setCTime(path string, ctime time.Time) error { - ctimespec := syscall.NsecToTimespec(ctime.UnixNano()) - pathp, e := syscall.UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := syscall.CreateFile(pathp, - syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil, - syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer syscall.Close(h) - c := syscall.NsecToFiletime(syscall.TimespecToNsec(ctimespec)) - return syscall.SetFileTime(h, &c, nil, nil) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/errors.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/errors.go deleted file mode 100644 index 288318985..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package system - -import ( - "errors" -) - -var ( - // ErrNotSupportedPlatform means the platform is not supported. - ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/events_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/events_windows.go deleted file mode 100644 index 04e2de787..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/events_windows.go +++ /dev/null @@ -1,83 +0,0 @@ -package system - -// This file implements syscalls for Win32 events which are not implemented -// in golang. - -import ( - "syscall" - "unsafe" -) - -var ( - procCreateEvent = modkernel32.NewProc("CreateEventW") - procOpenEvent = modkernel32.NewProc("OpenEventW") - procSetEvent = modkernel32.NewProc("SetEvent") - procResetEvent = modkernel32.NewProc("ResetEvent") - procPulseEvent = modkernel32.NewProc("PulseEvent") -) - -// CreateEvent implements win32 CreateEventW func in golang. It will create an event object. -func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) { - namep, _ := syscall.UTF16PtrFromString(name) - var _p1 uint32 - if manualReset { - _p1 = 1 - } - var _p2 uint32 - if initialState { - _p2 = 1 - } - r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) - use(unsafe.Pointer(namep)) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = e1 - } - return -} - -// OpenEvent implements win32 OpenEventW func in golang. It opens an event object. -func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) { - namep, _ := syscall.UTF16PtrFromString(name) - var _p1 uint32 - if inheritHandle { - _p1 = 1 - } - r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) - use(unsafe.Pointer(namep)) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = e1 - } - return -} - -// SetEvent implements win32 SetEvent func in golang. -func SetEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procSetEvent) -} - -// ResetEvent implements win32 ResetEvent func in golang. -func ResetEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procResetEvent) -} - -// PulseEvent implements win32 PulseEvent func in golang. -func PulseEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procPulseEvent) -} - -func setResetPulse(handle syscall.Handle, proc *syscall.LazyProc) (err error) { - r0, _, _ := proc.Call(uintptr(handle)) - if r0 != 0 { - err = syscall.Errno(r0) - } - return -} - -var temp unsafe.Pointer - -// use ensures a variable is kept alive without the GC freeing while still needed -func use(p unsafe.Pointer) { - temp = p -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys.go deleted file mode 100644 index c14feb849..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !windows - -package system - -import ( - "os" - "path/filepath" -) - -// MkdirAll creates a directory named path along with any necessary parents, -// with permission specified by attribute perm for all dir created. -func MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. -func IsAbs(path string) bool { - return filepath.IsAbs(path) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys_windows.go deleted file mode 100644 index 16823d551..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys_windows.go +++ /dev/null @@ -1,82 +0,0 @@ -// +build windows - -package system - -import ( - "os" - "path/filepath" - "regexp" - "strings" - "syscall" -) - -// MkdirAll implementation that is volume path aware for Windows. -func MkdirAll(path string, perm os.FileMode) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { - return nil - } - - // The rest of this method is copied from os.MkdirAll and should be kept - // as-is to ensure compatibility. - - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := os.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return &os.PathError{ - Op: "mkdir", - Path: path, - Err: syscall.ENOTDIR, - } - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent - err = MkdirAll(path[0:j-1], perm) - if err != nil { - return err - } - } - - // Parent now exists; invoke Mkdir and use its result. - err = os.Mkdir(path, perm) - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, -// golang filepath.IsAbs does not consider a path \windows\system32 as absolute -// as it doesn't start with a drive-letter/colon combination. However, in -// docker we need to verify things such as WORKDIR /windows/system32 in -// a Dockerfile (which gets translated to \windows\system32 when being processed -// by the daemon. This SHOULD be treated as absolute from a docker processing -// perspective. -func IsAbs(path string) bool { - if !filepath.IsAbs(path) { - if !strings.HasPrefix(path, string(os.PathSeparator)) { - return false - } - } - return true -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat.go deleted file mode 100644 index bd23c4d50..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// Lstat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Lstat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Lstat(path, s); err != nil { - return nil, err - } - return fromStatT(s) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_windows.go deleted file mode 100644 index 49e87eb40..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build windows - -package system - -import ( - "os" -) - -// Lstat calls os.Lstat to get a fileinfo interface back. -// This is then copied into our own locally defined structure. -// Note the Linux version uses fromStatT to do the copy back, -// but that not strictly necessary when already in an OS specific module. -func Lstat(path string) (*StatT, error) { - fi, err := os.Lstat(path) - if err != nil { - return nil, err - } - - return &StatT{ - name: fi.Name(), - size: fi.Size(), - mode: fi.Mode(), - modTime: fi.ModTime(), - isDir: fi.IsDir()}, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo.go deleted file mode 100644 index 3b6e947e6..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package system - -// MemInfo contains memory statistics of the host system. -type MemInfo struct { - // Total usable RAM (i.e. physical RAM minus a few reserved bits and the - // kernel binary code). - MemTotal int64 - - // Amount of free memory. - MemFree int64 - - // Total amount of swap space available. - SwapTotal int64 - - // Amount of swap space that is currently unused. - SwapFree int64 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux.go deleted file mode 100644 index c14dbf376..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux.go +++ /dev/null @@ -1,66 +0,0 @@ -package system - -import ( - "bufio" - "io" - "os" - "strconv" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units" -) - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - file, err := os.Open("/proc/meminfo") - if err != nil { - return nil, err - } - defer file.Close() - return parseMemInfo(file) -} - -// parseMemInfo parses the /proc/meminfo file into -// a MemInfo object given a io.Reader to the file. -// -// Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*MemInfo, error) { - meminfo := &MemInfo{} - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - // Expected format: ["MemTotal:", "1234", "kB"] - parts := strings.Fields(scanner.Text()) - - // Sanity checks: Skip malformed entries. - if len(parts) < 3 || parts[2] != "kB" { - continue - } - - // Convert to bytes. - size, err := strconv.Atoi(parts[1]) - if err != nil { - continue - } - bytes := int64(size) * units.KiB - - switch parts[0] { - case "MemTotal:": - meminfo.MemTotal = bytes - case "MemFree:": - meminfo.MemFree = bytes - case "SwapTotal:": - meminfo.SwapTotal = bytes - case "SwapFree:": - meminfo.SwapFree = bytes - } - - } - - // Handle errors that may have occurred during the reading of the file. - if err := scanner.Err(); err != nil { - return nil, err - } - - return meminfo, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unsupported.go deleted file mode 100644 index 82ddd30c1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !linux,!windows - -package system - -// ReadMemInfo is not supported on platforms other than linux and windows. -func ReadMemInfo() (*MemInfo, error) { - return nil, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_windows.go deleted file mode 100644 index d46642598..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_windows.go +++ /dev/null @@ -1,44 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -var ( - modkernel32 = syscall.NewLazyDLL("kernel32.dll") - - procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") -) - -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx -type memorystatusex struct { - dwLength uint32 - dwMemoryLoad uint32 - ullTotalPhys uint64 - ullAvailPhys uint64 - ullTotalPageFile uint64 - ullAvailPageFile uint64 - ullTotalVirtual uint64 - ullAvailVirtual uint64 - ullAvailExtendedVirtual uint64 -} - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - msi := &memorystatusex{ - dwLength: 64, - } - r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) - if r1 == 0 { - return &MemInfo{}, nil - } - return &MemInfo{ - MemTotal: int64(msi.ullTotalPhys), - MemFree: int64(msi.ullAvailPhys), - SwapTotal: int64(msi.ullTotalPageFile), - SwapFree: int64(msi.ullAvailPageFile), - }, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod.go deleted file mode 100644 index 73958182b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// Mknod creates a filesystem node (file, device special file or named pipe) named path -// with attributes specified by mode and dev. -func Mknod(path string, mode uint32, dev int) error { - return syscall.Mknod(path, mode, dev) -} - -// Mkdev is used to build the value of linux devices (in /dev/) which specifies major -// and minor number of the newly created device special file. -// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. -// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, -// then the top 12 bits of the minor. -func Mkdev(major int64, minor int64) uint32 { - return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff)) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod_windows.go deleted file mode 100644 index 2e863c021..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package system - -// Mknod is not implemented on Windows. -func Mknod(path string, mode uint32, dev int) error { - return ErrNotSupportedPlatform -} - -// Mkdev is not implemented on Windows. -func Mkdev(major int64, minor int64) uint32 { - panic("Mkdev not implemented on Windows.") -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_unix.go deleted file mode 100644 index 1b6cc9cbd..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows - -package system - -// DefaultPathEnv is unix style list of directories to search for -// executables. Each directory is separated from the next by a colon -// ':' character . -const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_windows.go deleted file mode 100644 index 09e7f89fe..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build windows - -package system - -// DefaultPathEnv is deliberately empty on Windows as the default path will be set by -// the container. Docker has no context of what the default path should be. -const DefaultPathEnv = "" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat.go deleted file mode 100644 index 087034c5e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat.go +++ /dev/null @@ -1,53 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// StatT type contains status of a file. It contains metadata -// like permission, owner, group, size, etc about a file. -type StatT struct { - mode uint32 - uid uint32 - gid uint32 - rdev uint64 - size int64 - mtim syscall.Timespec -} - -// Mode returns file's permission mode. -func (s StatT) Mode() uint32 { - return s.mode -} - -// UID returns file's user id of owner. -func (s StatT) UID() uint32 { - return s.uid -} - -// GID returns file's group id of owner. -func (s StatT) GID() uint32 { - return s.gid -} - -// Rdev returns file's device ID (if it's special file). -func (s StatT) Rdev() uint64 { - return s.rdev -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() syscall.Timespec { - return s.mtim -} - -// GetLastModification returns file's last modification time. -func (s StatT) GetLastModification() syscall.Timespec { - return s.Mtim() -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_freebsd.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_freebsd.go deleted file mode 100644 index d0fb6f151..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_freebsd.go +++ /dev/null @@ -1,27 +0,0 @@ -package system - -import ( - "syscall" -) - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} - -// Stat takes a path to a file and returns -// a system.Stat_t type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Stat(path, s); err != nil { - return nil, err - } - return fromStatT(s) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_linux.go deleted file mode 100644 index 8b1eded13..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_linux.go +++ /dev/null @@ -1,33 +0,0 @@ -package system - -import ( - "syscall" -) - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: s.Mode, - uid: s.Uid, - gid: s.Gid, - rdev: s.Rdev, - mtim: s.Mtim}, nil -} - -// FromStatT exists only on linux, and loads a system.StatT from a -// syscal.Stat_t. -func FromStatT(s *syscall.Stat_t) (*StatT, error) { - return fromStatT(s) -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Stat(path, s); err != nil { - return nil, err - } - return fromStatT(s) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_openbsd.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_openbsd.go deleted file mode 100644 index 3c3b71fb2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_openbsd.go +++ /dev/null @@ -1,15 +0,0 @@ -package system - -import ( - "syscall" -) - -// fromStatT creates a system.StatT type from a syscall.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_solaris.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_solaris.go deleted file mode 100644 index b01d08acf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_solaris.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build solaris - -package system - -import ( - "syscall" -) - -// fromStatT creates a system.StatT type from a syscall.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unsupported.go deleted file mode 100644 index f53e9de4d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build !linux,!windows,!freebsd,!solaris,!openbsd - -package system - -import ( - "syscall" -) - -// fromStatT creates a system.StatT type from a syscall.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_windows.go deleted file mode 100644 index 39490c625..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_windows.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build windows - -package system - -import ( - "os" - "time" -) - -// StatT type contains status of a file. It contains metadata -// like name, permission, size, etc about a file. -type StatT struct { - name string - size int64 - mode os.FileMode - modTime time.Time - isDir bool -} - -// Name returns file's name. -func (s StatT) Name() string { - return s.name -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mode returns file's permission mode. -func (s StatT) Mode() os.FileMode { - return s.mode -} - -// ModTime returns file's last modification time. -func (s StatT) ModTime() time.Time { - return s.modTime -} - -// IsDir returns whether file is actually a directory. -func (s StatT) IsDir() bool { - return s.isDir -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_unix.go deleted file mode 100644 index f1497c587..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux freebsd - -package system - -import "syscall" - -// Unmount is a platform-specific helper function to call -// the unmount syscall. -func Unmount(dest string) error { - return syscall.Unmount(dest, 0) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_windows.go deleted file mode 100644 index 273aa234b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_windows.go +++ /dev/null @@ -1,36 +0,0 @@ -package system - -import ( - "fmt" - "syscall" -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion struct { - Version uint32 - MajorVersion uint8 - MinorVersion uint8 - Build uint16 -} - -// GetOSVersion gets the operating system version on Windows. Note that -// docker.exe must be manifested to get the correct version information. -func GetOSVersion() (OSVersion, error) { - var err error - osv := OSVersion{} - osv.Version, err = syscall.GetVersion() - if err != nil { - return osv, fmt.Errorf("Failed to call GetVersion()") - } - osv.MajorVersion = uint8(osv.Version & 0xFF) - osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) - osv.Build = uint16(osv.Version >> 16) - return osv, nil -} - -// Unmount is a platform-specific helper function to call -// the unmount syscall. Not supported on Windows -func Unmount(dest string) error { - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask.go deleted file mode 100644 index c670fcd75..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// Umask sets current process's file mode creation mask to newmask -// and return oldmask. -func Umask(newmask int) (oldmask int, err error) { - return syscall.Umask(newmask), nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask_windows.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask_windows.go deleted file mode 100644 index 13f1de176..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package system - -// Umask is not supported on the windows platform. -func Umask(newmask int) (oldmask int, err error) { - // should not be called on cli code path - return 0, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_darwin.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_darwin.go deleted file mode 100644 index 0a1619754..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_darwin.go +++ /dev/null @@ -1,8 +0,0 @@ -package system - -import "syscall" - -// LUtimesNano is not supported by darwin platform. -func LUtimesNano(path string, ts []syscall.Timespec) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_freebsd.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_freebsd.go deleted file mode 100644 index e2eac3b55..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_freebsd.go +++ /dev/null @@ -1,22 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - var _path *byte - _path, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - - if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_linux.go deleted file mode 100644 index fc8a1aba9..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_linux.go +++ /dev/null @@ -1,26 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - // These are not currently available in syscall - atFdCwd := -100 - atSymLinkNoFollow := 0x100 - - var _path *byte - _path, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - - if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(atSymLinkNoFollow), 0, 0); err != 0 && err != syscall.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unsupported.go deleted file mode 100644 index 50c3a0436..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unsupported.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !linux,!freebsd,!darwin - -package system - -import "syscall" - -// LUtimesNano is not supported on platforms other than linux, freebsd and darwin. -func LUtimesNano(path string, ts []syscall.Timespec) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_linux.go deleted file mode 100644 index d2e2c0579..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_linux.go +++ /dev/null @@ -1,63 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// Lgetxattr retrieves the value of the extended attribute identified by attr -// and associated with the given path in the file system. -// It will returns a nil slice and nil error if the xattr is not set. -func Lgetxattr(path string, attr string) ([]byte, error) { - pathBytes, err := syscall.BytePtrFromString(path) - if err != nil { - return nil, err - } - attrBytes, err := syscall.BytePtrFromString(attr) - if err != nil { - return nil, err - } - - dest := make([]byte, 128) - destBytes := unsafe.Pointer(&dest[0]) - sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) - if errno == syscall.ENODATA { - return nil, nil - } - if errno == syscall.ERANGE { - dest = make([]byte, sz) - destBytes := unsafe.Pointer(&dest[0]) - sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) - } - if errno != 0 { - return nil, errno - } - - return dest[:sz], nil -} - -var _zero uintptr - -// Lsetxattr sets the value of the extended attribute identified by attr -// and associated with the given path in the file system. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - pathBytes, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - attrBytes, err := syscall.BytePtrFromString(attr) - if err != nil { - return err - } - var dataBytes unsafe.Pointer - if len(data) > 0 { - dataBytes = unsafe.Pointer(&data[0]) - } else { - dataBytes = unsafe.Pointer(&_zero) - } - _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0) - if errno != 0 { - return errno - } - return nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_unsupported.go deleted file mode 100644 index 0114f2227..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !linux - -package system - -// Lgetxattr is not supported on platforms other than linux. -func Lgetxattr(path string, attr string) ([]byte, error) { - return nil, ErrNotSupportedPlatform -} - -// Lsetxattr is not supported on platforms other than linux. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/CONTRIBUTING.md deleted file mode 100644 index 9ea86d784..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# Contributing to go-units - -Want to hack on go-units? Awesome! Here are instructions to get you started. - -go-units is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read Docker's -[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), -[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), -[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and -[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.code b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.code deleted file mode 100644 index b55b37bc3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.code +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.docs b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.docs deleted file mode 100644 index e26cd4fc8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.docs +++ /dev/null @@ -1,425 +0,0 @@ -Attribution-ShareAlike 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution-ShareAlike 4.0 International Public -License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-ShareAlike 4.0 International Public License ("Public -License"). To the extent this Public License may be interpreted as a -contract, You are granted the Licensed Rights in consideration of Your -acceptance of these terms and conditions, and the Licensor grants You -such rights in consideration of benefits the Licensor receives from -making the Licensed Material available under these terms and -conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. BY-SA Compatible License means a license listed at - creativecommons.org/compatiblelicenses, approved by Creative - Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - e. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name - of a Creative Commons Public License. The License Elements of this - Public License are Attribution and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - i. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - k. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - l. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - m. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. Additional offer from the Licensor -- Adapted Material. - Every recipient of Adapted Material from You - automatically receives an offer from the Licensor to - exercise the Licensed Rights in the Adapted Material - under the conditions of the Adapter's License You apply. - - c. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - b. ShareAlike. - - In addition to the conditions in Section 3(a), if You Share - Adapted Material You produce, the following conditions also apply. - - 1. The Adapter's License You apply must be a Creative Commons - license with the same License Elements, this version or - later, or a BY-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the - Adapter's License You apply. You may satisfy this condition - in any reasonable manner based on the medium, means, and - context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms - or conditions on, or apply any Effective Technological - Measures to, Adapted Material that restrict exercise of the - rights granted under the Adapter's License You apply. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material, - - including for purposes of Section 3(b); and - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public licenses. -Notwithstanding, Creative Commons may elect to apply one of its public -licenses to material it publishes and in those instances will be -considered the "Licensor." Except for the limited purpose of indicating -that material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the public -licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/MAINTAINERS deleted file mode 100644 index 477be8b21..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/MAINTAINERS +++ /dev/null @@ -1,27 +0,0 @@ -# go-connections maintainers file -# -# This file describes who runs the docker/go-connections project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "calavera", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - [people.calavera] - Name = "David Calavera" - Email = "david.calavera@gmail.com" - GitHub = "calavera" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/README.md deleted file mode 100644 index 3ce4d79da..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/README.md +++ /dev/null @@ -1,18 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) - -# Introduction - -go-units is a library to transform human friendly measurements into machine friendly values. - -## Usage - -See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. - -## Copyright and license - -Copyright © 2015 Docker, Inc. All rights reserved, except as follows. Code -is released under the Apache 2.0 license. The README.md file, and files in the -"docs" folder are licensed under the Creative Commons Attribution 4.0 -International License under the terms and conditions set forth in the file -"LICENSE.docs". You may obtain a duplicate copy of the same license, titled -CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/circle.yml b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/circle.yml deleted file mode 100644 index 9043b3547..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/circle.yml +++ /dev/null @@ -1,11 +0,0 @@ -dependencies: - post: - # install golint - - go get github.com/golang/lint/golint - -test: - pre: - # run analysis before tests - - go vet ./... - - test -z "$(golint ./... | tee /dev/stderr)" - - test -z "$(gofmt -s -l . | tee /dev/stderr)" diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration.go deleted file mode 100644 index c219a8a96..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration.go +++ /dev/null @@ -1,33 +0,0 @@ -// Package units provides helper function to parse and print size and time units -// in human-readable format. -package units - -import ( - "fmt" - "time" -) - -// HumanDuration returns a human-readable approximation of a duration -// (eg. "About a minute", "4 hours ago", etc.). -func HumanDuration(d time.Duration) string { - if seconds := int(d.Seconds()); seconds < 1 { - return "Less than a second" - } else if seconds < 60 { - return fmt.Sprintf("%d seconds", seconds) - } else if minutes := int(d.Minutes()); minutes == 1 { - return "About a minute" - } else if minutes < 60 { - return fmt.Sprintf("%d minutes", minutes) - } else if hours := int(d.Hours()); hours == 1 { - return "About an hour" - } else if hours < 48 { - return fmt.Sprintf("%d hours", hours) - } else if hours < 24*7*2 { - return fmt.Sprintf("%d days", hours/24) - } else if hours < 24*30*3 { - return fmt.Sprintf("%d weeks", hours/24/7) - } else if hours < 24*365*2 { - return fmt.Sprintf("%d months", hours/24/30) - } - return fmt.Sprintf("%d years", int(d.Hours())/24/365) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size.go deleted file mode 100644 index 3b59daff3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size.go +++ /dev/null @@ -1,95 +0,0 @@ -package units - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// See: http://en.wikipedia.org/wiki/Binary_prefix -const ( - // Decimal - - KB = 1000 - MB = 1000 * KB - GB = 1000 * MB - TB = 1000 * GB - PB = 1000 * TB - - // Binary - - KiB = 1024 - MiB = 1024 * KiB - GiB = 1024 * MiB - TiB = 1024 * GiB - PiB = 1024 * TiB -) - -type unitMap map[string]int64 - -var ( - decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} - binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} - sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`) -) - -var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} -var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - -// CustomSize returns a human-readable approximation of a size -// using custom format. -func CustomSize(format string, size float64, base float64, _map []string) string { - i := 0 - for size >= base { - size = size / base - i++ - } - return fmt.Sprintf(format, size, _map[i]) -} - -// HumanSize returns a human-readable approximation of a size -// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). -func HumanSize(size float64) string { - return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) -} - -// BytesSize returns a human-readable size in bytes, kibibytes, -// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). -func BytesSize(size float64) string { - return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs) -} - -// FromHumanSize returns an integer from a human-readable specification of a -// size using SI standard (eg. "44kB", "17MB"). -func FromHumanSize(size string) (int64, error) { - return parseSize(size, decimalMap) -} - -// RAMInBytes parses a human-readable string representing an amount of RAM -// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and -// returns the number of bytes, or -1 if the string is unparseable. -// Units are case-insensitive, and the 'b' suffix is optional. -func RAMInBytes(size string) (int64, error) { - return parseSize(size, binaryMap) -} - -// Parses the human-readable size string into the amount it represents. -func parseSize(sizeStr string, uMap unitMap) (int64, error) { - matches := sizeRegex.FindStringSubmatch(sizeStr) - if len(matches) != 3 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - size, err := strconv.ParseInt(matches[1], 10, 0) - if err != nil { - return -1, err - } - - unitPrefix := strings.ToLower(matches[2]) - if mul, ok := uMap[unitPrefix]; ok { - size *= mul - } - - return size, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit.go deleted file mode 100644 index 5ac7fd825..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit.go +++ /dev/null @@ -1,118 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "strings" -) - -// Ulimit is a human friendly version of Rlimit. -type Ulimit struct { - Name string - Hard int64 - Soft int64 -} - -// Rlimit specifies the resource limits, such as max open files. -type Rlimit struct { - Type int `json:"type,omitempty"` - Hard uint64 `json:"hard,omitempty"` - Soft uint64 `json:"soft,omitempty"` -} - -const ( - // magic numbers for making the syscall - // some of these are defined in the syscall package, but not all. - // Also since Windows client doesn't get access to the syscall package, need to - // define these here - rlimitAs = 9 - rlimitCore = 4 - rlimitCPU = 0 - rlimitData = 2 - rlimitFsize = 1 - rlimitLocks = 10 - rlimitMemlock = 8 - rlimitMsgqueue = 12 - rlimitNice = 13 - rlimitNofile = 7 - rlimitNproc = 6 - rlimitRss = 5 - rlimitRtprio = 14 - rlimitRttime = 15 - rlimitSigpending = 11 - rlimitStack = 3 -) - -var ulimitNameMapping = map[string]int{ - //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. - "core": rlimitCore, - "cpu": rlimitCPU, - "data": rlimitData, - "fsize": rlimitFsize, - "locks": rlimitLocks, - "memlock": rlimitMemlock, - "msgqueue": rlimitMsgqueue, - "nice": rlimitNice, - "nofile": rlimitNofile, - "nproc": rlimitNproc, - "rss": rlimitRss, - "rtprio": rlimitRtprio, - "rttime": rlimitRttime, - "sigpending": rlimitSigpending, - "stack": rlimitStack, -} - -// ParseUlimit parses and returns a Ulimit from the specified string. -func ParseUlimit(val string) (*Ulimit, error) { - parts := strings.SplitN(val, "=", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("invalid ulimit argument: %s", val) - } - - if _, exists := ulimitNameMapping[parts[0]]; !exists { - return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) - } - - var ( - soft int64 - hard = &soft // default to soft in case no hard was set - temp int64 - err error - ) - switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { - case 2: - temp, err = strconv.ParseInt(limitVals[1], 10, 64) - if err != nil { - return nil, err - } - hard = &temp - fallthrough - case 1: - soft, err = strconv.ParseInt(limitVals[0], 10, 64) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) - } - - if soft > *hard { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) - } - - return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil -} - -// GetRlimit returns the RLimit corresponding to Ulimit. -func (u *Ulimit) GetRlimit() (*Rlimit, error) { - t, exists := ulimitNameMapping[u.Name] - if !exists { - return nil, fmt.Errorf("invalid ulimit name %s", u.Name) - } - - return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil -} - -func (u *Ulimit) String() string { - return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE deleted file mode 100644 index 0e5fb8728..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md deleted file mode 100644 index c60a31b05..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md +++ /dev/null @@ -1,7 +0,0 @@ -context -======= -[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) - -gorilla/context is a general purpose registry for global request variables. - -Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go deleted file mode 100644 index 81cb128b1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context - -import ( - "net/http" - "sync" - "time" -) - -var ( - mutex sync.RWMutex - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) -) - -// Set stores a value for a given key in a given request. -func Set(r *http.Request, key, val interface{}) { - mutex.Lock() - if data[r] == nil { - data[r] = make(map[interface{}]interface{}) - datat[r] = time.Now().Unix() - } - data[r][key] = val - mutex.Unlock() -} - -// Get returns a value stored for a given key in a given request. -func Get(r *http.Request, key interface{}) interface{} { - mutex.RLock() - if ctx := data[r]; ctx != nil { - value := ctx[key] - mutex.RUnlock() - return value - } - mutex.RUnlock() - return nil -} - -// GetOk returns stored value and presence state like multi-value return of map access. -func GetOk(r *http.Request, key interface{}) (interface{}, bool) { - mutex.RLock() - if _, ok := data[r]; ok { - value, ok := data[r][key] - mutex.RUnlock() - return value, ok - } - mutex.RUnlock() - return nil, false -} - -// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. -func GetAll(r *http.Request) map[interface{}]interface{} { - mutex.RLock() - if context, ok := data[r]; ok { - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result - } - mutex.RUnlock() - return nil -} - -// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if -// the request was registered. -func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { - mutex.RLock() - context, ok := data[r] - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result, ok -} - -// Delete removes a value stored for a given key in a given request. -func Delete(r *http.Request, key interface{}) { - mutex.Lock() - if data[r] != nil { - delete(data[r], key) - } - mutex.Unlock() -} - -// Clear removes all values stored for a given request. -// -// This is usually called by a handler wrapper to clean up request -// variables at the end of a request lifetime. See ClearHandler(). -func Clear(r *http.Request) { - mutex.Lock() - clear(r) - mutex.Unlock() -} - -// clear is Clear without the lock. -func clear(r *http.Request) { - delete(data, r) - delete(datat, r) -} - -// Purge removes request data stored for longer than maxAge, in seconds. -// It returns the amount of requests removed. -// -// If maxAge <= 0, all request data is removed. -// -// This is only used for sanity check: in case context cleaning was not -// properly set some request data can be kept forever, consuming an increasing -// amount of memory. In case this is detected, Purge() must be called -// periodically until the problem is fixed. -func Purge(maxAge int) int { - mutex.Lock() - count := 0 - if maxAge <= 0 { - count = len(data) - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) - } else { - min := time.Now().Unix() - int64(maxAge) - for r := range data { - if datat[r] < min { - clear(r) - count++ - } - } - } - mutex.Unlock() - return count -} - -// ClearHandler wraps an http.Handler and clears request values at the end -// of a request lifetime. -func ClearHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer Clear(r) - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go deleted file mode 100644 index 73c740031..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package context stores values shared during a request lifetime. - -For example, a router can set variables extracted from the URL and later -application handlers can access those values, or it can be used to store -sessions values to be saved at the end of a request. There are several -others common uses. - -The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: - - http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 - -Here's the basic usage: first define the keys that you will need. The key -type is interface{} so a key can be of any type that supports equality. -Here we define a key using a custom int type to avoid name collisions: - - package foo - - import ( - "github.com/gorilla/context" - ) - - type key int - - const MyKey key = 0 - -Then set a variable. Variables are bound to an http.Request object, so you -need a request instance to set a value: - - context.Set(r, MyKey, "bar") - -The application can later access the variable using the same key you provided: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // val is "bar". - val := context.Get(r, foo.MyKey) - - // returns ("bar", true) - val, ok := context.GetOk(r, foo.MyKey) - // ... - } - -And that's all about the basic usage. We discuss some other ideas below. - -Any type can be stored in the context. To enforce a given type, make the key -private and wrap Get() and Set() to accept and return values of a specific -type: - - type key int - - const mykey key = 0 - - // GetMyKey returns a value for this package from the request values. - func GetMyKey(r *http.Request) SomeType { - if rv := context.Get(r, mykey); rv != nil { - return rv.(SomeType) - } - return nil - } - - // SetMyKey sets a value for this package in the request values. - func SetMyKey(r *http.Request, val SomeType) { - context.Set(r, mykey, val) - } - -Variables must be cleared at the end of a request, to remove all values -that were stored. This can be done in an http.Handler, after a request was -served. Just call Clear() passing the request: - - context.Clear(r) - -...or use ClearHandler(), which conveniently wraps an http.Handler to clear -variables at the end of a request lifetime. - -The Routers from the packages gorilla/mux and gorilla/pat call Clear() -so if you are using either of them you don't need to clear the context manually. -*/ -package context diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE deleted file mode 100644 index 0e5fb8728..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md deleted file mode 100644 index b987c9e5d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md +++ /dev/null @@ -1,240 +0,0 @@ -mux -=== -[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) -[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) - -Package `gorilla/mux` implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: - -* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. -* URL hosts and paths can have variables with an optional regular expression. -* Registered URLs can be built, or "reversed", which helps maintaining references to resources. -* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. -* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. - -Let's start registering a couple of URL paths and handlers: - -```go -func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) -} -``` - -Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. - -Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/products/{key}", ProductHandler) -r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: - -```go -vars := mux.Vars(request) -category := vars["category"] -``` - -And this is all you need to know about the basic usage. More advanced options are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: - -```go -r := mux.NewRouter() -// Only matches if domain is "www.example.com". -r.Host("www.example.com") -// Matches a dynamic subdomain. -r.Host("{subdomain:[a-z]+}.domain.com") -``` - -There are several other matchers that can be added. To match path prefixes: - -```go -r.PathPrefix("/products/") -``` - -...or HTTP methods: - -```go -r.Methods("GET", "POST") -``` - -...or URL schemes: - -```go -r.Schemes("https") -``` - -...or header values: - -```go -r.Headers("X-Requested-With", "XMLHttpRequest") -``` - -...or query values: - -```go -r.Queries("key", "value") -``` - -...or to use a custom matcher function: - -```go -r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 -}) -``` - -...and finally, it is possible to combine several matchers in a single route: - -```go -r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") -``` - -Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". - -For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: - -```go -r := mux.NewRouter() -s := r.Host("www.example.com").Subrouter() -``` - -Then register routes in the subrouter: - -```go -s.HandleFunc("/products/", ProductsHandler) -s.HandleFunc("/products/{key}", ProductHandler) -s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -``` - -The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: - -```go -r := mux.NewRouter() -s := r.PathPrefix("/products").Subrouter() -// "/products/" -s.HandleFunc("/", ProductsHandler) -// "/products/{key}/" -s.HandleFunc("/{key}/", ProductHandler) -// "/products/{key}/details" -s.HandleFunc("/{key}/details", ProductDetailsHandler) -``` - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") -``` - -To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: - -```go -url, err := r.Get("article").URL("category", "technology", "id", "42") -``` - -...and the result will be a `url.URL` with the following path: - -``` -"/articles/technology/42" -``` - -This also works for host variables: - -```go -r := mux.NewRouter() -r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// url.String() will be "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - -```go -r.HeadersRegexp("Content-Type", "application/(text|json)") -``` - -...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` - -There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: - -```go -// "http://news.domain.com/" -host, err := r.Get("article").URLHost("subdomain", "news") - -// "/articles/technology/42" -path, err := r.Get("article").URLPath("category", "technology", "id", "42") -``` - -And if you use subrouters, host and path defined separately can be built as well: - -```go -r := mux.NewRouter() -s := r.Host("{subdomain}.domain.com").Subrouter() -s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -## Full Example - -Here's a complete, runnable example of a small `mux` based server: - -```go -package main - -import ( - "net/http" - - "github.com/gorilla/mux" -) - -func YourHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Gorilla!\n")) -} - -func main() { - r := mux.NewRouter() - // Routes consist of a path and a handler function. - r.HandleFunc("/", YourHandler) - - // Bind to a port and pass our router in - http.ListenAndServe(":8000", r) -} -``` - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go deleted file mode 100644 index 49798cb5c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package gorilla/mux implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard -http.ServeMux, mux.Router matches incoming requests against a list of -registered routes and calls a handler for the route that matches the URL -or other conditions. The main features are: - - * Requests can be matched based on URL host, path, path prefix, schemes, - header and query values, HTTP methods or using custom matchers. - * URL hosts and paths can have variables with an optional regular - expression. - * Registered URLs can be built, or "reversed", which helps maintaining - references to resources. - * Routes can be used as subrouters: nested routes are only tested if the - parent route matches. This is useful to define groups of routes that - share common conditions like a host, a path prefix or other repeated - attributes. As a bonus, this optimizes request matching. - * It implements the http.Handler interface so it is compatible with the - standard http.ServeMux. - -Let's start registering a couple of URL paths and handlers: - - func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) - } - -Here we register three routes mapping URL paths to handlers. This is -equivalent to how http.HandleFunc() works: if an incoming request URL matches -one of the paths, the corresponding handler is called passing -(http.ResponseWriter, *http.Request) as parameters. - -Paths can have variables. They are defined using the format {name} or -{name:pattern}. If a regular expression pattern is not defined, the matched -variable will be anything until the next slash. For example: - - r := mux.NewRouter() - r.HandleFunc("/products/{key}", ProductHandler) - r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) - -The names are used to create a map of route variables which can be retrieved -calling mux.Vars(): - - vars := mux.Vars(request) - category := vars["category"] - -And this is all you need to know about the basic usage. More advanced options -are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host -pattern to be matched. They can also have variables: - - r := mux.NewRouter() - // Only matches if domain is "www.example.com". - r.Host("www.example.com") - // Matches a dynamic subdomain. - r.Host("{subdomain:[a-z]+}.domain.com") - -There are several other matchers that can be added. To match path prefixes: - - r.PathPrefix("/products/") - -...or HTTP methods: - - r.Methods("GET", "POST") - -...or URL schemes: - - r.Schemes("https") - -...or header values: - - r.Headers("X-Requested-With", "XMLHttpRequest") - -...or query values: - - r.Queries("key", "value") - -...or to use a custom matcher function: - - r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 - }) - -...and finally, it is possible to combine several matchers in a single route: - - r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") - -Setting the same matching conditions again and again can be boring, so we have -a way to group several routes that share the same requirements. -We call it "subrouting". - -For example, let's say we have several URLs that should only match when the -host is "www.example.com". Create a route for that host and get a "subrouter" -from it: - - r := mux.NewRouter() - s := r.Host("www.example.com").Subrouter() - -Then register routes in the subrouter: - - s.HandleFunc("/products/", ProductsHandler) - s.HandleFunc("/products/{key}", ProductHandler) - s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) - -The three URL paths we registered above will only be tested if the domain is -"www.example.com", because the subrouter is tested first. This is not -only convenient, but also optimizes request matching. You can create -subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define -subrouters in a central place and then parts of the app can register its -paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, -the inner routes use it as base for their paths: - - r := mux.NewRouter() - s := r.PathPrefix("/products").Subrouter() - // "/products/" - s.HandleFunc("/", ProductsHandler) - // "/products/{key}/" - s.HandleFunc("/{key}/", ProductHandler) - // "/products/{key}/details" - s.HandleFunc("/{key}/details", ProductDetailsHandler) - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, -or "reversed". We define a name calling Name() on a route. For example: - - r := mux.NewRouter() - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") - -To build a URL, get the route and call the URL() method, passing a sequence of -key/value pairs for the route variables. For the previous route, we would do: - - url, err := r.Get("article").URL("category", "technology", "id", "42") - -...and the result will be a url.URL with the following path: - - "/articles/technology/42" - -This also works for host variables: - - r := mux.NewRouter() - r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // url.String() will be "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") - -All variables defined in the route are required, and their values must -conform to the corresponding patterns. These requirements guarantee that a -generated URL will always match a registered route -- the only exception is -for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - - r.HeadersRegexp("Content-Type", "application/(text|json)") - -...and the route will match both requests with a Content-Type of `application/json` as well as -`application/text` - -There's also a way to build only the URL host or path for a route: -use the methods URLHost() or URLPath() instead. For the previous route, -we would do: - - // "http://news.domain.com/" - host, err := r.Get("article").URLHost("subdomain", "news") - - // "/articles/technology/42" - path, err := r.Get("article").URLPath("category", "technology", "id", "42") - -And if you use subrouters, host and path defined separately can be built -as well: - - r := mux.NewRouter() - s := r.Host("{subdomain}.domain.com").Subrouter() - s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -*/ -package mux diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go deleted file mode 100644 index cb03ddfe5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package mux - -import ( - "errors" - "fmt" - "net/http" - "path" - "regexp" - - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/context" -) - -// NewRouter returns a new router instance. -func NewRouter() *Router { - return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} -} - -// Router registers routes to be matched and dispatches a handler. -// -// It implements the http.Handler interface, so it can be registered to serve -// requests: -// -// var router = mux.NewRouter() -// -// func main() { -// http.Handle("/", router) -// } -// -// Or, for Google App Engine, register it in a init() function: -// -// func init() { -// http.Handle("/", router) -// } -// -// This will send all incoming requests to the router. -type Router struct { - // Configurable Handler to be used when no route matches. - NotFoundHandler http.Handler - // Parent route, if this is a subrouter. - parent parentRoute - // Routes to be matched, in order. - routes []*Route - // Routes by name for URL building. - namedRoutes map[string]*Route - // See Router.StrictSlash(). This defines the flag for new routes. - strictSlash bool - // If true, do not clear the request context after handling the request - KeepContext bool -} - -// Match matches registered routes against the request. -func (r *Router) Match(req *http.Request, match *RouteMatch) bool { - for _, route := range r.routes { - if route.Match(req, match) { - return true - } - } - - // Closest match for a router (includes sub-routers) - if r.NotFoundHandler != nil { - match.Handler = r.NotFoundHandler - return true - } - return false -} - -// ServeHTTP dispatches the handler registered in the matched route. -// -// When there is a match, the route variables can be retrieved calling -// mux.Vars(request). -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - // Clean path to canonical form and redirect. - if p := cleanPath(req.URL.Path); p != req.URL.Path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) - w.WriteHeader(http.StatusMovedPermanently) - return - } - var match RouteMatch - var handler http.Handler - if r.Match(req, &match) { - handler = match.Handler - setVars(req, match.Vars) - setCurrentRoute(req, match.Route) - } - if handler == nil { - handler = http.NotFoundHandler() - } - if !r.KeepContext { - defer context.Clear(req) - } - handler.ServeHTTP(w, req) -} - -// Get returns a route registered with the given name. -func (r *Router) Get(name string) *Route { - return r.getNamedRoutes()[name] -} - -// GetRoute returns a route registered with the given name. This method -// was renamed to Get() and remains here for backwards compatibility. -func (r *Router) GetRoute(name string) *Route { - return r.getNamedRoutes()[name] -} - -// StrictSlash defines the trailing slash behavior for new routes. The initial -// value is false. -// -// When true, if the route path is "/path/", accessing "/path" will redirect -// to the former and vice versa. In other words, your application will always -// see the path as specified in the route. -// -// When false, if the route path is "/path", accessing "/path/" will not match -// this route and vice versa. -// -// Special case: when a route sets a path prefix using the PathPrefix() method, -// strict slash is ignored for that route because the redirect behavior can't -// be determined from a prefix alone. However, any subrouters created from that -// route inherit the original StrictSlash setting. -func (r *Router) StrictSlash(value bool) *Router { - r.strictSlash = value - return r -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// getNamedRoutes returns the map where named routes are registered. -func (r *Router) getNamedRoutes() map[string]*Route { - if r.namedRoutes == nil { - if r.parent != nil { - r.namedRoutes = r.parent.getNamedRoutes() - } else { - r.namedRoutes = make(map[string]*Route) - } - } - return r.namedRoutes -} - -// getRegexpGroup returns regexp definitions from the parent route, if any. -func (r *Router) getRegexpGroup() *routeRegexpGroup { - if r.parent != nil { - return r.parent.getRegexpGroup() - } - return nil -} - -func (r *Router) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// Route factories -// ---------------------------------------------------------------------------- - -// NewRoute registers an empty route. -func (r *Router) NewRoute() *Route { - route := &Route{parent: r, strictSlash: r.strictSlash} - r.routes = append(r.routes, route) - return route -} - -// Handle registers a new route with a matcher for the URL path. -// See Route.Path() and Route.Handler(). -func (r *Router) Handle(path string, handler http.Handler) *Route { - return r.NewRoute().Path(path).Handler(handler) -} - -// HandleFunc registers a new route with a matcher for the URL path. -// See Route.Path() and Route.HandlerFunc(). -func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, - *http.Request)) *Route { - return r.NewRoute().Path(path).HandlerFunc(f) -} - -// Headers registers a new route with a matcher for request header values. -// See Route.Headers(). -func (r *Router) Headers(pairs ...string) *Route { - return r.NewRoute().Headers(pairs...) -} - -// Host registers a new route with a matcher for the URL host. -// See Route.Host(). -func (r *Router) Host(tpl string) *Route { - return r.NewRoute().Host(tpl) -} - -// MatcherFunc registers a new route with a custom matcher function. -// See Route.MatcherFunc(). -func (r *Router) MatcherFunc(f MatcherFunc) *Route { - return r.NewRoute().MatcherFunc(f) -} - -// Methods registers a new route with a matcher for HTTP methods. -// See Route.Methods(). -func (r *Router) Methods(methods ...string) *Route { - return r.NewRoute().Methods(methods...) -} - -// Path registers a new route with a matcher for the URL path. -// See Route.Path(). -func (r *Router) Path(tpl string) *Route { - return r.NewRoute().Path(tpl) -} - -// PathPrefix registers a new route with a matcher for the URL path prefix. -// See Route.PathPrefix(). -func (r *Router) PathPrefix(tpl string) *Route { - return r.NewRoute().PathPrefix(tpl) -} - -// Queries registers a new route with a matcher for URL query values. -// See Route.Queries(). -func (r *Router) Queries(pairs ...string) *Route { - return r.NewRoute().Queries(pairs...) -} - -// Schemes registers a new route with a matcher for URL schemes. -// See Route.Schemes(). -func (r *Router) Schemes(schemes ...string) *Route { - return r.NewRoute().Schemes(schemes...) -} - -// BuildVars registers a new route with a custom function for modifying -// route variables before building a URL. -func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { - return r.NewRoute().BuildVarsFunc(f) -} - -// Walk walks the router and all its sub-routers, calling walkFn for each route -// in the tree. The routes are walked in the order they were added. Sub-routers -// are explored depth-first. -func (r *Router) Walk(walkFn WalkFunc) error { - return r.walk(walkFn, []*Route{}) -} - -// SkipRouter is used as a return value from WalkFuncs to indicate that the -// router that walk is about to descend down to should be skipped. -var SkipRouter = errors.New("skip this router") - -// WalkFunc is the type of the function called for each route visited by Walk. -// At every invocation, it is given the current route, and the current router, -// and a list of ancestor routes that lead to the current route. -type WalkFunc func(route *Route, router *Router, ancestors []*Route) error - -func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { - for _, t := range r.routes { - if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" { - continue - } - - err := walkFn(t, r, ancestors) - if err == SkipRouter { - continue - } - for _, sr := range t.matchers { - if h, ok := sr.(*Router); ok { - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - } - } - if h, ok := t.handler.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - return nil -} - -// ---------------------------------------------------------------------------- -// Context -// ---------------------------------------------------------------------------- - -// RouteMatch stores information about a matched route. -type RouteMatch struct { - Route *Route - Handler http.Handler - Vars map[string]string -} - -type contextKey int - -const ( - varsKey contextKey = iota - routeKey -) - -// Vars returns the route variables for the current request, if any. -func Vars(r *http.Request) map[string]string { - if rv := context.Get(r, varsKey); rv != nil { - return rv.(map[string]string) - } - return nil -} - -// CurrentRoute returns the matched route for the current request, if any. -// This only works when called inside the handler of the matched route -// because the matched route is stored in the request context which is cleared -// after the handler returns, unless the KeepContext option is set on the -// Router. -func CurrentRoute(r *http.Request) *Route { - if rv := context.Get(r, routeKey); rv != nil { - return rv.(*Route) - } - return nil -} - -func setVars(r *http.Request, val interface{}) { - if val != nil { - context.Set(r, varsKey, val) - } -} - -func setCurrentRoute(r *http.Request, val interface{}) { - if val != nil { - context.Set(r, routeKey, val) - } -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -// cleanPath returns the canonical path for p, eliminating . and .. elements. -// Borrowed from the net/http package. -func cleanPath(p string) string { - if p == "" { - return "/" - } - if p[0] != '/' { - p = "/" + p - } - np := path.Clean(p) - // path.Clean removes trailing slash except for root; - // put the trailing slash back if necessary. - if p[len(p)-1] == '/' && np != "/" { - np += "/" - } - return np -} - -// uniqueVars returns an error if two slices contain duplicated strings. -func uniqueVars(s1, s2 []string) error { - for _, v1 := range s1 { - for _, v2 := range s2 { - if v1 == v2 { - return fmt.Errorf("mux: duplicated route variable %q", v2) - } - } - } - return nil -} - -// checkPairs returns the count of strings passed in, and an error if -// the count is not an even number. -func checkPairs(pairs ...string) (int, error) { - length := len(pairs) - if length%2 != 0 { - return length, fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - } - return length, nil -} - -// mapFromPairsToString converts variadic string parameters to a -// string to string map. -func mapFromPairsToString(pairs ...string) (map[string]string, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]string, length/2) - for i := 0; i < length; i += 2 { - m[pairs[i]] = pairs[i+1] - } - return m, nil -} - -// mapFromPairsToRegex converts variadic string paramers to a -// string to regex map. -func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]*regexp.Regexp, length/2) - for i := 0; i < length; i += 2 { - regex, err := regexp.Compile(pairs[i+1]) - if err != nil { - return nil, err - } - m[pairs[i]] = regex - } - return m, nil -} - -// matchInArray returns true if the given string value is in the array. -func matchInArray(arr []string, value string) bool { - for _, v := range arr { - if v == value { - return true - } - } - return false -} - -// matchMapWithString returns true if the given key/value pairs exist in a given map. -func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != "" { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v == value { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against -// the given regex -func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != nil { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v.MatchString(value) { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go deleted file mode 100644 index 06728dd54..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package mux - -import ( - "bytes" - "fmt" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" -) - -// newRouteRegexp parses a route template and returns a routeRegexp, -// used to match a host, a path or a query string. -// -// It will extract named variables, assemble a regexp to be matched, create -// a "reverse" template to build URLs and compile regexps to validate variable -// values used in URL building. -// -// Previously we accepted only Python-like identifiers for variable -// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that -// name and pattern can't be empty, and names can't contain a colon. -func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) { - // Check if it is well-formed. - idxs, errBraces := braceIndices(tpl) - if errBraces != nil { - return nil, errBraces - } - // Backup the original. - template := tpl - // Now let's parse it. - defaultPattern := "[^/]+" - if matchQuery { - defaultPattern = "[^?&]*" - } else if matchHost { - defaultPattern = "[^.]+" - matchPrefix = false - } - // Only match strict slash if not matching - if matchPrefix || matchHost || matchQuery { - strictSlash = false - } - // Set a flag for strictSlash. - endSlash := false - if strictSlash && strings.HasSuffix(tpl, "/") { - tpl = tpl[:len(tpl)-1] - endSlash = true - } - varsN := make([]string, len(idxs)/2) - varsR := make([]*regexp.Regexp, len(idxs)/2) - pattern := bytes.NewBufferString("") - pattern.WriteByte('^') - reverse := bytes.NewBufferString("") - var end int - var err error - for i := 0; i < len(idxs); i += 2 { - // Set all values we are interested in. - raw := tpl[end:idxs[i]] - end = idxs[i+1] - parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) - name := parts[0] - patt := defaultPattern - if len(parts) == 2 { - patt = parts[1] - } - // Name or pattern can't be empty. - if name == "" || patt == "" { - return nil, fmt.Errorf("mux: missing name or pattern in %q", - tpl[idxs[i]:end]) - } - // Build the regexp pattern. - varIdx := i / 2 - fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(varIdx), patt) - // Build the reverse template. - fmt.Fprintf(reverse, "%s%%s", raw) - - // Append variable name and compiled pattern. - varsN[varIdx] = name - varsR[varIdx], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) - if err != nil { - return nil, err - } - } - // Add the remaining. - raw := tpl[end:] - pattern.WriteString(regexp.QuoteMeta(raw)) - if strictSlash { - pattern.WriteString("[/]?") - } - if matchQuery { - // Add the default pattern if the query value is empty - if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { - pattern.WriteString(defaultPattern) - } - } - if !matchPrefix { - pattern.WriteByte('$') - } - reverse.WriteString(raw) - if endSlash { - reverse.WriteByte('/') - } - // Compile full regexp. - reg, errCompile := regexp.Compile(pattern.String()) - if errCompile != nil { - return nil, errCompile - } - // Done! - return &routeRegexp{ - template: template, - matchHost: matchHost, - matchQuery: matchQuery, - strictSlash: strictSlash, - regexp: reg, - reverse: reverse.String(), - varsN: varsN, - varsR: varsR, - }, nil -} - -// routeRegexp stores a regexp to match a host or path and information to -// collect and validate route variables. -type routeRegexp struct { - // The unmodified template. - template string - // True for host match, false for path or query string match. - matchHost bool - // True for query string match, false for path and host match. - matchQuery bool - // The strictSlash value defined on the route, but disabled if PathPrefix was used. - strictSlash bool - // Expanded regexp. - regexp *regexp.Regexp - // Reverse template. - reverse string - // Variable names. - varsN []string - // Variable regexps (validators). - varsR []*regexp.Regexp -} - -// Match matches the regexp against the URL host or path. -func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { - if !r.matchHost { - if r.matchQuery { - return r.matchQueryString(req) - } else { - return r.regexp.MatchString(req.URL.Path) - } - } - return r.regexp.MatchString(getHost(req)) -} - -// url builds a URL part using the given values. -func (r *routeRegexp) url(values map[string]string) (string, error) { - urlValues := make([]interface{}, len(r.varsN)) - for k, v := range r.varsN { - value, ok := values[v] - if !ok { - return "", fmt.Errorf("mux: missing route variable %q", v) - } - urlValues[k] = value - } - rv := fmt.Sprintf(r.reverse, urlValues...) - if !r.regexp.MatchString(rv) { - // The URL is checked against the full regexp, instead of checking - // individual variables. This is faster but to provide a good error - // message, we check individual regexps if the URL doesn't match. - for k, v := range r.varsN { - if !r.varsR[k].MatchString(values[v]) { - return "", fmt.Errorf( - "mux: variable %q doesn't match, expected %q", values[v], - r.varsR[k].String()) - } - } - } - return rv, nil -} - -// getUrlQuery returns a single query parameter from a request URL. -// For a URL with foo=bar&baz=ding, we return only the relevant key -// value pair for the routeRegexp. -func (r *routeRegexp) getUrlQuery(req *http.Request) string { - if !r.matchQuery { - return "" - } - templateKey := strings.SplitN(r.template, "=", 2)[0] - for key, vals := range req.URL.Query() { - if key == templateKey && len(vals) > 0 { - return key + "=" + vals[0] - } - } - return "" -} - -func (r *routeRegexp) matchQueryString(req *http.Request) bool { - return r.regexp.MatchString(r.getUrlQuery(req)) -} - -// braceIndices returns the first level curly brace indices from a string. -// It returns an error in case of unbalanced braces. -func braceIndices(s string) ([]int, error) { - var level, idx int - idxs := make([]int, 0) - for i := 0; i < len(s); i++ { - switch s[i] { - case '{': - if level++; level == 1 { - idx = i - } - case '}': - if level--; level == 0 { - idxs = append(idxs, idx, i+1) - } else if level < 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - } - } - if level != 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - return idxs, nil -} - -// varGroupName builds a capturing group name for the indexed variable. -func varGroupName(idx int) string { - return "v" + strconv.Itoa(idx) -} - -// ---------------------------------------------------------------------------- -// routeRegexpGroup -// ---------------------------------------------------------------------------- - -// routeRegexpGroup groups the route matchers that carry variables. -type routeRegexpGroup struct { - host *routeRegexp - path *routeRegexp - queries []*routeRegexp -} - -// setMatch extracts the variables from the URL once a route matches. -func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { - // Store host variables. - if v.host != nil { - hostVars := v.host.regexp.FindStringSubmatch(getHost(req)) - if hostVars != nil { - subexpNames := v.host.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[v.host.varsN[varName]] = hostVars[i+1] - varName++ - } - } - } - } - // Store path variables. - if v.path != nil { - pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path) - if pathVars != nil { - subexpNames := v.path.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[v.path.varsN[varName]] = pathVars[i+1] - varName++ - } - } - // Check if we should redirect. - if v.path.strictSlash { - p1 := strings.HasSuffix(req.URL.Path, "/") - p2 := strings.HasSuffix(v.path.template, "/") - if p1 != p2 { - u, _ := url.Parse(req.URL.String()) - if p1 { - u.Path = u.Path[:len(u.Path)-1] - } else { - u.Path += "/" - } - m.Handler = http.RedirectHandler(u.String(), 301) - } - } - } - } - // Store query string variables. - for _, q := range v.queries { - queryVars := q.regexp.FindStringSubmatch(q.getUrlQuery(req)) - if queryVars != nil { - subexpNames := q.regexp.SubexpNames() - varName := 0 - for i, name := range subexpNames[1:] { - if name != "" && name == varGroupName(varName) { - m.Vars[q.varsN[varName]] = queryVars[i+1] - varName++ - } - } - } - } -} - -// getHost tries its best to return the request host. -func getHost(r *http.Request) string { - if r.URL.IsAbs() { - return r.URL.Host - } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go deleted file mode 100644 index 913432c1c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package mux - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "regexp" - "strings" -) - -// Route stores information to match a request and build URLs. -type Route struct { - // Parent where the route was registered (a Router). - parent parentRoute - // Request handler for the route. - handler http.Handler - // List of matchers. - matchers []matcher - // Manager for the variables from host and path. - regexp *routeRegexpGroup - // If true, when the path pattern is "/path/", accessing "/path" will - // redirect to the former and vice versa. - strictSlash bool - // If true, this route never matches: it is only used to build URLs. - buildOnly bool - // The name used to build URLs. - name string - // Error resulted from building a route. - err error - - buildVarsFunc BuildVarsFunc -} - -// Match matches the route against the request. -func (r *Route) Match(req *http.Request, match *RouteMatch) bool { - if r.buildOnly || r.err != nil { - return false - } - // Match everything. - for _, m := range r.matchers { - if matched := m.Match(req, match); !matched { - return false - } - } - // Yay, we have a match. Let's collect some info about it. - if match.Route == nil { - match.Route = r - } - if match.Handler == nil { - match.Handler = r.handler - } - if match.Vars == nil { - match.Vars = make(map[string]string) - } - // Set variables. - if r.regexp != nil { - r.regexp.setMatch(req, match, r) - } - return true -} - -// ---------------------------------------------------------------------------- -// Route attributes -// ---------------------------------------------------------------------------- - -// GetError returns an error resulted from building the route, if any. -func (r *Route) GetError() error { - return r.err -} - -// BuildOnly sets the route to never match: it is only used to build URLs. -func (r *Route) BuildOnly() *Route { - r.buildOnly = true - return r -} - -// Handler -------------------------------------------------------------------- - -// Handler sets a handler for the route. -func (r *Route) Handler(handler http.Handler) *Route { - if r.err == nil { - r.handler = handler - } - return r -} - -// HandlerFunc sets a handler function for the route. -func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { - return r.Handler(http.HandlerFunc(f)) -} - -// GetHandler returns the handler for the route, if any. -func (r *Route) GetHandler() http.Handler { - return r.handler -} - -// Name ----------------------------------------------------------------------- - -// Name sets the name for the route, used to build URLs. -// If the name was registered already it will be overwritten. -func (r *Route) Name(name string) *Route { - if r.name != "" { - r.err = fmt.Errorf("mux: route already has name %q, can't set %q", - r.name, name) - } - if r.err == nil { - r.name = name - r.getNamedRoutes()[name] = r - } - return r -} - -// GetName returns the name for the route, if any. -func (r *Route) GetName() string { - return r.name -} - -// ---------------------------------------------------------------------------- -// Matchers -// ---------------------------------------------------------------------------- - -// matcher types try to match a request. -type matcher interface { - Match(*http.Request, *RouteMatch) bool -} - -// addMatcher adds a matcher to the route. -func (r *Route) addMatcher(m matcher) *Route { - if r.err == nil { - r.matchers = append(r.matchers, m) - } - return r -} - -// addRegexpMatcher adds a host or path matcher and builder to a route. -func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { - if r.err != nil { - return r.err - } - r.regexp = r.getRegexpGroup() - if !matchHost && !matchQuery { - if len(tpl) == 0 || tpl[0] != '/' { - return fmt.Errorf("mux: path must start with a slash, got %q", tpl) - } - if r.regexp.path != nil { - tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl - } - } - rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash) - if err != nil { - return err - } - for _, q := range r.regexp.queries { - if err = uniqueVars(rr.varsN, q.varsN); err != nil { - return err - } - } - if matchHost { - if r.regexp.path != nil { - if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { - return err - } - } - r.regexp.host = rr - } else { - if r.regexp.host != nil { - if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { - return err - } - } - if matchQuery { - r.regexp.queries = append(r.regexp.queries, rr) - } else { - r.regexp.path = rr - } - } - r.addMatcher(rr) - return nil -} - -// Headers -------------------------------------------------------------------- - -// headerMatcher matches the request against header values. -type headerMatcher map[string]string - -func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithString(m, r.Header, true) -} - -// Headers adds a matcher for request header values. -// It accepts a sequence of key/value pairs to be matched. For example: -// -// r := mux.NewRouter() -// r.Headers("Content-Type", "application/json", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both request header values match. -// If the value is an empty string, it will match any value if the key is set. -func (r *Route) Headers(pairs ...string) *Route { - if r.err == nil { - var headers map[string]string - headers, r.err = mapFromPairsToString(pairs...) - return r.addMatcher(headerMatcher(headers)) - } - return r -} - -// headerRegexMatcher matches the request against the route given a regex for the header -type headerRegexMatcher map[string]*regexp.Regexp - -func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithRegex(m, r.Header, true) -} - -// Regular expressions can be used with headers as well. -// It accepts a sequence of key/value pairs, where the value has regex support. For example -// r := mux.NewRouter() -// r.HeadersRegexp("Content-Type", "application/(text|json)", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both the request header matches both regular expressions. -// It the value is an empty string, it will match any value if the key is set. -func (r *Route) HeadersRegexp(pairs ...string) *Route { - if r.err == nil { - var headers map[string]*regexp.Regexp - headers, r.err = mapFromPairsToRegex(pairs...) - return r.addMatcher(headerRegexMatcher(headers)) - } - return r -} - -// Host ----------------------------------------------------------------------- - -// Host adds a matcher for the URL host. -// It accepts a template with zero or more URL variables enclosed by {}. -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next dot. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Host("www.example.com") -// r.Host("{subdomain}.domain.com") -// r.Host("{subdomain:[a-z]+}.domain.com") -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Host(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, true, false, false) - return r -} - -// MatcherFunc ---------------------------------------------------------------- - -// MatcherFunc is the function signature used by custom matchers. -type MatcherFunc func(*http.Request, *RouteMatch) bool - -func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { - return m(r, match) -} - -// MatcherFunc adds a custom function to be used as request matcher. -func (r *Route) MatcherFunc(f MatcherFunc) *Route { - return r.addMatcher(f) -} - -// Methods -------------------------------------------------------------------- - -// methodMatcher matches the request against HTTP methods. -type methodMatcher []string - -func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.Method) -} - -// Methods adds a matcher for HTTP methods. -// It accepts a sequence of one or more methods to be matched, e.g.: -// "GET", "POST", "PUT". -func (r *Route) Methods(methods ...string) *Route { - for k, v := range methods { - methods[k] = strings.ToUpper(v) - } - return r.addMatcher(methodMatcher(methods)) -} - -// Path ----------------------------------------------------------------------- - -// Path adds a matcher for the URL path. -// It accepts a template with zero or more URL variables enclosed by {}. The -// template must start with a "/". -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Path("/products/").Handler(ProductsHandler) -// r.Path("/products/{key}").Handler(ProductsHandler) -// r.Path("/articles/{category}/{id:[0-9]+}"). -// Handler(ArticleHandler) -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Path(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, false, false) - return r -} - -// PathPrefix ----------------------------------------------------------------- - -// PathPrefix adds a matcher for the URL path prefix. This matches if the given -// template is a prefix of the full URL path. See Route.Path() for details on -// the tpl argument. -// -// Note that it does not treat slashes specially ("/foobar/" will be matched by -// the prefix "/foo") so you may want to use a trailing slash here. -// -// Also note that the setting of Router.StrictSlash() has no effect on routes -// with a PathPrefix matcher. -func (r *Route) PathPrefix(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, true, false) - return r -} - -// Query ---------------------------------------------------------------------- - -// Queries adds a matcher for URL query values. -// It accepts a sequence of key/value pairs. Values may define variables. -// For example: -// -// r := mux.NewRouter() -// r.Queries("foo", "bar", "id", "{id:[0-9]+}") -// -// The above route will only match if the URL contains the defined queries -// values, e.g.: ?foo=bar&id=42. -// -// It the value is an empty string, it will match any value if the key is set. -// -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -func (r *Route) Queries(pairs ...string) *Route { - length := len(pairs) - if length%2 != 0 { - r.err = fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - return nil - } - for i := 0; i < length; i += 2 { - if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { - return r - } - } - - return r -} - -// Schemes -------------------------------------------------------------------- - -// schemeMatcher matches the request against URL schemes. -type schemeMatcher []string - -func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.URL.Scheme) -} - -// Schemes adds a matcher for URL schemes. -// It accepts a sequence of schemes to be matched, e.g.: "http", "https". -func (r *Route) Schemes(schemes ...string) *Route { - for k, v := range schemes { - schemes[k] = strings.ToLower(v) - } - return r.addMatcher(schemeMatcher(schemes)) -} - -// BuildVarsFunc -------------------------------------------------------------- - -// BuildVarsFunc is the function signature used by custom build variable -// functions (which can modify route variables before a route's URL is built). -type BuildVarsFunc func(map[string]string) map[string]string - -// BuildVarsFunc adds a custom function to be used to modify build variables -// before a route's URL is built. -func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { - r.buildVarsFunc = f - return r -} - -// Subrouter ------------------------------------------------------------------ - -// Subrouter creates a subrouter for the route. -// -// It will test the inner routes only if the parent route matched. For example: -// -// r := mux.NewRouter() -// s := r.Host("www.example.com").Subrouter() -// s.HandleFunc("/products/", ProductsHandler) -// s.HandleFunc("/products/{key}", ProductHandler) -// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -// -// Here, the routes registered in the subrouter won't be tested if the host -// doesn't match. -func (r *Route) Subrouter() *Router { - router := &Router{parent: r, strictSlash: r.strictSlash} - r.addMatcher(router) - return router -} - -// ---------------------------------------------------------------------------- -// URL building -// ---------------------------------------------------------------------------- - -// URL builds a URL for the route. -// -// It accepts a sequence of key/value pairs for the route variables. For -// example, given this route: -// -// r := mux.NewRouter() -// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// ...a URL for it can be built using: -// -// url, err := r.Get("article").URL("category", "technology", "id", "42") -// -// ...which will return an url.URL with the following path: -// -// "/articles/technology/42" -// -// This also works for host variables: -// -// r := mux.NewRouter() -// r.Host("{subdomain}.domain.com"). -// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// // url.String() will be "http://news.domain.com/articles/technology/42" -// url, err := r.Get("article").URL("subdomain", "news", -// "category", "technology", -// "id", "42") -// -// All variables defined in the route are required, and their values must -// conform to the corresponding patterns. -func (r *Route) URL(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil { - return nil, errors.New("mux: route doesn't have a host or path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - var scheme, host, path string - if r.regexp.host != nil { - // Set a default scheme. - scheme = "http" - if host, err = r.regexp.host.url(values); err != nil { - return nil, err - } - } - if r.regexp.path != nil { - if path, err = r.regexp.path.url(values); err != nil { - return nil, err - } - } - return &url.URL{ - Scheme: scheme, - Host: host, - Path: path, - }, nil -} - -// URLHost builds the host part of the URL for a route. See Route.URL(). -// -// The route must have a host defined. -func (r *Route) URLHost(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.host == nil { - return nil, errors.New("mux: route doesn't have a host") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - host, err := r.regexp.host.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Scheme: "http", - Host: host, - }, nil -} - -// URLPath builds the path part of the URL for a route. See Route.URL(). -// -// The route must have a path defined. -func (r *Route) URLPath(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.path == nil { - return nil, errors.New("mux: route doesn't have a path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - path, err := r.regexp.path.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Path: path, - }, nil -} - -// prepareVars converts the route variable pairs into a map. If the route has a -// BuildVarsFunc, it is invoked. -func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { - m, err := mapFromPairsToString(pairs...) - if err != nil { - return nil, err - } - return r.buildVars(m), nil -} - -func (r *Route) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - if r.buildVarsFunc != nil { - m = r.buildVarsFunc(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// parentRoute allows routes to know about parent host and path definitions. -type parentRoute interface { - getNamedRoutes() map[string]*Route - getRegexpGroup() *routeRegexpGroup - buildVars(map[string]string) map[string]string -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Route) getNamedRoutes() map[string]*Route { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - return r.parent.getNamedRoutes() -} - -// getRegexpGroup returns regexp definitions from this route. -func (r *Route) getRegexpGroup() *routeRegexpGroup { - if r.regexp == nil { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - regexp := r.parent.getRegexpGroup() - if regexp == nil { - r.regexp = new(routeRegexpGroup) - } else { - // Copy. - r.regexp = &routeRegexpGroup{ - host: regexp.host, - path: regexp.path, - queries: regexp.queries, - } - } - } - return r.regexp -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/LICENSE b/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/README.md b/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/README.md deleted file mode 100644 index 036e5313f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# cleanhttp - -Functions for accessing "clean" Go http.Client values - -------------- - -The Go standard library contains a default `http.Client` called -`http.DefaultClient`. It is a common idiom in Go code to start with -`http.DefaultClient` and tweak it as necessary, and in fact, this is -encouraged; from the `http` package documentation: - -> The Client's Transport typically has internal state (cached TCP connections), -so Clients should be reused instead of created as needed. Clients are safe for -concurrent use by multiple goroutines. - -Unfortunately, this is a shared value, and it is not uncommon for libraries to -assume that they are free to modify it at will. With enough dependencies, it -can be very easy to encounter strange problems and race conditions due to -manipulation of this shared value across libraries and goroutines (clients are -safe for concurrent use, but writing values to the client struct itself is not -protected). - -Making things worse is the fact that a bare `http.Client` will use a default -`http.Transport` called `http.DefaultTransport`, which is another global value -that behaves the same way. So it is not simply enough to replace -`http.DefaultClient` with `&http.Client{}`. - -This repository provides some simple functions to get a "clean" `http.Client` --- one that uses the same default values as the Go standard library, but -returns a client that does not share any state with other clients. diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/cleanhttp.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/cleanhttp.go deleted file mode 100644 index c692e23f4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/cleanhttp.go +++ /dev/null @@ -1,40 +0,0 @@ -package cleanhttp - -import ( - "net" - "net/http" - "runtime" - "time" -) - -// DefaultTransport returns a new http.Transport with the same default values -// as http.DefaultTransport -func DefaultTransport() *http.Transport { - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - } - SetTransportFinalizer(transport) - return transport -} - -// DefaultClient returns a new http.Client with the same default values as -// http.Client, but with a non-shared Transport -func DefaultClient() *http.Client { - return &http.Client{ - Transport: DefaultTransport(), - } -} - -// SetTransportFinalizer sets a finalizer on the transport to ensure that -// idle connections are closed prior to garbage collection; otherwise -// these may leak -func SetTransportFinalizer(transport *http.Transport) { - runtime.SetFinalizer(&transport, func(t **http.Transport) { - (*t).CloseIdleConnections() - }) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS b/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS deleted file mode 100644 index edbe20066..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS +++ /dev/null @@ -1,2 +0,0 @@ -Tianon Gravi (@tianon) -Aleksa Sarai (@cyphar) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup.go deleted file mode 100644 index 6f8a982ff..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup.go +++ /dev/null @@ -1,108 +0,0 @@ -package user - -import ( - "errors" - "fmt" - "syscall" -) - -var ( - // The current operating system does not provide the required data for user lookups. - ErrUnsupported = errors.New("user lookup: operating system does not provide passwd-formatted data") -) - -func lookupUser(filter func(u User) bool) (User, error) { - // Get operating system-specific passwd reader-closer. - passwd, err := GetPasswd() - if err != nil { - return User{}, err - } - defer passwd.Close() - - // Get the users. - users, err := ParsePasswdFilter(passwd, filter) - if err != nil { - return User{}, err - } - - // No user entries found. - if len(users) == 0 { - return User{}, fmt.Errorf("no matching entries in passwd file") - } - - // Assume the first entry is the "correct" one. - return users[0], nil -} - -// CurrentUser looks up the current user by their user id in /etc/passwd. If the -// user cannot be found (or there is no /etc/passwd file on the filesystem), -// then CurrentUser returns an error. -func CurrentUser() (User, error) { - return LookupUid(syscall.Getuid()) -} - -// LookupUser looks up a user by their username in /etc/passwd. If the user -// cannot be found (or there is no /etc/passwd file on the filesystem), then -// LookupUser returns an error. -func LookupUser(username string) (User, error) { - return lookupUser(func(u User) bool { - return u.Name == username - }) -} - -// LookupUid looks up a user by their user id in /etc/passwd. If the user cannot -// be found (or there is no /etc/passwd file on the filesystem), then LookupId -// returns an error. -func LookupUid(uid int) (User, error) { - return lookupUser(func(u User) bool { - return u.Uid == uid - }) -} - -func lookupGroup(filter func(g Group) bool) (Group, error) { - // Get operating system-specific group reader-closer. - group, err := GetGroup() - if err != nil { - return Group{}, err - } - defer group.Close() - - // Get the users. - groups, err := ParseGroupFilter(group, filter) - if err != nil { - return Group{}, err - } - - // No user entries found. - if len(groups) == 0 { - return Group{}, fmt.Errorf("no matching entries in group file") - } - - // Assume the first entry is the "correct" one. - return groups[0], nil -} - -// CurrentGroup looks up the current user's group by their primary group id's -// entry in /etc/passwd. If the group cannot be found (or there is no -// /etc/group file on the filesystem), then CurrentGroup returns an error. -func CurrentGroup() (Group, error) { - return LookupGid(syscall.Getgid()) -} - -// LookupGroup looks up a group by its name in /etc/group. If the group cannot -// be found (or there is no /etc/group file on the filesystem), then LookupGroup -// returns an error. -func LookupGroup(groupname string) (Group, error) { - return lookupGroup(func(g Group) bool { - return g.Name == groupname - }) -} - -// LookupGid looks up a group by its group id in /etc/group. If the group cannot -// be found (or there is no /etc/group file on the filesystem), then LookupGid -// returns an error. -func LookupGid(gid int) (Group, error) { - return lookupGroup(func(g Group) bool { - return g.Gid == gid - }) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go deleted file mode 100644 index 758b734c2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package user - -import ( - "io" - "os" -) - -// Unix-specific path to the passwd and group formatted files. -const ( - unixPasswdPath = "/etc/passwd" - unixGroupPath = "/etc/group" -) - -func GetPasswdPath() (string, error) { - return unixPasswdPath, nil -} - -func GetPasswd() (io.ReadCloser, error) { - return os.Open(unixPasswdPath) -} - -func GetGroupPath() (string, error) { - return unixGroupPath, nil -} - -func GetGroup() (io.ReadCloser, error) { - return os.Open(unixGroupPath) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go deleted file mode 100644 index 721794887..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris - -package user - -import "io" - -func GetPasswdPath() (string, error) { - return "", ErrUnsupported -} - -func GetPasswd() (io.ReadCloser, error) { - return nil, ErrUnsupported -} - -func GetGroupPath() (string, error) { - return "", ErrUnsupported -} - -func GetGroup() (io.ReadCloser, error) { - return nil, ErrUnsupported -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user.go b/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user.go deleted file mode 100644 index e6375ea4d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user.go +++ /dev/null @@ -1,418 +0,0 @@ -package user - -import ( - "bufio" - "fmt" - "io" - "os" - "strconv" - "strings" -) - -const ( - minId = 0 - maxId = 1<<31 - 1 //for 32-bit systems compatibility -) - -var ( - ErrRange = fmt.Errorf("Uids and gids must be in range %d-%d", minId, maxId) -) - -type User struct { - Name string - Pass string - Uid int - Gid int - Gecos string - Home string - Shell string -} - -type Group struct { - Name string - Pass string - Gid int - List []string -} - -func parseLine(line string, v ...interface{}) { - if line == "" { - return - } - - parts := strings.Split(line, ":") - for i, p := range parts { - if len(v) <= i { - // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files - break - } - - switch e := v[i].(type) { - case *string: - // "root", "adm", "/bin/bash" - *e = p - case *int: - // "0", "4", "1000" - // ignore string to int conversion errors, for great "tolerance" of naughty configuration files - *e, _ = strconv.Atoi(p) - case *[]string: - // "", "root", "root,adm,daemon" - if p != "" { - *e = strings.Split(p, ",") - } else { - *e = []string{} - } - default: - // panic, because this is a programming/logic error, not a runtime one - panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!") - } - } -} - -func ParsePasswdFile(path string) ([]User, error) { - passwd, err := os.Open(path) - if err != nil { - return nil, err - } - defer passwd.Close() - return ParsePasswd(passwd) -} - -func ParsePasswd(passwd io.Reader) ([]User, error) { - return ParsePasswdFilter(passwd, nil) -} - -func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) { - passwd, err := os.Open(path) - if err != nil { - return nil, err - } - defer passwd.Close() - return ParsePasswdFilter(passwd, filter) -} - -func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) { - if r == nil { - return nil, fmt.Errorf("nil source for passwd-formatted data") - } - - var ( - s = bufio.NewScanner(r) - out = []User{} - ) - - for s.Scan() { - if err := s.Err(); err != nil { - return nil, err - } - - text := strings.TrimSpace(s.Text()) - if text == "" { - continue - } - - // see: man 5 passwd - // name:password:UID:GID:GECOS:directory:shell - // Name:Pass:Uid:Gid:Gecos:Home:Shell - // root:x:0:0:root:/root:/bin/bash - // adm:x:3:4:adm:/var/adm:/bin/false - p := User{} - parseLine( - text, - &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell, - ) - - if filter == nil || filter(p) { - out = append(out, p) - } - } - - return out, nil -} - -func ParseGroupFile(path string) ([]Group, error) { - group, err := os.Open(path) - if err != nil { - return nil, err - } - defer group.Close() - return ParseGroup(group) -} - -func ParseGroup(group io.Reader) ([]Group, error) { - return ParseGroupFilter(group, nil) -} - -func ParseGroupFileFilter(path string, filter func(Group) bool) ([]Group, error) { - group, err := os.Open(path) - if err != nil { - return nil, err - } - defer group.Close() - return ParseGroupFilter(group, filter) -} - -func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) { - if r == nil { - return nil, fmt.Errorf("nil source for group-formatted data") - } - - var ( - s = bufio.NewScanner(r) - out = []Group{} - ) - - for s.Scan() { - if err := s.Err(); err != nil { - return nil, err - } - - text := s.Text() - if text == "" { - continue - } - - // see: man 5 group - // group_name:password:GID:user_list - // Name:Pass:Gid:List - // root:x:0:root - // adm:x:4:root,adm,daemon - p := Group{} - parseLine( - text, - &p.Name, &p.Pass, &p.Gid, &p.List, - ) - - if filter == nil || filter(p) { - out = append(out, p) - } - } - - return out, nil -} - -type ExecUser struct { - Uid, Gid int - Sgids []int - Home string -} - -// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the -// given file paths and uses that data as the arguments to GetExecUser. If the -// files cannot be opened for any reason, the error is ignored and a nil -// io.Reader is passed instead. -func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) { - passwd, err := os.Open(passwdPath) - if err != nil { - passwd = nil - } else { - defer passwd.Close() - } - - group, err := os.Open(groupPath) - if err != nil { - group = nil - } else { - defer group.Close() - } - - return GetExecUser(userSpec, defaults, passwd, group) -} - -// GetExecUser parses a user specification string (using the passwd and group -// readers as sources for /etc/passwd and /etc/group data, respectively). In -// the case of blank fields or missing data from the sources, the values in -// defaults is used. -// -// GetExecUser will return an error if a user or group literal could not be -// found in any entry in passwd and group respectively. -// -// Examples of valid user specifications are: -// * "" -// * "user" -// * "uid" -// * "user:group" -// * "uid:gid -// * "user:gid" -// * "uid:group" -func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) { - var ( - userArg, groupArg string - name string - ) - - if defaults == nil { - defaults = new(ExecUser) - } - - // Copy over defaults. - user := &ExecUser{ - Uid: defaults.Uid, - Gid: defaults.Gid, - Sgids: defaults.Sgids, - Home: defaults.Home, - } - - // Sgids slice *cannot* be nil. - if user.Sgids == nil { - user.Sgids = []int{} - } - - // allow for userArg to have either "user" syntax, or optionally "user:group" syntax - parseLine(userSpec, &userArg, &groupArg) - - users, err := ParsePasswdFilter(passwd, func(u User) bool { - if userArg == "" { - return u.Uid == user.Uid - } - return u.Name == userArg || strconv.Itoa(u.Uid) == userArg - }) - if err != nil && passwd != nil { - if userArg == "" { - userArg = strconv.Itoa(user.Uid) - } - return nil, fmt.Errorf("Unable to find user %v: %v", userArg, err) - } - - haveUser := users != nil && len(users) > 0 - if haveUser { - // if we found any user entries that matched our filter, let's take the first one as "correct" - name = users[0].Name - user.Uid = users[0].Uid - user.Gid = users[0].Gid - user.Home = users[0].Home - } else if userArg != "" { - // we asked for a user but didn't find them... let's check to see if we wanted a numeric user - user.Uid, err = strconv.Atoi(userArg) - if err != nil { - // not numeric - we have to bail - return nil, fmt.Errorf("Unable to find user %v", userArg) - } - - // Must be inside valid uid range. - if user.Uid < minId || user.Uid > maxId { - return nil, ErrRange - } - - // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit - } - - if groupArg != "" || name != "" { - groups, err := ParseGroupFilter(group, func(g Group) bool { - // Explicit group format takes precedence. - if groupArg != "" { - return g.Name == groupArg || strconv.Itoa(g.Gid) == groupArg - } - - // Check if user is a member. - for _, u := range g.List { - if u == name { - return true - } - } - - return false - }) - if err != nil && group != nil { - return nil, fmt.Errorf("Unable to find groups for user %v: %v", users[0].Name, err) - } - - haveGroup := groups != nil && len(groups) > 0 - if groupArg != "" { - if haveGroup { - // if we found any group entries that matched our filter, let's take the first one as "correct" - user.Gid = groups[0].Gid - } else { - // we asked for a group but didn't find id... let's check to see if we wanted a numeric group - user.Gid, err = strconv.Atoi(groupArg) - if err != nil { - // not numeric - we have to bail - return nil, fmt.Errorf("Unable to find group %v", groupArg) - } - - // Ensure gid is inside gid range. - if user.Gid < minId || user.Gid > maxId { - return nil, ErrRange - } - - // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit - } - } else if haveGroup { - // If implicit group format, fill supplementary gids. - user.Sgids = make([]int, len(groups)) - for i, group := range groups { - user.Sgids[i] = group.Gid - } - } - } - - return user, nil -} - -// GetAdditionalGroups looks up a list of groups by name or group id -// against the given /etc/group formatted data. If a group name cannot -// be found, an error will be returned. If a group id cannot be found, -// or the given group data is nil, the id will be returned as-is -// provided it is in the legal range. -func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) { - var groups = []Group{} - if group != nil { - var err error - groups, err = ParseGroupFilter(group, func(g Group) bool { - for _, ag := range additionalGroups { - if g.Name == ag || strconv.Itoa(g.Gid) == ag { - return true - } - } - return false - }) - if err != nil { - return nil, fmt.Errorf("Unable to find additional groups %v: %v", additionalGroups, err) - } - } - - gidMap := make(map[int]struct{}) - for _, ag := range additionalGroups { - var found bool - for _, g := range groups { - // if we found a matched group either by name or gid, take the - // first matched as correct - if g.Name == ag || strconv.Itoa(g.Gid) == ag { - if _, ok := gidMap[g.Gid]; !ok { - gidMap[g.Gid] = struct{}{} - found = true - break - } - } - } - // we asked for a group but didn't find it. let's check to see - // if we wanted a numeric group - if !found { - gid, err := strconv.Atoi(ag) - if err != nil { - return nil, fmt.Errorf("Unable to find group %s", ag) - } - // Ensure gid is inside gid range. - if gid < minId || gid > maxId { - return nil, ErrRange - } - gidMap[gid] = struct{}{} - } - } - gids := []int{} - for gid := range gidMap { - gids = append(gids, gid) - } - return gids, nil -} - -// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups -// that opens the groupPath given and gives it as an argument to -// GetAdditionalGroups. -func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { - group, err := os.Open(groupPath) - if err == nil { - defer group.Close() - } - return GetAdditionalGroups(additionalGroups, group) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context.go deleted file mode 100644 index dd138571f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context.go +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context // import "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out <-chan Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, c) - return c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - *cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm.s deleted file mode 100644 index 8ed2fdb94..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm.s +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -TEXT ·use(SB),NOSPLIT,$0 - RET diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_386.s deleted file mode 100644 index 8a7278319..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_386.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for 386, Darwin -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_amd64.s deleted file mode 100644 index 6321421f2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_amd64.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for AMD64, Darwin -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-104 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm.s deleted file mode 100644 index 333242d50..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm.s +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo -// +build arm,darwin - -#include "textflag.h" - -// -// System call support for ARM, Darwin -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - B syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - B syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - B syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - B syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - B syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_386.s deleted file mode 100644 index 7e55e0d31..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_386.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for 386, FreeBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-32 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-44 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-56 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-32 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-44 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_amd64.s deleted file mode 100644 index d5ed6726c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_amd64.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for AMD64, DragonFly -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-64 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-88 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-112 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-64 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-88 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_386.s deleted file mode 100644 index c9a0a2601..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_386.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for 386, FreeBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_arm.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_arm.s deleted file mode 100644 index 9227c875b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_arm.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for ARM, FreeBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - B syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - B syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - B syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - B syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - B syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_386.s deleted file mode 100644 index 4db290932..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_386.s +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System calls for 386, Linux -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - JMP syscall·Syscall6(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - JMP syscall·RawSyscall6(SB) - -TEXT ·socketcall(SB),NOSPLIT,$0-36 - JMP syscall·socketcall(SB) - -TEXT ·rawsocketcall(SB),NOSPLIT,$0-36 - JMP syscall·rawsocketcall(SB) - -TEXT ·seek(SB),NOSPLIT,$0-28 - JMP syscall·seek(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_amd64.s deleted file mode 100644 index 44e25c62f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_amd64.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System calls for AMD64, Linux -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - JMP syscall·Syscall6(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - JMP syscall·RawSyscall6(SB) - -TEXT ·gettimeofday(SB),NOSPLIT,$0-16 - JMP syscall·gettimeofday(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm.s deleted file mode 100644 index cf0b57465..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System calls for arm, Linux -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - B syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - B syscall·Syscall6(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - B syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - B syscall·RawSyscall6(SB) - -TEXT ·seek(SB),NOSPLIT,$0-32 - B syscall·seek(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm64.s deleted file mode 100644 index 4be9bfede..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm64.s +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux -// +build arm64 -// +build !gccgo - -#include "textflag.h" - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - B syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - B syscall·Syscall6(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - B syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - B syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_ppc64x.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_ppc64x.s deleted file mode 100644 index 8d231feb4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_ppc64x.s +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux -// +build ppc64 ppc64le -// +build !gccgo - -#include "textflag.h" - -// -// System calls for ppc64, Linux -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - BR syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - BR syscall·Syscall6(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - BR syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - BR syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_386.s deleted file mode 100644 index 48bdcd763..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_386.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for 386, NetBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_amd64.s deleted file mode 100644 index 2ede05c72..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_amd64.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for AMD64, NetBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-104 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_arm.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_arm.s deleted file mode 100644 index e8928571c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_arm.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for ARM, NetBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - B syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - B syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - B syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - B syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - B syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_386.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_386.s deleted file mode 100644 index 00576f3c8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_386.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for 386, OpenBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-28 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-40 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-52 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_amd64.s deleted file mode 100644 index 790ef77f8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_amd64.s +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System call support for AMD64, OpenBSD -// - -// Just jump to package syscall's implementation for all these functions. -// The runtime may know about them. - -TEXT ·Syscall(SB),NOSPLIT,$0-56 - JMP syscall·Syscall(SB) - -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - JMP syscall·Syscall6(SB) - -TEXT ·Syscall9(SB),NOSPLIT,$0-104 - JMP syscall·Syscall9(SB) - -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - JMP syscall·RawSyscall(SB) - -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - JMP syscall·RawSyscall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_solaris_amd64.s b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_solaris_amd64.s deleted file mode 100644 index 43ed17a05..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_solaris_amd64.s +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !gccgo - -#include "textflag.h" - -// -// System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go -// - -TEXT ·sysvicall6(SB),NOSPLIT,$0-64 - JMP syscall·sysvicall6(SB) - -TEXT ·rawSysvicall6(SB),NOSPLIT,$0-64 - JMP syscall·rawSysvicall6(SB) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/constants.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/constants.go deleted file mode 100644 index a96f0ebc2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/constants.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -const ( - R_OK = 0x4 - W_OK = 0x2 - X_OK = 0x1 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unix.go deleted file mode 100644 index 45e281a04..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unix.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -// Unix environment variables. - -package unix - -import "syscall" - -func Getenv(key string) (value string, found bool) { - return syscall.Getenv(key) -} - -func Setenv(key, value string) error { - return syscall.Setenv(key, value) -} - -func Clearenv() { - syscall.Clearenv() -} - -func Environ() []string { - return syscall.Environ() -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unset.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unset.go deleted file mode 100644 index 922226255..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unset.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.4 - -package unix - -import "syscall" - -func Unsetenv(key string) error { - // This was added in Go 1.4. - return syscall.Unsetenv(key) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock.go deleted file mode 100644 index ce67a5952..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build linux darwin freebsd openbsd netbsd dragonfly - -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd - -package unix - -import "unsafe" - -// fcntl64Syscall is usually SYS_FCNTL, but is overridden on 32-bit Linux -// systems by flock_linux_32bit.go to be SYS_FCNTL64. -var fcntl64Syscall uintptr = SYS_FCNTL - -// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. -func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { - _, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk))) - if errno == 0 { - return nil - } - return errno -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock_linux_32bit.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock_linux_32bit.go deleted file mode 100644 index 362831c3f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock_linux_32bit.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build linux,386 linux,arm - -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package unix - -func init() { - // On 32-bit Linux systems, the fcntl syscall that matches Go's - // Flock_t type is SYS_FCNTL64, not SYS_FCNTL. - fcntl64Syscall = SYS_FCNTL64 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo.go deleted file mode 100644 index 94c823212..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build gccgo - -package unix - -import "syscall" - -// We can't use the gc-syntax .s files for gccgo. On the plus side -// much of the functionality can be written directly in Go. - -//extern gccgoRealSyscall -func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr) - -func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - syscall.Entersyscall() - r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) - syscall.Exitsyscall() - return r, 0, syscall.Errno(errno) -} - -func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - syscall.Entersyscall() - r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) - syscall.Exitsyscall() - return r, 0, syscall.Errno(errno) -} - -func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) { - syscall.Entersyscall() - r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9) - syscall.Exitsyscall() - return r, 0, syscall.Errno(errno) -} - -func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) - return r, 0, syscall.Errno(errno) -} - -func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - r, errno := realSyscall(trap, a1, a2, a3, a4, a5, a6, 0, 0, 0) - return r, 0, syscall.Errno(errno) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_c.c b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_c.c deleted file mode 100644 index 07f6be039..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_c.c +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build gccgo - -#include -#include -#include - -#define _STRINGIFY2_(x) #x -#define _STRINGIFY_(x) _STRINGIFY2_(x) -#define GOSYM_PREFIX _STRINGIFY_(__USER_LABEL_PREFIX__) - -// Call syscall from C code because the gccgo support for calling from -// Go to C does not support varargs functions. - -struct ret { - uintptr_t r; - uintptr_t err; -}; - -struct ret -gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9) -{ - struct ret r; - - errno = 0; - r.r = syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9); - r.err = errno; - return r; -} - -// Define the use function in C so that it is not inlined. - -extern void use(void *) __asm__ (GOSYM_PREFIX GOPKGPATH ".use") __attribute__((noinline)); - -void -use(void *p __attribute__ ((unused))) -{ -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_linux_amd64.go deleted file mode 100644 index bffe1a77d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_linux_amd64.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build gccgo,linux,amd64 - -package unix - -import "syscall" - -//extern gettimeofday -func realGettimeofday(*Timeval, *byte) int32 - -func gettimeofday(tv *Timeval) (err syscall.Errno) { - r := realGettimeofday(tv, nil) - if r < 0 { - return syscall.GetErrno() - } - return 0 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkall.sh b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkall.sh deleted file mode 100755 index de95a4bbc..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkall.sh +++ /dev/null @@ -1,274 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# The unix package provides access to the raw system call -# interface of the underlying operating system. Porting Go to -# a new architecture/operating system combination requires -# some manual effort, though there are tools that automate -# much of the process. The auto-generated files have names -# beginning with z. -# -# This script runs or (given -n) prints suggested commands to generate z files -# for the current system. Running those commands is not automatic. -# This script is documentation more than anything else. -# -# * asm_${GOOS}_${GOARCH}.s -# -# This hand-written assembly file implements system call dispatch. -# There are three entry points: -# -# func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); -# func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr); -# func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr); -# -# The first and second are the standard ones; they differ only in -# how many arguments can be passed to the kernel. -# The third is for low-level use by the ForkExec wrapper; -# unlike the first two, it does not call into the scheduler to -# let it know that a system call is running. -# -# * syscall_${GOOS}.go -# -# This hand-written Go file implements system calls that need -# special handling and lists "//sys" comments giving prototypes -# for ones that can be auto-generated. Mksyscall reads those -# comments to generate the stubs. -# -# * syscall_${GOOS}_${GOARCH}.go -# -# Same as syscall_${GOOS}.go except that it contains code specific -# to ${GOOS} on one particular architecture. -# -# * types_${GOOS}.c -# -# This hand-written C file includes standard C headers and then -# creates typedef or enum names beginning with a dollar sign -# (use of $ in variable names is a gcc extension). The hardest -# part about preparing this file is figuring out which headers to -# include and which symbols need to be #defined to get the -# actual data structures that pass through to the kernel system calls. -# Some C libraries present alternate versions for binary compatibility -# and translate them on the way in and out of system calls, but -# there is almost always a #define that can get the real ones. -# See types_darwin.c and types_linux.c for examples. -# -# * zerror_${GOOS}_${GOARCH}.go -# -# This machine-generated file defines the system's error numbers, -# error strings, and signal numbers. The generator is "mkerrors.sh". -# Usually no arguments are needed, but mkerrors.sh will pass its -# arguments on to godefs. -# -# * zsyscall_${GOOS}_${GOARCH}.go -# -# Generated by mksyscall.pl; see syscall_${GOOS}.go above. -# -# * zsysnum_${GOOS}_${GOARCH}.go -# -# Generated by mksysnum_${GOOS}. -# -# * ztypes_${GOOS}_${GOARCH}.go -# -# Generated by godefs; see types_${GOOS}.c above. - -GOOSARCH="${GOOS}_${GOARCH}" - -# defaults -mksyscall="./mksyscall.pl" -mkerrors="./mkerrors.sh" -zerrors="zerrors_$GOOSARCH.go" -mksysctl="" -zsysctl="zsysctl_$GOOSARCH.go" -mksysnum= -mktypes= -run="sh" - -case "$1" in --syscalls) - for i in zsyscall*go - do - sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i - rm _$i - done - exit 0 - ;; --n) - run="cat" - shift -esac - -case "$#" in -0) - ;; -*) - echo 'usage: mkall.sh [-n]' 1>&2 - exit 2 -esac - -GOOSARCH_in=syscall_$GOOSARCH.go -case "$GOOSARCH" in -_* | *_ | _) - echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 - exit 1 - ;; -darwin_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_amd64) - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_arm) - mkerrors="$mkerrors" - mksysnum="./mksysnum_darwin.pl /usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -darwin_arm64) - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -dragonfly_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -dragonfly" - mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -dragonfly_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -dragonfly" - mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_amd64) - mkerrors="$mkerrors -m64" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -freebsd_arm) - mkerrors="$mkerrors" - mksyscall="./mksyscall.pl -l32 -arm" - mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" - # Let the type of C char be singed for making the bare syscall - # API consistent across over platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -linux_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32" - mksysnum="./mksysnum_linux.pl /usr/include/asm/unistd_32.h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -linux_amd64) - unistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1) - if [ "$unistd_h" = "" ]; then - echo >&2 cannot find unistd_64.h - exit 1 - fi - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_linux.pl $unistd_h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -linux_arm) - mkerrors="$mkerrors" - mksyscall="./mksyscall.pl -l32 -arm" - mksysnum="curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -linux_arm64) - unistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1) - if [ "$unistd_h" = "" ]; then - echo >&2 cannot find unistd_64.h - exit 1 - fi - mksysnum="./mksysnum_linux.pl $unistd_h" - # Let the type of C char be singed for making the bare syscall - # API consistent across over platforms. - mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" - ;; -linux_ppc64) - GOOSARCH_in=syscall_linux_ppc64x.go - unistd_h=/usr/include/asm/unistd.h - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_linux.pl $unistd_h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -linux_ppc64le) - GOOSARCH_in=syscall_linux_ppc64x.go - unistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h - mkerrors="$mkerrors -m64" - mksysnum="./mksysnum_linux.pl $unistd_h" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -netbsd" - mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -netbsd_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -netbsd" - mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -openbsd" - mksysctl="./mksysctl_openbsd.pl" - zsysctl="zsysctl_openbsd.go" - mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -openbsd_amd64) - mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -openbsd" - mksysctl="./mksysctl_openbsd.pl" - zsysctl="zsysctl_openbsd.go" - mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -solaris_amd64) - mksyscall="./mksyscall_solaris.pl" - mkerrors="$mkerrors -m64" - mksysnum= - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; -*) - echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 - exit 1 - ;; -esac - -( - if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi - case "$GOOS" in - *) - syscall_goos="syscall_$GOOS.go" - case "$GOOS" in - darwin | dragonfly | freebsd | netbsd | openbsd) - syscall_goos="syscall_bsd.go $syscall_goos" - ;; - esac - if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi - ;; - esac - if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi - if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi - if [ -n "$mktypes" ]; then - echo "echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go"; - echo "$mktypes types_$GOOS.go | gofmt >>ztypes_$GOOSARCH.go"; - fi -) | $run diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkerrors.sh b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkerrors.sh deleted file mode 100755 index c40d788c4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkerrors.sh +++ /dev/null @@ -1,476 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# Generate Go code listing errors and other #defined constant -# values (ENAMETOOLONG etc.), by asking the preprocessor -# about the definitions. - -unset LANG -export LC_ALL=C -export LC_CTYPE=C - -if test -z "$GOARCH" -o -z "$GOOS"; then - echo 1>&2 "GOARCH or GOOS not defined in environment" - exit 1 -fi - -CC=${CC:-cc} - -if [[ "$GOOS" -eq "solaris" ]]; then - # Assumes GNU versions of utilities in PATH. - export PATH=/usr/gnu/bin:$PATH -fi - -uname=$(uname) - -includes_Darwin=' -#define _DARWIN_C_SOURCE -#define KERNEL -#define _DARWIN_USE_64_BIT_INODE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - -includes_DragonFly=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - -includes_FreeBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if __FreeBSD__ >= 10 -#define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 -#undef SIOCAIFADDR -#define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data -#undef SIOCSIFPHYADDR -#define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data -#endif -' - -includes_Linux=' -#define _LARGEFILE_SOURCE -#define _LARGEFILE64_SOURCE -#ifndef __LP64__ -#define _FILE_OFFSET_BITS 64 -#endif -#define _GNU_SOURCE - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef MSG_FASTOPEN -#define MSG_FASTOPEN 0x20000000 -#endif - -#ifndef PTRACE_GETREGS -#define PTRACE_GETREGS 0xc -#endif - -#ifndef PTRACE_SETREGS -#define PTRACE_SETREGS 0xd -#endif -' - -includes_NetBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Needed since refers to it... -#define schedppq 1 -' - -includes_OpenBSD=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// We keep some constants not supported in OpenBSD 5.5 and beyond for -// the promise of compatibility. -#define EMUL_ENABLED 0x1 -#define EMUL_NATIVE 0x2 -#define IPV6_FAITH 0x1d -#define IPV6_OPTIONS 0x1 -#define IPV6_RTHDR_STRICT 0x1 -#define IPV6_SOCKOPT_RESERVED1 0x3 -#define SIOCGIFGENERIC 0xc020693a -#define SIOCSIFGENERIC 0x80206939 -#define WALTSIG 0x4 -' - -includes_SunOS=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' - - -includes=' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -' -ccflags="$@" - -# Write go tool cgo -godefs input. -( - echo package unix - echo - echo '/*' - indirect="includes_$(uname)" - echo "${!indirect} $includes" - echo '*/' - echo 'import "C"' - echo 'import "syscall"' - echo - echo 'const (' - - # The gcc command line prints all the #defines - # it encounters while processing the input - echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | - awk ' - $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} - - $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers - $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} - $2 ~ /^(SCM_SRCRT)$/ {next} - $2 ~ /^(MAP_FAILED)$/ {next} - $2 ~ /^ELF_.*$/ {next}# contains ELF_ARCH, etc. - - $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || - $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} - - $2 !~ /^ETH_/ && - $2 !~ /^EPROC_/ && - $2 !~ /^EQUIV_/ && - $2 !~ /^EXPR_/ && - $2 ~ /^E[A-Z0-9_]+$/ || - $2 ~ /^B[0-9_]+$/ || - $2 == "BOTHER" || - $2 ~ /^CI?BAUD(EX)?$/ || - $2 == "IBSHIFT" || - $2 ~ /^V[A-Z0-9]+$/ || - $2 ~ /^CS[A-Z0-9]/ || - $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || - $2 ~ /^IGN/ || - $2 ~ /^IX(ON|ANY|OFF)$/ || - $2 ~ /^IN(LCR|PCK)$/ || - $2 ~ /(^FLU?SH)|(FLU?SH$)/ || - $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || - $2 == "BRKINT" || - $2 == "HUPCL" || - $2 == "PENDIN" || - $2 == "TOSTOP" || - $2 == "XCASE" || - $2 == "ALTWERASE" || - $2 == "NOKERNINFO" || - $2 ~ /^PAR/ || - $2 ~ /^SIG[^_]/ || - $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || - $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || - $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || - $2 ~ /^O?XTABS$/ || - $2 ~ /^TC[IO](ON|OFF)$/ || - $2 ~ /^IN_/ || - $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || - $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || - $2 == "ICMPV6_FILTER" || - $2 == "SOMAXCONN" || - $2 == "NAME_MAX" || - $2 == "IFNAMSIZ" || - $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || - $2 ~ /^SYSCTL_VERS/ || - $2 ~ /^(MS|MNT)_/ || - $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || - $2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ || - $2 ~ /^LINUX_REBOOT_CMD_/ || - $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || - $2 !~ "NLA_TYPE_MASK" && - $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || - $2 ~ /^SIOC/ || - $2 ~ /^TIOC/ || - $2 ~ /^TCGET/ || - $2 ~ /^TCSET/ || - $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || - $2 !~ "RTF_BITS" && - $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || - $2 ~ /^BIOC/ || - $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || - $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ || - $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || - $2 ~ /^CLONE_[A-Z_]+/ || - $2 !~ /^(BPF_TIMEVAL)$/ && - $2 ~ /^(BPF|DLT)_/ || - $2 ~ /^CLOCK_/ || - $2 !~ "WMESGLEN" && - $2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)} - $2 ~ /^__WCOREFLAG$/ {next} - $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} - - {next} - ' | sort - - echo ')' -) >_const.go - -# Pull out the error names for later. -errors=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | - sort -) - -# Pull out the signal names for later. -signals=$( - echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | - egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | - sort -) - -# Again, writing regexps to a file. -echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | - sort >_error.grep -echo '#include ' | $CC -x c - -E -dM $ccflags | - awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | - egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | - sort >_signal.grep - -echo '// mkerrors.sh' "$@" -echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT' -echo -echo "// +build ${GOARCH},${GOOS}" -echo -go tool cgo -godefs -- "$@" _const.go >_error.out -cat _error.out | grep -vf _error.grep | grep -vf _signal.grep -echo -echo '// Errors' -echo 'const (' -cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' -echo ')' - -echo -echo '// Signals' -echo 'const (' -cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' -echo ')' - -# Run C program to print error and syscall strings. -( - echo -E " -#include -#include -#include -#include -#include -#include - -#define nelem(x) (sizeof(x)/sizeof((x)[0])) - -enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below - -int errors[] = { -" - for i in $errors - do - echo -E ' '$i, - done - - echo -E " -}; - -int signals[] = { -" - for i in $signals - do - echo -E ' '$i, - done - - # Use -E because on some systems bash builtin interprets \n itself. - echo -E ' -}; - -static int -intcmp(const void *a, const void *b) -{ - return *(int*)a - *(int*)b; -} - -int -main(void) -{ - int i, j, e; - char buf[1024], *p; - - printf("\n\n// Error table\n"); - printf("var errors = [...]string {\n"); - qsort(errors, nelem(errors), sizeof errors[0], intcmp); - for(i=0; i 0 && errors[i-1] == e) - continue; - strcpy(buf, strerror(e)); - // lowercase first letter: Bad -> bad, but STREAM -> STREAM. - if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) - buf[0] += a - A; - printf("\t%d: \"%s\",\n", e, buf); - } - printf("}\n\n"); - - printf("\n\n// Signal table\n"); - printf("var signals = [...]string {\n"); - qsort(signals, nelem(signals), sizeof signals[0], intcmp); - for(i=0; i 0 && signals[i-1] == e) - continue; - strcpy(buf, strsignal(e)); - // lowercase first letter: Bad -> bad, but STREAM -> STREAM. - if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) - buf[0] += a - A; - // cut trailing : number. - p = strrchr(buf, ":"[0]); - if(p) - *p = '\0'; - printf("\t%d: \"%s\",\n", e, buf); - } - printf("}\n\n"); - - return 0; -} - -' -) >_errors.c - -$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall.pl b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall.pl deleted file mode 100755 index b1e7766da..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall.pl +++ /dev/null @@ -1,323 +0,0 @@ -#!/usr/bin/env perl -# Copyright 2009 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -# This program reads a file containing function prototypes -# (like syscall_darwin.go) and generates system call bodies. -# The prototypes are marked by lines beginning with "//sys" -# and read like func declarations if //sys is replaced by func, but: -# * The parameter lists must give a name for each argument. -# This includes return parameters. -# * The parameter lists must give a type for each argument: -# the (x, y, z int) shorthand is not allowed. -# * If the return parameter is an error number, it must be named errno. - -# A line beginning with //sysnb is like //sys, except that the -# goroutine will not be suspended during the execution of the system -# call. This must only be used for system calls which can never -# block, as otherwise the system call could cause all goroutines to -# hang. - -use strict; - -my $cmdline = "mksyscall.pl " . join(' ', @ARGV); -my $errors = 0; -my $_32bit = ""; -my $plan9 = 0; -my $openbsd = 0; -my $netbsd = 0; -my $dragonfly = 0; -my $arm = 0; # 64-bit value should use (even, odd)-pair - -if($ARGV[0] eq "-b32") { - $_32bit = "big-endian"; - shift; -} elsif($ARGV[0] eq "-l32") { - $_32bit = "little-endian"; - shift; -} -if($ARGV[0] eq "-plan9") { - $plan9 = 1; - shift; -} -if($ARGV[0] eq "-openbsd") { - $openbsd = 1; - shift; -} -if($ARGV[0] eq "-netbsd") { - $netbsd = 1; - shift; -} -if($ARGV[0] eq "-dragonfly") { - $dragonfly = 1; - shift; -} -if($ARGV[0] eq "-arm") { - $arm = 1; - shift; -} - -if($ARGV[0] =~ /^-/) { - print STDERR "usage: mksyscall.pl [-b32 | -l32] [file ...]\n"; - exit 1; -} - -if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { - print STDERR "GOARCH or GOOS not defined in environment\n"; - exit 1; -} - -sub parseparamlist($) { - my ($list) = @_; - $list =~ s/^\s*//; - $list =~ s/\s*$//; - if($list eq "") { - return (); - } - return split(/\s*,\s*/, $list); -} - -sub parseparam($) { - my ($p) = @_; - if($p !~ /^(\S*) (\S*)$/) { - print STDERR "$ARGV:$.: malformed parameter: $p\n"; - $errors = 1; - return ("xx", "int"); - } - return ($1, $2); -} - -my $text = ""; -while(<>) { - chomp; - s/\s+/ /g; - s/^\s+//; - s/\s+$//; - my $nonblock = /^\/\/sysnb /; - next if !/^\/\/sys / && !$nonblock; - - # Line must be of the form - # func Open(path string, mode int, perm int) (fd int, errno error) - # Split into name, in params, out params. - if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { - print STDERR "$ARGV:$.: malformed //sys declaration\n"; - $errors = 1; - next; - } - my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); - - # Split argument lists on comma. - my @in = parseparamlist($in); - my @out = parseparamlist($out); - - # Try in vain to keep people from editing this file. - # The theory is that they jump into the middle of the file - # without reading the header. - $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; - - # Go function header. - my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; - $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; - - # Check if err return available - my $errvar = ""; - foreach my $p (@out) { - my ($name, $type) = parseparam($p); - if($type eq "error") { - $errvar = $name; - last; - } - } - - # Prepare arguments to Syscall. - my @args = (); - my @uses = (); - my $n = 0; - foreach my $p (@in) { - my ($name, $type) = parseparam($p); - if($type =~ /^\*/) { - push @args, "uintptr(unsafe.Pointer($name))"; - } elsif($type eq "string" && $errvar ne "") { - $text .= "\tvar _p$n *byte\n"; - $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; - $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - push @uses, "use(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type eq "string") { - print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; - $text .= "\tvar _p$n *byte\n"; - $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - push @uses, "use(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type =~ /^\[\](.*)/) { - # Convert slice into pointer, length. - # Have to be careful not to take address of &a[0] if len == 0: - # pass dummy pointer in that case. - # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). - $text .= "\tvar _p$n unsafe.Pointer\n"; - $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; - $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; - $text .= "\n"; - push @args, "uintptr(_p$n)", "uintptr(len($name))"; - $n++; - } elsif($type eq "int64" && ($openbsd || $netbsd)) { - push @args, "0"; - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } elsif($_32bit eq "little-endian") { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } else { - push @args, "uintptr($name)"; - } - } elsif($type eq "int64" && $dragonfly) { - if ($func !~ /^extp(read|write)/i) { - push @args, "0"; - } - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } elsif($_32bit eq "little-endian") { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } else { - push @args, "uintptr($name)"; - } - } elsif($type eq "int64" && $_32bit ne "") { - if(@args % 2 && $arm) { - # arm abi specifies 64-bit argument uses - # (even, odd) pair - push @args, "0" - } - if($_32bit eq "big-endian") { - push @args, "uintptr($name>>32)", "uintptr($name)"; - } else { - push @args, "uintptr($name)", "uintptr($name>>32)"; - } - } else { - push @args, "uintptr($name)"; - } - } - - # Determine which form to use; pad args with zeros. - my $asm = "Syscall"; - if ($nonblock) { - $asm = "RawSyscall"; - } - if(@args <= 3) { - while(@args < 3) { - push @args, "0"; - } - } elsif(@args <= 6) { - $asm .= "6"; - while(@args < 6) { - push @args, "0"; - } - } elsif(@args <= 9) { - $asm .= "9"; - while(@args < 9) { - push @args, "0"; - } - } else { - print STDERR "$ARGV:$.: too many arguments to system call\n"; - } - - # System call number. - if($sysname eq "") { - $sysname = "SYS_$func"; - $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar - $sysname =~ y/a-z/A-Z/; - } - - # Actual call. - my $args = join(', ', @args); - my $call = "$asm($sysname, $args)"; - - # Assign return values. - my $body = ""; - my @ret = ("_", "_", "_"); - my $do_errno = 0; - for(my $i=0; $i<@out; $i++) { - my $p = $out[$i]; - my ($name, $type) = parseparam($p); - my $reg = ""; - if($name eq "err" && !$plan9) { - $reg = "e1"; - $ret[2] = $reg; - $do_errno = 1; - } elsif($name eq "err" && $plan9) { - $ret[0] = "r0"; - $ret[2] = "e1"; - next; - } else { - $reg = sprintf("r%d", $i); - $ret[$i] = $reg; - } - if($type eq "bool") { - $reg = "$reg != 0"; - } - if($type eq "int64" && $_32bit ne "") { - # 64-bit number in r1:r0 or r0:r1. - if($i+2 > @out) { - print STDERR "$ARGV:$.: not enough registers for int64 return\n"; - } - if($_32bit eq "big-endian") { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); - } else { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); - } - $ret[$i] = sprintf("r%d", $i); - $ret[$i+1] = sprintf("r%d", $i+1); - } - if($reg ne "e1" || $plan9) { - $body .= "\t$name = $type($reg)\n"; - } - } - if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { - $text .= "\t$call\n"; - } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; - } - foreach my $use (@uses) { - $text .= "\t$use\n"; - } - $text .= $body; - - if ($plan9 && $ret[2] eq "e1") { - $text .= "\tif int32(r0) == -1 {\n"; - $text .= "\t\terr = e1\n"; - $text .= "\t}\n"; - } elsif ($do_errno) { - $text .= "\tif e1 != 0 {\n"; - $text .= "\t\terr = errnoErr(e1)\n"; - $text .= "\t}\n"; - } - $text .= "\treturn\n"; - $text .= "}\n\n"; -} - -chomp $text; -chomp $text; - -if($errors) { - exit 1; -} - -print <) { - chomp; - s/\s+/ /g; - s/^\s+//; - s/\s+$//; - $package = $1 if !$package && /^package (\S+)$/; - my $nonblock = /^\/\/sysnb /; - next if !/^\/\/sys / && !$nonblock; - - # Line must be of the form - # func Open(path string, mode int, perm int) (fd int, err error) - # Split into name, in params, out params. - if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { - print STDERR "$ARGV:$.: malformed //sys declaration\n"; - $errors = 1; - next; - } - my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); - - # Split argument lists on comma. - my @in = parseparamlist($in); - my @out = parseparamlist($out); - - # So file name. - if($modname eq "") { - $modname = "libc"; - } - - # System call name. - if($sysname eq "") { - $sysname = "$func"; - } - - # System call pointer variable name. - my $sysvarname = "proc$sysname"; - - my $strconvfunc = "BytePtrFromString"; - my $strconvtype = "*byte"; - - $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. - - # Runtime import of function to allow cross-platform builds. - $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; - # Link symbol to proc address variable. - $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; - # Library proc address variable. - push @vars, $sysvarname; - - # Go function header. - $out = join(', ', @out); - if($out ne "") { - $out = " ($out)"; - } - if($text ne "") { - $text .= "\n" - } - $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; - - # Check if err return available - my $errvar = ""; - foreach my $p (@out) { - my ($name, $type) = parseparam($p); - if($type eq "error") { - $errvar = $name; - last; - } - } - - # Prepare arguments to Syscall. - my @args = (); - my @uses = (); - my $n = 0; - foreach my $p (@in) { - my ($name, $type) = parseparam($p); - if($type =~ /^\*/) { - push @args, "uintptr(unsafe.Pointer($name))"; - } elsif($type eq "string" && $errvar ne "") { - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; - $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - push @uses, "use(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type eq "string") { - print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; - $text .= "\tvar _p$n $strconvtype\n"; - $text .= "\t_p$n, _ = $strconvfunc($name)\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))"; - push @uses, "use(unsafe.Pointer(_p$n))"; - $n++; - } elsif($type =~ /^\[\](.*)/) { - # Convert slice into pointer, length. - # Have to be careful not to take address of &a[0] if len == 0: - # pass nil in that case. - $text .= "\tvar _p$n *$1\n"; - $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; - push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; - $n++; - } elsif($type eq "int64" && $_32bit ne "") { - if($_32bit eq "big-endian") { - push @args, "uintptr($name >> 32)", "uintptr($name)"; - } else { - push @args, "uintptr($name)", "uintptr($name >> 32)"; - } - } elsif($type eq "bool") { - $text .= "\tvar _p$n uint32\n"; - $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; - push @args, "uintptr(_p$n)"; - $n++; - } else { - push @args, "uintptr($name)"; - } - } - my $nargs = @args; - - # Determine which form to use; pad args with zeros. - my $asm = "sysvicall6"; - if ($nonblock) { - $asm = "rawSysvicall6"; - } - if(@args <= 6) { - while(@args < 6) { - push @args, "0"; - } - } else { - print STDERR "$ARGV:$.: too many arguments to system call\n"; - } - - # Actual call. - my $args = join(', ', @args); - my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; - - # Assign return values. - my $body = ""; - my $failexpr = ""; - my @ret = ("_", "_", "_"); - my @pout= (); - my $do_errno = 0; - for(my $i=0; $i<@out; $i++) { - my $p = $out[$i]; - my ($name, $type) = parseparam($p); - my $reg = ""; - if($name eq "err") { - $reg = "e1"; - $ret[2] = $reg; - $do_errno = 1; - } else { - $reg = sprintf("r%d", $i); - $ret[$i] = $reg; - } - if($type eq "bool") { - $reg = "$reg != 0"; - } - if($type eq "int64" && $_32bit ne "") { - # 64-bit number in r1:r0 or r0:r1. - if($i+2 > @out) { - print STDERR "$ARGV:$.: not enough registers for int64 return\n"; - } - if($_32bit eq "big-endian") { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); - } else { - $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); - } - $ret[$i] = sprintf("r%d", $i); - $ret[$i+1] = sprintf("r%d", $i+1); - } - if($reg ne "e1") { - $body .= "\t$name = $type($reg)\n"; - } - } - if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { - $text .= "\t$call\n"; - } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; - } - foreach my $use (@uses) { - $text .= "\t$use\n"; - } - $text .= $body; - - if ($do_errno) { - $text .= "\tif e1 != 0 {\n"; - $text .= "\t\terr = e1\n"; - $text .= "\t}\n"; - } - $text .= "\treturn\n"; - $text .= "}\n"; -} - -if($errors) { - exit 1; -} - -print < "net.inet", - "net.inet.ipproto" => "net.inet", - "net.inet6.ipv6proto" => "net.inet6", - "net.inet6.ipv6" => "net.inet6.ip6", - "net.inet.icmpv6" => "net.inet6.icmp6", - "net.inet6.divert6" => "net.inet6.divert", - "net.inet6.tcp6" => "net.inet.tcp", - "net.inet6.udp6" => "net.inet.udp", - "mpls" => "net.mpls", - "swpenc" => "vm.swapencrypt" -); - -# Node mappings -my %node_map = ( - "net.inet.ip.ifq" => "net.ifq", - "net.inet.pfsync" => "net.pfsync", - "net.mpls.ifq" => "net.ifq" -); - -my $ctlname; -my %mib = (); -my %sysctl = (); -my $node; - -sub debug() { - print STDERR "$_[0]\n" if $debug; -} - -# Walk the MIB and build a sysctl name to OID mapping. -sub build_sysctl() { - my ($node, $name, $oid) = @_; - my %node = %{$node}; - my @oid = @{$oid}; - - foreach my $key (sort keys %node) { - my @node = @{$node{$key}}; - my $nodename = $name.($name ne '' ? '.' : '').$key; - my @nodeoid = (@oid, $node[0]); - if ($node[1] eq 'CTLTYPE_NODE') { - if (exists $node_map{$nodename}) { - $node = \%mib; - $ctlname = $node_map{$nodename}; - foreach my $part (split /\./, $ctlname) { - $node = \%{@{$$node{$part}}[2]}; - } - } else { - $node = $node[2]; - } - &build_sysctl($node, $nodename, \@nodeoid); - } elsif ($node[1] ne '') { - $sysctl{$nodename} = \@nodeoid; - } - } -} - -foreach my $ctl (@ctls) { - $ctls{$ctl} = $ctl; -} - -# Build MIB -foreach my $header (@headers) { - &debug("Processing $header..."); - open HEADER, "/usr/include/$header" || - print STDERR "Failed to open $header\n"; - while (
) { - if ($_ =~ /^#define\s+(CTL_NAMES)\s+{/ || - $_ =~ /^#define\s+(CTL_(.*)_NAMES)\s+{/ || - $_ =~ /^#define\s+((.*)CTL_NAMES)\s+{/) { - if ($1 eq 'CTL_NAMES') { - # Top level. - $node = \%mib; - } else { - # Node. - my $nodename = lc($2); - if ($header =~ /^netinet\//) { - $ctlname = "net.inet.$nodename"; - } elsif ($header =~ /^netinet6\//) { - $ctlname = "net.inet6.$nodename"; - } elsif ($header =~ /^net\//) { - $ctlname = "net.$nodename"; - } else { - $ctlname = "$nodename"; - $ctlname =~ s/^(fs|net|kern)_/$1\./; - } - if (exists $ctl_map{$ctlname}) { - $ctlname = $ctl_map{$ctlname}; - } - if (not exists $ctls{$ctlname}) { - &debug("Ignoring $ctlname..."); - next; - } - - # Walk down from the top of the MIB. - $node = \%mib; - foreach my $part (split /\./, $ctlname) { - if (not exists $$node{$part}) { - &debug("Missing node $part"); - $$node{$part} = [ 0, '', {} ]; - } - $node = \%{@{$$node{$part}}[2]}; - } - } - - # Populate current node with entries. - my $i = -1; - while (defined($_) && $_ !~ /^}/) { - $_ =
; - $i++ if $_ =~ /{.*}/; - next if $_ !~ /{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}/; - $$node{$1} = [ $i, $2, {} ]; - } - } - } - close HEADER; -} - -&build_sysctl(\%mib, "", []); - -print <){ - if(/^#define\s+SYS_(\w+)\s+([0-9]+)/){ - my $name = $1; - my $num = $2; - $name =~ y/a-z/A-Z/; - print " SYS_$name = $num;" - } -} - -print <){ - if(/^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$/){ - my $num = $1; - my $proto = $2; - my $name = "SYS_$3"; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - - print " $name = $num; // $proto\n"; - } -} - -print <){ - if(/^([0-9]+)\s+\S+\s+STD\s+({ \S+\s+(\w+).*)$/){ - my $num = $1; - my $proto = $2; - my $name = "SYS_$3"; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - if($name =~ /^SYS_CAP_+/ || $name =~ /^SYS___CAP_+/){ - next - } - - print " $name = $num; // $proto\n"; - - # We keep Capsicum syscall numbers for FreeBSD - # 9-STABLE here because we are not sure whether they - # are mature and stable. - if($num == 513){ - print " SYS_CAP_NEW = 514 // { int cap_new(int fd, uint64_t rights); }\n"; - print " SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \\\n"; - print " SYS_CAP_ENTER = 516 // { int cap_enter(void); }\n"; - print " SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }\n"; - } - } -} - -print < 999){ - # ignore deprecated syscalls that are no longer implemented - # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716 - return; - } - $name =~ y/a-z/A-Z/; - print " SYS_$name = $num;\n"; -} - -my $prev; -open(GCC, "gcc -E -dD $ARGV[0] |") || die "can't run gcc"; -while(){ - if(/^#define __NR_syscalls\s+/) { - # ignore redefinitions of __NR_syscalls - } - elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ - $prev = $2; - fmt($1, $2); - } - elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){ - $prev = $2; - fmt($1, $2); - } - elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ - fmt($1, $prev+$2) - } -} - -print <){ - if($line =~ /^(.*)\\$/) { - # Handle continuation - $line = $1; - $_ =~ s/^\s+//; - $line .= $_; - } else { - # New line - $line = $_; - } - next if $line =~ /\\$/; - if($line =~ /^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$/) { - my $num = $1; - my $proto = $6; - my $compat = $8; - my $name = "$7_$9"; - - $name = "$7_$11" if $11 ne ''; - $name =~ y/a-z/A-Z/; - - if($compat eq '' || $compat eq '30' || $compat eq '50') { - print " $name = $num; // $proto\n"; - } - } -} - -print <){ - if(/^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$/){ - my $num = $1; - my $proto = $3; - my $name = $4; - $name =~ y/a-z/A-Z/; - - # There are multiple entries for enosys and nosys, so comment them out. - if($name =~ /^SYS_E?NOSYS$/){ - $name = "// $name"; - } - if($name eq 'SYS_SYS_EXIT'){ - $name = 'SYS_EXIT'; - } - - print " $name = $num; // $proto\n"; - } -} - -print < len(b) { - return nil, nil, EINVAL - } - return h, b[cmsgAlignOf(SizeofCmsghdr):h.Len], nil -} - -// UnixRights encodes a set of open file descriptors into a socket -// control message for sending to another process. -func UnixRights(fds ...int) []byte { - datalen := len(fds) * 4 - b := make([]byte, CmsgSpace(datalen)) - h := (*Cmsghdr)(unsafe.Pointer(&b[0])) - h.Level = SOL_SOCKET - h.Type = SCM_RIGHTS - h.SetLen(CmsgLen(datalen)) - data := cmsgData(h) - for _, fd := range fds { - *(*int32)(data) = int32(fd) - data = unsafe.Pointer(uintptr(data) + 4) - } - return b -} - -// ParseUnixRights decodes a socket control message that contains an -// integer array of open file descriptors from another process. -func ParseUnixRights(m *SocketControlMessage) ([]int, error) { - if m.Header.Level != SOL_SOCKET { - return nil, EINVAL - } - if m.Header.Type != SCM_RIGHTS { - return nil, EINVAL - } - fds := make([]int, len(m.Data)>>2) - for i, j := 0, 0; i < len(m.Data); i += 4 { - fds[j] = int(*(*int32)(unsafe.Pointer(&m.Data[i]))) - j++ - } - return fds, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/str.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/str.go deleted file mode 100644 index 35ed66435..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/str.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -func itoa(val int) string { // do it here rather than with fmt to avoid dependency - if val < 0 { - return "-" + uitoa(uint(-val)) - } - return uitoa(uint(val)) -} - -func uitoa(val uint) string { - var buf [32]byte // big enough for int64 - i := len(buf) - 1 - for val >= 10 { - buf[i] = byte(val%10 + '0') - i-- - val /= 10 - } - buf[i] = byte(val + '0') - return string(buf[i:]) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall.go deleted file mode 100644 index 012f2d64f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -// Package unix contains an interface to the low-level operating system -// primitives. OS details vary depending on the underlying system, and -// by default, godoc will display OS-specific documentation for the current -// system. If you want godoc to display OS documentation for another -// system, set $GOOS and $GOARCH to the desired system. For example, if -// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS -// to freebsd and $GOARCH to arm. -// The primary use of this package is inside other packages that provide a more -// portable interface to the system, such as "os", "time" and "net". Use -// those packages rather than this one if you can. -// For details of the functions and data types in this package consult -// the manuals for the appropriate operating system. -// These calls return err == nil to indicate success; otherwise -// err represents an operating system error describing the failure and -// holds a value of type syscall.Errno. -package unix // import "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" - -import "unsafe" - -// ByteSliceFromString returns a NUL-terminated slice of bytes -// containing the text of s. If s contains a NUL byte at any -// location, it returns (nil, EINVAL). -func ByteSliceFromString(s string) ([]byte, error) { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return nil, EINVAL - } - } - a := make([]byte, len(s)+1) - copy(a, s) - return a, nil -} - -// BytePtrFromString returns a pointer to a NUL-terminated array of -// bytes containing the text of s. If s contains a NUL byte at any -// location, it returns (nil, EINVAL). -func BytePtrFromString(s string) (*byte, error) { - a, err := ByteSliceFromString(s) - if err != nil { - return nil, err - } - return &a[0], nil -} - -// Single-word zero for use when we need a valid pointer to 0 bytes. -// See mkunix.pl. -var _zero uintptr - -func (ts *Timespec) Unix() (sec int64, nsec int64) { - return int64(ts.Sec), int64(ts.Nsec) -} - -func (tv *Timeval) Unix() (sec int64, nsec int64) { - return int64(tv.Sec), int64(tv.Usec) * 1000 -} - -func (ts *Timespec) Nano() int64 { - return int64(ts.Sec)*1e9 + int64(ts.Nsec) -} - -func (tv *Timeval) Nano() int64 { - return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000 -} - -// use is a no-op, but the compiler cannot see that it is. -// Calling use(p) ensures that p is kept live until that point. -//go:noescape -func use(p unsafe.Pointer) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd.go deleted file mode 100644 index e9671764c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd.go +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd netbsd openbsd - -// BSD system call wrappers shared by *BSD based systems -// including OS X (Darwin) and FreeBSD. Like the other -// syscall_*.go files it is compiled as Go code but also -// used as input to mksyscall which parses the //sys -// lines and generates system call stubs. - -package unix - -import ( - "runtime" - "syscall" - "unsafe" -) - -/* - * Wrapped - */ - -//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) -//sysnb setgroups(ngid int, gid *_Gid_t) (err error) - -func Getgroups() (gids []int, err error) { - n, err := getgroups(0, nil) - if err != nil { - return nil, err - } - if n == 0 { - return nil, nil - } - - // Sanity check group count. Max is 16 on BSD. - if n < 0 || n > 1000 { - return nil, EINVAL - } - - a := make([]_Gid_t, n) - n, err = getgroups(n, &a[0]) - if err != nil { - return nil, err - } - gids = make([]int, n) - for i, v := range a[0:n] { - gids[i] = int(v) - } - return -} - -func Setgroups(gids []int) (err error) { - if len(gids) == 0 { - return setgroups(0, nil) - } - - a := make([]_Gid_t, len(gids)) - for i, v := range gids { - a[i] = _Gid_t(v) - } - return setgroups(len(a), &a[0]) -} - -func ReadDirent(fd int, buf []byte) (n int, err error) { - // Final argument is (basep *uintptr) and the syscall doesn't take nil. - // 64 bits should be enough. (32 bits isn't even on 386). Since the - // actual system call is getdirentries64, 64 is a good guess. - // TODO(rsc): Can we use a single global basep for all calls? - var base = (*uintptr)(unsafe.Pointer(new(uint64))) - return Getdirentries(fd, buf, base) -} - -// Wait status is 7 bits at bottom, either 0 (exited), -// 0x7F (stopped), or a signal number that caused an exit. -// The 0x80 bit is whether there was a core dump. -// An extra number (exit code, signal causing a stop) -// is in the high bits. - -type WaitStatus uint32 - -const ( - mask = 0x7F - core = 0x80 - shift = 8 - - exited = 0 - stopped = 0x7F -) - -func (w WaitStatus) Exited() bool { return w&mask == exited } - -func (w WaitStatus) ExitStatus() int { - if w&mask != exited { - return -1 - } - return int(w >> shift) -} - -func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } - -func (w WaitStatus) Signal() syscall.Signal { - sig := syscall.Signal(w & mask) - if sig == stopped || sig == 0 { - return -1 - } - return sig -} - -func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } - -func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP } - -func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } - -func (w WaitStatus) StopSignal() syscall.Signal { - if !w.Stopped() { - return -1 - } - return syscall.Signal(w>>shift) & 0xFF -} - -func (w WaitStatus) TrapCause() int { return -1 } - -//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) - -func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { - var status _C_int - wpid, err = wait4(pid, &status, options, rusage) - if wstatus != nil { - *wstatus = WaitStatus(status) - } - return -} - -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb socket(domain int, typ int, proto int) (fd int, err error) -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sys Shutdown(s int, how int) (err error) - -func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Len = SizeofSockaddrInet4 - sa.raw.Family = AF_INET - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil -} - -func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Len = SizeofSockaddrInet6 - sa.raw.Family = AF_INET6 - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - sa.raw.Scope_id = sa.ZoneId - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil -} - -func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { - name := sa.Name - n := len(name) - if n >= len(sa.raw.Path) || n == 0 { - return nil, 0, EINVAL - } - sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL - sa.raw.Family = AF_UNIX - for i := 0; i < n; i++ { - sa.raw.Path[i] = int8(name[i]) - } - return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil -} - -func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Index == 0 { - return nil, 0, EINVAL - } - sa.raw.Len = sa.Len - sa.raw.Family = AF_LINK - sa.raw.Index = sa.Index - sa.raw.Type = sa.Type - sa.raw.Nlen = sa.Nlen - sa.raw.Alen = sa.Alen - sa.raw.Slen = sa.Slen - for i := 0; i < len(sa.raw.Data); i++ { - sa.raw.Data[i] = sa.Data[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil -} - -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { - switch rsa.Addr.Family { - case AF_LINK: - pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa)) - sa := new(SockaddrDatalink) - sa.Len = pp.Len - sa.Family = pp.Family - sa.Index = pp.Index - sa.Type = pp.Type - sa.Nlen = pp.Nlen - sa.Alen = pp.Alen - sa.Slen = pp.Slen - for i := 0; i < len(sa.Data); i++ { - sa.Data[i] = pp.Data[i] - } - return sa, nil - - case AF_UNIX: - pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) - if pp.Len < 2 || pp.Len > SizeofSockaddrUnix { - return nil, EINVAL - } - sa := new(SockaddrUnix) - - // Some BSDs include the trailing NUL in the length, whereas - // others do not. Work around this by subtracting the leading - // family and len. The path is then scanned to see if a NUL - // terminator still exists within the length. - n := int(pp.Len) - 2 // subtract leading Family, Len - for i := 0; i < n; i++ { - if pp.Path[i] == 0 { - // found early NUL; assume Len included the NUL - // or was overestimating. - n = i - break - } - } - bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] - sa.Name = string(bytes) - return sa, nil - - case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - - case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - } - return nil, EAFNOSUPPORT -} - -func Accept(fd int) (nfd int, sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - nfd, err = accept(fd, &rsa, &len) - if err != nil { - return - } - if runtime.GOOS == "darwin" && len == 0 { - // Accepted socket has no address. - // This is likely due to a bug in xnu kernels, - // where instead of ECONNABORTED error socket - // is accepted, but has no address. - Close(nfd) - return 0, nil, ECONNABORTED - } - sa, err = anyToSockaddr(&rsa) - if err != nil { - Close(nfd) - nfd = 0 - } - return -} - -func Getsockname(fd int) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - if err = getsockname(fd, &rsa, &len); err != nil { - return - } - // TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be - // reported upstream. - if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 { - rsa.Addr.Family = AF_UNIX - rsa.Addr.Len = SizeofSockaddrUnix - } - return anyToSockaddr(&rsa) -} - -//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) - -func GetsockoptByte(fd, level, opt int) (value byte, err error) { - var n byte - vallen := _Socklen(1) - err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) - return n, err -} - -func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { - vallen := _Socklen(4) - err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) - return value, err -} - -func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { - var value IPMreq - vallen := _Socklen(SizeofIPMreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { - var value IPv6Mreq - vallen := _Socklen(SizeofIPv6Mreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { - var value IPv6MTUInfo - vallen := _Socklen(SizeofIPv6MTUInfo) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { - var value ICMPv6Filter - vallen := _Socklen(SizeofICMPv6Filter) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) - -func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { - var msg Msghdr - var rsa RawSockaddrAny - msg.Name = (*byte)(unsafe.Pointer(&rsa)) - msg.Namelen = uint32(SizeofSockaddrAny) - var iov Iovec - if len(p) > 0 { - iov.Base = (*byte)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy byte - if len(oob) > 0 { - // receive at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Control = (*byte)(unsafe.Pointer(&oob[0])) - msg.SetControllen(len(oob)) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = recvmsg(fd, &msg, flags); err != nil { - return - } - oobn = int(msg.Controllen) - recvflags = int(msg.Flags) - // source address is only specified if the socket is unconnected - if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) - } - return -} - -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) - -func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { - _, err = SendmsgN(fd, p, oob, to, flags) - return -} - -func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { - var ptr unsafe.Pointer - var salen _Socklen - if to != nil { - ptr, salen, err = to.sockaddr() - if err != nil { - return 0, err - } - } - var msg Msghdr - msg.Name = (*byte)(unsafe.Pointer(ptr)) - msg.Namelen = uint32(salen) - var iov Iovec - if len(p) > 0 { - iov.Base = (*byte)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy byte - if len(oob) > 0 { - // send at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Control = (*byte)(unsafe.Pointer(&oob[0])) - msg.SetControllen(len(oob)) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = sendmsg(fd, &msg, flags); err != nil { - return 0, err - } - if len(oob) > 0 && len(p) == 0 { - n = 0 - } - return n, nil -} - -//sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) - -func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) { - var change, event unsafe.Pointer - if len(changes) > 0 { - change = unsafe.Pointer(&changes[0]) - } - if len(events) > 0 { - event = unsafe.Pointer(&events[0]) - } - return kevent(kq, change, len(changes), event, len(events), timeout) -} - -//sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL - -// sysctlmib translates name to mib number and appends any additional args. -func sysctlmib(name string, args ...int) ([]_C_int, error) { - // Translate name to mib number. - mib, err := nametomib(name) - if err != nil { - return nil, err - } - - for _, a := range args { - mib = append(mib, _C_int(a)) - } - - return mib, nil -} - -func Sysctl(name string) (string, error) { - return SysctlArgs(name) -} - -func SysctlArgs(name string, args ...int) (string, error) { - mib, err := sysctlmib(name, args...) - if err != nil { - return "", err - } - - // Find size. - n := uintptr(0) - if err := sysctl(mib, nil, &n, nil, 0); err != nil { - return "", err - } - if n == 0 { - return "", nil - } - - // Read into buffer of that size. - buf := make([]byte, n) - if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { - return "", err - } - - // Throw away terminating NUL. - if n > 0 && buf[n-1] == '\x00' { - n-- - } - return string(buf[0:n]), nil -} - -func SysctlUint32(name string) (uint32, error) { - return SysctlUint32Args(name) -} - -func SysctlUint32Args(name string, args ...int) (uint32, error) { - mib, err := sysctlmib(name, args...) - if err != nil { - return 0, err - } - - n := uintptr(4) - buf := make([]byte, 4) - if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { - return 0, err - } - if n != 4 { - return 0, EIO - } - return *(*uint32)(unsafe.Pointer(&buf[0])), nil -} - -func SysctlUint64(name string, args ...int) (uint64, error) { - mib, err := sysctlmib(name, args...) - if err != nil { - return 0, err - } - - n := uintptr(8) - buf := make([]byte, 8) - if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { - return 0, err - } - if n != 8 { - return 0, EIO - } - return *(*uint64)(unsafe.Pointer(&buf[0])), nil -} - -func SysctlRaw(name string, args ...int) ([]byte, error) { - mib, err := sysctlmib(name, args...) - if err != nil { - return nil, err - } - - // Find size. - n := uintptr(0) - if err := sysctl(mib, nil, &n, nil, 0); err != nil { - return nil, err - } - if n == 0 { - return nil, nil - } - - // Read into buffer of that size. - buf := make([]byte, n) - if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { - return nil, err - } - - // The actual call may return less than the original reported required - // size so ensure we deal with that. - return buf[:n], nil -} - -//sys utimes(path string, timeval *[2]Timeval) (err error) - -func Utimes(path string, tv []Timeval) error { - if tv == nil { - return utimes(path, nil) - } - if len(tv) != 2 { - return EINVAL - } - return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -func UtimesNano(path string, ts []Timespec) error { - if ts == nil { - return utimes(path, nil) - } - // TODO: The BSDs can do utimensat with SYS_UTIMENSAT but it - // isn't supported by darwin so this uses utimes instead - if len(ts) != 2 { - return EINVAL - } - // Not as efficient as it could be because Timespec and - // Timeval have different types in the different OSes - tv := [2]Timeval{ - NsecToTimeval(TimespecToNsec(ts[0])), - NsecToTimeval(TimespecToNsec(ts[1])), - } - return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -//sys futimes(fd int, timeval *[2]Timeval) (err error) - -func Futimes(fd int, tv []Timeval) error { - if tv == nil { - return futimes(fd, nil) - } - if len(tv) != 2 { - return EINVAL - } - return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -//sys fcntl(fd int, cmd int, arg int) (val int, err error) - -// TODO: wrap -// Acct(name nil-string) (err error) -// Gethostuuid(uuid *byte, timeout *Timespec) (err error) -// Madvise(addr *byte, len int, behav int) (err error) -// Mprotect(addr *byte, len int, prot int) (err error) -// Msync(addr *byte, len int, flags int) (err error) -// Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error) - -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin.go deleted file mode 100644 index 0d1771c3f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin.go +++ /dev/null @@ -1,509 +0,0 @@ -// Copyright 2009,2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Darwin system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_bsd.go or syscall_unix.go. - -package unix - -import ( - errorspkg "errors" - "syscall" - "unsafe" -) - -const ImplementsGetwd = true - -func Getwd() (string, error) { - buf := make([]byte, 2048) - attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0) - if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 { - wd := string(attrs[0]) - // Sanity check that it's an absolute path and ends - // in a null byte, which we then strip. - if wd[0] == '/' && wd[len(wd)-1] == 0 { - return wd[:len(wd)-1], nil - } - } - // If pkg/os/getwd.go gets ENOTSUP, it will fall back to the - // slow algorithm. - return "", ENOTSUP -} - -type SockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - raw RawSockaddrDatalink -} - -// Translate "kern.hostname" to []_C_int{0,1,2,3}. -func nametomib(name string) (mib []_C_int, err error) { - const siz = unsafe.Sizeof(mib[0]) - - // NOTE(rsc): It seems strange to set the buffer to have - // size CTL_MAXNAME+2 but use only CTL_MAXNAME - // as the size. I don't know why the +2 is here, but the - // kernel uses +2 for its own implementation of this function. - // I am scared that if we don't include the +2 here, the kernel - // will silently write 2 words farther than we specify - // and we'll get memory corruption. - var buf [CTL_MAXNAME + 2]_C_int - n := uintptr(CTL_MAXNAME) * siz - - p := (*byte)(unsafe.Pointer(&buf[0])) - bytes, err := ByteSliceFromString(name) - if err != nil { - return nil, err - } - - // Magic sysctl: "setting" 0.3 to a string name - // lets you read back the array of integers form. - if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { - return nil, err - } - return buf[0 : n/siz], nil -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - if dirent.Reclen == 0 { - buf = nil - break - } - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:dirent.Namlen]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) -func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) } -func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) } - -const ( - attrBitMapCount = 5 - attrCmnFullpath = 0x08000000 -) - -type attrList struct { - bitmapCount uint16 - _ uint16 - CommonAttr uint32 - VolAttr uint32 - DirAttr uint32 - FileAttr uint32 - Forkattr uint32 -} - -func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) { - if len(attrBuf) < 4 { - return nil, errorspkg.New("attrBuf too small") - } - attrList.bitmapCount = attrBitMapCount - - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return nil, err - } - - _, _, e1 := Syscall6( - SYS_GETATTRLIST, - uintptr(unsafe.Pointer(_p0)), - uintptr(unsafe.Pointer(&attrList)), - uintptr(unsafe.Pointer(&attrBuf[0])), - uintptr(len(attrBuf)), - uintptr(options), - 0, - ) - if e1 != 0 { - return nil, e1 - } - size := *(*uint32)(unsafe.Pointer(&attrBuf[0])) - - // dat is the section of attrBuf that contains valid data, - // without the 4 byte length header. All attribute offsets - // are relative to dat. - dat := attrBuf - if int(size) < len(attrBuf) { - dat = dat[:size] - } - dat = dat[4:] // remove length prefix - - for i := uint32(0); int(i) < len(dat); { - header := dat[i:] - if len(header) < 8 { - return attrs, errorspkg.New("truncated attribute header") - } - datOff := *(*int32)(unsafe.Pointer(&header[0])) - attrLen := *(*uint32)(unsafe.Pointer(&header[4])) - if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) { - return attrs, errorspkg.New("truncated results; attrBuf too small") - } - end := uint32(datOff) + attrLen - attrs = append(attrs, dat[datOff:end]) - i = end - if r := i % 4; r != 0 { - i += (4 - r) - } - } - return -} - -//sysnb pipe() (r int, w int, err error) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - p[0], p[1], err = pipe() - return -} - -func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { - var _p0 unsafe.Pointer - var bufsize uintptr - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) - } - r0, _, e1 := Syscall(SYS_GETFSSTAT64, uintptr(_p0), bufsize, uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -/* - * Wrapped - */ - -//sys kill(pid int, signum int, posix int) (err error) - -func Kill(pid int, signum syscall.Signal) (err error) { return kill(pid, int(signum), 1) } - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chflags(path string, flags int) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(from int, to int) (err error) -//sys Exchangedata(path1 string, path2 string, options int) (err error) -//sys Exit(code int) -//sys Fchdir(fd int) (err error) -//sys Fchflags(fd int, flags int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 -//sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64 -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) = SYS_GETDIRENTRIES64 -//sys Getdtablesize() (size int) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) -//sysnb Getgid() (gid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgrp int) -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Getsid(pid int) (sid int, err error) -//sysnb Getuid() (uid int) -//sysnb Issetugid() (tainted bool) -//sys Kqueue() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Revoke(path string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK -//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) -//sys Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sys Setlogin(name string) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sys Setprivexec(flag int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tp *Timeval) (err error) -//sysnb Setuid(uid int) (err error) -//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 -//sys Statfs(path string, stat *Statfs_t) (err error) = SYS_STATFS64 -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sys Truncate(path string, length int64) (err error) -//sys Umask(newmask int) (oldmask int) -//sys Undelete(path string) (err error) -//sys Unlink(path string) (err error) -//sys Unmount(path string, flags int) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ -//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE - -/* - * Unimplemented - */ -// Profil -// Sigaction -// Sigprocmask -// Getlogin -// Sigpending -// Sigaltstack -// Ioctl -// Reboot -// Execve -// Vfork -// Sbrk -// Sstk -// Ovadvise -// Mincore -// Setitimer -// Swapon -// Select -// Sigsuspend -// Readv -// Writev -// Nfssvc -// Getfh -// Quotactl -// Mount -// Csops -// Waitid -// Add_profil -// Kdebug_trace -// Sigreturn -// Mmap -// Mlock -// Munlock -// Atsocket -// Kqueue_from_portset_np -// Kqueue_portset -// Getattrlist -// Setattrlist -// Getdirentriesattr -// Searchfs -// Delete -// Copyfile -// Poll -// Watchevent -// Waitevent -// Modwatch -// Getxattr -// Fgetxattr -// Setxattr -// Fsetxattr -// Removexattr -// Fremovexattr -// Listxattr -// Flistxattr -// Fsctl -// Initgroups -// Posix_spawn -// Nfsclnt -// Fhopen -// Minherit -// Semsys -// Msgsys -// Shmsys -// Semctl -// Semget -// Semop -// Msgctl -// Msgget -// Msgsnd -// Msgrcv -// Shmat -// Shmctl -// Shmdt -// Shmget -// Shm_open -// Shm_unlink -// Sem_open -// Sem_close -// Sem_unlink -// Sem_wait -// Sem_trywait -// Sem_post -// Sem_getvalue -// Sem_init -// Sem_destroy -// Open_extended -// Umask_extended -// Stat_extended -// Lstat_extended -// Fstat_extended -// Chmod_extended -// Fchmod_extended -// Access_extended -// Settid -// Gettid -// Setsgroups -// Getsgroups -// Setwgroups -// Getwgroups -// Mkfifo_extended -// Mkdir_extended -// Identitysvc -// Shared_region_check_np -// Shared_region_map_np -// __pthread_mutex_destroy -// __pthread_mutex_init -// __pthread_mutex_lock -// __pthread_mutex_trylock -// __pthread_mutex_unlock -// __pthread_cond_init -// __pthread_cond_destroy -// __pthread_cond_broadcast -// __pthread_cond_signal -// Setsid_with_pid -// __pthread_cond_timedwait -// Aio_fsync -// Aio_return -// Aio_suspend -// Aio_cancel -// Aio_error -// Aio_read -// Aio_write -// Lio_listio -// __pthread_cond_wait -// Iopolicysys -// Mlockall -// Munlockall -// __pthread_kill -// __pthread_sigmask -// __sigwait -// __disable_threadsignal -// __pthread_markcancel -// __pthread_canceled -// __semwait_signal -// Proc_info -// sendfile -// Stat64_extended -// Lstat64_extended -// Fstat64_extended -// __pthread_chdir -// __pthread_fchdir -// Audit -// Auditon -// Getauid -// Setauid -// Getaudit -// Setaudit -// Getaudit_addr -// Setaudit_addr -// Auditctl -// Bsdthread_create -// Bsdthread_terminate -// Stack_snapshot -// Bsdthread_register -// Workq_open -// Workq_ops -// __mac_execve -// __mac_syscall -// __mac_get_file -// __mac_set_file -// __mac_get_link -// __mac_set_link -// __mac_get_proc -// __mac_set_proc -// __mac_get_fd -// __mac_set_fd -// __mac_get_pid -// __mac_get_lcid -// __mac_get_lctx -// __mac_set_lctx -// Setlcid -// Read_nocancel -// Write_nocancel -// Open_nocancel -// Close_nocancel -// Wait4_nocancel -// Recvmsg_nocancel -// Sendmsg_nocancel -// Recvfrom_nocancel -// Accept_nocancel -// Msync_nocancel -// Fcntl_nocancel -// Select_nocancel -// Fsync_nocancel -// Connect_nocancel -// Sigsuspend_nocancel -// Readv_nocancel -// Writev_nocancel -// Sendto_nocancel -// Pread_nocancel -// Pwrite_nocancel -// Waitid_nocancel -// Poll_nocancel -// Msgsnd_nocancel -// Msgrcv_nocancel -// Sem_wait_nocancel -// Aio_suspend_nocancel -// __sigwait_nocancel -// __semwait_signal_nocancel -// __mac_mount -// __mac_get_mount -// __mac_getfsstat diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_386.go deleted file mode 100644 index 3195c8bf5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_386.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386,darwin - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int32(nsec / 1e9) - return -} - -//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = int32(sec) - tv.Usec = int32(usec) - return err -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var length = uint64(count) - - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0) - - written = int(length) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) - -// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions -// of darwin/386 the syscall is called sysctl instead of __sysctl. -const SYS___SYSCTL = SYS_SYSCTL diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_amd64.go deleted file mode 100644 index 7adb98ded..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_amd64.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,darwin - -package unix - -import ( - "syscall" - "unsafe" -) - -//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = sec - tv.Usec = usec - return err -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint64(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var length = uint64(count) - - _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0) - - written = int(length) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) - -// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions -// of darwin/amd64 the syscall is called sysctl instead of __sysctl. -const SYS___SYSCTL = SYS_SYSCTL diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm.go deleted file mode 100644 index e47ffd739..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int32(nsec / 1e9) - return -} - -//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = int32(sec) - tv.Usec = int32(usec) - return err -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var length = uint64(count) - - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(*offset>>32), uintptr(unsafe.Pointer(&length)), 0, 0, 0, 0) - - written = int(length) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm64.go deleted file mode 100644 index 2560a9599..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm64.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm64,darwin - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 16384 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = sec - tv.Usec = usec - return err -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint64(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var length = uint64(count) - - _, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0) - - written = int(length) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic - -// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions -// of darwin/arm64 the syscall is called sysctl instead of __sysctl. -const SYS___SYSCTL = SYS_SYSCTL diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly.go deleted file mode 100644 index fbbe0dce2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly.go +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright 2009,2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// FreeBSD system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_bsd.go or syscall_unix.go. - -package unix - -import "unsafe" - -type SockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - Rcf uint16 - Route [16]uint16 - raw RawSockaddrDatalink -} - -// Translate "kern.hostname" to []_C_int{0,1,2,3}. -func nametomib(name string) (mib []_C_int, err error) { - const siz = unsafe.Sizeof(mib[0]) - - // NOTE(rsc): It seems strange to set the buffer to have - // size CTL_MAXNAME+2 but use only CTL_MAXNAME - // as the size. I don't know why the +2 is here, but the - // kernel uses +2 for its own implementation of this function. - // I am scared that if we don't include the +2 here, the kernel - // will silently write 2 words farther than we specify - // and we'll get memory corruption. - var buf [CTL_MAXNAME + 2]_C_int - n := uintptr(CTL_MAXNAME) * siz - - p := (*byte)(unsafe.Pointer(&buf[0])) - bytes, err := ByteSliceFromString(name) - if err != nil { - return nil, err - } - - // Magic sysctl: "setting" 0.3 to a string name - // lets you read back the array of integers form. - if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { - return nil, err - } - return buf[0 : n/siz], nil -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - reclen := int(16+dirent.Namlen+1+7) & ^7 - buf = buf[reclen:] - if dirent.Fileno == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:dirent.Namlen]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sysnb pipe() (r int, w int, err error) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - p[0], p[1], err = pipe() - return -} - -//sys extpread(fd int, p []byte, flags int, offset int64) (n int, err error) -func Pread(fd int, p []byte, offset int64) (n int, err error) { - return extpread(fd, p, 0, offset) -} - -//sys extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - return extpwrite(fd, p, 0, offset) -} - -func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { - var _p0 unsafe.Pointer - var bufsize uintptr - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) - } - r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chflags(path string, flags int) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(from int, to int) (err error) -//sys Exit(code int) -//sys Fchdir(fd int) (err error) -//sys Fchflags(fd int, flags int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatfs(fd int, stat *Statfs_t) (err error) -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) -//sys Getdtablesize() (size int) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) -//sysnb Getgid() (gid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgrp int) -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Getsid(pid int) (sid int, err error) -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Getuid() (uid int) -//sys Issetugid() (tainted bool) -//sys Kill(pid int, signum syscall.Signal) (err error) -//sys Kqueue() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Revoke(path string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK -//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) -//sysnb Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sys Setlogin(name string) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tp *Timeval) (err error) -//sysnb Setuid(uid int) (err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Statfs(path string, stat *Statfs_t) (err error) -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sys Truncate(path string, length int64) (err error) -//sys Umask(newmask int) (oldmask int) -//sys Undelete(path string) (err error) -//sys Unlink(path string) (err error) -//sys Unmount(path string, flags int) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ -//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE - -/* - * Unimplemented - * TODO(jsing): Update this list for DragonFly. - */ -// Profil -// Sigaction -// Sigprocmask -// Getlogin -// Sigpending -// Sigaltstack -// Ioctl -// Reboot -// Execve -// Vfork -// Sbrk -// Sstk -// Ovadvise -// Mincore -// Setitimer -// Swapon -// Select -// Sigsuspend -// Readv -// Writev -// Nfssvc -// Getfh -// Quotactl -// Mount -// Csops -// Waitid -// Add_profil -// Kdebug_trace -// Sigreturn -// Mmap -// Atsocket -// Kqueue_from_portset_np -// Kqueue_portset -// Getattrlist -// Setattrlist -// Getdirentriesattr -// Searchfs -// Delete -// Copyfile -// Poll -// Watchevent -// Waitevent -// Modwatch -// Getxattr -// Fgetxattr -// Setxattr -// Fsetxattr -// Removexattr -// Fremovexattr -// Listxattr -// Flistxattr -// Fsctl -// Initgroups -// Posix_spawn -// Nfsclnt -// Fhopen -// Minherit -// Semsys -// Msgsys -// Shmsys -// Semctl -// Semget -// Semop -// Msgctl -// Msgget -// Msgsnd -// Msgrcv -// Shmat -// Shmctl -// Shmdt -// Shmget -// Shm_open -// Shm_unlink -// Sem_open -// Sem_close -// Sem_unlink -// Sem_wait -// Sem_trywait -// Sem_post -// Sem_getvalue -// Sem_init -// Sem_destroy -// Open_extended -// Umask_extended -// Stat_extended -// Lstat_extended -// Fstat_extended -// Chmod_extended -// Fchmod_extended -// Access_extended -// Settid -// Gettid -// Setsgroups -// Getsgroups -// Setwgroups -// Getwgroups -// Mkfifo_extended -// Mkdir_extended -// Identitysvc -// Shared_region_check_np -// Shared_region_map_np -// __pthread_mutex_destroy -// __pthread_mutex_init -// __pthread_mutex_lock -// __pthread_mutex_trylock -// __pthread_mutex_unlock -// __pthread_cond_init -// __pthread_cond_destroy -// __pthread_cond_broadcast -// __pthread_cond_signal -// Setsid_with_pid -// __pthread_cond_timedwait -// Aio_fsync -// Aio_return -// Aio_suspend -// Aio_cancel -// Aio_error -// Aio_read -// Aio_write -// Lio_listio -// __pthread_cond_wait -// Iopolicysys -// __pthread_kill -// __pthread_sigmask -// __sigwait -// __disable_threadsignal -// __pthread_markcancel -// __pthread_canceled -// __semwait_signal -// Proc_info -// Stat64_extended -// Lstat64_extended -// Fstat64_extended -// __pthread_chdir -// __pthread_fchdir -// Audit -// Auditon -// Getauid -// Setauid -// Getaudit -// Setaudit -// Getaudit_addr -// Setaudit_addr -// Auditctl -// Bsdthread_create -// Bsdthread_terminate -// Stack_snapshot -// Bsdthread_register -// Workq_open -// Workq_ops -// __mac_execve -// __mac_syscall -// __mac_get_file -// __mac_set_file -// __mac_get_link -// __mac_set_link -// __mac_get_proc -// __mac_set_proc -// __mac_get_fd -// __mac_set_fd -// __mac_get_pid -// __mac_get_lcid -// __mac_get_lctx -// __mac_set_lctx -// Setlcid -// Read_nocancel -// Write_nocancel -// Open_nocancel -// Close_nocancel -// Wait4_nocancel -// Recvmsg_nocancel -// Sendmsg_nocancel -// Recvfrom_nocancel -// Accept_nocancel -// Msync_nocancel -// Fcntl_nocancel -// Select_nocancel -// Fsync_nocancel -// Connect_nocancel -// Sigsuspend_nocancel -// Readv_nocancel -// Writev_nocancel -// Sendto_nocancel -// Pread_nocancel -// Pwrite_nocancel -// Waitid_nocancel -// Poll_nocancel -// Msgsnd_nocancel -// Msgrcv_nocancel -// Sem_wait_nocancel -// Aio_suspend_nocancel -// __sigwait_nocancel -// __semwait_signal_nocancel -// __mac_mount -// __mac_get_mount -// __mac_getfsstat diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_386.go deleted file mode 100644 index 41c2e6978..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_386.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386,dragonfly - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int32(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var writtenOut uint64 = 0 - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) - - written = int(writtenOut) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_amd64.go deleted file mode 100644 index 2ed92590e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_amd64.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,dragonfly - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = nsec % 1e9 / 1e3 - tv.Sec = int64(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint64(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var writtenOut uint64 = 0 - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0) - - written = int(writtenOut) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd.go deleted file mode 100644 index ec56ed608..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd.go +++ /dev/null @@ -1,682 +0,0 @@ -// Copyright 2009,2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// FreeBSD system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_bsd.go or syscall_unix.go. - -package unix - -import "unsafe" - -type SockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [46]int8 - raw RawSockaddrDatalink -} - -// Translate "kern.hostname" to []_C_int{0,1,2,3}. -func nametomib(name string) (mib []_C_int, err error) { - const siz = unsafe.Sizeof(mib[0]) - - // NOTE(rsc): It seems strange to set the buffer to have - // size CTL_MAXNAME+2 but use only CTL_MAXNAME - // as the size. I don't know why the +2 is here, but the - // kernel uses +2 for its own implementation of this function. - // I am scared that if we don't include the +2 here, the kernel - // will silently write 2 words farther than we specify - // and we'll get memory corruption. - var buf [CTL_MAXNAME + 2]_C_int - n := uintptr(CTL_MAXNAME) * siz - - p := (*byte)(unsafe.Pointer(&buf[0])) - bytes, err := ByteSliceFromString(name) - if err != nil { - return nil, err - } - - // Magic sysctl: "setting" 0.3 to a string name - // lets you read back the array of integers form. - if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil { - return nil, err - } - return buf[0 : n/siz], nil -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - if dirent.Reclen == 0 { - buf = nil - break - } - buf = buf[dirent.Reclen:] - if dirent.Fileno == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:dirent.Namlen]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sysnb pipe() (r int, w int, err error) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - p[0], p[1], err = pipe() - return -} - -func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { - var value IPMreqn - vallen := _Socklen(SizeofIPMreqn) - errno := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, errno -} - -func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) -} - -func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - nfd, err = accept4(fd, &rsa, &len, flags) - if err != nil { - return - } - if len > SizeofSockaddrAny { - panic("RawSockaddrAny too small") - } - sa, err = anyToSockaddr(&rsa) - if err != nil { - Close(nfd) - nfd = 0 - } - return -} - -func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { - var _p0 unsafe.Pointer - var bufsize uintptr - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) - } - r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -// Derive extattr namespace and attribute name - -func xattrnamespace(fullattr string) (ns int, attr string, err error) { - s := -1 - for idx, val := range fullattr { - if val == '.' { - s = idx - break - } - } - - if s == -1 { - return -1, "", ENOATTR - } - - namespace := fullattr[0:s] - attr = fullattr[s+1:] - - switch namespace { - case "user": - return EXTATTR_NAMESPACE_USER, attr, nil - case "system": - return EXTATTR_NAMESPACE_SYSTEM, attr, nil - default: - return -1, "", ENOATTR - } -} - -func initxattrdest(dest []byte, idx int) (d unsafe.Pointer) { - if len(dest) > idx { - return unsafe.Pointer(&dest[idx]) - } else { - return unsafe.Pointer(_zero) - } -} - -// FreeBSD implements its own syscalls to handle extended attributes - -func Getxattr(file string, attr string, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsize := len(dest) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return -1, err - } - - return ExtattrGetFile(file, nsid, a, uintptr(d), destsize) -} - -func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsize := len(dest) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return -1, err - } - - return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize) -} - -func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsize := len(dest) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return -1, err - } - - return ExtattrGetLink(link, nsid, a, uintptr(d), destsize) -} - -// flags are unused on FreeBSD - -func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { - d := unsafe.Pointer(&data[0]) - datasiz := len(data) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz) - return -} - -func Setxattr(file string, attr string, data []byte, flags int) (err error) { - d := unsafe.Pointer(&data[0]) - datasiz := len(data) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz) - return -} - -func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { - d := unsafe.Pointer(&data[0]) - datasiz := len(data) - - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz) - return -} - -func Removexattr(file string, attr string) (err error) { - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - err = ExtattrDeleteFile(file, nsid, a) - return -} - -func Fremovexattr(fd int, attr string) (err error) { - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - err = ExtattrDeleteFd(fd, nsid, a) - return -} - -func Lremovexattr(link string, attr string) (err error) { - nsid, a, err := xattrnamespace(attr) - if err != nil { - return - } - - err = ExtattrDeleteLink(link, nsid, a) - return -} - -func Listxattr(file string, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsiz := len(dest) - - // FreeBSD won't allow you to list xattrs from multiple namespaces - s := 0 - var e error - for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { - stmp, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) - - /* Errors accessing system attrs are ignored so that - * we can implement the Linux-like behavior of omitting errors that - * we don't have read permissions on - * - * Linux will still error if we ask for user attributes on a file that - * we don't have read permissions on, so don't ignore those errors - */ - if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil - continue - } else if e != nil { - return s, e - } - - s += stmp - destsiz -= s - if destsiz < 0 { - destsiz = 0 - } - d = initxattrdest(dest, s) - } - - return s, e -} - -func Flistxattr(fd int, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsiz := len(dest) - - s := 0 - var e error - for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { - stmp, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) - if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil - continue - } else if e != nil { - return s, e - } - - s += stmp - destsiz -= s - if destsiz < 0 { - destsiz = 0 - } - d = initxattrdest(dest, s) - } - - return s, e -} - -func Llistxattr(link string, dest []byte) (sz int, err error) { - d := initxattrdest(dest, 0) - destsiz := len(dest) - - s := 0 - var e error - for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { - stmp, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) - if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil - continue - } else if e != nil { - return s, e - } - - s += stmp - destsiz -= s - if destsiz < 0 { - destsiz = 0 - } - d = initxattrdest(dest, s) - } - - return s, e -} - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chflags(path string, flags int) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(from int, to int) (err error) -//sys Exit(code int) -//sys ExtattrGetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrSetFd(fd int, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrDeleteFd(fd int, attrnamespace int, attrname string) (err error) -//sys ExtattrListFd(fd int, attrnamespace int, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrGetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrSetFile(file string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrDeleteFile(file string, attrnamespace int, attrname string) (err error) -//sys ExtattrListFile(file string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrGetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) -//sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) -//sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) -//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE -//sys Fchdir(fd int) (err error) -//sys Fchflags(fd int, flags int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatfs(fd int, stat *Statfs_t) (err error) -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) -//sys Getdtablesize() (size int) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) -//sysnb Getgid() (gid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgrp int) -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Getsid(pid int) (sid int, err error) -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Getuid() (uid int) -//sys Issetugid() (tainted bool) -//sys Kill(pid int, signum syscall.Signal) (err error) -//sys Kqueue() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Revoke(path string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK -//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) -//sysnb Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sys Setlogin(name string) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tp *Timeval) (err error) -//sysnb Setuid(uid int) (err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Statfs(path string, stat *Statfs_t) (err error) -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sys Truncate(path string, length int64) (err error) -//sys Umask(newmask int) (oldmask int) -//sys Undelete(path string) (err error) -//sys Unlink(path string) (err error) -//sys Unmount(path string, flags int) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ -//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE -//sys accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) - -/* - * Unimplemented - */ -// Profil -// Sigaction -// Sigprocmask -// Getlogin -// Sigpending -// Sigaltstack -// Ioctl -// Reboot -// Execve -// Vfork -// Sbrk -// Sstk -// Ovadvise -// Mincore -// Setitimer -// Swapon -// Select -// Sigsuspend -// Readv -// Writev -// Nfssvc -// Getfh -// Quotactl -// Mount -// Csops -// Waitid -// Add_profil -// Kdebug_trace -// Sigreturn -// Mmap -// Mlock -// Munlock -// Atsocket -// Kqueue_from_portset_np -// Kqueue_portset -// Getattrlist -// Setattrlist -// Getdirentriesattr -// Searchfs -// Delete -// Copyfile -// Poll -// Watchevent -// Waitevent -// Modwatch -// Getxattr -// Fgetxattr -// Setxattr -// Fsetxattr -// Removexattr -// Fremovexattr -// Listxattr -// Flistxattr -// Fsctl -// Initgroups -// Posix_spawn -// Nfsclnt -// Fhopen -// Minherit -// Semsys -// Msgsys -// Shmsys -// Semctl -// Semget -// Semop -// Msgctl -// Msgget -// Msgsnd -// Msgrcv -// Shmat -// Shmctl -// Shmdt -// Shmget -// Shm_open -// Shm_unlink -// Sem_open -// Sem_close -// Sem_unlink -// Sem_wait -// Sem_trywait -// Sem_post -// Sem_getvalue -// Sem_init -// Sem_destroy -// Open_extended -// Umask_extended -// Stat_extended -// Lstat_extended -// Fstat_extended -// Chmod_extended -// Fchmod_extended -// Access_extended -// Settid -// Gettid -// Setsgroups -// Getsgroups -// Setwgroups -// Getwgroups -// Mkfifo_extended -// Mkdir_extended -// Identitysvc -// Shared_region_check_np -// Shared_region_map_np -// __pthread_mutex_destroy -// __pthread_mutex_init -// __pthread_mutex_lock -// __pthread_mutex_trylock -// __pthread_mutex_unlock -// __pthread_cond_init -// __pthread_cond_destroy -// __pthread_cond_broadcast -// __pthread_cond_signal -// Setsid_with_pid -// __pthread_cond_timedwait -// Aio_fsync -// Aio_return -// Aio_suspend -// Aio_cancel -// Aio_error -// Aio_read -// Aio_write -// Lio_listio -// __pthread_cond_wait -// Iopolicysys -// Mlockall -// Munlockall -// __pthread_kill -// __pthread_sigmask -// __sigwait -// __disable_threadsignal -// __pthread_markcancel -// __pthread_canceled -// __semwait_signal -// Proc_info -// Stat64_extended -// Lstat64_extended -// Fstat64_extended -// __pthread_chdir -// __pthread_fchdir -// Audit -// Auditon -// Getauid -// Setauid -// Getaudit -// Setaudit -// Getaudit_addr -// Setaudit_addr -// Auditctl -// Bsdthread_create -// Bsdthread_terminate -// Stack_snapshot -// Bsdthread_register -// Workq_open -// Workq_ops -// __mac_execve -// __mac_syscall -// __mac_get_file -// __mac_set_file -// __mac_get_link -// __mac_set_link -// __mac_get_proc -// __mac_set_proc -// __mac_get_fd -// __mac_set_fd -// __mac_get_pid -// __mac_get_lcid -// __mac_get_lctx -// __mac_set_lctx -// Setlcid -// Read_nocancel -// Write_nocancel -// Open_nocancel -// Close_nocancel -// Wait4_nocancel -// Recvmsg_nocancel -// Sendmsg_nocancel -// Recvfrom_nocancel -// Accept_nocancel -// Msync_nocancel -// Fcntl_nocancel -// Select_nocancel -// Fsync_nocancel -// Connect_nocancel -// Sigsuspend_nocancel -// Readv_nocancel -// Writev_nocancel -// Sendto_nocancel -// Pread_nocancel -// Pwrite_nocancel -// Waitid_nocancel -// Poll_nocancel -// Msgsnd_nocancel -// Msgrcv_nocancel -// Sem_wait_nocancel -// Aio_suspend_nocancel -// __sigwait_nocancel -// __semwait_signal_nocancel -// __mac_mount -// __mac_get_mount -// __mac_getfsstat diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_386.go deleted file mode 100644 index 6255d40ff..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_386.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386,freebsd - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int32(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var writtenOut uint64 = 0 - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) - - written = int(writtenOut) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_arm.go deleted file mode 100644 index 4e72d46a8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_arm.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm,freebsd - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return ts.Sec*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return tv.Sec*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = nsec / 1e9 - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - var writtenOut uint64 = 0 - _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) - - written = int(writtenOut) - - if e1 != 0 { - err = e1 - } - return -} - -func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux.go deleted file mode 100644 index d3ee5d2c2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux.go +++ /dev/null @@ -1,1086 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Linux system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and -// wrap it in our own nicer implementation. - -package unix - -import ( - "syscall" - "unsafe" -) - -/* - * Wrapped - */ - -func Access(path string, mode uint32) (err error) { - return Faccessat(AT_FDCWD, path, mode, 0) -} - -func Chmod(path string, mode uint32) (err error) { - return Fchmodat(AT_FDCWD, path, mode, 0) -} - -func Chown(path string, uid int, gid int) (err error) { - return Fchownat(AT_FDCWD, path, uid, gid, 0) -} - -func Creat(path string, mode uint32) (fd int, err error) { - return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode) -} - -//sys linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) - -func Link(oldpath string, newpath string) (err error) { - return linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0) -} - -func Mkdir(path string, mode uint32) (err error) { - return Mkdirat(AT_FDCWD, path, mode) -} - -func Mknod(path string, mode uint32, dev int) (err error) { - return Mknodat(AT_FDCWD, path, mode, dev) -} - -func Open(path string, mode int, perm uint32) (fd int, err error) { - return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm) -} - -//sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) - -func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - return openat(dirfd, path, flags|O_LARGEFILE, mode) -} - -//sys readlinkat(dirfd int, path string, buf []byte) (n int, err error) - -func Readlink(path string, buf []byte) (n int, err error) { - return readlinkat(AT_FDCWD, path, buf) -} - -func Rename(oldpath string, newpath string) (err error) { - return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath) -} - -func Rmdir(path string) error { - return unlinkat(AT_FDCWD, path, AT_REMOVEDIR) -} - -//sys symlinkat(oldpath string, newdirfd int, newpath string) (err error) - -func Symlink(oldpath string, newpath string) (err error) { - return symlinkat(oldpath, AT_FDCWD, newpath) -} - -func Unlink(path string) error { - return unlinkat(AT_FDCWD, path, 0) -} - -//sys unlinkat(dirfd int, path string, flags int) (err error) - -func Unlinkat(dirfd int, path string) error { - return unlinkat(dirfd, path, 0) -} - -//sys utimes(path string, times *[2]Timeval) (err error) - -func Utimes(path string, tv []Timeval) (err error) { - if tv == nil { - return utimes(path, nil) - } - if len(tv) != 2 { - return EINVAL - } - return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) - -func UtimesNano(path string, ts []Timespec) error { - if ts == nil { - err := utimensat(AT_FDCWD, path, nil, 0) - if err != ENOSYS { - return err - } - return utimes(path, nil) - } - if len(ts) != 2 { - return EINVAL - } - err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) - if err != ENOSYS { - return err - } - // If the utimensat syscall isn't available (utimensat was added to Linux - // in 2.6.22, Released, 8 July 2007) then fall back to utimes - var tv [2]Timeval - for i := 0; i < 2; i++ { - tv[i].Sec = ts[i].Sec - tv[i].Usec = ts[i].Nsec / 1000 - } - return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { - if ts == nil { - return utimensat(dirfd, path, nil, flags) - } - if len(ts) != 2 { - return EINVAL - } - return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) -} - -//sys futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) - -func Futimesat(dirfd int, path string, tv []Timeval) error { - pathp, err := BytePtrFromString(path) - if err != nil { - return err - } - if tv == nil { - return futimesat(dirfd, pathp, nil) - } - if len(tv) != 2 { - return EINVAL - } - return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -func Futimes(fd int, tv []Timeval) (err error) { - // Believe it or not, this is the best we can do on Linux - // (and is what glibc does). - return Utimes("/proc/self/fd/"+itoa(fd), tv) -} - -const ImplementsGetwd = true - -//sys Getcwd(buf []byte) (n int, err error) - -func Getwd() (wd string, err error) { - var buf [PathMax]byte - n, err := Getcwd(buf[0:]) - if err != nil { - return "", err - } - // Getcwd returns the number of bytes written to buf, including the NUL. - if n < 1 || n > len(buf) || buf[n-1] != 0 { - return "", EINVAL - } - return string(buf[0 : n-1]), nil -} - -func Getgroups() (gids []int, err error) { - n, err := getgroups(0, nil) - if err != nil { - return nil, err - } - if n == 0 { - return nil, nil - } - - // Sanity check group count. Max is 1<<16 on Linux. - if n < 0 || n > 1<<20 { - return nil, EINVAL - } - - a := make([]_Gid_t, n) - n, err = getgroups(n, &a[0]) - if err != nil { - return nil, err - } - gids = make([]int, n) - for i, v := range a[0:n] { - gids[i] = int(v) - } - return -} - -func Setgroups(gids []int) (err error) { - if len(gids) == 0 { - return setgroups(0, nil) - } - - a := make([]_Gid_t, len(gids)) - for i, v := range gids { - a[i] = _Gid_t(v) - } - return setgroups(len(a), &a[0]) -} - -type WaitStatus uint32 - -// Wait status is 7 bits at bottom, either 0 (exited), -// 0x7F (stopped), or a signal number that caused an exit. -// The 0x80 bit is whether there was a core dump. -// An extra number (exit code, signal causing a stop) -// is in the high bits. At least that's the idea. -// There are various irregularities. For example, the -// "continued" status is 0xFFFF, distinguishing itself -// from stopped via the core dump bit. - -const ( - mask = 0x7F - core = 0x80 - exited = 0x00 - stopped = 0x7F - shift = 8 -) - -func (w WaitStatus) Exited() bool { return w&mask == exited } - -func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited } - -func (w WaitStatus) Stopped() bool { return w&0xFF == stopped } - -func (w WaitStatus) Continued() bool { return w == 0xFFFF } - -func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } - -func (w WaitStatus) ExitStatus() int { - if !w.Exited() { - return -1 - } - return int(w>>shift) & 0xFF -} - -func (w WaitStatus) Signal() syscall.Signal { - if !w.Signaled() { - return -1 - } - return syscall.Signal(w & mask) -} - -func (w WaitStatus) StopSignal() syscall.Signal { - if !w.Stopped() { - return -1 - } - return syscall.Signal(w>>shift) & 0xFF -} - -func (w WaitStatus) TrapCause() int { - if w.StopSignal() != SIGTRAP { - return -1 - } - return int(w>>shift) >> 8 -} - -//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) - -func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { - var status _C_int - wpid, err = wait4(pid, &status, options, rusage) - if wstatus != nil { - *wstatus = WaitStatus(status) - } - return -} - -func Mkfifo(path string, mode uint32) (err error) { - return Mknod(path, mode|S_IFIFO, 0) -} - -func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Family = AF_INET - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil -} - -func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Family = AF_INET6 - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - sa.raw.Scope_id = sa.ZoneId - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil -} - -func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { - name := sa.Name - n := len(name) - if n >= len(sa.raw.Path) { - return nil, 0, EINVAL - } - sa.raw.Family = AF_UNIX - for i := 0; i < n; i++ { - sa.raw.Path[i] = int8(name[i]) - } - // length is family (uint16), name, NUL. - sl := _Socklen(2) - if n > 0 { - sl += _Socklen(n) + 1 - } - if sa.raw.Path[0] == '@' { - sa.raw.Path[0] = 0 - // Don't count trailing NUL for abstract address. - sl-- - } - - return unsafe.Pointer(&sa.raw), sl, nil -} - -type SockaddrLinklayer struct { - Protocol uint16 - Ifindex int - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]byte - raw RawSockaddrLinklayer -} - -func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff { - return nil, 0, EINVAL - } - sa.raw.Family = AF_PACKET - sa.raw.Protocol = sa.Protocol - sa.raw.Ifindex = int32(sa.Ifindex) - sa.raw.Hatype = sa.Hatype - sa.raw.Pkttype = sa.Pkttype - sa.raw.Halen = sa.Halen - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil -} - -type SockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 - raw RawSockaddrNetlink -} - -func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) { - sa.raw.Family = AF_NETLINK - sa.raw.Pad = sa.Pad - sa.raw.Pid = sa.Pid - sa.raw.Groups = sa.Groups - return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil -} - -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { - switch rsa.Addr.Family { - case AF_NETLINK: - pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa)) - sa := new(SockaddrNetlink) - sa.Family = pp.Family - sa.Pad = pp.Pad - sa.Pid = pp.Pid - sa.Groups = pp.Groups - return sa, nil - - case AF_PACKET: - pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa)) - sa := new(SockaddrLinklayer) - sa.Protocol = pp.Protocol - sa.Ifindex = int(pp.Ifindex) - sa.Hatype = pp.Hatype - sa.Pkttype = pp.Pkttype - sa.Halen = pp.Halen - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - - case AF_UNIX: - pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) - sa := new(SockaddrUnix) - if pp.Path[0] == 0 { - // "Abstract" Unix domain socket. - // Rewrite leading NUL as @ for textual display. - // (This is the standard convention.) - // Not friendly to overwrite in place, - // but the callers below don't care. - pp.Path[0] = '@' - } - - // Assume path ends at NUL. - // This is not technically the Linux semantics for - // abstract Unix domain sockets--they are supposed - // to be uninterpreted fixed-size binary blobs--but - // everyone uses this convention. - n := 0 - for n < len(pp.Path) && pp.Path[n] != 0 { - n++ - } - bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] - sa.Name = string(bytes) - return sa, nil - - case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - - case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - } - return nil, EAFNOSUPPORT -} - -func Accept(fd int) (nfd int, sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - nfd, err = accept(fd, &rsa, &len) - if err != nil { - return - } - sa, err = anyToSockaddr(&rsa) - if err != nil { - Close(nfd) - nfd = 0 - } - return -} - -func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - nfd, err = accept4(fd, &rsa, &len, flags) - if err != nil { - return - } - if len > SizeofSockaddrAny { - panic("RawSockaddrAny too small") - } - sa, err = anyToSockaddr(&rsa) - if err != nil { - Close(nfd) - nfd = 0 - } - return -} - -func Getsockname(fd int) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - if err = getsockname(fd, &rsa, &len); err != nil { - return - } - return anyToSockaddr(&rsa) -} - -func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { - vallen := _Socklen(4) - err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) - return value, err -} - -func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { - var value IPMreq - vallen := _Socklen(SizeofIPMreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { - var value IPMreqn - vallen := _Socklen(SizeofIPMreqn) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { - var value IPv6Mreq - vallen := _Socklen(SizeofIPv6Mreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { - var value IPv6MTUInfo - vallen := _Socklen(SizeofIPv6MTUInfo) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { - var value ICMPv6Filter - vallen := _Socklen(SizeofICMPv6Filter) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptUcred(fd, level, opt int) (*Ucred, error) { - var value Ucred - vallen := _Socklen(SizeofUcred) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) -} - -func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { - var msg Msghdr - var rsa RawSockaddrAny - msg.Name = (*byte)(unsafe.Pointer(&rsa)) - msg.Namelen = uint32(SizeofSockaddrAny) - var iov Iovec - if len(p) > 0 { - iov.Base = (*byte)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy byte - if len(oob) > 0 { - // receive at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Control = (*byte)(unsafe.Pointer(&oob[0])) - msg.SetControllen(len(oob)) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = recvmsg(fd, &msg, flags); err != nil { - return - } - oobn = int(msg.Controllen) - recvflags = int(msg.Flags) - // source address is only specified if the socket is unconnected - if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) - } - return -} - -func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { - _, err = SendmsgN(fd, p, oob, to, flags) - return -} - -func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { - var ptr unsafe.Pointer - var salen _Socklen - if to != nil { - var err error - ptr, salen, err = to.sockaddr() - if err != nil { - return 0, err - } - } - var msg Msghdr - msg.Name = (*byte)(unsafe.Pointer(ptr)) - msg.Namelen = uint32(salen) - var iov Iovec - if len(p) > 0 { - iov.Base = (*byte)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy byte - if len(oob) > 0 { - // send at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Control = (*byte)(unsafe.Pointer(&oob[0])) - msg.SetControllen(len(oob)) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = sendmsg(fd, &msg, flags); err != nil { - return 0, err - } - if len(oob) > 0 && len(p) == 0 { - n = 0 - } - return n, nil -} - -// BindToDevice binds the socket associated with fd to device. -func BindToDevice(fd int, device string) (err error) { - return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device) -} - -//sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) - -func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) { - // The peek requests are machine-size oriented, so we wrap it - // to retrieve arbitrary-length data. - - // The ptrace syscall differs from glibc's ptrace. - // Peeks returns the word in *data, not as the return value. - - var buf [sizeofPtr]byte - - // Leading edge. PEEKTEXT/PEEKDATA don't require aligned - // access (PEEKUSER warns that it might), but if we don't - // align our reads, we might straddle an unmapped page - // boundary and not get the bytes leading up to the page - // boundary. - n := 0 - if addr%sizeofPtr != 0 { - err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))) - if err != nil { - return 0, err - } - n += copy(out, buf[addr%sizeofPtr:]) - out = out[n:] - } - - // Remainder. - for len(out) > 0 { - // We use an internal buffer to guarantee alignment. - // It's not documented if this is necessary, but we're paranoid. - err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0]))) - if err != nil { - return n, err - } - copied := copy(out, buf[0:]) - n += copied - out = out[copied:] - } - - return n, nil -} - -func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { - return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out) -} - -func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { - return ptracePeek(PTRACE_PEEKDATA, pid, addr, out) -} - -func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) { - // As for ptracePeek, we need to align our accesses to deal - // with the possibility of straddling an invalid page. - - // Leading edge. - n := 0 - if addr%sizeofPtr != 0 { - var buf [sizeofPtr]byte - err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0]))) - if err != nil { - return 0, err - } - n += copy(buf[addr%sizeofPtr:], data) - word := *((*uintptr)(unsafe.Pointer(&buf[0]))) - err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word) - if err != nil { - return 0, err - } - data = data[n:] - } - - // Interior. - for len(data) > sizeofPtr { - word := *((*uintptr)(unsafe.Pointer(&data[0]))) - err = ptrace(pokeReq, pid, addr+uintptr(n), word) - if err != nil { - return n, err - } - n += sizeofPtr - data = data[sizeofPtr:] - } - - // Trailing edge. - if len(data) > 0 { - var buf [sizeofPtr]byte - err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0]))) - if err != nil { - return n, err - } - copy(buf[0:], data) - word := *((*uintptr)(unsafe.Pointer(&buf[0]))) - err = ptrace(pokeReq, pid, addr+uintptr(n), word) - if err != nil { - return n, err - } - n += len(data) - } - - return n, nil -} - -func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { - return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data) -} - -func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { - return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data) -} - -func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) { - return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout))) -} - -func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) { - return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs))) -} - -func PtraceSetOptions(pid int, options int) (err error) { - return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options)) -} - -func PtraceGetEventMsg(pid int) (msg uint, err error) { - var data _C_long - err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data))) - msg = uint(data) - return -} - -func PtraceCont(pid int, signal int) (err error) { - return ptrace(PTRACE_CONT, pid, 0, uintptr(signal)) -} - -func PtraceSyscall(pid int, signal int) (err error) { - return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal)) -} - -func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) } - -func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) } - -func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) } - -//sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) - -func Reboot(cmd int) (err error) { - return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "") -} - -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} - -func ReadDirent(fd int, buf []byte) (n int, err error) { - return Getdents(fd, buf) -} - -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - count = 0 - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:clen(bytes[:])]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) - -func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { - // Certain file systems get rather angry and EINVAL if you give - // them an empty string of data, rather than NULL. - if data == "" { - return mount(source, target, fstype, flags, nil) - } - datap, err := BytePtrFromString(data) - if err != nil { - return err - } - return mount(source, target, fstype, flags, datap) -} - -// Sendto -// Recvfrom -// Socketpair - -/* - * Direct access - */ -//sys Acct(path string) (err error) -//sys Adjtimex(buf *Timex) (state int, err error) -//sys Chdir(path string) (err error) -//sys Chroot(path string) (err error) -//sys ClockGettime(clockid int32, time *Timespec) (err error) -//sys Close(fd int) (err error) -//sys Dup(oldfd int) (fd int, err error) -//sys Dup3(oldfd int, newfd int, flags int) (err error) -//sysnb EpollCreate(size int) (fd int, err error) -//sysnb EpollCreate1(flag int) (fd int, err error) -//sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) -//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) -//sys Exit(code int) = SYS_EXIT_GROUP -//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) -//sys Fallocate(fd int, mode uint32, off int64, len int64) (err error) -//sys Fchdir(fd int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) -//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) -//sys fcntl(fd int, cmd int, arg int) (val int, err error) -//sys Fdatasync(fd int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fsync(fd int) (err error) -//sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 -//sysnb Getpgid(pid int) (pgid int, err error) - -func Getpgrp() (pid int) { - pid, _ = Getpgid(0) - return -} - -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Gettid() (tid int) -//sys Getxattr(path string, attr string, dest []byte) (sz int, err error) -//sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) -//sysnb InotifyInit1(flags int) (fd int, err error) -//sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) -//sysnb Kill(pid int, sig syscall.Signal) (err error) -//sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG -//sys Listxattr(path string, dest []byte) (sz int, err error) -//sys Mkdirat(dirfd int, path string, mode uint32) (err error) -//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Pause() (err error) -//sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT -//sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64 -//sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Removexattr(path string, attr string) (err error) -//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) -//sys Setdomainname(p []byte) (err error) -//sys Sethostname(p []byte) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tv *Timeval) (err error) - -// issue 1435. -// On linux Setuid and Setgid only affects the current thread, not the process. -// This does not match what most callers expect so we must return an error -// here rather than letting the caller think that the call succeeded. - -func Setuid(uid int) (err error) { - return EOPNOTSUPP -} - -func Setgid(uid int) (err error) { - return EOPNOTSUPP -} - -//sys Setpriority(which int, who int, prio int) (err error) -//sys Setxattr(path string, attr string, data []byte, flags int) (err error) -//sys Sync() -//sysnb Sysinfo(info *Sysinfo_t) (err error) -//sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error) -//sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error) -//sysnb Times(tms *Tms) (ticks uintptr, err error) -//sysnb Umask(mask int) (oldmask int) -//sysnb Uname(buf *Utsname) (err error) -//sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2 -//sys Unshare(flags int) (err error) -//sys Ustat(dev int, ubuf *Ustat_t) (err error) -//sys Utime(path string, buf *Utimbuf) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys exitThread(code int) (err error) = SYS_EXIT -//sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ -//sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE - -// mmap varies by architecture; see syscall_linux_*.go. -//sys munmap(addr uintptr, length uintptr) (err error) - -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - -//sys Madvise(b []byte, advice int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Mlock(b []byte) (err error) -//sys Munlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Munlockall() (err error) - -/* - * Unimplemented - */ -// AddKey -// AfsSyscall -// Alarm -// ArchPrctl -// Brk -// Capget -// Capset -// ClockGetres -// ClockNanosleep -// ClockSettime -// Clone -// CreateModule -// DeleteModule -// EpollCtlOld -// EpollPwait -// EpollWaitOld -// Eventfd -// Execve -// Fgetxattr -// Flistxattr -// Fork -// Fremovexattr -// Fsetxattr -// Futex -// GetKernelSyms -// GetMempolicy -// GetRobustList -// GetThreadArea -// Getitimer -// Getpmsg -// IoCancel -// IoDestroy -// IoGetevents -// IoSetup -// IoSubmit -// Ioctl -// IoprioGet -// IoprioSet -// KexecLoad -// Keyctl -// Lgetxattr -// Llistxattr -// LookupDcookie -// Lremovexattr -// Lsetxattr -// Mbind -// MigratePages -// Mincore -// ModifyLdt -// Mount -// MovePages -// Mprotect -// MqGetsetattr -// MqNotify -// MqOpen -// MqTimedreceive -// MqTimedsend -// MqUnlink -// Mremap -// Msgctl -// Msgget -// Msgrcv -// Msgsnd -// Msync -// Newfstatat -// Nfsservctl -// Personality -// Poll -// Ppoll -// Pselect6 -// Ptrace -// Putpmsg -// QueryModule -// Quotactl -// Readahead -// Readv -// RemapFilePages -// RequestKey -// RestartSyscall -// RtSigaction -// RtSigpending -// RtSigprocmask -// RtSigqueueinfo -// RtSigreturn -// RtSigsuspend -// RtSigtimedwait -// SchedGetPriorityMax -// SchedGetPriorityMin -// SchedGetaffinity -// SchedGetparam -// SchedGetscheduler -// SchedRrGetInterval -// SchedSetaffinity -// SchedSetparam -// SchedYield -// Security -// Semctl -// Semget -// Semop -// Semtimedop -// SetMempolicy -// SetRobustList -// SetThreadArea -// SetTidAddress -// Shmat -// Shmctl -// Shmdt -// Shmget -// Sigaltstack -// Signalfd -// Swapoff -// Swapon -// Sysfs -// TimerCreate -// TimerDelete -// TimerGetoverrun -// TimerGettime -// TimerSettime -// Timerfd -// Tkill (obsolete) -// Tuxcall -// Umount2 -// Uselib -// Utimensat -// Vfork -// Vhangup -// Vmsplice -// Vserver -// Waitid -// _Sysctl diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_386.go deleted file mode 100644 index 7171219af..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_386.go +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TODO(rsc): Rewrite all nn(SP) references into name+(nn-8)(FP) -// so that go vet can check that they are correct. - -// +build 386,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Sec = int32(nsec / 1e9) - tv.Usec = int32(nsec % 1e9 / 1e3) - return -} - -//sysnb pipe(p *[2]_C_int) (err error) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe(&pp) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -//sysnb pipe2(p *[2]_C_int, flags int) (err error) - -func Pipe2(p []int, flags int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, flags) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -// 64-bit file system and 32-bit uid calls -// (386 default is 32-bit file system and 16-bit uid). -//sys Dup2(oldfd int, newfd int) (err error) -//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 -//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 -//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 -//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 -//sysnb Getegid() (egid int) = SYS_GETEGID32 -//sysnb Geteuid() (euid int) = SYS_GETEUID32 -//sysnb Getgid() (gid int) = SYS_GETGID32 -//sysnb Getuid() (uid int) = SYS_GETUID32 -//sysnb InotifyInit() (fd int, err error) -//sys Ioperm(from int, num int, on int) (err error) -//sys Iopl(level int) (err error) -//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32 -//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 -//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 -//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 -//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32 -//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32 -//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32 -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32 -//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32 -//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32 -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) -//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 -//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) -//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 -//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32 -//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32 -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT - -//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - page := uintptr(offset / 4096) - if offset != int64(page)*4096 { - return 0, EINVAL - } - return mmap2(addr, length, prot, flags, fd, page) -} - -type rlimit32 struct { - Cur uint32 - Max uint32 -} - -//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT - -const rlimInf32 = ^uint32(0) -const rlimInf64 = ^uint64(0) - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - err = prlimit(0, resource, nil, rlim) - if err != ENOSYS { - return err - } - - rl := rlimit32{} - err = getrlimit(resource, &rl) - if err != nil { - return - } - - if rl.Cur == rlimInf32 { - rlim.Cur = rlimInf64 - } else { - rlim.Cur = uint64(rl.Cur) - } - - if rl.Max == rlimInf32 { - rlim.Max = rlimInf64 - } else { - rlim.Max = uint64(rl.Max) - } - return -} - -//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - err = prlimit(0, resource, rlim, nil) - if err != ENOSYS { - return err - } - - rl := rlimit32{} - if rlim.Cur == rlimInf64 { - rl.Cur = rlimInf32 - } else if rlim.Cur < uint64(rlimInf32) { - rl.Cur = uint32(rlim.Cur) - } else { - return EINVAL - } - if rlim.Max == rlimInf64 { - rl.Max = rlimInf32 - } else if rlim.Max < uint64(rlimInf32) { - rl.Max = uint32(rlim.Max) - } else { - return EINVAL - } - - return setrlimit(resource, &rl) -} - -// Underlying system call writes to newoffset via pointer. -// Implemented in assembly to avoid allocation. -func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - newoffset, errno := seek(fd, offset, whence) - if errno != 0 { - return 0, errno - } - return newoffset, nil -} - -// Vsyscalls on amd64. -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Time(t *Time_t) (tt Time_t, err error) - -// On x86 Linux, all the socket calls go through an extra indirection, -// I think because the 5-register system call interface can't handle -// the 6-argument calls like sendto and recvfrom. Instead the -// arguments to the underlying system call are the number below -// and a pointer to an array of uintptr. We hide the pointer in the -// socketcall assembly to avoid allocation on every system call. - -const ( - // see linux/net.h - _SOCKET = 1 - _BIND = 2 - _CONNECT = 3 - _LISTEN = 4 - _ACCEPT = 5 - _GETSOCKNAME = 6 - _GETPEERNAME = 7 - _SOCKETPAIR = 8 - _SEND = 9 - _RECV = 10 - _SENDTO = 11 - _RECVFROM = 12 - _SHUTDOWN = 13 - _SETSOCKOPT = 14 - _GETSOCKOPT = 15 - _SENDMSG = 16 - _RECVMSG = 17 - _ACCEPT4 = 18 - _RECVMMSG = 19 - _SENDMMSG = 20 -) - -func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno) -func rawsocketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno) - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - fd, e := socketcall(_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - fd, e := socketcall(_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - if e != 0 { - err = e - } - return -} - -func getsockname(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, e := rawsocketcall(_GETSOCKNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func getpeername(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, e := rawsocketcall(_GETPEERNAME, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) { - _, e := rawsocketcall(_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0) - if e != 0 { - err = e - } - return -} - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, e := socketcall(_BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, e := socketcall(_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func socket(domain int, typ int, proto int) (fd int, err error) { - fd, e := rawsocketcall(_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, e := socketcall(_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e != 0 { - err = e - } - return -} - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, e := socketcall(_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0) - if e != 0 { - err = e - } - return -} - -func recvfrom(s int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var base uintptr - if len(p) > 0 { - base = uintptr(unsafe.Pointer(&p[0])) - } - n, e := socketcall(_RECVFROM, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - if e != 0 { - err = e - } - return -} - -func sendto(s int, p []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var base uintptr - if len(p) > 0 { - base = uintptr(unsafe.Pointer(&p[0])) - } - _, e := socketcall(_SENDTO, uintptr(s), base, uintptr(len(p)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e != 0 { - err = e - } - return -} - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - n, e := socketcall(_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - n, e := socketcall(_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func Listen(s int, n int) (err error) { - _, e := socketcall(_LISTEN, uintptr(s), uintptr(n), 0, 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func Shutdown(s, how int) (err error) { - _, e := socketcall(_SHUTDOWN, uintptr(s), uintptr(how), 0, 0, 0, 0) - if e != 0 { - err = e - } - return -} - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) - if e != 0 { - err = e - } - return -} - -func Statfs(path string, buf *Statfs_t) (err error) { - pathp, err := BytePtrFromString(path) - if err != nil { - return err - } - _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) - if e != 0 { - err = e - } - return -} - -func (r *PtraceRegs) PC() uint64 { return uint64(uint32(r.Eip)) } - -func (r *PtraceRegs) SetPC(pc uint64) { r.Eip = int32(pc) } - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_amd64.go deleted file mode 100644 index ae70c2afc..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_amd64.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,linux - -package unix - -import "syscall" - -//sys Dup2(oldfd int, newfd int) (err error) -//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatfs(fd int, buf *Statfs_t) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (euid int) -//sysnb Getgid() (gid int) -//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) -//sysnb Getuid() (uid int) -//sysnb InotifyInit() (fd int, err error) -//sys Ioperm(from int, num int, on int) (err error) -//sys Iopl(level int) (err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Listen(s int, n int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 -//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) -//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) -//sys Setfsgid(gid int) (err error) -//sys Setfsuid(uid int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sys Shutdown(fd int, how int) (err error) -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Statfs(path string, buf *Statfs_t) (err error) -//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) -//sys Truncate(path string, length int64) (err error) -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) -//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) -//sysnb setgroups(n int, list *_Gid_t) (err error) -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) -//sysnb socket(domain int, typ int, proto int) (fd int, err error) -//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) - -//go:noescape -func gettimeofday(tv *Timeval) (err syscall.Errno) - -func Gettimeofday(tv *Timeval) (err error) { - errno := gettimeofday(tv) - if errno != 0 { - return errno - } - return nil -} - -func Getpagesize() int { return 4096 } - -func Time(t *Time_t) (tt Time_t, err error) { - var tv Timeval - errno := gettimeofday(&tv) - if errno != 0 { - return 0, errno - } - if t != nil { - *t = Time_t(tv.Sec) - } - return Time_t(tv.Sec), nil -} - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Sec = nsec / 1e9 - tv.Usec = nsec % 1e9 / 1e3 - return -} - -//sysnb pipe(p *[2]_C_int) (err error) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe(&pp) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -//sysnb pipe2(p *[2]_C_int, flags int) (err error) - -func Pipe2(p []int, flags int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, flags) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -func (r *PtraceRegs) PC() uint64 { return r.Rip } - -func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc } - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint64(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint64(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm.go deleted file mode 100644 index abc41c3ea..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int32(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Sec = int32(nsec / 1e9) - tv.Usec = int32(nsec % 1e9 / 1e3) - return -} - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, 0) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -//sysnb pipe2(p *[2]_C_int, flags int) (err error) - -func Pipe2(p []int, flags int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, flags) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -// Underlying system call writes to newoffset via pointer. -// Implemented in assembly to avoid allocation. -func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - newoffset, errno := seek(fd, offset, whence) - if errno != 0 { - return 0, errno - } - return newoffset, nil -} - -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) -//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) = SYS_GETGROUPS32 -//sysnb setgroups(n int, list *_Gid_t) (err error) = SYS_SETGROUPS32 -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) -//sysnb socket(domain int, typ int, proto int) (fd int, err error) -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) - -// 64-bit file system and 32-bit uid calls -// (16-bit uid calls are not always supported in newer kernels) -//sys Dup2(oldfd int, newfd int) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 -//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 -//sysnb Getegid() (egid int) = SYS_GETEGID32 -//sysnb Geteuid() (euid int) = SYS_GETEUID32 -//sysnb Getgid() (gid int) = SYS_GETGID32 -//sysnb Getuid() (uid int) = SYS_GETUID32 -//sysnb InotifyInit() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) = SYS_LCHOWN32 -//sys Listen(s int, n int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 -//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT -//sys Setfsgid(gid int) (err error) = SYS_SETFSGID32 -//sys Setfsuid(uid int) (err error) = SYS_SETFSUID32 -//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32 -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32 -//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32 -//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32 -//sys Shutdown(fd int, how int) (err error) -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) -//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 - -// Vsyscalls on amd64. -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Time(t *Time_t) (tt Time_t, err error) - -//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 -//sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 -//sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 - -func Fadvise(fd int, offset int64, length int64, advice int) (err error) { - _, _, e1 := Syscall6(SYS_ARM_FADVISE64_64, uintptr(fd), uintptr(advice), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -//sys mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e := Syscall(SYS_FSTATFS64, uintptr(fd), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) - if e != 0 { - err = e - } - return -} - -func Statfs(path string, buf *Statfs_t) (err error) { - pathp, err := BytePtrFromString(path) - if err != nil { - return err - } - _, _, e := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(pathp)), unsafe.Sizeof(*buf), uintptr(unsafe.Pointer(buf))) - if e != 0 { - err = e - } - return -} - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - page := uintptr(offset / 4096) - if offset != int64(page)*4096 { - return 0, EINVAL - } - return mmap2(addr, length, prot, flags, fd, page) -} - -type rlimit32 struct { - Cur uint32 - Max uint32 -} - -//sysnb getrlimit(resource int, rlim *rlimit32) (err error) = SYS_GETRLIMIT - -const rlimInf32 = ^uint32(0) -const rlimInf64 = ^uint64(0) - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - err = prlimit(0, resource, nil, rlim) - if err != ENOSYS { - return err - } - - rl := rlimit32{} - err = getrlimit(resource, &rl) - if err != nil { - return - } - - if rl.Cur == rlimInf32 { - rlim.Cur = rlimInf64 - } else { - rlim.Cur = uint64(rl.Cur) - } - - if rl.Max == rlimInf32 { - rlim.Max = rlimInf64 - } else { - rlim.Max = uint64(rl.Max) - } - return -} - -//sysnb setrlimit(resource int, rlim *rlimit32) (err error) = SYS_SETRLIMIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - err = prlimit(0, resource, rlim, nil) - if err != ENOSYS { - return err - } - - rl := rlimit32{} - if rlim.Cur == rlimInf64 { - rl.Cur = rlimInf32 - } else if rlim.Cur < uint64(rlimInf32) { - rl.Cur = uint32(rlim.Cur) - } else { - return EINVAL - } - if rlim.Max == rlimInf64 { - rl.Max = rlimInf32 - } else if rlim.Max < uint64(rlimInf32) { - rl.Max = uint32(rlim.Max) - } else { - return EINVAL - } - - return setrlimit(resource, &rl) -} - -func (r *PtraceRegs) PC() uint64 { return uint64(r.Uregs[15]) } - -func (r *PtraceRegs) SetPC(pc uint64) { r.Uregs[15] = uint32(pc) } - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm64.go deleted file mode 100644 index f3d72dfd3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm64.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm64,linux - -package unix - -const _SYS_dup = SYS_DUP3 - -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) -//sys Fstatfs(fd int, buf *Statfs_t) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (euid int) -//sysnb Getgid() (gid int) -//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) -//sysnb Getuid() (uid int) -//sys Listen(s int, n int) (err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 -//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS_PSELECT6 -//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) -//sys Setfsgid(gid int) (err error) -//sys Setfsuid(uid int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sys Shutdown(fd int, how int) (err error) -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) - -func Stat(path string, stat *Stat_t) (err error) { - return Fstatat(AT_FDCWD, path, stat, 0) -} - -func Lchown(path string, uid int, gid int) (err error) { - return Fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW) -} - -func Lstat(path string, stat *Stat_t) (err error) { - return Fstatat(AT_FDCWD, path, stat, AT_SYMLINK_NOFOLLOW) -} - -//sys Statfs(path string, buf *Statfs_t) (err error) -//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) -//sys Truncate(path string, length int64) (err error) -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) -//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) -//sysnb setgroups(n int, list *_Gid_t) (err error) -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) -//sysnb socket(domain int, typ int, proto int) (fd int, err error) -//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) - -func Getpagesize() int { return 65536 } - -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Time(t *Time_t) (tt Time_t, err error) - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Sec = nsec / 1e9 - tv.Usec = nsec % 1e9 / 1e3 - return -} - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, 0) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -//sysnb pipe2(p *[2]_C_int, flags int) (err error) - -func Pipe2(p []int, flags int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe2(&pp, flags) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -func (r *PtraceRegs) PC() uint64 { return r.Pc } - -func (r *PtraceRegs) SetPC(pc uint64) { r.Pc = pc } - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint64(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint64(length) -} - -func InotifyInit() (fd int, err error) { - return InotifyInit1(0) -} - -// TODO(dfc): constants that should be in zsysnum_linux_arm64.go, remove -// these when the deprecated syscalls that the syscall package relies on -// are removed. -const ( - SYS_GETPGRP = 1060 - SYS_UTIMES = 1037 - SYS_FUTIMESAT = 1066 - SYS_PAUSE = 1061 - SYS_USTAT = 1070 - SYS_UTIME = 1063 - SYS_LCHOWN = 1032 - SYS_TIME = 1062 - SYS_EPOLL_CREATE = 1042 - SYS_EPOLL_WAIT = 1069 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_ppc64x.go deleted file mode 100644 index 67eed6334..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux -// +build ppc64 ppc64le - -package unix - -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatfs(fd int, buf *Statfs_t) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (euid int) -//sysnb Getgid() (gid int) -//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) = SYS_UGETRLIMIT -//sysnb Getuid() (uid int) -//sys Ioperm(from int, num int, on int) (err error) -//sys Iopl(level int) (err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Listen(s int, n int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 -//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) -//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) -//sys Setfsgid(gid int) (err error) -//sys Setfsuid(uid int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sys Shutdown(fd int, how int) (err error) -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Statfs(path string, buf *Statfs_t) (err error) -//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) = SYS_SYNC_FILE_RANGE2 -//sys Truncate(path string, length int64) (err error) -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) -//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) -//sysnb getgroups(n int, list *_Gid_t) (nn int, err error) -//sysnb setgroups(n int, list *_Gid_t) (err error) -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) -//sysnb socket(domain int, typ int, proto int) (fd int, err error) -//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) - -func Getpagesize() int { return 65536 } - -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Time(t *Time_t) (tt Time_t, err error) - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Sec = nsec / 1e9 - tv.Usec = nsec % 1e9 / 1e3 - return -} - -func (r *PtraceRegs) PC() uint64 { return r.Nip } - -func (r *PtraceRegs) SetPC(pc uint64) { r.Nip = pc } - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint64(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint64(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd.go deleted file mode 100644 index c4e945cd6..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd.go +++ /dev/null @@ -1,492 +0,0 @@ -// Copyright 2009,2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// NetBSD system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_bsd.go or syscall_unix.go. - -package unix - -import ( - "syscall" - "unsafe" -) - -type SockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - raw RawSockaddrDatalink -} - -func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) - -func sysctlNodes(mib []_C_int) (nodes []Sysctlnode, err error) { - var olen uintptr - - // Get a list of all sysctl nodes below the given MIB by performing - // a sysctl for the given MIB with CTL_QUERY appended. - mib = append(mib, CTL_QUERY) - qnode := Sysctlnode{Flags: SYSCTL_VERS_1} - qp := (*byte)(unsafe.Pointer(&qnode)) - sz := unsafe.Sizeof(qnode) - if err = sysctl(mib, nil, &olen, qp, sz); err != nil { - return nil, err - } - - // Now that we know the size, get the actual nodes. - nodes = make([]Sysctlnode, olen/sz) - np := (*byte)(unsafe.Pointer(&nodes[0])) - if err = sysctl(mib, np, &olen, qp, sz); err != nil { - return nil, err - } - - return nodes, nil -} - -func nametomib(name string) (mib []_C_int, err error) { - - // Split name into components. - var parts []string - last := 0 - for i := 0; i < len(name); i++ { - if name[i] == '.' { - parts = append(parts, name[last:i]) - last = i + 1 - } - } - parts = append(parts, name[last:]) - - // Discover the nodes and construct the MIB OID. - for partno, part := range parts { - nodes, err := sysctlNodes(mib) - if err != nil { - return nil, err - } - for _, node := range nodes { - n := make([]byte, 0) - for i := range node.Name { - if node.Name[i] != 0 { - n = append(n, byte(node.Name[i])) - } - } - if string(n) == part { - mib = append(mib, _C_int(node.Num)) - break - } - } - if len(mib) != partno+1 { - return nil, EINVAL - } - } - - return mib, nil -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - if dirent.Reclen == 0 { - buf = nil - break - } - buf = buf[dirent.Reclen:] - if dirent.Fileno == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:dirent.Namlen]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sysnb pipe() (fd1 int, fd2 int, err error) -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - p[0], p[1], err = pipe() - return -} - -//sys getdents(fd int, buf []byte) (n int, err error) -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - return getdents(fd, buf) -} - -// TODO -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - return -1, ENOSYS -} - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chflags(path string, flags int) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(from int, to int) (err error) -//sys Exit(code int) -//sys Fchdir(fd int) (err error) -//sys Fchflags(fd int, flags int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) -//sysnb Getgid() (gid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgrp int) -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Getsid(pid int) (sid int, err error) -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Getuid() (uid int) -//sys Issetugid() (tainted bool) -//sys Kill(pid int, signum syscall.Signal) (err error) -//sys Kqueue() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Revoke(path string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK -//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) -//sysnb Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tp *Timeval) (err error) -//sysnb Setuid(uid int) (err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sys Truncate(path string, length int64) (err error) -//sys Umask(newmask int) (oldmask int) -//sys Unlink(path string) (err error) -//sys Unmount(path string, flags int) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ -//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE - -/* - * Unimplemented - */ -// ____semctl13 -// __clone -// __fhopen40 -// __fhstat40 -// __fhstatvfs140 -// __fstat30 -// __getcwd -// __getfh30 -// __getlogin -// __lstat30 -// __mount50 -// __msgctl13 -// __msync13 -// __ntp_gettime30 -// __posix_chown -// __posix_fadvise50 -// __posix_fchown -// __posix_lchown -// __posix_rename -// __setlogin -// __shmctl13 -// __sigaction_sigtramp -// __sigaltstack14 -// __sigpending14 -// __sigprocmask14 -// __sigsuspend14 -// __sigtimedwait -// __stat30 -// __syscall -// __vfork14 -// _ksem_close -// _ksem_destroy -// _ksem_getvalue -// _ksem_init -// _ksem_open -// _ksem_post -// _ksem_trywait -// _ksem_unlink -// _ksem_wait -// _lwp_continue -// _lwp_create -// _lwp_ctl -// _lwp_detach -// _lwp_exit -// _lwp_getname -// _lwp_getprivate -// _lwp_kill -// _lwp_park -// _lwp_self -// _lwp_setname -// _lwp_setprivate -// _lwp_suspend -// _lwp_unpark -// _lwp_unpark_all -// _lwp_wait -// _lwp_wakeup -// _pset_bind -// _sched_getaffinity -// _sched_getparam -// _sched_setaffinity -// _sched_setparam -// acct -// aio_cancel -// aio_error -// aio_fsync -// aio_read -// aio_return -// aio_suspend -// aio_write -// break -// clock_getres -// clock_gettime -// clock_settime -// compat_09_ogetdomainname -// compat_09_osetdomainname -// compat_09_ouname -// compat_10_omsgsys -// compat_10_osemsys -// compat_10_oshmsys -// compat_12_fstat12 -// compat_12_getdirentries -// compat_12_lstat12 -// compat_12_msync -// compat_12_oreboot -// compat_12_oswapon -// compat_12_stat12 -// compat_13_sigaction13 -// compat_13_sigaltstack13 -// compat_13_sigpending13 -// compat_13_sigprocmask13 -// compat_13_sigreturn13 -// compat_13_sigsuspend13 -// compat_14___semctl -// compat_14_msgctl -// compat_14_shmctl -// compat_16___sigaction14 -// compat_16___sigreturn14 -// compat_20_fhstatfs -// compat_20_fstatfs -// compat_20_getfsstat -// compat_20_statfs -// compat_30___fhstat30 -// compat_30___fstat13 -// compat_30___lstat13 -// compat_30___stat13 -// compat_30_fhopen -// compat_30_fhstat -// compat_30_fhstatvfs1 -// compat_30_getdents -// compat_30_getfh -// compat_30_ntp_gettime -// compat_30_socket -// compat_40_mount -// compat_43_fstat43 -// compat_43_lstat43 -// compat_43_oaccept -// compat_43_ocreat -// compat_43_oftruncate -// compat_43_ogetdirentries -// compat_43_ogetdtablesize -// compat_43_ogethostid -// compat_43_ogethostname -// compat_43_ogetkerninfo -// compat_43_ogetpagesize -// compat_43_ogetpeername -// compat_43_ogetrlimit -// compat_43_ogetsockname -// compat_43_okillpg -// compat_43_olseek -// compat_43_ommap -// compat_43_oquota -// compat_43_orecv -// compat_43_orecvfrom -// compat_43_orecvmsg -// compat_43_osend -// compat_43_osendmsg -// compat_43_osethostid -// compat_43_osethostname -// compat_43_osetrlimit -// compat_43_osigblock -// compat_43_osigsetmask -// compat_43_osigstack -// compat_43_osigvec -// compat_43_otruncate -// compat_43_owait -// compat_43_stat43 -// execve -// extattr_delete_fd -// extattr_delete_file -// extattr_delete_link -// extattr_get_fd -// extattr_get_file -// extattr_get_link -// extattr_list_fd -// extattr_list_file -// extattr_list_link -// extattr_set_fd -// extattr_set_file -// extattr_set_link -// extattrctl -// fchroot -// fdatasync -// fgetxattr -// fktrace -// flistxattr -// fork -// fremovexattr -// fsetxattr -// fstatvfs1 -// fsync_range -// getcontext -// getitimer -// getvfsstat -// getxattr -// ioctl -// ktrace -// lchflags -// lchmod -// lfs_bmapv -// lfs_markv -// lfs_segclean -// lfs_segwait -// lgetxattr -// lio_listio -// listxattr -// llistxattr -// lremovexattr -// lseek -// lsetxattr -// lutimes -// madvise -// mincore -// minherit -// modctl -// mq_close -// mq_getattr -// mq_notify -// mq_open -// mq_receive -// mq_send -// mq_setattr -// mq_timedreceive -// mq_timedsend -// mq_unlink -// mremap -// msgget -// msgrcv -// msgsnd -// nfssvc -// ntp_adjtime -// pmc_control -// pmc_get_info -// poll -// pollts -// preadv -// profil -// pselect -// pset_assign -// pset_create -// pset_destroy -// ptrace -// pwritev -// quotactl -// rasctl -// readv -// reboot -// removexattr -// sa_enable -// sa_preempt -// sa_register -// sa_setconcurrency -// sa_stacks -// sa_yield -// sbrk -// sched_yield -// semconfig -// semget -// semop -// setcontext -// setitimer -// setxattr -// shmat -// shmdt -// shmget -// sstk -// statvfs1 -// swapctl -// sysarch -// syscall -// timer_create -// timer_delete -// timer_getoverrun -// timer_gettime -// timer_settime -// undelete -// utrace -// uuidgen -// vadvise -// vfork -// writev diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_386.go deleted file mode 100644 index 1b0e1af12..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_386.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386,netbsd - -package unix - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int64(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = uint32(mode) - k.Flags = uint32(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_amd64.go deleted file mode 100644 index 1b6dcbe35..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_amd64.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,netbsd - -package unix - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int64(nsec / 1e9) - ts.Nsec = int64(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint64(fd) - k.Filter = uint32(mode) - k.Flags = uint32(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_arm.go deleted file mode 100644 index 87d1d6fed..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_arm.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm,netbsd - -package unix - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int64(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = uint32(mode) - k.Flags = uint32(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_no_getwd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_no_getwd.go deleted file mode 100644 index 530792ea9..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_no_getwd.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build dragonfly freebsd netbsd openbsd - -package unix - -const ImplementsGetwd = false - -func Getwd() (string, error) { return "", ENOTSUP } diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd.go deleted file mode 100644 index 246131d2a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd.go +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright 2009,2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// OpenBSD system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_bsd.go or syscall_unix.go. - -package unix - -import ( - "syscall" - "unsafe" -) - -type SockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [24]int8 - raw RawSockaddrDatalink -} - -func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) - -func nametomib(name string) (mib []_C_int, err error) { - - // Perform lookup via a binary search - left := 0 - right := len(sysctlMib) - 1 - for { - idx := left + (right-left)/2 - switch { - case name == sysctlMib[idx].ctlname: - return sysctlMib[idx].ctloid, nil - case name > sysctlMib[idx].ctlname: - left = idx + 1 - default: - right = idx - 1 - } - if left > right { - break - } - } - return nil, EINVAL -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - if dirent.Reclen == 0 { - buf = nil - break - } - buf = buf[dirent.Reclen:] - if dirent.Fileno == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:dirent.Namlen]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -//sysnb pipe(p *[2]_C_int) (err error) -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - var pp [2]_C_int - err = pipe(&pp) - p[0] = int(pp[0]) - p[1] = int(pp[1]) - return -} - -//sys getdents(fd int, buf []byte) (n int, err error) -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - return getdents(fd, buf) -} - -// TODO -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - return -1, ENOSYS -} - -func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { - var _p0 unsafe.Pointer - var bufsize uintptr - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) - } - r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chflags(path string, flags int) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(from int, to int) (err error) -//sys Exit(code int) -//sys Fchdir(fd int) (err error) -//sys Fchflags(fd int, flags int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Flock(fd int, how int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Fstatfs(fd int, stat *Statfs_t) (err error) -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) -//sysnb Getgid() (gid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgrp int) -//sysnb Getpid() (pid int) -//sysnb Getppid() (ppid int) -//sys Getpriority(which int, who int) (prio int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Getsid(pid int) (sid int, err error) -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Getuid() (uid int) -//sys Issetugid() (tainted bool) -//sys Kill(pid int, signum syscall.Signal) (err error) -//sys Kqueue() (fd int, err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Revoke(path string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK -//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) -//sysnb Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sys Setlogin(name string) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setresgid(rgid int, egid int, sgid int) (err error) -//sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Settimeofday(tp *Timeval) (err error) -//sysnb Setuid(uid int) (err error) -//sys Stat(path string, stat *Stat_t) (err error) -//sys Statfs(path string, stat *Statfs_t) (err error) -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sys Truncate(path string, length int64) (err error) -//sys Umask(newmask int) (oldmask int) -//sys Unlink(path string) (err error) -//sys Unmount(path string, flags int) (err error) -//sys write(fd int, p []byte) (n int, err error) -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ -//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE - -/* - * Unimplemented - */ -// __getcwd -// __semctl -// __syscall -// __sysctl -// adjfreq -// break -// clock_getres -// clock_gettime -// clock_settime -// closefrom -// execve -// faccessat -// fchmodat -// fchownat -// fcntl -// fhopen -// fhstat -// fhstatfs -// fork -// fstatat -// futimens -// getfh -// getgid -// getitimer -// getlogin -// getresgid -// getresuid -// getrtable -// getthrid -// ioctl -// ktrace -// lfs_bmapv -// lfs_markv -// lfs_segclean -// lfs_segwait -// linkat -// mincore -// minherit -// mkdirat -// mkfifoat -// mknodat -// mount -// mquery -// msgctl -// msgget -// msgrcv -// msgsnd -// nfssvc -// nnpfspioctl -// openat -// poll -// preadv -// profil -// pwritev -// quotactl -// readlinkat -// readv -// reboot -// renameat -// rfork -// sched_yield -// semget -// semop -// setgroups -// setitimer -// setrtable -// setsockopt -// shmat -// shmctl -// shmdt -// shmget -// sigaction -// sigaltstack -// sigpending -// sigprocmask -// sigreturn -// sigsuspend -// symlinkat -// sysarch -// syscall -// threxit -// thrsigdivert -// thrsleep -// thrwakeup -// unlinkat -// utimensat -// vfork -// writev diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_386.go deleted file mode 100644 index 9529b20e8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_386.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386,openbsd - -package unix - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = int64(nsec / 1e9) - ts.Nsec = int32(nsec % 1e9) - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = int32(nsec % 1e9 / 1e3) - tv.Sec = int64(nsec / 1e9) - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint32(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint32(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_amd64.go deleted file mode 100644 index fc6402946..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_amd64.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,openbsd - -package unix - -func Getpagesize() int { return 4096 } - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = nsec % 1e9 / 1e3 - tv.Sec = nsec / 1e9 - return -} - -func SetKevent(k *Kevent_t, fd, mode, flags int) { - k.Ident = uint64(fd) - k.Filter = int16(mode) - k.Flags = uint16(flags) -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (msghdr *Msghdr) SetControllen(length int) { - msghdr.Controllen = uint32(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris.go deleted file mode 100644 index 008373264..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris.go +++ /dev/null @@ -1,713 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Solaris system calls. -// This file is compiled as ordinary Go code, -// but it is also input to mksyscall, -// which parses the //sys lines and generates system call stubs. -// Note that sometimes we use a lowercase //sys name and wrap -// it in our own nicer implementation, either here or in -// syscall_solaris.go or syscall_unix.go. - -package unix - -import ( - "sync/atomic" - "syscall" - "unsafe" -) - -// Implemented in runtime/syscall_solaris.go. -type syscallFunc uintptr - -func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) -func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - -type SockaddrDatalink struct { - Family uint16 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [244]int8 - raw RawSockaddrDatalink -} - -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} - -// ParseDirent parses up to max directory entries in buf, -// appending the names to names. It returns the number -// bytes consumed from buf, the number of entries added -// to names, and the new names slice. -func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - for max != 0 && len(buf) > 0 { - dirent := (*Dirent)(unsafe.Pointer(&buf[0])) - if dirent.Reclen == 0 { - buf = nil - break - } - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:clen(bytes[:])]) - if name == "." || name == ".." { // Useless names - continue - } - max-- - count++ - names = append(names, name) - } - return origlen - len(buf), count, names -} - -func pipe() (r uintptr, w uintptr, err uintptr) - -func Pipe(p []int) (err error) { - if len(p) != 2 { - return EINVAL - } - r0, w0, e1 := pipe() - if e1 != 0 { - err = syscall.Errno(e1) - } - p[0], p[1] = int(r0), int(w0) - return -} - -func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Family = AF_INET - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil -} - -func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { - if sa.Port < 0 || sa.Port > 0xFFFF { - return nil, 0, EINVAL - } - sa.raw.Family = AF_INET6 - p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) - p[0] = byte(sa.Port >> 8) - p[1] = byte(sa.Port) - sa.raw.Scope_id = sa.ZoneId - for i := 0; i < len(sa.Addr); i++ { - sa.raw.Addr[i] = sa.Addr[i] - } - return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil -} - -func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { - name := sa.Name - n := len(name) - if n >= len(sa.raw.Path) { - return nil, 0, EINVAL - } - sa.raw.Family = AF_UNIX - for i := 0; i < n; i++ { - sa.raw.Path[i] = int8(name[i]) - } - // length is family (uint16), name, NUL. - sl := _Socklen(2) - if n > 0 { - sl += _Socklen(n) + 1 - } - if sa.raw.Path[0] == '@' { - sa.raw.Path[0] = 0 - // Don't count trailing NUL for abstract address. - sl-- - } - - return unsafe.Pointer(&sa.raw), sl, nil -} - -//sys getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getsockname - -func Getsockname(fd int) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - if err = getsockname(fd, &rsa, &len); err != nil { - return - } - return anyToSockaddr(&rsa) -} - -const ImplementsGetwd = true - -//sys Getcwd(buf []byte) (n int, err error) - -func Getwd() (wd string, err error) { - var buf [PathMax]byte - // Getcwd will return an error if it failed for any reason. - _, err = Getcwd(buf[0:]) - if err != nil { - return "", err - } - n := clen(buf[:]) - if n < 1 { - return "", EINVAL - } - return string(buf[:n]), nil -} - -/* - * Wrapped - */ - -//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error) -//sysnb setgroups(ngid int, gid *_Gid_t) (err error) - -func Getgroups() (gids []int, err error) { - n, err := getgroups(0, nil) - // Check for error and sanity check group count. Newer versions of - // Solaris allow up to 1024 (NGROUPS_MAX). - if n < 0 || n > 1024 { - if err != nil { - return nil, err - } - return nil, EINVAL - } else if n == 0 { - return nil, nil - } - - a := make([]_Gid_t, n) - n, err = getgroups(n, &a[0]) - if n == -1 { - return nil, err - } - gids = make([]int, n) - for i, v := range a[0:n] { - gids[i] = int(v) - } - return -} - -func Setgroups(gids []int) (err error) { - if len(gids) == 0 { - return setgroups(0, nil) - } - - a := make([]_Gid_t, len(gids)) - for i, v := range gids { - a[i] = _Gid_t(v) - } - return setgroups(len(a), &a[0]) -} - -func ReadDirent(fd int, buf []byte) (n int, err error) { - // Final argument is (basep *uintptr) and the syscall doesn't take nil. - // TODO(rsc): Can we use a single global basep for all calls? - return Getdents(fd, buf, new(uintptr)) -} - -// Wait status is 7 bits at bottom, either 0 (exited), -// 0x7F (stopped), or a signal number that caused an exit. -// The 0x80 bit is whether there was a core dump. -// An extra number (exit code, signal causing a stop) -// is in the high bits. - -type WaitStatus uint32 - -const ( - mask = 0x7F - core = 0x80 - shift = 8 - - exited = 0 - stopped = 0x7F -) - -func (w WaitStatus) Exited() bool { return w&mask == exited } - -func (w WaitStatus) ExitStatus() int { - if w&mask != exited { - return -1 - } - return int(w >> shift) -} - -func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 } - -func (w WaitStatus) Signal() syscall.Signal { - sig := syscall.Signal(w & mask) - if sig == stopped || sig == 0 { - return -1 - } - return sig -} - -func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 } - -func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP } - -func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP } - -func (w WaitStatus) StopSignal() syscall.Signal { - if !w.Stopped() { - return -1 - } - return syscall.Signal(w>>shift) & 0xFF -} - -func (w WaitStatus) TrapCause() int { return -1 } - -func wait4(pid uintptr, wstatus *WaitStatus, options uintptr, rusage *Rusage) (wpid uintptr, err uintptr) - -func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { - r0, e1 := wait4(uintptr(pid), wstatus, uintptr(options), rusage) - if e1 != 0 { - err = syscall.Errno(e1) - } - return int(r0), err -} - -func gethostname() (name string, err uintptr) - -func Gethostname() (name string, err error) { - name, e1 := gethostname() - if e1 != 0 { - err = syscall.Errno(e1) - } - return name, err -} - -//sys utimes(path string, times *[2]Timeval) (err error) - -func Utimes(path string, tv []Timeval) (err error) { - if tv == nil { - return utimes(path, nil) - } - if len(tv) != 2 { - return EINVAL - } - return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -//sys utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) - -func UtimesNano(path string, ts []Timespec) error { - if ts == nil { - return utimensat(AT_FDCWD, path, nil, 0) - } - if len(ts) != 2 { - return EINVAL - } - return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) -} - -func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { - if ts == nil { - return utimensat(dirfd, path, nil, flags) - } - if len(ts) != 2 { - return EINVAL - } - return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) -} - -//sys fcntl(fd int, cmd int, arg int) (val int, err error) - -// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. -func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0) - if e1 != 0 { - return e1 - } - return nil -} - -//sys futimesat(fildes int, path *byte, times *[2]Timeval) (err error) - -func Futimesat(dirfd int, path string, tv []Timeval) error { - pathp, err := BytePtrFromString(path) - if err != nil { - return err - } - if tv == nil { - return futimesat(dirfd, pathp, nil) - } - if len(tv) != 2 { - return EINVAL - } - return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -// Solaris doesn't have an futimes function because it allows NULL to be -// specified as the path for futimesat. However, Go doesn't like -// NULL-style string interfaces, so this simple wrapper is provided. -func Futimes(fd int, tv []Timeval) error { - if tv == nil { - return futimesat(fd, nil, nil) - } - if len(tv) != 2 { - return EINVAL - } - return futimesat(fd, nil, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) -} - -func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) { - switch rsa.Addr.Family { - case AF_UNIX: - pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa)) - sa := new(SockaddrUnix) - // Assume path ends at NUL. - // This is not technically the Solaris semantics for - // abstract Unix domain sockets -- they are supposed - // to be uninterpreted fixed-size binary blobs -- but - // everyone uses this convention. - n := 0 - for n < len(pp.Path) && pp.Path[n] != 0 { - n++ - } - bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n] - sa.Name = string(bytes) - return sa, nil - - case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - - case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] - } - return sa, nil - } - return nil, EAFNOSUPPORT -} - -//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = libsocket.accept - -func Accept(fd int) (nfd int, sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - nfd, err = accept(fd, &rsa, &len) - if nfd == -1 { - return - } - sa, err = anyToSockaddr(&rsa) - if err != nil { - Close(nfd) - nfd = 0 - } - return -} - -//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.recvmsg - -func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { - var msg Msghdr - var rsa RawSockaddrAny - msg.Name = (*byte)(unsafe.Pointer(&rsa)) - msg.Namelen = uint32(SizeofSockaddrAny) - var iov Iovec - if len(p) > 0 { - iov.Base = (*int8)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy int8 - if len(oob) > 0 { - // receive at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Accrights = (*int8)(unsafe.Pointer(&oob[0])) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = recvmsg(fd, &msg, flags); n == -1 { - return - } - oobn = int(msg.Accrightslen) - // source address is only specified if the socket is unconnected - if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) - } - return -} - -func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) { - _, err = SendmsgN(fd, p, oob, to, flags) - return -} - -//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) = libsocket.sendmsg - -func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) { - var ptr unsafe.Pointer - var salen _Socklen - if to != nil { - ptr, salen, err = to.sockaddr() - if err != nil { - return 0, err - } - } - var msg Msghdr - msg.Name = (*byte)(unsafe.Pointer(ptr)) - msg.Namelen = uint32(salen) - var iov Iovec - if len(p) > 0 { - iov.Base = (*int8)(unsafe.Pointer(&p[0])) - iov.SetLen(len(p)) - } - var dummy int8 - if len(oob) > 0 { - // send at least one normal byte - if len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) - } - msg.Accrights = (*int8)(unsafe.Pointer(&oob[0])) - } - msg.Iov = &iov - msg.Iovlen = 1 - if n, err = sendmsg(fd, &msg, flags); err != nil { - return 0, err - } - if len(oob) > 0 && len(p) == 0 { - n = 0 - } - return n, nil -} - -//sys acct(path *byte) (err error) - -func Acct(path string) (err error) { - if len(path) == 0 { - // Assume caller wants to disable accounting. - return acct(nil) - } - - pathp, err := BytePtrFromString(path) - if err != nil { - return err - } - return acct(pathp) -} - -/* - * Expose the ioctl function - */ - -//sys ioctl(fd int, req int, arg uintptr) (err error) - -func IoctlSetInt(fd int, req int, value int) (err error) { - return ioctl(fd, req, uintptr(value)) -} - -func IoctlSetWinsize(fd int, req int, value *Winsize) (err error) { - return ioctl(fd, req, uintptr(unsafe.Pointer(value))) -} - -func IoctlSetTermios(fd int, req int, value *Termios) (err error) { - return ioctl(fd, req, uintptr(unsafe.Pointer(value))) -} - -func IoctlSetTermio(fd int, req int, value *Termio) (err error) { - return ioctl(fd, req, uintptr(unsafe.Pointer(value))) -} - -func IoctlGetInt(fd int, req int) (int, error) { - var value int - err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) - return value, err -} - -func IoctlGetWinsize(fd int, req int) (*Winsize, error) { - var value Winsize - err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) - return &value, err -} - -func IoctlGetTermios(fd int, req int) (*Termios, error) { - var value Termios - err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) - return &value, err -} - -func IoctlGetTermio(fd int, req int) (*Termio, error) { - var value Termio - err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) - return &value, err -} - -/* - * Exposed directly - */ -//sys Access(path string, mode uint32) (err error) -//sys Adjtime(delta *Timeval, olddelta *Timeval) (err error) -//sys Chdir(path string) (err error) -//sys Chmod(path string, mode uint32) (err error) -//sys Chown(path string, uid int, gid int) (err error) -//sys Chroot(path string) (err error) -//sys Close(fd int) (err error) -//sys Creat(path string, mode uint32) (fd int, err error) -//sys Dup(fd int) (nfd int, err error) -//sys Dup2(oldfd int, newfd int) (err error) -//sys Exit(code int) -//sys Fchdir(fd int) (err error) -//sys Fchmod(fd int, mode uint32) (err error) -//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) -//sys Fchown(fd int, uid int, gid int) (err error) -//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) -//sys Fdatasync(fd int) (err error) -//sys Fpathconf(fd int, name int) (val int, err error) -//sys Fstat(fd int, stat *Stat_t) (err error) -//sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) -//sysnb Getgid() (gid int) -//sysnb Getpid() (pid int) -//sysnb Getpgid(pid int) (pgid int, err error) -//sysnb Getpgrp() (pgid int, err error) -//sys Geteuid() (euid int) -//sys Getegid() (egid int) -//sys Getppid() (ppid int) -//sys Getpriority(which int, who int) (n int, err error) -//sysnb Getrlimit(which int, lim *Rlimit) (err error) -//sysnb Getrusage(who int, rusage *Rusage) (err error) -//sysnb Gettimeofday(tv *Timeval) (err error) -//sysnb Getuid() (uid int) -//sys Kill(pid int, signum syscall.Signal) (err error) -//sys Lchown(path string, uid int, gid int) (err error) -//sys Link(path string, link string) (err error) -//sys Listen(s int, backlog int) (err error) = libsocket.listen -//sys Lstat(path string, stat *Stat_t) (err error) -//sys Madvise(b []byte, advice int) (err error) -//sys Mkdir(path string, mode uint32) (err error) -//sys Mkdirat(dirfd int, path string, mode uint32) (err error) -//sys Mkfifo(path string, mode uint32) (err error) -//sys Mkfifoat(dirfd int, path string, mode uint32) (err error) -//sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) -//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) -//sys Open(path string, mode int, perm uint32) (fd int, err error) -//sys Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) -//sys Pathconf(path string, name int) (val int, err error) -//sys Pause() (err error) -//sys Pread(fd int, p []byte, offset int64) (n int, err error) -//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys read(fd int, p []byte) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) -//sys Rename(from string, to string) (err error) -//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) -//sys Rmdir(path string) (err error) -//sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek -//sysnb Setegid(egid int) (err error) -//sysnb Seteuid(euid int) (err error) -//sysnb Setgid(gid int) (err error) -//sys Sethostname(p []byte) (err error) -//sysnb Setpgid(pid int, pgid int) (err error) -//sys Setpriority(which int, who int, prio int) (err error) -//sysnb Setregid(rgid int, egid int) (err error) -//sysnb Setreuid(ruid int, euid int) (err error) -//sysnb Setrlimit(which int, lim *Rlimit) (err error) -//sysnb Setsid() (pid int, err error) -//sysnb Setuid(uid int) (err error) -//sys Shutdown(s int, how int) (err error) = libsocket.shutdown -//sys Stat(path string, stat *Stat_t) (err error) -//sys Symlink(path string, link string) (err error) -//sys Sync() (err error) -//sysnb Times(tms *Tms) (ticks uintptr, err error) -//sys Truncate(path string, length int64) (err error) -//sys Fsync(fd int) (err error) -//sys Ftruncate(fd int, length int64) (err error) -//sys Umask(mask int) (oldmask int) -//sysnb Uname(buf *Utsname) (err error) -//sys Unmount(target string, flags int) (err error) = libc.umount -//sys Unlink(path string) (err error) -//sys Unlinkat(dirfd int, path string) (err error) -//sys Ustat(dev int, ubuf *Ustat_t) (err error) -//sys Utime(path string, buf *Utimbuf) (err error) -//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.bind -//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.connect -//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) -//sys munmap(addr uintptr, length uintptr) (err error) -//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.sendto -//sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.socket -//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.socketpair -//sys write(fd int, p []byte) (n int, err error) -//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) = libsocket.getsockopt -//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = libsocket.getpeername -//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt -//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -var mapper = &mmapper{ - active: make(map[*byte][]byte), - mmap: mmap, - munmap: munmap, -} - -func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - return mapper.Mmap(fd, offset, length, prot, flags) -} - -func Munmap(b []byte) (err error) { - return mapper.Munmap(b) -} - -//sys sysconf(name int) (n int64, err error) - -// pageSize caches the value of Getpagesize, since it can't change -// once the system is booted. -var pageSize int64 // accessed atomically - -func Getpagesize() int { - n := atomic.LoadInt64(&pageSize) - if n == 0 { - n, _ = sysconf(_SC_PAGESIZE) - atomic.StoreInt64(&pageSize, n) - } - return int(n) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris_amd64.go deleted file mode 100644 index 2e44630cd..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris_amd64.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,solaris - -package unix - -func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } - -func NsecToTimespec(nsec int64) (ts Timespec) { - ts.Sec = nsec / 1e9 - ts.Nsec = nsec % 1e9 - return -} - -func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } - -func NsecToTimeval(nsec int64) (tv Timeval) { - nsec += 999 // round up to microsecond - tv.Usec = nsec % 1e9 / 1e3 - tv.Sec = int64(nsec / 1e9) - return -} - -func (iov *Iovec) SetLen(length int) { - iov.Len = uint64(length) -} - -func (cmsg *Cmsghdr) SetLen(length int) { - cmsg.Len = uint32(length) -} - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - // TODO(aram): implement this, see issue 5847. - panic("unimplemented") -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix.go deleted file mode 100644 index b46b25028..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix.go +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -import ( - "runtime" - "sync" - "syscall" - "unsafe" -) - -var ( - Stdin = 0 - Stdout = 1 - Stderr = 2 -) - -const ( - darwin64Bit = runtime.GOOS == "darwin" && sizeofPtr == 8 - dragonfly64Bit = runtime.GOOS == "dragonfly" && sizeofPtr == 8 - netbsd32Bit = runtime.GOOS == "netbsd" && sizeofPtr == 4 -) - -// Do the interface allocations only once for common -// Errno values. -var ( - errEAGAIN error = syscall.EAGAIN - errEINVAL error = syscall.EINVAL - errENOENT error = syscall.ENOENT -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case EAGAIN: - return errEAGAIN - case EINVAL: - return errEINVAL - case ENOENT: - return errENOENT - } - return e -} - -func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) -func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) -func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) -func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - -// Mmap manager, for use by operating system-specific implementations. - -type mmapper struct { - sync.Mutex - active map[*byte][]byte // active mappings; key is last byte in mapping - mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error) - munmap func(addr uintptr, length uintptr) error -} - -func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { - if length <= 0 { - return nil, EINVAL - } - - // Map the requested memory. - addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) - if errno != nil { - return nil, errno - } - - // Slice memory layout - var sl = struct { - addr uintptr - len int - cap int - }{addr, length, length} - - // Use unsafe to turn sl into a []byte. - b := *(*[]byte)(unsafe.Pointer(&sl)) - - // Register mapping in m and return it. - p := &b[cap(b)-1] - m.Lock() - defer m.Unlock() - m.active[p] = b - return b, nil -} - -func (m *mmapper) Munmap(data []byte) (err error) { - if len(data) == 0 || len(data) != cap(data) { - return EINVAL - } - - // Find the base of the mapping. - p := &data[cap(data)-1] - m.Lock() - defer m.Unlock() - b := m.active[p] - if b == nil || &b[0] != &data[0] { - return EINVAL - } - - // Unmap the memory and update m. - if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil { - return errno - } - delete(m.active, p) - return nil -} - -func Read(fd int, p []byte) (n int, err error) { - n, err = read(fd, p) - if raceenabled { - if n > 0 { - raceWriteRange(unsafe.Pointer(&p[0]), n) - } - if err == nil { - raceAcquire(unsafe.Pointer(&ioSync)) - } - } - return -} - -func Write(fd int, p []byte) (n int, err error) { - if raceenabled { - raceReleaseMerge(unsafe.Pointer(&ioSync)) - } - n, err = write(fd, p) - if raceenabled && n > 0 { - raceReadRange(unsafe.Pointer(&p[0]), n) - } - return -} - -// For testing: clients can set this flag to force -// creation of IPv6 sockets to return EAFNOSUPPORT. -var SocketDisableIPv6 bool - -type Sockaddr interface { - sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs -} - -type SockaddrInet4 struct { - Port int - Addr [4]byte - raw RawSockaddrInet4 -} - -type SockaddrInet6 struct { - Port int - ZoneId uint32 - Addr [16]byte - raw RawSockaddrInet6 -} - -type SockaddrUnix struct { - Name string - raw RawSockaddrUnix -} - -func Bind(fd int, sa Sockaddr) (err error) { - ptr, n, err := sa.sockaddr() - if err != nil { - return err - } - return bind(fd, ptr, n) -} - -func Connect(fd int, sa Sockaddr) (err error) { - ptr, n, err := sa.sockaddr() - if err != nil { - return err - } - return connect(fd, ptr, n) -} - -func Getpeername(fd int) (sa Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - if err = getpeername(fd, &rsa, &len); err != nil { - return - } - return anyToSockaddr(&rsa) -} - -func GetsockoptInt(fd, level, opt int) (value int, err error) { - var n int32 - vallen := _Socklen(4) - err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) - return int(n), err -} - -func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { - var rsa RawSockaddrAny - var len _Socklen = SizeofSockaddrAny - if n, err = recvfrom(fd, p, flags, &rsa, &len); err != nil { - return - } - if rsa.Addr.Family != AF_UNSPEC { - from, err = anyToSockaddr(&rsa) - } - return -} - -func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { - ptr, n, err := to.sockaddr() - if err != nil { - return err - } - return sendto(fd, p, flags, ptr, n) -} - -func SetsockoptByte(fd, level, opt int, value byte) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(&value), 1) -} - -func SetsockoptInt(fd, level, opt int, value int) (err error) { - var n = int32(value) - return setsockopt(fd, level, opt, unsafe.Pointer(&n), 4) -} - -func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(&value[0]), 4) -} - -func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPMreq) -} - -func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(mreq), SizeofIPv6Mreq) -} - -func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { - return setsockopt(fd, level, opt, unsafe.Pointer(filter), SizeofICMPv6Filter) -} - -func SetsockoptLinger(fd, level, opt int, l *Linger) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(l), SizeofLinger) -} - -func SetsockoptString(fd, level, opt int, s string) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(&[]byte(s)[0]), uintptr(len(s))) -} - -func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error) { - return setsockopt(fd, level, opt, unsafe.Pointer(tv), unsafe.Sizeof(*tv)) -} - -func Socket(domain, typ, proto int) (fd int, err error) { - if domain == AF_INET6 && SocketDisableIPv6 { - return -1, EAFNOSUPPORT - } - fd, err = socket(domain, typ, proto) - return -} - -func Socketpair(domain, typ, proto int) (fd [2]int, err error) { - var fdx [2]int32 - err = socketpair(domain, typ, proto, &fdx) - if err == nil { - fd[0] = int(fdx[0]) - fd[1] = int(fdx[1]) - } - return -} - -func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - if raceenabled { - raceReleaseMerge(unsafe.Pointer(&ioSync)) - } - return sendfile(outfd, infd, offset, count) -} - -var ioSync int64 - -func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) } - -func SetNonblock(fd int, nonblocking bool) (err error) { - flag, err := fcntl(fd, F_GETFL, 0) - if err != nil { - return err - } - if nonblocking { - flag |= O_NONBLOCK - } else { - flag &= ^O_NONBLOCK - } - _, err = fcntl(fd, F_SETFL, flag) - return err -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_386.go deleted file mode 100644 index 8e6388835..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_386.go +++ /dev/null @@ -1,1576 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,darwin - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1c - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1e - AF_IPX = 0x17 - AF_ISDN = 0x1c - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NATM = 0x1f - AF_NDRV = 0x1b - AF_NETBIOS = 0x21 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PPP = 0x22 - AF_PUP = 0x4 - AF_RESERVED_36 = 0x24 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_SYSTEM = 0x20 - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_UTUN = 0x26 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc00c4279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4008426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80084267 - BIOCSETFNR = 0x8008427e - BIOCSETIF = 0x8020426c - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8008426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf5 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_MACHPORT = -0x8 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xe - EVFILT_THREADMARKER = 0xe - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xa - EVFILT_VM = -0xc - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG0 = 0x1000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_OOBAND = 0x2000 - EV_POLL = 0x1000 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_ADDFILESIGS = 0x3d - F_ADDSIGS = 0x3b - F_ALLOCATEALL = 0x4 - F_ALLOCATECONTIG = 0x2 - F_CHKCLEAN = 0x29 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x43 - F_FINDSIGS = 0x4e - F_FLUSH_DATA = 0x28 - F_FREEZE_FS = 0x35 - F_FULLFSYNC = 0x33 - F_GETCODEDIR = 0x48 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETLKPID = 0x42 - F_GETNOSIGPIPE = 0x4a - F_GETOWN = 0x5 - F_GETPATH = 0x32 - F_GETPATH_MTMINFO = 0x47 - F_GETPROTECTIONCLASS = 0x3f - F_GETPROTECTIONLEVEL = 0x4d - F_GLOBAL_NOCACHE = 0x37 - F_LOG2PHYS = 0x31 - F_LOG2PHYS_EXT = 0x41 - F_NOCACHE = 0x30 - F_NODIRECT = 0x3e - F_OK = 0x0 - F_PATHPKG_CHECK = 0x34 - F_PEOFPOSMODE = 0x3 - F_PREALLOCATE = 0x2a - F_RDADVISE = 0x2c - F_RDAHEAD = 0x2d - F_RDLCK = 0x1 - F_SETBACKINGSTORE = 0x46 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETLKWTIMEOUT = 0xa - F_SETNOSIGPIPE = 0x49 - F_SETOWN = 0x6 - F_SETPROTECTIONCLASS = 0x40 - F_SETSIZE = 0x2b - F_SINGLE_WRITER = 0x4c - F_THAW_FS = 0x36 - F_TRANSCODEKEY = 0x4b - F_UNLCK = 0x2 - F_VOLPOSMODE = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_AAL5 = 0x31 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ATM = 0x25 - IFT_BRIDGE = 0xd1 - IFT_CARP = 0xf8 - IFT_CELLULAR = 0xff - IFT_CEPT = 0x13 - IFT_DS3 = 0x1e - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_ETHER = 0x6 - IFT_FAITH = 0x38 - IFT_FDDI = 0xf - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_GIF = 0x37 - IFT_HDH1822 = 0x3 - IFT_HIPPI = 0x2f - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IEEE1394 = 0x90 - IFT_IEEE8023ADLAG = 0x88 - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88026 = 0xa - IFT_L2VLAN = 0x87 - IFT_LAPB = 0x10 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_NSIP = 0x1b - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PDP = 0xff - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PKTAP = 0xfe - IFT_PPP = 0x17 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PTPSERIAL = 0x16 - IFT_RS232 = 0x21 - IFT_SDLC = 0x11 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_STARLAN = 0xb - IFT_STF = 0x39 - IFT_T1 = 0x12 - IFT_ULTRA = 0x1d - IFT_V35 = 0x2d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LINKLOCALNETNUM = 0xa9fe0000 - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_2292DSTOPTS = 0x17 - IPV6_2292HOPLIMIT = 0x14 - IPV6_2292HOPOPTS = 0x16 - IPV6_2292NEXTHOP = 0x15 - IPV6_2292PKTINFO = 0x13 - IPV6_2292PKTOPTIONS = 0x19 - IPV6_2292RTHDR = 0x18 - IPV6_BINDV6ONLY = 0x1b - IPV6_BOUND_IF = 0x7d - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x3c - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVTCLASS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x24 - IPV6_UNICAST_HOPS = 0x4 - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BLOCK_SOURCE = 0x48 - IP_BOUND_IF = 0x19 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x28 - IP_FW_DEL = 0x29 - IP_FW_FLUSH = 0x2a - IP_FW_GET = 0x2c - IP_FW_RESETLOG = 0x2d - IP_FW_ZERO = 0x2b - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MF = 0x2000 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_IFINDEX = 0x42 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_NAT__XXX = 0x37 - IP_OFFMASK = 0x1fff - IP_OLD_FW_ADD = 0x32 - IP_OLD_FW_DEL = 0x33 - IP_OLD_FW_FLUSH = 0x34 - IP_OLD_FW_GET = 0x36 - IP_OLD_FW_RESETLOG = 0x38 - IP_OLD_FW_ZERO = 0x35 - IP_OPTIONS = 0x1 - IP_PKTINFO = 0x1a - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVPKTINFO = 0x1a - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x18 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_STRIPHDR = 0x17 - IP_TOS = 0x3 - IP_TRAFFIC_MGT_BACKGROUND = 0x41 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_CAN_REUSE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_FREE_REUSABLE = 0x7 - MADV_FREE_REUSE = 0x8 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MADV_ZERO_WIRED_PAGES = 0x6 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_JIT = 0x800 - MAP_NOCACHE = 0x400 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_SHARED = 0x1 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FLUSH = 0x400 - MSG_HAVEMORE = 0x2000 - MSG_HOLD = 0x800 - MSG_NEEDSA = 0x10000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_RCVMORE = 0x4000 - MSG_SEND = 0x1000 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MSG_WAITSTREAM = 0x200 - MS_ASYNC = 0x1 - MS_DEACTIVATE = 0x8 - MS_INVALIDATE = 0x2 - MS_KILLPAGES = 0x4 - MS_SYNC = 0x10 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_DUMP2 = 0x7 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLIST2 = 0x6 - NET_RT_MAXID = 0xa - NET_RT_STAT = 0x4 - NET_RT_TRASH = 0x5 - NOFLSH = 0x80000000 - NOTE_ABSOLUTE = 0x8 - NOTE_ATTRIB = 0x8 - NOTE_BACKGROUND = 0x40 - NOTE_CHILD = 0x4 - NOTE_CRITICAL = 0x20 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXITSTATUS = 0x4000000 - NOTE_EXIT_CSERROR = 0x40000 - NOTE_EXIT_DECRYPTFAIL = 0x10000 - NOTE_EXIT_DETAIL = 0x2000000 - NOTE_EXIT_DETAIL_MASK = 0x70000 - NOTE_EXIT_MEMORY = 0x20000 - NOTE_EXIT_REPARENTED = 0x80000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LEEWAY = 0x10 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_NONE = 0x80 - NOTE_NSECONDS = 0x4 - NOTE_PCTRLMASK = -0x100000 - NOTE_PDATAMASK = 0xfffff - NOTE_REAP = 0x10000000 - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_SECONDS = 0x1 - NOTE_SIGNAL = 0x8000000 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_USECONDS = 0x2 - NOTE_VM_ERROR = 0x10000000 - NOTE_VM_PRESSURE = 0x80000000 - NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 - NOTE_VM_PRESSURE_TERMINATE = 0x40000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFDEL = 0x20000 - OFILL = 0x80 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALERT = 0x20000000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x1000000 - O_CREAT = 0x200 - O_DIRECTORY = 0x100000 - O_DP_GETRAWENCRYPTED = 0x1 - O_DSYNC = 0x400000 - O_EVTONLY = 0x8000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x20000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_POPUP = 0x80000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYMLINK = 0x200000 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PT_ATTACH = 0xa - PT_ATTACHEXC = 0xe - PT_CONTINUE = 0x7 - PT_DENY_ATTACH = 0x1f - PT_DETACH = 0xb - PT_FIRSTMACH = 0x20 - PT_FORCEQUOTA = 0x1e - PT_KILL = 0x8 - PT_READ_D = 0x2 - PT_READ_I = 0x1 - PT_READ_U = 0x3 - PT_SIGEXC = 0xc - PT_STEP = 0x9 - PT_THUPDATE = 0xd - PT_TRACE_ME = 0x0 - PT_WRITE_D = 0x5 - PT_WRITE_I = 0x4 - PT_WRITE_U = 0x6 - RLIMIT_AS = 0x5 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_CPU_USAGE_MONITOR = 0x2 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_CONDEMNED = 0x2000000 - RTF_DELCLONE = 0x80 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_IFREF = 0x4000000 - RTF_IFSCOPE = 0x1000000 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_NOIFREF = 0x2000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_PROXY = 0x8000000 - RTF_REJECT = 0x8 - RTF_ROUTER = 0x10000000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_GET2 = 0x14 - RTM_IFINFO = 0xe - RTM_IFINFO2 = 0x12 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_NEWMADDR2 = 0x13 - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SCM_TIMESTAMP_MONOTONIC = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCARPIPLL = 0xc0206928 - SIOCATMARK = 0x40047307 - SIOCAUTOADDR = 0xc0206926 - SIOCAUTONETMASK = 0x80206927 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206941 - SIOCGDRVSPEC = 0xc01c697b - SIOCGETVLAN = 0xc020697f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFALTMTU = 0xc0206948 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBOND = 0xc0206947 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020695b - SIOCGIFCONF = 0xc0086924 - SIOCGIFDEVMTU = 0xc0206944 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFKPI = 0xc0206987 - SIOCGIFMAC = 0xc0206982 - SIOCGIFMEDIA = 0xc0286938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206940 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc020693f - SIOCGIFSTATUS = 0xc331693d - SIOCGIFVLAN = 0xc020697f - SIOCGIFWAKEFLAGS = 0xc0206988 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCIFCREATE = 0xc0206978 - SIOCIFCREATE2 = 0xc020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc00c6981 - SIOCRSLVMULTI = 0xc008693b - SIOCSDRVSPEC = 0x801c697b - SIOCSETVLAN = 0x8020697e - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFALTMTU = 0x80206945 - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBOND = 0x80206946 - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020695a - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFKPI = 0x80206986 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206983 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x8040693e - SIOCSIFPHYS = 0x80206936 - SIOCSIFVLAN = 0x8020697e - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_DONTTRUNC = 0x2000 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1010 - SO_LINGER = 0x80 - SO_LINGER_SEC = 0x1080 - SO_NKE = 0x1021 - SO_NOADDRERR = 0x1023 - SO_NOSIGPIPE = 0x1022 - SO_NOTIFYCONFLICT = 0x1026 - SO_NP_EXTENSIONS = 0x1083 - SO_NREAD = 0x1020 - SO_NUMRCVPKT = 0x1112 - SO_NWRITE = 0x1024 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1011 - SO_RANDOMPORT = 0x1082 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_REUSESHAREUID = 0x1025 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TIMESTAMP_MONOTONIC = 0x800 - SO_TYPE = 0x1008 - SO_UPCALLCLOSEWAIT = 0x1027 - SO_USELOOPBACK = 0x40 - SO_WANTMORE = 0x4000 - SO_WANTOOBFLAG = 0x8000 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONNECTIONTIMEOUT = 0x20 - TCP_ENABLE_ECN = 0x104 - TCP_KEEPALIVE = 0x10 - TCP_KEEPCNT = 0x102 - TCP_KEEPINTVL = 0x101 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0xd8 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_NOTSENT_LOWAT = 0x201 - TCP_RXT_CONNDROPTIME = 0x80 - TCP_RXT_FINDROP = 0x100 - TCP_SENDMOREACKS = 0x103 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40087458 - TIOCDRAIN = 0x2000745e - TIOCDSIMICROCODE = 0x20007455 - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGWINSZ = 0x40087468 - TIOCIXOFF = 0x20007480 - TIOCIXON = 0x20007481 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTYGNAME = 0x40807453 - TIOCPTYGRANT = 0x20007454 - TIOCPTYUNLK = 0x20007452 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCONS = 0x20007463 - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40087459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x10 - WCOREFLAG = 0x80 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOWAIT = 0x20 - WORDSIZE = 0x20 - WSTOPPED = 0x8 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADARCH = syscall.Errno(0x56) - EBADEXEC = syscall.Errno(0x55) - EBADF = syscall.Errno(0x9) - EBADMACHO = syscall.Errno(0x58) - EBADMSG = syscall.Errno(0x5e) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x59) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDEVERR = syscall.Errno(0x53) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x5a) - EILSEQ = syscall.Errno(0x5c) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x6a) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5f) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x60) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x61) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5b) - ENOPOLICY = syscall.Errno(0x67) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x62) - ENOSTR = syscall.Errno(0x63) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x68) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x66) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x69) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x64) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - EPWROFF = syscall.Errno(0x52) - EQFULL = syscall.Errno(0x6a) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHLIBVERS = syscall.Errno(0x57) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x65) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_amd64.go deleted file mode 100644 index 9594f9381..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ /dev/null @@ -1,1576 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,darwin - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1c - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1e - AF_IPX = 0x17 - AF_ISDN = 0x1c - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NATM = 0x1f - AF_NDRV = 0x1b - AF_NETBIOS = 0x21 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PPP = 0x22 - AF_PUP = 0x4 - AF_RESERVED_36 = 0x24 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_SYSTEM = 0x20 - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_UTUN = 0x26 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc00c4279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80104267 - BIOCSETFNR = 0x8010427e - BIOCSETIF = 0x8020426c - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8010426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf5 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_MACHPORT = -0x8 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xe - EVFILT_THREADMARKER = 0xe - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xa - EVFILT_VM = -0xc - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG0 = 0x1000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_OOBAND = 0x2000 - EV_POLL = 0x1000 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_ADDFILESIGS = 0x3d - F_ADDSIGS = 0x3b - F_ALLOCATEALL = 0x4 - F_ALLOCATECONTIG = 0x2 - F_CHKCLEAN = 0x29 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x43 - F_FINDSIGS = 0x4e - F_FLUSH_DATA = 0x28 - F_FREEZE_FS = 0x35 - F_FULLFSYNC = 0x33 - F_GETCODEDIR = 0x48 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETLKPID = 0x42 - F_GETNOSIGPIPE = 0x4a - F_GETOWN = 0x5 - F_GETPATH = 0x32 - F_GETPATH_MTMINFO = 0x47 - F_GETPROTECTIONCLASS = 0x3f - F_GETPROTECTIONLEVEL = 0x4d - F_GLOBAL_NOCACHE = 0x37 - F_LOG2PHYS = 0x31 - F_LOG2PHYS_EXT = 0x41 - F_NOCACHE = 0x30 - F_NODIRECT = 0x3e - F_OK = 0x0 - F_PATHPKG_CHECK = 0x34 - F_PEOFPOSMODE = 0x3 - F_PREALLOCATE = 0x2a - F_RDADVISE = 0x2c - F_RDAHEAD = 0x2d - F_RDLCK = 0x1 - F_SETBACKINGSTORE = 0x46 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETLKWTIMEOUT = 0xa - F_SETNOSIGPIPE = 0x49 - F_SETOWN = 0x6 - F_SETPROTECTIONCLASS = 0x40 - F_SETSIZE = 0x2b - F_SINGLE_WRITER = 0x4c - F_THAW_FS = 0x36 - F_TRANSCODEKEY = 0x4b - F_UNLCK = 0x2 - F_VOLPOSMODE = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_AAL5 = 0x31 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ATM = 0x25 - IFT_BRIDGE = 0xd1 - IFT_CARP = 0xf8 - IFT_CELLULAR = 0xff - IFT_CEPT = 0x13 - IFT_DS3 = 0x1e - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_ETHER = 0x6 - IFT_FAITH = 0x38 - IFT_FDDI = 0xf - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_GIF = 0x37 - IFT_HDH1822 = 0x3 - IFT_HIPPI = 0x2f - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IEEE1394 = 0x90 - IFT_IEEE8023ADLAG = 0x88 - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88026 = 0xa - IFT_L2VLAN = 0x87 - IFT_LAPB = 0x10 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_NSIP = 0x1b - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PDP = 0xff - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PKTAP = 0xfe - IFT_PPP = 0x17 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PTPSERIAL = 0x16 - IFT_RS232 = 0x21 - IFT_SDLC = 0x11 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_STARLAN = 0xb - IFT_STF = 0x39 - IFT_T1 = 0x12 - IFT_ULTRA = 0x1d - IFT_V35 = 0x2d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LINKLOCALNETNUM = 0xa9fe0000 - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_2292DSTOPTS = 0x17 - IPV6_2292HOPLIMIT = 0x14 - IPV6_2292HOPOPTS = 0x16 - IPV6_2292NEXTHOP = 0x15 - IPV6_2292PKTINFO = 0x13 - IPV6_2292PKTOPTIONS = 0x19 - IPV6_2292RTHDR = 0x18 - IPV6_BINDV6ONLY = 0x1b - IPV6_BOUND_IF = 0x7d - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x3c - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVTCLASS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x24 - IPV6_UNICAST_HOPS = 0x4 - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BLOCK_SOURCE = 0x48 - IP_BOUND_IF = 0x19 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x28 - IP_FW_DEL = 0x29 - IP_FW_FLUSH = 0x2a - IP_FW_GET = 0x2c - IP_FW_RESETLOG = 0x2d - IP_FW_ZERO = 0x2b - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MF = 0x2000 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_IFINDEX = 0x42 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_NAT__XXX = 0x37 - IP_OFFMASK = 0x1fff - IP_OLD_FW_ADD = 0x32 - IP_OLD_FW_DEL = 0x33 - IP_OLD_FW_FLUSH = 0x34 - IP_OLD_FW_GET = 0x36 - IP_OLD_FW_RESETLOG = 0x38 - IP_OLD_FW_ZERO = 0x35 - IP_OPTIONS = 0x1 - IP_PKTINFO = 0x1a - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVPKTINFO = 0x1a - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x18 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_STRIPHDR = 0x17 - IP_TOS = 0x3 - IP_TRAFFIC_MGT_BACKGROUND = 0x41 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_CAN_REUSE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_FREE_REUSABLE = 0x7 - MADV_FREE_REUSE = 0x8 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MADV_ZERO_WIRED_PAGES = 0x6 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_JIT = 0x800 - MAP_NOCACHE = 0x400 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_SHARED = 0x1 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FLUSH = 0x400 - MSG_HAVEMORE = 0x2000 - MSG_HOLD = 0x800 - MSG_NEEDSA = 0x10000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_RCVMORE = 0x4000 - MSG_SEND = 0x1000 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MSG_WAITSTREAM = 0x200 - MS_ASYNC = 0x1 - MS_DEACTIVATE = 0x8 - MS_INVALIDATE = 0x2 - MS_KILLPAGES = 0x4 - MS_SYNC = 0x10 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_DUMP2 = 0x7 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLIST2 = 0x6 - NET_RT_MAXID = 0xa - NET_RT_STAT = 0x4 - NET_RT_TRASH = 0x5 - NOFLSH = 0x80000000 - NOTE_ABSOLUTE = 0x8 - NOTE_ATTRIB = 0x8 - NOTE_BACKGROUND = 0x40 - NOTE_CHILD = 0x4 - NOTE_CRITICAL = 0x20 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXITSTATUS = 0x4000000 - NOTE_EXIT_CSERROR = 0x40000 - NOTE_EXIT_DECRYPTFAIL = 0x10000 - NOTE_EXIT_DETAIL = 0x2000000 - NOTE_EXIT_DETAIL_MASK = 0x70000 - NOTE_EXIT_MEMORY = 0x20000 - NOTE_EXIT_REPARENTED = 0x80000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LEEWAY = 0x10 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_NONE = 0x80 - NOTE_NSECONDS = 0x4 - NOTE_PCTRLMASK = -0x100000 - NOTE_PDATAMASK = 0xfffff - NOTE_REAP = 0x10000000 - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_SECONDS = 0x1 - NOTE_SIGNAL = 0x8000000 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_USECONDS = 0x2 - NOTE_VM_ERROR = 0x10000000 - NOTE_VM_PRESSURE = 0x80000000 - NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 - NOTE_VM_PRESSURE_TERMINATE = 0x40000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFDEL = 0x20000 - OFILL = 0x80 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALERT = 0x20000000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x1000000 - O_CREAT = 0x200 - O_DIRECTORY = 0x100000 - O_DP_GETRAWENCRYPTED = 0x1 - O_DSYNC = 0x400000 - O_EVTONLY = 0x8000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x20000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_POPUP = 0x80000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYMLINK = 0x200000 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PT_ATTACH = 0xa - PT_ATTACHEXC = 0xe - PT_CONTINUE = 0x7 - PT_DENY_ATTACH = 0x1f - PT_DETACH = 0xb - PT_FIRSTMACH = 0x20 - PT_FORCEQUOTA = 0x1e - PT_KILL = 0x8 - PT_READ_D = 0x2 - PT_READ_I = 0x1 - PT_READ_U = 0x3 - PT_SIGEXC = 0xc - PT_STEP = 0x9 - PT_THUPDATE = 0xd - PT_TRACE_ME = 0x0 - PT_WRITE_D = 0x5 - PT_WRITE_I = 0x4 - PT_WRITE_U = 0x6 - RLIMIT_AS = 0x5 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_CPU_USAGE_MONITOR = 0x2 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_CONDEMNED = 0x2000000 - RTF_DELCLONE = 0x80 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_IFREF = 0x4000000 - RTF_IFSCOPE = 0x1000000 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_NOIFREF = 0x2000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_PROXY = 0x8000000 - RTF_REJECT = 0x8 - RTF_ROUTER = 0x10000000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_GET2 = 0x14 - RTM_IFINFO = 0xe - RTM_IFINFO2 = 0x12 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_NEWMADDR2 = 0x13 - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SCM_TIMESTAMP_MONOTONIC = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCARPIPLL = 0xc0206928 - SIOCATMARK = 0x40047307 - SIOCAUTOADDR = 0xc0206926 - SIOCAUTONETMASK = 0x80206927 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206941 - SIOCGDRVSPEC = 0xc028697b - SIOCGETVLAN = 0xc020697f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFALTMTU = 0xc0206948 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBOND = 0xc0206947 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020695b - SIOCGIFCONF = 0xc00c6924 - SIOCGIFDEVMTU = 0xc0206944 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFKPI = 0xc0206987 - SIOCGIFMAC = 0xc0206982 - SIOCGIFMEDIA = 0xc02c6938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206940 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc020693f - SIOCGIFSTATUS = 0xc331693d - SIOCGIFVLAN = 0xc020697f - SIOCGIFWAKEFLAGS = 0xc0206988 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCIFCREATE = 0xc0206978 - SIOCIFCREATE2 = 0xc020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106981 - SIOCRSLVMULTI = 0xc010693b - SIOCSDRVSPEC = 0x8028697b - SIOCSETVLAN = 0x8020697e - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFALTMTU = 0x80206945 - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBOND = 0x80206946 - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020695a - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFKPI = 0x80206986 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206983 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x8040693e - SIOCSIFPHYS = 0x80206936 - SIOCSIFVLAN = 0x8020697e - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_DONTTRUNC = 0x2000 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1010 - SO_LINGER = 0x80 - SO_LINGER_SEC = 0x1080 - SO_NKE = 0x1021 - SO_NOADDRERR = 0x1023 - SO_NOSIGPIPE = 0x1022 - SO_NOTIFYCONFLICT = 0x1026 - SO_NP_EXTENSIONS = 0x1083 - SO_NREAD = 0x1020 - SO_NUMRCVPKT = 0x1112 - SO_NWRITE = 0x1024 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1011 - SO_RANDOMPORT = 0x1082 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_REUSESHAREUID = 0x1025 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TIMESTAMP_MONOTONIC = 0x800 - SO_TYPE = 0x1008 - SO_UPCALLCLOSEWAIT = 0x1027 - SO_USELOOPBACK = 0x40 - SO_WANTMORE = 0x4000 - SO_WANTOOBFLAG = 0x8000 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONNECTIONTIMEOUT = 0x20 - TCP_ENABLE_ECN = 0x104 - TCP_KEEPALIVE = 0x10 - TCP_KEEPCNT = 0x102 - TCP_KEEPINTVL = 0x101 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0xd8 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_NOTSENT_LOWAT = 0x201 - TCP_RXT_CONNDROPTIME = 0x80 - TCP_RXT_FINDROP = 0x100 - TCP_SENDMOREACKS = 0x103 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40107458 - TIOCDRAIN = 0x2000745e - TIOCDSIMICROCODE = 0x20007455 - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x40487413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGWINSZ = 0x40087468 - TIOCIXOFF = 0x20007480 - TIOCIXON = 0x20007481 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTYGNAME = 0x40807453 - TIOCPTYGRANT = 0x20007454 - TIOCPTYUNLK = 0x20007452 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCONS = 0x20007463 - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x80487414 - TIOCSETAF = 0x80487416 - TIOCSETAW = 0x80487415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40107459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x10 - WCOREFLAG = 0x80 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOWAIT = 0x20 - WORDSIZE = 0x40 - WSTOPPED = 0x8 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADARCH = syscall.Errno(0x56) - EBADEXEC = syscall.Errno(0x55) - EBADF = syscall.Errno(0x9) - EBADMACHO = syscall.Errno(0x58) - EBADMSG = syscall.Errno(0x5e) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x59) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDEVERR = syscall.Errno(0x53) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x5a) - EILSEQ = syscall.Errno(0x5c) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x6a) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5f) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x60) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x61) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5b) - ENOPOLICY = syscall.Errno(0x67) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x62) - ENOSTR = syscall.Errno(0x63) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x68) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x66) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x69) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x64) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - EPWROFF = syscall.Errno(0x52) - EQFULL = syscall.Errno(0x6a) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHLIBVERS = syscall.Errno(0x57) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x65) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm.go deleted file mode 100644 index a410e88ed..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm.go +++ /dev/null @@ -1,1293 +0,0 @@ -// mkerrors.sh -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- _const.go - -// +build arm,darwin - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1c - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1e - AF_IPX = 0x17 - AF_ISDN = 0x1c - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NATM = 0x1f - AF_NDRV = 0x1b - AF_NETBIOS = 0x21 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PPP = 0x22 - AF_PUP = 0x4 - AF_RESERVED_36 = 0x24 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_SYSTEM = 0x20 - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_UTUN = 0x26 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc00c4279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80104267 - BIOCSETIF = 0x8020426c - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8010426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AX25 = 0x3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_C_HDLC = 0x68 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_FDDI = 0xa - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_NULL = 0x0 - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_SERIAL = 0x32 - DLT_PRONET = 0x4 - DLT_RAW = 0xc - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_MACHPORT = -0x8 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xe - EVFILT_THREADMARKER = 0xe - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xa - EVFILT_VM = -0xc - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG0 = 0x1000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_OOBAND = 0x2000 - EV_POLL = 0x1000 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_ADDFILESIGS = 0x3d - F_ADDSIGS = 0x3b - F_ALLOCATEALL = 0x4 - F_ALLOCATECONTIG = 0x2 - F_CHKCLEAN = 0x29 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x43 - F_FINDSIGS = 0x4e - F_FLUSH_DATA = 0x28 - F_FREEZE_FS = 0x35 - F_FULLFSYNC = 0x33 - F_GETCODEDIR = 0x48 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETLKPID = 0x42 - F_GETNOSIGPIPE = 0x4a - F_GETOWN = 0x5 - F_GETPATH = 0x32 - F_GETPATH_MTMINFO = 0x47 - F_GETPROTECTIONCLASS = 0x3f - F_GETPROTECTIONLEVEL = 0x4d - F_GLOBAL_NOCACHE = 0x37 - F_LOG2PHYS = 0x31 - F_LOG2PHYS_EXT = 0x41 - F_NOCACHE = 0x30 - F_NODIRECT = 0x3e - F_OK = 0x0 - F_PATHPKG_CHECK = 0x34 - F_PEOFPOSMODE = 0x3 - F_PREALLOCATE = 0x2a - F_RDADVISE = 0x2c - F_RDAHEAD = 0x2d - F_RDLCK = 0x1 - F_SETBACKINGSTORE = 0x46 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETLKWTIMEOUT = 0xa - F_SETNOSIGPIPE = 0x49 - F_SETOWN = 0x6 - F_SETPROTECTIONCLASS = 0x40 - F_SETSIZE = 0x2b - F_SINGLE_WRITER = 0x4c - F_THAW_FS = 0x36 - F_TRANSCODEKEY = 0x4b - F_UNLCK = 0x2 - F_VOLPOSMODE = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_AAL5 = 0x31 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ATM = 0x25 - IFT_BRIDGE = 0xd1 - IFT_CARP = 0xf8 - IFT_CELLULAR = 0xff - IFT_CEPT = 0x13 - IFT_DS3 = 0x1e - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_ETHER = 0x6 - IFT_FAITH = 0x38 - IFT_FDDI = 0xf - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_GIF = 0x37 - IFT_HDH1822 = 0x3 - IFT_HIPPI = 0x2f - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IEEE1394 = 0x90 - IFT_IEEE8023ADLAG = 0x88 - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88026 = 0xa - IFT_L2VLAN = 0x87 - IFT_LAPB = 0x10 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_NSIP = 0x1b - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PDP = 0xff - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PPP = 0x17 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PTPSERIAL = 0x16 - IFT_RS232 = 0x21 - IFT_SDLC = 0x11 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_STARLAN = 0xb - IFT_STF = 0x39 - IFT_T1 = 0x12 - IFT_ULTRA = 0x1d - IFT_V35 = 0x2d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LINKLOCALNETNUM = 0xa9fe0000 - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_2292DSTOPTS = 0x17 - IPV6_2292HOPLIMIT = 0x14 - IPV6_2292HOPOPTS = 0x16 - IPV6_2292NEXTHOP = 0x15 - IPV6_2292PKTINFO = 0x13 - IPV6_2292PKTOPTIONS = 0x19 - IPV6_2292RTHDR = 0x18 - IPV6_BINDV6ONLY = 0x1b - IPV6_BOUND_IF = 0x7d - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVTCLASS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x24 - IPV6_UNICAST_HOPS = 0x4 - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BLOCK_SOURCE = 0x48 - IP_BOUND_IF = 0x19 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x28 - IP_FW_DEL = 0x29 - IP_FW_FLUSH = 0x2a - IP_FW_GET = 0x2c - IP_FW_RESETLOG = 0x2d - IP_FW_ZERO = 0x2b - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MF = 0x2000 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_IFINDEX = 0x42 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_NAT__XXX = 0x37 - IP_OFFMASK = 0x1fff - IP_OLD_FW_ADD = 0x32 - IP_OLD_FW_DEL = 0x33 - IP_OLD_FW_FLUSH = 0x34 - IP_OLD_FW_GET = 0x36 - IP_OLD_FW_RESETLOG = 0x38 - IP_OLD_FW_ZERO = 0x35 - IP_OPTIONS = 0x1 - IP_PKTINFO = 0x1a - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVPKTINFO = 0x1a - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x18 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_STRIPHDR = 0x17 - IP_TOS = 0x3 - IP_TRAFFIC_MGT_BACKGROUND = 0x41 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_CAN_REUSE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_FREE_REUSABLE = 0x7 - MADV_FREE_REUSE = 0x8 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MADV_ZERO_WIRED_PAGES = 0x6 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_JIT = 0x800 - MAP_NOCACHE = 0x400 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_SHARED = 0x1 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FLUSH = 0x400 - MSG_HAVEMORE = 0x2000 - MSG_HOLD = 0x800 - MSG_NEEDSA = 0x10000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_RCVMORE = 0x4000 - MSG_SEND = 0x1000 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MSG_WAITSTREAM = 0x200 - MS_ASYNC = 0x1 - MS_DEACTIVATE = 0x8 - MS_INVALIDATE = 0x2 - MS_KILLPAGES = 0x4 - MS_SYNC = 0x10 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_DUMP2 = 0x7 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLIST2 = 0x6 - NET_RT_MAXID = 0xa - NET_RT_STAT = 0x4 - NET_RT_TRASH = 0x5 - NOFLSH = 0x80000000 - NOTE_ABSOLUTE = 0x8 - NOTE_ATTRIB = 0x8 - NOTE_BACKGROUND = 0x40 - NOTE_CHILD = 0x4 - NOTE_CRITICAL = 0x20 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXITSTATUS = 0x4000000 - NOTE_EXIT_CSERROR = 0x40000 - NOTE_EXIT_DECRYPTFAIL = 0x10000 - NOTE_EXIT_DETAIL = 0x2000000 - NOTE_EXIT_DETAIL_MASK = 0x70000 - NOTE_EXIT_MEMORY = 0x20000 - NOTE_EXIT_REPARENTED = 0x80000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LEEWAY = 0x10 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_NONE = 0x80 - NOTE_NSECONDS = 0x4 - NOTE_PCTRLMASK = -0x100000 - NOTE_PDATAMASK = 0xfffff - NOTE_REAP = 0x10000000 - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_SECONDS = 0x1 - NOTE_SIGNAL = 0x8000000 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_USECONDS = 0x2 - NOTE_VM_ERROR = 0x10000000 - NOTE_VM_PRESSURE = 0x80000000 - NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 - NOTE_VM_PRESSURE_TERMINATE = 0x40000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFDEL = 0x20000 - OFILL = 0x80 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALERT = 0x20000000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x1000000 - O_CREAT = 0x200 - O_DIRECTORY = 0x100000 - O_DP_GETRAWENCRYPTED = 0x1 - O_DSYNC = 0x400000 - O_EVTONLY = 0x8000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x20000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_POPUP = 0x80000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYMLINK = 0x200000 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PT_ATTACH = 0xa - PT_ATTACHEXC = 0xe - PT_CONTINUE = 0x7 - PT_DENY_ATTACH = 0x1f - PT_DETACH = 0xb - PT_FIRSTMACH = 0x20 - PT_FORCEQUOTA = 0x1e - PT_KILL = 0x8 - PT_READ_D = 0x2 - PT_READ_I = 0x1 - PT_READ_U = 0x3 - PT_SIGEXC = 0xc - PT_STEP = 0x9 - PT_THUPDATE = 0xd - PT_TRACE_ME = 0x0 - PT_WRITE_D = 0x5 - PT_WRITE_I = 0x4 - PT_WRITE_U = 0x6 - RLIMIT_AS = 0x5 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_CPU_USAGE_MONITOR = 0x2 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_CONDEMNED = 0x2000000 - RTF_DELCLONE = 0x80 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_IFREF = 0x4000000 - RTF_IFSCOPE = 0x1000000 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_PROXY = 0x8000000 - RTF_REJECT = 0x8 - RTF_ROUTER = 0x10000000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_GET2 = 0x14 - RTM_IFINFO = 0xe - RTM_IFINFO2 = 0x12 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_NEWMADDR2 = 0x13 - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SCM_TIMESTAMP_MONOTONIC = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCARPIPLL = 0xc0206928 - SIOCATMARK = 0x40047307 - SIOCAUTOADDR = 0xc0206926 - SIOCAUTONETMASK = 0x80206927 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206941 - SIOCGDRVSPEC = 0xc028697b - SIOCGETVLAN = 0xc020697f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFALTMTU = 0xc0206948 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBOND = 0xc0206947 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020695b - SIOCGIFCONF = 0xc00c6924 - SIOCGIFDEVMTU = 0xc0206944 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFKPI = 0xc0206987 - SIOCGIFMAC = 0xc0206982 - SIOCGIFMEDIA = 0xc02c6938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206940 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc020693f - SIOCGIFSTATUS = 0xc331693d - SIOCGIFVLAN = 0xc020697f - SIOCGIFWAKEFLAGS = 0xc0206988 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCIFCREATE = 0xc0206978 - SIOCIFCREATE2 = 0xc020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106981 - SIOCRSLVMULTI = 0xc010693b - SIOCSDRVSPEC = 0x8028697b - SIOCSETVLAN = 0x8020697e - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFALTMTU = 0x80206945 - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBOND = 0x80206946 - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020695a - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFKPI = 0x80206986 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206983 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x8040693e - SIOCSIFPHYS = 0x80206936 - SIOCSIFVLAN = 0x8020697e - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_DONTTRUNC = 0x2000 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1010 - SO_LINGER = 0x80 - SO_LINGER_SEC = 0x1080 - SO_NKE = 0x1021 - SO_NOADDRERR = 0x1023 - SO_NOSIGPIPE = 0x1022 - SO_NOTIFYCONFLICT = 0x1026 - SO_NP_EXTENSIONS = 0x1083 - SO_NREAD = 0x1020 - SO_NUMRCVPKT = 0x1112 - SO_NWRITE = 0x1024 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1011 - SO_RANDOMPORT = 0x1082 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_REUSESHAREUID = 0x1025 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TIMESTAMP_MONOTONIC = 0x800 - SO_TYPE = 0x1008 - SO_UPCALLCLOSEWAIT = 0x1027 - SO_USELOOPBACK = 0x40 - SO_WANTMORE = 0x4000 - SO_WANTOOBFLAG = 0x8000 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONNECTIONTIMEOUT = 0x20 - TCP_ENABLE_ECN = 0x104 - TCP_KEEPALIVE = 0x10 - TCP_KEEPCNT = 0x102 - TCP_KEEPINTVL = 0x101 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0xd8 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_NOTSENT_LOWAT = 0x201 - TCP_RXT_CONNDROPTIME = 0x80 - TCP_RXT_FINDROP = 0x100 - TCP_SENDMOREACKS = 0x103 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40107458 - TIOCDRAIN = 0x2000745e - TIOCDSIMICROCODE = 0x20007455 - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x40487413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGWINSZ = 0x40087468 - TIOCIXOFF = 0x20007480 - TIOCIXON = 0x20007481 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTYGNAME = 0x40807453 - TIOCPTYGRANT = 0x20007454 - TIOCPTYUNLK = 0x20007452 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCONS = 0x20007463 - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x80487414 - TIOCSETAF = 0x80487416 - TIOCSETAW = 0x80487415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40107459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x10 - WCOREFLAG = 0x80 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOWAIT = 0x20 - WORDSIZE = 0x40 - WSTOPPED = 0x8 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADARCH = syscall.Errno(0x56) - EBADEXEC = syscall.Errno(0x55) - EBADF = syscall.Errno(0x9) - EBADMACHO = syscall.Errno(0x58) - EBADMSG = syscall.Errno(0x5e) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x59) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDEVERR = syscall.Errno(0x53) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x5a) - EILSEQ = syscall.Errno(0x5c) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x6a) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5f) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x60) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x61) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5b) - ENOPOLICY = syscall.Errno(0x67) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x62) - ENOSTR = syscall.Errno(0x63) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x68) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x66) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x69) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x64) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - EPWROFF = syscall.Errno(0x52) - EQFULL = syscall.Errno(0x6a) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHLIBVERS = syscall.Errno(0x57) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x65) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm64.go deleted file mode 100644 index 3189c6b34..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ /dev/null @@ -1,1576 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm64,darwin - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1c - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1e - AF_IPX = 0x17 - AF_ISDN = 0x1c - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NATM = 0x1f - AF_NDRV = 0x1b - AF_NETBIOS = 0x21 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PPP = 0x22 - AF_PUP = 0x4 - AF_RESERVED_36 = 0x24 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_SYSTEM = 0x20 - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_UTUN = 0x26 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc00c4279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80104267 - BIOCSETFNR = 0x8010427e - BIOCSETIF = 0x8020426c - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8010426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf5 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_MACHPORT = -0x8 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xe - EVFILT_THREADMARKER = 0xe - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xa - EVFILT_VM = -0xc - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG0 = 0x1000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_OOBAND = 0x2000 - EV_POLL = 0x1000 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_ADDFILESIGS = 0x3d - F_ADDSIGS = 0x3b - F_ALLOCATEALL = 0x4 - F_ALLOCATECONTIG = 0x2 - F_CHKCLEAN = 0x29 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x43 - F_FINDSIGS = 0x4e - F_FLUSH_DATA = 0x28 - F_FREEZE_FS = 0x35 - F_FULLFSYNC = 0x33 - F_GETCODEDIR = 0x48 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETLKPID = 0x42 - F_GETNOSIGPIPE = 0x4a - F_GETOWN = 0x5 - F_GETPATH = 0x32 - F_GETPATH_MTMINFO = 0x47 - F_GETPROTECTIONCLASS = 0x3f - F_GETPROTECTIONLEVEL = 0x4d - F_GLOBAL_NOCACHE = 0x37 - F_LOG2PHYS = 0x31 - F_LOG2PHYS_EXT = 0x41 - F_NOCACHE = 0x30 - F_NODIRECT = 0x3e - F_OK = 0x0 - F_PATHPKG_CHECK = 0x34 - F_PEOFPOSMODE = 0x3 - F_PREALLOCATE = 0x2a - F_RDADVISE = 0x2c - F_RDAHEAD = 0x2d - F_RDLCK = 0x1 - F_SETBACKINGSTORE = 0x46 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETLKWTIMEOUT = 0xa - F_SETNOSIGPIPE = 0x49 - F_SETOWN = 0x6 - F_SETPROTECTIONCLASS = 0x40 - F_SETSIZE = 0x2b - F_SINGLE_WRITER = 0x4c - F_THAW_FS = 0x36 - F_TRANSCODEKEY = 0x4b - F_UNLCK = 0x2 - F_VOLPOSMODE = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_AAL5 = 0x31 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ATM = 0x25 - IFT_BRIDGE = 0xd1 - IFT_CARP = 0xf8 - IFT_CELLULAR = 0xff - IFT_CEPT = 0x13 - IFT_DS3 = 0x1e - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_ETHER = 0x6 - IFT_FAITH = 0x38 - IFT_FDDI = 0xf - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_GIF = 0x37 - IFT_HDH1822 = 0x3 - IFT_HIPPI = 0x2f - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IEEE1394 = 0x90 - IFT_IEEE8023ADLAG = 0x88 - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88026 = 0xa - IFT_L2VLAN = 0x87 - IFT_LAPB = 0x10 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_NSIP = 0x1b - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PDP = 0xff - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PKTAP = 0xfe - IFT_PPP = 0x17 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PTPSERIAL = 0x16 - IFT_RS232 = 0x21 - IFT_SDLC = 0x11 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_STARLAN = 0xb - IFT_STF = 0x39 - IFT_T1 = 0x12 - IFT_ULTRA = 0x1d - IFT_V35 = 0x2d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LINKLOCALNETNUM = 0xa9fe0000 - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_2292DSTOPTS = 0x17 - IPV6_2292HOPLIMIT = 0x14 - IPV6_2292HOPOPTS = 0x16 - IPV6_2292NEXTHOP = 0x15 - IPV6_2292PKTINFO = 0x13 - IPV6_2292PKTOPTIONS = 0x19 - IPV6_2292RTHDR = 0x18 - IPV6_BINDV6ONLY = 0x1b - IPV6_BOUND_IF = 0x7d - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x3c - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVTCLASS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x24 - IPV6_UNICAST_HOPS = 0x4 - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BLOCK_SOURCE = 0x48 - IP_BOUND_IF = 0x19 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x28 - IP_FW_DEL = 0x29 - IP_FW_FLUSH = 0x2a - IP_FW_GET = 0x2c - IP_FW_RESETLOG = 0x2d - IP_FW_ZERO = 0x2b - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MF = 0x2000 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_IFINDEX = 0x42 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_NAT__XXX = 0x37 - IP_OFFMASK = 0x1fff - IP_OLD_FW_ADD = 0x32 - IP_OLD_FW_DEL = 0x33 - IP_OLD_FW_FLUSH = 0x34 - IP_OLD_FW_GET = 0x36 - IP_OLD_FW_RESETLOG = 0x38 - IP_OLD_FW_ZERO = 0x35 - IP_OPTIONS = 0x1 - IP_PKTINFO = 0x1a - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVPKTINFO = 0x1a - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x18 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_STRIPHDR = 0x17 - IP_TOS = 0x3 - IP_TRAFFIC_MGT_BACKGROUND = 0x41 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_CAN_REUSE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_FREE_REUSABLE = 0x7 - MADV_FREE_REUSE = 0x8 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MADV_ZERO_WIRED_PAGES = 0x6 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_JIT = 0x800 - MAP_NOCACHE = 0x400 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_SHARED = 0x1 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FLUSH = 0x400 - MSG_HAVEMORE = 0x2000 - MSG_HOLD = 0x800 - MSG_NEEDSA = 0x10000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_RCVMORE = 0x4000 - MSG_SEND = 0x1000 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MSG_WAITSTREAM = 0x200 - MS_ASYNC = 0x1 - MS_DEACTIVATE = 0x8 - MS_INVALIDATE = 0x2 - MS_KILLPAGES = 0x4 - MS_SYNC = 0x10 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_DUMP2 = 0x7 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLIST2 = 0x6 - NET_RT_MAXID = 0xa - NET_RT_STAT = 0x4 - NET_RT_TRASH = 0x5 - NOFLSH = 0x80000000 - NOTE_ABSOLUTE = 0x8 - NOTE_ATTRIB = 0x8 - NOTE_BACKGROUND = 0x40 - NOTE_CHILD = 0x4 - NOTE_CRITICAL = 0x20 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXITSTATUS = 0x4000000 - NOTE_EXIT_CSERROR = 0x40000 - NOTE_EXIT_DECRYPTFAIL = 0x10000 - NOTE_EXIT_DETAIL = 0x2000000 - NOTE_EXIT_DETAIL_MASK = 0x70000 - NOTE_EXIT_MEMORY = 0x20000 - NOTE_EXIT_REPARENTED = 0x80000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LEEWAY = 0x10 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_NONE = 0x80 - NOTE_NSECONDS = 0x4 - NOTE_PCTRLMASK = -0x100000 - NOTE_PDATAMASK = 0xfffff - NOTE_REAP = 0x10000000 - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_SECONDS = 0x1 - NOTE_SIGNAL = 0x8000000 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_USECONDS = 0x2 - NOTE_VM_ERROR = 0x10000000 - NOTE_VM_PRESSURE = 0x80000000 - NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 - NOTE_VM_PRESSURE_TERMINATE = 0x40000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFDEL = 0x20000 - OFILL = 0x80 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALERT = 0x20000000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x1000000 - O_CREAT = 0x200 - O_DIRECTORY = 0x100000 - O_DP_GETRAWENCRYPTED = 0x1 - O_DSYNC = 0x400000 - O_EVTONLY = 0x8000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x20000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_POPUP = 0x80000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYMLINK = 0x200000 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PT_ATTACH = 0xa - PT_ATTACHEXC = 0xe - PT_CONTINUE = 0x7 - PT_DENY_ATTACH = 0x1f - PT_DETACH = 0xb - PT_FIRSTMACH = 0x20 - PT_FORCEQUOTA = 0x1e - PT_KILL = 0x8 - PT_READ_D = 0x2 - PT_READ_I = 0x1 - PT_READ_U = 0x3 - PT_SIGEXC = 0xc - PT_STEP = 0x9 - PT_THUPDATE = 0xd - PT_TRACE_ME = 0x0 - PT_WRITE_D = 0x5 - PT_WRITE_I = 0x4 - PT_WRITE_U = 0x6 - RLIMIT_AS = 0x5 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_CPU_USAGE_MONITOR = 0x2 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_CONDEMNED = 0x2000000 - RTF_DELCLONE = 0x80 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_IFREF = 0x4000000 - RTF_IFSCOPE = 0x1000000 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_NOIFREF = 0x2000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_PROXY = 0x8000000 - RTF_REJECT = 0x8 - RTF_ROUTER = 0x10000000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_GET2 = 0x14 - RTM_IFINFO = 0xe - RTM_IFINFO2 = 0x12 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_NEWMADDR2 = 0x13 - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SCM_TIMESTAMP_MONOTONIC = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCARPIPLL = 0xc0206928 - SIOCATMARK = 0x40047307 - SIOCAUTOADDR = 0xc0206926 - SIOCAUTONETMASK = 0x80206927 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206941 - SIOCGDRVSPEC = 0xc028697b - SIOCGETVLAN = 0xc020697f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFALTMTU = 0xc0206948 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBOND = 0xc0206947 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020695b - SIOCGIFCONF = 0xc00c6924 - SIOCGIFDEVMTU = 0xc0206944 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFKPI = 0xc0206987 - SIOCGIFMAC = 0xc0206982 - SIOCGIFMEDIA = 0xc02c6938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206940 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc020693f - SIOCGIFSTATUS = 0xc331693d - SIOCGIFVLAN = 0xc020697f - SIOCGIFWAKEFLAGS = 0xc0206988 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCIFCREATE = 0xc0206978 - SIOCIFCREATE2 = 0xc020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106981 - SIOCRSLVMULTI = 0xc010693b - SIOCSDRVSPEC = 0x8028697b - SIOCSETVLAN = 0x8020697e - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFALTMTU = 0x80206945 - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBOND = 0x80206946 - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020695a - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFKPI = 0x80206986 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206983 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x8040693e - SIOCSIFPHYS = 0x80206936 - SIOCSIFVLAN = 0x8020697e - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_DONTTRUNC = 0x2000 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1010 - SO_LINGER = 0x80 - SO_LINGER_SEC = 0x1080 - SO_NKE = 0x1021 - SO_NOADDRERR = 0x1023 - SO_NOSIGPIPE = 0x1022 - SO_NOTIFYCONFLICT = 0x1026 - SO_NP_EXTENSIONS = 0x1083 - SO_NREAD = 0x1020 - SO_NUMRCVPKT = 0x1112 - SO_NWRITE = 0x1024 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1011 - SO_RANDOMPORT = 0x1082 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_REUSESHAREUID = 0x1025 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TIMESTAMP_MONOTONIC = 0x800 - SO_TYPE = 0x1008 - SO_UPCALLCLOSEWAIT = 0x1027 - SO_USELOOPBACK = 0x40 - SO_WANTMORE = 0x4000 - SO_WANTOOBFLAG = 0x8000 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONNECTIONTIMEOUT = 0x20 - TCP_ENABLE_ECN = 0x104 - TCP_KEEPALIVE = 0x10 - TCP_KEEPCNT = 0x102 - TCP_KEEPINTVL = 0x101 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0xd8 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_NOTSENT_LOWAT = 0x201 - TCP_RXT_CONNDROPTIME = 0x80 - TCP_RXT_FINDROP = 0x100 - TCP_SENDMOREACKS = 0x103 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40107458 - TIOCDRAIN = 0x2000745e - TIOCDSIMICROCODE = 0x20007455 - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x40487413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGWINSZ = 0x40087468 - TIOCIXOFF = 0x20007480 - TIOCIXON = 0x20007481 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTYGNAME = 0x40807453 - TIOCPTYGRANT = 0x20007454 - TIOCPTYUNLK = 0x20007452 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCONS = 0x20007463 - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x80487414 - TIOCSETAF = 0x80487416 - TIOCSETAW = 0x80487415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40107459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x10 - WCOREFLAG = 0x80 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOWAIT = 0x20 - WORDSIZE = 0x40 - WSTOPPED = 0x8 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADARCH = syscall.Errno(0x56) - EBADEXEC = syscall.Errno(0x55) - EBADF = syscall.Errno(0x9) - EBADMACHO = syscall.Errno(0x58) - EBADMSG = syscall.Errno(0x5e) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x59) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDEVERR = syscall.Errno(0x53) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x5a) - EILSEQ = syscall.Errno(0x5c) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x6a) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5f) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x60) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x61) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5b) - ENOPOLICY = syscall.Errno(0x67) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x62) - ENOSTR = syscall.Errno(0x63) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x68) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x66) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x69) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x64) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - EPWROFF = syscall.Errno(0x52) - EQFULL = syscall.Errno(0x6a) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHLIBVERS = syscall.Errno(0x57) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x65) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_386.go deleted file mode 100644 index 2a329f06e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_386.go +++ /dev/null @@ -1,1530 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,dragonfly - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ATM = 0x1e - AF_BLUETOOTH = 0x21 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x23 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1c - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x24 - AF_MPLS = 0x22 - AF_NATM = 0x1d - AF_NETGRAPH = 0x20 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0084279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4008426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x2000427a - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80084267 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x8008427b - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8008426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DEFAULTBUFSIZE = 0x1000 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MAX_CLONES = 0x80 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DOCSIS = 0x8f - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_REDBACK_SMARTEDGE = 0x20 - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DBF = 0xf - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_EXCEPT = -0x8 - EVFILT_MARKER = 0xf - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0x8 - EVFILT_TIMER = -0x7 - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_NODATA = 0x1000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTEXIT_LWP = 0x10000 - EXTEXIT_PROC = 0x0 - EXTEXIT_SETINT = 0x1 - EXTEXIT_SIMPLE = 0x0 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_DUP2FD = 0xa - F_DUP2FD_CLOEXEC = 0x12 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x11 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETOWN = 0x5 - F_OK = 0x0 - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x118e72 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MONITOR = 0x40000 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NPOLLING = 0x100000 - IFF_OACTIVE = 0x400 - IFF_OACTIVE_COMPAT = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_POLLING = 0x10000 - IFF_POLLING_COMPAT = 0x10000 - IFF_PPROMISC = 0x20000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_SMART = 0x20 - IFF_STATICARP = 0x80000 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xf3 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VOICEEM = 0x64 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CARP = 0x70 - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MOBILE = 0x37 - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SKIP = 0x39 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TLSP = 0x38 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_UNKNOWN = 0x102 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_BINDV6ONLY = 0x1b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MSFILTER = 0x4a - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PKTOPTIONS = 0x34 - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_PREFER_TEMPADDR = 0x3f - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x32 - IP_FW_DEL = 0x33 - IP_FW_FLUSH = 0x34 - IP_FW_GET = 0x36 - IP_FW_RESETLOG = 0x37 - IP_FW_ZERO = 0x35 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x42 - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x41 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_AUTOSYNC = 0x7 - MADV_CONTROL_END = 0xb - MADV_CONTROL_START = 0xa - MADV_CORE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_INVAL = 0xa - MADV_NOCORE = 0x8 - MADV_NORMAL = 0x0 - MADV_NOSYNC = 0x6 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SETMAP = 0xb - MADV_WILLNEED = 0x3 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_NOCORE = 0x20000 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_NOSYNC = 0x800 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_SIZEALIGN = 0x40000 - MAP_STACK = 0x400 - MAP_TRYFIXED = 0x10000 - MAP_VPAGETABLE = 0x2000 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FBLOCKING = 0x10000 - MSG_FMASK = 0xffff0000 - MSG_FNONBLOCKING = 0x20000 - MSG_NOSIGNAL = 0x400 - MSG_NOTIFICATION = 0x200 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_SYNC = 0x800 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x0 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_MAXID = 0x4 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_OOB = 0x2 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x20000 - O_CREAT = 0x200 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x8000000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FAPPEND = 0x100000 - O_FASYNCWRITE = 0x800000 - O_FBLOCKING = 0x40000 - O_FBUFFERED = 0x2000000 - O_FMASK = 0x7fc0000 - O_FNONBLOCKING = 0x80000 - O_FOFFSET = 0x200000 - O_FSYNC = 0x80 - O_FSYNCWRITE = 0x400000 - O_FUNBUFFERED = 0x1000000 - O_MAPONREAD = 0x4000000 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0xb - RTAX_MPLS1 = 0x8 - RTAX_MPLS2 = 0x9 - RTAX_MPLS3 = 0xa - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_MPLS1 = 0x100 - RTA_MPLS2 = 0x200 - RTA_MPLS3 = 0x400 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MPLSOPS = 0x1000000 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_REJECT = 0x8 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x12 - RTM_IFANNOUNCE = 0x11 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x6 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_IWCAPSEGS = 0x400 - RTV_IWMAXSEGS = 0x200 - RTV_MSL = 0x100 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCADDRT = 0x8030720a - SIOCAIFADDR = 0x8040691a - SIOCALIFADDR = 0x8118691b - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80206932 - SIOCDELRT = 0x8030720b - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8118691d - SIOCGDRVSPEC = 0xc01c697b - SIOCGETSGCNT = 0xc0147210 - SIOCGETVIFCNT = 0xc014720f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020691f - SIOCGIFCONF = 0xc0086924 - SIOCGIFDATA = 0xc0206926 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc024698a - SIOCGIFINDEX = 0xc0206920 - SIOCGIFMEDIA = 0xc0286938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPOLLCPU = 0xc020697e - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFSTATUS = 0xc331693b - SIOCGIFTSOLEN = 0xc0206980 - SIOCGLIFADDR = 0xc118691c - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGPRIVATE_0 = 0xc0206950 - SIOCGPRIVATE_1 = 0xc0206951 - SIOCIFCREATE = 0xc020697a - SIOCIFCREATE2 = 0xc020697c - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCSDRVSPEC = 0x801c697b - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020691e - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNAME = 0x80206928 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPHYS = 0x80206936 - SIOCSIFPOLLCPU = 0x8020697d - SIOCSIFTSOLEN = 0x8020697f - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NOSIGPIPE = 0x800 - SO_OOBINLINE = 0x100 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDSPACE = 0x100a - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_FASTKEEP = 0x80 - TCP_KEEPCNT = 0x400 - TCP_KEEPIDLE = 0x100 - TCP_KEEPINIT = 0x20 - TCP_KEEPINTVL = 0x200 - TCP_MAXBURST = 0x4 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0x100 - TCP_MIN_WINSHIFT = 0x5 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_SIGNATURE_ENABLE = 0x10 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40087458 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGSID = 0x40047463 - TIOCGSIZE = 0x40087468 - TIOCGWINSZ = 0x40087468 - TIOCISPTMASTER = 0x20007455 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSSIZE = 0x80087467 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40087459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VCHECKPT = 0x13 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VERASE2 = 0x7 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x4 - WCOREFLAG = 0x80 - WLINUXCLONE = 0x80000000 - WNOHANG = 0x1 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EASYNC = syscall.Errno(0x63) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x59) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x55) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDOOFUS = syscall.Errno(0x58) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x56) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x63) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5a) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x57) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5b) - ENOMEDIUM = syscall.Errno(0x5d) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x5c) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUNUSED94 = syscall.Errno(0x5e) - EUNUSED95 = syscall.Errno(0x5f) - EUNUSED96 = syscall.Errno(0x60) - EUNUSED97 = syscall.Errno(0x61) - EUNUSED98 = syscall.Errno(0x62) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCKPT = syscall.Signal(0x21) - SIGCKPTEXIT = syscall.Signal(0x22) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "no medium found", - 94: "unknown error: 94", - 95: "unknown error: 95", - 96: "unknown error: 96", - 97: "unknown error: 97", - 98: "unknown error: 98", - 99: "unknown error: 99", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread Scheduler", - 33: "checkPoint", - 34: "checkPointExit", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go deleted file mode 100644 index 0feceee15..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go +++ /dev/null @@ -1,1530 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,dragonfly - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ATM = 0x1e - AF_BLUETOOTH = 0x21 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x23 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1c - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x24 - AF_MPLS = 0x22 - AF_NATM = 0x1d - AF_NETGRAPH = 0x20 - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SIP = 0x18 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0104279 - BIOCGETIF = 0x4020426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x2000427a - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044278 - BIOCSETF = 0x80104267 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x8010427b - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8010426d - BIOCSSEESENT = 0x80044277 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x8 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DEFAULTBUFSIZE = 0x1000 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MAX_CLONES = 0x80 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DOCSIS = 0x8f - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_REDBACK_SMARTEDGE = 0x20 - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DBF = 0xf - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_EXCEPT = -0x8 - EVFILT_MARKER = 0xf - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0x8 - EVFILT_TIMER = -0x7 - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_NODATA = 0x1000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTEXIT_LWP = 0x10000 - EXTEXIT_PROC = 0x0 - EXTEXIT_SETINT = 0x1 - EXTEXIT_SIMPLE = 0x0 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_DUP2FD = 0xa - F_DUP2FD_CLOEXEC = 0x12 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x11 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETOWN = 0x5 - F_OK = 0x0 - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x118e72 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MONITOR = 0x40000 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NPOLLING = 0x100000 - IFF_OACTIVE = 0x400 - IFF_OACTIVE_COMPAT = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_POLLING = 0x10000 - IFF_POLLING_COMPAT = 0x10000 - IFF_PPROMISC = 0x20000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_SMART = 0x20 - IFF_STATICARP = 0x80000 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xf3 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VOICEEM = 0x64 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CARP = 0x70 - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0xfe - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MOBILE = 0x37 - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEP = 0x21 - IPPROTO_SKIP = 0x39 - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TLSP = 0x38 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_UNKNOWN = 0x102 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_BINDV6ONLY = 0x1b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MSFILTER = 0x4a - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PKTOPTIONS = 0x34 - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_PREFER_TEMPADDR = 0x3f - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW_ADD = 0x32 - IP_FW_DEL = 0x33 - IP_FW_FLUSH = 0x34 - IP_FW_GET = 0x36 - IP_FW_RESETLOG = 0x37 - IP_FW_ZERO = 0x35 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x42 - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x41 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_AUTOSYNC = 0x7 - MADV_CONTROL_END = 0xb - MADV_CONTROL_START = 0xa - MADV_CORE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_INVAL = 0xa - MADV_NOCORE = 0x8 - MADV_NORMAL = 0x0 - MADV_NOSYNC = 0x6 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SETMAP = 0xb - MADV_WILLNEED = 0x3 - MAP_ANON = 0x1000 - MAP_COPY = 0x2 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_NOCORE = 0x20000 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_NOSYNC = 0x800 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_SIZEALIGN = 0x40000 - MAP_STACK = 0x400 - MAP_TRYFIXED = 0x10000 - MAP_VPAGETABLE = 0x2000 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_FBLOCKING = 0x10000 - MSG_FMASK = 0xffff0000 - MSG_FNONBLOCKING = 0x20000 - MSG_NOSIGNAL = 0x400 - MSG_NOTIFICATION = 0x200 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_SYNC = 0x800 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x0 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_MAXID = 0x4 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_OOB = 0x2 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x20000 - O_CREAT = 0x200 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x8000000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FAPPEND = 0x100000 - O_FASYNCWRITE = 0x800000 - O_FBLOCKING = 0x40000 - O_FBUFFERED = 0x2000000 - O_FMASK = 0x7fc0000 - O_FNONBLOCKING = 0x80000 - O_FOFFSET = 0x200000 - O_FSYNC = 0x80 - O_FSYNCWRITE = 0x400000 - O_FUNBUFFERED = 0x1000000 - O_MAPONREAD = 0x4000000 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0xb - RTAX_MPLS1 = 0x8 - RTAX_MPLS2 = 0x9 - RTAX_MPLS3 = 0xa - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_MPLS1 = 0x100 - RTA_MPLS2 = 0x200 - RTA_MPLS3 = 0x400 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MPLSOPS = 0x1000000 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_REJECT = 0x8 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_WASCLONED = 0x20000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x12 - RTM_IFANNOUNCE = 0x11 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x6 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_IWCAPSEGS = 0x400 - RTV_IWMAXSEGS = 0x200 - RTV_MSL = 0x100 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCADDRT = 0x8040720a - SIOCAIFADDR = 0x8040691a - SIOCALIFADDR = 0x8118691b - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80206932 - SIOCDELRT = 0x8040720b - SIOCDIFADDR = 0x80206919 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8118691d - SIOCGDRVSPEC = 0xc028697b - SIOCGETSGCNT = 0xc0207210 - SIOCGETVIFCNT = 0xc028720f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020691f - SIOCGIFCONF = 0xc0106924 - SIOCGIFDATA = 0xc0206926 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc028698a - SIOCGIFINDEX = 0xc0206920 - SIOCGIFMEDIA = 0xc0306938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPOLLCPU = 0xc020697e - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFSTATUS = 0xc331693b - SIOCGIFTSOLEN = 0xc0206980 - SIOCGLIFADDR = 0xc118691c - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGPRIVATE_0 = 0xc0206950 - SIOCGPRIVATE_1 = 0xc0206951 - SIOCIFCREATE = 0xc020697a - SIOCIFCREATE2 = 0xc020697c - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106978 - SIOCSDRVSPEC = 0x8028697b - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020691e - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNAME = 0x80206928 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPHYS = 0x80206936 - SIOCSIFPOLLCPU = 0x8020697d - SIOCSIFTSOLEN = 0x8020697f - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NOSIGPIPE = 0x800 - SO_OOBINLINE = 0x100 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDSPACE = 0x100a - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_FASTKEEP = 0x80 - TCP_KEEPCNT = 0x400 - TCP_KEEPIDLE = 0x100 - TCP_KEEPINIT = 0x20 - TCP_KEEPINTVL = 0x200 - TCP_MAXBURST = 0x4 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MINMSS = 0x100 - TCP_MIN_WINSHIFT = 0x5 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_SIGNATURE_ENABLE = 0x10 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x40107458 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGSID = 0x40047463 - TIOCGSIZE = 0x40087468 - TIOCGWINSZ = 0x40087468 - TIOCISPTMASTER = 0x20007455 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMODG = 0x40047403 - TIOCMODS = 0x80047404 - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2000745f - TIOCSPGRP = 0x80047476 - TIOCSSIZE = 0x80087467 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40107459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VCHECKPT = 0x13 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VERASE2 = 0x7 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x4 - WCOREFLAG = 0x80 - WLINUXCLONE = 0x80000000 - WNOHANG = 0x1 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EASYNC = syscall.Errno(0x63) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x59) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x55) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDOOFUS = syscall.Errno(0x58) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x56) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x63) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5a) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x57) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5b) - ENOMEDIUM = syscall.Errno(0x5d) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x5c) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUNUSED94 = syscall.Errno(0x5e) - EUNUSED95 = syscall.Errno(0x5f) - EUNUSED96 = syscall.Errno(0x60) - EUNUSED97 = syscall.Errno(0x61) - EUNUSED98 = syscall.Errno(0x62) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCKPT = syscall.Signal(0x21) - SIGCKPTEXIT = syscall.Signal(0x22) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "no medium found", - 94: "unknown error: 94", - 95: "unknown error: 95", - 96: "unknown error: 96", - 97: "unknown error: 97", - 98: "unknown error: 98", - 99: "unknown error: 99", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread Scheduler", - 33: "checkPoint", - 34: "checkPointExit", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_386.go deleted file mode 100644 index 7b95751c3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_386.go +++ /dev/null @@ -1,1743 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ARP = 0x23 - AF_ATM = 0x1e - AF_BLUETOOTH = 0x24 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1c - AF_INET6_SDP = 0x2a - AF_INET_SDP = 0x28 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x2a - AF_NATM = 0x1d - AF_NETBIOS = 0x6 - AF_NETGRAPH = 0x20 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SCLUSTER = 0x22 - AF_SIP = 0x18 - AF_SLOW = 0x21 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VENDOR00 = 0x27 - AF_VENDOR01 = 0x29 - AF_VENDOR02 = 0x2b - AF_VENDOR03 = 0x2d - AF_VENDOR04 = 0x2f - AF_VENDOR05 = 0x31 - AF_VENDOR06 = 0x33 - AF_VENDOR07 = 0x35 - AF_VENDOR08 = 0x37 - AF_VENDOR09 = 0x39 - AF_VENDOR10 = 0x3b - AF_VENDOR11 = 0x3d - AF_VENDOR12 = 0x3f - AF_VENDOR13 = 0x41 - AF_VENDOR14 = 0x43 - AF_VENDOR15 = 0x45 - AF_VENDOR16 = 0x47 - AF_VENDOR17 = 0x49 - AF_VENDOR18 = 0x4b - AF_VENDOR19 = 0x4d - AF_VENDOR20 = 0x4f - AF_VENDOR21 = 0x51 - AF_VENDOR22 = 0x53 - AF_VENDOR23 = 0x55 - AF_VENDOR24 = 0x57 - AF_VENDOR25 = 0x59 - AF_VENDOR26 = 0x5b - AF_VENDOR27 = 0x5d - AF_VENDOR28 = 0x5f - AF_VENDOR29 = 0x61 - AF_VENDOR30 = 0x63 - AF_VENDOR31 = 0x65 - AF_VENDOR32 = 0x67 - AF_VENDOR33 = 0x69 - AF_VENDOR34 = 0x6b - AF_VENDOR35 = 0x6d - AF_VENDOR36 = 0x6f - AF_VENDOR37 = 0x71 - AF_VENDOR38 = 0x73 - AF_VENDOR39 = 0x75 - AF_VENDOR40 = 0x77 - AF_VENDOR41 = 0x79 - AF_VENDOR42 = 0x7b - AF_VENDOR43 = 0x7d - AF_VENDOR44 = 0x7f - AF_VENDOR45 = 0x81 - AF_VENDOR46 = 0x83 - AF_VENDOR47 = 0x85 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B460800 = 0x70800 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B921600 = 0xe1000 - B9600 = 0x2580 - BIOCFEEDBACK = 0x8004427c - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDIRECTION = 0x40044276 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0084279 - BIOCGETBUFMODE = 0x4004427d - BIOCGETIF = 0x4020426b - BIOCGETZMAX = 0x4004427f - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4008426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCGTSTAMP = 0x40044283 - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x2000427a - BIOCPROMISC = 0x20004269 - BIOCROTZBUF = 0x400c4280 - BIOCSBLEN = 0xc0044266 - BIOCSDIRECTION = 0x80044277 - BIOCSDLT = 0x80044278 - BIOCSETBUFMODE = 0x8004427e - BIOCSETF = 0x80084267 - BIOCSETFNR = 0x80084282 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x8008427b - BIOCSETZBUF = 0x800c4281 - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8008426d - BIOCSSEESENT = 0x80044277 - BIOCSTSTAMP = 0x80044284 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_BUFMODE_BUFFER = 0x1 - BPF_BUFMODE_ZBUF = 0x2 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_T_BINTIME = 0x2 - BPF_T_BINTIME_FAST = 0x102 - BPF_T_BINTIME_MONOTONIC = 0x202 - BPF_T_BINTIME_MONOTONIC_FAST = 0x302 - BPF_T_FAST = 0x100 - BPF_T_FLAG_MASK = 0x300 - BPF_T_FORMAT_MASK = 0x3 - BPF_T_MICROTIME = 0x0 - BPF_T_MICROTIME_FAST = 0x100 - BPF_T_MICROTIME_MONOTONIC = 0x200 - BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 - BPF_T_MONOTONIC = 0x200 - BPF_T_MONOTONIC_FAST = 0x300 - BPF_T_NANOTIME = 0x1 - BPF_T_NANOTIME_FAST = 0x101 - BPF_T_NANOTIME_MONOTONIC = 0x201 - BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 - BPF_T_NONE = 0x3 - BPF_T_NORMAL = 0x0 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CLOCK_MONOTONIC = 0x4 - CLOCK_MONOTONIC_FAST = 0xc - CLOCK_MONOTONIC_PRECISE = 0xb - CLOCK_PROCESS_CPUTIME_ID = 0xf - CLOCK_PROF = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_FAST = 0xa - CLOCK_REALTIME_PRECISE = 0x9 - CLOCK_SECOND = 0xd - CLOCK_THREAD_CPUTIME_ID = 0xe - CLOCK_UPTIME = 0x5 - CLOCK_UPTIME_FAST = 0x8 - CLOCK_UPTIME_PRECISE = 0x7 - CLOCK_VIRTUAL = 0x1 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0x18 - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf6 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x79 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_LIO = -0xa - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xb - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xb - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_DROP = 0x1000 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTATTR_NAMESPACE_EMPTY = 0x0 - EXTATTR_NAMESPACE_SYSTEM = 0x2 - EXTATTR_NAMESPACE_USER = 0x1 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_CANCEL = 0x5 - F_DUP2FD = 0xa - F_DUP2FD_CLOEXEC = 0x12 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x11 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0xb - F_GETOWN = 0x5 - F_OGETLK = 0x7 - F_OK = 0x0 - F_OSETLK = 0x8 - F_OSETLKW = 0x9 - F_RDAHEAD = 0x10 - F_RDLCK = 0x1 - F_READAHEAD = 0xf - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0xc - F_SETLKW = 0xd - F_SETLK_REMOTE = 0xe - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_UNLCKSYS = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x218f72 - IFF_CANTCONFIG = 0x10000 - IFF_DEBUG = 0x4 - IFF_DRV_OACTIVE = 0x400 - IFF_DRV_RUNNING = 0x40 - IFF_DYING = 0x200000 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MONITOR = 0x40000 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PPROMISC = 0x20000 - IFF_PROMISC = 0x100 - IFF_RENAMING = 0x400000 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_SMART = 0x20 - IFF_STATICARP = 0x80000 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_IPXIP = 0xf9 - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf6 - IFT_PFSYNC = 0xf7 - IFT_PLC = 0xae - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xd7 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VOICEEM = 0x64 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IN_RFC3021_MASK = 0xfffffffe - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CARP = 0x70 - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0x102 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HIP = 0x8b - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MH = 0x87 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MOBILE = 0x37 - IPPROTO_MPLS = 0x89 - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OLD_DIVERT = 0xfe - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_RESERVED_253 = 0xfd - IPPROTO_RESERVED_254 = 0xfe - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEND = 0x103 - IPPROTO_SEP = 0x21 - IPPROTO_SHIM6 = 0x8c - IPPROTO_SKIP = 0x39 - IPPROTO_SPACER = 0x7fff - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TLSP = 0x38 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_BINDANY = 0x40 - IPV6_BINDV6ONLY = 0x1b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MSFILTER = 0x4a - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_PREFER_TEMPADDR = 0x3f - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BINDANY = 0x18 - IP_BLOCK_SOURCE = 0x48 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DONTFRAG = 0x43 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET3 = 0x31 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW3 = 0x30 - IP_FW_ADD = 0x32 - IP_FW_DEL = 0x33 - IP_FW_FLUSH = 0x34 - IP_FW_GET = 0x36 - IP_FW_NAT_CFG = 0x38 - IP_FW_NAT_DEL = 0x39 - IP_FW_NAT_GET_CONFIG = 0x3a - IP_FW_NAT_GET_LOG = 0x3b - IP_FW_RESETLOG = 0x37 - IP_FW_TABLE_ADD = 0x28 - IP_FW_TABLE_DEL = 0x29 - IP_FW_TABLE_FLUSH = 0x2a - IP_FW_TABLE_GETSIZE = 0x2b - IP_FW_TABLE_LIST = 0x2c - IP_FW_ZERO = 0x35 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 - IP_MF = 0x2000 - IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_OFFMASK = 0x1fff - IP_ONESBCAST = 0x17 - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTOS = 0x44 - IP_RECVTTL = 0x41 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_SENDSRCADDR = 0x7 - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_AUTOSYNC = 0x7 - MADV_CORE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_NOCORE = 0x8 - MADV_NORMAL = 0x0 - MADV_NOSYNC = 0x6 - MADV_PROTECT = 0xa - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MAP_ALIGNED_SUPER = 0x1000000 - MAP_ALIGNMENT_MASK = -0x1000000 - MAP_ALIGNMENT_SHIFT = 0x18 - MAP_ANON = 0x1000 - MAP_ANONYMOUS = 0x1000 - MAP_COPY = 0x2 - MAP_EXCL = 0x4000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_NOCORE = 0x20000 - MAP_NORESERVE = 0x40 - MAP_NOSYNC = 0x800 - MAP_PREFAULT_READ = 0x40000 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_RESERVED0100 = 0x100 - MAP_SHARED = 0x1 - MAP_STACK = 0x400 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CMSG_CLOEXEC = 0x40000 - MSG_COMPAT = 0x8000 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_NBIO = 0x4000 - MSG_NOSIGNAL = 0x20000 - MSG_NOTIFICATION = 0x2000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x0 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLISTL = 0x5 - NET_RT_IFMALIST = 0x4 - NET_RT_MAXID = 0x6 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x100000 - O_CREAT = 0x200 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x20000 - O_EXCL = 0x800 - O_EXEC = 0x40000 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_TTY_INIT = 0x80000 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x1004d808 - RTF_GATEWAY = 0x2 - RTF_GWFLAG_COMPAT = 0x80000000 - RTF_HOST = 0x4 - RTF_LLDATA = 0x400 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_REJECT = 0x8 - RTF_RNH_LOCKED = 0x40000000 - RTF_STATIC = 0x800 - RTF_STICKY = 0x10000000 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x12 - RTM_IFANNOUNCE = 0x11 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RTV_WEIGHT = 0x100 - RT_ALL_FIBS = -0x1 - RT_CACHING_CONTEXT = 0x1 - RT_DEFAULT_FIB = 0x0 - RT_NORTREF = 0x2 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_BINTIME = 0x4 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCADDRT = 0x8030720a - SIOCAIFADDR = 0x8040691a - SIOCAIFGROUP = 0x80246987 - SIOCALIFADDR = 0x8118691b - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80206932 - SIOCDELRT = 0x8030720b - SIOCDIFADDR = 0x80206919 - SIOCDIFGROUP = 0x80246989 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8118691d - SIOCGDRVSPEC = 0xc01c697b - SIOCGETSGCNT = 0xc0147210 - SIOCGETVIFCNT = 0xc014720f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020691f - SIOCGIFCONF = 0xc0086924 - SIOCGIFDESCR = 0xc020692a - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFIB = 0xc020695c - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc024698a - SIOCGIFGROUP = 0xc0246988 - SIOCGIFINDEX = 0xc0206920 - SIOCGIFMAC = 0xc0206926 - SIOCGIFMEDIA = 0xc0286938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFSTATUS = 0xc331693b - SIOCGLIFADDR = 0xc118691c - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGPRIVATE_0 = 0xc0206950 - SIOCGPRIVATE_1 = 0xc0206951 - SIOCIFCREATE = 0xc020697a - SIOCIFCREATE2 = 0xc020697c - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCSDRVSPEC = 0x801c697b - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020691e - SIOCSIFDESCR = 0x80206929 - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFIB = 0x8020695d - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206927 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNAME = 0x80206928 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPHYS = 0x80206936 - SIOCSIFRVNET = 0xc020695b - SIOCSIFVNET = 0xc020695a - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_CLOEXEC = 0x10000000 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_NONBLOCK = 0x20000000 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BINTIME = 0x2000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1009 - SO_LINGER = 0x80 - SO_LISTENINCQLEN = 0x1013 - SO_LISTENQLEN = 0x1012 - SO_LISTENQLIMIT = 0x1011 - SO_NOSIGPIPE = 0x800 - SO_NO_DDP = 0x8000 - SO_NO_OFFLOAD = 0x4000 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1010 - SO_PROTOCOL = 0x1016 - SO_PROTOTYPE = 0x1016 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SETFIB = 0x1014 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SO_USER_COOKIE = 0x1015 - SO_VENDOR = 0x80000000 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CA_NAME_MAX = 0x10 - TCP_CONGESTION = 0x40 - TCP_INFO = 0x20 - TCP_KEEPCNT = 0x400 - TCP_KEEPIDLE = 0x100 - TCP_KEEPINIT = 0x80 - TCP_KEEPINTVL = 0x200 - TCP_MAXBURST = 0x4 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x10 - TCP_MINMSS = 0xd8 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_VENDOR = 0x80000000 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGPTN = 0x4004740f - TIOCGSID = 0x40047463 - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DCD = 0x40 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTMASTER = 0x2000741c - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2004745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40087459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VERASE2 = 0x7 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x4 - WCOREFLAG = 0x80 - WEXITED = 0x10 - WLINUXCLONE = 0x80000000 - WNOHANG = 0x1 - WNOWAIT = 0x8 - WSTOPPED = 0x2 - WTRAPPED = 0x20 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x59) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x55) - ECAPMODE = syscall.Errno(0x5e) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDOOFUS = syscall.Errno(0x58) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x56) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x60) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5a) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x57) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCAPABLE = syscall.Errno(0x5d) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x5f) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x60) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x5c) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGLIBRT = syscall.Signal(0x21) - SIGLWP = syscall.Signal(0x20) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_amd64.go deleted file mode 100644 index e48e7799a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_amd64.go +++ /dev/null @@ -1,1748 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ARP = 0x23 - AF_ATM = 0x1e - AF_BLUETOOTH = 0x24 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1c - AF_INET6_SDP = 0x2a - AF_INET_SDP = 0x28 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x2a - AF_NATM = 0x1d - AF_NETBIOS = 0x6 - AF_NETGRAPH = 0x20 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SCLUSTER = 0x22 - AF_SIP = 0x18 - AF_SLOW = 0x21 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VENDOR00 = 0x27 - AF_VENDOR01 = 0x29 - AF_VENDOR02 = 0x2b - AF_VENDOR03 = 0x2d - AF_VENDOR04 = 0x2f - AF_VENDOR05 = 0x31 - AF_VENDOR06 = 0x33 - AF_VENDOR07 = 0x35 - AF_VENDOR08 = 0x37 - AF_VENDOR09 = 0x39 - AF_VENDOR10 = 0x3b - AF_VENDOR11 = 0x3d - AF_VENDOR12 = 0x3f - AF_VENDOR13 = 0x41 - AF_VENDOR14 = 0x43 - AF_VENDOR15 = 0x45 - AF_VENDOR16 = 0x47 - AF_VENDOR17 = 0x49 - AF_VENDOR18 = 0x4b - AF_VENDOR19 = 0x4d - AF_VENDOR20 = 0x4f - AF_VENDOR21 = 0x51 - AF_VENDOR22 = 0x53 - AF_VENDOR23 = 0x55 - AF_VENDOR24 = 0x57 - AF_VENDOR25 = 0x59 - AF_VENDOR26 = 0x5b - AF_VENDOR27 = 0x5d - AF_VENDOR28 = 0x5f - AF_VENDOR29 = 0x61 - AF_VENDOR30 = 0x63 - AF_VENDOR31 = 0x65 - AF_VENDOR32 = 0x67 - AF_VENDOR33 = 0x69 - AF_VENDOR34 = 0x6b - AF_VENDOR35 = 0x6d - AF_VENDOR36 = 0x6f - AF_VENDOR37 = 0x71 - AF_VENDOR38 = 0x73 - AF_VENDOR39 = 0x75 - AF_VENDOR40 = 0x77 - AF_VENDOR41 = 0x79 - AF_VENDOR42 = 0x7b - AF_VENDOR43 = 0x7d - AF_VENDOR44 = 0x7f - AF_VENDOR45 = 0x81 - AF_VENDOR46 = 0x83 - AF_VENDOR47 = 0x85 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B460800 = 0x70800 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B921600 = 0xe1000 - B9600 = 0x2580 - BIOCFEEDBACK = 0x8004427c - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDIRECTION = 0x40044276 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0104279 - BIOCGETBUFMODE = 0x4004427d - BIOCGETIF = 0x4020426b - BIOCGETZMAX = 0x4008427f - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCGTSTAMP = 0x40044283 - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x2000427a - BIOCPROMISC = 0x20004269 - BIOCROTZBUF = 0x40184280 - BIOCSBLEN = 0xc0044266 - BIOCSDIRECTION = 0x80044277 - BIOCSDLT = 0x80044278 - BIOCSETBUFMODE = 0x8004427e - BIOCSETF = 0x80104267 - BIOCSETFNR = 0x80104282 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x8010427b - BIOCSETZBUF = 0x80184281 - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8010426d - BIOCSSEESENT = 0x80044277 - BIOCSTSTAMP = 0x80044284 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x8 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_BUFMODE_BUFFER = 0x1 - BPF_BUFMODE_ZBUF = 0x2 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_T_BINTIME = 0x2 - BPF_T_BINTIME_FAST = 0x102 - BPF_T_BINTIME_MONOTONIC = 0x202 - BPF_T_BINTIME_MONOTONIC_FAST = 0x302 - BPF_T_FAST = 0x100 - BPF_T_FLAG_MASK = 0x300 - BPF_T_FORMAT_MASK = 0x3 - BPF_T_MICROTIME = 0x0 - BPF_T_MICROTIME_FAST = 0x100 - BPF_T_MICROTIME_MONOTONIC = 0x200 - BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 - BPF_T_MONOTONIC = 0x200 - BPF_T_MONOTONIC_FAST = 0x300 - BPF_T_NANOTIME = 0x1 - BPF_T_NANOTIME_FAST = 0x101 - BPF_T_NANOTIME_MONOTONIC = 0x201 - BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 - BPF_T_NONE = 0x3 - BPF_T_NORMAL = 0x0 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CLOCK_MONOTONIC = 0x4 - CLOCK_MONOTONIC_FAST = 0xc - CLOCK_MONOTONIC_PRECISE = 0xb - CLOCK_PROCESS_CPUTIME_ID = 0xf - CLOCK_PROF = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_FAST = 0xa - CLOCK_REALTIME_PRECISE = 0x9 - CLOCK_SECOND = 0xd - CLOCK_THREAD_CPUTIME_ID = 0xe - CLOCK_UPTIME = 0x5 - CLOCK_UPTIME_FAST = 0x8 - CLOCK_UPTIME_PRECISE = 0x7 - CLOCK_VIRTUAL = 0x1 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0x18 - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf6 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x79 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_LIO = -0xa - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xb - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xb - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_DROP = 0x1000 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTATTR_NAMESPACE_EMPTY = 0x0 - EXTATTR_NAMESPACE_SYSTEM = 0x2 - EXTATTR_NAMESPACE_USER = 0x1 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_CANCEL = 0x5 - F_DUP2FD = 0xa - F_DUP2FD_CLOEXEC = 0x12 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x11 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0xb - F_GETOWN = 0x5 - F_OGETLK = 0x7 - F_OK = 0x0 - F_OSETLK = 0x8 - F_OSETLKW = 0x9 - F_RDAHEAD = 0x10 - F_RDLCK = 0x1 - F_READAHEAD = 0xf - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0xc - F_SETLKW = 0xd - F_SETLK_REMOTE = 0xe - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_UNLCKSYS = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x218f72 - IFF_CANTCONFIG = 0x10000 - IFF_DEBUG = 0x4 - IFF_DRV_OACTIVE = 0x400 - IFF_DRV_RUNNING = 0x40 - IFF_DYING = 0x200000 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MONITOR = 0x40000 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PPROMISC = 0x20000 - IFF_PROMISC = 0x100 - IFF_RENAMING = 0x400000 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_SMART = 0x20 - IFF_STATICARP = 0x80000 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_IPXIP = 0xf9 - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf6 - IFT_PFSYNC = 0xf7 - IFT_PLC = 0xae - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xd7 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VOICEEM = 0x64 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IN_RFC3021_MASK = 0xfffffffe - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CARP = 0x70 - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0x102 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HIP = 0x8b - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MH = 0x87 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MOBILE = 0x37 - IPPROTO_MPLS = 0x89 - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OLD_DIVERT = 0xfe - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_RESERVED_253 = 0xfd - IPPROTO_RESERVED_254 = 0xfe - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEND = 0x103 - IPPROTO_SEP = 0x21 - IPPROTO_SHIM6 = 0x8c - IPPROTO_SKIP = 0x39 - IPPROTO_SPACER = 0x7fff - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TLSP = 0x38 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_BINDANY = 0x40 - IPV6_BINDV6ONLY = 0x1b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MSFILTER = 0x4a - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_PREFER_TEMPADDR = 0x3f - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BINDANY = 0x18 - IP_BLOCK_SOURCE = 0x48 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DONTFRAG = 0x43 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET3 = 0x31 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW3 = 0x30 - IP_FW_ADD = 0x32 - IP_FW_DEL = 0x33 - IP_FW_FLUSH = 0x34 - IP_FW_GET = 0x36 - IP_FW_NAT_CFG = 0x38 - IP_FW_NAT_DEL = 0x39 - IP_FW_NAT_GET_CONFIG = 0x3a - IP_FW_NAT_GET_LOG = 0x3b - IP_FW_RESETLOG = 0x37 - IP_FW_TABLE_ADD = 0x28 - IP_FW_TABLE_DEL = 0x29 - IP_FW_TABLE_FLUSH = 0x2a - IP_FW_TABLE_GETSIZE = 0x2b - IP_FW_TABLE_LIST = 0x2c - IP_FW_ZERO = 0x35 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 - IP_MF = 0x2000 - IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_OFFMASK = 0x1fff - IP_ONESBCAST = 0x17 - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTOS = 0x44 - IP_RECVTTL = 0x41 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_SENDSRCADDR = 0x7 - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_AUTOSYNC = 0x7 - MADV_CORE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_NOCORE = 0x8 - MADV_NORMAL = 0x0 - MADV_NOSYNC = 0x6 - MADV_PROTECT = 0xa - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MAP_32BIT = 0x80000 - MAP_ALIGNED_SUPER = 0x1000000 - MAP_ALIGNMENT_MASK = -0x1000000 - MAP_ALIGNMENT_SHIFT = 0x18 - MAP_ANON = 0x1000 - MAP_ANONYMOUS = 0x1000 - MAP_COPY = 0x2 - MAP_EXCL = 0x4000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_NOCORE = 0x20000 - MAP_NORESERVE = 0x40 - MAP_NOSYNC = 0x800 - MAP_PREFAULT_READ = 0x40000 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_RESERVED0100 = 0x100 - MAP_SHARED = 0x1 - MAP_STACK = 0x400 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CMSG_CLOEXEC = 0x40000 - MSG_COMPAT = 0x8000 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_NBIO = 0x4000 - MSG_NOSIGNAL = 0x20000 - MSG_NOTIFICATION = 0x2000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x0 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLISTL = 0x5 - NET_RT_IFMALIST = 0x4 - NET_RT_MAXID = 0x6 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_MSECONDS = 0x2 - NOTE_NSECONDS = 0x8 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_SECONDS = 0x1 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_USECONDS = 0x4 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x100000 - O_CREAT = 0x200 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x20000 - O_EXCL = 0x800 - O_EXEC = 0x40000 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_TTY_INIT = 0x80000 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x1004d808 - RTF_GATEWAY = 0x2 - RTF_GWFLAG_COMPAT = 0x80000000 - RTF_HOST = 0x4 - RTF_LLDATA = 0x400 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_REJECT = 0x8 - RTF_RNH_LOCKED = 0x40000000 - RTF_STATIC = 0x800 - RTF_STICKY = 0x10000000 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x12 - RTM_IFANNOUNCE = 0x11 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RTV_WEIGHT = 0x100 - RT_ALL_FIBS = -0x1 - RT_CACHING_CONTEXT = 0x1 - RT_DEFAULT_FIB = 0x0 - RT_NORTREF = 0x2 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_BINTIME = 0x4 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCADDRT = 0x8040720a - SIOCAIFADDR = 0x8040691a - SIOCAIFGROUP = 0x80286987 - SIOCALIFADDR = 0x8118691b - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80206932 - SIOCDELRT = 0x8040720b - SIOCDIFADDR = 0x80206919 - SIOCDIFGROUP = 0x80286989 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8118691d - SIOCGDRVSPEC = 0xc028697b - SIOCGETSGCNT = 0xc0207210 - SIOCGETVIFCNT = 0xc028720f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020691f - SIOCGIFCONF = 0xc0106924 - SIOCGIFDESCR = 0xc020692a - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFIB = 0xc020695c - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc028698a - SIOCGIFGROUP = 0xc0286988 - SIOCGIFINDEX = 0xc0206920 - SIOCGIFMAC = 0xc0206926 - SIOCGIFMEDIA = 0xc0306938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFSTATUS = 0xc331693b - SIOCGLIFADDR = 0xc118691c - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGPRIVATE_0 = 0xc0206950 - SIOCGPRIVATE_1 = 0xc0206951 - SIOCIFCREATE = 0xc020697a - SIOCIFCREATE2 = 0xc020697c - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106978 - SIOCSDRVSPEC = 0x8028697b - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020691e - SIOCSIFDESCR = 0x80206929 - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFIB = 0x8020695d - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206927 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNAME = 0x80206928 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPHYS = 0x80206936 - SIOCSIFRVNET = 0xc020695b - SIOCSIFVNET = 0xc020695a - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_CLOEXEC = 0x10000000 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_NONBLOCK = 0x20000000 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BINTIME = 0x2000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1009 - SO_LINGER = 0x80 - SO_LISTENINCQLEN = 0x1013 - SO_LISTENQLEN = 0x1012 - SO_LISTENQLIMIT = 0x1011 - SO_NOSIGPIPE = 0x800 - SO_NO_DDP = 0x8000 - SO_NO_OFFLOAD = 0x4000 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1010 - SO_PROTOCOL = 0x1016 - SO_PROTOTYPE = 0x1016 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SETFIB = 0x1014 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SO_USER_COOKIE = 0x1015 - SO_VENDOR = 0x80000000 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CA_NAME_MAX = 0x10 - TCP_CONGESTION = 0x40 - TCP_INFO = 0x20 - TCP_KEEPCNT = 0x400 - TCP_KEEPIDLE = 0x100 - TCP_KEEPINIT = 0x80 - TCP_KEEPINTVL = 0x200 - TCP_MAXBURST = 0x4 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x10 - TCP_MINMSS = 0xd8 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_VENDOR = 0x80000000 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGPTN = 0x4004740f - TIOCGSID = 0x40047463 - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DCD = 0x40 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTMASTER = 0x2000741c - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2004745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40107459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VERASE2 = 0x7 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x4 - WCOREFLAG = 0x80 - WEXITED = 0x10 - WLINUXCLONE = 0x80000000 - WNOHANG = 0x1 - WNOWAIT = 0x8 - WSTOPPED = 0x2 - WTRAPPED = 0x20 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x59) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x55) - ECAPMODE = syscall.Errno(0x5e) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDOOFUS = syscall.Errno(0x58) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x56) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x60) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5a) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x57) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCAPABLE = syscall.Errno(0x5d) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x5f) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x60) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x5c) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGLIBRT = syscall.Signal(0x21) - SIGLWP = syscall.Signal(0x20) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_arm.go deleted file mode 100644 index 2afbe2d5e..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_arm.go +++ /dev/null @@ -1,1729 +0,0 @@ -// mkerrors.sh -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,freebsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ARP = 0x23 - AF_ATM = 0x1e - AF_BLUETOOTH = 0x24 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x25 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1c - AF_INET6_SDP = 0x2a - AF_INET_SDP = 0x28 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x2a - AF_NATM = 0x1d - AF_NETBIOS = 0x6 - AF_NETGRAPH = 0x20 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SCLUSTER = 0x22 - AF_SIP = 0x18 - AF_SLOW = 0x21 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VENDOR00 = 0x27 - AF_VENDOR01 = 0x29 - AF_VENDOR02 = 0x2b - AF_VENDOR03 = 0x2d - AF_VENDOR04 = 0x2f - AF_VENDOR05 = 0x31 - AF_VENDOR06 = 0x33 - AF_VENDOR07 = 0x35 - AF_VENDOR08 = 0x37 - AF_VENDOR09 = 0x39 - AF_VENDOR10 = 0x3b - AF_VENDOR11 = 0x3d - AF_VENDOR12 = 0x3f - AF_VENDOR13 = 0x41 - AF_VENDOR14 = 0x43 - AF_VENDOR15 = 0x45 - AF_VENDOR16 = 0x47 - AF_VENDOR17 = 0x49 - AF_VENDOR18 = 0x4b - AF_VENDOR19 = 0x4d - AF_VENDOR20 = 0x4f - AF_VENDOR21 = 0x51 - AF_VENDOR22 = 0x53 - AF_VENDOR23 = 0x55 - AF_VENDOR24 = 0x57 - AF_VENDOR25 = 0x59 - AF_VENDOR26 = 0x5b - AF_VENDOR27 = 0x5d - AF_VENDOR28 = 0x5f - AF_VENDOR29 = 0x61 - AF_VENDOR30 = 0x63 - AF_VENDOR31 = 0x65 - AF_VENDOR32 = 0x67 - AF_VENDOR33 = 0x69 - AF_VENDOR34 = 0x6b - AF_VENDOR35 = 0x6d - AF_VENDOR36 = 0x6f - AF_VENDOR37 = 0x71 - AF_VENDOR38 = 0x73 - AF_VENDOR39 = 0x75 - AF_VENDOR40 = 0x77 - AF_VENDOR41 = 0x79 - AF_VENDOR42 = 0x7b - AF_VENDOR43 = 0x7d - AF_VENDOR44 = 0x7f - AF_VENDOR45 = 0x81 - AF_VENDOR46 = 0x83 - AF_VENDOR47 = 0x85 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B460800 = 0x70800 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B921600 = 0xe1000 - B9600 = 0x2580 - BIOCFEEDBACK = 0x8004427c - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDIRECTION = 0x40044276 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0084279 - BIOCGETBUFMODE = 0x4004427d - BIOCGETIF = 0x4020426b - BIOCGETZMAX = 0x4004427f - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044272 - BIOCGRTIMEOUT = 0x4008426e - BIOCGSEESENT = 0x40044276 - BIOCGSTATS = 0x4008426f - BIOCGTSTAMP = 0x40044283 - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x2000427a - BIOCPROMISC = 0x20004269 - BIOCROTZBUF = 0x400c4280 - BIOCSBLEN = 0xc0044266 - BIOCSDIRECTION = 0x80044277 - BIOCSDLT = 0x80044278 - BIOCSETBUFMODE = 0x8004427e - BIOCSETF = 0x80084267 - BIOCSETFNR = 0x80084282 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x8008427b - BIOCSETZBUF = 0x800c4281 - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044273 - BIOCSRTIMEOUT = 0x8008426d - BIOCSSEESENT = 0x80044277 - BIOCSTSTAMP = 0x80044284 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_BUFMODE_BUFFER = 0x1 - BPF_BUFMODE_ZBUF = 0x2 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x80000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_T_BINTIME = 0x2 - BPF_T_BINTIME_FAST = 0x102 - BPF_T_BINTIME_MONOTONIC = 0x202 - BPF_T_BINTIME_MONOTONIC_FAST = 0x302 - BPF_T_FAST = 0x100 - BPF_T_FLAG_MASK = 0x300 - BPF_T_FORMAT_MASK = 0x3 - BPF_T_MICROTIME = 0x0 - BPF_T_MICROTIME_FAST = 0x100 - BPF_T_MICROTIME_MONOTONIC = 0x200 - BPF_T_MICROTIME_MONOTONIC_FAST = 0x300 - BPF_T_MONOTONIC = 0x200 - BPF_T_MONOTONIC_FAST = 0x300 - BPF_T_NANOTIME = 0x1 - BPF_T_NANOTIME_FAST = 0x101 - BPF_T_NANOTIME_MONOTONIC = 0x201 - BPF_T_NANOTIME_MONOTONIC_FAST = 0x301 - BPF_T_NONE = 0x3 - BPF_T_NORMAL = 0x0 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0x18 - CTL_NET = 0x4 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CHDLC = 0x68 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DBUS = 0xe7 - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_DVB_CI = 0xeb - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NOFCS = 0xe6 - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPFILTER = 0x74 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xf2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_ATM_CEMIC = 0xee - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FIBRECHANNEL = 0xea - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_SRX_E2E = 0xe9 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_JUNIPER_VS = 0xe8 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_PPP_WITHDIRECTION = 0xa6 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0xf6 - DLT_MATCHING_MIN = 0x68 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPEG_2_TS = 0xf3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_MUX27010 = 0xec - DLT_NETANALYZER = 0xf0 - DLT_NETANALYZER_TRANSPARENT = 0xf1 - DLT_NFC_LLCP = 0xf5 - DLT_NFLOG = 0xef - DLT_NG40 = 0xf4 - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x79 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PPP_WITH_DIRECTION = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DLT_STANAG_5066_D_PDU = 0xed - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_USER0 = 0x93 - DLT_USER1 = 0x94 - DLT_USER10 = 0x9d - DLT_USER11 = 0x9e - DLT_USER12 = 0x9f - DLT_USER13 = 0xa0 - DLT_USER14 = 0xa1 - DLT_USER15 = 0xa2 - DLT_USER2 = 0x95 - DLT_USER3 = 0x96 - DLT_USER4 = 0x97 - DLT_USER5 = 0x98 - DLT_USER6 = 0x99 - DLT_USER7 = 0x9a - DLT_USER8 = 0x9b - DLT_USER9 = 0x9c - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EVFILT_AIO = -0x3 - EVFILT_FS = -0x9 - EVFILT_LIO = -0xa - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xb - EVFILT_TIMER = -0x7 - EVFILT_USER = -0xb - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_DISPATCH = 0x80 - EV_DROP = 0x1000 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_RECEIPT = 0x40 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTATTR_NAMESPACE_EMPTY = 0x0 - EXTATTR_NAMESPACE_SYSTEM = 0x2 - EXTATTR_NAMESPACE_USER = 0x1 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_CANCEL = 0x5 - F_DUP2FD = 0xa - F_DUP2FD_CLOEXEC = 0x12 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x11 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0xb - F_GETOWN = 0x5 - F_OGETLK = 0x7 - F_OK = 0x0 - F_OSETLK = 0x8 - F_OSETLKW = 0x9 - F_RDAHEAD = 0x10 - F_RDLCK = 0x1 - F_READAHEAD = 0xf - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0xc - F_SETLKW = 0xd - F_SETLK_REMOTE = 0xe - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_UNLCKSYS = 0x4 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ALTPHYS = 0x4000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x218f72 - IFF_CANTCONFIG = 0x10000 - IFF_DEBUG = 0x4 - IFF_DRV_OACTIVE = 0x400 - IFF_DRV_RUNNING = 0x40 - IFF_DYING = 0x200000 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MONITOR = 0x40000 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PPROMISC = 0x20000 - IFF_PROMISC = 0x100 - IFF_RENAMING = 0x400000 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_SMART = 0x20 - IFF_STATICARP = 0x80000 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_IPXIP = 0xf9 - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf6 - IFT_PFSYNC = 0xf7 - IFT_PLC = 0xae - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xd7 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VOICEEM = 0x64 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IN_RFC3021_MASK = 0xfffffffe - IPPROTO_3PC = 0x22 - IPPROTO_ADFS = 0x44 - IPPROTO_AH = 0x33 - IPPROTO_AHIP = 0x3d - IPPROTO_APES = 0x63 - IPPROTO_ARGUS = 0xd - IPPROTO_AX25 = 0x5d - IPPROTO_BHA = 0x31 - IPPROTO_BLT = 0x1e - IPPROTO_BRSATMON = 0x4c - IPPROTO_CARP = 0x70 - IPPROTO_CFTP = 0x3e - IPPROTO_CHAOS = 0x10 - IPPROTO_CMTP = 0x26 - IPPROTO_CPHB = 0x49 - IPPROTO_CPNX = 0x48 - IPPROTO_DDP = 0x25 - IPPROTO_DGP = 0x56 - IPPROTO_DIVERT = 0x102 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_EMCON = 0xe - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GMTP = 0x64 - IPPROTO_GRE = 0x2f - IPPROTO_HELLO = 0x3f - IPPROTO_HIP = 0x8b - IPPROTO_HMP = 0x14 - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IDPR = 0x23 - IPPROTO_IDRP = 0x2d - IPPROTO_IGMP = 0x2 - IPPROTO_IGP = 0x55 - IPPROTO_IGRP = 0x58 - IPPROTO_IL = 0x28 - IPPROTO_INLSP = 0x34 - IPPROTO_INP = 0x20 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPCV = 0x47 - IPPROTO_IPEIP = 0x5e - IPPROTO_IPIP = 0x4 - IPPROTO_IPPC = 0x43 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IRTP = 0x1c - IPPROTO_KRYPTOLAN = 0x41 - IPPROTO_LARP = 0x5b - IPPROTO_LEAF1 = 0x19 - IPPROTO_LEAF2 = 0x1a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MEAS = 0x13 - IPPROTO_MH = 0x87 - IPPROTO_MHRP = 0x30 - IPPROTO_MICP = 0x5f - IPPROTO_MOBILE = 0x37 - IPPROTO_MPLS = 0x89 - IPPROTO_MTP = 0x5c - IPPROTO_MUX = 0x12 - IPPROTO_ND = 0x4d - IPPROTO_NHRP = 0x36 - IPPROTO_NONE = 0x3b - IPPROTO_NSP = 0x1f - IPPROTO_NVPII = 0xb - IPPROTO_OLD_DIVERT = 0xfe - IPPROTO_OSPFIGP = 0x59 - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PGM = 0x71 - IPPROTO_PIGP = 0x9 - IPPROTO_PIM = 0x67 - IPPROTO_PRM = 0x15 - IPPROTO_PUP = 0xc - IPPROTO_PVP = 0x4b - IPPROTO_RAW = 0xff - IPPROTO_RCCMON = 0xa - IPPROTO_RDP = 0x1b - IPPROTO_RESERVED_253 = 0xfd - IPPROTO_RESERVED_254 = 0xfe - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_RVD = 0x42 - IPPROTO_SATEXPAK = 0x40 - IPPROTO_SATMON = 0x45 - IPPROTO_SCCSP = 0x60 - IPPROTO_SCTP = 0x84 - IPPROTO_SDRP = 0x2a - IPPROTO_SEND = 0x103 - IPPROTO_SEP = 0x21 - IPPROTO_SHIM6 = 0x8c - IPPROTO_SKIP = 0x39 - IPPROTO_SPACER = 0x7fff - IPPROTO_SRPC = 0x5a - IPPROTO_ST = 0x7 - IPPROTO_SVMTP = 0x52 - IPPROTO_SWIPE = 0x35 - IPPROTO_TCF = 0x57 - IPPROTO_TCP = 0x6 - IPPROTO_TLSP = 0x38 - IPPROTO_TP = 0x1d - IPPROTO_TPXX = 0x27 - IPPROTO_TRUNK1 = 0x17 - IPPROTO_TRUNK2 = 0x18 - IPPROTO_TTP = 0x54 - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPPROTO_VINES = 0x53 - IPPROTO_VISA = 0x46 - IPPROTO_VMTP = 0x51 - IPPROTO_WBEXPAK = 0x4f - IPPROTO_WBMON = 0x4e - IPPROTO_WSN = 0x4a - IPPROTO_XNET = 0xf - IPPROTO_XTP = 0x24 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_BINDANY = 0x40 - IPV6_BINDV6ONLY = 0x1b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_FW_ADD = 0x1e - IPV6_FW_DEL = 0x1f - IPV6_FW_FLUSH = 0x20 - IPV6_FW_GET = 0x22 - IPV6_FW_ZERO = 0x21 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXOPTHDR = 0x800 - IPV6_MAXPACKET = 0xffff - IPV6_MAX_GROUP_SRC_FILTER = 0x200 - IPV6_MAX_MEMBERSHIPS = 0xfff - IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f - IPV6_MMTU = 0x500 - IPV6_MSFILTER = 0x4a - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_PREFER_TEMPADDR = 0x3f - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_ADD_SOURCE_MEMBERSHIP = 0x46 - IP_BINDANY = 0x18 - IP_BLOCK_SOURCE = 0x48 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DONTFRAG = 0x43 - IP_DROP_MEMBERSHIP = 0xd - IP_DROP_SOURCE_MEMBERSHIP = 0x47 - IP_DUMMYNET3 = 0x31 - IP_DUMMYNET_CONFIGURE = 0x3c - IP_DUMMYNET_DEL = 0x3d - IP_DUMMYNET_FLUSH = 0x3e - IP_DUMMYNET_GET = 0x40 - IP_FAITH = 0x16 - IP_FW3 = 0x30 - IP_FW_ADD = 0x32 - IP_FW_DEL = 0x33 - IP_FW_FLUSH = 0x34 - IP_FW_GET = 0x36 - IP_FW_NAT_CFG = 0x38 - IP_FW_NAT_DEL = 0x39 - IP_FW_NAT_GET_CONFIG = 0x3a - IP_FW_NAT_GET_LOG = 0x3b - IP_FW_RESETLOG = 0x37 - IP_FW_TABLE_ADD = 0x28 - IP_FW_TABLE_DEL = 0x29 - IP_FW_TABLE_FLUSH = 0x2a - IP_FW_TABLE_GETSIZE = 0x2b - IP_FW_TABLE_LIST = 0x2c - IP_FW_ZERO = 0x35 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x15 - IP_MAXPACKET = 0xffff - IP_MAX_GROUP_SRC_FILTER = 0x200 - IP_MAX_MEMBERSHIPS = 0xfff - IP_MAX_SOCK_MUTE_FILTER = 0x80 - IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 - IP_MF = 0x2000 - IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f - IP_MSFILTER = 0x4a - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_MULTICAST_VIF = 0xe - IP_OFFMASK = 0x1fff - IP_ONESBCAST = 0x17 - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTOS = 0x44 - IP_RECVTTL = 0x41 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RSVP_OFF = 0x10 - IP_RSVP_ON = 0xf - IP_RSVP_VIF_OFF = 0x12 - IP_RSVP_VIF_ON = 0x11 - IP_SENDSRCADDR = 0x7 - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x49 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_AUTOSYNC = 0x7 - MADV_CORE = 0x9 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_NOCORE = 0x8 - MADV_NORMAL = 0x0 - MADV_NOSYNC = 0x6 - MADV_PROTECT = 0xa - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MAP_ALIGNED_SUPER = 0x1000000 - MAP_ALIGNMENT_MASK = -0x1000000 - MAP_ALIGNMENT_SHIFT = 0x18 - MAP_ANON = 0x1000 - MAP_ANONYMOUS = 0x1000 - MAP_COPY = 0x2 - MAP_EXCL = 0x4000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_NOCORE = 0x20000 - MAP_NORESERVE = 0x40 - MAP_NOSYNC = 0x800 - MAP_PREFAULT_READ = 0x40000 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_RESERVED0080 = 0x80 - MAP_RESERVED0100 = 0x100 - MAP_SHARED = 0x1 - MAP_STACK = 0x400 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CMSG_CLOEXEC = 0x40000 - MSG_COMPAT = 0x8000 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOF = 0x100 - MSG_EOR = 0x8 - MSG_NBIO = 0x4000 - MSG_NOSIGNAL = 0x20000 - MSG_NOTIFICATION = 0x2000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x0 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_IFLISTL = 0x5 - NET_RT_IFMALIST = 0x4 - NET_RT_MAXID = 0x6 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FFAND = 0x40000000 - NOTE_FFCOPY = 0xc0000000 - NOTE_FFCTRLMASK = 0xc0000000 - NOTE_FFLAGSMASK = 0xffffff - NOTE_FFNOP = 0x0 - NOTE_FFOR = 0x80000000 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRIGGER = 0x1000000 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x100000 - O_CREAT = 0x200 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x20000 - O_EXCL = 0x800 - O_EXEC = 0x40000 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_TTY_INIT = 0x80000 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x8 - RTAX_NETMASK = 0x2 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTF_BLACKHOLE = 0x1000 - RTF_BROADCAST = 0x400000 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x1004d808 - RTF_GATEWAY = 0x2 - RTF_GWFLAG_COMPAT = 0x80000000 - RTF_HOST = 0x4 - RTF_LLDATA = 0x400 - RTF_LLINFO = 0x400 - RTF_LOCAL = 0x200000 - RTF_MODIFIED = 0x20 - RTF_MULTICAST = 0x800000 - RTF_PINNED = 0x100000 - RTF_PRCLONING = 0x10000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x40000 - RTF_REJECT = 0x8 - RTF_RNH_LOCKED = 0x40000000 - RTF_STATIC = 0x800 - RTF_STICKY = 0x10000000 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DELMADDR = 0x10 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x12 - RTM_IFANNOUNCE = 0x11 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_NEWMADDR = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RTV_WEIGHT = 0x100 - RT_ALL_FIBS = -0x1 - RT_CACHING_CONTEXT = 0x1 - RT_DEFAULT_FIB = 0x0 - RT_NORTREF = 0x2 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_BINTIME = 0x4 - SCM_CREDS = 0x3 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x2 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCADDRT = 0x8030720a - SIOCAIFADDR = 0x8040691a - SIOCAIFGROUP = 0x80246987 - SIOCALIFADDR = 0x8118691b - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80206932 - SIOCDELRT = 0x8030720b - SIOCDIFADDR = 0x80206919 - SIOCDIFGROUP = 0x80246989 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8118691d - SIOCGDRVSPEC = 0xc01c697b - SIOCGETSGCNT = 0xc0147210 - SIOCGETVIFCNT = 0xc014720f - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCAP = 0xc020691f - SIOCGIFCONF = 0xc0086924 - SIOCGIFDESCR = 0xc020692a - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFIB = 0xc020695c - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc024698a - SIOCGIFGROUP = 0xc0246988 - SIOCGIFINDEX = 0xc0206920 - SIOCGIFMAC = 0xc0206926 - SIOCGIFMEDIA = 0xc0286938 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc0206933 - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPHYS = 0xc0206935 - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFSTATUS = 0xc331693b - SIOCGLIFADDR = 0xc118691c - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGPRIVATE_0 = 0xc0206950 - SIOCGPRIVATE_1 = 0xc0206951 - SIOCIFCREATE = 0xc020697a - SIOCIFCREATE2 = 0xc020697c - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCSDRVSPEC = 0x801c697b - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFCAP = 0x8020691e - SIOCSIFDESCR = 0x80206929 - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFIB = 0x8020695d - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020693c - SIOCSIFMAC = 0x80206927 - SIOCSIFMEDIA = 0xc0206937 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x80206934 - SIOCSIFNAME = 0x80206928 - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPHYS = 0x80206936 - SIOCSIFRVNET = 0xc020695b - SIOCSIFVNET = 0xc020695a - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SOCK_CLOEXEC = 0x10000000 - SOCK_DGRAM = 0x2 - SOCK_MAXADDRLEN = 0xff - SOCK_NONBLOCK = 0x20000000 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BINTIME = 0x2000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LABEL = 0x1009 - SO_LINGER = 0x80 - SO_LISTENINCQLEN = 0x1013 - SO_LISTENQLEN = 0x1012 - SO_LISTENQLIMIT = 0x1011 - SO_NOSIGPIPE = 0x800 - SO_NO_DDP = 0x8000 - SO_NO_OFFLOAD = 0x4000 - SO_OOBINLINE = 0x100 - SO_PEERLABEL = 0x1010 - SO_PROTOCOL = 0x1016 - SO_PROTOTYPE = 0x1016 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SETFIB = 0x1014 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_TIMESTAMP = 0x400 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SO_USER_COOKIE = 0x1015 - SO_VENDOR = 0x80000000 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CA_NAME_MAX = 0x10 - TCP_CONGESTION = 0x40 - TCP_INFO = 0x20 - TCP_KEEPCNT = 0x400 - TCP_KEEPIDLE = 0x100 - TCP_KEEPINIT = 0x80 - TCP_KEEPINTVL = 0x200 - TCP_MAXBURST = 0x4 - TCP_MAXHLEN = 0x3c - TCP_MAXOLEN = 0x28 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x4 - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x10 - TCP_MINMSS = 0xd8 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCP_NOOPT = 0x8 - TCP_NOPUSH = 0x4 - TCP_VENDOR = 0x80000000 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLUSH = 0x80047410 - TIOCGDRAINWAIT = 0x40047456 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGPGRP = 0x40047477 - TIOCGPTN = 0x4004740f - TIOCGSID = 0x40047463 - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGDTRWAIT = 0x4004745a - TIOCMGET = 0x4004746a - TIOCMSDTRWAIT = 0x8004745b - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DCD = 0x40 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTMASTER = 0x2000741c - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDRAINWAIT = 0x80047457 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSIG = 0x2004745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x20007465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCTIMESTAMP = 0x40087459 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VERASE2 = 0x7 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WCONTINUED = 0x4 - WCOREFLAG = 0x80 - WEXITED = 0x10 - WLINUXCLONE = 0x80000000 - WNOHANG = 0x1 - WNOWAIT = 0x8 - WSTOPPED = 0x2 - WTRAPPED = 0x20 - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x59) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x55) - ECAPMODE = syscall.Errno(0x5e) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDOOFUS = syscall.Errno(0x58) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x56) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x60) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5a) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x57) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCAPABLE = syscall.Errno(0x5d) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTRECOVERABLE = syscall.Errno(0x5f) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x2d) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EOWNERDEAD = syscall.Errno(0x60) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x5c) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGLIBRT = syscall.Signal(0x21) - SIGLWP = syscall.Signal(0x20) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_386.go deleted file mode 100644 index d370be0ec..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_386.go +++ /dev/null @@ -1,1817 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_NFC = 0x27 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CAIF = 0x336 - ARPHRD_CAN = 0x118 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PHONET = 0x334 - ARPHRD_PHONET_PIPE = 0x335 - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x1008 - B110 = 0x3 - B115200 = 0x1002 - B1152000 = 0x1009 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x100a - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x100b - B230400 = 0x1003 - B2400 = 0xb - B2500000 = 0x100c - B300 = 0x7 - B3000000 = 0x100d - B3500000 = 0x100e - B38400 = 0xf - B4000000 = 0x100f - B460800 = 0x1004 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x1005 - B57600 = 0x1001 - B576000 = 0x1006 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x1007 - B9600 = 0xd - BOTHER = 0x1000 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x2000 - BSDLY = 0x2000 - CBAUD = 0x100f - CBAUDEX = 0x1000 - CFLUSH = 0xf - CIBAUD = 0x100f0000 - CLOCAL = 0x800 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x200 - CR2 = 0x400 - CR3 = 0x600 - CRDLY = 0x600 - CREAD = 0x80 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x10 - CS7 = 0x20 - CS8 = 0x30 - CSIGNAL = 0xff - CSIZE = 0x30 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x40 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x200 - ECHOE = 0x10 - ECHOK = 0x20 - ECHOKE = 0x800 - ECHONL = 0x40 - ECHOPRT = 0x400 - ENCODING_DEFAULT = 0x0 - ENCODING_FM_MARK = 0x3 - ENCODING_FM_SPACE = 0x4 - ENCODING_MANCHESTER = 0x5 - ENCODING_NRZ = 0x1 - ENCODING_NRZI = 0x2 - EPOLLERR = 0x8 - EPOLLET = 0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - EPOLL_NONBLOCK = 0x800 - ETH_P_1588 = 0x88f7 - ETH_P_8021AD = 0x88a8 - ETH_P_8021AH = 0x88e7 - ETH_P_8021Q = 0x8100 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_AARP = 0x80f3 - ETH_P_AF_IUCV = 0xfbfb - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_QINQ1 = 0x9100 - ETH_P_QINQ2 = 0x9200 - ETH_P_QINQ3 = 0x9300 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TDLS = 0x890d - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x8000 - FFDLY = 0x8000 - FLUSHO = 0x1000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0xc - F_GETLK64 = 0xc - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0xd - F_SETLK64 = 0xd - F_SETLKW = 0xe - F_SETLKW64 = 0xe - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x400 - IBSHIFT = 0x10 - ICANON = 0x2 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x8000 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_NODAD = 0x2 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x7 - IFF_802_1Q_VLAN = 0x1 - IFF_ALLMULTI = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BONDING = 0x20 - IFF_BRIDGE_PORT = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DISABLE_NETPOLL = 0x1000 - IFF_DONT_BRIDGE = 0x800 - IFF_DORMANT = 0x20000 - IFF_DYNAMIC = 0x8000 - IFF_EBRIDGE = 0x2 - IFF_ECHO = 0x40000 - IFF_ISATAP = 0x80 - IFF_LOOPBACK = 0x8 - IFF_LOWER_UP = 0x10000 - IFF_MACVLAN_PORT = 0x2000 - IFF_MASTER = 0x400 - IFF_MASTER_8023AD = 0x8 - IFF_MASTER_ALB = 0x10 - IFF_MASTER_ARPMON = 0x100 - IFF_MULTICAST = 0x1000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_OVS_DATAPATH = 0x8000 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_SLAVE_INACTIVE = 0x4 - IFF_SLAVE_NEEDARP = 0x40 - IFF_TAP = 0x2 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_TX_SKB_SHARING = 0x10000 - IFF_UNICAST_FLT = 0x20000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFF_VOLATILE = 0x70c5a - IFF_WAN_HDLC = 0x200 - IFF_XMIT_DST_RELEASE = 0x400 - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_ALL = 0x31 - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_XFRM_POLICY = 0x11 - ISIG = 0x1 - ISTRIP = 0x20 - IUCLC = 0x200 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x1000 - IXON = 0x400 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DOFORK = 0xb - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_32BIT = 0x40 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_HUGETLB = 0x40000 - MAP_LOCKED = 0x2000 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x4000 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_STACK = 0x20000 - MAP_TYPE = 0xf - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_CRYPTO = 0x15 - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x100 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_DUMP_INTR = 0x10 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x2 - ONLCR = 0x4 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x4000 - O_DIRECTORY = 0x10000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x101000 - O_LARGEFILE = 0x8000 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x20000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x101000 - O_SYNC = 0x101000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_AUXDATA = 0x8 - PACKET_BROADCAST = 0x1 - PACKET_COPY_THRESH = 0x7 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FANOUT = 0x12 - PACKET_FANOUT_CPU = 0x2 - PACKET_FANOUT_FLAG_DEFRAG = 0x8000 - PACKET_FANOUT_HASH = 0x0 - PACKET_FANOUT_LB = 0x1 - PACKET_FASTROUTE = 0x6 - PACKET_HDRLEN = 0xb - PACKET_HOST = 0x0 - PACKET_LOOPBACK = 0x5 - PACKET_LOSS = 0xe - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MR_UNICAST = 0x3 - PACKET_MULTICAST = 0x2 - PACKET_ORIGDEV = 0x9 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RESERVE = 0xc - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PACKET_TIMESTAMP = 0x11 - PACKET_TX_RING = 0xd - PACKET_TX_TIMESTAMP = 0x10 - PACKET_VERSION = 0xa - PACKET_VNET_HDR = 0xf - PARENB = 0x100 - PARITY_CRC16_PR0 = 0x2 - PARITY_CRC16_PR0_CCITT = 0x4 - PARITY_CRC16_PR1 = 0x3 - PARITY_CRC16_PR1_CCITT = 0x5 - PARITY_CRC32_PR0_CCITT = 0x6 - PARITY_CRC32_PR1_CCITT = 0x7 - PARITY_DEFAULT = 0x0 - PARITY_NONE = 0x1 - PARMRK = 0x8 - PARODD = 0x200 - PENDIN = 0x4000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_NO_NEW_PRIVS = 0x27 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECUREBITS = 0x1b - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_MM = 0x23 - PR_SET_MM_BRK = 0x7 - PR_SET_MM_END_CODE = 0x2 - PR_SET_MM_END_DATA = 0x4 - PR_SET_MM_START_BRK = 0x6 - PR_SET_MM_START_CODE = 0x1 - PR_SET_MM_START_DATA = 0x3 - PR_SET_MM_START_STACK = 0x5 - PR_SET_NAME = 0xf - PR_SET_NO_NEW_PRIVS = 0x26 - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_PTRACER_ANY = 0xffffffff - PR_SET_SECCOMP = 0x16 - PR_SET_SECUREBITS = 0x1c - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_SECCOMP = 0x7 - PTRACE_EVENT_STOP = 0x80 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETFPREGS = 0xe - PTRACE_GETFPXREGS = 0x12 - PTRACE_GETREGS = 0xc - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GET_THREAD_AREA = 0x19 - PTRACE_INTERRUPT = 0x4207 - PTRACE_KILL = 0x8 - PTRACE_LISTEN = 0x4208 - PTRACE_OLDSETOPTIONS = 0x15 - PTRACE_O_MASK = 0xff - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESECCOMP = 0x80 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SEIZE = 0x4206 - PTRACE_SEIZE_DEVEL = 0x80000000 - PTRACE_SETFPREGS = 0xf - PTRACE_SETFPXREGS = 0x13 - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SET_THREAD_AREA = 0x1a - PTRACE_SINGLEBLOCK = 0x21 - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_SYSEMU = 0x1f - PTRACE_SYSEMU_SINGLESTEP = 0x20 - PTRACE_TRACEME = 0x0 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xe - RTAX_MTU = 0x2 - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x10 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x4f - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x10 - RTM_NR_MSGTYPES = 0x40 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_MARK = 0x24 - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x10 - SO_PASSSEC = 0x22 - SO_PEERCRED = 0x11 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x12 - SO_RCVTIMEO = 0x14 - SO_REUSEADDR = 0x2 - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x13 - SO_SNDTIMEO = 0x15 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x800 - TAB2 = 0x1000 - TAB3 = 0x1800 - TABDLY = 0x1800 - TCFLSH = 0x540b - TCGETA = 0x5405 - TCGETS = 0x5401 - TCGETS2 = 0x802c542a - TCGETX = 0x5432 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_QUICKACK = 0xc - TCP_SYNCNT = 0x7 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x5409 - TCSBRKP = 0x5425 - TCSETA = 0x5406 - TCSETAF = 0x5408 - TCSETAW = 0x5407 - TCSETS = 0x5402 - TCSETS2 = 0x402c542b - TCSETSF = 0x5404 - TCSETSF2 = 0x402c542d - TCSETSW = 0x5403 - TCSETSW2 = 0x402c542c - TCSETX = 0x5433 - TCSETXF = 0x5434 - TCSETXW = 0x5435 - TCXONC = 0x540a - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x80045432 - TIOCGETD = 0x5424 - TIOCGEXCL = 0x80045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGPGRP = 0x540f - TIOCGPKT = 0x80045438 - TIOCGPTLCK = 0x80045439 - TIOCGPTN = 0x80045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x5413 - TIOCINQ = 0x541b - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x5411 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETD = 0x5423 - TIOCSIG = 0x40045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSPGRP = 0x5410 - TIOCSPTLCK = 0x40045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTI = 0x5412 - TIOCSWINSZ = 0x5414 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x100 - TUNATTACHFILTER = 0x400854d5 - TUNDETACHFILTER = 0x400854d6 - TUNGETFEATURES = 0x800454cf - TUNGETIFF = 0x800454d2 - TUNGETSNDBUF = 0x800454d3 - TUNGETVNETHDRSZ = 0x800454d7 - TUNSETDEBUG = 0x400454c9 - TUNSETGROUP = 0x400454ce - TUNSETIFF = 0x400454ca - TUNSETLINK = 0x400454cd - TUNSETNOCSUM = 0x400454c8 - TUNSETOFFLOAD = 0x400454d0 - TUNSETOWNER = 0x400454cc - TUNSETPERSIST = 0x400454cb - TUNSETSNDBUF = 0x400454d4 - TUNSETTXFILTER = 0x400454d1 - TUNSETVNETHDRSZ = 0x400454d8 - VDISCARD = 0xd - VEOF = 0x4 - VEOL = 0xb - VEOL2 = 0x10 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x6 - VQUIT = 0x1 - VREPRINT = 0xc - VSTART = 0x8 - VSTOP = 0x9 - VSUSP = 0xa - VSWTC = 0x7 - VT0 = 0x0 - VT1 = 0x4000 - VTDLY = 0x4000 - VTIME = 0x5 - VWERASE = 0xe - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x20 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4 - XTABS = 0x1800 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x23) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale NFS file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "unknown error 133", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_amd64.go deleted file mode 100644 index b83fb40b3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ /dev/null @@ -1,1818 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x28 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_NFC = 0x27 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CAIF = 0x336 - ARPHRD_CAN = 0x118 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PHONET = 0x334 - ARPHRD_PHONET_PIPE = 0x335 - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x1008 - B110 = 0x3 - B115200 = 0x1002 - B1152000 = 0x1009 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x100a - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x100b - B230400 = 0x1003 - B2400 = 0xb - B2500000 = 0x100c - B300 = 0x7 - B3000000 = 0x100d - B3500000 = 0x100e - B38400 = 0xf - B4000000 = 0x100f - B460800 = 0x1004 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x1005 - B57600 = 0x1001 - B576000 = 0x1006 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x1007 - B9600 = 0xd - BOTHER = 0x1000 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x2000 - BSDLY = 0x2000 - CBAUD = 0x100f - CBAUDEX = 0x1000 - CFLUSH = 0xf - CIBAUD = 0x100f0000 - CLOCAL = 0x800 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x200 - CR2 = 0x400 - CR3 = 0x600 - CRDLY = 0x600 - CREAD = 0x80 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x10 - CS7 = 0x20 - CS8 = 0x30 - CSIGNAL = 0xff - CSIZE = 0x30 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x40 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x200 - ECHOE = 0x10 - ECHOK = 0x20 - ECHOKE = 0x800 - ECHONL = 0x40 - ECHOPRT = 0x400 - ENCODING_DEFAULT = 0x0 - ENCODING_FM_MARK = 0x3 - ENCODING_FM_SPACE = 0x4 - ENCODING_MANCHESTER = 0x5 - ENCODING_NRZ = 0x1 - ENCODING_NRZI = 0x2 - EPOLLERR = 0x8 - EPOLLET = 0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - EPOLL_NONBLOCK = 0x800 - ETH_P_1588 = 0x88f7 - ETH_P_8021AD = 0x88a8 - ETH_P_8021AH = 0x88e7 - ETH_P_8021Q = 0x8100 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_AARP = 0x80f3 - ETH_P_AF_IUCV = 0xfbfb - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_QINQ1 = 0x9100 - ETH_P_QINQ2 = 0x9200 - ETH_P_QINQ3 = 0x9300 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TDLS = 0x890d - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x8000 - FFDLY = 0x8000 - FLUSHO = 0x1000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0x5 - F_GETLK64 = 0x5 - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0x6 - F_SETLK64 = 0x6 - F_SETLKW = 0x7 - F_SETLKW64 = 0x7 - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x400 - IBSHIFT = 0x10 - ICANON = 0x2 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x8000 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_NODAD = 0x2 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x7 - IFF_802_1Q_VLAN = 0x1 - IFF_ALLMULTI = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BONDING = 0x20 - IFF_BRIDGE_PORT = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DISABLE_NETPOLL = 0x1000 - IFF_DONT_BRIDGE = 0x800 - IFF_DORMANT = 0x20000 - IFF_DYNAMIC = 0x8000 - IFF_EBRIDGE = 0x2 - IFF_ECHO = 0x40000 - IFF_ISATAP = 0x80 - IFF_LOOPBACK = 0x8 - IFF_LOWER_UP = 0x10000 - IFF_MACVLAN_PORT = 0x2000 - IFF_MASTER = 0x400 - IFF_MASTER_8023AD = 0x8 - IFF_MASTER_ALB = 0x10 - IFF_MASTER_ARPMON = 0x100 - IFF_MULTICAST = 0x1000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_OVS_DATAPATH = 0x8000 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_SLAVE_INACTIVE = 0x4 - IFF_SLAVE_NEEDARP = 0x40 - IFF_TAP = 0x2 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_TX_SKB_SHARING = 0x10000 - IFF_UNICAST_FLT = 0x20000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFF_VOLATILE = 0x70c5a - IFF_WAN_HDLC = 0x200 - IFF_XMIT_DST_RELEASE = 0x400 - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_ALL = 0x31 - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_XFRM_POLICY = 0x11 - ISIG = 0x1 - ISTRIP = 0x20 - IUCLC = 0x200 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x1000 - IXON = 0x400 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DOFORK = 0xb - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_32BIT = 0x40 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_HUGETLB = 0x40000 - MAP_LOCKED = 0x2000 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x4000 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_STACK = 0x20000 - MAP_TYPE = 0xf - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_CRYPTO = 0x15 - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x100 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_DUMP_INTR = 0x10 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x2 - ONLCR = 0x4 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x4000 - O_DIRECTORY = 0x10000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x101000 - O_LARGEFILE = 0x0 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x20000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x101000 - O_SYNC = 0x101000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_AUXDATA = 0x8 - PACKET_BROADCAST = 0x1 - PACKET_COPY_THRESH = 0x7 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FANOUT = 0x12 - PACKET_FANOUT_CPU = 0x2 - PACKET_FANOUT_FLAG_DEFRAG = 0x8000 - PACKET_FANOUT_HASH = 0x0 - PACKET_FANOUT_LB = 0x1 - PACKET_FASTROUTE = 0x6 - PACKET_HDRLEN = 0xb - PACKET_HOST = 0x0 - PACKET_LOOPBACK = 0x5 - PACKET_LOSS = 0xe - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MR_UNICAST = 0x3 - PACKET_MULTICAST = 0x2 - PACKET_ORIGDEV = 0x9 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RESERVE = 0xc - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PACKET_TIMESTAMP = 0x11 - PACKET_TX_RING = 0xd - PACKET_TX_TIMESTAMP = 0x10 - PACKET_VERSION = 0xa - PACKET_VNET_HDR = 0xf - PARENB = 0x100 - PARITY_CRC16_PR0 = 0x2 - PARITY_CRC16_PR0_CCITT = 0x4 - PARITY_CRC16_PR1 = 0x3 - PARITY_CRC16_PR1_CCITT = 0x5 - PARITY_CRC32_PR0_CCITT = 0x6 - PARITY_CRC32_PR1_CCITT = 0x7 - PARITY_DEFAULT = 0x0 - PARITY_NONE = 0x1 - PARMRK = 0x8 - PARODD = 0x200 - PENDIN = 0x4000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_NO_NEW_PRIVS = 0x27 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECUREBITS = 0x1b - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_MM = 0x23 - PR_SET_MM_BRK = 0x7 - PR_SET_MM_END_CODE = 0x2 - PR_SET_MM_END_DATA = 0x4 - PR_SET_MM_START_BRK = 0x6 - PR_SET_MM_START_CODE = 0x1 - PR_SET_MM_START_DATA = 0x3 - PR_SET_MM_START_STACK = 0x5 - PR_SET_NAME = 0xf - PR_SET_NO_NEW_PRIVS = 0x26 - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_PTRACER_ANY = -0x1 - PR_SET_SECCOMP = 0x16 - PR_SET_SECUREBITS = 0x1c - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ARCH_PRCTL = 0x1e - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_SECCOMP = 0x7 - PTRACE_EVENT_STOP = 0x80 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETFPREGS = 0xe - PTRACE_GETFPXREGS = 0x12 - PTRACE_GETREGS = 0xc - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GET_THREAD_AREA = 0x19 - PTRACE_INTERRUPT = 0x4207 - PTRACE_KILL = 0x8 - PTRACE_LISTEN = 0x4208 - PTRACE_OLDSETOPTIONS = 0x15 - PTRACE_O_MASK = 0xff - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESECCOMP = 0x80 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SEIZE = 0x4206 - PTRACE_SEIZE_DEVEL = 0x80000000 - PTRACE_SETFPREGS = 0xf - PTRACE_SETFPXREGS = 0x13 - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SET_THREAD_AREA = 0x1a - PTRACE_SINGLEBLOCK = 0x21 - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_SYSEMU = 0x1f - PTRACE_SYSEMU_SINGLESTEP = 0x20 - PTRACE_TRACEME = 0x0 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xe - RTAX_MTU = 0x2 - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x10 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x4f - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x10 - RTM_NR_MSGTYPES = 0x40 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_MARK = 0x24 - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x10 - SO_PASSSEC = 0x22 - SO_PEERCRED = 0x11 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x12 - SO_RCVTIMEO = 0x14 - SO_REUSEADDR = 0x2 - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x13 - SO_SNDTIMEO = 0x15 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x800 - TAB2 = 0x1000 - TAB3 = 0x1800 - TABDLY = 0x1800 - TCFLSH = 0x540b - TCGETA = 0x5405 - TCGETS = 0x5401 - TCGETS2 = 0x802c542a - TCGETX = 0x5432 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_QUICKACK = 0xc - TCP_SYNCNT = 0x7 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x5409 - TCSBRKP = 0x5425 - TCSETA = 0x5406 - TCSETAF = 0x5408 - TCSETAW = 0x5407 - TCSETS = 0x5402 - TCSETS2 = 0x402c542b - TCSETSF = 0x5404 - TCSETSF2 = 0x402c542d - TCSETSW = 0x5403 - TCSETSW2 = 0x402c542c - TCSETX = 0x5433 - TCSETXF = 0x5434 - TCSETXW = 0x5435 - TCXONC = 0x540a - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x80045432 - TIOCGETD = 0x5424 - TIOCGEXCL = 0x80045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGPGRP = 0x540f - TIOCGPKT = 0x80045438 - TIOCGPTLCK = 0x80045439 - TIOCGPTN = 0x80045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x5413 - TIOCINQ = 0x541b - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x5411 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETD = 0x5423 - TIOCSIG = 0x40045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSPGRP = 0x5410 - TIOCSPTLCK = 0x40045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTI = 0x5412 - TIOCSWINSZ = 0x5414 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x100 - TUNATTACHFILTER = 0x401054d5 - TUNDETACHFILTER = 0x401054d6 - TUNGETFEATURES = 0x800454cf - TUNGETIFF = 0x800454d2 - TUNGETSNDBUF = 0x800454d3 - TUNGETVNETHDRSZ = 0x800454d7 - TUNSETDEBUG = 0x400454c9 - TUNSETGROUP = 0x400454ce - TUNSETIFF = 0x400454ca - TUNSETLINK = 0x400454cd - TUNSETNOCSUM = 0x400454c8 - TUNSETOFFLOAD = 0x400454d0 - TUNSETOWNER = 0x400454cc - TUNSETPERSIST = 0x400454cb - TUNSETSNDBUF = 0x400454d4 - TUNSETTXFILTER = 0x400454d1 - TUNSETVNETHDRSZ = 0x400454d8 - VDISCARD = 0xd - VEOF = 0x4 - VEOL = 0xb - VEOL2 = 0x10 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x6 - VQUIT = 0x1 - VREPRINT = 0xc - VSTART = 0x8 - VSTOP = 0x9 - VSUSP = 0xa - VSWTC = 0x7 - VT0 = 0x0 - VT1 = 0x4000 - VTDLY = 0x4000 - VTIME = 0x5 - VWERASE = 0xe - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x40 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4 - XTABS = 0x1800 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x23) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale NFS file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "unknown error 133", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm.go deleted file mode 100644 index 1cc76a78c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm.go +++ /dev/null @@ -1,1742 +0,0 @@ -// mkerrors.sh -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x27 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802154_PHY = 0x325 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x1008 - B110 = 0x3 - B115200 = 0x1002 - B1152000 = 0x1009 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x100a - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x100b - B230400 = 0x1003 - B2400 = 0xb - B2500000 = 0x100c - B300 = 0x7 - B3000000 = 0x100d - B3500000 = 0x100e - B38400 = 0xf - B4000000 = 0x100f - B460800 = 0x1004 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x1005 - B57600 = 0x1001 - B576000 = 0x1006 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x1007 - B9600 = 0xd - BOTHER = 0x1000 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x2000 - BSDLY = 0x2000 - CBAUD = 0x100f - CBAUDEX = 0x1000 - CFLUSH = 0xf - CIBAUD = 0x100f0000 - CLOCAL = 0x800 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x200 - CR2 = 0x400 - CR3 = 0x600 - CRDLY = 0x600 - CREAD = 0x80 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x10 - CS7 = 0x20 - CS8 = 0x30 - CSIGNAL = 0xff - CSIZE = 0x30 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x40 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ELF_NGREG = 0x12 - ELF_PRARGSZ = 0x50 - ECHO = 0x8 - ECHOCTL = 0x200 - ECHOE = 0x10 - ECHOK = 0x20 - ECHOKE = 0x800 - ECHONL = 0x40 - ECHOPRT = 0x400 - EPOLLERR = 0x8 - EPOLLET = -0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - EPOLL_NONBLOCK = 0x800 - ETH_P_1588 = 0x88f7 - ETH_P_8021Q = 0x8100 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_AARP = 0x80f3 - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x8000 - FFDLY = 0x8000 - FLUSHO = 0x1000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0xc - F_GETLK64 = 0xc - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0xd - F_SETLK64 = 0xd - F_SETLKW = 0xe - F_SETLKW64 = 0xe - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x400 - IBSHIFT = 0x10 - ICANON = 0x2 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x8000 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_NODAD = 0x2 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x7 - IFF_ALLMULTI = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DYNAMIC = 0x8000 - IFF_LOOPBACK = 0x8 - IFF_MASTER = 0x400 - IFF_MULTICAST = 0x1000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_TAP = 0x2 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_XFRM_POLICY = 0x11 - ISIG = 0x1 - ISTRIP = 0x20 - IUCLC = 0x200 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x1000 - IXON = 0x400 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DOFORK = 0xb - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_LOCKED = 0x2000 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x4000 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_TYPE = 0xf - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x100 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x2 - ONLCR = 0x4 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x4000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x1000 - O_LARGEFILE = 0x20000 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x8000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x1000 - O_SYNC = 0x1000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_BROADCAST = 0x1 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FASTROUTE = 0x6 - PACKET_HOST = 0x0 - PACKET_LOOPBACK = 0x5 - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MULTICAST = 0x2 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PARENB = 0x100 - PARMRK = 0x8 - PARODD = 0x200 - PENDIN = 0x4000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_CLEAR_SECCOMP_FILTER = 0x25 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECCOMP_FILTER = 0x23 - PR_GET_SECUREBITS = 0x1b - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SECCOMP_FILTER_EVENT = 0x1 - PR_SECCOMP_FILTER_SYSCALL = 0x0 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_NAME = 0xf - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_SECCOMP = 0x16 - PR_SET_SECCOMP_FILTER = 0x24 - PR_SET_SECUREBITS = 0x1c - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETCRUNCHREGS = 0x19 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETFPREGS = 0xe - PTRACE_GETHBPREGS = 0x1d - PTRACE_GETREGS = 0xc - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GETVFPREGS = 0x1b - PTRACE_GETWMMXREGS = 0x12 - PTRACE_GET_THREAD_AREA = 0x16 - PTRACE_KILL = 0x8 - PTRACE_OLDSETOPTIONS = 0x15 - PTRACE_O_MASK = 0x7f - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SETCRUNCHREGS = 0x1a - PTRACE_SETFPREGS = 0xf - PTRACE_SETHBPREGS = 0x1e - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SETVFPREGS = 0x1c - PTRACE_SETWMMXREGS = 0x13 - PTRACE_SET_SYSCALL = 0x17 - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_TRACEME = 0x0 - PT_DATA_ADDR = 0x10004 - PT_TEXT_ADDR = 0x10000 - PT_TEXT_END_ADDR = 0x10008 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xe - RTAX_MTU = 0x2 - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x10 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x4f - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x10 - RTM_NR_MSGTYPES = 0x40 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_MARK = 0x24 - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x10 - SO_PASSSEC = 0x22 - SO_PEERCRED = 0x11 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x12 - SO_RCVTIMEO = 0x14 - SO_REUSEADDR = 0x2 - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x13 - SO_SNDTIMEO = 0x15 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x800 - TAB2 = 0x1000 - TAB3 = 0x1800 - TABDLY = 0x1800 - TCFLSH = 0x540b - TCGETA = 0x5405 - TCGETS = 0x5401 - TCGETS2 = 0x802c542a - TCGETX = 0x5432 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_QUICKACK = 0xc - TCP_SYNCNT = 0x7 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x5409 - TCSBRKP = 0x5425 - TCSETA = 0x5406 - TCSETAF = 0x5408 - TCSETAW = 0x5407 - TCSETS = 0x5402 - TCSETS2 = 0x402c542b - TCSETSF = 0x5404 - TCSETSF2 = 0x402c542d - TCSETSW = 0x5403 - TCSETSW2 = 0x402c542c - TCSETX = 0x5433 - TCSETXF = 0x5434 - TCSETXW = 0x5435 - TCXONC = 0x540a - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x80045432 - TIOCGETD = 0x5424 - TIOCGEXCL = 0x80045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGPGRP = 0x540f - TIOCGPKT = 0x80045438 - TIOCGPTLCK = 0x80045439 - TIOCGPTN = 0x80045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x5413 - TIOCINQ = 0x541b - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x5411 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETD = 0x5423 - TIOCSIG = 0x40045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSPGRP = 0x5410 - TIOCSPTLCK = 0x40045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTI = 0x5412 - TIOCSWINSZ = 0x5414 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x100 - TUNATTACHFILTER = 0x400854d5 - TUNDETACHFILTER = 0x400854d6 - TUNGETFEATURES = 0x800454cf - TUNGETIFF = 0x800454d2 - TUNGETSNDBUF = 0x800454d3 - TUNGETVNETHDRSZ = 0x800454d7 - TUNSETDEBUG = 0x400454c9 - TUNSETGROUP = 0x400454ce - TUNSETIFF = 0x400454ca - TUNSETLINK = 0x400454cd - TUNSETNOCSUM = 0x400454c8 - TUNSETOFFLOAD = 0x400454d0 - TUNSETOWNER = 0x400454cc - TUNSETPERSIST = 0x400454cb - TUNSETSNDBUF = 0x400454d4 - TUNSETTXFILTER = 0x400454d1 - TUNSETVNETHDRSZ = 0x400454d8 - VDISCARD = 0xd - VEOF = 0x4 - VEOL = 0xb - VEOL2 = 0x10 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x6 - VQUIT = 0x1 - VREPRINT = 0xc - VSTART = 0x8 - VSTOP = 0x9 - VSUSP = 0xa - VSWTC = 0x7 - VT0 = 0x0 - VT1 = 0x4000 - VTDLY = 0x4000 - VTIME = 0x5 - VWERASE = 0xe - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x20 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4 - XTABS = 0x1800 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x23) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale NFS file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "unknown error 133", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm64.go deleted file mode 100644 index 47027b79c..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ /dev/null @@ -1,1896 +0,0 @@ -// mkerrors.sh -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm64,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x29 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_NFC = 0x27 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VSOCK = 0x28 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CAIF = 0x336 - ARPHRD_CAN = 0x118 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802154_MONITOR = 0x325 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IP6GRE = 0x337 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETLINK = 0x338 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PHONET = 0x334 - ARPHRD_PHONET_PIPE = 0x335 - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x1008 - B110 = 0x3 - B115200 = 0x1002 - B1152000 = 0x1009 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x100a - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x100b - B230400 = 0x1003 - B2400 = 0xb - B2500000 = 0x100c - B300 = 0x7 - B3000000 = 0x100d - B3500000 = 0x100e - B38400 = 0xf - B4000000 = 0x100f - B460800 = 0x1004 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x1005 - B57600 = 0x1001 - B576000 = 0x1006 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x1007 - B9600 = 0xd - BOTHER = 0x1000 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MOD = 0x90 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BPF_XOR = 0xa0 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x2000 - BSDLY = 0x2000 - CBAUD = 0x100f - CBAUDEX = 0x1000 - CFLUSH = 0xf - CIBAUD = 0x100f0000 - CLOCAL = 0x800 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x200 - CR2 = 0x400 - CR3 = 0x600 - CRDLY = 0x600 - CREAD = 0x80 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x10 - CS7 = 0x20 - CS8 = 0x30 - CSIGNAL = 0xff - CSIZE = 0x30 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x40 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x200 - ECHOE = 0x10 - ECHOK = 0x20 - ECHOKE = 0x800 - ECHONL = 0x40 - ECHOPRT = 0x400 - ELF_NGREG = 0x22 - ELF_PRARGSZ = 0x50 - ENCODING_DEFAULT = 0x0 - ENCODING_FM_MARK = 0x3 - ENCODING_FM_SPACE = 0x4 - ENCODING_MANCHESTER = 0x5 - ENCODING_NRZ = 0x1 - ENCODING_NRZI = 0x2 - EPOLLERR = 0x8 - EPOLLET = 0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWAKEUP = 0x20000000 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - ETH_P_1588 = 0x88f7 - ETH_P_8021AD = 0x88a8 - ETH_P_8021AH = 0x88e7 - ETH_P_8021Q = 0x8100 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_802_3_MIN = 0x600 - ETH_P_802_EX1 = 0x88b5 - ETH_P_AARP = 0x80f3 - ETH_P_AF_IUCV = 0xfbfb - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BATMAN = 0x4305 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CANFD = 0xd - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_MVRP = 0x88f5 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PRP = 0x88fb - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_QINQ1 = 0x9100 - ETH_P_QINQ2 = 0x9200 - ETH_P_QINQ3 = 0x9300 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TDLS = 0x890d - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x8000 - FFDLY = 0x8000 - FLUSHO = 0x1000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0x5 - F_GETLK64 = 0x5 - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0x6 - F_SETLK64 = 0x6 - F_SETLKW = 0x7 - F_SETLKW64 = 0x7 - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x400 - IBSHIFT = 0x10 - ICANON = 0x2 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x8000 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_NODAD = 0x2 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x7 - IFF_802_1Q_VLAN = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ATTACH_QUEUE = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BONDING = 0x20 - IFF_BRIDGE_PORT = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DETACH_QUEUE = 0x400 - IFF_DISABLE_NETPOLL = 0x1000 - IFF_DONT_BRIDGE = 0x800 - IFF_DORMANT = 0x20000 - IFF_DYNAMIC = 0x8000 - IFF_EBRIDGE = 0x2 - IFF_ECHO = 0x40000 - IFF_ISATAP = 0x80 - IFF_LIVE_ADDR_CHANGE = 0x100000 - IFF_LOOPBACK = 0x8 - IFF_LOWER_UP = 0x10000 - IFF_MACVLAN = 0x200000 - IFF_MACVLAN_PORT = 0x2000 - IFF_MASTER = 0x400 - IFF_MASTER_8023AD = 0x8 - IFF_MASTER_ALB = 0x10 - IFF_MASTER_ARPMON = 0x100 - IFF_MULTICAST = 0x1000 - IFF_MULTI_QUEUE = 0x100 - IFF_NOARP = 0x80 - IFF_NOFILTER = 0x1000 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_OVS_DATAPATH = 0x8000 - IFF_PERSIST = 0x800 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_SLAVE_INACTIVE = 0x4 - IFF_SLAVE_NEEDARP = 0x40 - IFF_SUPP_NOFCS = 0x80000 - IFF_TAP = 0x2 - IFF_TEAM_PORT = 0x40000 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_TX_SKB_SHARING = 0x10000 - IFF_UNICAST_FLT = 0x20000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFF_VOLATILE = 0x70c5a - IFF_WAN_HDLC = 0x200 - IFF_XMIT_DST_RELEASE = 0x400 - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_BEETPH = 0x5e - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MH = 0x87 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_ALL = 0x31 - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_UNICAST_IF = 0x32 - IP_XFRM_POLICY = 0x11 - ISIG = 0x1 - ISTRIP = 0x20 - IUCLC = 0x200 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x1000 - IXON = 0x400 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DODUMP = 0x11 - MADV_DOFORK = 0xb - MADV_DONTDUMP = 0x10 - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_HUGETLB = 0x40000 - MAP_HUGE_MASK = 0x3f - MAP_HUGE_SHIFT = 0x1a - MAP_LOCKED = 0x2000 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x4000 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_STACK = 0x20000 - MAP_TYPE = 0xf - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_CRYPTO = 0x15 - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_RX_RING = 0x6 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_SOCK_DIAG = 0x4 - NETLINK_TX_RING = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x100 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_DUMP_INTR = 0x10 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x2 - ONLCR = 0x4 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x10000 - O_DIRECTORY = 0x4000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x101000 - O_LARGEFILE = 0x0 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x8000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x101000 - O_SYNC = 0x101000 - O_TMPFILE = 0x410000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_AUXDATA = 0x8 - PACKET_BROADCAST = 0x1 - PACKET_COPY_THRESH = 0x7 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FANOUT = 0x12 - PACKET_FANOUT_CPU = 0x2 - PACKET_FANOUT_FLAG_DEFRAG = 0x8000 - PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 - PACKET_FANOUT_HASH = 0x0 - PACKET_FANOUT_LB = 0x1 - PACKET_FANOUT_RND = 0x4 - PACKET_FANOUT_ROLLOVER = 0x3 - PACKET_FASTROUTE = 0x6 - PACKET_HDRLEN = 0xb - PACKET_HOST = 0x0 - PACKET_LOOPBACK = 0x5 - PACKET_LOSS = 0xe - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MR_UNICAST = 0x3 - PACKET_MULTICAST = 0x2 - PACKET_ORIGDEV = 0x9 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RESERVE = 0xc - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PACKET_TIMESTAMP = 0x11 - PACKET_TX_HAS_OFF = 0x13 - PACKET_TX_RING = 0xd - PACKET_TX_TIMESTAMP = 0x10 - PACKET_VERSION = 0xa - PACKET_VNET_HDR = 0xf - PARENB = 0x100 - PARITY_CRC16_PR0 = 0x2 - PARITY_CRC16_PR0_CCITT = 0x4 - PARITY_CRC16_PR1 = 0x3 - PARITY_CRC16_PR1_CCITT = 0x5 - PARITY_CRC32_PR0_CCITT = 0x6 - PARITY_CRC32_PR1_CCITT = 0x7 - PARITY_DEFAULT = 0x0 - PARITY_NONE = 0x1 - PARMRK = 0x8 - PARODD = 0x200 - PENDIN = 0x4000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_CHILD_SUBREAPER = 0x25 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_NO_NEW_PRIVS = 0x27 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECUREBITS = 0x1b - PR_GET_TID_ADDRESS = 0x28 - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SET_CHILD_SUBREAPER = 0x24 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_MM = 0x23 - PR_SET_MM_ARG_END = 0x9 - PR_SET_MM_ARG_START = 0x8 - PR_SET_MM_AUXV = 0xc - PR_SET_MM_BRK = 0x7 - PR_SET_MM_END_CODE = 0x2 - PR_SET_MM_END_DATA = 0x4 - PR_SET_MM_ENV_END = 0xb - PR_SET_MM_ENV_START = 0xa - PR_SET_MM_EXE_FILE = 0xd - PR_SET_MM_START_BRK = 0x6 - PR_SET_MM_START_CODE = 0x1 - PR_SET_MM_START_DATA = 0x3 - PR_SET_MM_START_STACK = 0x5 - PR_SET_NAME = 0xf - PR_SET_NO_NEW_PRIVS = 0x26 - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_PTRACER_ANY = -0x1 - PR_SET_SECCOMP = 0x16 - PR_SET_SECUREBITS = 0x1c - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_SECCOMP = 0x7 - PTRACE_EVENT_STOP = 0x80 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETREGS = 0xc - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GETSIGMASK = 0x420a - PTRACE_INTERRUPT = 0x4207 - PTRACE_KILL = 0x8 - PTRACE_LISTEN = 0x4208 - PTRACE_O_EXITKILL = 0x100000 - PTRACE_O_MASK = 0x1000ff - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESECCOMP = 0x80 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKSIGINFO = 0x4209 - PTRACE_PEEKSIGINFO_SHARED = 0x1 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SEIZE = 0x4206 - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SETSIGMASK = 0x420b - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_TRACEME = 0x0 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xf - RTAX_MTU = 0x2 - RTAX_QUICKACK = 0xf - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x11 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELMDB = 0x55 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMDB = 0x56 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETNETCONF = 0x52 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x57 - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWMDB = 0x54 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWNETCONF = 0x50 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x12 - RTM_NR_MSGTYPES = 0x48 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MROUTED = 0x11 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SCM_WIFI_STATUS = 0x29 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_BUSY_POLL = 0x2e - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_GET_FILTER = 0x1a - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_LOCK_FILTER = 0x2c - SO_MARK = 0x24 - SO_MAX_PACING_RATE = 0x2f - SO_NOFCS = 0x2b - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x10 - SO_PASSSEC = 0x22 - SO_PEEK_OFF = 0x2a - SO_PEERCRED = 0x11 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x12 - SO_RCVTIMEO = 0x14 - SO_REUSEADDR = 0x2 - SO_REUSEPORT = 0xf - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SELECT_ERR_QUEUE = 0x2d - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x13 - SO_SNDTIMEO = 0x15 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - SO_WIFI_STATUS = 0x29 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x800 - TAB2 = 0x1000 - TAB3 = 0x1800 - TABDLY = 0x1800 - TCFLSH = 0x540b - TCGETA = 0x5405 - TCGETS = 0x5401 - TCGETS2 = 0x802c542a - TCGETX = 0x5432 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_COOKIE_IN_ALWAYS = 0x1 - TCP_COOKIE_MAX = 0x10 - TCP_COOKIE_MIN = 0x8 - TCP_COOKIE_OUT_NEVER = 0x2 - TCP_COOKIE_PAIR_SIZE = 0x20 - TCP_COOKIE_TRANSACTIONS = 0xf - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_FASTOPEN = 0x17 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_MSS_DEFAULT = 0x218 - TCP_MSS_DESIRED = 0x4c4 - TCP_NODELAY = 0x1 - TCP_QUEUE_SEQ = 0x15 - TCP_QUICKACK = 0xc - TCP_REPAIR = 0x13 - TCP_REPAIR_OPTIONS = 0x16 - TCP_REPAIR_QUEUE = 0x14 - TCP_SYNCNT = 0x7 - TCP_S_DATA_IN = 0x4 - TCP_S_DATA_OUT = 0x8 - TCP_THIN_DUPACK = 0x11 - TCP_THIN_LINEAR_TIMEOUTS = 0x10 - TCP_TIMESTAMP = 0x18 - TCP_USER_TIMEOUT = 0x12 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x5409 - TCSBRKP = 0x5425 - TCSETA = 0x5406 - TCSETAF = 0x5408 - TCSETAW = 0x5407 - TCSETS = 0x5402 - TCSETS2 = 0x402c542b - TCSETSF = 0x5404 - TCSETSF2 = 0x402c542d - TCSETSW = 0x5403 - TCSETSW2 = 0x402c542c - TCSETX = 0x5433 - TCSETXF = 0x5434 - TCSETXW = 0x5435 - TCXONC = 0x540a - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x80045432 - TIOCGETD = 0x5424 - TIOCGEXCL = 0x80045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGPGRP = 0x540f - TIOCGPKT = 0x80045438 - TIOCGPTLCK = 0x80045439 - TIOCGPTN = 0x80045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x5413 - TIOCINQ = 0x541b - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x5411 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETD = 0x5423 - TIOCSIG = 0x40045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSPGRP = 0x5410 - TIOCSPTLCK = 0x40045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTI = 0x5412 - TIOCSWINSZ = 0x5414 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x100 - TUNATTACHFILTER = 0x401054d5 - TUNDETACHFILTER = 0x401054d6 - TUNGETFEATURES = 0x800454cf - TUNGETFILTER = 0x801054db - TUNGETIFF = 0x800454d2 - TUNGETSNDBUF = 0x800454d3 - TUNGETVNETHDRSZ = 0x800454d7 - TUNSETDEBUG = 0x400454c9 - TUNSETGROUP = 0x400454ce - TUNSETIFF = 0x400454ca - TUNSETIFINDEX = 0x400454da - TUNSETLINK = 0x400454cd - TUNSETNOCSUM = 0x400454c8 - TUNSETOFFLOAD = 0x400454d0 - TUNSETOWNER = 0x400454cc - TUNSETPERSIST = 0x400454cb - TUNSETQUEUE = 0x400454d9 - TUNSETSNDBUF = 0x400454d4 - TUNSETTXFILTER = 0x400454d1 - TUNSETVNETHDRSZ = 0x400454d8 - VDISCARD = 0xd - VEOF = 0x4 - VEOL = 0xb - VEOL2 = 0x10 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x6 - VQUIT = 0x1 - VREPRINT = 0xc - VSTART = 0x8 - VSTOP = 0x9 - VSUSP = 0xa - VSWTC = 0x7 - VT0 = 0x0 - VT1 = 0x4000 - VTDLY = 0x4000 - VTIME = 0x5 - VWERASE = 0xe - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x40 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4 - XTABS = 0x1800 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x23) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64.go deleted file mode 100644 index 5b90d07ed..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ /dev/null @@ -1,1969 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build ppc64,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x29 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_NFC = 0x27 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VSOCK = 0x28 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_6LOWPAN = 0x339 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CAIF = 0x336 - ARPHRD_CAN = 0x118 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802154_MONITOR = 0x325 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IP6GRE = 0x337 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETLINK = 0x338 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PHONET = 0x334 - ARPHRD_PHONET_PIPE = 0x335 - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x17 - B110 = 0x3 - B115200 = 0x11 - B1152000 = 0x18 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x19 - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x1a - B230400 = 0x12 - B2400 = 0xb - B2500000 = 0x1b - B300 = 0x7 - B3000000 = 0x1c - B3500000 = 0x1d - B38400 = 0xf - B4000000 = 0x1e - B460800 = 0x13 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x14 - B57600 = 0x10 - B576000 = 0x15 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x16 - B9600 = 0xd - BOTHER = 0x1f - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MOD = 0x90 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BPF_XOR = 0xa0 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x8000 - BSDLY = 0x8000 - CBAUD = 0xff - CBAUDEX = 0x0 - CFLUSH = 0xf - CIBAUD = 0xff0000 - CLOCAL = 0x8000 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x1000 - CR2 = 0x2000 - CR3 = 0x3000 - CRDLY = 0x3000 - CREAD = 0x800 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIGNAL = 0xff - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - ENCODING_DEFAULT = 0x0 - ENCODING_FM_MARK = 0x3 - ENCODING_FM_SPACE = 0x4 - ENCODING_MANCHESTER = 0x5 - ENCODING_NRZ = 0x1 - ENCODING_NRZI = 0x2 - EPOLLERR = 0x8 - EPOLLET = 0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWAKEUP = 0x20000000 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - ETH_P_1588 = 0x88f7 - ETH_P_8021AD = 0x88a8 - ETH_P_8021AH = 0x88e7 - ETH_P_8021Q = 0x8100 - ETH_P_80221 = 0x8917 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_802_3_MIN = 0x600 - ETH_P_802_EX1 = 0x88b5 - ETH_P_AARP = 0x80f3 - ETH_P_AF_IUCV = 0xfbfb - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BATMAN = 0x4305 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CANFD = 0xd - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_LOOPBACK = 0x9000 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_MVRP = 0x88f5 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PRP = 0x88fb - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_QINQ1 = 0x9100 - ETH_P_QINQ2 = 0x9200 - ETH_P_QINQ3 = 0x9300 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TDLS = 0x890d - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - ETH_P_XDSA = 0xf8 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x4000 - FFDLY = 0x4000 - FLUSHO = 0x800000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0x5 - F_GETLK64 = 0xc - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OFD_GETLK = 0x24 - F_OFD_SETLK = 0x25 - F_OFD_SETLKW = 0x26 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0x6 - F_SETLK64 = 0xd - F_SETLKW = 0x7 - F_SETLKW64 = 0xe - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x4000 - IBSHIFT = 0x10 - ICANON = 0x100 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x400 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_MANAGETEMPADDR = 0x100 - IFA_F_NODAD = 0x2 - IFA_F_NOPREFIXROUTE = 0x200 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x8 - IFF_ALLMULTI = 0x200 - IFF_ATTACH_QUEUE = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DETACH_QUEUE = 0x400 - IFF_DORMANT = 0x20000 - IFF_DYNAMIC = 0x8000 - IFF_ECHO = 0x40000 - IFF_LOOPBACK = 0x8 - IFF_LOWER_UP = 0x10000 - IFF_MASTER = 0x400 - IFF_MULTICAST = 0x1000 - IFF_MULTI_QUEUE = 0x100 - IFF_NOARP = 0x80 - IFF_NOFILTER = 0x1000 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_PERSIST = 0x800 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_TAP = 0x2 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFF_VOLATILE = 0x70c5a - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_BEETPH = 0x5e - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MH = 0x87 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_INTERFACE = 0x4 - IPV6_PMTUDISC_OMIT = 0x5 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_ALL = 0x31 - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_NODEFRAG = 0x16 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_INTERFACE = 0x4 - IP_PMTUDISC_OMIT = 0x5 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_UNICAST_IF = 0x32 - IP_XFRM_POLICY = 0x11 - ISIG = 0x80 - ISTRIP = 0x20 - IUCLC = 0x1000 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DODUMP = 0x11 - MADV_DOFORK = 0xb - MADV_DONTDUMP = 0x10 - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_HUGETLB = 0x40000 - MAP_HUGE_MASK = 0x3f - MAP_HUGE_SHIFT = 0x1a - MAP_LOCKED = 0x80 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x40 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_STACK = 0x20000 - MAP_TYPE = 0xf - MCL_CURRENT = 0x2000 - MCL_FUTURE = 0x4000 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_CRYPTO = 0x15 - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_RX_RING = 0x6 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_SOCK_DIAG = 0x4 - NETLINK_TX_RING = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NL2 = 0x200 - NL3 = 0x300 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x300 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_DUMP_INTR = 0x10 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80000000 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x4 - ONLCR = 0x2 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x20000 - O_DIRECTORY = 0x4000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x101000 - O_LARGEFILE = 0x0 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x8000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x101000 - O_SYNC = 0x101000 - O_TMPFILE = 0x410000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_AUXDATA = 0x8 - PACKET_BROADCAST = 0x1 - PACKET_COPY_THRESH = 0x7 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FANOUT = 0x12 - PACKET_FANOUT_CPU = 0x2 - PACKET_FANOUT_FLAG_DEFRAG = 0x8000 - PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 - PACKET_FANOUT_HASH = 0x0 - PACKET_FANOUT_LB = 0x1 - PACKET_FANOUT_QM = 0x5 - PACKET_FANOUT_RND = 0x4 - PACKET_FANOUT_ROLLOVER = 0x3 - PACKET_FASTROUTE = 0x6 - PACKET_HDRLEN = 0xb - PACKET_HOST = 0x0 - PACKET_KERNEL = 0x7 - PACKET_LOOPBACK = 0x5 - PACKET_LOSS = 0xe - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MR_UNICAST = 0x3 - PACKET_MULTICAST = 0x2 - PACKET_ORIGDEV = 0x9 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_QDISC_BYPASS = 0x14 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RESERVE = 0xc - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PACKET_TIMESTAMP = 0x11 - PACKET_TX_HAS_OFF = 0x13 - PACKET_TX_RING = 0xd - PACKET_TX_TIMESTAMP = 0x10 - PACKET_USER = 0x6 - PACKET_VERSION = 0xa - PACKET_VNET_HDR = 0xf - PARENB = 0x1000 - PARITY_CRC16_PR0 = 0x2 - PARITY_CRC16_PR0_CCITT = 0x4 - PARITY_CRC16_PR1 = 0x3 - PARITY_CRC16_PR1_CCITT = 0x5 - PARITY_CRC32_PR0_CCITT = 0x6 - PARITY_CRC32_PR1_CCITT = 0x7 - PARITY_DEFAULT = 0x0 - PARITY_NONE = 0x1 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_SAO = 0x10 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_CHILD_SUBREAPER = 0x25 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_NO_NEW_PRIVS = 0x27 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECUREBITS = 0x1b - PR_GET_THP_DISABLE = 0x2a - PR_GET_TID_ADDRESS = 0x28 - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SET_CHILD_SUBREAPER = 0x24 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_MM = 0x23 - PR_SET_MM_ARG_END = 0x9 - PR_SET_MM_ARG_START = 0x8 - PR_SET_MM_AUXV = 0xc - PR_SET_MM_BRK = 0x7 - PR_SET_MM_END_CODE = 0x2 - PR_SET_MM_END_DATA = 0x4 - PR_SET_MM_ENV_END = 0xb - PR_SET_MM_ENV_START = 0xa - PR_SET_MM_EXE_FILE = 0xd - PR_SET_MM_MAP = 0xe - PR_SET_MM_MAP_SIZE = 0xf - PR_SET_MM_START_BRK = 0x6 - PR_SET_MM_START_CODE = 0x1 - PR_SET_MM_START_DATA = 0x3 - PR_SET_MM_START_STACK = 0x5 - PR_SET_NAME = 0xf - PR_SET_NO_NEW_PRIVS = 0x26 - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_PTRACER_ANY = -0x1 - PR_SET_SECCOMP = 0x16 - PR_SET_SECUREBITS = 0x1c - PR_SET_THP_DISABLE = 0x29 - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_SECCOMP = 0x7 - PTRACE_EVENT_STOP = 0x80 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETEVRREGS = 0x14 - PTRACE_GETFPREGS = 0xe - PTRACE_GETREGS = 0xc - PTRACE_GETREGS64 = 0x16 - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GETSIGMASK = 0x420a - PTRACE_GETVRREGS = 0x12 - PTRACE_GETVSRREGS = 0x1b - PTRACE_GET_DEBUGREG = 0x19 - PTRACE_INTERRUPT = 0x4207 - PTRACE_KILL = 0x8 - PTRACE_LISTEN = 0x4208 - PTRACE_O_EXITKILL = 0x100000 - PTRACE_O_MASK = 0x1000ff - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESECCOMP = 0x80 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKSIGINFO = 0x4209 - PTRACE_PEEKSIGINFO_SHARED = 0x1 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SEIZE = 0x4206 - PTRACE_SETEVRREGS = 0x15 - PTRACE_SETFPREGS = 0xf - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGS64 = 0x17 - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SETSIGMASK = 0x420b - PTRACE_SETVRREGS = 0x13 - PTRACE_SETVSRREGS = 0x1c - PTRACE_SET_DEBUGREG = 0x1a - PTRACE_SINGLEBLOCK = 0x100 - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_TRACEME = 0x0 - PT_CCR = 0x26 - PT_CTR = 0x23 - PT_DAR = 0x29 - PT_DSCR = 0x2c - PT_DSISR = 0x2a - PT_FPR0 = 0x30 - PT_FPSCR = 0x50 - PT_LNK = 0x24 - PT_MSR = 0x21 - PT_NIP = 0x20 - PT_ORIG_R3 = 0x22 - PT_R0 = 0x0 - PT_R1 = 0x1 - PT_R10 = 0xa - PT_R11 = 0xb - PT_R12 = 0xc - PT_R13 = 0xd - PT_R14 = 0xe - PT_R15 = 0xf - PT_R16 = 0x10 - PT_R17 = 0x11 - PT_R18 = 0x12 - PT_R19 = 0x13 - PT_R2 = 0x2 - PT_R20 = 0x14 - PT_R21 = 0x15 - PT_R22 = 0x16 - PT_R23 = 0x17 - PT_R24 = 0x18 - PT_R25 = 0x19 - PT_R26 = 0x1a - PT_R27 = 0x1b - PT_R28 = 0x1c - PT_R29 = 0x1d - PT_R3 = 0x3 - PT_R30 = 0x1e - PT_R31 = 0x1f - PT_R4 = 0x4 - PT_R5 = 0x5 - PT_R6 = 0x6 - PT_R7 = 0x7 - PT_R8 = 0x8 - PT_R9 = 0x9 - PT_REGS_COUNT = 0x2c - PT_RESULT = 0x2b - PT_SOFTE = 0x27 - PT_TRAP = 0x28 - PT_VR0 = 0x52 - PT_VRSAVE = 0x94 - PT_VSCR = 0x93 - PT_VSR0 = 0x96 - PT_VSR31 = 0xd4 - PT_XER = 0x25 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xf - RTAX_MTU = 0x2 - RTAX_QUICKACK = 0xf - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x11 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELMDB = 0x55 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMDB = 0x56 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETNETCONF = 0x52 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x57 - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWMDB = 0x54 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWNETCONF = 0x50 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x12 - RTM_NR_MSGTYPES = 0x48 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MROUTED = 0x11 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SCM_WIFI_STATUS = 0x29 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BPF_EXTENSIONS = 0x30 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_BUSY_POLL = 0x2e - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_GET_FILTER = 0x1a - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_LOCK_FILTER = 0x2c - SO_MARK = 0x24 - SO_MAX_PACING_RATE = 0x2f - SO_NOFCS = 0x2b - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x14 - SO_PASSSEC = 0x22 - SO_PEEK_OFF = 0x2a - SO_PEERCRED = 0x15 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x10 - SO_RCVTIMEO = 0x12 - SO_REUSEADDR = 0x2 - SO_REUSEPORT = 0xf - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SELECT_ERR_QUEUE = 0x2d - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x11 - SO_SNDTIMEO = 0x13 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - SO_WIFI_STATUS = 0x29 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x400 - TAB2 = 0x800 - TAB3 = 0xc00 - TABDLY = 0xc00 - TCFLSH = 0x2000741f - TCGETA = 0x40147417 - TCGETS = 0x402c7413 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_COOKIE_IN_ALWAYS = 0x1 - TCP_COOKIE_MAX = 0x10 - TCP_COOKIE_MIN = 0x8 - TCP_COOKIE_OUT_NEVER = 0x2 - TCP_COOKIE_PAIR_SIZE = 0x20 - TCP_COOKIE_TRANSACTIONS = 0xf - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_FASTOPEN = 0x17 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_MSS_DEFAULT = 0x218 - TCP_MSS_DESIRED = 0x4c4 - TCP_NODELAY = 0x1 - TCP_QUEUE_SEQ = 0x15 - TCP_QUICKACK = 0xc - TCP_REPAIR = 0x13 - TCP_REPAIR_OPTIONS = 0x16 - TCP_REPAIR_QUEUE = 0x14 - TCP_SYNCNT = 0x7 - TCP_S_DATA_IN = 0x4 - TCP_S_DATA_OUT = 0x8 - TCP_THIN_DUPACK = 0x11 - TCP_THIN_LINEAR_TIMEOUTS = 0x10 - TCP_TIMESTAMP = 0x18 - TCP_USER_TIMEOUT = 0x12 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x2000741d - TCSBRKP = 0x5425 - TCSETA = 0x80147418 - TCSETAF = 0x8014741c - TCSETAW = 0x80147419 - TCSETS = 0x802c7414 - TCSETSF = 0x802c7416 - TCSETSW = 0x802c7415 - TCXONC = 0x2000741e - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x40045432 - TIOCGETC = 0x40067412 - TIOCGETD = 0x5424 - TIOCGETP = 0x40067408 - TIOCGEXCL = 0x40045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGLTC = 0x40067474 - TIOCGPGRP = 0x40047477 - TIOCGPKT = 0x40045438 - TIOCGPTLCK = 0x40045439 - TIOCGPTN = 0x40045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x40087468 - TIOCINQ = 0x4004667f - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_LOOP = 0x8000 - TIOCM_OUT1 = 0x2000 - TIOCM_OUT2 = 0x4000 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETC = 0x80067411 - TIOCSETD = 0x5423 - TIOCSETN = 0x8006740a - TIOCSETP = 0x80067409 - TIOCSIG = 0x80045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSLTC = 0x80067475 - TIOCSPGRP = 0x80047476 - TIOCSPTLCK = 0x80045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTART = 0x2000746e - TIOCSTI = 0x5412 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x400000 - TUNATTACHFILTER = 0x801054d5 - TUNDETACHFILTER = 0x801054d6 - TUNGETFEATURES = 0x400454cf - TUNGETFILTER = 0x401054db - TUNGETIFF = 0x400454d2 - TUNGETSNDBUF = 0x400454d3 - TUNGETVNETHDRSZ = 0x400454d7 - TUNSETDEBUG = 0x800454c9 - TUNSETGROUP = 0x800454ce - TUNSETIFF = 0x800454ca - TUNSETIFINDEX = 0x800454da - TUNSETLINK = 0x800454cd - TUNSETNOCSUM = 0x800454c8 - TUNSETOFFLOAD = 0x800454d0 - TUNSETOWNER = 0x800454cc - TUNSETPERSIST = 0x800454cb - TUNSETQUEUE = 0x800454d9 - TUNSETSNDBUF = 0x800454d4 - TUNSETTXFILTER = 0x800454d1 - TUNSETVNETHDRSZ = 0x800454d8 - VDISCARD = 0x10 - VEOF = 0x4 - VEOL = 0x6 - VEOL2 = 0x8 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x5 - VQUIT = 0x1 - VREPRINT = 0xb - VSTART = 0xd - VSTOP = 0xe - VSUSP = 0xc - VSWTC = 0x9 - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x7 - VWERASE = 0xa - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x40 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4000 - XTABS = 0xc00 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x3a) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 58: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64le.go deleted file mode 100644 index 0861bd566..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ /dev/null @@ -1,1968 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build ppc64le,linux - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_ALG = 0x26 - AF_APPLETALK = 0x5 - AF_ASH = 0x12 - AF_ATMPVC = 0x8 - AF_ATMSVC = 0x14 - AF_AX25 = 0x3 - AF_BLUETOOTH = 0x1f - AF_BRIDGE = 0x7 - AF_CAIF = 0x25 - AF_CAN = 0x1d - AF_DECnet = 0xc - AF_ECONET = 0x13 - AF_FILE = 0x1 - AF_IEEE802154 = 0x24 - AF_INET = 0x2 - AF_INET6 = 0xa - AF_IPX = 0x4 - AF_IRDA = 0x17 - AF_ISDN = 0x22 - AF_IUCV = 0x20 - AF_KEY = 0xf - AF_LLC = 0x1a - AF_LOCAL = 0x1 - AF_MAX = 0x29 - AF_NETBEUI = 0xd - AF_NETLINK = 0x10 - AF_NETROM = 0x6 - AF_NFC = 0x27 - AF_PACKET = 0x11 - AF_PHONET = 0x23 - AF_PPPOX = 0x18 - AF_RDS = 0x15 - AF_ROSE = 0xb - AF_ROUTE = 0x10 - AF_RXRPC = 0x21 - AF_SECURITY = 0xe - AF_SNA = 0x16 - AF_TIPC = 0x1e - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_VSOCK = 0x28 - AF_WANPIPE = 0x19 - AF_X25 = 0x9 - ARPHRD_ADAPT = 0x108 - ARPHRD_APPLETLK = 0x8 - ARPHRD_ARCNET = 0x7 - ARPHRD_ASH = 0x30d - ARPHRD_ATM = 0x13 - ARPHRD_AX25 = 0x3 - ARPHRD_BIF = 0x307 - ARPHRD_CAIF = 0x336 - ARPHRD_CAN = 0x118 - ARPHRD_CHAOS = 0x5 - ARPHRD_CISCO = 0x201 - ARPHRD_CSLIP = 0x101 - ARPHRD_CSLIP6 = 0x103 - ARPHRD_DDCMP = 0x205 - ARPHRD_DLCI = 0xf - ARPHRD_ECONET = 0x30e - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_EUI64 = 0x1b - ARPHRD_FCAL = 0x311 - ARPHRD_FCFABRIC = 0x313 - ARPHRD_FCPL = 0x312 - ARPHRD_FCPP = 0x310 - ARPHRD_FDDI = 0x306 - ARPHRD_FRAD = 0x302 - ARPHRD_HDLC = 0x201 - ARPHRD_HIPPI = 0x30c - ARPHRD_HWX25 = 0x110 - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IEEE80211 = 0x321 - ARPHRD_IEEE80211_PRISM = 0x322 - ARPHRD_IEEE80211_RADIOTAP = 0x323 - ARPHRD_IEEE802154 = 0x324 - ARPHRD_IEEE802154_MONITOR = 0x325 - ARPHRD_IEEE802_TR = 0x320 - ARPHRD_INFINIBAND = 0x20 - ARPHRD_IP6GRE = 0x337 - ARPHRD_IPDDP = 0x309 - ARPHRD_IPGRE = 0x30a - ARPHRD_IRDA = 0x30f - ARPHRD_LAPB = 0x204 - ARPHRD_LOCALTLK = 0x305 - ARPHRD_LOOPBACK = 0x304 - ARPHRD_METRICOM = 0x17 - ARPHRD_NETLINK = 0x338 - ARPHRD_NETROM = 0x0 - ARPHRD_NONE = 0xfffe - ARPHRD_PHONET = 0x334 - ARPHRD_PHONET_PIPE = 0x335 - ARPHRD_PIMREG = 0x30b - ARPHRD_PPP = 0x200 - ARPHRD_PRONET = 0x4 - ARPHRD_RAWHDLC = 0x206 - ARPHRD_ROSE = 0x10e - ARPHRD_RSRVD = 0x104 - ARPHRD_SIT = 0x308 - ARPHRD_SKIP = 0x303 - ARPHRD_SLIP = 0x100 - ARPHRD_SLIP6 = 0x102 - ARPHRD_TUNNEL = 0x300 - ARPHRD_TUNNEL6 = 0x301 - ARPHRD_VOID = 0xffff - ARPHRD_X25 = 0x10f - B0 = 0x0 - B1000000 = 0x17 - B110 = 0x3 - B115200 = 0x11 - B1152000 = 0x18 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B1500000 = 0x19 - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B2000000 = 0x1a - B230400 = 0x12 - B2400 = 0xb - B2500000 = 0x1b - B300 = 0x7 - B3000000 = 0x1c - B3500000 = 0x1d - B38400 = 0xf - B4000000 = 0x1e - B460800 = 0x13 - B4800 = 0xc - B50 = 0x1 - B500000 = 0x14 - B57600 = 0x10 - B576000 = 0x15 - B600 = 0x8 - B75 = 0x2 - B921600 = 0x16 - B9600 = 0xd - BOTHER = 0x1f - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXINSNS = 0x1000 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MOD = 0x90 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BPF_XOR = 0xa0 - BRKINT = 0x2 - BS0 = 0x0 - BS1 = 0x8000 - BSDLY = 0x8000 - CBAUD = 0xff - CBAUDEX = 0x0 - CFLUSH = 0xf - CIBAUD = 0xff0000 - CLOCAL = 0x8000 - CLOCK_BOOTTIME = 0x7 - CLOCK_BOOTTIME_ALARM = 0x9 - CLOCK_DEFAULT = 0x0 - CLOCK_EXT = 0x1 - CLOCK_INT = 0x2 - CLOCK_MONOTONIC = 0x1 - CLOCK_MONOTONIC_COARSE = 0x6 - CLOCK_MONOTONIC_RAW = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_REALTIME_ALARM = 0x8 - CLOCK_REALTIME_COARSE = 0x5 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CLOCK_TXFROMRX = 0x4 - CLOCK_TXINT = 0x3 - CLONE_CHILD_CLEARTID = 0x200000 - CLONE_CHILD_SETTID = 0x1000000 - CLONE_DETACHED = 0x400000 - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_IO = 0x80000000 - CLONE_NEWIPC = 0x8000000 - CLONE_NEWNET = 0x40000000 - CLONE_NEWNS = 0x20000 - CLONE_NEWPID = 0x20000000 - CLONE_NEWUSER = 0x10000000 - CLONE_NEWUTS = 0x4000000 - CLONE_PARENT = 0x8000 - CLONE_PARENT_SETTID = 0x100000 - CLONE_PTRACE = 0x2000 - CLONE_SETTLS = 0x80000 - CLONE_SIGHAND = 0x800 - CLONE_SYSVSEM = 0x40000 - CLONE_THREAD = 0x10000 - CLONE_UNTRACED = 0x800000 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CMSPAR = 0x40000000 - CR0 = 0x0 - CR1 = 0x1000 - CR2 = 0x2000 - CR3 = 0x3000 - CRDLY = 0x3000 - CREAD = 0x800 - CRTSCTS = 0x80000000 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIGNAL = 0xff - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x0 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - ENCODING_DEFAULT = 0x0 - ENCODING_FM_MARK = 0x3 - ENCODING_FM_SPACE = 0x4 - ENCODING_MANCHESTER = 0x5 - ENCODING_NRZ = 0x1 - ENCODING_NRZI = 0x2 - EPOLLERR = 0x8 - EPOLLET = 0x80000000 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLONESHOT = 0x40000000 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDHUP = 0x2000 - EPOLLRDNORM = 0x40 - EPOLLWAKEUP = 0x20000000 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CLOEXEC = 0x80000 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - ETH_P_1588 = 0x88f7 - ETH_P_8021AD = 0x88a8 - ETH_P_8021AH = 0x88e7 - ETH_P_8021Q = 0x8100 - ETH_P_802_2 = 0x4 - ETH_P_802_3 = 0x1 - ETH_P_802_3_MIN = 0x600 - ETH_P_802_EX1 = 0x88b5 - ETH_P_AARP = 0x80f3 - ETH_P_AF_IUCV = 0xfbfb - ETH_P_ALL = 0x3 - ETH_P_AOE = 0x88a2 - ETH_P_ARCNET = 0x1a - ETH_P_ARP = 0x806 - ETH_P_ATALK = 0x809b - ETH_P_ATMFATE = 0x8884 - ETH_P_ATMMPOA = 0x884c - ETH_P_AX25 = 0x2 - ETH_P_BATMAN = 0x4305 - ETH_P_BPQ = 0x8ff - ETH_P_CAIF = 0xf7 - ETH_P_CAN = 0xc - ETH_P_CANFD = 0xd - ETH_P_CONTROL = 0x16 - ETH_P_CUST = 0x6006 - ETH_P_DDCMP = 0x6 - ETH_P_DEC = 0x6000 - ETH_P_DIAG = 0x6005 - ETH_P_DNA_DL = 0x6001 - ETH_P_DNA_RC = 0x6002 - ETH_P_DNA_RT = 0x6003 - ETH_P_DSA = 0x1b - ETH_P_ECONET = 0x18 - ETH_P_EDSA = 0xdada - ETH_P_FCOE = 0x8906 - ETH_P_FIP = 0x8914 - ETH_P_HDLC = 0x19 - ETH_P_IEEE802154 = 0xf6 - ETH_P_IEEEPUP = 0xa00 - ETH_P_IEEEPUPAT = 0xa01 - ETH_P_IP = 0x800 - ETH_P_IPV6 = 0x86dd - ETH_P_IPX = 0x8137 - ETH_P_IRDA = 0x17 - ETH_P_LAT = 0x6004 - ETH_P_LINK_CTL = 0x886c - ETH_P_LOCALTALK = 0x9 - ETH_P_LOOP = 0x60 - ETH_P_MOBITEX = 0x15 - ETH_P_MPLS_MC = 0x8848 - ETH_P_MPLS_UC = 0x8847 - ETH_P_MVRP = 0x88f5 - ETH_P_PAE = 0x888e - ETH_P_PAUSE = 0x8808 - ETH_P_PHONET = 0xf5 - ETH_P_PPPTALK = 0x10 - ETH_P_PPP_DISC = 0x8863 - ETH_P_PPP_MP = 0x8 - ETH_P_PPP_SES = 0x8864 - ETH_P_PRP = 0x88fb - ETH_P_PUP = 0x200 - ETH_P_PUPAT = 0x201 - ETH_P_QINQ1 = 0x9100 - ETH_P_QINQ2 = 0x9200 - ETH_P_QINQ3 = 0x9300 - ETH_P_RARP = 0x8035 - ETH_P_SCA = 0x6007 - ETH_P_SLOW = 0x8809 - ETH_P_SNAP = 0x5 - ETH_P_TDLS = 0x890d - ETH_P_TEB = 0x6558 - ETH_P_TIPC = 0x88ca - ETH_P_TRAILER = 0x1c - ETH_P_TR_802_2 = 0x11 - ETH_P_WAN_PPP = 0x7 - ETH_P_WCCP = 0x883e - ETH_P_X25 = 0x805 - EXTA = 0xe - EXTB = 0xf - EXTPROC = 0x10000000 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FF0 = 0x0 - FF1 = 0x4000 - FFDLY = 0x4000 - FLUSHO = 0x800000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x406 - F_EXLCK = 0x4 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLEASE = 0x401 - F_GETLK = 0x5 - F_GETLK64 = 0xc - F_GETOWN = 0x9 - F_GETOWN_EX = 0x10 - F_GETPIPE_SZ = 0x408 - F_GETSIG = 0xb - F_LOCK = 0x1 - F_NOTIFY = 0x402 - F_OK = 0x0 - F_RDLCK = 0x0 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLEASE = 0x400 - F_SETLK = 0x6 - F_SETLK64 = 0xd - F_SETLKW = 0x7 - F_SETLKW64 = 0xe - F_SETOWN = 0x8 - F_SETOWN_EX = 0xf - F_SETPIPE_SZ = 0x407 - F_SETSIG = 0xa - F_SHLCK = 0x8 - F_TEST = 0x3 - F_TLOCK = 0x2 - F_ULOCK = 0x0 - F_UNLCK = 0x2 - F_WRLCK = 0x1 - HUPCL = 0x4000 - IBSHIFT = 0x10 - ICANON = 0x100 - ICMPV6_FILTER = 0x1 - ICRNL = 0x100 - IEXTEN = 0x400 - IFA_F_DADFAILED = 0x8 - IFA_F_DEPRECATED = 0x20 - IFA_F_HOMEADDRESS = 0x10 - IFA_F_NODAD = 0x2 - IFA_F_OPTIMISTIC = 0x4 - IFA_F_PERMANENT = 0x80 - IFA_F_SECONDARY = 0x1 - IFA_F_TEMPORARY = 0x1 - IFA_F_TENTATIVE = 0x40 - IFA_MAX = 0x7 - IFF_802_1Q_VLAN = 0x1 - IFF_ALLMULTI = 0x200 - IFF_ATTACH_QUEUE = 0x200 - IFF_AUTOMEDIA = 0x4000 - IFF_BONDING = 0x20 - IFF_BRIDGE_PORT = 0x4000 - IFF_BROADCAST = 0x2 - IFF_DEBUG = 0x4 - IFF_DETACH_QUEUE = 0x400 - IFF_DISABLE_NETPOLL = 0x1000 - IFF_DONT_BRIDGE = 0x800 - IFF_DORMANT = 0x20000 - IFF_DYNAMIC = 0x8000 - IFF_EBRIDGE = 0x2 - IFF_ECHO = 0x40000 - IFF_ISATAP = 0x80 - IFF_LIVE_ADDR_CHANGE = 0x100000 - IFF_LOOPBACK = 0x8 - IFF_LOWER_UP = 0x10000 - IFF_MACVLAN = 0x200000 - IFF_MACVLAN_PORT = 0x2000 - IFF_MASTER = 0x400 - IFF_MASTER_8023AD = 0x8 - IFF_MASTER_ALB = 0x10 - IFF_MASTER_ARPMON = 0x100 - IFF_MULTICAST = 0x1000 - IFF_MULTI_QUEUE = 0x100 - IFF_NOARP = 0x80 - IFF_NOFILTER = 0x1000 - IFF_NOTRAILERS = 0x20 - IFF_NO_PI = 0x1000 - IFF_ONE_QUEUE = 0x2000 - IFF_OVS_DATAPATH = 0x8000 - IFF_PERSIST = 0x800 - IFF_POINTOPOINT = 0x10 - IFF_PORTSEL = 0x2000 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SLAVE = 0x800 - IFF_SLAVE_INACTIVE = 0x4 - IFF_SLAVE_NEEDARP = 0x40 - IFF_SUPP_NOFCS = 0x80000 - IFF_TAP = 0x2 - IFF_TEAM_PORT = 0x40000 - IFF_TUN = 0x1 - IFF_TUN_EXCL = 0x8000 - IFF_TX_SKB_SHARING = 0x10000 - IFF_UNICAST_FLT = 0x20000 - IFF_UP = 0x1 - IFF_VNET_HDR = 0x4000 - IFF_VOLATILE = 0x70c5a - IFF_WAN_HDLC = 0x200 - IFF_XMIT_DST_RELEASE = 0x400 - IFNAMSIZ = 0x10 - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_ACCESS = 0x1 - IN_ALL_EVENTS = 0xfff - IN_ATTRIB = 0x4 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLOEXEC = 0x80000 - IN_CLOSE = 0x18 - IN_CLOSE_NOWRITE = 0x10 - IN_CLOSE_WRITE = 0x8 - IN_CREATE = 0x100 - IN_DELETE = 0x200 - IN_DELETE_SELF = 0x400 - IN_DONT_FOLLOW = 0x2000000 - IN_EXCL_UNLINK = 0x4000000 - IN_IGNORED = 0x8000 - IN_ISDIR = 0x40000000 - IN_LOOPBACKNET = 0x7f - IN_MASK_ADD = 0x20000000 - IN_MODIFY = 0x2 - IN_MOVE = 0xc0 - IN_MOVED_FROM = 0x40 - IN_MOVED_TO = 0x80 - IN_MOVE_SELF = 0x800 - IN_NONBLOCK = 0x800 - IN_ONESHOT = 0x80000000 - IN_ONLYDIR = 0x1000000 - IN_OPEN = 0x20 - IN_Q_OVERFLOW = 0x4000 - IN_UNMOUNT = 0x2000 - IPPROTO_AH = 0x33 - IPPROTO_BEETPH = 0x5e - IPPROTO_COMP = 0x6c - IPPROTO_DCCP = 0x21 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPIP = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MH = 0x87 - IPPROTO_MTP = 0x5c - IPPROTO_NONE = 0x3b - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_UDPLITE = 0x88 - IPV6_2292DSTOPTS = 0x4 - IPV6_2292HOPLIMIT = 0x8 - IPV6_2292HOPOPTS = 0x3 - IPV6_2292PKTINFO = 0x2 - IPV6_2292PKTOPTIONS = 0x6 - IPV6_2292RTHDR = 0x5 - IPV6_ADDRFORM = 0x1 - IPV6_ADD_MEMBERSHIP = 0x14 - IPV6_AUTHHDR = 0xa - IPV6_CHECKSUM = 0x7 - IPV6_DROP_MEMBERSHIP = 0x15 - IPV6_DSTOPTS = 0x3b - IPV6_HOPLIMIT = 0x34 - IPV6_HOPOPTS = 0x36 - IPV6_IPSEC_POLICY = 0x22 - IPV6_JOIN_ANYCAST = 0x1b - IPV6_JOIN_GROUP = 0x14 - IPV6_LEAVE_ANYCAST = 0x1c - IPV6_LEAVE_GROUP = 0x15 - IPV6_MTU = 0x18 - IPV6_MTU_DISCOVER = 0x17 - IPV6_MULTICAST_HOPS = 0x12 - IPV6_MULTICAST_IF = 0x11 - IPV6_MULTICAST_LOOP = 0x13 - IPV6_NEXTHOP = 0x9 - IPV6_PKTINFO = 0x32 - IPV6_PMTUDISC_DO = 0x2 - IPV6_PMTUDISC_DONT = 0x0 - IPV6_PMTUDISC_PROBE = 0x3 - IPV6_PMTUDISC_WANT = 0x1 - IPV6_RECVDSTOPTS = 0x3a - IPV6_RECVERR = 0x19 - IPV6_RECVHOPLIMIT = 0x33 - IPV6_RECVHOPOPTS = 0x35 - IPV6_RECVPKTINFO = 0x31 - IPV6_RECVRTHDR = 0x38 - IPV6_RECVTCLASS = 0x42 - IPV6_ROUTER_ALERT = 0x16 - IPV6_RTHDR = 0x39 - IPV6_RTHDRDSTOPTS = 0x37 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_RXDSTOPTS = 0x3b - IPV6_RXHOPOPTS = 0x36 - IPV6_TCLASS = 0x43 - IPV6_UNICAST_HOPS = 0x10 - IPV6_V6ONLY = 0x1a - IPV6_XFRM_POLICY = 0x23 - IP_ADD_MEMBERSHIP = 0x23 - IP_ADD_SOURCE_MEMBERSHIP = 0x27 - IP_BLOCK_SOURCE = 0x26 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0x24 - IP_DROP_SOURCE_MEMBERSHIP = 0x28 - IP_FREEBIND = 0xf - IP_HDRINCL = 0x3 - IP_IPSEC_POLICY = 0x10 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINTTL = 0x15 - IP_MSFILTER = 0x29 - IP_MSS = 0x240 - IP_MTU = 0xe - IP_MTU_DISCOVER = 0xa - IP_MULTICAST_ALL = 0x31 - IP_MULTICAST_IF = 0x20 - IP_MULTICAST_LOOP = 0x22 - IP_MULTICAST_TTL = 0x21 - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x4 - IP_ORIGDSTADDR = 0x14 - IP_PASSSEC = 0x12 - IP_PKTINFO = 0x8 - IP_PKTOPTIONS = 0x9 - IP_PMTUDISC = 0xa - IP_PMTUDISC_DO = 0x2 - IP_PMTUDISC_DONT = 0x0 - IP_PMTUDISC_PROBE = 0x3 - IP_PMTUDISC_WANT = 0x1 - IP_RECVERR = 0xb - IP_RECVOPTS = 0x6 - IP_RECVORIGDSTADDR = 0x14 - IP_RECVRETOPTS = 0x7 - IP_RECVTOS = 0xd - IP_RECVTTL = 0xc - IP_RETOPTS = 0x7 - IP_RF = 0x8000 - IP_ROUTER_ALERT = 0x5 - IP_TOS = 0x1 - IP_TRANSPARENT = 0x13 - IP_TTL = 0x2 - IP_UNBLOCK_SOURCE = 0x25 - IP_UNICAST_IF = 0x32 - IP_XFRM_POLICY = 0x11 - ISIG = 0x80 - ISTRIP = 0x20 - IUCLC = 0x1000 - IUTF8 = 0x4000 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LINUX_REBOOT_CMD_CAD_OFF = 0x0 - LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef - LINUX_REBOOT_CMD_HALT = 0xcdef0123 - LINUX_REBOOT_CMD_KEXEC = 0x45584543 - LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc - LINUX_REBOOT_CMD_RESTART = 0x1234567 - LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 - LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 - LINUX_REBOOT_MAGIC1 = 0xfee1dead - LINUX_REBOOT_MAGIC2 = 0x28121969 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DODUMP = 0x11 - MADV_DOFORK = 0xb - MADV_DONTDUMP = 0x10 - MADV_DONTFORK = 0xa - MADV_DONTNEED = 0x4 - MADV_HUGEPAGE = 0xe - MADV_HWPOISON = 0x64 - MADV_MERGEABLE = 0xc - MADV_NOHUGEPAGE = 0xf - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_REMOVE = 0x9 - MADV_SEQUENTIAL = 0x2 - MADV_UNMERGEABLE = 0xd - MADV_WILLNEED = 0x3 - MAP_ANON = 0x20 - MAP_ANONYMOUS = 0x20 - MAP_DENYWRITE = 0x800 - MAP_EXECUTABLE = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_GROWSDOWN = 0x100 - MAP_HUGETLB = 0x40000 - MAP_HUGE_MASK = 0x3f - MAP_HUGE_SHIFT = 0x1a - MAP_LOCKED = 0x80 - MAP_NONBLOCK = 0x10000 - MAP_NORESERVE = 0x40 - MAP_POPULATE = 0x8000 - MAP_PRIVATE = 0x2 - MAP_SHARED = 0x1 - MAP_STACK = 0x20000 - MAP_TYPE = 0xf - MCL_CURRENT = 0x2000 - MCL_FUTURE = 0x4000 - MNT_DETACH = 0x2 - MNT_EXPIRE = 0x4 - MNT_FORCE = 0x1 - MSG_CMSG_CLOEXEC = 0x40000000 - MSG_CONFIRM = 0x800 - MSG_CTRUNC = 0x8 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x40 - MSG_EOR = 0x80 - MSG_ERRQUEUE = 0x2000 - MSG_FASTOPEN = 0x20000000 - MSG_FIN = 0x200 - MSG_MORE = 0x8000 - MSG_NOSIGNAL = 0x4000 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_PROXY = 0x10 - MSG_RST = 0x1000 - MSG_SYN = 0x400 - MSG_TRUNC = 0x20 - MSG_TRYHARD = 0x4 - MSG_WAITALL = 0x100 - MSG_WAITFORONE = 0x10000 - MS_ACTIVE = 0x40000000 - MS_ASYNC = 0x1 - MS_BIND = 0x1000 - MS_DIRSYNC = 0x80 - MS_INVALIDATE = 0x2 - MS_I_VERSION = 0x800000 - MS_KERNMOUNT = 0x400000 - MS_MANDLOCK = 0x40 - MS_MGC_MSK = 0xffff0000 - MS_MGC_VAL = 0xc0ed0000 - MS_MOVE = 0x2000 - MS_NOATIME = 0x400 - MS_NODEV = 0x4 - MS_NODIRATIME = 0x800 - MS_NOEXEC = 0x8 - MS_NOSUID = 0x2 - MS_NOUSER = -0x80000000 - MS_POSIXACL = 0x10000 - MS_PRIVATE = 0x40000 - MS_RDONLY = 0x1 - MS_REC = 0x4000 - MS_RELATIME = 0x200000 - MS_REMOUNT = 0x20 - MS_RMT_MASK = 0x800051 - MS_SHARED = 0x100000 - MS_SILENT = 0x8000 - MS_SLAVE = 0x80000 - MS_STRICTATIME = 0x1000000 - MS_SYNC = 0x4 - MS_SYNCHRONOUS = 0x10 - MS_UNBINDABLE = 0x20000 - NAME_MAX = 0xff - NETLINK_ADD_MEMBERSHIP = 0x1 - NETLINK_AUDIT = 0x9 - NETLINK_BROADCAST_ERROR = 0x4 - NETLINK_CONNECTOR = 0xb - NETLINK_CRYPTO = 0x15 - NETLINK_DNRTMSG = 0xe - NETLINK_DROP_MEMBERSHIP = 0x2 - NETLINK_ECRYPTFS = 0x13 - NETLINK_FIB_LOOKUP = 0xa - NETLINK_FIREWALL = 0x3 - NETLINK_GENERIC = 0x10 - NETLINK_INET_DIAG = 0x4 - NETLINK_IP6_FW = 0xd - NETLINK_ISCSI = 0x8 - NETLINK_KOBJECT_UEVENT = 0xf - NETLINK_NETFILTER = 0xc - NETLINK_NFLOG = 0x5 - NETLINK_NO_ENOBUFS = 0x5 - NETLINK_PKTINFO = 0x3 - NETLINK_RDMA = 0x14 - NETLINK_ROUTE = 0x0 - NETLINK_RX_RING = 0x6 - NETLINK_SCSITRANSPORT = 0x12 - NETLINK_SELINUX = 0x7 - NETLINK_SOCK_DIAG = 0x4 - NETLINK_TX_RING = 0x7 - NETLINK_UNUSED = 0x1 - NETLINK_USERSOCK = 0x2 - NETLINK_XFRM = 0x6 - NL0 = 0x0 - NL1 = 0x100 - NL2 = 0x200 - NL3 = 0x300 - NLA_ALIGNTO = 0x4 - NLA_F_NESTED = 0x8000 - NLA_F_NET_BYTEORDER = 0x4000 - NLA_HDRLEN = 0x4 - NLDLY = 0x300 - NLMSG_ALIGNTO = 0x4 - NLMSG_DONE = 0x3 - NLMSG_ERROR = 0x2 - NLMSG_HDRLEN = 0x10 - NLMSG_MIN_TYPE = 0x10 - NLMSG_NOOP = 0x1 - NLMSG_OVERRUN = 0x4 - NLM_F_ACK = 0x4 - NLM_F_APPEND = 0x800 - NLM_F_ATOMIC = 0x400 - NLM_F_CREATE = 0x400 - NLM_F_DUMP = 0x300 - NLM_F_DUMP_INTR = 0x10 - NLM_F_ECHO = 0x8 - NLM_F_EXCL = 0x200 - NLM_F_MATCH = 0x200 - NLM_F_MULTI = 0x2 - NLM_F_REPLACE = 0x100 - NLM_F_REQUEST = 0x1 - NLM_F_ROOT = 0x100 - NOFLSH = 0x80000000 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - OLCUC = 0x4 - ONLCR = 0x2 - ONLRET = 0x20 - ONOCR = 0x10 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x400 - O_ASYNC = 0x2000 - O_CLOEXEC = 0x80000 - O_CREAT = 0x40 - O_DIRECT = 0x20000 - O_DIRECTORY = 0x4000 - O_DSYNC = 0x1000 - O_EXCL = 0x80 - O_FSYNC = 0x101000 - O_LARGEFILE = 0x0 - O_NDELAY = 0x800 - O_NOATIME = 0x40000 - O_NOCTTY = 0x100 - O_NOFOLLOW = 0x8000 - O_NONBLOCK = 0x800 - O_PATH = 0x200000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x101000 - O_SYNC = 0x101000 - O_TMPFILE = 0x410000 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - PACKET_ADD_MEMBERSHIP = 0x1 - PACKET_AUXDATA = 0x8 - PACKET_BROADCAST = 0x1 - PACKET_COPY_THRESH = 0x7 - PACKET_DROP_MEMBERSHIP = 0x2 - PACKET_FANOUT = 0x12 - PACKET_FANOUT_CPU = 0x2 - PACKET_FANOUT_FLAG_DEFRAG = 0x8000 - PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 - PACKET_FANOUT_HASH = 0x0 - PACKET_FANOUT_LB = 0x1 - PACKET_FANOUT_RND = 0x4 - PACKET_FANOUT_ROLLOVER = 0x3 - PACKET_FASTROUTE = 0x6 - PACKET_HDRLEN = 0xb - PACKET_HOST = 0x0 - PACKET_LOOPBACK = 0x5 - PACKET_LOSS = 0xe - PACKET_MR_ALLMULTI = 0x2 - PACKET_MR_MULTICAST = 0x0 - PACKET_MR_PROMISC = 0x1 - PACKET_MR_UNICAST = 0x3 - PACKET_MULTICAST = 0x2 - PACKET_ORIGDEV = 0x9 - PACKET_OTHERHOST = 0x3 - PACKET_OUTGOING = 0x4 - PACKET_RECV_OUTPUT = 0x3 - PACKET_RESERVE = 0xc - PACKET_RX_RING = 0x5 - PACKET_STATISTICS = 0x6 - PACKET_TIMESTAMP = 0x11 - PACKET_TX_HAS_OFF = 0x13 - PACKET_TX_RING = 0xd - PACKET_TX_TIMESTAMP = 0x10 - PACKET_VERSION = 0xa - PACKET_VNET_HDR = 0xf - PARENB = 0x1000 - PARITY_CRC16_PR0 = 0x2 - PARITY_CRC16_PR0_CCITT = 0x4 - PARITY_CRC16_PR1 = 0x3 - PARITY_CRC16_PR1_CCITT = 0x5 - PARITY_CRC32_PR0_CCITT = 0x6 - PARITY_CRC32_PR1_CCITT = 0x7 - PARITY_DEFAULT = 0x0 - PARITY_NONE = 0x1 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_GROWSDOWN = 0x1000000 - PROT_GROWSUP = 0x2000000 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_SAO = 0x10 - PROT_WRITE = 0x2 - PR_CAPBSET_DROP = 0x18 - PR_CAPBSET_READ = 0x17 - PR_ENDIAN_BIG = 0x0 - PR_ENDIAN_LITTLE = 0x1 - PR_ENDIAN_PPC_LITTLE = 0x2 - PR_FPEMU_NOPRINT = 0x1 - PR_FPEMU_SIGFPE = 0x2 - PR_FP_EXC_ASYNC = 0x2 - PR_FP_EXC_DISABLED = 0x0 - PR_FP_EXC_DIV = 0x10000 - PR_FP_EXC_INV = 0x100000 - PR_FP_EXC_NONRECOV = 0x1 - PR_FP_EXC_OVF = 0x20000 - PR_FP_EXC_PRECISE = 0x3 - PR_FP_EXC_RES = 0x80000 - PR_FP_EXC_SW_ENABLE = 0x80 - PR_FP_EXC_UND = 0x40000 - PR_GET_CHILD_SUBREAPER = 0x25 - PR_GET_DUMPABLE = 0x3 - PR_GET_ENDIAN = 0x13 - PR_GET_FPEMU = 0x9 - PR_GET_FPEXC = 0xb - PR_GET_KEEPCAPS = 0x7 - PR_GET_NAME = 0x10 - PR_GET_NO_NEW_PRIVS = 0x27 - PR_GET_PDEATHSIG = 0x2 - PR_GET_SECCOMP = 0x15 - PR_GET_SECUREBITS = 0x1b - PR_GET_TID_ADDRESS = 0x28 - PR_GET_TIMERSLACK = 0x1e - PR_GET_TIMING = 0xd - PR_GET_TSC = 0x19 - PR_GET_UNALIGN = 0x5 - PR_MCE_KILL = 0x21 - PR_MCE_KILL_CLEAR = 0x0 - PR_MCE_KILL_DEFAULT = 0x2 - PR_MCE_KILL_EARLY = 0x1 - PR_MCE_KILL_GET = 0x22 - PR_MCE_KILL_LATE = 0x0 - PR_MCE_KILL_SET = 0x1 - PR_SET_CHILD_SUBREAPER = 0x24 - PR_SET_DUMPABLE = 0x4 - PR_SET_ENDIAN = 0x14 - PR_SET_FPEMU = 0xa - PR_SET_FPEXC = 0xc - PR_SET_KEEPCAPS = 0x8 - PR_SET_MM = 0x23 - PR_SET_MM_ARG_END = 0x9 - PR_SET_MM_ARG_START = 0x8 - PR_SET_MM_AUXV = 0xc - PR_SET_MM_BRK = 0x7 - PR_SET_MM_END_CODE = 0x2 - PR_SET_MM_END_DATA = 0x4 - PR_SET_MM_ENV_END = 0xb - PR_SET_MM_ENV_START = 0xa - PR_SET_MM_EXE_FILE = 0xd - PR_SET_MM_START_BRK = 0x6 - PR_SET_MM_START_CODE = 0x1 - PR_SET_MM_START_DATA = 0x3 - PR_SET_MM_START_STACK = 0x5 - PR_SET_NAME = 0xf - PR_SET_NO_NEW_PRIVS = 0x26 - PR_SET_PDEATHSIG = 0x1 - PR_SET_PTRACER = 0x59616d61 - PR_SET_PTRACER_ANY = -0x1 - PR_SET_SECCOMP = 0x16 - PR_SET_SECUREBITS = 0x1c - PR_SET_TIMERSLACK = 0x1d - PR_SET_TIMING = 0xe - PR_SET_TSC = 0x1a - PR_SET_UNALIGN = 0x6 - PR_TASK_PERF_EVENTS_DISABLE = 0x1f - PR_TASK_PERF_EVENTS_ENABLE = 0x20 - PR_TIMING_STATISTICAL = 0x0 - PR_TIMING_TIMESTAMP = 0x1 - PR_TSC_ENABLE = 0x1 - PR_TSC_SIGSEGV = 0x2 - PR_UNALIGN_NOPRINT = 0x1 - PR_UNALIGN_SIGBUS = 0x2 - PTRACE_ATTACH = 0x10 - PTRACE_CONT = 0x7 - PTRACE_DETACH = 0x11 - PTRACE_EVENT_CLONE = 0x3 - PTRACE_EVENT_EXEC = 0x4 - PTRACE_EVENT_EXIT = 0x6 - PTRACE_EVENT_FORK = 0x1 - PTRACE_EVENT_SECCOMP = 0x7 - PTRACE_EVENT_STOP = 0x80 - PTRACE_EVENT_VFORK = 0x2 - PTRACE_EVENT_VFORK_DONE = 0x5 - PTRACE_GETEVENTMSG = 0x4201 - PTRACE_GETEVRREGS = 0x14 - PTRACE_GETFPREGS = 0xe - PTRACE_GETREGS = 0xc - PTRACE_GETREGS64 = 0x16 - PTRACE_GETREGSET = 0x4204 - PTRACE_GETSIGINFO = 0x4202 - PTRACE_GETSIGMASK = 0x420a - PTRACE_GETVRREGS = 0x12 - PTRACE_GETVSRREGS = 0x1b - PTRACE_GET_DEBUGREG = 0x19 - PTRACE_INTERRUPT = 0x4207 - PTRACE_KILL = 0x8 - PTRACE_LISTEN = 0x4208 - PTRACE_O_EXITKILL = 0x100000 - PTRACE_O_MASK = 0x1000ff - PTRACE_O_TRACECLONE = 0x8 - PTRACE_O_TRACEEXEC = 0x10 - PTRACE_O_TRACEEXIT = 0x40 - PTRACE_O_TRACEFORK = 0x2 - PTRACE_O_TRACESECCOMP = 0x80 - PTRACE_O_TRACESYSGOOD = 0x1 - PTRACE_O_TRACEVFORK = 0x4 - PTRACE_O_TRACEVFORKDONE = 0x20 - PTRACE_PEEKDATA = 0x2 - PTRACE_PEEKSIGINFO = 0x4209 - PTRACE_PEEKSIGINFO_SHARED = 0x1 - PTRACE_PEEKTEXT = 0x1 - PTRACE_PEEKUSR = 0x3 - PTRACE_POKEDATA = 0x5 - PTRACE_POKETEXT = 0x4 - PTRACE_POKEUSR = 0x6 - PTRACE_SEIZE = 0x4206 - PTRACE_SETEVRREGS = 0x15 - PTRACE_SETFPREGS = 0xf - PTRACE_SETOPTIONS = 0x4200 - PTRACE_SETREGS = 0xd - PTRACE_SETREGS64 = 0x17 - PTRACE_SETREGSET = 0x4205 - PTRACE_SETSIGINFO = 0x4203 - PTRACE_SETSIGMASK = 0x420b - PTRACE_SETVRREGS = 0x13 - PTRACE_SETVSRREGS = 0x1c - PTRACE_SET_DEBUGREG = 0x1a - PTRACE_SINGLEBLOCK = 0x100 - PTRACE_SINGLESTEP = 0x9 - PTRACE_SYSCALL = 0x18 - PTRACE_TRACEME = 0x0 - PT_CCR = 0x26 - PT_CTR = 0x23 - PT_DAR = 0x29 - PT_DSCR = 0x2c - PT_DSISR = 0x2a - PT_FPR0 = 0x30 - PT_FPSCR = 0x50 - PT_LNK = 0x24 - PT_MSR = 0x21 - PT_NIP = 0x20 - PT_ORIG_R3 = 0x22 - PT_R0 = 0x0 - PT_R1 = 0x1 - PT_R10 = 0xa - PT_R11 = 0xb - PT_R12 = 0xc - PT_R13 = 0xd - PT_R14 = 0xe - PT_R15 = 0xf - PT_R16 = 0x10 - PT_R17 = 0x11 - PT_R18 = 0x12 - PT_R19 = 0x13 - PT_R2 = 0x2 - PT_R20 = 0x14 - PT_R21 = 0x15 - PT_R22 = 0x16 - PT_R23 = 0x17 - PT_R24 = 0x18 - PT_R25 = 0x19 - PT_R26 = 0x1a - PT_R27 = 0x1b - PT_R28 = 0x1c - PT_R29 = 0x1d - PT_R3 = 0x3 - PT_R30 = 0x1e - PT_R31 = 0x1f - PT_R4 = 0x4 - PT_R5 = 0x5 - PT_R6 = 0x6 - PT_R7 = 0x7 - PT_R8 = 0x8 - PT_R9 = 0x9 - PT_REGS_COUNT = 0x2c - PT_RESULT = 0x2b - PT_SOFTE = 0x27 - PT_TRAP = 0x28 - PT_VR0 = 0x52 - PT_VRSAVE = 0x94 - PT_VSCR = 0x93 - PT_VSR0 = 0x96 - PT_VSR31 = 0xd4 - PT_XER = 0x25 - RLIMIT_AS = 0x9 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x7 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x1 - RTAX_ADVMSS = 0x8 - RTAX_CWND = 0x7 - RTAX_FEATURES = 0xc - RTAX_FEATURE_ALLFRAG = 0x8 - RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_SACK = 0x2 - RTAX_FEATURE_TIMESTAMP = 0x4 - RTAX_HOPLIMIT = 0xa - RTAX_INITCWND = 0xb - RTAX_INITRWND = 0xe - RTAX_LOCK = 0x1 - RTAX_MAX = 0xf - RTAX_MTU = 0x2 - RTAX_QUICKACK = 0xf - RTAX_REORDERING = 0x9 - RTAX_RTO_MIN = 0xd - RTAX_RTT = 0x4 - RTAX_RTTVAR = 0x5 - RTAX_SSTHRESH = 0x6 - RTAX_UNSPEC = 0x0 - RTAX_WINDOW = 0x3 - RTA_ALIGNTO = 0x4 - RTA_MAX = 0x11 - RTCF_DIRECTSRC = 0x4000000 - RTCF_DOREDIRECT = 0x1000000 - RTCF_LOG = 0x2000000 - RTCF_MASQ = 0x400000 - RTCF_NAT = 0x800000 - RTCF_VALVE = 0x200000 - RTF_ADDRCLASSMASK = 0xf8000000 - RTF_ADDRCONF = 0x40000 - RTF_ALLONLINK = 0x20000 - RTF_BROADCAST = 0x10000000 - RTF_CACHE = 0x1000000 - RTF_DEFAULT = 0x10000 - RTF_DYNAMIC = 0x10 - RTF_FLOW = 0x2000000 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INTERFACE = 0x40000000 - RTF_IRTT = 0x100 - RTF_LINKRT = 0x100000 - RTF_LOCAL = 0x80000000 - RTF_MODIFIED = 0x20 - RTF_MSS = 0x40 - RTF_MTU = 0x40 - RTF_MULTICAST = 0x20000000 - RTF_NAT = 0x8000000 - RTF_NOFORWARD = 0x1000 - RTF_NONEXTHOP = 0x200000 - RTF_NOPMTUDISC = 0x4000 - RTF_POLICY = 0x4000000 - RTF_REINSTATE = 0x8 - RTF_REJECT = 0x200 - RTF_STATIC = 0x400 - RTF_THROW = 0x2000 - RTF_UP = 0x1 - RTF_WINDOW = 0x80 - RTF_XRESOLVE = 0x800 - RTM_BASE = 0x10 - RTM_DELACTION = 0x31 - RTM_DELADDR = 0x15 - RTM_DELADDRLABEL = 0x49 - RTM_DELLINK = 0x11 - RTM_DELMDB = 0x55 - RTM_DELNEIGH = 0x1d - RTM_DELQDISC = 0x25 - RTM_DELROUTE = 0x19 - RTM_DELRULE = 0x21 - RTM_DELTCLASS = 0x29 - RTM_DELTFILTER = 0x2d - RTM_F_CLONED = 0x200 - RTM_F_EQUALIZE = 0x400 - RTM_F_NOTIFY = 0x100 - RTM_F_PREFIX = 0x800 - RTM_GETACTION = 0x32 - RTM_GETADDR = 0x16 - RTM_GETADDRLABEL = 0x4a - RTM_GETANYCAST = 0x3e - RTM_GETDCB = 0x4e - RTM_GETLINK = 0x12 - RTM_GETMDB = 0x56 - RTM_GETMULTICAST = 0x3a - RTM_GETNEIGH = 0x1e - RTM_GETNEIGHTBL = 0x42 - RTM_GETNETCONF = 0x52 - RTM_GETQDISC = 0x26 - RTM_GETROUTE = 0x1a - RTM_GETRULE = 0x22 - RTM_GETTCLASS = 0x2a - RTM_GETTFILTER = 0x2e - RTM_MAX = 0x57 - RTM_NEWACTION = 0x30 - RTM_NEWADDR = 0x14 - RTM_NEWADDRLABEL = 0x48 - RTM_NEWLINK = 0x10 - RTM_NEWMDB = 0x54 - RTM_NEWNDUSEROPT = 0x44 - RTM_NEWNEIGH = 0x1c - RTM_NEWNEIGHTBL = 0x40 - RTM_NEWNETCONF = 0x50 - RTM_NEWPREFIX = 0x34 - RTM_NEWQDISC = 0x24 - RTM_NEWROUTE = 0x18 - RTM_NEWRULE = 0x20 - RTM_NEWTCLASS = 0x28 - RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x12 - RTM_NR_MSGTYPES = 0x48 - RTM_SETDCB = 0x4f - RTM_SETLINK = 0x13 - RTM_SETNEIGHTBL = 0x43 - RTNH_ALIGNTO = 0x4 - RTNH_F_DEAD = 0x1 - RTNH_F_ONLINK = 0x4 - RTNH_F_PERVASIVE = 0x2 - RTN_MAX = 0xb - RTPROT_BIRD = 0xc - RTPROT_BOOT = 0x3 - RTPROT_DHCP = 0x10 - RTPROT_DNROUTED = 0xd - RTPROT_GATED = 0x8 - RTPROT_KERNEL = 0x2 - RTPROT_MROUTED = 0x11 - RTPROT_MRT = 0xa - RTPROT_NTK = 0xf - RTPROT_RA = 0x9 - RTPROT_REDIRECT = 0x1 - RTPROT_STATIC = 0x4 - RTPROT_UNSPEC = 0x0 - RTPROT_XORP = 0xe - RTPROT_ZEBRA = 0xb - RT_CLASS_DEFAULT = 0xfd - RT_CLASS_LOCAL = 0xff - RT_CLASS_MAIN = 0xfe - RT_CLASS_MAX = 0xff - RT_CLASS_UNSPEC = 0x0 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_CREDENTIALS = 0x2 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x1d - SCM_TIMESTAMPING = 0x25 - SCM_TIMESTAMPNS = 0x23 - SCM_WIFI_STATUS = 0x29 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDDLCI = 0x8980 - SIOCADDMULTI = 0x8931 - SIOCADDRT = 0x890b - SIOCATMARK = 0x8905 - SIOCDARP = 0x8953 - SIOCDELDLCI = 0x8981 - SIOCDELMULTI = 0x8932 - SIOCDELRT = 0x890c - SIOCDEVPRIVATE = 0x89f0 - SIOCDIFADDR = 0x8936 - SIOCDRARP = 0x8960 - SIOCGARP = 0x8954 - SIOCGIFADDR = 0x8915 - SIOCGIFBR = 0x8940 - SIOCGIFBRDADDR = 0x8919 - SIOCGIFCONF = 0x8912 - SIOCGIFCOUNT = 0x8938 - SIOCGIFDSTADDR = 0x8917 - SIOCGIFENCAP = 0x8925 - SIOCGIFFLAGS = 0x8913 - SIOCGIFHWADDR = 0x8927 - SIOCGIFINDEX = 0x8933 - SIOCGIFMAP = 0x8970 - SIOCGIFMEM = 0x891f - SIOCGIFMETRIC = 0x891d - SIOCGIFMTU = 0x8921 - SIOCGIFNAME = 0x8910 - SIOCGIFNETMASK = 0x891b - SIOCGIFPFLAGS = 0x8935 - SIOCGIFSLAVE = 0x8929 - SIOCGIFTXQLEN = 0x8942 - SIOCGPGRP = 0x8904 - SIOCGRARP = 0x8961 - SIOCGSTAMP = 0x8906 - SIOCGSTAMPNS = 0x8907 - SIOCPROTOPRIVATE = 0x89e0 - SIOCRTMSG = 0x890d - SIOCSARP = 0x8955 - SIOCSIFADDR = 0x8916 - SIOCSIFBR = 0x8941 - SIOCSIFBRDADDR = 0x891a - SIOCSIFDSTADDR = 0x8918 - SIOCSIFENCAP = 0x8926 - SIOCSIFFLAGS = 0x8914 - SIOCSIFHWADDR = 0x8924 - SIOCSIFHWBROADCAST = 0x8937 - SIOCSIFLINK = 0x8911 - SIOCSIFMAP = 0x8971 - SIOCSIFMEM = 0x8920 - SIOCSIFMETRIC = 0x891e - SIOCSIFMTU = 0x8922 - SIOCSIFNAME = 0x8923 - SIOCSIFNETMASK = 0x891c - SIOCSIFPFLAGS = 0x8934 - SIOCSIFSLAVE = 0x8930 - SIOCSIFTXQLEN = 0x8943 - SIOCSPGRP = 0x8902 - SIOCSRARP = 0x8962 - SOCK_CLOEXEC = 0x80000 - SOCK_DCCP = 0x6 - SOCK_DGRAM = 0x2 - SOCK_NONBLOCK = 0x800 - SOCK_PACKET = 0xa - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_AAL = 0x109 - SOL_ATM = 0x108 - SOL_DECNET = 0x105 - SOL_ICMPV6 = 0x3a - SOL_IP = 0x0 - SOL_IPV6 = 0x29 - SOL_IRDA = 0x10a - SOL_PACKET = 0x107 - SOL_RAW = 0xff - SOL_SOCKET = 0x1 - SOL_TCP = 0x6 - SOL_X25 = 0x106 - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x1e - SO_ATTACH_FILTER = 0x1a - SO_BINDTODEVICE = 0x19 - SO_BROADCAST = 0x6 - SO_BSDCOMPAT = 0xe - SO_BUSY_POLL = 0x2e - SO_DEBUG = 0x1 - SO_DETACH_FILTER = 0x1b - SO_DOMAIN = 0x27 - SO_DONTROUTE = 0x5 - SO_ERROR = 0x4 - SO_GET_FILTER = 0x1a - SO_KEEPALIVE = 0x9 - SO_LINGER = 0xd - SO_LOCK_FILTER = 0x2c - SO_MARK = 0x24 - SO_MAX_PACING_RATE = 0x2f - SO_NOFCS = 0x2b - SO_NO_CHECK = 0xb - SO_OOBINLINE = 0xa - SO_PASSCRED = 0x14 - SO_PASSSEC = 0x22 - SO_PEEK_OFF = 0x2a - SO_PEERCRED = 0x15 - SO_PEERNAME = 0x1c - SO_PEERSEC = 0x1f - SO_PRIORITY = 0xc - SO_PROTOCOL = 0x26 - SO_RCVBUF = 0x8 - SO_RCVBUFFORCE = 0x21 - SO_RCVLOWAT = 0x10 - SO_RCVTIMEO = 0x12 - SO_REUSEADDR = 0x2 - SO_REUSEPORT = 0xf - SO_RXQ_OVFL = 0x28 - SO_SECURITY_AUTHENTICATION = 0x16 - SO_SECURITY_ENCRYPTION_NETWORK = 0x18 - SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 - SO_SELECT_ERR_QUEUE = 0x2d - SO_SNDBUF = 0x7 - SO_SNDBUFFORCE = 0x20 - SO_SNDLOWAT = 0x11 - SO_SNDTIMEO = 0x13 - SO_TIMESTAMP = 0x1d - SO_TIMESTAMPING = 0x25 - SO_TIMESTAMPNS = 0x23 - SO_TYPE = 0x3 - SO_WIFI_STATUS = 0x29 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TAB0 = 0x0 - TAB1 = 0x400 - TAB2 = 0x800 - TAB3 = 0xc00 - TABDLY = 0xc00 - TCFLSH = 0x2000741f - TCGETA = 0x40147417 - TCGETS = 0x402c7413 - TCIFLUSH = 0x0 - TCIOFF = 0x2 - TCIOFLUSH = 0x2 - TCION = 0x3 - TCOFLUSH = 0x1 - TCOOFF = 0x0 - TCOON = 0x1 - TCP_CONGESTION = 0xd - TCP_COOKIE_IN_ALWAYS = 0x1 - TCP_COOKIE_MAX = 0x10 - TCP_COOKIE_MIN = 0x8 - TCP_COOKIE_OUT_NEVER = 0x2 - TCP_COOKIE_PAIR_SIZE = 0x20 - TCP_COOKIE_TRANSACTIONS = 0xf - TCP_CORK = 0x3 - TCP_DEFER_ACCEPT = 0x9 - TCP_FASTOPEN = 0x17 - TCP_INFO = 0xb - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x4 - TCP_KEEPINTVL = 0x5 - TCP_LINGER2 = 0x8 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0xe - TCP_MD5SIG_MAXKEYLEN = 0x50 - TCP_MSS = 0x200 - TCP_MSS_DEFAULT = 0x218 - TCP_MSS_DESIRED = 0x4c4 - TCP_NODELAY = 0x1 - TCP_QUEUE_SEQ = 0x15 - TCP_QUICKACK = 0xc - TCP_REPAIR = 0x13 - TCP_REPAIR_OPTIONS = 0x16 - TCP_REPAIR_QUEUE = 0x14 - TCP_SYNCNT = 0x7 - TCP_S_DATA_IN = 0x4 - TCP_S_DATA_OUT = 0x8 - TCP_THIN_DUPACK = 0x11 - TCP_THIN_LINEAR_TIMEOUTS = 0x10 - TCP_TIMESTAMP = 0x18 - TCP_USER_TIMEOUT = 0x12 - TCP_WINDOW_CLAMP = 0xa - TCSAFLUSH = 0x2 - TCSBRK = 0x2000741d - TCSBRKP = 0x5425 - TCSETA = 0x80147418 - TCSETAF = 0x8014741c - TCSETAW = 0x80147419 - TCSETS = 0x802c7414 - TCSETSF = 0x802c7416 - TCSETSW = 0x802c7415 - TCXONC = 0x2000741e - TIOCCBRK = 0x5428 - TIOCCONS = 0x541d - TIOCEXCL = 0x540c - TIOCGDEV = 0x40045432 - TIOCGETC = 0x40067412 - TIOCGETD = 0x5424 - TIOCGETP = 0x40067408 - TIOCGEXCL = 0x40045440 - TIOCGICOUNT = 0x545d - TIOCGLCKTRMIOS = 0x5456 - TIOCGLTC = 0x40067474 - TIOCGPGRP = 0x40047477 - TIOCGPKT = 0x40045438 - TIOCGPTLCK = 0x40045439 - TIOCGPTN = 0x40045430 - TIOCGRS485 = 0x542e - TIOCGSERIAL = 0x541e - TIOCGSID = 0x5429 - TIOCGSOFTCAR = 0x5419 - TIOCGWINSZ = 0x40087468 - TIOCINQ = 0x4004667f - TIOCLINUX = 0x541c - TIOCMBIC = 0x5417 - TIOCMBIS = 0x5416 - TIOCMGET = 0x5415 - TIOCMIWAIT = 0x545c - TIOCMSET = 0x5418 - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_LOOP = 0x8000 - TIOCM_OUT1 = 0x2000 - TIOCM_OUT2 = 0x4000 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x5422 - TIOCNXCL = 0x540d - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x5420 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCSBRK = 0x5427 - TIOCSCTTY = 0x540e - TIOCSERCONFIG = 0x5453 - TIOCSERGETLSR = 0x5459 - TIOCSERGETMULTI = 0x545a - TIOCSERGSTRUCT = 0x5458 - TIOCSERGWILD = 0x5454 - TIOCSERSETMULTI = 0x545b - TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 - TIOCSETC = 0x80067411 - TIOCSETD = 0x5423 - TIOCSETN = 0x8006740a - TIOCSETP = 0x80067409 - TIOCSIG = 0x80045436 - TIOCSLCKTRMIOS = 0x5457 - TIOCSLTC = 0x80067475 - TIOCSPGRP = 0x80047476 - TIOCSPTLCK = 0x80045431 - TIOCSRS485 = 0x542f - TIOCSSERIAL = 0x541f - TIOCSSOFTCAR = 0x541a - TIOCSTART = 0x2000746e - TIOCSTI = 0x5412 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCVHANGUP = 0x5437 - TOSTOP = 0x400000 - TUNATTACHFILTER = 0x801054d5 - TUNDETACHFILTER = 0x801054d6 - TUNGETFEATURES = 0x400454cf - TUNGETFILTER = 0x401054db - TUNGETIFF = 0x400454d2 - TUNGETSNDBUF = 0x400454d3 - TUNGETVNETHDRSZ = 0x400454d7 - TUNSETDEBUG = 0x800454c9 - TUNSETGROUP = 0x800454ce - TUNSETIFF = 0x800454ca - TUNSETIFINDEX = 0x800454da - TUNSETLINK = 0x800454cd - TUNSETNOCSUM = 0x800454c8 - TUNSETOFFLOAD = 0x800454d0 - TUNSETOWNER = 0x800454cc - TUNSETPERSIST = 0x800454cb - TUNSETQUEUE = 0x800454d9 - TUNSETSNDBUF = 0x800454d4 - TUNSETTXFILTER = 0x800454d1 - TUNSETVNETHDRSZ = 0x800454d8 - VDISCARD = 0x10 - VEOF = 0x4 - VEOL = 0x6 - VEOL2 = 0x8 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x5 - VQUIT = 0x1 - VREPRINT = 0xb - VSTART = 0xd - VSTOP = 0xe - VSUSP = 0xc - VSWTC = 0x9 - VT0 = 0x0 - VT1 = 0x10000 - VTDLY = 0x10000 - VTIME = 0x7 - VWERASE = 0xa - WALL = 0x40000000 - WCLONE = 0x80000000 - WCONTINUED = 0x8 - WEXITED = 0x4 - WNOHANG = 0x1 - WNOTHREAD = 0x20000000 - WNOWAIT = 0x1000000 - WORDSIZE = 0x40 - WSTOPPED = 0x2 - WUNTRACED = 0x2 - XCASE = 0x4000 - XTABS = 0xc00 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x62) - EADDRNOTAVAIL = syscall.Errno(0x63) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x61) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x72) - EBADE = syscall.Errno(0x34) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x4d) - EBADMSG = syscall.Errno(0x4a) - EBADR = syscall.Errno(0x35) - EBADRQC = syscall.Errno(0x38) - EBADSLT = syscall.Errno(0x39) - EBFONT = syscall.Errno(0x3b) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x7d) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x2c) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x67) - ECONNREFUSED = syscall.Errno(0x6f) - ECONNRESET = syscall.Errno(0x68) - EDEADLK = syscall.Errno(0x23) - EDEADLOCK = syscall.Errno(0x3a) - EDESTADDRREQ = syscall.Errno(0x59) - EDOM = syscall.Errno(0x21) - EDOTDOT = syscall.Errno(0x49) - EDQUOT = syscall.Errno(0x7a) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x70) - EHOSTUNREACH = syscall.Errno(0x71) - EHWPOISON = syscall.Errno(0x85) - EIDRM = syscall.Errno(0x2b) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x73) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x6a) - EISDIR = syscall.Errno(0x15) - EISNAM = syscall.Errno(0x78) - EKEYEXPIRED = syscall.Errno(0x7f) - EKEYREJECTED = syscall.Errno(0x81) - EKEYREVOKED = syscall.Errno(0x80) - EL2HLT = syscall.Errno(0x33) - EL2NSYNC = syscall.Errno(0x2d) - EL3HLT = syscall.Errno(0x2e) - EL3RST = syscall.Errno(0x2f) - ELIBACC = syscall.Errno(0x4f) - ELIBBAD = syscall.Errno(0x50) - ELIBEXEC = syscall.Errno(0x53) - ELIBMAX = syscall.Errno(0x52) - ELIBSCN = syscall.Errno(0x51) - ELNRNG = syscall.Errno(0x30) - ELOOP = syscall.Errno(0x28) - EMEDIUMTYPE = syscall.Errno(0x7c) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x5a) - EMULTIHOP = syscall.Errno(0x48) - ENAMETOOLONG = syscall.Errno(0x24) - ENAVAIL = syscall.Errno(0x77) - ENETDOWN = syscall.Errno(0x64) - ENETRESET = syscall.Errno(0x66) - ENETUNREACH = syscall.Errno(0x65) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x37) - ENOBUFS = syscall.Errno(0x69) - ENOCSI = syscall.Errno(0x32) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOKEY = syscall.Errno(0x7e) - ENOLCK = syscall.Errno(0x25) - ENOLINK = syscall.Errno(0x43) - ENOMEDIUM = syscall.Errno(0x7b) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x2a) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x5c) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x26) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x6b) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x27) - ENOTNAM = syscall.Errno(0x76) - ENOTRECOVERABLE = syscall.Errno(0x83) - ENOTSOCK = syscall.Errno(0x58) - ENOTSUP = syscall.Errno(0x5f) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x4c) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x5f) - EOVERFLOW = syscall.Errno(0x4b) - EOWNERDEAD = syscall.Errno(0x82) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x60) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x5d) - EPROTOTYPE = syscall.Errno(0x5b) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x4e) - EREMOTE = syscall.Errno(0x42) - EREMOTEIO = syscall.Errno(0x79) - ERESTART = syscall.Errno(0x55) - ERFKILL = syscall.Errno(0x84) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x6c) - ESOCKTNOSUPPORT = syscall.Errno(0x5e) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x74) - ESTRPIPE = syscall.Errno(0x56) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x6e) - ETOOMANYREFS = syscall.Errno(0x6d) - ETXTBSY = syscall.Errno(0x1a) - EUCLEAN = syscall.Errno(0x75) - EUNATCH = syscall.Errno(0x31) - EUSERS = syscall.Errno(0x57) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x36) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0x7) - SIGCHLD = syscall.Signal(0x11) - SIGCLD = syscall.Signal(0x11) - SIGCONT = syscall.Signal(0x12) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x1d) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x1d) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x1e) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTKFLT = syscall.Signal(0x10) - SIGSTOP = syscall.Signal(0x13) - SIGSYS = syscall.Signal(0x1f) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x14) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGUNUSED = syscall.Signal(0x1f) - SIGURG = syscall.Signal(0x17) - SIGUSR1 = syscall.Signal(0xa) - SIGUSR2 = syscall.Signal(0xc) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 58: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_386.go deleted file mode 100644 index b4338d5f2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_386.go +++ /dev/null @@ -1,1712 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,netbsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ARP = 0x1c - AF_BLUETOOTH = 0x1f - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x20 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x18 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x23 - AF_MPLS = 0x21 - AF_NATM = 0x1b - AF_NS = 0x6 - AF_OROUTE = 0x11 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x22 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - ARPHRD_ARCNET = 0x7 - ARPHRD_ETHER = 0x1 - ARPHRD_FRELAY = 0xf - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_STRIP = 0x17 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B460800 = 0x70800 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B921600 = 0xe1000 - B9600 = 0x2580 - BIOCFEEDBACK = 0x8004427d - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0084277 - BIOCGETIF = 0x4090426b - BIOCGFEEDBACK = 0x4004427c - BIOCGHDRCMPLT = 0x40044274 - BIOCGRTIMEOUT = 0x400c427b - BIOCGSEESENT = 0x40044278 - BIOCGSTATS = 0x4080426f - BIOCGSTATSOLD = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044276 - BIOCSETF = 0x80084267 - BIOCSETIF = 0x8090426c - BIOCSFEEDBACK = 0x8004427d - BIOCSHDRCMPLT = 0x80044275 - BIOCSRTIMEOUT = 0x800c427a - BIOCSSEESENT = 0x80044279 - BIOCSTCPF = 0x80084272 - BIOCSUDPF = 0x80084273 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALIGNMENT32 = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DFLTBUFSIZE = 0x100000 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x1000000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CLONE_CSIGNAL = 0xff - CLONE_FILES = 0x400 - CLONE_FS = 0x200 - CLONE_PID = 0x1000 - CLONE_PTRACE = 0x2000 - CLONE_SIGHAND = 0x800 - CLONE_VFORK = 0x4000 - CLONE_VM = 0x100 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - CTL_QUERY = -0x2 - DIOCBSFLUSH = 0x20006478 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HDLC = 0x10 - DLT_HHDLC = 0x79 - DLT_HIPPI = 0xf - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0xe - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RAWAF_MASK = 0x2240000 - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xd - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EMUL_LINUX = 0x1 - EMUL_LINUX32 = 0x5 - EMUL_MAXID = 0x6 - EN_SW_CTL_INF = 0x1000 - EN_SW_CTL_PREC = 0x300 - EN_SW_CTL_ROUND = 0xc00 - EN_SW_DATACHAIN = 0x80 - EN_SW_DENORM = 0x2 - EN_SW_INVOP = 0x1 - EN_SW_OVERFLOW = 0x8 - EN_SW_PRECLOSS = 0x20 - EN_SW_UNDERFLOW = 0x10 - EN_SW_ZERODIV = 0x4 - ETHERCAP_JUMBO_MTU = 0x4 - ETHERCAP_VLAN_HWTAGGING = 0x2 - ETHERCAP_VLAN_MTU = 0x1 - ETHERMIN = 0x2e - ETHERMTU = 0x5dc - ETHERMTU_JUMBO = 0x2328 - ETHERTYPE_8023 = 0x4 - ETHERTYPE_AARP = 0x80f3 - ETHERTYPE_ACCTON = 0x8390 - ETHERTYPE_AEONIC = 0x8036 - ETHERTYPE_ALPHA = 0x814a - ETHERTYPE_AMBER = 0x6008 - ETHERTYPE_AMOEBA = 0x8145 - ETHERTYPE_APOLLO = 0x80f7 - ETHERTYPE_APOLLODOMAIN = 0x8019 - ETHERTYPE_APPLETALK = 0x809b - ETHERTYPE_APPLITEK = 0x80c7 - ETHERTYPE_ARGONAUT = 0x803a - ETHERTYPE_ARP = 0x806 - ETHERTYPE_AT = 0x809b - ETHERTYPE_ATALK = 0x809b - ETHERTYPE_ATOMIC = 0x86df - ETHERTYPE_ATT = 0x8069 - ETHERTYPE_ATTSTANFORD = 0x8008 - ETHERTYPE_AUTOPHON = 0x806a - ETHERTYPE_AXIS = 0x8856 - ETHERTYPE_BCLOOP = 0x9003 - ETHERTYPE_BOFL = 0x8102 - ETHERTYPE_CABLETRON = 0x7034 - ETHERTYPE_CHAOS = 0x804 - ETHERTYPE_COMDESIGN = 0x806c - ETHERTYPE_COMPUGRAPHIC = 0x806d - ETHERTYPE_COUNTERPOINT = 0x8062 - ETHERTYPE_CRONUS = 0x8004 - ETHERTYPE_CRONUSVLN = 0x8003 - ETHERTYPE_DCA = 0x1234 - ETHERTYPE_DDE = 0x807b - ETHERTYPE_DEBNI = 0xaaaa - ETHERTYPE_DECAM = 0x8048 - ETHERTYPE_DECCUST = 0x6006 - ETHERTYPE_DECDIAG = 0x6005 - ETHERTYPE_DECDNS = 0x803c - ETHERTYPE_DECDTS = 0x803e - ETHERTYPE_DECEXPER = 0x6000 - ETHERTYPE_DECLAST = 0x8041 - ETHERTYPE_DECLTM = 0x803f - ETHERTYPE_DECMUMPS = 0x6009 - ETHERTYPE_DECNETBIOS = 0x8040 - ETHERTYPE_DELTACON = 0x86de - ETHERTYPE_DIDDLE = 0x4321 - ETHERTYPE_DLOG1 = 0x660 - ETHERTYPE_DLOG2 = 0x661 - ETHERTYPE_DN = 0x6003 - ETHERTYPE_DOGFIGHT = 0x1989 - ETHERTYPE_DSMD = 0x8039 - ETHERTYPE_ECMA = 0x803 - ETHERTYPE_ENCRYPT = 0x803d - ETHERTYPE_ES = 0x805d - ETHERTYPE_EXCELAN = 0x8010 - ETHERTYPE_EXPERDATA = 0x8049 - ETHERTYPE_FLIP = 0x8146 - ETHERTYPE_FLOWCONTROL = 0x8808 - ETHERTYPE_FRARP = 0x808 - ETHERTYPE_GENDYN = 0x8068 - ETHERTYPE_HAYES = 0x8130 - ETHERTYPE_HIPPI_FP = 0x8180 - ETHERTYPE_HITACHI = 0x8820 - ETHERTYPE_HP = 0x8005 - ETHERTYPE_IEEEPUP = 0xa00 - ETHERTYPE_IEEEPUPAT = 0xa01 - ETHERTYPE_IMLBL = 0x4c42 - ETHERTYPE_IMLBLDIAG = 0x424c - ETHERTYPE_IP = 0x800 - ETHERTYPE_IPAS = 0x876c - ETHERTYPE_IPV6 = 0x86dd - ETHERTYPE_IPX = 0x8137 - ETHERTYPE_IPXNEW = 0x8037 - ETHERTYPE_KALPANA = 0x8582 - ETHERTYPE_LANBRIDGE = 0x8038 - ETHERTYPE_LANPROBE = 0x8888 - ETHERTYPE_LAT = 0x6004 - ETHERTYPE_LBACK = 0x9000 - ETHERTYPE_LITTLE = 0x8060 - ETHERTYPE_LOGICRAFT = 0x8148 - ETHERTYPE_LOOPBACK = 0x9000 - ETHERTYPE_MATRA = 0x807a - ETHERTYPE_MAX = 0xffff - ETHERTYPE_MERIT = 0x807c - ETHERTYPE_MICP = 0x873a - ETHERTYPE_MOPDL = 0x6001 - ETHERTYPE_MOPRC = 0x6002 - ETHERTYPE_MOTOROLA = 0x818d - ETHERTYPE_MPLS = 0x8847 - ETHERTYPE_MPLS_MCAST = 0x8848 - ETHERTYPE_MUMPS = 0x813f - ETHERTYPE_NBPCC = 0x3c04 - ETHERTYPE_NBPCLAIM = 0x3c09 - ETHERTYPE_NBPCLREQ = 0x3c05 - ETHERTYPE_NBPCLRSP = 0x3c06 - ETHERTYPE_NBPCREQ = 0x3c02 - ETHERTYPE_NBPCRSP = 0x3c03 - ETHERTYPE_NBPDG = 0x3c07 - ETHERTYPE_NBPDGB = 0x3c08 - ETHERTYPE_NBPDLTE = 0x3c0a - ETHERTYPE_NBPRAR = 0x3c0c - ETHERTYPE_NBPRAS = 0x3c0b - ETHERTYPE_NBPRST = 0x3c0d - ETHERTYPE_NBPSCD = 0x3c01 - ETHERTYPE_NBPVCD = 0x3c00 - ETHERTYPE_NBS = 0x802 - ETHERTYPE_NCD = 0x8149 - ETHERTYPE_NESTAR = 0x8006 - ETHERTYPE_NETBEUI = 0x8191 - ETHERTYPE_NOVELL = 0x8138 - ETHERTYPE_NS = 0x600 - ETHERTYPE_NSAT = 0x601 - ETHERTYPE_NSCOMPAT = 0x807 - ETHERTYPE_NTRAILER = 0x10 - ETHERTYPE_OS9 = 0x7007 - ETHERTYPE_OS9NET = 0x7009 - ETHERTYPE_PACER = 0x80c6 - ETHERTYPE_PAE = 0x888e - ETHERTYPE_PCS = 0x4242 - ETHERTYPE_PLANNING = 0x8044 - ETHERTYPE_PPP = 0x880b - ETHERTYPE_PPPOE = 0x8864 - ETHERTYPE_PPPOEDISC = 0x8863 - ETHERTYPE_PRIMENTS = 0x7031 - ETHERTYPE_PUP = 0x200 - ETHERTYPE_PUPAT = 0x200 - ETHERTYPE_RACAL = 0x7030 - ETHERTYPE_RATIONAL = 0x8150 - ETHERTYPE_RAWFR = 0x6559 - ETHERTYPE_RCL = 0x1995 - ETHERTYPE_RDP = 0x8739 - ETHERTYPE_RETIX = 0x80f2 - ETHERTYPE_REVARP = 0x8035 - ETHERTYPE_SCA = 0x6007 - ETHERTYPE_SECTRA = 0x86db - ETHERTYPE_SECUREDATA = 0x876d - ETHERTYPE_SGITW = 0x817e - ETHERTYPE_SG_BOUNCE = 0x8016 - ETHERTYPE_SG_DIAG = 0x8013 - ETHERTYPE_SG_NETGAMES = 0x8014 - ETHERTYPE_SG_RESV = 0x8015 - ETHERTYPE_SIMNET = 0x5208 - ETHERTYPE_SLOWPROTOCOLS = 0x8809 - ETHERTYPE_SNA = 0x80d5 - ETHERTYPE_SNMP = 0x814c - ETHERTYPE_SONIX = 0xfaf5 - ETHERTYPE_SPIDER = 0x809f - ETHERTYPE_SPRITE = 0x500 - ETHERTYPE_STP = 0x8181 - ETHERTYPE_TALARIS = 0x812b - ETHERTYPE_TALARISMC = 0x852b - ETHERTYPE_TCPCOMP = 0x876b - ETHERTYPE_TCPSM = 0x9002 - ETHERTYPE_TEC = 0x814f - ETHERTYPE_TIGAN = 0x802f - ETHERTYPE_TRAIL = 0x1000 - ETHERTYPE_TRANSETHER = 0x6558 - ETHERTYPE_TYMSHARE = 0x802e - ETHERTYPE_UBBST = 0x7005 - ETHERTYPE_UBDEBUG = 0x900 - ETHERTYPE_UBDIAGLOOP = 0x7002 - ETHERTYPE_UBDL = 0x7000 - ETHERTYPE_UBNIU = 0x7001 - ETHERTYPE_UBNMC = 0x7003 - ETHERTYPE_VALID = 0x1600 - ETHERTYPE_VARIAN = 0x80dd - ETHERTYPE_VAXELN = 0x803b - ETHERTYPE_VEECO = 0x8067 - ETHERTYPE_VEXP = 0x805b - ETHERTYPE_VGLAB = 0x8131 - ETHERTYPE_VINES = 0xbad - ETHERTYPE_VINESECHO = 0xbaf - ETHERTYPE_VINESLOOP = 0xbae - ETHERTYPE_VITAL = 0xff00 - ETHERTYPE_VLAN = 0x8100 - ETHERTYPE_VLTLMAN = 0x8080 - ETHERTYPE_VPROD = 0x805c - ETHERTYPE_VURESERVED = 0x8147 - ETHERTYPE_WATERLOO = 0x8130 - ETHERTYPE_WELLFLEET = 0x8103 - ETHERTYPE_X25 = 0x805 - ETHERTYPE_X75 = 0x801 - ETHERTYPE_XNSSM = 0x9001 - ETHERTYPE_XTP = 0x817d - ETHER_ADDR_LEN = 0x6 - ETHER_CRC_LEN = 0x4 - ETHER_CRC_POLY_BE = 0x4c11db6 - ETHER_CRC_POLY_LE = 0xedb88320 - ETHER_HDR_LEN = 0xe - ETHER_MAX_LEN = 0x5ee - ETHER_MAX_LEN_JUMBO = 0x233a - ETHER_MIN_LEN = 0x40 - ETHER_PPPOE_ENCAP_LEN = 0x8 - ETHER_TYPE_LEN = 0x2 - ETHER_VLAN_ENCAP_LEN = 0x4 - EVFILT_AIO = 0x2 - EVFILT_PROC = 0x4 - EVFILT_READ = 0x0 - EVFILT_SIGNAL = 0x5 - EVFILT_SYSCOUNT = 0x7 - EVFILT_TIMER = 0x6 - EVFILT_VNODE = 0x3 - EVFILT_WRITE = 0x1 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x100 - FLUSHO = 0x800000 - F_CLOSEM = 0xa - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0xc - F_FSCTL = -0x80000000 - F_FSDIRMASK = 0x70000000 - F_FSIN = 0x10000000 - F_FSINOUT = 0x30000000 - F_FSOUT = 0x20000000 - F_FSPRIV = 0x8000 - F_FSVOID = 0x40000000 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETNOSIGPIPE = 0xd - F_GETOWN = 0x5 - F_MAXFD = 0xb - F_OK = 0x0 - F_PARAM_MASK = 0xfff - F_PARAM_MAX = 0xfff - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETNOSIGPIPE = 0xe - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFA_ROUTE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x8f52 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ECONET = 0xce - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LINEGROUP = 0xd2 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_PON155 = 0xcf - IFT_PON622 = 0xd0 - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPATM = 0xc5 - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_Q2931 = 0xc9 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SIPSIG = 0xcc - IFT_SIPTG = 0xcb - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xd7 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TELINK = 0xc8 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VIRTUALTG = 0xca - IFT_VOICEDID = 0xd5 - IFT_VOICEEM = 0x64 - IFT_VOICEEMFGD = 0xd3 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFGDEANA = 0xd4 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERCABLE = 0xc6 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IPPROTO_AH = 0x33 - IPPROTO_CARP = 0x70 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPIP = 0x4 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IPV6_ICMP = 0x3a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MOBILE = 0x37 - IPPROTO_NONE = 0x3b - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_VRRP = 0x70 - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_EF = 0x8000 - IP_ERRORMTU = 0x15 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x16 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINFRAGSIZE = 0x45 - IP_MINTTL = 0x18 - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x17 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x6 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SPACEAVAIL = 0x5 - MADV_WILLNEED = 0x3 - MAP_ALIGNMENT_16MB = 0x18000000 - MAP_ALIGNMENT_1TB = 0x28000000 - MAP_ALIGNMENT_256TB = 0x30000000 - MAP_ALIGNMENT_4GB = 0x20000000 - MAP_ALIGNMENT_64KB = 0x10000000 - MAP_ALIGNMENT_64PB = 0x38000000 - MAP_ALIGNMENT_MASK = -0x1000000 - MAP_ALIGNMENT_SHIFT = 0x18 - MAP_ANON = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_INHERIT_COPY = 0x1 - MAP_INHERIT_DEFAULT = 0x1 - MAP_INHERIT_DONATE_COPY = 0x3 - MAP_INHERIT_NONE = 0x2 - MAP_INHERIT_SHARE = 0x0 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_STACK = 0x2000 - MAP_TRYFIXED = 0x400 - MAP_WIRED = 0x800 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_BCAST = 0x100 - MSG_CMSG_CLOEXEC = 0x800 - MSG_CONTROLMBUF = 0x2000000 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOR = 0x8 - MSG_IOVUSRSPACE = 0x4000000 - MSG_LENUSRSPACE = 0x8000000 - MSG_MCAST = 0x200 - MSG_NAMEMBUF = 0x1000000 - MSG_NBIO = 0x1000 - MSG_NOSIGNAL = 0x400 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_USERFLAGS = 0xffffff - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_SYNC = 0x4 - NAME_MAX = 0x1ff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x5 - NET_RT_MAXID = 0x6 - NET_RT_OIFLIST = 0x4 - NET_RT_OOIFLIST = 0x3 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFIOGETBMAP = 0xc004667a - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALT_IO = 0x40000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x400000 - O_CREAT = 0x200 - O_DIRECT = 0x80000 - O_DIRECTORY = 0x200000 - O_DSYNC = 0x10000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_NOSIGPIPE = 0x1000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x20000 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PRI_IOFLUSH = 0x7c - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x9 - RTAX_NETMASK = 0x2 - RTAX_TAG = 0x8 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTA_TAG = 0x100 - RTF_ANNOUNCE = 0x20000 - RTF_BLACKHOLE = 0x1000 - RTF_CLONED = 0x2000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_MASK = 0x80 - RTF_MODIFIED = 0x20 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_REJECT = 0x8 - RTF_SRC = 0x10000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_CHGADDR = 0x15 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x11 - RTM_IFANNOUNCE = 0x10 - RTM_IFINFO = 0x14 - RTM_LLINFO_UPD = 0x13 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_OIFINFO = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_OOIFINFO = 0xe - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_SETGATE = 0x12 - RTM_VERSION = 0x4 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x4 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x8 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80906931 - SIOCADDRT = 0x8030720a - SIOCAIFADDR = 0x8040691a - SIOCALIFADDR = 0x8118691c - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80906932 - SIOCDELRT = 0x8030720b - SIOCDIFADDR = 0x80906919 - SIOCDIFPHYADDR = 0x80906949 - SIOCDLIFADDR = 0x8118691e - SIOCGDRVSPEC = 0xc01c697b - SIOCGETPFSYNC = 0xc09069f8 - SIOCGETSGCNT = 0xc0147534 - SIOCGETVIFCNT = 0xc0147533 - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0906921 - SIOCGIFADDRPREF = 0xc0946920 - SIOCGIFALIAS = 0xc040691b - SIOCGIFBRDADDR = 0xc0906923 - SIOCGIFCAP = 0xc0206976 - SIOCGIFCONF = 0xc0086926 - SIOCGIFDATA = 0xc0946985 - SIOCGIFDLT = 0xc0906977 - SIOCGIFDSTADDR = 0xc0906922 - SIOCGIFFLAGS = 0xc0906911 - SIOCGIFGENERIC = 0xc090693a - SIOCGIFMEDIA = 0xc0286936 - SIOCGIFMETRIC = 0xc0906917 - SIOCGIFMTU = 0xc090697e - SIOCGIFNETMASK = 0xc0906925 - SIOCGIFPDSTADDR = 0xc0906948 - SIOCGIFPSRCADDR = 0xc0906947 - SIOCGLIFADDR = 0xc118691d - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLINKSTR = 0xc01c6987 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGVH = 0xc0906983 - SIOCIFCREATE = 0x8090697a - SIOCIFDESTROY = 0x80906979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCINITIFADDR = 0xc0446984 - SIOCSDRVSPEC = 0x801c697b - SIOCSETPFSYNC = 0x809069f7 - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8090690c - SIOCSIFADDRPREF = 0x8094691f - SIOCSIFBRDADDR = 0x80906913 - SIOCSIFCAP = 0x80206975 - SIOCSIFDSTADDR = 0x8090690e - SIOCSIFFLAGS = 0x80906910 - SIOCSIFGENERIC = 0x80906939 - SIOCSIFMEDIA = 0xc0906935 - SIOCSIFMETRIC = 0x80906918 - SIOCSIFMTU = 0x8090697f - SIOCSIFNETMASK = 0x80906916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLINKSTR = 0x801c6988 - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SIOCSVH = 0xc0906982 - SIOCZIFDATA = 0xc0946986 - SOCK_CLOEXEC = 0x10000000 - SOCK_DGRAM = 0x2 - SOCK_FLAGS_MASK = 0xf0000000 - SOCK_NONBLOCK = 0x20000000 - SOCK_NOSIGPIPE = 0x40000000 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NOHEADER = 0x100a - SO_NOSIGPIPE = 0x800 - SO_OOBINLINE = 0x100 - SO_OVERFLOWED = 0x1009 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x100c - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x100b - SO_TIMESTAMP = 0x2000 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SYSCTL_VERSION = 0x1000000 - SYSCTL_VERS_0 = 0x0 - SYSCTL_VERS_1 = 0x1000000 - SYSCTL_VERS_MASK = 0xff000000 - S_ARCH1 = 0x10000 - S_ARCH2 = 0x20000 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - S_LOGIN_SET = 0x1 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONGCTL = 0x20 - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x3 - TCP_KEEPINIT = 0x7 - TCP_KEEPINTVL = 0x5 - TCP_MAXBURST = 0x4 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x10 - TCP_MINMSS = 0xd8 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x400c7458 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLAG_CDTRCTS = 0x10 - TIOCFLAG_CLOCAL = 0x2 - TIOCFLAG_CRTSCTS = 0x4 - TIOCFLAG_MDMBUF = 0x8 - TIOCFLAG_SOFTCAR = 0x1 - TIOCFLUSH = 0x80047410 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGFLAGS = 0x4004745d - TIOCGLINED = 0x40207442 - TIOCGPGRP = 0x40047477 - TIOCGQSIZE = 0x40047481 - TIOCGRANTPT = 0x20007447 - TIOCGSID = 0x40047463 - TIOCGSIZE = 0x40087468 - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGET = 0x4004746a - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTMGET = 0x40287446 - TIOCPTSNAME = 0x40287448 - TIOCRCVFRAME = 0x80047445 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSFLAGS = 0x8004745c - TIOCSIG = 0x2000745f - TIOCSLINED = 0x80207443 - TIOCSPGRP = 0x80047476 - TIOCSQSIZE = 0x80047480 - TIOCSSIZE = 0x80087467 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x80047465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCUCNTL = 0x80047466 - TIOCXMTFRAME = 0x80047444 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WALL = 0x8 - WALLSIG = 0x8 - WALTSIG = 0x4 - WCLONE = 0x4 - WCOREFLAG = 0x80 - WNOHANG = 0x1 - WNOWAIT = 0x10000 - WNOZOMBIE = 0x20000 - WOPTSCHECKED = 0x40000 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x58) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x57) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x55) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x60) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5e) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x59) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5f) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x5a) - ENOSTR = syscall.Errno(0x5b) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x56) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x60) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x5c) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x20) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large or too small", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol option not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "illegal byte sequence", - 86: "not supported", - 87: "operation Canceled", - 88: "bad or Corrupt message", - 89: "no message available", - 90: "no STREAM resources", - 91: "not a STREAM", - 92: "STREAM ioctl timeout", - 93: "attribute not found", - 94: "multihop attempted", - 95: "link has been severed", - 96: "protocol error", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "power fail/restart", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_arm.go deleted file mode 100644 index ac85ca645..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_arm.go +++ /dev/null @@ -1,1688 +0,0 @@ -// mkerrors.sh -marm -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,netbsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -marm _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_ARP = 0x1c - AF_BLUETOOTH = 0x1f - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_HYLINK = 0xf - AF_IEEE80211 = 0x20 - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x18 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x23 - AF_MPLS = 0x21 - AF_NATM = 0x1b - AF_NS = 0x6 - AF_OROUTE = 0x11 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x22 - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - ARPHRD_ARCNET = 0x7 - ARPHRD_ETHER = 0x1 - ARPHRD_FRELAY = 0xf - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - ARPHRD_STRIP = 0x17 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B460800 = 0x70800 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B921600 = 0xe1000 - B9600 = 0x2580 - BIOCFEEDBACK = 0x8004427d - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc0084277 - BIOCGETIF = 0x4090426b - BIOCGFEEDBACK = 0x4004427c - BIOCGHDRCMPLT = 0x40044274 - BIOCGRTIMEOUT = 0x400c427b - BIOCGSEESENT = 0x40044278 - BIOCGSTATS = 0x4080426f - BIOCGSTATSOLD = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDLT = 0x80044276 - BIOCSETF = 0x80084267 - BIOCSETIF = 0x8090426c - BIOCSFEEDBACK = 0x8004427d - BIOCSHDRCMPLT = 0x80044275 - BIOCSRTIMEOUT = 0x800c427a - BIOCSSEESENT = 0x80044279 - BIOCSTCPF = 0x80084272 - BIOCSUDPF = 0x80084273 - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALIGNMENT32 = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DFLTBUFSIZE = 0x100000 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x1000000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - CTL_QUERY = -0x2 - DIOCBSFLUSH = 0x20006478 - DLT_A429 = 0xb8 - DLT_A653_ICM = 0xb9 - DLT_AIRONET_HEADER = 0x78 - DLT_AOS = 0xde - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_AX25_KISS = 0xca - DLT_BACNET_MS_TP = 0xa5 - DLT_BLUETOOTH_HCI_H4 = 0xbb - DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 - DLT_CAN20B = 0xbe - DLT_CAN_SOCKETCAN = 0xe3 - DLT_CHAOS = 0x5 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_C_HDLC_WITH_DIR = 0xcd - DLT_DECT = 0xdd - DLT_DOCSIS = 0x8f - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF = 0xc5 - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FC_2 = 0xe0 - DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 - DLT_FDDI = 0xa - DLT_FLEXRAY = 0xd2 - DLT_FRELAY = 0x6b - DLT_FRELAY_WITH_DIR = 0xce - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_GSMTAP_ABIS = 0xda - DLT_GSMTAP_UM = 0xd9 - DLT_HDLC = 0x10 - DLT_HHDLC = 0x79 - DLT_HIPPI = 0xf - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IEEE802_15_4 = 0xc3 - DLT_IEEE802_15_4_LINUX = 0xbf - DLT_IEEE802_15_4_NONASK_PHY = 0xd7 - DLT_IEEE802_16_MAC_CPS = 0xbc - DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 - DLT_IPMB = 0xc7 - DLT_IPMB_LINUX = 0xd1 - DLT_IPNET = 0xe2 - DLT_IPV4 = 0xe4 - DLT_IPV6 = 0xe5 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_ISM = 0xc2 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_JUNIPER_ST = 0xc8 - DLT_JUNIPER_VP = 0xb7 - DLT_LAPB_WITH_DIR = 0xcf - DLT_LAPD = 0xcb - DLT_LIN = 0xd4 - DLT_LINUX_EVDEV = 0xd8 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MFR = 0xb6 - DLT_MOST = 0xd3 - DLT_MPLS = 0xdb - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPI = 0xc0 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0xe - DLT_PPP_ETHER = 0x33 - DLT_PPP_PPPD = 0xa6 - DLT_PPP_SERIAL = 0x32 - DLT_PPP_WITH_DIR = 0xcc - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAIF1 = 0xc6 - DLT_RAW = 0xc - DLT_RAWAF_MASK = 0x2240000 - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SITA = 0xc4 - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xd - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - DLT_USB = 0xba - DLT_USB_LINUX = 0xbd - DLT_USB_LINUX_MMAPPED = 0xdc - DLT_WIHART = 0xdf - DLT_X2E_SERIAL = 0xd5 - DLT_X2E_XORAYA = 0xd6 - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - DT_WHT = 0xe - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EMUL_LINUX = 0x1 - EMUL_LINUX32 = 0x5 - EMUL_MAXID = 0x6 - ETHERCAP_JUMBO_MTU = 0x4 - ETHERCAP_VLAN_HWTAGGING = 0x2 - ETHERCAP_VLAN_MTU = 0x1 - ETHERMIN = 0x2e - ETHERMTU = 0x5dc - ETHERMTU_JUMBO = 0x2328 - ETHERTYPE_8023 = 0x4 - ETHERTYPE_AARP = 0x80f3 - ETHERTYPE_ACCTON = 0x8390 - ETHERTYPE_AEONIC = 0x8036 - ETHERTYPE_ALPHA = 0x814a - ETHERTYPE_AMBER = 0x6008 - ETHERTYPE_AMOEBA = 0x8145 - ETHERTYPE_APOLLO = 0x80f7 - ETHERTYPE_APOLLODOMAIN = 0x8019 - ETHERTYPE_APPLETALK = 0x809b - ETHERTYPE_APPLITEK = 0x80c7 - ETHERTYPE_ARGONAUT = 0x803a - ETHERTYPE_ARP = 0x806 - ETHERTYPE_AT = 0x809b - ETHERTYPE_ATALK = 0x809b - ETHERTYPE_ATOMIC = 0x86df - ETHERTYPE_ATT = 0x8069 - ETHERTYPE_ATTSTANFORD = 0x8008 - ETHERTYPE_AUTOPHON = 0x806a - ETHERTYPE_AXIS = 0x8856 - ETHERTYPE_BCLOOP = 0x9003 - ETHERTYPE_BOFL = 0x8102 - ETHERTYPE_CABLETRON = 0x7034 - ETHERTYPE_CHAOS = 0x804 - ETHERTYPE_COMDESIGN = 0x806c - ETHERTYPE_COMPUGRAPHIC = 0x806d - ETHERTYPE_COUNTERPOINT = 0x8062 - ETHERTYPE_CRONUS = 0x8004 - ETHERTYPE_CRONUSVLN = 0x8003 - ETHERTYPE_DCA = 0x1234 - ETHERTYPE_DDE = 0x807b - ETHERTYPE_DEBNI = 0xaaaa - ETHERTYPE_DECAM = 0x8048 - ETHERTYPE_DECCUST = 0x6006 - ETHERTYPE_DECDIAG = 0x6005 - ETHERTYPE_DECDNS = 0x803c - ETHERTYPE_DECDTS = 0x803e - ETHERTYPE_DECEXPER = 0x6000 - ETHERTYPE_DECLAST = 0x8041 - ETHERTYPE_DECLTM = 0x803f - ETHERTYPE_DECMUMPS = 0x6009 - ETHERTYPE_DECNETBIOS = 0x8040 - ETHERTYPE_DELTACON = 0x86de - ETHERTYPE_DIDDLE = 0x4321 - ETHERTYPE_DLOG1 = 0x660 - ETHERTYPE_DLOG2 = 0x661 - ETHERTYPE_DN = 0x6003 - ETHERTYPE_DOGFIGHT = 0x1989 - ETHERTYPE_DSMD = 0x8039 - ETHERTYPE_ECMA = 0x803 - ETHERTYPE_ENCRYPT = 0x803d - ETHERTYPE_ES = 0x805d - ETHERTYPE_EXCELAN = 0x8010 - ETHERTYPE_EXPERDATA = 0x8049 - ETHERTYPE_FLIP = 0x8146 - ETHERTYPE_FLOWCONTROL = 0x8808 - ETHERTYPE_FRARP = 0x808 - ETHERTYPE_GENDYN = 0x8068 - ETHERTYPE_HAYES = 0x8130 - ETHERTYPE_HIPPI_FP = 0x8180 - ETHERTYPE_HITACHI = 0x8820 - ETHERTYPE_HP = 0x8005 - ETHERTYPE_IEEEPUP = 0xa00 - ETHERTYPE_IEEEPUPAT = 0xa01 - ETHERTYPE_IMLBL = 0x4c42 - ETHERTYPE_IMLBLDIAG = 0x424c - ETHERTYPE_IP = 0x800 - ETHERTYPE_IPAS = 0x876c - ETHERTYPE_IPV6 = 0x86dd - ETHERTYPE_IPX = 0x8137 - ETHERTYPE_IPXNEW = 0x8037 - ETHERTYPE_KALPANA = 0x8582 - ETHERTYPE_LANBRIDGE = 0x8038 - ETHERTYPE_LANPROBE = 0x8888 - ETHERTYPE_LAT = 0x6004 - ETHERTYPE_LBACK = 0x9000 - ETHERTYPE_LITTLE = 0x8060 - ETHERTYPE_LOGICRAFT = 0x8148 - ETHERTYPE_LOOPBACK = 0x9000 - ETHERTYPE_MATRA = 0x807a - ETHERTYPE_MAX = 0xffff - ETHERTYPE_MERIT = 0x807c - ETHERTYPE_MICP = 0x873a - ETHERTYPE_MOPDL = 0x6001 - ETHERTYPE_MOPRC = 0x6002 - ETHERTYPE_MOTOROLA = 0x818d - ETHERTYPE_MPLS = 0x8847 - ETHERTYPE_MPLS_MCAST = 0x8848 - ETHERTYPE_MUMPS = 0x813f - ETHERTYPE_NBPCC = 0x3c04 - ETHERTYPE_NBPCLAIM = 0x3c09 - ETHERTYPE_NBPCLREQ = 0x3c05 - ETHERTYPE_NBPCLRSP = 0x3c06 - ETHERTYPE_NBPCREQ = 0x3c02 - ETHERTYPE_NBPCRSP = 0x3c03 - ETHERTYPE_NBPDG = 0x3c07 - ETHERTYPE_NBPDGB = 0x3c08 - ETHERTYPE_NBPDLTE = 0x3c0a - ETHERTYPE_NBPRAR = 0x3c0c - ETHERTYPE_NBPRAS = 0x3c0b - ETHERTYPE_NBPRST = 0x3c0d - ETHERTYPE_NBPSCD = 0x3c01 - ETHERTYPE_NBPVCD = 0x3c00 - ETHERTYPE_NBS = 0x802 - ETHERTYPE_NCD = 0x8149 - ETHERTYPE_NESTAR = 0x8006 - ETHERTYPE_NETBEUI = 0x8191 - ETHERTYPE_NOVELL = 0x8138 - ETHERTYPE_NS = 0x600 - ETHERTYPE_NSAT = 0x601 - ETHERTYPE_NSCOMPAT = 0x807 - ETHERTYPE_NTRAILER = 0x10 - ETHERTYPE_OS9 = 0x7007 - ETHERTYPE_OS9NET = 0x7009 - ETHERTYPE_PACER = 0x80c6 - ETHERTYPE_PAE = 0x888e - ETHERTYPE_PCS = 0x4242 - ETHERTYPE_PLANNING = 0x8044 - ETHERTYPE_PPP = 0x880b - ETHERTYPE_PPPOE = 0x8864 - ETHERTYPE_PPPOEDISC = 0x8863 - ETHERTYPE_PRIMENTS = 0x7031 - ETHERTYPE_PUP = 0x200 - ETHERTYPE_PUPAT = 0x200 - ETHERTYPE_RACAL = 0x7030 - ETHERTYPE_RATIONAL = 0x8150 - ETHERTYPE_RAWFR = 0x6559 - ETHERTYPE_RCL = 0x1995 - ETHERTYPE_RDP = 0x8739 - ETHERTYPE_RETIX = 0x80f2 - ETHERTYPE_REVARP = 0x8035 - ETHERTYPE_SCA = 0x6007 - ETHERTYPE_SECTRA = 0x86db - ETHERTYPE_SECUREDATA = 0x876d - ETHERTYPE_SGITW = 0x817e - ETHERTYPE_SG_BOUNCE = 0x8016 - ETHERTYPE_SG_DIAG = 0x8013 - ETHERTYPE_SG_NETGAMES = 0x8014 - ETHERTYPE_SG_RESV = 0x8015 - ETHERTYPE_SIMNET = 0x5208 - ETHERTYPE_SLOWPROTOCOLS = 0x8809 - ETHERTYPE_SNA = 0x80d5 - ETHERTYPE_SNMP = 0x814c - ETHERTYPE_SONIX = 0xfaf5 - ETHERTYPE_SPIDER = 0x809f - ETHERTYPE_SPRITE = 0x500 - ETHERTYPE_STP = 0x8181 - ETHERTYPE_TALARIS = 0x812b - ETHERTYPE_TALARISMC = 0x852b - ETHERTYPE_TCPCOMP = 0x876b - ETHERTYPE_TCPSM = 0x9002 - ETHERTYPE_TEC = 0x814f - ETHERTYPE_TIGAN = 0x802f - ETHERTYPE_TRAIL = 0x1000 - ETHERTYPE_TRANSETHER = 0x6558 - ETHERTYPE_TYMSHARE = 0x802e - ETHERTYPE_UBBST = 0x7005 - ETHERTYPE_UBDEBUG = 0x900 - ETHERTYPE_UBDIAGLOOP = 0x7002 - ETHERTYPE_UBDL = 0x7000 - ETHERTYPE_UBNIU = 0x7001 - ETHERTYPE_UBNMC = 0x7003 - ETHERTYPE_VALID = 0x1600 - ETHERTYPE_VARIAN = 0x80dd - ETHERTYPE_VAXELN = 0x803b - ETHERTYPE_VEECO = 0x8067 - ETHERTYPE_VEXP = 0x805b - ETHERTYPE_VGLAB = 0x8131 - ETHERTYPE_VINES = 0xbad - ETHERTYPE_VINESECHO = 0xbaf - ETHERTYPE_VINESLOOP = 0xbae - ETHERTYPE_VITAL = 0xff00 - ETHERTYPE_VLAN = 0x8100 - ETHERTYPE_VLTLMAN = 0x8080 - ETHERTYPE_VPROD = 0x805c - ETHERTYPE_VURESERVED = 0x8147 - ETHERTYPE_WATERLOO = 0x8130 - ETHERTYPE_WELLFLEET = 0x8103 - ETHERTYPE_X25 = 0x805 - ETHERTYPE_X75 = 0x801 - ETHERTYPE_XNSSM = 0x9001 - ETHERTYPE_XTP = 0x817d - ETHER_ADDR_LEN = 0x6 - ETHER_CRC_LEN = 0x4 - ETHER_CRC_POLY_BE = 0x4c11db6 - ETHER_CRC_POLY_LE = 0xedb88320 - ETHER_HDR_LEN = 0xe - ETHER_MAX_LEN = 0x5ee - ETHER_MAX_LEN_JUMBO = 0x233a - ETHER_MIN_LEN = 0x40 - ETHER_PPPOE_ENCAP_LEN = 0x8 - ETHER_TYPE_LEN = 0x2 - ETHER_VLAN_ENCAP_LEN = 0x4 - EVFILT_AIO = 0x2 - EVFILT_PROC = 0x4 - EVFILT_READ = 0x0 - EVFILT_SIGNAL = 0x5 - EVFILT_SYSCOUNT = 0x7 - EVFILT_TIMER = 0x6 - EVFILT_VNODE = 0x3 - EVFILT_WRITE = 0x1 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x100 - FLUSHO = 0x800000 - F_CLOSEM = 0xa - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0xc - F_FSCTL = -0x80000000 - F_FSDIRMASK = 0x70000000 - F_FSIN = 0x10000000 - F_FSINOUT = 0x30000000 - F_FSOUT = 0x20000000 - F_FSPRIV = 0x8000 - F_FSVOID = 0x40000000 - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETNOSIGPIPE = 0xd - F_GETOWN = 0x5 - F_MAXFD = 0xb - F_OK = 0x0 - F_PARAM_MASK = 0xfff - F_PARAM_MAX = 0xfff - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETNOSIGPIPE = 0xe - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFA_ROUTE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x8f52 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf8 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ECONET = 0xce - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf2 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LINEGROUP = 0xd2 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_PON155 = 0xcf - IFT_PON622 = 0xd0 - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPATM = 0xc5 - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf1 - IFT_Q2931 = 0xc9 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SIPSIG = 0xcc - IFT_SIPTG = 0xcb - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_STF = 0xd7 - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TELINK = 0xc8 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VIRTUALTG = 0xca - IFT_VOICEDID = 0xd5 - IFT_VOICEEM = 0x64 - IFT_VOICEEMFGD = 0xd3 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFGDEANA = 0xd4 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERCABLE = 0xc6 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IPPROTO_AH = 0x33 - IPPROTO_CARP = 0x70 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPIP = 0x4 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_IPV6_ICMP = 0x3a - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x34 - IPPROTO_MOBILE = 0x37 - IPPROTO_NONE = 0x3b - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPPROTO_VRRP = 0x70 - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPSEC_POLICY = 0x1c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_PATHMTU = 0x2c - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DROP_MEMBERSHIP = 0xd - IP_EF = 0x8000 - IP_ERRORMTU = 0x15 - IP_HDRINCL = 0x2 - IP_IPSEC_POLICY = 0x16 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0x14 - IP_MF = 0x2000 - IP_MINFRAGSIZE = 0x45 - IP_MINTTL = 0x18 - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x14 - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVTTL = 0x17 - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x6 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SPACEAVAIL = 0x5 - MADV_WILLNEED = 0x3 - MAP_ALIGNMENT_16MB = 0x18000000 - MAP_ALIGNMENT_1TB = 0x28000000 - MAP_ALIGNMENT_256TB = 0x30000000 - MAP_ALIGNMENT_4GB = 0x20000000 - MAP_ALIGNMENT_64KB = 0x10000000 - MAP_ALIGNMENT_64PB = 0x38000000 - MAP_ALIGNMENT_MASK = -0x1000000 - MAP_ALIGNMENT_SHIFT = 0x18 - MAP_ANON = 0x1000 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_INHERIT_COPY = 0x1 - MAP_INHERIT_DEFAULT = 0x1 - MAP_INHERIT_DONATE_COPY = 0x3 - MAP_INHERIT_NONE = 0x2 - MAP_INHERIT_SHARE = 0x0 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_STACK = 0x2000 - MAP_TRYFIXED = 0x400 - MAP_WIRED = 0x800 - MSG_BCAST = 0x100 - MSG_CMSG_CLOEXEC = 0x800 - MSG_CONTROLMBUF = 0x2000000 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOR = 0x8 - MSG_IOVUSRSPACE = 0x4000000 - MSG_LENUSRSPACE = 0x8000000 - MSG_MCAST = 0x200 - MSG_NAMEMBUF = 0x1000000 - MSG_NBIO = 0x1000 - MSG_NOSIGNAL = 0x400 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_USERFLAGS = 0xffffff - MSG_WAITALL = 0x40 - NAME_MAX = 0x1ff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x5 - NET_RT_MAXID = 0x6 - NET_RT_OIFLIST = 0x4 - NET_RT_OOIFLIST = 0x3 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - OFIOGETBMAP = 0xc004667a - ONLCR = 0x2 - ONLRET = 0x40 - ONOCR = 0x20 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_ALT_IO = 0x40000 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x400000 - O_CREAT = 0x200 - O_DIRECT = 0x80000 - O_DIRECTORY = 0x200000 - O_DSYNC = 0x10000 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_NOSIGPIPE = 0x1000000 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x20000 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PRI_IOFLUSH = 0x7c - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - RLIMIT_AS = 0xa - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x9 - RTAX_NETMASK = 0x2 - RTAX_TAG = 0x8 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTA_TAG = 0x100 - RTF_ANNOUNCE = 0x20000 - RTF_BLACKHOLE = 0x1000 - RTF_CLONED = 0x2000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_MASK = 0x80 - RTF_MODIFIED = 0x20 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_REJECT = 0x8 - RTF_SRC = 0x10000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_CHGADDR = 0x15 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_GET = 0x4 - RTM_IEEE80211 = 0x11 - RTM_IFANNOUNCE = 0x10 - RTM_IFINFO = 0x14 - RTM_LLINFO_UPD = 0x13 - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_OIFINFO = 0xf - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_OOIFINFO = 0xe - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_SETGATE = 0x12 - RTM_VERSION = 0x4 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_CREDS = 0x4 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x8 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80906931 - SIOCADDRT = 0x8030720a - SIOCAIFADDR = 0x8040691a - SIOCALIFADDR = 0x8118691c - SIOCATMARK = 0x40047307 - SIOCDELMULTI = 0x80906932 - SIOCDELRT = 0x8030720b - SIOCDIFADDR = 0x80906919 - SIOCDIFPHYADDR = 0x80906949 - SIOCDLIFADDR = 0x8118691e - SIOCGDRVSPEC = 0xc01c697b - SIOCGETPFSYNC = 0xc09069f8 - SIOCGETSGCNT = 0xc0147534 - SIOCGETVIFCNT = 0xc0147533 - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0906921 - SIOCGIFADDRPREF = 0xc0946920 - SIOCGIFALIAS = 0xc040691b - SIOCGIFBRDADDR = 0xc0906923 - SIOCGIFCAP = 0xc0206976 - SIOCGIFCONF = 0xc0086926 - SIOCGIFDATA = 0xc0946985 - SIOCGIFDLT = 0xc0906977 - SIOCGIFDSTADDR = 0xc0906922 - SIOCGIFFLAGS = 0xc0906911 - SIOCGIFGENERIC = 0xc090693a - SIOCGIFMEDIA = 0xc0286936 - SIOCGIFMETRIC = 0xc0906917 - SIOCGIFMTU = 0xc090697e - SIOCGIFNETMASK = 0xc0906925 - SIOCGIFPDSTADDR = 0xc0906948 - SIOCGIFPSRCADDR = 0xc0906947 - SIOCGLIFADDR = 0xc118691d - SIOCGLIFPHYADDR = 0xc118694b - SIOCGLINKSTR = 0xc01c6987 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGVH = 0xc0906983 - SIOCIFCREATE = 0x8090697a - SIOCIFDESTROY = 0x80906979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCINITIFADDR = 0xc0446984 - SIOCSDRVSPEC = 0x801c697b - SIOCSETPFSYNC = 0x809069f7 - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8090690c - SIOCSIFADDRPREF = 0x8094691f - SIOCSIFBRDADDR = 0x80906913 - SIOCSIFCAP = 0x80206975 - SIOCSIFDSTADDR = 0x8090690e - SIOCSIFFLAGS = 0x80906910 - SIOCSIFGENERIC = 0x80906939 - SIOCSIFMEDIA = 0xc0906935 - SIOCSIFMETRIC = 0x80906918 - SIOCSIFMTU = 0x8090697f - SIOCSIFNETMASK = 0x80906916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSLIFPHYADDR = 0x8118694a - SIOCSLINKSTR = 0x801c6988 - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SIOCSVH = 0xc0906982 - SIOCZIFDATA = 0xc0946986 - SOCK_CLOEXEC = 0x10000000 - SOCK_DGRAM = 0x2 - SOCK_FLAGS_MASK = 0xf0000000 - SOCK_NONBLOCK = 0x20000000 - SOCK_NOSIGPIPE = 0x40000000 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ACCEPTFILTER = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NOHEADER = 0x100a - SO_NOSIGPIPE = 0x800 - SO_OOBINLINE = 0x100 - SO_OVERFLOWED = 0x1009 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x100c - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x100b - SO_TIMESTAMP = 0x2000 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SYSCTL_VERSION = 0x1000000 - SYSCTL_VERS_0 = 0x0 - SYSCTL_VERS_1 = 0x1000000 - SYSCTL_VERS_MASK = 0xff000000 - S_ARCH1 = 0x10000 - S_ARCH2 = 0x20000 - S_BLKSIZE = 0x200 - S_IEXEC = 0x40 - S_IFBLK = 0x6000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFIFO = 0x1000 - S_IFLNK = 0xa000 - S_IFMT = 0xf000 - S_IFREG = 0x8000 - S_IFSOCK = 0xc000 - S_IFWHT = 0xe000 - S_IREAD = 0x100 - S_IRGRP = 0x20 - S_IROTH = 0x4 - S_IRUSR = 0x100 - S_IRWXG = 0x38 - S_IRWXO = 0x7 - S_IRWXU = 0x1c0 - S_ISGID = 0x400 - S_ISTXT = 0x200 - S_ISUID = 0x800 - S_ISVTX = 0x200 - S_IWGRP = 0x10 - S_IWOTH = 0x2 - S_IWRITE = 0x80 - S_IWUSR = 0x80 - S_IXGRP = 0x8 - S_IXOTH = 0x1 - S_IXUSR = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_CONGCTL = 0x20 - TCP_KEEPCNT = 0x6 - TCP_KEEPIDLE = 0x3 - TCP_KEEPINIT = 0x7 - TCP_KEEPINTVL = 0x5 - TCP_MAXBURST = 0x4 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x10 - TCP_MINMSS = 0xd8 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDCDTIMESTAMP = 0x400c7458 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLAG_CDTRCTS = 0x10 - TIOCFLAG_CLOCAL = 0x2 - TIOCFLAG_CRTSCTS = 0x4 - TIOCFLAG_MDMBUF = 0x8 - TIOCFLAG_SOFTCAR = 0x1 - TIOCFLUSH = 0x80047410 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGFLAGS = 0x4004745d - TIOCGLINED = 0x40207442 - TIOCGPGRP = 0x40047477 - TIOCGQSIZE = 0x40047481 - TIOCGRANTPT = 0x20007447 - TIOCGSID = 0x40047463 - TIOCGSIZE = 0x40087468 - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGET = 0x4004746a - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCPTMGET = 0x48087446 - TIOCPTSNAME = 0x48087448 - TIOCRCVFRAME = 0x80047445 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSFLAGS = 0x8004745c - TIOCSIG = 0x2000745f - TIOCSLINED = 0x80207443 - TIOCSPGRP = 0x80047476 - TIOCSQSIZE = 0x80047480 - TIOCSSIZE = 0x80087467 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x80047465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSWINSZ = 0x80087467 - TIOCUCNTL = 0x80047466 - TIOCXMTFRAME = 0x80047444 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WALL = 0x8 - WALLSIG = 0x8 - WALTSIG = 0x4 - WCLONE = 0x4 - WCOREFLAG = 0x80 - WNOHANG = 0x1 - WNOWAIT = 0x10000 - WNOZOMBIE = 0x20000 - WOPTSCHECKED = 0x40000 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADMSG = syscall.Errno(0x58) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x57) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x52) - EILSEQ = syscall.Errno(0x55) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x60) - ELOOP = syscall.Errno(0x3e) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - EMULTIHOP = syscall.Errno(0x5e) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x5d) - ENOBUFS = syscall.Errno(0x37) - ENODATA = syscall.Errno(0x59) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOLINK = syscall.Errno(0x5f) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x53) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x5a) - ENOSTR = syscall.Errno(0x5b) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x56) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x54) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTO = syscall.Errno(0x60) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIME = syscall.Errno(0x5c) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGPWR = syscall.Signal(0x20) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large or too small", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol option not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "illegal byte sequence", - 86: "not supported", - 87: "operation Canceled", - 88: "bad or Corrupt message", - 89: "no message available", - 90: "no STREAM resources", - 91: "not a STREAM", - 92: "STREAM ioctl timeout", - 93: "attribute not found", - 94: "multihop attempted", - 95: "link has been severed", - 96: "protocol error", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "power fail/restart", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_386.go deleted file mode 100644 index 3322e998d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_386.go +++ /dev/null @@ -1,1584 +0,0 @@ -// mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,openbsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m32 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_BLUETOOTH = 0x20 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_ENCAP = 0x1c - AF_HYLINK = 0xf - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x18 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_KEY = 0x1e - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x24 - AF_MPLS = 0x21 - AF_NATM = 0x1b - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SIP = 0x1d - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - ARPHRD_ETHER = 0x1 - ARPHRD_FRELAY = 0xf - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDIRFILT = 0x4004427c - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc008427b - BIOCGETIF = 0x4020426b - BIOCGFILDROP = 0x40044278 - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044273 - BIOCGRTIMEOUT = 0x400c426e - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x20004276 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDIRFILT = 0x8004427d - BIOCSDLT = 0x8004427a - BIOCSETF = 0x80084267 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x80084277 - BIOCSFILDROP = 0x80044279 - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044272 - BIOCSRTIMEOUT = 0x800c426d - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIRECTION_IN = 0x1 - BPF_DIRECTION_OUT = 0x2 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x200000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0xff - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DIOCOSFPFLUSH = 0x2000444e - DLT_ARCNET = 0x7 - DLT_ATM_RFC1483 = 0xb - DLT_AX25 = 0x3 - DLT_CHAOS = 0x5 - DLT_C_HDLC = 0x68 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0xd - DLT_FDDI = 0xa - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_LOOP = 0xc - DLT_MPLS = 0xdb - DLT_NULL = 0x0 - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_SERIAL = 0x32 - DLT_PRONET = 0x4 - DLT_RAW = 0xe - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EMT_TAGOVF = 0x1 - EMUL_ENABLED = 0x1 - EMUL_NATIVE = 0x2 - ENDRUNDISC = 0x9 - ETHERMIN = 0x2e - ETHERMTU = 0x5dc - ETHERTYPE_8023 = 0x4 - ETHERTYPE_AARP = 0x80f3 - ETHERTYPE_ACCTON = 0x8390 - ETHERTYPE_AEONIC = 0x8036 - ETHERTYPE_ALPHA = 0x814a - ETHERTYPE_AMBER = 0x6008 - ETHERTYPE_AMOEBA = 0x8145 - ETHERTYPE_AOE = 0x88a2 - ETHERTYPE_APOLLO = 0x80f7 - ETHERTYPE_APOLLODOMAIN = 0x8019 - ETHERTYPE_APPLETALK = 0x809b - ETHERTYPE_APPLITEK = 0x80c7 - ETHERTYPE_ARGONAUT = 0x803a - ETHERTYPE_ARP = 0x806 - ETHERTYPE_AT = 0x809b - ETHERTYPE_ATALK = 0x809b - ETHERTYPE_ATOMIC = 0x86df - ETHERTYPE_ATT = 0x8069 - ETHERTYPE_ATTSTANFORD = 0x8008 - ETHERTYPE_AUTOPHON = 0x806a - ETHERTYPE_AXIS = 0x8856 - ETHERTYPE_BCLOOP = 0x9003 - ETHERTYPE_BOFL = 0x8102 - ETHERTYPE_CABLETRON = 0x7034 - ETHERTYPE_CHAOS = 0x804 - ETHERTYPE_COMDESIGN = 0x806c - ETHERTYPE_COMPUGRAPHIC = 0x806d - ETHERTYPE_COUNTERPOINT = 0x8062 - ETHERTYPE_CRONUS = 0x8004 - ETHERTYPE_CRONUSVLN = 0x8003 - ETHERTYPE_DCA = 0x1234 - ETHERTYPE_DDE = 0x807b - ETHERTYPE_DEBNI = 0xaaaa - ETHERTYPE_DECAM = 0x8048 - ETHERTYPE_DECCUST = 0x6006 - ETHERTYPE_DECDIAG = 0x6005 - ETHERTYPE_DECDNS = 0x803c - ETHERTYPE_DECDTS = 0x803e - ETHERTYPE_DECEXPER = 0x6000 - ETHERTYPE_DECLAST = 0x8041 - ETHERTYPE_DECLTM = 0x803f - ETHERTYPE_DECMUMPS = 0x6009 - ETHERTYPE_DECNETBIOS = 0x8040 - ETHERTYPE_DELTACON = 0x86de - ETHERTYPE_DIDDLE = 0x4321 - ETHERTYPE_DLOG1 = 0x660 - ETHERTYPE_DLOG2 = 0x661 - ETHERTYPE_DN = 0x6003 - ETHERTYPE_DOGFIGHT = 0x1989 - ETHERTYPE_DSMD = 0x8039 - ETHERTYPE_ECMA = 0x803 - ETHERTYPE_ENCRYPT = 0x803d - ETHERTYPE_ES = 0x805d - ETHERTYPE_EXCELAN = 0x8010 - ETHERTYPE_EXPERDATA = 0x8049 - ETHERTYPE_FLIP = 0x8146 - ETHERTYPE_FLOWCONTROL = 0x8808 - ETHERTYPE_FRARP = 0x808 - ETHERTYPE_GENDYN = 0x8068 - ETHERTYPE_HAYES = 0x8130 - ETHERTYPE_HIPPI_FP = 0x8180 - ETHERTYPE_HITACHI = 0x8820 - ETHERTYPE_HP = 0x8005 - ETHERTYPE_IEEEPUP = 0xa00 - ETHERTYPE_IEEEPUPAT = 0xa01 - ETHERTYPE_IMLBL = 0x4c42 - ETHERTYPE_IMLBLDIAG = 0x424c - ETHERTYPE_IP = 0x800 - ETHERTYPE_IPAS = 0x876c - ETHERTYPE_IPV6 = 0x86dd - ETHERTYPE_IPX = 0x8137 - ETHERTYPE_IPXNEW = 0x8037 - ETHERTYPE_KALPANA = 0x8582 - ETHERTYPE_LANBRIDGE = 0x8038 - ETHERTYPE_LANPROBE = 0x8888 - ETHERTYPE_LAT = 0x6004 - ETHERTYPE_LBACK = 0x9000 - ETHERTYPE_LITTLE = 0x8060 - ETHERTYPE_LLDP = 0x88cc - ETHERTYPE_LOGICRAFT = 0x8148 - ETHERTYPE_LOOPBACK = 0x9000 - ETHERTYPE_MATRA = 0x807a - ETHERTYPE_MAX = 0xffff - ETHERTYPE_MERIT = 0x807c - ETHERTYPE_MICP = 0x873a - ETHERTYPE_MOPDL = 0x6001 - ETHERTYPE_MOPRC = 0x6002 - ETHERTYPE_MOTOROLA = 0x818d - ETHERTYPE_MPLS = 0x8847 - ETHERTYPE_MPLS_MCAST = 0x8848 - ETHERTYPE_MUMPS = 0x813f - ETHERTYPE_NBPCC = 0x3c04 - ETHERTYPE_NBPCLAIM = 0x3c09 - ETHERTYPE_NBPCLREQ = 0x3c05 - ETHERTYPE_NBPCLRSP = 0x3c06 - ETHERTYPE_NBPCREQ = 0x3c02 - ETHERTYPE_NBPCRSP = 0x3c03 - ETHERTYPE_NBPDG = 0x3c07 - ETHERTYPE_NBPDGB = 0x3c08 - ETHERTYPE_NBPDLTE = 0x3c0a - ETHERTYPE_NBPRAR = 0x3c0c - ETHERTYPE_NBPRAS = 0x3c0b - ETHERTYPE_NBPRST = 0x3c0d - ETHERTYPE_NBPSCD = 0x3c01 - ETHERTYPE_NBPVCD = 0x3c00 - ETHERTYPE_NBS = 0x802 - ETHERTYPE_NCD = 0x8149 - ETHERTYPE_NESTAR = 0x8006 - ETHERTYPE_NETBEUI = 0x8191 - ETHERTYPE_NOVELL = 0x8138 - ETHERTYPE_NS = 0x600 - ETHERTYPE_NSAT = 0x601 - ETHERTYPE_NSCOMPAT = 0x807 - ETHERTYPE_NTRAILER = 0x10 - ETHERTYPE_OS9 = 0x7007 - ETHERTYPE_OS9NET = 0x7009 - ETHERTYPE_PACER = 0x80c6 - ETHERTYPE_PAE = 0x888e - ETHERTYPE_PCS = 0x4242 - ETHERTYPE_PLANNING = 0x8044 - ETHERTYPE_PPP = 0x880b - ETHERTYPE_PPPOE = 0x8864 - ETHERTYPE_PPPOEDISC = 0x8863 - ETHERTYPE_PRIMENTS = 0x7031 - ETHERTYPE_PUP = 0x200 - ETHERTYPE_PUPAT = 0x200 - ETHERTYPE_QINQ = 0x88a8 - ETHERTYPE_RACAL = 0x7030 - ETHERTYPE_RATIONAL = 0x8150 - ETHERTYPE_RAWFR = 0x6559 - ETHERTYPE_RCL = 0x1995 - ETHERTYPE_RDP = 0x8739 - ETHERTYPE_RETIX = 0x80f2 - ETHERTYPE_REVARP = 0x8035 - ETHERTYPE_SCA = 0x6007 - ETHERTYPE_SECTRA = 0x86db - ETHERTYPE_SECUREDATA = 0x876d - ETHERTYPE_SGITW = 0x817e - ETHERTYPE_SG_BOUNCE = 0x8016 - ETHERTYPE_SG_DIAG = 0x8013 - ETHERTYPE_SG_NETGAMES = 0x8014 - ETHERTYPE_SG_RESV = 0x8015 - ETHERTYPE_SIMNET = 0x5208 - ETHERTYPE_SLOW = 0x8809 - ETHERTYPE_SNA = 0x80d5 - ETHERTYPE_SNMP = 0x814c - ETHERTYPE_SONIX = 0xfaf5 - ETHERTYPE_SPIDER = 0x809f - ETHERTYPE_SPRITE = 0x500 - ETHERTYPE_STP = 0x8181 - ETHERTYPE_TALARIS = 0x812b - ETHERTYPE_TALARISMC = 0x852b - ETHERTYPE_TCPCOMP = 0x876b - ETHERTYPE_TCPSM = 0x9002 - ETHERTYPE_TEC = 0x814f - ETHERTYPE_TIGAN = 0x802f - ETHERTYPE_TRAIL = 0x1000 - ETHERTYPE_TRANSETHER = 0x6558 - ETHERTYPE_TYMSHARE = 0x802e - ETHERTYPE_UBBST = 0x7005 - ETHERTYPE_UBDEBUG = 0x900 - ETHERTYPE_UBDIAGLOOP = 0x7002 - ETHERTYPE_UBDL = 0x7000 - ETHERTYPE_UBNIU = 0x7001 - ETHERTYPE_UBNMC = 0x7003 - ETHERTYPE_VALID = 0x1600 - ETHERTYPE_VARIAN = 0x80dd - ETHERTYPE_VAXELN = 0x803b - ETHERTYPE_VEECO = 0x8067 - ETHERTYPE_VEXP = 0x805b - ETHERTYPE_VGLAB = 0x8131 - ETHERTYPE_VINES = 0xbad - ETHERTYPE_VINESECHO = 0xbaf - ETHERTYPE_VINESLOOP = 0xbae - ETHERTYPE_VITAL = 0xff00 - ETHERTYPE_VLAN = 0x8100 - ETHERTYPE_VLTLMAN = 0x8080 - ETHERTYPE_VPROD = 0x805c - ETHERTYPE_VURESERVED = 0x8147 - ETHERTYPE_WATERLOO = 0x8130 - ETHERTYPE_WELLFLEET = 0x8103 - ETHERTYPE_X25 = 0x805 - ETHERTYPE_X75 = 0x801 - ETHERTYPE_XNSSM = 0x9001 - ETHERTYPE_XTP = 0x817d - ETHER_ADDR_LEN = 0x6 - ETHER_ALIGN = 0x2 - ETHER_CRC_LEN = 0x4 - ETHER_CRC_POLY_BE = 0x4c11db6 - ETHER_CRC_POLY_LE = 0xedb88320 - ETHER_HDR_LEN = 0xe - ETHER_MAX_DIX_LEN = 0x600 - ETHER_MAX_LEN = 0x5ee - ETHER_MIN_LEN = 0x40 - ETHER_TYPE_LEN = 0x2 - ETHER_VLAN_ENCAP_LEN = 0x4 - EVFILT_AIO = -0x3 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0x7 - EVFILT_TIMER = -0x7 - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0xa - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETOWN = 0x5 - F_OK = 0x0 - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFA_ROUTE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x8e52 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BLUETOOTH = 0xf8 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf7 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DUMMY = 0xf1 - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ECONET = 0xce - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf3 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LINEGROUP = 0xd2 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFLOW = 0xf9 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_PON155 = 0xcf - IFT_PON622 = 0xd0 - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPATM = 0xc5 - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf2 - IFT_Q2931 = 0xc9 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SIPSIG = 0xcc - IFT_SIPTG = 0xcb - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TELINK = 0xc8 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VIRTUALTG = 0xca - IFT_VOICEDID = 0xd5 - IFT_VOICEEM = 0x64 - IFT_VOICEEMFGD = 0xd3 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFGDEANA = 0xd4 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERCABLE = 0xc6 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IN_RFC3021_HOST = 0x1 - IN_RFC3021_NET = 0xfffffffe - IN_RFC3021_NSHIFT = 0x1f - IPPROTO_AH = 0x33 - IPPROTO_CARP = 0x70 - IPPROTO_DIVERT = 0x102 - IPPROTO_DIVERT_INIT = 0x2 - IPPROTO_DIVERT_RESP = 0x1 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPIP = 0x4 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x103 - IPPROTO_MOBILE = 0x37 - IPPROTO_MPLS = 0x89 - IPPROTO_NONE = 0x3b - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPV6_AUTH_LEVEL = 0x35 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_ESP_NETWORK_LEVEL = 0x37 - IPV6_ESP_TRANS_LEVEL = 0x36 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPCOMP_LEVEL = 0x3c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_OPTIONS = 0x1 - IPV6_PATHMTU = 0x2c - IPV6_PIPEX = 0x3f - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVDSTPORT = 0x40 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTABLE = 0x1021 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_AUTH_LEVEL = 0x14 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DIVERTFL = 0x1022 - IP_DROP_MEMBERSHIP = 0xd - IP_ESP_NETWORK_LEVEL = 0x16 - IP_ESP_TRANS_LEVEL = 0x15 - IP_HDRINCL = 0x2 - IP_IPCOMP_LEVEL = 0x1d - IP_IPSECFLOWINFO = 0x24 - IP_IPSEC_LOCAL_AUTH = 0x1b - IP_IPSEC_LOCAL_CRED = 0x19 - IP_IPSEC_LOCAL_ID = 0x17 - IP_IPSEC_REMOTE_AUTH = 0x1c - IP_IPSEC_REMOTE_CRED = 0x1a - IP_IPSEC_REMOTE_ID = 0x18 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0xfff - IP_MF = 0x2000 - IP_MINTTL = 0x20 - IP_MIN_MEMBERSHIPS = 0xf - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PIPEX = 0x22 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVDSTPORT = 0x21 - IP_RECVIF = 0x1e - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVRTABLE = 0x23 - IP_RECVTTL = 0x1f - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RTABLE = 0x1021 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LCNT_OVERLOAD_FLUSH = 0x6 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x6 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SPACEAVAIL = 0x5 - MADV_WILLNEED = 0x3 - MAP_ANON = 0x1000 - MAP_COPY = 0x4 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_FLAGMASK = 0x1ff7 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_INHERIT_COPY = 0x1 - MAP_INHERIT_DONATE_COPY = 0x3 - MAP_INHERIT_NONE = 0x2 - MAP_INHERIT_SHARE = 0x0 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_TRYFIXED = 0x400 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_BCAST = 0x100 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOR = 0x8 - MSG_MCAST = 0x200 - MSG_NOSIGNAL = 0x400 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x4 - MS_SYNC = 0x2 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_MAXID = 0x6 - NET_RT_STATS = 0x4 - NET_RT_TABLE = 0x5 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EOF = 0x2 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRUNCATE = 0x80 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x80 - ONOCR = 0x40 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x10000 - O_CREAT = 0x200 - O_DIRECTORY = 0x20000 - O_DSYNC = 0x80 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x80 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PF_FLUSH = 0x1 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - PT_MASK = 0x3ff000 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_LABEL = 0xa - RTAX_MAX = 0xb - RTAX_NETMASK = 0x2 - RTAX_SRC = 0x8 - RTAX_SRCMASK = 0x9 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_LABEL = 0x400 - RTA_NETMASK = 0x4 - RTA_SRC = 0x100 - RTA_SRCMASK = 0x200 - RTF_ANNOUNCE = 0x4000 - RTF_BLACKHOLE = 0x1000 - RTF_CLONED = 0x10000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x10f808 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_MASK = 0x80 - RTF_MODIFIED = 0x20 - RTF_MPATH = 0x40000 - RTF_MPLS = 0x100000 - RTF_PERMANENT_ARP = 0x2000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x2000 - RTF_REJECT = 0x8 - RTF_SOURCE = 0x20000 - RTF_STATIC = 0x800 - RTF_TUNNEL = 0x100000 - RTF_UP = 0x1 - RTF_USETRAILERS = 0x8000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DESYNC = 0x10 - RTM_GET = 0x4 - RTM_IFANNOUNCE = 0xf - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MAXSIZE = 0x800 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RT_TABLEID_MAX = 0xff - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCAIFGROUP = 0x80246987 - SIOCALIFADDR = 0x8218691c - SIOCATMARK = 0x40047307 - SIOCBRDGADD = 0x8054693c - SIOCBRDGADDS = 0x80546941 - SIOCBRDGARL = 0x806e694d - SIOCBRDGDADDR = 0x81286947 - SIOCBRDGDEL = 0x8054693d - SIOCBRDGDELS = 0x80546942 - SIOCBRDGFLUSH = 0x80546948 - SIOCBRDGFRL = 0x806e694e - SIOCBRDGGCACHE = 0xc0146941 - SIOCBRDGGFD = 0xc0146952 - SIOCBRDGGHT = 0xc0146951 - SIOCBRDGGIFFLGS = 0xc054693e - SIOCBRDGGMA = 0xc0146953 - SIOCBRDGGPARAM = 0xc03c6958 - SIOCBRDGGPRI = 0xc0146950 - SIOCBRDGGRL = 0xc028694f - SIOCBRDGGSIFS = 0xc054693c - SIOCBRDGGTO = 0xc0146946 - SIOCBRDGIFS = 0xc0546942 - SIOCBRDGRTS = 0xc0186943 - SIOCBRDGSADDR = 0xc1286944 - SIOCBRDGSCACHE = 0x80146940 - SIOCBRDGSFD = 0x80146952 - SIOCBRDGSHT = 0x80146951 - SIOCBRDGSIFCOST = 0x80546955 - SIOCBRDGSIFFLGS = 0x8054693f - SIOCBRDGSIFPRIO = 0x80546954 - SIOCBRDGSMA = 0x80146953 - SIOCBRDGSPRI = 0x80146950 - SIOCBRDGSPROTO = 0x8014695a - SIOCBRDGSTO = 0x80146945 - SIOCBRDGSTXHC = 0x80146959 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFGROUP = 0x80246989 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8218691e - SIOCGETKALIVE = 0xc01869a4 - SIOCGETLABEL = 0x8020699a - SIOCGETPFLOW = 0xc02069fe - SIOCGETPFSYNC = 0xc02069f8 - SIOCGETSGCNT = 0xc0147534 - SIOCGETVIFCNT = 0xc0147533 - SIOCGETVLAN = 0xc0206990 - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCONF = 0xc0086924 - SIOCGIFDATA = 0xc020691b - SIOCGIFDESCR = 0xc0206981 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGATTR = 0xc024698b - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc024698a - SIOCGIFGROUP = 0xc0246988 - SIOCGIFHARDMTU = 0xc02069a5 - SIOCGIFMEDIA = 0xc0286936 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc020697e - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPRIORITY = 0xc020699c - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFRDOMAIN = 0xc02069a0 - SIOCGIFRTLABEL = 0xc0206983 - SIOCGIFTIMESLOT = 0xc0206986 - SIOCGIFXFLAGS = 0xc020699e - SIOCGLIFADDR = 0xc218691d - SIOCGLIFPHYADDR = 0xc218694b - SIOCGLIFPHYRTABLE = 0xc02069a2 - SIOCGLIFPHYTTL = 0xc02069a9 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGSPPPPARAMS = 0xc0206994 - SIOCGVH = 0xc02069f6 - SIOCGVNETID = 0xc02069a7 - SIOCIFCREATE = 0x8020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc00c6978 - SIOCSETKALIVE = 0x801869a3 - SIOCSETLABEL = 0x80206999 - SIOCSETPFLOW = 0x802069fd - SIOCSETPFSYNC = 0x802069f7 - SIOCSETVLAN = 0x8020698f - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFDESCR = 0x80206980 - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGATTR = 0x8024698c - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020691f - SIOCSIFMEDIA = 0xc0206935 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x8020697f - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPRIORITY = 0x8020699b - SIOCSIFRDOMAIN = 0x8020699f - SIOCSIFRTLABEL = 0x80206982 - SIOCSIFTIMESLOT = 0x80206985 - SIOCSIFXFLAGS = 0x8020699d - SIOCSLIFPHYADDR = 0x8218694a - SIOCSLIFPHYRTABLE = 0x802069a1 - SIOCSLIFPHYTTL = 0x802069a8 - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SIOCSSPPPPARAMS = 0x80206993 - SIOCSVH = 0xc02069f5 - SIOCSVNETID = 0x802069a6 - SOCK_DGRAM = 0x2 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BINDANY = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NETPROC = 0x1020 - SO_OOBINLINE = 0x100 - SO_PEERCRED = 0x1022 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_RTABLE = 0x1021 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_SPLICE = 0x1023 - SO_TIMESTAMP = 0x800 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_MAXBURST = 0x4 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x3 - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x4 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOPUSH = 0x10 - TCP_NSTATES = 0xb - TCP_SACK_ENABLE = 0x8 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLAG_CLOCAL = 0x2 - TIOCFLAG_CRTSCTS = 0x4 - TIOCFLAG_MDMBUF = 0x8 - TIOCFLAG_PPS = 0x10 - TIOCFLAG_SOFTCAR = 0x1 - TIOCFLUSH = 0x80047410 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGFLAGS = 0x4004745d - TIOCGPGRP = 0x40047477 - TIOCGSID = 0x40047463 - TIOCGTSTAMP = 0x400c745b - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGET = 0x4004746a - TIOCMODG = 0x4004746a - TIOCMODS = 0x8004746d - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSFLAGS = 0x8004745c - TIOCSIG = 0x8004745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x80047465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSTSTAMP = 0x8008745a - TIOCSWINSZ = 0x80087467 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WALTSIG = 0x4 - WCONTINUED = 0x8 - WCOREFLAG = 0x80 - WNOHANG = 0x1 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x58) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x59) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EIPSEC = syscall.Errno(0x52) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x5b) - ELOOP = syscall.Errno(0x3e) - EMEDIUMTYPE = syscall.Errno(0x56) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x53) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOMEDIUM = syscall.Errno(0x55) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5a) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x5b) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x57) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "IPsec processing failure", - 83: "attribute not found", - 84: "illegal byte sequence", - 85: "no medium found", - 86: "wrong medium type", - 87: "value too large to be stored in data type", - 88: "operation canceled", - 89: "identifier removed", - 90: "no message of desired type", - 91: "not supported", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread AST", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_amd64.go deleted file mode 100644 index 1758ecca9..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_amd64.go +++ /dev/null @@ -1,1583 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,openbsd - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_APPLETALK = 0x10 - AF_BLUETOOTH = 0x20 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_CNT = 0x15 - AF_COIP = 0x14 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_E164 = 0x1a - AF_ECMA = 0x8 - AF_ENCAP = 0x1c - AF_HYLINK = 0xf - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x18 - AF_IPX = 0x17 - AF_ISDN = 0x1a - AF_ISO = 0x7 - AF_KEY = 0x1e - AF_LAT = 0xe - AF_LINK = 0x12 - AF_LOCAL = 0x1 - AF_MAX = 0x24 - AF_MPLS = 0x21 - AF_NATM = 0x1b - AF_NS = 0x6 - AF_OSI = 0x7 - AF_PUP = 0x4 - AF_ROUTE = 0x11 - AF_SIP = 0x1d - AF_SNA = 0xb - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - ARPHRD_ETHER = 0x1 - ARPHRD_FRELAY = 0xf - ARPHRD_IEEE1394 = 0x18 - ARPHRD_IEEE802 = 0x6 - B0 = 0x0 - B110 = 0x6e - B115200 = 0x1c200 - B1200 = 0x4b0 - B134 = 0x86 - B14400 = 0x3840 - B150 = 0x96 - B1800 = 0x708 - B19200 = 0x4b00 - B200 = 0xc8 - B230400 = 0x38400 - B2400 = 0x960 - B28800 = 0x7080 - B300 = 0x12c - B38400 = 0x9600 - B4800 = 0x12c0 - B50 = 0x32 - B57600 = 0xe100 - B600 = 0x258 - B7200 = 0x1c20 - B75 = 0x4b - B76800 = 0x12c00 - B9600 = 0x2580 - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDIRFILT = 0x4004427c - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = 0xc010427b - BIOCGETIF = 0x4020426b - BIOCGFILDROP = 0x40044278 - BIOCGHDRCMPLT = 0x40044274 - BIOCGRSIG = 0x40044273 - BIOCGRTIMEOUT = 0x4010426e - BIOCGSTATS = 0x4008426f - BIOCIMMEDIATE = 0x80044270 - BIOCLOCK = 0x20004276 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = 0xc0044266 - BIOCSDIRFILT = 0x8004427d - BIOCSDLT = 0x8004427a - BIOCSETF = 0x80104267 - BIOCSETIF = 0x8020426c - BIOCSETWF = 0x80104277 - BIOCSFILDROP = 0x80044279 - BIOCSHDRCMPLT = 0x80044275 - BIOCSRSIG = 0x80044272 - BIOCSRTIMEOUT = 0x8010426d - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DIRECTION_IN = 0x1 - BPF_DIRECTION_OUT = 0x2 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x200000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x8000 - CREAD = 0x800 - CS5 = 0x0 - CS6 = 0x100 - CS7 = 0x200 - CS8 = 0x300 - CSIZE = 0x300 - CSTART = 0x11 - CSTATUS = 0xff - CSTOP = 0x13 - CSTOPB = 0x400 - CSUSP = 0x1a - CTL_MAXNAME = 0xc - CTL_NET = 0x4 - DIOCOSFPFLUSH = 0x2000444e - DLT_ARCNET = 0x7 - DLT_ATM_RFC1483 = 0xb - DLT_AX25 = 0x3 - DLT_CHAOS = 0x5 - DLT_C_HDLC = 0x68 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0xd - DLT_FDDI = 0xa - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_LOOP = 0xc - DLT_MPLS = 0xdb - DLT_NULL = 0x0 - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 - DLT_PPP_ETHER = 0x33 - DLT_PPP_SERIAL = 0x32 - DLT_PRONET = 0x4 - DLT_RAW = 0xe - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf - DT_BLK = 0x6 - DT_CHR = 0x2 - DT_DIR = 0x4 - DT_FIFO = 0x1 - DT_LNK = 0xa - DT_REG = 0x8 - DT_SOCK = 0xc - DT_UNKNOWN = 0x0 - ECHO = 0x8 - ECHOCTL = 0x40 - ECHOE = 0x2 - ECHOK = 0x4 - ECHOKE = 0x1 - ECHONL = 0x10 - ECHOPRT = 0x20 - EMT_TAGOVF = 0x1 - EMUL_ENABLED = 0x1 - EMUL_NATIVE = 0x2 - ENDRUNDISC = 0x9 - ETHERMIN = 0x2e - ETHERMTU = 0x5dc - ETHERTYPE_8023 = 0x4 - ETHERTYPE_AARP = 0x80f3 - ETHERTYPE_ACCTON = 0x8390 - ETHERTYPE_AEONIC = 0x8036 - ETHERTYPE_ALPHA = 0x814a - ETHERTYPE_AMBER = 0x6008 - ETHERTYPE_AMOEBA = 0x8145 - ETHERTYPE_AOE = 0x88a2 - ETHERTYPE_APOLLO = 0x80f7 - ETHERTYPE_APOLLODOMAIN = 0x8019 - ETHERTYPE_APPLETALK = 0x809b - ETHERTYPE_APPLITEK = 0x80c7 - ETHERTYPE_ARGONAUT = 0x803a - ETHERTYPE_ARP = 0x806 - ETHERTYPE_AT = 0x809b - ETHERTYPE_ATALK = 0x809b - ETHERTYPE_ATOMIC = 0x86df - ETHERTYPE_ATT = 0x8069 - ETHERTYPE_ATTSTANFORD = 0x8008 - ETHERTYPE_AUTOPHON = 0x806a - ETHERTYPE_AXIS = 0x8856 - ETHERTYPE_BCLOOP = 0x9003 - ETHERTYPE_BOFL = 0x8102 - ETHERTYPE_CABLETRON = 0x7034 - ETHERTYPE_CHAOS = 0x804 - ETHERTYPE_COMDESIGN = 0x806c - ETHERTYPE_COMPUGRAPHIC = 0x806d - ETHERTYPE_COUNTERPOINT = 0x8062 - ETHERTYPE_CRONUS = 0x8004 - ETHERTYPE_CRONUSVLN = 0x8003 - ETHERTYPE_DCA = 0x1234 - ETHERTYPE_DDE = 0x807b - ETHERTYPE_DEBNI = 0xaaaa - ETHERTYPE_DECAM = 0x8048 - ETHERTYPE_DECCUST = 0x6006 - ETHERTYPE_DECDIAG = 0x6005 - ETHERTYPE_DECDNS = 0x803c - ETHERTYPE_DECDTS = 0x803e - ETHERTYPE_DECEXPER = 0x6000 - ETHERTYPE_DECLAST = 0x8041 - ETHERTYPE_DECLTM = 0x803f - ETHERTYPE_DECMUMPS = 0x6009 - ETHERTYPE_DECNETBIOS = 0x8040 - ETHERTYPE_DELTACON = 0x86de - ETHERTYPE_DIDDLE = 0x4321 - ETHERTYPE_DLOG1 = 0x660 - ETHERTYPE_DLOG2 = 0x661 - ETHERTYPE_DN = 0x6003 - ETHERTYPE_DOGFIGHT = 0x1989 - ETHERTYPE_DSMD = 0x8039 - ETHERTYPE_ECMA = 0x803 - ETHERTYPE_ENCRYPT = 0x803d - ETHERTYPE_ES = 0x805d - ETHERTYPE_EXCELAN = 0x8010 - ETHERTYPE_EXPERDATA = 0x8049 - ETHERTYPE_FLIP = 0x8146 - ETHERTYPE_FLOWCONTROL = 0x8808 - ETHERTYPE_FRARP = 0x808 - ETHERTYPE_GENDYN = 0x8068 - ETHERTYPE_HAYES = 0x8130 - ETHERTYPE_HIPPI_FP = 0x8180 - ETHERTYPE_HITACHI = 0x8820 - ETHERTYPE_HP = 0x8005 - ETHERTYPE_IEEEPUP = 0xa00 - ETHERTYPE_IEEEPUPAT = 0xa01 - ETHERTYPE_IMLBL = 0x4c42 - ETHERTYPE_IMLBLDIAG = 0x424c - ETHERTYPE_IP = 0x800 - ETHERTYPE_IPAS = 0x876c - ETHERTYPE_IPV6 = 0x86dd - ETHERTYPE_IPX = 0x8137 - ETHERTYPE_IPXNEW = 0x8037 - ETHERTYPE_KALPANA = 0x8582 - ETHERTYPE_LANBRIDGE = 0x8038 - ETHERTYPE_LANPROBE = 0x8888 - ETHERTYPE_LAT = 0x6004 - ETHERTYPE_LBACK = 0x9000 - ETHERTYPE_LITTLE = 0x8060 - ETHERTYPE_LLDP = 0x88cc - ETHERTYPE_LOGICRAFT = 0x8148 - ETHERTYPE_LOOPBACK = 0x9000 - ETHERTYPE_MATRA = 0x807a - ETHERTYPE_MAX = 0xffff - ETHERTYPE_MERIT = 0x807c - ETHERTYPE_MICP = 0x873a - ETHERTYPE_MOPDL = 0x6001 - ETHERTYPE_MOPRC = 0x6002 - ETHERTYPE_MOTOROLA = 0x818d - ETHERTYPE_MPLS = 0x8847 - ETHERTYPE_MPLS_MCAST = 0x8848 - ETHERTYPE_MUMPS = 0x813f - ETHERTYPE_NBPCC = 0x3c04 - ETHERTYPE_NBPCLAIM = 0x3c09 - ETHERTYPE_NBPCLREQ = 0x3c05 - ETHERTYPE_NBPCLRSP = 0x3c06 - ETHERTYPE_NBPCREQ = 0x3c02 - ETHERTYPE_NBPCRSP = 0x3c03 - ETHERTYPE_NBPDG = 0x3c07 - ETHERTYPE_NBPDGB = 0x3c08 - ETHERTYPE_NBPDLTE = 0x3c0a - ETHERTYPE_NBPRAR = 0x3c0c - ETHERTYPE_NBPRAS = 0x3c0b - ETHERTYPE_NBPRST = 0x3c0d - ETHERTYPE_NBPSCD = 0x3c01 - ETHERTYPE_NBPVCD = 0x3c00 - ETHERTYPE_NBS = 0x802 - ETHERTYPE_NCD = 0x8149 - ETHERTYPE_NESTAR = 0x8006 - ETHERTYPE_NETBEUI = 0x8191 - ETHERTYPE_NOVELL = 0x8138 - ETHERTYPE_NS = 0x600 - ETHERTYPE_NSAT = 0x601 - ETHERTYPE_NSCOMPAT = 0x807 - ETHERTYPE_NTRAILER = 0x10 - ETHERTYPE_OS9 = 0x7007 - ETHERTYPE_OS9NET = 0x7009 - ETHERTYPE_PACER = 0x80c6 - ETHERTYPE_PAE = 0x888e - ETHERTYPE_PCS = 0x4242 - ETHERTYPE_PLANNING = 0x8044 - ETHERTYPE_PPP = 0x880b - ETHERTYPE_PPPOE = 0x8864 - ETHERTYPE_PPPOEDISC = 0x8863 - ETHERTYPE_PRIMENTS = 0x7031 - ETHERTYPE_PUP = 0x200 - ETHERTYPE_PUPAT = 0x200 - ETHERTYPE_QINQ = 0x88a8 - ETHERTYPE_RACAL = 0x7030 - ETHERTYPE_RATIONAL = 0x8150 - ETHERTYPE_RAWFR = 0x6559 - ETHERTYPE_RCL = 0x1995 - ETHERTYPE_RDP = 0x8739 - ETHERTYPE_RETIX = 0x80f2 - ETHERTYPE_REVARP = 0x8035 - ETHERTYPE_SCA = 0x6007 - ETHERTYPE_SECTRA = 0x86db - ETHERTYPE_SECUREDATA = 0x876d - ETHERTYPE_SGITW = 0x817e - ETHERTYPE_SG_BOUNCE = 0x8016 - ETHERTYPE_SG_DIAG = 0x8013 - ETHERTYPE_SG_NETGAMES = 0x8014 - ETHERTYPE_SG_RESV = 0x8015 - ETHERTYPE_SIMNET = 0x5208 - ETHERTYPE_SLOW = 0x8809 - ETHERTYPE_SNA = 0x80d5 - ETHERTYPE_SNMP = 0x814c - ETHERTYPE_SONIX = 0xfaf5 - ETHERTYPE_SPIDER = 0x809f - ETHERTYPE_SPRITE = 0x500 - ETHERTYPE_STP = 0x8181 - ETHERTYPE_TALARIS = 0x812b - ETHERTYPE_TALARISMC = 0x852b - ETHERTYPE_TCPCOMP = 0x876b - ETHERTYPE_TCPSM = 0x9002 - ETHERTYPE_TEC = 0x814f - ETHERTYPE_TIGAN = 0x802f - ETHERTYPE_TRAIL = 0x1000 - ETHERTYPE_TRANSETHER = 0x6558 - ETHERTYPE_TYMSHARE = 0x802e - ETHERTYPE_UBBST = 0x7005 - ETHERTYPE_UBDEBUG = 0x900 - ETHERTYPE_UBDIAGLOOP = 0x7002 - ETHERTYPE_UBDL = 0x7000 - ETHERTYPE_UBNIU = 0x7001 - ETHERTYPE_UBNMC = 0x7003 - ETHERTYPE_VALID = 0x1600 - ETHERTYPE_VARIAN = 0x80dd - ETHERTYPE_VAXELN = 0x803b - ETHERTYPE_VEECO = 0x8067 - ETHERTYPE_VEXP = 0x805b - ETHERTYPE_VGLAB = 0x8131 - ETHERTYPE_VINES = 0xbad - ETHERTYPE_VINESECHO = 0xbaf - ETHERTYPE_VINESLOOP = 0xbae - ETHERTYPE_VITAL = 0xff00 - ETHERTYPE_VLAN = 0x8100 - ETHERTYPE_VLTLMAN = 0x8080 - ETHERTYPE_VPROD = 0x805c - ETHERTYPE_VURESERVED = 0x8147 - ETHERTYPE_WATERLOO = 0x8130 - ETHERTYPE_WELLFLEET = 0x8103 - ETHERTYPE_X25 = 0x805 - ETHERTYPE_X75 = 0x801 - ETHERTYPE_XNSSM = 0x9001 - ETHERTYPE_XTP = 0x817d - ETHER_ADDR_LEN = 0x6 - ETHER_ALIGN = 0x2 - ETHER_CRC_LEN = 0x4 - ETHER_CRC_POLY_BE = 0x4c11db6 - ETHER_CRC_POLY_LE = 0xedb88320 - ETHER_HDR_LEN = 0xe - ETHER_MAX_DIX_LEN = 0x600 - ETHER_MAX_LEN = 0x5ee - ETHER_MIN_LEN = 0x40 - ETHER_TYPE_LEN = 0x2 - ETHER_VLAN_ENCAP_LEN = 0x4 - EVFILT_AIO = -0x3 - EVFILT_PROC = -0x5 - EVFILT_READ = -0x1 - EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0x7 - EVFILT_TIMER = -0x7 - EVFILT_VNODE = -0x4 - EVFILT_WRITE = -0x2 - EV_ADD = 0x1 - EV_CLEAR = 0x20 - EV_DELETE = 0x2 - EV_DISABLE = 0x8 - EV_ENABLE = 0x4 - EV_EOF = 0x8000 - EV_ERROR = 0x4000 - EV_FLAG1 = 0x2000 - EV_ONESHOT = 0x10 - EV_SYSFLAGS = 0xf000 - EXTA = 0x4b00 - EXTB = 0x9600 - EXTPROC = 0x800 - FD_CLOEXEC = 0x1 - FD_SETSIZE = 0x400 - FLUSHO = 0x800000 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0xa - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0x7 - F_GETOWN = 0x5 - F_OK = 0x0 - F_RDLCK = 0x1 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x8 - F_SETLKW = 0x9 - F_SETOWN = 0x6 - F_UNLCK = 0x2 - F_WRLCK = 0x3 - HUPCL = 0x4000 - ICANON = 0x100 - ICMP6_FILTER = 0x12 - ICRNL = 0x100 - IEXTEN = 0x400 - IFAN_ARRIVAL = 0x0 - IFAN_DEPARTURE = 0x1 - IFA_ROUTE = 0x1 - IFF_ALLMULTI = 0x200 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x8e52 - IFF_DEBUG = 0x4 - IFF_LINK0 = 0x1000 - IFF_LINK1 = 0x2000 - IFF_LINK2 = 0x4000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x8000 - IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 - IFF_OACTIVE = 0x400 - IFF_POINTOPOINT = 0x10 - IFF_PROMISC = 0x100 - IFF_RUNNING = 0x40 - IFF_SIMPLEX = 0x800 - IFF_UP = 0x1 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_A12MPPSWITCH = 0x82 - IFT_AAL2 = 0xbb - IFT_AAL5 = 0x31 - IFT_ADSL = 0x5e - IFT_AFLANE8023 = 0x3b - IFT_AFLANE8025 = 0x3c - IFT_ARAP = 0x58 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ASYNC = 0x54 - IFT_ATM = 0x25 - IFT_ATMDXI = 0x69 - IFT_ATMFUNI = 0x6a - IFT_ATMIMA = 0x6b - IFT_ATMLOGICAL = 0x50 - IFT_ATMRADIO = 0xbd - IFT_ATMSUBINTERFACE = 0x86 - IFT_ATMVCIENDPT = 0xc2 - IFT_ATMVIRTUAL = 0x95 - IFT_BGPPOLICYACCOUNTING = 0xa2 - IFT_BLUETOOTH = 0xf8 - IFT_BRIDGE = 0xd1 - IFT_BSC = 0x53 - IFT_CARP = 0xf7 - IFT_CCTEMUL = 0x3d - IFT_CEPT = 0x13 - IFT_CES = 0x85 - IFT_CHANNEL = 0x46 - IFT_CNR = 0x55 - IFT_COFFEE = 0x84 - IFT_COMPOSITELINK = 0x9b - IFT_DCN = 0x8d - IFT_DIGITALPOWERLINE = 0x8a - IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba - IFT_DLSW = 0x4a - IFT_DOCSCABLEDOWNSTREAM = 0x80 - IFT_DOCSCABLEMACLAYER = 0x7f - IFT_DOCSCABLEUPSTREAM = 0x81 - IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd - IFT_DS0 = 0x51 - IFT_DS0BUNDLE = 0x52 - IFT_DS1FDL = 0xaa - IFT_DS3 = 0x1e - IFT_DTM = 0x8c - IFT_DUMMY = 0xf1 - IFT_DVBASILN = 0xac - IFT_DVBASIOUT = 0xad - IFT_DVBRCCDOWNSTREAM = 0x93 - IFT_DVBRCCMACLAYER = 0x92 - IFT_DVBRCCUPSTREAM = 0x94 - IFT_ECONET = 0xce - IFT_ENC = 0xf4 - IFT_EON = 0x19 - IFT_EPLRS = 0x57 - IFT_ESCON = 0x49 - IFT_ETHER = 0x6 - IFT_FAITH = 0xf3 - IFT_FAST = 0x7d - IFT_FASTETHER = 0x3e - IFT_FASTETHERFX = 0x45 - IFT_FDDI = 0xf - IFT_FIBRECHANNEL = 0x38 - IFT_FRAMERELAYINTERCONNECT = 0x3a - IFT_FRAMERELAYMPI = 0x5c - IFT_FRDLCIENDPT = 0xc1 - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_FRF16MFRBUNDLE = 0xa3 - IFT_FRFORWARD = 0x9e - IFT_G703AT2MB = 0x43 - IFT_G703AT64K = 0x42 - IFT_GIF = 0xf0 - IFT_GIGABITETHERNET = 0x75 - IFT_GR303IDT = 0xb2 - IFT_GR303RDT = 0xb1 - IFT_H323GATEKEEPER = 0xa4 - IFT_H323PROXY = 0xa5 - IFT_HDH1822 = 0x3 - IFT_HDLC = 0x76 - IFT_HDSL2 = 0xa8 - IFT_HIPERLAN2 = 0xb7 - IFT_HIPPI = 0x2f - IFT_HIPPIINTERFACE = 0x39 - IFT_HOSTPAD = 0x5a - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IBM370PARCHAN = 0x48 - IFT_IDSL = 0x9a - IFT_IEEE1394 = 0x90 - IFT_IEEE80211 = 0x47 - IFT_IEEE80212 = 0x37 - IFT_IEEE8023ADLAG = 0xa1 - IFT_IFGSN = 0x91 - IFT_IMT = 0xbe - IFT_INFINIBAND = 0xc7 - IFT_INTERLEAVE = 0x7c - IFT_IP = 0x7e - IFT_IPFORWARD = 0x8e - IFT_IPOVERATM = 0x72 - IFT_IPOVERCDLC = 0x6d - IFT_IPOVERCLAW = 0x6e - IFT_IPSWITCH = 0x4e - IFT_ISDN = 0x3f - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISDNS = 0x4b - IFT_ISDNU = 0x4c - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88025CRFPINT = 0x62 - IFT_ISO88025DTR = 0x56 - IFT_ISO88025FIBER = 0x73 - IFT_ISO88026 = 0xa - IFT_ISUP = 0xb3 - IFT_L2VLAN = 0x87 - IFT_L3IPVLAN = 0x88 - IFT_L3IPXVLAN = 0x89 - IFT_LAPB = 0x10 - IFT_LAPD = 0x4d - IFT_LAPF = 0x77 - IFT_LINEGROUP = 0xd2 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MEDIAMAILOVERIP = 0x8b - IFT_MFSIGLINK = 0xa7 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_MPC = 0x71 - IFT_MPLS = 0xa6 - IFT_MPLSTUNNEL = 0x96 - IFT_MSDSL = 0x8f - IFT_MVL = 0xbf - IFT_MYRINET = 0x63 - IFT_NFAS = 0xaf - IFT_NSIP = 0x1b - IFT_OPTICALCHANNEL = 0xc3 - IFT_OPTICALTRANSPORT = 0xc4 - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PFLOG = 0xf5 - IFT_PFLOW = 0xf9 - IFT_PFSYNC = 0xf6 - IFT_PLC = 0xae - IFT_PON155 = 0xcf - IFT_PON622 = 0xd0 - IFT_POS = 0xab - IFT_PPP = 0x17 - IFT_PPPMULTILINKBUNDLE = 0x6c - IFT_PROPATM = 0xc5 - IFT_PROPBWAP2MP = 0xb8 - IFT_PROPCNLS = 0x59 - IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 - IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 - IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PROPWIRELESSP2P = 0x9d - IFT_PTPSERIAL = 0x16 - IFT_PVC = 0xf2 - IFT_Q2931 = 0xc9 - IFT_QLLC = 0x44 - IFT_RADIOMAC = 0xbc - IFT_RADSL = 0x5f - IFT_REACHDSL = 0xc0 - IFT_RFC1483 = 0x9f - IFT_RS232 = 0x21 - IFT_RSRB = 0x4f - IFT_SDLC = 0x11 - IFT_SDSL = 0x60 - IFT_SHDSL = 0xa9 - IFT_SIP = 0x1f - IFT_SIPSIG = 0xcc - IFT_SIPTG = 0xcb - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETOVERHEADCHANNEL = 0xb9 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_SRP = 0x97 - IFT_SS7SIGLINK = 0x9c - IFT_STACKTOSTACK = 0x6f - IFT_STARLAN = 0xb - IFT_T1 = 0x12 - IFT_TDLC = 0x74 - IFT_TELINK = 0xc8 - IFT_TERMPAD = 0x5b - IFT_TR008 = 0xb0 - IFT_TRANSPHDLC = 0x7b - IFT_TUNNEL = 0x83 - IFT_ULTRA = 0x1d - IFT_USB = 0xa0 - IFT_V11 = 0x40 - IFT_V35 = 0x2d - IFT_V36 = 0x41 - IFT_V37 = 0x78 - IFT_VDSL = 0x61 - IFT_VIRTUALIPADDRESS = 0x70 - IFT_VIRTUALTG = 0xca - IFT_VOICEDID = 0xd5 - IFT_VOICEEM = 0x64 - IFT_VOICEEMFGD = 0xd3 - IFT_VOICEENCAP = 0x67 - IFT_VOICEFGDEANA = 0xd4 - IFT_VOICEFXO = 0x65 - IFT_VOICEFXS = 0x66 - IFT_VOICEOVERATM = 0x98 - IFT_VOICEOVERCABLE = 0xc6 - IFT_VOICEOVERFRAMERELAY = 0x99 - IFT_VOICEOVERIP = 0x68 - IFT_X213 = 0x5d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25HUNTGROUP = 0x7a - IFT_X25MLP = 0x79 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_LOOPBACKNET = 0x7f - IN_RFC3021_HOST = 0x1 - IN_RFC3021_NET = 0xfffffffe - IN_RFC3021_NSHIFT = 0x1f - IPPROTO_AH = 0x33 - IPPROTO_CARP = 0x70 - IPPROTO_DIVERT = 0x102 - IPPROTO_DIVERT_INIT = 0x2 - IPPROTO_DIVERT_RESP = 0x1 - IPPROTO_DONE = 0x101 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x62 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_ETHERIP = 0x61 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_GRE = 0x2f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPCOMP = 0x6c - IPPROTO_IPIP = 0x4 - IPPROTO_IPV4 = 0x4 - IPPROTO_IPV6 = 0x29 - IPPROTO_MAX = 0x100 - IPPROTO_MAXID = 0x103 - IPPROTO_MOBILE = 0x37 - IPPROTO_MPLS = 0x89 - IPPROTO_NONE = 0x3b - IPPROTO_PFSYNC = 0xf0 - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_TCP = 0x6 - IPPROTO_TP = 0x1d - IPPROTO_UDP = 0x11 - IPV6_AUTH_LEVEL = 0x35 - IPV6_AUTOFLOWLABEL = 0x3b - IPV6_CHECKSUM = 0x1a - IPV6_DEFAULT_MULTICAST_HOPS = 0x1 - IPV6_DEFAULT_MULTICAST_LOOP = 0x1 - IPV6_DEFHLIM = 0x40 - IPV6_DONTFRAG = 0x3e - IPV6_DSTOPTS = 0x32 - IPV6_ESP_NETWORK_LEVEL = 0x37 - IPV6_ESP_TRANS_LEVEL = 0x36 - IPV6_FAITH = 0x1d - IPV6_FLOWINFO_MASK = 0xffffff0f - IPV6_FLOWLABEL_MASK = 0xffff0f00 - IPV6_FRAGTTL = 0x78 - IPV6_HLIMDEC = 0x1 - IPV6_HOPLIMIT = 0x2f - IPV6_HOPOPTS = 0x31 - IPV6_IPCOMP_LEVEL = 0x3c - IPV6_JOIN_GROUP = 0xc - IPV6_LEAVE_GROUP = 0xd - IPV6_MAXHLIM = 0xff - IPV6_MAXPACKET = 0xffff - IPV6_MMTU = 0x500 - IPV6_MULTICAST_HOPS = 0xa - IPV6_MULTICAST_IF = 0x9 - IPV6_MULTICAST_LOOP = 0xb - IPV6_NEXTHOP = 0x30 - IPV6_OPTIONS = 0x1 - IPV6_PATHMTU = 0x2c - IPV6_PIPEX = 0x3f - IPV6_PKTINFO = 0x2e - IPV6_PORTRANGE = 0xe - IPV6_PORTRANGE_DEFAULT = 0x0 - IPV6_PORTRANGE_HIGH = 0x1 - IPV6_PORTRANGE_LOW = 0x2 - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVDSTPORT = 0x40 - IPV6_RECVHOPLIMIT = 0x25 - IPV6_RECVHOPOPTS = 0x27 - IPV6_RECVPATHMTU = 0x2b - IPV6_RECVPKTINFO = 0x24 - IPV6_RECVRTHDR = 0x26 - IPV6_RECVTCLASS = 0x39 - IPV6_RTABLE = 0x1021 - IPV6_RTHDR = 0x33 - IPV6_RTHDRDSTOPTS = 0x23 - IPV6_RTHDR_LOOSE = 0x0 - IPV6_RTHDR_STRICT = 0x1 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SOCKOPT_RESERVED1 = 0x3 - IPV6_TCLASS = 0x3d - IPV6_UNICAST_HOPS = 0x4 - IPV6_USE_MIN_MTU = 0x2a - IPV6_V6ONLY = 0x1b - IPV6_VERSION = 0x60 - IPV6_VERSION_MASK = 0xf0 - IP_ADD_MEMBERSHIP = 0xc - IP_AUTH_LEVEL = 0x14 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DIVERTFL = 0x1022 - IP_DROP_MEMBERSHIP = 0xd - IP_ESP_NETWORK_LEVEL = 0x16 - IP_ESP_TRANS_LEVEL = 0x15 - IP_HDRINCL = 0x2 - IP_IPCOMP_LEVEL = 0x1d - IP_IPSECFLOWINFO = 0x24 - IP_IPSEC_LOCAL_AUTH = 0x1b - IP_IPSEC_LOCAL_CRED = 0x19 - IP_IPSEC_LOCAL_ID = 0x17 - IP_IPSEC_REMOTE_AUTH = 0x1c - IP_IPSEC_REMOTE_CRED = 0x1a - IP_IPSEC_REMOTE_ID = 0x18 - IP_MAXPACKET = 0xffff - IP_MAX_MEMBERSHIPS = 0xfff - IP_MF = 0x2000 - IP_MINTTL = 0x20 - IP_MIN_MEMBERSHIPS = 0xf - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x9 - IP_MULTICAST_LOOP = 0xb - IP_MULTICAST_TTL = 0xa - IP_OFFMASK = 0x1fff - IP_OPTIONS = 0x1 - IP_PIPEX = 0x22 - IP_PORTRANGE = 0x13 - IP_PORTRANGE_DEFAULT = 0x0 - IP_PORTRANGE_HIGH = 0x1 - IP_PORTRANGE_LOW = 0x2 - IP_RECVDSTADDR = 0x7 - IP_RECVDSTPORT = 0x21 - IP_RECVIF = 0x1e - IP_RECVOPTS = 0x5 - IP_RECVRETOPTS = 0x6 - IP_RECVRTABLE = 0x23 - IP_RECVTTL = 0x1f - IP_RETOPTS = 0x8 - IP_RF = 0x8000 - IP_RTABLE = 0x1021 - IP_TOS = 0x3 - IP_TTL = 0x4 - ISIG = 0x80 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x400 - IXON = 0x200 - LCNT_OVERLOAD_FLUSH = 0x6 - LOCK_EX = 0x2 - LOCK_NB = 0x4 - LOCK_SH = 0x1 - LOCK_UN = 0x8 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x6 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_SPACEAVAIL = 0x5 - MADV_WILLNEED = 0x3 - MAP_ANON = 0x1000 - MAP_COPY = 0x4 - MAP_FILE = 0x0 - MAP_FIXED = 0x10 - MAP_FLAGMASK = 0x1ff7 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 - MAP_INHERIT_COPY = 0x1 - MAP_INHERIT_DONATE_COPY = 0x3 - MAP_INHERIT_NONE = 0x2 - MAP_INHERIT_SHARE = 0x0 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_TRYFIXED = 0x400 - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_BCAST = 0x100 - MSG_CTRUNC = 0x20 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_EOR = 0x8 - MSG_MCAST = 0x200 - MSG_NOSIGNAL = 0x400 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x10 - MSG_WAITALL = 0x40 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x4 - MS_SYNC = 0x2 - NAME_MAX = 0xff - NET_RT_DUMP = 0x1 - NET_RT_FLAGS = 0x2 - NET_RT_IFLIST = 0x3 - NET_RT_MAXID = 0x6 - NET_RT_STATS = 0x4 - NET_RT_TABLE = 0x5 - NOFLSH = 0x80000000 - NOTE_ATTRIB = 0x8 - NOTE_CHILD = 0x4 - NOTE_DELETE = 0x1 - NOTE_EOF = 0x2 - NOTE_EXEC = 0x20000000 - NOTE_EXIT = 0x80000000 - NOTE_EXTEND = 0x4 - NOTE_FORK = 0x40000000 - NOTE_LINK = 0x10 - NOTE_LOWAT = 0x1 - NOTE_PCTRLMASK = 0xf0000000 - NOTE_PDATAMASK = 0xfffff - NOTE_RENAME = 0x20 - NOTE_REVOKE = 0x40 - NOTE_TRACK = 0x1 - NOTE_TRACKERR = 0x2 - NOTE_TRUNCATE = 0x80 - NOTE_WRITE = 0x2 - OCRNL = 0x10 - ONLCR = 0x2 - ONLRET = 0x80 - ONOCR = 0x40 - ONOEOT = 0x8 - OPOST = 0x1 - O_ACCMODE = 0x3 - O_APPEND = 0x8 - O_ASYNC = 0x40 - O_CLOEXEC = 0x10000 - O_CREAT = 0x200 - O_DIRECTORY = 0x20000 - O_DSYNC = 0x80 - O_EXCL = 0x800 - O_EXLOCK = 0x20 - O_FSYNC = 0x80 - O_NDELAY = 0x4 - O_NOCTTY = 0x8000 - O_NOFOLLOW = 0x100 - O_NONBLOCK = 0x4 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x80 - O_SHLOCK = 0x10 - O_SYNC = 0x80 - O_TRUNC = 0x400 - O_WRONLY = 0x1 - PARENB = 0x1000 - PARMRK = 0x8 - PARODD = 0x2000 - PENDIN = 0x20000000 - PF_FLUSH = 0x1 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x8 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = 0x7fffffffffffffff - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_LABEL = 0xa - RTAX_MAX = 0xb - RTAX_NETMASK = 0x2 - RTAX_SRC = 0x8 - RTAX_SRCMASK = 0x9 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_LABEL = 0x400 - RTA_NETMASK = 0x4 - RTA_SRC = 0x100 - RTA_SRCMASK = 0x200 - RTF_ANNOUNCE = 0x4000 - RTF_BLACKHOLE = 0x1000 - RTF_CLONED = 0x10000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x10f808 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_LLINFO = 0x400 - RTF_MASK = 0x80 - RTF_MODIFIED = 0x20 - RTF_MPATH = 0x40000 - RTF_MPLS = 0x100000 - RTF_PERMANENT_ARP = 0x2000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_PROTO3 = 0x2000 - RTF_REJECT = 0x8 - RTF_SOURCE = 0x20000 - RTF_STATIC = 0x800 - RTF_TUNNEL = 0x100000 - RTF_UP = 0x1 - RTF_USETRAILERS = 0x8000 - RTF_XRESOLVE = 0x200 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_DESYNC = 0x10 - RTM_GET = 0x4 - RTM_IFANNOUNCE = 0xf - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MAXSIZE = 0x800 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_RTTUNIT = 0xf4240 - RTM_VERSION = 0x5 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RT_TABLEID_MAX = 0xff - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - RUSAGE_THREAD = 0x1 - SCM_RIGHTS = 0x1 - SCM_TIMESTAMP = 0x4 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIOCADDMULTI = 0x80206931 - SIOCAIFADDR = 0x8040691a - SIOCAIFGROUP = 0x80286987 - SIOCALIFADDR = 0x8218691c - SIOCATMARK = 0x40047307 - SIOCBRDGADD = 0x8058693c - SIOCBRDGADDS = 0x80586941 - SIOCBRDGARL = 0x806e694d - SIOCBRDGDADDR = 0x81286947 - SIOCBRDGDEL = 0x8058693d - SIOCBRDGDELS = 0x80586942 - SIOCBRDGFLUSH = 0x80586948 - SIOCBRDGFRL = 0x806e694e - SIOCBRDGGCACHE = 0xc0146941 - SIOCBRDGGFD = 0xc0146952 - SIOCBRDGGHT = 0xc0146951 - SIOCBRDGGIFFLGS = 0xc058693e - SIOCBRDGGMA = 0xc0146953 - SIOCBRDGGPARAM = 0xc0406958 - SIOCBRDGGPRI = 0xc0146950 - SIOCBRDGGRL = 0xc030694f - SIOCBRDGGSIFS = 0xc058693c - SIOCBRDGGTO = 0xc0146946 - SIOCBRDGIFS = 0xc0586942 - SIOCBRDGRTS = 0xc0206943 - SIOCBRDGSADDR = 0xc1286944 - SIOCBRDGSCACHE = 0x80146940 - SIOCBRDGSFD = 0x80146952 - SIOCBRDGSHT = 0x80146951 - SIOCBRDGSIFCOST = 0x80586955 - SIOCBRDGSIFFLGS = 0x8058693f - SIOCBRDGSIFPRIO = 0x80586954 - SIOCBRDGSMA = 0x80146953 - SIOCBRDGSPRI = 0x80146950 - SIOCBRDGSPROTO = 0x8014695a - SIOCBRDGSTO = 0x80146945 - SIOCBRDGSTXHC = 0x80146959 - SIOCDELMULTI = 0x80206932 - SIOCDIFADDR = 0x80206919 - SIOCDIFGROUP = 0x80286989 - SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8218691e - SIOCGETKALIVE = 0xc01869a4 - SIOCGETLABEL = 0x8020699a - SIOCGETPFLOW = 0xc02069fe - SIOCGETPFSYNC = 0xc02069f8 - SIOCGETSGCNT = 0xc0207534 - SIOCGETVIFCNT = 0xc0287533 - SIOCGETVLAN = 0xc0206990 - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = 0xc0206921 - SIOCGIFASYNCMAP = 0xc020697c - SIOCGIFBRDADDR = 0xc0206923 - SIOCGIFCONF = 0xc0106924 - SIOCGIFDATA = 0xc020691b - SIOCGIFDESCR = 0xc0206981 - SIOCGIFDSTADDR = 0xc0206922 - SIOCGIFFLAGS = 0xc0206911 - SIOCGIFGATTR = 0xc028698b - SIOCGIFGENERIC = 0xc020693a - SIOCGIFGMEMB = 0xc028698a - SIOCGIFGROUP = 0xc0286988 - SIOCGIFHARDMTU = 0xc02069a5 - SIOCGIFMEDIA = 0xc0306936 - SIOCGIFMETRIC = 0xc0206917 - SIOCGIFMTU = 0xc020697e - SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 - SIOCGIFPRIORITY = 0xc020699c - SIOCGIFPSRCADDR = 0xc0206947 - SIOCGIFRDOMAIN = 0xc02069a0 - SIOCGIFRTLABEL = 0xc0206983 - SIOCGIFTIMESLOT = 0xc0206986 - SIOCGIFXFLAGS = 0xc020699e - SIOCGLIFADDR = 0xc218691d - SIOCGLIFPHYADDR = 0xc218694b - SIOCGLIFPHYRTABLE = 0xc02069a2 - SIOCGLIFPHYTTL = 0xc02069a9 - SIOCGLOWAT = 0x40047303 - SIOCGPGRP = 0x40047309 - SIOCGSPPPPARAMS = 0xc0206994 - SIOCGVH = 0xc02069f6 - SIOCGVNETID = 0xc02069a7 - SIOCIFCREATE = 0x8020697a - SIOCIFDESTROY = 0x80206979 - SIOCIFGCLONERS = 0xc0106978 - SIOCSETKALIVE = 0x801869a3 - SIOCSETLABEL = 0x80206999 - SIOCSETPFLOW = 0x802069fd - SIOCSETPFSYNC = 0x802069f7 - SIOCSETVLAN = 0x8020698f - SIOCSHIWAT = 0x80047300 - SIOCSIFADDR = 0x8020690c - SIOCSIFASYNCMAP = 0x8020697d - SIOCSIFBRDADDR = 0x80206913 - SIOCSIFDESCR = 0x80206980 - SIOCSIFDSTADDR = 0x8020690e - SIOCSIFFLAGS = 0x80206910 - SIOCSIFGATTR = 0x8028698c - SIOCSIFGENERIC = 0x80206939 - SIOCSIFLLADDR = 0x8020691f - SIOCSIFMEDIA = 0xc0206935 - SIOCSIFMETRIC = 0x80206918 - SIOCSIFMTU = 0x8020697f - SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 - SIOCSIFPRIORITY = 0x8020699b - SIOCSIFRDOMAIN = 0x8020699f - SIOCSIFRTLABEL = 0x80206982 - SIOCSIFTIMESLOT = 0x80206985 - SIOCSIFXFLAGS = 0x8020699d - SIOCSLIFPHYADDR = 0x8218694a - SIOCSLIFPHYRTABLE = 0x802069a1 - SIOCSLIFPHYTTL = 0x802069a8 - SIOCSLOWAT = 0x80047302 - SIOCSPGRP = 0x80047308 - SIOCSSPPPPARAMS = 0x80206993 - SIOCSVH = 0xc02069f5 - SIOCSVNETID = 0x802069a6 - SOCK_DGRAM = 0x2 - SOCK_RAW = 0x3 - SOCK_RDM = 0x4 - SOCK_SEQPACKET = 0x5 - SOCK_STREAM = 0x1 - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_BINDANY = 0x1000 - SO_BROADCAST = 0x20 - SO_DEBUG = 0x1 - SO_DONTROUTE = 0x10 - SO_ERROR = 0x1007 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_NETPROC = 0x1020 - SO_OOBINLINE = 0x100 - SO_PEERCRED = 0x1022 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVTIMEO = 0x1006 - SO_REUSEADDR = 0x4 - SO_REUSEPORT = 0x200 - SO_RTABLE = 0x1021 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_SPLICE = 0x1023 - SO_TIMESTAMP = 0x800 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - TCIFLUSH = 0x1 - TCIOFLUSH = 0x3 - TCOFLUSH = 0x2 - TCP_MAXBURST = 0x4 - TCP_MAXSEG = 0x2 - TCP_MAXWIN = 0xffff - TCP_MAX_SACK = 0x3 - TCP_MAX_WINSHIFT = 0xe - TCP_MD5SIG = 0x4 - TCP_MSS = 0x200 - TCP_NODELAY = 0x1 - TCP_NOPUSH = 0x10 - TCP_NSTATES = 0xb - TCP_SACK_ENABLE = 0x8 - TCSAFLUSH = 0x2 - TIOCCBRK = 0x2000747a - TIOCCDTR = 0x20007478 - TIOCCONS = 0x80047462 - TIOCDRAIN = 0x2000745e - TIOCEXCL = 0x2000740d - TIOCEXT = 0x80047460 - TIOCFLAG_CLOCAL = 0x2 - TIOCFLAG_CRTSCTS = 0x4 - TIOCFLAG_MDMBUF = 0x8 - TIOCFLAG_PPS = 0x10 - TIOCFLAG_SOFTCAR = 0x1 - TIOCFLUSH = 0x80047410 - TIOCGETA = 0x402c7413 - TIOCGETD = 0x4004741a - TIOCGFLAGS = 0x4004745d - TIOCGPGRP = 0x40047477 - TIOCGSID = 0x40047463 - TIOCGTSTAMP = 0x4010745b - TIOCGWINSZ = 0x40087468 - TIOCMBIC = 0x8004746b - TIOCMBIS = 0x8004746c - TIOCMGET = 0x4004746a - TIOCMODG = 0x4004746a - TIOCMODS = 0x8004746d - TIOCMSET = 0x8004746d - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x20007471 - TIOCNXCL = 0x2000740e - TIOCOUTQ = 0x40047473 - TIOCPKT = 0x80047470 - TIOCPKT_DATA = 0x0 - TIOCPKT_DOSTOP = 0x20 - TIOCPKT_FLUSHREAD = 0x1 - TIOCPKT_FLUSHWRITE = 0x2 - TIOCPKT_IOCTL = 0x40 - TIOCPKT_NOSTOP = 0x10 - TIOCPKT_START = 0x8 - TIOCPKT_STOP = 0x4 - TIOCREMOTE = 0x80047469 - TIOCSBRK = 0x2000747b - TIOCSCTTY = 0x20007461 - TIOCSDTR = 0x20007479 - TIOCSETA = 0x802c7414 - TIOCSETAF = 0x802c7416 - TIOCSETAW = 0x802c7415 - TIOCSETD = 0x8004741b - TIOCSFLAGS = 0x8004745c - TIOCSIG = 0x8004745f - TIOCSPGRP = 0x80047476 - TIOCSTART = 0x2000746e - TIOCSTAT = 0x80047465 - TIOCSTI = 0x80017472 - TIOCSTOP = 0x2000746f - TIOCSTSTAMP = 0x8008745a - TIOCSWINSZ = 0x80087467 - TIOCUCNTL = 0x80047466 - TOSTOP = 0x400000 - VDISCARD = 0xf - VDSUSP = 0xb - VEOF = 0x0 - VEOL = 0x1 - VEOL2 = 0x2 - VERASE = 0x3 - VINTR = 0x8 - VKILL = 0x5 - VLNEXT = 0xe - VMIN = 0x10 - VQUIT = 0x9 - VREPRINT = 0x6 - VSTART = 0xc - VSTATUS = 0x12 - VSTOP = 0xd - VSUSP = 0xa - VTIME = 0x11 - VWERASE = 0x4 - WALTSIG = 0x4 - WCONTINUED = 0x8 - WCOREFLAG = 0x80 - WNOHANG = 0x1 - WSTOPPED = 0x7f - WUNTRACED = 0x2 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x30) - EADDRNOTAVAIL = syscall.Errno(0x31) - EAFNOSUPPORT = syscall.Errno(0x2f) - EAGAIN = syscall.Errno(0x23) - EALREADY = syscall.Errno(0x25) - EAUTH = syscall.Errno(0x50) - EBADF = syscall.Errno(0x9) - EBADRPC = syscall.Errno(0x48) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x58) - ECHILD = syscall.Errno(0xa) - ECONNABORTED = syscall.Errno(0x35) - ECONNREFUSED = syscall.Errno(0x3d) - ECONNRESET = syscall.Errno(0x36) - EDEADLK = syscall.Errno(0xb) - EDESTADDRREQ = syscall.Errno(0x27) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x45) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EFTYPE = syscall.Errno(0x4f) - EHOSTDOWN = syscall.Errno(0x40) - EHOSTUNREACH = syscall.Errno(0x41) - EIDRM = syscall.Errno(0x59) - EILSEQ = syscall.Errno(0x54) - EINPROGRESS = syscall.Errno(0x24) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EIPSEC = syscall.Errno(0x52) - EISCONN = syscall.Errno(0x38) - EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x5b) - ELOOP = syscall.Errno(0x3e) - EMEDIUMTYPE = syscall.Errno(0x56) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x28) - ENAMETOOLONG = syscall.Errno(0x3f) - ENEEDAUTH = syscall.Errno(0x51) - ENETDOWN = syscall.Errno(0x32) - ENETRESET = syscall.Errno(0x34) - ENETUNREACH = syscall.Errno(0x33) - ENFILE = syscall.Errno(0x17) - ENOATTR = syscall.Errno(0x53) - ENOBUFS = syscall.Errno(0x37) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x4d) - ENOMEDIUM = syscall.Errno(0x55) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x5a) - ENOPROTOOPT = syscall.Errno(0x2a) - ENOSPC = syscall.Errno(0x1c) - ENOSYS = syscall.Errno(0x4e) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x39) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x42) - ENOTSOCK = syscall.Errno(0x26) - ENOTSUP = syscall.Errno(0x5b) - ENOTTY = syscall.Errno(0x19) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x2d) - EOVERFLOW = syscall.Errno(0x57) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x2e) - EPIPE = syscall.Errno(0x20) - EPROCLIM = syscall.Errno(0x43) - EPROCUNAVAIL = syscall.Errno(0x4c) - EPROGMISMATCH = syscall.Errno(0x4b) - EPROGUNAVAIL = syscall.Errno(0x4a) - EPROTONOSUPPORT = syscall.Errno(0x2b) - EPROTOTYPE = syscall.Errno(0x29) - ERANGE = syscall.Errno(0x22) - EREMOTE = syscall.Errno(0x47) - EROFS = syscall.Errno(0x1e) - ERPCMISMATCH = syscall.Errno(0x49) - ESHUTDOWN = syscall.Errno(0x3a) - ESOCKTNOSUPPORT = syscall.Errno(0x2c) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESTALE = syscall.Errno(0x46) - ETIMEDOUT = syscall.Errno(0x3c) - ETOOMANYREFS = syscall.Errno(0x3b) - ETXTBSY = syscall.Errno(0x1a) - EUSERS = syscall.Errno(0x44) - EWOULDBLOCK = syscall.Errno(0x23) - EXDEV = syscall.Errno(0x12) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCHLD = syscall.Signal(0x14) - SIGCONT = syscall.Signal(0x13) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x1d) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x17) - SIGIOT = syscall.Signal(0x6) - SIGKILL = syscall.Signal(0x9) - SIGPIPE = syscall.Signal(0xd) - SIGPROF = syscall.Signal(0x1b) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x11) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHR = syscall.Signal(0x20) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x12) - SIGTTIN = syscall.Signal(0x15) - SIGTTOU = syscall.Signal(0x16) - SIGURG = syscall.Signal(0x10) - SIGUSR1 = syscall.Signal(0x1e) - SIGUSR2 = syscall.Signal(0x1f) - SIGVTALRM = syscall.Signal(0x1a) - SIGWINCH = syscall.Signal(0x1c) - SIGXCPU = syscall.Signal(0x18) - SIGXFSZ = syscall.Signal(0x19) -) - -// Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "IPsec processing failure", - 83: "attribute not found", - 84: "illegal byte sequence", - 85: "no medium found", - 86: "wrong medium type", - 87: "value too large to be stored in data type", - 88: "operation canceled", - 89: "identifier removed", - 90: "no message of desired type", - 91: "not supported", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread AST", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go deleted file mode 100644 index a08922b98..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go +++ /dev/null @@ -1,1436 +0,0 @@ -// mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,solaris - -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -m64 _const.go - -package unix - -import "syscall" - -const ( - AF_802 = 0x12 - AF_APPLETALK = 0x10 - AF_CCITT = 0xa - AF_CHAOS = 0x5 - AF_DATAKIT = 0x9 - AF_DECnet = 0xc - AF_DLI = 0xd - AF_ECMA = 0x8 - AF_FILE = 0x1 - AF_GOSIP = 0x16 - AF_HYLINK = 0xf - AF_IMPLINK = 0x3 - AF_INET = 0x2 - AF_INET6 = 0x1a - AF_INET_OFFLOAD = 0x1e - AF_IPX = 0x17 - AF_KEY = 0x1b - AF_LAT = 0xe - AF_LINK = 0x19 - AF_LOCAL = 0x1 - AF_MAX = 0x20 - AF_NBS = 0x7 - AF_NCA = 0x1c - AF_NIT = 0x11 - AF_NS = 0x6 - AF_OSI = 0x13 - AF_OSINET = 0x15 - AF_PACKET = 0x20 - AF_POLICY = 0x1d - AF_PUP = 0x4 - AF_ROUTE = 0x18 - AF_SNA = 0xb - AF_TRILL = 0x1f - AF_UNIX = 0x1 - AF_UNSPEC = 0x0 - AF_X25 = 0x14 - ARPHRD_ARCNET = 0x7 - ARPHRD_ATM = 0x10 - ARPHRD_AX25 = 0x3 - ARPHRD_CHAOS = 0x5 - ARPHRD_EETHER = 0x2 - ARPHRD_ETHER = 0x1 - ARPHRD_FC = 0x12 - ARPHRD_FRAME = 0xf - ARPHRD_HDLC = 0x11 - ARPHRD_IB = 0x20 - ARPHRD_IEEE802 = 0x6 - ARPHRD_IPATM = 0x13 - ARPHRD_METRICOM = 0x17 - ARPHRD_TUNNEL = 0x1f - B0 = 0x0 - B110 = 0x3 - B115200 = 0x12 - B1200 = 0x9 - B134 = 0x4 - B150 = 0x5 - B153600 = 0x13 - B1800 = 0xa - B19200 = 0xe - B200 = 0x6 - B230400 = 0x14 - B2400 = 0xb - B300 = 0x7 - B307200 = 0x15 - B38400 = 0xf - B460800 = 0x16 - B4800 = 0xc - B50 = 0x1 - B57600 = 0x10 - B600 = 0x8 - B75 = 0x2 - B76800 = 0x11 - B921600 = 0x17 - B9600 = 0xd - BIOCFLUSH = 0x20004268 - BIOCGBLEN = 0x40044266 - BIOCGDLT = 0x4004426a - BIOCGDLTLIST = -0x3fefbd89 - BIOCGDLTLIST32 = -0x3ff7bd89 - BIOCGETIF = 0x4020426b - BIOCGETLIF = 0x4078426b - BIOCGHDRCMPLT = 0x40044274 - BIOCGRTIMEOUT = 0x4010427b - BIOCGRTIMEOUT32 = 0x4008427b - BIOCGSEESENT = 0x40044278 - BIOCGSTATS = 0x4080426f - BIOCGSTATSOLD = 0x4008426f - BIOCIMMEDIATE = -0x7ffbbd90 - BIOCPROMISC = 0x20004269 - BIOCSBLEN = -0x3ffbbd9a - BIOCSDLT = -0x7ffbbd8a - BIOCSETF = -0x7fefbd99 - BIOCSETF32 = -0x7ff7bd99 - BIOCSETIF = -0x7fdfbd94 - BIOCSETLIF = -0x7f87bd94 - BIOCSHDRCMPLT = -0x7ffbbd8b - BIOCSRTIMEOUT = -0x7fefbd86 - BIOCSRTIMEOUT32 = -0x7ff7bd86 - BIOCSSEESENT = -0x7ffbbd87 - BIOCSTCPF = -0x7fefbd8e - BIOCSUDPF = -0x7fefbd8d - BIOCVERSION = 0x40044271 - BPF_A = 0x10 - BPF_ABS = 0x20 - BPF_ADD = 0x0 - BPF_ALIGNMENT = 0x4 - BPF_ALU = 0x4 - BPF_AND = 0x50 - BPF_B = 0x10 - BPF_DFLTBUFSIZE = 0x100000 - BPF_DIV = 0x30 - BPF_H = 0x8 - BPF_IMM = 0x0 - BPF_IND = 0x40 - BPF_JA = 0x0 - BPF_JEQ = 0x10 - BPF_JGE = 0x30 - BPF_JGT = 0x20 - BPF_JMP = 0x5 - BPF_JSET = 0x40 - BPF_K = 0x0 - BPF_LD = 0x0 - BPF_LDX = 0x1 - BPF_LEN = 0x80 - BPF_LSH = 0x60 - BPF_MAJOR_VERSION = 0x1 - BPF_MAXBUFSIZE = 0x1000000 - BPF_MAXINSNS = 0x200 - BPF_MEM = 0x60 - BPF_MEMWORDS = 0x10 - BPF_MINBUFSIZE = 0x20 - BPF_MINOR_VERSION = 0x1 - BPF_MISC = 0x7 - BPF_MSH = 0xa0 - BPF_MUL = 0x20 - BPF_NEG = 0x80 - BPF_OR = 0x40 - BPF_RELEASE = 0x30bb6 - BPF_RET = 0x6 - BPF_RSH = 0x70 - BPF_ST = 0x2 - BPF_STX = 0x3 - BPF_SUB = 0x10 - BPF_TAX = 0x0 - BPF_TXA = 0x80 - BPF_W = 0x0 - BPF_X = 0x8 - BRKINT = 0x2 - CFLUSH = 0xf - CLOCAL = 0x800 - CLOCK_HIGHRES = 0x4 - CLOCK_LEVEL = 0xa - CLOCK_MONOTONIC = 0x4 - CLOCK_PROCESS_CPUTIME_ID = 0x5 - CLOCK_PROF = 0x2 - CLOCK_REALTIME = 0x3 - CLOCK_THREAD_CPUTIME_ID = 0x2 - CLOCK_VIRTUAL = 0x1 - CREAD = 0x80 - CS5 = 0x0 - CS6 = 0x10 - CS7 = 0x20 - CS8 = 0x30 - CSIZE = 0x30 - CSTART = 0x11 - CSTATUS = 0x14 - CSTOP = 0x13 - CSTOPB = 0x40 - CSUSP = 0x1a - CSWTCH = 0x1a - DLT_AIRONET_HEADER = 0x78 - DLT_APPLE_IP_OVER_IEEE1394 = 0x8a - DLT_ARCNET = 0x7 - DLT_ARCNET_LINUX = 0x81 - DLT_ATM_CLIP = 0x13 - DLT_ATM_RFC1483 = 0xb - DLT_AURORA = 0x7e - DLT_AX25 = 0x3 - DLT_BACNET_MS_TP = 0xa5 - DLT_CHAOS = 0x5 - DLT_CISCO_IOS = 0x76 - DLT_C_HDLC = 0x68 - DLT_DOCSIS = 0x8f - DLT_ECONET = 0x73 - DLT_EN10MB = 0x1 - DLT_EN3MB = 0x2 - DLT_ENC = 0x6d - DLT_ERF_ETH = 0xaf - DLT_ERF_POS = 0xb0 - DLT_FDDI = 0xa - DLT_FRELAY = 0x6b - DLT_GCOM_SERIAL = 0xad - DLT_GCOM_T1E1 = 0xac - DLT_GPF_F = 0xab - DLT_GPF_T = 0xaa - DLT_GPRS_LLC = 0xa9 - DLT_HDLC = 0x10 - DLT_HHDLC = 0x79 - DLT_HIPPI = 0xf - DLT_IBM_SN = 0x92 - DLT_IBM_SP = 0x91 - DLT_IEEE802 = 0x6 - DLT_IEEE802_11 = 0x69 - DLT_IEEE802_11_RADIO = 0x7f - DLT_IEEE802_11_RADIO_AVS = 0xa3 - DLT_IPNET = 0xe2 - DLT_IPOIB = 0xa2 - DLT_IP_OVER_FC = 0x7a - DLT_JUNIPER_ATM1 = 0x89 - DLT_JUNIPER_ATM2 = 0x87 - DLT_JUNIPER_CHDLC = 0xb5 - DLT_JUNIPER_ES = 0x84 - DLT_JUNIPER_ETHER = 0xb2 - DLT_JUNIPER_FRELAY = 0xb4 - DLT_JUNIPER_GGSN = 0x85 - DLT_JUNIPER_MFR = 0x86 - DLT_JUNIPER_MLFR = 0x83 - DLT_JUNIPER_MLPPP = 0x82 - DLT_JUNIPER_MONITOR = 0xa4 - DLT_JUNIPER_PIC_PEER = 0xae - DLT_JUNIPER_PPP = 0xb3 - DLT_JUNIPER_PPPOE = 0xa7 - DLT_JUNIPER_PPPOE_ATM = 0xa8 - DLT_JUNIPER_SERVICES = 0x88 - DLT_LINUX_IRDA = 0x90 - DLT_LINUX_LAPD = 0xb1 - DLT_LINUX_SLL = 0x71 - DLT_LOOP = 0x6c - DLT_LTALK = 0x72 - DLT_MTP2 = 0x8c - DLT_MTP2_WITH_PHDR = 0x8b - DLT_MTP3 = 0x8d - DLT_NULL = 0x0 - DLT_PCI_EXP = 0x7d - DLT_PFLOG = 0x75 - DLT_PFSYNC = 0x12 - DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0xe - DLT_PPP_PPPD = 0xa6 - DLT_PRISM_HEADER = 0x77 - DLT_PRONET = 0x4 - DLT_RAW = 0xc - DLT_RAWAF_MASK = 0x2240000 - DLT_RIO = 0x7c - DLT_SCCP = 0x8e - DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xd - DLT_SUNATM = 0x7b - DLT_SYMANTEC_FIREWALL = 0x63 - DLT_TZSP = 0x80 - ECHO = 0x8 - ECHOCTL = 0x200 - ECHOE = 0x10 - ECHOK = 0x20 - ECHOKE = 0x800 - ECHONL = 0x40 - ECHOPRT = 0x400 - EMPTY_SET = 0x0 - EMT_CPCOVF = 0x1 - EQUALITY_CHECK = 0x0 - EXTA = 0xe - EXTB = 0xf - FD_CLOEXEC = 0x1 - FD_NFDBITS = 0x40 - FD_SETSIZE = 0x10000 - FLUSHALL = 0x1 - FLUSHDATA = 0x0 - FLUSHO = 0x2000 - F_ALLOCSP = 0xa - F_ALLOCSP64 = 0xa - F_BADFD = 0x2e - F_BLKSIZE = 0x13 - F_BLOCKS = 0x12 - F_CHKFL = 0x8 - F_COMPAT = 0x8 - F_DUP2FD = 0x9 - F_DUP2FD_CLOEXEC = 0x24 - F_DUPFD = 0x0 - F_DUPFD_CLOEXEC = 0x25 - F_FREESP = 0xb - F_FREESP64 = 0xb - F_GETFD = 0x1 - F_GETFL = 0x3 - F_GETLK = 0xe - F_GETLK64 = 0xe - F_GETOWN = 0x17 - F_GETXFL = 0x2d - F_HASREMOTELOCKS = 0x1a - F_ISSTREAM = 0xd - F_MANDDNY = 0x10 - F_MDACC = 0x20 - F_NODNY = 0x0 - F_NPRIV = 0x10 - F_PRIV = 0xf - F_QUOTACTL = 0x11 - F_RDACC = 0x1 - F_RDDNY = 0x1 - F_RDLCK = 0x1 - F_REVOKE = 0x19 - F_RMACC = 0x4 - F_RMDNY = 0x4 - F_RWACC = 0x3 - F_RWDNY = 0x3 - F_SETFD = 0x2 - F_SETFL = 0x4 - F_SETLK = 0x6 - F_SETLK64 = 0x6 - F_SETLK64_NBMAND = 0x2a - F_SETLKW = 0x7 - F_SETLKW64 = 0x7 - F_SETLK_NBMAND = 0x2a - F_SETOWN = 0x18 - F_SHARE = 0x28 - F_SHARE_NBMAND = 0x2b - F_UNLCK = 0x3 - F_UNLKSYS = 0x4 - F_UNSHARE = 0x29 - F_WRACC = 0x2 - F_WRDNY = 0x2 - F_WRLCK = 0x2 - HUPCL = 0x400 - ICANON = 0x2 - ICRNL = 0x100 - IEXTEN = 0x8000 - IFF_ADDRCONF = 0x80000 - IFF_ALLMULTI = 0x200 - IFF_ANYCAST = 0x400000 - IFF_BROADCAST = 0x2 - IFF_CANTCHANGE = 0x7f203003b5a - IFF_COS_ENABLED = 0x200000000 - IFF_DEBUG = 0x4 - IFF_DEPRECATED = 0x40000 - IFF_DHCPRUNNING = 0x4000 - IFF_DUPLICATE = 0x4000000000 - IFF_FAILED = 0x10000000 - IFF_FIXEDMTU = 0x1000000000 - IFF_INACTIVE = 0x40000000 - IFF_INTELLIGENT = 0x400 - IFF_IPMP = 0x8000000000 - IFF_IPMP_CANTCHANGE = 0x10000000 - IFF_IPMP_INVALID = 0x1ec200080 - IFF_IPV4 = 0x1000000 - IFF_IPV6 = 0x2000000 - IFF_L3PROTECT = 0x40000000000 - IFF_LOOPBACK = 0x8 - IFF_MULTICAST = 0x800 - IFF_MULTI_BCAST = 0x1000 - IFF_NOACCEPT = 0x4000000 - IFF_NOARP = 0x80 - IFF_NOFAILOVER = 0x8000000 - IFF_NOLINKLOCAL = 0x20000000000 - IFF_NOLOCAL = 0x20000 - IFF_NONUD = 0x200000 - IFF_NORTEXCH = 0x800000 - IFF_NOTRAILERS = 0x20 - IFF_NOXMIT = 0x10000 - IFF_OFFLINE = 0x80000000 - IFF_POINTOPOINT = 0x10 - IFF_PREFERRED = 0x400000000 - IFF_PRIVATE = 0x8000 - IFF_PROMISC = 0x100 - IFF_ROUTER = 0x100000 - IFF_RUNNING = 0x40 - IFF_STANDBY = 0x20000000 - IFF_TEMPORARY = 0x800000000 - IFF_UNNUMBERED = 0x2000 - IFF_UP = 0x1 - IFF_VIRTUAL = 0x2000000000 - IFF_VRRP = 0x10000000000 - IFF_XRESOLV = 0x100000000 - IFNAMSIZ = 0x10 - IFT_1822 = 0x2 - IFT_6TO4 = 0xca - IFT_AAL5 = 0x31 - IFT_ARCNET = 0x23 - IFT_ARCNETPLUS = 0x24 - IFT_ATM = 0x25 - IFT_CEPT = 0x13 - IFT_DS3 = 0x1e - IFT_EON = 0x19 - IFT_ETHER = 0x6 - IFT_FDDI = 0xf - IFT_FRELAY = 0x20 - IFT_FRELAYDCE = 0x2c - IFT_HDH1822 = 0x3 - IFT_HIPPI = 0x2f - IFT_HSSI = 0x2e - IFT_HY = 0xe - IFT_IB = 0xc7 - IFT_IPV4 = 0xc8 - IFT_IPV6 = 0xc9 - IFT_ISDNBASIC = 0x14 - IFT_ISDNPRIMARY = 0x15 - IFT_ISO88022LLC = 0x29 - IFT_ISO88023 = 0x7 - IFT_ISO88024 = 0x8 - IFT_ISO88025 = 0x9 - IFT_ISO88026 = 0xa - IFT_LAPB = 0x10 - IFT_LOCALTALK = 0x2a - IFT_LOOP = 0x18 - IFT_MIOX25 = 0x26 - IFT_MODEM = 0x30 - IFT_NSIP = 0x1b - IFT_OTHER = 0x1 - IFT_P10 = 0xc - IFT_P80 = 0xd - IFT_PARA = 0x22 - IFT_PPP = 0x17 - IFT_PROPMUX = 0x36 - IFT_PROPVIRTUAL = 0x35 - IFT_PTPSERIAL = 0x16 - IFT_RS232 = 0x21 - IFT_SDLC = 0x11 - IFT_SIP = 0x1f - IFT_SLIP = 0x1c - IFT_SMDSDXI = 0x2b - IFT_SMDSICIP = 0x34 - IFT_SONET = 0x27 - IFT_SONETPATH = 0x32 - IFT_SONETVT = 0x33 - IFT_STARLAN = 0xb - IFT_T1 = 0x12 - IFT_ULTRA = 0x1d - IFT_V35 = 0x2d - IFT_X25 = 0x5 - IFT_X25DDN = 0x4 - IFT_X25PLE = 0x28 - IFT_XETHER = 0x1a - IGNBRK = 0x1 - IGNCR = 0x80 - IGNPAR = 0x4 - IMAXBEL = 0x2000 - INLCR = 0x40 - INPCK = 0x10 - IN_AUTOCONF_MASK = 0xffff0000 - IN_AUTOCONF_NET = 0xa9fe0000 - IN_CLASSA_HOST = 0xffffff - IN_CLASSA_MAX = 0x80 - IN_CLASSA_NET = 0xff000000 - IN_CLASSA_NSHIFT = 0x18 - IN_CLASSB_HOST = 0xffff - IN_CLASSB_MAX = 0x10000 - IN_CLASSB_NET = 0xffff0000 - IN_CLASSB_NSHIFT = 0x10 - IN_CLASSC_HOST = 0xff - IN_CLASSC_NET = 0xffffff00 - IN_CLASSC_NSHIFT = 0x8 - IN_CLASSD_HOST = 0xfffffff - IN_CLASSD_NET = 0xf0000000 - IN_CLASSD_NSHIFT = 0x1c - IN_CLASSE_NET = 0xffffffff - IN_LOOPBACKNET = 0x7f - IN_PRIVATE12_MASK = 0xfff00000 - IN_PRIVATE12_NET = 0xac100000 - IN_PRIVATE16_MASK = 0xffff0000 - IN_PRIVATE16_NET = 0xc0a80000 - IN_PRIVATE8_MASK = 0xff000000 - IN_PRIVATE8_NET = 0xa000000 - IPPROTO_AH = 0x33 - IPPROTO_DSTOPTS = 0x3c - IPPROTO_EGP = 0x8 - IPPROTO_ENCAP = 0x4 - IPPROTO_EON = 0x50 - IPPROTO_ESP = 0x32 - IPPROTO_FRAGMENT = 0x2c - IPPROTO_GGP = 0x3 - IPPROTO_HELLO = 0x3f - IPPROTO_HOPOPTS = 0x0 - IPPROTO_ICMP = 0x1 - IPPROTO_ICMPV6 = 0x3a - IPPROTO_IDP = 0x16 - IPPROTO_IGMP = 0x2 - IPPROTO_IP = 0x0 - IPPROTO_IPV6 = 0x29 - IPPROTO_MAX = 0x100 - IPPROTO_ND = 0x4d - IPPROTO_NONE = 0x3b - IPPROTO_OSPF = 0x59 - IPPROTO_PIM = 0x67 - IPPROTO_PUP = 0xc - IPPROTO_RAW = 0xff - IPPROTO_ROUTING = 0x2b - IPPROTO_RSVP = 0x2e - IPPROTO_SCTP = 0x84 - IPPROTO_TCP = 0x6 - IPPROTO_UDP = 0x11 - IPV6_ADD_MEMBERSHIP = 0x9 - IPV6_BOUND_IF = 0x41 - IPV6_CHECKSUM = 0x18 - IPV6_DONTFRAG = 0x21 - IPV6_DROP_MEMBERSHIP = 0xa - IPV6_DSTOPTS = 0xf - IPV6_FLOWINFO_FLOWLABEL = 0xffff0f00 - IPV6_FLOWINFO_TCLASS = 0xf00f - IPV6_HOPLIMIT = 0xc - IPV6_HOPOPTS = 0xe - IPV6_JOIN_GROUP = 0x9 - IPV6_LEAVE_GROUP = 0xa - IPV6_MULTICAST_HOPS = 0x7 - IPV6_MULTICAST_IF = 0x6 - IPV6_MULTICAST_LOOP = 0x8 - IPV6_NEXTHOP = 0xd - IPV6_PAD1_OPT = 0x0 - IPV6_PATHMTU = 0x25 - IPV6_PKTINFO = 0xb - IPV6_PREFER_SRC_CGA = 0x20 - IPV6_PREFER_SRC_CGADEFAULT = 0x10 - IPV6_PREFER_SRC_CGAMASK = 0x30 - IPV6_PREFER_SRC_COA = 0x2 - IPV6_PREFER_SRC_DEFAULT = 0x15 - IPV6_PREFER_SRC_HOME = 0x1 - IPV6_PREFER_SRC_MASK = 0x3f - IPV6_PREFER_SRC_MIPDEFAULT = 0x1 - IPV6_PREFER_SRC_MIPMASK = 0x3 - IPV6_PREFER_SRC_NONCGA = 0x10 - IPV6_PREFER_SRC_PUBLIC = 0x4 - IPV6_PREFER_SRC_TMP = 0x8 - IPV6_PREFER_SRC_TMPDEFAULT = 0x4 - IPV6_PREFER_SRC_TMPMASK = 0xc - IPV6_RECVDSTOPTS = 0x28 - IPV6_RECVHOPLIMIT = 0x13 - IPV6_RECVHOPOPTS = 0x14 - IPV6_RECVPATHMTU = 0x24 - IPV6_RECVPKTINFO = 0x12 - IPV6_RECVRTHDR = 0x16 - IPV6_RECVRTHDRDSTOPTS = 0x17 - IPV6_RECVTCLASS = 0x19 - IPV6_RTHDR = 0x10 - IPV6_RTHDRDSTOPTS = 0x11 - IPV6_RTHDR_TYPE_0 = 0x0 - IPV6_SEC_OPT = 0x22 - IPV6_SRC_PREFERENCES = 0x23 - IPV6_TCLASS = 0x26 - IPV6_UNICAST_HOPS = 0x5 - IPV6_UNSPEC_SRC = 0x42 - IPV6_USE_MIN_MTU = 0x20 - IPV6_V6ONLY = 0x27 - IP_ADD_MEMBERSHIP = 0x13 - IP_ADD_SOURCE_MEMBERSHIP = 0x17 - IP_BLOCK_SOURCE = 0x15 - IP_BOUND_IF = 0x41 - IP_BROADCAST = 0x106 - IP_BROADCAST_TTL = 0x43 - IP_DEFAULT_MULTICAST_LOOP = 0x1 - IP_DEFAULT_MULTICAST_TTL = 0x1 - IP_DF = 0x4000 - IP_DHCPINIT_IF = 0x45 - IP_DONTFRAG = 0x1b - IP_DONTROUTE = 0x105 - IP_DROP_MEMBERSHIP = 0x14 - IP_DROP_SOURCE_MEMBERSHIP = 0x18 - IP_HDRINCL = 0x2 - IP_MAXPACKET = 0xffff - IP_MF = 0x2000 - IP_MSS = 0x240 - IP_MULTICAST_IF = 0x10 - IP_MULTICAST_LOOP = 0x12 - IP_MULTICAST_TTL = 0x11 - IP_NEXTHOP = 0x19 - IP_OPTIONS = 0x1 - IP_PKTINFO = 0x1a - IP_RECVDSTADDR = 0x7 - IP_RECVIF = 0x9 - IP_RECVOPTS = 0x5 - IP_RECVPKTINFO = 0x1a - IP_RECVRETOPTS = 0x6 - IP_RECVSLLA = 0xa - IP_RECVTTL = 0xb - IP_RETOPTS = 0x8 - IP_REUSEADDR = 0x104 - IP_SEC_OPT = 0x22 - IP_TOS = 0x3 - IP_TTL = 0x4 - IP_UNBLOCK_SOURCE = 0x16 - IP_UNSPEC_SRC = 0x42 - ISIG = 0x1 - ISTRIP = 0x20 - IXANY = 0x800 - IXOFF = 0x1000 - IXON = 0x400 - MADV_ACCESS_DEFAULT = 0x6 - MADV_ACCESS_LWP = 0x7 - MADV_ACCESS_MANY = 0x8 - MADV_DONTNEED = 0x4 - MADV_FREE = 0x5 - MADV_NORMAL = 0x0 - MADV_RANDOM = 0x1 - MADV_SEQUENTIAL = 0x2 - MADV_WILLNEED = 0x3 - MAP_32BIT = 0x80 - MAP_ALIGN = 0x200 - MAP_ANON = 0x100 - MAP_ANONYMOUS = 0x100 - MAP_FIXED = 0x10 - MAP_INITDATA = 0x800 - MAP_NORESERVE = 0x40 - MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 - MAP_SHARED = 0x1 - MAP_TEXT = 0x400 - MAP_TYPE = 0xf - MCL_CURRENT = 0x1 - MCL_FUTURE = 0x2 - MSG_CTRUNC = 0x10 - MSG_DONTROUTE = 0x4 - MSG_DONTWAIT = 0x80 - MSG_DUPCTRL = 0x800 - MSG_EOR = 0x8 - MSG_MAXIOVLEN = 0x10 - MSG_NOTIFICATION = 0x100 - MSG_OOB = 0x1 - MSG_PEEK = 0x2 - MSG_TRUNC = 0x20 - MSG_WAITALL = 0x40 - MSG_XPG4_2 = 0x8000 - MS_ASYNC = 0x1 - MS_INVALIDATE = 0x2 - MS_OLDSYNC = 0x0 - MS_SYNC = 0x4 - M_FLUSH = 0x86 - NOFLSH = 0x80 - OCRNL = 0x8 - OFDEL = 0x80 - OFILL = 0x40 - ONLCR = 0x4 - ONLRET = 0x20 - ONOCR = 0x10 - OPENFAIL = -0x1 - OPOST = 0x1 - O_ACCMODE = 0x600003 - O_APPEND = 0x8 - O_CLOEXEC = 0x800000 - O_CREAT = 0x100 - O_DSYNC = 0x40 - O_EXCL = 0x400 - O_EXEC = 0x400000 - O_LARGEFILE = 0x2000 - O_NDELAY = 0x4 - O_NOCTTY = 0x800 - O_NOFOLLOW = 0x20000 - O_NOLINKS = 0x40000 - O_NONBLOCK = 0x80 - O_RDONLY = 0x0 - O_RDWR = 0x2 - O_RSYNC = 0x8000 - O_SEARCH = 0x200000 - O_SIOCGIFCONF = -0x3ff796ec - O_SIOCGLIFCONF = -0x3fef9688 - O_SYNC = 0x10 - O_TRUNC = 0x200 - O_WRONLY = 0x1 - O_XATTR = 0x4000 - PARENB = 0x100 - PAREXT = 0x100000 - PARMRK = 0x8 - PARODD = 0x200 - PENDIN = 0x4000 - PRIO_PGRP = 0x1 - PRIO_PROCESS = 0x0 - PRIO_USER = 0x2 - PROT_EXEC = 0x4 - PROT_NONE = 0x0 - PROT_READ = 0x1 - PROT_WRITE = 0x2 - RLIMIT_AS = 0x6 - RLIMIT_CORE = 0x4 - RLIMIT_CPU = 0x0 - RLIMIT_DATA = 0x2 - RLIMIT_FSIZE = 0x1 - RLIMIT_NOFILE = 0x5 - RLIMIT_STACK = 0x3 - RLIM_INFINITY = -0x3 - RTAX_AUTHOR = 0x6 - RTAX_BRD = 0x7 - RTAX_DST = 0x0 - RTAX_GATEWAY = 0x1 - RTAX_GENMASK = 0x3 - RTAX_IFA = 0x5 - RTAX_IFP = 0x4 - RTAX_MAX = 0x9 - RTAX_NETMASK = 0x2 - RTAX_SRC = 0x8 - RTA_AUTHOR = 0x40 - RTA_BRD = 0x80 - RTA_DST = 0x1 - RTA_GATEWAY = 0x2 - RTA_GENMASK = 0x8 - RTA_IFA = 0x20 - RTA_IFP = 0x10 - RTA_NETMASK = 0x4 - RTA_NUMBITS = 0x9 - RTA_SRC = 0x100 - RTF_BLACKHOLE = 0x1000 - RTF_CLONING = 0x100 - RTF_DONE = 0x40 - RTF_DYNAMIC = 0x10 - RTF_GATEWAY = 0x2 - RTF_HOST = 0x4 - RTF_INDIRECT = 0x40000 - RTF_KERNEL = 0x80000 - RTF_LLINFO = 0x400 - RTF_MASK = 0x80 - RTF_MODIFIED = 0x20 - RTF_MULTIRT = 0x10000 - RTF_PRIVATE = 0x2000 - RTF_PROTO1 = 0x8000 - RTF_PROTO2 = 0x4000 - RTF_REJECT = 0x8 - RTF_SETSRC = 0x20000 - RTF_STATIC = 0x800 - RTF_UP = 0x1 - RTF_XRESOLVE = 0x200 - RTF_ZONE = 0x100000 - RTM_ADD = 0x1 - RTM_CHANGE = 0x3 - RTM_CHGADDR = 0xf - RTM_DELADDR = 0xd - RTM_DELETE = 0x2 - RTM_FREEADDR = 0x10 - RTM_GET = 0x4 - RTM_IFINFO = 0xe - RTM_LOCK = 0x8 - RTM_LOSING = 0x5 - RTM_MISS = 0x7 - RTM_NEWADDR = 0xc - RTM_OLDADD = 0x9 - RTM_OLDDEL = 0xa - RTM_REDIRECT = 0x6 - RTM_RESOLVE = 0xb - RTM_VERSION = 0x3 - RTV_EXPIRE = 0x4 - RTV_HOPCOUNT = 0x2 - RTV_MTU = 0x1 - RTV_RPIPE = 0x8 - RTV_RTT = 0x40 - RTV_RTTVAR = 0x80 - RTV_SPIPE = 0x10 - RTV_SSTHRESH = 0x20 - RT_AWARE = 0x1 - RUSAGE_CHILDREN = -0x1 - RUSAGE_SELF = 0x0 - SCM_RIGHTS = 0x1010 - SCM_TIMESTAMP = 0x1013 - SCM_UCRED = 0x1012 - SHUT_RD = 0x0 - SHUT_RDWR = 0x2 - SHUT_WR = 0x1 - SIG2STR_MAX = 0x20 - SIOCADDMULTI = -0x7fdf96cf - SIOCADDRT = -0x7fcf8df6 - SIOCATMARK = 0x40047307 - SIOCDARP = -0x7fdb96e0 - SIOCDELMULTI = -0x7fdf96ce - SIOCDELRT = -0x7fcf8df5 - SIOCDXARP = -0x7fff9658 - SIOCGARP = -0x3fdb96e1 - SIOCGDSTINFO = -0x3fff965c - SIOCGENADDR = -0x3fdf96ab - SIOCGENPSTATS = -0x3fdf96c7 - SIOCGETLSGCNT = -0x3fef8deb - SIOCGETNAME = 0x40107334 - SIOCGETPEER = 0x40107335 - SIOCGETPROP = -0x3fff8f44 - SIOCGETSGCNT = -0x3feb8deb - SIOCGETSYNC = -0x3fdf96d3 - SIOCGETVIFCNT = -0x3feb8dec - SIOCGHIWAT = 0x40047301 - SIOCGIFADDR = -0x3fdf96f3 - SIOCGIFBRDADDR = -0x3fdf96e9 - SIOCGIFCONF = -0x3ff796a4 - SIOCGIFDSTADDR = -0x3fdf96f1 - SIOCGIFFLAGS = -0x3fdf96ef - SIOCGIFHWADDR = -0x3fdf9647 - SIOCGIFINDEX = -0x3fdf96a6 - SIOCGIFMEM = -0x3fdf96ed - SIOCGIFMETRIC = -0x3fdf96e5 - SIOCGIFMTU = -0x3fdf96ea - SIOCGIFMUXID = -0x3fdf96a8 - SIOCGIFNETMASK = -0x3fdf96e7 - SIOCGIFNUM = 0x40046957 - SIOCGIP6ADDRPOLICY = -0x3fff965e - SIOCGIPMSFILTER = -0x3ffb964c - SIOCGLIFADDR = -0x3f87968f - SIOCGLIFBINDING = -0x3f879666 - SIOCGLIFBRDADDR = -0x3f879685 - SIOCGLIFCONF = -0x3fef965b - SIOCGLIFDADSTATE = -0x3f879642 - SIOCGLIFDSTADDR = -0x3f87968d - SIOCGLIFFLAGS = -0x3f87968b - SIOCGLIFGROUPINFO = -0x3f4b9663 - SIOCGLIFGROUPNAME = -0x3f879664 - SIOCGLIFHWADDR = -0x3f879640 - SIOCGLIFINDEX = -0x3f87967b - SIOCGLIFLNKINFO = -0x3f879674 - SIOCGLIFMETRIC = -0x3f879681 - SIOCGLIFMTU = -0x3f879686 - SIOCGLIFMUXID = -0x3f87967d - SIOCGLIFNETMASK = -0x3f879683 - SIOCGLIFNUM = -0x3ff3967e - SIOCGLIFSRCOF = -0x3fef964f - SIOCGLIFSUBNET = -0x3f879676 - SIOCGLIFTOKEN = -0x3f879678 - SIOCGLIFUSESRC = -0x3f879651 - SIOCGLIFZONE = -0x3f879656 - SIOCGLOWAT = 0x40047303 - SIOCGMSFILTER = -0x3ffb964e - SIOCGPGRP = 0x40047309 - SIOCGSTAMP = -0x3fef9646 - SIOCGXARP = -0x3fff9659 - SIOCIFDETACH = -0x7fdf96c8 - SIOCILB = -0x3ffb9645 - SIOCLIFADDIF = -0x3f879691 - SIOCLIFDELND = -0x7f879673 - SIOCLIFGETND = -0x3f879672 - SIOCLIFREMOVEIF = -0x7f879692 - SIOCLIFSETND = -0x7f879671 - SIOCLOWER = -0x7fdf96d7 - SIOCSARP = -0x7fdb96e2 - SIOCSCTPGOPT = -0x3fef9653 - SIOCSCTPPEELOFF = -0x3ffb9652 - SIOCSCTPSOPT = -0x7fef9654 - SIOCSENABLESDP = -0x3ffb9649 - SIOCSETPROP = -0x7ffb8f43 - SIOCSETSYNC = -0x7fdf96d4 - SIOCSHIWAT = -0x7ffb8d00 - SIOCSIFADDR = -0x7fdf96f4 - SIOCSIFBRDADDR = -0x7fdf96e8 - SIOCSIFDSTADDR = -0x7fdf96f2 - SIOCSIFFLAGS = -0x7fdf96f0 - SIOCSIFINDEX = -0x7fdf96a5 - SIOCSIFMEM = -0x7fdf96ee - SIOCSIFMETRIC = -0x7fdf96e4 - SIOCSIFMTU = -0x7fdf96eb - SIOCSIFMUXID = -0x7fdf96a7 - SIOCSIFNAME = -0x7fdf96b7 - SIOCSIFNETMASK = -0x7fdf96e6 - SIOCSIP6ADDRPOLICY = -0x7fff965d - SIOCSIPMSFILTER = -0x7ffb964b - SIOCSLGETREQ = -0x3fdf96b9 - SIOCSLIFADDR = -0x7f879690 - SIOCSLIFBRDADDR = -0x7f879684 - SIOCSLIFDSTADDR = -0x7f87968e - SIOCSLIFFLAGS = -0x7f87968c - SIOCSLIFGROUPNAME = -0x7f879665 - SIOCSLIFINDEX = -0x7f87967a - SIOCSLIFLNKINFO = -0x7f879675 - SIOCSLIFMETRIC = -0x7f879680 - SIOCSLIFMTU = -0x7f879687 - SIOCSLIFMUXID = -0x7f87967c - SIOCSLIFNAME = -0x3f87967f - SIOCSLIFNETMASK = -0x7f879682 - SIOCSLIFPREFIX = -0x3f879641 - SIOCSLIFSUBNET = -0x7f879677 - SIOCSLIFTOKEN = -0x7f879679 - SIOCSLIFUSESRC = -0x7f879650 - SIOCSLIFZONE = -0x7f879655 - SIOCSLOWAT = -0x7ffb8cfe - SIOCSLSTAT = -0x7fdf96b8 - SIOCSMSFILTER = -0x7ffb964d - SIOCSPGRP = -0x7ffb8cf8 - SIOCSPROMISC = -0x7ffb96d0 - SIOCSQPTR = -0x3ffb9648 - SIOCSSDSTATS = -0x3fdf96d2 - SIOCSSESTATS = -0x3fdf96d1 - SIOCSXARP = -0x7fff965a - SIOCTMYADDR = -0x3ff79670 - SIOCTMYSITE = -0x3ff7966e - SIOCTONLINK = -0x3ff7966f - SIOCUPPER = -0x7fdf96d8 - SIOCX25RCV = -0x3fdf96c4 - SIOCX25TBL = -0x3fdf96c3 - SIOCX25XMT = -0x3fdf96c5 - SIOCXPROTO = 0x20007337 - SOCK_CLOEXEC = 0x80000 - SOCK_DGRAM = 0x1 - SOCK_NDELAY = 0x200000 - SOCK_NONBLOCK = 0x100000 - SOCK_RAW = 0x4 - SOCK_RDM = 0x5 - SOCK_SEQPACKET = 0x6 - SOCK_STREAM = 0x2 - SOCK_TYPE_MASK = 0xffff - SOL_FILTER = 0xfffc - SOL_PACKET = 0xfffd - SOL_ROUTE = 0xfffe - SOL_SOCKET = 0xffff - SOMAXCONN = 0x80 - SO_ACCEPTCONN = 0x2 - SO_ALL = 0x3f - SO_ALLZONES = 0x1014 - SO_ANON_MLP = 0x100a - SO_ATTACH_FILTER = 0x40000001 - SO_BAND = 0x4000 - SO_BROADCAST = 0x20 - SO_COPYOPT = 0x80000 - SO_DEBUG = 0x1 - SO_DELIM = 0x8000 - SO_DETACH_FILTER = 0x40000002 - SO_DGRAM_ERRIND = 0x200 - SO_DOMAIN = 0x100c - SO_DONTLINGER = -0x81 - SO_DONTROUTE = 0x10 - SO_ERROPT = 0x40000 - SO_ERROR = 0x1007 - SO_EXCLBIND = 0x1015 - SO_HIWAT = 0x10 - SO_ISNTTY = 0x800 - SO_ISTTY = 0x400 - SO_KEEPALIVE = 0x8 - SO_LINGER = 0x80 - SO_LOWAT = 0x20 - SO_MAC_EXEMPT = 0x100b - SO_MAC_IMPLICIT = 0x1016 - SO_MAXBLK = 0x100000 - SO_MAXPSZ = 0x8 - SO_MINPSZ = 0x4 - SO_MREADOFF = 0x80 - SO_MREADON = 0x40 - SO_NDELOFF = 0x200 - SO_NDELON = 0x100 - SO_NODELIM = 0x10000 - SO_OOBINLINE = 0x100 - SO_PROTOTYPE = 0x1009 - SO_RCVBUF = 0x1002 - SO_RCVLOWAT = 0x1004 - SO_RCVPSH = 0x100d - SO_RCVTIMEO = 0x1006 - SO_READOPT = 0x1 - SO_RECVUCRED = 0x400 - SO_REUSEADDR = 0x4 - SO_SECATTR = 0x1011 - SO_SNDBUF = 0x1001 - SO_SNDLOWAT = 0x1003 - SO_SNDTIMEO = 0x1005 - SO_STRHOLD = 0x20000 - SO_TAIL = 0x200000 - SO_TIMESTAMP = 0x1013 - SO_TONSTOP = 0x2000 - SO_TOSTOP = 0x1000 - SO_TYPE = 0x1008 - SO_USELOOPBACK = 0x40 - SO_VRRP = 0x1017 - SO_WROFF = 0x2 - TCFLSH = 0x5407 - TCGETA = 0x5401 - TCGETS = 0x540d - TCIFLUSH = 0x0 - TCIOFLUSH = 0x2 - TCOFLUSH = 0x1 - TCP_ABORT_THRESHOLD = 0x11 - TCP_ANONPRIVBIND = 0x20 - TCP_CONN_ABORT_THRESHOLD = 0x13 - TCP_CONN_NOTIFY_THRESHOLD = 0x12 - TCP_CORK = 0x18 - TCP_EXCLBIND = 0x21 - TCP_INIT_CWND = 0x15 - TCP_KEEPALIVE = 0x8 - TCP_KEEPALIVE_ABORT_THRESHOLD = 0x17 - TCP_KEEPALIVE_THRESHOLD = 0x16 - TCP_KEEPCNT = 0x23 - TCP_KEEPIDLE = 0x22 - TCP_KEEPINTVL = 0x24 - TCP_LINGER2 = 0x1c - TCP_MAXSEG = 0x2 - TCP_MSS = 0x218 - TCP_NODELAY = 0x1 - TCP_NOTIFY_THRESHOLD = 0x10 - TCP_RECVDSTADDR = 0x14 - TCP_RTO_INITIAL = 0x19 - TCP_RTO_MAX = 0x1b - TCP_RTO_MIN = 0x1a - TCSAFLUSH = 0x5410 - TCSBRK = 0x5405 - TCSETA = 0x5402 - TCSETAF = 0x5404 - TCSETAW = 0x5403 - TCSETS = 0x540e - TCSETSF = 0x5410 - TCSETSW = 0x540f - TCXONC = 0x5406 - TIOC = 0x5400 - TIOCCBRK = 0x747a - TIOCCDTR = 0x7478 - TIOCCILOOP = 0x746c - TIOCEXCL = 0x740d - TIOCFLUSH = 0x7410 - TIOCGETC = 0x7412 - TIOCGETD = 0x7400 - TIOCGETP = 0x7408 - TIOCGLTC = 0x7474 - TIOCGPGRP = 0x7414 - TIOCGPPS = 0x547d - TIOCGPPSEV = 0x547f - TIOCGSID = 0x7416 - TIOCGSOFTCAR = 0x5469 - TIOCGWINSZ = 0x5468 - TIOCHPCL = 0x7402 - TIOCKBOF = 0x5409 - TIOCKBON = 0x5408 - TIOCLBIC = 0x747e - TIOCLBIS = 0x747f - TIOCLGET = 0x747c - TIOCLSET = 0x747d - TIOCMBIC = 0x741c - TIOCMBIS = 0x741b - TIOCMGET = 0x741d - TIOCMSET = 0x741a - TIOCM_CAR = 0x40 - TIOCM_CD = 0x40 - TIOCM_CTS = 0x20 - TIOCM_DSR = 0x100 - TIOCM_DTR = 0x2 - TIOCM_LE = 0x1 - TIOCM_RI = 0x80 - TIOCM_RNG = 0x80 - TIOCM_RTS = 0x4 - TIOCM_SR = 0x10 - TIOCM_ST = 0x8 - TIOCNOTTY = 0x7471 - TIOCNXCL = 0x740e - TIOCOUTQ = 0x7473 - TIOCREMOTE = 0x741e - TIOCSBRK = 0x747b - TIOCSCTTY = 0x7484 - TIOCSDTR = 0x7479 - TIOCSETC = 0x7411 - TIOCSETD = 0x7401 - TIOCSETN = 0x740a - TIOCSETP = 0x7409 - TIOCSIGNAL = 0x741f - TIOCSILOOP = 0x746d - TIOCSLTC = 0x7475 - TIOCSPGRP = 0x7415 - TIOCSPPS = 0x547e - TIOCSSOFTCAR = 0x546a - TIOCSTART = 0x746e - TIOCSTI = 0x7417 - TIOCSTOP = 0x746f - TIOCSWINSZ = 0x5467 - TOSTOP = 0x100 - VCEOF = 0x8 - VCEOL = 0x9 - VDISCARD = 0xd - VDSUSP = 0xb - VEOF = 0x4 - VEOL = 0x5 - VEOL2 = 0x6 - VERASE = 0x2 - VINTR = 0x0 - VKILL = 0x3 - VLNEXT = 0xf - VMIN = 0x4 - VQUIT = 0x1 - VREPRINT = 0xc - VSTART = 0x8 - VSTATUS = 0x10 - VSTOP = 0x9 - VSUSP = 0xa - VSWTCH = 0x7 - VT0 = 0x0 - VT1 = 0x4000 - VTDLY = 0x4000 - VTIME = 0x5 - VWERASE = 0xe - WCONTFLG = 0xffff - WCONTINUED = 0x8 - WCOREFLG = 0x80 - WEXITED = 0x1 - WNOHANG = 0x40 - WNOWAIT = 0x80 - WOPTMASK = 0xcf - WRAP = 0x20000 - WSIGMASK = 0x7f - WSTOPFLG = 0x7f - WSTOPPED = 0x4 - WTRAPPED = 0x2 - WUNTRACED = 0x4 -) - -// Errors -const ( - E2BIG = syscall.Errno(0x7) - EACCES = syscall.Errno(0xd) - EADDRINUSE = syscall.Errno(0x7d) - EADDRNOTAVAIL = syscall.Errno(0x7e) - EADV = syscall.Errno(0x44) - EAFNOSUPPORT = syscall.Errno(0x7c) - EAGAIN = syscall.Errno(0xb) - EALREADY = syscall.Errno(0x95) - EBADE = syscall.Errno(0x32) - EBADF = syscall.Errno(0x9) - EBADFD = syscall.Errno(0x51) - EBADMSG = syscall.Errno(0x4d) - EBADR = syscall.Errno(0x33) - EBADRQC = syscall.Errno(0x36) - EBADSLT = syscall.Errno(0x37) - EBFONT = syscall.Errno(0x39) - EBUSY = syscall.Errno(0x10) - ECANCELED = syscall.Errno(0x2f) - ECHILD = syscall.Errno(0xa) - ECHRNG = syscall.Errno(0x25) - ECOMM = syscall.Errno(0x46) - ECONNABORTED = syscall.Errno(0x82) - ECONNREFUSED = syscall.Errno(0x92) - ECONNRESET = syscall.Errno(0x83) - EDEADLK = syscall.Errno(0x2d) - EDEADLOCK = syscall.Errno(0x38) - EDESTADDRREQ = syscall.Errno(0x60) - EDOM = syscall.Errno(0x21) - EDQUOT = syscall.Errno(0x31) - EEXIST = syscall.Errno(0x11) - EFAULT = syscall.Errno(0xe) - EFBIG = syscall.Errno(0x1b) - EHOSTDOWN = syscall.Errno(0x93) - EHOSTUNREACH = syscall.Errno(0x94) - EIDRM = syscall.Errno(0x24) - EILSEQ = syscall.Errno(0x58) - EINPROGRESS = syscall.Errno(0x96) - EINTR = syscall.Errno(0x4) - EINVAL = syscall.Errno(0x16) - EIO = syscall.Errno(0x5) - EISCONN = syscall.Errno(0x85) - EISDIR = syscall.Errno(0x15) - EL2HLT = syscall.Errno(0x2c) - EL2NSYNC = syscall.Errno(0x26) - EL3HLT = syscall.Errno(0x27) - EL3RST = syscall.Errno(0x28) - ELIBACC = syscall.Errno(0x53) - ELIBBAD = syscall.Errno(0x54) - ELIBEXEC = syscall.Errno(0x57) - ELIBMAX = syscall.Errno(0x56) - ELIBSCN = syscall.Errno(0x55) - ELNRNG = syscall.Errno(0x29) - ELOCKUNMAPPED = syscall.Errno(0x48) - ELOOP = syscall.Errno(0x5a) - EMFILE = syscall.Errno(0x18) - EMLINK = syscall.Errno(0x1f) - EMSGSIZE = syscall.Errno(0x61) - EMULTIHOP = syscall.Errno(0x4a) - ENAMETOOLONG = syscall.Errno(0x4e) - ENETDOWN = syscall.Errno(0x7f) - ENETRESET = syscall.Errno(0x81) - ENETUNREACH = syscall.Errno(0x80) - ENFILE = syscall.Errno(0x17) - ENOANO = syscall.Errno(0x35) - ENOBUFS = syscall.Errno(0x84) - ENOCSI = syscall.Errno(0x2b) - ENODATA = syscall.Errno(0x3d) - ENODEV = syscall.Errno(0x13) - ENOENT = syscall.Errno(0x2) - ENOEXEC = syscall.Errno(0x8) - ENOLCK = syscall.Errno(0x2e) - ENOLINK = syscall.Errno(0x43) - ENOMEM = syscall.Errno(0xc) - ENOMSG = syscall.Errno(0x23) - ENONET = syscall.Errno(0x40) - ENOPKG = syscall.Errno(0x41) - ENOPROTOOPT = syscall.Errno(0x63) - ENOSPC = syscall.Errno(0x1c) - ENOSR = syscall.Errno(0x3f) - ENOSTR = syscall.Errno(0x3c) - ENOSYS = syscall.Errno(0x59) - ENOTACTIVE = syscall.Errno(0x49) - ENOTBLK = syscall.Errno(0xf) - ENOTCONN = syscall.Errno(0x86) - ENOTDIR = syscall.Errno(0x14) - ENOTEMPTY = syscall.Errno(0x5d) - ENOTRECOVERABLE = syscall.Errno(0x3b) - ENOTSOCK = syscall.Errno(0x5f) - ENOTSUP = syscall.Errno(0x30) - ENOTTY = syscall.Errno(0x19) - ENOTUNIQ = syscall.Errno(0x50) - ENXIO = syscall.Errno(0x6) - EOPNOTSUPP = syscall.Errno(0x7a) - EOVERFLOW = syscall.Errno(0x4f) - EOWNERDEAD = syscall.Errno(0x3a) - EPERM = syscall.Errno(0x1) - EPFNOSUPPORT = syscall.Errno(0x7b) - EPIPE = syscall.Errno(0x20) - EPROTO = syscall.Errno(0x47) - EPROTONOSUPPORT = syscall.Errno(0x78) - EPROTOTYPE = syscall.Errno(0x62) - ERANGE = syscall.Errno(0x22) - EREMCHG = syscall.Errno(0x52) - EREMOTE = syscall.Errno(0x42) - ERESTART = syscall.Errno(0x5b) - EROFS = syscall.Errno(0x1e) - ESHUTDOWN = syscall.Errno(0x8f) - ESOCKTNOSUPPORT = syscall.Errno(0x79) - ESPIPE = syscall.Errno(0x1d) - ESRCH = syscall.Errno(0x3) - ESRMNT = syscall.Errno(0x45) - ESTALE = syscall.Errno(0x97) - ESTRPIPE = syscall.Errno(0x5c) - ETIME = syscall.Errno(0x3e) - ETIMEDOUT = syscall.Errno(0x91) - ETOOMANYREFS = syscall.Errno(0x90) - ETXTBSY = syscall.Errno(0x1a) - EUNATCH = syscall.Errno(0x2a) - EUSERS = syscall.Errno(0x5e) - EWOULDBLOCK = syscall.Errno(0xb) - EXDEV = syscall.Errno(0x12) - EXFULL = syscall.Errno(0x34) -) - -// Signals -const ( - SIGABRT = syscall.Signal(0x6) - SIGALRM = syscall.Signal(0xe) - SIGBUS = syscall.Signal(0xa) - SIGCANCEL = syscall.Signal(0x24) - SIGCHLD = syscall.Signal(0x12) - SIGCLD = syscall.Signal(0x12) - SIGCONT = syscall.Signal(0x19) - SIGEMT = syscall.Signal(0x7) - SIGFPE = syscall.Signal(0x8) - SIGFREEZE = syscall.Signal(0x22) - SIGHUP = syscall.Signal(0x1) - SIGILL = syscall.Signal(0x4) - SIGINFO = syscall.Signal(0x29) - SIGINT = syscall.Signal(0x2) - SIGIO = syscall.Signal(0x16) - SIGIOT = syscall.Signal(0x6) - SIGJVM1 = syscall.Signal(0x27) - SIGJVM2 = syscall.Signal(0x28) - SIGKILL = syscall.Signal(0x9) - SIGLOST = syscall.Signal(0x25) - SIGLWP = syscall.Signal(0x21) - SIGPIPE = syscall.Signal(0xd) - SIGPOLL = syscall.Signal(0x16) - SIGPROF = syscall.Signal(0x1d) - SIGPWR = syscall.Signal(0x13) - SIGQUIT = syscall.Signal(0x3) - SIGSEGV = syscall.Signal(0xb) - SIGSTOP = syscall.Signal(0x17) - SIGSYS = syscall.Signal(0xc) - SIGTERM = syscall.Signal(0xf) - SIGTHAW = syscall.Signal(0x23) - SIGTRAP = syscall.Signal(0x5) - SIGTSTP = syscall.Signal(0x18) - SIGTTIN = syscall.Signal(0x1a) - SIGTTOU = syscall.Signal(0x1b) - SIGURG = syscall.Signal(0x15) - SIGUSR1 = syscall.Signal(0x10) - SIGUSR2 = syscall.Signal(0x11) - SIGVTALRM = syscall.Signal(0x1c) - SIGWAITING = syscall.Signal(0x20) - SIGWINCH = syscall.Signal(0x14) - SIGXCPU = syscall.Signal(0x1e) - SIGXFSZ = syscall.Signal(0x1f) - SIGXRES = syscall.Signal(0x26) -) - -// Error table -var errors = [...]string{ - 1: "not owner", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "I/O error", - 6: "no such device or address", - 7: "arg list too long", - 8: "exec format error", - 9: "bad file number", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "not enough space", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "file table overflow", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "argument out of domain", - 34: "result too large", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "deadlock situation detected/avoided", - 46: "no record locks available", - 47: "operation canceled", - 48: "operation not supported", - 49: "disc quota exceeded", - 50: "bad exchange descriptor", - 51: "bad request descriptor", - 52: "message tables full", - 53: "anode table overflow", - 54: "bad request code", - 55: "invalid slot", - 56: "file locking deadlock", - 57: "bad font file format", - 58: "owner of the lock died", - 59: "lock is not recoverable", - 60: "not a stream device", - 61: "no data available", - 62: "timer expired", - 63: "out of stream resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "locked lock was unmapped ", - 73: "facility is not active", - 74: "multihop attempted", - 77: "not a data message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in more shared libraries than system limit", - 87: "can not exec a shared library directly", - 88: "illegal byte sequence", - 89: "operation not applicable", - 90: "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS", - 91: "error 91", - 92: "error 92", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "option not supported by protocol", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported on transport endpoint", - 123: "protocol family not supported", - 124: "address family not supported by protocol family", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection because of reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 143: "cannot send after socket shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale NFS file handle", -} - -// Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal Instruction", - 5: "trace/Breakpoint Trap", - 6: "abort", - 7: "emulation Trap", - 8: "arithmetic Exception", - 9: "killed", - 10: "bus Error", - 11: "segmentation Fault", - 12: "bad System Call", - 13: "broken Pipe", - 14: "alarm Clock", - 15: "terminated", - 16: "user Signal 1", - 17: "user Signal 2", - 18: "child Status Changed", - 19: "power-Fail/Restart", - 20: "window Size Change", - 21: "urgent Socket Condition", - 22: "pollable Event", - 23: "stopped (signal)", - 24: "stopped (user)", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual Timer Expired", - 29: "profiling Timer Expired", - 30: "cpu Limit Exceeded", - 31: "file Size Limit Exceeded", - 32: "no runnable lwp", - 33: "inter-lwp signal", - 34: "checkpoint Freeze", - 35: "checkpoint Thaw", - 36: "thread Cancellation", - 37: "resource Lost", - 38: "resource Control Exceeded", - 39: "reserved for JVM 1", - 40: "reserved for JVM 2", - 41: "information Request", -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm.go deleted file mode 100644 index 640e85426..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm.go +++ /dev/null @@ -1,1426 +0,0 @@ -// mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,darwin - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (r int, w int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - r = int(r0) - w = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kill(pid int, signum int, posix int) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exchangedata(path1 string, path2 string, options int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path1) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(path2) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdtablesize() (size int) { - r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) - size = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setprivexec(flag int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Undelete(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int32(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm64.go deleted file mode 100644 index 933f67bbf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ /dev/null @@ -1,1426 +0,0 @@ -// mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm64,darwin - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (r int, w int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - r = int(r0) - w = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kill(pid int, signum int, posix int) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exchangedata(path1 string, path2 string, options int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path1) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(path2) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdtablesize() (size int) { - r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) - size = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setprivexec(flag int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Undelete(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int64(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_386.go deleted file mode 100644 index 32e46af60..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_386.go +++ /dev/null @@ -1,1412 +0,0 @@ -// mksyscall.pl -l32 -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_386.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,dragonfly - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (r int, w int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - r = int(r0) - w = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func extpread(fd int, p []byte, flags int, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EXTPREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EXTPWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdtablesize() (size int) { - r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) - size = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) - newoffset = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Undelete(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go deleted file mode 100644 index 3fa6ff796..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ /dev/null @@ -1,1412 +0,0 @@ -// mksyscall.pl -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,dragonfly - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (r int, w int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - r = int(r0) - w = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func extpread(fd int, p []byte, flags int, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EXTPREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EXTPWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETDIRENTRIES, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdtablesize() (size int) { - r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0) - size = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Undelete(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_386.go deleted file mode 100644 index ff6c39dc2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_386.go +++ /dev/null @@ -1,1628 +0,0 @@ -// mksyscall.pl -l32 syscall_linux.go syscall_linux_386.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe(p *[2]_C_int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fadvise(fd int, offset int64, length int64, advice int) (err error) { - _, _, e1 := Syscall6(SYS_FADVISE64_64, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length), uintptr(length>>32)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit() (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ioperm(from int, num int, on int) (err error) { - _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Iopl(level int) (err error) { - _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID32, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID32, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID32, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID32, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { - _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(n), uintptr(n>>32), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getrlimit(resource int, rlim *rlimit32) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setrlimit(resource int, rlim *rlimit32) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Time(t *Time_t) (tt Time_t, err error) { - r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) - tt = Time_t(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_amd64.go deleted file mode 100644 index c2438522d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ /dev/null @@ -1,1822 +0,0 @@ -// mksyscall.pl syscall_linux.go syscall_linux_amd64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fadvise(fd int, offset int64, length int64, advice int) (err error) { - _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit() (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ioperm(from int, num int, on int) (err error) { - _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Iopl(level int) (err error) { - _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, n int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, buf *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { - _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe(p *[2]_C_int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm.go deleted file mode 100644 index dd66c9758..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ /dev/null @@ -1,1756 +0,0 @@ -// mksyscall.pl -l32 -arm syscall_linux.go syscall_linux_arm.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS32, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, flags int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(flags), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN32, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit() (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN32, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, n int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE64, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS__NEWSELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID32, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID32, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID32, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID32, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID32, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID32, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Time(t *Time_t) (tt Time_t, err error) { - r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) - tt = Time_t(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_TRUNCATE64, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE64, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap2(addr uintptr, length uintptr, prot int, flags int, fd int, pageOffset uintptr) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP2, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(pageOffset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getrlimit(resource int, rlim *rlimit32) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setrlimit(resource int, rlim *rlimit32) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm64.go deleted file mode 100644 index d0a6ed829..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ /dev/null @@ -1,1750 +0,0 @@ -// mksyscall.pl syscall_linux.go syscall_linux_arm64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm64,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, n int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, buf *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { - _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Time(t *Time_t) (tt Time_t, err error) { - r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) - tt = Time_t(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64.go deleted file mode 100644 index f58a3ff2f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ /dev/null @@ -1,1792 +0,0 @@ -// mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build ppc64,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ioperm(from int, num int, on int) (err error) { - _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Iopl(level int) (err error) { - _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, n int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, buf *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { - _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Time(t *Time_t) (tt Time_t, err error) { - r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) - tt = Time_t(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go deleted file mode 100644 index 22fc7a457..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ /dev/null @@ -1,1792 +0,0 @@ -// mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build ppc64le,linux - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func unlinkat(dirfd int, path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getcwd(buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(arg) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(source) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(target) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - use(unsafe.Pointer(_p2)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Acct(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtimex(buf *Timex) (state int, err error) { - r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) - state = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func ClockGettime(clockid int32, time *Timespec) (err error) { - _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup3(oldfd int, newfd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate(size int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCreate1(flag int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - var _p0 unsafe.Pointer - if len(events) > 0 { - _p0 = unsafe.Pointer(&events[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_EPOLL_WAIT, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { - _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(len), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fdatasync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) - tid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getxattr(path string, attr string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(dest) > 0 { - _p2 = unsafe.Pointer(&dest[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(pathname) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) - use(unsafe.Pointer(_p0)) - watchdesc = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyInit1(flags int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { - r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) - success = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Klogctl(typ int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listxattr(path string, dest []byte) (sz int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(dest) > 0 { - _p1 = unsafe.Pointer(&dest[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) - use(unsafe.Pointer(_p0)) - sz = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pause() (err error) { - _, _, e1 := Syscall(SYS_PAUSE, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func PivotRoot(newroot string, putold string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(newroot) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(putold) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { - _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { - _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Removexattr(path string, attr string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setdomainname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sethostname(p []byte) (err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(attr) - if err != nil { - return - } - var _p2 unsafe.Pointer - if len(data) > 0 { - _p2 = unsafe.Pointer(&data[0]) - } else { - _p2 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sysinfo(info *Sysinfo_t) (err error) { - _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { - _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Uname(buf *Utsname) (err error) { - _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unshare(flags int) (err error) { - _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func exitThread(code int) (err error) { - _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, p *byte, np int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Madvise(b []byte, advice int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, buf *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - euid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_UGETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ioperm(from int, num int, on int) (err error) { - _, _, e1 := Syscall(SYS_IOPERM, uintptr(from), uintptr(num), uintptr(on)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Iopl(level int) (err error) { - _, _, e1 := Syscall(SYS_IOPL, uintptr(level), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, n int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE64, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) - written = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsgid(gid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setfsuid(uid int) (err error) { - _, _, e1 := Syscall(SYS_SETFSUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, buf *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func SyncFileRange(fd int, off int64, n int64, flags int) (err error) { - _, _, e1 := Syscall6(SYS_SYNC_FILE_RANGE2, uintptr(fd), uintptr(off), uintptr(n), uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) { - r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flags), uintptr(fd), uintptr(offset)) - xaddr = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Time(t *Time_t) (tt Time_t, err error) { - r0, _, e1 := RawSyscall(SYS_TIME, uintptr(unsafe.Pointer(t)), 0, 0) - tt = Time_t(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_386.go deleted file mode 100644 index 00ca1f9c1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ /dev/null @@ -1,1326 +0,0 @@ -// mksyscall.pl -l32 -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,netbsd - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (fd1 int, fd2 int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - fd1 = int(r0) - fd2 = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) - newoffset = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go deleted file mode 100644 index 03f31b973..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ /dev/null @@ -1,1326 +0,0 @@ -// mksyscall.pl -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,netbsd - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (fd1 int, fd2 int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - fd1 = int(r0) - fd2 = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_arm.go deleted file mode 100644 index 84dc61cfa..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ /dev/null @@ -1,1326 +0,0 @@ -// mksyscall.pl -l32 -arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build arm,netbsd - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe() (fd1 int, fd2 int, err error) { - r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) - fd1 = int(r0) - fd2 = int(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) - newoffset = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_386.go deleted file mode 100644 index 02b3528a6..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ /dev/null @@ -1,1386 +0,0 @@ -// mksyscall.pl -l32 -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build 386,openbsd - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe(p *[2]_C_int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) - newoffset = int64(int64(r1)<<32 | int64(r0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go deleted file mode 100644 index 7dc2b7eaf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ /dev/null @@ -1,1386 +0,0 @@ -// mksyscall.pl -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,openbsd - -package unix - -import ( - "syscall" - "unsafe" -) - -var _ syscall.Errno - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) - wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func utimes(path string, timeval *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func pipe(p *[2]_C_int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func getdents(fd int, buf []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chflags(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) - nfd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) - pgrp = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) - ppid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) - tainted = bool(r0 != 0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func read(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) - } else { - _p1 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Revoke(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setlogin(name string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(name) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Statfs(path string, stat *Statfs_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) - oldmask = int(r0) - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Unmount(path string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func write(fd int, p []byte) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) - ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_solaris_amd64.go deleted file mode 100644 index 8d2a8365b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ /dev/null @@ -1,1559 +0,0 @@ -// mksyscall_solaris.pl syscall_solaris.go syscall_solaris_amd64.go -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT - -// +build amd64,solaris - -package unix - -import ( - "syscall" - "unsafe" -) - -//go:cgo_import_dynamic libc_getsockname getsockname "libsocket.so" -//go:cgo_import_dynamic libc_getcwd getcwd "libc.so" -//go:cgo_import_dynamic libc_getgroups getgroups "libc.so" -//go:cgo_import_dynamic libc_setgroups setgroups "libc.so" -//go:cgo_import_dynamic libc_utimes utimes "libc.so" -//go:cgo_import_dynamic libc_utimensat utimensat "libc.so" -//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" -//go:cgo_import_dynamic libc_futimesat futimesat "libc.so" -//go:cgo_import_dynamic libc_accept accept "libsocket.so" -//go:cgo_import_dynamic libc_recvmsg recvmsg "libsocket.so" -//go:cgo_import_dynamic libc_sendmsg sendmsg "libsocket.so" -//go:cgo_import_dynamic libc_acct acct "libc.so" -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" -//go:cgo_import_dynamic libc_access access "libc.so" -//go:cgo_import_dynamic libc_adjtime adjtime "libc.so" -//go:cgo_import_dynamic libc_chdir chdir "libc.so" -//go:cgo_import_dynamic libc_chmod chmod "libc.so" -//go:cgo_import_dynamic libc_chown chown "libc.so" -//go:cgo_import_dynamic libc_chroot chroot "libc.so" -//go:cgo_import_dynamic libc_close close "libc.so" -//go:cgo_import_dynamic libc_creat creat "libc.so" -//go:cgo_import_dynamic libc_dup dup "libc.so" -//go:cgo_import_dynamic libc_dup2 dup2 "libc.so" -//go:cgo_import_dynamic libc_exit exit "libc.so" -//go:cgo_import_dynamic libc_fchdir fchdir "libc.so" -//go:cgo_import_dynamic libc_fchmod fchmod "libc.so" -//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" -//go:cgo_import_dynamic libc_fchown fchown "libc.so" -//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" -//go:cgo_import_dynamic libc_fdatasync fdatasync "libc.so" -//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" -//go:cgo_import_dynamic libc_fstat fstat "libc.so" -//go:cgo_import_dynamic libc_getdents getdents "libc.so" -//go:cgo_import_dynamic libc_getgid getgid "libc.so" -//go:cgo_import_dynamic libc_getpid getpid "libc.so" -//go:cgo_import_dynamic libc_getpgid getpgid "libc.so" -//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" -//go:cgo_import_dynamic libc_geteuid geteuid "libc.so" -//go:cgo_import_dynamic libc_getegid getegid "libc.so" -//go:cgo_import_dynamic libc_getppid getppid "libc.so" -//go:cgo_import_dynamic libc_getpriority getpriority "libc.so" -//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" -//go:cgo_import_dynamic libc_getrusage getrusage "libc.so" -//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" -//go:cgo_import_dynamic libc_getuid getuid "libc.so" -//go:cgo_import_dynamic libc_kill kill "libc.so" -//go:cgo_import_dynamic libc_lchown lchown "libc.so" -//go:cgo_import_dynamic libc_link link "libc.so" -//go:cgo_import_dynamic libc_listen listen "libsocket.so" -//go:cgo_import_dynamic libc_lstat lstat "libc.so" -//go:cgo_import_dynamic libc_madvise madvise "libc.so" -//go:cgo_import_dynamic libc_mkdir mkdir "libc.so" -//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" -//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" -//go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" -//go:cgo_import_dynamic libc_mknod mknod "libc.so" -//go:cgo_import_dynamic libc_mknodat mknodat "libc.so" -//go:cgo_import_dynamic libc_mlock mlock "libc.so" -//go:cgo_import_dynamic libc_mlockall mlockall "libc.so" -//go:cgo_import_dynamic libc_mprotect mprotect "libc.so" -//go:cgo_import_dynamic libc_munlock munlock "libc.so" -//go:cgo_import_dynamic libc_munlockall munlockall "libc.so" -//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" -//go:cgo_import_dynamic libc_open open "libc.so" -//go:cgo_import_dynamic libc_openat openat "libc.so" -//go:cgo_import_dynamic libc_pathconf pathconf "libc.so" -//go:cgo_import_dynamic libc_pause pause "libc.so" -//go:cgo_import_dynamic libc_pread pread "libc.so" -//go:cgo_import_dynamic libc_pwrite pwrite "libc.so" -//go:cgo_import_dynamic libc_read read "libc.so" -//go:cgo_import_dynamic libc_readlink readlink "libc.so" -//go:cgo_import_dynamic libc_rename rename "libc.so" -//go:cgo_import_dynamic libc_renameat renameat "libc.so" -//go:cgo_import_dynamic libc_rmdir rmdir "libc.so" -//go:cgo_import_dynamic libc_lseek lseek "libc.so" -//go:cgo_import_dynamic libc_setegid setegid "libc.so" -//go:cgo_import_dynamic libc_seteuid seteuid "libc.so" -//go:cgo_import_dynamic libc_setgid setgid "libc.so" -//go:cgo_import_dynamic libc_sethostname sethostname "libc.so" -//go:cgo_import_dynamic libc_setpgid setpgid "libc.so" -//go:cgo_import_dynamic libc_setpriority setpriority "libc.so" -//go:cgo_import_dynamic libc_setregid setregid "libc.so" -//go:cgo_import_dynamic libc_setreuid setreuid "libc.so" -//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" -//go:cgo_import_dynamic libc_setsid setsid "libc.so" -//go:cgo_import_dynamic libc_setuid setuid "libc.so" -//go:cgo_import_dynamic libc_shutdown shutdown "libsocket.so" -//go:cgo_import_dynamic libc_stat stat "libc.so" -//go:cgo_import_dynamic libc_symlink symlink "libc.so" -//go:cgo_import_dynamic libc_sync sync "libc.so" -//go:cgo_import_dynamic libc_times times "libc.so" -//go:cgo_import_dynamic libc_truncate truncate "libc.so" -//go:cgo_import_dynamic libc_fsync fsync "libc.so" -//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" -//go:cgo_import_dynamic libc_umask umask "libc.so" -//go:cgo_import_dynamic libc_uname uname "libc.so" -//go:cgo_import_dynamic libc_umount umount "libc.so" -//go:cgo_import_dynamic libc_unlink unlink "libc.so" -//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" -//go:cgo_import_dynamic libc_ustat ustat "libc.so" -//go:cgo_import_dynamic libc_utime utime "libc.so" -//go:cgo_import_dynamic libc_bind bind "libsocket.so" -//go:cgo_import_dynamic libc_connect connect "libsocket.so" -//go:cgo_import_dynamic libc_mmap mmap "libc.so" -//go:cgo_import_dynamic libc_munmap munmap "libc.so" -//go:cgo_import_dynamic libc_sendto sendto "libsocket.so" -//go:cgo_import_dynamic libc_socket socket "libsocket.so" -//go:cgo_import_dynamic libc_socketpair socketpair "libsocket.so" -//go:cgo_import_dynamic libc_write write "libc.so" -//go:cgo_import_dynamic libc_getsockopt getsockopt "libsocket.so" -//go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so" -//go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" -//go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so" -//go:cgo_import_dynamic libc_sysconf sysconf "libc.so" - -//go:linkname procgetsockname libc_getsockname -//go:linkname procGetcwd libc_getcwd -//go:linkname procgetgroups libc_getgroups -//go:linkname procsetgroups libc_setgroups -//go:linkname procutimes libc_utimes -//go:linkname procutimensat libc_utimensat -//go:linkname procfcntl libc_fcntl -//go:linkname procfutimesat libc_futimesat -//go:linkname procaccept libc_accept -//go:linkname procrecvmsg libc_recvmsg -//go:linkname procsendmsg libc_sendmsg -//go:linkname procacct libc_acct -//go:linkname procioctl libc_ioctl -//go:linkname procAccess libc_access -//go:linkname procAdjtime libc_adjtime -//go:linkname procChdir libc_chdir -//go:linkname procChmod libc_chmod -//go:linkname procChown libc_chown -//go:linkname procChroot libc_chroot -//go:linkname procClose libc_close -//go:linkname procCreat libc_creat -//go:linkname procDup libc_dup -//go:linkname procDup2 libc_dup2 -//go:linkname procExit libc_exit -//go:linkname procFchdir libc_fchdir -//go:linkname procFchmod libc_fchmod -//go:linkname procFchmodat libc_fchmodat -//go:linkname procFchown libc_fchown -//go:linkname procFchownat libc_fchownat -//go:linkname procFdatasync libc_fdatasync -//go:linkname procFpathconf libc_fpathconf -//go:linkname procFstat libc_fstat -//go:linkname procGetdents libc_getdents -//go:linkname procGetgid libc_getgid -//go:linkname procGetpid libc_getpid -//go:linkname procGetpgid libc_getpgid -//go:linkname procGetpgrp libc_getpgrp -//go:linkname procGeteuid libc_geteuid -//go:linkname procGetegid libc_getegid -//go:linkname procGetppid libc_getppid -//go:linkname procGetpriority libc_getpriority -//go:linkname procGetrlimit libc_getrlimit -//go:linkname procGetrusage libc_getrusage -//go:linkname procGettimeofday libc_gettimeofday -//go:linkname procGetuid libc_getuid -//go:linkname procKill libc_kill -//go:linkname procLchown libc_lchown -//go:linkname procLink libc_link -//go:linkname proclisten libc_listen -//go:linkname procLstat libc_lstat -//go:linkname procMadvise libc_madvise -//go:linkname procMkdir libc_mkdir -//go:linkname procMkdirat libc_mkdirat -//go:linkname procMkfifo libc_mkfifo -//go:linkname procMkfifoat libc_mkfifoat -//go:linkname procMknod libc_mknod -//go:linkname procMknodat libc_mknodat -//go:linkname procMlock libc_mlock -//go:linkname procMlockall libc_mlockall -//go:linkname procMprotect libc_mprotect -//go:linkname procMunlock libc_munlock -//go:linkname procMunlockall libc_munlockall -//go:linkname procNanosleep libc_nanosleep -//go:linkname procOpen libc_open -//go:linkname procOpenat libc_openat -//go:linkname procPathconf libc_pathconf -//go:linkname procPause libc_pause -//go:linkname procPread libc_pread -//go:linkname procPwrite libc_pwrite -//go:linkname procread libc_read -//go:linkname procReadlink libc_readlink -//go:linkname procRename libc_rename -//go:linkname procRenameat libc_renameat -//go:linkname procRmdir libc_rmdir -//go:linkname proclseek libc_lseek -//go:linkname procSetegid libc_setegid -//go:linkname procSeteuid libc_seteuid -//go:linkname procSetgid libc_setgid -//go:linkname procSethostname libc_sethostname -//go:linkname procSetpgid libc_setpgid -//go:linkname procSetpriority libc_setpriority -//go:linkname procSetregid libc_setregid -//go:linkname procSetreuid libc_setreuid -//go:linkname procSetrlimit libc_setrlimit -//go:linkname procSetsid libc_setsid -//go:linkname procSetuid libc_setuid -//go:linkname procshutdown libc_shutdown -//go:linkname procStat libc_stat -//go:linkname procSymlink libc_symlink -//go:linkname procSync libc_sync -//go:linkname procTimes libc_times -//go:linkname procTruncate libc_truncate -//go:linkname procFsync libc_fsync -//go:linkname procFtruncate libc_ftruncate -//go:linkname procUmask libc_umask -//go:linkname procUname libc_uname -//go:linkname procumount libc_umount -//go:linkname procUnlink libc_unlink -//go:linkname procUnlinkat libc_unlinkat -//go:linkname procUstat libc_ustat -//go:linkname procUtime libc_utime -//go:linkname procbind libc_bind -//go:linkname procconnect libc_connect -//go:linkname procmmap libc_mmap -//go:linkname procmunmap libc_munmap -//go:linkname procsendto libc_sendto -//go:linkname procsocket libc_socket -//go:linkname procsocketpair libc_socketpair -//go:linkname procwrite libc_write -//go:linkname procgetsockopt libc_getsockopt -//go:linkname procgetpeername libc_getpeername -//go:linkname procsetsockopt libc_setsockopt -//go:linkname procrecvfrom libc_recvfrom -//go:linkname procsysconf libc_sysconf - -var ( - procgetsockname, - procGetcwd, - procgetgroups, - procsetgroups, - procutimes, - procutimensat, - procfcntl, - procfutimesat, - procaccept, - procrecvmsg, - procsendmsg, - procacct, - procioctl, - procAccess, - procAdjtime, - procChdir, - procChmod, - procChown, - procChroot, - procClose, - procCreat, - procDup, - procDup2, - procExit, - procFchdir, - procFchmod, - procFchmodat, - procFchown, - procFchownat, - procFdatasync, - procFpathconf, - procFstat, - procGetdents, - procGetgid, - procGetpid, - procGetpgid, - procGetpgrp, - procGeteuid, - procGetegid, - procGetppid, - procGetpriority, - procGetrlimit, - procGetrusage, - procGettimeofday, - procGetuid, - procKill, - procLchown, - procLink, - proclisten, - procLstat, - procMadvise, - procMkdir, - procMkdirat, - procMkfifo, - procMkfifoat, - procMknod, - procMknodat, - procMlock, - procMlockall, - procMprotect, - procMunlock, - procMunlockall, - procNanosleep, - procOpen, - procOpenat, - procPathconf, - procPause, - procPread, - procPwrite, - procread, - procReadlink, - procRename, - procRenameat, - procRmdir, - proclseek, - procSetegid, - procSeteuid, - procSetgid, - procSethostname, - procSetpgid, - procSetpriority, - procSetregid, - procSetreuid, - procSetrlimit, - procSetsid, - procSetuid, - procshutdown, - procStat, - procSymlink, - procSync, - procTimes, - procTruncate, - procFsync, - procFtruncate, - procUmask, - procUname, - procumount, - procUnlink, - procUnlinkat, - procUstat, - procUtime, - procbind, - procconnect, - procmmap, - procmunmap, - procsendto, - procsocket, - procsocketpair, - procwrite, - procgetsockopt, - procgetpeername, - procsetsockopt, - procrecvfrom, - procsysconf syscallFunc -) - -func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockname)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Getcwd(buf []byte) (n int, err error) { - var _p0 *byte - if len(buf) > 0 { - _p0 = &buf[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetcwd)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func utimes(path string, times *[2]Timeval) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimes)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimensat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) - val = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func futimesat(fildes int, path *byte, times *[2]Timeval) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfutimesat)), 3, uintptr(fildes), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times)), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept)), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsendmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func acct(path *byte) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procacct)), 1, uintptr(unsafe.Pointer(path)), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func ioctl(fd int, req int, arg uintptr) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Access(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAccess)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAdjtime)), 2, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Chdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Chmod(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChmod)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Chown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Chroot(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChroot)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Close(fd int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClose)), 1, uintptr(fd), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Creat(path string, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procCreat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Dup(fd int) (nfd int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup)), 1, uintptr(fd), 0, 0, 0, 0, 0) - nfd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup2)), 2, uintptr(oldfd), uintptr(newfd), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Exit(code int) { - sysvicall6(uintptr(unsafe.Pointer(&procExit)), 1, uintptr(code), 0, 0, 0, 0, 0) - return -} - -func Fchdir(fd int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchdir)), 1, uintptr(fd), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmod)), 2, uintptr(fd), uintptr(mode), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchownat)), 5, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Fdatasync(fd int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFdatasync)), 1, uintptr(fd), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFpathconf)), 2, uintptr(fd), uintptr(name), 0, 0, 0, 0) - val = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstat)), 2, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) { - var _p0 *byte - if len(buf) > 0 { - _p0 = &buf[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetdents)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Getgid() (gid int) { - r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetgid)), 0, 0, 0, 0, 0, 0, 0) - gid = int(r0) - return -} - -func Getpid() (pid int) { - r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpid)), 0, 0, 0, 0, 0, 0, 0) - pid = int(r0) - return -} - -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgid)), 1, uintptr(pid), 0, 0, 0, 0, 0) - pgid = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Getpgrp() (pgid int, err error) { - r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgrp)), 0, 0, 0, 0, 0, 0, 0) - pgid = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Geteuid() (euid int) { - r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGeteuid)), 0, 0, 0, 0, 0, 0, 0) - euid = int(r0) - return -} - -func Getegid() (egid int) { - r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetegid)), 0, 0, 0, 0, 0, 0, 0) - egid = int(r0) - return -} - -func Getppid() (ppid int) { - r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procGetppid)), 0, 0, 0, 0, 0, 0, 0) - ppid = int(r0) - return -} - -func Getpriority(which int, who int) (n int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetpriority)), 2, uintptr(which), uintptr(who), 0, 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrusage)), 2, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGettimeofday)), 1, uintptr(unsafe.Pointer(tv)), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Getuid() (uid int) { - r0, _, _ := rawSysvicall6(uintptr(unsafe.Pointer(&procGetuid)), 0, 0, 0, 0, 0, 0, 0) - uid = int(r0) - return -} - -func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procKill)), 2, uintptr(pid), uintptr(signum), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Lchown(path string, uid int, gid int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLchown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Link(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = e1 - } - return -} - -func Listen(s int, backlog int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclisten)), 2, uintptr(s), uintptr(backlog), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Lstat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLstat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Madvise(b []byte, advice int) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMadvise)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(advice), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdir)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mkdirat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mkfifo(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifo)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mkfifoat(dirfd int, path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifoat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknod)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Mlock(b []byte) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Mlockall(flags int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlockall)), 1, uintptr(flags), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Mprotect(b []byte, prot int) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMprotect)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(prot), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Munlock(b []byte) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Munlockall() (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlockall)), 0, 0, 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procNanosleep)), 2, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Open(path string, mode int, perm uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpen)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpenat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) - use(unsafe.Pointer(_p0)) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Pathconf(path string, name int) (val int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPathconf)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - val = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Pause() (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPause)), 0, 0, 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPwrite)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func read(fd int, p []byte) (n int, err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - if len(buf) > 0 { - _p1 = &buf[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procReadlink)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(len(buf)), 0, 0, 0) - use(unsafe.Pointer(_p0)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRename)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = e1 - } - return -} - -func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(oldpath) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(newpath) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRenameat)), 4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = e1 - } - return -} - -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRmdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclseek)), 3, uintptr(fd), uintptr(offset), uintptr(whence), 0, 0, 0) - newoffset = int64(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Setegid(egid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Seteuid(euid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSeteuid)), 1, uintptr(euid), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setgid(gid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetgid)), 1, uintptr(gid), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Sethostname(p []byte) (err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetpgid)), 2, uintptr(pid), uintptr(pgid), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSetpriority)), 3, uintptr(which), uintptr(who), uintptr(prio), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setregid(rgid int, egid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetreuid)), 2, uintptr(ruid), uintptr(euid), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Setsid() (pid int, err error) { - r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetsid)), 0, 0, 0, 0, 0, 0, 0) - pid = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Setuid(uid int) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetuid)), 1, uintptr(uid), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Shutdown(s int, how int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procshutdown)), 2, uintptr(s), uintptr(how), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Symlink(path string, link string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(link) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSymlink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - use(unsafe.Pointer(_p1)) - if e1 != 0 { - err = e1 - } - return -} - -func Sync() (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSync)), 0, 0, 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procTimes)), 1, uintptr(unsafe.Pointer(tms)), 0, 0, 0, 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = e1 - } - return -} - -func Truncate(path string, length int64) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procTruncate)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Fsync(fd int) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFsync)), 1, uintptr(fd), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFtruncate)), 2, uintptr(fd), uintptr(length), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Umask(mask int) (oldmask int) { - r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procUmask)), 1, uintptr(mask), 0, 0, 0, 0, 0) - oldmask = int(r0) - return -} - -func Uname(buf *Utsname) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Unmount(target string, flags int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(target) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procumount)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Unlink(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlink)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Unlinkat(dirfd int, path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func Ustat(dev int, ubuf *Ustat_t) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUstat)), 2, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func Utime(path string, buf *Utimbuf) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUtime)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0) - use(unsafe.Pointer(_p0)) - if e1 != 0 { - err = e1 - } - return -} - -func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procbind)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procconnect)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmmap)), 6, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) - ret = uintptr(r0) - if e1 != 0 { - err = e1 - } - return -} - -func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmunmap)), 2, uintptr(addr), uintptr(length), 0, 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { - var _p0 *byte - if len(buf) > 0 { - _p0 = &buf[0] - } - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsendto)), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = e1 - } - return -} - -func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsocket)), 3, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) - fd = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsocketpair)), 4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func write(fd int, p []byte) (n int, err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = e1 - } - return -} - -func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetpeername)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) - if e1 != 0 { - err = e1 - } - return -} - -func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = e1 - } - return -} - -func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { - var _p0 *byte - if len(p) > 0 { - _p0 = &p[0] - } - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvfrom)), 6, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) - n = int(r0) - if e1 != 0 { - err = e1 - } - return -} - -func sysconf(name int) (n int64, err error) { - r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsysconf)), 1, uintptr(name), 0, 0, 0, 0, 0) - n = int64(r0) - if e1 != 0 { - err = e1 - } - return -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysctl_openbsd.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysctl_openbsd.go deleted file mode 100644 index 83bb935b9..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysctl_openbsd.go +++ /dev/null @@ -1,270 +0,0 @@ -// mksysctl_openbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -package unix - -type mibentry struct { - ctlname string - ctloid []_C_int -} - -var sysctlMib = []mibentry{ - {"ddb.console", []_C_int{9, 6}}, - {"ddb.log", []_C_int{9, 7}}, - {"ddb.max_line", []_C_int{9, 3}}, - {"ddb.max_width", []_C_int{9, 2}}, - {"ddb.panic", []_C_int{9, 5}}, - {"ddb.radix", []_C_int{9, 1}}, - {"ddb.tab_stop_width", []_C_int{9, 4}}, - {"ddb.trigger", []_C_int{9, 8}}, - {"fs.posix.setuid", []_C_int{3, 1, 1}}, - {"hw.allowpowerdown", []_C_int{6, 22}}, - {"hw.byteorder", []_C_int{6, 4}}, - {"hw.cpuspeed", []_C_int{6, 12}}, - {"hw.diskcount", []_C_int{6, 10}}, - {"hw.disknames", []_C_int{6, 8}}, - {"hw.diskstats", []_C_int{6, 9}}, - {"hw.machine", []_C_int{6, 1}}, - {"hw.model", []_C_int{6, 2}}, - {"hw.ncpu", []_C_int{6, 3}}, - {"hw.ncpufound", []_C_int{6, 21}}, - {"hw.pagesize", []_C_int{6, 7}}, - {"hw.physmem", []_C_int{6, 19}}, - {"hw.product", []_C_int{6, 15}}, - {"hw.serialno", []_C_int{6, 17}}, - {"hw.setperf", []_C_int{6, 13}}, - {"hw.usermem", []_C_int{6, 20}}, - {"hw.uuid", []_C_int{6, 18}}, - {"hw.vendor", []_C_int{6, 14}}, - {"hw.version", []_C_int{6, 16}}, - {"kern.arandom", []_C_int{1, 37}}, - {"kern.argmax", []_C_int{1, 8}}, - {"kern.boottime", []_C_int{1, 21}}, - {"kern.bufcachepercent", []_C_int{1, 72}}, - {"kern.ccpu", []_C_int{1, 45}}, - {"kern.clockrate", []_C_int{1, 12}}, - {"kern.consdev", []_C_int{1, 75}}, - {"kern.cp_time", []_C_int{1, 40}}, - {"kern.cp_time2", []_C_int{1, 71}}, - {"kern.cryptodevallowsoft", []_C_int{1, 53}}, - {"kern.domainname", []_C_int{1, 22}}, - {"kern.file", []_C_int{1, 73}}, - {"kern.forkstat", []_C_int{1, 42}}, - {"kern.fscale", []_C_int{1, 46}}, - {"kern.fsync", []_C_int{1, 33}}, - {"kern.hostid", []_C_int{1, 11}}, - {"kern.hostname", []_C_int{1, 10}}, - {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}}, - {"kern.job_control", []_C_int{1, 19}}, - {"kern.malloc.buckets", []_C_int{1, 39, 1}}, - {"kern.malloc.kmemnames", []_C_int{1, 39, 3}}, - {"kern.maxclusters", []_C_int{1, 67}}, - {"kern.maxfiles", []_C_int{1, 7}}, - {"kern.maxlocksperuid", []_C_int{1, 70}}, - {"kern.maxpartitions", []_C_int{1, 23}}, - {"kern.maxproc", []_C_int{1, 6}}, - {"kern.maxthread", []_C_int{1, 25}}, - {"kern.maxvnodes", []_C_int{1, 5}}, - {"kern.mbstat", []_C_int{1, 59}}, - {"kern.msgbuf", []_C_int{1, 48}}, - {"kern.msgbufsize", []_C_int{1, 38}}, - {"kern.nchstats", []_C_int{1, 41}}, - {"kern.netlivelocks", []_C_int{1, 76}}, - {"kern.nfiles", []_C_int{1, 56}}, - {"kern.ngroups", []_C_int{1, 18}}, - {"kern.nosuidcoredump", []_C_int{1, 32}}, - {"kern.nprocs", []_C_int{1, 47}}, - {"kern.nselcoll", []_C_int{1, 43}}, - {"kern.nthreads", []_C_int{1, 26}}, - {"kern.numvnodes", []_C_int{1, 58}}, - {"kern.osrelease", []_C_int{1, 2}}, - {"kern.osrevision", []_C_int{1, 3}}, - {"kern.ostype", []_C_int{1, 1}}, - {"kern.osversion", []_C_int{1, 27}}, - {"kern.pool_debug", []_C_int{1, 77}}, - {"kern.posix1version", []_C_int{1, 17}}, - {"kern.proc", []_C_int{1, 66}}, - {"kern.random", []_C_int{1, 31}}, - {"kern.rawpartition", []_C_int{1, 24}}, - {"kern.saved_ids", []_C_int{1, 20}}, - {"kern.securelevel", []_C_int{1, 9}}, - {"kern.seminfo", []_C_int{1, 61}}, - {"kern.shminfo", []_C_int{1, 62}}, - {"kern.somaxconn", []_C_int{1, 28}}, - {"kern.sominconn", []_C_int{1, 29}}, - {"kern.splassert", []_C_int{1, 54}}, - {"kern.stackgap_random", []_C_int{1, 50}}, - {"kern.sysvipc_info", []_C_int{1, 51}}, - {"kern.sysvmsg", []_C_int{1, 34}}, - {"kern.sysvsem", []_C_int{1, 35}}, - {"kern.sysvshm", []_C_int{1, 36}}, - {"kern.timecounter.choice", []_C_int{1, 69, 4}}, - {"kern.timecounter.hardware", []_C_int{1, 69, 3}}, - {"kern.timecounter.tick", []_C_int{1, 69, 1}}, - {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}}, - {"kern.tty.maxptys", []_C_int{1, 44, 6}}, - {"kern.tty.nptys", []_C_int{1, 44, 7}}, - {"kern.tty.tk_cancc", []_C_int{1, 44, 4}}, - {"kern.tty.tk_nin", []_C_int{1, 44, 1}}, - {"kern.tty.tk_nout", []_C_int{1, 44, 2}}, - {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}}, - {"kern.tty.ttyinfo", []_C_int{1, 44, 5}}, - {"kern.ttycount", []_C_int{1, 57}}, - {"kern.userasymcrypto", []_C_int{1, 60}}, - {"kern.usercrypto", []_C_int{1, 52}}, - {"kern.usermount", []_C_int{1, 30}}, - {"kern.version", []_C_int{1, 4}}, - {"kern.vnode", []_C_int{1, 13}}, - {"kern.watchdog.auto", []_C_int{1, 64, 2}}, - {"kern.watchdog.period", []_C_int{1, 64, 1}}, - {"net.bpf.bufsize", []_C_int{4, 31, 1}}, - {"net.bpf.maxbufsize", []_C_int{4, 31, 2}}, - {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}}, - {"net.inet.ah.stats", []_C_int{4, 2, 51, 2}}, - {"net.inet.carp.allow", []_C_int{4, 2, 112, 1}}, - {"net.inet.carp.log", []_C_int{4, 2, 112, 3}}, - {"net.inet.carp.preempt", []_C_int{4, 2, 112, 2}}, - {"net.inet.carp.stats", []_C_int{4, 2, 112, 4}}, - {"net.inet.divert.recvspace", []_C_int{4, 2, 258, 1}}, - {"net.inet.divert.sendspace", []_C_int{4, 2, 258, 2}}, - {"net.inet.divert.stats", []_C_int{4, 2, 258, 3}}, - {"net.inet.esp.enable", []_C_int{4, 2, 50, 1}}, - {"net.inet.esp.stats", []_C_int{4, 2, 50, 4}}, - {"net.inet.esp.udpencap", []_C_int{4, 2, 50, 2}}, - {"net.inet.esp.udpencap_port", []_C_int{4, 2, 50, 3}}, - {"net.inet.etherip.allow", []_C_int{4, 2, 97, 1}}, - {"net.inet.etherip.stats", []_C_int{4, 2, 97, 2}}, - {"net.inet.gre.allow", []_C_int{4, 2, 47, 1}}, - {"net.inet.gre.wccp", []_C_int{4, 2, 47, 2}}, - {"net.inet.icmp.bmcastecho", []_C_int{4, 2, 1, 2}}, - {"net.inet.icmp.errppslimit", []_C_int{4, 2, 1, 3}}, - {"net.inet.icmp.maskrepl", []_C_int{4, 2, 1, 1}}, - {"net.inet.icmp.rediraccept", []_C_int{4, 2, 1, 4}}, - {"net.inet.icmp.redirtimeout", []_C_int{4, 2, 1, 5}}, - {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}}, - {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}}, - {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}}, - {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}}, - {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}}, - {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}}, - {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}}, - {"net.inet.ip.ifq.drops", []_C_int{4, 2, 0, 30, 3}}, - {"net.inet.ip.ifq.len", []_C_int{4, 2, 0, 30, 1}}, - {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}}, - {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}}, - {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}}, - {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}}, - {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}}, - {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}}, - {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}}, - {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}}, - {"net.inet.ip.multipath", []_C_int{4, 2, 0, 32}}, - {"net.inet.ip.portfirst", []_C_int{4, 2, 0, 7}}, - {"net.inet.ip.porthifirst", []_C_int{4, 2, 0, 9}}, - {"net.inet.ip.porthilast", []_C_int{4, 2, 0, 10}}, - {"net.inet.ip.portlast", []_C_int{4, 2, 0, 8}}, - {"net.inet.ip.redirect", []_C_int{4, 2, 0, 2}}, - {"net.inet.ip.sourceroute", []_C_int{4, 2, 0, 5}}, - {"net.inet.ip.stats", []_C_int{4, 2, 0, 33}}, - {"net.inet.ip.ttl", []_C_int{4, 2, 0, 3}}, - {"net.inet.ipcomp.enable", []_C_int{4, 2, 108, 1}}, - {"net.inet.ipcomp.stats", []_C_int{4, 2, 108, 2}}, - {"net.inet.ipip.allow", []_C_int{4, 2, 4, 1}}, - {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}}, - {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}}, - {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}}, - {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}}, - {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}}, - {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}}, - {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}}, - {"net.inet.tcp.drop", []_C_int{4, 2, 6, 19}}, - {"net.inet.tcp.ecn", []_C_int{4, 2, 6, 14}}, - {"net.inet.tcp.ident", []_C_int{4, 2, 6, 9}}, - {"net.inet.tcp.keepidle", []_C_int{4, 2, 6, 3}}, - {"net.inet.tcp.keepinittime", []_C_int{4, 2, 6, 2}}, - {"net.inet.tcp.keepintvl", []_C_int{4, 2, 6, 4}}, - {"net.inet.tcp.mssdflt", []_C_int{4, 2, 6, 11}}, - {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}}, - {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}}, - {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}}, - {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}}, - {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}}, - {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}}, - {"net.inet.tcp.slowhz", []_C_int{4, 2, 6, 5}}, - {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}}, - {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}}, - {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}}, - {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}}, - {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}}, - {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}}, - {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}}, - {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}}, - {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}}, - {"net.inet6.divert.sendspace", []_C_int{4, 24, 86, 2}}, - {"net.inet6.divert.stats", []_C_int{4, 24, 86, 3}}, - {"net.inet6.icmp6.errppslimit", []_C_int{4, 24, 30, 14}}, - {"net.inet6.icmp6.mtudisc_hiwat", []_C_int{4, 24, 30, 16}}, - {"net.inet6.icmp6.mtudisc_lowat", []_C_int{4, 24, 30, 17}}, - {"net.inet6.icmp6.nd6_debug", []_C_int{4, 24, 30, 18}}, - {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}}, - {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}}, - {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}}, - {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}}, - {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}}, - {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}}, - {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}}, - {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}}, - {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}}, - {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}}, - {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}}, - {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}}, - {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}}, - {"net.inet6.ip6.defmcasthlim", []_C_int{4, 24, 17, 18}}, - {"net.inet6.ip6.forwarding", []_C_int{4, 24, 17, 1}}, - {"net.inet6.ip6.forwsrcrt", []_C_int{4, 24, 17, 5}}, - {"net.inet6.ip6.hdrnestlimit", []_C_int{4, 24, 17, 15}}, - {"net.inet6.ip6.hlim", []_C_int{4, 24, 17, 3}}, - {"net.inet6.ip6.log_interval", []_C_int{4, 24, 17, 14}}, - {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}}, - {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}}, - {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}}, - {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}}, - {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}}, - {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}}, - {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}}, - {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}}, - {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}}, - {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}}, - {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}}, - {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}}, - {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}}, - {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}}, - {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}}, - {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}}, - {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}}, - {"net.key.sadb_dump", []_C_int{4, 30, 1}}, - {"net.key.spd_dump", []_C_int{4, 30, 2}}, - {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}}, - {"net.mpls.ifq.drops", []_C_int{4, 33, 3, 3}}, - {"net.mpls.ifq.len", []_C_int{4, 33, 3, 1}}, - {"net.mpls.ifq.maxlen", []_C_int{4, 33, 3, 2}}, - {"net.mpls.mapttl_ip", []_C_int{4, 33, 5}}, - {"net.mpls.mapttl_ip6", []_C_int{4, 33, 6}}, - {"net.mpls.maxloop_inkernel", []_C_int{4, 33, 4}}, - {"net.mpls.ttl", []_C_int{4, 33, 2}}, - {"net.pflow.stats", []_C_int{4, 34, 1}}, - {"net.pipex.enable", []_C_int{4, 35, 1}}, - {"vm.anonmin", []_C_int{2, 7}}, - {"vm.loadavg", []_C_int{2, 2}}, - {"vm.maxslp", []_C_int{2, 10}}, - {"vm.nkmempages", []_C_int{2, 6}}, - {"vm.psstrings", []_C_int{2, 3}}, - {"vm.swapencrypt.enable", []_C_int{2, 5, 0}}, - {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}}, - {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}}, - {"vm.uspace", []_C_int{2, 11}}, - {"vm.uvmexp", []_C_int{2, 4}}, - {"vm.vmmeter", []_C_int{2, 1}}, - {"vm.vnodemin", []_C_int{2, 9}}, - {"vm.vtextmin", []_C_int{2, 8}}, -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_386.go deleted file mode 100644 index 2786773ba..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_386.go +++ /dev/null @@ -1,398 +0,0 @@ -// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,darwin - -package unix - -const ( - SYS_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAIT4 = 7 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_CHDIR = 12 - SYS_FCHDIR = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_CHOWN = 16 - SYS_GETFSSTAT = 18 - SYS_GETPID = 20 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_GETEUID = 25 - SYS_PTRACE = 26 - SYS_RECVMSG = 27 - SYS_SENDMSG = 28 - SYS_RECVFROM = 29 - SYS_ACCEPT = 30 - SYS_GETPEERNAME = 31 - SYS_GETSOCKNAME = 32 - SYS_ACCESS = 33 - SYS_CHFLAGS = 34 - SYS_FCHFLAGS = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_GETPPID = 39 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_GETEGID = 43 - SYS_SIGACTION = 46 - SYS_GETGID = 47 - SYS_SIGPROCMASK = 48 - SYS_GETLOGIN = 49 - SYS_SETLOGIN = 50 - SYS_ACCT = 51 - SYS_SIGPENDING = 52 - SYS_SIGALTSTACK = 53 - SYS_IOCTL = 54 - SYS_REBOOT = 55 - SYS_REVOKE = 56 - SYS_SYMLINK = 57 - SYS_READLINK = 58 - SYS_EXECVE = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_MSYNC = 65 - SYS_VFORK = 66 - SYS_MUNMAP = 73 - SYS_MPROTECT = 74 - SYS_MADVISE = 75 - SYS_MINCORE = 78 - SYS_GETGROUPS = 79 - SYS_SETGROUPS = 80 - SYS_GETPGRP = 81 - SYS_SETPGID = 82 - SYS_SETITIMER = 83 - SYS_SWAPON = 85 - SYS_GETITIMER = 86 - SYS_GETDTABLESIZE = 89 - SYS_DUP2 = 90 - SYS_FCNTL = 92 - SYS_SELECT = 93 - SYS_FSYNC = 95 - SYS_SETPRIORITY = 96 - SYS_SOCKET = 97 - SYS_CONNECT = 98 - SYS_GETPRIORITY = 100 - SYS_BIND = 104 - SYS_SETSOCKOPT = 105 - SYS_LISTEN = 106 - SYS_SIGSUSPEND = 111 - SYS_GETTIMEOFDAY = 116 - SYS_GETRUSAGE = 117 - SYS_GETSOCKOPT = 118 - SYS_READV = 120 - SYS_WRITEV = 121 - SYS_SETTIMEOFDAY = 122 - SYS_FCHOWN = 123 - SYS_FCHMOD = 124 - SYS_SETREUID = 126 - SYS_SETREGID = 127 - SYS_RENAME = 128 - SYS_FLOCK = 131 - SYS_MKFIFO = 132 - SYS_SENDTO = 133 - SYS_SHUTDOWN = 134 - SYS_SOCKETPAIR = 135 - SYS_MKDIR = 136 - SYS_RMDIR = 137 - SYS_UTIMES = 138 - SYS_FUTIMES = 139 - SYS_ADJTIME = 140 - SYS_GETHOSTUUID = 142 - SYS_SETSID = 147 - SYS_GETPGID = 151 - SYS_SETPRIVEXEC = 152 - SYS_PREAD = 153 - SYS_PWRITE = 154 - SYS_NFSSVC = 155 - SYS_STATFS = 157 - SYS_FSTATFS = 158 - SYS_UNMOUNT = 159 - SYS_GETFH = 161 - SYS_QUOTACTL = 165 - SYS_MOUNT = 167 - SYS_CSOPS = 169 - SYS_CSOPS_AUDITTOKEN = 170 - SYS_WAITID = 173 - SYS_KDEBUG_TRACE64 = 179 - SYS_KDEBUG_TRACE = 180 - SYS_SETGID = 181 - SYS_SETEGID = 182 - SYS_SETEUID = 183 - SYS_SIGRETURN = 184 - SYS_CHUD = 185 - SYS_FDATASYNC = 187 - SYS_STAT = 188 - SYS_FSTAT = 189 - SYS_LSTAT = 190 - SYS_PATHCONF = 191 - SYS_FPATHCONF = 192 - SYS_GETRLIMIT = 194 - SYS_SETRLIMIT = 195 - SYS_GETDIRENTRIES = 196 - SYS_MMAP = 197 - SYS_LSEEK = 199 - SYS_TRUNCATE = 200 - SYS_FTRUNCATE = 201 - SYS_SYSCTL = 202 - SYS_MLOCK = 203 - SYS_MUNLOCK = 204 - SYS_UNDELETE = 205 - SYS_OPEN_DPROTECTED_NP = 216 - SYS_GETATTRLIST = 220 - SYS_SETATTRLIST = 221 - SYS_GETDIRENTRIESATTR = 222 - SYS_EXCHANGEDATA = 223 - SYS_SEARCHFS = 225 - SYS_DELETE = 226 - SYS_COPYFILE = 227 - SYS_FGETATTRLIST = 228 - SYS_FSETATTRLIST = 229 - SYS_POLL = 230 - SYS_WATCHEVENT = 231 - SYS_WAITEVENT = 232 - SYS_MODWATCH = 233 - SYS_GETXATTR = 234 - SYS_FGETXATTR = 235 - SYS_SETXATTR = 236 - SYS_FSETXATTR = 237 - SYS_REMOVEXATTR = 238 - SYS_FREMOVEXATTR = 239 - SYS_LISTXATTR = 240 - SYS_FLISTXATTR = 241 - SYS_FSCTL = 242 - SYS_INITGROUPS = 243 - SYS_POSIX_SPAWN = 244 - SYS_FFSCTL = 245 - SYS_NFSCLNT = 247 - SYS_FHOPEN = 248 - SYS_MINHERIT = 250 - SYS_SEMSYS = 251 - SYS_MSGSYS = 252 - SYS_SHMSYS = 253 - SYS_SEMCTL = 254 - SYS_SEMGET = 255 - SYS_SEMOP = 256 - SYS_MSGCTL = 258 - SYS_MSGGET = 259 - SYS_MSGSND = 260 - SYS_MSGRCV = 261 - SYS_SHMAT = 262 - SYS_SHMCTL = 263 - SYS_SHMDT = 264 - SYS_SHMGET = 265 - SYS_SHM_OPEN = 266 - SYS_SHM_UNLINK = 267 - SYS_SEM_OPEN = 268 - SYS_SEM_CLOSE = 269 - SYS_SEM_UNLINK = 270 - SYS_SEM_WAIT = 271 - SYS_SEM_TRYWAIT = 272 - SYS_SEM_POST = 273 - SYS_SYSCTLBYNAME = 274 - SYS_OPEN_EXTENDED = 277 - SYS_UMASK_EXTENDED = 278 - SYS_STAT_EXTENDED = 279 - SYS_LSTAT_EXTENDED = 280 - SYS_FSTAT_EXTENDED = 281 - SYS_CHMOD_EXTENDED = 282 - SYS_FCHMOD_EXTENDED = 283 - SYS_ACCESS_EXTENDED = 284 - SYS_SETTID = 285 - SYS_GETTID = 286 - SYS_SETSGROUPS = 287 - SYS_GETSGROUPS = 288 - SYS_SETWGROUPS = 289 - SYS_GETWGROUPS = 290 - SYS_MKFIFO_EXTENDED = 291 - SYS_MKDIR_EXTENDED = 292 - SYS_IDENTITYSVC = 293 - SYS_SHARED_REGION_CHECK_NP = 294 - SYS_VM_PRESSURE_MONITOR = 296 - SYS_PSYNCH_RW_LONGRDLOCK = 297 - SYS_PSYNCH_RW_YIELDWRLOCK = 298 - SYS_PSYNCH_RW_DOWNGRADE = 299 - SYS_PSYNCH_RW_UPGRADE = 300 - SYS_PSYNCH_MUTEXWAIT = 301 - SYS_PSYNCH_MUTEXDROP = 302 - SYS_PSYNCH_CVBROAD = 303 - SYS_PSYNCH_CVSIGNAL = 304 - SYS_PSYNCH_CVWAIT = 305 - SYS_PSYNCH_RW_RDLOCK = 306 - SYS_PSYNCH_RW_WRLOCK = 307 - SYS_PSYNCH_RW_UNLOCK = 308 - SYS_PSYNCH_RW_UNLOCK2 = 309 - SYS_GETSID = 310 - SYS_SETTID_WITH_PID = 311 - SYS_PSYNCH_CVCLRPREPOST = 312 - SYS_AIO_FSYNC = 313 - SYS_AIO_RETURN = 314 - SYS_AIO_SUSPEND = 315 - SYS_AIO_CANCEL = 316 - SYS_AIO_ERROR = 317 - SYS_AIO_READ = 318 - SYS_AIO_WRITE = 319 - SYS_LIO_LISTIO = 320 - SYS_IOPOLICYSYS = 322 - SYS_PROCESS_POLICY = 323 - SYS_MLOCKALL = 324 - SYS_MUNLOCKALL = 325 - SYS_ISSETUGID = 327 - SYS___PTHREAD_KILL = 328 - SYS___PTHREAD_SIGMASK = 329 - SYS___SIGWAIT = 330 - SYS___DISABLE_THREADSIGNAL = 331 - SYS___PTHREAD_MARKCANCEL = 332 - SYS___PTHREAD_CANCELED = 333 - SYS___SEMWAIT_SIGNAL = 334 - SYS_PROC_INFO = 336 - SYS_SENDFILE = 337 - SYS_STAT64 = 338 - SYS_FSTAT64 = 339 - SYS_LSTAT64 = 340 - SYS_STAT64_EXTENDED = 341 - SYS_LSTAT64_EXTENDED = 342 - SYS_FSTAT64_EXTENDED = 343 - SYS_GETDIRENTRIES64 = 344 - SYS_STATFS64 = 345 - SYS_FSTATFS64 = 346 - SYS_GETFSSTAT64 = 347 - SYS___PTHREAD_CHDIR = 348 - SYS___PTHREAD_FCHDIR = 349 - SYS_AUDIT = 350 - SYS_AUDITON = 351 - SYS_GETAUID = 353 - SYS_SETAUID = 354 - SYS_GETAUDIT_ADDR = 357 - SYS_SETAUDIT_ADDR = 358 - SYS_AUDITCTL = 359 - SYS_BSDTHREAD_CREATE = 360 - SYS_BSDTHREAD_TERMINATE = 361 - SYS_KQUEUE = 362 - SYS_KEVENT = 363 - SYS_LCHOWN = 364 - SYS_STACK_SNAPSHOT = 365 - SYS_BSDTHREAD_REGISTER = 366 - SYS_WORKQ_OPEN = 367 - SYS_WORKQ_KERNRETURN = 368 - SYS_KEVENT64 = 369 - SYS___OLD_SEMWAIT_SIGNAL = 370 - SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 - SYS_THREAD_SELFID = 372 - SYS_LEDGER = 373 - SYS___MAC_EXECVE = 380 - SYS___MAC_SYSCALL = 381 - SYS___MAC_GET_FILE = 382 - SYS___MAC_SET_FILE = 383 - SYS___MAC_GET_LINK = 384 - SYS___MAC_SET_LINK = 385 - SYS___MAC_GET_PROC = 386 - SYS___MAC_SET_PROC = 387 - SYS___MAC_GET_FD = 388 - SYS___MAC_SET_FD = 389 - SYS___MAC_GET_PID = 390 - SYS___MAC_GET_LCID = 391 - SYS___MAC_GET_LCTX = 392 - SYS___MAC_SET_LCTX = 393 - SYS_SETLCID = 394 - SYS_GETLCID = 395 - SYS_READ_NOCANCEL = 396 - SYS_WRITE_NOCANCEL = 397 - SYS_OPEN_NOCANCEL = 398 - SYS_CLOSE_NOCANCEL = 399 - SYS_WAIT4_NOCANCEL = 400 - SYS_RECVMSG_NOCANCEL = 401 - SYS_SENDMSG_NOCANCEL = 402 - SYS_RECVFROM_NOCANCEL = 403 - SYS_ACCEPT_NOCANCEL = 404 - SYS_MSYNC_NOCANCEL = 405 - SYS_FCNTL_NOCANCEL = 406 - SYS_SELECT_NOCANCEL = 407 - SYS_FSYNC_NOCANCEL = 408 - SYS_CONNECT_NOCANCEL = 409 - SYS_SIGSUSPEND_NOCANCEL = 410 - SYS_READV_NOCANCEL = 411 - SYS_WRITEV_NOCANCEL = 412 - SYS_SENDTO_NOCANCEL = 413 - SYS_PREAD_NOCANCEL = 414 - SYS_PWRITE_NOCANCEL = 415 - SYS_WAITID_NOCANCEL = 416 - SYS_POLL_NOCANCEL = 417 - SYS_MSGSND_NOCANCEL = 418 - SYS_MSGRCV_NOCANCEL = 419 - SYS_SEM_WAIT_NOCANCEL = 420 - SYS_AIO_SUSPEND_NOCANCEL = 421 - SYS___SIGWAIT_NOCANCEL = 422 - SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 - SYS___MAC_MOUNT = 424 - SYS___MAC_GET_MOUNT = 425 - SYS___MAC_GETFSSTAT = 426 - SYS_FSGETPATH = 427 - SYS_AUDIT_SESSION_SELF = 428 - SYS_AUDIT_SESSION_JOIN = 429 - SYS_FILEPORT_MAKEPORT = 430 - SYS_FILEPORT_MAKEFD = 431 - SYS_AUDIT_SESSION_PORT = 432 - SYS_PID_SUSPEND = 433 - SYS_PID_RESUME = 434 - SYS_PID_HIBERNATE = 435 - SYS_PID_SHUTDOWN_SOCKETS = 436 - SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 - SYS_KAS_INFO = 439 - SYS_MEMORYSTATUS_CONTROL = 440 - SYS_GUARDED_OPEN_NP = 441 - SYS_GUARDED_CLOSE_NP = 442 - SYS_GUARDED_KQUEUE_NP = 443 - SYS_CHANGE_FDGUARD_NP = 444 - SYS_PROC_RLIMIT_CONTROL = 446 - SYS_CONNECTX = 447 - SYS_DISCONNECTX = 448 - SYS_PEELOFF = 449 - SYS_SOCKET_DELEGATE = 450 - SYS_TELEMETRY = 451 - SYS_PROC_UUID_POLICY = 452 - SYS_MEMORYSTATUS_GET_LEVEL = 453 - SYS_SYSTEM_OVERRIDE = 454 - SYS_VFS_PURGE = 455 - SYS_SFI_CTL = 456 - SYS_SFI_PIDCTL = 457 - SYS_COALITION = 458 - SYS_COALITION_INFO = 459 - SYS_NECP_MATCH_POLICY = 460 - SYS_GETATTRLISTBULK = 461 - SYS_OPENAT = 463 - SYS_OPENAT_NOCANCEL = 464 - SYS_RENAMEAT = 465 - SYS_FACCESSAT = 466 - SYS_FCHMODAT = 467 - SYS_FCHOWNAT = 468 - SYS_FSTATAT = 469 - SYS_FSTATAT64 = 470 - SYS_LINKAT = 471 - SYS_UNLINKAT = 472 - SYS_READLINKAT = 473 - SYS_SYMLINKAT = 474 - SYS_MKDIRAT = 475 - SYS_GETATTRLISTAT = 476 - SYS_PROC_TRACE_LOG = 477 - SYS_BSDTHREAD_CTL = 478 - SYS_OPENBYID_NP = 479 - SYS_RECVMSG_X = 480 - SYS_SENDMSG_X = 481 - SYS_THREAD_SELFUSAGE = 482 - SYS_CSRCTL = 483 - SYS_GUARDED_OPEN_DPROTECTED_NP = 484 - SYS_GUARDED_WRITE_NP = 485 - SYS_GUARDED_PWRITE_NP = 486 - SYS_GUARDED_WRITEV_NP = 487 - SYS_RENAME_EXT = 488 - SYS_MREMAP_ENCRYPTED = 489 - SYS_MAXSYSCALL = 490 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_amd64.go deleted file mode 100644 index 09de240c8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_amd64.go +++ /dev/null @@ -1,398 +0,0 @@ -// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/sys/syscall.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build amd64,darwin - -package unix - -const ( - SYS_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAIT4 = 7 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_CHDIR = 12 - SYS_FCHDIR = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_CHOWN = 16 - SYS_GETFSSTAT = 18 - SYS_GETPID = 20 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_GETEUID = 25 - SYS_PTRACE = 26 - SYS_RECVMSG = 27 - SYS_SENDMSG = 28 - SYS_RECVFROM = 29 - SYS_ACCEPT = 30 - SYS_GETPEERNAME = 31 - SYS_GETSOCKNAME = 32 - SYS_ACCESS = 33 - SYS_CHFLAGS = 34 - SYS_FCHFLAGS = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_GETPPID = 39 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_GETEGID = 43 - SYS_SIGACTION = 46 - SYS_GETGID = 47 - SYS_SIGPROCMASK = 48 - SYS_GETLOGIN = 49 - SYS_SETLOGIN = 50 - SYS_ACCT = 51 - SYS_SIGPENDING = 52 - SYS_SIGALTSTACK = 53 - SYS_IOCTL = 54 - SYS_REBOOT = 55 - SYS_REVOKE = 56 - SYS_SYMLINK = 57 - SYS_READLINK = 58 - SYS_EXECVE = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_MSYNC = 65 - SYS_VFORK = 66 - SYS_MUNMAP = 73 - SYS_MPROTECT = 74 - SYS_MADVISE = 75 - SYS_MINCORE = 78 - SYS_GETGROUPS = 79 - SYS_SETGROUPS = 80 - SYS_GETPGRP = 81 - SYS_SETPGID = 82 - SYS_SETITIMER = 83 - SYS_SWAPON = 85 - SYS_GETITIMER = 86 - SYS_GETDTABLESIZE = 89 - SYS_DUP2 = 90 - SYS_FCNTL = 92 - SYS_SELECT = 93 - SYS_FSYNC = 95 - SYS_SETPRIORITY = 96 - SYS_SOCKET = 97 - SYS_CONNECT = 98 - SYS_GETPRIORITY = 100 - SYS_BIND = 104 - SYS_SETSOCKOPT = 105 - SYS_LISTEN = 106 - SYS_SIGSUSPEND = 111 - SYS_GETTIMEOFDAY = 116 - SYS_GETRUSAGE = 117 - SYS_GETSOCKOPT = 118 - SYS_READV = 120 - SYS_WRITEV = 121 - SYS_SETTIMEOFDAY = 122 - SYS_FCHOWN = 123 - SYS_FCHMOD = 124 - SYS_SETREUID = 126 - SYS_SETREGID = 127 - SYS_RENAME = 128 - SYS_FLOCK = 131 - SYS_MKFIFO = 132 - SYS_SENDTO = 133 - SYS_SHUTDOWN = 134 - SYS_SOCKETPAIR = 135 - SYS_MKDIR = 136 - SYS_RMDIR = 137 - SYS_UTIMES = 138 - SYS_FUTIMES = 139 - SYS_ADJTIME = 140 - SYS_GETHOSTUUID = 142 - SYS_SETSID = 147 - SYS_GETPGID = 151 - SYS_SETPRIVEXEC = 152 - SYS_PREAD = 153 - SYS_PWRITE = 154 - SYS_NFSSVC = 155 - SYS_STATFS = 157 - SYS_FSTATFS = 158 - SYS_UNMOUNT = 159 - SYS_GETFH = 161 - SYS_QUOTACTL = 165 - SYS_MOUNT = 167 - SYS_CSOPS = 169 - SYS_CSOPS_AUDITTOKEN = 170 - SYS_WAITID = 173 - SYS_KDEBUG_TRACE64 = 179 - SYS_KDEBUG_TRACE = 180 - SYS_SETGID = 181 - SYS_SETEGID = 182 - SYS_SETEUID = 183 - SYS_SIGRETURN = 184 - SYS_CHUD = 185 - SYS_FDATASYNC = 187 - SYS_STAT = 188 - SYS_FSTAT = 189 - SYS_LSTAT = 190 - SYS_PATHCONF = 191 - SYS_FPATHCONF = 192 - SYS_GETRLIMIT = 194 - SYS_SETRLIMIT = 195 - SYS_GETDIRENTRIES = 196 - SYS_MMAP = 197 - SYS_LSEEK = 199 - SYS_TRUNCATE = 200 - SYS_FTRUNCATE = 201 - SYS_SYSCTL = 202 - SYS_MLOCK = 203 - SYS_MUNLOCK = 204 - SYS_UNDELETE = 205 - SYS_OPEN_DPROTECTED_NP = 216 - SYS_GETATTRLIST = 220 - SYS_SETATTRLIST = 221 - SYS_GETDIRENTRIESATTR = 222 - SYS_EXCHANGEDATA = 223 - SYS_SEARCHFS = 225 - SYS_DELETE = 226 - SYS_COPYFILE = 227 - SYS_FGETATTRLIST = 228 - SYS_FSETATTRLIST = 229 - SYS_POLL = 230 - SYS_WATCHEVENT = 231 - SYS_WAITEVENT = 232 - SYS_MODWATCH = 233 - SYS_GETXATTR = 234 - SYS_FGETXATTR = 235 - SYS_SETXATTR = 236 - SYS_FSETXATTR = 237 - SYS_REMOVEXATTR = 238 - SYS_FREMOVEXATTR = 239 - SYS_LISTXATTR = 240 - SYS_FLISTXATTR = 241 - SYS_FSCTL = 242 - SYS_INITGROUPS = 243 - SYS_POSIX_SPAWN = 244 - SYS_FFSCTL = 245 - SYS_NFSCLNT = 247 - SYS_FHOPEN = 248 - SYS_MINHERIT = 250 - SYS_SEMSYS = 251 - SYS_MSGSYS = 252 - SYS_SHMSYS = 253 - SYS_SEMCTL = 254 - SYS_SEMGET = 255 - SYS_SEMOP = 256 - SYS_MSGCTL = 258 - SYS_MSGGET = 259 - SYS_MSGSND = 260 - SYS_MSGRCV = 261 - SYS_SHMAT = 262 - SYS_SHMCTL = 263 - SYS_SHMDT = 264 - SYS_SHMGET = 265 - SYS_SHM_OPEN = 266 - SYS_SHM_UNLINK = 267 - SYS_SEM_OPEN = 268 - SYS_SEM_CLOSE = 269 - SYS_SEM_UNLINK = 270 - SYS_SEM_WAIT = 271 - SYS_SEM_TRYWAIT = 272 - SYS_SEM_POST = 273 - SYS_SYSCTLBYNAME = 274 - SYS_OPEN_EXTENDED = 277 - SYS_UMASK_EXTENDED = 278 - SYS_STAT_EXTENDED = 279 - SYS_LSTAT_EXTENDED = 280 - SYS_FSTAT_EXTENDED = 281 - SYS_CHMOD_EXTENDED = 282 - SYS_FCHMOD_EXTENDED = 283 - SYS_ACCESS_EXTENDED = 284 - SYS_SETTID = 285 - SYS_GETTID = 286 - SYS_SETSGROUPS = 287 - SYS_GETSGROUPS = 288 - SYS_SETWGROUPS = 289 - SYS_GETWGROUPS = 290 - SYS_MKFIFO_EXTENDED = 291 - SYS_MKDIR_EXTENDED = 292 - SYS_IDENTITYSVC = 293 - SYS_SHARED_REGION_CHECK_NP = 294 - SYS_VM_PRESSURE_MONITOR = 296 - SYS_PSYNCH_RW_LONGRDLOCK = 297 - SYS_PSYNCH_RW_YIELDWRLOCK = 298 - SYS_PSYNCH_RW_DOWNGRADE = 299 - SYS_PSYNCH_RW_UPGRADE = 300 - SYS_PSYNCH_MUTEXWAIT = 301 - SYS_PSYNCH_MUTEXDROP = 302 - SYS_PSYNCH_CVBROAD = 303 - SYS_PSYNCH_CVSIGNAL = 304 - SYS_PSYNCH_CVWAIT = 305 - SYS_PSYNCH_RW_RDLOCK = 306 - SYS_PSYNCH_RW_WRLOCK = 307 - SYS_PSYNCH_RW_UNLOCK = 308 - SYS_PSYNCH_RW_UNLOCK2 = 309 - SYS_GETSID = 310 - SYS_SETTID_WITH_PID = 311 - SYS_PSYNCH_CVCLRPREPOST = 312 - SYS_AIO_FSYNC = 313 - SYS_AIO_RETURN = 314 - SYS_AIO_SUSPEND = 315 - SYS_AIO_CANCEL = 316 - SYS_AIO_ERROR = 317 - SYS_AIO_READ = 318 - SYS_AIO_WRITE = 319 - SYS_LIO_LISTIO = 320 - SYS_IOPOLICYSYS = 322 - SYS_PROCESS_POLICY = 323 - SYS_MLOCKALL = 324 - SYS_MUNLOCKALL = 325 - SYS_ISSETUGID = 327 - SYS___PTHREAD_KILL = 328 - SYS___PTHREAD_SIGMASK = 329 - SYS___SIGWAIT = 330 - SYS___DISABLE_THREADSIGNAL = 331 - SYS___PTHREAD_MARKCANCEL = 332 - SYS___PTHREAD_CANCELED = 333 - SYS___SEMWAIT_SIGNAL = 334 - SYS_PROC_INFO = 336 - SYS_SENDFILE = 337 - SYS_STAT64 = 338 - SYS_FSTAT64 = 339 - SYS_LSTAT64 = 340 - SYS_STAT64_EXTENDED = 341 - SYS_LSTAT64_EXTENDED = 342 - SYS_FSTAT64_EXTENDED = 343 - SYS_GETDIRENTRIES64 = 344 - SYS_STATFS64 = 345 - SYS_FSTATFS64 = 346 - SYS_GETFSSTAT64 = 347 - SYS___PTHREAD_CHDIR = 348 - SYS___PTHREAD_FCHDIR = 349 - SYS_AUDIT = 350 - SYS_AUDITON = 351 - SYS_GETAUID = 353 - SYS_SETAUID = 354 - SYS_GETAUDIT_ADDR = 357 - SYS_SETAUDIT_ADDR = 358 - SYS_AUDITCTL = 359 - SYS_BSDTHREAD_CREATE = 360 - SYS_BSDTHREAD_TERMINATE = 361 - SYS_KQUEUE = 362 - SYS_KEVENT = 363 - SYS_LCHOWN = 364 - SYS_STACK_SNAPSHOT = 365 - SYS_BSDTHREAD_REGISTER = 366 - SYS_WORKQ_OPEN = 367 - SYS_WORKQ_KERNRETURN = 368 - SYS_KEVENT64 = 369 - SYS___OLD_SEMWAIT_SIGNAL = 370 - SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 - SYS_THREAD_SELFID = 372 - SYS_LEDGER = 373 - SYS___MAC_EXECVE = 380 - SYS___MAC_SYSCALL = 381 - SYS___MAC_GET_FILE = 382 - SYS___MAC_SET_FILE = 383 - SYS___MAC_GET_LINK = 384 - SYS___MAC_SET_LINK = 385 - SYS___MAC_GET_PROC = 386 - SYS___MAC_SET_PROC = 387 - SYS___MAC_GET_FD = 388 - SYS___MAC_SET_FD = 389 - SYS___MAC_GET_PID = 390 - SYS___MAC_GET_LCID = 391 - SYS___MAC_GET_LCTX = 392 - SYS___MAC_SET_LCTX = 393 - SYS_SETLCID = 394 - SYS_GETLCID = 395 - SYS_READ_NOCANCEL = 396 - SYS_WRITE_NOCANCEL = 397 - SYS_OPEN_NOCANCEL = 398 - SYS_CLOSE_NOCANCEL = 399 - SYS_WAIT4_NOCANCEL = 400 - SYS_RECVMSG_NOCANCEL = 401 - SYS_SENDMSG_NOCANCEL = 402 - SYS_RECVFROM_NOCANCEL = 403 - SYS_ACCEPT_NOCANCEL = 404 - SYS_MSYNC_NOCANCEL = 405 - SYS_FCNTL_NOCANCEL = 406 - SYS_SELECT_NOCANCEL = 407 - SYS_FSYNC_NOCANCEL = 408 - SYS_CONNECT_NOCANCEL = 409 - SYS_SIGSUSPEND_NOCANCEL = 410 - SYS_READV_NOCANCEL = 411 - SYS_WRITEV_NOCANCEL = 412 - SYS_SENDTO_NOCANCEL = 413 - SYS_PREAD_NOCANCEL = 414 - SYS_PWRITE_NOCANCEL = 415 - SYS_WAITID_NOCANCEL = 416 - SYS_POLL_NOCANCEL = 417 - SYS_MSGSND_NOCANCEL = 418 - SYS_MSGRCV_NOCANCEL = 419 - SYS_SEM_WAIT_NOCANCEL = 420 - SYS_AIO_SUSPEND_NOCANCEL = 421 - SYS___SIGWAIT_NOCANCEL = 422 - SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 - SYS___MAC_MOUNT = 424 - SYS___MAC_GET_MOUNT = 425 - SYS___MAC_GETFSSTAT = 426 - SYS_FSGETPATH = 427 - SYS_AUDIT_SESSION_SELF = 428 - SYS_AUDIT_SESSION_JOIN = 429 - SYS_FILEPORT_MAKEPORT = 430 - SYS_FILEPORT_MAKEFD = 431 - SYS_AUDIT_SESSION_PORT = 432 - SYS_PID_SUSPEND = 433 - SYS_PID_RESUME = 434 - SYS_PID_HIBERNATE = 435 - SYS_PID_SHUTDOWN_SOCKETS = 436 - SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 - SYS_KAS_INFO = 439 - SYS_MEMORYSTATUS_CONTROL = 440 - SYS_GUARDED_OPEN_NP = 441 - SYS_GUARDED_CLOSE_NP = 442 - SYS_GUARDED_KQUEUE_NP = 443 - SYS_CHANGE_FDGUARD_NP = 444 - SYS_PROC_RLIMIT_CONTROL = 446 - SYS_CONNECTX = 447 - SYS_DISCONNECTX = 448 - SYS_PEELOFF = 449 - SYS_SOCKET_DELEGATE = 450 - SYS_TELEMETRY = 451 - SYS_PROC_UUID_POLICY = 452 - SYS_MEMORYSTATUS_GET_LEVEL = 453 - SYS_SYSTEM_OVERRIDE = 454 - SYS_VFS_PURGE = 455 - SYS_SFI_CTL = 456 - SYS_SFI_PIDCTL = 457 - SYS_COALITION = 458 - SYS_COALITION_INFO = 459 - SYS_NECP_MATCH_POLICY = 460 - SYS_GETATTRLISTBULK = 461 - SYS_OPENAT = 463 - SYS_OPENAT_NOCANCEL = 464 - SYS_RENAMEAT = 465 - SYS_FACCESSAT = 466 - SYS_FCHMODAT = 467 - SYS_FCHOWNAT = 468 - SYS_FSTATAT = 469 - SYS_FSTATAT64 = 470 - SYS_LINKAT = 471 - SYS_UNLINKAT = 472 - SYS_READLINKAT = 473 - SYS_SYMLINKAT = 474 - SYS_MKDIRAT = 475 - SYS_GETATTRLISTAT = 476 - SYS_PROC_TRACE_LOG = 477 - SYS_BSDTHREAD_CTL = 478 - SYS_OPENBYID_NP = 479 - SYS_RECVMSG_X = 480 - SYS_SENDMSG_X = 481 - SYS_THREAD_SELFUSAGE = 482 - SYS_CSRCTL = 483 - SYS_GUARDED_OPEN_DPROTECTED_NP = 484 - SYS_GUARDED_WRITE_NP = 485 - SYS_GUARDED_PWRITE_NP = 486 - SYS_GUARDED_WRITEV_NP = 487 - SYS_RENAME_EXT = 488 - SYS_MREMAP_ENCRYPTED = 489 - SYS_MAXSYSCALL = 490 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm.go deleted file mode 100644 index b8c9aea85..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm.go +++ /dev/null @@ -1,358 +0,0 @@ -// mksysnum_darwin.pl /usr/include/sys/syscall.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build arm,darwin - -package unix - -const ( - SYS_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAIT4 = 7 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_CHDIR = 12 - SYS_FCHDIR = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_CHOWN = 16 - SYS_GETFSSTAT = 18 - SYS_GETPID = 20 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_GETEUID = 25 - SYS_PTRACE = 26 - SYS_RECVMSG = 27 - SYS_SENDMSG = 28 - SYS_RECVFROM = 29 - SYS_ACCEPT = 30 - SYS_GETPEERNAME = 31 - SYS_GETSOCKNAME = 32 - SYS_ACCESS = 33 - SYS_CHFLAGS = 34 - SYS_FCHFLAGS = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_GETPPID = 39 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_GETEGID = 43 - SYS_SIGACTION = 46 - SYS_GETGID = 47 - SYS_SIGPROCMASK = 48 - SYS_GETLOGIN = 49 - SYS_SETLOGIN = 50 - SYS_ACCT = 51 - SYS_SIGPENDING = 52 - SYS_SIGALTSTACK = 53 - SYS_IOCTL = 54 - SYS_REBOOT = 55 - SYS_REVOKE = 56 - SYS_SYMLINK = 57 - SYS_READLINK = 58 - SYS_EXECVE = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_MSYNC = 65 - SYS_VFORK = 66 - SYS_MUNMAP = 73 - SYS_MPROTECT = 74 - SYS_MADVISE = 75 - SYS_MINCORE = 78 - SYS_GETGROUPS = 79 - SYS_SETGROUPS = 80 - SYS_GETPGRP = 81 - SYS_SETPGID = 82 - SYS_SETITIMER = 83 - SYS_SWAPON = 85 - SYS_GETITIMER = 86 - SYS_GETDTABLESIZE = 89 - SYS_DUP2 = 90 - SYS_FCNTL = 92 - SYS_SELECT = 93 - SYS_FSYNC = 95 - SYS_SETPRIORITY = 96 - SYS_SOCKET = 97 - SYS_CONNECT = 98 - SYS_GETPRIORITY = 100 - SYS_BIND = 104 - SYS_SETSOCKOPT = 105 - SYS_LISTEN = 106 - SYS_SIGSUSPEND = 111 - SYS_GETTIMEOFDAY = 116 - SYS_GETRUSAGE = 117 - SYS_GETSOCKOPT = 118 - SYS_READV = 120 - SYS_WRITEV = 121 - SYS_SETTIMEOFDAY = 122 - SYS_FCHOWN = 123 - SYS_FCHMOD = 124 - SYS_SETREUID = 126 - SYS_SETREGID = 127 - SYS_RENAME = 128 - SYS_FLOCK = 131 - SYS_MKFIFO = 132 - SYS_SENDTO = 133 - SYS_SHUTDOWN = 134 - SYS_SOCKETPAIR = 135 - SYS_MKDIR = 136 - SYS_RMDIR = 137 - SYS_UTIMES = 138 - SYS_FUTIMES = 139 - SYS_ADJTIME = 140 - SYS_GETHOSTUUID = 142 - SYS_SETSID = 147 - SYS_GETPGID = 151 - SYS_SETPRIVEXEC = 152 - SYS_PREAD = 153 - SYS_PWRITE = 154 - SYS_NFSSVC = 155 - SYS_STATFS = 157 - SYS_FSTATFS = 158 - SYS_UNMOUNT = 159 - SYS_GETFH = 161 - SYS_QUOTACTL = 165 - SYS_MOUNT = 167 - SYS_CSOPS = 169 - SYS_CSOPS_AUDITTOKEN = 170 - SYS_WAITID = 173 - SYS_KDEBUG_TRACE = 180 - SYS_SETGID = 181 - SYS_SETEGID = 182 - SYS_SETEUID = 183 - SYS_SIGRETURN = 184 - SYS_CHUD = 185 - SYS_FDATASYNC = 187 - SYS_STAT = 188 - SYS_FSTAT = 189 - SYS_LSTAT = 190 - SYS_PATHCONF = 191 - SYS_FPATHCONF = 192 - SYS_GETRLIMIT = 194 - SYS_SETRLIMIT = 195 - SYS_GETDIRENTRIES = 196 - SYS_MMAP = 197 - SYS_LSEEK = 199 - SYS_TRUNCATE = 200 - SYS_FTRUNCATE = 201 - SYS___SYSCTL = 202 - SYS_MLOCK = 203 - SYS_MUNLOCK = 204 - SYS_UNDELETE = 205 - SYS_ATSOCKET = 206 - SYS_ATGETMSG = 207 - SYS_ATPUTMSG = 208 - SYS_ATPSNDREQ = 209 - SYS_ATPSNDRSP = 210 - SYS_ATPGETREQ = 211 - SYS_ATPGETRSP = 212 - SYS_OPEN_DPROTECTED_NP = 216 - SYS_GETATTRLIST = 220 - SYS_SETATTRLIST = 221 - SYS_GETDIRENTRIESATTR = 222 - SYS_EXCHANGEDATA = 223 - SYS_SEARCHFS = 225 - SYS_DELETE = 226 - SYS_COPYFILE = 227 - SYS_FGETATTRLIST = 228 - SYS_FSETATTRLIST = 229 - SYS_POLL = 230 - SYS_WATCHEVENT = 231 - SYS_WAITEVENT = 232 - SYS_MODWATCH = 233 - SYS_GETXATTR = 234 - SYS_FGETXATTR = 235 - SYS_SETXATTR = 236 - SYS_FSETXATTR = 237 - SYS_REMOVEXATTR = 238 - SYS_FREMOVEXATTR = 239 - SYS_LISTXATTR = 240 - SYS_FLISTXATTR = 241 - SYS_FSCTL = 242 - SYS_INITGROUPS = 243 - SYS_POSIX_SPAWN = 244 - SYS_FFSCTL = 245 - SYS_NFSCLNT = 247 - SYS_FHOPEN = 248 - SYS_MINHERIT = 250 - SYS_SEMSYS = 251 - SYS_MSGSYS = 252 - SYS_SHMSYS = 253 - SYS_SEMCTL = 254 - SYS_SEMGET = 255 - SYS_SEMOP = 256 - SYS_MSGCTL = 258 - SYS_MSGGET = 259 - SYS_MSGSND = 260 - SYS_MSGRCV = 261 - SYS_SHMAT = 262 - SYS_SHMCTL = 263 - SYS_SHMDT = 264 - SYS_SHMGET = 265 - SYS_SHM_OPEN = 266 - SYS_SHM_UNLINK = 267 - SYS_SEM_OPEN = 268 - SYS_SEM_CLOSE = 269 - SYS_SEM_UNLINK = 270 - SYS_SEM_WAIT = 271 - SYS_SEM_TRYWAIT = 272 - SYS_SEM_POST = 273 - SYS_SEM_GETVALUE = 274 - SYS_SEM_INIT = 275 - SYS_SEM_DESTROY = 276 - SYS_OPEN_EXTENDED = 277 - SYS_UMASK_EXTENDED = 278 - SYS_STAT_EXTENDED = 279 - SYS_LSTAT_EXTENDED = 280 - SYS_FSTAT_EXTENDED = 281 - SYS_CHMOD_EXTENDED = 282 - SYS_FCHMOD_EXTENDED = 283 - SYS_ACCESS_EXTENDED = 284 - SYS_SETTID = 285 - SYS_GETTID = 286 - SYS_SETSGROUPS = 287 - SYS_GETSGROUPS = 288 - SYS_SETWGROUPS = 289 - SYS_GETWGROUPS = 290 - SYS_MKFIFO_EXTENDED = 291 - SYS_MKDIR_EXTENDED = 292 - SYS_IDENTITYSVC = 293 - SYS_SHARED_REGION_CHECK_NP = 294 - SYS_VM_PRESSURE_MONITOR = 296 - SYS_PSYNCH_RW_LONGRDLOCK = 297 - SYS_PSYNCH_RW_YIELDWRLOCK = 298 - SYS_PSYNCH_RW_DOWNGRADE = 299 - SYS_PSYNCH_RW_UPGRADE = 300 - SYS_PSYNCH_MUTEXWAIT = 301 - SYS_PSYNCH_MUTEXDROP = 302 - SYS_PSYNCH_CVBROAD = 303 - SYS_PSYNCH_CVSIGNAL = 304 - SYS_PSYNCH_CVWAIT = 305 - SYS_PSYNCH_RW_RDLOCK = 306 - SYS_PSYNCH_RW_WRLOCK = 307 - SYS_PSYNCH_RW_UNLOCK = 308 - SYS_PSYNCH_RW_UNLOCK2 = 309 - SYS_GETSID = 310 - SYS_SETTID_WITH_PID = 311 - SYS_PSYNCH_CVCLRPREPOST = 312 - SYS_AIO_FSYNC = 313 - SYS_AIO_RETURN = 314 - SYS_AIO_SUSPEND = 315 - SYS_AIO_CANCEL = 316 - SYS_AIO_ERROR = 317 - SYS_AIO_READ = 318 - SYS_AIO_WRITE = 319 - SYS_LIO_LISTIO = 320 - SYS_IOPOLICYSYS = 322 - SYS_PROCESS_POLICY = 323 - SYS_MLOCKALL = 324 - SYS_MUNLOCKALL = 325 - SYS_ISSETUGID = 327 - SYS___PTHREAD_KILL = 328 - SYS___PTHREAD_SIGMASK = 329 - SYS___SIGWAIT = 330 - SYS___DISABLE_THREADSIGNAL = 331 - SYS___PTHREAD_MARKCANCEL = 332 - SYS___PTHREAD_CANCELED = 333 - SYS___SEMWAIT_SIGNAL = 334 - SYS_PROC_INFO = 336 - SYS_SENDFILE = 337 - SYS_STAT64 = 338 - SYS_FSTAT64 = 339 - SYS_LSTAT64 = 340 - SYS_STAT64_EXTENDED = 341 - SYS_LSTAT64_EXTENDED = 342 - SYS_FSTAT64_EXTENDED = 343 - SYS_GETDIRENTRIES64 = 344 - SYS_STATFS64 = 345 - SYS_FSTATFS64 = 346 - SYS_GETFSSTAT64 = 347 - SYS___PTHREAD_CHDIR = 348 - SYS___PTHREAD_FCHDIR = 349 - SYS_AUDIT = 350 - SYS_AUDITON = 351 - SYS_GETAUID = 353 - SYS_SETAUID = 354 - SYS_GETAUDIT_ADDR = 357 - SYS_SETAUDIT_ADDR = 358 - SYS_AUDITCTL = 359 - SYS_BSDTHREAD_CREATE = 360 - SYS_BSDTHREAD_TERMINATE = 361 - SYS_KQUEUE = 362 - SYS_KEVENT = 363 - SYS_LCHOWN = 364 - SYS_STACK_SNAPSHOT = 365 - SYS_BSDTHREAD_REGISTER = 366 - SYS_WORKQ_OPEN = 367 - SYS_WORKQ_KERNRETURN = 368 - SYS_KEVENT64 = 369 - SYS___OLD_SEMWAIT_SIGNAL = 370 - SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 - SYS_THREAD_SELFID = 372 - SYS_LEDGER = 373 - SYS___MAC_EXECVE = 380 - SYS___MAC_SYSCALL = 381 - SYS___MAC_GET_FILE = 382 - SYS___MAC_SET_FILE = 383 - SYS___MAC_GET_LINK = 384 - SYS___MAC_SET_LINK = 385 - SYS___MAC_GET_PROC = 386 - SYS___MAC_SET_PROC = 387 - SYS___MAC_GET_FD = 388 - SYS___MAC_SET_FD = 389 - SYS___MAC_GET_PID = 390 - SYS___MAC_GET_LCID = 391 - SYS___MAC_GET_LCTX = 392 - SYS___MAC_SET_LCTX = 393 - SYS_SETLCID = 394 - SYS_GETLCID = 395 - SYS_READ_NOCANCEL = 396 - SYS_WRITE_NOCANCEL = 397 - SYS_OPEN_NOCANCEL = 398 - SYS_CLOSE_NOCANCEL = 399 - SYS_WAIT4_NOCANCEL = 400 - SYS_RECVMSG_NOCANCEL = 401 - SYS_SENDMSG_NOCANCEL = 402 - SYS_RECVFROM_NOCANCEL = 403 - SYS_ACCEPT_NOCANCEL = 404 - SYS_MSYNC_NOCANCEL = 405 - SYS_FCNTL_NOCANCEL = 406 - SYS_SELECT_NOCANCEL = 407 - SYS_FSYNC_NOCANCEL = 408 - SYS_CONNECT_NOCANCEL = 409 - SYS_SIGSUSPEND_NOCANCEL = 410 - SYS_READV_NOCANCEL = 411 - SYS_WRITEV_NOCANCEL = 412 - SYS_SENDTO_NOCANCEL = 413 - SYS_PREAD_NOCANCEL = 414 - SYS_PWRITE_NOCANCEL = 415 - SYS_WAITID_NOCANCEL = 416 - SYS_POLL_NOCANCEL = 417 - SYS_MSGSND_NOCANCEL = 418 - SYS_MSGRCV_NOCANCEL = 419 - SYS_SEM_WAIT_NOCANCEL = 420 - SYS_AIO_SUSPEND_NOCANCEL = 421 - SYS___SIGWAIT_NOCANCEL = 422 - SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 - SYS___MAC_MOUNT = 424 - SYS___MAC_GET_MOUNT = 425 - SYS___MAC_GETFSSTAT = 426 - SYS_FSGETPATH = 427 - SYS_AUDIT_SESSION_SELF = 428 - SYS_AUDIT_SESSION_JOIN = 429 - SYS_FILEPORT_MAKEPORT = 430 - SYS_FILEPORT_MAKEFD = 431 - SYS_AUDIT_SESSION_PORT = 432 - SYS_PID_SUSPEND = 433 - SYS_PID_RESUME = 434 - SYS_PID_HIBERNATE = 435 - SYS_PID_SHUTDOWN_SOCKETS = 436 - SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 - SYS_KAS_INFO = 439 - SYS_MAXSYSCALL = 440 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm64.go deleted file mode 100644 index 26677ebbf..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm64.go +++ /dev/null @@ -1,398 +0,0 @@ -// mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/include/sys/syscall.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build arm64,darwin - -package unix - -const ( - SYS_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAIT4 = 7 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_CHDIR = 12 - SYS_FCHDIR = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_CHOWN = 16 - SYS_GETFSSTAT = 18 - SYS_GETPID = 20 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_GETEUID = 25 - SYS_PTRACE = 26 - SYS_RECVMSG = 27 - SYS_SENDMSG = 28 - SYS_RECVFROM = 29 - SYS_ACCEPT = 30 - SYS_GETPEERNAME = 31 - SYS_GETSOCKNAME = 32 - SYS_ACCESS = 33 - SYS_CHFLAGS = 34 - SYS_FCHFLAGS = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_GETPPID = 39 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_GETEGID = 43 - SYS_SIGACTION = 46 - SYS_GETGID = 47 - SYS_SIGPROCMASK = 48 - SYS_GETLOGIN = 49 - SYS_SETLOGIN = 50 - SYS_ACCT = 51 - SYS_SIGPENDING = 52 - SYS_SIGALTSTACK = 53 - SYS_IOCTL = 54 - SYS_REBOOT = 55 - SYS_REVOKE = 56 - SYS_SYMLINK = 57 - SYS_READLINK = 58 - SYS_EXECVE = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_MSYNC = 65 - SYS_VFORK = 66 - SYS_MUNMAP = 73 - SYS_MPROTECT = 74 - SYS_MADVISE = 75 - SYS_MINCORE = 78 - SYS_GETGROUPS = 79 - SYS_SETGROUPS = 80 - SYS_GETPGRP = 81 - SYS_SETPGID = 82 - SYS_SETITIMER = 83 - SYS_SWAPON = 85 - SYS_GETITIMER = 86 - SYS_GETDTABLESIZE = 89 - SYS_DUP2 = 90 - SYS_FCNTL = 92 - SYS_SELECT = 93 - SYS_FSYNC = 95 - SYS_SETPRIORITY = 96 - SYS_SOCKET = 97 - SYS_CONNECT = 98 - SYS_GETPRIORITY = 100 - SYS_BIND = 104 - SYS_SETSOCKOPT = 105 - SYS_LISTEN = 106 - SYS_SIGSUSPEND = 111 - SYS_GETTIMEOFDAY = 116 - SYS_GETRUSAGE = 117 - SYS_GETSOCKOPT = 118 - SYS_READV = 120 - SYS_WRITEV = 121 - SYS_SETTIMEOFDAY = 122 - SYS_FCHOWN = 123 - SYS_FCHMOD = 124 - SYS_SETREUID = 126 - SYS_SETREGID = 127 - SYS_RENAME = 128 - SYS_FLOCK = 131 - SYS_MKFIFO = 132 - SYS_SENDTO = 133 - SYS_SHUTDOWN = 134 - SYS_SOCKETPAIR = 135 - SYS_MKDIR = 136 - SYS_RMDIR = 137 - SYS_UTIMES = 138 - SYS_FUTIMES = 139 - SYS_ADJTIME = 140 - SYS_GETHOSTUUID = 142 - SYS_SETSID = 147 - SYS_GETPGID = 151 - SYS_SETPRIVEXEC = 152 - SYS_PREAD = 153 - SYS_PWRITE = 154 - SYS_NFSSVC = 155 - SYS_STATFS = 157 - SYS_FSTATFS = 158 - SYS_UNMOUNT = 159 - SYS_GETFH = 161 - SYS_QUOTACTL = 165 - SYS_MOUNT = 167 - SYS_CSOPS = 169 - SYS_CSOPS_AUDITTOKEN = 170 - SYS_WAITID = 173 - SYS_KDEBUG_TRACE64 = 179 - SYS_KDEBUG_TRACE = 180 - SYS_SETGID = 181 - SYS_SETEGID = 182 - SYS_SETEUID = 183 - SYS_SIGRETURN = 184 - SYS_CHUD = 185 - SYS_FDATASYNC = 187 - SYS_STAT = 188 - SYS_FSTAT = 189 - SYS_LSTAT = 190 - SYS_PATHCONF = 191 - SYS_FPATHCONF = 192 - SYS_GETRLIMIT = 194 - SYS_SETRLIMIT = 195 - SYS_GETDIRENTRIES = 196 - SYS_MMAP = 197 - SYS_LSEEK = 199 - SYS_TRUNCATE = 200 - SYS_FTRUNCATE = 201 - SYS_SYSCTL = 202 - SYS_MLOCK = 203 - SYS_MUNLOCK = 204 - SYS_UNDELETE = 205 - SYS_OPEN_DPROTECTED_NP = 216 - SYS_GETATTRLIST = 220 - SYS_SETATTRLIST = 221 - SYS_GETDIRENTRIESATTR = 222 - SYS_EXCHANGEDATA = 223 - SYS_SEARCHFS = 225 - SYS_DELETE = 226 - SYS_COPYFILE = 227 - SYS_FGETATTRLIST = 228 - SYS_FSETATTRLIST = 229 - SYS_POLL = 230 - SYS_WATCHEVENT = 231 - SYS_WAITEVENT = 232 - SYS_MODWATCH = 233 - SYS_GETXATTR = 234 - SYS_FGETXATTR = 235 - SYS_SETXATTR = 236 - SYS_FSETXATTR = 237 - SYS_REMOVEXATTR = 238 - SYS_FREMOVEXATTR = 239 - SYS_LISTXATTR = 240 - SYS_FLISTXATTR = 241 - SYS_FSCTL = 242 - SYS_INITGROUPS = 243 - SYS_POSIX_SPAWN = 244 - SYS_FFSCTL = 245 - SYS_NFSCLNT = 247 - SYS_FHOPEN = 248 - SYS_MINHERIT = 250 - SYS_SEMSYS = 251 - SYS_MSGSYS = 252 - SYS_SHMSYS = 253 - SYS_SEMCTL = 254 - SYS_SEMGET = 255 - SYS_SEMOP = 256 - SYS_MSGCTL = 258 - SYS_MSGGET = 259 - SYS_MSGSND = 260 - SYS_MSGRCV = 261 - SYS_SHMAT = 262 - SYS_SHMCTL = 263 - SYS_SHMDT = 264 - SYS_SHMGET = 265 - SYS_SHM_OPEN = 266 - SYS_SHM_UNLINK = 267 - SYS_SEM_OPEN = 268 - SYS_SEM_CLOSE = 269 - SYS_SEM_UNLINK = 270 - SYS_SEM_WAIT = 271 - SYS_SEM_TRYWAIT = 272 - SYS_SEM_POST = 273 - SYS_SYSCTLBYNAME = 274 - SYS_OPEN_EXTENDED = 277 - SYS_UMASK_EXTENDED = 278 - SYS_STAT_EXTENDED = 279 - SYS_LSTAT_EXTENDED = 280 - SYS_FSTAT_EXTENDED = 281 - SYS_CHMOD_EXTENDED = 282 - SYS_FCHMOD_EXTENDED = 283 - SYS_ACCESS_EXTENDED = 284 - SYS_SETTID = 285 - SYS_GETTID = 286 - SYS_SETSGROUPS = 287 - SYS_GETSGROUPS = 288 - SYS_SETWGROUPS = 289 - SYS_GETWGROUPS = 290 - SYS_MKFIFO_EXTENDED = 291 - SYS_MKDIR_EXTENDED = 292 - SYS_IDENTITYSVC = 293 - SYS_SHARED_REGION_CHECK_NP = 294 - SYS_VM_PRESSURE_MONITOR = 296 - SYS_PSYNCH_RW_LONGRDLOCK = 297 - SYS_PSYNCH_RW_YIELDWRLOCK = 298 - SYS_PSYNCH_RW_DOWNGRADE = 299 - SYS_PSYNCH_RW_UPGRADE = 300 - SYS_PSYNCH_MUTEXWAIT = 301 - SYS_PSYNCH_MUTEXDROP = 302 - SYS_PSYNCH_CVBROAD = 303 - SYS_PSYNCH_CVSIGNAL = 304 - SYS_PSYNCH_CVWAIT = 305 - SYS_PSYNCH_RW_RDLOCK = 306 - SYS_PSYNCH_RW_WRLOCK = 307 - SYS_PSYNCH_RW_UNLOCK = 308 - SYS_PSYNCH_RW_UNLOCK2 = 309 - SYS_GETSID = 310 - SYS_SETTID_WITH_PID = 311 - SYS_PSYNCH_CVCLRPREPOST = 312 - SYS_AIO_FSYNC = 313 - SYS_AIO_RETURN = 314 - SYS_AIO_SUSPEND = 315 - SYS_AIO_CANCEL = 316 - SYS_AIO_ERROR = 317 - SYS_AIO_READ = 318 - SYS_AIO_WRITE = 319 - SYS_LIO_LISTIO = 320 - SYS_IOPOLICYSYS = 322 - SYS_PROCESS_POLICY = 323 - SYS_MLOCKALL = 324 - SYS_MUNLOCKALL = 325 - SYS_ISSETUGID = 327 - SYS___PTHREAD_KILL = 328 - SYS___PTHREAD_SIGMASK = 329 - SYS___SIGWAIT = 330 - SYS___DISABLE_THREADSIGNAL = 331 - SYS___PTHREAD_MARKCANCEL = 332 - SYS___PTHREAD_CANCELED = 333 - SYS___SEMWAIT_SIGNAL = 334 - SYS_PROC_INFO = 336 - SYS_SENDFILE = 337 - SYS_STAT64 = 338 - SYS_FSTAT64 = 339 - SYS_LSTAT64 = 340 - SYS_STAT64_EXTENDED = 341 - SYS_LSTAT64_EXTENDED = 342 - SYS_FSTAT64_EXTENDED = 343 - SYS_GETDIRENTRIES64 = 344 - SYS_STATFS64 = 345 - SYS_FSTATFS64 = 346 - SYS_GETFSSTAT64 = 347 - SYS___PTHREAD_CHDIR = 348 - SYS___PTHREAD_FCHDIR = 349 - SYS_AUDIT = 350 - SYS_AUDITON = 351 - SYS_GETAUID = 353 - SYS_SETAUID = 354 - SYS_GETAUDIT_ADDR = 357 - SYS_SETAUDIT_ADDR = 358 - SYS_AUDITCTL = 359 - SYS_BSDTHREAD_CREATE = 360 - SYS_BSDTHREAD_TERMINATE = 361 - SYS_KQUEUE = 362 - SYS_KEVENT = 363 - SYS_LCHOWN = 364 - SYS_STACK_SNAPSHOT = 365 - SYS_BSDTHREAD_REGISTER = 366 - SYS_WORKQ_OPEN = 367 - SYS_WORKQ_KERNRETURN = 368 - SYS_KEVENT64 = 369 - SYS___OLD_SEMWAIT_SIGNAL = 370 - SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL = 371 - SYS_THREAD_SELFID = 372 - SYS_LEDGER = 373 - SYS___MAC_EXECVE = 380 - SYS___MAC_SYSCALL = 381 - SYS___MAC_GET_FILE = 382 - SYS___MAC_SET_FILE = 383 - SYS___MAC_GET_LINK = 384 - SYS___MAC_SET_LINK = 385 - SYS___MAC_GET_PROC = 386 - SYS___MAC_SET_PROC = 387 - SYS___MAC_GET_FD = 388 - SYS___MAC_SET_FD = 389 - SYS___MAC_GET_PID = 390 - SYS___MAC_GET_LCID = 391 - SYS___MAC_GET_LCTX = 392 - SYS___MAC_SET_LCTX = 393 - SYS_SETLCID = 394 - SYS_GETLCID = 395 - SYS_READ_NOCANCEL = 396 - SYS_WRITE_NOCANCEL = 397 - SYS_OPEN_NOCANCEL = 398 - SYS_CLOSE_NOCANCEL = 399 - SYS_WAIT4_NOCANCEL = 400 - SYS_RECVMSG_NOCANCEL = 401 - SYS_SENDMSG_NOCANCEL = 402 - SYS_RECVFROM_NOCANCEL = 403 - SYS_ACCEPT_NOCANCEL = 404 - SYS_MSYNC_NOCANCEL = 405 - SYS_FCNTL_NOCANCEL = 406 - SYS_SELECT_NOCANCEL = 407 - SYS_FSYNC_NOCANCEL = 408 - SYS_CONNECT_NOCANCEL = 409 - SYS_SIGSUSPEND_NOCANCEL = 410 - SYS_READV_NOCANCEL = 411 - SYS_WRITEV_NOCANCEL = 412 - SYS_SENDTO_NOCANCEL = 413 - SYS_PREAD_NOCANCEL = 414 - SYS_PWRITE_NOCANCEL = 415 - SYS_WAITID_NOCANCEL = 416 - SYS_POLL_NOCANCEL = 417 - SYS_MSGSND_NOCANCEL = 418 - SYS_MSGRCV_NOCANCEL = 419 - SYS_SEM_WAIT_NOCANCEL = 420 - SYS_AIO_SUSPEND_NOCANCEL = 421 - SYS___SIGWAIT_NOCANCEL = 422 - SYS___SEMWAIT_SIGNAL_NOCANCEL = 423 - SYS___MAC_MOUNT = 424 - SYS___MAC_GET_MOUNT = 425 - SYS___MAC_GETFSSTAT = 426 - SYS_FSGETPATH = 427 - SYS_AUDIT_SESSION_SELF = 428 - SYS_AUDIT_SESSION_JOIN = 429 - SYS_FILEPORT_MAKEPORT = 430 - SYS_FILEPORT_MAKEFD = 431 - SYS_AUDIT_SESSION_PORT = 432 - SYS_PID_SUSPEND = 433 - SYS_PID_RESUME = 434 - SYS_PID_HIBERNATE = 435 - SYS_PID_SHUTDOWN_SOCKETS = 436 - SYS_SHARED_REGION_MAP_AND_SLIDE_NP = 438 - SYS_KAS_INFO = 439 - SYS_MEMORYSTATUS_CONTROL = 440 - SYS_GUARDED_OPEN_NP = 441 - SYS_GUARDED_CLOSE_NP = 442 - SYS_GUARDED_KQUEUE_NP = 443 - SYS_CHANGE_FDGUARD_NP = 444 - SYS_PROC_RLIMIT_CONTROL = 446 - SYS_CONNECTX = 447 - SYS_DISCONNECTX = 448 - SYS_PEELOFF = 449 - SYS_SOCKET_DELEGATE = 450 - SYS_TELEMETRY = 451 - SYS_PROC_UUID_POLICY = 452 - SYS_MEMORYSTATUS_GET_LEVEL = 453 - SYS_SYSTEM_OVERRIDE = 454 - SYS_VFS_PURGE = 455 - SYS_SFI_CTL = 456 - SYS_SFI_PIDCTL = 457 - SYS_COALITION = 458 - SYS_COALITION_INFO = 459 - SYS_NECP_MATCH_POLICY = 460 - SYS_GETATTRLISTBULK = 461 - SYS_OPENAT = 463 - SYS_OPENAT_NOCANCEL = 464 - SYS_RENAMEAT = 465 - SYS_FACCESSAT = 466 - SYS_FCHMODAT = 467 - SYS_FCHOWNAT = 468 - SYS_FSTATAT = 469 - SYS_FSTATAT64 = 470 - SYS_LINKAT = 471 - SYS_UNLINKAT = 472 - SYS_READLINKAT = 473 - SYS_SYMLINKAT = 474 - SYS_MKDIRAT = 475 - SYS_GETATTRLISTAT = 476 - SYS_PROC_TRACE_LOG = 477 - SYS_BSDTHREAD_CTL = 478 - SYS_OPENBYID_NP = 479 - SYS_RECVMSG_X = 480 - SYS_SENDMSG_X = 481 - SYS_THREAD_SELFUSAGE = 482 - SYS_CSRCTL = 483 - SYS_GUARDED_OPEN_DPROTECTED_NP = 484 - SYS_GUARDED_WRITE_NP = 485 - SYS_GUARDED_PWRITE_NP = 486 - SYS_GUARDED_WRITEV_NP = 487 - SYS_RENAME_EXT = 488 - SYS_MREMAP_ENCRYPTED = 489 - SYS_MAXSYSCALL = 490 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_386.go deleted file mode 100644 index 785240a75..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_386.go +++ /dev/null @@ -1,304 +0,0 @@ -// mksysnum_dragonfly.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,dragonfly - -package unix - -const ( - // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int - SYS_EXIT = 1 // { void exit(int rval); } - SYS_FORK = 2 // { int fork(void); } - SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); } - SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } - SYS_CLOSE = 6 // { int close(int fd); } - SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, \ - SYS_LINK = 9 // { int link(char *path, char *link); } - SYS_UNLINK = 10 // { int unlink(char *path); } - SYS_CHDIR = 12 // { int chdir(char *path); } - SYS_FCHDIR = 13 // { int fchdir(int fd); } - SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } - SYS_CHMOD = 15 // { int chmod(char *path, int mode); } - SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } - SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int - SYS_GETFSSTAT = 18 // { int getfsstat(struct statfs *buf, long bufsize, \ - SYS_GETPID = 20 // { pid_t getpid(void); } - SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, \ - SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } - SYS_SETUID = 23 // { int setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t getuid(void); } - SYS_GETEUID = 25 // { uid_t geteuid(void); } - SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, \ - SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } - SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } - SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, \ - SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, int *anamelen); } - SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, int *alen); } - SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, int *alen); } - SYS_ACCESS = 33 // { int access(char *path, int flags); } - SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } - SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } - SYS_SYNC = 36 // { int sync(void); } - SYS_KILL = 37 // { int kill(int pid, int signum); } - SYS_GETPPID = 39 // { pid_t getppid(void); } - SYS_DUP = 41 // { int dup(u_int fd); } - SYS_PIPE = 42 // { int pipe(void); } - SYS_GETEGID = 43 // { gid_t getegid(void); } - SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, \ - SYS_GETGID = 47 // { gid_t getgid(void); } - SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } - SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } - SYS_ACCT = 51 // { int acct(char *path); } - SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); } - SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } - SYS_REBOOT = 55 // { int reboot(int opt); } - SYS_REVOKE = 56 // { int revoke(char *path); } - SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } - SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); } - SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); } - SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int - SYS_CHROOT = 61 // { int chroot(char *path); } - SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); } - SYS_VFORK = 66 // { pid_t vfork(void); } - SYS_SBRK = 69 // { int sbrk(int incr); } - SYS_SSTK = 70 // { int sstk(int incr); } - SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int mprotect(void *addr, size_t len, int prot); } - SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); } - SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); } - SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); } - SYS_GETPGRP = 81 // { int getpgrp(void); } - SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } - SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, \ - SYS_SWAPON = 85 // { int swapon(char *name); } - SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); } - SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } - SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } - SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } - SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ - SYS_FSYNC = 95 // { int fsync(int fd); } - SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); } - SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); } - SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); } - SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } - SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); } - SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int listen(int s, int backlog); } - SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ - SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); } - SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); } - SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ - SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ - SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } - SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } - SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } - SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } - SYS_RENAME = 128 // { int rename(char *from, char *to); } - SYS_FLOCK = 131 // { int flock(int fd, int how); } - SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } - SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ - SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, \ - SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } - SYS_RMDIR = 137 // { int rmdir(char *path); } - SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); } - SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ - SYS_SETSID = 147 // { int setsid(void); } - SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ - SYS_STATFS = 157 // { int statfs(char *path, struct statfs *buf); } - SYS_FSTATFS = 158 // { int fstatfs(int fd, struct statfs *buf); } - SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); } - SYS_GETDOMAINNAME = 162 // { int getdomainname(char *domainname, int len); } - SYS_SETDOMAINNAME = 163 // { int setdomainname(char *domainname, int len); } - SYS_UNAME = 164 // { int uname(struct utsname *name); } - SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } - SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ - SYS_EXTPREAD = 173 // { ssize_t extpread(int fd, void *buf, \ - SYS_EXTPWRITE = 174 // { ssize_t extpwrite(int fd, const void *buf, \ - SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int setgid(gid_t gid); } - SYS_SETEGID = 182 // { int setegid(gid_t egid); } - SYS_SETEUID = 183 // { int seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } - SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ - SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ - SYS_MMAP = 197 // { caddr_t mmap(caddr_t addr, size_t len, int prot, \ - // SYS_NOSYS = 198; // { int nosys(void); } __syscall __syscall_args int - SYS_LSEEK = 199 // { off_t lseek(int fd, int pad, off_t offset, \ - SYS_TRUNCATE = 200 // { int truncate(char *path, int pad, off_t length); } - SYS_FTRUNCATE = 201 // { int ftruncate(int fd, int pad, off_t length); } - SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, \ - SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int undelete(char *path); } - SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } - SYS_GETPGID = 207 // { int getpgid(pid_t pid); } - SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ - SYS___SEMCTL = 220 // { int __semctl(int semid, int semnum, int cmd, \ - SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); } - SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, \ - SYS_MSGCTL = 224 // { int msgctl(int msqid, int cmd, \ - SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int msgsnd(int msqid, void *msgp, size_t msgsz, \ - SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, \ - SYS_SHMAT = 228 // { caddr_t shmat(int shmid, const void *shmaddr, \ - SYS_SHMCTL = 229 // { int shmctl(int shmid, int cmd, \ - SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); } - SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); } - SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 233 // { int clock_settime(clockid_t clock_id, \ - SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ - SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ - SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); } - SYS_RFORK = 251 // { int rfork(int flags); } - SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, \ - SYS_ISSETUGID = 253 // { int issetugid(void); } - SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } - SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } - SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); } - SYS_EXTPREADV = 289 // { ssize_t extpreadv(int fd, struct iovec *iovp, \ - SYS_EXTPWRITEV = 290 // { ssize_t extpwritev(int fd, struct iovec *iovp,\ - SYS_FHSTATFS = 297 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); } - SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); } - SYS_MODNEXT = 300 // { int modnext(int modid); } - SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat* stat); } - SYS_MODFNEXT = 302 // { int modfnext(int modid); } - SYS_MODFIND = 303 // { int modfind(const char *name); } - SYS_KLDLOAD = 304 // { int kldload(const char *file); } - SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } - SYS_KLDFIND = 306 // { int kldfind(const char *file); } - SYS_KLDNEXT = 307 // { int kldnext(int fileid); } - SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); } - SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } - SYS_GETSID = 310 // { int getsid(pid_t pid); } - SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); } - SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); } - SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); } - SYS_AIO_SUSPEND = 315 // { int aio_suspend(struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); } - SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); } - SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); } - SYS_AIO_READ = 318 // { int aio_read(struct aiocb *aiocbp); } - SYS_AIO_WRITE = 319 // { int aio_write(struct aiocb *aiocbp); } - SYS_LIO_LISTIO = 320 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); } - SYS_YIELD = 321 // { int yield(void); } - SYS_MLOCKALL = 324 // { int mlockall(int how); } - SYS_MUNLOCKALL = 325 // { int munlockall(void); } - SYS___GETCWD = 326 // { int __getcwd(u_char *buf, u_int buflen); } - SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); } - SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); } - SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); } - SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } - SYS_SCHED_YIELD = 331 // { int sched_yield (void); } - SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } - SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } - SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); } - SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } - SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); } - SYS_JAIL = 338 // { int jail(struct jail *jail); } - SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, \ - SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } - SYS_SIGACTION = 342 // { int sigaction(int sig, const struct sigaction *act, \ - SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } - SYS_SIGRETURN = 344 // { int sigreturn(ucontext_t *sigcntxp); } - SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set,\ - SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set,\ - SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ - SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ - SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, \ - SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, \ - SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ - SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); } - SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ - SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, \ - SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ - SYS_EXTATTR_SET_FILE = 356 // { int extattr_set_file(const char *path, \ - SYS_EXTATTR_GET_FILE = 357 // { int extattr_get_file(const char *path, \ - SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ - SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete(struct aiocb **aiocbp, struct timespec *timeout); } - SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); } - SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); } - SYS_KQUEUE = 362 // { int kqueue(void); } - SYS_KEVENT = 363 // { int kevent(int fd, \ - SYS_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } - SYS_LCHFLAGS = 391 // { int lchflags(char *path, int flags); } - SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); } - SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, \ - SYS_VARSYM_SET = 450 // { int varsym_set(int level, const char *name, const char *data); } - SYS_VARSYM_GET = 451 // { int varsym_get(int mask, const char *wild, char *buf, int bufsize); } - SYS_VARSYM_LIST = 452 // { int varsym_list(int level, char *buf, int maxsize, int *marker); } - SYS_EXEC_SYS_REGISTER = 465 // { int exec_sys_register(void *entry); } - SYS_EXEC_SYS_UNREGISTER = 466 // { int exec_sys_unregister(int id); } - SYS_SYS_CHECKPOINT = 467 // { int sys_checkpoint(int type, int fd, pid_t pid, int retval); } - SYS_MOUNTCTL = 468 // { int mountctl(const char *path, int op, int fd, const void *ctl, int ctllen, void *buf, int buflen); } - SYS_UMTX_SLEEP = 469 // { int umtx_sleep(volatile const int *ptr, int value, int timeout); } - SYS_UMTX_WAKEUP = 470 // { int umtx_wakeup(volatile const int *ptr, int count); } - SYS_JAIL_ATTACH = 471 // { int jail_attach(int jid); } - SYS_SET_TLS_AREA = 472 // { int set_tls_area(int which, struct tls_info *info, size_t infosize); } - SYS_GET_TLS_AREA = 473 // { int get_tls_area(int which, struct tls_info *info, size_t infosize); } - SYS_CLOSEFROM = 474 // { int closefrom(int fd); } - SYS_STAT = 475 // { int stat(const char *path, struct stat *ub); } - SYS_FSTAT = 476 // { int fstat(int fd, struct stat *sb); } - SYS_LSTAT = 477 // { int lstat(const char *path, struct stat *ub); } - SYS_FHSTAT = 478 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); } - SYS_GETDIRENTRIES = 479 // { int getdirentries(int fd, char *buf, u_int count, \ - SYS_GETDENTS = 480 // { int getdents(int fd, char *buf, size_t count); } - SYS_USCHED_SET = 481 // { int usched_set(pid_t pid, int cmd, void *data, \ - SYS_EXTACCEPT = 482 // { int extaccept(int s, int flags, caddr_t name, int *anamelen); } - SYS_EXTCONNECT = 483 // { int extconnect(int s, int flags, caddr_t name, int namelen); } - SYS_MCONTROL = 485 // { int mcontrol(void *addr, size_t len, int behav, off_t value); } - SYS_VMSPACE_CREATE = 486 // { int vmspace_create(void *id, int type, void *data); } - SYS_VMSPACE_DESTROY = 487 // { int vmspace_destroy(void *id); } - SYS_VMSPACE_CTL = 488 // { int vmspace_ctl(void *id, int cmd, \ - SYS_VMSPACE_MMAP = 489 // { int vmspace_mmap(void *id, void *addr, size_t len, \ - SYS_VMSPACE_MUNMAP = 490 // { int vmspace_munmap(void *id, void *addr, \ - SYS_VMSPACE_MCONTROL = 491 // { int vmspace_mcontrol(void *id, void *addr, \ - SYS_VMSPACE_PREAD = 492 // { ssize_t vmspace_pread(void *id, void *buf, \ - SYS_VMSPACE_PWRITE = 493 // { ssize_t vmspace_pwrite(void *id, const void *buf, \ - SYS_EXTEXIT = 494 // { void extexit(int how, int status, void *addr); } - SYS_LWP_CREATE = 495 // { int lwp_create(struct lwp_params *params); } - SYS_LWP_GETTID = 496 // { lwpid_t lwp_gettid(void); } - SYS_LWP_KILL = 497 // { int lwp_kill(pid_t pid, lwpid_t tid, int signum); } - SYS_LWP_RTPRIO = 498 // { int lwp_rtprio(int function, pid_t pid, lwpid_t tid, struct rtprio *rtp); } - SYS_PSELECT = 499 // { int pselect(int nd, fd_set *in, fd_set *ou, \ - SYS_STATVFS = 500 // { int statvfs(const char *path, struct statvfs *buf); } - SYS_FSTATVFS = 501 // { int fstatvfs(int fd, struct statvfs *buf); } - SYS_FHSTATVFS = 502 // { int fhstatvfs(const struct fhandle *u_fhp, struct statvfs *buf); } - SYS_GETVFSSTAT = 503 // { int getvfsstat(struct statfs *buf, \ - SYS_OPENAT = 504 // { int openat(int fd, char *path, int flags, int mode); } - SYS_FSTATAT = 505 // { int fstatat(int fd, char *path, \ - SYS_FCHMODAT = 506 // { int fchmodat(int fd, char *path, int mode, \ - SYS_FCHOWNAT = 507 // { int fchownat(int fd, char *path, int uid, int gid, \ - SYS_UNLINKAT = 508 // { int unlinkat(int fd, char *path, int flags); } - SYS_FACCESSAT = 509 // { int faccessat(int fd, char *path, int amode, \ - SYS_MQ_OPEN = 510 // { mqd_t mq_open(const char * name, int oflag, \ - SYS_MQ_CLOSE = 511 // { int mq_close(mqd_t mqdes); } - SYS_MQ_UNLINK = 512 // { int mq_unlink(const char *name); } - SYS_MQ_GETATTR = 513 // { int mq_getattr(mqd_t mqdes, \ - SYS_MQ_SETATTR = 514 // { int mq_setattr(mqd_t mqdes, \ - SYS_MQ_NOTIFY = 515 // { int mq_notify(mqd_t mqdes, \ - SYS_MQ_SEND = 516 // { int mq_send(mqd_t mqdes, const char *msg_ptr, \ - SYS_MQ_RECEIVE = 517 // { ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, \ - SYS_MQ_TIMEDSEND = 518 // { int mq_timedsend(mqd_t mqdes, \ - SYS_MQ_TIMEDRECEIVE = 519 // { ssize_t mq_timedreceive(mqd_t mqdes, \ - SYS_IOPRIO_SET = 520 // { int ioprio_set(int which, int who, int prio); } - SYS_IOPRIO_GET = 521 // { int ioprio_get(int which, int who); } - SYS_CHROOT_KERNEL = 522 // { int chroot_kernel(char *path); } - SYS_RENAMEAT = 523 // { int renameat(int oldfd, char *old, int newfd, \ - SYS_MKDIRAT = 524 // { int mkdirat(int fd, char *path, mode_t mode); } - SYS_MKFIFOAT = 525 // { int mkfifoat(int fd, char *path, mode_t mode); } - SYS_MKNODAT = 526 // { int mknodat(int fd, char *path, mode_t mode, \ - SYS_READLINKAT = 527 // { int readlinkat(int fd, char *path, char *buf, \ - SYS_SYMLINKAT = 528 // { int symlinkat(char *path1, int fd, char *path2); } - SYS_SWAPOFF = 529 // { int swapoff(char *name); } - SYS_VQUOTACTL = 530 // { int vquotactl(const char *path, \ - SYS_LINKAT = 531 // { int linkat(int fd1, char *path1, int fd2, \ - SYS_EACCESS = 532 // { int eaccess(char *path, int flags); } - SYS_LPATHCONF = 533 // { int lpathconf(char *path, int name); } - SYS_VMM_GUEST_CTL = 534 // { int vmm_guest_ctl(int op, struct vmm_guest_options *options); } - SYS_VMM_GUEST_SYNC_ADDR = 535 // { int vmm_guest_sync_addr(long *dstaddr, long *srcaddr); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go deleted file mode 100644 index d6038fa9b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go +++ /dev/null @@ -1,304 +0,0 @@ -// mksysnum_dragonfly.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build amd64,dragonfly - -package unix - -const ( - // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int - SYS_EXIT = 1 // { void exit(int rval); } - SYS_FORK = 2 // { int fork(void); } - SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); } - SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } - SYS_CLOSE = 6 // { int close(int fd); } - SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, \ - SYS_LINK = 9 // { int link(char *path, char *link); } - SYS_UNLINK = 10 // { int unlink(char *path); } - SYS_CHDIR = 12 // { int chdir(char *path); } - SYS_FCHDIR = 13 // { int fchdir(int fd); } - SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } - SYS_CHMOD = 15 // { int chmod(char *path, int mode); } - SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } - SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int - SYS_GETFSSTAT = 18 // { int getfsstat(struct statfs *buf, long bufsize, \ - SYS_GETPID = 20 // { pid_t getpid(void); } - SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, \ - SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } - SYS_SETUID = 23 // { int setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t getuid(void); } - SYS_GETEUID = 25 // { uid_t geteuid(void); } - SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, \ - SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } - SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } - SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, \ - SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, int *anamelen); } - SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, int *alen); } - SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, int *alen); } - SYS_ACCESS = 33 // { int access(char *path, int flags); } - SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } - SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } - SYS_SYNC = 36 // { int sync(void); } - SYS_KILL = 37 // { int kill(int pid, int signum); } - SYS_GETPPID = 39 // { pid_t getppid(void); } - SYS_DUP = 41 // { int dup(u_int fd); } - SYS_PIPE = 42 // { int pipe(void); } - SYS_GETEGID = 43 // { gid_t getegid(void); } - SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, \ - SYS_GETGID = 47 // { gid_t getgid(void); } - SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } - SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } - SYS_ACCT = 51 // { int acct(char *path); } - SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); } - SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } - SYS_REBOOT = 55 // { int reboot(int opt); } - SYS_REVOKE = 56 // { int revoke(char *path); } - SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } - SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); } - SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); } - SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int - SYS_CHROOT = 61 // { int chroot(char *path); } - SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); } - SYS_VFORK = 66 // { pid_t vfork(void); } - SYS_SBRK = 69 // { int sbrk(int incr); } - SYS_SSTK = 70 // { int sstk(int incr); } - SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int mprotect(void *addr, size_t len, int prot); } - SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); } - SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); } - SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); } - SYS_GETPGRP = 81 // { int getpgrp(void); } - SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } - SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, \ - SYS_SWAPON = 85 // { int swapon(char *name); } - SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); } - SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } - SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } - SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } - SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ - SYS_FSYNC = 95 // { int fsync(int fd); } - SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); } - SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); } - SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); } - SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } - SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); } - SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int listen(int s, int backlog); } - SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ - SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); } - SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); } - SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ - SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ - SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } - SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } - SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } - SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } - SYS_RENAME = 128 // { int rename(char *from, char *to); } - SYS_FLOCK = 131 // { int flock(int fd, int how); } - SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } - SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ - SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, \ - SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } - SYS_RMDIR = 137 // { int rmdir(char *path); } - SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); } - SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ - SYS_SETSID = 147 // { int setsid(void); } - SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ - SYS_STATFS = 157 // { int statfs(char *path, struct statfs *buf); } - SYS_FSTATFS = 158 // { int fstatfs(int fd, struct statfs *buf); } - SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); } - SYS_GETDOMAINNAME = 162 // { int getdomainname(char *domainname, int len); } - SYS_SETDOMAINNAME = 163 // { int setdomainname(char *domainname, int len); } - SYS_UNAME = 164 // { int uname(struct utsname *name); } - SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } - SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ - SYS_EXTPREAD = 173 // { ssize_t extpread(int fd, void *buf, \ - SYS_EXTPWRITE = 174 // { ssize_t extpwrite(int fd, const void *buf, \ - SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int setgid(gid_t gid); } - SYS_SETEGID = 182 // { int setegid(gid_t egid); } - SYS_SETEUID = 183 // { int seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } - SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ - SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ - SYS_MMAP = 197 // { caddr_t mmap(caddr_t addr, size_t len, int prot, \ - // SYS_NOSYS = 198; // { int nosys(void); } __syscall __syscall_args int - SYS_LSEEK = 199 // { off_t lseek(int fd, int pad, off_t offset, \ - SYS_TRUNCATE = 200 // { int truncate(char *path, int pad, off_t length); } - SYS_FTRUNCATE = 201 // { int ftruncate(int fd, int pad, off_t length); } - SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, \ - SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int undelete(char *path); } - SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } - SYS_GETPGID = 207 // { int getpgid(pid_t pid); } - SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ - SYS___SEMCTL = 220 // { int __semctl(int semid, int semnum, int cmd, \ - SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); } - SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, \ - SYS_MSGCTL = 224 // { int msgctl(int msqid, int cmd, \ - SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int msgsnd(int msqid, void *msgp, size_t msgsz, \ - SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, \ - SYS_SHMAT = 228 // { caddr_t shmat(int shmid, const void *shmaddr, \ - SYS_SHMCTL = 229 // { int shmctl(int shmid, int cmd, \ - SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); } - SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); } - SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 233 // { int clock_settime(clockid_t clock_id, \ - SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ - SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ - SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); } - SYS_RFORK = 251 // { int rfork(int flags); } - SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, \ - SYS_ISSETUGID = 253 // { int issetugid(void); } - SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } - SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } - SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); } - SYS_EXTPREADV = 289 // { ssize_t extpreadv(int fd, struct iovec *iovp, \ - SYS_EXTPWRITEV = 290 // { ssize_t extpwritev(int fd, struct iovec *iovp,\ - SYS_FHSTATFS = 297 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); } - SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); } - SYS_MODNEXT = 300 // { int modnext(int modid); } - SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat* stat); } - SYS_MODFNEXT = 302 // { int modfnext(int modid); } - SYS_MODFIND = 303 // { int modfind(const char *name); } - SYS_KLDLOAD = 304 // { int kldload(const char *file); } - SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } - SYS_KLDFIND = 306 // { int kldfind(const char *file); } - SYS_KLDNEXT = 307 // { int kldnext(int fileid); } - SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); } - SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } - SYS_GETSID = 310 // { int getsid(pid_t pid); } - SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); } - SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); } - SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); } - SYS_AIO_SUSPEND = 315 // { int aio_suspend(struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); } - SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); } - SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); } - SYS_AIO_READ = 318 // { int aio_read(struct aiocb *aiocbp); } - SYS_AIO_WRITE = 319 // { int aio_write(struct aiocb *aiocbp); } - SYS_LIO_LISTIO = 320 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); } - SYS_YIELD = 321 // { int yield(void); } - SYS_MLOCKALL = 324 // { int mlockall(int how); } - SYS_MUNLOCKALL = 325 // { int munlockall(void); } - SYS___GETCWD = 326 // { int __getcwd(u_char *buf, u_int buflen); } - SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); } - SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); } - SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); } - SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } - SYS_SCHED_YIELD = 331 // { int sched_yield (void); } - SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } - SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } - SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); } - SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } - SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); } - SYS_JAIL = 338 // { int jail(struct jail *jail); } - SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, \ - SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } - SYS_SIGACTION = 342 // { int sigaction(int sig, const struct sigaction *act, \ - SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } - SYS_SIGRETURN = 344 // { int sigreturn(ucontext_t *sigcntxp); } - SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set,\ - SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set,\ - SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ - SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ - SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, \ - SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, \ - SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ - SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); } - SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ - SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, \ - SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ - SYS_EXTATTR_SET_FILE = 356 // { int extattr_set_file(const char *path, \ - SYS_EXTATTR_GET_FILE = 357 // { int extattr_get_file(const char *path, \ - SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ - SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete(struct aiocb **aiocbp, struct timespec *timeout); } - SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); } - SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); } - SYS_KQUEUE = 362 // { int kqueue(void); } - SYS_KEVENT = 363 // { int kevent(int fd, \ - SYS_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } - SYS_LCHFLAGS = 391 // { int lchflags(char *path, int flags); } - SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); } - SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, \ - SYS_VARSYM_SET = 450 // { int varsym_set(int level, const char *name, const char *data); } - SYS_VARSYM_GET = 451 // { int varsym_get(int mask, const char *wild, char *buf, int bufsize); } - SYS_VARSYM_LIST = 452 // { int varsym_list(int level, char *buf, int maxsize, int *marker); } - SYS_EXEC_SYS_REGISTER = 465 // { int exec_sys_register(void *entry); } - SYS_EXEC_SYS_UNREGISTER = 466 // { int exec_sys_unregister(int id); } - SYS_SYS_CHECKPOINT = 467 // { int sys_checkpoint(int type, int fd, pid_t pid, int retval); } - SYS_MOUNTCTL = 468 // { int mountctl(const char *path, int op, int fd, const void *ctl, int ctllen, void *buf, int buflen); } - SYS_UMTX_SLEEP = 469 // { int umtx_sleep(volatile const int *ptr, int value, int timeout); } - SYS_UMTX_WAKEUP = 470 // { int umtx_wakeup(volatile const int *ptr, int count); } - SYS_JAIL_ATTACH = 471 // { int jail_attach(int jid); } - SYS_SET_TLS_AREA = 472 // { int set_tls_area(int which, struct tls_info *info, size_t infosize); } - SYS_GET_TLS_AREA = 473 // { int get_tls_area(int which, struct tls_info *info, size_t infosize); } - SYS_CLOSEFROM = 474 // { int closefrom(int fd); } - SYS_STAT = 475 // { int stat(const char *path, struct stat *ub); } - SYS_FSTAT = 476 // { int fstat(int fd, struct stat *sb); } - SYS_LSTAT = 477 // { int lstat(const char *path, struct stat *ub); } - SYS_FHSTAT = 478 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); } - SYS_GETDIRENTRIES = 479 // { int getdirentries(int fd, char *buf, u_int count, \ - SYS_GETDENTS = 480 // { int getdents(int fd, char *buf, size_t count); } - SYS_USCHED_SET = 481 // { int usched_set(pid_t pid, int cmd, void *data, \ - SYS_EXTACCEPT = 482 // { int extaccept(int s, int flags, caddr_t name, int *anamelen); } - SYS_EXTCONNECT = 483 // { int extconnect(int s, int flags, caddr_t name, int namelen); } - SYS_MCONTROL = 485 // { int mcontrol(void *addr, size_t len, int behav, off_t value); } - SYS_VMSPACE_CREATE = 486 // { int vmspace_create(void *id, int type, void *data); } - SYS_VMSPACE_DESTROY = 487 // { int vmspace_destroy(void *id); } - SYS_VMSPACE_CTL = 488 // { int vmspace_ctl(void *id, int cmd, \ - SYS_VMSPACE_MMAP = 489 // { int vmspace_mmap(void *id, void *addr, size_t len, \ - SYS_VMSPACE_MUNMAP = 490 // { int vmspace_munmap(void *id, void *addr, \ - SYS_VMSPACE_MCONTROL = 491 // { int vmspace_mcontrol(void *id, void *addr, \ - SYS_VMSPACE_PREAD = 492 // { ssize_t vmspace_pread(void *id, void *buf, \ - SYS_VMSPACE_PWRITE = 493 // { ssize_t vmspace_pwrite(void *id, const void *buf, \ - SYS_EXTEXIT = 494 // { void extexit(int how, int status, void *addr); } - SYS_LWP_CREATE = 495 // { int lwp_create(struct lwp_params *params); } - SYS_LWP_GETTID = 496 // { lwpid_t lwp_gettid(void); } - SYS_LWP_KILL = 497 // { int lwp_kill(pid_t pid, lwpid_t tid, int signum); } - SYS_LWP_RTPRIO = 498 // { int lwp_rtprio(int function, pid_t pid, lwpid_t tid, struct rtprio *rtp); } - SYS_PSELECT = 499 // { int pselect(int nd, fd_set *in, fd_set *ou, \ - SYS_STATVFS = 500 // { int statvfs(const char *path, struct statvfs *buf); } - SYS_FSTATVFS = 501 // { int fstatvfs(int fd, struct statvfs *buf); } - SYS_FHSTATVFS = 502 // { int fhstatvfs(const struct fhandle *u_fhp, struct statvfs *buf); } - SYS_GETVFSSTAT = 503 // { int getvfsstat(struct statfs *buf, \ - SYS_OPENAT = 504 // { int openat(int fd, char *path, int flags, int mode); } - SYS_FSTATAT = 505 // { int fstatat(int fd, char *path, \ - SYS_FCHMODAT = 506 // { int fchmodat(int fd, char *path, int mode, \ - SYS_FCHOWNAT = 507 // { int fchownat(int fd, char *path, int uid, int gid, \ - SYS_UNLINKAT = 508 // { int unlinkat(int fd, char *path, int flags); } - SYS_FACCESSAT = 509 // { int faccessat(int fd, char *path, int amode, \ - SYS_MQ_OPEN = 510 // { mqd_t mq_open(const char * name, int oflag, \ - SYS_MQ_CLOSE = 511 // { int mq_close(mqd_t mqdes); } - SYS_MQ_UNLINK = 512 // { int mq_unlink(const char *name); } - SYS_MQ_GETATTR = 513 // { int mq_getattr(mqd_t mqdes, \ - SYS_MQ_SETATTR = 514 // { int mq_setattr(mqd_t mqdes, \ - SYS_MQ_NOTIFY = 515 // { int mq_notify(mqd_t mqdes, \ - SYS_MQ_SEND = 516 // { int mq_send(mqd_t mqdes, const char *msg_ptr, \ - SYS_MQ_RECEIVE = 517 // { ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, \ - SYS_MQ_TIMEDSEND = 518 // { int mq_timedsend(mqd_t mqdes, \ - SYS_MQ_TIMEDRECEIVE = 519 // { ssize_t mq_timedreceive(mqd_t mqdes, \ - SYS_IOPRIO_SET = 520 // { int ioprio_set(int which, int who, int prio); } - SYS_IOPRIO_GET = 521 // { int ioprio_get(int which, int who); } - SYS_CHROOT_KERNEL = 522 // { int chroot_kernel(char *path); } - SYS_RENAMEAT = 523 // { int renameat(int oldfd, char *old, int newfd, \ - SYS_MKDIRAT = 524 // { int mkdirat(int fd, char *path, mode_t mode); } - SYS_MKFIFOAT = 525 // { int mkfifoat(int fd, char *path, mode_t mode); } - SYS_MKNODAT = 526 // { int mknodat(int fd, char *path, mode_t mode, \ - SYS_READLINKAT = 527 // { int readlinkat(int fd, char *path, char *buf, \ - SYS_SYMLINKAT = 528 // { int symlinkat(char *path1, int fd, char *path2); } - SYS_SWAPOFF = 529 // { int swapoff(char *name); } - SYS_VQUOTACTL = 530 // { int vquotactl(const char *path, \ - SYS_LINKAT = 531 // { int linkat(int fd1, char *path1, int fd2, \ - SYS_EACCESS = 532 // { int eaccess(char *path, int flags); } - SYS_LPATHCONF = 533 // { int lpathconf(char *path, int name); } - SYS_VMM_GUEST_CTL = 534 // { int vmm_guest_ctl(int op, struct vmm_guest_options *options); } - SYS_VMM_GUEST_SYNC_ADDR = 535 // { int vmm_guest_sync_addr(long *dstaddr, long *srcaddr); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_386.go deleted file mode 100644 index 262a84536..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_386.go +++ /dev/null @@ -1,351 +0,0 @@ -// mksysnum_freebsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,freebsd - -package unix - -const ( - // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int - SYS_EXIT = 1 // { void sys_exit(int rval); } exit \ - SYS_FORK = 2 // { int fork(void); } - SYS_READ = 3 // { ssize_t read(int fd, void *buf, \ - SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \ - SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } - SYS_CLOSE = 6 // { int close(int fd); } - SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \ - SYS_LINK = 9 // { int link(char *path, char *link); } - SYS_UNLINK = 10 // { int unlink(char *path); } - SYS_CHDIR = 12 // { int chdir(char *path); } - SYS_FCHDIR = 13 // { int fchdir(int fd); } - SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } - SYS_CHMOD = 15 // { int chmod(char *path, int mode); } - SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } - SYS_OBREAK = 17 // { int obreak(char *nsize); } break \ - SYS_GETPID = 20 // { pid_t getpid(void); } - SYS_MOUNT = 21 // { int mount(char *type, char *path, \ - SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } - SYS_SETUID = 23 // { int setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t getuid(void); } - SYS_GETEUID = 25 // { uid_t geteuid(void); } - SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \ - SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \ - SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \ - SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \ - SYS_ACCEPT = 30 // { int accept(int s, \ - SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \ - SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \ - SYS_ACCESS = 33 // { int access(char *path, int amode); } - SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); } - SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); } - SYS_SYNC = 36 // { int sync(void); } - SYS_KILL = 37 // { int kill(int pid, int signum); } - SYS_GETPPID = 39 // { pid_t getppid(void); } - SYS_DUP = 41 // { int dup(u_int fd); } - SYS_PIPE = 42 // { int pipe(void); } - SYS_GETEGID = 43 // { gid_t getegid(void); } - SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \ - SYS_GETGID = 47 // { gid_t getgid(void); } - SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \ - SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } - SYS_ACCT = 51 // { int acct(char *path); } - SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \ - SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \ - SYS_REBOOT = 55 // { int reboot(int opt); } - SYS_REVOKE = 56 // { int revoke(char *path); } - SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } - SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \ - SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \ - SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \ - SYS_CHROOT = 61 // { int chroot(char *path); } - SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \ - SYS_VFORK = 66 // { int vfork(void); } - SYS_SBRK = 69 // { int sbrk(int incr); } - SYS_SSTK = 70 // { int sstk(int incr); } - SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \ - SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \ - SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \ - SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \ - SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \ - SYS_GETPGRP = 81 // { int getpgrp(void); } - SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } - SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \ - SYS_SWAPON = 85 // { int swapon(char *name); } - SYS_GETITIMER = 86 // { int getitimer(u_int which, \ - SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } - SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } - SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } - SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ - SYS_FSYNC = 95 // { int fsync(int fd); } - SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \ - SYS_SOCKET = 97 // { int socket(int domain, int type, \ - SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \ - SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } - SYS_BIND = 104 // { int bind(int s, caddr_t name, \ - SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int listen(int s, int backlog); } - SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ - SYS_GETRUSAGE = 117 // { int getrusage(int who, \ - SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \ - SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ - SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ - SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } - SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } - SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } - SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } - SYS_RENAME = 128 // { int rename(char *from, char *to); } - SYS_FLOCK = 131 // { int flock(int fd, int how); } - SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } - SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ - SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \ - SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } - SYS_RMDIR = 137 // { int rmdir(char *path); } - SYS_UTIMES = 138 // { int utimes(char *path, \ - SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ - SYS_SETSID = 147 // { int setsid(void); } - SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ - SYS_LGETFH = 160 // { int lgetfh(char *fname, \ - SYS_GETFH = 161 // { int getfh(char *fname, \ - SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } - SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ - SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \ - SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \ - SYS_SETFIB = 175 // { int setfib(int fibnum); } - SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int setgid(gid_t gid); } - SYS_SETEGID = 182 // { int setegid(gid_t egid); } - SYS_SETEUID = 183 // { int seteuid(uid_t euid); } - SYS_STAT = 188 // { int stat(char *path, struct stat *ub); } - SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); } - SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); } - SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } - SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ - SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ - SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \ - SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \ - SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \ - SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \ - SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \ - SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \ - SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int undelete(char *path); } - SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } - SYS_GETPGID = 207 // { int getpgid(pid_t pid); } - SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ - SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 233 // { int clock_settime( \ - SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ - SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \ - SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); } - SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \ - SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \ - SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); } - SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ - SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); } - SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \ - SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \ - SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\ - SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); } - SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \ - SYS_RFORK = 251 // { int rfork(int flags); } - SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \ - SYS_ISSETUGID = 253 // { int issetugid(void); } - SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } - SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \ - SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } - SYS_LUTIMES = 276 // { int lutimes(char *path, \ - SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); } - SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); } - SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); } - SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \ - SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \ - SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \ - SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \ - SYS_MODNEXT = 300 // { int modnext(int modid); } - SYS_MODSTAT = 301 // { int modstat(int modid, \ - SYS_MODFNEXT = 302 // { int modfnext(int modid); } - SYS_MODFIND = 303 // { int modfind(const char *name); } - SYS_KLDLOAD = 304 // { int kldload(const char *file); } - SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } - SYS_KLDFIND = 306 // { int kldfind(const char *file); } - SYS_KLDNEXT = 307 // { int kldnext(int fileid); } - SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \ - SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } - SYS_GETSID = 310 // { int getsid(pid_t pid); } - SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \ - SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \ - SYS_YIELD = 321 // { int yield(void); } - SYS_MLOCKALL = 324 // { int mlockall(int how); } - SYS_MUNLOCKALL = 325 // { int munlockall(void); } - SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); } - SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \ - SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \ - SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \ - SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } - SYS_SCHED_YIELD = 331 // { int sched_yield (void); } - SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } - SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } - SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \ - SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } - SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \ - SYS_JAIL = 338 // { int jail(struct jail *jail); } - SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \ - SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } - SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } - SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \ - SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \ - SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ - SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ - SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \ - SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \ - SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ - SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \ - SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ - SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \ - SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ - SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \ - SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \ - SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ - SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \ - SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \ - SYS_KQUEUE = 362 // { int kqueue(void); } - SYS_KEVENT = 363 // { int kevent(int fd, \ - SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \ - SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \ - SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \ - SYS___SETUGID = 374 // { int __setugid(int flag); } - SYS_EACCESS = 376 // { int eaccess(char *path, int amode); } - SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \ - SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); } - SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); } - SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \ - SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \ - SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \ - SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \ - SYS_KENV = 390 // { int kenv(int what, const char *name, \ - SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \ - SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \ - SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \ - SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \ - SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \ - SYS_STATFS = 396 // { int statfs(char *path, \ - SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); } - SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \ - SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \ - SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \ - SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \ - SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \ - SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \ - SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \ - SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \ - SYS_SIGACTION = 416 // { int sigaction(int sig, \ - SYS_SIGRETURN = 417 // { int sigreturn( \ - SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); } - SYS_SETCONTEXT = 422 // { int setcontext( \ - SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \ - SYS_SWAPOFF = 424 // { int swapoff(const char *name); } - SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \ - SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \ - SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \ - SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \ - SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \ - SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \ - SYS_THR_EXIT = 431 // { void thr_exit(long *state); } - SYS_THR_SELF = 432 // { int thr_self(long *id); } - SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); } - SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); } - SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); } - SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); } - SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \ - SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \ - SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \ - SYS_THR_SUSPEND = 442 // { int thr_suspend( \ - SYS_THR_WAKE = 443 // { int thr_wake(long id); } - SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); } - SYS_AUDIT = 445 // { int audit(const void *record, \ - SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \ - SYS_GETAUID = 447 // { int getauid(uid_t *auid); } - SYS_SETAUID = 448 // { int setauid(uid_t *auid); } - SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); } - SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); } - SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \ - SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \ - SYS_AUDITCTL = 453 // { int auditctl(char *path); } - SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \ - SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \ - SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); } - SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); } - SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); } - SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \ - SYS_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } - SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ - SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ - SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ - SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \ - SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \ - SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \ - SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \ - SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); } - SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); } - SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); } - SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \ - SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); } - SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); } - SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \ - SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \ - SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \ - SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \ - SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \ - SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \ - SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \ - SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \ - SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \ - SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \ - SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \ - SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); } - SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); } - SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \ - SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \ - SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \ - SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \ - SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \ - SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); } - SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); } - SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \ - SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \ - SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); } - SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); } - SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); } - SYS_CAP_NEW = 514 // { int cap_new(int fd, uint64_t rights); } - SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ - SYS_CAP_ENTER = 516 // { int cap_enter(void); } - SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); } - SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); } - SYS_PDKILL = 519 // { int pdkill(int fd, int signum); } - SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); } - SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \ - SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \ - SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); } - SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \ - SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \ - SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \ - SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \ - SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \ - SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \ - SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \ - SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \ - SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \ - SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \ - SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \ - SYS_ACCEPT4 = 541 // { int accept4(int s, \ - SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); } - SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \ - SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \ -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_arm.go deleted file mode 100644 index 206b9f612..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_arm.go +++ /dev/null @@ -1,351 +0,0 @@ -// mksysnum_freebsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build arm,freebsd - -package unix - -const ( - // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int - SYS_EXIT = 1 // { void sys_exit(int rval); } exit \ - SYS_FORK = 2 // { int fork(void); } - SYS_READ = 3 // { ssize_t read(int fd, void *buf, \ - SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, \ - SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } - SYS_CLOSE = 6 // { int close(int fd); } - SYS_WAIT4 = 7 // { int wait4(int pid, int *status, \ - SYS_LINK = 9 // { int link(char *path, char *link); } - SYS_UNLINK = 10 // { int unlink(char *path); } - SYS_CHDIR = 12 // { int chdir(char *path); } - SYS_FCHDIR = 13 // { int fchdir(int fd); } - SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } - SYS_CHMOD = 15 // { int chmod(char *path, int mode); } - SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } - SYS_OBREAK = 17 // { int obreak(char *nsize); } break \ - SYS_GETPID = 20 // { pid_t getpid(void); } - SYS_MOUNT = 21 // { int mount(char *type, char *path, \ - SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } - SYS_SETUID = 23 // { int setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t getuid(void); } - SYS_GETEUID = 25 // { uid_t geteuid(void); } - SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, \ - SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, \ - SYS_SENDMSG = 28 // { int sendmsg(int s, struct msghdr *msg, \ - SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, \ - SYS_ACCEPT = 30 // { int accept(int s, \ - SYS_GETPEERNAME = 31 // { int getpeername(int fdes, \ - SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, \ - SYS_ACCESS = 33 // { int access(char *path, int amode); } - SYS_CHFLAGS = 34 // { int chflags(const char *path, u_long flags); } - SYS_FCHFLAGS = 35 // { int fchflags(int fd, u_long flags); } - SYS_SYNC = 36 // { int sync(void); } - SYS_KILL = 37 // { int kill(int pid, int signum); } - SYS_GETPPID = 39 // { pid_t getppid(void); } - SYS_DUP = 41 // { int dup(u_int fd); } - SYS_PIPE = 42 // { int pipe(void); } - SYS_GETEGID = 43 // { gid_t getegid(void); } - SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, \ - SYS_GETGID = 47 // { gid_t getgid(void); } - SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int \ - SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } - SYS_ACCT = 51 // { int acct(char *path); } - SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, \ - SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, \ - SYS_REBOOT = 55 // { int reboot(int opt); } - SYS_REVOKE = 56 // { int revoke(char *path); } - SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } - SYS_READLINK = 58 // { ssize_t readlink(char *path, char *buf, \ - SYS_EXECVE = 59 // { int execve(char *fname, char **argv, \ - SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args \ - SYS_CHROOT = 61 // { int chroot(char *path); } - SYS_MSYNC = 65 // { int msync(void *addr, size_t len, \ - SYS_VFORK = 66 // { int vfork(void); } - SYS_SBRK = 69 // { int sbrk(int incr); } - SYS_SSTK = 70 // { int sstk(int incr); } - SYS_OVADVISE = 72 // { int ovadvise(int anom); } vadvise \ - SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int mprotect(const void *addr, size_t len, \ - SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, \ - SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, \ - SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, \ - SYS_GETPGRP = 81 // { int getpgrp(void); } - SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } - SYS_SETITIMER = 83 // { int setitimer(u_int which, struct \ - SYS_SWAPON = 85 // { int swapon(char *name); } - SYS_GETITIMER = 86 // { int getitimer(u_int which, \ - SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } - SYS_DUP2 = 90 // { int dup2(u_int from, u_int to); } - SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } - SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, \ - SYS_FSYNC = 95 // { int fsync(int fd); } - SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, \ - SYS_SOCKET = 97 // { int socket(int domain, int type, \ - SYS_CONNECT = 98 // { int connect(int s, caddr_t name, \ - SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } - SYS_BIND = 104 // { int bind(int s, caddr_t name, \ - SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int listen(int s, int backlog); } - SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, \ - SYS_GETRUSAGE = 117 // { int getrusage(int who, \ - SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, \ - SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, \ - SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, \ - SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } - SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } - SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } - SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } - SYS_RENAME = 128 // { int rename(char *from, char *to); } - SYS_FLOCK = 131 // { int flock(int fd, int how); } - SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } - SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, \ - SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, \ - SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } - SYS_RMDIR = 137 // { int rmdir(char *path); } - SYS_UTIMES = 138 // { int utimes(char *path, \ - SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, \ - SYS_SETSID = 147 // { int setsid(void); } - SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, \ - SYS_LGETFH = 160 // { int lgetfh(char *fname, \ - SYS_GETFH = 161 // { int getfh(char *fname, \ - SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } - SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, \ - SYS_FREEBSD6_PREAD = 173 // { ssize_t freebsd6_pread(int fd, void *buf, \ - SYS_FREEBSD6_PWRITE = 174 // { ssize_t freebsd6_pwrite(int fd, \ - SYS_SETFIB = 175 // { int setfib(int fibnum); } - SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int setgid(gid_t gid); } - SYS_SETEGID = 182 // { int setegid(gid_t egid); } - SYS_SETEUID = 183 // { int seteuid(uid_t euid); } - SYS_STAT = 188 // { int stat(char *path, struct stat *ub); } - SYS_FSTAT = 189 // { int fstat(int fd, struct stat *sb); } - SYS_LSTAT = 190 // { int lstat(char *path, struct stat *ub); } - SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } - SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, \ - SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, \ - SYS_GETDIRENTRIES = 196 // { int getdirentries(int fd, char *buf, \ - SYS_FREEBSD6_MMAP = 197 // { caddr_t freebsd6_mmap(caddr_t addr, \ - SYS_FREEBSD6_LSEEK = 199 // { off_t freebsd6_lseek(int fd, int pad, \ - SYS_FREEBSD6_TRUNCATE = 200 // { int freebsd6_truncate(char *path, int pad, \ - SYS_FREEBSD6_FTRUNCATE = 201 // { int freebsd6_ftruncate(int fd, int pad, \ - SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, \ - SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int undelete(char *path); } - SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } - SYS_GETPGID = 207 // { int getpgid(pid_t pid); } - SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, \ - SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 233 // { int clock_settime( \ - SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, \ - SYS_KTIMER_CREATE = 235 // { int ktimer_create(clockid_t clock_id, \ - SYS_KTIMER_DELETE = 236 // { int ktimer_delete(int timerid); } - SYS_KTIMER_SETTIME = 237 // { int ktimer_settime(int timerid, int flags, \ - SYS_KTIMER_GETTIME = 238 // { int ktimer_gettime(int timerid, struct \ - SYS_KTIMER_GETOVERRUN = 239 // { int ktimer_getoverrun(int timerid); } - SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, \ - SYS_FFCLOCK_GETCOUNTER = 241 // { int ffclock_getcounter(ffcounter *ffcount); } - SYS_FFCLOCK_SETESTIMATE = 242 // { int ffclock_setestimate( \ - SYS_FFCLOCK_GETESTIMATE = 243 // { int ffclock_getestimate( \ - SYS_CLOCK_GETCPUCLOCKID2 = 247 // { int clock_getcpuclockid2(id_t id,\ - SYS_NTP_GETTIME = 248 // { int ntp_gettime(struct ntptimeval *ntvp); } - SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, \ - SYS_RFORK = 251 // { int rfork(int flags); } - SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, \ - SYS_ISSETUGID = 253 // { int issetugid(void); } - SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } - SYS_GETDENTS = 272 // { int getdents(int fd, char *buf, \ - SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } - SYS_LUTIMES = 276 // { int lutimes(char *path, \ - SYS_NSTAT = 278 // { int nstat(char *path, struct nstat *ub); } - SYS_NFSTAT = 279 // { int nfstat(int fd, struct nstat *sb); } - SYS_NLSTAT = 280 // { int nlstat(char *path, struct nstat *ub); } - SYS_PREADV = 289 // { ssize_t preadv(int fd, struct iovec *iovp, \ - SYS_PWRITEV = 290 // { ssize_t pwritev(int fd, struct iovec *iovp, \ - SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, \ - SYS_FHSTAT = 299 // { int fhstat(const struct fhandle *u_fhp, \ - SYS_MODNEXT = 300 // { int modnext(int modid); } - SYS_MODSTAT = 301 // { int modstat(int modid, \ - SYS_MODFNEXT = 302 // { int modfnext(int modid); } - SYS_MODFIND = 303 // { int modfind(const char *name); } - SYS_KLDLOAD = 304 // { int kldload(const char *file); } - SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } - SYS_KLDFIND = 306 // { int kldfind(const char *file); } - SYS_KLDNEXT = 307 // { int kldnext(int fileid); } - SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct \ - SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } - SYS_GETSID = 310 // { int getsid(pid_t pid); } - SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, \ - SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, \ - SYS_YIELD = 321 // { int yield(void); } - SYS_MLOCKALL = 324 // { int mlockall(int how); } - SYS_MUNLOCKALL = 325 // { int munlockall(void); } - SYS___GETCWD = 326 // { int __getcwd(char *buf, u_int buflen); } - SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, \ - SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct \ - SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int \ - SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } - SYS_SCHED_YIELD = 331 // { int sched_yield (void); } - SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } - SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } - SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, \ - SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } - SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, \ - SYS_JAIL = 338 // { int jail(struct jail *jail); } - SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, \ - SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } - SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } - SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set, \ - SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set, \ - SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, \ - SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, \ - SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, \ - SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, \ - SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, \ - SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, \ - SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, \ - SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, \ - SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, \ - SYS_EXTATTR_SET_FILE = 356 // { ssize_t extattr_set_file( \ - SYS_EXTATTR_GET_FILE = 357 // { ssize_t extattr_get_file( \ - SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, \ - SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, \ - SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, \ - SYS_KQUEUE = 362 // { int kqueue(void); } - SYS_KEVENT = 363 // { int kevent(int fd, \ - SYS_EXTATTR_SET_FD = 371 // { ssize_t extattr_set_fd(int fd, \ - SYS_EXTATTR_GET_FD = 372 // { ssize_t extattr_get_fd(int fd, \ - SYS_EXTATTR_DELETE_FD = 373 // { int extattr_delete_fd(int fd, \ - SYS___SETUGID = 374 // { int __setugid(int flag); } - SYS_EACCESS = 376 // { int eaccess(char *path, int amode); } - SYS_NMOUNT = 378 // { int nmount(struct iovec *iovp, \ - SYS___MAC_GET_PROC = 384 // { int __mac_get_proc(struct mac *mac_p); } - SYS___MAC_SET_PROC = 385 // { int __mac_set_proc(struct mac *mac_p); } - SYS___MAC_GET_FD = 386 // { int __mac_get_fd(int fd, \ - SYS___MAC_GET_FILE = 387 // { int __mac_get_file(const char *path_p, \ - SYS___MAC_SET_FD = 388 // { int __mac_set_fd(int fd, \ - SYS___MAC_SET_FILE = 389 // { int __mac_set_file(const char *path_p, \ - SYS_KENV = 390 // { int kenv(int what, const char *name, \ - SYS_LCHFLAGS = 391 // { int lchflags(const char *path, \ - SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, \ - SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, \ - SYS_MAC_SYSCALL = 394 // { int mac_syscall(const char *policy, \ - SYS_GETFSSTAT = 395 // { int getfsstat(struct statfs *buf, \ - SYS_STATFS = 396 // { int statfs(char *path, \ - SYS_FSTATFS = 397 // { int fstatfs(int fd, struct statfs *buf); } - SYS_FHSTATFS = 398 // { int fhstatfs(const struct fhandle *u_fhp, \ - SYS___MAC_GET_PID = 409 // { int __mac_get_pid(pid_t pid, \ - SYS___MAC_GET_LINK = 410 // { int __mac_get_link(const char *path_p, \ - SYS___MAC_SET_LINK = 411 // { int __mac_set_link(const char *path_p, \ - SYS_EXTATTR_SET_LINK = 412 // { ssize_t extattr_set_link( \ - SYS_EXTATTR_GET_LINK = 413 // { ssize_t extattr_get_link( \ - SYS_EXTATTR_DELETE_LINK = 414 // { int extattr_delete_link( \ - SYS___MAC_EXECVE = 415 // { int __mac_execve(char *fname, char **argv, \ - SYS_SIGACTION = 416 // { int sigaction(int sig, \ - SYS_SIGRETURN = 417 // { int sigreturn( \ - SYS_GETCONTEXT = 421 // { int getcontext(struct __ucontext *ucp); } - SYS_SETCONTEXT = 422 // { int setcontext( \ - SYS_SWAPCONTEXT = 423 // { int swapcontext(struct __ucontext *oucp, \ - SYS_SWAPOFF = 424 // { int swapoff(const char *name); } - SYS___ACL_GET_LINK = 425 // { int __acl_get_link(const char *path, \ - SYS___ACL_SET_LINK = 426 // { int __acl_set_link(const char *path, \ - SYS___ACL_DELETE_LINK = 427 // { int __acl_delete_link(const char *path, \ - SYS___ACL_ACLCHECK_LINK = 428 // { int __acl_aclcheck_link(const char *path, \ - SYS_SIGWAIT = 429 // { int sigwait(const sigset_t *set, \ - SYS_THR_CREATE = 430 // { int thr_create(ucontext_t *ctx, long *id, \ - SYS_THR_EXIT = 431 // { void thr_exit(long *state); } - SYS_THR_SELF = 432 // { int thr_self(long *id); } - SYS_THR_KILL = 433 // { int thr_kill(long id, int sig); } - SYS__UMTX_LOCK = 434 // { int _umtx_lock(struct umtx *umtx); } - SYS__UMTX_UNLOCK = 435 // { int _umtx_unlock(struct umtx *umtx); } - SYS_JAIL_ATTACH = 436 // { int jail_attach(int jid); } - SYS_EXTATTR_LIST_FD = 437 // { ssize_t extattr_list_fd(int fd, \ - SYS_EXTATTR_LIST_FILE = 438 // { ssize_t extattr_list_file( \ - SYS_EXTATTR_LIST_LINK = 439 // { ssize_t extattr_list_link( \ - SYS_THR_SUSPEND = 442 // { int thr_suspend( \ - SYS_THR_WAKE = 443 // { int thr_wake(long id); } - SYS_KLDUNLOADF = 444 // { int kldunloadf(int fileid, int flags); } - SYS_AUDIT = 445 // { int audit(const void *record, \ - SYS_AUDITON = 446 // { int auditon(int cmd, void *data, \ - SYS_GETAUID = 447 // { int getauid(uid_t *auid); } - SYS_SETAUID = 448 // { int setauid(uid_t *auid); } - SYS_GETAUDIT = 449 // { int getaudit(struct auditinfo *auditinfo); } - SYS_SETAUDIT = 450 // { int setaudit(struct auditinfo *auditinfo); } - SYS_GETAUDIT_ADDR = 451 // { int getaudit_addr( \ - SYS_SETAUDIT_ADDR = 452 // { int setaudit_addr( \ - SYS_AUDITCTL = 453 // { int auditctl(char *path); } - SYS__UMTX_OP = 454 // { int _umtx_op(void *obj, int op, \ - SYS_THR_NEW = 455 // { int thr_new(struct thr_param *param, \ - SYS_SIGQUEUE = 456 // { int sigqueue(pid_t pid, int signum, void *value); } - SYS_ABORT2 = 463 // { int abort2(const char *why, int nargs, void **args); } - SYS_THR_SET_NAME = 464 // { int thr_set_name(long id, const char *name); } - SYS_RTPRIO_THREAD = 466 // { int rtprio_thread(int function, \ - SYS_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } - SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ - SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ - SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ - SYS_PREAD = 475 // { ssize_t pread(int fd, void *buf, \ - SYS_PWRITE = 476 // { ssize_t pwrite(int fd, const void *buf, \ - SYS_MMAP = 477 // { caddr_t mmap(caddr_t addr, size_t len, \ - SYS_LSEEK = 478 // { off_t lseek(int fd, off_t offset, \ - SYS_TRUNCATE = 479 // { int truncate(char *path, off_t length); } - SYS_FTRUNCATE = 480 // { int ftruncate(int fd, off_t length); } - SYS_THR_KILL2 = 481 // { int thr_kill2(pid_t pid, long id, int sig); } - SYS_SHM_OPEN = 482 // { int shm_open(const char *path, int flags, \ - SYS_SHM_UNLINK = 483 // { int shm_unlink(const char *path); } - SYS_CPUSET = 484 // { int cpuset(cpusetid_t *setid); } - SYS_CPUSET_SETID = 485 // { int cpuset_setid(cpuwhich_t which, id_t id, \ - SYS_CPUSET_GETID = 486 // { int cpuset_getid(cpulevel_t level, \ - SYS_CPUSET_GETAFFINITY = 487 // { int cpuset_getaffinity(cpulevel_t level, \ - SYS_CPUSET_SETAFFINITY = 488 // { int cpuset_setaffinity(cpulevel_t level, \ - SYS_FACCESSAT = 489 // { int faccessat(int fd, char *path, int amode, \ - SYS_FCHMODAT = 490 // { int fchmodat(int fd, char *path, mode_t mode, \ - SYS_FCHOWNAT = 491 // { int fchownat(int fd, char *path, uid_t uid, \ - SYS_FEXECVE = 492 // { int fexecve(int fd, char **argv, \ - SYS_FSTATAT = 493 // { int fstatat(int fd, char *path, \ - SYS_FUTIMESAT = 494 // { int futimesat(int fd, char *path, \ - SYS_LINKAT = 495 // { int linkat(int fd1, char *path1, int fd2, \ - SYS_MKDIRAT = 496 // { int mkdirat(int fd, char *path, mode_t mode); } - SYS_MKFIFOAT = 497 // { int mkfifoat(int fd, char *path, mode_t mode); } - SYS_MKNODAT = 498 // { int mknodat(int fd, char *path, mode_t mode, \ - SYS_OPENAT = 499 // { int openat(int fd, char *path, int flag, \ - SYS_READLINKAT = 500 // { int readlinkat(int fd, char *path, char *buf, \ - SYS_RENAMEAT = 501 // { int renameat(int oldfd, char *old, int newfd, \ - SYS_SYMLINKAT = 502 // { int symlinkat(char *path1, int fd, \ - SYS_UNLINKAT = 503 // { int unlinkat(int fd, char *path, int flag); } - SYS_POSIX_OPENPT = 504 // { int posix_openpt(int flags); } - SYS_JAIL_GET = 506 // { int jail_get(struct iovec *iovp, \ - SYS_JAIL_SET = 507 // { int jail_set(struct iovec *iovp, \ - SYS_JAIL_REMOVE = 508 // { int jail_remove(int jid); } - SYS_CLOSEFROM = 509 // { int closefrom(int lowfd); } - SYS_LPATHCONF = 513 // { int lpathconf(char *path, int name); } - SYS_CAP_NEW = 514 // { int cap_new(int fd, uint64_t rights); } - SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ - SYS_CAP_ENTER = 516 // { int cap_enter(void); } - SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); } - SYS_PDFORK = 518 // { int pdfork(int *fdp, int flags); } - SYS_PDKILL = 519 // { int pdkill(int fd, int signum); } - SYS_PDGETPID = 520 // { int pdgetpid(int fd, pid_t *pidp); } - SYS_PSELECT = 522 // { int pselect(int nd, fd_set *in, \ - SYS_GETLOGINCLASS = 523 // { int getloginclass(char *namebuf, \ - SYS_SETLOGINCLASS = 524 // { int setloginclass(const char *namebuf); } - SYS_RCTL_GET_RACCT = 525 // { int rctl_get_racct(const void *inbufp, \ - SYS_RCTL_GET_RULES = 526 // { int rctl_get_rules(const void *inbufp, \ - SYS_RCTL_GET_LIMITS = 527 // { int rctl_get_limits(const void *inbufp, \ - SYS_RCTL_ADD_RULE = 528 // { int rctl_add_rule(const void *inbufp, \ - SYS_RCTL_REMOVE_RULE = 529 // { int rctl_remove_rule(const void *inbufp, \ - SYS_POSIX_FALLOCATE = 530 // { int posix_fallocate(int fd, \ - SYS_POSIX_FADVISE = 531 // { int posix_fadvise(int fd, off_t offset, \ - SYS_WAIT6 = 532 // { int wait6(idtype_t idtype, id_t id, \ - SYS_BINDAT = 538 // { int bindat(int fd, int s, caddr_t name, \ - SYS_CONNECTAT = 539 // { int connectat(int fd, int s, caddr_t name, \ - SYS_CHFLAGSAT = 540 // { int chflagsat(int fd, const char *path, \ - SYS_ACCEPT4 = 541 // { int accept4(int s, \ - SYS_PIPE2 = 542 // { int pipe2(int *fildes, int flags); } - SYS_PROCCTL = 544 // { int procctl(idtype_t idtype, id_t id, \ - SYS_PPOLL = 545 // { int ppoll(struct pollfd *fds, u_int nfds, \ -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_386.go deleted file mode 100644 index ba952c675..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_386.go +++ /dev/null @@ -1,355 +0,0 @@ -// mksysnum_linux.pl /usr/include/asm/unistd_32.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,linux - -package unix - -const ( - SYS_RESTART_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAITPID = 7 - SYS_CREAT = 8 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_EXECVE = 11 - SYS_CHDIR = 12 - SYS_TIME = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_LCHOWN = 16 - SYS_BREAK = 17 - SYS_OLDSTAT = 18 - SYS_LSEEK = 19 - SYS_GETPID = 20 - SYS_MOUNT = 21 - SYS_UMOUNT = 22 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_STIME = 25 - SYS_PTRACE = 26 - SYS_ALARM = 27 - SYS_OLDFSTAT = 28 - SYS_PAUSE = 29 - SYS_UTIME = 30 - SYS_STTY = 31 - SYS_GTTY = 32 - SYS_ACCESS = 33 - SYS_NICE = 34 - SYS_FTIME = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_RENAME = 38 - SYS_MKDIR = 39 - SYS_RMDIR = 40 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_TIMES = 43 - SYS_PROF = 44 - SYS_BRK = 45 - SYS_SETGID = 46 - SYS_GETGID = 47 - SYS_SIGNAL = 48 - SYS_GETEUID = 49 - SYS_GETEGID = 50 - SYS_ACCT = 51 - SYS_UMOUNT2 = 52 - SYS_LOCK = 53 - SYS_IOCTL = 54 - SYS_FCNTL = 55 - SYS_MPX = 56 - SYS_SETPGID = 57 - SYS_ULIMIT = 58 - SYS_OLDOLDUNAME = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_USTAT = 62 - SYS_DUP2 = 63 - SYS_GETPPID = 64 - SYS_GETPGRP = 65 - SYS_SETSID = 66 - SYS_SIGACTION = 67 - SYS_SGETMASK = 68 - SYS_SSETMASK = 69 - SYS_SETREUID = 70 - SYS_SETREGID = 71 - SYS_SIGSUSPEND = 72 - SYS_SIGPENDING = 73 - SYS_SETHOSTNAME = 74 - SYS_SETRLIMIT = 75 - SYS_GETRLIMIT = 76 - SYS_GETRUSAGE = 77 - SYS_GETTIMEOFDAY = 78 - SYS_SETTIMEOFDAY = 79 - SYS_GETGROUPS = 80 - SYS_SETGROUPS = 81 - SYS_SELECT = 82 - SYS_SYMLINK = 83 - SYS_OLDLSTAT = 84 - SYS_READLINK = 85 - SYS_USELIB = 86 - SYS_SWAPON = 87 - SYS_REBOOT = 88 - SYS_READDIR = 89 - SYS_MMAP = 90 - SYS_MUNMAP = 91 - SYS_TRUNCATE = 92 - SYS_FTRUNCATE = 93 - SYS_FCHMOD = 94 - SYS_FCHOWN = 95 - SYS_GETPRIORITY = 96 - SYS_SETPRIORITY = 97 - SYS_PROFIL = 98 - SYS_STATFS = 99 - SYS_FSTATFS = 100 - SYS_IOPERM = 101 - SYS_SOCKETCALL = 102 - SYS_SYSLOG = 103 - SYS_SETITIMER = 104 - SYS_GETITIMER = 105 - SYS_STAT = 106 - SYS_LSTAT = 107 - SYS_FSTAT = 108 - SYS_OLDUNAME = 109 - SYS_IOPL = 110 - SYS_VHANGUP = 111 - SYS_IDLE = 112 - SYS_VM86OLD = 113 - SYS_WAIT4 = 114 - SYS_SWAPOFF = 115 - SYS_SYSINFO = 116 - SYS_IPC = 117 - SYS_FSYNC = 118 - SYS_SIGRETURN = 119 - SYS_CLONE = 120 - SYS_SETDOMAINNAME = 121 - SYS_UNAME = 122 - SYS_MODIFY_LDT = 123 - SYS_ADJTIMEX = 124 - SYS_MPROTECT = 125 - SYS_SIGPROCMASK = 126 - SYS_CREATE_MODULE = 127 - SYS_INIT_MODULE = 128 - SYS_DELETE_MODULE = 129 - SYS_GET_KERNEL_SYMS = 130 - SYS_QUOTACTL = 131 - SYS_GETPGID = 132 - SYS_FCHDIR = 133 - SYS_BDFLUSH = 134 - SYS_SYSFS = 135 - SYS_PERSONALITY = 136 - SYS_AFS_SYSCALL = 137 - SYS_SETFSUID = 138 - SYS_SETFSGID = 139 - SYS__LLSEEK = 140 - SYS_GETDENTS = 141 - SYS__NEWSELECT = 142 - SYS_FLOCK = 143 - SYS_MSYNC = 144 - SYS_READV = 145 - SYS_WRITEV = 146 - SYS_GETSID = 147 - SYS_FDATASYNC = 148 - SYS__SYSCTL = 149 - SYS_MLOCK = 150 - SYS_MUNLOCK = 151 - SYS_MLOCKALL = 152 - SYS_MUNLOCKALL = 153 - SYS_SCHED_SETPARAM = 154 - SYS_SCHED_GETPARAM = 155 - SYS_SCHED_SETSCHEDULER = 156 - SYS_SCHED_GETSCHEDULER = 157 - SYS_SCHED_YIELD = 158 - SYS_SCHED_GET_PRIORITY_MAX = 159 - SYS_SCHED_GET_PRIORITY_MIN = 160 - SYS_SCHED_RR_GET_INTERVAL = 161 - SYS_NANOSLEEP = 162 - SYS_MREMAP = 163 - SYS_SETRESUID = 164 - SYS_GETRESUID = 165 - SYS_VM86 = 166 - SYS_QUERY_MODULE = 167 - SYS_POLL = 168 - SYS_NFSSERVCTL = 169 - SYS_SETRESGID = 170 - SYS_GETRESGID = 171 - SYS_PRCTL = 172 - SYS_RT_SIGRETURN = 173 - SYS_RT_SIGACTION = 174 - SYS_RT_SIGPROCMASK = 175 - SYS_RT_SIGPENDING = 176 - SYS_RT_SIGTIMEDWAIT = 177 - SYS_RT_SIGQUEUEINFO = 178 - SYS_RT_SIGSUSPEND = 179 - SYS_PREAD64 = 180 - SYS_PWRITE64 = 181 - SYS_CHOWN = 182 - SYS_GETCWD = 183 - SYS_CAPGET = 184 - SYS_CAPSET = 185 - SYS_SIGALTSTACK = 186 - SYS_SENDFILE = 187 - SYS_GETPMSG = 188 - SYS_PUTPMSG = 189 - SYS_VFORK = 190 - SYS_UGETRLIMIT = 191 - SYS_MMAP2 = 192 - SYS_TRUNCATE64 = 193 - SYS_FTRUNCATE64 = 194 - SYS_STAT64 = 195 - SYS_LSTAT64 = 196 - SYS_FSTAT64 = 197 - SYS_LCHOWN32 = 198 - SYS_GETUID32 = 199 - SYS_GETGID32 = 200 - SYS_GETEUID32 = 201 - SYS_GETEGID32 = 202 - SYS_SETREUID32 = 203 - SYS_SETREGID32 = 204 - SYS_GETGROUPS32 = 205 - SYS_SETGROUPS32 = 206 - SYS_FCHOWN32 = 207 - SYS_SETRESUID32 = 208 - SYS_GETRESUID32 = 209 - SYS_SETRESGID32 = 210 - SYS_GETRESGID32 = 211 - SYS_CHOWN32 = 212 - SYS_SETUID32 = 213 - SYS_SETGID32 = 214 - SYS_SETFSUID32 = 215 - SYS_SETFSGID32 = 216 - SYS_PIVOT_ROOT = 217 - SYS_MINCORE = 218 - SYS_MADVISE = 219 - SYS_MADVISE1 = 219 - SYS_GETDENTS64 = 220 - SYS_FCNTL64 = 221 - SYS_GETTID = 224 - SYS_READAHEAD = 225 - SYS_SETXATTR = 226 - SYS_LSETXATTR = 227 - SYS_FSETXATTR = 228 - SYS_GETXATTR = 229 - SYS_LGETXATTR = 230 - SYS_FGETXATTR = 231 - SYS_LISTXATTR = 232 - SYS_LLISTXATTR = 233 - SYS_FLISTXATTR = 234 - SYS_REMOVEXATTR = 235 - SYS_LREMOVEXATTR = 236 - SYS_FREMOVEXATTR = 237 - SYS_TKILL = 238 - SYS_SENDFILE64 = 239 - SYS_FUTEX = 240 - SYS_SCHED_SETAFFINITY = 241 - SYS_SCHED_GETAFFINITY = 242 - SYS_SET_THREAD_AREA = 243 - SYS_GET_THREAD_AREA = 244 - SYS_IO_SETUP = 245 - SYS_IO_DESTROY = 246 - SYS_IO_GETEVENTS = 247 - SYS_IO_SUBMIT = 248 - SYS_IO_CANCEL = 249 - SYS_FADVISE64 = 250 - SYS_EXIT_GROUP = 252 - SYS_LOOKUP_DCOOKIE = 253 - SYS_EPOLL_CREATE = 254 - SYS_EPOLL_CTL = 255 - SYS_EPOLL_WAIT = 256 - SYS_REMAP_FILE_PAGES = 257 - SYS_SET_TID_ADDRESS = 258 - SYS_TIMER_CREATE = 259 - SYS_TIMER_SETTIME = 260 - SYS_TIMER_GETTIME = 261 - SYS_TIMER_GETOVERRUN = 262 - SYS_TIMER_DELETE = 263 - SYS_CLOCK_SETTIME = 264 - SYS_CLOCK_GETTIME = 265 - SYS_CLOCK_GETRES = 266 - SYS_CLOCK_NANOSLEEP = 267 - SYS_STATFS64 = 268 - SYS_FSTATFS64 = 269 - SYS_TGKILL = 270 - SYS_UTIMES = 271 - SYS_FADVISE64_64 = 272 - SYS_VSERVER = 273 - SYS_MBIND = 274 - SYS_GET_MEMPOLICY = 275 - SYS_SET_MEMPOLICY = 276 - SYS_MQ_OPEN = 277 - SYS_MQ_UNLINK = 278 - SYS_MQ_TIMEDSEND = 279 - SYS_MQ_TIMEDRECEIVE = 280 - SYS_MQ_NOTIFY = 281 - SYS_MQ_GETSETATTR = 282 - SYS_KEXEC_LOAD = 283 - SYS_WAITID = 284 - SYS_ADD_KEY = 286 - SYS_REQUEST_KEY = 287 - SYS_KEYCTL = 288 - SYS_IOPRIO_SET = 289 - SYS_IOPRIO_GET = 290 - SYS_INOTIFY_INIT = 291 - SYS_INOTIFY_ADD_WATCH = 292 - SYS_INOTIFY_RM_WATCH = 293 - SYS_MIGRATE_PAGES = 294 - SYS_OPENAT = 295 - SYS_MKDIRAT = 296 - SYS_MKNODAT = 297 - SYS_FCHOWNAT = 298 - SYS_FUTIMESAT = 299 - SYS_FSTATAT64 = 300 - SYS_UNLINKAT = 301 - SYS_RENAMEAT = 302 - SYS_LINKAT = 303 - SYS_SYMLINKAT = 304 - SYS_READLINKAT = 305 - SYS_FCHMODAT = 306 - SYS_FACCESSAT = 307 - SYS_PSELECT6 = 308 - SYS_PPOLL = 309 - SYS_UNSHARE = 310 - SYS_SET_ROBUST_LIST = 311 - SYS_GET_ROBUST_LIST = 312 - SYS_SPLICE = 313 - SYS_SYNC_FILE_RANGE = 314 - SYS_TEE = 315 - SYS_VMSPLICE = 316 - SYS_MOVE_PAGES = 317 - SYS_GETCPU = 318 - SYS_EPOLL_PWAIT = 319 - SYS_UTIMENSAT = 320 - SYS_SIGNALFD = 321 - SYS_TIMERFD_CREATE = 322 - SYS_EVENTFD = 323 - SYS_FALLOCATE = 324 - SYS_TIMERFD_SETTIME = 325 - SYS_TIMERFD_GETTIME = 326 - SYS_SIGNALFD4 = 327 - SYS_EVENTFD2 = 328 - SYS_EPOLL_CREATE1 = 329 - SYS_DUP3 = 330 - SYS_PIPE2 = 331 - SYS_INOTIFY_INIT1 = 332 - SYS_PREADV = 333 - SYS_PWRITEV = 334 - SYS_RT_TGSIGQUEUEINFO = 335 - SYS_PERF_EVENT_OPEN = 336 - SYS_RECVMMSG = 337 - SYS_FANOTIFY_INIT = 338 - SYS_FANOTIFY_MARK = 339 - SYS_PRLIMIT64 = 340 - SYS_NAME_TO_HANDLE_AT = 341 - SYS_OPEN_BY_HANDLE_AT = 342 - SYS_CLOCK_ADJTIME = 343 - SYS_SYNCFS = 344 - SYS_SENDMMSG = 345 - SYS_SETNS = 346 - SYS_PROCESS_VM_READV = 347 - SYS_PROCESS_VM_WRITEV = 348 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_amd64.go deleted file mode 100644 index ddac31f58..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ /dev/null @@ -1,321 +0,0 @@ -// mksysnum_linux.pl /usr/include/asm/unistd_64.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build amd64,linux - -package unix - -const ( - SYS_READ = 0 - SYS_WRITE = 1 - SYS_OPEN = 2 - SYS_CLOSE = 3 - SYS_STAT = 4 - SYS_FSTAT = 5 - SYS_LSTAT = 6 - SYS_POLL = 7 - SYS_LSEEK = 8 - SYS_MMAP = 9 - SYS_MPROTECT = 10 - SYS_MUNMAP = 11 - SYS_BRK = 12 - SYS_RT_SIGACTION = 13 - SYS_RT_SIGPROCMASK = 14 - SYS_RT_SIGRETURN = 15 - SYS_IOCTL = 16 - SYS_PREAD64 = 17 - SYS_PWRITE64 = 18 - SYS_READV = 19 - SYS_WRITEV = 20 - SYS_ACCESS = 21 - SYS_PIPE = 22 - SYS_SELECT = 23 - SYS_SCHED_YIELD = 24 - SYS_MREMAP = 25 - SYS_MSYNC = 26 - SYS_MINCORE = 27 - SYS_MADVISE = 28 - SYS_SHMGET = 29 - SYS_SHMAT = 30 - SYS_SHMCTL = 31 - SYS_DUP = 32 - SYS_DUP2 = 33 - SYS_PAUSE = 34 - SYS_NANOSLEEP = 35 - SYS_GETITIMER = 36 - SYS_ALARM = 37 - SYS_SETITIMER = 38 - SYS_GETPID = 39 - SYS_SENDFILE = 40 - SYS_SOCKET = 41 - SYS_CONNECT = 42 - SYS_ACCEPT = 43 - SYS_SENDTO = 44 - SYS_RECVFROM = 45 - SYS_SENDMSG = 46 - SYS_RECVMSG = 47 - SYS_SHUTDOWN = 48 - SYS_BIND = 49 - SYS_LISTEN = 50 - SYS_GETSOCKNAME = 51 - SYS_GETPEERNAME = 52 - SYS_SOCKETPAIR = 53 - SYS_SETSOCKOPT = 54 - SYS_GETSOCKOPT = 55 - SYS_CLONE = 56 - SYS_FORK = 57 - SYS_VFORK = 58 - SYS_EXECVE = 59 - SYS_EXIT = 60 - SYS_WAIT4 = 61 - SYS_KILL = 62 - SYS_UNAME = 63 - SYS_SEMGET = 64 - SYS_SEMOP = 65 - SYS_SEMCTL = 66 - SYS_SHMDT = 67 - SYS_MSGGET = 68 - SYS_MSGSND = 69 - SYS_MSGRCV = 70 - SYS_MSGCTL = 71 - SYS_FCNTL = 72 - SYS_FLOCK = 73 - SYS_FSYNC = 74 - SYS_FDATASYNC = 75 - SYS_TRUNCATE = 76 - SYS_FTRUNCATE = 77 - SYS_GETDENTS = 78 - SYS_GETCWD = 79 - SYS_CHDIR = 80 - SYS_FCHDIR = 81 - SYS_RENAME = 82 - SYS_MKDIR = 83 - SYS_RMDIR = 84 - SYS_CREAT = 85 - SYS_LINK = 86 - SYS_UNLINK = 87 - SYS_SYMLINK = 88 - SYS_READLINK = 89 - SYS_CHMOD = 90 - SYS_FCHMOD = 91 - SYS_CHOWN = 92 - SYS_FCHOWN = 93 - SYS_LCHOWN = 94 - SYS_UMASK = 95 - SYS_GETTIMEOFDAY = 96 - SYS_GETRLIMIT = 97 - SYS_GETRUSAGE = 98 - SYS_SYSINFO = 99 - SYS_TIMES = 100 - SYS_PTRACE = 101 - SYS_GETUID = 102 - SYS_SYSLOG = 103 - SYS_GETGID = 104 - SYS_SETUID = 105 - SYS_SETGID = 106 - SYS_GETEUID = 107 - SYS_GETEGID = 108 - SYS_SETPGID = 109 - SYS_GETPPID = 110 - SYS_GETPGRP = 111 - SYS_SETSID = 112 - SYS_SETREUID = 113 - SYS_SETREGID = 114 - SYS_GETGROUPS = 115 - SYS_SETGROUPS = 116 - SYS_SETRESUID = 117 - SYS_GETRESUID = 118 - SYS_SETRESGID = 119 - SYS_GETRESGID = 120 - SYS_GETPGID = 121 - SYS_SETFSUID = 122 - SYS_SETFSGID = 123 - SYS_GETSID = 124 - SYS_CAPGET = 125 - SYS_CAPSET = 126 - SYS_RT_SIGPENDING = 127 - SYS_RT_SIGTIMEDWAIT = 128 - SYS_RT_SIGQUEUEINFO = 129 - SYS_RT_SIGSUSPEND = 130 - SYS_SIGALTSTACK = 131 - SYS_UTIME = 132 - SYS_MKNOD = 133 - SYS_USELIB = 134 - SYS_PERSONALITY = 135 - SYS_USTAT = 136 - SYS_STATFS = 137 - SYS_FSTATFS = 138 - SYS_SYSFS = 139 - SYS_GETPRIORITY = 140 - SYS_SETPRIORITY = 141 - SYS_SCHED_SETPARAM = 142 - SYS_SCHED_GETPARAM = 143 - SYS_SCHED_SETSCHEDULER = 144 - SYS_SCHED_GETSCHEDULER = 145 - SYS_SCHED_GET_PRIORITY_MAX = 146 - SYS_SCHED_GET_PRIORITY_MIN = 147 - SYS_SCHED_RR_GET_INTERVAL = 148 - SYS_MLOCK = 149 - SYS_MUNLOCK = 150 - SYS_MLOCKALL = 151 - SYS_MUNLOCKALL = 152 - SYS_VHANGUP = 153 - SYS_MODIFY_LDT = 154 - SYS_PIVOT_ROOT = 155 - SYS__SYSCTL = 156 - SYS_PRCTL = 157 - SYS_ARCH_PRCTL = 158 - SYS_ADJTIMEX = 159 - SYS_SETRLIMIT = 160 - SYS_CHROOT = 161 - SYS_SYNC = 162 - SYS_ACCT = 163 - SYS_SETTIMEOFDAY = 164 - SYS_MOUNT = 165 - SYS_UMOUNT2 = 166 - SYS_SWAPON = 167 - SYS_SWAPOFF = 168 - SYS_REBOOT = 169 - SYS_SETHOSTNAME = 170 - SYS_SETDOMAINNAME = 171 - SYS_IOPL = 172 - SYS_IOPERM = 173 - SYS_CREATE_MODULE = 174 - SYS_INIT_MODULE = 175 - SYS_DELETE_MODULE = 176 - SYS_GET_KERNEL_SYMS = 177 - SYS_QUERY_MODULE = 178 - SYS_QUOTACTL = 179 - SYS_NFSSERVCTL = 180 - SYS_GETPMSG = 181 - SYS_PUTPMSG = 182 - SYS_AFS_SYSCALL = 183 - SYS_TUXCALL = 184 - SYS_SECURITY = 185 - SYS_GETTID = 186 - SYS_READAHEAD = 187 - SYS_SETXATTR = 188 - SYS_LSETXATTR = 189 - SYS_FSETXATTR = 190 - SYS_GETXATTR = 191 - SYS_LGETXATTR = 192 - SYS_FGETXATTR = 193 - SYS_LISTXATTR = 194 - SYS_LLISTXATTR = 195 - SYS_FLISTXATTR = 196 - SYS_REMOVEXATTR = 197 - SYS_LREMOVEXATTR = 198 - SYS_FREMOVEXATTR = 199 - SYS_TKILL = 200 - SYS_TIME = 201 - SYS_FUTEX = 202 - SYS_SCHED_SETAFFINITY = 203 - SYS_SCHED_GETAFFINITY = 204 - SYS_SET_THREAD_AREA = 205 - SYS_IO_SETUP = 206 - SYS_IO_DESTROY = 207 - SYS_IO_GETEVENTS = 208 - SYS_IO_SUBMIT = 209 - SYS_IO_CANCEL = 210 - SYS_GET_THREAD_AREA = 211 - SYS_LOOKUP_DCOOKIE = 212 - SYS_EPOLL_CREATE = 213 - SYS_EPOLL_CTL_OLD = 214 - SYS_EPOLL_WAIT_OLD = 215 - SYS_REMAP_FILE_PAGES = 216 - SYS_GETDENTS64 = 217 - SYS_SET_TID_ADDRESS = 218 - SYS_RESTART_SYSCALL = 219 - SYS_SEMTIMEDOP = 220 - SYS_FADVISE64 = 221 - SYS_TIMER_CREATE = 222 - SYS_TIMER_SETTIME = 223 - SYS_TIMER_GETTIME = 224 - SYS_TIMER_GETOVERRUN = 225 - SYS_TIMER_DELETE = 226 - SYS_CLOCK_SETTIME = 227 - SYS_CLOCK_GETTIME = 228 - SYS_CLOCK_GETRES = 229 - SYS_CLOCK_NANOSLEEP = 230 - SYS_EXIT_GROUP = 231 - SYS_EPOLL_WAIT = 232 - SYS_EPOLL_CTL = 233 - SYS_TGKILL = 234 - SYS_UTIMES = 235 - SYS_VSERVER = 236 - SYS_MBIND = 237 - SYS_SET_MEMPOLICY = 238 - SYS_GET_MEMPOLICY = 239 - SYS_MQ_OPEN = 240 - SYS_MQ_UNLINK = 241 - SYS_MQ_TIMEDSEND = 242 - SYS_MQ_TIMEDRECEIVE = 243 - SYS_MQ_NOTIFY = 244 - SYS_MQ_GETSETATTR = 245 - SYS_KEXEC_LOAD = 246 - SYS_WAITID = 247 - SYS_ADD_KEY = 248 - SYS_REQUEST_KEY = 249 - SYS_KEYCTL = 250 - SYS_IOPRIO_SET = 251 - SYS_IOPRIO_GET = 252 - SYS_INOTIFY_INIT = 253 - SYS_INOTIFY_ADD_WATCH = 254 - SYS_INOTIFY_RM_WATCH = 255 - SYS_MIGRATE_PAGES = 256 - SYS_OPENAT = 257 - SYS_MKDIRAT = 258 - SYS_MKNODAT = 259 - SYS_FCHOWNAT = 260 - SYS_FUTIMESAT = 261 - SYS_NEWFSTATAT = 262 - SYS_UNLINKAT = 263 - SYS_RENAMEAT = 264 - SYS_LINKAT = 265 - SYS_SYMLINKAT = 266 - SYS_READLINKAT = 267 - SYS_FCHMODAT = 268 - SYS_FACCESSAT = 269 - SYS_PSELECT6 = 270 - SYS_PPOLL = 271 - SYS_UNSHARE = 272 - SYS_SET_ROBUST_LIST = 273 - SYS_GET_ROBUST_LIST = 274 - SYS_SPLICE = 275 - SYS_TEE = 276 - SYS_SYNC_FILE_RANGE = 277 - SYS_VMSPLICE = 278 - SYS_MOVE_PAGES = 279 - SYS_UTIMENSAT = 280 - SYS_EPOLL_PWAIT = 281 - SYS_SIGNALFD = 282 - SYS_TIMERFD_CREATE = 283 - SYS_EVENTFD = 284 - SYS_FALLOCATE = 285 - SYS_TIMERFD_SETTIME = 286 - SYS_TIMERFD_GETTIME = 287 - SYS_ACCEPT4 = 288 - SYS_SIGNALFD4 = 289 - SYS_EVENTFD2 = 290 - SYS_EPOLL_CREATE1 = 291 - SYS_DUP3 = 292 - SYS_PIPE2 = 293 - SYS_INOTIFY_INIT1 = 294 - SYS_PREADV = 295 - SYS_PWRITEV = 296 - SYS_RT_TGSIGQUEUEINFO = 297 - SYS_PERF_EVENT_OPEN = 298 - SYS_RECVMMSG = 299 - SYS_FANOTIFY_INIT = 300 - SYS_FANOTIFY_MARK = 301 - SYS_PRLIMIT64 = 302 - SYS_NAME_TO_HANDLE_AT = 303 - SYS_OPEN_BY_HANDLE_AT = 304 - SYS_CLOCK_ADJTIME = 305 - SYS_SYNCFS = 306 - SYS_SENDMMSG = 307 - SYS_SETNS = 308 - SYS_GETCPU = 309 - SYS_PROCESS_VM_READV = 310 - SYS_PROCESS_VM_WRITEV = 311 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm.go deleted file mode 100644 index 45ced17fc..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ /dev/null @@ -1,356 +0,0 @@ -// mksysnum_linux.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build arm,linux - -package unix - -const ( - SYS_OABI_SYSCALL_BASE = 0 - SYS_SYSCALL_BASE = 0 - SYS_RESTART_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_CREAT = 8 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_EXECVE = 11 - SYS_CHDIR = 12 - SYS_TIME = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_LCHOWN = 16 - SYS_LSEEK = 19 - SYS_GETPID = 20 - SYS_MOUNT = 21 - SYS_UMOUNT = 22 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_STIME = 25 - SYS_PTRACE = 26 - SYS_ALARM = 27 - SYS_PAUSE = 29 - SYS_UTIME = 30 - SYS_ACCESS = 33 - SYS_NICE = 34 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_RENAME = 38 - SYS_MKDIR = 39 - SYS_RMDIR = 40 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_TIMES = 43 - SYS_BRK = 45 - SYS_SETGID = 46 - SYS_GETGID = 47 - SYS_GETEUID = 49 - SYS_GETEGID = 50 - SYS_ACCT = 51 - SYS_UMOUNT2 = 52 - SYS_IOCTL = 54 - SYS_FCNTL = 55 - SYS_SETPGID = 57 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_USTAT = 62 - SYS_DUP2 = 63 - SYS_GETPPID = 64 - SYS_GETPGRP = 65 - SYS_SETSID = 66 - SYS_SIGACTION = 67 - SYS_SETREUID = 70 - SYS_SETREGID = 71 - SYS_SIGSUSPEND = 72 - SYS_SIGPENDING = 73 - SYS_SETHOSTNAME = 74 - SYS_SETRLIMIT = 75 - SYS_GETRLIMIT = 76 - SYS_GETRUSAGE = 77 - SYS_GETTIMEOFDAY = 78 - SYS_SETTIMEOFDAY = 79 - SYS_GETGROUPS = 80 - SYS_SETGROUPS = 81 - SYS_SELECT = 82 - SYS_SYMLINK = 83 - SYS_READLINK = 85 - SYS_USELIB = 86 - SYS_SWAPON = 87 - SYS_REBOOT = 88 - SYS_READDIR = 89 - SYS_MMAP = 90 - SYS_MUNMAP = 91 - SYS_TRUNCATE = 92 - SYS_FTRUNCATE = 93 - SYS_FCHMOD = 94 - SYS_FCHOWN = 95 - SYS_GETPRIORITY = 96 - SYS_SETPRIORITY = 97 - SYS_STATFS = 99 - SYS_FSTATFS = 100 - SYS_SOCKETCALL = 102 - SYS_SYSLOG = 103 - SYS_SETITIMER = 104 - SYS_GETITIMER = 105 - SYS_STAT = 106 - SYS_LSTAT = 107 - SYS_FSTAT = 108 - SYS_VHANGUP = 111 - SYS_SYSCALL = 113 - SYS_WAIT4 = 114 - SYS_SWAPOFF = 115 - SYS_SYSINFO = 116 - SYS_IPC = 117 - SYS_FSYNC = 118 - SYS_SIGRETURN = 119 - SYS_CLONE = 120 - SYS_SETDOMAINNAME = 121 - SYS_UNAME = 122 - SYS_ADJTIMEX = 124 - SYS_MPROTECT = 125 - SYS_SIGPROCMASK = 126 - SYS_INIT_MODULE = 128 - SYS_DELETE_MODULE = 129 - SYS_QUOTACTL = 131 - SYS_GETPGID = 132 - SYS_FCHDIR = 133 - SYS_BDFLUSH = 134 - SYS_SYSFS = 135 - SYS_PERSONALITY = 136 - SYS_SETFSUID = 138 - SYS_SETFSGID = 139 - SYS__LLSEEK = 140 - SYS_GETDENTS = 141 - SYS__NEWSELECT = 142 - SYS_FLOCK = 143 - SYS_MSYNC = 144 - SYS_READV = 145 - SYS_WRITEV = 146 - SYS_GETSID = 147 - SYS_FDATASYNC = 148 - SYS__SYSCTL = 149 - SYS_MLOCK = 150 - SYS_MUNLOCK = 151 - SYS_MLOCKALL = 152 - SYS_MUNLOCKALL = 153 - SYS_SCHED_SETPARAM = 154 - SYS_SCHED_GETPARAM = 155 - SYS_SCHED_SETSCHEDULER = 156 - SYS_SCHED_GETSCHEDULER = 157 - SYS_SCHED_YIELD = 158 - SYS_SCHED_GET_PRIORITY_MAX = 159 - SYS_SCHED_GET_PRIORITY_MIN = 160 - SYS_SCHED_RR_GET_INTERVAL = 161 - SYS_NANOSLEEP = 162 - SYS_MREMAP = 163 - SYS_SETRESUID = 164 - SYS_GETRESUID = 165 - SYS_POLL = 168 - SYS_NFSSERVCTL = 169 - SYS_SETRESGID = 170 - SYS_GETRESGID = 171 - SYS_PRCTL = 172 - SYS_RT_SIGRETURN = 173 - SYS_RT_SIGACTION = 174 - SYS_RT_SIGPROCMASK = 175 - SYS_RT_SIGPENDING = 176 - SYS_RT_SIGTIMEDWAIT = 177 - SYS_RT_SIGQUEUEINFO = 178 - SYS_RT_SIGSUSPEND = 179 - SYS_PREAD64 = 180 - SYS_PWRITE64 = 181 - SYS_CHOWN = 182 - SYS_GETCWD = 183 - SYS_CAPGET = 184 - SYS_CAPSET = 185 - SYS_SIGALTSTACK = 186 - SYS_SENDFILE = 187 - SYS_VFORK = 190 - SYS_UGETRLIMIT = 191 - SYS_MMAP2 = 192 - SYS_TRUNCATE64 = 193 - SYS_FTRUNCATE64 = 194 - SYS_STAT64 = 195 - SYS_LSTAT64 = 196 - SYS_FSTAT64 = 197 - SYS_LCHOWN32 = 198 - SYS_GETUID32 = 199 - SYS_GETGID32 = 200 - SYS_GETEUID32 = 201 - SYS_GETEGID32 = 202 - SYS_SETREUID32 = 203 - SYS_SETREGID32 = 204 - SYS_GETGROUPS32 = 205 - SYS_SETGROUPS32 = 206 - SYS_FCHOWN32 = 207 - SYS_SETRESUID32 = 208 - SYS_GETRESUID32 = 209 - SYS_SETRESGID32 = 210 - SYS_GETRESGID32 = 211 - SYS_CHOWN32 = 212 - SYS_SETUID32 = 213 - SYS_SETGID32 = 214 - SYS_SETFSUID32 = 215 - SYS_SETFSGID32 = 216 - SYS_GETDENTS64 = 217 - SYS_PIVOT_ROOT = 218 - SYS_MINCORE = 219 - SYS_MADVISE = 220 - SYS_FCNTL64 = 221 - SYS_GETTID = 224 - SYS_READAHEAD = 225 - SYS_SETXATTR = 226 - SYS_LSETXATTR = 227 - SYS_FSETXATTR = 228 - SYS_GETXATTR = 229 - SYS_LGETXATTR = 230 - SYS_FGETXATTR = 231 - SYS_LISTXATTR = 232 - SYS_LLISTXATTR = 233 - SYS_FLISTXATTR = 234 - SYS_REMOVEXATTR = 235 - SYS_LREMOVEXATTR = 236 - SYS_FREMOVEXATTR = 237 - SYS_TKILL = 238 - SYS_SENDFILE64 = 239 - SYS_FUTEX = 240 - SYS_SCHED_SETAFFINITY = 241 - SYS_SCHED_GETAFFINITY = 242 - SYS_IO_SETUP = 243 - SYS_IO_DESTROY = 244 - SYS_IO_GETEVENTS = 245 - SYS_IO_SUBMIT = 246 - SYS_IO_CANCEL = 247 - SYS_EXIT_GROUP = 248 - SYS_LOOKUP_DCOOKIE = 249 - SYS_EPOLL_CREATE = 250 - SYS_EPOLL_CTL = 251 - SYS_EPOLL_WAIT = 252 - SYS_REMAP_FILE_PAGES = 253 - SYS_SET_TID_ADDRESS = 256 - SYS_TIMER_CREATE = 257 - SYS_TIMER_SETTIME = 258 - SYS_TIMER_GETTIME = 259 - SYS_TIMER_GETOVERRUN = 260 - SYS_TIMER_DELETE = 261 - SYS_CLOCK_SETTIME = 262 - SYS_CLOCK_GETTIME = 263 - SYS_CLOCK_GETRES = 264 - SYS_CLOCK_NANOSLEEP = 265 - SYS_STATFS64 = 266 - SYS_FSTATFS64 = 267 - SYS_TGKILL = 268 - SYS_UTIMES = 269 - SYS_ARM_FADVISE64_64 = 270 - SYS_PCICONFIG_IOBASE = 271 - SYS_PCICONFIG_READ = 272 - SYS_PCICONFIG_WRITE = 273 - SYS_MQ_OPEN = 274 - SYS_MQ_UNLINK = 275 - SYS_MQ_TIMEDSEND = 276 - SYS_MQ_TIMEDRECEIVE = 277 - SYS_MQ_NOTIFY = 278 - SYS_MQ_GETSETATTR = 279 - SYS_WAITID = 280 - SYS_SOCKET = 281 - SYS_BIND = 282 - SYS_CONNECT = 283 - SYS_LISTEN = 284 - SYS_ACCEPT = 285 - SYS_GETSOCKNAME = 286 - SYS_GETPEERNAME = 287 - SYS_SOCKETPAIR = 288 - SYS_SEND = 289 - SYS_SENDTO = 290 - SYS_RECV = 291 - SYS_RECVFROM = 292 - SYS_SHUTDOWN = 293 - SYS_SETSOCKOPT = 294 - SYS_GETSOCKOPT = 295 - SYS_SENDMSG = 296 - SYS_RECVMSG = 297 - SYS_SEMOP = 298 - SYS_SEMGET = 299 - SYS_SEMCTL = 300 - SYS_MSGSND = 301 - SYS_MSGRCV = 302 - SYS_MSGGET = 303 - SYS_MSGCTL = 304 - SYS_SHMAT = 305 - SYS_SHMDT = 306 - SYS_SHMGET = 307 - SYS_SHMCTL = 308 - SYS_ADD_KEY = 309 - SYS_REQUEST_KEY = 310 - SYS_KEYCTL = 311 - SYS_SEMTIMEDOP = 312 - SYS_VSERVER = 313 - SYS_IOPRIO_SET = 314 - SYS_IOPRIO_GET = 315 - SYS_INOTIFY_INIT = 316 - SYS_INOTIFY_ADD_WATCH = 317 - SYS_INOTIFY_RM_WATCH = 318 - SYS_MBIND = 319 - SYS_GET_MEMPOLICY = 320 - SYS_SET_MEMPOLICY = 321 - SYS_OPENAT = 322 - SYS_MKDIRAT = 323 - SYS_MKNODAT = 324 - SYS_FCHOWNAT = 325 - SYS_FUTIMESAT = 326 - SYS_FSTATAT64 = 327 - SYS_UNLINKAT = 328 - SYS_RENAMEAT = 329 - SYS_LINKAT = 330 - SYS_SYMLINKAT = 331 - SYS_READLINKAT = 332 - SYS_FCHMODAT = 333 - SYS_FACCESSAT = 334 - SYS_PSELECT6 = 335 - SYS_PPOLL = 336 - SYS_UNSHARE = 337 - SYS_SET_ROBUST_LIST = 338 - SYS_GET_ROBUST_LIST = 339 - SYS_SPLICE = 340 - SYS_ARM_SYNC_FILE_RANGE = 341 - SYS_TEE = 342 - SYS_VMSPLICE = 343 - SYS_MOVE_PAGES = 344 - SYS_GETCPU = 345 - SYS_EPOLL_PWAIT = 346 - SYS_KEXEC_LOAD = 347 - SYS_UTIMENSAT = 348 - SYS_SIGNALFD = 349 - SYS_TIMERFD_CREATE = 350 - SYS_EVENTFD = 351 - SYS_FALLOCATE = 352 - SYS_TIMERFD_SETTIME = 353 - SYS_TIMERFD_GETTIME = 354 - SYS_SIGNALFD4 = 355 - SYS_EVENTFD2 = 356 - SYS_EPOLL_CREATE1 = 357 - SYS_DUP3 = 358 - SYS_PIPE2 = 359 - SYS_INOTIFY_INIT1 = 360 - SYS_PREADV = 361 - SYS_PWRITEV = 362 - SYS_RT_TGSIGQUEUEINFO = 363 - SYS_PERF_EVENT_OPEN = 364 - SYS_RECVMMSG = 365 - SYS_ACCEPT4 = 366 - SYS_FANOTIFY_INIT = 367 - SYS_FANOTIFY_MARK = 368 - SYS_PRLIMIT64 = 369 - SYS_NAME_TO_HANDLE_AT = 370 - SYS_OPEN_BY_HANDLE_AT = 371 - SYS_CLOCK_ADJTIME = 372 - SYS_SYNCFS = 373 - SYS_SENDMMSG = 374 - SYS_SETNS = 375 - SYS_PROCESS_VM_READV = 376 - SYS_PROCESS_VM_WRITEV = 377 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm64.go deleted file mode 100644 index 2e9514f28..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ /dev/null @@ -1,272 +0,0 @@ -// mksysnum_linux.pl /usr/include/asm-generic/unistd.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build arm64,linux - -package unix - -const ( - SYS_IO_SETUP = 0 - SYS_IO_DESTROY = 1 - SYS_IO_SUBMIT = 2 - SYS_IO_CANCEL = 3 - SYS_IO_GETEVENTS = 4 - SYS_SETXATTR = 5 - SYS_LSETXATTR = 6 - SYS_FSETXATTR = 7 - SYS_GETXATTR = 8 - SYS_LGETXATTR = 9 - SYS_FGETXATTR = 10 - SYS_LISTXATTR = 11 - SYS_LLISTXATTR = 12 - SYS_FLISTXATTR = 13 - SYS_REMOVEXATTR = 14 - SYS_LREMOVEXATTR = 15 - SYS_FREMOVEXATTR = 16 - SYS_GETCWD = 17 - SYS_LOOKUP_DCOOKIE = 18 - SYS_EVENTFD2 = 19 - SYS_EPOLL_CREATE1 = 20 - SYS_EPOLL_CTL = 21 - SYS_EPOLL_PWAIT = 22 - SYS_DUP = 23 - SYS_DUP3 = 24 - SYS_FCNTL = 25 - SYS_INOTIFY_INIT1 = 26 - SYS_INOTIFY_ADD_WATCH = 27 - SYS_INOTIFY_RM_WATCH = 28 - SYS_IOCTL = 29 - SYS_IOPRIO_SET = 30 - SYS_IOPRIO_GET = 31 - SYS_FLOCK = 32 - SYS_MKNODAT = 33 - SYS_MKDIRAT = 34 - SYS_UNLINKAT = 35 - SYS_SYMLINKAT = 36 - SYS_LINKAT = 37 - SYS_RENAMEAT = 38 - SYS_UMOUNT2 = 39 - SYS_MOUNT = 40 - SYS_PIVOT_ROOT = 41 - SYS_NFSSERVCTL = 42 - SYS_STATFS = 43 - SYS_FSTATFS = 44 - SYS_TRUNCATE = 45 - SYS_FTRUNCATE = 46 - SYS_FALLOCATE = 47 - SYS_FACCESSAT = 48 - SYS_CHDIR = 49 - SYS_FCHDIR = 50 - SYS_CHROOT = 51 - SYS_FCHMOD = 52 - SYS_FCHMODAT = 53 - SYS_FCHOWNAT = 54 - SYS_FCHOWN = 55 - SYS_OPENAT = 56 - SYS_CLOSE = 57 - SYS_VHANGUP = 58 - SYS_PIPE2 = 59 - SYS_QUOTACTL = 60 - SYS_GETDENTS64 = 61 - SYS_LSEEK = 62 - SYS_READ = 63 - SYS_WRITE = 64 - SYS_READV = 65 - SYS_WRITEV = 66 - SYS_PREAD64 = 67 - SYS_PWRITE64 = 68 - SYS_PREADV = 69 - SYS_PWRITEV = 70 - SYS_SENDFILE = 71 - SYS_PSELECT6 = 72 - SYS_PPOLL = 73 - SYS_SIGNALFD4 = 74 - SYS_VMSPLICE = 75 - SYS_SPLICE = 76 - SYS_TEE = 77 - SYS_READLINKAT = 78 - SYS_FSTATAT = 79 - SYS_FSTAT = 80 - SYS_SYNC = 81 - SYS_FSYNC = 82 - SYS_FDATASYNC = 83 - SYS_SYNC_FILE_RANGE = 84 - SYS_TIMERFD_CREATE = 85 - SYS_TIMERFD_SETTIME = 86 - SYS_TIMERFD_GETTIME = 87 - SYS_UTIMENSAT = 88 - SYS_ACCT = 89 - SYS_CAPGET = 90 - SYS_CAPSET = 91 - SYS_PERSONALITY = 92 - SYS_EXIT = 93 - SYS_EXIT_GROUP = 94 - SYS_WAITID = 95 - SYS_SET_TID_ADDRESS = 96 - SYS_UNSHARE = 97 - SYS_FUTEX = 98 - SYS_SET_ROBUST_LIST = 99 - SYS_GET_ROBUST_LIST = 100 - SYS_NANOSLEEP = 101 - SYS_GETITIMER = 102 - SYS_SETITIMER = 103 - SYS_KEXEC_LOAD = 104 - SYS_INIT_MODULE = 105 - SYS_DELETE_MODULE = 106 - SYS_TIMER_CREATE = 107 - SYS_TIMER_GETTIME = 108 - SYS_TIMER_GETOVERRUN = 109 - SYS_TIMER_SETTIME = 110 - SYS_TIMER_DELETE = 111 - SYS_CLOCK_SETTIME = 112 - SYS_CLOCK_GETTIME = 113 - SYS_CLOCK_GETRES = 114 - SYS_CLOCK_NANOSLEEP = 115 - SYS_SYSLOG = 116 - SYS_PTRACE = 117 - SYS_SCHED_SETPARAM = 118 - SYS_SCHED_SETSCHEDULER = 119 - SYS_SCHED_GETSCHEDULER = 120 - SYS_SCHED_GETPARAM = 121 - SYS_SCHED_SETAFFINITY = 122 - SYS_SCHED_GETAFFINITY = 123 - SYS_SCHED_YIELD = 124 - SYS_SCHED_GET_PRIORITY_MAX = 125 - SYS_SCHED_GET_PRIORITY_MIN = 126 - SYS_SCHED_RR_GET_INTERVAL = 127 - SYS_RESTART_SYSCALL = 128 - SYS_KILL = 129 - SYS_TKILL = 130 - SYS_TGKILL = 131 - SYS_SIGALTSTACK = 132 - SYS_RT_SIGSUSPEND = 133 - SYS_RT_SIGACTION = 134 - SYS_RT_SIGPROCMASK = 135 - SYS_RT_SIGPENDING = 136 - SYS_RT_SIGTIMEDWAIT = 137 - SYS_RT_SIGQUEUEINFO = 138 - SYS_RT_SIGRETURN = 139 - SYS_SETPRIORITY = 140 - SYS_GETPRIORITY = 141 - SYS_REBOOT = 142 - SYS_SETREGID = 143 - SYS_SETGID = 144 - SYS_SETREUID = 145 - SYS_SETUID = 146 - SYS_SETRESUID = 147 - SYS_GETRESUID = 148 - SYS_SETRESGID = 149 - SYS_GETRESGID = 150 - SYS_SETFSUID = 151 - SYS_SETFSGID = 152 - SYS_TIMES = 153 - SYS_SETPGID = 154 - SYS_GETPGID = 155 - SYS_GETSID = 156 - SYS_SETSID = 157 - SYS_GETGROUPS = 158 - SYS_SETGROUPS = 159 - SYS_UNAME = 160 - SYS_SETHOSTNAME = 161 - SYS_SETDOMAINNAME = 162 - SYS_GETRLIMIT = 163 - SYS_SETRLIMIT = 164 - SYS_GETRUSAGE = 165 - SYS_UMASK = 166 - SYS_PRCTL = 167 - SYS_GETCPU = 168 - SYS_GETTIMEOFDAY = 169 - SYS_SETTIMEOFDAY = 170 - SYS_ADJTIMEX = 171 - SYS_GETPID = 172 - SYS_GETPPID = 173 - SYS_GETUID = 174 - SYS_GETEUID = 175 - SYS_GETGID = 176 - SYS_GETEGID = 177 - SYS_GETTID = 178 - SYS_SYSINFO = 179 - SYS_MQ_OPEN = 180 - SYS_MQ_UNLINK = 181 - SYS_MQ_TIMEDSEND = 182 - SYS_MQ_TIMEDRECEIVE = 183 - SYS_MQ_NOTIFY = 184 - SYS_MQ_GETSETATTR = 185 - SYS_MSGGET = 186 - SYS_MSGCTL = 187 - SYS_MSGRCV = 188 - SYS_MSGSND = 189 - SYS_SEMGET = 190 - SYS_SEMCTL = 191 - SYS_SEMTIMEDOP = 192 - SYS_SEMOP = 193 - SYS_SHMGET = 194 - SYS_SHMCTL = 195 - SYS_SHMAT = 196 - SYS_SHMDT = 197 - SYS_SOCKET = 198 - SYS_SOCKETPAIR = 199 - SYS_BIND = 200 - SYS_LISTEN = 201 - SYS_ACCEPT = 202 - SYS_CONNECT = 203 - SYS_GETSOCKNAME = 204 - SYS_GETPEERNAME = 205 - SYS_SENDTO = 206 - SYS_RECVFROM = 207 - SYS_SETSOCKOPT = 208 - SYS_GETSOCKOPT = 209 - SYS_SHUTDOWN = 210 - SYS_SENDMSG = 211 - SYS_RECVMSG = 212 - SYS_READAHEAD = 213 - SYS_BRK = 214 - SYS_MUNMAP = 215 - SYS_MREMAP = 216 - SYS_ADD_KEY = 217 - SYS_REQUEST_KEY = 218 - SYS_KEYCTL = 219 - SYS_CLONE = 220 - SYS_EXECVE = 221 - SYS_MMAP = 222 - SYS_FADVISE64 = 223 - SYS_SWAPON = 224 - SYS_SWAPOFF = 225 - SYS_MPROTECT = 226 - SYS_MSYNC = 227 - SYS_MLOCK = 228 - SYS_MUNLOCK = 229 - SYS_MLOCKALL = 230 - SYS_MUNLOCKALL = 231 - SYS_MINCORE = 232 - SYS_MADVISE = 233 - SYS_REMAP_FILE_PAGES = 234 - SYS_MBIND = 235 - SYS_GET_MEMPOLICY = 236 - SYS_SET_MEMPOLICY = 237 - SYS_MIGRATE_PAGES = 238 - SYS_MOVE_PAGES = 239 - SYS_RT_TGSIGQUEUEINFO = 240 - SYS_PERF_EVENT_OPEN = 241 - SYS_ACCEPT4 = 242 - SYS_RECVMMSG = 243 - SYS_ARCH_SPECIFIC_SYSCALL = 244 - SYS_WAIT4 = 260 - SYS_PRLIMIT64 = 261 - SYS_FANOTIFY_INIT = 262 - SYS_FANOTIFY_MARK = 263 - SYS_NAME_TO_HANDLE_AT = 264 - SYS_OPEN_BY_HANDLE_AT = 265 - SYS_CLOCK_ADJTIME = 266 - SYS_SYNCFS = 267 - SYS_SETNS = 268 - SYS_SENDMMSG = 269 - SYS_PROCESS_VM_READV = 270 - SYS_PROCESS_VM_WRITEV = 271 - SYS_KCMP = 272 - SYS_FINIT_MODULE = 273 - SYS_SCHED_SETATTR = 274 - SYS_SCHED_GETATTR = 275 - SYS_RENAMEAT2 = 276 - SYS_SECCOMP = 277 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64.go deleted file mode 100644 index e1b08f00d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ /dev/null @@ -1,360 +0,0 @@ -// mksysnum_linux.pl /usr/include/asm/unistd.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build ppc64,linux - -package unix - -const ( - SYS_RESTART_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAITPID = 7 - SYS_CREAT = 8 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_EXECVE = 11 - SYS_CHDIR = 12 - SYS_TIME = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_LCHOWN = 16 - SYS_BREAK = 17 - SYS_OLDSTAT = 18 - SYS_LSEEK = 19 - SYS_GETPID = 20 - SYS_MOUNT = 21 - SYS_UMOUNT = 22 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_STIME = 25 - SYS_PTRACE = 26 - SYS_ALARM = 27 - SYS_OLDFSTAT = 28 - SYS_PAUSE = 29 - SYS_UTIME = 30 - SYS_STTY = 31 - SYS_GTTY = 32 - SYS_ACCESS = 33 - SYS_NICE = 34 - SYS_FTIME = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_RENAME = 38 - SYS_MKDIR = 39 - SYS_RMDIR = 40 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_TIMES = 43 - SYS_PROF = 44 - SYS_BRK = 45 - SYS_SETGID = 46 - SYS_GETGID = 47 - SYS_SIGNAL = 48 - SYS_GETEUID = 49 - SYS_GETEGID = 50 - SYS_ACCT = 51 - SYS_UMOUNT2 = 52 - SYS_LOCK = 53 - SYS_IOCTL = 54 - SYS_FCNTL = 55 - SYS_MPX = 56 - SYS_SETPGID = 57 - SYS_ULIMIT = 58 - SYS_OLDOLDUNAME = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_USTAT = 62 - SYS_DUP2 = 63 - SYS_GETPPID = 64 - SYS_GETPGRP = 65 - SYS_SETSID = 66 - SYS_SIGACTION = 67 - SYS_SGETMASK = 68 - SYS_SSETMASK = 69 - SYS_SETREUID = 70 - SYS_SETREGID = 71 - SYS_SIGSUSPEND = 72 - SYS_SIGPENDING = 73 - SYS_SETHOSTNAME = 74 - SYS_SETRLIMIT = 75 - SYS_GETRLIMIT = 76 - SYS_GETRUSAGE = 77 - SYS_GETTIMEOFDAY = 78 - SYS_SETTIMEOFDAY = 79 - SYS_GETGROUPS = 80 - SYS_SETGROUPS = 81 - SYS_SELECT = 82 - SYS_SYMLINK = 83 - SYS_OLDLSTAT = 84 - SYS_READLINK = 85 - SYS_USELIB = 86 - SYS_SWAPON = 87 - SYS_REBOOT = 88 - SYS_READDIR = 89 - SYS_MMAP = 90 - SYS_MUNMAP = 91 - SYS_TRUNCATE = 92 - SYS_FTRUNCATE = 93 - SYS_FCHMOD = 94 - SYS_FCHOWN = 95 - SYS_GETPRIORITY = 96 - SYS_SETPRIORITY = 97 - SYS_PROFIL = 98 - SYS_STATFS = 99 - SYS_FSTATFS = 100 - SYS_IOPERM = 101 - SYS_SOCKETCALL = 102 - SYS_SYSLOG = 103 - SYS_SETITIMER = 104 - SYS_GETITIMER = 105 - SYS_STAT = 106 - SYS_LSTAT = 107 - SYS_FSTAT = 108 - SYS_OLDUNAME = 109 - SYS_IOPL = 110 - SYS_VHANGUP = 111 - SYS_IDLE = 112 - SYS_VM86 = 113 - SYS_WAIT4 = 114 - SYS_SWAPOFF = 115 - SYS_SYSINFO = 116 - SYS_IPC = 117 - SYS_FSYNC = 118 - SYS_SIGRETURN = 119 - SYS_CLONE = 120 - SYS_SETDOMAINNAME = 121 - SYS_UNAME = 122 - SYS_MODIFY_LDT = 123 - SYS_ADJTIMEX = 124 - SYS_MPROTECT = 125 - SYS_SIGPROCMASK = 126 - SYS_CREATE_MODULE = 127 - SYS_INIT_MODULE = 128 - SYS_DELETE_MODULE = 129 - SYS_GET_KERNEL_SYMS = 130 - SYS_QUOTACTL = 131 - SYS_GETPGID = 132 - SYS_FCHDIR = 133 - SYS_BDFLUSH = 134 - SYS_SYSFS = 135 - SYS_PERSONALITY = 136 - SYS_AFS_SYSCALL = 137 - SYS_SETFSUID = 138 - SYS_SETFSGID = 139 - SYS__LLSEEK = 140 - SYS_GETDENTS = 141 - SYS__NEWSELECT = 142 - SYS_FLOCK = 143 - SYS_MSYNC = 144 - SYS_READV = 145 - SYS_WRITEV = 146 - SYS_GETSID = 147 - SYS_FDATASYNC = 148 - SYS__SYSCTL = 149 - SYS_MLOCK = 150 - SYS_MUNLOCK = 151 - SYS_MLOCKALL = 152 - SYS_MUNLOCKALL = 153 - SYS_SCHED_SETPARAM = 154 - SYS_SCHED_GETPARAM = 155 - SYS_SCHED_SETSCHEDULER = 156 - SYS_SCHED_GETSCHEDULER = 157 - SYS_SCHED_YIELD = 158 - SYS_SCHED_GET_PRIORITY_MAX = 159 - SYS_SCHED_GET_PRIORITY_MIN = 160 - SYS_SCHED_RR_GET_INTERVAL = 161 - SYS_NANOSLEEP = 162 - SYS_MREMAP = 163 - SYS_SETRESUID = 164 - SYS_GETRESUID = 165 - SYS_QUERY_MODULE = 166 - SYS_POLL = 167 - SYS_NFSSERVCTL = 168 - SYS_SETRESGID = 169 - SYS_GETRESGID = 170 - SYS_PRCTL = 171 - SYS_RT_SIGRETURN = 172 - SYS_RT_SIGACTION = 173 - SYS_RT_SIGPROCMASK = 174 - SYS_RT_SIGPENDING = 175 - SYS_RT_SIGTIMEDWAIT = 176 - SYS_RT_SIGQUEUEINFO = 177 - SYS_RT_SIGSUSPEND = 178 - SYS_PREAD64 = 179 - SYS_PWRITE64 = 180 - SYS_CHOWN = 181 - SYS_GETCWD = 182 - SYS_CAPGET = 183 - SYS_CAPSET = 184 - SYS_SIGALTSTACK = 185 - SYS_SENDFILE = 186 - SYS_GETPMSG = 187 - SYS_PUTPMSG = 188 - SYS_VFORK = 189 - SYS_UGETRLIMIT = 190 - SYS_READAHEAD = 191 - SYS_PCICONFIG_READ = 198 - SYS_PCICONFIG_WRITE = 199 - SYS_PCICONFIG_IOBASE = 200 - SYS_MULTIPLEXER = 201 - SYS_GETDENTS64 = 202 - SYS_PIVOT_ROOT = 203 - SYS_MADVISE = 205 - SYS_MINCORE = 206 - SYS_GETTID = 207 - SYS_TKILL = 208 - SYS_SETXATTR = 209 - SYS_LSETXATTR = 210 - SYS_FSETXATTR = 211 - SYS_GETXATTR = 212 - SYS_LGETXATTR = 213 - SYS_FGETXATTR = 214 - SYS_LISTXATTR = 215 - SYS_LLISTXATTR = 216 - SYS_FLISTXATTR = 217 - SYS_REMOVEXATTR = 218 - SYS_LREMOVEXATTR = 219 - SYS_FREMOVEXATTR = 220 - SYS_FUTEX = 221 - SYS_SCHED_SETAFFINITY = 222 - SYS_SCHED_GETAFFINITY = 223 - SYS_TUXCALL = 225 - SYS_IO_SETUP = 227 - SYS_IO_DESTROY = 228 - SYS_IO_GETEVENTS = 229 - SYS_IO_SUBMIT = 230 - SYS_IO_CANCEL = 231 - SYS_SET_TID_ADDRESS = 232 - SYS_FADVISE64 = 233 - SYS_EXIT_GROUP = 234 - SYS_LOOKUP_DCOOKIE = 235 - SYS_EPOLL_CREATE = 236 - SYS_EPOLL_CTL = 237 - SYS_EPOLL_WAIT = 238 - SYS_REMAP_FILE_PAGES = 239 - SYS_TIMER_CREATE = 240 - SYS_TIMER_SETTIME = 241 - SYS_TIMER_GETTIME = 242 - SYS_TIMER_GETOVERRUN = 243 - SYS_TIMER_DELETE = 244 - SYS_CLOCK_SETTIME = 245 - SYS_CLOCK_GETTIME = 246 - SYS_CLOCK_GETRES = 247 - SYS_CLOCK_NANOSLEEP = 248 - SYS_SWAPCONTEXT = 249 - SYS_TGKILL = 250 - SYS_UTIMES = 251 - SYS_STATFS64 = 252 - SYS_FSTATFS64 = 253 - SYS_RTAS = 255 - SYS_SYS_DEBUG_SETCONTEXT = 256 - SYS_MIGRATE_PAGES = 258 - SYS_MBIND = 259 - SYS_GET_MEMPOLICY = 260 - SYS_SET_MEMPOLICY = 261 - SYS_MQ_OPEN = 262 - SYS_MQ_UNLINK = 263 - SYS_MQ_TIMEDSEND = 264 - SYS_MQ_TIMEDRECEIVE = 265 - SYS_MQ_NOTIFY = 266 - SYS_MQ_GETSETATTR = 267 - SYS_KEXEC_LOAD = 268 - SYS_ADD_KEY = 269 - SYS_REQUEST_KEY = 270 - SYS_KEYCTL = 271 - SYS_WAITID = 272 - SYS_IOPRIO_SET = 273 - SYS_IOPRIO_GET = 274 - SYS_INOTIFY_INIT = 275 - SYS_INOTIFY_ADD_WATCH = 276 - SYS_INOTIFY_RM_WATCH = 277 - SYS_SPU_RUN = 278 - SYS_SPU_CREATE = 279 - SYS_PSELECT6 = 280 - SYS_PPOLL = 281 - SYS_UNSHARE = 282 - SYS_SPLICE = 283 - SYS_TEE = 284 - SYS_VMSPLICE = 285 - SYS_OPENAT = 286 - SYS_MKDIRAT = 287 - SYS_MKNODAT = 288 - SYS_FCHOWNAT = 289 - SYS_FUTIMESAT = 290 - SYS_NEWFSTATAT = 291 - SYS_UNLINKAT = 292 - SYS_RENAMEAT = 293 - SYS_LINKAT = 294 - SYS_SYMLINKAT = 295 - SYS_READLINKAT = 296 - SYS_FCHMODAT = 297 - SYS_FACCESSAT = 298 - SYS_GET_ROBUST_LIST = 299 - SYS_SET_ROBUST_LIST = 300 - SYS_MOVE_PAGES = 301 - SYS_GETCPU = 302 - SYS_EPOLL_PWAIT = 303 - SYS_UTIMENSAT = 304 - SYS_SIGNALFD = 305 - SYS_TIMERFD_CREATE = 306 - SYS_EVENTFD = 307 - SYS_SYNC_FILE_RANGE2 = 308 - SYS_FALLOCATE = 309 - SYS_SUBPAGE_PROT = 310 - SYS_TIMERFD_SETTIME = 311 - SYS_TIMERFD_GETTIME = 312 - SYS_SIGNALFD4 = 313 - SYS_EVENTFD2 = 314 - SYS_EPOLL_CREATE1 = 315 - SYS_DUP3 = 316 - SYS_PIPE2 = 317 - SYS_INOTIFY_INIT1 = 318 - SYS_PERF_EVENT_OPEN = 319 - SYS_PREADV = 320 - SYS_PWRITEV = 321 - SYS_RT_TGSIGQUEUEINFO = 322 - SYS_FANOTIFY_INIT = 323 - SYS_FANOTIFY_MARK = 324 - SYS_PRLIMIT64 = 325 - SYS_SOCKET = 326 - SYS_BIND = 327 - SYS_CONNECT = 328 - SYS_LISTEN = 329 - SYS_ACCEPT = 330 - SYS_GETSOCKNAME = 331 - SYS_GETPEERNAME = 332 - SYS_SOCKETPAIR = 333 - SYS_SEND = 334 - SYS_SENDTO = 335 - SYS_RECV = 336 - SYS_RECVFROM = 337 - SYS_SHUTDOWN = 338 - SYS_SETSOCKOPT = 339 - SYS_GETSOCKOPT = 340 - SYS_SENDMSG = 341 - SYS_RECVMSG = 342 - SYS_RECVMMSG = 343 - SYS_ACCEPT4 = 344 - SYS_NAME_TO_HANDLE_AT = 345 - SYS_OPEN_BY_HANDLE_AT = 346 - SYS_CLOCK_ADJTIME = 347 - SYS_SYNCFS = 348 - SYS_SENDMMSG = 349 - SYS_SETNS = 350 - SYS_PROCESS_VM_READV = 351 - SYS_PROCESS_VM_WRITEV = 352 - SYS_FINIT_MODULE = 353 - SYS_KCMP = 354 - SYS_SCHED_SETATTR = 355 - SYS_SCHED_GETATTR = 356 - SYS_RENAMEAT2 = 357 - SYS_SECCOMP = 358 - SYS_GETRANDOM = 359 - SYS_MEMFD_CREATE = 360 - SYS_BPF = 361 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go deleted file mode 100644 index 45e63f51a..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ /dev/null @@ -1,353 +0,0 @@ -// mksysnum_linux.pl /usr/include/powerpc64le-linux-gnu/asm/unistd.h -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build ppc64le,linux - -package unix - -const ( - SYS_RESTART_SYSCALL = 0 - SYS_EXIT = 1 - SYS_FORK = 2 - SYS_READ = 3 - SYS_WRITE = 4 - SYS_OPEN = 5 - SYS_CLOSE = 6 - SYS_WAITPID = 7 - SYS_CREAT = 8 - SYS_LINK = 9 - SYS_UNLINK = 10 - SYS_EXECVE = 11 - SYS_CHDIR = 12 - SYS_TIME = 13 - SYS_MKNOD = 14 - SYS_CHMOD = 15 - SYS_LCHOWN = 16 - SYS_BREAK = 17 - SYS_OLDSTAT = 18 - SYS_LSEEK = 19 - SYS_GETPID = 20 - SYS_MOUNT = 21 - SYS_UMOUNT = 22 - SYS_SETUID = 23 - SYS_GETUID = 24 - SYS_STIME = 25 - SYS_PTRACE = 26 - SYS_ALARM = 27 - SYS_OLDFSTAT = 28 - SYS_PAUSE = 29 - SYS_UTIME = 30 - SYS_STTY = 31 - SYS_GTTY = 32 - SYS_ACCESS = 33 - SYS_NICE = 34 - SYS_FTIME = 35 - SYS_SYNC = 36 - SYS_KILL = 37 - SYS_RENAME = 38 - SYS_MKDIR = 39 - SYS_RMDIR = 40 - SYS_DUP = 41 - SYS_PIPE = 42 - SYS_TIMES = 43 - SYS_PROF = 44 - SYS_BRK = 45 - SYS_SETGID = 46 - SYS_GETGID = 47 - SYS_SIGNAL = 48 - SYS_GETEUID = 49 - SYS_GETEGID = 50 - SYS_ACCT = 51 - SYS_UMOUNT2 = 52 - SYS_LOCK = 53 - SYS_IOCTL = 54 - SYS_FCNTL = 55 - SYS_MPX = 56 - SYS_SETPGID = 57 - SYS_ULIMIT = 58 - SYS_OLDOLDUNAME = 59 - SYS_UMASK = 60 - SYS_CHROOT = 61 - SYS_USTAT = 62 - SYS_DUP2 = 63 - SYS_GETPPID = 64 - SYS_GETPGRP = 65 - SYS_SETSID = 66 - SYS_SIGACTION = 67 - SYS_SGETMASK = 68 - SYS_SSETMASK = 69 - SYS_SETREUID = 70 - SYS_SETREGID = 71 - SYS_SIGSUSPEND = 72 - SYS_SIGPENDING = 73 - SYS_SETHOSTNAME = 74 - SYS_SETRLIMIT = 75 - SYS_GETRLIMIT = 76 - SYS_GETRUSAGE = 77 - SYS_GETTIMEOFDAY = 78 - SYS_SETTIMEOFDAY = 79 - SYS_GETGROUPS = 80 - SYS_SETGROUPS = 81 - SYS_SELECT = 82 - SYS_SYMLINK = 83 - SYS_OLDLSTAT = 84 - SYS_READLINK = 85 - SYS_USELIB = 86 - SYS_SWAPON = 87 - SYS_REBOOT = 88 - SYS_READDIR = 89 - SYS_MMAP = 90 - SYS_MUNMAP = 91 - SYS_TRUNCATE = 92 - SYS_FTRUNCATE = 93 - SYS_FCHMOD = 94 - SYS_FCHOWN = 95 - SYS_GETPRIORITY = 96 - SYS_SETPRIORITY = 97 - SYS_PROFIL = 98 - SYS_STATFS = 99 - SYS_FSTATFS = 100 - SYS_IOPERM = 101 - SYS_SOCKETCALL = 102 - SYS_SYSLOG = 103 - SYS_SETITIMER = 104 - SYS_GETITIMER = 105 - SYS_STAT = 106 - SYS_LSTAT = 107 - SYS_FSTAT = 108 - SYS_OLDUNAME = 109 - SYS_IOPL = 110 - SYS_VHANGUP = 111 - SYS_IDLE = 112 - SYS_VM86 = 113 - SYS_WAIT4 = 114 - SYS_SWAPOFF = 115 - SYS_SYSINFO = 116 - SYS_IPC = 117 - SYS_FSYNC = 118 - SYS_SIGRETURN = 119 - SYS_CLONE = 120 - SYS_SETDOMAINNAME = 121 - SYS_UNAME = 122 - SYS_MODIFY_LDT = 123 - SYS_ADJTIMEX = 124 - SYS_MPROTECT = 125 - SYS_SIGPROCMASK = 126 - SYS_CREATE_MODULE = 127 - SYS_INIT_MODULE = 128 - SYS_DELETE_MODULE = 129 - SYS_GET_KERNEL_SYMS = 130 - SYS_QUOTACTL = 131 - SYS_GETPGID = 132 - SYS_FCHDIR = 133 - SYS_BDFLUSH = 134 - SYS_SYSFS = 135 - SYS_PERSONALITY = 136 - SYS_AFS_SYSCALL = 137 - SYS_SETFSUID = 138 - SYS_SETFSGID = 139 - SYS__LLSEEK = 140 - SYS_GETDENTS = 141 - SYS__NEWSELECT = 142 - SYS_FLOCK = 143 - SYS_MSYNC = 144 - SYS_READV = 145 - SYS_WRITEV = 146 - SYS_GETSID = 147 - SYS_FDATASYNC = 148 - SYS__SYSCTL = 149 - SYS_MLOCK = 150 - SYS_MUNLOCK = 151 - SYS_MLOCKALL = 152 - SYS_MUNLOCKALL = 153 - SYS_SCHED_SETPARAM = 154 - SYS_SCHED_GETPARAM = 155 - SYS_SCHED_SETSCHEDULER = 156 - SYS_SCHED_GETSCHEDULER = 157 - SYS_SCHED_YIELD = 158 - SYS_SCHED_GET_PRIORITY_MAX = 159 - SYS_SCHED_GET_PRIORITY_MIN = 160 - SYS_SCHED_RR_GET_INTERVAL = 161 - SYS_NANOSLEEP = 162 - SYS_MREMAP = 163 - SYS_SETRESUID = 164 - SYS_GETRESUID = 165 - SYS_QUERY_MODULE = 166 - SYS_POLL = 167 - SYS_NFSSERVCTL = 168 - SYS_SETRESGID = 169 - SYS_GETRESGID = 170 - SYS_PRCTL = 171 - SYS_RT_SIGRETURN = 172 - SYS_RT_SIGACTION = 173 - SYS_RT_SIGPROCMASK = 174 - SYS_RT_SIGPENDING = 175 - SYS_RT_SIGTIMEDWAIT = 176 - SYS_RT_SIGQUEUEINFO = 177 - SYS_RT_SIGSUSPEND = 178 - SYS_PREAD64 = 179 - SYS_PWRITE64 = 180 - SYS_CHOWN = 181 - SYS_GETCWD = 182 - SYS_CAPGET = 183 - SYS_CAPSET = 184 - SYS_SIGALTSTACK = 185 - SYS_SENDFILE = 186 - SYS_GETPMSG = 187 - SYS_PUTPMSG = 188 - SYS_VFORK = 189 - SYS_UGETRLIMIT = 190 - SYS_READAHEAD = 191 - SYS_PCICONFIG_READ = 198 - SYS_PCICONFIG_WRITE = 199 - SYS_PCICONFIG_IOBASE = 200 - SYS_MULTIPLEXER = 201 - SYS_GETDENTS64 = 202 - SYS_PIVOT_ROOT = 203 - SYS_MADVISE = 205 - SYS_MINCORE = 206 - SYS_GETTID = 207 - SYS_TKILL = 208 - SYS_SETXATTR = 209 - SYS_LSETXATTR = 210 - SYS_FSETXATTR = 211 - SYS_GETXATTR = 212 - SYS_LGETXATTR = 213 - SYS_FGETXATTR = 214 - SYS_LISTXATTR = 215 - SYS_LLISTXATTR = 216 - SYS_FLISTXATTR = 217 - SYS_REMOVEXATTR = 218 - SYS_LREMOVEXATTR = 219 - SYS_FREMOVEXATTR = 220 - SYS_FUTEX = 221 - SYS_SCHED_SETAFFINITY = 222 - SYS_SCHED_GETAFFINITY = 223 - SYS_TUXCALL = 225 - SYS_IO_SETUP = 227 - SYS_IO_DESTROY = 228 - SYS_IO_GETEVENTS = 229 - SYS_IO_SUBMIT = 230 - SYS_IO_CANCEL = 231 - SYS_SET_TID_ADDRESS = 232 - SYS_FADVISE64 = 233 - SYS_EXIT_GROUP = 234 - SYS_LOOKUP_DCOOKIE = 235 - SYS_EPOLL_CREATE = 236 - SYS_EPOLL_CTL = 237 - SYS_EPOLL_WAIT = 238 - SYS_REMAP_FILE_PAGES = 239 - SYS_TIMER_CREATE = 240 - SYS_TIMER_SETTIME = 241 - SYS_TIMER_GETTIME = 242 - SYS_TIMER_GETOVERRUN = 243 - SYS_TIMER_DELETE = 244 - SYS_CLOCK_SETTIME = 245 - SYS_CLOCK_GETTIME = 246 - SYS_CLOCK_GETRES = 247 - SYS_CLOCK_NANOSLEEP = 248 - SYS_SWAPCONTEXT = 249 - SYS_TGKILL = 250 - SYS_UTIMES = 251 - SYS_STATFS64 = 252 - SYS_FSTATFS64 = 253 - SYS_RTAS = 255 - SYS_SYS_DEBUG_SETCONTEXT = 256 - SYS_MIGRATE_PAGES = 258 - SYS_MBIND = 259 - SYS_GET_MEMPOLICY = 260 - SYS_SET_MEMPOLICY = 261 - SYS_MQ_OPEN = 262 - SYS_MQ_UNLINK = 263 - SYS_MQ_TIMEDSEND = 264 - SYS_MQ_TIMEDRECEIVE = 265 - SYS_MQ_NOTIFY = 266 - SYS_MQ_GETSETATTR = 267 - SYS_KEXEC_LOAD = 268 - SYS_ADD_KEY = 269 - SYS_REQUEST_KEY = 270 - SYS_KEYCTL = 271 - SYS_WAITID = 272 - SYS_IOPRIO_SET = 273 - SYS_IOPRIO_GET = 274 - SYS_INOTIFY_INIT = 275 - SYS_INOTIFY_ADD_WATCH = 276 - SYS_INOTIFY_RM_WATCH = 277 - SYS_SPU_RUN = 278 - SYS_SPU_CREATE = 279 - SYS_PSELECT6 = 280 - SYS_PPOLL = 281 - SYS_UNSHARE = 282 - SYS_SPLICE = 283 - SYS_TEE = 284 - SYS_VMSPLICE = 285 - SYS_OPENAT = 286 - SYS_MKDIRAT = 287 - SYS_MKNODAT = 288 - SYS_FCHOWNAT = 289 - SYS_FUTIMESAT = 290 - SYS_NEWFSTATAT = 291 - SYS_UNLINKAT = 292 - SYS_RENAMEAT = 293 - SYS_LINKAT = 294 - SYS_SYMLINKAT = 295 - SYS_READLINKAT = 296 - SYS_FCHMODAT = 297 - SYS_FACCESSAT = 298 - SYS_GET_ROBUST_LIST = 299 - SYS_SET_ROBUST_LIST = 300 - SYS_MOVE_PAGES = 301 - SYS_GETCPU = 302 - SYS_EPOLL_PWAIT = 303 - SYS_UTIMENSAT = 304 - SYS_SIGNALFD = 305 - SYS_TIMERFD_CREATE = 306 - SYS_EVENTFD = 307 - SYS_SYNC_FILE_RANGE2 = 308 - SYS_FALLOCATE = 309 - SYS_SUBPAGE_PROT = 310 - SYS_TIMERFD_SETTIME = 311 - SYS_TIMERFD_GETTIME = 312 - SYS_SIGNALFD4 = 313 - SYS_EVENTFD2 = 314 - SYS_EPOLL_CREATE1 = 315 - SYS_DUP3 = 316 - SYS_PIPE2 = 317 - SYS_INOTIFY_INIT1 = 318 - SYS_PERF_EVENT_OPEN = 319 - SYS_PREADV = 320 - SYS_PWRITEV = 321 - SYS_RT_TGSIGQUEUEINFO = 322 - SYS_FANOTIFY_INIT = 323 - SYS_FANOTIFY_MARK = 324 - SYS_PRLIMIT64 = 325 - SYS_SOCKET = 326 - SYS_BIND = 327 - SYS_CONNECT = 328 - SYS_LISTEN = 329 - SYS_ACCEPT = 330 - SYS_GETSOCKNAME = 331 - SYS_GETPEERNAME = 332 - SYS_SOCKETPAIR = 333 - SYS_SEND = 334 - SYS_SENDTO = 335 - SYS_RECV = 336 - SYS_RECVFROM = 337 - SYS_SHUTDOWN = 338 - SYS_SETSOCKOPT = 339 - SYS_GETSOCKOPT = 340 - SYS_SENDMSG = 341 - SYS_RECVMSG = 342 - SYS_RECVMMSG = 343 - SYS_ACCEPT4 = 344 - SYS_NAME_TO_HANDLE_AT = 345 - SYS_OPEN_BY_HANDLE_AT = 346 - SYS_CLOCK_ADJTIME = 347 - SYS_SYNCFS = 348 - SYS_SENDMMSG = 349 - SYS_SETNS = 350 - SYS_PROCESS_VM_READV = 351 - SYS_PROCESS_VM_WRITEV = 352 - SYS_FINIT_MODULE = 353 - SYS_KCMP = 354 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_386.go deleted file mode 100644 index f60d8f988..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_386.go +++ /dev/null @@ -1,273 +0,0 @@ -// mksysnum_netbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,netbsd - -package unix - -const ( - SYS_EXIT = 1 // { void|sys||exit(int rval); } - SYS_FORK = 2 // { int|sys||fork(void); } - SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } - SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } - SYS_CLOSE = 6 // { int|sys||close(int fd); } - SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } - SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } - SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } - SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } - SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } - SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } - SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } - SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } - SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } - SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } - SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } - SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } - SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } - SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } - SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } - SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } - SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } - SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } - SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } - SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } - SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } - SYS_SYNC = 36 // { void|sys||sync(void); } - SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } - SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } - SYS_DUP = 41 // { int|sys||dup(int fd); } - SYS_PIPE = 42 // { int|sys||pipe(void); } - SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } - SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } - SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } - SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } - SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } - SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } - SYS_ACCT = 51 // { int|sys||acct(const char *path); } - SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } - SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } - SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } - SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } - SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } - SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } - SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } - SYS_VFORK = 66 // { int|sys||vfork(void); } - SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } - SYS_SSTK = 70 // { int|sys||sstk(int incr); } - SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } - SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } - SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } - SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } - SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } - SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } - SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } - SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } - SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } - SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } - SYS_FSYNC = 95 // { int|sys||fsync(int fd); } - SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } - SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } - SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } - SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } - SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } - SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } - SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } - SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } - SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } - SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } - SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } - SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } - SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } - SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } - SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } - SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } - SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } - SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } - SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } - SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } - SYS_SETSID = 147 // { int|sys||setsid(void); } - SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } - SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } - SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } - SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } - SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } - SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } - SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } - SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } - SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } - SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } - SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } - SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } - SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } - SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } - SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } - SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } - SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } - SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } - SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } - SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } - SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } - SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } - SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } - SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } - SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } - SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } - SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } - SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } - SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } - SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } - SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } - SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } - SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } - SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } - SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } - SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } - SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } - SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } - SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } - SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } - SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } - SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } - SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } - SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } - SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } - SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } - SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } - SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } - SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } - SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } - SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } - SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } - SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } - SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } - SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } - SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } - SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } - SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } - SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } - SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } - SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } - SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } - SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } - SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } - SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } - SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } - SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } - SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } - SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } - SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } - SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } - SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } - SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } - SYS_KQUEUE = 344 // { int|sys||kqueue(void); } - SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } - SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } - SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } - SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } - SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } - SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } - SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } - SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } - SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } - SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } - SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } - SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } - SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } - SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } - SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } - SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } - SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } - SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } - SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } - SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } - SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } - SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } - SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } - SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } - SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } - SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } - SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } - SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } - SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } - SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } - SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } - SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } - SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } - SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } - SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } - SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } - SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } - SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } - SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } - SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } - SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } - SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } - SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } - SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } - SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } - SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } - SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } - SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } - SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } - SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } - SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } - SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } - SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } - SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } - SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } - SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } - SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } - SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } - SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } - SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } - SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } - SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } - SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } - SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } - SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } - SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } - SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } - SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } - SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } - SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } - SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } - SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } - SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } - SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } - SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } - SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } - SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } - SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } - SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } - SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } - SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } - SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } - SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } - SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } - SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } - SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } - SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } - SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } - SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } - SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } - SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go deleted file mode 100644 index 48a91d464..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go +++ /dev/null @@ -1,273 +0,0 @@ -// mksysnum_netbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build amd64,netbsd - -package unix - -const ( - SYS_EXIT = 1 // { void|sys||exit(int rval); } - SYS_FORK = 2 // { int|sys||fork(void); } - SYS_READ = 3 // { ssize_t|sys||read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t|sys||write(int fd, const void *buf, size_t nbyte); } - SYS_OPEN = 5 // { int|sys||open(const char *path, int flags, ... mode_t mode); } - SYS_CLOSE = 6 // { int|sys||close(int fd); } - SYS_LINK = 9 // { int|sys||link(const char *path, const char *link); } - SYS_UNLINK = 10 // { int|sys||unlink(const char *path); } - SYS_CHDIR = 12 // { int|sys||chdir(const char *path); } - SYS_FCHDIR = 13 // { int|sys||fchdir(int fd); } - SYS_CHMOD = 15 // { int|sys||chmod(const char *path, mode_t mode); } - SYS_CHOWN = 16 // { int|sys||chown(const char *path, uid_t uid, gid_t gid); } - SYS_BREAK = 17 // { int|sys||obreak(char *nsize); } - SYS_GETPID = 20 // { pid_t|sys||getpid_with_ppid(void); } - SYS_UNMOUNT = 22 // { int|sys||unmount(const char *path, int flags); } - SYS_SETUID = 23 // { int|sys||setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t|sys||getuid_with_euid(void); } - SYS_GETEUID = 25 // { uid_t|sys||geteuid(void); } - SYS_PTRACE = 26 // { int|sys||ptrace(int req, pid_t pid, void *addr, int data); } - SYS_RECVMSG = 27 // { ssize_t|sys||recvmsg(int s, struct msghdr *msg, int flags); } - SYS_SENDMSG = 28 // { ssize_t|sys||sendmsg(int s, const struct msghdr *msg, int flags); } - SYS_RECVFROM = 29 // { ssize_t|sys||recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } - SYS_ACCEPT = 30 // { int|sys||accept(int s, struct sockaddr *name, socklen_t *anamelen); } - SYS_GETPEERNAME = 31 // { int|sys||getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } - SYS_GETSOCKNAME = 32 // { int|sys||getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } - SYS_ACCESS = 33 // { int|sys||access(const char *path, int flags); } - SYS_CHFLAGS = 34 // { int|sys||chflags(const char *path, u_long flags); } - SYS_FCHFLAGS = 35 // { int|sys||fchflags(int fd, u_long flags); } - SYS_SYNC = 36 // { void|sys||sync(void); } - SYS_KILL = 37 // { int|sys||kill(pid_t pid, int signum); } - SYS_GETPPID = 39 // { pid_t|sys||getppid(void); } - SYS_DUP = 41 // { int|sys||dup(int fd); } - SYS_PIPE = 42 // { int|sys||pipe(void); } - SYS_GETEGID = 43 // { gid_t|sys||getegid(void); } - SYS_PROFIL = 44 // { int|sys||profil(char *samples, size_t size, u_long offset, u_int scale); } - SYS_KTRACE = 45 // { int|sys||ktrace(const char *fname, int ops, int facs, pid_t pid); } - SYS_GETGID = 47 // { gid_t|sys||getgid_with_egid(void); } - SYS___GETLOGIN = 49 // { int|sys||__getlogin(char *namebuf, size_t namelen); } - SYS___SETLOGIN = 50 // { int|sys||__setlogin(const char *namebuf); } - SYS_ACCT = 51 // { int|sys||acct(const char *path); } - SYS_IOCTL = 54 // { int|sys||ioctl(int fd, u_long com, ... void *data); } - SYS_REVOKE = 56 // { int|sys||revoke(const char *path); } - SYS_SYMLINK = 57 // { int|sys||symlink(const char *path, const char *link); } - SYS_READLINK = 58 // { ssize_t|sys||readlink(const char *path, char *buf, size_t count); } - SYS_EXECVE = 59 // { int|sys||execve(const char *path, char * const *argp, char * const *envp); } - SYS_UMASK = 60 // { mode_t|sys||umask(mode_t newmask); } - SYS_CHROOT = 61 // { int|sys||chroot(const char *path); } - SYS_VFORK = 66 // { int|sys||vfork(void); } - SYS_SBRK = 69 // { int|sys||sbrk(intptr_t incr); } - SYS_SSTK = 70 // { int|sys||sstk(int incr); } - SYS_VADVISE = 72 // { int|sys||ovadvise(int anom); } - SYS_MUNMAP = 73 // { int|sys||munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int|sys||mprotect(void *addr, size_t len, int prot); } - SYS_MADVISE = 75 // { int|sys||madvise(void *addr, size_t len, int behav); } - SYS_MINCORE = 78 // { int|sys||mincore(void *addr, size_t len, char *vec); } - SYS_GETGROUPS = 79 // { int|sys||getgroups(int gidsetsize, gid_t *gidset); } - SYS_SETGROUPS = 80 // { int|sys||setgroups(int gidsetsize, const gid_t *gidset); } - SYS_GETPGRP = 81 // { int|sys||getpgrp(void); } - SYS_SETPGID = 82 // { int|sys||setpgid(pid_t pid, pid_t pgid); } - SYS_DUP2 = 90 // { int|sys||dup2(int from, int to); } - SYS_FCNTL = 92 // { int|sys||fcntl(int fd, int cmd, ... void *arg); } - SYS_FSYNC = 95 // { int|sys||fsync(int fd); } - SYS_SETPRIORITY = 96 // { int|sys||setpriority(int which, id_t who, int prio); } - SYS_CONNECT = 98 // { int|sys||connect(int s, const struct sockaddr *name, socklen_t namelen); } - SYS_GETPRIORITY = 100 // { int|sys||getpriority(int which, id_t who); } - SYS_BIND = 104 // { int|sys||bind(int s, const struct sockaddr *name, socklen_t namelen); } - SYS_SETSOCKOPT = 105 // { int|sys||setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } - SYS_LISTEN = 106 // { int|sys||listen(int s, int backlog); } - SYS_GETSOCKOPT = 118 // { int|sys||getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } - SYS_READV = 120 // { ssize_t|sys||readv(int fd, const struct iovec *iovp, int iovcnt); } - SYS_WRITEV = 121 // { ssize_t|sys||writev(int fd, const struct iovec *iovp, int iovcnt); } - SYS_FCHOWN = 123 // { int|sys||fchown(int fd, uid_t uid, gid_t gid); } - SYS_FCHMOD = 124 // { int|sys||fchmod(int fd, mode_t mode); } - SYS_SETREUID = 126 // { int|sys||setreuid(uid_t ruid, uid_t euid); } - SYS_SETREGID = 127 // { int|sys||setregid(gid_t rgid, gid_t egid); } - SYS_RENAME = 128 // { int|sys||rename(const char *from, const char *to); } - SYS_FLOCK = 131 // { int|sys||flock(int fd, int how); } - SYS_MKFIFO = 132 // { int|sys||mkfifo(const char *path, mode_t mode); } - SYS_SENDTO = 133 // { ssize_t|sys||sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } - SYS_SHUTDOWN = 134 // { int|sys||shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int|sys||socketpair(int domain, int type, int protocol, int *rsv); } - SYS_MKDIR = 136 // { int|sys||mkdir(const char *path, mode_t mode); } - SYS_RMDIR = 137 // { int|sys||rmdir(const char *path); } - SYS_SETSID = 147 // { int|sys||setsid(void); } - SYS_SYSARCH = 165 // { int|sys||sysarch(int op, void *parms); } - SYS_PREAD = 173 // { ssize_t|sys||pread(int fd, void *buf, size_t nbyte, int PAD, off_t offset); } - SYS_PWRITE = 174 // { ssize_t|sys||pwrite(int fd, const void *buf, size_t nbyte, int PAD, off_t offset); } - SYS_NTP_ADJTIME = 176 // { int|sys||ntp_adjtime(struct timex *tp); } - SYS_SETGID = 181 // { int|sys||setgid(gid_t gid); } - SYS_SETEGID = 182 // { int|sys||setegid(gid_t egid); } - SYS_SETEUID = 183 // { int|sys||seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { long|sys||pathconf(const char *path, int name); } - SYS_FPATHCONF = 192 // { long|sys||fpathconf(int fd, int name); } - SYS_GETRLIMIT = 194 // { int|sys||getrlimit(int which, struct rlimit *rlp); } - SYS_SETRLIMIT = 195 // { int|sys||setrlimit(int which, const struct rlimit *rlp); } - SYS_MMAP = 197 // { void *|sys||mmap(void *addr, size_t len, int prot, int flags, int fd, long PAD, off_t pos); } - SYS_LSEEK = 199 // { off_t|sys||lseek(int fd, int PAD, off_t offset, int whence); } - SYS_TRUNCATE = 200 // { int|sys||truncate(const char *path, int PAD, off_t length); } - SYS_FTRUNCATE = 201 // { int|sys||ftruncate(int fd, int PAD, off_t length); } - SYS___SYSCTL = 202 // { int|sys||__sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, const void *new, size_t newlen); } - SYS_MLOCK = 203 // { int|sys||mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int|sys||munlock(const void *addr, size_t len); } - SYS_UNDELETE = 205 // { int|sys||undelete(const char *path); } - SYS_GETPGID = 207 // { pid_t|sys||getpgid(pid_t pid); } - SYS_REBOOT = 208 // { int|sys||reboot(int opt, char *bootstr); } - SYS_POLL = 209 // { int|sys||poll(struct pollfd *fds, u_int nfds, int timeout); } - SYS_SEMGET = 221 // { int|sys||semget(key_t key, int nsems, int semflg); } - SYS_SEMOP = 222 // { int|sys||semop(int semid, struct sembuf *sops, size_t nsops); } - SYS_SEMCONFIG = 223 // { int|sys||semconfig(int flag); } - SYS_MSGGET = 225 // { int|sys||msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int|sys||msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } - SYS_MSGRCV = 227 // { ssize_t|sys||msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } - SYS_SHMAT = 228 // { void *|sys||shmat(int shmid, const void *shmaddr, int shmflg); } - SYS_SHMDT = 230 // { int|sys||shmdt(const void *shmaddr); } - SYS_SHMGET = 231 // { int|sys||shmget(key_t key, size_t size, int shmflg); } - SYS_TIMER_CREATE = 235 // { int|sys||timer_create(clockid_t clock_id, struct sigevent *evp, timer_t *timerid); } - SYS_TIMER_DELETE = 236 // { int|sys||timer_delete(timer_t timerid); } - SYS_TIMER_GETOVERRUN = 239 // { int|sys||timer_getoverrun(timer_t timerid); } - SYS_FDATASYNC = 241 // { int|sys||fdatasync(int fd); } - SYS_MLOCKALL = 242 // { int|sys||mlockall(int flags); } - SYS_MUNLOCKALL = 243 // { int|sys||munlockall(void); } - SYS_SIGQUEUEINFO = 245 // { int|sys||sigqueueinfo(pid_t pid, const siginfo_t *info); } - SYS_MODCTL = 246 // { int|sys||modctl(int cmd, void *arg); } - SYS___POSIX_RENAME = 270 // { int|sys||__posix_rename(const char *from, const char *to); } - SYS_SWAPCTL = 271 // { int|sys||swapctl(int cmd, void *arg, int misc); } - SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } - SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } - SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } - SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } - SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } - SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } - SYS_GETSID = 286 // { pid_t|sys||getsid(pid_t pid); } - SYS___CLONE = 287 // { pid_t|sys||__clone(int flags, void *stack); } - SYS_FKTRACE = 288 // { int|sys||fktrace(int fd, int ops, int facs, pid_t pid); } - SYS_PREADV = 289 // { ssize_t|sys||preadv(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } - SYS_PWRITEV = 290 // { ssize_t|sys||pwritev(int fd, const struct iovec *iovp, int iovcnt, int PAD, off_t offset); } - SYS___GETCWD = 296 // { int|sys||__getcwd(char *bufp, size_t length); } - SYS_FCHROOT = 297 // { int|sys||fchroot(int fd); } - SYS_LCHFLAGS = 304 // { int|sys||lchflags(const char *path, u_long flags); } - SYS_ISSETUGID = 305 // { int|sys||issetugid(void); } - SYS_UTRACE = 306 // { int|sys||utrace(const char *label, void *addr, size_t len); } - SYS_GETCONTEXT = 307 // { int|sys||getcontext(struct __ucontext *ucp); } - SYS_SETCONTEXT = 308 // { int|sys||setcontext(const struct __ucontext *ucp); } - SYS__LWP_CREATE = 309 // { int|sys||_lwp_create(const struct __ucontext *ucp, u_long flags, lwpid_t *new_lwp); } - SYS__LWP_EXIT = 310 // { int|sys||_lwp_exit(void); } - SYS__LWP_SELF = 311 // { lwpid_t|sys||_lwp_self(void); } - SYS__LWP_WAIT = 312 // { int|sys||_lwp_wait(lwpid_t wait_for, lwpid_t *departed); } - SYS__LWP_SUSPEND = 313 // { int|sys||_lwp_suspend(lwpid_t target); } - SYS__LWP_CONTINUE = 314 // { int|sys||_lwp_continue(lwpid_t target); } - SYS__LWP_WAKEUP = 315 // { int|sys||_lwp_wakeup(lwpid_t target); } - SYS__LWP_GETPRIVATE = 316 // { void *|sys||_lwp_getprivate(void); } - SYS__LWP_SETPRIVATE = 317 // { void|sys||_lwp_setprivate(void *ptr); } - SYS__LWP_KILL = 318 // { int|sys||_lwp_kill(lwpid_t target, int signo); } - SYS__LWP_DETACH = 319 // { int|sys||_lwp_detach(lwpid_t target); } - SYS__LWP_UNPARK = 321 // { int|sys||_lwp_unpark(lwpid_t target, const void *hint); } - SYS__LWP_UNPARK_ALL = 322 // { ssize_t|sys||_lwp_unpark_all(const lwpid_t *targets, size_t ntargets, const void *hint); } - SYS__LWP_SETNAME = 323 // { int|sys||_lwp_setname(lwpid_t target, const char *name); } - SYS__LWP_GETNAME = 324 // { int|sys||_lwp_getname(lwpid_t target, char *name, size_t len); } - SYS__LWP_CTL = 325 // { int|sys||_lwp_ctl(int features, struct lwpctl **address); } - SYS___SIGACTION_SIGTRAMP = 340 // { int|sys||__sigaction_sigtramp(int signum, const struct sigaction *nsa, struct sigaction *osa, const void *tramp, int vers); } - SYS_PMC_GET_INFO = 341 // { int|sys||pmc_get_info(int ctr, int op, void *args); } - SYS_PMC_CONTROL = 342 // { int|sys||pmc_control(int ctr, int op, void *args); } - SYS_RASCTL = 343 // { int|sys||rasctl(void *addr, size_t len, int op); } - SYS_KQUEUE = 344 // { int|sys||kqueue(void); } - SYS__SCHED_SETPARAM = 346 // { int|sys||_sched_setparam(pid_t pid, lwpid_t lid, int policy, const struct sched_param *params); } - SYS__SCHED_GETPARAM = 347 // { int|sys||_sched_getparam(pid_t pid, lwpid_t lid, int *policy, struct sched_param *params); } - SYS__SCHED_SETAFFINITY = 348 // { int|sys||_sched_setaffinity(pid_t pid, lwpid_t lid, size_t size, const cpuset_t *cpuset); } - SYS__SCHED_GETAFFINITY = 349 // { int|sys||_sched_getaffinity(pid_t pid, lwpid_t lid, size_t size, cpuset_t *cpuset); } - SYS_SCHED_YIELD = 350 // { int|sys||sched_yield(void); } - SYS_FSYNC_RANGE = 354 // { int|sys||fsync_range(int fd, int flags, off_t start, off_t length); } - SYS_UUIDGEN = 355 // { int|sys||uuidgen(struct uuid *store, int count); } - SYS_GETVFSSTAT = 356 // { int|sys||getvfsstat(struct statvfs *buf, size_t bufsize, int flags); } - SYS_STATVFS1 = 357 // { int|sys||statvfs1(const char *path, struct statvfs *buf, int flags); } - SYS_FSTATVFS1 = 358 // { int|sys||fstatvfs1(int fd, struct statvfs *buf, int flags); } - SYS_EXTATTRCTL = 360 // { int|sys||extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_FILE = 361 // { int|sys||extattr_set_file(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_FILE = 362 // { ssize_t|sys||extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_FILE = 363 // { int|sys||extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_FD = 364 // { int|sys||extattr_set_fd(int fd, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_FD = 365 // { ssize_t|sys||extattr_get_fd(int fd, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_FD = 366 // { int|sys||extattr_delete_fd(int fd, int attrnamespace, const char *attrname); } - SYS_EXTATTR_SET_LINK = 367 // { int|sys||extattr_set_link(const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes); } - SYS_EXTATTR_GET_LINK = 368 // { ssize_t|sys||extattr_get_link(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } - SYS_EXTATTR_DELETE_LINK = 369 // { int|sys||extattr_delete_link(const char *path, int attrnamespace, const char *attrname); } - SYS_EXTATTR_LIST_FD = 370 // { ssize_t|sys||extattr_list_fd(int fd, int attrnamespace, void *data, size_t nbytes); } - SYS_EXTATTR_LIST_FILE = 371 // { ssize_t|sys||extattr_list_file(const char *path, int attrnamespace, void *data, size_t nbytes); } - SYS_EXTATTR_LIST_LINK = 372 // { ssize_t|sys||extattr_list_link(const char *path, int attrnamespace, void *data, size_t nbytes); } - SYS_SETXATTR = 375 // { int|sys||setxattr(const char *path, const char *name, const void *value, size_t size, int flags); } - SYS_LSETXATTR = 376 // { int|sys||lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags); } - SYS_FSETXATTR = 377 // { int|sys||fsetxattr(int fd, const char *name, const void *value, size_t size, int flags); } - SYS_GETXATTR = 378 // { int|sys||getxattr(const char *path, const char *name, void *value, size_t size); } - SYS_LGETXATTR = 379 // { int|sys||lgetxattr(const char *path, const char *name, void *value, size_t size); } - SYS_FGETXATTR = 380 // { int|sys||fgetxattr(int fd, const char *name, void *value, size_t size); } - SYS_LISTXATTR = 381 // { int|sys||listxattr(const char *path, char *list, size_t size); } - SYS_LLISTXATTR = 382 // { int|sys||llistxattr(const char *path, char *list, size_t size); } - SYS_FLISTXATTR = 383 // { int|sys||flistxattr(int fd, char *list, size_t size); } - SYS_REMOVEXATTR = 384 // { int|sys||removexattr(const char *path, const char *name); } - SYS_LREMOVEXATTR = 385 // { int|sys||lremovexattr(const char *path, const char *name); } - SYS_FREMOVEXATTR = 386 // { int|sys||fremovexattr(int fd, const char *name); } - SYS_GETDENTS = 390 // { int|sys|30|getdents(int fd, char *buf, size_t count); } - SYS_SOCKET = 394 // { int|sys|30|socket(int domain, int type, int protocol); } - SYS_GETFH = 395 // { int|sys|30|getfh(const char *fname, void *fhp, size_t *fh_size); } - SYS_MOUNT = 410 // { int|sys|50|mount(const char *type, const char *path, int flags, void *data, size_t data_len); } - SYS_MREMAP = 411 // { void *|sys||mremap(void *old_address, size_t old_size, void *new_address, size_t new_size, int flags); } - SYS_PSET_CREATE = 412 // { int|sys||pset_create(psetid_t *psid); } - SYS_PSET_DESTROY = 413 // { int|sys||pset_destroy(psetid_t psid); } - SYS_PSET_ASSIGN = 414 // { int|sys||pset_assign(psetid_t psid, cpuid_t cpuid, psetid_t *opsid); } - SYS__PSET_BIND = 415 // { int|sys||_pset_bind(idtype_t idtype, id_t first_id, id_t second_id, psetid_t psid, psetid_t *opsid); } - SYS_POSIX_FADVISE = 416 // { int|sys|50|posix_fadvise(int fd, int PAD, off_t offset, off_t len, int advice); } - SYS_SELECT = 417 // { int|sys|50|select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } - SYS_GETTIMEOFDAY = 418 // { int|sys|50|gettimeofday(struct timeval *tp, void *tzp); } - SYS_SETTIMEOFDAY = 419 // { int|sys|50|settimeofday(const struct timeval *tv, const void *tzp); } - SYS_UTIMES = 420 // { int|sys|50|utimes(const char *path, const struct timeval *tptr); } - SYS_ADJTIME = 421 // { int|sys|50|adjtime(const struct timeval *delta, struct timeval *olddelta); } - SYS_FUTIMES = 423 // { int|sys|50|futimes(int fd, const struct timeval *tptr); } - SYS_LUTIMES = 424 // { int|sys|50|lutimes(const char *path, const struct timeval *tptr); } - SYS_SETITIMER = 425 // { int|sys|50|setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } - SYS_GETITIMER = 426 // { int|sys|50|getitimer(int which, struct itimerval *itv); } - SYS_CLOCK_GETTIME = 427 // { int|sys|50|clock_gettime(clockid_t clock_id, struct timespec *tp); } - SYS_CLOCK_SETTIME = 428 // { int|sys|50|clock_settime(clockid_t clock_id, const struct timespec *tp); } - SYS_CLOCK_GETRES = 429 // { int|sys|50|clock_getres(clockid_t clock_id, struct timespec *tp); } - SYS_NANOSLEEP = 430 // { int|sys|50|nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } - SYS___SIGTIMEDWAIT = 431 // { int|sys|50|__sigtimedwait(const sigset_t *set, siginfo_t *info, struct timespec *timeout); } - SYS__LWP_PARK = 434 // { int|sys|50|_lwp_park(const struct timespec *ts, lwpid_t unpark, const void *hint, const void *unparkhint); } - SYS_KEVENT = 435 // { int|sys|50|kevent(int fd, const struct kevent *changelist, size_t nchanges, struct kevent *eventlist, size_t nevents, const struct timespec *timeout); } - SYS_PSELECT = 436 // { int|sys|50|pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } - SYS_POLLTS = 437 // { int|sys|50|pollts(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } - SYS_STAT = 439 // { int|sys|50|stat(const char *path, struct stat *ub); } - SYS_FSTAT = 440 // { int|sys|50|fstat(int fd, struct stat *sb); } - SYS_LSTAT = 441 // { int|sys|50|lstat(const char *path, struct stat *ub); } - SYS___SEMCTL = 442 // { int|sys|50|__semctl(int semid, int semnum, int cmd, ... union __semun *arg); } - SYS_SHMCTL = 443 // { int|sys|50|shmctl(int shmid, int cmd, struct shmid_ds *buf); } - SYS_MSGCTL = 444 // { int|sys|50|msgctl(int msqid, int cmd, struct msqid_ds *buf); } - SYS_GETRUSAGE = 445 // { int|sys|50|getrusage(int who, struct rusage *rusage); } - SYS_TIMER_SETTIME = 446 // { int|sys|50|timer_settime(timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue); } - SYS_TIMER_GETTIME = 447 // { int|sys|50|timer_gettime(timer_t timerid, struct itimerspec *value); } - SYS_NTP_GETTIME = 448 // { int|sys|50|ntp_gettime(struct ntptimeval *ntvp); } - SYS_WAIT4 = 449 // { int|sys|50|wait4(pid_t pid, int *status, int options, struct rusage *rusage); } - SYS_MKNOD = 450 // { int|sys|50|mknod(const char *path, mode_t mode, dev_t dev); } - SYS_FHSTAT = 451 // { int|sys|50|fhstat(const void *fhp, size_t fh_size, struct stat *sb); } - SYS_PIPE2 = 453 // { int|sys||pipe2(int *fildes, int flags); } - SYS_DUP3 = 454 // { int|sys||dup3(int from, int to, int flags); } - SYS_KQUEUE1 = 455 // { int|sys||kqueue1(int flags); } - SYS_PACCEPT = 456 // { int|sys||paccept(int s, struct sockaddr *name, socklen_t *anamelen, const sigset_t *mask, int flags); } - SYS_LINKAT = 457 // { int|sys||linkat(int fd1, const char *name1, int fd2, const char *name2, int flags); } - SYS_RENAMEAT = 458 // { int|sys||renameat(int fromfd, const char *from, int tofd, const char *to); } - SYS_MKFIFOAT = 459 // { int|sys||mkfifoat(int fd, const char *path, mode_t mode); } - SYS_MKNODAT = 460 // { int|sys||mknodat(int fd, const char *path, mode_t mode, uint32_t dev); } - SYS_MKDIRAT = 461 // { int|sys||mkdirat(int fd, const char *path, mode_t mode); } - SYS_FACCESSAT = 462 // { int|sys||faccessat(int fd, const char *path, int amode, int flag); } - SYS_FCHMODAT = 463 // { int|sys||fchmodat(int fd, const char *path, mode_t mode, int flag); } - SYS_FCHOWNAT = 464 // { int|sys||fchownat(int fd, const char *path, uid_t owner, gid_t group, int flag); } - SYS_FEXECVE = 465 // { int|sys||fexecve(int fd, char * const *argp, char * const *envp); } - SYS_FSTATAT = 466 // { int|sys||fstatat(int fd, const char *path, struct stat *buf, int flag); } - SYS_UTIMENSAT = 467 // { int|sys||utimensat(int fd, const char *path, const struct timespec *tptr, int flag); } - SYS_OPENAT = 468 // { int|sys||openat(int fd, const char *path, int oflags, ... mode_t mode); } - SYS_READLINKAT = 469 // { int|sys||readlinkat(int fd, const char *path, char *buf, size_t bufsize); } - SYS_SYMLINKAT = 470 // { int|sys||symlinkat(const char *path1, int fd, const char *path2); } - SYS_UNLINKAT = 471 // { int|sys||unlinkat(int fd, const char *path, int flag); } - SYS_FUTIMENS = 472 // { int|sys||futimens(int fd, const struct timespec *tptr); } - SYS___QUOTACTL = 473 // { int|sys||__quotactl(const char *path, struct quotactl_args *args); } - SYS_POSIX_SPAWN = 474 // { int|sys||posix_spawn(pid_t *pid, const char *path, const struct posix_spawn_file_actions *file_actions, const struct posix_spawnattr *attrp, char *const *argv, char *const *envp); } - SYS_RECVMMSG = 475 // { int|sys||recvmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout); } - SYS_SENDMMSG = 476 // { int|sys||sendmmsg(int s, struct mmsghdr *mmsg, unsigned int vlen, unsigned int flags); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_386.go deleted file mode 100644 index 3e8ce2a1d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_386.go +++ /dev/null @@ -1,207 +0,0 @@ -// mksysnum_openbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build 386,openbsd - -package unix - -const ( - SYS_EXIT = 1 // { void sys_exit(int rval); } - SYS_FORK = 2 // { int sys_fork(void); } - SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ - SYS_OPEN = 5 // { int sys_open(const char *path, \ - SYS_CLOSE = 6 // { int sys_close(int fd); } - SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ - SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } - SYS_UNLINK = 10 // { int sys_unlink(const char *path); } - SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \ - SYS_CHDIR = 12 // { int sys_chdir(const char *path); } - SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } - SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \ - SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } - SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \ - SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break - SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } - SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \ - SYS_GETPID = 20 // { pid_t sys_getpid(void); } - SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \ - SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } - SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t sys_getuid(void); } - SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } - SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \ - SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \ - SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \ - SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \ - SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ - SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ - SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ - SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); } - SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } - SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } - SYS_SYNC = 36 // { void sys_sync(void); } - SYS_KILL = 37 // { int sys_kill(int pid, int signum); } - SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } - SYS_GETPPID = 39 // { pid_t sys_getppid(void); } - SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } - SYS_DUP = 41 // { int sys_dup(int fd); } - SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \ - SYS_GETEGID = 43 // { gid_t sys_getegid(void); } - SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \ - SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ - SYS_GETGID = 47 // { gid_t sys_getgid(void); } - SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } - SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } - SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } - SYS_ACCT = 51 // { int sys_acct(const char *path); } - SYS_SIGPENDING = 52 // { int sys_sigpending(void); } - SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } - SYS_IOCTL = 54 // { int sys_ioctl(int fd, \ - SYS_REBOOT = 55 // { int sys_reboot(int opt); } - SYS_REVOKE = 56 // { int sys_revoke(const char *path); } - SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ - SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \ - SYS_EXECVE = 59 // { int sys_execve(const char *path, \ - SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } - SYS_CHROOT = 61 // { int sys_chroot(const char *path); } - SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \ - SYS_STATFS = 63 // { int sys_statfs(const char *path, \ - SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } - SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \ - SYS_VFORK = 66 // { int sys_vfork(void); } - SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \ - SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \ - SYS_SETITIMER = 69 // { int sys_setitimer(int which, \ - SYS_GETITIMER = 70 // { int sys_getitimer(int which, \ - SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \ - SYS_KEVENT = 72 // { int sys_kevent(int fd, \ - SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \ - SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \ - SYS_UTIMES = 76 // { int sys_utimes(const char *path, \ - SYS_FUTIMES = 77 // { int sys_futimes(int fd, \ - SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ - SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ - SYS_GETPGRP = 81 // { int sys_getpgrp(void); } - SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); } - SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ - SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ - SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ - SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ - SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } - SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ - SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } - SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ - SYS_FSYNC = 95 // { int sys_fsync(int fd); } - SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } - SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } - SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ - SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } - SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } - SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } - SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ - SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } - SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ - SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ - SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } - SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { ssize_t sys_readv(int fd, \ - SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ - SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } - SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } - SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } - SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } - SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } - SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } - SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } - SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \ - SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \ - SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } - SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } - SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ - SYS_SETSID = 147 // { int sys_setsid(void); } - SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ - SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } - SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } - SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } - SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \ - SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \ - SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } - SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } - SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } - SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } - SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } - SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \ - SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \ - SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \ - SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ - SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ - SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } - SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ - SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } - SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } - SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \ - SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } - SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \ - SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \ - SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \ - SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } - SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \ - SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \ - SYS_ISSETUGID = 253 // { int sys_issetugid(void); } - SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } - SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } - SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } - SYS_PIPE = 263 // { int sys_pipe(int *fdp); } - SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } - SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \ - SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \ - SYS_KQUEUE = 269 // { int sys_kqueue(void); } - SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } - SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } - SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \ - SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \ - SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \ - SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \ - SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \ - SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } - SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \ - SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } - SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \ - SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \ - SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \ - SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \ - SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \ - SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } - SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } - SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \ - SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } - SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \ - SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } - SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \ - SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } - SYS_GETRTABLE = 311 // { int sys_getrtable(void); } - SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \ - SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \ - SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \ - SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \ - SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \ - SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \ - SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \ - SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \ - SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \ - SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \ - SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \ - SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \ - SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } - SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go deleted file mode 100644 index bd28146dd..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go +++ /dev/null @@ -1,207 +0,0 @@ -// mksysnum_openbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT - -// +build amd64,openbsd - -package unix - -const ( - SYS_EXIT = 1 // { void sys_exit(int rval); } - SYS_FORK = 2 // { int sys_fork(void); } - SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } - SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ - SYS_OPEN = 5 // { int sys_open(const char *path, \ - SYS_CLOSE = 6 // { int sys_close(int fd); } - SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ - SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } - SYS_UNLINK = 10 // { int sys_unlink(const char *path); } - SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \ - SYS_CHDIR = 12 // { int sys_chdir(const char *path); } - SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } - SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \ - SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } - SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \ - SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break - SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } - SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \ - SYS_GETPID = 20 // { pid_t sys_getpid(void); } - SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \ - SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } - SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } - SYS_GETUID = 24 // { uid_t sys_getuid(void); } - SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } - SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \ - SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \ - SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \ - SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \ - SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ - SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ - SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ - SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); } - SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } - SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } - SYS_SYNC = 36 // { void sys_sync(void); } - SYS_KILL = 37 // { int sys_kill(int pid, int signum); } - SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } - SYS_GETPPID = 39 // { pid_t sys_getppid(void); } - SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } - SYS_DUP = 41 // { int sys_dup(int fd); } - SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \ - SYS_GETEGID = 43 // { gid_t sys_getegid(void); } - SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \ - SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \ - SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ - SYS_GETGID = 47 // { gid_t sys_getgid(void); } - SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } - SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } - SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } - SYS_ACCT = 51 // { int sys_acct(const char *path); } - SYS_SIGPENDING = 52 // { int sys_sigpending(void); } - SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } - SYS_IOCTL = 54 // { int sys_ioctl(int fd, \ - SYS_REBOOT = 55 // { int sys_reboot(int opt); } - SYS_REVOKE = 56 // { int sys_revoke(const char *path); } - SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ - SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \ - SYS_EXECVE = 59 // { int sys_execve(const char *path, \ - SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } - SYS_CHROOT = 61 // { int sys_chroot(const char *path); } - SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \ - SYS_STATFS = 63 // { int sys_statfs(const char *path, \ - SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } - SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \ - SYS_VFORK = 66 // { int sys_vfork(void); } - SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \ - SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \ - SYS_SETITIMER = 69 // { int sys_setitimer(int which, \ - SYS_GETITIMER = 70 // { int sys_getitimer(int which, \ - SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \ - SYS_KEVENT = 72 // { int sys_kevent(int fd, \ - SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } - SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \ - SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \ - SYS_UTIMES = 76 // { int sys_utimes(const char *path, \ - SYS_FUTIMES = 77 // { int sys_futimes(int fd, \ - SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, \ - SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ - SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ - SYS_GETPGRP = 81 // { int sys_getpgrp(void); } - SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); } - SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ - SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ - SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ - SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ - SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ - SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } - SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ - SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } - SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ - SYS_FSYNC = 95 // { int sys_fsync(int fd); } - SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } - SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } - SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ - SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } - SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } - SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } - SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ - SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ - SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } - SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ - SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ - SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } - SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ - SYS_READV = 120 // { ssize_t sys_readv(int fd, \ - SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ - SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } - SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } - SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } - SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } - SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } - SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } - SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } - SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \ - SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } - SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \ - SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } - SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } - SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ - SYS_SETSID = 147 // { int sys_setsid(void); } - SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ - SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } - SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } - SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } - SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \ - SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \ - SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } - SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } - SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } - SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } - SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } - SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } - SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \ - SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \ - SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \ - SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ - SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ - SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } - SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ - SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } - SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } - SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } - SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \ - SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } - SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } - SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \ - SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \ - SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \ - SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } - SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \ - SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \ - SYS_ISSETUGID = 253 // { int sys_issetugid(void); } - SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } - SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } - SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } - SYS_PIPE = 263 // { int sys_pipe(int *fdp); } - SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } - SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \ - SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \ - SYS_KQUEUE = 269 // { int sys_kqueue(void); } - SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } - SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } - SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \ - SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \ - SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \ - SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \ - SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \ - SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } - SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \ - SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } - SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \ - SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \ - SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \ - SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \ - SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \ - SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } - SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } - SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \ - SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } - SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \ - SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } - SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \ - SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } - SYS_GETRTABLE = 311 // { int sys_getrtable(void); } - SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \ - SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \ - SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \ - SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \ - SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \ - SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \ - SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \ - SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \ - SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \ - SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \ - SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \ - SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \ - SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } - SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_solaris_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_solaris_amd64.go deleted file mode 100644 index c70865985..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_solaris_amd64.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,solaris - -package unix - -// TODO(aram): remove these before Go 1.3. -const ( - SYS_EXECVE = 59 - SYS_FCNTL = 62 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_386.go deleted file mode 100644 index 2de1d44e2..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_386.go +++ /dev/null @@ -1,447 +0,0 @@ -// +build 386,darwin -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Timeval32 struct{} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev int32 - Mode uint16 - Nlink uint16 - Ino uint64 - Uid uint32 - Gid uint32 - Rdev int32 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize int32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare [2]int64 -} - -type Statfs_t struct { - Bsize uint32 - Iosize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Owner uint32 - Type uint32 - Flags uint32 - Fssubtype uint32 - Fstypename [16]int8 - Mntonname [1024]int8 - Mntfromname [1024]int8 - Reserved [8]uint32 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Fstore_t struct { - Flags uint32 - Posmode int32 - Offset int64 - Length int64 - Bytesalloc int64 -} - -type Radvisory_t struct { - Offset int64 - Count int32 -} - -type Fbootstraptransfer_t struct { - Offset int64 - Length uint32 - Buffer *byte -} - -type Log2phys_t struct { - Flags uint32 - Contigbytes int64 - Devoffset int64 -} - -type Fsid struct { - Val [2]int32 -} - -type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet4Pktinfo struct { - Ifindex uint32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int32 - Udata *byte -} - -type FdSet struct { - Bits [32]int32 -} - -const ( - SizeofIfMsghdr = 0x70 - SizeofIfData = 0x60 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfmaMsghdr2 = 0x14 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Typelen uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Unused1 uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Recvtiming uint32 - Xmittiming uint32 - Lastchange Timeval - Unused2 uint32 - Hwassist uint32 - Reserved1 uint32 - Reserved2 uint32 -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire int32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Filler [4]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_amd64.go deleted file mode 100644 index 044657878..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_amd64.go +++ /dev/null @@ -1,462 +0,0 @@ -// +build amd64,darwin -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Timeval32 struct { - Sec int32 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev int32 - Mode uint16 - Nlink uint16 - Ino uint64 - Uid uint32 - Gid uint32 - Rdev int32 - Pad_cgo_0 [4]byte - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize int32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare [2]int64 -} - -type Statfs_t struct { - Bsize uint32 - Iosize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Owner uint32 - Type uint32 - Flags uint32 - Fssubtype uint32 - Fstypename [16]int8 - Mntonname [1024]int8 - Mntfromname [1024]int8 - Reserved [8]uint32 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Fstore_t struct { - Flags uint32 - Posmode int32 - Offset int64 - Length int64 - Bytesalloc int64 -} - -type Radvisory_t struct { - Offset int64 - Count int32 - Pad_cgo_0 [4]byte -} - -type Fbootstraptransfer_t struct { - Offset int64 - Length uint64 - Buffer *byte -} - -type Log2phys_t struct { - Flags uint32 - Pad_cgo_0 [8]byte - Pad_cgo_1 [8]byte -} - -type Fsid struct { - Val [2]int32 -} - -type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet4Pktinfo struct { - Ifindex uint32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x30 - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint64 - Filter int16 - Flags uint16 - Fflags uint32 - Data int64 - Udata *byte -} - -type FdSet struct { - Bits [32]int32 -} - -const ( - SizeofIfMsghdr = 0x70 - SizeofIfData = 0x60 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfmaMsghdr2 = 0x14 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Typelen uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Unused1 uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Recvtiming uint32 - Xmittiming uint32 - Lastchange Timeval32 - Unused2 uint32 - Hwassist uint32 - Reserved1 uint32 - Reserved2 uint32 -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire int32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Filler [4]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x10 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval32 - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type Termios struct { - Iflag uint64 - Oflag uint64 - Cflag uint64 - Lflag uint64 - Cc [20]uint8 - Pad_cgo_0 [4]byte - Ispeed uint64 - Ospeed uint64 -} - -const ( - AT_FDCWD = -0x2 - AT_SYMLINK_NOFOLLOW = 0x20 -) diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm.go deleted file mode 100644 index 66df363ce..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm.go +++ /dev/null @@ -1,449 +0,0 @@ -// NOTE: cgo can't generate struct Stat_t and struct Statfs_t yet -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -// +build arm,darwin - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Timeval32 [0]byte - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev int32 - Mode uint16 - Nlink uint16 - Ino uint64 - Uid uint32 - Gid uint32 - Rdev int32 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize int32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare [2]int64 -} - -type Statfs_t struct { - Bsize uint32 - Iosize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Owner uint32 - Type uint32 - Flags uint32 - Fssubtype uint32 - Fstypename [16]int8 - Mntonname [1024]int8 - Mntfromname [1024]int8 - Reserved [8]uint32 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Fstore_t struct { - Flags uint32 - Posmode int32 - Offset int64 - Length int64 - Bytesalloc int64 -} - -type Radvisory_t struct { - Offset int64 - Count int32 -} - -type Fbootstraptransfer_t struct { - Offset int64 - Length uint32 - Buffer *byte -} - -type Log2phys_t struct { - Flags uint32 - Contigbytes int64 - Devoffset int64 -} - -type Fsid struct { - Val [2]int32 -} - -type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet4Pktinfo struct { - Ifindex uint32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int32 - Udata *byte -} - -type FdSet struct { - Bits [32]int32 -} - -const ( - SizeofIfMsghdr = 0x70 - SizeofIfData = 0x60 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfmaMsghdr2 = 0x14 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Typelen uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Unused1 uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Recvtiming uint32 - Xmittiming uint32 - Lastchange Timeval - Unused2 uint32 - Hwassist uint32 - Reserved1 uint32 - Reserved2 uint32 -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire int32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Filler [4]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm64.go deleted file mode 100644 index 85d56eabd..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm64.go +++ /dev/null @@ -1,457 +0,0 @@ -// +build arm64,darwin -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Timeval32 struct { - Sec int32 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev int32 - Mode uint16 - Nlink uint16 - Ino uint64 - Uid uint32 - Gid uint32 - Rdev int32 - Pad_cgo_0 [4]byte - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize int32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare [2]int64 -} - -type Statfs_t struct { - Bsize uint32 - Iosize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Owner uint32 - Type uint32 - Flags uint32 - Fssubtype uint32 - Fstypename [16]int8 - Mntonname [1024]int8 - Mntfromname [1024]int8 - Reserved [8]uint32 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Fstore_t struct { - Flags uint32 - Posmode int32 - Offset int64 - Length int64 - Bytesalloc int64 -} - -type Radvisory_t struct { - Offset int64 - Count int32 - Pad_cgo_0 [4]byte -} - -type Fbootstraptransfer_t struct { - Offset int64 - Length uint64 - Buffer *byte -} - -type Log2phys_t struct { - Flags uint32 - Pad_cgo_0 [8]byte - Pad_cgo_1 [8]byte -} - -type Fsid struct { - Val [2]int32 -} - -type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet4Pktinfo struct { - Ifindex uint32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x30 - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint64 - Filter int16 - Flags uint16 - Fflags uint32 - Data int64 - Udata *byte -} - -type FdSet struct { - Bits [32]int32 -} - -const ( - SizeofIfMsghdr = 0x70 - SizeofIfData = 0x60 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfmaMsghdr2 = 0x14 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Typelen uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Unused1 uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Recvtiming uint32 - Xmittiming uint32 - Lastchange Timeval32 - Unused2 uint32 - Hwassist uint32 - Reserved1 uint32 - Reserved2 uint32 -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire int32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Filler [4]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x10 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval32 - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type Termios struct { - Iflag uint64 - Oflag uint64 - Cflag uint64 - Lflag uint64 - Cc [20]uint8 - Pad_cgo_0 [4]byte - Ispeed uint64 - Ospeed uint64 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_386.go deleted file mode 100644 index b7e7ff088..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_386.go +++ /dev/null @@ -1,437 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_dragonfly.go - -// +build 386,dragonfly - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Ino uint64 - Nlink uint32 - Dev uint32 - Mode uint16 - Padding1 uint16 - Uid uint32 - Gid uint32 - Rdev uint32 - Atim Timespec - Mtim Timespec - Ctim Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare1 int64 - Qspare2 int64 -} - -type Statfs_t struct { - Spare2 int32 - Bsize int32 - Iosize int32 - Blocks int32 - Bfree int32 - Bavail int32 - Files int32 - Ffree int32 - Fsid Fsid - Owner uint32 - Type int32 - Flags int32 - Syncwrites int32 - Asyncwrites int32 - Fstypename [16]int8 - Mntonname [80]int8 - Syncreads int32 - Asyncreads int32 - Spares1 int16 - Mntfromname [80]int8 - Spares2 int16 - Spare [2]int32 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Namlen uint16 - Type uint8 - Unused1 uint8 - Unused2 uint32 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - Rcf uint16 - Route [16]uint16 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x36 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int32 - Udata *byte -} - -type FdSet struct { - Bits [32]uint32 -} - -const ( - SizeofIfMsghdr = 0x68 - SizeofIfData = 0x58 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Pad_cgo_0 [2]byte - Mtu uint32 - Metric uint32 - Link_state uint32 - Baudrate uint64 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Hwassist uint32 - Unused uint32 - Lastchange Timeval -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Pksent uint32 - Expire uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Recvpipe uint32 - Hopcount uint32 - Mssopt uint16 - Pad uint16 - Msl uint32 - Iwmaxsegs uint32 - Iwcapsegs uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go deleted file mode 100644 index 8a6f4e1ce..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go +++ /dev/null @@ -1,443 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_dragonfly.go - -// +build amd64,dragonfly - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Ino uint64 - Nlink uint32 - Dev uint32 - Mode uint16 - Padding1 uint16 - Uid uint32 - Gid uint32 - Rdev uint32 - Atim Timespec - Mtim Timespec - Ctim Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Lspare int32 - Qspare1 int64 - Qspare2 int64 -} - -type Statfs_t struct { - Spare2 int64 - Bsize int64 - Iosize int64 - Blocks int64 - Bfree int64 - Bavail int64 - Files int64 - Ffree int64 - Fsid Fsid - Owner uint32 - Type int32 - Flags int32 - Pad_cgo_0 [4]byte - Syncwrites int64 - Asyncwrites int64 - Fstypename [16]int8 - Mntonname [80]int8 - Syncreads int64 - Asyncreads int64 - Spares1 int16 - Mntfromname [80]int8 - Spares2 int16 - Pad_cgo_1 [4]byte - Spare [2]int64 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Namlen uint16 - Type uint8 - Unused1 uint8 - Unused2 uint32 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 - Rcf uint16 - Route [16]uint16 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x36 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x30 - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint64 - Filter int16 - Flags uint16 - Fflags uint32 - Data int64 - Udata *byte -} - -type FdSet struct { - Bits [16]uint64 -} - -const ( - SizeofIfMsghdr = 0xb0 - SizeofIfData = 0xa0 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x98 - SizeofRtMetrics = 0x70 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Recvquota uint8 - Xmitquota uint8 - Pad_cgo_0 [2]byte - Mtu uint64 - Metric uint64 - Link_state uint64 - Baudrate uint64 - Ipackets uint64 - Ierrors uint64 - Opackets uint64 - Oerrors uint64 - Collisions uint64 - Ibytes uint64 - Obytes uint64 - Imcasts uint64 - Omcasts uint64 - Iqdrops uint64 - Noproto uint64 - Hwassist uint64 - Unused uint64 - Lastchange Timeval -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint64 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint64 - Mtu uint64 - Pksent uint64 - Expire uint64 - Sendpipe uint64 - Ssthresh uint64 - Rtt uint64 - Rttvar uint64 - Recvpipe uint64 - Hopcount uint64 - Mssopt uint16 - Pad uint16 - Pad_cgo_0 [4]byte - Msl uint64 - Iwmaxsegs uint64 - Iwcapsegs uint64 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x10 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x20 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [6]byte -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_386.go deleted file mode 100644 index 8cf30947b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ /dev/null @@ -1,502 +0,0 @@ -// +build 386,freebsd -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Dev uint32 - Ino uint32 - Mode uint16 - Nlink uint16 - Uid uint32 - Gid uint32 - Rdev uint32 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Lspare int32 - Birthtimespec Timespec - Pad_cgo_0 [8]byte -} - -type Statfs_t struct { - Version uint32 - Type uint32 - Flags uint64 - Bsize uint64 - Iosize uint64 - Blocks uint64 - Bfree uint64 - Bavail int64 - Files uint64 - Ffree int64 - Syncwrites uint64 - Asyncwrites uint64 - Syncreads uint64 - Asyncreads uint64 - Spare [10]uint64 - Namemax uint32 - Owner uint32 - Fsid Fsid - Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 - Sysid int32 -} - -type Dirent struct { - Fileno uint32 - Reclen uint16 - Type uint8 - Namlen uint8 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -const ( - FADV_NORMAL = 0x0 - FADV_RANDOM = 0x1 - FADV_SEQUENTIAL = 0x2 - FADV_WILLNEED = 0x3 - FADV_DONTNEED = 0x4 - FADV_NOREUSE = 0x5 -) - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [46]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x36 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int32 - Udata *byte -} - -type FdSet struct { - X__fds_bits [32]uint32 -} - -const ( - sizeofIfMsghdr = 0x64 - SizeofIfMsghdr = 0x60 - sizeofIfData = 0x54 - SizeofIfData = 0x50 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type ifMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data ifData -} - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type ifData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Vhid uint8 - Baudrate_pf uint8 - Datalen uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Hwassist uint64 - Epoch int32 - Lastchange Timeval -} - -type IfData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Spare_char1 uint8 - Spare_char2 uint8 - Datalen uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Hwassist uint32 - Epoch int32 - Lastchange Timeval -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Fmask int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire uint32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Weight uint32 - Filler [3]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfZbuf = 0xc - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 - SizeofBpfZbufHeader = 0x20 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfZbuf struct { - Bufa *byte - Bufb *byte - Buflen uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type BpfZbufHeader struct { - Kernel_gen uint32 - Kernel_len uint32 - User_gen uint32 - X_bzh_pad [5]uint32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_arm.go deleted file mode 100644 index 5472b5428..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_arm.go +++ /dev/null @@ -1,497 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -fsigned-char types_freebsd.go - -// +build arm,freebsd - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int32 - Pad_cgo_0 [4]byte -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Dev uint32 - Ino uint32 - Mode uint16 - Nlink uint16 - Uid uint32 - Gid uint32 - Rdev uint32 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Lspare int32 - Birthtimespec Timespec -} - -type Statfs_t struct { - Version uint32 - Type uint32 - Flags uint64 - Bsize uint64 - Iosize uint64 - Blocks uint64 - Bfree uint64 - Bavail int64 - Files uint64 - Ffree int64 - Syncwrites uint64 - Asyncwrites uint64 - Syncreads uint64 - Asyncreads uint64 - Spare [10]uint64 - Namemax uint32 - Owner uint32 - Fsid Fsid - Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 - Sysid int32 - Pad_cgo_0 [4]byte -} - -type Dirent struct { - Fileno uint32 - Reclen uint16 - Type uint8 - Namlen uint8 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [46]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x36 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int32 - Udata *byte -} - -type FdSet struct { - X__fds_bits [32]uint32 -} - -const ( - sizeofIfMsghdr = 0x70 - SizeofIfMsghdr = 0x70 - sizeofIfData = 0x60 - SizeofIfData = 0x60 - SizeofIfaMsghdr = 0x14 - SizeofIfmaMsghdr = 0x10 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x5c - SizeofRtMetrics = 0x38 -) - -type ifMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data ifData -} - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type ifData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Vhid uint8 - Baudrate_pf uint8 - Datalen uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Hwassist uint64 - Epoch int64 - Lastchange Timeval -} - -type IfData struct { - Type uint8 - Physical uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Spare_char1 uint8 - Spare_char2 uint8 - Datalen uint8 - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Hwassist uint32 - Pad_cgo_0 [4]byte - Epoch int64 - Lastchange Timeval -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Fmask int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire uint32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 - Weight uint32 - Filler [3]uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfZbuf = 0xc - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x20 - SizeofBpfZbufHeader = 0x20 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfZbuf struct { - Bufa *byte - Bufb *byte - Buflen uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [6]byte -} - -type BpfZbufHeader struct { - Kernel_gen uint32 - Kernel_len uint32 - User_gen uint32 - X_bzh_pad [5]uint32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_386.go deleted file mode 100644 index cf5db0e1b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_386.go +++ /dev/null @@ -1,590 +0,0 @@ -// +build 386,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Timex struct { - Modes uint32 - Offset int32 - Freq int32 - Maxerror int32 - Esterror int32 - Status int32 - Constant int32 - Precision int32 - Tolerance int32 - Time Timeval - Tick int32 - Ppsfreq int32 - Jitter int32 - Shift int32 - Stabil int32 - Jitcnt int32 - Calcnt int32 - Errcnt int32 - Stbcnt int32 - Tai int32 - Pad_cgo_0 [44]byte -} - -type Time_t int32 - -type Tms struct { - Utime int32 - Stime int32 - Cutime int32 - Cstime int32 -} - -type Utimbuf struct { - Actime int32 - Modtime int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - X__pad1 uint16 - Pad_cgo_0 [2]byte - X__st_ino uint32 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - X__pad2 uint16 - Pad_cgo_1 [2]byte - Size int64 - Blksize int32 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Ino uint64 -} - -type Statfs_t struct { - Type int32 - Bsize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int32 - Frsize int32 - Flags int32 - Spare [4]int32 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [1]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Start int64 - Len int64 - Pid int32 -} - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x1d - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x8 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]int8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - Ebx int32 - Ecx int32 - Edx int32 - Esi int32 - Edi int32 - Ebp int32 - Eax int32 - Xds int32 - Xes int32 - Xfs int32 - Xgs int32 - Orig_eax int32 - Eip int32 - Xcs int32 - Eflags int32 - Esp int32 - Xss int32 -} - -type FdSet struct { - Bits [32]int32 -} - -type Sysinfo_t struct { - Uptime int32 - Loads [3]uint32 - Totalram uint32 - Freeram uint32 - Sharedram uint32 - Bufferram uint32 - Totalswap uint32 - Freeswap uint32 - Procs uint16 - Pad uint16 - Totalhigh uint32 - Freehigh uint32 - Unit uint32 - X_f [8]int8 -} - -type Utsname struct { - Sysname [65]int8 - Nodename [65]int8 - Release [65]int8 - Version [65]int8 - Machine [65]int8 - Domainname [65]int8 -} - -type Ustat_t struct { - Tfree int32 - Tinode uint32 - Fname [6]int8 - Fpack [6]int8 -} - -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_SYMLINK_NOFOLLOW = 0x100 - AT_REMOVEDIR = 0x200 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Line uint8 - Cc [19]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_amd64.go deleted file mode 100644 index ac27784ab..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ /dev/null @@ -1,608 +0,0 @@ -// +build amd64,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Timex struct { - Modes uint32 - Pad_cgo_0 [4]byte - Offset int64 - Freq int64 - Maxerror int64 - Esterror int64 - Status int32 - Pad_cgo_1 [4]byte - Constant int64 - Precision int64 - Tolerance int64 - Time Timeval - Tick int64 - Ppsfreq int64 - Jitter int64 - Shift int32 - Pad_cgo_2 [4]byte - Stabil int64 - Jitcnt int64 - Calcnt int64 - Errcnt int64 - Stbcnt int64 - Tai int32 - Pad_cgo_3 [44]byte -} - -type Time_t int64 - -type Tms struct { - Utime int64 - Stime int64 - Cutime int64 - Cstime int64 -} - -type Utimbuf struct { - Actime int64 - Modtime int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Ino uint64 - Nlink uint64 - Mode uint32 - Uid uint32 - Gid uint32 - X__pad0 int32 - Rdev uint64 - Size int64 - Blksize int64 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - X__unused [3]int64 -} - -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte -} - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type Cmsghdr struct { - Len uint64 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x38 - SizeofCmsghdr = 0x10 - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x1d - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x10 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]int8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - R15 uint64 - R14 uint64 - R13 uint64 - R12 uint64 - Rbp uint64 - Rbx uint64 - R11 uint64 - R10 uint64 - R9 uint64 - R8 uint64 - Rax uint64 - Rcx uint64 - Rdx uint64 - Rsi uint64 - Rdi uint64 - Orig_rax uint64 - Rip uint64 - Cs uint64 - Eflags uint64 - Rsp uint64 - Ss uint64 - Fs_base uint64 - Gs_base uint64 - Ds uint64 - Es uint64 - Fs uint64 - Gs uint64 -} - -type FdSet struct { - Bits [16]int64 -} - -type Sysinfo_t struct { - Uptime int64 - Loads [3]uint64 - Totalram uint64 - Freeram uint64 - Sharedram uint64 - Bufferram uint64 - Totalswap uint64 - Freeswap uint64 - Procs uint16 - Pad uint16 - Pad_cgo_0 [4]byte - Totalhigh uint64 - Freehigh uint64 - Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte -} - -type Utsname struct { - Sysname [65]int8 - Nodename [65]int8 - Release [65]int8 - Version [65]int8 - Machine [65]int8 - Domainname [65]int8 -} - -type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte -} - -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_SYMLINK_NOFOLLOW = 0x100 - AT_REMOVEDIR = 0x200 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Line uint8 - Cc [19]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm.go deleted file mode 100644 index b318bb851..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm.go +++ /dev/null @@ -1,579 +0,0 @@ -// +build arm,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Timex struct { - Modes uint32 - Offset int32 - Freq int32 - Maxerror int32 - Esterror int32 - Status int32 - Constant int32 - Precision int32 - Tolerance int32 - Time Timeval - Tick int32 - Ppsfreq int32 - Jitter int32 - Shift int32 - Stabil int32 - Jitcnt int32 - Calcnt int32 - Errcnt int32 - Stbcnt int32 - Tai int32 - Pad_cgo_0 [44]byte -} - -type Time_t int32 - -type Tms struct { - Utime int32 - Stime int32 - Cutime int32 - Cstime int32 -} - -type Utimbuf struct { - Actime int32 - Modtime int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - X__pad1 uint16 - Pad_cgo_0 [2]byte - X__st_ino uint32 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - X__pad2 uint16 - Pad_cgo_1 [6]byte - Size int64 - Blksize int32 - Pad_cgo_2 [4]byte - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Ino uint64 -} - -type Statfs_t struct { - Type int32 - Bsize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int32 - Frsize int32 - Flags int32 - Spare [4]int32 - Pad_cgo_0 [4]byte -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte -} - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]uint8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]uint8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x1d - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x8 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]uint8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - Uregs [18]uint32 -} - -type FdSet struct { - Bits [32]int32 -} - -type Sysinfo_t struct { - Uptime int32 - Loads [3]uint32 - Totalram uint32 - Freeram uint32 - Sharedram uint32 - Bufferram uint32 - Totalswap uint32 - Freeswap uint32 - Procs uint16 - Pad uint16 - Totalhigh uint32 - Freehigh uint32 - Unit uint32 - X_f [8]uint8 -} - -type Utsname struct { - Sysname [65]uint8 - Nodename [65]uint8 - Release [65]uint8 - Version [65]uint8 - Machine [65]uint8 - Domainname [65]uint8 -} - -type Ustat_t struct { - Tfree int32 - Tinode uint32 - Fname [6]uint8 - Fpack [6]uint8 -} - -type EpollEvent struct { - Events uint32 - PadFd int32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_SYMLINK_NOFOLLOW = 0x100 - AT_REMOVEDIR = 0x200 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Line uint8 - Cc [19]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm64.go deleted file mode 100644 index a159aadab..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ /dev/null @@ -1,595 +0,0 @@ -// +build arm64,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs -- -fsigned-char types_linux.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Timex struct { - Modes uint32 - Pad_cgo_0 [4]byte - Offset int64 - Freq int64 - Maxerror int64 - Esterror int64 - Status int32 - Pad_cgo_1 [4]byte - Constant int64 - Precision int64 - Tolerance int64 - Time Timeval - Tick int64 - Ppsfreq int64 - Jitter int64 - Shift int32 - Pad_cgo_2 [4]byte - Stabil int64 - Jitcnt int64 - Calcnt int64 - Errcnt int64 - Stbcnt int64 - Tai int32 - Pad_cgo_3 [44]byte -} - -type Time_t int64 - -type Tms struct { - Utime int64 - Stime int64 - Cutime int64 - Cstime int64 -} - -type Utimbuf struct { - Actime int64 - Modtime int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Ino uint64 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - X__pad1 uint64 - Size int64 - Blksize int32 - X__pad2 int32 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - X__glibc_reserved [2]int32 -} - -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte -} - -const ( - FADV_NORMAL = 0x0 - FADV_RANDOM = 0x1 - FADV_SEQUENTIAL = 0x2 - FADV_WILLNEED = 0x3 - FADV_DONTNEED = 0x4 - FADV_NOREUSE = 0x5 -) - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type Cmsghdr struct { - Len uint64 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x38 - SizeofCmsghdr = 0x10 - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x22 - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x10 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]int8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - Regs [31]uint64 - Sp uint64 - Pc uint64 - Pstate uint64 -} - -type FdSet struct { - Bits [16]int64 -} - -type Sysinfo_t struct { - Uptime int64 - Loads [3]uint64 - Totalram uint64 - Freeram uint64 - Sharedram uint64 - Bufferram uint64 - Totalswap uint64 - Freeswap uint64 - Procs uint16 - Pad uint16 - Pad_cgo_0 [4]byte - Totalhigh uint64 - Freehigh uint64 - Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte -} - -type Utsname struct { - Sysname [65]int8 - Nodename [65]int8 - Release [65]int8 - Version [65]int8 - Machine [65]int8 - Domainname [65]int8 -} - -type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte -} - -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 - AT_SYMLINK_NOFOLLOW = 0x100 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Line uint8 - Cc [19]uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64.go deleted file mode 100644 index b14cbfef0..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ /dev/null @@ -1,605 +0,0 @@ -// +build ppc64,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Timex struct { - Modes uint32 - Pad_cgo_0 [4]byte - Offset int64 - Freq int64 - Maxerror int64 - Esterror int64 - Status int32 - Pad_cgo_1 [4]byte - Constant int64 - Precision int64 - Tolerance int64 - Time Timeval - Tick int64 - Ppsfreq int64 - Jitter int64 - Shift int32 - Pad_cgo_2 [4]byte - Stabil int64 - Jitcnt int64 - Calcnt int64 - Errcnt int64 - Stbcnt int64 - Tai int32 - Pad_cgo_3 [44]byte -} - -type Time_t int64 - -type Tms struct { - Utime int64 - Stime int64 - Cutime int64 - Cstime int64 -} - -type Utimbuf struct { - Actime int64 - Modtime int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Ino uint64 - Nlink uint64 - Mode uint32 - Uid uint32 - Gid uint32 - X__pad2 int32 - Rdev uint64 - Size int64 - Blksize int64 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - X__glibc_reserved4 uint64 - X__glibc_reserved5 uint64 - X__glibc_reserved6 uint64 -} - -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte -} - -const ( - FADV_NORMAL = 0x0 - FADV_RANDOM = 0x1 - FADV_SEQUENTIAL = 0x2 - FADV_WILLNEED = 0x3 - FADV_DONTNEED = 0x4 - FADV_NOREUSE = 0x5 -) - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]uint8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]uint8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type Cmsghdr struct { - Len uint64 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x38 - SizeofCmsghdr = 0x10 - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x23 - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x10 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]uint8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - Gpr [32]uint64 - Nip uint64 - Msr uint64 - Orig_gpr3 uint64 - Ctr uint64 - Link uint64 - Xer uint64 - Ccr uint64 - Softe uint64 - Trap uint64 - Dar uint64 - Dsisr uint64 - Result uint64 -} - -type FdSet struct { - Bits [16]int64 -} - -type Sysinfo_t struct { - Uptime int64 - Loads [3]uint64 - Totalram uint64 - Freeram uint64 - Sharedram uint64 - Bufferram uint64 - Totalswap uint64 - Freeswap uint64 - Procs uint16 - Pad uint16 - Pad_cgo_0 [4]byte - Totalhigh uint64 - Freehigh uint64 - Unit uint32 - X_f [0]uint8 - Pad_cgo_1 [4]byte -} - -type Utsname struct { - Sysname [65]uint8 - Nodename [65]uint8 - Release [65]uint8 - Version [65]uint8 - Machine [65]uint8 - Domainname [65]uint8 -} - -type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]uint8 - Fpack [6]uint8 - Pad_cgo_1 [4]byte -} - -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 - AT_SYMLINK_NOFOLLOW = 0x100 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [19]uint8 - Line uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64le.go deleted file mode 100644 index 22c96a2f0..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ /dev/null @@ -1,605 +0,0 @@ -// +build ppc64le,linux -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_linux.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - PathMax = 0x1000 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Timex struct { - Modes uint32 - Pad_cgo_0 [4]byte - Offset int64 - Freq int64 - Maxerror int64 - Esterror int64 - Status int32 - Pad_cgo_1 [4]byte - Constant int64 - Precision int64 - Tolerance int64 - Time Timeval - Tick int64 - Ppsfreq int64 - Jitter int64 - Shift int32 - Pad_cgo_2 [4]byte - Stabil int64 - Jitcnt int64 - Calcnt int64 - Errcnt int64 - Stbcnt int64 - Tai int32 - Pad_cgo_3 [44]byte -} - -type Time_t int64 - -type Tms struct { - Utime int64 - Stime int64 - Cutime int64 - Cstime int64 -} - -type Utimbuf struct { - Actime int64 - Modtime int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Ino uint64 - Nlink uint64 - Mode uint32 - Uid uint32 - Gid uint32 - X__pad2 int32 - Rdev uint64 - Size int64 - Blksize int64 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - X__glibc_reserved4 uint64 - X__glibc_reserved5 uint64 - X__glibc_reserved6 uint64 -} - -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte -} - -type Fsid struct { - X__val [2]int32 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte -} - -const ( - FADV_NORMAL = 0x0 - FADV_RANDOM = 0x1 - FADV_SEQUENTIAL = 0x2 - FADV_WILLNEED = 0x3 - FADV_DONTNEED = 0x4 - FADV_NOREUSE = 0x5 -) - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrLinklayer struct { - Family uint16 - Protocol uint16 - Ifindex int32 - Hatype uint16 - Pkttype uint8 - Halen uint8 - Addr [8]uint8 -} - -type RawSockaddrNetlink struct { - Family uint16 - Pad uint16 - Pid uint32 - Groups uint32 -} - -type RawSockaddr struct { - Family uint16 - Data [14]uint8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [96]uint8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPMreqn struct { - Multiaddr [4]byte /* in_addr */ - Address [4]byte /* in_addr */ - Ifindex int32 -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type Cmsghdr struct { - Len uint64 - Level int32 - Type int32 - X__cmsg_data [0]uint8 -} - -type Inet4Pktinfo struct { - Ifindex int32 - Spec_dst [4]byte /* in_addr */ - Addr [4]byte /* in_addr */ -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Data [8]uint32 -} - -type Ucred struct { - Pid int32 - Uid uint32 - Gid uint32 -} - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Pad_cgo_0 [2]byte - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x70 - SizeofSockaddrUnix = 0x6e - SizeofSockaddrLinklayer = 0x14 - SizeofSockaddrNetlink = 0xc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPMreqn = 0xc - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x38 - SizeofCmsghdr = 0x10 - SizeofInet4Pktinfo = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 - SizeofUcred = 0xc - SizeofTCPInfo = 0x68 -) - -const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x22 - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 -) - -type NlMsghdr struct { - Len uint32 - Type uint16 - Flags uint16 - Seq uint32 - Pid uint32 -} - -type NlMsgerr struct { - Error int32 - Msg NlMsghdr -} - -type RtGenmsg struct { - Family uint8 -} - -type NlAttr struct { - Len uint16 - Type uint16 -} - -type RtAttr struct { - Len uint16 - Type uint16 -} - -type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 -} - -type IfAddrmsg struct { - Family uint8 - Prefixlen uint8 - Flags uint8 - Scope uint8 - Index uint32 -} - -type RtMsg struct { - Family uint8 - Dst_len uint8 - Src_len uint8 - Tos uint8 - Table uint8 - Protocol uint8 - Scope uint8 - Type uint8 - Flags uint32 -} - -type RtNexthop struct { - Len uint16 - Flags uint8 - Hops uint8 - Ifindex int32 -} - -const ( - SizeofSockFilter = 0x8 - SizeofSockFprog = 0x10 -) - -type SockFilter struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter -} - -type InotifyEvent struct { - Wd int32 - Mask uint32 - Cookie uint32 - Len uint32 - Name [0]uint8 -} - -const SizeofInotifyEvent = 0x10 - -type PtraceRegs struct { - Gpr [32]uint64 - Nip uint64 - Msr uint64 - Orig_gpr3 uint64 - Ctr uint64 - Link uint64 - Xer uint64 - Ccr uint64 - Softe uint64 - Trap uint64 - Dar uint64 - Dsisr uint64 - Result uint64 -} - -type FdSet struct { - Bits [16]int64 -} - -type Sysinfo_t struct { - Uptime int64 - Loads [3]uint64 - Totalram uint64 - Freeram uint64 - Sharedram uint64 - Bufferram uint64 - Totalswap uint64 - Freeswap uint64 - Procs uint16 - Pad uint16 - Pad_cgo_0 [4]byte - Totalhigh uint64 - Freehigh uint64 - Unit uint32 - X_f [0]uint8 - Pad_cgo_1 [4]byte -} - -type Utsname struct { - Sysname [65]uint8 - Nodename [65]uint8 - Release [65]uint8 - Version [65]uint8 - Machine [65]uint8 - Domainname [65]uint8 -} - -type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]uint8 - Fpack [6]uint8 - Pad_cgo_1 [4]byte -} - -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 - AT_SYMLINK_NOFOLLOW = 0x100 -) - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [19]uint8 - Line uint8 - Ispeed uint32 - Ospeed uint32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_386.go deleted file mode 100644 index caf755fb8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_386.go +++ /dev/null @@ -1,396 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_netbsd.go - -// +build 386,netbsd - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int32 -} - -type Timeval struct { - Sec int64 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Mode uint32 - Ino uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Spare [2]uint32 -} - -type Statfs_t [0]byte - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [512]int8 - Pad_cgo_0 [3]byte -} - -type Fsid struct { - X__fsid_val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter uint32 - Flags uint32 - Fflags uint32 - Data int64 - Udata int32 -} - -type FdSet struct { - Bits [8]uint32 -} - -const ( - SizeofIfMsghdr = 0x98 - SizeofIfData = 0x84 - SizeofIfaMsghdr = 0x18 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x78 - SizeofRtMetrics = 0x50 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData - Pad_cgo_1 [4]byte -} - -type IfData struct { - Type uint8 - Addrlen uint8 - Hdrlen uint8 - Pad_cgo_0 [1]byte - Link_state int32 - Mtu uint64 - Metric uint64 - Baudrate uint64 - Ipackets uint64 - Ierrors uint64 - Opackets uint64 - Oerrors uint64 - Collisions uint64 - Ibytes uint64 - Obytes uint64 - Imcasts uint64 - Omcasts uint64 - Iqdrops uint64 - Noproto uint64 - Lastchange Timespec -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Metric int32 - Index uint16 - Pad_cgo_0 [6]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits int32 - Pad_cgo_1 [4]byte - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint64 - Mtu uint64 - Hopcount uint64 - Recvpipe uint64 - Sendpipe uint64 - Ssthresh uint64 - Rtt uint64 - Rttvar uint64 - Expire int64 - Pksent int64 -} - -type Mclpool [0]byte - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x80 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint64 - Drop uint64 - Capt uint64 - Padding [13]uint64 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type BpfTimeval struct { - Sec int32 - Usec int32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed int32 - Ospeed int32 -} - -type Sysctlnode struct { - Flags uint32 - Num int32 - Name [32]int8 - Ver uint32 - X__rsvd uint32 - Un [16]byte - X_sysctl_size [8]byte - X_sysctl_func [8]byte - X_sysctl_parent [8]byte - X_sysctl_desc [8]byte -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_arm.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_arm.go deleted file mode 100644 index c0758f9d3..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_arm.go +++ /dev/null @@ -1,401 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_netbsd.go - -// +build arm,netbsd - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int32 - Pad_cgo_0 [4]byte -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -type Stat_t struct { - Dev uint64 - Mode uint32 - Pad_cgo_0 [4]byte - Ino uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Pad_cgo_1 [4]byte - Rdev uint64 - Atimespec Timespec - Mtimespec Timespec - Ctimespec Timespec - Birthtimespec Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Spare [2]uint32 - Pad_cgo_2 [4]byte -} - -type Statfs_t [0]byte - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [512]int8 - Pad_cgo_0 [3]byte -} - -type Fsid struct { - X__fsid_val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [12]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x14 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter uint32 - Flags uint32 - Fflags uint32 - Data int64 - Udata int32 - Pad_cgo_0 [4]byte -} - -type FdSet struct { - Bits [8]uint32 -} - -const ( - SizeofIfMsghdr = 0x98 - SizeofIfData = 0x88 - SizeofIfaMsghdr = 0x18 - SizeofIfAnnounceMsghdr = 0x18 - SizeofRtMsghdr = 0x78 - SizeofRtMetrics = 0x50 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Addrlen uint8 - Hdrlen uint8 - Pad_cgo_0 [1]byte - Link_state int32 - Mtu uint64 - Metric uint64 - Baudrate uint64 - Ipackets uint64 - Ierrors uint64 - Opackets uint64 - Oerrors uint64 - Collisions uint64 - Ibytes uint64 - Obytes uint64 - Imcasts uint64 - Omcasts uint64 - Iqdrops uint64 - Noproto uint64 - Lastchange Timespec -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Metric int32 - Index uint16 - Pad_cgo_0 [6]byte -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Name [16]int8 - What uint16 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits int32 - Pad_cgo_1 [4]byte - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint64 - Mtu uint64 - Hopcount uint64 - Recvpipe uint64 - Sendpipe uint64 - Ssthresh uint64 - Rtt uint64 - Rttvar uint64 - Expire int64 - Pksent int64 -} - -type Mclpool [0]byte - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x80 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint64 - Drop uint64 - Capt uint64 - Padding [13]uint64 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type BpfTimeval struct { - Sec int32 - Usec int32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed int32 - Ospeed int32 -} - -type Sysctlnode struct { - Flags uint32 - Num int32 - Name [32]int8 - Ver uint32 - X__rsvd uint32 - Un [16]byte - X_sysctl_size [8]byte - X_sysctl_func [8]byte - X_sysctl_parent [8]byte - X_sysctl_desc [8]byte -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_386.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_386.go deleted file mode 100644 index 860a46979..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_386.go +++ /dev/null @@ -1,441 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_openbsd.go - -// +build 386,openbsd - -package unix - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int32 -} - -type Timeval struct { - Sec int64 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Mode uint32 - Dev int32 - Ino uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev int32 - Atim Timespec - Mtim Timespec - Ctim Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - X__st_birthtim Timespec -} - -type Statfs_t struct { - F_flags uint32 - F_bsize uint32 - F_iosize uint32 - F_blocks uint64 - F_bfree uint64 - F_bavail int64 - F_files uint64 - F_ffree uint64 - F_favail int64 - F_syncwrites uint64 - F_syncreads uint64 - F_asyncwrites uint64 - F_asyncreads uint64 - F_fsid Fsid - F_namemax uint32 - F_owner uint32 - F_ctime uint64 - F_fstypename [16]int8 - F_mntonname [90]int8 - F_mntfromname [90]int8 - F_mntfromspec [90]int8 - Pad_cgo_0 [2]byte - Mount_info [160]byte -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Off int64 - Reclen uint16 - Type uint8 - Namlen uint8 - X__d_padding [4]uint8 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [24]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint32 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Iov *Iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x20 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x1c - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint32 - Filter int16 - Flags uint16 - Fflags uint32 - Data int64 - Udata *byte -} - -type FdSet struct { - Bits [32]uint32 -} - -const ( - SizeofIfMsghdr = 0xec - SizeofIfData = 0xd4 - SizeofIfaMsghdr = 0x18 - SizeofIfAnnounceMsghdr = 0x1a - SizeofRtMsghdr = 0x60 - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Pad1 uint8 - Pad2 uint8 - Addrs int32 - Flags int32 - Xflags int32 - Data IfData -} - -type IfData struct { - Type uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Mtu uint32 - Metric uint32 - Pad uint32 - Baudrate uint64 - Ipackets uint64 - Ierrors uint64 - Opackets uint64 - Oerrors uint64 - Collisions uint64 - Ibytes uint64 - Obytes uint64 - Imcasts uint64 - Omcasts uint64 - Iqdrops uint64 - Noproto uint64 - Capabilities uint32 - Lastchange Timeval - Mclpool [7]Mclpool -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Pad1 uint8 - Pad2 uint8 - Addrs int32 - Flags int32 - Metric int32 -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - What uint16 - Name [16]int8 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Priority uint8 - Mpls uint8 - Addrs int32 - Flags int32 - Fmask int32 - Pid int32 - Seq int32 - Errno int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Pksent uint64 - Expire int64 - Locks uint32 - Mtu uint32 - Refcnt uint32 - Hopcount uint32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pad uint32 -} - -type Mclpool struct { - Grown int32 - Alive uint16 - Hwm uint16 - Cwm uint16 - Lwm uint16 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x8 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type BpfTimeval struct { - Sec uint32 - Usec uint32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed int32 - Ospeed int32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_amd64.go deleted file mode 100644 index 23c52727f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_amd64.go +++ /dev/null @@ -1,448 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_openbsd.go - -// +build amd64,openbsd - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Mode uint32 - Dev int32 - Ino uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev int32 - Atim Timespec - Mtim Timespec - Ctim Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Pad_cgo_0 [4]byte - X__st_birthtim Timespec -} - -type Statfs_t struct { - F_flags uint32 - F_bsize uint32 - F_iosize uint32 - Pad_cgo_0 [4]byte - F_blocks uint64 - F_bfree uint64 - F_bavail int64 - F_files uint64 - F_ffree uint64 - F_favail int64 - F_syncwrites uint64 - F_syncreads uint64 - F_asyncwrites uint64 - F_asyncreads uint64 - F_fsid Fsid - F_namemax uint32 - F_owner uint32 - F_ctime uint64 - F_fstypename [16]int8 - F_mntonname [90]int8 - F_mntfromname [90]int8 - F_mntfromspec [90]int8 - Pad_cgo_1 [2]byte - Mount_info [160]byte -} - -type Flock_t struct { - Start int64 - Len int64 - Pid int32 - Type int16 - Whence int16 -} - -type Dirent struct { - Fileno uint64 - Off int64 - Reclen uint16 - Type uint8 - Namlen uint8 - X__d_padding [4]uint8 - Name [256]int8 -} - -type Fsid struct { - Val [2]int32 -} - -type RawSockaddrInet4 struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -type RawSockaddrUnix struct { - Len uint8 - Family uint8 - Path [104]int8 -} - -type RawSockaddrDatalink struct { - Len uint8 - Family uint8 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [24]int8 -} - -type RawSockaddr struct { - Len uint8 - Family uint8 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [92]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *byte - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen uint32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - Filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x1c - SizeofSockaddrAny = 0x6c - SizeofSockaddrUnix = 0x6a - SizeofSockaddrDatalink = 0x20 - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x30 - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x20 - SizeofICMPv6Filter = 0x20 -) - -const ( - PTRACE_TRACEME = 0x0 - PTRACE_CONT = 0x7 - PTRACE_KILL = 0x8 -) - -type Kevent_t struct { - Ident uint64 - Filter int16 - Flags uint16 - Fflags uint32 - Data int64 - Udata *byte -} - -type FdSet struct { - Bits [32]uint32 -} - -const ( - SizeofIfMsghdr = 0xf8 - SizeofIfData = 0xe0 - SizeofIfaMsghdr = 0x18 - SizeofIfAnnounceMsghdr = 0x1a - SizeofRtMsghdr = 0x60 - SizeofRtMetrics = 0x38 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Pad1 uint8 - Pad2 uint8 - Addrs int32 - Flags int32 - Xflags int32 - Data IfData -} - -type IfData struct { - Type uint8 - Addrlen uint8 - Hdrlen uint8 - Link_state uint8 - Mtu uint32 - Metric uint32 - Pad uint32 - Baudrate uint64 - Ipackets uint64 - Ierrors uint64 - Opackets uint64 - Oerrors uint64 - Collisions uint64 - Ibytes uint64 - Obytes uint64 - Imcasts uint64 - Omcasts uint64 - Iqdrops uint64 - Noproto uint64 - Capabilities uint32 - Pad_cgo_0 [4]byte - Lastchange Timeval - Mclpool [7]Mclpool - Pad_cgo_1 [4]byte -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Pad1 uint8 - Pad2 uint8 - Addrs int32 - Flags int32 - Metric int32 -} - -type IfAnnounceMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - What uint16 - Name [16]int8 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Hdrlen uint16 - Index uint16 - Tableid uint16 - Priority uint8 - Mpls uint8 - Addrs int32 - Flags int32 - Fmask int32 - Pid int32 - Seq int32 - Errno int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Pksent uint64 - Expire int64 - Locks uint32 - Mtu uint32 - Refcnt uint32 - Hopcount uint32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pad uint32 -} - -type Mclpool struct { - Grown int32 - Alive uint16 - Hwm uint16 - Cwm uint16 - Lwm uint16 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x8 - SizeofBpfProgram = 0x10 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint32 - Drop uint32 -} - -type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -type BpfTimeval struct { - Sec uint32 - Usec uint32 -} - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]uint8 - Ispeed int32 - Ospeed int32 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_solaris_amd64.go b/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_solaris_amd64.go deleted file mode 100644 index b3b928a51..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_solaris_amd64.go +++ /dev/null @@ -1,422 +0,0 @@ -// +build amd64,solaris -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_solaris.go - -package unix - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 - PathMax = 0x400 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Timeval32 struct { - Sec int32 - Usec int32 -} - -type Tms struct { - Utime int64 - Stime int64 - Cutime int64 - Cstime int64 -} - -type Utimbuf struct { - Actime int64 - Modtime int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type _Gid_t uint32 - -const ( - S_IFMT = 0xf000 - S_IFIFO = 0x1000 - S_IFCHR = 0x2000 - S_IFDIR = 0x4000 - S_IFBLK = 0x6000 - S_IFREG = 0x8000 - S_IFLNK = 0xa000 - S_IFSOCK = 0xc000 - S_ISUID = 0x800 - S_ISGID = 0x400 - S_ISVTX = 0x200 - S_IRUSR = 0x100 - S_IWUSR = 0x80 - S_IXUSR = 0x40 -) - -type Stat_t struct { - Dev uint64 - Ino uint64 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - Size int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Blksize int32 - Pad_cgo_0 [4]byte - Blocks int64 - Fstype [16]int8 -} - -type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Sysid int32 - Pid int32 - Pad [4]int64 -} - -type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Name [1]int8 - Pad_cgo_0 [5]byte -} - -type RawSockaddrInet4 struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type RawSockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 - X__sin6_src_id uint32 -} - -type RawSockaddrUnix struct { - Family uint16 - Path [108]int8 -} - -type RawSockaddrDatalink struct { - Family uint16 - Index uint16 - Type uint8 - Nlen uint8 - Alen uint8 - Slen uint8 - Data [244]int8 -} - -type RawSockaddr struct { - Family uint16 - Data [14]int8 -} - -type RawSockaddrAny struct { - Addr RawSockaddr - Pad [236]int8 -} - -type _Socklen uint32 - -type Linger struct { - Onoff int32 - Linger int32 -} - -type Iovec struct { - Base *int8 - Len uint64 -} - -type IPMreq struct { - Multiaddr [4]byte /* in_addr */ - Interface [4]byte /* in_addr */ -} - -type IPv6Mreq struct { - Multiaddr [16]byte /* in6_addr */ - Interface uint32 -} - -type Msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *Iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Accrights *int8 - Accrightslen int32 - Pad_cgo_2 [4]byte -} - -type Cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type Inet6Pktinfo struct { - Addr [16]byte /* in6_addr */ - Ifindex uint32 -} - -type IPv6MTUInfo struct { - Addr RawSockaddrInet6 - Mtu uint32 -} - -type ICMPv6Filter struct { - X__icmp6_filt [8]uint32 -} - -const ( - SizeofSockaddrInet4 = 0x10 - SizeofSockaddrInet6 = 0x20 - SizeofSockaddrAny = 0xfc - SizeofSockaddrUnix = 0x6e - SizeofSockaddrDatalink = 0xfc - SizeofLinger = 0x8 - SizeofIPMreq = 0x8 - SizeofIPv6Mreq = 0x14 - SizeofMsghdr = 0x30 - SizeofCmsghdr = 0xc - SizeofInet6Pktinfo = 0x14 - SizeofIPv6MTUInfo = 0x24 - SizeofICMPv6Filter = 0x20 -) - -type FdSet struct { - Bits [1024]int64 -} - -type Utsname struct { - Sysname [257]int8 - Nodename [257]int8 - Release [257]int8 - Version [257]int8 - Machine [257]int8 -} - -type Ustat_t struct { - Tfree int64 - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_0 [4]byte -} - -const ( - AT_FDCWD = 0xffd19553 - AT_SYMLINK_NOFOLLOW = 0x1000 - AT_SYMLINK_FOLLOW = 0x2000 - AT_REMOVEDIR = 0x1 - AT_EACCESS = 0x4 -) - -const ( - SizeofIfMsghdr = 0x54 - SizeofIfData = 0x44 - SizeofIfaMsghdr = 0x14 - SizeofRtMsghdr = 0x4c - SizeofRtMetrics = 0x28 -) - -type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData -} - -type IfData struct { - Type uint8 - Addrlen uint8 - Hdrlen uint8 - Pad_cgo_0 [1]byte - Mtu uint32 - Metric uint32 - Baudrate uint32 - Ipackets uint32 - Ierrors uint32 - Opackets uint32 - Oerrors uint32 - Collisions uint32 - Ibytes uint32 - Obytes uint32 - Imcasts uint32 - Omcasts uint32 - Iqdrops uint32 - Noproto uint32 - Lastchange Timeval32 -} - -type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 -} - -type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics -} - -type RtMetrics struct { - Locks uint32 - Mtu uint32 - Hopcount uint32 - Expire uint32 - Recvpipe uint32 - Sendpipe uint32 - Ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Pksent uint32 -} - -const ( - SizeofBpfVersion = 0x4 - SizeofBpfStat = 0x80 - SizeofBpfProgram = 0x10 - SizeofBpfInsn = 0x8 - SizeofBpfHdr = 0x14 -) - -type BpfVersion struct { - Major uint16 - Minor uint16 -} - -type BpfStat struct { - Recv uint64 - Drop uint64 - Capt uint64 - Padding [13]uint64 -} - -type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn -} - -type BpfInsn struct { - Code uint16 - Jt uint8 - Jf uint8 - K uint32 -} - -type BpfTimeval struct { - Sec int32 - Usec int32 -} - -type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte -} - -const _SC_PAGESIZE = 0xb - -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [19]uint8 - Pad_cgo_0 [1]byte -} - -type Termio struct { - Iflag uint16 - Oflag uint16 - Cflag uint16 - Lflag uint16 - Line int8 - Cc [8]uint8 - Pad_cgo_0 [1]byte -} - -type Winsize struct { - Row uint16 - Col uint16 - Xpixel uint16 - Ypixel uint16 -} diff --git a/vendor/github.com/fsouza/go-dockerclient/image.go b/vendor/github.com/fsouza/go-dockerclient/image.go deleted file mode 100644 index fd51c3f92..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/image.go +++ /dev/null @@ -1,642 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "time" -) - -// APIImages represent an image returned in the ListImages call. -type APIImages struct { - ID string `json:"Id" yaml:"Id"` - RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty"` - Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` - Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` - VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty"` - ParentID string `json:"ParentId,omitempty" yaml:"ParentId,omitempty"` - RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty"` - Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` -} - -// RootFS represents the underlying layers used by an image -type RootFS struct { - Type string `json:"Type,omitempty" yaml:"Type,omitempty"` - Layers []string `json:"Layers,omitempty" yaml:"Layers,omitempty"` -} - -// Image is the type representing a docker image and its various properties -type Image struct { - ID string `json:"Id" yaml:"Id"` - RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty"` - Parent string `json:"Parent,omitempty" yaml:"Parent,omitempty"` - Comment string `json:"Comment,omitempty" yaml:"Comment,omitempty"` - Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty"` - Container string `json:"Container,omitempty" yaml:"Container,omitempty"` - ContainerConfig Config `json:"ContainerConfig,omitempty" yaml:"ContainerConfig,omitempty"` - DockerVersion string `json:"DockerVersion,omitempty" yaml:"DockerVersion,omitempty"` - Author string `json:"Author,omitempty" yaml:"Author,omitempty"` - Config *Config `json:"Config,omitempty" yaml:"Config,omitempty"` - Architecture string `json:"Architecture,omitempty" yaml:"Architecture,omitempty"` - Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` - VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty"` - RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty"` - RootFS *RootFS `json:"RootFS,omitempty" yaml:"RootFS,omitempty"` -} - -// ImagePre012 serves the same purpose as the Image type except that it is for -// earlier versions of the Docker API (pre-012 to be specific) -type ImagePre012 struct { - ID string `json:"id"` - Parent string `json:"parent,omitempty"` - Comment string `json:"comment,omitempty"` - Created time.Time `json:"created"` - Container string `json:"container,omitempty"` - ContainerConfig Config `json:"container_config,omitempty"` - DockerVersion string `json:"docker_version,omitempty"` - Author string `json:"author,omitempty"` - Config *Config `json:"config,omitempty"` - Architecture string `json:"architecture,omitempty"` - Size int64 `json:"size,omitempty"` -} - -var ( - // ErrNoSuchImage is the error returned when the image does not exist. - ErrNoSuchImage = errors.New("no such image") - - // ErrMissingRepo is the error returned when the remote repository is - // missing. - ErrMissingRepo = errors.New("missing remote repository e.g. 'github.com/user/repo'") - - // ErrMissingOutputStream is the error returned when no output stream - // is provided to some calls, like BuildImage. - ErrMissingOutputStream = errors.New("missing output stream") - - // ErrMultipleContexts is the error returned when both a ContextDir and - // InputStream are provided in BuildImageOptions - ErrMultipleContexts = errors.New("image build may not be provided BOTH context dir and input stream") - - // ErrMustSpecifyNames is the error rreturned when the Names field on - // ExportImagesOptions is nil or empty - ErrMustSpecifyNames = errors.New("must specify at least one name to export") -) - -// ListImagesOptions specify parameters to the ListImages function. -// -// See https://goo.gl/xBe1u3 for more details. -type ListImagesOptions struct { - All bool - Filters map[string][]string - Digests bool - Filter string -} - -// ListImages returns the list of available images in the server. -// -// See https://goo.gl/xBe1u3 for more details. -func (c *Client) ListImages(opts ListImagesOptions) ([]APIImages, error) { - path := "/images/json?" + queryString(opts) - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var images []APIImages - if err := json.NewDecoder(resp.Body).Decode(&images); err != nil { - return nil, err - } - return images, nil -} - -// ImageHistory represent a layer in an image's history returned by the -// ImageHistory call. -type ImageHistory struct { - ID string `json:"Id" yaml:"Id"` - Tags []string `json:"Tags,omitempty" yaml:"Tags,omitempty"` - Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` - CreatedBy string `json:"CreatedBy,omitempty" yaml:"CreatedBy,omitempty"` - Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` -} - -// ImageHistory returns the history of the image by its name or ID. -// -// See https://goo.gl/8bnTId for more details. -func (c *Client) ImageHistory(name string) ([]ImageHistory, error) { - resp, err := c.do("GET", "/images/"+name+"/history", doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, ErrNoSuchImage - } - return nil, err - } - defer resp.Body.Close() - var history []ImageHistory - if err := json.NewDecoder(resp.Body).Decode(&history); err != nil { - return nil, err - } - return history, nil -} - -// RemoveImage removes an image by its name or ID. -// -// See https://goo.gl/V3ZWnK for more details. -func (c *Client) RemoveImage(name string) error { - resp, err := c.do("DELETE", "/images/"+name, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return ErrNoSuchImage - } - return err - } - resp.Body.Close() - return nil -} - -// RemoveImageOptions present the set of options available for removing an image -// from a registry. -// -// See https://goo.gl/V3ZWnK for more details. -type RemoveImageOptions struct { - Force bool `qs:"force"` - NoPrune bool `qs:"noprune"` -} - -// RemoveImageExtended removes an image by its name or ID. -// Extra params can be passed, see RemoveImageOptions -// -// See https://goo.gl/V3ZWnK for more details. -func (c *Client) RemoveImageExtended(name string, opts RemoveImageOptions) error { - uri := fmt.Sprintf("/images/%s?%s", name, queryString(&opts)) - resp, err := c.do("DELETE", uri, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return ErrNoSuchImage - } - return err - } - resp.Body.Close() - return nil -} - -// InspectImage returns an image by its name or ID. -// -// See https://goo.gl/jHPcg6 for more details. -func (c *Client) InspectImage(name string) (*Image, error) { - resp, err := c.do("GET", "/images/"+name+"/json", doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, ErrNoSuchImage - } - return nil, err - } - defer resp.Body.Close() - - var image Image - - // if the caller elected to skip checking the server's version, assume it's the latest - if c.SkipServerVersionCheck || c.expectedAPIVersion.GreaterThanOrEqualTo(apiVersion112) { - if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { - return nil, err - } - } else { - var imagePre012 ImagePre012 - if err := json.NewDecoder(resp.Body).Decode(&imagePre012); err != nil { - return nil, err - } - - image.ID = imagePre012.ID - image.Parent = imagePre012.Parent - image.Comment = imagePre012.Comment - image.Created = imagePre012.Created - image.Container = imagePre012.Container - image.ContainerConfig = imagePre012.ContainerConfig - image.DockerVersion = imagePre012.DockerVersion - image.Author = imagePre012.Author - image.Config = imagePre012.Config - image.Architecture = imagePre012.Architecture - image.Size = imagePre012.Size - } - - return &image, nil -} - -// PushImageOptions represents options to use in the PushImage method. -// -// See https://goo.gl/zPtZaT for more details. -type PushImageOptions struct { - // Name of the image - Name string - - // Tag of the image - Tag string - - // Registry server to push the image - Registry string - - OutputStream io.Writer `qs:"-"` - RawJSONStream bool `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` -} - -// PushImage pushes an image to a remote registry, logging progress to w. -// -// An empty instance of AuthConfiguration may be used for unauthenticated -// pushes. -// -// See https://goo.gl/zPtZaT for more details. -func (c *Client) PushImage(opts PushImageOptions, auth AuthConfiguration) error { - if opts.Name == "" { - return ErrNoSuchImage - } - headers, err := headersWithAuth(auth) - if err != nil { - return err - } - name := opts.Name - opts.Name = "" - path := "/images/" + name + "/push?" + queryString(&opts) - return c.stream("POST", path, streamOptions{ - setRawTerminal: true, - rawJSONStream: opts.RawJSONStream, - headers: headers, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// PullImageOptions present the set of options available for pulling an image -// from a registry. -// -// See https://goo.gl/iJkZjD for more details. -type PullImageOptions struct { - Repository string `qs:"fromImage"` - Registry string - Tag string - - OutputStream io.Writer `qs:"-"` - RawJSONStream bool `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` -} - -// PullImage pulls an image from a remote registry, logging progress to -// opts.OutputStream. -// -// See https://goo.gl/iJkZjD for more details. -func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error { - if opts.Repository == "" { - return ErrNoSuchImage - } - - headers, err := headersWithAuth(auth) - if err != nil { - return err - } - return c.createImage(queryString(&opts), headers, nil, opts.OutputStream, opts.RawJSONStream, opts.InactivityTimeout) -} - -func (c *Client) createImage(qs string, headers map[string]string, in io.Reader, w io.Writer, rawJSONStream bool, timeout time.Duration) error { - path := "/images/create?" + qs - return c.stream("POST", path, streamOptions{ - setRawTerminal: true, - headers: headers, - in: in, - stdout: w, - rawJSONStream: rawJSONStream, - inactivityTimeout: timeout, - }) -} - -// LoadImageOptions represents the options for LoadImage Docker API Call -// -// See https://goo.gl/JyClMX for more details. -type LoadImageOptions struct { - InputStream io.Reader -} - -// LoadImage imports a tarball docker image -// -// See https://goo.gl/JyClMX for more details. -func (c *Client) LoadImage(opts LoadImageOptions) error { - return c.stream("POST", "/images/load", streamOptions{ - setRawTerminal: true, - in: opts.InputStream, - }) -} - -// ExportImageOptions represent the options for ExportImage Docker API call. -// -// See https://goo.gl/le7vK8 for more details. -type ExportImageOptions struct { - Name string - OutputStream io.Writer - InactivityTimeout time.Duration `qs:"-"` -} - -// ExportImage exports an image (as a tar file) into the stream. -// -// See https://goo.gl/le7vK8 for more details. -func (c *Client) ExportImage(opts ExportImageOptions) error { - return c.stream("GET", fmt.Sprintf("/images/%s/get", opts.Name), streamOptions{ - setRawTerminal: true, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// ExportImagesOptions represent the options for ExportImages Docker API call -// -// See https://goo.gl/huC7HA for more details. -type ExportImagesOptions struct { - Names []string - OutputStream io.Writer `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` -} - -// ExportImages exports one or more images (as a tar file) into the stream -// -// See https://goo.gl/huC7HA for more details. -func (c *Client) ExportImages(opts ExportImagesOptions) error { - if opts.Names == nil || len(opts.Names) == 0 { - return ErrMustSpecifyNames - } - return c.stream("GET", "/images/get?"+queryString(&opts), streamOptions{ - setRawTerminal: true, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -// ImportImageOptions present the set of informations available for importing -// an image from a source file or the stdin. -// -// See https://goo.gl/iJkZjD for more details. -type ImportImageOptions struct { - Repository string `qs:"repo"` - Source string `qs:"fromSrc"` - Tag string `qs:"tag"` - - InputStream io.Reader `qs:"-"` - OutputStream io.Writer `qs:"-"` - RawJSONStream bool `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` -} - -// ImportImage imports an image from a url, a file or stdin -// -// See https://goo.gl/iJkZjD for more details. -func (c *Client) ImportImage(opts ImportImageOptions) error { - if opts.Repository == "" { - return ErrNoSuchImage - } - if opts.Source != "-" { - opts.InputStream = nil - } - if opts.Source != "-" && !isURL(opts.Source) { - f, err := os.Open(opts.Source) - if err != nil { - return err - } - opts.InputStream = f - opts.Source = "-" - } - return c.createImage(queryString(&opts), nil, opts.InputStream, opts.OutputStream, opts.RawJSONStream, opts.InactivityTimeout) -} - -// BuildImageOptions present the set of informations available for building an -// image from a tarfile with a Dockerfile in it. -// -// For more details about the Docker building process, see -// http://goo.gl/tlPXPu. -type BuildImageOptions struct { - Name string `qs:"t"` - Dockerfile string `qs:"dockerfile"` - NoCache bool `qs:"nocache"` - SuppressOutput bool `qs:"q"` - Pull bool `qs:"pull"` - RmTmpContainer bool `qs:"rm"` - ForceRmTmpContainer bool `qs:"forcerm"` - Memory int64 `qs:"memory"` - Memswap int64 `qs:"memswap"` - CPUShares int64 `qs:"cpushares"` - CPUQuota int64 `qs:"cpuquota"` - CPUPeriod int64 `qs:"cpuperiod"` - CPUSetCPUs string `qs:"cpusetcpus"` - InputStream io.Reader `qs:"-"` - OutputStream io.Writer `qs:"-"` - RawJSONStream bool `qs:"-"` - Remote string `qs:"remote"` - Auth AuthConfiguration `qs:"-"` // for older docker X-Registry-Auth header - AuthConfigs AuthConfigurations `qs:"-"` // for newer docker X-Registry-Config header - ContextDir string `qs:"-"` - Ulimits []ULimit `qs:"-"` - BuildArgs []BuildArg `qs:"-"` - InactivityTimeout time.Duration `qs:"-"` -} - -// BuildArg represents arguments that can be passed to the image when building -// it from a Dockerfile. -// -// For more details about the Docker building process, see -// http://goo.gl/tlPXPu. -type BuildArg struct { - Name string `json:"Name,omitempty" yaml:"Name,omitempty"` - Value string `json:"Value,omitempty" yaml:"Value,omitempty"` -} - -// BuildImage builds an image from a tarball's url or a Dockerfile in the input -// stream. -// -// See https://goo.gl/xySxCe for more details. -func (c *Client) BuildImage(opts BuildImageOptions) error { - if opts.OutputStream == nil { - return ErrMissingOutputStream - } - headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs)) - if err != nil { - return err - } - - if opts.Remote != "" && opts.Name == "" { - opts.Name = opts.Remote - } - if opts.InputStream != nil || opts.ContextDir != "" { - headers["Content-Type"] = "application/tar" - } else if opts.Remote == "" { - return ErrMissingRepo - } - if opts.ContextDir != "" { - if opts.InputStream != nil { - return ErrMultipleContexts - } - var err error - if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil { - return err - } - } - - qs := queryString(&opts) - if len(opts.Ulimits) > 0 { - if b, err := json.Marshal(opts.Ulimits); err == nil { - item := url.Values(map[string][]string{}) - item.Add("ulimits", string(b)) - qs = fmt.Sprintf("%s&%s", qs, item.Encode()) - } - } - - if len(opts.BuildArgs) > 0 { - v := make(map[string]string) - for _, arg := range opts.BuildArgs { - v[arg.Name] = arg.Value - } - if b, err := json.Marshal(v); err == nil { - item := url.Values(map[string][]string{}) - item.Add("buildargs", string(b)) - qs = fmt.Sprintf("%s&%s", qs, item.Encode()) - } - } - - return c.stream("POST", fmt.Sprintf("/build?%s", qs), streamOptions{ - setRawTerminal: true, - rawJSONStream: opts.RawJSONStream, - headers: headers, - in: opts.InputStream, - stdout: opts.OutputStream, - inactivityTimeout: opts.InactivityTimeout, - }) -} - -func (c *Client) versionedAuthConfigs(authConfigs AuthConfigurations) interface{} { - if c.serverAPIVersion == nil { - c.checkAPIVersion() - } - if c.serverAPIVersion != nil && c.serverAPIVersion.GreaterThanOrEqualTo(apiVersion119) { - return AuthConfigurations119(authConfigs.Configs) - } - return authConfigs -} - -// TagImageOptions present the set of options to tag an image. -// -// See https://goo.gl/98ZzkU for more details. -type TagImageOptions struct { - Repo string - Tag string - Force bool -} - -// TagImage adds a tag to the image identified by the given name. -// -// See https://goo.gl/98ZzkU for more details. -func (c *Client) TagImage(name string, opts TagImageOptions) error { - if name == "" { - return ErrNoSuchImage - } - resp, err := c.do("POST", fmt.Sprintf("/images/"+name+"/tag?%s", - queryString(&opts)), doOptions{}) - - if err != nil { - return err - } - - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotFound { - return ErrNoSuchImage - } - - return err -} - -func isURL(u string) bool { - p, err := url.Parse(u) - if err != nil { - return false - } - return p.Scheme == "http" || p.Scheme == "https" -} - -func headersWithAuth(auths ...interface{}) (map[string]string, error) { - var headers = make(map[string]string) - - for _, auth := range auths { - switch auth.(type) { - case AuthConfiguration: - var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(auth); err != nil { - return nil, err - } - headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes()) - case AuthConfigurations, AuthConfigurations119: - var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(auth); err != nil { - return nil, err - } - headers["X-Registry-Config"] = base64.URLEncoding.EncodeToString(buf.Bytes()) - } - } - - return headers, nil -} - -// APIImageSearch reflect the result of a search on the Docker Hub. -// -// See https://goo.gl/AYjyrF for more details. -type APIImageSearch struct { - Description string `json:"description,omitempty" yaml:"description,omitempty"` - IsOfficial bool `json:"is_official,omitempty" yaml:"is_official,omitempty"` - IsAutomated bool `json:"is_automated,omitempty" yaml:"is_automated,omitempty"` - Name string `json:"name,omitempty" yaml:"name,omitempty"` - StarCount int `json:"star_count,omitempty" yaml:"star_count,omitempty"` -} - -// SearchImages search the docker hub with a specific given term. -// -// See https://goo.gl/AYjyrF for more details. -func (c *Client) SearchImages(term string) ([]APIImageSearch, error) { - resp, err := c.do("GET", "/images/search?term="+term, doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var searchResult []APIImageSearch - if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { - return nil, err - } - return searchResult, nil -} - -// SearchImagesEx search the docker hub with a specific given term and authentication. -// -// See https://goo.gl/AYjyrF for more details. -func (c *Client) SearchImagesEx(term string, auth AuthConfiguration) ([]APIImageSearch, error) { - headers, err := headersWithAuth(auth) - if err != nil { - return nil, err - } - - resp, err := c.do("GET", "/images/search?term="+term, doOptions{ - headers: headers, - }) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - - var searchResult []APIImageSearch - if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { - return nil, err - } - - return searchResult, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/misc.go b/vendor/github.com/fsouza/go-dockerclient/misc.go deleted file mode 100644 index ce9e9750b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/misc.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "strings" -) - -// Version returns version information about the docker server. -// -// See https://goo.gl/ND9R8L for more details. -func (c *Client) Version() (*Env, error) { - resp, err := c.do("GET", "/version", doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var env Env - if err := env.Decode(resp.Body); err != nil { - return nil, err - } - return &env, nil -} - -// DockerInfo contains information about the Docker server -// -// See https://goo.gl/bHUoz9 for more details. -type DockerInfo struct { - ID string - Containers int - ContainersRunning int - ContainersPaused int - ContainersStopped int - Images int - Driver string - DriverStatus [][2]string - SystemStatus [][2]string - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - NFd int - OomKillDisable bool - NGoroutines int - SystemTime string - ExecutionDriver string - LoggingDriver string - CgroupDriver string - NEventsListener int - KernelVersion string - OperatingSystem string - OSType string - Architecture string - IndexServerAddress string - NCPU int - MemTotal int64 - DockerRootDir string - HTTPProxy string `json:"HttpProxy"` - HTTPSProxy string `json:"HttpsProxy"` - NoProxy string - Name string - Labels []string - ExperimentalBuild bool - ServerVersion string - ClusterStore string - ClusterAdvertise string -} - -// PluginsInfo is a struct with the plugins registered with the docker daemon -// -// for more information, see: https://goo.gl/bHUoz9 -type PluginsInfo struct { - // List of Volume plugins registered - Volume []string - // List of Network plugins registered - Network []string - // List of Authorization plugins registered - Authorization []string -} - -// Info returns system-wide information about the Docker server. -// -// See https://goo.gl/ElTHi2 for more details. -func (c *Client) Info() (*DockerInfo, error) { - resp, err := c.do("GET", "/info", doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var info DockerInfo - if err := json.NewDecoder(resp.Body).Decode(&info); err != nil { - return nil, err - } - return &info, nil -} - -// ParseRepositoryTag gets the name of the repository and returns it splitted -// in two parts: the repository and the tag. -// -// Some examples: -// -// localhost.localdomain:5000/samalba/hipache:latest -> localhost.localdomain:5000/samalba/hipache, latest -// localhost.localdomain:5000/samalba/hipache -> localhost.localdomain:5000/samalba/hipache, "" -func ParseRepositoryTag(repoTag string) (repository string, tag string) { - n := strings.LastIndex(repoTag, ":") - if n < 0 { - return repoTag, "" - } - if tag := repoTag[n+1:]; !strings.Contains(tag, "/") { - return repoTag[:n], tag - } - return repoTag, "" -} diff --git a/vendor/github.com/fsouza/go-dockerclient/network.go b/vendor/github.com/fsouza/go-dockerclient/network.go deleted file mode 100644 index a6812495b..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/network.go +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" -) - -// ErrNetworkAlreadyExists is the error returned by CreateNetwork when the -// network already exists. -var ErrNetworkAlreadyExists = errors.New("network already exists") - -// Network represents a network. -// -// See https://goo.gl/6GugX3 for more details. -type Network struct { - Name string - ID string `json:"Id"` - Scope string - Driver string - IPAM IPAMOptions - Containers map[string]Endpoint - Options map[string]string - Internal bool - EnableIPv6 bool `json:"EnableIPv6"` -} - -// Endpoint contains network resources allocated and used for a container in a network -// -// See https://goo.gl/6GugX3 for more details. -type Endpoint struct { - Name string - ID string `json:"EndpointID"` - MacAddress string - IPv4Address string - IPv6Address string -} - -// ListNetworks returns all networks. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) ListNetworks() ([]Network, error) { - resp, err := c.do("GET", "/networks", doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var networks []Network - if err := json.NewDecoder(resp.Body).Decode(&networks); err != nil { - return nil, err - } - return networks, nil -} - -// NetworkFilterOpts is an aggregation of key=value that Docker -// uses to filter networks -type NetworkFilterOpts map[string]map[string]bool - -// FilteredListNetworks returns all networks with the filters applied -// -// See goo.gl/zd2mx4 for more details. -func (c *Client) FilteredListNetworks(opts NetworkFilterOpts) ([]Network, error) { - params := bytes.NewBuffer(nil) - if err := json.NewEncoder(params).Encode(&opts); err != nil { - return nil, err - } - path := "/networks?filters=" + params.String() - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var networks []Network - if err := json.NewDecoder(resp.Body).Decode(&networks); err != nil { - return nil, err - } - return networks, nil -} - -// NetworkInfo returns information about a network by its ID. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) NetworkInfo(id string) (*Network, error) { - path := "/networks/" + id - resp, err := c.do("GET", path, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, &NoSuchNetwork{ID: id} - } - return nil, err - } - defer resp.Body.Close() - var network Network - if err := json.NewDecoder(resp.Body).Decode(&network); err != nil { - return nil, err - } - return &network, nil -} - -// CreateNetworkOptions specify parameters to the CreateNetwork function and -// (for now) is the expected body of the "create network" http request message -// -// See https://goo.gl/6GugX3 for more details. -type CreateNetworkOptions struct { - Name string `json:"Name"` - CheckDuplicate bool `json:"CheckDuplicate"` - Driver string `json:"Driver"` - IPAM IPAMOptions `json:"IPAM"` - Options map[string]interface{} `json:"Options"` - Internal bool `json:"Internal"` - EnableIPv6 bool `json:"EnableIPv6"` -} - -// IPAMOptions controls IP Address Management when creating a network -// -// See https://goo.gl/T8kRVH for more details. -type IPAMOptions struct { - Driver string `json:"Driver"` - Config []IPAMConfig `json:"Config"` -} - -// IPAMConfig represents IPAM configurations -// -// See https://goo.gl/T8kRVH for more details. -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -// CreateNetwork creates a new network, returning the network instance, -// or an error in case of failure. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) CreateNetwork(opts CreateNetworkOptions) (*Network, error) { - resp, err := c.do( - "POST", - "/networks/create", - doOptions{ - data: opts, - }, - ) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusConflict { - return nil, ErrNetworkAlreadyExists - } - return nil, err - } - defer resp.Body.Close() - - type createNetworkResponse struct { - ID string - } - var ( - network Network - cnr createNetworkResponse - ) - if err := json.NewDecoder(resp.Body).Decode(&cnr); err != nil { - return nil, err - } - - network.Name = opts.Name - network.ID = cnr.ID - network.Driver = opts.Driver - - return &network, nil -} - -// RemoveNetwork removes a network or returns an error in case of failure. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) RemoveNetwork(id string) error { - resp, err := c.do("DELETE", "/networks/"+id, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchNetwork{ID: id} - } - return err - } - resp.Body.Close() - return nil -} - -// NetworkConnectionOptions specify parameters to the ConnectNetwork and -// DisconnectNetwork function. -// -// See https://goo.gl/RV7BJU for more details. -type NetworkConnectionOptions struct { - Container string - - // EndpointConfig is only applicable to the ConnectNetwork call - EndpointConfig *EndpointConfig `json:"EndpointConfig,omitempty"` - - // Force is only applicable to the DisconnectNetwork call - Force bool -} - -// EndpointConfig stores network endpoint details -// -// See https://goo.gl/RV7BJU for more details. -type EndpointConfig struct { - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string -} - -// EndpointIPAMConfig represents IPAM configurations for an -// endpoint -// -// See https://goo.gl/RV7BJU for more details. -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` -} - -// ConnectNetwork adds a container to a network or returns an error in case of -// failure. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) ConnectNetwork(id string, opts NetworkConnectionOptions) error { - resp, err := c.do("POST", "/networks/"+id+"/connect", doOptions{data: opts}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} - } - return err - } - resp.Body.Close() - return nil -} - -// DisconnectNetwork removes a container from a network or returns an error in -// case of failure. -// -// See https://goo.gl/6GugX3 for more details. -func (c *Client) DisconnectNetwork(id string, opts NetworkConnectionOptions) error { - resp, err := c.do("POST", "/networks/"+id+"/disconnect", doOptions{data: opts}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} - } - return err - } - resp.Body.Close() - return nil -} - -// NoSuchNetwork is the error returned when a given network does not exist. -type NoSuchNetwork struct { - ID string -} - -func (err *NoSuchNetwork) Error() string { - return fmt.Sprintf("No such network: %s", err.ID) -} - -// NoSuchNetworkOrContainer is the error returned when a given network or -// container does not exist. -type NoSuchNetworkOrContainer struct { - NetworkID string - ContainerID string -} - -func (err *NoSuchNetworkOrContainer) Error() string { - return fmt.Sprintf("No such network (%s) or container (%s)", err.NetworkID, err.ContainerID) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/signal.go b/vendor/github.com/fsouza/go-dockerclient/signal.go deleted file mode 100644 index 16aa00388..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/signal.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -// Signal represents a signal that can be send to the container on -// KillContainer call. -type Signal int - -// These values represent all signals available on Linux, where containers will -// be running. -const ( - SIGABRT = Signal(0x6) - SIGALRM = Signal(0xe) - SIGBUS = Signal(0x7) - SIGCHLD = Signal(0x11) - SIGCLD = Signal(0x11) - SIGCONT = Signal(0x12) - SIGFPE = Signal(0x8) - SIGHUP = Signal(0x1) - SIGILL = Signal(0x4) - SIGINT = Signal(0x2) - SIGIO = Signal(0x1d) - SIGIOT = Signal(0x6) - SIGKILL = Signal(0x9) - SIGPIPE = Signal(0xd) - SIGPOLL = Signal(0x1d) - SIGPROF = Signal(0x1b) - SIGPWR = Signal(0x1e) - SIGQUIT = Signal(0x3) - SIGSEGV = Signal(0xb) - SIGSTKFLT = Signal(0x10) - SIGSTOP = Signal(0x13) - SIGSYS = Signal(0x1f) - SIGTERM = Signal(0xf) - SIGTRAP = Signal(0x5) - SIGTSTP = Signal(0x14) - SIGTTIN = Signal(0x15) - SIGTTOU = Signal(0x16) - SIGUNUSED = Signal(0x1f) - SIGURG = Signal(0x17) - SIGUSR1 = Signal(0xa) - SIGUSR2 = Signal(0xc) - SIGVTALRM = Signal(0x1a) - SIGWINCH = Signal(0x1c) - SIGXCPU = Signal(0x18) - SIGXFSZ = Signal(0x19) -) diff --git a/vendor/github.com/fsouza/go-dockerclient/tar.go b/vendor/github.com/fsouza/go-dockerclient/tar.go deleted file mode 100644 index 48042cbda..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/tar.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils" -) - -func createTarStream(srcPath, dockerfilePath string) (io.ReadCloser, error) { - excludes, err := parseDockerignore(srcPath) - if err != nil { - return nil, err - } - - includes := []string{"."} - - // If .dockerignore mentions .dockerignore or the Dockerfile - // then make sure we send both files over to the daemon - // because Dockerfile is, obviously, needed no matter what, and - // .dockerignore is needed to know if either one needs to be - // removed. The deamon will remove them for us, if needed, after it - // parses the Dockerfile. - // - // https://github.com/docker/docker/issues/8330 - // - forceIncludeFiles := []string{".dockerignore", dockerfilePath} - - for _, includeFile := range forceIncludeFiles { - if includeFile == "" { - continue - } - keepThem, err := fileutils.Matches(includeFile, excludes) - if err != nil { - return nil, fmt.Errorf("cannot match .dockerfile: '%s', error: %s", includeFile, err) - } - if keepThem { - includes = append(includes, includeFile) - } - } - - if err := validateContextDirectory(srcPath, excludes); err != nil { - return nil, err - } - tarOpts := &archive.TarOptions{ - ExcludePatterns: excludes, - IncludeFiles: includes, - Compression: archive.Uncompressed, - NoLchown: true, - } - return archive.TarWithOptions(srcPath, tarOpts) -} - -// validateContextDirectory checks if all the contents of the directory -// can be read and returns an error if some files can't be read. -// Symlinks which point to non-existing files don't trigger an error -func validateContextDirectory(srcPath string, excludes []string) error { - return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { - // skip this directory/file if it's not in the path, it won't get added to the context - if relFilePath, err := filepath.Rel(srcPath, filePath); err != nil { - return err - } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil { - return err - } else if skip { - if f.IsDir() { - return filepath.SkipDir - } - return nil - } - - if err != nil { - if os.IsPermission(err) { - return fmt.Errorf("can't stat '%s'", filePath) - } - if os.IsNotExist(err) { - return nil - } - return err - } - - // skip checking if symlinks point to non-existing files, such symlinks can be useful - // also skip named pipes, because they hanging on open - if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 { - return nil - } - - if !f.IsDir() { - currentFile, err := os.Open(filePath) - if err != nil && os.IsPermission(err) { - return fmt.Errorf("no permission to read from '%s'", filePath) - } - currentFile.Close() - } - return nil - }) -} - -func parseDockerignore(root string) ([]string, error) { - var excludes []string - ignore, err := ioutil.ReadFile(path.Join(root, ".dockerignore")) - if err != nil && !os.IsNotExist(err) { - return excludes, fmt.Errorf("error reading .dockerignore: '%s'", err) - } - excludes = strings.Split(string(ignore), "\n") - - return excludes, nil -} diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/Dockerfile b/vendor/github.com/fsouza/go-dockerclient/testing/data/Dockerfile deleted file mode 100644 index 0948dcfa8..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/Dockerfile +++ /dev/null @@ -1,15 +0,0 @@ -# this file describes how to build tsuru python image -# to run it: -# 1- install docker -# 2- run: $ docker build -t tsuru/python https://raw.github.com/tsuru/basebuilder/master/python/Dockerfile - -from base:ubuntu-quantal -run apt-get install wget -y --force-yes -run wget http://github.com/tsuru/basebuilder/tarball/master -O basebuilder.tar.gz --no-check-certificate -run mkdir /var/lib/tsuru -run tar -xvf basebuilder.tar.gz -C /var/lib/tsuru --strip 1 -run cp /var/lib/tsuru/python/deploy /var/lib/tsuru -run cp /var/lib/tsuru/base/restart /var/lib/tsuru -run cp /var/lib/tsuru/base/start /var/lib/tsuru -run /var/lib/tsuru/base/install -run /var/lib/tsuru/base/setup diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/barfile b/vendor/github.com/fsouza/go-dockerclient/testing/data/barfile deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/ca.pem b/vendor/github.com/fsouza/go-dockerclient/testing/data/ca.pem deleted file mode 100644 index 8e38bba13..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/ca.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC1TCCAb+gAwIBAgIQJ9MsNxrUxumNbAytGi3GEDALBgkqhkiG9w0BAQswFjEU -MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTM4WhcNMTcwOTMwMjAy -MTM4WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD -ggEPADCCAQoCggEBALpFCSARjG+5yXoqr7UMzuE0df7RRZfeRZI06lJ02ZqV4Iii -rgL7ML9yPxX50NbLnjiilSDTUhnyocYFItokzUzz8qpX/nlYhuN2Iqwh4d0aWS8z -f5y248F+H1z+HY2W8NPl/6DVlVwYaNW1/k+RPMlHS0INLR6j+3Ievew7RNE0NnM2 -znELW6NetekDt3GUcz0Z95vDUDfdPnIk1eIFMmYvLxZh23xOca4Q37a3S8F3d+dN -+OOpwjdgY9Qme0NQUaXpgp58jWuQfB8q7mZrdnLlLqRa8gx1HeDSotX7UmWtWPkb -vd9EdlKLYw5PVpxMV1rkwf2t4TdgD5NfkpXlXkkCAwEAAaMjMCEwDgYDVR0PAQH/ -BAQDAgCkMA8GA1UdEwEB/wQFMAMBAf8wCwYJKoZIhvcNAQELA4IBAQBxYjHVSKqE -MJw7CW0GddesULtXXVWGJuZdWJLQlPvPMfIfjIvlcZyS4cdVNiQ3sREFIZz8TpII -CT0/Pg3sgv/FcOQe1CN0xZYZcyiAZHK1z0fJQq2qVpdv7+tJcjI2vvU6NI24iQCo -W1wz25trJz9QbdB2MRLMjyz7TSWuafztIvcfEzaIdQ0Whqund/cSuPGQx5IwF83F -rvlkOyJSH2+VIEBTCIuykJeL0DLTt8cePBQR5L1ISXb4RUMK9ZtqRscBRv8sn7o2 -ixG3wtL0gYF4xLtsQWVxI3iFVrU3WzOH/3c5shVRkWBd+AQRSwCJI4mKH7penJCF -i3/zzlkvOnjV ------END CERTIFICATE----- diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/cert.pem b/vendor/github.com/fsouza/go-dockerclient/testing/data/cert.pem deleted file mode 100644 index 5e7244b24..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/cert.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC6DCCAdKgAwIBAgIRANO6ymxQAjp66KmEka1G6b0wCwYJKoZIhvcNAQELMBYx -FDASBgNVBAoTC0Jvb3QyRG9ja2VyMB4XDTE0MTAxNjIwMjE1MloXDTE3MDkzMDIw -MjE1MlowFjEUMBIGA1UEChMLQm9vdDJEb2NrZXIwggEiMA0GCSqGSIb3DQEBAQUA -A4IBDwAwggEKAoIBAQDGA1mAhSOpZspD1dpZ7qVEQrIJw4Xo8252jHaORnEdDiFm -b6brEmr6jw8t4P3IGxbqBc/TqRV+SSXxwYEVvfpeQKH+SmqStoMNtD3Ura161az4 -V0BcxMtSlsUGpoz+//QCAq8qiaxMwgiyc5253mkQm88anj2cNt7xbewiu/KFWuf7 -BVpNK1+ltpJmlukfcj/G+I1bw7j1KxBjDrFqe5cyDuuZcDL2tmUXP/ZWDyXwSv+H -AOckqn44z6aXlBkVvOXDBZJqY76d/vWVDNCuZeXRnqlhP3t1kH4V0RQXo+JD2tgt -JgdU0unzyoFOSWNUBPm73tqmjUGGAmGHBmeegJr/AgMBAAGjNTAzMA4GA1UdDwEB -/wQEAwIAgDATBgNVHSUEDDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMAsGCSqG -SIb3DQEBCwOCAQEABVTWl5SmBP+j5He5bQsgnIXjviSKqe40/10V4LJAOmilycRF -zLrzM+YMwfjg6PLIs8CldAMWHw9y9ktZY4MxkgCktaiaN/QmMTMwFWEcN4wy5IpM -U5l93eAg7xsnY430h3QBBADujX4wdF3fs8rSL8zAAQFL0ihurwU124K3yXKsrwpb -CiVUGfIN4sPwjy8Ws9oxHFDC9/P8lgjHZ1nBIf8KSHnMzlxDGj7isQfhtH+7mcCL -cM1qO2NirS2v7uaEPPY+MJstAz+W7EJCW9dfMSmHna2SDC37Xkin7uEY9z+qaKFL -8d/XxOB/L8Ucy8VZhdsv0dsBq5KfJntITM0ksQ== ------END CERTIFICATE----- diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/container.tar b/vendor/github.com/fsouza/go-dockerclient/testing/data/container.tar deleted file mode 100644 index e4b066e3b6df8cb78ac445a34234f3780d164cf4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2048 zcmeH_Q3``F42FH)DgF~kTC`qZ7s*`9%A^%r$Bu89Fp<6NMew1akmheFe?H>)Y5N#5 z`(UT)m>?q4G^iwZ#(XmAwH8Ujv`|_rQd)Ig3sQ!(szArs+5bAH%#&Di1HU}iJx_zp z+3uU9k~Zgl)J<3?S%)LS_Hgc7e)t4AX&%Rz>>WAcX2Ec>82D}md=O1Y)p%bo=N_rJ OD+CIGLZA@%gTMmt=q{T8 diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar b/vendor/github.com/fsouza/go-dockerclient/testing/data/dockerfile.tar deleted file mode 100644 index 32c9ce64704835cd096b85ac44c35b5087b5ccdd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2560 zcmeHGy>8<$49;3V1%d0TNOs}`$a>xT46-c8LTt+?QB8ACf0XPiQll-h0~9$I?_v`_`p)qp;@ z0OJK)JAmosQD=m*-~y?5ASGvD1{zS;L7n!AYz2z}2Y8%Kb25fgK0fDb5l4UE+{yF$ zXs`{{TG^hbn!J);Cl1>2UV0=k!T8hL+GbhfZ2u5L51|SJ2KFb&fyiW3|3Qw(jvC+i zouk4oz*u9Q((Iyric9uLhPZsmgZ8ANMrS_2p5cn+n!M}dU&=mMrdq8|OlgOvF-oFN zh5A!%9Pk(EcxS4q(c~Z~u-BL7!+gIN2&&-GnGy1YRpY|{e@?X?J9}9;KY_$PxYO}H o;5QJT#=q||{Y*ZuNn-Gk-)jtGb|Y`+PV+v2`vmS2xaA4_1I+dVl>h($ diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/foofile b/vendor/github.com/fsouza/go-dockerclient/testing/data/foofile deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/key.pem b/vendor/github.com/fsouza/go-dockerclient/testing/data/key.pem deleted file mode 100644 index a9346bcf4..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAxgNZgIUjqWbKQ9XaWe6lREKyCcOF6PNudox2jkZxHQ4hZm+m -6xJq+o8PLeD9yBsW6gXP06kVfkkl8cGBFb36XkCh/kpqkraDDbQ91K2tetWs+FdA -XMTLUpbFBqaM/v/0AgKvKomsTMIIsnOdud5pEJvPGp49nDbe8W3sIrvyhVrn+wVa -TStfpbaSZpbpH3I/xviNW8O49SsQYw6xanuXMg7rmXAy9rZlFz/2Vg8l8Er/hwDn -JKp+OM+ml5QZFbzlwwWSamO+nf71lQzQrmXl0Z6pYT97dZB+FdEUF6PiQ9rYLSYH -VNLp88qBTkljVAT5u97apo1BhgJhhwZnnoCa/wIDAQABAoIBAQCaGy9EC9pmU95l -DwGh7k5nIrUnTilg1FwLHWSDdCVCZKXv8ENrPelOWZqJrUo1u4eI2L8XTsewgkNq -tJu/DRzWz9yDaO0qg6rZNobMh+K076lvmZA44twOydJLS8H+D7ua+PXU2FLlZjmY -kMyXRJZmW6zCXZc7haTbJx6ZJccoquk/DkS4FcFurJP177u1YrWS9TTw9kensUtU -jQ63uf56UTN1i+0+Rxl7OW1TZlqwlri5I4njg5249+FxwwHzIq8+l7zD7K9pl8c/ -nG1HuulvU2bVlDlRdyslMPAH34vw9Sku1BD8furrJLr1na5lRSLKJODEaIPEsLwv -CdEUwP9JAoGBAO76ZW80RyNB2fA+wbTq70Sr8CwrXxYemXrez5LKDC7SsohKFCPE -IedpO/n+nmymiiJvMm874EExoG6BVrbkWkeb+2vinEfOQNlDMsDx7WLjPekP3t6i -rXHO3CjFooVFq2z3mZa/Nc5NZqu8fNWNCKJxZDJphdoj6sORNJIUvZVjAoGBANQd -++J+ITcu3/+A6JrGcgLunBFQYPqkiItk0J4QKYKuX5ik9rWcQDN8TTtfW2mDuiQ4 -NrCwuVPq1V1kB16JzH017SsYLo9g8I20YjnBZge9pKTeUaLVTb3C50LW8FBylop0 -Bnm597dNbtSjphjoTMg0XyC19o3Esf2YeWG0QNS1AoGAWWDfFRNJU99qIldmXULM -0DM6NVrXSk+ReYnhunXEzrJQwXZrR+EwCPurydk36Uz0NuK9yypquhdUeF/5TZfk -SAoHo5byekyipl9imRUigqyY2BTudvgCxKDoaHtaSFwBPFTyZZYICquaLbrmOXxw -8UhVgCFFRYvPXuts7QHC0h8CgYBWEvy9gfU0kV7wLX02IUTuj6jhFb7ktpN6DSTi -nyhZES1VoctDEu6ydcRZTW6ouH12aSE4Pd5WgTqntQmQgVZrkNB25k8ue2Xh+srJ -KQOgLIJ9LIHwE6KCWG7DnrjRzE3uTPq7to0g4tkQjH/AJ7PQof/gJDayfJjFkXPg -A+cy6QKBgEPbKpiqscm03gT2QanBut5pg4dqPOxp0SlErA3kSFNTRK3oYBQPC+LH -qA5nD5brdkeNBB58Rll8Zpzxiff50bcvLP/7/Sb3NjaXFTEY0gVbdRof3n6N0YP3 -Hu5XDNJ9RNkNzE5RIG1g86KE+aKlcrKMaigqAiuIy2PSnjkQeGk8 ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/server.pem b/vendor/github.com/fsouza/go-dockerclient/testing/data/server.pem deleted file mode 100644 index 89cc445e1..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/server.pem +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC/DCCAeagAwIBAgIQMUILcXtvmSOK63zEBo0VXzALBgkqhkiG9w0BAQswFjEU -MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTQ2WhcNMTcwOTMwMjAy -MTQ2WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD -ggEPADCCAQoCggEBANxUOUhNnqFnrTlLsBYzfFRZWQo268l+4K4lOJCVbfDonP3g -Mz0vGi9fcyFqEWSA8Y+ShXna625HTnReCwFdsu0861qCIq7v95hFFCyOe0iIxpd0 -AKLnl90d+1vonE7andgFgoobbTiMly4UK4H6z8D148fFNIihoteOG3PIF89TFxP7 -CJ/3wXnx/IKpdlO8PAnub3tBPJHvGDj7KORLy4IBxRX5VBAdfGNybE66fcrehEva -rLA4m9pgiaR/Nnr9FdKhPyqYdjflLNvzydxNvMIV4M0hFlhXmYvpMjA5/XsTnsyV -t9JHJa5Upwqsbne08t7rsm7liZNxZlko8xPOTQcCAwEAAaNKMEgwDgYDVR0PAQH/ -BAQDAgCgMAwGA1UdEwEB/wQCMAAwKAYDVR0RBCEwH4ILYm9vdDJkb2NrZXKHBH8A -AAGHBAoAAg+HBMCoO2cwCwYJKoZIhvcNAQELA4IBAQAYoYcDkDWkl73FZ0WnPmAj -LiF7HU95Qg3KyEpFsAJeShSLPPbQntmwhdekEzY4tQ3eKQB/+zHFjzsCr/lmDUmH -Ea/ryQ17C+jyH+Ykg0IWW6L6veZhvRDg6Z9focVtPVBRxPTqC/Qhb54blWRASV+W -UreMuXQ5+1dQptAM7ixOeLVHjBi/bd9TL3jvwBVCr9QedteMjjK4TCF9Tbcou+MF -2w3OJJZMDhcD+YwoK9uJDqlKmcTm/vVMbSsp/pTMcnQ7jxCeR8/XyX+VwTZwaHAa -o92Q/eg3THAiWhvyT/SzyH9dHHBAyXynUwGCggKawHktfvW4QXRPuLxLrJ7iB5cy ------END CERTIFICATE----- diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem b/vendor/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem deleted file mode 100644 index c897e5da5..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEoAIBAAKCAQEA3FQ5SE2eoWetOUuwFjN8VFlZCjbryX7griU4kJVt8Oic/eAz -PS8aL19zIWoRZIDxj5KFedrrbkdOdF4LAV2y7TzrWoIiru/3mEUULI57SIjGl3QA -oueX3R37W+icTtqd2AWCihttOIyXLhQrgfrPwPXjx8U0iKGi144bc8gXz1MXE/sI -n/fBefH8gql2U7w8Ce5ve0E8ke8YOPso5EvLggHFFflUEB18Y3JsTrp9yt6ES9qs -sDib2mCJpH82ev0V0qE/Kph2N+Us2/PJ3E28whXgzSEWWFeZi+kyMDn9exOezJW3 -0kclrlSnCqxud7Ty3uuybuWJk3FmWSjzE85NBwIDAQABAoIBAG0ak+cW8LeShHf7 -3+2Of0GxoOLrAWWdG5uAuPr31CJYve0FybnBimDtDjD8ujIfm/7xmoEWBEFutA3x -x9dcU88gvJbsHEqub9gKVQwfXjMz78tt2SbSMiR/xUnk7QorPcCMMfE71aEMFYzu -1gCed6Rg3vO81t/V0rKVH0j9S7UQz5v/oX15eVDV5LOqyCHwAi6K0eXXbqnbI0TH -SOQ/nexM2msVXWbO9t6ra6f5V7FXziDK5Xi+rPxRbX9mkrDzxDAevfuRqYBx5vtL -W2Q2hKjUAHFgXFniNSZBS7dCdAtz0el/3ct+cNmpuTMhhs7M6wC1CuYiZ/DxLiFh -Si73VckCgYEA+/ceh3+VjtQ0rgEw8sD9bqYEA8IaBiObjneIoFnKBYRG7yZd8JMm -HD4M/aQ1qhcRLPN7GR03YQULgQJURbKSjJHnhfTXHyeHC3NN4gMVHQXewu2MHCh6 -7FCQ9CfK0KcYLgegVVvL3PrF3hyWGnmTu+G0UkDQRYVnaNrB7snrW6UCgYEA39tq -+MCQdu0moJ5szSZf02undg9EeW6isk9qzi7TId3/MLci2eH7PEnipipPUK3+DERq -aba0y0TKgBR2EXvXLFJA/+kfdo2loIEHOfox85HVfxgUaFRti63ZI0uF8D0QT2Yy -oJal+RFghVoSnv4LjhRKEPbIkScTXGjdK+7wFjsCfz79iKRXQQx0ALd/lL0bgkAn -QNmvrNHcFQeI2p8700WNzC39aX67SsvEt3qxkrjzC1gxhpTAuReIK1gVPPwvqHN8 -BmV20FD5kMlMCix2mNCopwgUWvKvLAvoGFTxncKMA39+aJbuXAjiqJTekKgNvOE7 -i9kEWw0GTNPp3JHV6QECgYAPwb0M11kT1euDIMOdyRazpf86kyaJuZzgGjD1ZFxe -JOcigbGFTp/FhZnbglzk2+pm6KXo3QBq0mPCki4hWusxZnTGzpz1VlETNCHTFeZQ -M7KoaIR/N3oie9Et59H8r/+m5xWnMhNqratyl316DX24uXrhKM3DUdHODl+LCR2D -IwKBgE1MbHuwolUPEw3HeO4R7NMFVTFei7E/fpUsimPfArGg8UydwvloNT1myJos -N2JzfGGjN2KPVcBk9fOs71mJ6VcK3C3g5JIccplk6h9VNaw55+zdQvKPTzoBoTvy -A+Fwx2AlF61KeRF87DL2YTRJ6B9MHmWgf7+GVZOxomLgEAcZ ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/fsouza/go-dockerclient/testing/server.go b/vendor/github.com/fsouza/go-dockerclient/testing/server.go deleted file mode 100644 index 7b65a8c3d..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/testing/server.go +++ /dev/null @@ -1,1334 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package testing provides a fake implementation of the Docker API, useful for -// testing purpose. -package testing - -import ( - "archive/tar" - "crypto/rand" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - mathrand "math/rand" - "net" - "net/http" - "regexp" - "strconv" - "strings" - "sync" - "time" - - "github.com/fsouza/go-dockerclient" - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy" - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux" -) - -var nameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`) - -// DockerServer represents a programmable, concurrent (not much), HTTP server -// implementing a fake version of the Docker remote API. -// -// It can used in standalone mode, listening for connections or as an arbitrary -// HTTP handler. -// -// For more details on the remote API, check http://goo.gl/G3plxW. -type DockerServer struct { - containers []*docker.Container - uploadedFiles map[string]string - execs []*docker.ExecInspect - execMut sync.RWMutex - cMut sync.RWMutex - images []docker.Image - iMut sync.RWMutex - imgIDs map[string]string - networks []*docker.Network - netMut sync.RWMutex - listener net.Listener - mux *mux.Router - hook func(*http.Request) - failures map[string]string - multiFailures []map[string]string - execCallbacks map[string]func() - statsCallbacks map[string]func(string) docker.Stats - customHandlers map[string]http.Handler - handlerMutex sync.RWMutex - cChan chan<- *docker.Container - volStore map[string]*volumeCounter - volMut sync.RWMutex -} - -type volumeCounter struct { - volume docker.Volume - count int -} - -// NewServer returns a new instance of the fake server, in standalone mode. Use -// the method URL to get the URL of the server. -// -// It receives the bind address (use 127.0.0.1:0 for getting an available port -// on the host), a channel of containers and a hook function, that will be -// called on every request. -// -// The fake server will send containers in the channel whenever the container -// changes its state, via the HTTP API (i.e.: create, start and stop). This -// channel may be nil, which means that the server won't notify on state -// changes. -func NewServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request)) (*DockerServer, error) { - listener, err := net.Listen("tcp", bind) - if err != nil { - return nil, err - } - server := DockerServer{ - listener: listener, - imgIDs: make(map[string]string), - hook: hook, - failures: make(map[string]string), - execCallbacks: make(map[string]func()), - statsCallbacks: make(map[string]func(string) docker.Stats), - customHandlers: make(map[string]http.Handler), - uploadedFiles: make(map[string]string), - cChan: containerChan, - } - server.buildMuxer() - go http.Serve(listener, &server) - return &server, nil -} - -func (s *DockerServer) notify(container *docker.Container) { - if s.cChan != nil { - s.cChan <- container - } -} - -func (s *DockerServer) buildMuxer() { - s.mux = mux.NewRouter() - s.mux.Path("/commit").Methods("POST").HandlerFunc(s.handlerWrapper(s.commitContainer)) - s.mux.Path("/containers/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listContainers)) - s.mux.Path("/containers/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createContainer)) - s.mux.Path("/containers/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectContainer)) - s.mux.Path("/containers/{id:.*}/rename").Methods("POST").HandlerFunc(s.handlerWrapper(s.renameContainer)) - s.mux.Path("/containers/{id:.*}/top").Methods("GET").HandlerFunc(s.handlerWrapper(s.topContainer)) - s.mux.Path("/containers/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startContainer)) - s.mux.Path("/containers/{id:.*}/kill").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) - s.mux.Path("/containers/{id:.*}/stop").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) - s.mux.Path("/containers/{id:.*}/pause").Methods("POST").HandlerFunc(s.handlerWrapper(s.pauseContainer)) - s.mux.Path("/containers/{id:.*}/unpause").Methods("POST").HandlerFunc(s.handlerWrapper(s.unpauseContainer)) - s.mux.Path("/containers/{id:.*}/wait").Methods("POST").HandlerFunc(s.handlerWrapper(s.waitContainer)) - s.mux.Path("/containers/{id:.*}/attach").Methods("POST").HandlerFunc(s.handlerWrapper(s.attachContainer)) - s.mux.Path("/containers/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeContainer)) - s.mux.Path("/containers/{id:.*}/exec").Methods("POST").HandlerFunc(s.handlerWrapper(s.createExecContainer)) - s.mux.Path("/containers/{id:.*}/stats").Methods("GET").HandlerFunc(s.handlerWrapper(s.statsContainer)) - s.mux.Path("/containers/{id:.*}/archive").Methods("PUT").HandlerFunc(s.handlerWrapper(s.uploadToContainer)) - s.mux.Path("/exec/{id:.*}/resize").Methods("POST").HandlerFunc(s.handlerWrapper(s.resizeExecContainer)) - s.mux.Path("/exec/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startExecContainer)) - s.mux.Path("/exec/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectExecContainer)) - s.mux.Path("/images/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.pullImage)) - s.mux.Path("/build").Methods("POST").HandlerFunc(s.handlerWrapper(s.buildImage)) - s.mux.Path("/images/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listImages)) - s.mux.Path("/images/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeImage)) - s.mux.Path("/images/{name:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectImage)) - s.mux.Path("/images/{name:.*}/push").Methods("POST").HandlerFunc(s.handlerWrapper(s.pushImage)) - s.mux.Path("/images/{name:.*}/tag").Methods("POST").HandlerFunc(s.handlerWrapper(s.tagImage)) - s.mux.Path("/events").Methods("GET").HandlerFunc(s.listEvents) - s.mux.Path("/_ping").Methods("GET").HandlerFunc(s.handlerWrapper(s.pingDocker)) - s.mux.Path("/images/load").Methods("POST").HandlerFunc(s.handlerWrapper(s.loadImage)) - s.mux.Path("/images/{id:.*}/get").Methods("GET").HandlerFunc(s.handlerWrapper(s.getImage)) - s.mux.Path("/networks").Methods("GET").HandlerFunc(s.handlerWrapper(s.listNetworks)) - s.mux.Path("/networks/{id:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.networkInfo)) - s.mux.Path("/networks").Methods("POST").HandlerFunc(s.handlerWrapper(s.createNetwork)) - s.mux.Path("/volumes").Methods("GET").HandlerFunc(s.handlerWrapper(s.listVolumes)) - s.mux.Path("/volumes/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createVolume)) - s.mux.Path("/volumes/{name:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectVolume)) - s.mux.Path("/volumes/{name:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeVolume)) - s.mux.Path("/info").Methods("GET").HandlerFunc(s.handlerWrapper(s.infoDocker)) -} - -// SetHook changes the hook function used by the server. -// -// The hook function is a function called on every request. -func (s *DockerServer) SetHook(hook func(*http.Request)) { - s.hook = hook -} - -// PrepareExec adds a callback to a container exec in the fake server. -// -// This function will be called whenever the given exec id is started, and the -// given exec id will remain in the "Running" start while the function is -// running, so it's useful for emulating an exec that runs for two seconds, for -// example: -// -// opts := docker.CreateExecOptions{ -// AttachStdin: true, -// AttachStdout: true, -// AttachStderr: true, -// Tty: true, -// Cmd: []string{"/bin/bash", "-l"}, -// } -// // Client points to a fake server. -// exec, err := client.CreateExec(opts) -// // handle error -// server.PrepareExec(exec.ID, func() {time.Sleep(2 * time.Second)}) -// err = client.StartExec(exec.ID, docker.StartExecOptions{Tty: true}) // will block for 2 seconds -// // handle error -func (s *DockerServer) PrepareExec(id string, callback func()) { - s.execCallbacks[id] = callback -} - -// PrepareStats adds a callback that will be called for each container stats -// call. -// -// This callback function will be called multiple times if stream is set to -// true when stats is called. -func (s *DockerServer) PrepareStats(id string, callback func(string) docker.Stats) { - s.statsCallbacks[id] = callback -} - -// PrepareFailure adds a new expected failure based on a URL regexp it receives -// an id for the failure. -func (s *DockerServer) PrepareFailure(id string, urlRegexp string) { - s.failures[id] = urlRegexp -} - -// PrepareMultiFailures enqueues a new expected failure based on a URL regexp -// it receives an id for the failure. -func (s *DockerServer) PrepareMultiFailures(id string, urlRegexp string) { - s.multiFailures = append(s.multiFailures, map[string]string{"error": id, "url": urlRegexp}) -} - -// ResetFailure removes an expected failure identified by the given id. -func (s *DockerServer) ResetFailure(id string) { - delete(s.failures, id) -} - -// ResetMultiFailures removes all enqueued failures. -func (s *DockerServer) ResetMultiFailures() { - s.multiFailures = []map[string]string{} -} - -// CustomHandler registers a custom handler for a specific path. -// -// For example: -// -// server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { -// http.Error(w, "Something wrong is not right", http.StatusInternalServerError) -// })) -func (s *DockerServer) CustomHandler(path string, handler http.Handler) { - s.handlerMutex.Lock() - s.customHandlers[path] = handler - s.handlerMutex.Unlock() -} - -// MutateContainer changes the state of a container, returning an error if the -// given id does not match to any container "running" in the server. -func (s *DockerServer) MutateContainer(id string, state docker.State) error { - for _, container := range s.containers { - if container.ID == id { - container.State = state - return nil - } - } - return errors.New("container not found") -} - -// Stop stops the server. -func (s *DockerServer) Stop() { - if s.listener != nil { - s.listener.Close() - } -} - -// URL returns the HTTP URL of the server. -func (s *DockerServer) URL() string { - if s.listener == nil { - return "" - } - return "http://" + s.listener.Addr().String() + "/" -} - -// ServeHTTP handles HTTP requests sent to the server. -func (s *DockerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.handlerMutex.RLock() - defer s.handlerMutex.RUnlock() - for re, handler := range s.customHandlers { - if m, _ := regexp.MatchString(re, r.URL.Path); m { - handler.ServeHTTP(w, r) - return - } - } - s.mux.ServeHTTP(w, r) - if s.hook != nil { - s.hook(r) - } -} - -// DefaultHandler returns default http.Handler mux, it allows customHandlers to -// call the default behavior if wanted. -func (s *DockerServer) DefaultHandler() http.Handler { - return s.mux -} - -func (s *DockerServer) handlerWrapper(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - for errorID, urlRegexp := range s.failures { - matched, err := regexp.MatchString(urlRegexp, r.URL.Path) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !matched { - continue - } - http.Error(w, errorID, http.StatusBadRequest) - return - } - for i, failure := range s.multiFailures { - matched, err := regexp.MatchString(failure["url"], r.URL.Path) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !matched { - continue - } - http.Error(w, failure["error"], http.StatusBadRequest) - s.multiFailures = append(s.multiFailures[:i], s.multiFailures[i+1:]...) - return - } - f(w, r) - } -} - -func (s *DockerServer) listContainers(w http.ResponseWriter, r *http.Request) { - all := r.URL.Query().Get("all") - s.cMut.RLock() - result := make([]docker.APIContainers, 0, len(s.containers)) - for _, container := range s.containers { - if all == "1" || container.State.Running { - result = append(result, docker.APIContainers{ - ID: container.ID, - Image: container.Image, - Command: fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " ")), - Created: container.Created.Unix(), - Status: container.State.String(), - Ports: container.NetworkSettings.PortMappingAPI(), - Names: []string{fmt.Sprintf("/%s", container.Name)}, - }) - } - } - s.cMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) listImages(w http.ResponseWriter, r *http.Request) { - s.cMut.RLock() - result := make([]docker.APIImages, len(s.images)) - for i, image := range s.images { - result[i] = docker.APIImages{ - ID: image.ID, - Created: image.Created.Unix(), - } - for tag, id := range s.imgIDs { - if id == image.ID { - result[i].RepoTags = append(result[i].RepoTags, tag) - } - } - } - s.cMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) findImage(id string) (string, error) { - s.iMut.RLock() - defer s.iMut.RUnlock() - image, ok := s.imgIDs[id] - if ok { - return image, nil - } - image, _, err := s.findImageByID(id) - return image, err -} - -func (s *DockerServer) findImageByID(id string) (string, int, error) { - s.iMut.RLock() - defer s.iMut.RUnlock() - for i, image := range s.images { - if image.ID == id { - return image.ID, i, nil - } - } - return "", -1, errors.New("No such image") -} - -func (s *DockerServer) createContainer(w http.ResponseWriter, r *http.Request) { - var config struct { - *docker.Config - HostConfig *docker.HostConfig - } - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - name := r.URL.Query().Get("name") - if name != "" && !nameRegexp.MatchString(name) { - http.Error(w, "Invalid container name", http.StatusInternalServerError) - return - } - if _, err := s.findImage(config.Image); err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - ports := map[docker.Port][]docker.PortBinding{} - for port := range config.ExposedPorts { - ports[port] = []docker.PortBinding{{ - HostIP: "0.0.0.0", - HostPort: strconv.Itoa(mathrand.Int() % 0xffff), - }} - } - - //the container may not have cmd when using a Dockerfile - var path string - var args []string - if len(config.Cmd) == 1 { - path = config.Cmd[0] - } else if len(config.Cmd) > 1 { - path = config.Cmd[0] - args = config.Cmd[1:] - } - - generatedID := s.generateID() - config.Config.Hostname = generatedID[:12] - container := docker.Container{ - Name: name, - ID: generatedID, - Created: time.Now(), - Path: path, - Args: args, - Config: config.Config, - HostConfig: config.HostConfig, - State: docker.State{ - Running: false, - Pid: mathrand.Int() % 50000, - ExitCode: 0, - StartedAt: time.Now(), - }, - Image: config.Image, - NetworkSettings: &docker.NetworkSettings{ - IPAddress: fmt.Sprintf("172.16.42.%d", mathrand.Int()%250+2), - IPPrefixLen: 24, - Gateway: "172.16.42.1", - Bridge: "docker0", - Ports: ports, - }, - } - s.cMut.Lock() - if container.Name != "" { - for _, c := range s.containers { - if c.Name == container.Name { - defer s.cMut.Unlock() - http.Error(w, "there's already a container with this name", http.StatusConflict) - return - } - } - } - s.containers = append(s.containers, &container) - s.cMut.Unlock() - w.WriteHeader(http.StatusCreated) - s.notify(&container) - - json.NewEncoder(w).Encode(container) -} - -func (s *DockerServer) generateID() string { - var buf [16]byte - rand.Read(buf[:]) - return fmt.Sprintf("%x", buf) -} - -func (s *DockerServer) renameContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, index, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - copy := *container - copy.Name = r.URL.Query().Get("name") - s.cMut.Lock() - defer s.cMut.Unlock() - if s.containers[index].ID == copy.ID { - s.containers[index] = © - } - w.WriteHeader(http.StatusNoContent) -} - -func (s *DockerServer) inspectContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(container) -} - -func (s *DockerServer) statsContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - _, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - stream, _ := strconv.ParseBool(r.URL.Query().Get("stream")) - callback := s.statsCallbacks[id] - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - encoder := json.NewEncoder(w) - for { - var stats docker.Stats - if callback != nil { - stats = callback(id) - } - encoder.Encode(stats) - if !stream { - break - } - } -} - -func (s *DockerServer) uploadToContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if !container.State.Running { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "Container %s is not running", id) - return - } - path := r.URL.Query().Get("path") - s.uploadedFiles[id] = path - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) topContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if !container.State.Running { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "Container %s is not running", id) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - result := docker.TopResult{ - Titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, - Processes: [][]string{ - {"root", "7535", "7516", "0", "03:20", "?", "00:00:00", container.Path + " " + strings.Join(container.Args, " ")}, - }, - } - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) startContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - defer r.Body.Close() - var hostConfig docker.HostConfig - err = json.NewDecoder(r.Body).Decode(&hostConfig) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - container.HostConfig = &hostConfig - if len(hostConfig.PortBindings) > 0 { - ports := map[docker.Port][]docker.PortBinding{} - for key, items := range hostConfig.PortBindings { - bindings := make([]docker.PortBinding, len(items)) - for i := range items { - binding := docker.PortBinding{ - HostIP: items[i].HostIP, - HostPort: items[i].HostPort, - } - if binding.HostIP == "" { - binding.HostIP = "0.0.0.0" - } - if binding.HostPort == "" { - binding.HostPort = strconv.Itoa(mathrand.Int() % 0xffff) - } - bindings[i] = binding - } - ports[key] = bindings - } - container.NetworkSettings.Ports = ports - } - if container.State.Running { - http.Error(w, "", http.StatusNotModified) - return - } - container.State.Running = true - s.notify(container) -} - -func (s *DockerServer) stopContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if !container.State.Running { - http.Error(w, "Container not running", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Running = false - s.notify(container) -} - -func (s *DockerServer) pauseContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if container.State.Paused { - http.Error(w, "Container already paused", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Paused = true -} - -func (s *DockerServer) unpauseContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - s.cMut.Lock() - defer s.cMut.Unlock() - if !container.State.Paused { - http.Error(w, "Container not paused", http.StatusBadRequest) - return - } - w.WriteHeader(http.StatusNoContent) - container.State.Paused = false -} - -func (s *DockerServer) attachContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - hijacker, ok := w.(http.Hijacker) - if !ok { - http.Error(w, "cannot hijack connection", http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/vnd.docker.raw-stream") - w.WriteHeader(http.StatusOK) - conn, _, err := hijacker.Hijack() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - wg := sync.WaitGroup{} - if r.URL.Query().Get("stdin") == "1" { - wg.Add(1) - go func() { - ioutil.ReadAll(conn) - wg.Done() - }() - } - outStream := stdcopy.NewStdWriter(conn, stdcopy.Stdout) - if container.State.Running { - fmt.Fprintf(outStream, "Container is running\n") - } else { - fmt.Fprintf(outStream, "Container is not running\n") - } - fmt.Fprintln(outStream, "What happened?") - fmt.Fprintln(outStream, "Something happened") - wg.Wait() - if r.URL.Query().Get("stream") == "1" { - for { - time.Sleep(1e6) - s.cMut.RLock() - if !container.State.Running { - s.cMut.RUnlock() - break - } - s.cMut.RUnlock() - } - } - conn.Close() -} - -func (s *DockerServer) waitContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - for { - time.Sleep(1e6) - s.cMut.RLock() - if !container.State.Running { - s.cMut.RUnlock() - break - } - s.cMut.RUnlock() - } - result := map[string]int{"StatusCode": container.State.ExitCode} - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) removeContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - force := r.URL.Query().Get("force") - s.cMut.Lock() - defer s.cMut.Unlock() - container, index, err := s.findContainerWithLock(id, false) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if container.State.Running && force != "1" { - msg := "Error: API error (406): Impossible to remove a running container, please stop it first" - http.Error(w, msg, http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusNoContent) - s.containers[index] = s.containers[len(s.containers)-1] - s.containers = s.containers[:len(s.containers)-1] -} - -func (s *DockerServer) commitContainer(w http.ResponseWriter, r *http.Request) { - id := r.URL.Query().Get("container") - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - config := new(docker.Config) - runConfig := r.URL.Query().Get("run") - if runConfig != "" { - err = json.Unmarshal([]byte(runConfig), config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - } - w.WriteHeader(http.StatusOK) - image := docker.Image{ - ID: "img-" + container.ID, - Parent: container.Image, - Container: container.ID, - Comment: r.URL.Query().Get("m"), - Author: r.URL.Query().Get("author"), - Config: config, - } - repository := r.URL.Query().Get("repo") - tag := r.URL.Query().Get("tag") - s.iMut.Lock() - s.images = append(s.images, image) - if repository != "" { - if tag != "" { - repository += ":" + tag - } - s.imgIDs[repository] = image.ID - } - s.iMut.Unlock() - fmt.Fprintf(w, `{"ID":%q}`, image.ID) -} - -func (s *DockerServer) findContainer(idOrName string) (*docker.Container, int, error) { - return s.findContainerWithLock(idOrName, true) -} - -func (s *DockerServer) findContainerWithLock(idOrName string, shouldLock bool) (*docker.Container, int, error) { - if shouldLock { - s.cMut.RLock() - defer s.cMut.RUnlock() - } - for i, container := range s.containers { - if container.ID == idOrName || container.Name == idOrName { - return container, i, nil - } - } - return nil, -1, errors.New("No such container") -} - -func (s *DockerServer) buildImage(w http.ResponseWriter, r *http.Request) { - if ct := r.Header.Get("Content-Type"); ct == "application/tar" { - gotDockerFile := false - tr := tar.NewReader(r.Body) - for { - header, err := tr.Next() - if err != nil { - break - } - if header.Name == "Dockerfile" { - gotDockerFile = true - } - } - if !gotDockerFile { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("miss Dockerfile")) - return - } - } - //we did not use that Dockerfile to build image cause we are a fake Docker daemon - image := docker.Image{ - ID: s.generateID(), - Created: time.Now(), - } - - query := r.URL.Query() - repository := image.ID - if t := query.Get("t"); t != "" { - repository = t - } - s.iMut.Lock() - s.images = append(s.images, image) - s.imgIDs[repository] = image.ID - s.iMut.Unlock() - w.Write([]byte(fmt.Sprintf("Successfully built %s", image.ID))) -} - -func (s *DockerServer) pullImage(w http.ResponseWriter, r *http.Request) { - fromImageName := r.URL.Query().Get("fromImage") - tag := r.URL.Query().Get("tag") - image := docker.Image{ - ID: s.generateID(), - Config: &docker.Config{}, - } - s.iMut.Lock() - s.images = append(s.images, image) - if fromImageName != "" { - if tag != "" { - fromImageName = fmt.Sprintf("%s:%s", fromImageName, tag) - } - s.imgIDs[fromImageName] = image.ID - } - s.iMut.Unlock() -} - -func (s *DockerServer) pushImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - tag := r.URL.Query().Get("tag") - if tag != "" { - name += ":" + tag - } - s.iMut.RLock() - if _, ok := s.imgIDs[name]; !ok { - s.iMut.RUnlock() - http.Error(w, "No such image", http.StatusNotFound) - return - } - s.iMut.RUnlock() - fmt.Fprintln(w, "Pushing...") - fmt.Fprintln(w, "Pushed") -} - -func (s *DockerServer) tagImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - s.iMut.RLock() - if _, ok := s.imgIDs[name]; !ok { - s.iMut.RUnlock() - http.Error(w, "No such image", http.StatusNotFound) - return - } - s.iMut.RUnlock() - s.iMut.Lock() - defer s.iMut.Unlock() - newRepo := r.URL.Query().Get("repo") - newTag := r.URL.Query().Get("tag") - if newTag != "" { - newRepo += ":" + newTag - } - s.imgIDs[newRepo] = s.imgIDs[name] - w.WriteHeader(http.StatusCreated) -} - -func (s *DockerServer) removeImage(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - s.iMut.RLock() - var tag string - if img, ok := s.imgIDs[id]; ok { - id, tag = img, id - } - var tags []string - for tag, taggedID := range s.imgIDs { - if taggedID == id { - tags = append(tags, tag) - } - } - s.iMut.RUnlock() - _, index, err := s.findImageByID(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.WriteHeader(http.StatusNoContent) - s.iMut.Lock() - defer s.iMut.Unlock() - if len(tags) < 2 { - s.images[index] = s.images[len(s.images)-1] - s.images = s.images[:len(s.images)-1] - } - if tag != "" { - delete(s.imgIDs, tag) - } -} - -func (s *DockerServer) inspectImage(w http.ResponseWriter, r *http.Request) { - name := mux.Vars(r)["name"] - s.iMut.RLock() - defer s.iMut.RUnlock() - if id, ok := s.imgIDs[name]; ok { - for _, img := range s.images { - if img.ID == id { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(img) - return - } - } - } - http.Error(w, "not found", http.StatusNotFound) -} - -func (s *DockerServer) listEvents(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - var events [][]byte - count := mathrand.Intn(20) - for i := 0; i < count; i++ { - data, err := json.Marshal(s.generateEvent()) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - events = append(events, data) - } - w.WriteHeader(http.StatusOK) - for _, d := range events { - fmt.Fprintln(w, d) - time.Sleep(time.Duration(mathrand.Intn(200)) * time.Millisecond) - } -} - -func (s *DockerServer) pingDocker(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) generateEvent() *docker.APIEvents { - var eventType string - switch mathrand.Intn(4) { - case 0: - eventType = "create" - case 1: - eventType = "start" - case 2: - eventType = "stop" - case 3: - eventType = "destroy" - } - return &docker.APIEvents{ - ID: s.generateID(), - Status: eventType, - From: "mybase:latest", - Time: time.Now().Unix(), - } -} - -func (s *DockerServer) loadImage(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func (s *DockerServer) getImage(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/tar") -} - -func (s *DockerServer) createExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - container, _, err := s.findContainer(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - - execID := s.generateID() - container.ExecIDs = append(container.ExecIDs, execID) - - exec := docker.ExecInspect{ - ID: execID, - Container: *container, - } - - var params docker.CreateExecOptions - err = json.NewDecoder(r.Body).Decode(¶ms) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if len(params.Cmd) > 0 { - exec.ProcessConfig.EntryPoint = params.Cmd[0] - if len(params.Cmd) > 1 { - exec.ProcessConfig.Arguments = params.Cmd[1:] - } - } - - exec.ProcessConfig.User = params.User - exec.ProcessConfig.Tty = params.Tty - - s.execMut.Lock() - s.execs = append(s.execs, &exec) - s.execMut.Unlock() - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]string{"Id": exec.ID}) -} - -func (s *DockerServer) startExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if exec, err := s.getExec(id, false); err == nil { - s.execMut.Lock() - exec.Running = true - s.execMut.Unlock() - if callback, ok := s.execCallbacks[id]; ok { - callback() - delete(s.execCallbacks, id) - } else if callback, ok := s.execCallbacks["*"]; ok { - callback() - delete(s.execCallbacks, "*") - } - s.execMut.Lock() - exec.Running = false - s.execMut.Unlock() - w.WriteHeader(http.StatusOK) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) resizeExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if _, err := s.getExec(id, false); err == nil { - w.WriteHeader(http.StatusOK) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) inspectExecContainer(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - if exec, err := s.getExec(id, true); err == nil { - w.WriteHeader(http.StatusOK) - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(exec) - return - } - w.WriteHeader(http.StatusNotFound) -} - -func (s *DockerServer) getExec(id string, copy bool) (*docker.ExecInspect, error) { - s.execMut.RLock() - defer s.execMut.RUnlock() - for _, exec := range s.execs { - if exec.ID == id { - if copy { - cp := *exec - exec = &cp - } - return exec, nil - } - } - return nil, errors.New("exec not found") -} - -func (s *DockerServer) findNetwork(idOrName string) (*docker.Network, int, error) { - s.netMut.RLock() - defer s.netMut.RUnlock() - for i, network := range s.networks { - if network.ID == idOrName || network.Name == idOrName { - return network, i, nil - } - } - return nil, -1, errors.New("No such network") -} - -func (s *DockerServer) listNetworks(w http.ResponseWriter, r *http.Request) { - s.netMut.RLock() - result := make([]docker.Network, 0, len(s.networks)) - for _, network := range s.networks { - result = append(result, *network) - } - s.netMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) networkInfo(w http.ResponseWriter, r *http.Request) { - id := mux.Vars(r)["id"] - network, _, err := s.findNetwork(id) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(network) -} - -// isValidName validates configuration objects supported by libnetwork -func isValidName(name string) bool { - if name == "" || strings.Contains(name, ".") { - return false - } - return true -} - -func (s *DockerServer) createNetwork(w http.ResponseWriter, r *http.Request) { - var config *docker.CreateNetworkOptions - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&config) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if !isValidName(config.Name) { - http.Error(w, "Invalid network name", http.StatusBadRequest) - return - } - if n, _, _ := s.findNetwork(config.Name); n != nil { - http.Error(w, "network already exists", http.StatusForbidden) - return - } - - generatedID := s.generateID() - network := docker.Network{ - Name: config.Name, - ID: generatedID, - Driver: config.Driver, - } - s.netMut.Lock() - s.networks = append(s.networks, &network) - s.netMut.Unlock() - w.WriteHeader(http.StatusCreated) - var c = struct{ ID string }{ID: network.ID} - json.NewEncoder(w).Encode(c) -} - -func (s *DockerServer) listVolumes(w http.ResponseWriter, r *http.Request) { - s.volMut.RLock() - result := make([]docker.Volume, 0, len(s.volStore)) - for _, volumeCounter := range s.volStore { - result = append(result, volumeCounter.volume) - } - s.volMut.RUnlock() - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(result) -} - -func (s *DockerServer) createVolume(w http.ResponseWriter, r *http.Request) { - var data struct { - *docker.CreateVolumeOptions - } - defer r.Body.Close() - err := json.NewDecoder(r.Body).Decode(&data) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - volume := &docker.Volume{ - Name: data.CreateVolumeOptions.Name, - Driver: data.CreateVolumeOptions.Driver, - } - // If the name is not specified, generate one. Just using generateID for now - if len(volume.Name) == 0 { - volume.Name = s.generateID() - } - // If driver is not specified, use local - if len(volume.Driver) == 0 { - volume.Driver = "local" - } - // Mount point is a default one with name - volume.Mountpoint = "/var/lib/docker/volumes/" + volume.Name - - // If the volume already exists, don't re-add it. - exists := false - s.volMut.Lock() - if s.volStore != nil { - _, exists = s.volStore[volume.Name] - } else { - // No volumes, create volStore - s.volStore = make(map[string]*volumeCounter) - } - if !exists { - s.volStore[volume.Name] = &volumeCounter{ - volume: *volume, - count: 0, - } - } - s.volMut.Unlock() - w.WriteHeader(http.StatusCreated) - json.NewEncoder(w).Encode(volume) -} - -func (s *DockerServer) inspectVolume(w http.ResponseWriter, r *http.Request) { - s.volMut.RLock() - defer s.volMut.RUnlock() - name := mux.Vars(r)["name"] - vol, err := s.findVolume(name) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(vol.volume) -} - -func (s *DockerServer) findVolume(name string) (*volumeCounter, error) { - vol, ok := s.volStore[name] - if !ok { - return nil, errors.New("no such volume") - } - return vol, nil -} - -func (s *DockerServer) removeVolume(w http.ResponseWriter, r *http.Request) { - s.volMut.Lock() - defer s.volMut.Unlock() - name := mux.Vars(r)["name"] - vol, err := s.findVolume(name) - if err != nil { - http.Error(w, err.Error(), http.StatusNotFound) - return - } - if vol.count != 0 { - http.Error(w, "volume in use and cannot be removed", http.StatusConflict) - return - } - s.volStore[vol.volume.Name] = nil - w.WriteHeader(http.StatusNoContent) -} - -func (s *DockerServer) infoDocker(w http.ResponseWriter, r *http.Request) { - s.cMut.RLock() - defer s.cMut.RUnlock() - s.iMut.RLock() - defer s.iMut.RUnlock() - var running, stopped, paused int - for _, c := range s.containers { - if c.State.Running { - running++ - } else { - stopped++ - } - if c.State.Paused { - paused++ - } - } - envs := map[string]interface{}{ - "ID": "AAAA:XXXX:0000:BBBB:AAAA:XXXX:0000:BBBB:AAAA:XXXX:0000:BBBB", - "Containers": len(s.containers), - "ContainersRunning": running, - "ContainersPaused": paused, - "ContainersStopped": stopped, - "Images": len(s.images), - "Driver": "aufs", - "DriverStatus": [][]string{}, - "SystemStatus": nil, - "Plugins": map[string]interface{}{ - "Volume": []string{ - "local", - }, - "Network": []string{ - "bridge", - "null", - "host", - }, - "Authorization": nil, - }, - "MemoryLimit": true, - "SwapLimit": false, - "CpuCfsPeriod": true, - "CpuCfsQuota": true, - "CPUShares": true, - "CPUSet": true, - "IPv4Forwarding": true, - "BridgeNfIptables": true, - "BridgeNfIp6tables": true, - "Debug": false, - "NFd": 79, - "OomKillDisable": true, - "NGoroutines": 101, - "SystemTime": "2016-02-25T18:13:10.25870078Z", - "ExecutionDriver": "native-0.2", - "LoggingDriver": "json-file", - "NEventsListener": 0, - "KernelVersion": "3.13.0-77-generic", - "OperatingSystem": "Ubuntu 14.04.3 LTS", - "OSType": "linux", - "Architecture": "x86_64", - "IndexServerAddress": "https://index.docker.io/v1/", - "RegistryConfig": map[string]interface{}{ - "InsecureRegistryCIDRs": []string{}, - "IndexConfigs": map[string]interface{}{}, - "Mirrors": nil, - }, - "InitSha1": "e2042dbb0fcf49bb9da199186d9a5063cda92a01", - "InitPath": "/usr/lib/docker/dockerinit", - "NCPU": 1, - "MemTotal": 2099204096, - "DockerRootDir": "/var/lib/docker", - "HttpProxy": "", - "HttpsProxy": "", - "NoProxy": "", - "Name": "vagrant-ubuntu-trusty-64", - "Labels": nil, - "ExperimentalBuild": false, - "ServerVersion": "1.10.1", - "ClusterStore": "", - "ClusterAdvertise": "", - } - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(envs) -} diff --git a/vendor/github.com/fsouza/go-dockerclient/tls.go b/vendor/github.com/fsouza/go-dockerclient/tls.go deleted file mode 100644 index bb5790b5f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/tls.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// -// The content is borrowed from Docker's own source code to provide a simple -// tls based dialer - -package docker - -import ( - "crypto/tls" - "errors" - "net" - "strings" - "time" -) - -type tlsClientCon struct { - *tls.Conn - rawConn net.Conn -} - -func (c *tlsClientCon) CloseWrite() error { - // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it - // on its underlying connection. - if cwc, ok := c.rawConn.(interface { - CloseWrite() error - }); ok { - return cwc.CloseWrite() - } - return nil -} - -func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { - // We want the Timeout and Deadline values from dialer to cover the - // whole process: TCP connection and TLS handshake. This means that we - // also need to start our own timers now. - timeout := dialer.Timeout - - if !dialer.Deadline.IsZero() { - deadlineTimeout := dialer.Deadline.Sub(time.Now()) - if timeout == 0 || deadlineTimeout < timeout { - timeout = deadlineTimeout - } - } - - var errChannel chan error - - if timeout != 0 { - errChannel = make(chan error, 2) - time.AfterFunc(timeout, func() { - errChannel <- errors.New("") - }) - } - - rawConn, err := dialer.Dial(network, addr) - if err != nil { - return nil, err - } - - colonPos := strings.LastIndex(addr, ":") - if colonPos == -1 { - colonPos = len(addr) - } - hostname := addr[:colonPos] - - // If no ServerName is set, infer the ServerName - // from the hostname we're connecting to. - if config.ServerName == "" { - // Make a copy to avoid polluting argument or default. - config = copyTLSConfig(config) - config.ServerName = hostname - } - - conn := tls.Client(rawConn, config) - - if timeout == 0 { - err = conn.Handshake() - } else { - go func() { - errChannel <- conn.Handshake() - }() - - err = <-errChannel - } - - if err != nil { - rawConn.Close() - return nil, err - } - - // This is Docker difference with standard's crypto/tls package: returned a - // wrapper which holds both the TLS and raw connections. - return &tlsClientCon{conn, rawConn}, nil -} - -// this exists to silent an error message in go vet -func copyTLSConfig(cfg *tls.Config) *tls.Config { - return &tls.Config{ - Certificates: cfg.Certificates, - CipherSuites: cfg.CipherSuites, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - ClientSessionCache: cfg.ClientSessionCache, - CurvePreferences: cfg.CurvePreferences, - InsecureSkipVerify: cfg.InsecureSkipVerify, - MaxVersion: cfg.MaxVersion, - MinVersion: cfg.MinVersion, - NameToCertificate: cfg.NameToCertificate, - NextProtos: cfg.NextProtos, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - Rand: cfg.Rand, - RootCAs: cfg.RootCAs, - ServerName: cfg.ServerName, - SessionTicketKey: cfg.SessionTicketKey, - SessionTicketsDisabled: cfg.SessionTicketsDisabled, - } -} diff --git a/vendor/github.com/fsouza/go-dockerclient/travis-scripts/install.bash b/vendor/github.com/fsouza/go-dockerclient/travis-scripts/install.bash deleted file mode 100755 index 9d1708fa9..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/travis-scripts/install.bash +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -x - -# Copyright 2016 go-dockerclient authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -if [[ $TRAVIS_OS_NAME == "linux" ]]; then - sudo stop docker || true - sudo rm -rf /var/lib/docker - sudo rm -f `which docker` - - set -e - sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D - echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" | sudo tee /etc/apt/sources.list.d/docker.list - sudo apt-get update - sudo apt-get install docker-engine=${DOCKER_VERSION}-0~$(lsb_release -cs) -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -fi diff --git a/vendor/github.com/fsouza/go-dockerclient/travis-scripts/run-tests.bash b/vendor/github.com/fsouza/go-dockerclient/travis-scripts/run-tests.bash deleted file mode 100755 index 0d836cd4f..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/travis-scripts/run-tests.bash +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash -ex - -# Copyright 2016 go-dockerclient authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -if ! [[ $TRAVIS_GO_VERSION =~ ^1\.[34] ]]; then - make lint vet -fi - -make fmtcheck gotest GO_TEST_FLAGS=-race - -if [[ $TRAVIS_OS_NAME == "linux" ]]; then - DOCKER_HOST=tcp://127.0.0.1:2375 make integration -fi diff --git a/vendor/github.com/fsouza/go-dockerclient/volume.go b/vendor/github.com/fsouza/go-dockerclient/volume.go deleted file mode 100644 index 5fe8ee3d6..000000000 --- a/vendor/github.com/fsouza/go-dockerclient/volume.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package docker - -import ( - "encoding/json" - "errors" - "net/http" -) - -var ( - // ErrNoSuchVolume is the error returned when the volume does not exist. - ErrNoSuchVolume = errors.New("no such volume") - - // ErrVolumeInUse is the error returned when the volume requested to be removed is still in use. - ErrVolumeInUse = errors.New("volume in use and cannot be removed") -) - -// Volume represents a volume. -// -// See https://goo.gl/FZA4BK for more details. -type Volume struct { - Name string `json:"Name" yaml:"Name"` - Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty"` - Mountpoint string `json:"Mountpoint,omitempty" yaml:"Mountpoint,omitempty"` - Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` -} - -// ListVolumesOptions specify parameters to the ListVolumes function. -// -// See https://goo.gl/FZA4BK for more details. -type ListVolumesOptions struct { - Filters map[string][]string -} - -// ListVolumes returns a list of available volumes in the server. -// -// See https://goo.gl/FZA4BK for more details. -func (c *Client) ListVolumes(opts ListVolumesOptions) ([]Volume, error) { - resp, err := c.do("GET", "/volumes?"+queryString(opts), doOptions{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - m := make(map[string]interface{}) - if err := json.NewDecoder(resp.Body).Decode(&m); err != nil { - return nil, err - } - var volumes []Volume - volumesJSON, ok := m["Volumes"] - if !ok { - return volumes, nil - } - data, err := json.Marshal(volumesJSON) - if err != nil { - return nil, err - } - if err := json.Unmarshal(data, &volumes); err != nil { - return nil, err - } - return volumes, nil -} - -// CreateVolumeOptions specify parameters to the CreateVolume function. -// -// See https://goo.gl/pBUbZ9 for more details. -type CreateVolumeOptions struct { - Name string - Driver string - DriverOpts map[string]string -} - -// CreateVolume creates a volume on the server. -// -// See https://goo.gl/pBUbZ9 for more details. -func (c *Client) CreateVolume(opts CreateVolumeOptions) (*Volume, error) { - resp, err := c.do("POST", "/volumes/create", doOptions{data: opts}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - var volume Volume - if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { - return nil, err - } - return &volume, nil -} - -// InspectVolume returns a volume by its name. -// -// See https://goo.gl/0g9A6i for more details. -func (c *Client) InspectVolume(name string) (*Volume, error) { - resp, err := c.do("GET", "/volumes/"+name, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { - return nil, ErrNoSuchVolume - } - return nil, err - } - defer resp.Body.Close() - var volume Volume - if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { - return nil, err - } - return &volume, nil -} - -// RemoveVolume removes a volume by its name. -// -// See https://goo.gl/79GNQz for more details. -func (c *Client) RemoveVolume(name string) error { - resp, err := c.do("DELETE", "/volumes/"+name, doOptions{}) - if err != nil { - if e, ok := err.(*Error); ok { - if e.Status == http.StatusNotFound { - return ErrNoSuchVolume - } - if e.Status == http.StatusConflict { - return ErrVolumeInUse - } - } - return nil - } - defer resp.Body.Close() - return nil -} diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE deleted file mode 100644 index 7805d36de..000000000 --- a/vendor/github.com/ghodss/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b4..000000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go deleted file mode 100644 index 586007402..000000000 --- a/vendor/github.com/ghodss/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go deleted file mode 100644 index 6e7f14fc7..000000000 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ /dev/null @@ -1,305 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "reflect" - "strconv" - - "gopkg.in/yaml.v2" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// JSONOpt is a decoding option for decoding from JSON format. -type JSONOpt func(*json.Decoder) *json.Decoder - -// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, -// optionally configuring the behavior of the JSON unmarshal. -func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo, yaml.Unmarshal) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = jsonUnmarshal(bytes.NewReader(j), o, opts...) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// jsonUnmarshal unmarshals the JSON byte stream from the given reader into the -// object, optionally applying decoder options prior to decoding. We are not -// using json.Unmarshal directly as we want the chance to pass in non-default -// options. -func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error { - d := json.NewDecoder(r) - for _, opt := range opts { - d = opt(d) - } - if err := d.Decode(&o); err != nil { - return fmt.Errorf("while decoding JSON: %v", err) - } - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, -// passing JSON through this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -// -// For strict decoding of YAML, use YAMLToJSONStrict. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.Unmarshal) -} - -// YAMLToJSONStrict is like YAMLToJSON but enables strict YAML decoding, -// returning an error on any duplicate field names. -func YAMLToJSONStrict(y []byte) ([]byte, error) { - return yamlToJSON(y, nil, yaml.UnmarshalStrict) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value, yamlUnmarshal func([]byte, interface{}) error) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yamlUnmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/github.com/ghodss/yaml/yaml_go110.go b/vendor/github.com/ghodss/yaml/yaml_go110.go deleted file mode 100644 index ab3e06a22..000000000 --- a/vendor/github.com/ghodss/yaml/yaml_go110.go +++ /dev/null @@ -1,14 +0,0 @@ -// This file contains changes that are only compatible with go 1.10 and onwards. - -// +build go1.10 - -package yaml - -import "encoding/json" - -// DisallowUnknownFields configures the JSON decoder to error out if unknown -// fields come along, instead of dropping them by default. -func DisallowUnknownFields(d *json.Decoder) *json.Decoder { - d.DisallowUnknownFields() - return d -} diff --git a/vendor/github.com/go-errors/errors/LICENSE.MIT b/vendor/github.com/go-errors/errors/LICENSE.MIT deleted file mode 100644 index c9a5b2eeb..000000000 --- a/vendor/github.com/go-errors/errors/LICENSE.MIT +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2015 Conrad Irwin - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-errors/errors/README.md b/vendor/github.com/go-errors/errors/README.md deleted file mode 100644 index 5d4f1873d..000000000 --- a/vendor/github.com/go-errors/errors/README.md +++ /dev/null @@ -1,66 +0,0 @@ -go-errors/errors -================ - -[![Build Status](https://travis-ci.org/go-errors/errors.svg?branch=master)](https://travis-ci.org/go-errors/errors) - -Package errors adds stacktrace support to errors in go. - -This is particularly useful when you want to understand the state of execution -when an error was returned unexpectedly. - -It provides the type \*Error which implements the standard golang error -interface, so you can use this library interchangably with code that is -expecting a normal error return. - -Usage ------ - -Full documentation is available on -[godoc](https://godoc.org/github.com/go-errors/errors), but here's a simple -example: - -```go -package crashy - -import "github.com/go-errors/errors" - -var Crashed = errors.Errorf("oh dear") - -func Crash() error { - return errors.New(Crashed) -} -``` - -This can be called as follows: - -```go -package main - -import ( - "crashy" - "fmt" - "github.com/go-errors/errors" -) - -func main() { - err := crashy.Crash() - if err != nil { - if errors.Is(err, crashy.Crashed) { - fmt.Println(err.(*errors.Error).ErrorStack()) - } else { - panic(err) - } - } -} -``` - -Meta-fu -------- - -This package was original written to allow reporting to -[Bugsnag](https://bugsnag.com/) from -[bugsnag-go](https://github.com/bugsnag/bugsnag-go), but after I found similar -packages by Facebook and Dropbox, it was moved to one canonical location so -everyone can benefit. - -This package is licensed under the MIT license, see LICENSE.MIT for details. diff --git a/vendor/github.com/go-errors/errors/cover.out b/vendor/github.com/go-errors/errors/cover.out deleted file mode 100644 index ab18b0519..000000000 --- a/vendor/github.com/go-errors/errors/cover.out +++ /dev/null @@ -1,89 +0,0 @@ -mode: set -github.com/go-errors/errors/stackframe.go:27.51,30.25 2 1 -github.com/go-errors/errors/stackframe.go:33.2,38.8 3 1 -github.com/go-errors/errors/stackframe.go:30.25,32.3 1 0 -github.com/go-errors/errors/stackframe.go:43.47,44.31 1 1 -github.com/go-errors/errors/stackframe.go:47.2,47.48 1 1 -github.com/go-errors/errors/stackframe.go:44.31,46.3 1 1 -github.com/go-errors/errors/stackframe.go:52.42,56.16 3 1 -github.com/go-errors/errors/stackframe.go:60.2,60.60 1 1 -github.com/go-errors/errors/stackframe.go:56.16,58.3 1 0 -github.com/go-errors/errors/stackframe.go:64.55,67.16 2 1 -github.com/go-errors/errors/stackframe.go:71.2,72.61 2 1 -github.com/go-errors/errors/stackframe.go:76.2,76.66 1 1 -github.com/go-errors/errors/stackframe.go:67.16,69.3 1 0 -github.com/go-errors/errors/stackframe.go:72.61,74.3 1 0 -github.com/go-errors/errors/stackframe.go:79.56,91.63 3 1 -github.com/go-errors/errors/stackframe.go:95.2,95.53 1 1 -github.com/go-errors/errors/stackframe.go:100.2,101.18 2 1 -github.com/go-errors/errors/stackframe.go:91.63,94.3 2 1 -github.com/go-errors/errors/stackframe.go:95.53,98.3 2 1 -github.com/go-errors/errors/error.go:70.32,73.23 2 1 -github.com/go-errors/errors/error.go:80.2,85.3 3 1 -github.com/go-errors/errors/error.go:74.2,75.10 1 1 -github.com/go-errors/errors/error.go:76.2,77.28 1 1 -github.com/go-errors/errors/error.go:92.43,95.23 2 1 -github.com/go-errors/errors/error.go:104.2,109.3 3 1 -github.com/go-errors/errors/error.go:96.2,97.11 1 1 -github.com/go-errors/errors/error.go:98.2,99.10 1 1 -github.com/go-errors/errors/error.go:100.2,101.28 1 1 -github.com/go-errors/errors/error.go:115.39,117.19 1 1 -github.com/go-errors/errors/error.go:121.2,121.29 1 1 -github.com/go-errors/errors/error.go:125.2,125.43 1 1 -github.com/go-errors/errors/error.go:129.2,129.14 1 1 -github.com/go-errors/errors/error.go:117.19,119.3 1 1 -github.com/go-errors/errors/error.go:121.29,123.3 1 1 -github.com/go-errors/errors/error.go:125.43,127.3 1 1 -github.com/go-errors/errors/error.go:135.53,137.2 1 1 -github.com/go-errors/errors/error.go:140.34,142.2 1 1 -github.com/go-errors/errors/error.go:146.34,149.42 2 1 -github.com/go-errors/errors/error.go:153.2,153.20 1 1 -github.com/go-errors/errors/error.go:149.42,151.3 1 1 -github.com/go-errors/errors/error.go:158.39,160.2 1 1 -github.com/go-errors/errors/error.go:164.46,165.23 1 1 -github.com/go-errors/errors/error.go:173.2,173.19 1 1 -github.com/go-errors/errors/error.go:165.23,168.32 2 1 -github.com/go-errors/errors/error.go:168.32,170.4 1 1 -github.com/go-errors/errors/error.go:177.37,178.42 1 1 -github.com/go-errors/errors/error.go:181.2,181.41 1 1 -github.com/go-errors/errors/error.go:178.42,180.3 1 1 -github.com/go-errors/errors/parse_panic.go:10.39,12.2 1 1 -github.com/go-errors/errors/parse_panic.go:16.46,24.34 5 1 -github.com/go-errors/errors/parse_panic.go:70.2,70.43 1 1 -github.com/go-errors/errors/parse_panic.go:73.2,73.55 1 0 -github.com/go-errors/errors/parse_panic.go:24.34,27.23 2 1 -github.com/go-errors/errors/parse_panic.go:27.23,28.42 1 1 -github.com/go-errors/errors/parse_panic.go:28.42,31.5 2 1 -github.com/go-errors/errors/parse_panic.go:31.6,33.5 1 0 -github.com/go-errors/errors/parse_panic.go:35.5,35.29 1 1 -github.com/go-errors/errors/parse_panic.go:35.29,36.86 1 1 -github.com/go-errors/errors/parse_panic.go:36.86,38.5 1 1 -github.com/go-errors/errors/parse_panic.go:40.5,40.32 1 1 -github.com/go-errors/errors/parse_panic.go:40.32,41.18 1 1 -github.com/go-errors/errors/parse_panic.go:45.4,46.46 2 1 -github.com/go-errors/errors/parse_panic.go:51.4,53.23 2 1 -github.com/go-errors/errors/parse_panic.go:57.4,58.18 2 1 -github.com/go-errors/errors/parse_panic.go:62.4,63.17 2 1 -github.com/go-errors/errors/parse_panic.go:41.18,43.10 2 1 -github.com/go-errors/errors/parse_panic.go:46.46,49.5 2 1 -github.com/go-errors/errors/parse_panic.go:53.23,55.5 1 0 -github.com/go-errors/errors/parse_panic.go:58.18,60.5 1 0 -github.com/go-errors/errors/parse_panic.go:63.17,65.10 2 1 -github.com/go-errors/errors/parse_panic.go:70.43,72.3 1 1 -github.com/go-errors/errors/parse_panic.go:80.85,82.29 2 1 -github.com/go-errors/errors/parse_panic.go:85.2,85.15 1 1 -github.com/go-errors/errors/parse_panic.go:88.2,90.63 2 1 -github.com/go-errors/errors/parse_panic.go:94.2,94.53 1 1 -github.com/go-errors/errors/parse_panic.go:99.2,101.36 2 1 -github.com/go-errors/errors/parse_panic.go:105.2,106.15 2 1 -github.com/go-errors/errors/parse_panic.go:109.2,112.49 3 1 -github.com/go-errors/errors/parse_panic.go:116.2,117.16 2 1 -github.com/go-errors/errors/parse_panic.go:121.2,126.8 1 1 -github.com/go-errors/errors/parse_panic.go:82.29,84.3 1 0 -github.com/go-errors/errors/parse_panic.go:85.15,87.3 1 1 -github.com/go-errors/errors/parse_panic.go:90.63,93.3 2 1 -github.com/go-errors/errors/parse_panic.go:94.53,97.3 2 1 -github.com/go-errors/errors/parse_panic.go:101.36,103.3 1 0 -github.com/go-errors/errors/parse_panic.go:106.15,108.3 1 0 -github.com/go-errors/errors/parse_panic.go:112.49,114.3 1 1 -github.com/go-errors/errors/parse_panic.go:117.16,119.3 1 0 diff --git a/vendor/github.com/go-errors/errors/error.go b/vendor/github.com/go-errors/errors/error.go deleted file mode 100644 index ea5d2b206..000000000 --- a/vendor/github.com/go-errors/errors/error.go +++ /dev/null @@ -1,224 +0,0 @@ -// Package errors provides errors that have stack-traces. -// -// This is particularly useful when you want to understand the -// state of execution when an error was returned unexpectedly. -// -// It provides the type *Error which implements the standard -// golang error interface, so you can use this library interchangably -// with code that is expecting a normal error return. -// -// For example: -// -// package crashy -// -// import "github.com/go-errors/errors" -// -// var Crashed = errors.Errorf("oh dear") -// -// func Crash() error { -// return errors.New(Crashed) -// } -// -// This can be called as follows: -// -// package main -// -// import ( -// "crashy" -// "fmt" -// "github.com/go-errors/errors" -// ) -// -// func main() { -// err := crashy.Crash() -// if err != nil { -// if errors.Is(err, crashy.Crashed) { -// fmt.Println(err.(*errors.Error).ErrorStack()) -// } else { -// panic(err) -// } -// } -// } -// -// This package was original written to allow reporting to Bugsnag, -// but after I found similar packages by Facebook and Dropbox, it -// was moved to one canonical location so everyone can benefit. -package errors - -import ( - "bytes" - "fmt" - "reflect" - "runtime" -) - -// The maximum number of stackframes on any error. -var MaxStackDepth = 50 - -// Error is an error with an attached stacktrace. It can be used -// wherever the builtin error interface is expected. -type Error struct { - Err error - stack []uintptr - frames []StackFrame - prefix string -} - -// New makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The stacktrace will point to the line of code that -// called New. -func New(e interface{}) *Error { - var err error - - switch e := e.(type) { - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// Wrap makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The skip parameter indicates how far up the stack -// to start the stacktrace. 0 is from the current call, 1 from its caller, etc. -func Wrap(e interface{}, skip int) *Error { - if e == nil { - return nil - } - - var err error - - switch e := e.(type) { - case *Error: - return e - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2+skip, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// WrapPrefix makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the -// error message when calling Error(). The skip parameter indicates how far -// up the stack to start the stacktrace. 0 is from the current call, -// 1 from its caller, etc. -func WrapPrefix(e interface{}, prefix string, skip int) *Error { - if e == nil { - return nil - } - - err := Wrap(e, 1+skip) - - if err.prefix != "" { - prefix = fmt.Sprintf("%s: %s", prefix, err.prefix) - } - - return &Error{ - Err: err.Err, - stack: err.stack, - prefix: prefix, - } - -} - -// Is detects whether the error is equal to a given error. Errors -// are considered equal by this function if they are the same object, -// or if they both contain the same error inside an errors.Error. -func Is(e error, original error) bool { - - if e == original { - return true - } - - if e, ok := e.(*Error); ok { - return Is(e.Err, original) - } - - if original, ok := original.(*Error); ok { - return Is(e, original.Err) - } - - return false -} - -// Errorf creates a new error with the given message. You can use it -// as a drop-in replacement for fmt.Errorf() to provide descriptive -// errors in return values. -func Errorf(format string, a ...interface{}) *Error { - return Wrap(fmt.Errorf(format, a...), 1) -} - -// Error returns the underlying error's message. -func (err *Error) Error() string { - - msg := err.Err.Error() - if err.prefix != "" { - msg = fmt.Sprintf("%s: %s", err.prefix, msg) - } - - return msg -} - -// Stack returns the callstack formatted the same way that go does -// in runtime/debug.Stack() -func (err *Error) Stack() []byte { - buf := bytes.Buffer{} - - for _, frame := range err.StackFrames() { - buf.WriteString(frame.String()) - } - - return buf.Bytes() -} - -// Callers satisfies the bugsnag ErrorWithCallerS() interface -// so that the stack can be read out. -func (err *Error) Callers() []uintptr { - return err.stack -} - -// ErrorStack returns a string that contains both the -// error message and the callstack. -func (err *Error) ErrorStack() string { - return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack()) -} - -// StackFrames returns an array of frames containing information about the -// stack. -func (err *Error) StackFrames() []StackFrame { - if err.frames == nil { - err.frames = make([]StackFrame, len(err.stack)) - - for i, pc := range err.stack { - err.frames[i] = NewStackFrame(pc) - } - } - - return err.frames -} - -// TypeName returns the type this error. e.g. *errors.stringError. -func (err *Error) TypeName() string { - if _, ok := err.Err.(uncaughtPanic); ok { - return "panic" - } - return reflect.TypeOf(err.Err).String() -} diff --git a/vendor/github.com/go-errors/errors/parse_panic.go b/vendor/github.com/go-errors/errors/parse_panic.go deleted file mode 100644 index cc37052d7..000000000 --- a/vendor/github.com/go-errors/errors/parse_panic.go +++ /dev/null @@ -1,127 +0,0 @@ -package errors - -import ( - "strconv" - "strings" -) - -type uncaughtPanic struct{ message string } - -func (p uncaughtPanic) Error() string { - return p.message -} - -// ParsePanic allows you to get an error object from the output of a go program -// that panicked. This is particularly useful with https://github.com/mitchellh/panicwrap. -func ParsePanic(text string) (*Error, error) { - lines := strings.Split(text, "\n") - - state := "start" - - var message string - var stack []StackFrame - - for i := 0; i < len(lines); i++ { - line := lines[i] - - if state == "start" { - if strings.HasPrefix(line, "panic: ") { - message = strings.TrimPrefix(line, "panic: ") - state = "seek" - } else { - return nil, Errorf("bugsnag.panicParser: Invalid line (no prefix): %s", line) - } - - } else if state == "seek" { - if strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "[running]:") { - state = "parsing" - } - - } else if state == "parsing" { - if line == "" { - state = "done" - break - } - createdBy := false - if strings.HasPrefix(line, "created by ") { - line = strings.TrimPrefix(line, "created by ") - createdBy = true - } - - i++ - - if i >= len(lines) { - return nil, Errorf("bugsnag.panicParser: Invalid line (unpaired): %s", line) - } - - frame, err := parsePanicFrame(line, lines[i], createdBy) - if err != nil { - return nil, err - } - - stack = append(stack, *frame) - if createdBy { - state = "done" - break - } - } - } - - if state == "done" || state == "parsing" { - return &Error{Err: uncaughtPanic{message}, frames: stack}, nil - } - return nil, Errorf("could not parse panic: %v", text) -} - -// The lines we're passing look like this: -// -// main.(*foo).destruct(0xc208067e98) -// /0/go/src/github.com/bugsnag/bugsnag-go/pan/main.go:22 +0x151 -func parsePanicFrame(name string, line string, createdBy bool) (*StackFrame, error) { - idx := strings.LastIndex(name, "(") - if idx == -1 && !createdBy { - return nil, Errorf("bugsnag.panicParser: Invalid line (no call): %s", name) - } - if idx != -1 { - name = name[:idx] - } - pkg := "" - - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - - if !strings.HasPrefix(line, "\t") { - return nil, Errorf("bugsnag.panicParser: Invalid line (no tab): %s", line) - } - - idx = strings.LastIndex(line, ":") - if idx == -1 { - return nil, Errorf("bugsnag.panicParser: Invalid line (no line number): %s", line) - } - file := line[1:idx] - - number := line[idx+1:] - if idx = strings.Index(number, " +"); idx > -1 { - number = number[:idx] - } - - lno, err := strconv.ParseInt(number, 10, 32) - if err != nil { - return nil, Errorf("bugsnag.panicParser: Invalid line (bad line number): %s", line) - } - - return &StackFrame{ - File: file, - LineNumber: int(lno), - Package: pkg, - Name: name, - }, nil -} diff --git a/vendor/github.com/go-errors/errors/stackframe.go b/vendor/github.com/go-errors/errors/stackframe.go deleted file mode 100644 index 750ab9a52..000000000 --- a/vendor/github.com/go-errors/errors/stackframe.go +++ /dev/null @@ -1,102 +0,0 @@ -package errors - -import ( - "bytes" - "fmt" - "io/ioutil" - "runtime" - "strings" -) - -// A StackFrame contains all necessary information about to generate a line -// in a callstack. -type StackFrame struct { - // The path to the file containing this ProgramCounter - File string - // The LineNumber in that file - LineNumber int - // The Name of the function that contains this ProgramCounter - Name string - // The Package that contains this function - Package string - // The underlying ProgramCounter - ProgramCounter uintptr -} - -// NewStackFrame popoulates a stack frame object from the program counter. -func NewStackFrame(pc uintptr) (frame StackFrame) { - - frame = StackFrame{ProgramCounter: pc} - if frame.Func() == nil { - return - } - frame.Package, frame.Name = packageAndName(frame.Func()) - - // pc -1 because the program counters we use are usually return addresses, - // and we want to show the line that corresponds to the function call - frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1) - return - -} - -// Func returns the function that contained this frame. -func (frame *StackFrame) Func() *runtime.Func { - if frame.ProgramCounter == 0 { - return nil - } - return runtime.FuncForPC(frame.ProgramCounter) -} - -// String returns the stackframe formatted in the same way as go does -// in runtime/debug.Stack() -func (frame *StackFrame) String() string { - str := fmt.Sprintf("%s:%d (0x%x)\n", frame.File, frame.LineNumber, frame.ProgramCounter) - - source, err := frame.SourceLine() - if err != nil { - return str - } - - return str + fmt.Sprintf("\t%s: %s\n", frame.Name, source) -} - -// SourceLine gets the line of code (from File and Line) of the original source if possible. -func (frame *StackFrame) SourceLine() (string, error) { - data, err := ioutil.ReadFile(frame.File) - - if err != nil { - return "", New(err) - } - - lines := bytes.Split(data, []byte{'\n'}) - if frame.LineNumber <= 0 || frame.LineNumber >= len(lines) { - return "???", nil - } - // -1 because line-numbers are 1 based, but our array is 0 based - return string(bytes.Trim(lines[frame.LineNumber-1], " \t")), nil -} - -func packageAndName(fn *runtime.Func) (string, string) { - name := fn.Name() - pkg := "" - - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - // Since the package path might contains dots (e.g. code.google.com/...), - // we first remove the path prefix if there is one. - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - return pkg, name -} diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE deleted file mode 100644 index 37ec93a14..000000000 --- a/vendor/github.com/go-ini/ini/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile deleted file mode 100644 index ac034e525..000000000 --- a/vendor/github.com/go-ini/ini/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -.PHONY: build test bench vet - -build: vet bench - -test: - go test -v -cover -race - -bench: - go test -v -cover -race -test.bench=. -test.benchmem - -vet: - go vet diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md deleted file mode 100644 index 22a42344a..000000000 --- a/vendor/github.com/go-ini/ini/README.md +++ /dev/null @@ -1,734 +0,0 @@ -INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) -=== - -![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200) - -Package ini provides INI file read and write functionality in Go. - -[简体中文](README_ZH.md) - -## Feature - -- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. -- Read with recursion values. -- Read with parent-child sections. -- Read with auto-increment key names. -- Read with multiple-line values. -- Read with tons of helper methods. -- Read and convert values to Go types. -- Read and **WRITE** comments of sections and keys. -- Manipulate sections, keys and comments with ease. -- Keep sections and keys in order as you parse and save. - -## Installation - -To use a tagged revision: - - go get gopkg.in/ini.v1 - -To use with latest changes: - - go get github.com/go-ini/ini - -Please add `-u` flag to update in the future. - -### Testing - -If you want to test on your machine, please apply `-t` flag: - - go get -t gopkg.in/ini.v1 - -Please add `-u` flag to update in the future. - -## Getting Started - -### Loading from data sources - -A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error. - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -Or start with an empty object: - -```go -cfg := ini.Empty() -``` - -When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later. - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error. - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual. - -#### Ignore cases of key name - -When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing. - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 and sec2 are the exactly same section object -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 and key2 are the exactly same key object -key1, err := cfg.GetKey("Key") -key2, err := cfg.GetKey("KeY") -``` - -#### MySQL-like boolean key - -MySQL's configuration allows a key without value as follows: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options: - -```go -cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read. - -#### Comment - -Take care that following format will be treated as comment: - -1. Line begins with `#` or `;` -2. Words after `#` or `;` -3. Words after section name (i.e words after `[some section name]`) - -If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```. - -### Working with sections - -To get a section, you would need to: - -```go -section, err := cfg.GetSection("section name") -``` - -For a shortcut for default section, just give an empty string as name: - -```go -section, err := cfg.GetSection("") -``` - -When you're pretty sure the section exists, following code could make your life easier: - -```go -section := cfg.Section("section name") -``` - -What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you. - -To create a new section: - -```go -err := cfg.NewSection("new section") -``` - -To get a list of sections or section names: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### Working with keys - -To get a key under a section: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -Same rule applies to key operations: - -```go -key := cfg.Section("").Key("key name") -``` - -To check if a key exists: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -To create a new key: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -To get a list of keys or key names: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -To get a clone hash of keys and corresponding values: - -```go -hash := cfg.Section("").KeysHash() -``` - -### Working with values - -To get a string value: - -```go -val := cfg.Section("").Key("key name").String() -``` - -To validate key value on the fly: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -To check if raw value exists: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -To get value with types: - -```go -// For boolean values: -// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// Methods start with Must also accept one argument for default value -// when key not found or fail to parse value to given type. -// Except method MustString, which you have to pass a default value. - -v = cfg.Section("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -What if my value is three-line long? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -Not a problem! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -That's cool, how about continuation lines? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -Piece of cake! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -Well, I hate continuation lines, how do I disable that? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -Holy crap! - -Note that single quotes around values will be stripped: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -That's all? Hmm, no. - -#### Helper methods of working with values - -To get value with given candidates: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates. - -To validate value in a given range: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### Auto-split values into a slice - -To use zero value of type for invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -To exclude invalid values out of result slice: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -Or to return nothing but error when have invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### Save your configuration - -Finally, it's time to save your configuration to somewhere. - -A typical way to save configuration is writing it to a file: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -Another way to save is writing to a `io.Writer` interface: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -By default, spaces are used to align "=" sign between key and values, to disable that: - -```go -ini.PrettyFormat = false -``` - -## Advanced Usage - -### Recursive Values - -For all value of keys, there is a special syntax `%()s`, where `` is the key name in same section or default section, and `%()s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions. - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### Parent-child Sections - -You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section. - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### Retrieve parent keys available to a child section - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### Unparseable Sections - -Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`: - -```go -cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### Auto-increment Key Names - -If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter. - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### Map To Struct - -Want more objective way to play with INI? Cool. - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // Things can be simpler. - err = ini.MapTo(p, "path/to/ini") - // ... - - // Just map a section? Fine. - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -Can I have default value for field? Absolutely. - -Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type. - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -It's really cool, but what's the point if you can't give me my file back from struct? - -### Reflect From Struct - -Why not? - -```go -type Embeded struct { - Dates []time.Time `delim:"|"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int - GPA float64 - NeverMind string `ini:"-"` - *Embeded -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -So, what do I get? - -```ini -NAME = Unknwon -Male = true -Age = 21 -GPA = 2.8 - -[Embeded] -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### Name Mapper - -To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name. - -There are 2 built-in name mappers: - -- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key. -- `TitleUnderscore`: it converts to format `title_underscore` then match section or key. - -To use them: - -```go -type Info struct { - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -Same rules of name mapper apply to `ini.ReflectFromWithMapper` function. - -#### Value Mapper - -To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`. - -#### Other Notes On Map/Reflect - -Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome. - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## Getting Help - -- [API Documentation](https://gowalker.org/gopkg.in/ini.v1) -- [File An Issue](https://github.com/go-ini/ini/issues/new) - -## FAQs - -### What does `BlockMode` field do? - -By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster. - -### Why another INI library? - -Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster. - -To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path) - -## License - -This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text. diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md deleted file mode 100644 index 3b4fb6604..000000000 --- a/vendor/github.com/go-ini/ini/README_ZH.md +++ /dev/null @@ -1,721 +0,0 @@ -本包提供了 Go 语言中读写 INI 文件的功能。 - -## 功能特性 - -- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`) -- 支持递归读取键值 -- 支持读取父子分区 -- 支持读取自增键名 -- 支持读取多行的键值 -- 支持大量辅助方法 -- 支持在读取时直接转换为 Go 语言类型 -- 支持读取和 **写入** 分区和键的注释 -- 轻松操作分区、键值和注释 -- 在保存文件时分区和键值会保持原有的顺序 - -## 下载安装 - -使用一个特定版本: - - go get gopkg.in/ini.v1 - -使用最新版: - - go get github.com/go-ini/ini - -如需更新请添加 `-u` 选项。 - -### 测试安装 - -如果您想要在自己的机器上运行测试,请使用 `-t` 标记: - - go get -t gopkg.in/ini.v1 - -如需更新请添加 `-u` 选项。 - -## 开始使用 - -### 从数据源加载 - -一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -或者从一个空白的文件开始: - -```go -cfg := ini.Empty() -``` - -当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。 - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误): - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。 - -#### 忽略键名的大小写 - -有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写: - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 和 sec2 指向同一个分区对象 -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 和 key2 指向同一个键对象 -key1, err := cfg.GetKey("Key") -key2, err := cfg.GetKey("KeY") -``` - -#### 类似 MySQL 配置中的布尔值键 - -MySQL 的配置文件中会出现没有具体值的布尔类型的键: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理: - -```go -cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -这些键的值永远为 `true`,且在保存到文件时也只会输出键名。 - -#### 关于注释 - -下述几种情况的内容将被视为注释: - -1. 所有以 `#` 或 `;` 开头的行 -2. 所有在 `#` 或 `;` 之后的内容 -3. 分区标签后的文字 (即 `[分区名]` 之后的内容) - -如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。 - -### 操作分区(Section) - -获取指定分区: - -```go -section, err := cfg.GetSection("section name") -``` - -如果您想要获取默认分区,则可以用空字符串代替分区名: - -```go -section, err := cfg.GetSection("") -``` - -当您非常确定某个分区是存在的,可以使用以下简便方法: - -```go -section := cfg.Section("section name") -``` - -如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。 - -创建一个分区: - -```go -err := cfg.NewSection("new section") -``` - -获取所有分区对象或名称: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### 操作键(Key) - -获取某个分区下的键: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -和分区一样,您也可以直接获取键而忽略错误处理: - -```go -key := cfg.Section("").Key("key name") -``` - -判断某个键是否存在: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -创建一个新的键: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -获取分区下的所有键或键名: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -获取分区下的所有键值对的克隆: - -```go -hash := cfg.Section("").KeysHash() -``` - -### 操作键值(Value) - -获取一个类型为字符串(string)的值: - -```go -val := cfg.Section("").Key("key name").String() -``` - -获取值的同时通过自定义函数进行处理验证: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -判断某个原值是否存在: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -获取其它类型的值: - -```go -// 布尔值的规则: -// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值, -// 当键不存在或者转换失败时,则会直接返回该默认值。 -// 但是,MustString 方法必须传递一个默认值。 - -v = cfg.Seciont("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -如果我的值有好多行怎么办? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -嗯哼?小 case! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -简直是小菜一碟! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -哇靠给力啊! - -需要注意的是,值两侧的单引号会被自动剔除: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -这就是全部了?哈哈,当然不是。 - -#### 操作键值的辅助方法 - -获取键值时设定候选值: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。 - -验证获取的值是否在指定范围内: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### 自动分割键值到切片(slice) - -当存在无效输入时,使用零值代替: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -从结果切片中剔除无效输入: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -当存在无效输入时,直接返回错误: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### 保存配置 - -终于到了这个时刻,是时候保存一下配置了。 - -比较原始的做法是输出配置到某个文件: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能: - -```go -ini.PrettyFormat = false -``` - -## 高级用法 - -### 递归读取键值 - -在获取所有键值的过程中,特殊语法 `%()s` 会被应用,其中 `` 可以是相同分区或者默认分区下的键名。字符串 `%()s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。 - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### 读取父子分区 - -您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。 - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### 获取上级父分区下的所有键名 - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### 无法解析的分区 - -如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理: - -```go -cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### 读取自增键名 - -如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。 - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### 映射到结构 - -想要使用更加面向对象的方式玩转 INI 吗?好主意。 - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // 一切竟可以如此的简单。 - err = ini.MapTo(p, "path/to/ini") - // ... - - // 嗯哼?只需要映射一个分区吗? - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。 - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用? - -### 从结构反射 - -可是,我有说不能吗? - -```go -type Embeded struct { - Dates []time.Time `delim:"|"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int - GPA float64 - NeverMind string `ini:"-"` - *Embeded -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -瞧瞧,奇迹发生了。 - -```ini -NAME = Unknwon -Male = true -Age = 21 -GPA = 2.8 - -[Embeded] -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### 名称映射器(Name Mapper) - -为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。 - -目前有 2 款内置的映射器: - -- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。 -- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。 - -使用方法: - -```go -type Info struct{ - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。 - -#### 值映射器(Value Mapper) - -值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。 - -#### 映射/反射的其它说明 - -任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚! - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## 获取帮助 - -- [API 文档](https://gowalker.org/gopkg.in/ini.v1) -- [创建工单](https://github.com/go-ini/ini/issues/new) - -## 常见问题 - -### 字段 `BlockMode` 是什么? - -默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。 - -### 为什么要写另一个 INI 解析库? - -许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。 - -为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了) diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go deleted file mode 100644 index 80afe7431..000000000 --- a/vendor/github.com/go-ini/ini/error.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "fmt" -) - -type ErrDelimiterNotFound struct { - Line string -} - -func IsErrDelimiterNotFound(err error) bool { - _, ok := err.(ErrDelimiterNotFound) - return ok -} - -func (err ErrDelimiterNotFound) Error() string { - return fmt.Sprintf("key-value delimiter not found: %s", err.Line) -} diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go deleted file mode 100644 index 77e0dbde6..000000000 --- a/vendor/github.com/go-ini/ini/ini.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -// Package ini provides INI file read and write functionality in Go. -package ini - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -const ( - // Name for default section. You can use this constant or the string literal. - // In most of cases, an empty string is all you need to access the section. - DEFAULT_SECTION = "DEFAULT" - - // Maximum allowed depth when recursively substituing variable names. - _DEPTH_VALUES = 99 - _VERSION = "1.23.1" -) - -// Version returns current package version literal. -func Version() string { - return _VERSION -} - -var ( - // Delimiter to determine or compose a new line. - // This variable will be changed to "\r\n" automatically on Windows - // at package init time. - LineBreak = "\n" - - // Variable regexp pattern: %(variable)s - varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`) - - // Indicate whether to align "=" sign with spaces to produce pretty output - // or reduce all possible spaces for compact format. - PrettyFormat = true - - // Explicitly write DEFAULT section header - DefaultHeader = false -) - -func init() { - if runtime.GOOS == "windows" { - LineBreak = "\r\n" - } -} - -func inSlice(str string, s []string) bool { - for _, v := range s { - if str == v { - return true - } - } - return false -} - -// dataSource is an interface that returns object which can be read and closed. -type dataSource interface { - ReadCloser() (io.ReadCloser, error) -} - -// sourceFile represents an object that contains content on the local file system. -type sourceFile struct { - name string -} - -func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) { - return os.Open(s.name) -} - -type bytesReadCloser struct { - reader io.Reader -} - -func (rc *bytesReadCloser) Read(p []byte) (n int, err error) { - return rc.reader.Read(p) -} - -func (rc *bytesReadCloser) Close() error { - return nil -} - -// sourceData represents an object that contains content in memory. -type sourceData struct { - data []byte -} - -func (s *sourceData) ReadCloser() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(s.data)), nil -} - -// sourceReadCloser represents an input stream with Close method. -type sourceReadCloser struct { - reader io.ReadCloser -} - -func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { - return s.reader, nil -} - -// File represents a combination of a or more INI file(s) in memory. -type File struct { - // Should make things safe, but sometimes doesn't matter. - BlockMode bool - // Make sure data is safe in multiple goroutines. - lock sync.RWMutex - - // Allow combination of multiple data sources. - dataSources []dataSource - // Actual data is stored here. - sections map[string]*Section - - // To keep data in order. - sectionList []string - - options LoadOptions - - NameMapper - ValueMapper -} - -// newFile initializes File object with given data sources. -func newFile(dataSources []dataSource, opts LoadOptions) *File { - return &File{ - BlockMode: true, - dataSources: dataSources, - sections: make(map[string]*Section), - sectionList: make([]string, 0, 10), - options: opts, - } -} - -func parseDataSource(source interface{}) (dataSource, error) { - switch s := source.(type) { - case string: - return sourceFile{s}, nil - case []byte: - return &sourceData{s}, nil - case io.ReadCloser: - return &sourceReadCloser{s}, nil - default: - return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s) - } -} - -type LoadOptions struct { - // Loose indicates whether the parser should ignore nonexistent files or return error. - Loose bool - // Insensitive indicates whether the parser forces all section and key names to lowercase. - Insensitive bool - // IgnoreContinuation indicates whether to ignore continuation lines while parsing. - IgnoreContinuation bool - // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing. - // This type of keys are mostly used in my.cnf. - AllowBooleanKeys bool - // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise - // conform to key/value pairs. Specify the names of those blocks here. - UnparseableSections []string -} - -func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) { - sources := make([]dataSource, len(others)+1) - sources[0], err = parseDataSource(source) - if err != nil { - return nil, err - } - for i := range others { - sources[i+1], err = parseDataSource(others[i]) - if err != nil { - return nil, err - } - } - f := newFile(sources, opts) - if err = f.Reload(); err != nil { - return nil, err - } - return f, nil -} - -// Load loads and parses from INI data sources. -// Arguments can be mixed of file name with string type, or raw data in []byte. -// It will return error if list contains nonexistent files. -func Load(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{}, source, others...) -} - -// LooseLoad has exactly same functionality as Load function -// except it ignores nonexistent files instead of returning error. -func LooseLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Loose: true}, source, others...) -} - -// InsensitiveLoad has exactly same functionality as Load function -// except it forces all section and key names to be lowercased. -func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Insensitive: true}, source, others...) -} - -// Empty returns an empty file object. -func Empty() *File { - // Ignore error here, we sure our data is good. - f, _ := Load([]byte("")) - return f -} - -// NewSection creates a new section. -func (f *File) NewSection(name string) (*Section, error) { - if len(name) == 0 { - return nil, errors.New("error creating new section: empty section name") - } else if f.options.Insensitive && name != DEFAULT_SECTION { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if inSlice(name, f.sectionList) { - return f.sections[name], nil - } - - f.sectionList = append(f.sectionList, name) - f.sections[name] = newSection(f, name) - return f.sections[name], nil -} - -// NewRawSection creates a new section with an unparseable body. -func (f *File) NewRawSection(name, body string) (*Section, error) { - section, err := f.NewSection(name) - if err != nil { - return nil, err - } - - section.isRawSection = true - section.rawBody = body - return section, nil -} - -// NewSections creates a list of sections. -func (f *File) NewSections(names ...string) (err error) { - for _, name := range names { - if _, err = f.NewSection(name); err != nil { - return err - } - } - return nil -} - -// GetSection returns section by given name. -func (f *File) GetSection(name string) (*Section, error) { - if len(name) == 0 { - name = DEFAULT_SECTION - } else if f.options.Insensitive { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sec := f.sections[name] - if sec == nil { - return nil, fmt.Errorf("section '%s' does not exist", name) - } - return sec, nil -} - -// Section assumes named section exists and returns a zero-value when not. -func (f *File) Section(name string) *Section { - sec, err := f.GetSection(name) - if err != nil { - // Note: It's OK here because the only possible error is empty section name, - // but if it's empty, this piece of code won't be executed. - sec, _ = f.NewSection(name) - return sec - } - return sec -} - -// Section returns list of Section. -func (f *File) Sections() []*Section { - sections := make([]*Section, len(f.sectionList)) - for i := range f.sectionList { - sections[i] = f.Section(f.sectionList[i]) - } - return sections -} - -// SectionStrings returns list of section names. -func (f *File) SectionStrings() []string { - list := make([]string, len(f.sectionList)) - copy(list, f.sectionList) - return list -} - -// DeleteSection deletes a section. -func (f *File) DeleteSection(name string) { - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if len(name) == 0 { - name = DEFAULT_SECTION - } - - for i, s := range f.sectionList { - if s == name { - f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...) - delete(f.sections, name) - return - } - } -} - -func (f *File) reload(s dataSource) error { - r, err := s.ReadCloser() - if err != nil { - return err - } - defer r.Close() - - return f.parse(r) -} - -// Reload reloads and parses all data sources. -func (f *File) Reload() (err error) { - for _, s := range f.dataSources { - if err = f.reload(s); err != nil { - // In loose mode, we create an empty default section for nonexistent files. - if os.IsNotExist(err) && f.options.Loose { - f.parse(bytes.NewBuffer(nil)) - continue - } - return err - } - } - return nil -} - -// Append appends one or more data sources and reloads automatically. -func (f *File) Append(source interface{}, others ...interface{}) error { - ds, err := parseDataSource(source) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - for _, s := range others { - ds, err = parseDataSource(s) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - } - return f.Reload() -} - -// WriteToIndent writes content into io.Writer with given indention. -// If PrettyFormat has been set to be true, -// it will align "=" sign with spaces under each section. -func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) { - equalSign := "=" - if PrettyFormat { - equalSign = " = " - } - - // Use buffer to make sure target is safe until finish encoding. - buf := bytes.NewBuffer(nil) - for i, sname := range f.sectionList { - sec := f.Section(sname) - if len(sec.Comment) > 0 { - if sec.Comment[0] != '#' && sec.Comment[0] != ';' { - sec.Comment = "; " + sec.Comment - } - if _, err = buf.WriteString(sec.Comment + LineBreak); err != nil { - return 0, err - } - } - - if i > 0 || DefaultHeader { - if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil { - return 0, err - } - } else { - // Write nothing if default section is empty - if len(sec.keyList) == 0 { - continue - } - } - - if sec.isRawSection { - if _, err = buf.WriteString(sec.rawBody); err != nil { - return 0, err - } - continue - } - - // Count and generate alignment length and buffer spaces using the - // longest key. Keys may be modifed if they contain certain characters so - // we need to take that into account in our calculation. - alignLength := 0 - if PrettyFormat { - for _, kname := range sec.keyList { - keyLength := len(kname) - // First case will surround key by ` and second by """ - if strings.ContainsAny(kname, "\"=:") { - keyLength += 2 - } else if strings.Contains(kname, "`") { - keyLength += 6 - } - - if keyLength > alignLength { - alignLength = keyLength - } - } - } - alignSpaces := bytes.Repeat([]byte(" "), alignLength) - - for _, kname := range sec.keyList { - key := sec.Key(kname) - if len(key.Comment) > 0 { - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - if key.Comment[0] != '#' && key.Comment[0] != ';' { - key.Comment = "; " + key.Comment - } - if _, err = buf.WriteString(key.Comment + LineBreak); err != nil { - return 0, err - } - } - - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - switch { - case key.isAutoIncrement: - kname = "-" - case strings.ContainsAny(kname, "\"=:"): - kname = "`" + kname + "`" - case strings.Contains(kname, "`"): - kname = `"""` + kname + `"""` - } - if _, err = buf.WriteString(kname); err != nil { - return 0, err - } - - if key.isBooleanType { - continue - } - - // Write out alignment spaces before "=" sign - if PrettyFormat { - buf.Write(alignSpaces[:alignLength-len(kname)]) - } - - val := key.value - // In case key value contains "\n", "`", "\"", "#" or ";" - if strings.ContainsAny(val, "\n`") { - val = `"""` + val + `"""` - } else if strings.ContainsAny(val, "#;") { - val = "`" + val + "`" - } - if _, err = buf.WriteString(equalSign + val + LineBreak); err != nil { - return 0, err - } - } - - // Put a line between sections - if _, err = buf.WriteString(LineBreak); err != nil { - return 0, err - } - } - - return buf.WriteTo(w) -} - -// WriteTo writes file content into io.Writer. -func (f *File) WriteTo(w io.Writer) (int64, error) { - return f.WriteToIndent(w, "") -} - -// SaveToIndent writes content to file system with given value indention. -func (f *File) SaveToIndent(filename, indent string) error { - // Note: Because we are truncating with os.Create, - // so it's safer to save to a temporary file location and rename afte done. - tmpPath := filename + "." + strconv.Itoa(time.Now().Nanosecond()) + ".tmp" - defer os.Remove(tmpPath) - - fw, err := os.Create(tmpPath) - if err != nil { - return err - } - - if _, err = f.WriteToIndent(fw, indent); err != nil { - fw.Close() - return err - } - fw.Close() - - // Remove old file and rename the new one. - os.Remove(filename) - return os.Rename(tmpPath, filename) -} - -// SaveTo writes content to file system. -func (f *File) SaveTo(filename string) error { - return f.SaveToIndent(filename, "") -} diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go deleted file mode 100644 index 9738c55a2..000000000 --- a/vendor/github.com/go-ini/ini/key.go +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "fmt" - "strconv" - "strings" - "time" -) - -// Key represents a key under a section. -type Key struct { - s *Section - name string - value string - isAutoIncrement bool - isBooleanType bool - - Comment string -} - -// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv -type ValueMapper func(string) string - -// Name returns name of key. -func (k *Key) Name() string { - return k.name -} - -// Value returns raw value of key for performance purpose. -func (k *Key) Value() string { - return k.value -} - -// String returns string representation of value. -func (k *Key) String() string { - val := k.value - if k.s.f.ValueMapper != nil { - val = k.s.f.ValueMapper(val) - } - if strings.Index(val, "%") == -1 { - return val - } - - for i := 0; i < _DEPTH_VALUES; i++ { - vr := varPattern.FindString(val) - if len(vr) == 0 { - break - } - - // Take off leading '%(' and trailing ')s'. - noption := strings.TrimLeft(vr, "%(") - noption = strings.TrimRight(noption, ")s") - - // Search in the same section. - nk, err := k.s.GetKey(noption) - if err != nil { - // Search again in default section. - nk, _ = k.s.f.Section("").GetKey(noption) - } - - // Substitute by new value and take off leading '%(' and trailing ')s'. - val = strings.Replace(val, vr, nk.value, -1) - } - return val -} - -// Validate accepts a validate function which can -// return modifed result as key value. -func (k *Key) Validate(fn func(string) string) string { - return fn(k.String()) -} - -// parseBool returns the boolean value represented by the string. -// -// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, -// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. -// Any other value returns an error. -func parseBool(str string) (value bool, err error) { - switch str { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": - return false, nil - } - return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) -} - -// Bool returns bool type value. -func (k *Key) Bool() (bool, error) { - return parseBool(k.String()) -} - -// Float64 returns float64 type value. -func (k *Key) Float64() (float64, error) { - return strconv.ParseFloat(k.String(), 64) -} - -// Int returns int type value. -func (k *Key) Int() (int, error) { - return strconv.Atoi(k.String()) -} - -// Int64 returns int64 type value. -func (k *Key) Int64() (int64, error) { - return strconv.ParseInt(k.String(), 10, 64) -} - -// Uint returns uint type valued. -func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 10, 64) - return uint(u), e -} - -// Uint64 returns uint64 type value. -func (k *Key) Uint64() (uint64, error) { - return strconv.ParseUint(k.String(), 10, 64) -} - -// Duration returns time.Duration type value. -func (k *Key) Duration() (time.Duration, error) { - return time.ParseDuration(k.String()) -} - -// TimeFormat parses with given format and returns time.Time type value. -func (k *Key) TimeFormat(format string) (time.Time, error) { - return time.Parse(format, k.String()) -} - -// Time parses with RFC3339 format and returns time.Time type value. -func (k *Key) Time() (time.Time, error) { - return k.TimeFormat(time.RFC3339) -} - -// MustString returns default value if key value is empty. -func (k *Key) MustString(defaultVal string) string { - val := k.String() - if len(val) == 0 { - k.value = defaultVal - return defaultVal - } - return val -} - -// MustBool always returns value without error, -// it returns false if error occurs. -func (k *Key) MustBool(defaultVal ...bool) bool { - val, err := k.Bool() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatBool(defaultVal[0]) - return defaultVal[0] - } - return val -} - -// MustFloat64 always returns value without error, -// it returns 0.0 if error occurs. -func (k *Key) MustFloat64(defaultVal ...float64) float64 { - val, err := k.Float64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) - return defaultVal[0] - } - return val -} - -// MustInt always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt(defaultVal ...int) int { - val, err := k.Int() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(int64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustInt64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt64(defaultVal ...int64) int64 { - val, err := k.Int64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustUint always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint(defaultVal ...uint) uint { - val, err := k.Uint() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustUint64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint64(defaultVal ...uint64) uint64 { - val, err := k.Uint64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustDuration always returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { - val, err := k.Duration() - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].String() - return defaultVal[0] - } - return val -} - -// MustTimeFormat always parses with given format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { - val, err := k.TimeFormat(format) - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].Format(format) - return defaultVal[0] - } - return val -} - -// MustTime always parses with RFC3339 format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTime(defaultVal ...time.Time) time.Time { - return k.MustTimeFormat(time.RFC3339, defaultVal...) -} - -// In always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) In(defaultVal string, candidates []string) string { - val := k.String() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InFloat64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { - val := k.MustFloat64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt(defaultVal int, candidates []int) int { - val := k.MustInt() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { - val := k.MustInt64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint(defaultVal uint, candidates []uint) uint { - val := k.MustUint() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { - val := k.MustUint64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTimeFormat always parses with given format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { - val := k.MustTimeFormat(format) - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTime always parses with RFC3339 format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { - return k.InTimeFormat(time.RFC3339, defaultVal, candidates) -} - -// RangeFloat64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { - val := k.MustFloat64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt(defaultVal, min, max int) int { - val := k.MustInt() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { - val := k.MustInt64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeTimeFormat checks if value with given format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { - val := k.MustTimeFormat(format) - if val.Unix() < min.Unix() || val.Unix() > max.Unix() { - return defaultVal - } - return val -} - -// RangeTime checks if value with RFC3339 format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { - return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) -} - -// Strings returns list of string divided by given delimiter. -func (k *Key) Strings(delim string) []string { - str := k.String() - if len(str) == 0 { - return []string{} - } - - vals := strings.Split(str, delim) - for i := range vals { - vals[i] = strings.TrimSpace(vals[i]) - } - return vals -} - -// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Float64s(delim string) []float64 { - vals, _ := k.getFloat64s(delim, true, false) - return vals -} - -// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Ints(delim string) []int { - vals, _ := k.getInts(delim, true, false) - return vals -} - -// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Int64s(delim string) []int64 { - vals, _ := k.getInt64s(delim, true, false) - return vals -} - -// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uints(delim string) []uint { - vals, _ := k.getUints(delim, true, false) - return vals -} - -// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uint64s(delim string) []uint64 { - vals, _ := k.getUint64s(delim, true, false) - return vals -} - -// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) TimesFormat(format, delim string) []time.Time { - vals, _ := k.getTimesFormat(format, delim, true, false) - return vals -} - -// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) Times(delim string) []time.Time { - return k.TimesFormat(time.RFC3339, delim) -} - -// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then -// it will not be included to result list. -func (k *Key) ValidFloat64s(delim string) []float64 { - vals, _ := k.getFloat64s(delim, false, false) - return vals -} - -// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will -// not be included to result list. -func (k *Key) ValidInts(delim string) []int { - vals, _ := k.getInts(delim, false, false) - return vals -} - -// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, -// then it will not be included to result list. -func (k *Key) ValidInt64s(delim string) []int64 { - vals, _ := k.getInt64s(delim, false, false) - return vals -} - -// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, -// then it will not be included to result list. -func (k *Key) ValidUints(delim string) []uint { - vals, _ := k.getUints(delim, false, false) - return vals -} - -// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned -// integer, then it will not be included to result list. -func (k *Key) ValidUint64s(delim string) []uint64 { - vals, _ := k.getUint64s(delim, false, false) - return vals -} - -// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimesFormat(format, delim string) []time.Time { - vals, _ := k.getTimesFormat(format, delim, false, false) - return vals -} - -// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimes(delim string) []time.Time { - return k.ValidTimesFormat(time.RFC3339, delim) -} - -// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictFloat64s(delim string) ([]float64, error) { - return k.getFloat64s(delim, false, true) -} - -// StrictInts returns list of int divided by given delimiter or error on first invalid input. -func (k *Key) StrictInts(delim string) ([]int, error) { - return k.getInts(delim, false, true) -} - -// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictInt64s(delim string) ([]int64, error) { - return k.getInt64s(delim, false, true) -} - -// StrictUints returns list of uint divided by given delimiter or error on first invalid input. -func (k *Key) StrictUints(delim string) ([]uint, error) { - return k.getUints(delim, false, true) -} - -// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictUint64s(delim string) ([]uint64, error) { - return k.getUint64s(delim, false, true) -} - -// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { - return k.getTimesFormat(format, delim, false, true) -} - -// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimes(delim string) ([]time.Time, error) { - return k.StrictTimesFormat(time.RFC3339, delim) -} - -// getFloat64s returns list of float64 divided by given delimiter. -func (k *Key) getFloat64s(delim string, addInvalid, returnOnInvalid bool) ([]float64, error) { - strs := k.Strings(delim) - vals := make([]float64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseFloat(str, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// getInts returns list of int divided by given delimiter. -func (k *Key) getInts(delim string, addInvalid, returnOnInvalid bool) ([]int, error) { - strs := k.Strings(delim) - vals := make([]int, 0, len(strs)) - for _, str := range strs { - val, err := strconv.Atoi(str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// getInt64s returns list of int64 divided by given delimiter. -func (k *Key) getInt64s(delim string, addInvalid, returnOnInvalid bool) ([]int64, error) { - strs := k.Strings(delim) - vals := make([]int64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseInt(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// getUints returns list of uint divided by given delimiter. -func (k *Key) getUints(delim string, addInvalid, returnOnInvalid bool) ([]uint, error) { - strs := k.Strings(delim) - vals := make([]uint, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 0) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, uint(val)) - } - } - return vals, nil -} - -// getUint64s returns list of uint64 divided by given delimiter. -func (k *Key) getUint64s(delim string, addInvalid, returnOnInvalid bool) ([]uint64, error) { - strs := k.Strings(delim) - vals := make([]uint64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// getTimesFormat parses with given format and returns list of time.Time divided by given delimiter. -func (k *Key) getTimesFormat(format, delim string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { - strs := k.Strings(delim) - vals := make([]time.Time, 0, len(strs)) - for _, str := range strs { - val, err := time.Parse(format, str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// SetValue changes key value. -func (k *Key) SetValue(v string) { - if k.s.f.BlockMode { - k.s.f.lock.Lock() - defer k.s.f.lock.Unlock() - } - - k.value = v - k.s.keysHash[k.name] = v -} diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go deleted file mode 100644 index b0aabe33b..000000000 --- a/vendor/github.com/go-ini/ini/parser.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2015 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strconv" - "strings" - "unicode" -) - -type tokenType int - -const ( - _TOKEN_INVALID tokenType = iota - _TOKEN_COMMENT - _TOKEN_SECTION - _TOKEN_KEY -) - -type parser struct { - buf *bufio.Reader - isEOF bool - count int - comment *bytes.Buffer -} - -func newParser(r io.Reader) *parser { - return &parser{ - buf: bufio.NewReader(r), - count: 1, - comment: &bytes.Buffer{}, - } -} - -// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. -// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding -func (p *parser) BOM() error { - mask, err := p.buf.Peek(2) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 2 { - return nil - } - - switch { - case mask[0] == 254 && mask[1] == 255: - fallthrough - case mask[0] == 255 && mask[1] == 254: - p.buf.Read(mask) - case mask[0] == 239 && mask[1] == 187: - mask, err := p.buf.Peek(3) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 3 { - return nil - } - if mask[2] == 191 { - p.buf.Read(mask) - } - } - return nil -} - -func (p *parser) readUntil(delim byte) ([]byte, error) { - data, err := p.buf.ReadBytes(delim) - if err != nil { - if err == io.EOF { - p.isEOF = true - } else { - return nil, err - } - } - return data, nil -} - -func cleanComment(in []byte) ([]byte, bool) { - i := bytes.IndexAny(in, "#;") - if i == -1 { - return nil, false - } - return in[i:], true -} - -func readKeyName(in []byte) (string, int, error) { - line := string(in) - - // Check if key name surrounded by quotes. - var keyQuote string - if line[0] == '"' { - if len(line) > 6 && string(line[0:3]) == `"""` { - keyQuote = `"""` - } else { - keyQuote = `"` - } - } else if line[0] == '`' { - keyQuote = "`" - } - - // Get out key name - endIdx := -1 - if len(keyQuote) > 0 { - startIdx := len(keyQuote) - // FIXME: fail case -> """"""name"""=value - pos := strings.Index(line[startIdx:], keyQuote) - if pos == -1 { - return "", -1, fmt.Errorf("missing closing key quote: %s", line) - } - pos += startIdx - - // Find key-value delimiter - i := strings.IndexAny(line[pos+startIdx:], "=:") - if i < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - endIdx = pos + i - return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil - } - - endIdx = strings.IndexAny(line, "=:") - if endIdx < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil -} - -func (p *parser) readMultilines(line, val, valQuote string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := string(data) - - pos := strings.LastIndex(next, valQuote) - if pos > -1 { - val += next[:pos] - - comment, has := cleanComment([]byte(next[pos:])) - if has { - p.comment.Write(bytes.TrimSpace(comment)) - } - break - } - val += next - if p.isEOF { - return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) - } - } - return val, nil -} - -func (p *parser) readContinuationLines(val string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := strings.TrimSpace(string(data)) - - if len(next) == 0 { - break - } - val += next - if val[len(val)-1] != '\\' { - break - } - val = val[:len(val)-1] - } - return val, nil -} - -// hasSurroundedQuote check if and only if the first and last characters -// are quotes \" or \'. -// It returns false if any other parts also contain same kind of quotes. -func hasSurroundedQuote(in string, quote byte) bool { - return len(in) > 2 && in[0] == quote && in[len(in)-1] == quote && - strings.IndexByte(in[1:], quote) == len(in)-2 -} - -func (p *parser) readValue(in []byte, ignoreContinuation bool) (string, error) { - line := strings.TrimLeftFunc(string(in), unicode.IsSpace) - if len(line) == 0 { - return "", nil - } - - var valQuote string - if len(line) > 3 && string(line[0:3]) == `"""` { - valQuote = `"""` - } else if line[0] == '`' { - valQuote = "`" - } - - if len(valQuote) > 0 { - startIdx := len(valQuote) - pos := strings.LastIndex(line[startIdx:], valQuote) - // Check for multi-line value - if pos == -1 { - return p.readMultilines(line, line[startIdx:], valQuote) - } - - return line[startIdx : pos+startIdx], nil - } - - // Won't be able to reach here if value only contains whitespace. - line = strings.TrimSpace(line) - - // Check continuation lines when desired. - if !ignoreContinuation && line[len(line)-1] == '\\' { - return p.readContinuationLines(line[:len(line)-1]) - } - - i := strings.IndexAny(line, "#;") - if i > -1 { - p.comment.WriteString(line[i:]) - line = strings.TrimSpace(line[:i]) - } - - // Trim single quotes - if hasSurroundedQuote(line, '\'') || - hasSurroundedQuote(line, '"') { - line = line[1 : len(line)-1] - } - return line, nil -} - -// parse parses data through an io.Reader. -func (f *File) parse(reader io.Reader) (err error) { - p := newParser(reader) - if err = p.BOM(); err != nil { - return fmt.Errorf("BOM: %v", err) - } - - // Ignore error because default section name is never empty string. - section, _ := f.NewSection(DEFAULT_SECTION) - - var line []byte - var inUnparseableSection bool - for !p.isEOF { - line, err = p.readUntil('\n') - if err != nil { - return err - } - - line = bytes.TrimLeftFunc(line, unicode.IsSpace) - if len(line) == 0 { - continue - } - - // Comments - if line[0] == '#' || line[0] == ';' { - // Note: we do not care ending line break, - // it is needed for adding second line, - // so just clean it once at the end when set to value. - p.comment.Write(line) - continue - } - - // Section - if line[0] == '[' { - // Read to the next ']' (TODO: support quoted strings) - // TODO(unknwon): use LastIndexByte when stop supporting Go1.4 - closeIdx := bytes.LastIndex(line, []byte("]")) - if closeIdx == -1 { - return fmt.Errorf("unclosed section: %s", line) - } - - name := string(line[1:closeIdx]) - section, err = f.NewSection(name) - if err != nil { - return err - } - - comment, has := cleanComment(line[closeIdx+1:]) - if has { - p.comment.Write(comment) - } - - section.Comment = strings.TrimSpace(p.comment.String()) - - // Reset aotu-counter and comments - p.comment.Reset() - p.count = 1 - - inUnparseableSection = false - for i := range f.options.UnparseableSections { - if f.options.UnparseableSections[i] == name || - (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { - inUnparseableSection = true - continue - } - } - continue - } - - if inUnparseableSection { - section.isRawSection = true - section.rawBody += string(line) - continue - } - - kname, offset, err := readKeyName(line) - if err != nil { - // Treat as boolean key when desired, and whole line is key name. - if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys { - key, err := section.NewKey(string(line), "true") - if err != nil { - return err - } - key.isBooleanType = true - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - continue - } - return err - } - - // Auto increment. - isAutoIncr := false - if kname == "-" { - isAutoIncr = true - kname = "#" + strconv.Itoa(p.count) - p.count++ - } - - key, err := section.NewKey(kname, "") - if err != nil { - return err - } - key.isAutoIncrement = isAutoIncr - - value, err := p.readValue(line[offset:], f.options.IgnoreContinuation) - if err != nil { - return err - } - key.SetValue(value) - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - } - return nil -} diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go deleted file mode 100644 index 45d2f3bfd..000000000 --- a/vendor/github.com/go-ini/ini/section.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "errors" - "fmt" - "strings" -) - -// Section represents a config section. -type Section struct { - f *File - Comment string - name string - keys map[string]*Key - keyList []string - keysHash map[string]string - - isRawSection bool - rawBody string -} - -func newSection(f *File, name string) *Section { - return &Section{ - f: f, - name: name, - keys: make(map[string]*Key), - keyList: make([]string, 0, 10), - keysHash: make(map[string]string), - } -} - -// Name returns name of Section. -func (s *Section) Name() string { - return s.name -} - -// Body returns rawBody of Section if the section was marked as unparseable. -// It still follows the other rules of the INI format surrounding leading/trailing whitespace. -func (s *Section) Body() string { - return strings.TrimSpace(s.rawBody) -} - -// NewKey creates a new key to given section. -func (s *Section) NewKey(name, val string) (*Key, error) { - if len(name) == 0 { - return nil, errors.New("error creating new key: empty key name") - } else if s.f.options.Insensitive { - name = strings.ToLower(name) - } - - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - if inSlice(name, s.keyList) { - s.keys[name].value = val - return s.keys[name], nil - } - - s.keyList = append(s.keyList, name) - s.keys[name] = &Key{ - s: s, - name: name, - value: val, - } - s.keysHash[name] = val - return s.keys[name], nil -} - -// GetKey returns key in section by given name. -func (s *Section) GetKey(name string) (*Key, error) { - // FIXME: change to section level lock? - if s.f.BlockMode { - s.f.lock.RLock() - } - if s.f.options.Insensitive { - name = strings.ToLower(name) - } - key := s.keys[name] - if s.f.BlockMode { - s.f.lock.RUnlock() - } - - if key == nil { - // Check if it is a child-section. - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - return sec.GetKey(name) - } else { - break - } - } - return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) - } - return key, nil -} - -// HasKey returns true if section contains a key with given name. -func (s *Section) HasKey(name string) bool { - key, _ := s.GetKey(name) - return key != nil -} - -// Haskey is a backwards-compatible name for HasKey. -func (s *Section) Haskey(name string) bool { - return s.HasKey(name) -} - -// HasValue returns true if section contains given raw value. -func (s *Section) HasValue(value string) bool { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - for _, k := range s.keys { - if value == k.value { - return true - } - } - return false -} - -// Key assumes named Key exists in section and returns a zero-value when not. -func (s *Section) Key(name string) *Key { - key, err := s.GetKey(name) - if err != nil { - // It's OK here because the only possible error is empty key name, - // but if it's empty, this piece of code won't be executed. - key, _ = s.NewKey(name, "") - return key - } - return key -} - -// Keys returns list of keys of section. -func (s *Section) Keys() []*Key { - keys := make([]*Key, len(s.keyList)) - for i := range s.keyList { - keys[i] = s.Key(s.keyList[i]) - } - return keys -} - -// ParentKeys returns list of keys of parent section. -func (s *Section) ParentKeys() []*Key { - var parentKeys []*Key - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - parentKeys = append(parentKeys, sec.Keys()...) - } else { - break - } - - } - return parentKeys -} - -// KeyStrings returns list of key names of section. -func (s *Section) KeyStrings() []string { - list := make([]string, len(s.keyList)) - copy(list, s.keyList) - return list -} - -// KeysHash returns keys hash consisting of names and values. -func (s *Section) KeysHash() map[string]string { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - hash := map[string]string{} - for key, value := range s.keysHash { - hash[key] = value - } - return hash -} - -// DeleteKey deletes a key from section. -func (s *Section) DeleteKey(name string) { - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - for i, k := range s.keyList { - if k == name { - s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) - delete(s.keys, name) - return - } - } -} diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go deleted file mode 100644 index 5ef38d865..000000000 --- a/vendor/github.com/go-ini/ini/struct.go +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "time" - "unicode" -) - -// NameMapper represents a ini tag name mapper. -type NameMapper func(string) string - -// Built-in name getters. -var ( - // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. - AllCapsUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - } - newstr = append(newstr, unicode.ToUpper(chr)) - } - return string(newstr) - } - // TitleUnderscore converts to format title_underscore. - TitleUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - chr -= ('A' - 'a') - } - newstr = append(newstr, chr) - } - return string(newstr) - } -) - -func (s *Section) parseFieldName(raw, actual string) string { - if len(actual) > 0 { - return actual - } - if s.f.NameMapper != nil { - return s.f.NameMapper(raw) - } - return raw -} - -func parseDelim(actual string) string { - if len(actual) > 0 { - return actual - } - return "," -} - -var reflectTime = reflect.TypeOf(time.Now()).Kind() - -// setSliceWithProperType sets proper values to slice based on its type. -func setSliceWithProperType(key *Key, field reflect.Value, delim string) error { - strs := key.Strings(delim) - numVals := len(strs) - if numVals == 0 { - return nil - } - - var vals interface{} - - sliceOf := field.Type().Elem().Kind() - switch sliceOf { - case reflect.String: - vals = strs - case reflect.Int: - vals = key.Ints(delim) - case reflect.Int64: - vals = key.Int64s(delim) - case reflect.Uint: - vals = key.Uints(delim) - case reflect.Uint64: - vals = key.Uint64s(delim) - case reflect.Float64: - vals = key.Float64s(delim) - case reflectTime: - vals = key.Times(delim) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - - slice := reflect.MakeSlice(field.Type(), numVals, numVals) - for i := 0; i < numVals; i++ { - switch sliceOf { - case reflect.String: - slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i])) - case reflect.Int: - slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i])) - case reflect.Int64: - slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i])) - case reflect.Uint: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i])) - case reflect.Uint64: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i])) - case reflect.Float64: - slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i])) - case reflectTime: - slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i])) - } - } - field.Set(slice) - return nil -} - -// setWithProperType sets proper value to field based on its type, -// but it does not return error for failing parsing, -// because we want to use default value that is already assigned to strcut. -func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { - switch t.Kind() { - case reflect.String: - if len(key.String()) == 0 { - return nil - } - field.SetString(key.String()) - case reflect.Bool: - boolVal, err := key.Bool() - if err != nil { - return nil - } - field.SetBool(boolVal) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - intVal, err := key.Int64() - if err != nil || intVal == 0 { - return nil - } - field.SetInt(intVal) - // byte is an alias for uint8, so supporting uint8 breaks support for byte - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - uintVal, err := key.Uint64() - if err != nil { - return nil - } - field.SetUint(uintVal) - - case reflect.Float32, reflect.Float64: - floatVal, err := key.Float64() - if err != nil { - return nil - } - field.SetFloat(floatVal) - case reflectTime: - timeVal, err := key.Time() - if err != nil { - return nil - } - field.Set(reflect.ValueOf(timeVal)) - case reflect.Slice: - return setSliceWithProperType(key, field, delim) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -func (s *Section) mapTo(val reflect.Value) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - opts := strings.SplitN(tag, ",", 2) // strip off possible omitempty - fieldName := s.parseFieldName(tpField.Name, opts[0]) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous - isStruct := tpField.Type.Kind() == reflect.Struct - if isAnonymous { - field.Set(reflect.New(tpField.Type.Elem())) - } - - if isAnonymous || isStruct { - if sec, err := s.f.GetSection(fieldName); err == nil { - if err = sec.mapTo(field); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - continue - } - } - - if key, err := s.GetKey(fieldName); err == nil { - if err = setWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - } - } - return nil -} - -// MapTo maps section to given struct. -func (s *Section) MapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val) -} - -// MapTo maps file to given struct. -func (f *File) MapTo(v interface{}) error { - return f.Section("").MapTo(v) -} - -// MapTo maps data sources to given struct with name mapper. -func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.MapTo(v) -} - -// MapTo maps data sources to given struct. -func MapTo(v, source interface{}, others ...interface{}) error { - return MapToWithMapper(v, nil, source, others...) -} - -// reflectSliceWithProperType does the opposite thing as setSliceWithProperType. -func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { - slice := field.Slice(0, field.Len()) - if field.Len() == 0 { - return nil - } - - var buf bytes.Buffer - sliceOf := field.Type().Elem().Kind() - for i := 0; i < field.Len(); i++ { - switch sliceOf { - case reflect.String: - buf.WriteString(slice.Index(i).String()) - case reflect.Int, reflect.Int64: - buf.WriteString(fmt.Sprint(slice.Index(i).Int())) - case reflect.Uint, reflect.Uint64: - buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) - case reflect.Float64: - buf.WriteString(fmt.Sprint(slice.Index(i).Float())) - case reflectTime: - buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - buf.WriteString(delim) - } - key.SetValue(buf.String()[:buf.Len()-1]) - return nil -} - -// reflectWithProperType does the opposite thing as setWithProperType. -func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { - switch t.Kind() { - case reflect.String: - key.SetValue(field.String()) - case reflect.Bool: - key.SetValue(fmt.Sprint(field.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - key.SetValue(fmt.Sprint(field.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - key.SetValue(fmt.Sprint(field.Uint())) - case reflect.Float32, reflect.Float64: - key.SetValue(fmt.Sprint(field.Float())) - case reflectTime: - key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) - case reflect.Slice: - return reflectSliceWithProperType(key, field, delim) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -// CR: copied from encoding/json/encode.go with modifications of time.Time support. -// TODO: add more test coverage. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflectTime: - return v.Interface().(time.Time).IsZero() - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} - -func (s *Section) reflectFrom(val reflect.Value) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - opts := strings.SplitN(tag, ",", 2) - if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) { - continue - } - - fieldName := s.parseFieldName(tpField.Name, opts[0]) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) || - (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { - // Note: The only error here is section doesn't exist. - sec, err := s.f.GetSection(fieldName) - if err != nil { - // Note: fieldName can never be empty here, ignore error. - sec, _ = s.f.NewSection(fieldName) - } - if err = sec.reflectFrom(field); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - continue - } - - // Note: Same reason as secion. - key, err := s.GetKey(fieldName) - if err != nil { - key, _ = s.NewKey(fieldName, "") - } - if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - - } - return nil -} - -// ReflectFrom reflects secion from given struct. -func (s *Section) ReflectFrom(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot reflect from non-pointer struct") - } - - return s.reflectFrom(val) -} - -// ReflectFrom reflects file from given struct. -func (f *File) ReflectFrom(v interface{}) error { - return f.Section("").ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct with name mapper. -func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { - cfg.NameMapper = mapper - return cfg.ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct. -func ReflectFrom(cfg *File, v interface{}) error { - return ReflectFromWithMapper(cfg, v, nil) -} diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS new file mode 100644 index 000000000..15167cd74 --- /dev/null +++ b/vendor/github.com/golang/protobuf/AUTHORS @@ -0,0 +1,3 @@ +# This source code refers to The Go Authors for copyright purposes. +# The master list of authors is in the main Go distribution, +# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS new file mode 100644 index 000000000..1c4577e96 --- /dev/null +++ b/vendor/github.com/golang/protobuf/CONTRIBUTORS @@ -0,0 +1,3 @@ +# This source code was written by the Go contributors. +# The master list of contributors is in the main Go distribution, +# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore new file mode 100644 index 000000000..042091d9b --- /dev/null +++ b/vendor/github.com/golang/snappy/.gitignore @@ -0,0 +1,16 @@ +cmd/snappytool/snappytool +testdata/bench + +# These explicitly listed benchmark data files are for an obsolete version of +# snappy_test.go. +testdata/alice29.txt +testdata/asyoulik.txt +testdata/fireworks.jpeg +testdata/geo.protodata +testdata/html +testdata/html_x_4 +testdata/kppkn.gtb +testdata/lcet10.txt +testdata/paper-100k.pdf +testdata/plrabn12.txt +testdata/urls.10K diff --git a/vendor/github.com/golang/snappy/AUTHORS b/vendor/github.com/golang/snappy/AUTHORS new file mode 100644 index 000000000..bcfa19520 --- /dev/null +++ b/vendor/github.com/golang/snappy/AUTHORS @@ -0,0 +1,15 @@ +# This is the official list of Snappy-Go authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. + +Damian Gryski +Google Inc. +Jan Mercl <0xjnml@gmail.com> +Rodolfo Carvalho +Sebastien Binet diff --git a/vendor/github.com/golang/snappy/CONTRIBUTORS b/vendor/github.com/golang/snappy/CONTRIBUTORS new file mode 100644 index 000000000..931ae3160 --- /dev/null +++ b/vendor/github.com/golang/snappy/CONTRIBUTORS @@ -0,0 +1,37 @@ +# This is the official list of people who can contribute +# (and typically have contributed) code to the Snappy-Go repository. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# The submission process automatically checks to make sure +# that people submitting code are listed in this file (by email address). +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# http://code.google.com/legal/individual-cla-v1.0.html +# http://code.google.com/legal/corporate-cla-v1.0.html +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. + +# Names should be added to this file like so: +# Name + +# Please keep the list sorted. + +Damian Gryski +Jan Mercl <0xjnml@gmail.com> +Kai Backman +Marc-Antoine Ruel +Nigel Tao +Rob Pike +Rodolfo Carvalho +Russ Cox +Sebastien Binet diff --git a/vendor/github.com/google/go-github/LICENSE b/vendor/github.com/golang/snappy/LICENSE similarity index 95% rename from vendor/github.com/google/go-github/LICENSE rename to vendor/github.com/golang/snappy/LICENSE index 28b6486f0..6050c10f4 100644 --- a/vendor/github.com/google/go-github/LICENSE +++ b/vendor/github.com/golang/snappy/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2013 The go-github AUTHORS. All rights reserved. +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are diff --git a/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README new file mode 100644 index 000000000..cea12879a --- /dev/null +++ b/vendor/github.com/golang/snappy/README @@ -0,0 +1,107 @@ +The Snappy compression format in the Go programming language. + +To download and install from source: +$ go get github.com/golang/snappy + +Unless otherwise noted, the Snappy-Go source files are distributed +under the BSD-style license found in the LICENSE file. + + + +Benchmarks. + +The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten +or so files, the same set used by the C++ Snappy code (github.com/google/snappy +and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @ +3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29: + +"go test -test.bench=." + +_UFlat0-8 2.19GB/s ± 0% html +_UFlat1-8 1.41GB/s ± 0% urls +_UFlat2-8 23.5GB/s ± 2% jpg +_UFlat3-8 1.91GB/s ± 0% jpg_200 +_UFlat4-8 14.0GB/s ± 1% pdf +_UFlat5-8 1.97GB/s ± 0% html4 +_UFlat6-8 814MB/s ± 0% txt1 +_UFlat7-8 785MB/s ± 0% txt2 +_UFlat8-8 857MB/s ± 0% txt3 +_UFlat9-8 719MB/s ± 1% txt4 +_UFlat10-8 2.84GB/s ± 0% pb +_UFlat11-8 1.05GB/s ± 0% gaviota + +_ZFlat0-8 1.04GB/s ± 0% html +_ZFlat1-8 534MB/s ± 0% urls +_ZFlat2-8 15.7GB/s ± 1% jpg +_ZFlat3-8 740MB/s ± 3% jpg_200 +_ZFlat4-8 9.20GB/s ± 1% pdf +_ZFlat5-8 991MB/s ± 0% html4 +_ZFlat6-8 379MB/s ± 0% txt1 +_ZFlat7-8 352MB/s ± 0% txt2 +_ZFlat8-8 396MB/s ± 1% txt3 +_ZFlat9-8 327MB/s ± 1% txt4 +_ZFlat10-8 1.33GB/s ± 1% pb +_ZFlat11-8 605MB/s ± 1% gaviota + + + +"go test -test.bench=. -tags=noasm" + +_UFlat0-8 621MB/s ± 2% html +_UFlat1-8 494MB/s ± 1% urls +_UFlat2-8 23.2GB/s ± 1% jpg +_UFlat3-8 1.12GB/s ± 1% jpg_200 +_UFlat4-8 4.35GB/s ± 1% pdf +_UFlat5-8 609MB/s ± 0% html4 +_UFlat6-8 296MB/s ± 0% txt1 +_UFlat7-8 288MB/s ± 0% txt2 +_UFlat8-8 309MB/s ± 1% txt3 +_UFlat9-8 280MB/s ± 1% txt4 +_UFlat10-8 753MB/s ± 0% pb +_UFlat11-8 400MB/s ± 0% gaviota + +_ZFlat0-8 409MB/s ± 1% html +_ZFlat1-8 250MB/s ± 1% urls +_ZFlat2-8 12.3GB/s ± 1% jpg +_ZFlat3-8 132MB/s ± 0% jpg_200 +_ZFlat4-8 2.92GB/s ± 0% pdf +_ZFlat5-8 405MB/s ± 1% html4 +_ZFlat6-8 179MB/s ± 1% txt1 +_ZFlat7-8 170MB/s ± 1% txt2 +_ZFlat8-8 189MB/s ± 1% txt3 +_ZFlat9-8 164MB/s ± 1% txt4 +_ZFlat10-8 479MB/s ± 1% pb +_ZFlat11-8 270MB/s ± 1% gaviota + + + +For comparison (Go's encoded output is byte-for-byte identical to C++'s), here +are the numbers from C++ Snappy's + +make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log + +BM_UFlat/0 2.4GB/s html +BM_UFlat/1 1.4GB/s urls +BM_UFlat/2 21.8GB/s jpg +BM_UFlat/3 1.5GB/s jpg_200 +BM_UFlat/4 13.3GB/s pdf +BM_UFlat/5 2.1GB/s html4 +BM_UFlat/6 1.0GB/s txt1 +BM_UFlat/7 959.4MB/s txt2 +BM_UFlat/8 1.0GB/s txt3 +BM_UFlat/9 864.5MB/s txt4 +BM_UFlat/10 2.9GB/s pb +BM_UFlat/11 1.2GB/s gaviota + +BM_ZFlat/0 944.3MB/s html (22.31 %) +BM_ZFlat/1 501.6MB/s urls (47.78 %) +BM_ZFlat/2 14.3GB/s jpg (99.95 %) +BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %) +BM_ZFlat/4 8.3GB/s pdf (83.30 %) +BM_ZFlat/5 903.5MB/s html4 (22.52 %) +BM_ZFlat/6 336.0MB/s txt1 (57.88 %) +BM_ZFlat/7 312.3MB/s txt2 (61.91 %) +BM_ZFlat/8 353.1MB/s txt3 (54.99 %) +BM_ZFlat/9 289.9MB/s txt4 (66.26 %) +BM_ZFlat/10 1.2GB/s pb (19.68 %) +BM_ZFlat/11 527.4MB/s gaviota (37.72 %) diff --git a/vendor/github.com/golang/snappy/decode.go b/vendor/github.com/golang/snappy/decode.go new file mode 100644 index 000000000..72efb0353 --- /dev/null +++ b/vendor/github.com/golang/snappy/decode.go @@ -0,0 +1,237 @@ +// Copyright 2011 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package snappy + +import ( + "encoding/binary" + "errors" + "io" +) + +var ( + // ErrCorrupt reports that the input is invalid. + ErrCorrupt = errors.New("snappy: corrupt input") + // ErrTooLarge reports that the uncompressed length is too large. + ErrTooLarge = errors.New("snappy: decoded block is too large") + // ErrUnsupported reports that the input isn't supported. + ErrUnsupported = errors.New("snappy: unsupported input") + + errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") +) + +// DecodedLen returns the length of the decoded block. +func DecodedLen(src []byte) (int, error) { + v, _, err := decodedLen(src) + return v, err +} + +// decodedLen returns the length of the decoded block and the number of bytes +// that the length header occupied. +func decodedLen(src []byte) (blockLen, headerLen int, err error) { + v, n := binary.Uvarint(src) + if n <= 0 || v > 0xffffffff { + return 0, 0, ErrCorrupt + } + + const wordSize = 32 << (^uint(0) >> 32 & 1) + if wordSize == 32 && v > 0x7fffffff { + return 0, 0, ErrTooLarge + } + return int(v), n, nil +} + +const ( + decodeErrCodeCorrupt = 1 + decodeErrCodeUnsupportedLiteralLength = 2 +) + +// Decode returns the decoded form of src. The returned slice may be a sub- +// slice of dst if dst was large enough to hold the entire decoded block. +// Otherwise, a newly allocated slice will be returned. +// +// The dst and src must not overlap. It is valid to pass a nil dst. +func Decode(dst, src []byte) ([]byte, error) { + dLen, s, err := decodedLen(src) + if err != nil { + return nil, err + } + if dLen <= len(dst) { + dst = dst[:dLen] + } else { + dst = make([]byte, dLen) + } + switch decode(dst, src[s:]) { + case 0: + return dst, nil + case decodeErrCodeUnsupportedLiteralLength: + return nil, errUnsupportedLiteralLength + } + return nil, ErrCorrupt +} + +// NewReader returns a new Reader that decompresses from r, using the framing +// format described at +// https://github.com/google/snappy/blob/master/framing_format.txt +func NewReader(r io.Reader) *Reader { + return &Reader{ + r: r, + decoded: make([]byte, maxBlockSize), + buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), + } +} + +// Reader is an io.Reader that can read Snappy-compressed bytes. +type Reader struct { + r io.Reader + err error + decoded []byte + buf []byte + // decoded[i:j] contains decoded bytes that have not yet been passed on. + i, j int + readHeader bool +} + +// Reset discards any buffered data, resets all state, and switches the Snappy +// reader to read from r. This permits reusing a Reader rather than allocating +// a new one. +func (r *Reader) Reset(reader io.Reader) { + r.r = reader + r.err = nil + r.i = 0 + r.j = 0 + r.readHeader = false +} + +func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { + if _, r.err = io.ReadFull(r.r, p); r.err != nil { + if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { + r.err = ErrCorrupt + } + return false + } + return true +} + +// Read satisfies the io.Reader interface. +func (r *Reader) Read(p []byte) (int, error) { + if r.err != nil { + return 0, r.err + } + for { + if r.i < r.j { + n := copy(p, r.decoded[r.i:r.j]) + r.i += n + return n, nil + } + if !r.readFull(r.buf[:4], true) { + return 0, r.err + } + chunkType := r.buf[0] + if !r.readHeader { + if chunkType != chunkTypeStreamIdentifier { + r.err = ErrCorrupt + return 0, r.err + } + r.readHeader = true + } + chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 + if chunkLen > len(r.buf) { + r.err = ErrUnsupported + return 0, r.err + } + + // The chunk types are specified at + // https://github.com/google/snappy/blob/master/framing_format.txt + switch chunkType { + case chunkTypeCompressedData: + // Section 4.2. Compressed data (chunk type 0x00). + if chunkLen < checksumSize { + r.err = ErrCorrupt + return 0, r.err + } + buf := r.buf[:chunkLen] + if !r.readFull(buf, false) { + return 0, r.err + } + checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + buf = buf[checksumSize:] + + n, err := DecodedLen(buf) + if err != nil { + r.err = err + return 0, r.err + } + if n > len(r.decoded) { + r.err = ErrCorrupt + return 0, r.err + } + if _, err := Decode(r.decoded, buf); err != nil { + r.err = err + return 0, r.err + } + if crc(r.decoded[:n]) != checksum { + r.err = ErrCorrupt + return 0, r.err + } + r.i, r.j = 0, n + continue + + case chunkTypeUncompressedData: + // Section 4.3. Uncompressed data (chunk type 0x01). + if chunkLen < checksumSize { + r.err = ErrCorrupt + return 0, r.err + } + buf := r.buf[:checksumSize] + if !r.readFull(buf, false) { + return 0, r.err + } + checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 + // Read directly into r.decoded instead of via r.buf. + n := chunkLen - checksumSize + if n > len(r.decoded) { + r.err = ErrCorrupt + return 0, r.err + } + if !r.readFull(r.decoded[:n], false) { + return 0, r.err + } + if crc(r.decoded[:n]) != checksum { + r.err = ErrCorrupt + return 0, r.err + } + r.i, r.j = 0, n + continue + + case chunkTypeStreamIdentifier: + // Section 4.1. Stream identifier (chunk type 0xff). + if chunkLen != len(magicBody) { + r.err = ErrCorrupt + return 0, r.err + } + if !r.readFull(r.buf[:len(magicBody)], false) { + return 0, r.err + } + for i := 0; i < len(magicBody); i++ { + if r.buf[i] != magicBody[i] { + r.err = ErrCorrupt + return 0, r.err + } + } + continue + } + + if chunkType <= 0x7f { + // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). + r.err = ErrUnsupported + return 0, r.err + } + // Section 4.4 Padding (chunk type 0xfe). + // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). + if !r.readFull(r.buf[:chunkLen], false) { + return 0, r.err + } + } +} diff --git a/vendor/github.com/golang/snappy/decode_amd64.go b/vendor/github.com/golang/snappy/decode_amd64.go new file mode 100644 index 000000000..fcd192b84 --- /dev/null +++ b/vendor/github.com/golang/snappy/decode_amd64.go @@ -0,0 +1,14 @@ +// Copyright 2016 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine +// +build gc +// +build !noasm + +package snappy + +// decode has the same semantics as in decode_other.go. +// +//go:noescape +func decode(dst, src []byte) int diff --git a/vendor/github.com/golang/snappy/decode_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s new file mode 100644 index 000000000..e6179f65e --- /dev/null +++ b/vendor/github.com/golang/snappy/decode_amd64.s @@ -0,0 +1,490 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine +// +build gc +// +build !noasm + +#include "textflag.h" + +// The asm code generally follows the pure Go code in decode_other.go, except +// where marked with a "!!!". + +// func decode(dst, src []byte) int +// +// All local variables fit into registers. The non-zero stack size is only to +// spill registers and push args when issuing a CALL. The register allocation: +// - AX scratch +// - BX scratch +// - CX length or x +// - DX offset +// - SI &src[s] +// - DI &dst[d] +// + R8 dst_base +// + R9 dst_len +// + R10 dst_base + dst_len +// + R11 src_base +// + R12 src_len +// + R13 src_base + src_len +// - R14 used by doCopy +// - R15 used by doCopy +// +// The registers R8-R13 (marked with a "+") are set at the start of the +// function, and after a CALL returns, and are not otherwise modified. +// +// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI. +// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI. +TEXT ·decode(SB), NOSPLIT, $48-56 + // Initialize SI, DI and R8-R13. + MOVQ dst_base+0(FP), R8 + MOVQ dst_len+8(FP), R9 + MOVQ R8, DI + MOVQ R8, R10 + ADDQ R9, R10 + MOVQ src_base+24(FP), R11 + MOVQ src_len+32(FP), R12 + MOVQ R11, SI + MOVQ R11, R13 + ADDQ R12, R13 + +loop: + // for s < len(src) + CMPQ SI, R13 + JEQ end + + // CX = uint32(src[s]) + // + // switch src[s] & 0x03 + MOVBLZX (SI), CX + MOVL CX, BX + ANDL $3, BX + CMPL BX, $1 + JAE tagCopy + + // ---------------------------------------- + // The code below handles literal tags. + + // case tagLiteral: + // x := uint32(src[s] >> 2) + // switch + SHRL $2, CX + CMPL CX, $60 + JAE tagLit60Plus + + // case x < 60: + // s++ + INCQ SI + +doLit: + // This is the end of the inner "switch", when we have a literal tag. + // + // We assume that CX == x and x fits in a uint32, where x is the variable + // used in the pure Go decode_other.go code. + + // length = int(x) + 1 + // + // Unlike the pure Go code, we don't need to check if length <= 0 because + // CX can hold 64 bits, so the increment cannot overflow. + INCQ CX + + // Prepare to check if copying length bytes will run past the end of dst or + // src. + // + // AX = len(dst) - d + // BX = len(src) - s + MOVQ R10, AX + SUBQ DI, AX + MOVQ R13, BX + SUBQ SI, BX + + // !!! Try a faster technique for short (16 or fewer bytes) copies. + // + // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 { + // goto callMemmove // Fall back on calling runtime·memmove. + // } + // + // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s + // against 21 instead of 16, because it cannot assume that all of its input + // is contiguous in memory and so it needs to leave enough source bytes to + // read the next tag without refilling buffers, but Go's Decode assumes + // contiguousness (the src argument is a []byte). + CMPQ CX, $16 + JGT callMemmove + CMPQ AX, $16 + JLT callMemmove + CMPQ BX, $16 + JLT callMemmove + + // !!! Implement the copy from src to dst as a 16-byte load and store. + // (Decode's documentation says that dst and src must not overlap.) + // + // This always copies 16 bytes, instead of only length bytes, but that's + // OK. If the input is a valid Snappy encoding then subsequent iterations + // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a + // non-nil error), so the overrun will be ignored. + // + // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or + // 16-byte loads and stores. This technique probably wouldn't be as + // effective on architectures that are fussier about alignment. + MOVOU 0(SI), X0 + MOVOU X0, 0(DI) + + // d += length + // s += length + ADDQ CX, DI + ADDQ CX, SI + JMP loop + +callMemmove: + // if length > len(dst)-d || length > len(src)-s { etc } + CMPQ CX, AX + JGT errCorrupt + CMPQ CX, BX + JGT errCorrupt + + // copy(dst[d:], src[s:s+length]) + // + // This means calling runtime·memmove(&dst[d], &src[s], length), so we push + // DI, SI and CX as arguments. Coincidentally, we also need to spill those + // three registers to the stack, to save local variables across the CALL. + MOVQ DI, 0(SP) + MOVQ SI, 8(SP) + MOVQ CX, 16(SP) + MOVQ DI, 24(SP) + MOVQ SI, 32(SP) + MOVQ CX, 40(SP) + CALL runtime·memmove(SB) + + // Restore local variables: unspill registers from the stack and + // re-calculate R8-R13. + MOVQ 24(SP), DI + MOVQ 32(SP), SI + MOVQ 40(SP), CX + MOVQ dst_base+0(FP), R8 + MOVQ dst_len+8(FP), R9 + MOVQ R8, R10 + ADDQ R9, R10 + MOVQ src_base+24(FP), R11 + MOVQ src_len+32(FP), R12 + MOVQ R11, R13 + ADDQ R12, R13 + + // d += length + // s += length + ADDQ CX, DI + ADDQ CX, SI + JMP loop + +tagLit60Plus: + // !!! This fragment does the + // + // s += x - 58; if uint(s) > uint(len(src)) { etc } + // + // checks. In the asm version, we code it once instead of once per switch case. + ADDQ CX, SI + SUBQ $58, SI + MOVQ SI, BX + SUBQ R11, BX + CMPQ BX, R12 + JA errCorrupt + + // case x == 60: + CMPL CX, $61 + JEQ tagLit61 + JA tagLit62Plus + + // x = uint32(src[s-1]) + MOVBLZX -1(SI), CX + JMP doLit + +tagLit61: + // case x == 61: + // x = uint32(src[s-2]) | uint32(src[s-1])<<8 + MOVWLZX -2(SI), CX + JMP doLit + +tagLit62Plus: + CMPL CX, $62 + JA tagLit63 + + // case x == 62: + // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 + MOVWLZX -3(SI), CX + MOVBLZX -1(SI), BX + SHLL $16, BX + ORL BX, CX + JMP doLit + +tagLit63: + // case x == 63: + // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 + MOVL -4(SI), CX + JMP doLit + +// The code above handles literal tags. +// ---------------------------------------- +// The code below handles copy tags. + +tagCopy4: + // case tagCopy4: + // s += 5 + ADDQ $5, SI + + // if uint(s) > uint(len(src)) { etc } + MOVQ SI, BX + SUBQ R11, BX + CMPQ BX, R12 + JA errCorrupt + + // length = 1 + int(src[s-5])>>2 + SHRQ $2, CX + INCQ CX + + // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) + MOVLQZX -4(SI), DX + JMP doCopy + +tagCopy2: + // case tagCopy2: + // s += 3 + ADDQ $3, SI + + // if uint(s) > uint(len(src)) { etc } + MOVQ SI, BX + SUBQ R11, BX + CMPQ BX, R12 + JA errCorrupt + + // length = 1 + int(src[s-3])>>2 + SHRQ $2, CX + INCQ CX + + // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) + MOVWQZX -2(SI), DX + JMP doCopy + +tagCopy: + // We have a copy tag. We assume that: + // - BX == src[s] & 0x03 + // - CX == src[s] + CMPQ BX, $2 + JEQ tagCopy2 + JA tagCopy4 + + // case tagCopy1: + // s += 2 + ADDQ $2, SI + + // if uint(s) > uint(len(src)) { etc } + MOVQ SI, BX + SUBQ R11, BX + CMPQ BX, R12 + JA errCorrupt + + // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) + MOVQ CX, DX + ANDQ $0xe0, DX + SHLQ $3, DX + MOVBQZX -1(SI), BX + ORQ BX, DX + + // length = 4 + int(src[s-2])>>2&0x7 + SHRQ $2, CX + ANDQ $7, CX + ADDQ $4, CX + +doCopy: + // This is the end of the outer "switch", when we have a copy tag. + // + // We assume that: + // - CX == length && CX > 0 + // - DX == offset + + // if offset <= 0 { etc } + CMPQ DX, $0 + JLE errCorrupt + + // if d < offset { etc } + MOVQ DI, BX + SUBQ R8, BX + CMPQ BX, DX + JLT errCorrupt + + // if length > len(dst)-d { etc } + MOVQ R10, BX + SUBQ DI, BX + CMPQ CX, BX + JGT errCorrupt + + // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length + // + // Set: + // - R14 = len(dst)-d + // - R15 = &dst[d-offset] + MOVQ R10, R14 + SUBQ DI, R14 + MOVQ DI, R15 + SUBQ DX, R15 + + // !!! Try a faster technique for short (16 or fewer bytes) forward copies. + // + // First, try using two 8-byte load/stores, similar to the doLit technique + // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is + // still OK if offset >= 8. Note that this has to be two 8-byte load/stores + // and not one 16-byte load/store, and the first store has to be before the + // second load, due to the overlap if offset is in the range [8, 16). + // + // if length > 16 || offset < 8 || len(dst)-d < 16 { + // goto slowForwardCopy + // } + // copy 16 bytes + // d += length + CMPQ CX, $16 + JGT slowForwardCopy + CMPQ DX, $8 + JLT slowForwardCopy + CMPQ R14, $16 + JLT slowForwardCopy + MOVQ 0(R15), AX + MOVQ AX, 0(DI) + MOVQ 8(R15), BX + MOVQ BX, 8(DI) + ADDQ CX, DI + JMP loop + +slowForwardCopy: + // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we + // can still try 8-byte load stores, provided we can overrun up to 10 extra + // bytes. As above, the overrun will be fixed up by subsequent iterations + // of the outermost loop. + // + // The C++ snappy code calls this technique IncrementalCopyFastPath. Its + // commentary says: + // + // ---- + // + // The main part of this loop is a simple copy of eight bytes at a time + // until we've copied (at least) the requested amount of bytes. However, + // if d and d-offset are less than eight bytes apart (indicating a + // repeating pattern of length < 8), we first need to expand the pattern in + // order to get the correct results. For instance, if the buffer looks like + // this, with the eight-byte and patterns marked as + // intervals: + // + // abxxxxxxxxxxxx + // [------] d-offset + // [------] d + // + // a single eight-byte copy from to will repeat the pattern + // once, after which we can move two bytes without moving : + // + // ababxxxxxxxxxx + // [------] d-offset + // [------] d + // + // and repeat the exercise until the two no longer overlap. + // + // This allows us to do very well in the special case of one single byte + // repeated many times, without taking a big hit for more general cases. + // + // The worst case of extra writing past the end of the match occurs when + // offset == 1 and length == 1; the last copy will read from byte positions + // [0..7] and write to [4..11], whereas it was only supposed to write to + // position 1. Thus, ten excess bytes. + // + // ---- + // + // That "10 byte overrun" worst case is confirmed by Go's + // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy + // and finishSlowForwardCopy algorithm. + // + // if length > len(dst)-d-10 { + // goto verySlowForwardCopy + // } + SUBQ $10, R14 + CMPQ CX, R14 + JGT verySlowForwardCopy + +makeOffsetAtLeast8: + // !!! As above, expand the pattern so that offset >= 8 and we can use + // 8-byte load/stores. + // + // for offset < 8 { + // copy 8 bytes from dst[d-offset:] to dst[d:] + // length -= offset + // d += offset + // offset += offset + // // The two previous lines together means that d-offset, and therefore + // // R15, is unchanged. + // } + CMPQ DX, $8 + JGE fixUpSlowForwardCopy + MOVQ (R15), BX + MOVQ BX, (DI) + SUBQ DX, CX + ADDQ DX, DI + ADDQ DX, DX + JMP makeOffsetAtLeast8 + +fixUpSlowForwardCopy: + // !!! Add length (which might be negative now) to d (implied by DI being + // &dst[d]) so that d ends up at the right place when we jump back to the + // top of the loop. Before we do that, though, we save DI to AX so that, if + // length is positive, copying the remaining length bytes will write to the + // right place. + MOVQ DI, AX + ADDQ CX, DI + +finishSlowForwardCopy: + // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative + // length means that we overrun, but as above, that will be fixed up by + // subsequent iterations of the outermost loop. + CMPQ CX, $0 + JLE loop + MOVQ (R15), BX + MOVQ BX, (AX) + ADDQ $8, R15 + ADDQ $8, AX + SUBQ $8, CX + JMP finishSlowForwardCopy + +verySlowForwardCopy: + // verySlowForwardCopy is a simple implementation of forward copy. In C + // parlance, this is a do/while loop instead of a while loop, since we know + // that length > 0. In Go syntax: + // + // for { + // dst[d] = dst[d - offset] + // d++ + // length-- + // if length == 0 { + // break + // } + // } + MOVB (R15), BX + MOVB BX, (DI) + INCQ R15 + INCQ DI + DECQ CX + JNZ verySlowForwardCopy + JMP loop + +// The code above handles copy tags. +// ---------------------------------------- + +end: + // This is the end of the "for s < len(src)". + // + // if d != len(dst) { etc } + CMPQ DI, R10 + JNE errCorrupt + + // return 0 + MOVQ $0, ret+48(FP) + RET + +errCorrupt: + // return decodeErrCodeCorrupt + MOVQ $1, ret+48(FP) + RET diff --git a/vendor/github.com/golang/snappy/decode_other.go b/vendor/github.com/golang/snappy/decode_other.go new file mode 100644 index 000000000..8c9f2049b --- /dev/null +++ b/vendor/github.com/golang/snappy/decode_other.go @@ -0,0 +1,101 @@ +// Copyright 2016 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !amd64 appengine !gc noasm + +package snappy + +// decode writes the decoding of src to dst. It assumes that the varint-encoded +// length of the decompressed bytes has already been read, and that len(dst) +// equals that length. +// +// It returns 0 on success or a decodeErrCodeXxx error code on failure. +func decode(dst, src []byte) int { + var d, s, offset, length int + for s < len(src) { + switch src[s] & 0x03 { + case tagLiteral: + x := uint32(src[s] >> 2) + switch { + case x < 60: + s++ + case x == 60: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-1]) + case x == 61: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-2]) | uint32(src[s-1])<<8 + case x == 62: + s += 4 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 + case x == 63: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 + } + length = int(x) + 1 + if length <= 0 { + return decodeErrCodeUnsupportedLiteralLength + } + if length > len(dst)-d || length > len(src)-s { + return decodeErrCodeCorrupt + } + copy(dst[d:], src[s:s+length]) + d += length + s += length + continue + + case tagCopy1: + s += 2 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 4 + int(src[s-2])>>2&0x7 + offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) + + case tagCopy2: + s += 3 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 1 + int(src[s-3])>>2 + offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) + + case tagCopy4: + s += 5 + if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. + return decodeErrCodeCorrupt + } + length = 1 + int(src[s-5])>>2 + offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) + } + + if offset <= 0 || d < offset || length > len(dst)-d { + return decodeErrCodeCorrupt + } + // Copy from an earlier sub-slice of dst to a later sub-slice. Unlike + // the built-in copy function, this byte-by-byte copy always runs + // forwards, even if the slices overlap. Conceptually, this is: + // + // d += forwardCopy(dst[d:d+length], dst[d-offset:]) + for end := d + length; d != end; d++ { + dst[d] = dst[d-offset] + } + } + if d != len(dst) { + return decodeErrCodeCorrupt + } + return 0 +} diff --git a/vendor/github.com/golang/snappy/encode.go b/vendor/github.com/golang/snappy/encode.go new file mode 100644 index 000000000..8d393e904 --- /dev/null +++ b/vendor/github.com/golang/snappy/encode.go @@ -0,0 +1,285 @@ +// Copyright 2011 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package snappy + +import ( + "encoding/binary" + "errors" + "io" +) + +// Encode returns the encoded form of src. The returned slice may be a sub- +// slice of dst if dst was large enough to hold the entire encoded block. +// Otherwise, a newly allocated slice will be returned. +// +// The dst and src must not overlap. It is valid to pass a nil dst. +func Encode(dst, src []byte) []byte { + if n := MaxEncodedLen(len(src)); n < 0 { + panic(ErrTooLarge) + } else if len(dst) < n { + dst = make([]byte, n) + } + + // The block starts with the varint-encoded length of the decompressed bytes. + d := binary.PutUvarint(dst, uint64(len(src))) + + for len(src) > 0 { + p := src + src = nil + if len(p) > maxBlockSize { + p, src = p[:maxBlockSize], p[maxBlockSize:] + } + if len(p) < minNonLiteralBlockSize { + d += emitLiteral(dst[d:], p) + } else { + d += encodeBlock(dst[d:], p) + } + } + return dst[:d] +} + +// inputMargin is the minimum number of extra input bytes to keep, inside +// encodeBlock's inner loop. On some architectures, this margin lets us +// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) +// literals can be implemented as a single load to and store from a 16-byte +// register. That literal's actual length can be as short as 1 byte, so this +// can copy up to 15 bytes too much, but that's OK as subsequent iterations of +// the encoding loop will fix up the copy overrun, and this inputMargin ensures +// that we don't overrun the dst and src buffers. +const inputMargin = 16 - 1 + +// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that +// could be encoded with a copy tag. This is the minimum with respect to the +// algorithm used by encodeBlock, not a minimum enforced by the file format. +// +// The encoded output must start with at least a 1 byte literal, as there are +// no previous bytes to copy. A minimal (1 byte) copy after that, generated +// from an emitCopy call in encodeBlock's main loop, would require at least +// another inputMargin bytes, for the reason above: we want any emitLiteral +// calls inside encodeBlock's main loop to use the fast path if possible, which +// requires being able to overrun by inputMargin bytes. Thus, +// minNonLiteralBlockSize equals 1 + 1 + inputMargin. +// +// The C++ code doesn't use this exact threshold, but it could, as discussed at +// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion +// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an +// optimization. It should not affect the encoded form. This is tested by +// TestSameEncodingAsCppShortCopies. +const minNonLiteralBlockSize = 1 + 1 + inputMargin + +// MaxEncodedLen returns the maximum length of a snappy block, given its +// uncompressed length. +// +// It will return a negative value if srcLen is too large to encode. +func MaxEncodedLen(srcLen int) int { + n := uint64(srcLen) + if n > 0xffffffff { + return -1 + } + // Compressed data can be defined as: + // compressed := item* literal* + // item := literal* copy + // + // The trailing literal sequence has a space blowup of at most 62/60 + // since a literal of length 60 needs one tag byte + one extra byte + // for length information. + // + // Item blowup is trickier to measure. Suppose the "copy" op copies + // 4 bytes of data. Because of a special check in the encoding code, + // we produce a 4-byte copy only if the offset is < 65536. Therefore + // the copy op takes 3 bytes to encode, and this type of item leads + // to at most the 62/60 blowup for representing literals. + // + // Suppose the "copy" op copies 5 bytes of data. If the offset is big + // enough, it will take 5 bytes to encode the copy op. Therefore the + // worst case here is a one-byte literal followed by a five-byte copy. + // That is, 6 bytes of input turn into 7 bytes of "compressed" data. + // + // This last factor dominates the blowup, so the final estimate is: + n = 32 + n + n/6 + if n > 0xffffffff { + return -1 + } + return int(n) +} + +var errClosed = errors.New("snappy: Writer is closed") + +// NewWriter returns a new Writer that compresses to w. +// +// The Writer returned does not buffer writes. There is no need to Flush or +// Close such a Writer. +// +// Deprecated: the Writer returned is not suitable for many small writes, only +// for few large writes. Use NewBufferedWriter instead, which is efficient +// regardless of the frequency and shape of the writes, and remember to Close +// that Writer when done. +func NewWriter(w io.Writer) *Writer { + return &Writer{ + w: w, + obuf: make([]byte, obufLen), + } +} + +// NewBufferedWriter returns a new Writer that compresses to w, using the +// framing format described at +// https://github.com/google/snappy/blob/master/framing_format.txt +// +// The Writer returned buffers writes. Users must call Close to guarantee all +// data has been forwarded to the underlying io.Writer. They may also call +// Flush zero or more times before calling Close. +func NewBufferedWriter(w io.Writer) *Writer { + return &Writer{ + w: w, + ibuf: make([]byte, 0, maxBlockSize), + obuf: make([]byte, obufLen), + } +} + +// Writer is an io.Writer that can write Snappy-compressed bytes. +type Writer struct { + w io.Writer + err error + + // ibuf is a buffer for the incoming (uncompressed) bytes. + // + // Its use is optional. For backwards compatibility, Writers created by the + // NewWriter function have ibuf == nil, do not buffer incoming bytes, and + // therefore do not need to be Flush'ed or Close'd. + ibuf []byte + + // obuf is a buffer for the outgoing (compressed) bytes. + obuf []byte + + // wroteStreamHeader is whether we have written the stream header. + wroteStreamHeader bool +} + +// Reset discards the writer's state and switches the Snappy writer to write to +// w. This permits reusing a Writer rather than allocating a new one. +func (w *Writer) Reset(writer io.Writer) { + w.w = writer + w.err = nil + if w.ibuf != nil { + w.ibuf = w.ibuf[:0] + } + w.wroteStreamHeader = false +} + +// Write satisfies the io.Writer interface. +func (w *Writer) Write(p []byte) (nRet int, errRet error) { + if w.ibuf == nil { + // Do not buffer incoming bytes. This does not perform or compress well + // if the caller of Writer.Write writes many small slices. This + // behavior is therefore deprecated, but still supported for backwards + // compatibility with code that doesn't explicitly Flush or Close. + return w.write(p) + } + + // The remainder of this method is based on bufio.Writer.Write from the + // standard library. + + for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { + var n int + if len(w.ibuf) == 0 { + // Large write, empty buffer. + // Write directly from p to avoid copy. + n, _ = w.write(p) + } else { + n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) + w.ibuf = w.ibuf[:len(w.ibuf)+n] + w.Flush() + } + nRet += n + p = p[n:] + } + if w.err != nil { + return nRet, w.err + } + n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) + w.ibuf = w.ibuf[:len(w.ibuf)+n] + nRet += n + return nRet, nil +} + +func (w *Writer) write(p []byte) (nRet int, errRet error) { + if w.err != nil { + return 0, w.err + } + for len(p) > 0 { + obufStart := len(magicChunk) + if !w.wroteStreamHeader { + w.wroteStreamHeader = true + copy(w.obuf, magicChunk) + obufStart = 0 + } + + var uncompressed []byte + if len(p) > maxBlockSize { + uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] + } else { + uncompressed, p = p, nil + } + checksum := crc(uncompressed) + + // Compress the buffer, discarding the result if the improvement + // isn't at least 12.5%. + compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) + chunkType := uint8(chunkTypeCompressedData) + chunkLen := 4 + len(compressed) + obufEnd := obufHeaderLen + len(compressed) + if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { + chunkType = chunkTypeUncompressedData + chunkLen = 4 + len(uncompressed) + obufEnd = obufHeaderLen + } + + // Fill in the per-chunk header that comes before the body. + w.obuf[len(magicChunk)+0] = chunkType + w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) + w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) + w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) + w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) + w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) + w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) + w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) + + if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { + w.err = err + return nRet, err + } + if chunkType == chunkTypeUncompressedData { + if _, err := w.w.Write(uncompressed); err != nil { + w.err = err + return nRet, err + } + } + nRet += len(uncompressed) + } + return nRet, nil +} + +// Flush flushes the Writer to its underlying io.Writer. +func (w *Writer) Flush() error { + if w.err != nil { + return w.err + } + if len(w.ibuf) == 0 { + return nil + } + w.write(w.ibuf) + w.ibuf = w.ibuf[:0] + return w.err +} + +// Close calls Flush and then closes the Writer. +func (w *Writer) Close() error { + w.Flush() + ret := w.err + if w.err == nil { + w.err = errClosed + } + return ret +} diff --git a/vendor/github.com/golang/snappy/encode_amd64.go b/vendor/github.com/golang/snappy/encode_amd64.go new file mode 100644 index 000000000..150d91bc8 --- /dev/null +++ b/vendor/github.com/golang/snappy/encode_amd64.go @@ -0,0 +1,29 @@ +// Copyright 2016 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine +// +build gc +// +build !noasm + +package snappy + +// emitLiteral has the same semantics as in encode_other.go. +// +//go:noescape +func emitLiteral(dst, lit []byte) int + +// emitCopy has the same semantics as in encode_other.go. +// +//go:noescape +func emitCopy(dst []byte, offset, length int) int + +// extendMatch has the same semantics as in encode_other.go. +// +//go:noescape +func extendMatch(src []byte, i, j int) int + +// encodeBlock has the same semantics as in encode_other.go. +// +//go:noescape +func encodeBlock(dst, src []byte) (d int) diff --git a/vendor/github.com/golang/snappy/encode_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s new file mode 100644 index 000000000..adfd979fe --- /dev/null +++ b/vendor/github.com/golang/snappy/encode_amd64.s @@ -0,0 +1,730 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine +// +build gc +// +build !noasm + +#include "textflag.h" + +// The XXX lines assemble on Go 1.4, 1.5 and 1.7, but not 1.6, due to a +// Go toolchain regression. See https://github.com/golang/go/issues/15426 and +// https://github.com/golang/snappy/issues/29 +// +// As a workaround, the package was built with a known good assembler, and +// those instructions were disassembled by "objdump -d" to yield the +// 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 +// style comments, in AT&T asm syntax. Note that rsp here is a physical +// register, not Go/asm's SP pseudo-register (see https://golang.org/doc/asm). +// The instructions were then encoded as "BYTE $0x.." sequences, which assemble +// fine on Go 1.6. + +// The asm code generally follows the pure Go code in encode_other.go, except +// where marked with a "!!!". + +// ---------------------------------------------------------------------------- + +// func emitLiteral(dst, lit []byte) int +// +// All local variables fit into registers. The register allocation: +// - AX len(lit) +// - BX n +// - DX return value +// - DI &dst[i] +// - R10 &lit[0] +// +// The 24 bytes of stack space is to call runtime·memmove. +// +// The unusual register allocation of local variables, such as R10 for the +// source pointer, matches the allocation used at the call site in encodeBlock, +// which makes it easier to manually inline this function. +TEXT ·emitLiteral(SB), NOSPLIT, $24-56 + MOVQ dst_base+0(FP), DI + MOVQ lit_base+24(FP), R10 + MOVQ lit_len+32(FP), AX + MOVQ AX, DX + MOVL AX, BX + SUBL $1, BX + + CMPL BX, $60 + JLT oneByte + CMPL BX, $256 + JLT twoBytes + +threeBytes: + MOVB $0xf4, 0(DI) + MOVW BX, 1(DI) + ADDQ $3, DI + ADDQ $3, DX + JMP memmove + +twoBytes: + MOVB $0xf0, 0(DI) + MOVB BX, 1(DI) + ADDQ $2, DI + ADDQ $2, DX + JMP memmove + +oneByte: + SHLB $2, BX + MOVB BX, 0(DI) + ADDQ $1, DI + ADDQ $1, DX + +memmove: + MOVQ DX, ret+48(FP) + + // copy(dst[i:], lit) + // + // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push + // DI, R10 and AX as arguments. + MOVQ DI, 0(SP) + MOVQ R10, 8(SP) + MOVQ AX, 16(SP) + CALL runtime·memmove(SB) + RET + +// ---------------------------------------------------------------------------- + +// func emitCopy(dst []byte, offset, length int) int +// +// All local variables fit into registers. The register allocation: +// - AX length +// - SI &dst[0] +// - DI &dst[i] +// - R11 offset +// +// The unusual register allocation of local variables, such as R11 for the +// offset, matches the allocation used at the call site in encodeBlock, which +// makes it easier to manually inline this function. +TEXT ·emitCopy(SB), NOSPLIT, $0-48 + MOVQ dst_base+0(FP), DI + MOVQ DI, SI + MOVQ offset+24(FP), R11 + MOVQ length+32(FP), AX + +loop0: + // for length >= 68 { etc } + CMPL AX, $68 + JLT step1 + + // Emit a length 64 copy, encoded as 3 bytes. + MOVB $0xfe, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + SUBL $64, AX + JMP loop0 + +step1: + // if length > 64 { etc } + CMPL AX, $64 + JLE step2 + + // Emit a length 60 copy, encoded as 3 bytes. + MOVB $0xee, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + SUBL $60, AX + +step2: + // if length >= 12 || offset >= 2048 { goto step3 } + CMPL AX, $12 + JGE step3 + CMPL R11, $2048 + JGE step3 + + // Emit the remaining copy, encoded as 2 bytes. + MOVB R11, 1(DI) + SHRL $8, R11 + SHLB $5, R11 + SUBB $4, AX + SHLB $2, AX + ORB AX, R11 + ORB $1, R11 + MOVB R11, 0(DI) + ADDQ $2, DI + + // Return the number of bytes written. + SUBQ SI, DI + MOVQ DI, ret+40(FP) + RET + +step3: + // Emit the remaining copy, encoded as 3 bytes. + SUBL $1, AX + SHLB $2, AX + ORB $2, AX + MOVB AX, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + + // Return the number of bytes written. + SUBQ SI, DI + MOVQ DI, ret+40(FP) + RET + +// ---------------------------------------------------------------------------- + +// func extendMatch(src []byte, i, j int) int +// +// All local variables fit into registers. The register allocation: +// - DX &src[0] +// - SI &src[j] +// - R13 &src[len(src) - 8] +// - R14 &src[len(src)] +// - R15 &src[i] +// +// The unusual register allocation of local variables, such as R15 for a source +// pointer, matches the allocation used at the call site in encodeBlock, which +// makes it easier to manually inline this function. +TEXT ·extendMatch(SB), NOSPLIT, $0-48 + MOVQ src_base+0(FP), DX + MOVQ src_len+8(FP), R14 + MOVQ i+24(FP), R15 + MOVQ j+32(FP), SI + ADDQ DX, R14 + ADDQ DX, R15 + ADDQ DX, SI + MOVQ R14, R13 + SUBQ $8, R13 + +cmp8: + // As long as we are 8 or more bytes before the end of src, we can load and + // compare 8 bytes at a time. If those 8 bytes are equal, repeat. + CMPQ SI, R13 + JA cmp1 + MOVQ (R15), AX + MOVQ (SI), BX + CMPQ AX, BX + JNE bsf + ADDQ $8, R15 + ADDQ $8, SI + JMP cmp8 + +bsf: + // If those 8 bytes were not equal, XOR the two 8 byte values, and return + // the index of the first byte that differs. The BSF instruction finds the + // least significant 1 bit, the amd64 architecture is little-endian, and + // the shift by 3 converts a bit index to a byte index. + XORQ AX, BX + BSFQ BX, BX + SHRQ $3, BX + ADDQ BX, SI + + // Convert from &src[ret] to ret. + SUBQ DX, SI + MOVQ SI, ret+40(FP) + RET + +cmp1: + // In src's tail, compare 1 byte at a time. + CMPQ SI, R14 + JAE extendMatchEnd + MOVB (R15), AX + MOVB (SI), BX + CMPB AX, BX + JNE extendMatchEnd + ADDQ $1, R15 + ADDQ $1, SI + JMP cmp1 + +extendMatchEnd: + // Convert from &src[ret] to ret. + SUBQ DX, SI + MOVQ SI, ret+40(FP) + RET + +// ---------------------------------------------------------------------------- + +// func encodeBlock(dst, src []byte) (d int) +// +// All local variables fit into registers, other than "var table". The register +// allocation: +// - AX . . +// - BX . . +// - CX 56 shift (note that amd64 shifts by non-immediates must use CX). +// - DX 64 &src[0], tableSize +// - SI 72 &src[s] +// - DI 80 &dst[d] +// - R9 88 sLimit +// - R10 . &src[nextEmit] +// - R11 96 prevHash, currHash, nextHash, offset +// - R12 104 &src[base], skip +// - R13 . &src[nextS], &src[len(src) - 8] +// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x +// - R15 112 candidate +// +// The second column (56, 64, etc) is the stack offset to spill the registers +// when calling other functions. We could pack this slightly tighter, but it's +// simpler to have a dedicated spill map independent of the function called. +// +// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An +// extra 56 bytes, to call other functions, and an extra 64 bytes, to spill +// local variables (registers) during calls gives 32768 + 56 + 64 = 32888. +TEXT ·encodeBlock(SB), 0, $32888-56 + MOVQ dst_base+0(FP), DI + MOVQ src_base+24(FP), SI + MOVQ src_len+32(FP), R14 + + // shift, tableSize := uint32(32-8), 1<<8 + MOVQ $24, CX + MOVQ $256, DX + +calcShift: + // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { + // shift-- + // } + CMPQ DX, $16384 + JGE varTable + CMPQ DX, R14 + JGE varTable + SUBQ $1, CX + SHLQ $1, DX + JMP calcShift + +varTable: + // var table [maxTableSize]uint16 + // + // In the asm code, unlike the Go code, we can zero-initialize only the + // first tableSize elements. Each uint16 element is 2 bytes and each MOVOU + // writes 16 bytes, so we can do only tableSize/8 writes instead of the + // 2048 writes that would zero-initialize all of table's 32768 bytes. + SHRQ $3, DX + LEAQ table-32768(SP), BX + PXOR X0, X0 + +memclr: + MOVOU X0, 0(BX) + ADDQ $16, BX + SUBQ $1, DX + JNZ memclr + + // !!! DX = &src[0] + MOVQ SI, DX + + // sLimit := len(src) - inputMargin + MOVQ R14, R9 + SUBQ $15, R9 + + // !!! Pre-emptively spill CX, DX and R9 to the stack. Their values don't + // change for the rest of the function. + MOVQ CX, 56(SP) + MOVQ DX, 64(SP) + MOVQ R9, 88(SP) + + // nextEmit := 0 + MOVQ DX, R10 + + // s := 1 + ADDQ $1, SI + + // nextHash := hash(load32(src, s), shift) + MOVL 0(SI), R11 + IMULL $0x1e35a7bd, R11 + SHRL CX, R11 + +outer: + // for { etc } + + // skip := 32 + MOVQ $32, R12 + + // nextS := s + MOVQ SI, R13 + + // candidate := 0 + MOVQ $0, R15 + +inner0: + // for { etc } + + // s := nextS + MOVQ R13, SI + + // bytesBetweenHashLookups := skip >> 5 + MOVQ R12, R14 + SHRQ $5, R14 + + // nextS = s + bytesBetweenHashLookups + ADDQ R14, R13 + + // skip += bytesBetweenHashLookups + ADDQ R14, R12 + + // if nextS > sLimit { goto emitRemainder } + MOVQ R13, AX + SUBQ DX, AX + CMPQ AX, R9 + JA emitRemainder + + // candidate = int(table[nextHash]) + // XXX: MOVWQZX table-32768(SP)(R11*2), R15 + // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 + BYTE $0x4e + BYTE $0x0f + BYTE $0xb7 + BYTE $0x7c + BYTE $0x5c + BYTE $0x78 + + // table[nextHash] = uint16(s) + MOVQ SI, AX + SUBQ DX, AX + + // XXX: MOVW AX, table-32768(SP)(R11*2) + // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) + BYTE $0x66 + BYTE $0x42 + BYTE $0x89 + BYTE $0x44 + BYTE $0x5c + BYTE $0x78 + + // nextHash = hash(load32(src, nextS), shift) + MOVL 0(R13), R11 + IMULL $0x1e35a7bd, R11 + SHRL CX, R11 + + // if load32(src, s) != load32(src, candidate) { continue } break + MOVL 0(SI), AX + MOVL (DX)(R15*1), BX + CMPL AX, BX + JNE inner0 + +fourByteMatch: + // As per the encode_other.go code: + // + // A 4-byte match has been found. We'll later see etc. + + // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment + // on inputMargin in encode.go. + MOVQ SI, AX + SUBQ R10, AX + CMPQ AX, $16 + JLE emitLiteralFastPath + + // ---------------------------------------- + // Begin inline of the emitLiteral call. + // + // d += emitLiteral(dst[d:], src[nextEmit:s]) + + MOVL AX, BX + SUBL $1, BX + + CMPL BX, $60 + JLT inlineEmitLiteralOneByte + CMPL BX, $256 + JLT inlineEmitLiteralTwoBytes + +inlineEmitLiteralThreeBytes: + MOVB $0xf4, 0(DI) + MOVW BX, 1(DI) + ADDQ $3, DI + JMP inlineEmitLiteralMemmove + +inlineEmitLiteralTwoBytes: + MOVB $0xf0, 0(DI) + MOVB BX, 1(DI) + ADDQ $2, DI + JMP inlineEmitLiteralMemmove + +inlineEmitLiteralOneByte: + SHLB $2, BX + MOVB BX, 0(DI) + ADDQ $1, DI + +inlineEmitLiteralMemmove: + // Spill local variables (registers) onto the stack; call; unspill. + // + // copy(dst[i:], lit) + // + // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push + // DI, R10 and AX as arguments. + MOVQ DI, 0(SP) + MOVQ R10, 8(SP) + MOVQ AX, 16(SP) + ADDQ AX, DI // Finish the "d +=" part of "d += emitLiteral(etc)". + MOVQ SI, 72(SP) + MOVQ DI, 80(SP) + MOVQ R15, 112(SP) + CALL runtime·memmove(SB) + MOVQ 56(SP), CX + MOVQ 64(SP), DX + MOVQ 72(SP), SI + MOVQ 80(SP), DI + MOVQ 88(SP), R9 + MOVQ 112(SP), R15 + JMP inner1 + +inlineEmitLiteralEnd: + // End inline of the emitLiteral call. + // ---------------------------------------- + +emitLiteralFastPath: + // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2". + MOVB AX, BX + SUBB $1, BX + SHLB $2, BX + MOVB BX, (DI) + ADDQ $1, DI + + // !!! Implement the copy from lit to dst as a 16-byte load and store. + // (Encode's documentation says that dst and src must not overlap.) + // + // This always copies 16 bytes, instead of only len(lit) bytes, but that's + // OK. Subsequent iterations will fix up the overrun. + // + // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or + // 16-byte loads and stores. This technique probably wouldn't be as + // effective on architectures that are fussier about alignment. + MOVOU 0(R10), X0 + MOVOU X0, 0(DI) + ADDQ AX, DI + +inner1: + // for { etc } + + // base := s + MOVQ SI, R12 + + // !!! offset := base - candidate + MOVQ R12, R11 + SUBQ R15, R11 + SUBQ DX, R11 + + // ---------------------------------------- + // Begin inline of the extendMatch call. + // + // s = extendMatch(src, candidate+4, s+4) + + // !!! R14 = &src[len(src)] + MOVQ src_len+32(FP), R14 + ADDQ DX, R14 + + // !!! R13 = &src[len(src) - 8] + MOVQ R14, R13 + SUBQ $8, R13 + + // !!! R15 = &src[candidate + 4] + ADDQ $4, R15 + ADDQ DX, R15 + + // !!! s += 4 + ADDQ $4, SI + +inlineExtendMatchCmp8: + // As long as we are 8 or more bytes before the end of src, we can load and + // compare 8 bytes at a time. If those 8 bytes are equal, repeat. + CMPQ SI, R13 + JA inlineExtendMatchCmp1 + MOVQ (R15), AX + MOVQ (SI), BX + CMPQ AX, BX + JNE inlineExtendMatchBSF + ADDQ $8, R15 + ADDQ $8, SI + JMP inlineExtendMatchCmp8 + +inlineExtendMatchBSF: + // If those 8 bytes were not equal, XOR the two 8 byte values, and return + // the index of the first byte that differs. The BSF instruction finds the + // least significant 1 bit, the amd64 architecture is little-endian, and + // the shift by 3 converts a bit index to a byte index. + XORQ AX, BX + BSFQ BX, BX + SHRQ $3, BX + ADDQ BX, SI + JMP inlineExtendMatchEnd + +inlineExtendMatchCmp1: + // In src's tail, compare 1 byte at a time. + CMPQ SI, R14 + JAE inlineExtendMatchEnd + MOVB (R15), AX + MOVB (SI), BX + CMPB AX, BX + JNE inlineExtendMatchEnd + ADDQ $1, R15 + ADDQ $1, SI + JMP inlineExtendMatchCmp1 + +inlineExtendMatchEnd: + // End inline of the extendMatch call. + // ---------------------------------------- + + // ---------------------------------------- + // Begin inline of the emitCopy call. + // + // d += emitCopy(dst[d:], base-candidate, s-base) + + // !!! length := s - base + MOVQ SI, AX + SUBQ R12, AX + +inlineEmitCopyLoop0: + // for length >= 68 { etc } + CMPL AX, $68 + JLT inlineEmitCopyStep1 + + // Emit a length 64 copy, encoded as 3 bytes. + MOVB $0xfe, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + SUBL $64, AX + JMP inlineEmitCopyLoop0 + +inlineEmitCopyStep1: + // if length > 64 { etc } + CMPL AX, $64 + JLE inlineEmitCopyStep2 + + // Emit a length 60 copy, encoded as 3 bytes. + MOVB $0xee, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + SUBL $60, AX + +inlineEmitCopyStep2: + // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 } + CMPL AX, $12 + JGE inlineEmitCopyStep3 + CMPL R11, $2048 + JGE inlineEmitCopyStep3 + + // Emit the remaining copy, encoded as 2 bytes. + MOVB R11, 1(DI) + SHRL $8, R11 + SHLB $5, R11 + SUBB $4, AX + SHLB $2, AX + ORB AX, R11 + ORB $1, R11 + MOVB R11, 0(DI) + ADDQ $2, DI + JMP inlineEmitCopyEnd + +inlineEmitCopyStep3: + // Emit the remaining copy, encoded as 3 bytes. + SUBL $1, AX + SHLB $2, AX + ORB $2, AX + MOVB AX, 0(DI) + MOVW R11, 1(DI) + ADDQ $3, DI + +inlineEmitCopyEnd: + // End inline of the emitCopy call. + // ---------------------------------------- + + // nextEmit = s + MOVQ SI, R10 + + // if s >= sLimit { goto emitRemainder } + MOVQ SI, AX + SUBQ DX, AX + CMPQ AX, R9 + JAE emitRemainder + + // As per the encode_other.go code: + // + // We could immediately etc. + + // x := load64(src, s-1) + MOVQ -1(SI), R14 + + // prevHash := hash(uint32(x>>0), shift) + MOVL R14, R11 + IMULL $0x1e35a7bd, R11 + SHRL CX, R11 + + // table[prevHash] = uint16(s-1) + MOVQ SI, AX + SUBQ DX, AX + SUBQ $1, AX + + // XXX: MOVW AX, table-32768(SP)(R11*2) + // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) + BYTE $0x66 + BYTE $0x42 + BYTE $0x89 + BYTE $0x44 + BYTE $0x5c + BYTE $0x78 + + // currHash := hash(uint32(x>>8), shift) + SHRQ $8, R14 + MOVL R14, R11 + IMULL $0x1e35a7bd, R11 + SHRL CX, R11 + + // candidate = int(table[currHash]) + // XXX: MOVWQZX table-32768(SP)(R11*2), R15 + // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 + BYTE $0x4e + BYTE $0x0f + BYTE $0xb7 + BYTE $0x7c + BYTE $0x5c + BYTE $0x78 + + // table[currHash] = uint16(s) + ADDQ $1, AX + + // XXX: MOVW AX, table-32768(SP)(R11*2) + // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) + BYTE $0x66 + BYTE $0x42 + BYTE $0x89 + BYTE $0x44 + BYTE $0x5c + BYTE $0x78 + + // if uint32(x>>8) == load32(src, candidate) { continue } + MOVL (DX)(R15*1), BX + CMPL R14, BX + JEQ inner1 + + // nextHash = hash(uint32(x>>16), shift) + SHRQ $8, R14 + MOVL R14, R11 + IMULL $0x1e35a7bd, R11 + SHRL CX, R11 + + // s++ + ADDQ $1, SI + + // break out of the inner1 for loop, i.e. continue the outer loop. + JMP outer + +emitRemainder: + // if nextEmit < len(src) { etc } + MOVQ src_len+32(FP), AX + ADDQ DX, AX + CMPQ R10, AX + JEQ encodeBlockEnd + + // d += emitLiteral(dst[d:], src[nextEmit:]) + // + // Push args. + MOVQ DI, 0(SP) + MOVQ $0, 8(SP) // Unnecessary, as the callee ignores it, but conservative. + MOVQ $0, 16(SP) // Unnecessary, as the callee ignores it, but conservative. + MOVQ R10, 24(SP) + SUBQ R10, AX + MOVQ AX, 32(SP) + MOVQ AX, 40(SP) // Unnecessary, as the callee ignores it, but conservative. + + // Spill local variables (registers) onto the stack; call; unspill. + MOVQ DI, 80(SP) + CALL ·emitLiteral(SB) + MOVQ 80(SP), DI + + // Finish the "d +=" part of "d += emitLiteral(etc)". + ADDQ 48(SP), DI + +encodeBlockEnd: + MOVQ dst_base+0(FP), AX + SUBQ AX, DI + MOVQ DI, d+48(FP) + RET diff --git a/vendor/github.com/golang/snappy/encode_other.go b/vendor/github.com/golang/snappy/encode_other.go new file mode 100644 index 000000000..dbcae905e --- /dev/null +++ b/vendor/github.com/golang/snappy/encode_other.go @@ -0,0 +1,238 @@ +// Copyright 2016 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !amd64 appengine !gc noasm + +package snappy + +func load32(b []byte, i int) uint32 { + b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. + return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 +} + +func load64(b []byte, i int) uint64 { + b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. + return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | + uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 +} + +// emitLiteral writes a literal chunk and returns the number of bytes written. +// +// It assumes that: +// dst is long enough to hold the encoded bytes +// 1 <= len(lit) && len(lit) <= 65536 +func emitLiteral(dst, lit []byte) int { + i, n := 0, uint(len(lit)-1) + switch { + case n < 60: + dst[0] = uint8(n)<<2 | tagLiteral + i = 1 + case n < 1<<8: + dst[0] = 60<<2 | tagLiteral + dst[1] = uint8(n) + i = 2 + default: + dst[0] = 61<<2 | tagLiteral + dst[1] = uint8(n) + dst[2] = uint8(n >> 8) + i = 3 + } + return i + copy(dst[i:], lit) +} + +// emitCopy writes a copy chunk and returns the number of bytes written. +// +// It assumes that: +// dst is long enough to hold the encoded bytes +// 1 <= offset && offset <= 65535 +// 4 <= length && length <= 65535 +func emitCopy(dst []byte, offset, length int) int { + i := 0 + // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The + // threshold for this loop is a little higher (at 68 = 64 + 4), and the + // length emitted down below is is a little lower (at 60 = 64 - 4), because + // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed + // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as + // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as + // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a + // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an + // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. + for length >= 68 { + // Emit a length 64 copy, encoded as 3 bytes. + dst[i+0] = 63<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + i += 3 + length -= 64 + } + if length > 64 { + // Emit a length 60 copy, encoded as 3 bytes. + dst[i+0] = 59<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + i += 3 + length -= 60 + } + if length >= 12 || offset >= 2048 { + // Emit the remaining copy, encoded as 3 bytes. + dst[i+0] = uint8(length-1)<<2 | tagCopy2 + dst[i+1] = uint8(offset) + dst[i+2] = uint8(offset >> 8) + return i + 3 + } + // Emit the remaining copy, encoded as 2 bytes. + dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 + dst[i+1] = uint8(offset) + return i + 2 +} + +// extendMatch returns the largest k such that k <= len(src) and that +// src[i:i+k-j] and src[j:k] have the same contents. +// +// It assumes that: +// 0 <= i && i < j && j <= len(src) +func extendMatch(src []byte, i, j int) int { + for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { + } + return j +} + +func hash(u, shift uint32) uint32 { + return (u * 0x1e35a7bd) >> shift +} + +// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It +// assumes that the varint-encoded length of the decompressed bytes has already +// been written. +// +// It also assumes that: +// len(dst) >= MaxEncodedLen(len(src)) && +// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize +func encodeBlock(dst, src []byte) (d int) { + // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. + // The table element type is uint16, as s < sLimit and sLimit < len(src) + // and len(src) <= maxBlockSize and maxBlockSize == 65536. + const ( + maxTableSize = 1 << 14 + // tableMask is redundant, but helps the compiler eliminate bounds + // checks. + tableMask = maxTableSize - 1 + ) + shift := uint32(32 - 8) + for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { + shift-- + } + // In Go, all array elements are zero-initialized, so there is no advantage + // to a smaller tableSize per se. However, it matches the C++ algorithm, + // and in the asm versions of this code, we can get away with zeroing only + // the first tableSize elements. + var table [maxTableSize]uint16 + + // sLimit is when to stop looking for offset/length copies. The inputMargin + // lets us use a fast path for emitLiteral in the main loop, while we are + // looking for copies. + sLimit := len(src) - inputMargin + + // nextEmit is where in src the next emitLiteral should start from. + nextEmit := 0 + + // The encoded form must start with a literal, as there are no previous + // bytes to copy, so we start looking for hash matches at s == 1. + s := 1 + nextHash := hash(load32(src, s), shift) + + for { + // Copied from the C++ snappy implementation: + // + // Heuristic match skipping: If 32 bytes are scanned with no matches + // found, start looking only at every other byte. If 32 more bytes are + // scanned (or skipped), look at every third byte, etc.. When a match + // is found, immediately go back to looking at every byte. This is a + // small loss (~5% performance, ~0.1% density) for compressible data + // due to more bookkeeping, but for non-compressible data (such as + // JPEG) it's a huge win since the compressor quickly "realizes" the + // data is incompressible and doesn't bother looking for matches + // everywhere. + // + // The "skip" variable keeps track of how many bytes there are since + // the last match; dividing it by 32 (ie. right-shifting by five) gives + // the number of bytes to move ahead for each iteration. + skip := 32 + + nextS := s + candidate := 0 + for { + s = nextS + bytesBetweenHashLookups := skip >> 5 + nextS = s + bytesBetweenHashLookups + skip += bytesBetweenHashLookups + if nextS > sLimit { + goto emitRemainder + } + candidate = int(table[nextHash&tableMask]) + table[nextHash&tableMask] = uint16(s) + nextHash = hash(load32(src, nextS), shift) + if load32(src, s) == load32(src, candidate) { + break + } + } + + // A 4-byte match has been found. We'll later see if more than 4 bytes + // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit + // them as literal bytes. + d += emitLiteral(dst[d:], src[nextEmit:s]) + + // Call emitCopy, and then see if another emitCopy could be our next + // move. Repeat until we find no match for the input immediately after + // what was consumed by the last emitCopy call. + // + // If we exit this loop normally then we need to call emitLiteral next, + // though we don't yet know how big the literal will be. We handle that + // by proceeding to the next iteration of the main loop. We also can + // exit this loop via goto if we get close to exhausting the input. + for { + // Invariant: we have a 4-byte match at s, and no need to emit any + // literal bytes prior to s. + base := s + + // Extend the 4-byte match as long as possible. + // + // This is an inlined version of: + // s = extendMatch(src, candidate+4, s+4) + s += 4 + for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { + } + + d += emitCopy(dst[d:], base-candidate, s-base) + nextEmit = s + if s >= sLimit { + goto emitRemainder + } + + // We could immediately start working at s now, but to improve + // compression we first update the hash table at s-1 and at s. If + // another emitCopy is not our next move, also calculate nextHash + // at s+1. At least on GOARCH=amd64, these three hash calculations + // are faster as one load64 call (with some shifts) instead of + // three load32 calls. + x := load64(src, s-1) + prevHash := hash(uint32(x>>0), shift) + table[prevHash&tableMask] = uint16(s - 1) + currHash := hash(uint32(x>>8), shift) + candidate = int(table[currHash&tableMask]) + table[currHash&tableMask] = uint16(s) + if uint32(x>>8) != load32(src, candidate) { + nextHash = hash(uint32(x>>16), shift) + s++ + break + } + } + } + +emitRemainder: + if nextEmit < len(src) { + d += emitLiteral(dst[d:], src[nextEmit:]) + } + return d +} diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go new file mode 100644 index 000000000..ece692ea4 --- /dev/null +++ b/vendor/github.com/golang/snappy/snappy.go @@ -0,0 +1,98 @@ +// Copyright 2011 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package snappy implements the Snappy compression format. It aims for very +// high speeds and reasonable compression. +// +// There are actually two Snappy formats: block and stream. They are related, +// but different: trying to decompress block-compressed data as a Snappy stream +// will fail, and vice versa. The block format is the Decode and Encode +// functions and the stream format is the Reader and Writer types. +// +// The block format, the more common case, is used when the complete size (the +// number of bytes) of the original data is known upfront, at the time +// compression starts. The stream format, also known as the framing format, is +// for when that isn't always true. +// +// The canonical, C++ implementation is at https://github.com/google/snappy and +// it only implements the block format. +package snappy // import "github.com/golang/snappy" + +import ( + "hash/crc32" +) + +/* +Each encoded block begins with the varint-encoded length of the decoded data, +followed by a sequence of chunks. Chunks begin and end on byte boundaries. The +first byte of each chunk is broken into its 2 least and 6 most significant bits +called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. +Zero means a literal tag. All other values mean a copy tag. + +For literal tags: + - If m < 60, the next 1 + m bytes are literal bytes. + - Otherwise, let n be the little-endian unsigned integer denoted by the next + m - 59 bytes. The next 1 + n bytes after that are literal bytes. + +For copy tags, length bytes are copied from offset bytes ago, in the style of +Lempel-Ziv compression algorithms. In particular: + - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). + The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 + of the offset. The next byte is bits 0-7 of the offset. + - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). + The length is 1 + m. The offset is the little-endian unsigned integer + denoted by the next 2 bytes. + - For l == 3, this tag is a legacy format that is no longer issued by most + encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in + [1, 65). The length is 1 + m. The offset is the little-endian unsigned + integer denoted by the next 4 bytes. +*/ +const ( + tagLiteral = 0x00 + tagCopy1 = 0x01 + tagCopy2 = 0x02 + tagCopy4 = 0x03 +) + +const ( + checksumSize = 4 + chunkHeaderSize = 4 + magicChunk = "\xff\x06\x00\x00" + magicBody + magicBody = "sNaPpY" + + // maxBlockSize is the maximum size of the input to encodeBlock. It is not + // part of the wire format per se, but some parts of the encoder assume + // that an offset fits into a uint16. + // + // Also, for the framing format (Writer type instead of Encode function), + // https://github.com/google/snappy/blob/master/framing_format.txt says + // that "the uncompressed data in a chunk must be no longer than 65536 + // bytes". + maxBlockSize = 65536 + + // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is + // hard coded to be a const instead of a variable, so that obufLen can also + // be a const. Their equivalence is confirmed by + // TestMaxEncodedLenOfMaxBlockSize. + maxEncodedLenOfMaxBlockSize = 76490 + + obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize + obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize +) + +const ( + chunkTypeCompressedData = 0x00 + chunkTypeUncompressedData = 0x01 + chunkTypePadding = 0xfe + chunkTypeStreamIdentifier = 0xff +) + +var crcTable = crc32.MakeTable(crc32.Castagnoli) + +// crc implements the checksum specified in section 3 of +// https://github.com/google/snappy/blob/master/framing_format.txt +func crc(b []byte) uint32 { + c := crc32.Update(0, crcTable, b) + return uint32(c>>15|c<<17) + 0xa282ead8 +} diff --git a/vendor/github.com/google/go-cmp/cmp/compare.go b/vendor/github.com/google/go-cmp/cmp/compare.go index 2133562b0..7e215f220 100644 --- a/vendor/github.com/google/go-cmp/cmp/compare.go +++ b/vendor/github.com/google/go-cmp/cmp/compare.go @@ -29,17 +29,26 @@ package cmp import ( "fmt" "reflect" - "strings" "github.com/google/go-cmp/cmp/internal/diff" - "github.com/google/go-cmp/cmp/internal/flags" "github.com/google/go-cmp/cmp/internal/function" "github.com/google/go-cmp/cmp/internal/value" ) +// BUG(dsnet): Maps with keys containing NaN values cannot be properly compared due to +// the reflection package's inability to retrieve such entries. Equal will panic +// anytime it comes across a NaN key, but this behavior may change. +// +// See https://golang.org/issue/11104 for more details. + +var nothing = reflect.Value{} + // Equal reports whether x and y are equal by recursively applying the // following rules in the given order to x and y and all of their sub-values: // +// • If two values are not of the same type, then they are never equal +// and the overall result is false. +// // • Let S be the set of all Ignore, Transformer, and Comparer options that // remain after applying all path filters, value filters, and type filters. // If at least one Ignore exists in S, then the comparison is ignored. @@ -52,79 +61,43 @@ import ( // // • If the values have an Equal method of the form "(T) Equal(T) bool" or // "(T) Equal(I) bool" where T is assignable to I, then use the result of -// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and -// evaluation proceeds to the next rule. +// x.Equal(y) even if x or y is nil. +// Otherwise, no such method exists and evaluation proceeds to the next rule. // // • Lastly, try to compare x and y based on their basic kinds. // Simple kinds like booleans, integers, floats, complex numbers, strings, and // channels are compared using the equivalent of the == operator in Go. // Functions are only equal if they are both nil, otherwise they are unequal. +// Pointers are equal if the underlying values they point to are also equal. +// Interfaces are equal if their underlying concrete values are also equal. // -// Structs are equal if recursively calling Equal on all fields report equal. -// If a struct contains unexported fields, Equal panics unless an Ignore option -// (e.g., cmpopts.IgnoreUnexported) ignores that field or the AllowUnexported -// option explicitly permits comparing the unexported field. -// -// Slices are equal if they are both nil or both non-nil, where recursively -// calling Equal on all non-ignored slice or array elements report equal. -// Empty non-nil slices and nil slices are not equal; to equate empty slices, -// consider using cmpopts.EquateEmpty. +// Structs are equal if all of their fields are equal. If a struct contains +// unexported fields, Equal panics unless the AllowUnexported option is used or +// an Ignore option (e.g., cmpopts.IgnoreUnexported) ignores that field. // -// Maps are equal if they are both nil or both non-nil, where recursively -// calling Equal on all non-ignored map entries report equal. +// Arrays, slices, and maps are equal if they are both nil or both non-nil +// with the same length and the elements at each index or key are equal. +// Note that a non-nil empty slice and a nil slice are not equal. +// To equate empty slices and maps, consider using cmpopts.EquateEmpty. // Map keys are equal according to the == operator. // To use custom comparisons for map keys, consider using cmpopts.SortMaps. -// Empty non-nil maps and nil maps are not equal; to equate empty maps, -// consider using cmpopts.EquateEmpty. -// -// Pointers and interfaces are equal if they are both nil or both non-nil, -// where they have the same underlying concrete type and recursively -// calling Equal on the underlying values reports equal. func Equal(x, y interface{}, opts ...Option) bool { - vx := reflect.ValueOf(x) - vy := reflect.ValueOf(y) - - // If the inputs are different types, auto-wrap them in an empty interface - // so that they have the same parent type. - var t reflect.Type - if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { - t = reflect.TypeOf((*interface{})(nil)).Elem() - if vx.IsValid() { - vvx := reflect.New(t).Elem() - vvx.Set(vx) - vx = vvx - } - if vy.IsValid() { - vvy := reflect.New(t).Elem() - vvy.Set(vy) - vy = vvy - } - } else { - t = vx.Type() - } - s := newState(opts) - s.compareAny(&pathStep{t, vx, vy}) + s.compareAny(reflect.ValueOf(x), reflect.ValueOf(y)) return s.result.Equal() } // Diff returns a human-readable report of the differences between two values. // It returns an empty string if and only if Equal returns true for the same -// input values and options. -// -// The output is displayed as a literal in pseudo-Go syntax. -// At the start of each line, a "-" prefix indicates an element removed from x, -// a "+" prefix to indicates an element added to y, and the lack of a prefix -// indicates an element common to both x and y. If possible, the output -// uses fmt.Stringer.String or error.Error methods to produce more humanly -// readable outputs. In such cases, the string is prefixed with either an -// 's' or 'e' character, respectively, to indicate that the method was called. +// input values and options. The output string will use the "-" symbol to +// indicate elements removed from x, and the "+" symbol to indicate elements +// added to y. // -// Do not depend on this output being stable. If you need the ability to -// programmatically interpret the difference, consider using a custom Reporter. +// Do not depend on this output being stable. func Diff(x, y interface{}, opts ...Option) string { r := new(defaultReporter) - eq := Equal(x, y, Options(opts), Reporter(r)) + opts = Options{Options(opts), r} + eq := Equal(x, y, opts...) d := r.String() if (d == "") != eq { panic("inconsistent difference and equality results") @@ -135,13 +108,9 @@ func Diff(x, y interface{}, opts ...Option) string { type state struct { // These fields represent the "comparison state". // Calling statelessCompare must not result in observable changes to these. - result diff.Result // The current result of comparison - curPath Path // The current path in the value tree - reporters []reporter // Optional reporters - - // recChecker checks for infinite cycles applying the same set of - // transformers upon the output of itself. - recChecker recChecker + result diff.Result // The current result of comparison + curPath Path // The current path in the value tree + reporter reporter // Optional reporter used for difference formatting // dynChecker triggers pseudo-random checks for option correctness. // It is safe for statelessCompare to mutate this value. @@ -153,9 +122,10 @@ type state struct { } func newState(opts []Option) *state { - // Always ensure a validator option exists to validate the inputs. - s := &state{opts: Options{validator{}}} - s.processOption(Options(opts)) + s := new(state) + for _, opt := range opts { + s.processOption(opt) + } return s } @@ -182,7 +152,10 @@ func (s *state) processOption(opt Option) { s.exporters[t] = true } case reporter: - s.reporters = append(s.reporters, opt) + if s.reporter != nil { + panic("difference reporter already registered") + } + s.reporter = opt default: panic(fmt.Sprintf("unknown option %T", opt)) } @@ -191,88 +164,153 @@ func (s *state) processOption(opt Option) { // statelessCompare compares two values and returns the result. // This function is stateless in that it does not alter the current result, // or output to any registered reporters. -func (s *state) statelessCompare(step PathStep) diff.Result { +func (s *state) statelessCompare(vx, vy reflect.Value) diff.Result { // We do not save and restore the curPath because all of the compareX // methods should properly push and pop from the path. // It is an implementation bug if the contents of curPath differs from // when calling this function to when returning from it. - oldResult, oldReporters := s.result, s.reporters + oldResult, oldReporter := s.result, s.reporter s.result = diff.Result{} // Reset result - s.reporters = nil // Remove reporters to avoid spurious printouts - s.compareAny(step) + s.reporter = nil // Remove reporter to avoid spurious printouts + s.compareAny(vx, vy) res := s.result - s.result, s.reporters = oldResult, oldReporters + s.result, s.reporter = oldResult, oldReporter return res } -func (s *state) compareAny(step PathStep) { - // Update the path stack. - s.curPath.push(step) - defer s.curPath.pop() - for _, r := range s.reporters { - r.PushStep(step) - defer r.PopStep() - } - s.recChecker.Check(s.curPath) +func (s *state) compareAny(vx, vy reflect.Value) { + // TODO: Support cyclic data structures. - // Obtain the current type and values. - t := step.Type() - vx, vy := step.Values() + // Rule 0: Differing types are never equal. + if !vx.IsValid() || !vy.IsValid() { + s.report(vx.IsValid() == vy.IsValid(), vx, vy) + return + } + if vx.Type() != vy.Type() { + s.report(false, vx, vy) // Possible for path to be empty + return + } + t := vx.Type() + if len(s.curPath) == 0 { + s.curPath.push(&pathStep{typ: t}) + defer s.curPath.pop() + } + vx, vy = s.tryExporting(vx, vy) // Rule 1: Check whether an option applies on this node in the value tree. - if s.tryOptions(t, vx, vy) { + if s.tryOptions(vx, vy, t) { return } // Rule 2: Check whether the type has a valid Equal method. - if s.tryMethod(t, vx, vy) { + if s.tryMethod(vx, vy, t) { return } - // Rule 3: Compare based on the underlying kind. + // Rule 3: Recursively descend into each value's underlying kind. switch t.Kind() { case reflect.Bool: - s.report(vx.Bool() == vy.Bool(), 0) + s.report(vx.Bool() == vy.Bool(), vx, vy) + return case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - s.report(vx.Int() == vy.Int(), 0) + s.report(vx.Int() == vy.Int(), vx, vy) + return case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - s.report(vx.Uint() == vy.Uint(), 0) + s.report(vx.Uint() == vy.Uint(), vx, vy) + return case reflect.Float32, reflect.Float64: - s.report(vx.Float() == vy.Float(), 0) + s.report(vx.Float() == vy.Float(), vx, vy) + return case reflect.Complex64, reflect.Complex128: - s.report(vx.Complex() == vy.Complex(), 0) + s.report(vx.Complex() == vy.Complex(), vx, vy) + return case reflect.String: - s.report(vx.String() == vy.String(), 0) + s.report(vx.String() == vy.String(), vx, vy) + return case reflect.Chan, reflect.UnsafePointer: - s.report(vx.Pointer() == vy.Pointer(), 0) + s.report(vx.Pointer() == vy.Pointer(), vx, vy) + return case reflect.Func: - s.report(vx.IsNil() && vy.IsNil(), 0) - case reflect.Struct: - s.compareStruct(t, vx, vy) - case reflect.Slice, reflect.Array: - s.compareSlice(t, vx, vy) - case reflect.Map: - s.compareMap(t, vx, vy) + s.report(vx.IsNil() && vy.IsNil(), vx, vy) + return case reflect.Ptr: - s.comparePtr(t, vx, vy) + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), vx, vy) + return + } + s.curPath.push(&indirect{pathStep{t.Elem()}}) + defer s.curPath.pop() + s.compareAny(vx.Elem(), vy.Elem()) + return case reflect.Interface: - s.compareInterface(t, vx, vy) + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), vx, vy) + return + } + if vx.Elem().Type() != vy.Elem().Type() { + s.report(false, vx.Elem(), vy.Elem()) + return + } + s.curPath.push(&typeAssertion{pathStep{vx.Elem().Type()}}) + defer s.curPath.pop() + s.compareAny(vx.Elem(), vy.Elem()) + return + case reflect.Slice: + if vx.IsNil() || vy.IsNil() { + s.report(vx.IsNil() && vy.IsNil(), vx, vy) + return + } + fallthrough + case reflect.Array: + s.compareArray(vx, vy, t) + return + case reflect.Map: + s.compareMap(vx, vy, t) + return + case reflect.Struct: + s.compareStruct(vx, vy, t) + return default: panic(fmt.Sprintf("%v kind not handled", t.Kind())) } } -func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool { +func (s *state) tryExporting(vx, vy reflect.Value) (reflect.Value, reflect.Value) { + if sf, ok := s.curPath[len(s.curPath)-1].(*structField); ok && sf.unexported { + if sf.force { + // Use unsafe pointer arithmetic to get read-write access to an + // unexported field in the struct. + vx = unsafeRetrieveField(sf.pvx, sf.field) + vy = unsafeRetrieveField(sf.pvy, sf.field) + } else { + // We are not allowed to export the value, so invalidate them + // so that tryOptions can panic later if not explicitly ignored. + vx = nothing + vy = nothing + } + } + return vx, vy +} + +func (s *state) tryOptions(vx, vy reflect.Value, t reflect.Type) bool { + // If there were no FilterValues, we will not detect invalid inputs, + // so manually check for them and append invalid if necessary. + // We still evaluate the options since an ignore can override invalid. + opts := s.opts + if !vx.IsValid() || !vy.IsValid() { + opts = Options{opts, invalid{}} + } + // Evaluate all filters and apply the remaining options. - if opt := s.opts.filter(s, t, vx, vy); opt != nil { + if opt := opts.filter(s, vx, vy, t); opt != nil { opt.apply(s, vx, vy) return true } return false } -func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool { +func (s *state) tryMethod(vx, vy reflect.Value, t reflect.Type) bool { // Check if this type even has an Equal method. m, ok := t.MethodByName("Equal") if !ok || !function.IsType(m.Type, function.EqualAssignable) { @@ -280,11 +318,11 @@ func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool { } eq := s.callTTBFunc(m.Func, vx, vy) - s.report(eq, reportByMethod) + s.report(eq, vx, vy) return true } -func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value { +func (s *state) callTRFunc(f, v reflect.Value) reflect.Value { v = sanitizeValue(v, f.Type().In(0)) if !s.dynChecker.Next() { return f.Call([]reflect.Value{v})[0] @@ -295,15 +333,15 @@ func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value { // unsafe mutations to the input. c := make(chan reflect.Value) go detectRaces(c, f, v) - got := <-c want := f.Call([]reflect.Value{v})[0] - if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() { + if got := <-c; !s.statelessCompare(got, want).Equal() { // To avoid false-positives with non-reflexive equality operations, // we sanity check whether a value is equal to itself. - if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() { + if !s.statelessCompare(want, want).Equal() { return want } - panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f))) + fn := getFuncName(f.Pointer()) + panic(fmt.Sprintf("non-deterministic function detected: %s", fn)) } return want } @@ -321,10 +359,10 @@ func (s *state) callTTBFunc(f, x, y reflect.Value) bool { // unsafe mutations to the input. c := make(chan reflect.Value) go detectRaces(c, f, y, x) - got := <-c want := f.Call([]reflect.Value{x, y})[0].Bool() - if !got.IsValid() || got.Bool() != want { - panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f))) + if got := <-c; !got.IsValid() || got.Bool() != want { + fn := getFuncName(f.Pointer()) + panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", fn)) } return want } @@ -342,241 +380,140 @@ func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { // assuming that T is assignable to R. // Otherwise, it returns the input value as is. func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value { - // TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143). - if !flags.AtLeastGo110 { - if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t { - return reflect.New(t).Elem() - } + // TODO(dsnet): Remove this hacky workaround. + // See https://golang.org/issue/22143 + if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t { + return reflect.New(t).Elem() } return v } -func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { - var vax, vay reflect.Value // Addressable versions of vx and vy +func (s *state) compareArray(vx, vy reflect.Value, t reflect.Type) { + step := &sliceIndex{pathStep{t.Elem()}, 0, 0} + s.curPath.push(step) - step := StructField{&structField{}} - for i := 0; i < t.NumField(); i++ { - step.typ = t.Field(i).Type - step.vx = vx.Field(i) - step.vy = vy.Field(i) - step.name = t.Field(i).Name - step.idx = i - step.unexported = !isExported(step.name) - if step.unexported { - if step.name == "_" { - continue - } - // Defer checking of unexported fields until later to give an - // Ignore a chance to ignore the field. - if !vax.IsValid() || !vay.IsValid() { - // For retrieveUnexportedField to work, the parent struct must - // be addressable. Create a new copy of the values if - // necessary to make them addressable. - vax = makeAddressable(vx) - vay = makeAddressable(vy) - } - step.mayForce = s.exporters[t] - step.pvx = vax - step.pvy = vay - step.field = t.Field(i) - } - s.compareAny(step) - } -} + // Compute an edit-script for slices vx and vy. + es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result { + step.xkey, step.ykey = ix, iy + return s.statelessCompare(vx.Index(ix), vy.Index(iy)) + }) -func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) { - isSlice := t.Kind() == reflect.Slice - if isSlice && (vx.IsNil() || vy.IsNil()) { - s.report(vx.IsNil() && vy.IsNil(), 0) + // Report the entire slice as is if the arrays are of primitive kind, + // and the arrays are different enough. + isPrimitive := false + switch t.Elem().Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + isPrimitive = true + } + if isPrimitive && es.Dist() > (vx.Len()+vy.Len())/4 { + s.curPath.pop() // Pop first since we are reporting the whole slice + s.report(false, vx, vy) return } - // TODO: Support cyclic data structures. - - step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}}} - withIndexes := func(ix, iy int) SliceIndex { - if ix >= 0 { - step.vx, step.xkey = vx.Index(ix), ix - } else { - step.vx, step.xkey = reflect.Value{}, -1 - } - if iy >= 0 { - step.vy, step.ykey = vy.Index(iy), iy - } else { - step.vy, step.ykey = reflect.Value{}, -1 - } - return step - } - - // Ignore options are able to ignore missing elements in a slice. - // However, detecting these reliably requires an optimal differencing - // algorithm, for which diff.Difference is not. - // - // Instead, we first iterate through both slices to detect which elements - // would be ignored if standing alone. The index of non-discarded elements - // are stored in a separate slice, which diffing is then performed on. - var indexesX, indexesY []int - var ignoredX, ignoredY []bool - for ix := 0; ix < vx.Len(); ix++ { - ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0 - if !ignored { - indexesX = append(indexesX, ix) - } - ignoredX = append(ignoredX, ignored) - } - for iy := 0; iy < vy.Len(); iy++ { - ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0 - if !ignored { - indexesY = append(indexesY, iy) - } - ignoredY = append(ignoredY, ignored) - } - - // Compute an edit-script for slices vx and vy (excluding ignored elements). - edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result { - return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy])) - }) - - // Replay the ignore-scripts and the edit-script. + // Replay the edit-script. var ix, iy int - for ix < vx.Len() || iy < vy.Len() { - var e diff.EditType - switch { - case ix < len(ignoredX) && ignoredX[ix]: - e = diff.UniqueX - case iy < len(ignoredY) && ignoredY[iy]: - e = diff.UniqueY - default: - e, edits = edits[0], edits[1:] - } + for _, e := range es { switch e { case diff.UniqueX: - s.compareAny(withIndexes(ix, -1)) + step.xkey, step.ykey = ix, -1 + s.report(false, vx.Index(ix), nothing) ix++ case diff.UniqueY: - s.compareAny(withIndexes(-1, iy)) + step.xkey, step.ykey = -1, iy + s.report(false, nothing, vy.Index(iy)) iy++ default: - s.compareAny(withIndexes(ix, iy)) + step.xkey, step.ykey = ix, iy + if e == diff.Identity { + s.report(true, vx.Index(ix), vy.Index(iy)) + } else { + s.compareAny(vx.Index(ix), vy.Index(iy)) + } ix++ iy++ } } + s.curPath.pop() + return } -func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) { +func (s *state) compareMap(vx, vy reflect.Value, t reflect.Type) { if vx.IsNil() || vy.IsNil() { - s.report(vx.IsNil() && vy.IsNil(), 0) + s.report(vx.IsNil() && vy.IsNil(), vx, vy) return } - // TODO: Support cyclic data structures. - // We combine and sort the two map keys so that we can perform the // comparisons in a deterministic order. - step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}} + step := &mapIndex{pathStep: pathStep{t.Elem()}} + s.curPath.push(step) + defer s.curPath.pop() for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) { - step.vx = vx.MapIndex(k) - step.vy = vy.MapIndex(k) step.key = k - if !step.vx.IsValid() && !step.vy.IsValid() { - // It is possible for both vx and vy to be invalid if the - // key contained a NaN value in it. - // - // Even with the ability to retrieve NaN keys in Go 1.12, - // there still isn't a sensible way to compare the values since - // a NaN key may map to multiple unordered values. - // The most reasonable way to compare NaNs would be to compare the - // set of values. However, this is impossible to do efficiently - // since set equality is provably an O(n^2) operation given only - // an Equal function. If we had a Less function or Hash function, - // this could be done in O(n*log(n)) or O(n), respectively. - // - // Rather than adding complex logic to deal with NaNs, make it - // the user's responsibility to compare such obscure maps. - const help = "consider providing a Comparer to compare the map" - panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help)) + vvx := vx.MapIndex(k) + vvy := vy.MapIndex(k) + switch { + case vvx.IsValid() && vvy.IsValid(): + s.compareAny(vvx, vvy) + case vvx.IsValid() && !vvy.IsValid(): + s.report(false, vvx, nothing) + case !vvx.IsValid() && vvy.IsValid(): + s.report(false, nothing, vvy) + default: + // It is possible for both vvx and vvy to be invalid if the + // key contained a NaN value in it. There is no way in + // reflection to be able to retrieve these values. + // See https://golang.org/issue/11104 + panic(fmt.Sprintf("%#v has map key with NaNs", s.curPath)) } - s.compareAny(step) } } -func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) { - if vx.IsNil() || vy.IsNil() { - s.report(vx.IsNil() && vy.IsNil(), 0) - return - } - - // TODO: Support cyclic data structures. - - vx, vy = vx.Elem(), vy.Elem() - s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}}) -} - -func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) { - if vx.IsNil() || vy.IsNil() { - s.report(vx.IsNil() && vy.IsNil(), 0) - return - } - vx, vy = vx.Elem(), vy.Elem() - if vx.Type() != vy.Type() { - s.report(false, 0) - return - } - s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}}) -} +func (s *state) compareStruct(vx, vy reflect.Value, t reflect.Type) { + var vax, vay reflect.Value // Addressable versions of vx and vy -func (s *state) report(eq bool, rf resultFlags) { - if rf&reportByIgnore == 0 { - if eq { - s.result.NumSame++ - rf |= reportEqual - } else { - s.result.NumDiff++ - rf |= reportUnequal + step := &structField{} + s.curPath.push(step) + defer s.curPath.pop() + for i := 0; i < t.NumField(); i++ { + vvx := vx.Field(i) + vvy := vy.Field(i) + step.typ = t.Field(i).Type + step.name = t.Field(i).Name + step.idx = i + step.unexported = !isExported(step.name) + if step.unexported { + // Defer checking of unexported fields until later to give an + // Ignore a chance to ignore the field. + if !vax.IsValid() || !vay.IsValid() { + // For unsafeRetrieveField to work, the parent struct must + // be addressable. Create a new copy of the values if + // necessary to make them addressable. + vax = makeAddressable(vx) + vay = makeAddressable(vy) + } + step.force = s.exporters[t] + step.pvx = vax + step.pvy = vay + step.field = t.Field(i) } - } - for _, r := range s.reporters { - r.Report(Result{flags: rf}) + s.compareAny(vvx, vvy) } } -// recChecker tracks the state needed to periodically perform checks that -// user provided transformers are not stuck in an infinitely recursive cycle. -type recChecker struct{ next int } - -// Check scans the Path for any recursive transformers and panics when any -// recursive transformers are detected. Note that the presence of a -// recursive Transformer does not necessarily imply an infinite cycle. -// As such, this check only activates after some minimal number of path steps. -func (rc *recChecker) Check(p Path) { - const minLen = 1 << 16 - if rc.next == 0 { - rc.next = minLen - } - if len(p) < rc.next { - return - } - rc.next <<= 1 - - // Check whether the same transformer has appeared at least twice. - var ss []string - m := map[Option]int{} - for _, ps := range p { - if t, ok := ps.(Transform); ok { - t := t.Option() - if m[t] == 1 { // Transformer was used exactly once before - tf := t.(*transformer).fnc.Type() - ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) - } - m[t]++ - } +// report records the result of a single comparison. +// It also calls Report if any reporter is registered. +func (s *state) report(eq bool, vx, vy reflect.Value) { + if eq { + s.result.NSame++ + } else { + s.result.NDiff++ } - if len(ss) > 0 { - const warning = "recursive set of Transformers detected" - const help = "consider using cmpopts.AcyclicTransformer" - set := strings.Join(ss, "\n\t") - panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) + if s.reporter != nil { + s.reporter.Report(vx, vy, eq, s.curPath) } } diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go index fe98dcc67..42afa4960 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. -// +build !cmp_debug +// +build !debug package diff diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go index 597b6ae56..fd9f7f177 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. -// +build cmp_debug +// +build debug package diff @@ -14,7 +14,7 @@ import ( ) // The algorithm can be seen running in real-time by enabling debugging: -// go test -tags=cmp_debug -v +// go test -tags=debug -v // // Example output: // === RUN TestDifference/#34 diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go index 3d2e42662..260befea2 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go @@ -85,31 +85,22 @@ func (es EditScript) LenY() int { return len(es) - es.stats().NX } type EqualFunc func(ix int, iy int) Result // Result is the result of comparison. -// NumSame is the number of sub-elements that are equal. -// NumDiff is the number of sub-elements that are not equal. -type Result struct{ NumSame, NumDiff int } - -// BoolResult returns a Result that is either Equal or not Equal. -func BoolResult(b bool) Result { - if b { - return Result{NumSame: 1} // Equal, Similar - } else { - return Result{NumDiff: 2} // Not Equal, not Similar - } -} +// NSame is the number of sub-elements that are equal. +// NDiff is the number of sub-elements that are not equal. +type Result struct{ NSame, NDiff int } // Equal indicates whether the symbols are equal. Two symbols are equal -// if and only if NumDiff == 0. If Equal, then they are also Similar. -func (r Result) Equal() bool { return r.NumDiff == 0 } +// if and only if NDiff == 0. If Equal, then they are also Similar. +func (r Result) Equal() bool { return r.NDiff == 0 } // Similar indicates whether two symbols are similar and may be represented // by using the Modified type. As a special case, we consider binary comparisons // (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar. // -// The exact ratio of NumSame to NumDiff to determine similarity may change. +// The exact ratio of NSame to NDiff to determine similarity may change. func (r Result) Similar() bool { - // Use NumSame+1 to offset NumSame so that binary comparisons are similar. - return r.NumSame+1 >= r.NumDiff + // Use NSame+1 to offset NSame so that binary comparisons are similar. + return r.NSame+1 >= r.NDiff } // Difference reports whether two lists of lengths nx and ny are equal @@ -200,9 +191,9 @@ func Difference(nx, ny int, f EqualFunc) (es EditScript) { // that two lists commonly differ because elements were added to the front // or end of the other list. // - // Running the tests with the "cmp_debug" build tag prints a visualization - // of the algorithm running in real-time. This is educational for - // understanding how the algorithm works. See debug_enable.go. + // Running the tests with the "debug" build tag prints a visualization of + // the algorithm running in real-time. This is educational for understanding + // how the algorithm works. See debug_enable.go. f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es) for { // Forward search from the beginning. diff --git a/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go b/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go deleted file mode 100644 index a9e7fc0b5..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package flags - -// Deterministic controls whether the output of Diff should be deterministic. -// This is only used for testing. -var Deterministic bool diff --git a/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_legacy.go b/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_legacy.go deleted file mode 100644 index 01aed0a15..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_legacy.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -// +build !go1.10 - -package flags - -// AtLeastGo110 reports whether the Go toolchain is at least Go 1.10. -const AtLeastGo110 = false diff --git a/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_recent.go b/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_recent.go deleted file mode 100644 index c0b667f58..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/flags/toolchain_recent.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -// +build go1.10 - -package flags - -// AtLeastGo110 reports whether the Go toolchain is at least Go 1.10. -const AtLeastGo110 = true diff --git a/vendor/github.com/google/go-cmp/cmp/internal/function/func.go b/vendor/github.com/google/go-cmp/cmp/internal/function/func.go index ace1dbe86..4c35ff11e 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/function/func.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/function/func.go @@ -2,34 +2,25 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. -// Package function provides functionality for identifying function types. +// Package function identifies function types. package function -import ( - "reflect" - "regexp" - "runtime" - "strings" -) +import "reflect" type funcType int const ( _ funcType = iota - tbFunc // func(T) bool ttbFunc // func(T, T) bool - trbFunc // func(T, R) bool tibFunc // func(T, I) bool trFunc // func(T) R - Equal = ttbFunc // func(T, T) bool - EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool - Transformer = trFunc // func(T) R - ValueFilter = ttbFunc // func(T, T) bool - Less = ttbFunc // func(T, T) bool - ValuePredicate = tbFunc // func(T) bool - KeyValuePredicate = trbFunc // func(T, R) bool + Equal = ttbFunc // func(T, T) bool + EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool + Transformer = trFunc // func(T) R + ValueFilter = ttbFunc // func(T, T) bool + Less = ttbFunc // func(T, T) bool ) var boolType = reflect.TypeOf(true) @@ -41,18 +32,10 @@ func IsType(t reflect.Type, ft funcType) bool { } ni, no := t.NumIn(), t.NumOut() switch ft { - case tbFunc: // func(T) bool - if ni == 1 && no == 1 && t.Out(0) == boolType { - return true - } case ttbFunc: // func(T, T) bool if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType { return true } - case trbFunc: // func(T, R) bool - if ni == 2 && no == 1 && t.Out(0) == boolType { - return true - } case tibFunc: // func(T, I) bool if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType { return true @@ -64,36 +47,3 @@ func IsType(t reflect.Type, ft funcType) bool { } return false } - -var lastIdentRx = regexp.MustCompile(`[_\p{L}][_\p{L}\p{N}]*$`) - -// NameOf returns the name of the function value. -func NameOf(v reflect.Value) string { - fnc := runtime.FuncForPC(v.Pointer()) - if fnc == nil { - return "" - } - fullName := fnc.Name() // e.g., "long/path/name/mypkg.(*MyType).(long/path/name/mypkg.myMethod)-fm" - - // Method closures have a "-fm" suffix. - fullName = strings.TrimSuffix(fullName, "-fm") - - var name string - for len(fullName) > 0 { - inParen := strings.HasSuffix(fullName, ")") - fullName = strings.TrimSuffix(fullName, ")") - - s := lastIdentRx.FindString(fullName) - if s == "" { - break - } - name = s + "." + name - fullName = strings.TrimSuffix(fullName, s) - - if i := strings.LastIndexByte(fullName, '('); inParen && i >= 0 { - fullName = fullName[:i] - } - fullName = strings.TrimSuffix(fullName, ".") - } - return strings.TrimSuffix(name, ".") -} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/format.go b/vendor/github.com/google/go-cmp/cmp/internal/value/format.go new file mode 100644 index 000000000..657e50877 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/format.go @@ -0,0 +1,277 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE.md file. + +// Package value provides functionality for reflect.Value types. +package value + +import ( + "fmt" + "reflect" + "strconv" + "strings" + "unicode" +) + +var stringerIface = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() + +// Format formats the value v as a string. +// +// This is similar to fmt.Sprintf("%+v", v) except this: +// * Prints the type unless it can be elided +// * Avoids printing struct fields that are zero +// * Prints a nil-slice as being nil, not empty +// * Prints map entries in deterministic order +func Format(v reflect.Value, conf FormatConfig) string { + conf.printType = true + conf.followPointers = true + conf.realPointers = true + return formatAny(v, conf, nil) +} + +type FormatConfig struct { + UseStringer bool // Should the String method be used if available? + printType bool // Should we print the type before the value? + PrintPrimitiveType bool // Should we print the type of primitives? + followPointers bool // Should we recursively follow pointers? + realPointers bool // Should we print the real address of pointers? +} + +func formatAny(v reflect.Value, conf FormatConfig, visited map[uintptr]bool) string { + // TODO: Should this be a multi-line printout in certain situations? + + if !v.IsValid() { + return "" + } + if conf.UseStringer && v.Type().Implements(stringerIface) && v.CanInterface() { + if (v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) && v.IsNil() { + return "" + } + + const stringerPrefix = "s" // Indicates that the String method was used + s := v.Interface().(fmt.Stringer).String() + return stringerPrefix + formatString(s) + } + + switch v.Kind() { + case reflect.Bool: + return formatPrimitive(v.Type(), v.Bool(), conf) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return formatPrimitive(v.Type(), v.Int(), conf) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + if v.Type().PkgPath() == "" || v.Kind() == reflect.Uintptr { + // Unnamed uints are usually bytes or words, so use hexadecimal. + return formatPrimitive(v.Type(), formatHex(v.Uint()), conf) + } + return formatPrimitive(v.Type(), v.Uint(), conf) + case reflect.Float32, reflect.Float64: + return formatPrimitive(v.Type(), v.Float(), conf) + case reflect.Complex64, reflect.Complex128: + return formatPrimitive(v.Type(), v.Complex(), conf) + case reflect.String: + return formatPrimitive(v.Type(), formatString(v.String()), conf) + case reflect.UnsafePointer, reflect.Chan, reflect.Func: + return formatPointer(v, conf) + case reflect.Ptr: + if v.IsNil() { + if conf.printType { + return fmt.Sprintf("(%v)(nil)", v.Type()) + } + return "" + } + if visited[v.Pointer()] || !conf.followPointers { + return formatPointer(v, conf) + } + visited = insertPointer(visited, v.Pointer()) + return "&" + formatAny(v.Elem(), conf, visited) + case reflect.Interface: + if v.IsNil() { + if conf.printType { + return fmt.Sprintf("%v(nil)", v.Type()) + } + return "" + } + return formatAny(v.Elem(), conf, visited) + case reflect.Slice: + if v.IsNil() { + if conf.printType { + return fmt.Sprintf("%v(nil)", v.Type()) + } + return "" + } + if visited[v.Pointer()] { + return formatPointer(v, conf) + } + visited = insertPointer(visited, v.Pointer()) + fallthrough + case reflect.Array: + var ss []string + subConf := conf + subConf.printType = v.Type().Elem().Kind() == reflect.Interface + for i := 0; i < v.Len(); i++ { + s := formatAny(v.Index(i), subConf, visited) + ss = append(ss, s) + } + s := fmt.Sprintf("{%s}", strings.Join(ss, ", ")) + if conf.printType { + return v.Type().String() + s + } + return s + case reflect.Map: + if v.IsNil() { + if conf.printType { + return fmt.Sprintf("%v(nil)", v.Type()) + } + return "" + } + if visited[v.Pointer()] { + return formatPointer(v, conf) + } + visited = insertPointer(visited, v.Pointer()) + + var ss []string + keyConf, valConf := conf, conf + keyConf.printType = v.Type().Key().Kind() == reflect.Interface + keyConf.followPointers = false + valConf.printType = v.Type().Elem().Kind() == reflect.Interface + for _, k := range SortKeys(v.MapKeys()) { + sk := formatAny(k, keyConf, visited) + sv := formatAny(v.MapIndex(k), valConf, visited) + ss = append(ss, fmt.Sprintf("%s: %s", sk, sv)) + } + s := fmt.Sprintf("{%s}", strings.Join(ss, ", ")) + if conf.printType { + return v.Type().String() + s + } + return s + case reflect.Struct: + var ss []string + subConf := conf + subConf.printType = true + for i := 0; i < v.NumField(); i++ { + vv := v.Field(i) + if isZero(vv) { + continue // Elide zero value fields + } + name := v.Type().Field(i).Name + subConf.UseStringer = conf.UseStringer + s := formatAny(vv, subConf, visited) + ss = append(ss, fmt.Sprintf("%s: %s", name, s)) + } + s := fmt.Sprintf("{%s}", strings.Join(ss, ", ")) + if conf.printType { + return v.Type().String() + s + } + return s + default: + panic(fmt.Sprintf("%v kind not handled", v.Kind())) + } +} + +func formatString(s string) string { + // Use quoted string if it the same length as a raw string literal. + // Otherwise, attempt to use the raw string form. + qs := strconv.Quote(s) + if len(qs) == 1+len(s)+1 { + return qs + } + + // Disallow newlines to ensure output is a single line. + // Only allow printable runes for readability purposes. + rawInvalid := func(r rune) bool { + return r == '`' || r == '\n' || !unicode.IsPrint(r) + } + if strings.IndexFunc(s, rawInvalid) < 0 { + return "`" + s + "`" + } + return qs +} + +func formatPrimitive(t reflect.Type, v interface{}, conf FormatConfig) string { + if conf.printType && (conf.PrintPrimitiveType || t.PkgPath() != "") { + return fmt.Sprintf("%v(%v)", t, v) + } + return fmt.Sprintf("%v", v) +} + +func formatPointer(v reflect.Value, conf FormatConfig) string { + p := v.Pointer() + if !conf.realPointers { + p = 0 // For deterministic printing purposes + } + s := formatHex(uint64(p)) + if conf.printType { + return fmt.Sprintf("(%v)(%s)", v.Type(), s) + } + return s +} + +func formatHex(u uint64) string { + var f string + switch { + case u <= 0xff: + f = "0x%02x" + case u <= 0xffff: + f = "0x%04x" + case u <= 0xffffff: + f = "0x%06x" + case u <= 0xffffffff: + f = "0x%08x" + case u <= 0xffffffffff: + f = "0x%010x" + case u <= 0xffffffffffff: + f = "0x%012x" + case u <= 0xffffffffffffff: + f = "0x%014x" + case u <= 0xffffffffffffffff: + f = "0x%016x" + } + return fmt.Sprintf(f, u) +} + +// insertPointer insert p into m, allocating m if necessary. +func insertPointer(m map[uintptr]bool, p uintptr) map[uintptr]bool { + if m == nil { + m = make(map[uintptr]bool) + } + m[p] = true + return m +} + +// isZero reports whether v is the zero value. +// This does not rely on Interface and so can be used on unexported fields. +func isZero(v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + return v.Bool() == false + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Complex64, reflect.Complex128: + return v.Complex() == 0 + case reflect.String: + return v.String() == "" + case reflect.UnsafePointer: + return v.Pointer() == 0 + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + return v.IsNil() + case reflect.Array: + for i := 0; i < v.Len(); i++ { + if !isZero(v.Index(i)) { + return false + } + } + return true + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go deleted file mode 100644 index 0a01c4796..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2018, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -// +build purego - -package value - -import "reflect" - -// Pointer is an opaque typed pointer and is guaranteed to be comparable. -type Pointer struct { - p uintptr - t reflect.Type -} - -// PointerOf returns a Pointer from v, which must be a -// reflect.Ptr, reflect.Slice, or reflect.Map. -func PointerOf(v reflect.Value) Pointer { - // NOTE: Storing a pointer as an uintptr is technically incorrect as it - // assumes that the GC implementation does not use a moving collector. - return Pointer{v.Pointer(), v.Type()} -} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go deleted file mode 100644 index da134ae2a..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2018, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -// +build !purego - -package value - -import ( - "reflect" - "unsafe" -) - -// Pointer is an opaque typed pointer and is guaranteed to be comparable. -type Pointer struct { - p unsafe.Pointer - t reflect.Type -} - -// PointerOf returns a Pointer from v, which must be a -// reflect.Ptr, reflect.Slice, or reflect.Map. -func PointerOf(v reflect.Value) Pointer { - // The proper representation of a pointer is unsafe.Pointer, - // which is necessary if the GC ever uses a moving collector. - return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} -} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go b/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go index 938f646f0..fe8aa27a0 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go @@ -19,7 +19,7 @@ func SortKeys(vs []reflect.Value) []reflect.Value { } // Sort the map keys. - sort.Slice(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) }) + sort.Sort(valueSorter(vs)) // Deduplicate keys (fails for NaNs). vs2 := vs[:1] @@ -31,6 +31,13 @@ func SortKeys(vs []reflect.Value) []reflect.Value { return vs2 } +// TODO: Use sort.Slice once Google AppEngine is on Go1.8 or above. +type valueSorter []reflect.Value + +func (vs valueSorter) Len() int { return len(vs) } +func (vs valueSorter) Less(i, j int) bool { return isLess(vs[i], vs[j]) } +func (vs valueSorter) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } + // isLess is a generic function for sorting arbitrary map keys. // The inputs must be of the same type and must be comparable. func isLess(x, y reflect.Value) bool { diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/zero.go b/vendor/github.com/google/go-cmp/cmp/internal/value/zero.go deleted file mode 100644 index d13a12ccf..000000000 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/zero.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package value - -import "reflect" - -// IsZero reports whether v is the zero value. -// This does not rely on Interface and so can be used on unexported fields. -func IsZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return v.Bool() == false - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Complex64, reflect.Complex128: - return v.Complex() == 0 - case reflect.String: - return v.String() == "" - case reflect.UnsafePointer: - return v.Pointer() == 0 - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - return v.IsNil() - case reflect.Array: - for i := 0; i < v.Len(); i++ { - if !IsZero(v.Index(i)) { - return false - } - } - return true - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - if !IsZero(v.Field(i)) { - return false - } - } - return true - } - return false -} diff --git a/vendor/github.com/google/go-cmp/cmp/options.go b/vendor/github.com/google/go-cmp/cmp/options.go index 793448160..91d4b066e 100644 --- a/vendor/github.com/google/go-cmp/cmp/options.go +++ b/vendor/github.com/google/go-cmp/cmp/options.go @@ -7,7 +7,7 @@ package cmp import ( "fmt" "reflect" - "regexp" + "runtime" "strings" "github.com/google/go-cmp/cmp/internal/function" @@ -29,11 +29,11 @@ type Option interface { // An Options is returned only if multiple comparers or transformers // can apply simultaneously and will only contain values of those types // or sub-Options containing values of those types. - filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption + filter(s *state, vx, vy reflect.Value, t reflect.Type) applicableOption } // applicableOption represents the following types: -// Fundamental: ignore | validator | *comparer | *transformer +// Fundamental: ignore | invalid | *comparer | *transformer // Grouping: Options type applicableOption interface { Option @@ -43,7 +43,7 @@ type applicableOption interface { } // coreOption represents the following types: -// Fundamental: ignore | validator | *comparer | *transformer +// Fundamental: ignore | invalid | *comparer | *transformer // Filters: *pathFilter | *valuesFilter type coreOption interface { Option @@ -63,19 +63,19 @@ func (core) isCore() {} // on all individual options held within. type Options []Option -func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) { +func (opts Options) filter(s *state, vx, vy reflect.Value, t reflect.Type) (out applicableOption) { for _, opt := range opts { - switch opt := opt.filter(s, t, vx, vy); opt.(type) { + switch opt := opt.filter(s, vx, vy, t); opt.(type) { case ignore: return ignore{} // Only ignore can short-circuit evaluation - case validator: - out = validator{} // Takes precedence over comparer or transformer + case invalid: + out = invalid{} // Takes precedence over comparer or transformer case *comparer, *transformer, Options: switch out.(type) { case nil: out = opt - case validator: - // Keep validator + case invalid: + // Keep invalid case *comparer, *transformer, Options: out = Options{out, opt} // Conflicting comparers or transformers } @@ -106,11 +106,6 @@ func (opts Options) String() string { // FilterPath returns a new Option where opt is only evaluated if filter f // returns true for the current Path in the value tree. // -// This filter is called even if a slice element or map entry is missing and -// provides an opportunity to ignore such cases. The filter function must be -// symmetric such that the filter result is identical regardless of whether the -// missing value is from x or y. -// // The option passed in may be an Ignore, Transformer, Comparer, Options, or // a previously filtered Option. func FilterPath(f func(Path) bool, opt Option) Option { @@ -129,22 +124,22 @@ type pathFilter struct { opt Option } -func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { +func (f pathFilter) filter(s *state, vx, vy reflect.Value, t reflect.Type) applicableOption { if f.fnc(s.curPath) { - return f.opt.filter(s, t, vx, vy) + return f.opt.filter(s, vx, vy, t) } return nil } func (f pathFilter) String() string { - return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt) + fn := getFuncName(reflect.ValueOf(f.fnc).Pointer()) + return fmt.Sprintf("FilterPath(%s, %v)", fn, f.opt) } // FilterValues returns a new Option where opt is only evaluated if filter f, // which is a function of the form "func(T, T) bool", returns true for the -// current pair of values being compared. If either value is invalid or -// the type of the values is not assignable to T, then this filter implicitly -// returns false. +// current pair of values being compared. If the type of the values is not +// assignable to T, then this filter implicitly returns false. // // The filter function must be // symmetric (i.e., agnostic to the order of the inputs) and @@ -176,18 +171,19 @@ type valuesFilter struct { opt Option } -func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { - if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() { - return nil +func (f valuesFilter) filter(s *state, vx, vy reflect.Value, t reflect.Type) applicableOption { + if !vx.IsValid() || !vy.IsValid() { + return invalid{} } if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) { - return f.opt.filter(s, t, vx, vy) + return f.opt.filter(s, vx, vy, t) } return nil } func (f valuesFilter) String() string { - return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt) + fn := getFuncName(f.fnc.Pointer()) + return fmt.Sprintf("FilterValues(%s, %v)", fn, f.opt) } // Ignore is an Option that causes all comparisons to be ignored. @@ -198,45 +194,20 @@ func Ignore() Option { return ignore{} } type ignore struct{ core } func (ignore) isFiltered() bool { return false } -func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} } -func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) } +func (ignore) filter(_ *state, _, _ reflect.Value, _ reflect.Type) applicableOption { return ignore{} } +func (ignore) apply(_ *state, _, _ reflect.Value) { return } func (ignore) String() string { return "Ignore()" } -// validator is a sentinel Option type to indicate that some options could not -// be evaluated due to unexported fields, missing slice elements, or -// missing map entries. Both values are validator only for unexported fields. -type validator struct{ core } - -func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption { - if !vx.IsValid() || !vy.IsValid() { - return validator{} - } - if !vx.CanInterface() || !vy.CanInterface() { - return validator{} - } - return nil -} -func (validator) apply(s *state, vx, vy reflect.Value) { - // Implies missing slice element or map entry. - if !vx.IsValid() || !vy.IsValid() { - s.report(vx.IsValid() == vy.IsValid(), 0) - return - } - - // Unable to Interface implies unexported field without visibility access. - if !vx.CanInterface() || !vy.CanInterface() { - const help = "consider using a custom Comparer; if you control the implementation of type, you can also consider AllowUnexported or cmpopts.IgnoreUnexported" - panic(fmt.Sprintf("cannot handle unexported field: %#v\n%s", s.curPath, help)) - } +// invalid is a sentinel Option type to indicate that some options could not +// be evaluated due to unexported fields. +type invalid struct{ core } - panic("not reachable") +func (invalid) filter(_ *state, _, _ reflect.Value, _ reflect.Type) applicableOption { return invalid{} } +func (invalid) apply(s *state, _, _ reflect.Value) { + const help = "consider using AllowUnexported or cmpopts.IgnoreUnexported" + panic(fmt.Sprintf("cannot handle unexported field: %#v\n%s", s.curPath, help)) } -// identRx represents a valid identifier according to the Go specification. -const identRx = `[_\p{L}][_\p{L}\p{N}]*` - -var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) - // Transformer returns an Option that applies a transformation function that // converts values of a certain type into that of another. // @@ -249,25 +220,18 @@ var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) // input and output types are the same), an implicit filter is added such that // a transformer is applicable only if that exact transformer is not already // in the tail of the Path since the last non-Transform step. -// For situations where the implicit filter is still insufficient, -// consider using cmpopts.AcyclicTransformer, which adds a filter -// to prevent the transformer from being recursively applied upon itself. // // The name is a user provided label that is used as the Transform.Name in the -// transformation PathStep (and eventually shown in the Diff output). -// The name must be a valid identifier or qualified identifier in Go syntax. -// If empty, an arbitrary name is used. +// transformation PathStep. If empty, an arbitrary name is used. func Transformer(name string, f interface{}) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.Transformer) || v.IsNil() { panic(fmt.Sprintf("invalid transformer function: %T", f)) } if name == "" { - name = function.NameOf(v) - if !identsRx.MatchString(name) { - name = "λ" // Lambda-symbol as placeholder name - } - } else if !identsRx.MatchString(name) { + name = "λ" // Lambda-symbol as place-holder for anonymous transformer + } + if !isValid(name) { panic(fmt.Sprintf("invalid name: %q", name)) } tr := &transformer{name: name, fnc: reflect.ValueOf(f)} @@ -286,9 +250,9 @@ type transformer struct { func (tr *transformer) isFiltered() bool { return tr.typ != nil } -func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption { +func (tr *transformer) filter(s *state, _, _ reflect.Value, t reflect.Type) applicableOption { for i := len(s.curPath) - 1; i >= 0; i-- { - if t, ok := s.curPath[i].(Transform); !ok { + if t, ok := s.curPath[i].(*transform); !ok { break // Hit most recent non-Transform step } else if tr == t.trans { return nil // Cannot directly use same Transform @@ -301,15 +265,18 @@ func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) appl } func (tr *transformer) apply(s *state, vx, vy reflect.Value) { - step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}} - vvx := s.callTRFunc(tr.fnc, vx, step) - vvy := s.callTRFunc(tr.fnc, vy, step) - step.vx, step.vy = vvx, vvy - s.compareAny(step) + // Update path before calling the Transformer so that dynamic checks + // will use the updated path. + s.curPath.push(&transform{pathStep{tr.fnc.Type().Out(0)}, tr}) + defer s.curPath.pop() + + vx = s.callTRFunc(tr.fnc, vx) + vy = s.callTRFunc(tr.fnc, vy) + s.compareAny(vx, vy) } func (tr transformer) String() string { - return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc)) + return fmt.Sprintf("Transformer(%s, %s)", tr.name, getFuncName(tr.fnc.Pointer())) } // Comparer returns an Option that determines whether two values are equal @@ -344,7 +311,7 @@ type comparer struct { func (cm *comparer) isFiltered() bool { return cm.typ != nil } -func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption { +func (cm *comparer) filter(_ *state, _, _ reflect.Value, t reflect.Type) applicableOption { if cm.typ == nil || t.AssignableTo(cm.typ) { return cm } @@ -353,11 +320,11 @@ func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applica func (cm *comparer) apply(s *state, vx, vy reflect.Value) { eq := s.callTTBFunc(cm.fnc, vx, vy) - s.report(eq, reportByFunc) + s.report(eq, vx, vy) } func (cm comparer) String() string { - return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc)) + return fmt.Sprintf("Comparer(%s)", getFuncName(cm.fnc.Pointer())) } // AllowUnexported returns an Option that forcibly allows operations on @@ -371,7 +338,7 @@ func (cm comparer) String() string { // defined in an internal package where the semantic meaning of an unexported // field is in the control of the user. // -// In many cases, a custom Comparer should be used instead that defines +// For some cases, a custom Comparer should be used instead that defines // equality as a function of the public API of a type rather than the underlying // unexported implementation. // @@ -403,92 +370,27 @@ func AllowUnexported(types ...interface{}) Option { type visibleStructs map[reflect.Type]bool -func (visibleStructs) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { +func (visibleStructs) filter(_ *state, _, _ reflect.Value, _ reflect.Type) applicableOption { panic("not implemented") } -// Result represents the comparison result for a single node and -// is provided by cmp when calling Result (see Reporter). -type Result struct { - _ [0]func() // Make Result incomparable - flags resultFlags -} - -// Equal reports whether the node was determined to be equal or not. -// As a special case, ignored nodes are considered equal. -func (r Result) Equal() bool { - return r.flags&(reportEqual|reportByIgnore) != 0 -} - -// ByIgnore reports whether the node is equal because it was ignored. -// This never reports true if Equal reports false. -func (r Result) ByIgnore() bool { - return r.flags&reportByIgnore != 0 -} - -// ByMethod reports whether the Equal method determined equality. -func (r Result) ByMethod() bool { - return r.flags&reportByMethod != 0 -} - -// ByFunc reports whether a Comparer function determined equality. -func (r Result) ByFunc() bool { - return r.flags&reportByFunc != 0 -} - -type resultFlags uint - -const ( - _ resultFlags = (1 << iota) / 2 - - reportEqual - reportUnequal - reportByIgnore - reportByMethod - reportByFunc -) - -// Reporter is an Option that can be passed to Equal. When Equal traverses -// the value trees, it calls PushStep as it descends into each node in the -// tree and PopStep as it ascend out of the node. The leaves of the tree are -// either compared (determined to be equal or not equal) or ignored and reported -// as such by calling the Report method. -func Reporter(r interface { - // PushStep is called when a tree-traversal operation is performed. - // The PathStep itself is only valid until the step is popped. - // The PathStep.Values are valid for the duration of the entire traversal - // and must not be mutated. - // - // Equal always calls PushStep at the start to provide an operation-less - // PathStep used to report the root values. +// reporter is an Option that configures how differences are reported. +type reporter interface { + // TODO: Not exported yet. // - // Within a slice, the exact set of inserted, removed, or modified elements - // is unspecified and may change in future implementations. - // The entries of a map are iterated through in an unspecified order. - PushStep(PathStep) - - // Report is called exactly once on leaf nodes to report whether the - // comparison identified the node as equal, unequal, or ignored. - // A leaf node is one that is immediately preceded by and followed by - // a pair of PushStep and PopStep calls. - Report(Result) - - // PopStep ascends back up the value tree. - // There is always a matching pop call for every push call. - PopStep() -}) Option { - return reporter{r} -} + // Perhaps add PushStep and PopStep and change Report to only accept + // a PathStep instead of the full-path? Adding a PushStep and PopStep makes + // it clear that we are traversing the value tree in a depth-first-search + // manner, which has an effect on how values are printed. -type reporter struct{ reporterIface } -type reporterIface interface { - PushStep(PathStep) - Report(Result) - PopStep() -} + Option -func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { - panic("not implemented") + // Report is called for every comparison made and will be provided with + // the two values being compared, the equality result, and the + // current path in the value tree. It is possible for x or y to be an + // invalid reflect.Value if one of the values is non-existent; + // which is possible with maps and slices. + Report(x, y reflect.Value, eq bool, p Path) } // normalizeOption normalizes the input options such that all Options groups @@ -522,3 +424,30 @@ func flattenOptions(dst, src Options) Options { } return dst } + +// getFuncName returns a short function name from the pointer. +// The string parsing logic works up until Go1.9. +func getFuncName(p uintptr) string { + fnc := runtime.FuncForPC(p) + if fnc == nil { + return "" + } + name := fnc.Name() // E.g., "long/path/name/mypkg.(mytype).(long/path/name/mypkg.myfunc)-fm" + if strings.HasSuffix(name, ")-fm") || strings.HasSuffix(name, ")·fm") { + // Strip the package name from method name. + name = strings.TrimSuffix(name, ")-fm") + name = strings.TrimSuffix(name, ")·fm") + if i := strings.LastIndexByte(name, '('); i >= 0 { + methodName := name[i+1:] // E.g., "long/path/name/mypkg.myfunc" + if j := strings.LastIndexByte(methodName, '.'); j >= 0 { + methodName = methodName[j+1:] // E.g., "myfunc" + } + name = name[:i] + methodName // E.g., "long/path/name/mypkg.(mytype)." + "myfunc" + } + } + if i := strings.LastIndexByte(name, '/'); i >= 0 { + // Strip the package name. + name = name[i+1:] // E.g., "mypkg.(mytype).myfunc" + } + return name +} diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go index 96fffd291..c08a3cf80 100644 --- a/vendor/github.com/google/go-cmp/cmp/path.go +++ b/vendor/github.com/google/go-cmp/cmp/path.go @@ -12,52 +12,80 @@ import ( "unicode/utf8" ) -// Path is a list of PathSteps describing the sequence of operations to get -// from some root type to the current position in the value tree. -// The first Path element is always an operation-less PathStep that exists -// simply to identify the initial type. -// -// When traversing structs with embedded structs, the embedded struct will -// always be accessed as a field before traversing the fields of the -// embedded struct themselves. That is, an exported field from the -// embedded struct will never be accessed directly from the parent struct. -type Path []PathStep - -// PathStep is a union-type for specific operations to traverse -// a value's tree structure. Users of this package never need to implement -// these types as values of this type will be returned by this package. -// -// Implementations of this interface are -// StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform. -type PathStep interface { - String() string +type ( + // Path is a list of PathSteps describing the sequence of operations to get + // from some root type to the current position in the value tree. + // The first Path element is always an operation-less PathStep that exists + // simply to identify the initial type. + // + // When traversing structs with embedded structs, the embedded struct will + // always be accessed as a field before traversing the fields of the + // embedded struct themselves. That is, an exported field from the + // embedded struct will never be accessed directly from the parent struct. + Path []PathStep + + // PathStep is a union-type for specific operations to traverse + // a value's tree structure. Users of this package never need to implement + // these types as values of this type will be returned by this package. + PathStep interface { + String() string + Type() reflect.Type // Resulting type after performing the path step + isPathStep() + } - // Type is the resulting type after performing the path step. - Type() reflect.Type + // SliceIndex is an index operation on a slice or array at some index Key. + SliceIndex interface { + PathStep + Key() int // May return -1 if in a split state + + // SplitKeys returns the indexes for indexing into slices in the + // x and y values, respectively. These indexes may differ due to the + // insertion or removal of an element in one of the slices, causing + // all of the indexes to be shifted. If an index is -1, then that + // indicates that the element does not exist in the associated slice. + // + // Key is guaranteed to return -1 if and only if the indexes returned + // by SplitKeys are not the same. SplitKeys will never return -1 for + // both indexes. + SplitKeys() (x int, y int) + + isSliceIndex() + } + // MapIndex is an index operation on a map at some index Key. + MapIndex interface { + PathStep + Key() reflect.Value + isMapIndex() + } + // TypeAssertion represents a type assertion on an interface. + TypeAssertion interface { + PathStep + isTypeAssertion() + } + // StructField represents a struct field access on a field called Name. + StructField interface { + PathStep + Name() string + Index() int + isStructField() + } + // Indirect represents pointer indirection on the parent type. + Indirect interface { + PathStep + isIndirect() + } + // Transform is a transformation from the parent type to the current type. + Transform interface { + PathStep + Name() string + Func() reflect.Value - // Values is the resulting values after performing the path step. - // The type of each valid value is guaranteed to be identical to Type. - // - // In some cases, one or both may be invalid or have restrictions: - // • For StructField, both are not interface-able if the current field - // is unexported and the struct type is not explicitly permitted by - // AllowUnexported to traverse unexported fields. - // • For SliceIndex, one may be invalid if an element is missing from - // either the x or y slice. - // • For MapIndex, one may be invalid if an entry is missing from - // either the x or y map. - // - // The provided values must not be mutated. - Values() (vx, vy reflect.Value) -} + // Option returns the originally constructed Transformer option. + // The == operator can be used to detect the exact option used. + Option() Option -var ( - _ PathStep = StructField{} - _ PathStep = SliceIndex{} - _ PathStep = MapIndex{} - _ PathStep = Indirect{} - _ PathStep = TypeAssertion{} - _ PathStep = Transform{} + isTransform() + } ) func (pa *Path) push(s PathStep) { @@ -96,7 +124,7 @@ func (pa Path) Index(i int) PathStep { func (pa Path) String() string { var ss []string for _, s := range pa { - if _, ok := s.(StructField); ok { + if _, ok := s.(*structField); ok { ss = append(ss, s.String()) } } @@ -116,13 +144,13 @@ func (pa Path) GoString() string { nextStep = pa[i+1] } switch s := s.(type) { - case Indirect: + case *indirect: numIndirect++ pPre, pPost := "(", ")" switch nextStep.(type) { - case Indirect: + case *indirect: continue // Next step is indirection, so let them batch up - case StructField: + case *structField: numIndirect-- // Automatic indirection on struct fields case nil: pPre, pPost = "", "" // Last step; no need for parenthesis @@ -133,10 +161,19 @@ func (pa Path) GoString() string { } numIndirect = 0 continue - case Transform: + case *transform: ssPre = append(ssPre, s.trans.name+"(") ssPost = append(ssPost, ")") continue + case *typeAssertion: + // As a special-case, elide type assertions on anonymous types + // since they are typically generated dynamically and can be very + // verbose. For example, some transforms return interface{} because + // of Go's lack of generics, but typically take in and return the + // exact same concrete type. + if s.Type().PkgPath() == "" { + continue + } } ssPost = append(ssPost, s.String()) } @@ -146,13 +183,44 @@ func (pa Path) GoString() string { return strings.Join(ssPre, "") + strings.Join(ssPost, "") } -type pathStep struct { - typ reflect.Type - vx, vy reflect.Value -} +type ( + pathStep struct { + typ reflect.Type + } -func (ps pathStep) Type() reflect.Type { return ps.typ } -func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy } + sliceIndex struct { + pathStep + xkey, ykey int + } + mapIndex struct { + pathStep + key reflect.Value + } + typeAssertion struct { + pathStep + } + structField struct { + pathStep + name string + idx int + + // These fields are used for forcibly accessing an unexported field. + // pvx, pvy, and field are only valid if unexported is true. + unexported bool + force bool // Forcibly allow visibility + pvx, pvy reflect.Value // Parent values + field reflect.StructField // Field information + } + indirect struct { + pathStep + } + transform struct { + pathStep + trans *transformer + } +) + +func (ps pathStep) Type() reflect.Type { return ps.typ } func (ps pathStep) String() string { if ps.typ == nil { return "" @@ -164,54 +232,7 @@ func (ps pathStep) String() string { return fmt.Sprintf("{%s}", s) } -// StructField represents a struct field access on a field called Name. -type StructField struct{ *structField } -type structField struct { - pathStep - name string - idx int - - // These fields are used for forcibly accessing an unexported field. - // pvx, pvy, and field are only valid if unexported is true. - unexported bool - mayForce bool // Forcibly allow visibility - pvx, pvy reflect.Value // Parent values - field reflect.StructField // Field information -} - -func (sf StructField) Type() reflect.Type { return sf.typ } -func (sf StructField) Values() (vx, vy reflect.Value) { - if !sf.unexported { - return sf.vx, sf.vy // CanInterface reports true - } - - // Forcibly obtain read-write access to an unexported struct field. - if sf.mayForce { - vx = retrieveUnexportedField(sf.pvx, sf.field) - vy = retrieveUnexportedField(sf.pvy, sf.field) - return vx, vy // CanInterface reports true - } - return sf.vx, sf.vy // CanInterface reports false -} -func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) } - -// Name is the field name. -func (sf StructField) Name() string { return sf.name } - -// Index is the index of the field in the parent struct type. -// See reflect.Type.Field. -func (sf StructField) Index() int { return sf.idx } - -// SliceIndex is an index operation on a slice or array at some index Key. -type SliceIndex struct{ *sliceIndex } -type sliceIndex struct { - pathStep - xkey, ykey int -} - -func (si SliceIndex) Type() reflect.Type { return si.typ } -func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy } -func (si SliceIndex) String() string { +func (si sliceIndex) String() string { switch { case si.xkey == si.ykey: return fmt.Sprintf("[%d]", si.xkey) @@ -226,83 +247,63 @@ func (si SliceIndex) String() string { return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey) } } +func (mi mapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) } +func (ta typeAssertion) String() string { return fmt.Sprintf(".(%v)", ta.typ) } +func (sf structField) String() string { return fmt.Sprintf(".%s", sf.name) } +func (in indirect) String() string { return "*" } +func (tf transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } -// Key is the index key; it may return -1 if in a split state -func (si SliceIndex) Key() int { +func (si sliceIndex) Key() int { if si.xkey != si.ykey { return -1 } return si.xkey } +func (si sliceIndex) SplitKeys() (x, y int) { return si.xkey, si.ykey } +func (mi mapIndex) Key() reflect.Value { return mi.key } +func (sf structField) Name() string { return sf.name } +func (sf structField) Index() int { return sf.idx } +func (tf transform) Name() string { return tf.trans.name } +func (tf transform) Func() reflect.Value { return tf.trans.fnc } +func (tf transform) Option() Option { return tf.trans } + +func (pathStep) isPathStep() {} +func (sliceIndex) isSliceIndex() {} +func (mapIndex) isMapIndex() {} +func (typeAssertion) isTypeAssertion() {} +func (structField) isStructField() {} +func (indirect) isIndirect() {} +func (transform) isTransform() {} -// SplitKeys are the indexes for indexing into slices in the -// x and y values, respectively. These indexes may differ due to the -// insertion or removal of an element in one of the slices, causing -// all of the indexes to be shifted. If an index is -1, then that -// indicates that the element does not exist in the associated slice. -// -// Key is guaranteed to return -1 if and only if the indexes returned -// by SplitKeys are not the same. SplitKeys will never return -1 for -// both indexes. -func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey } - -// MapIndex is an index operation on a map at some index Key. -type MapIndex struct{ *mapIndex } -type mapIndex struct { - pathStep - key reflect.Value -} - -func (mi MapIndex) Type() reflect.Type { return mi.typ } -func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy } -func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) } - -// Key is the value of the map key. -func (mi MapIndex) Key() reflect.Value { return mi.key } - -// Indirect represents pointer indirection on the parent type. -type Indirect struct{ *indirect } -type indirect struct { - pathStep -} - -func (in Indirect) Type() reflect.Type { return in.typ } -func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy } -func (in Indirect) String() string { return "*" } - -// TypeAssertion represents a type assertion on an interface. -type TypeAssertion struct{ *typeAssertion } -type typeAssertion struct { - pathStep -} - -func (ta TypeAssertion) Type() reflect.Type { return ta.typ } -func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy } -func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", ta.typ) } - -// Transform is a transformation from the parent type to the current type. -type Transform struct{ *transform } -type transform struct { - pathStep - trans *transformer -} - -func (tf Transform) Type() reflect.Type { return tf.typ } -func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy } -func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } - -// Name is the name of the Transformer. -func (tf Transform) Name() string { return tf.trans.name } - -// Func is the function pointer to the transformer function. -func (tf Transform) Func() reflect.Value { return tf.trans.fnc } - -// Option returns the originally constructed Transformer option. -// The == operator can be used to detect the exact option used. -func (tf Transform) Option() Option { return tf.trans } +var ( + _ SliceIndex = sliceIndex{} + _ MapIndex = mapIndex{} + _ TypeAssertion = typeAssertion{} + _ StructField = structField{} + _ Indirect = indirect{} + _ Transform = transform{} + + _ PathStep = sliceIndex{} + _ PathStep = mapIndex{} + _ PathStep = typeAssertion{} + _ PathStep = structField{} + _ PathStep = indirect{} + _ PathStep = transform{} +) // isExported reports whether the identifier is exported. func isExported(id string) bool { r, _ := utf8.DecodeRuneInString(id) return unicode.IsUpper(r) } + +// isValid reports whether the identifier is valid. +// Empty and underscore-only strings are not valid. +func isValid(id string) bool { + ok := id != "" && id != "_" + for j, c := range id { + ok = ok && (j > 0 || !unicode.IsDigit(c)) + ok = ok && (c == '_' || unicode.IsLetter(c) || unicode.IsDigit(c)) + } + return ok +} diff --git a/vendor/github.com/google/go-cmp/cmp/report.go b/vendor/github.com/google/go-cmp/cmp/report.go deleted file mode 100644 index 6ddf29993..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -// defaultReporter implements the reporter interface. -// -// As Equal serially calls the PushStep, Report, and PopStep methods, the -// defaultReporter constructs a tree-based representation of the compared value -// and the result of each comparison (see valueNode). -// -// When the String method is called, the FormatDiff method transforms the -// valueNode tree into a textNode tree, which is a tree-based representation -// of the textual output (see textNode). -// -// Lastly, the textNode.String method produces the final report as a string. -type defaultReporter struct { - root *valueNode - curr *valueNode -} - -func (r *defaultReporter) PushStep(ps PathStep) { - r.curr = r.curr.PushStep(ps) - if r.root == nil { - r.root = r.curr - } -} -func (r *defaultReporter) Report(rs Result) { - r.curr.Report(rs) -} -func (r *defaultReporter) PopStep() { - r.curr = r.curr.PopStep() -} - -// String provides a full report of the differences detected as a structured -// literal in pseudo-Go syntax. String may only be called after the entire tree -// has been traversed. -func (r *defaultReporter) String() string { - assert(r.root != nil && r.curr == nil) - if r.root.NumDiff == 0 { - return "" - } - return formatOptions{}.FormatDiff(r.root).String() -} - -func assert(ok bool) { - if !ok { - panic("assertion failure") - } -} diff --git a/vendor/github.com/google/go-cmp/cmp/report_compare.go b/vendor/github.com/google/go-cmp/cmp/report_compare.go deleted file mode 100644 index 05efb992c..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report_compare.go +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -import ( - "fmt" - "reflect" - - "github.com/google/go-cmp/cmp/internal/value" -) - -// TODO: Enforce limits? -// * Enforce maximum number of records to print per node? -// * Enforce maximum size in bytes allowed? -// * As a heuristic, use less verbosity for equal nodes than unequal nodes. -// TODO: Enforce unique outputs? -// * Avoid Stringer methods if it results in same output? -// * Print pointer address if outputs still equal? - -// numContextRecords is the number of surrounding equal records to print. -const numContextRecords = 2 - -type diffMode byte - -const ( - diffUnknown diffMode = 0 - diffIdentical diffMode = ' ' - diffRemoved diffMode = '-' - diffInserted diffMode = '+' -) - -type typeMode int - -const ( - // emitType always prints the type. - emitType typeMode = iota - // elideType never prints the type. - elideType - // autoType prints the type only for composite kinds - // (i.e., structs, slices, arrays, and maps). - autoType -) - -type formatOptions struct { - // DiffMode controls the output mode of FormatDiff. - // - // If diffUnknown, then produce a diff of the x and y values. - // If diffIdentical, then emit values as if they were equal. - // If diffRemoved, then only emit x values (ignoring y values). - // If diffInserted, then only emit y values (ignoring x values). - DiffMode diffMode - - // TypeMode controls whether to print the type for the current node. - // - // As a general rule of thumb, we always print the type of the next node - // after an interface, and always elide the type of the next node after - // a slice or map node. - TypeMode typeMode - - // formatValueOptions are options specific to printing reflect.Values. - formatValueOptions -} - -func (opts formatOptions) WithDiffMode(d diffMode) formatOptions { - opts.DiffMode = d - return opts -} -func (opts formatOptions) WithTypeMode(t typeMode) formatOptions { - opts.TypeMode = t - return opts -} - -// FormatDiff converts a valueNode tree into a textNode tree, where the later -// is a textual representation of the differences detected in the former. -func (opts formatOptions) FormatDiff(v *valueNode) textNode { - // Check whether we have specialized formatting for this node. - // This is not necessary, but helpful for producing more readable outputs. - if opts.CanFormatDiffSlice(v) { - return opts.FormatDiffSlice(v) - } - - // For leaf nodes, format the value based on the reflect.Values alone. - if v.MaxDepth == 0 { - switch opts.DiffMode { - case diffUnknown, diffIdentical: - // Format Equal. - if v.NumDiff == 0 { - outx := opts.FormatValue(v.ValueX, visitedPointers{}) - outy := opts.FormatValue(v.ValueY, visitedPointers{}) - if v.NumIgnored > 0 && v.NumSame == 0 { - return textEllipsis - } else if outx.Len() < outy.Len() { - return outx - } else { - return outy - } - } - - // Format unequal. - assert(opts.DiffMode == diffUnknown) - var list textList - outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, visitedPointers{}) - outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, visitedPointers{}) - if outx != nil { - list = append(list, textRecord{Diff: '-', Value: outx}) - } - if outy != nil { - list = append(list, textRecord{Diff: '+', Value: outy}) - } - return opts.WithTypeMode(emitType).FormatType(v.Type, list) - case diffRemoved: - return opts.FormatValue(v.ValueX, visitedPointers{}) - case diffInserted: - return opts.FormatValue(v.ValueY, visitedPointers{}) - default: - panic("invalid diff mode") - } - } - - // Descend into the child value node. - if v.TransformerName != "" { - out := opts.WithTypeMode(emitType).FormatDiff(v.Value) - out = textWrap{"Inverse(" + v.TransformerName + ", ", out, ")"} - return opts.FormatType(v.Type, out) - } else { - switch k := v.Type.Kind(); k { - case reflect.Struct, reflect.Array, reflect.Slice, reflect.Map: - return opts.FormatType(v.Type, opts.formatDiffList(v.Records, k)) - case reflect.Ptr: - return textWrap{"&", opts.FormatDiff(v.Value), ""} - case reflect.Interface: - return opts.WithTypeMode(emitType).FormatDiff(v.Value) - default: - panic(fmt.Sprintf("%v cannot have children", k)) - } - } -} - -func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) textNode { - // Derive record name based on the data structure kind. - var name string - var formatKey func(reflect.Value) string - switch k { - case reflect.Struct: - name = "field" - opts = opts.WithTypeMode(autoType) - formatKey = func(v reflect.Value) string { return v.String() } - case reflect.Slice, reflect.Array: - name = "element" - opts = opts.WithTypeMode(elideType) - formatKey = func(reflect.Value) string { return "" } - case reflect.Map: - name = "entry" - opts = opts.WithTypeMode(elideType) - formatKey = formatMapKey - } - - // Handle unification. - switch opts.DiffMode { - case diffIdentical, diffRemoved, diffInserted: - var list textList - var deferredEllipsis bool // Add final "..." to indicate records were dropped - for _, r := range recs { - // Elide struct fields that are zero value. - if k == reflect.Struct { - var isZero bool - switch opts.DiffMode { - case diffIdentical: - isZero = value.IsZero(r.Value.ValueX) || value.IsZero(r.Value.ValueX) - case diffRemoved: - isZero = value.IsZero(r.Value.ValueX) - case diffInserted: - isZero = value.IsZero(r.Value.ValueY) - } - if isZero { - continue - } - } - // Elide ignored nodes. - if r.Value.NumIgnored > 0 && r.Value.NumSame+r.Value.NumDiff == 0 { - deferredEllipsis = !(k == reflect.Slice || k == reflect.Array) - if !deferredEllipsis { - list.AppendEllipsis(diffStats{}) - } - continue - } - if out := opts.FormatDiff(r.Value); out != nil { - list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) - } - } - if deferredEllipsis { - list.AppendEllipsis(diffStats{}) - } - return textWrap{"{", list, "}"} - case diffUnknown: - default: - panic("invalid diff mode") - } - - // Handle differencing. - var list textList - groups := coalesceAdjacentRecords(name, recs) - for i, ds := range groups { - // Handle equal records. - if ds.NumDiff() == 0 { - // Compute the number of leading and trailing records to print. - var numLo, numHi int - numEqual := ds.NumIgnored + ds.NumIdentical - for numLo < numContextRecords && numLo+numHi < numEqual && i != 0 { - if r := recs[numLo].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { - break - } - numLo++ - } - for numHi < numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { - if r := recs[numEqual-numHi-1].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { - break - } - numHi++ - } - if numEqual-(numLo+numHi) == 1 && ds.NumIgnored == 0 { - numHi++ // Avoid pointless coalescing of a single equal record - } - - // Format the equal values. - for _, r := range recs[:numLo] { - out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value) - list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) - } - if numEqual > numLo+numHi { - ds.NumIdentical -= numLo + numHi - list.AppendEllipsis(ds) - } - for _, r := range recs[numEqual-numHi : numEqual] { - out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value) - list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) - } - recs = recs[numEqual:] - continue - } - - // Handle unequal records. - for _, r := range recs[:ds.NumDiff()] { - switch { - case opts.CanFormatDiffSlice(r.Value): - out := opts.FormatDiffSlice(r.Value) - list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) - case r.Value.NumChildren == r.Value.MaxDepth: - outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value) - outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value) - if outx != nil { - list = append(list, textRecord{Diff: diffRemoved, Key: formatKey(r.Key), Value: outx}) - } - if outy != nil { - list = append(list, textRecord{Diff: diffInserted, Key: formatKey(r.Key), Value: outy}) - } - default: - out := opts.FormatDiff(r.Value) - list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) - } - } - recs = recs[ds.NumDiff():] - } - assert(len(recs) == 0) - return textWrap{"{", list, "}"} -} - -// coalesceAdjacentRecords coalesces the list of records into groups of -// adjacent equal, or unequal counts. -func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) { - var prevCase int // Arbitrary index into which case last occurred - lastStats := func(i int) *diffStats { - if prevCase != i { - groups = append(groups, diffStats{Name: name}) - prevCase = i - } - return &groups[len(groups)-1] - } - for _, r := range recs { - switch rv := r.Value; { - case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0: - lastStats(1).NumIgnored++ - case rv.NumDiff == 0: - lastStats(1).NumIdentical++ - case rv.NumDiff > 0 && !rv.ValueY.IsValid(): - lastStats(2).NumRemoved++ - case rv.NumDiff > 0 && !rv.ValueX.IsValid(): - lastStats(2).NumInserted++ - default: - lastStats(2).NumModified++ - } - } - return groups -} diff --git a/vendor/github.com/google/go-cmp/cmp/report_reflect.go b/vendor/github.com/google/go-cmp/cmp/report_reflect.go deleted file mode 100644 index 5521c604c..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report_reflect.go +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "unicode" - - "github.com/google/go-cmp/cmp/internal/flags" - "github.com/google/go-cmp/cmp/internal/value" -) - -type formatValueOptions struct { - // AvoidStringer controls whether to avoid calling custom stringer - // methods like error.Error or fmt.Stringer.String. - AvoidStringer bool - - // ShallowPointers controls whether to avoid descending into pointers. - // Useful when printing map keys, where pointer comparison is performed - // on the pointer address rather than the pointed-at value. - ShallowPointers bool - - // PrintAddresses controls whether to print the address of all pointers, - // slice elements, and maps. - PrintAddresses bool -} - -// FormatType prints the type as if it were wrapping s. -// This may return s as-is depending on the current type and TypeMode mode. -func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode { - // Check whether to emit the type or not. - switch opts.TypeMode { - case autoType: - switch t.Kind() { - case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map: - if s.Equal(textNil) { - return s - } - default: - return s - } - case elideType: - return s - } - - // Determine the type label, applying special handling for unnamed types. - typeName := t.String() - if t.Name() == "" { - // According to Go grammar, certain type literals contain symbols that - // do not strongly bind to the next lexicographical token (e.g., *T). - switch t.Kind() { - case reflect.Chan, reflect.Func, reflect.Ptr: - typeName = "(" + typeName + ")" - } - typeName = strings.Replace(typeName, "struct {", "struct{", -1) - typeName = strings.Replace(typeName, "interface {", "interface{", -1) - } - - // Avoid wrap the value in parenthesis if unnecessary. - if s, ok := s.(textWrap); ok { - hasParens := strings.HasPrefix(s.Prefix, "(") && strings.HasSuffix(s.Suffix, ")") - hasBraces := strings.HasPrefix(s.Prefix, "{") && strings.HasSuffix(s.Suffix, "}") - if hasParens || hasBraces { - return textWrap{typeName, s, ""} - } - } - return textWrap{typeName + "(", s, ")"} -} - -// FormatValue prints the reflect.Value, taking extra care to avoid descending -// into pointers already in m. As pointers are visited, m is also updated. -func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out textNode) { - if !v.IsValid() { - return nil - } - t := v.Type() - - // Check whether there is an Error or String method to call. - if !opts.AvoidStringer && v.CanInterface() { - // Avoid calling Error or String methods on nil receivers since many - // implementations crash when doing so. - if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() { - switch v := v.Interface().(type) { - case error: - return textLine("e" + formatString(v.Error())) - case fmt.Stringer: - return textLine("s" + formatString(v.String())) - } - } - } - - // Check whether to explicitly wrap the result with the type. - var skipType bool - defer func() { - if !skipType { - out = opts.FormatType(t, out) - } - }() - - var ptr string - switch t.Kind() { - case reflect.Bool: - return textLine(fmt.Sprint(v.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return textLine(fmt.Sprint(v.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - // Unnamed uints are usually bytes or words, so use hexadecimal. - if t.PkgPath() == "" || t.Kind() == reflect.Uintptr { - return textLine(formatHex(v.Uint())) - } - return textLine(fmt.Sprint(v.Uint())) - case reflect.Float32, reflect.Float64: - return textLine(fmt.Sprint(v.Float())) - case reflect.Complex64, reflect.Complex128: - return textLine(fmt.Sprint(v.Complex())) - case reflect.String: - return textLine(formatString(v.String())) - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - return textLine(formatPointer(v)) - case reflect.Struct: - var list textList - for i := 0; i < v.NumField(); i++ { - vv := v.Field(i) - if value.IsZero(vv) { - continue // Elide fields with zero values - } - s := opts.WithTypeMode(autoType).FormatValue(vv, m) - list = append(list, textRecord{Key: t.Field(i).Name, Value: s}) - } - return textWrap{"{", list, "}"} - case reflect.Slice: - if v.IsNil() { - return textNil - } - if opts.PrintAddresses { - ptr = formatPointer(v) - } - fallthrough - case reflect.Array: - var list textList - for i := 0; i < v.Len(); i++ { - vi := v.Index(i) - if vi.CanAddr() { // Check for cyclic elements - p := vi.Addr() - if m.Visit(p) { - var out textNode - out = textLine(formatPointer(p)) - out = opts.WithTypeMode(emitType).FormatType(p.Type(), out) - out = textWrap{"*", out, ""} - list = append(list, textRecord{Value: out}) - continue - } - } - s := opts.WithTypeMode(elideType).FormatValue(vi, m) - list = append(list, textRecord{Value: s}) - } - return textWrap{ptr + "{", list, "}"} - case reflect.Map: - if v.IsNil() { - return textNil - } - if m.Visit(v) { - return textLine(formatPointer(v)) - } - - var list textList - for _, k := range value.SortKeys(v.MapKeys()) { - sk := formatMapKey(k) - sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), m) - list = append(list, textRecord{Key: sk, Value: sv}) - } - if opts.PrintAddresses { - ptr = formatPointer(v) - } - return textWrap{ptr + "{", list, "}"} - case reflect.Ptr: - if v.IsNil() { - return textNil - } - if m.Visit(v) || opts.ShallowPointers { - return textLine(formatPointer(v)) - } - if opts.PrintAddresses { - ptr = formatPointer(v) - } - skipType = true // Let the underlying value print the type instead - return textWrap{"&" + ptr, opts.FormatValue(v.Elem(), m), ""} - case reflect.Interface: - if v.IsNil() { - return textNil - } - // Interfaces accept different concrete types, - // so configure the underlying value to explicitly print the type. - skipType = true // Print the concrete type instead - return opts.WithTypeMode(emitType).FormatValue(v.Elem(), m) - default: - panic(fmt.Sprintf("%v kind not handled", v.Kind())) - } -} - -// formatMapKey formats v as if it were a map key. -// The result is guaranteed to be a single line. -func formatMapKey(v reflect.Value) string { - var opts formatOptions - opts.TypeMode = elideType - opts.AvoidStringer = true - opts.ShallowPointers = true - s := opts.FormatValue(v, visitedPointers{}).String() - return strings.TrimSpace(s) -} - -// formatString prints s as a double-quoted or backtick-quoted string. -func formatString(s string) string { - // Use quoted string if it the same length as a raw string literal. - // Otherwise, attempt to use the raw string form. - qs := strconv.Quote(s) - if len(qs) == 1+len(s)+1 { - return qs - } - - // Disallow newlines to ensure output is a single line. - // Only allow printable runes for readability purposes. - rawInvalid := func(r rune) bool { - return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t') - } - if strings.IndexFunc(s, rawInvalid) < 0 { - return "`" + s + "`" - } - return qs -} - -// formatHex prints u as a hexadecimal integer in Go notation. -func formatHex(u uint64) string { - var f string - switch { - case u <= 0xff: - f = "0x%02x" - case u <= 0xffff: - f = "0x%04x" - case u <= 0xffffff: - f = "0x%06x" - case u <= 0xffffffff: - f = "0x%08x" - case u <= 0xffffffffff: - f = "0x%010x" - case u <= 0xffffffffffff: - f = "0x%012x" - case u <= 0xffffffffffffff: - f = "0x%014x" - case u <= 0xffffffffffffffff: - f = "0x%016x" - } - return fmt.Sprintf(f, u) -} - -// formatPointer prints the address of the pointer. -func formatPointer(v reflect.Value) string { - p := v.Pointer() - if flags.Deterministic { - p = 0xdeadf00f // Only used for stable testing purposes - } - return fmt.Sprintf("⟪0x%x⟫", p) -} - -type visitedPointers map[value.Pointer]struct{} - -// Visit inserts pointer v into the visited map and reports whether it had -// already been visited before. -func (m visitedPointers) Visit(v reflect.Value) bool { - p := value.PointerOf(v) - _, visited := m[p] - m[p] = struct{}{} - return visited -} diff --git a/vendor/github.com/google/go-cmp/cmp/report_slices.go b/vendor/github.com/google/go-cmp/cmp/report_slices.go deleted file mode 100644 index 8cb3265e7..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report_slices.go +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -import ( - "bytes" - "fmt" - "reflect" - "strings" - "unicode" - "unicode/utf8" - - "github.com/google/go-cmp/cmp/internal/diff" -) - -// CanFormatDiffSlice reports whether we support custom formatting for nodes -// that are slices of primitive kinds or strings. -func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool { - switch { - case opts.DiffMode != diffUnknown: - return false // Must be formatting in diff mode - case v.NumDiff == 0: - return false // No differences detected - case v.NumIgnored+v.NumCompared+v.NumTransformed > 0: - // TODO: Handle the case where someone uses bytes.Equal on a large slice. - return false // Some custom option was used to determined equality - case !v.ValueX.IsValid() || !v.ValueY.IsValid(): - return false // Both values must be valid - } - - switch t := v.Type; t.Kind() { - case reflect.String: - case reflect.Array, reflect.Slice: - // Only slices of primitive types have specialized handling. - switch t.Elem().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, - reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: - default: - return false - } - - // If a sufficient number of elements already differ, - // use specialized formatting even if length requirement is not met. - if v.NumDiff > v.NumSame { - return true - } - default: - return false - } - - // Use specialized string diffing for longer slices or strings. - const minLength = 64 - return v.ValueX.Len() >= minLength && v.ValueY.Len() >= minLength -} - -// FormatDiffSlice prints a diff for the slices (or strings) represented by v. -// This provides custom-tailored logic to make printing of differences in -// textual strings and slices of primitive kinds more readable. -func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { - assert(opts.DiffMode == diffUnknown) - t, vx, vy := v.Type, v.ValueX, v.ValueY - - // Auto-detect the type of the data. - var isLinedText, isText, isBinary bool - var sx, sy string - switch { - case t.Kind() == reflect.String: - sx, sy = vx.String(), vy.String() - isText = true // Initial estimate, verify later - case t.Kind() == reflect.Slice && t.Elem() == reflect.TypeOf(byte(0)): - sx, sy = string(vx.Bytes()), string(vy.Bytes()) - isBinary = true // Initial estimate, verify later - case t.Kind() == reflect.Array: - // Arrays need to be addressable for slice operations to work. - vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem() - vx2.Set(vx) - vy2.Set(vy) - vx, vy = vx2, vy2 - } - if isText || isBinary { - var numLines, lastLineIdx, maxLineLen int - isBinary = false - for i, r := range sx + sy { - if !(unicode.IsPrint(r) || unicode.IsSpace(r)) || r == utf8.RuneError { - isBinary = true - break - } - if r == '\n' { - if maxLineLen < i-lastLineIdx { - lastLineIdx = i - lastLineIdx - } - lastLineIdx = i + 1 - numLines++ - } - } - isText = !isBinary - isLinedText = isText && numLines >= 4 && maxLineLen <= 256 - } - - // Format the string into printable records. - var list textList - var delim string - switch { - // If the text appears to be multi-lined text, - // then perform differencing across individual lines. - case isLinedText: - ssx := strings.Split(sx, "\n") - ssy := strings.Split(sy, "\n") - list = opts.formatDiffSlice( - reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line", - func(v reflect.Value, d diffMode) textRecord { - s := formatString(v.Index(0).String()) - return textRecord{Diff: d, Value: textLine(s)} - }, - ) - delim = "\n" - // If the text appears to be single-lined text, - // then perform differencing in approximately fixed-sized chunks. - // The output is printed as quoted strings. - case isText: - list = opts.formatDiffSlice( - reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte", - func(v reflect.Value, d diffMode) textRecord { - s := formatString(v.String()) - return textRecord{Diff: d, Value: textLine(s)} - }, - ) - delim = "" - // If the text appears to be binary data, - // then perform differencing in approximately fixed-sized chunks. - // The output is inspired by hexdump. - case isBinary: - list = opts.formatDiffSlice( - reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte", - func(v reflect.Value, d diffMode) textRecord { - var ss []string - for i := 0; i < v.Len(); i++ { - ss = append(ss, formatHex(v.Index(i).Uint())) - } - s := strings.Join(ss, ", ") - comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String()))) - return textRecord{Diff: d, Value: textLine(s), Comment: comment} - }, - ) - // For all other slices of primitive types, - // then perform differencing in approximately fixed-sized chunks. - // The size of each chunk depends on the width of the element kind. - default: - var chunkSize int - if t.Elem().Kind() == reflect.Bool { - chunkSize = 16 - } else { - switch t.Elem().Bits() { - case 8: - chunkSize = 16 - case 16: - chunkSize = 12 - case 32: - chunkSize = 8 - default: - chunkSize = 8 - } - } - list = opts.formatDiffSlice( - vx, vy, chunkSize, t.Elem().Kind().String(), - func(v reflect.Value, d diffMode) textRecord { - var ss []string - for i := 0; i < v.Len(); i++ { - switch t.Elem().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - ss = append(ss, fmt.Sprint(v.Index(i).Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - ss = append(ss, formatHex(v.Index(i).Uint())) - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: - ss = append(ss, fmt.Sprint(v.Index(i).Interface())) - } - } - s := strings.Join(ss, ", ") - return textRecord{Diff: d, Value: textLine(s)} - }, - ) - } - - // Wrap the output with appropriate type information. - var out textNode = textWrap{"{", list, "}"} - if !isText { - // The "{...}" byte-sequence literal is not valid Go syntax for strings. - // Emit the type for extra clarity (e.g. "string{...}"). - if t.Kind() == reflect.String { - opts = opts.WithTypeMode(emitType) - } - return opts.FormatType(t, out) - } - switch t.Kind() { - case reflect.String: - out = textWrap{"strings.Join(", out, fmt.Sprintf(", %q)", delim)} - if t != reflect.TypeOf(string("")) { - out = opts.FormatType(t, out) - } - case reflect.Slice: - out = textWrap{"bytes.Join(", out, fmt.Sprintf(", %q)", delim)} - if t != reflect.TypeOf([]byte(nil)) { - out = opts.FormatType(t, out) - } - } - return out -} - -// formatASCII formats s as an ASCII string. -// This is useful for printing binary strings in a semi-legible way. -func formatASCII(s string) string { - b := bytes.Repeat([]byte{'.'}, len(s)) - for i := 0; i < len(s); i++ { - if ' ' <= s[i] && s[i] <= '~' { - b[i] = s[i] - } - } - return string(b) -} - -func (opts formatOptions) formatDiffSlice( - vx, vy reflect.Value, chunkSize int, name string, - makeRec func(reflect.Value, diffMode) textRecord, -) (list textList) { - es := diff.Difference(vx.Len(), vy.Len(), func(ix int, iy int) diff.Result { - return diff.BoolResult(vx.Index(ix).Interface() == vy.Index(iy).Interface()) - }) - - appendChunks := func(v reflect.Value, d diffMode) int { - n0 := v.Len() - for v.Len() > 0 { - n := chunkSize - if n > v.Len() { - n = v.Len() - } - list = append(list, makeRec(v.Slice(0, n), d)) - v = v.Slice(n, v.Len()) - } - return n0 - v.Len() - } - - groups := coalesceAdjacentEdits(name, es) - groups = coalesceInterveningIdentical(groups, chunkSize/4) - for i, ds := range groups { - // Print equal. - if ds.NumDiff() == 0 { - // Compute the number of leading and trailing equal bytes to print. - var numLo, numHi int - numEqual := ds.NumIgnored + ds.NumIdentical - for numLo < chunkSize*numContextRecords && numLo+numHi < numEqual && i != 0 { - numLo++ - } - for numHi < chunkSize*numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { - numHi++ - } - if numEqual-(numLo+numHi) <= chunkSize && ds.NumIgnored == 0 { - numHi = numEqual - numLo // Avoid pointless coalescing of single equal row - } - - // Print the equal bytes. - appendChunks(vx.Slice(0, numLo), diffIdentical) - if numEqual > numLo+numHi { - ds.NumIdentical -= numLo + numHi - list.AppendEllipsis(ds) - } - appendChunks(vx.Slice(numEqual-numHi, numEqual), diffIdentical) - vx = vx.Slice(numEqual, vx.Len()) - vy = vy.Slice(numEqual, vy.Len()) - continue - } - - // Print unequal. - nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved) - vx = vx.Slice(nx, vx.Len()) - ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted) - vy = vy.Slice(ny, vy.Len()) - } - assert(vx.Len() == 0 && vy.Len() == 0) - return list -} - -// coalesceAdjacentEdits coalesces the list of edits into groups of adjacent -// equal or unequal counts. -func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) { - var prevCase int // Arbitrary index into which case last occurred - lastStats := func(i int) *diffStats { - if prevCase != i { - groups = append(groups, diffStats{Name: name}) - prevCase = i - } - return &groups[len(groups)-1] - } - for _, e := range es { - switch e { - case diff.Identity: - lastStats(1).NumIdentical++ - case diff.UniqueX: - lastStats(2).NumRemoved++ - case diff.UniqueY: - lastStats(2).NumInserted++ - case diff.Modified: - lastStats(2).NumModified++ - } - } - return groups -} - -// coalesceInterveningIdentical coalesces sufficiently short (<= windowSize) -// equal groups into adjacent unequal groups that currently result in a -// dual inserted/removed printout. This acts as a high-pass filter to smooth -// out high-frequency changes within the windowSize. -func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats { - groups, groupsOrig := groups[:0], groups - for i, ds := range groupsOrig { - if len(groups) >= 2 && ds.NumDiff() > 0 { - prev := &groups[len(groups)-2] // Unequal group - curr := &groups[len(groups)-1] // Equal group - next := &groupsOrig[i] // Unequal group - hadX, hadY := prev.NumRemoved > 0, prev.NumInserted > 0 - hasX, hasY := next.NumRemoved > 0, next.NumInserted > 0 - if ((hadX || hasX) && (hadY || hasY)) && curr.NumIdentical <= windowSize { - *prev = (*prev).Append(*curr).Append(*next) - groups = groups[:len(groups)-1] // Truncate off equal group - continue - } - } - groups = append(groups, ds) - } - return groups -} diff --git a/vendor/github.com/google/go-cmp/cmp/report_text.go b/vendor/github.com/google/go-cmp/cmp/report_text.go deleted file mode 100644 index 80605d0e4..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report_text.go +++ /dev/null @@ -1,382 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -import ( - "bytes" - "fmt" - "math/rand" - "strings" - "time" - - "github.com/google/go-cmp/cmp/internal/flags" -) - -var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 - -type indentMode int - -func (n indentMode) appendIndent(b []byte, d diffMode) []byte { - if flags.Deterministic || randBool { - // Use regular spaces (U+0020). - switch d { - case diffUnknown, diffIdentical: - b = append(b, " "...) - case diffRemoved: - b = append(b, "- "...) - case diffInserted: - b = append(b, "+ "...) - } - } else { - // Use non-breaking spaces (U+00a0). - switch d { - case diffUnknown, diffIdentical: - b = append(b, "  "...) - case diffRemoved: - b = append(b, "- "...) - case diffInserted: - b = append(b, "+ "...) - } - } - return repeatCount(n).appendChar(b, '\t') -} - -type repeatCount int - -func (n repeatCount) appendChar(b []byte, c byte) []byte { - for ; n > 0; n-- { - b = append(b, c) - } - return b -} - -// textNode is a simplified tree-based representation of structured text. -// Possible node types are textWrap, textList, or textLine. -type textNode interface { - // Len reports the length in bytes of a single-line version of the tree. - // Nested textRecord.Diff and textRecord.Comment fields are ignored. - Len() int - // Equal reports whether the two trees are structurally identical. - // Nested textRecord.Diff and textRecord.Comment fields are compared. - Equal(textNode) bool - // String returns the string representation of the text tree. - // It is not guaranteed that len(x.String()) == x.Len(), - // nor that x.String() == y.String() implies that x.Equal(y). - String() string - - // formatCompactTo formats the contents of the tree as a single-line string - // to the provided buffer. Any nested textRecord.Diff and textRecord.Comment - // fields are ignored. - // - // However, not all nodes in the tree should be collapsed as a single-line. - // If a node can be collapsed as a single-line, it is replaced by a textLine - // node. Since the top-level node cannot replace itself, this also returns - // the current node itself. - // - // This does not mutate the receiver. - formatCompactTo([]byte, diffMode) ([]byte, textNode) - // formatExpandedTo formats the contents of the tree as a multi-line string - // to the provided buffer. In order for column alignment to operate well, - // formatCompactTo must be called before calling formatExpandedTo. - formatExpandedTo([]byte, diffMode, indentMode) []byte -} - -// textWrap is a wrapper that concatenates a prefix and/or a suffix -// to the underlying node. -type textWrap struct { - Prefix string // e.g., "bytes.Buffer{" - Value textNode // textWrap | textList | textLine - Suffix string // e.g., "}" -} - -func (s textWrap) Len() int { - return len(s.Prefix) + s.Value.Len() + len(s.Suffix) -} -func (s1 textWrap) Equal(s2 textNode) bool { - if s2, ok := s2.(textWrap); ok { - return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix - } - return false -} -func (s textWrap) String() string { - var d diffMode - var n indentMode - _, s2 := s.formatCompactTo(nil, d) - b := n.appendIndent(nil, d) // Leading indent - b = s2.formatExpandedTo(b, d, n) // Main body - b = append(b, '\n') // Trailing newline - return string(b) -} -func (s textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { - n0 := len(b) // Original buffer length - b = append(b, s.Prefix...) - b, s.Value = s.Value.formatCompactTo(b, d) - b = append(b, s.Suffix...) - if _, ok := s.Value.(textLine); ok { - return b, textLine(b[n0:]) - } - return b, s -} -func (s textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { - b = append(b, s.Prefix...) - b = s.Value.formatExpandedTo(b, d, n) - b = append(b, s.Suffix...) - return b -} - -// textList is a comma-separated list of textWrap or textLine nodes. -// The list may be formatted as multi-lines or single-line at the discretion -// of the textList.formatCompactTo method. -type textList []textRecord -type textRecord struct { - Diff diffMode // e.g., 0 or '-' or '+' - Key string // e.g., "MyField" - Value textNode // textWrap | textLine - Comment fmt.Stringer // e.g., "6 identical fields" -} - -// AppendEllipsis appends a new ellipsis node to the list if none already -// exists at the end. If cs is non-zero it coalesces the statistics with the -// previous diffStats. -func (s *textList) AppendEllipsis(ds diffStats) { - hasStats := ds != diffStats{} - if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) { - if hasStats { - *s = append(*s, textRecord{Value: textEllipsis, Comment: ds}) - } else { - *s = append(*s, textRecord{Value: textEllipsis}) - } - return - } - if hasStats { - (*s)[len(*s)-1].Comment = (*s)[len(*s)-1].Comment.(diffStats).Append(ds) - } -} - -func (s textList) Len() (n int) { - for i, r := range s { - n += len(r.Key) - if r.Key != "" { - n += len(": ") - } - n += r.Value.Len() - if i < len(s)-1 { - n += len(", ") - } - } - return n -} - -func (s1 textList) Equal(s2 textNode) bool { - if s2, ok := s2.(textList); ok { - if len(s1) != len(s2) { - return false - } - for i := range s1 { - r1, r2 := s1[i], s2[i] - if !(r1.Diff == r2.Diff && r1.Key == r2.Key && r1.Value.Equal(r2.Value) && r1.Comment == r2.Comment) { - return false - } - } - return true - } - return false -} - -func (s textList) String() string { - return textWrap{"{", s, "}"}.String() -} - -func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { - s = append(textList(nil), s...) // Avoid mutating original - - // Determine whether we can collapse this list as a single line. - n0 := len(b) // Original buffer length - var multiLine bool - for i, r := range s { - if r.Diff == diffInserted || r.Diff == diffRemoved { - multiLine = true - } - b = append(b, r.Key...) - if r.Key != "" { - b = append(b, ": "...) - } - b, s[i].Value = r.Value.formatCompactTo(b, d|r.Diff) - if _, ok := s[i].Value.(textLine); !ok { - multiLine = true - } - if r.Comment != nil { - multiLine = true - } - if i < len(s)-1 { - b = append(b, ", "...) - } - } - // Force multi-lined output when printing a removed/inserted node that - // is sufficiently long. - if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > 80 { - multiLine = true - } - if !multiLine { - return b, textLine(b[n0:]) - } - return b, s -} - -func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { - alignKeyLens := s.alignLens( - func(r textRecord) bool { - _, isLine := r.Value.(textLine) - return r.Key == "" || !isLine - }, - func(r textRecord) int { return len(r.Key) }, - ) - alignValueLens := s.alignLens( - func(r textRecord) bool { - _, isLine := r.Value.(textLine) - return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil - }, - func(r textRecord) int { return len(r.Value.(textLine)) }, - ) - - // Format the list as a multi-lined output. - n++ - for i, r := range s { - b = n.appendIndent(append(b, '\n'), d|r.Diff) - if r.Key != "" { - b = append(b, r.Key+": "...) - } - b = alignKeyLens[i].appendChar(b, ' ') - - b = r.Value.formatExpandedTo(b, d|r.Diff, n) - if !r.Value.Equal(textEllipsis) { - b = append(b, ',') - } - b = alignValueLens[i].appendChar(b, ' ') - - if r.Comment != nil { - b = append(b, " // "+r.Comment.String()...) - } - } - n-- - - return n.appendIndent(append(b, '\n'), d) -} - -func (s textList) alignLens( - skipFunc func(textRecord) bool, - lenFunc func(textRecord) int, -) []repeatCount { - var startIdx, endIdx, maxLen int - lens := make([]repeatCount, len(s)) - for i, r := range s { - if skipFunc(r) { - for j := startIdx; j < endIdx && j < len(s); j++ { - lens[j] = repeatCount(maxLen - lenFunc(s[j])) - } - startIdx, endIdx, maxLen = i+1, i+1, 0 - } else { - if maxLen < lenFunc(r) { - maxLen = lenFunc(r) - } - endIdx = i + 1 - } - } - for j := startIdx; j < endIdx && j < len(s); j++ { - lens[j] = repeatCount(maxLen - lenFunc(s[j])) - } - return lens -} - -// textLine is a single-line segment of text and is always a leaf node -// in the textNode tree. -type textLine []byte - -var ( - textNil = textLine("nil") - textEllipsis = textLine("...") -) - -func (s textLine) Len() int { - return len(s) -} -func (s1 textLine) Equal(s2 textNode) bool { - if s2, ok := s2.(textLine); ok { - return bytes.Equal([]byte(s1), []byte(s2)) - } - return false -} -func (s textLine) String() string { - return string(s) -} -func (s textLine) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { - return append(b, s...), s -} -func (s textLine) formatExpandedTo(b []byte, _ diffMode, _ indentMode) []byte { - return append(b, s...) -} - -type diffStats struct { - Name string - NumIgnored int - NumIdentical int - NumRemoved int - NumInserted int - NumModified int -} - -func (s diffStats) NumDiff() int { - return s.NumRemoved + s.NumInserted + s.NumModified -} - -func (s diffStats) Append(ds diffStats) diffStats { - assert(s.Name == ds.Name) - s.NumIgnored += ds.NumIgnored - s.NumIdentical += ds.NumIdentical - s.NumRemoved += ds.NumRemoved - s.NumInserted += ds.NumInserted - s.NumModified += ds.NumModified - return s -} - -// String prints a humanly-readable summary of coalesced records. -// -// Example: -// diffStats{Name: "Field", NumIgnored: 5}.String() => "5 ignored fields" -func (s diffStats) String() string { - var ss []string - var sum int - labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"} - counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified} - for i, n := range counts { - if n > 0 { - ss = append(ss, fmt.Sprintf("%d %v", n, labels[i])) - } - sum += n - } - - // Pluralize the name (adjusting for some obscure English grammar rules). - name := s.Name - if sum > 1 { - name = name + "s" - if strings.HasSuffix(name, "ys") { - name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries" - } - } - - // Format the list according to English grammar (with Oxford comma). - switch n := len(ss); n { - case 0: - return "" - case 1, 2: - return strings.Join(ss, " and ") + " " + name - default: - return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name - } -} - -type commentString string - -func (s commentString) String() string { return string(s) } diff --git a/vendor/github.com/google/go-cmp/cmp/report_value.go b/vendor/github.com/google/go-cmp/cmp/report_value.go deleted file mode 100644 index 83031a7f5..000000000 --- a/vendor/github.com/google/go-cmp/cmp/report_value.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2019, The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.md file. - -package cmp - -import "reflect" - -// valueNode represents a single node within a report, which is a -// structured representation of the value tree, containing information -// regarding which nodes are equal or not. -type valueNode struct { - parent *valueNode - - Type reflect.Type - ValueX reflect.Value - ValueY reflect.Value - - // NumSame is the number of leaf nodes that are equal. - // All descendants are equal only if NumDiff is 0. - NumSame int - // NumDiff is the number of leaf nodes that are not equal. - NumDiff int - // NumIgnored is the number of leaf nodes that are ignored. - NumIgnored int - // NumCompared is the number of leaf nodes that were compared - // using an Equal method or Comparer function. - NumCompared int - // NumTransformed is the number of non-leaf nodes that were transformed. - NumTransformed int - // NumChildren is the number of transitive descendants of this node. - // This counts from zero; thus, leaf nodes have no descendants. - NumChildren int - // MaxDepth is the maximum depth of the tree. This counts from zero; - // thus, leaf nodes have a depth of zero. - MaxDepth int - - // Records is a list of struct fields, slice elements, or map entries. - Records []reportRecord // If populated, implies Value is not populated - - // Value is the result of a transformation, pointer indirect, of - // type assertion. - Value *valueNode // If populated, implies Records is not populated - - // TransformerName is the name of the transformer. - TransformerName string // If non-empty, implies Value is populated -} -type reportRecord struct { - Key reflect.Value // Invalid for slice element - Value *valueNode -} - -func (parent *valueNode) PushStep(ps PathStep) (child *valueNode) { - vx, vy := ps.Values() - child = &valueNode{parent: parent, Type: ps.Type(), ValueX: vx, ValueY: vy} - switch s := ps.(type) { - case StructField: - assert(parent.Value == nil) - parent.Records = append(parent.Records, reportRecord{Key: reflect.ValueOf(s.Name()), Value: child}) - case SliceIndex: - assert(parent.Value == nil) - parent.Records = append(parent.Records, reportRecord{Value: child}) - case MapIndex: - assert(parent.Value == nil) - parent.Records = append(parent.Records, reportRecord{Key: s.Key(), Value: child}) - case Indirect: - assert(parent.Value == nil && parent.Records == nil) - parent.Value = child - case TypeAssertion: - assert(parent.Value == nil && parent.Records == nil) - parent.Value = child - case Transform: - assert(parent.Value == nil && parent.Records == nil) - parent.Value = child - parent.TransformerName = s.Name() - parent.NumTransformed++ - default: - assert(parent == nil) // Must be the root step - } - return child -} - -func (r *valueNode) Report(rs Result) { - assert(r.MaxDepth == 0) // May only be called on leaf nodes - - if rs.ByIgnore() { - r.NumIgnored++ - } else { - if rs.Equal() { - r.NumSame++ - } else { - r.NumDiff++ - } - } - assert(r.NumSame+r.NumDiff+r.NumIgnored == 1) - - if rs.ByMethod() { - r.NumCompared++ - } - if rs.ByFunc() { - r.NumCompared++ - } - assert(r.NumCompared <= 1) -} - -func (child *valueNode) PopStep() (parent *valueNode) { - if child.parent == nil { - return nil - } - parent = child.parent - parent.NumSame += child.NumSame - parent.NumDiff += child.NumDiff - parent.NumIgnored += child.NumIgnored - parent.NumCompared += child.NumCompared - parent.NumTransformed += child.NumTransformed - parent.NumChildren += child.NumChildren + 1 - if parent.MaxDepth < child.MaxDepth+1 { - parent.MaxDepth = child.MaxDepth + 1 - } - return parent -} diff --git a/vendor/github.com/google/go-cmp/cmp/reporter.go b/vendor/github.com/google/go-cmp/cmp/reporter.go new file mode 100644 index 000000000..20e9f18e0 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/reporter.go @@ -0,0 +1,53 @@ +// Copyright 2017, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE.md file. + +package cmp + +import ( + "fmt" + "reflect" + "strings" + + "github.com/google/go-cmp/cmp/internal/value" +) + +type defaultReporter struct { + Option + diffs []string // List of differences, possibly truncated + ndiffs int // Total number of differences + nbytes int // Number of bytes in diffs + nlines int // Number of lines in diffs +} + +var _ reporter = (*defaultReporter)(nil) + +func (r *defaultReporter) Report(x, y reflect.Value, eq bool, p Path) { + if eq { + return // Ignore equal results + } + const maxBytes = 4096 + const maxLines = 256 + r.ndiffs++ + if r.nbytes < maxBytes && r.nlines < maxLines { + sx := value.Format(x, value.FormatConfig{UseStringer: true}) + sy := value.Format(y, value.FormatConfig{UseStringer: true}) + if sx == sy { + // Unhelpful output, so use more exact formatting. + sx = value.Format(x, value.FormatConfig{PrintPrimitiveType: true}) + sy = value.Format(y, value.FormatConfig{PrintPrimitiveType: true}) + } + s := fmt.Sprintf("%#v:\n\t-: %s\n\t+: %s\n", p, sx, sy) + r.diffs = append(r.diffs, s) + r.nbytes += len(s) + r.nlines += strings.Count(s, "\n") + } +} + +func (r *defaultReporter) String() string { + s := strings.Join(r.diffs, "") + if r.ndiffs == len(r.diffs) { + return s + } + return fmt.Sprintf("%s... %d more differences ...", s, r.ndiffs-len(r.diffs)) +} diff --git a/vendor/github.com/google/go-cmp/cmp/export_panic.go b/vendor/github.com/google/go-cmp/cmp/unsafe_panic.go similarity index 60% rename from vendor/github.com/google/go-cmp/cmp/export_panic.go rename to vendor/github.com/google/go-cmp/cmp/unsafe_panic.go index abc3a1c3e..d1518eb3a 100644 --- a/vendor/github.com/google/go-cmp/cmp/export_panic.go +++ b/vendor/github.com/google/go-cmp/cmp/unsafe_panic.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. -// +build purego +// +build purego appengine js package cmp @@ -10,6 +10,6 @@ import "reflect" const supportAllowUnexported = false -func retrieveUnexportedField(reflect.Value, reflect.StructField) reflect.Value { - panic("retrieveUnexportedField is not implemented") +func unsafeRetrieveField(reflect.Value, reflect.StructField) reflect.Value { + panic("unsafeRetrieveField is not implemented") } diff --git a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go b/vendor/github.com/google/go-cmp/cmp/unsafe_reflect.go similarity index 64% rename from vendor/github.com/google/go-cmp/cmp/export_unsafe.go rename to vendor/github.com/google/go-cmp/cmp/unsafe_reflect.go index 59d4ee91b..579b65507 100644 --- a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go +++ b/vendor/github.com/google/go-cmp/cmp/unsafe_reflect.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. -// +build !purego +// +build !purego,!appengine,!js package cmp @@ -13,11 +13,11 @@ import ( const supportAllowUnexported = true -// retrieveUnexportedField uses unsafe to forcibly retrieve any field from -// a struct such that the value has read-write permissions. +// unsafeRetrieveField uses unsafe to forcibly retrieve any field from a struct +// such that the value has read-write permissions. // // The parent struct, v, must be addressable, while f must be a StructField // describing the field to retrieve. -func retrieveUnexportedField(v reflect.Value, f reflect.StructField) reflect.Value { +func unsafeRetrieveField(v reflect.Value, f reflect.StructField) reflect.Value { return reflect.NewAt(f.Type, unsafe.Pointer(v.UnsafeAddr()+f.Offset)).Elem() } diff --git a/vendor/github.com/google/go-github/github/activity.go b/vendor/github.com/google/go-github/github/activity.go deleted file mode 100644 index d6c992c7f..000000000 --- a/vendor/github.com/google/go-github/github/activity.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import "context" - -// ActivityService handles communication with the activity related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/activity/ -type ActivityService service - -// FeedLink represents a link to a related resource. -type FeedLink struct { - HRef *string `json:"href,omitempty"` - Type *string `json:"type,omitempty"` -} - -// Feeds represents timeline resources in Atom format. -type Feeds struct { - TimelineURL *string `json:"timeline_url,omitempty"` - UserURL *string `json:"user_url,omitempty"` - CurrentUserPublicURL *string `json:"current_user_public_url,omitempty"` - CurrentUserURL *string `json:"current_user_url,omitempty"` - CurrentUserActorURL *string `json:"current_user_actor_url,omitempty"` - CurrentUserOrganizationURL *string `json:"current_user_organization_url,omitempty"` - CurrentUserOrganizationURLs []string `json:"current_user_organization_urls,omitempty"` - Links *struct { - Timeline *FeedLink `json:"timeline,omitempty"` - User *FeedLink `json:"user,omitempty"` - CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"` - CurrentUser *FeedLink `json:"current_user,omitempty"` - CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"` - CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"` - CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"` - } `json:"_links,omitempty"` -} - -// ListFeeds lists all the feeds available to the authenticated user. -// -// GitHub provides several timeline resources in Atom format: -// Timeline: The GitHub global public timeline -// User: The public timeline for any user, using URI template -// Current user public: The public timeline for the authenticated user -// Current user: The private timeline for the authenticated user -// Current user actor: The private timeline for activity created by the -// authenticated user -// Current user organizations: The private timeline for the organizations -// the authenticated user is a member of. -// -// Note: Private feeds are only returned when authenticating via Basic Auth -// since current feed URIs use the older, non revocable auth tokens. -func (s *ActivityService) ListFeeds(ctx context.Context) (*Feeds, *Response, error) { - req, err := s.client.NewRequest("GET", "feeds", nil) - if err != nil { - return nil, nil, err - } - - f := &Feeds{} - resp, err := s.client.Do(ctx, req, f) - if err != nil { - return nil, resp, err - } - - return f, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_events.go b/vendor/github.com/google/go-github/github/activity_events.go deleted file mode 100644 index a919b11c5..000000000 --- a/vendor/github.com/google/go-github/github/activity_events.go +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "time" -) - -// Event represents a GitHub event. -type Event struct { - Type *string `json:"type,omitempty"` - Public *bool `json:"public,omitempty"` - RawPayload *json.RawMessage `json:"payload,omitempty"` - Repo *Repository `json:"repo,omitempty"` - Actor *User `json:"actor,omitempty"` - Org *Organization `json:"org,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ID *string `json:"id,omitempty"` -} - -func (e Event) String() string { - return Stringify(e) -} - -// ParsePayload parses the event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -func (e *Event) ParsePayload() (payload interface{}, err error) { - switch *e.Type { - case "CheckRunEvent": - payload = &CheckRunEvent{} - case "CheckSuiteEvent": - payload = &CheckSuiteEvent{} - case "CommitCommentEvent": - payload = &CommitCommentEvent{} - case "CreateEvent": - payload = &CreateEvent{} - case "DeleteEvent": - payload = &DeleteEvent{} - case "DeploymentEvent": - payload = &DeploymentEvent{} - case "DeploymentStatusEvent": - payload = &DeploymentStatusEvent{} - case "ForkEvent": - payload = &ForkEvent{} - case "GollumEvent": - payload = &GollumEvent{} - case "InstallationEvent": - payload = &InstallationEvent{} - case "InstallationRepositoriesEvent": - payload = &InstallationRepositoriesEvent{} - case "IssueCommentEvent": - payload = &IssueCommentEvent{} - case "IssuesEvent": - payload = &IssuesEvent{} - case "LabelEvent": - payload = &LabelEvent{} - case "MarketplacePurchaseEvent": - payload = &MarketplacePurchaseEvent{} - case "MemberEvent": - payload = &MemberEvent{} - case "MembershipEvent": - payload = &MembershipEvent{} - case "MilestoneEvent": - payload = &MilestoneEvent{} - case "OrganizationEvent": - payload = &OrganizationEvent{} - case "OrgBlockEvent": - payload = &OrgBlockEvent{} - case "PageBuildEvent": - payload = &PageBuildEvent{} - case "PingEvent": - payload = &PingEvent{} - case "ProjectEvent": - payload = &ProjectEvent{} - case "ProjectCardEvent": - payload = &ProjectCardEvent{} - case "ProjectColumnEvent": - payload = &ProjectColumnEvent{} - case "PublicEvent": - payload = &PublicEvent{} - case "PullRequestEvent": - payload = &PullRequestEvent{} - case "PullRequestReviewEvent": - payload = &PullRequestReviewEvent{} - case "PullRequestReviewCommentEvent": - payload = &PullRequestReviewCommentEvent{} - case "PushEvent": - payload = &PushEvent{} - case "ReleaseEvent": - payload = &ReleaseEvent{} - case "RepositoryEvent": - payload = &RepositoryEvent{} - case "StatusEvent": - payload = &StatusEvent{} - case "TeamEvent": - payload = &TeamEvent{} - case "TeamAddEvent": - payload = &TeamAddEvent{} - case "WatchEvent": - payload = &WatchEvent{} - } - err = json.Unmarshal(*e.RawPayload, &payload) - return payload, err -} - -// Payload returns the parsed event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -// -// Deprecated: Use ParsePayload instead, which returns an error -// rather than panics if JSON unmarshaling raw payload fails. -func (e *Event) Payload() (payload interface{}) { - var err error - payload, err = e.ParsePayload() - if err != nil { - panic(err) - } - return payload -} - -// ListEvents drinks from the firehose of all public events across GitHub. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events -func (s *ActivityService) ListEvents(ctx context.Context, opt *ListOptions) ([]*Event, *Response, error) { - u, err := addOptions("events", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-repository-events -func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListIssueEventsForRepository lists issue events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository -func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForRepoNetwork lists public events for a network of repositories. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories -func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("networks/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForOrganization lists public events for an organization. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-an-organization -func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("orgs/%v/events", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsPerformedByUser lists the events performed by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-performed-by-a-user -func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/events/public", user) - } else { - u = fmt.Sprintf("users/%v/events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsReceivedByUser lists the events received by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received -func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/received_events/public", user) - } else { - u = fmt.Sprintf("users/%v/received_events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListUserEventsForOrganization provides the user’s organization dashboard. You -// must be authenticated as the user to view this. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-for-an-organization -func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("users/%v/events/orgs/%v", user, org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_notifications.go b/vendor/github.com/google/go-github/github/activity_notifications.go deleted file mode 100644 index 45c8b2aec..000000000 --- a/vendor/github.com/google/go-github/github/activity_notifications.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Notification identifies a GitHub notification for a user. -type Notification struct { - ID *string `json:"id,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Subject *NotificationSubject `json:"subject,omitempty"` - - // Reason identifies the event that triggered the notification. - // - // GitHub API docs: https://developer.github.com/v3/activity/notifications/#notification-reasons - Reason *string `json:"reason,omitempty"` - - Unread *bool `json:"unread,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - LastReadAt *time.Time `json:"last_read_at,omitempty"` - URL *string `json:"url,omitempty"` -} - -// NotificationSubject identifies the subject of a notification. -type NotificationSubject struct { - Title *string `json:"title,omitempty"` - URL *string `json:"url,omitempty"` - LatestCommentURL *string `json:"latest_comment_url,omitempty"` - Type *string `json:"type,omitempty"` -} - -// NotificationListOptions specifies the optional parameters to the -// ActivityService.ListNotifications method. -type NotificationListOptions struct { - All bool `url:"all,omitempty"` - Participating bool `url:"participating,omitempty"` - Since time.Time `url:"since,omitempty"` - Before time.Time `url:"before,omitempty"` - - ListOptions -} - -// ListNotifications lists all notifications for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications -func (s *ActivityService) ListNotifications(ctx context.Context, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("notifications") - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -// ListRepositoryNotifications lists all notifications in a given repository -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository -func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -type markReadOptions struct { - LastReadAt time.Time `json:"last_read_at,omitempty"` -} - -// MarkNotificationsRead marks all notifications up to lastRead as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-as-read -func (s *ActivityService) MarkNotificationsRead(ctx context.Context, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - req, err := s.client.NewRequest("PUT", "notifications", opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// MarkRepositoryNotificationsRead marks all notifications up to lastRead in -// the specified repository as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository -func (s *ActivityService) MarkRepositoryNotificationsRead(ctx context.Context, owner, repo string, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - req, err := s.client.NewRequest("PUT", u, opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThread gets the specified notification thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#view-a-single-thread -func (s *ActivityService) GetThread(ctx context.Context, id string) (*Notification, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - notification := new(Notification) - resp, err := s.client.Do(ctx, req, notification) - if err != nil { - return nil, resp, err - } - - return notification, resp, nil -} - -// MarkThreadRead marks the specified thread as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read -func (s *ActivityService) MarkThreadRead(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThreadSubscription checks to see if the authenticated user is subscribed -// to a thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription -func (s *ActivityService) GetThreadSubscription(ctx context.Context, id string) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// SetThreadSubscription sets the subscription for the specified thread for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription -func (s *ActivityService) SetThreadSubscription(ctx context.Context, id string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteThreadSubscription deletes the subscription for the specified thread -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription -func (s *ActivityService) DeleteThreadSubscription(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_star.go b/vendor/github.com/google/go-github/github/activity_star.go deleted file mode 100644 index d5b067127..000000000 --- a/vendor/github.com/google/go-github/github/activity_star.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// StarredRepository is returned by ListStarred. -type StarredRepository struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - Repository *Repository `json:"repo,omitempty"` -} - -// Stargazer represents a user that has starred a repository. -type Stargazer struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - User *User `json:"user,omitempty"` -} - -// ListStargazers lists people who have starred the specified repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-stargazers -func (s *ActivityService) ListStargazers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/stargazers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var stargazers []*Stargazer - resp, err := s.client.Do(ctx, req, &stargazers) - if err != nil { - return nil, resp, err - } - - return stargazers, resp, nil -} - -// ActivityListStarredOptions specifies the optional parameters to the -// ActivityService.ListStarred method. -type ActivityListStarredOptions struct { - // How to sort the repository list. Possible values are: created, updated, - // pushed, full_name. Default is "full_name". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Possible values are: asc, desc. - // Default is "asc" when sort is "full_name", otherwise default is "desc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListStarred lists all the repos starred by a user. Passing the empty string -// will list the starred repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-repositories-being-starred -func (s *ActivityService) ListStarred(ctx context.Context, user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/starred", user) - } else { - u = "user/starred" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var repos []*StarredRepository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsStarred checks if a repository is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository -func (s *ActivityService) IsStarred(ctx context.Context, owner, repo string) (bool, *Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Star a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#star-a-repository -func (s *ActivityService) Star(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#unstar-a-repository -func (s *ActivityService) Unstar(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_watching.go b/vendor/github.com/google/go-github/github/activity_watching.go deleted file mode 100644 index c749ca86e..000000000 --- a/vendor/github.com/google/go-github/github/activity_watching.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Subscription identifies a repository or thread subscription. -type Subscription struct { - Subscribed *bool `json:"subscribed,omitempty"` - Ignored *bool `json:"ignored,omitempty"` - Reason *string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - - // only populated for repository subscriptions - RepositoryURL *string `json:"repository_url,omitempty"` - - // only populated for thread subscriptions - ThreadURL *string `json:"thread_url,omitempty"` -} - -// ListWatchers lists watchers of a particular repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-watchers -func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscribers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watchers []*User - resp, err := s.client.Do(ctx, req, &watchers) - if err != nil { - return nil, resp, err - } - - return watchers, resp, nil -} - -// ListWatched lists the repositories the specified user is watching. Passing -// the empty string will fetch watched repos for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched -func (s *ActivityService) ListWatched(ctx context.Context, user string, opt *ListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/subscriptions", user) - } else { - u = "user/subscriptions" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watched []*Repository - resp, err := s.client.Do(ctx, req, &watched) - if err != nil { - return nil, resp, err - } - - return watched, resp, nil -} - -// GetRepositorySubscription returns the subscription for the specified -// repository for the authenticated user. If the authenticated user is not -// watching the repository, a nil Subscription is returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#get-a-repository-subscription -func (s *ActivityService) GetRepositorySubscription(ctx context.Context, owner, repo string) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - // if it's just a 404, don't return that as an error - _, err = parseBoolResponse(err) - return nil, resp, err - } - - return sub, resp, nil -} - -// SetRepositorySubscription sets the subscription for the specified repository -// for the authenticated user. -// -// To watch a repository, set subscription.Subscribed to true. -// To ignore notifications made within a repository, set subscription.Ignored to true. -// To stop watching a repository, use DeleteRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#set-a-repository-subscription -func (s *ActivityService) SetRepositorySubscription(ctx context.Context, owner, repo string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteRepositorySubscription deletes the subscription for the specified -// repository for the authenticated user. -// -// This is used to stop watching a repository. To control whether or not to -// receive notifications from a repository, use SetRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#delete-a-repository-subscription -func (s *ActivityService) DeleteRepositorySubscription(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/admin.go b/vendor/github.com/google/go-github/github/admin.go deleted file mode 100644 index 2d96733a1..000000000 --- a/vendor/github.com/google/go-github/github/admin.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// AdminService handles communication with the admin related methods of the -// GitHub API. These API routes are normally only accessible for GitHub -// Enterprise installations. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ -type AdminService service - -// TeamLDAPMapping represents the mapping between a GitHub team and an LDAP group. -type TeamLDAPMapping struct { - ID *int64 `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Slug *string `json:"slug,omitempty"` - Description *string `json:"description,omitempty"` - Privacy *string `json:"privacy,omitempty"` - Permission *string `json:"permission,omitempty"` - - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` -} - -func (m TeamLDAPMapping) String() string { - return Stringify(m) -} - -// UserLDAPMapping represents the mapping between a GitHub user and an LDAP user. -type UserLDAPMapping struct { - ID *int64 `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - Login *string `json:"login,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` -} - -func (m UserLDAPMapping) String() string { - return Stringify(m) -} - -// UpdateUserLDAPMapping updates the mapping between a GitHub user and an LDAP user. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-user -func (s *AdminService) UpdateUserLDAPMapping(ctx context.Context, user string, mapping *UserLDAPMapping) (*UserLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/users/%v/mapping", user) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(UserLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// UpdateTeamLDAPMapping updates the mapping between a GitHub team and an LDAP group. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-team -func (s *AdminService) UpdateTeamLDAPMapping(ctx context.Context, team int64, mapping *TeamLDAPMapping) (*TeamLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/teams/%v/mapping", team) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(TeamLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/admin_stats.go b/vendor/github.com/google/go-github/github/admin_stats.go deleted file mode 100644 index b5645f8c1..000000000 --- a/vendor/github.com/google/go-github/github/admin_stats.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// AdminStats represents a variety of stats of a Github Enterprise -// installation. -type AdminStats struct { - Issues *IssueStats `json:"issues,omitempty"` - Hooks *HookStats `json:"hooks,omitempty"` - Milestones *MilestoneStats `json:"milestones,omitempty"` - Orgs *OrgStats `json:"orgs,omitempty"` - Comments *CommentStats `json:"comments,omitempty"` - Pages *PageStats `json:"pages,omitempty"` - Users *UserStats `json:"users,omitempty"` - Gists *GistStats `json:"gists,omitempty"` - Pulls *PullStats `json:"pulls,omitempty"` - Repos *RepoStats `json:"repos,omitempty"` -} - -func (s AdminStats) String() string { - return Stringify(s) -} - -// IssueStats represents the number of total, open and closed issues. -type IssueStats struct { - TotalIssues *int `json:"total_issues,omitempty"` - OpenIssues *int `json:"open_issues,omitempty"` - ClosedIssues *int `json:"closed_issues,omitempty"` -} - -func (s IssueStats) String() string { - return Stringify(s) -} - -// HookStats represents the number of total, active and inactive hooks. -type HookStats struct { - TotalHooks *int `json:"total_hooks,omitempty"` - ActiveHooks *int `json:"active_hooks,omitempty"` - InactiveHooks *int `json:"inactive_hooks,omitempty"` -} - -func (s HookStats) String() string { - return Stringify(s) -} - -// MilestoneStats represents the number of total, open and close milestones. -type MilestoneStats struct { - TotalMilestones *int `json:"total_milestones,omitempty"` - OpenMilestones *int `json:"open_milestones,omitempty"` - ClosedMilestones *int `json:"closed_milestones,omitempty"` -} - -func (s MilestoneStats) String() string { - return Stringify(s) -} - -// OrgStats represents the number of total, disabled organizations and the team -// and team member count. -type OrgStats struct { - TotalOrgs *int `json:"total_orgs,omitempty"` - DisabledOrgs *int `json:"disabled_orgs,omitempty"` - TotalTeams *int `json:"total_teams,omitempty"` - TotalTeamMembers *int `json:"total_team_members,omitempty"` -} - -func (s OrgStats) String() string { - return Stringify(s) -} - -// CommentStats represents the number of total comments on commits, gists, issues -// and pull requests. -type CommentStats struct { - TotalCommitComments *int `json:"total_commit_comments,omitempty"` - TotalGistComments *int `json:"total_gist_comments,omitempty"` - TotalIssueComments *int `json:"total_issue_comments,omitempty"` - TotalPullRequestComments *int `json:"total_pull_request_comments,omitempty"` -} - -func (s CommentStats) String() string { - return Stringify(s) -} - -// PageStats represents the total number of github pages. -type PageStats struct { - TotalPages *int `json:"total_pages,omitempty"` -} - -func (s PageStats) String() string { - return Stringify(s) -} - -// UserStats represents the number of total, admin and suspended users. -type UserStats struct { - TotalUsers *int `json:"total_users,omitempty"` - AdminUsers *int `json:"admin_users,omitempty"` - SuspendedUsers *int `json:"suspended_users,omitempty"` -} - -func (s UserStats) String() string { - return Stringify(s) -} - -// GistStats represents the number of total, private and public gists. -type GistStats struct { - TotalGists *int `json:"total_gists,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` -} - -func (s GistStats) String() string { - return Stringify(s) -} - -// PullStats represents the number of total, merged, mergable and unmergeable -// pull-requests. -type PullStats struct { - TotalPulls *int `json:"total_pulls,omitempty"` - MergedPulls *int `json:"merged_pulls,omitempty"` - MergablePulls *int `json:"mergeable_pulls,omitempty"` - UnmergablePulls *int `json:"unmergeable_pulls,omitempty"` -} - -func (s PullStats) String() string { - return Stringify(s) -} - -// RepoStats represents the number of total, root, fork, organization repositories -// together with the total number of pushes and wikis. -type RepoStats struct { - TotalRepos *int `json:"total_repos,omitempty"` - RootRepos *int `json:"root_repos,omitempty"` - ForkRepos *int `json:"fork_repos,omitempty"` - OrgRepos *int `json:"org_repos,omitempty"` - TotalPushes *int `json:"total_pushes,omitempty"` - TotalWikis *int `json:"total_wikis,omitempty"` -} - -func (s RepoStats) String() string { - return Stringify(s) -} - -// GetAdminStats returns a variety of metrics about a Github Enterprise -// installation. -// -// Please note that this is only available to site administrators, -// otherwise it will error with a 404 not found (instead of 401 or 403). -// -// GitHub API docs: https://developer.github.com/v3/enterprise-admin/admin_stats/ -func (s *AdminService) GetAdminStats(ctx context.Context) (*AdminStats, *Response, error) { - u := fmt.Sprintf("enterprise/stats/all") - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - m := new(AdminStats) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps.go b/vendor/github.com/google/go-github/github/apps.go deleted file mode 100644 index 32d4f2f45..000000000 --- a/vendor/github.com/google/go-github/github/apps.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// AppsService provides access to the installation related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/apps/ -type AppsService service - -// App represents a GitHub App. -type App struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - ExternalURL *string `json:"external_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -// InstallationToken represents an installation token. -type InstallationToken struct { - Token *string `json:"token,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// InstallationPermissions lists the permissions for metadata, contents, issues and single file for an installation. -type InstallationPermissions struct { - Metadata *string `json:"metadata,omitempty"` - Contents *string `json:"contents,omitempty"` - Issues *string `json:"issues,omitempty"` - SingleFile *string `json:"single_file,omitempty"` -} - -// Installation represents a GitHub Apps installation. -type Installation struct { - ID *int64 `json:"id,omitempty"` - AppID *int64 `json:"app_id,omitempty"` - TargetID *int64 `json:"target_id,omitempty"` - Account *User `json:"account,omitempty"` - AccessTokensURL *string `json:"access_tokens_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - TargetType *string `json:"target_type,omitempty"` - SingleFileName *string `json:"single_file_name,omitempty"` - RepositorySelection *string `json:"repository_selection,omitempty"` - Events []string `json:"events,omitempty"` - Permissions *InstallationPermissions `json:"permissions,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -func (i Installation) String() string { - return Stringify(i) -} - -// Get a single GitHub App. Passing the empty string will get -// the authenticated GitHub App. -// -// Note: appSlug is just the URL-friendly name of your GitHub App. -// You can find this on the settings page for your GitHub App -// (e.g., https://github.com/settings/apps/:app_slug). -// -// GitHub API docs: https://developer.github.com/v3/apps/#get-a-single-github-app -func (s *AppsService) Get(ctx context.Context, appSlug string) (*App, *Response, error) { - var u string - if appSlug != "" { - u = fmt.Sprintf("apps/%v", appSlug) - } else { - u = "app" - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - app := new(App) - resp, err := s.client.Do(ctx, req, app) - if err != nil { - return nil, resp, err - } - - return app, resp, nil -} - -// ListInstallations lists the installations that the current GitHub App has. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-installations -func (s *AppsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("app/installations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var i []*Installation - resp, err := s.client.Do(ctx, req, &i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// GetInstallation returns the specified installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/#get-a-single-installation -func (s *AppsService) GetInstallation(ctx context.Context, id int64) (*Installation, *Response, error) { - return s.getInstallation(ctx, fmt.Sprintf("app/installations/%v", id)) -} - -// ListUserInstallations lists installations that are accessible to the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/apps/#list-installations-for-user -func (s *AppsService) ListUserInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("user/installations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var i struct { - Installations []*Installation `json:"installations"` - } - resp, err := s.client.Do(ctx, req, &i) - if err != nil { - return nil, resp, err - } - - return i.Installations, resp, nil -} - -// CreateInstallationToken creates a new installation token. -// -// GitHub API docs: https://developer.github.com/v3/apps/#create-a-new-installation-token -func (s *AppsService) CreateInstallationToken(ctx context.Context, id int64) (*InstallationToken, *Response, error) { - u := fmt.Sprintf("installations/%v/access_tokens", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - t := new(InstallationToken) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// FindOrganizationInstallation finds the organization's installation information. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-organization-installation -func (s *AppsService) FindOrganizationInstallation(ctx context.Context, org string) (*Installation, *Response, error) { - return s.getInstallation(ctx, fmt.Sprintf("orgs/%v/installation", org)) -} - -// FindRepositoryInstallation finds the repository's installation information. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-repository-installation -func (s *AppsService) FindRepositoryInstallation(ctx context.Context, owner, repo string) (*Installation, *Response, error) { - return s.getInstallation(ctx, fmt.Sprintf("repos/%v/%v/installation", owner, repo)) -} - -// FindRepositoryInstallationByID finds the repository's installation information. -// -// Note: FindRepositoryInstallationByID uses the undocumented GitHub API endpoint /repositories/:id/installation. -func (s *AppsService) FindRepositoryInstallationByID(ctx context.Context, id int64) (*Installation, *Response, error) { - return s.getInstallation(ctx, fmt.Sprintf("repositories/%d/installation", id)) -} - -// FindUserInstallation finds the user's installation information. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-repository-installation -func (s *AppsService) FindUserInstallation(ctx context.Context, user string) (*Installation, *Response, error) { - return s.getInstallation(ctx, fmt.Sprintf("users/%v/installation", user)) -} - -func (s *AppsService) getInstallation(ctx context.Context, url string) (*Installation, *Response, error) { - req, err := s.client.NewRequest("GET", url, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - i := new(Installation) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps_installation.go b/vendor/github.com/google/go-github/github/apps_installation.go deleted file mode 100644 index ccfecb8d8..000000000 --- a/vendor/github.com/google/go-github/github/apps_installation.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListRepos lists the repositories that are accessible to the authenticated installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories -func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { - u, err := addOptions("installation/repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var r struct { - Repositories []*Repository `json:"repositories"` - } - resp, err := s.client.Do(ctx, req, &r) - if err != nil { - return nil, resp, err - } - - return r.Repositories, resp, nil -} - -// ListUserRepos lists repositories that are accessible -// to the authenticated user for an installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories-accessible-to-the-user-for-an-installation -func (s *AppsService) ListUserRepos(ctx context.Context, id int64, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("user/installations/%v/repositories", id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var r struct { - Repositories []*Repository `json:"repositories"` - } - resp, err := s.client.Do(ctx, req, &r) - if err != nil { - return nil, resp, err - } - - return r.Repositories, resp, nil -} - -// AddRepository adds a single repository to an installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#add-repository-to-installation -func (s *AppsService) AddRepository(ctx context.Context, instID, repoID int64) (*Repository, *Response, error) { - u := fmt.Sprintf("apps/installations/%v/repositories/%v", instID, repoID) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// RemoveRepository removes a single repository from an installation. -// -// GitHub docs: https://developer.github.com/v3/apps/installations/#remove-repository-from-installation -func (s *AppsService) RemoveRepository(ctx context.Context, instID, repoID int64) (*Response, error) { - u := fmt.Sprintf("apps/installations/%v/repositories/%v", instID, repoID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/apps_marketplace.go b/vendor/github.com/google/go-github/github/apps_marketplace.go deleted file mode 100644 index 3f35b9155..000000000 --- a/vendor/github.com/google/go-github/github/apps_marketplace.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// MarketplaceService handles communication with the marketplace related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/ -type MarketplaceService struct { - client *Client - // Stubbed controls whether endpoints that return stubbed data are used - // instead of production endpoints. Stubbed data is fake data that's useful - // for testing your GitHub Apps. Stubbed data is hard-coded and will not - // change based on actual subscriptions. - // - // GitHub API docs: https://developer.github.com/v3/apps/marketplace/ - Stubbed bool -} - -// MarketplacePlan represents a GitHub Apps Marketplace Listing Plan. -type MarketplacePlan struct { - URL *string `json:"url,omitempty"` - AccountsURL *string `json:"accounts_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - MonthlyPriceInCents *int `json:"monthly_price_in_cents,omitempty"` - YearlyPriceInCents *int `json:"yearly_price_in_cents,omitempty"` - PriceModel *string `json:"price_model,omitempty"` - UnitName *string `json:"unit_name,omitempty"` - Bullets *[]string `json:"bullets,omitempty"` -} - -// MarketplacePurchase represents a GitHub Apps Marketplace Purchase. -type MarketplacePurchase struct { - BillingCycle *string `json:"billing_cycle,omitempty"` - NextBillingDate *string `json:"next_billing_date,omitempty"` - UnitCount *int `json:"unit_count,omitempty"` - Plan *MarketplacePlan `json:"plan,omitempty"` - Account *MarketplacePlanAccount `json:"account,omitempty"` -} - -// MarketplacePlanAccount represents a GitHub Account (user or organization) on a specific plan. -type MarketplacePlanAccount struct { - URL *string `json:"url,omitempty"` - Type *string `json:"type,omitempty"` - ID *int64 `json:"id,omitempty"` - Login *string `json:"login,omitempty"` - Email *string `json:"email,omitempty"` - OrganizationBillingEmail *string `json:"organization_billing_email,omitempty"` - MarketplacePurchase *MarketplacePurchase `json:"marketplace_purchase,omitempty"` -} - -// ListPlans lists all plans for your Marketplace listing. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-plans-for-your-marketplace-listing -func (s *MarketplaceService) ListPlans(ctx context.Context, opt *ListOptions) ([]*MarketplacePlan, *Response, error) { - uri := s.marketplaceURI("plans") - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var plans []*MarketplacePlan - resp, err := s.client.Do(ctx, req, &plans) - if err != nil { - return nil, resp, err - } - - return plans, resp, nil -} - -// ListPlanAccountsForPlan lists all GitHub accounts (user or organization) on a specific plan. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-github-accounts-user-or-organization-on-a-specific-plan -func (s *MarketplaceService) ListPlanAccountsForPlan(ctx context.Context, planID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { - uri := s.marketplaceURI(fmt.Sprintf("plans/%v/accounts", planID)) - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var accounts []*MarketplacePlanAccount - resp, err := s.client.Do(ctx, req, &accounts) - if err != nil { - return nil, resp, err - } - - return accounts, resp, nil -} - -// ListPlanAccountsForAccount lists all GitHub accounts (user or organization) associated with an account. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#check-if-a-github-account-is-associated-with-any-marketplace-listing -func (s *MarketplaceService) ListPlanAccountsForAccount(ctx context.Context, accountID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { - uri := s.marketplaceURI(fmt.Sprintf("accounts/%v", accountID)) - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var accounts []*MarketplacePlanAccount - resp, err := s.client.Do(ctx, req, &accounts) - if err != nil { - return nil, resp, err - } - - return accounts, resp, nil -} - -// ListMarketplacePurchasesForUser lists all GitHub marketplace purchases made by a user. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#get-a-users-marketplace-purchases -func (s *MarketplaceService) ListMarketplacePurchasesForUser(ctx context.Context, opt *ListOptions) ([]*MarketplacePurchase, *Response, error) { - uri := "user/marketplace_purchases" - if s.Stubbed { - uri = "user/marketplace_purchases/stubbed" - } - - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var purchases []*MarketplacePurchase - resp, err := s.client.Do(ctx, req, &purchases) - if err != nil { - return nil, resp, err - } - - return purchases, resp, nil -} - -func (s *MarketplaceService) marketplaceURI(endpoint string) string { - url := "marketplace_listing" - if s.Stubbed { - url = "marketplace_listing/stubbed" - } - return url + "/" + endpoint -} diff --git a/vendor/github.com/google/go-github/github/authorizations.go b/vendor/github.com/google/go-github/github/authorizations.go deleted file mode 100644 index 190205b02..000000000 --- a/vendor/github.com/google/go-github/github/authorizations.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Scope models a GitHub authorization scope. -// -// GitHub API docs: https://developer.github.com/v3/oauth/#scopes -type Scope string - -// This is the set of scopes for GitHub API V3 -const ( - ScopeNone Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact? - ScopeUser Scope = "user" - ScopeUserEmail Scope = "user:email" - ScopeUserFollow Scope = "user:follow" - ScopePublicRepo Scope = "public_repo" - ScopeRepo Scope = "repo" - ScopeRepoDeployment Scope = "repo_deployment" - ScopeRepoStatus Scope = "repo:status" - ScopeDeleteRepo Scope = "delete_repo" - ScopeNotifications Scope = "notifications" - ScopeGist Scope = "gist" - ScopeReadRepoHook Scope = "read:repo_hook" - ScopeWriteRepoHook Scope = "write:repo_hook" - ScopeAdminRepoHook Scope = "admin:repo_hook" - ScopeAdminOrgHook Scope = "admin:org_hook" - ScopeReadOrg Scope = "read:org" - ScopeWriteOrg Scope = "write:org" - ScopeAdminOrg Scope = "admin:org" - ScopeReadPublicKey Scope = "read:public_key" - ScopeWritePublicKey Scope = "write:public_key" - ScopeAdminPublicKey Scope = "admin:public_key" - ScopeReadGPGKey Scope = "read:gpg_key" - ScopeWriteGPGKey Scope = "write:gpg_key" - ScopeAdminGPGKey Scope = "admin:gpg_key" -) - -// AuthorizationsService handles communication with the authorization related -// methods of the GitHub API. -// -// This service requires HTTP Basic Authentication; it cannot be accessed using -// an OAuth token. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/ -type AuthorizationsService service - -// Authorization represents an individual GitHub authorization. -type Authorization struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Scopes []Scope `json:"scopes,omitempty"` - Token *string `json:"token,omitempty"` - TokenLastEight *string `json:"token_last_eight,omitempty"` - HashedToken *string `json:"hashed_token,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` - - // User is only populated by the Check and Reset methods. - User *User `json:"user,omitempty"` -} - -func (a Authorization) String() string { - return Stringify(a) -} - -// AuthorizationApp represents an individual GitHub app (in the context of authorization). -type AuthorizationApp struct { - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - ClientID *string `json:"client_id,omitempty"` -} - -func (a AuthorizationApp) String() string { - return Stringify(a) -} - -// Grant represents an OAuth application that has been granted access to an account. -type Grant struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -func (g Grant) String() string { - return Stringify(g) -} - -// AuthorizationRequest represents a request to create an authorization. -type AuthorizationRequest struct { - Scopes []Scope `json:"scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - ClientID *string `json:"client_id,omitempty"` - ClientSecret *string `json:"client_secret,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationRequest) String() string { - return Stringify(a) -} - -// AuthorizationUpdateRequest represents a request to update an authorization. -// -// Note that for any one update, you must only provide one of the "scopes" -// fields. That is, you may provide only one of "Scopes", or "AddScopes", or -// "RemoveScopes". -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -type AuthorizationUpdateRequest struct { - Scopes []string `json:"scopes,omitempty"` - AddScopes []string `json:"add_scopes,omitempty"` - RemoveScopes []string `json:"remove_scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationUpdateRequest) String() string { - return Stringify(a) -} - -// List the authorizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations -func (s *AuthorizationsService) List(ctx context.Context, opt *ListOptions) ([]*Authorization, *Response, error) { - u := "authorizations" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var auths []*Authorization - resp, err := s.client.Do(ctx, req, &auths) - if err != nil { - return nil, resp, err - } - return auths, resp, nil -} - -// Get a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization -func (s *AuthorizationsService) Get(ctx context.Context, id int64) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// Create a new authorization for the specified OAuth application. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization -func (s *AuthorizationsService) Create(ctx context.Context, auth *AuthorizationRequest) (*Authorization, *Response, error) { - u := "authorizations" - - req, err := s.client.NewRequest("POST", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// GetOrCreateForApp creates a new authorization for the specified OAuth -// application, only if an authorization for that application doesn’t already -// exist for the user. -// -// If a new token is created, the HTTP status code will be "201 Created", and -// the returned Authorization.Token field will be populated. If an existing -// token is returned, the status code will be "200 OK" and the -// Authorization.Token field will be empty. -// -// clientID is the OAuth Client ID with which to create the token. -// -// GitHub API docs: -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app-and-fingerprint -func (s *AuthorizationsService) GetOrCreateForApp(ctx context.Context, clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error) { - var u string - if auth.Fingerprint == nil || *auth.Fingerprint == "" { - u = fmt.Sprintf("authorizations/clients/%v", clientID) - } else { - u = fmt.Sprintf("authorizations/clients/%v/%v", clientID, *auth.Fingerprint) - } - - req, err := s.client.NewRequest("PUT", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Edit a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -func (s *AuthorizationsService) Edit(ctx context.Context, id int64, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("PATCH", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Delete a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization -func (s *AuthorizationsService) Delete(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Check if an OAuth token is valid for a specific app. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#check-an-authorization -func (s *AuthorizationsService) Check(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Reset is used to reset a valid OAuth token without end user involvement. -// Applications must save the "token" property in the response, because changes -// take effect immediately. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization -func (s *AuthorizationsService) Reset(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Revoke an authorization for an application. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application -func (s *AuthorizationsService) Revoke(ctx context.Context, clientID string, token string) (*Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListGrants lists the set of OAuth applications that have been granted -// access to a user's account. This will return one entry for each application -// that has been granted access to the account, regardless of the number of -// tokens an application has generated for the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants -func (s *AuthorizationsService) ListGrants(ctx context.Context, opt *ListOptions) ([]*Grant, *Response, error) { - u, err := addOptions("applications/grants", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grants := []*Grant{} - resp, err := s.client.Do(ctx, req, &grants) - if err != nil { - return nil, resp, err - } - - return grants, resp, nil -} - -// GetGrant gets a single OAuth application grant. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-grant -func (s *AuthorizationsService) GetGrant(ctx context.Context, id int64) (*Grant, *Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grant := new(Grant) - resp, err := s.client.Do(ctx, req, grant) - if err != nil { - return nil, resp, err - } - - return grant, resp, nil -} - -// DeleteGrant deletes an OAuth application grant. Deleting an application's -// grant will also delete all OAuth tokens associated with the application for -// the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-a-grant -func (s *AuthorizationsService) DeleteGrant(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// CreateImpersonation creates an impersonation OAuth token. -// -// This requires admin permissions. With the returned Authorization.Token -// you can e.g. create or delete a user's public SSH key. NOTE: creating a -// new token automatically revokes an existing one. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#create-an-impersonation-oauth-token -func (s *AuthorizationsService) CreateImpersonation(ctx context.Context, username string, authReq *AuthorizationRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("POST", u, authReq) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// DeleteImpersonation deletes an impersonation OAuth token. -// -// NOTE: there can be only one at a time. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#delete-an-impersonation-oauth-token -func (s *AuthorizationsService) DeleteImpersonation(ctx context.Context, username string) (*Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/checks.go b/vendor/github.com/google/go-github/github/checks.go deleted file mode 100644 index 2a6ce4193..000000000 --- a/vendor/github.com/google/go-github/github/checks.go +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ChecksService provides access to the Checks API in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/checks/ -type ChecksService service - -// CheckRun represents a GitHub check run on a repository associated with a GitHub app. -type CheckRun struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - HeadSHA *string `json:"head_sha,omitempty"` - ExternalID *string `json:"external_id,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Status *string `json:"status,omitempty"` - Conclusion *string `json:"conclusion,omitempty"` - StartedAt *Timestamp `json:"started_at,omitempty"` - CompletedAt *Timestamp `json:"completed_at,omitempty"` - Output *CheckRunOutput `json:"output,omitempty"` - Name *string `json:"name,omitempty"` - CheckSuite *CheckSuite `json:"check_suite,omitempty"` - App *App `json:"app,omitempty"` - PullRequests []*PullRequest `json:"pull_requests,omitempty"` -} - -// CheckRunOutput represents the output of a CheckRun. -type CheckRunOutput struct { - Title *string `json:"title,omitempty"` - Summary *string `json:"summary,omitempty"` - Text *string `json:"text,omitempty"` - AnnotationsCount *int `json:"annotations_count,omitempty"` - AnnotationsURL *string `json:"annotations_url,omitempty"` - Annotations []*CheckRunAnnotation `json:"annotations,omitempty"` - Images []*CheckRunImage `json:"images,omitempty"` -} - -// CheckRunAnnotation represents an annotation object for a CheckRun output. -type CheckRunAnnotation struct { - Path *string `json:"path,omitempty"` - BlobHRef *string `json:"blob_href,omitempty"` - StartLine *int `json:"start_line,omitempty"` - EndLine *int `json:"end_line,omitempty"` - AnnotationLevel *string `json:"annotation_level,omitempty"` - Message *string `json:"message,omitempty"` - Title *string `json:"title,omitempty"` - RawDetails *string `json:"raw_details,omitempty"` -} - -// CheckRunImage represents an image object for a CheckRun output. -type CheckRunImage struct { - Alt *string `json:"alt,omitempty"` - ImageURL *string `json:"image_url,omitempty"` - Caption *string `json:"caption,omitempty"` -} - -// CheckSuite represents a suite of check runs. -type CheckSuite struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - HeadBranch *string `json:"head_branch,omitempty"` - HeadSHA *string `json:"head_sha,omitempty"` - URL *string `json:"url,omitempty"` - BeforeSHA *string `json:"before,omitempty"` - AfterSHA *string `json:"after,omitempty"` - Status *string `json:"status,omitempty"` - Conclusion *string `json:"conclusion,omitempty"` - App *App `json:"app,omitempty"` - Repository *Repository `json:"repository,omitempty"` - PullRequests []*PullRequest `json:"pull_requests,omitempty"` -} - -func (c CheckRun) String() string { - return Stringify(c) -} - -func (c CheckSuite) String() string { - return Stringify(c) -} - -// GetCheckRun gets a check-run for a repository. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#get-a-single-check-run -func (s *ChecksService) GetCheckRun(ctx context.Context, owner, repo string, checkRunID int64) (*CheckRun, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-runs/%v", owner, repo, checkRunID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - checkRun := new(CheckRun) - resp, err := s.client.Do(ctx, req, checkRun) - if err != nil { - return nil, resp, err - } - - return checkRun, resp, nil -} - -// GetCheckSuite gets a single check suite. -// -// GitHub API docs: https://developer.github.com/v3/checks/suites/#get-a-single-check-suite -func (s *ChecksService) GetCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64) (*CheckSuite, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-suites/%v", owner, repo, checkSuiteID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - checkSuite := new(CheckSuite) - resp, err := s.client.Do(ctx, req, checkSuite) - if err != nil { - return nil, resp, err - } - - return checkSuite, resp, nil -} - -// CreateCheckRunOptions sets up parameters needed to create a CheckRun. -type CreateCheckRunOptions struct { - Name string `json:"name"` // The name of the check (e.g., "code-coverage"). (Required.) - HeadBranch string `json:"head_branch"` // The name of the branch to perform a check against. (Required.) - HeadSHA string `json:"head_sha"` // The SHA of the commit. (Required.) - DetailsURL *string `json:"details_url,omitempty"` // The URL of the integrator's site that has the full details of the check. (Optional.) - ExternalID *string `json:"external_id,omitempty"` // A reference for the run on the integrator's system. (Optional.) - Status *string `json:"status,omitempty"` // The current status. Can be one of "queued", "in_progress", or "completed". Default: "queued". (Optional.) - Conclusion *string `json:"conclusion,omitempty"` // Can be one of "success", "failure", "neutral", "cancelled", "timed_out", or "action_required". (Optional. Required if you provide a status of "completed".) - StartedAt *Timestamp `json:"started_at,omitempty"` // The time that the check run began. (Optional.) - CompletedAt *Timestamp `json:"completed_at,omitempty"` // The time the check completed. (Optional. Required if you provide conclusion.) - Output *CheckRunOutput `json:"output,omitempty"` // Provide descriptive details about the run. (Optional) -} - -// CreateCheckRun creates a check run for repository. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#create-a-check-run -func (s *ChecksService) CreateCheckRun(ctx context.Context, owner, repo string, opt CreateCheckRunOptions) (*CheckRun, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-runs", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - checkRun := new(CheckRun) - resp, err := s.client.Do(ctx, req, checkRun) - if err != nil { - return nil, resp, err - } - - return checkRun, resp, nil -} - -// UpdateCheckRunOptions sets up parameters needed to update a CheckRun. -type UpdateCheckRunOptions struct { - Name string `json:"name"` // The name of the check (e.g., "code-coverage"). (Required.) - HeadBranch *string `json:"head_branch,omitempty"` // The name of the branch to perform a check against. (Optional.) - HeadSHA *string `json:"head_sha,omitempty"` // The SHA of the commit. (Optional.) - DetailsURL *string `json:"details_url,omitempty"` // The URL of the integrator's site that has the full details of the check. (Optional.) - ExternalID *string `json:"external_id,omitempty"` // A reference for the run on the integrator's system. (Optional.) - Status *string `json:"status,omitempty"` // The current status. Can be one of "queued", "in_progress", or "completed". Default: "queued". (Optional.) - Conclusion *string `json:"conclusion,omitempty"` // Can be one of "success", "failure", "neutral", "cancelled", "timed_out", or "action_required". (Optional. Required if you provide a status of "completed".) - CompletedAt *Timestamp `json:"completed_at,omitempty"` // The time the check completed. (Optional. Required if you provide conclusion.) - Output *CheckRunOutput `json:"output,omitempty"` // Provide descriptive details about the run. (Optional) -} - -// UpdateCheckRun updates a check run for a specific commit in a repository. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#update-a-check-run -func (s *ChecksService) UpdateCheckRun(ctx context.Context, owner, repo string, checkRunID int64, opt UpdateCheckRunOptions) (*CheckRun, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-runs/%v", owner, repo, checkRunID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - checkRun := new(CheckRun) - resp, err := s.client.Do(ctx, req, checkRun) - if err != nil { - return nil, resp, err - } - - return checkRun, resp, nil -} - -// ListCheckRunAnnotations lists the annotations for a check run. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#list-annotations-for-a-check-run -func (s *ChecksService) ListCheckRunAnnotations(ctx context.Context, owner, repo string, checkRunID int64, opt *ListOptions) ([]*CheckRunAnnotation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-runs/%v/annotations", owner, repo, checkRunID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - var checkRunAnnotations []*CheckRunAnnotation - resp, err := s.client.Do(ctx, req, &checkRunAnnotations) - if err != nil { - return nil, resp, err - } - - return checkRunAnnotations, resp, nil -} - -// ListCheckRunsOptions represents parameters to list check runs. -type ListCheckRunsOptions struct { - CheckName *string `url:"check_name,omitempty"` // Returns check runs with the specified name. - Status *string `url:"status,omitempty"` // Returns check runs with the specified status. Can be one of "queued", "in_progress", or "completed". - Filter *string `url:"filter,omitempty"` // Filters check runs by their completed_at timestamp. Can be one of "latest" (returning the most recent check runs) or "all". Default: "latest" - - ListOptions -} - -// ListCheckRunsResults represents the result of a check run list. -type ListCheckRunsResults struct { - Total *int `json:"total_count,omitempty"` - CheckRuns []*CheckRun `json:"check_runs,omitempty"` -} - -// ListCheckRunsForRef lists check runs for a specific ref. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref -func (s *ChecksService) ListCheckRunsForRef(ctx context.Context, owner, repo, ref string, opt *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/check-runs", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - var checkRunResults *ListCheckRunsResults - resp, err := s.client.Do(ctx, req, &checkRunResults) - if err != nil { - return nil, resp, err - } - - return checkRunResults, resp, nil -} - -// ListCheckRunsCheckSuite lists check runs for a check suite. -// -// GitHub API docs: https://developer.github.com/v3/checks/runs/#list-check-runs-in-a-check-suite -func (s *ChecksService) ListCheckRunsCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64, opt *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-suites/%v/check-runs", owner, repo, checkSuiteID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - var checkRunResults *ListCheckRunsResults - resp, err := s.client.Do(ctx, req, &checkRunResults) - if err != nil { - return nil, resp, err - } - - return checkRunResults, resp, nil -} - -// ListCheckSuiteOptions represents parameters to list check suites. -type ListCheckSuiteOptions struct { - CheckName *string `url:"check_name,omitempty"` // Filters checks suites by the name of the check run. - AppID *int `url:"app_id,omitempty"` // Filters check suites by GitHub App id. - - ListOptions -} - -// ListCheckSuiteResults represents the result of a check run list. -type ListCheckSuiteResults struct { - Total *int `json:"total_count,omitempty"` - CheckSuites []*CheckSuite `json:"check_suites,omitempty"` -} - -// ListCheckSuitesForRef lists check suite for a specific ref. -// -// GitHub API docs: https://developer.github.com/v3/checks/suites/#list-check-suites-for-a-specific-ref -func (s *ChecksService) ListCheckSuitesForRef(ctx context.Context, owner, repo, ref string, opt *ListCheckSuiteOptions) (*ListCheckSuiteResults, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/check-suites", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - var checkSuiteResults *ListCheckSuiteResults - resp, err := s.client.Do(ctx, req, &checkSuiteResults) - if err != nil { - return nil, resp, err - } - - return checkSuiteResults, resp, nil -} - -// AutoTriggerCheck enables or disables automatic creation of CheckSuite events upon pushes to the repository. -type AutoTriggerCheck struct { - AppID *int64 `json:"app_id,omitempty"` // The id of the GitHub App. (Required.) - Setting *bool `json:"setting,omitempty"` // Set to "true" to enable automatic creation of CheckSuite events upon pushes to the repository, or "false" to disable them. Default: "true" (Required.) -} - -// CheckSuitePreferenceOptions set options for check suite preferences for a repository. -type CheckSuitePreferenceOptions struct { - PreferenceList *PreferenceList `json:"auto_trigger_checks,omitempty"` // A list of auto trigger checks that can be set for a check suite in a repository. -} - -// CheckSuitePreferenceResults represents the results of the preference set operation. -type CheckSuitePreferenceResults struct { - Preferences *PreferenceList `json:"preferences,omitempty"` - Repository *Repository `json:"repository,omitempty"` -} - -// PreferenceList represents a list of auto trigger checks for repository -type PreferenceList struct { - AutoTriggerChecks []*AutoTriggerCheck `json:"auto_trigger_checks,omitempty"` // A slice of auto trigger checks that can be set for a check suite in a repository. -} - -// SetCheckSuitePreferences changes the default automatic flow when creating check suites. -// -// GitHub API docs: https://developer.github.com/v3/checks/suites/#set-preferences-for-check-suites-on-a-repository -func (s *ChecksService) SetCheckSuitePreferences(ctx context.Context, owner, repo string, opt CheckSuitePreferenceOptions) (*CheckSuitePreferenceResults, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-suites/preferences", owner, repo) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - var checkSuitePrefResults *CheckSuitePreferenceResults - resp, err := s.client.Do(ctx, req, &checkSuitePrefResults) - if err != nil { - return nil, resp, err - } - - return checkSuitePrefResults, resp, nil -} - -// CreateCheckSuiteOptions sets up parameters to manually create a check suites -type CreateCheckSuiteOptions struct { - HeadSHA string `json:"head_sha"` // The sha of the head commit. (Required.) - HeadBranch *string `json:"head_branch,omitempty"` // The name of the head branch where the code changes are implemented. -} - -// CreateCheckSuite manually creates a check suite for a repository. -// -// GitHub API docs: https://developer.github.com/v3/checks/suites/#create-a-check-suite -func (s *ChecksService) CreateCheckSuite(ctx context.Context, owner, repo string, opt CreateCheckSuiteOptions) (*CheckSuite, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-suites", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - checkSuite := new(CheckSuite) - resp, err := s.client.Do(ctx, req, checkSuite) - if err != nil { - return nil, resp, err - } - - return checkSuite, resp, nil -} - -// ReRequestCheckSuite triggers GitHub to rerequest an existing check suite, without pushing new code to a repository. -// -// GitHub API docs: https://developer.github.com/v3/checks/suites/#rerequest-check-suite -func (s *ChecksService) ReRequestCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/check-suites/%v/rerequest", owner, repo, checkSuiteID) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", mediaTypeCheckRunsPreview) - - resp, err := s.client.Do(ctx, req, nil) - return resp, err -} diff --git a/vendor/github.com/google/go-github/github/doc.go b/vendor/github.com/google/go-github/github/doc.go deleted file mode 100644 index 96445d264..000000000 --- a/vendor/github.com/google/go-github/github/doc.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package github provides a client for using the GitHub API. - -Usage: - - import "github.com/google/go-github/github" - -Construct a new GitHub client, then use the various services on the client to -access different parts of the GitHub API. For example: - - client := github.NewClient(nil) - - // list all organizations for user "willnorris" - orgs, _, err := client.Organizations.List(ctx, "willnorris", nil) - -Some API methods have optional parameters that can be passed. For example: - - client := github.NewClient(nil) - - // list public repositories for org "github" - opt := &github.RepositoryListByOrgOptions{Type: "public"} - repos, _, err := client.Repositories.ListByOrg(ctx, "github", opt) - -The services of a client divide the API into logical chunks and correspond to -the structure of the GitHub API documentation at -https://developer.github.com/v3/. - -NOTE: Using the https://godoc.org/context package, one can easily -pass cancelation signals and deadlines to various services of the client for -handling a request. In case there is no context available, then context.Background() -can be used as a starting point. - -For more sample code snippets, head over to the https://github.com/google/go-github/tree/master/example directory. - -Authentication - -The go-github library does not directly handle authentication. Instead, when -creating a new client, pass an http.Client that can handle authentication for -you. The easiest and recommended way to do this is using the golang.org/x/oauth2 -library, but you can always use any other library that provides an http.Client. -If you have an OAuth2 access token (for example, a personal API token), you can -use it with the oauth2 library using: - - import "golang.org/x/oauth2" - - func main() { - ctx := context.Background() - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: "... your access token ..."}, - ) - tc := oauth2.NewClient(ctx, ts) - - client := github.NewClient(tc) - - // list all repositories for the authenticated user - repos, _, err := client.Repositories.List(ctx, "", nil) - } - -Note that when using an authenticated Client, all calls made by the client will -include the specified OAuth token. Therefore, authenticated clients should -almost never be shared between different users. - -See the oauth2 docs for complete instructions on using that library. - -For API methods that require HTTP Basic Authentication, use the -BasicAuthTransport. - -GitHub Apps authentication can be provided by the -https://github.com/bradleyfalzon/ghinstallation package. - - import "github.com/bradleyfalzon/ghinstallation" - - func main() { - // Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99. - itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem") - if err != nil { - // Handle error. - } - - // Use installation transport with client - client := github.NewClient(&http.Client{Transport: itr}) - - // Use client... - } - -Rate Limiting - -GitHub imposes a rate limit on all API clients. Unauthenticated clients are -limited to 60 requests per hour, while authenticated clients can make up to -5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated -clients are limited to 10 requests per minute, while authenticated clients -can make up to 30 requests per minute. To receive the higher rate limit when -making calls that are not issued on behalf of a user, -use UnauthenticatedRateLimitedTransport. - -The returned Response.Rate value contains the rate limit information -from the most recent API call. If a recent enough response isn't -available, you can use RateLimits to fetch the most up-to-date rate -limit data for the client. - -To detect an API rate limit error, you can check if its type is *github.RateLimitError: - - repos, _, err := client.Repositories.List(ctx, "", nil) - if _, ok := err.(*github.RateLimitError); ok { - log.Println("hit rate limit") - } - -Learn more about GitHub rate limiting at -https://developer.github.com/v3/#rate-limiting. - -Accepted Status - -Some endpoints may return a 202 Accepted status code, meaning that the -information required is not yet ready and was scheduled to be gathered on -the GitHub side. Methods known to behave like this are documented specifying -this behavior. - -To detect this condition of error, you can check if its type is -*github.AcceptedError: - - stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo) - if _, ok := err.(*github.AcceptedError); ok { - log.Println("scheduled on GitHub side") - } - -Conditional Requests - -The GitHub API has good support for conditional requests which will help -prevent you from burning through your rate limit, as well as help speed up your -application. go-github does not handle conditional requests directly, but is -instead designed to work with a caching http.Transport. We recommend using -https://github.com/gregjones/httpcache for that. - -Learn more about GitHub conditional requests at -https://developer.github.com/v3/#conditional-requests. - -Creating and Updating Resources - -All structs for GitHub resources use pointer values for all non-repeated fields. -This allows distinguishing between unset fields and those set to a zero-value. -Helper functions have been provided to easily create these pointers for string, -bool, and int values. For example: - - // create a new private repository named "foo" - repo := &github.Repository{ - Name: github.String("foo"), - Private: github.Bool(true), - } - client.Repositories.Create(ctx, "", repo) - -Users who have worked with protocol buffers should find this pattern familiar. - -Pagination - -All requests for resource collections (repos, pull requests, issues, etc.) -support pagination. Pagination options are described in the -github.ListOptions struct and passed to the list methods directly or as an -embedded type of a more specific list options struct (for example -github.PullRequestListOptions). Pages information is available via the -github.Response struct. - - client := github.NewClient(nil) - - opt := &github.RepositoryListByOrgOptions{ - ListOptions: github.ListOptions{PerPage: 10}, - } - // get all pages of results - var allRepos []*github.Repository - for { - repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt) - if err != nil { - return err - } - allRepos = append(allRepos, repos...) - if resp.NextPage == 0 { - break - } - opt.Page = resp.NextPage - } - -*/ -package github diff --git a/vendor/github.com/google/go-github/github/event_types.go b/vendor/github.com/google/go-github/github/event_types.go deleted file mode 100644 index 27df3aef5..000000000 --- a/vendor/github.com/google/go-github/github/event_types.go +++ /dev/null @@ -1,787 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// These event types are shared between the Events API and used as Webhook payloads. - -package github - -// CheckRunEvent is triggered when a check run is "created", "updated", or "re-requested". -// The Webhook event name is "check_run". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#checkrunevent -type CheckRunEvent struct { - CheckRun *CheckRun `json:"check_run,omitempty"` - // The action performed. Can be "created", "updated" or "re-requested". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// CheckSuiteEvent is triggered when a check suite is "completed", "requested", or "re-requested". -// The Webhook event name is "check_suite". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#checksuiteevent -type CheckSuiteEvent struct { - CheckSuite *CheckSuite `json:"check_suite,omitempty"` - // The action performed. Can be "completed", "requested" or "re-requested". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// CommitCommentEvent is triggered when a commit comment is created. -// The Webhook event name is "commit_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent -type CommitCommentEvent struct { - Comment *RepositoryComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// CreateEvent represents a created repository, branch, or tag. -// The Webhook event name is "create". -// -// Note: webhooks will not receive this event for created repositories. -// Additionally, webhooks will not receive this event for tags if more -// than three tags are pushed at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#createevent -type CreateEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was created. Possible values are: "repository", "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Description *string `json:"description,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeleteEvent represents a deleted branch or tag. -// The Webhook event name is "delete". -// -// Note: webhooks will not receive this event for tags if more than three tags -// are deleted at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deleteevent -type DeleteEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was deleted. Possible values are: "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentEvent represents a deployment. -// The Webhook event name is "deployment". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentevent -type DeploymentEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentStatusEvent represents a deployment status. -// The Webhook event name is "deployment_status". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent -type DeploymentStatusEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ForkEvent is triggered when a user forks a repository. -// The Webhook event name is "fork". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#forkevent -type ForkEvent struct { - // Forkee is the created repository. - Forkee *Repository `json:"forkee,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// Page represents a single Wiki page. -type Page struct { - PageName *string `json:"page_name,omitempty"` - Title *string `json:"title,omitempty"` - Summary *string `json:"summary,omitempty"` - Action *string `json:"action,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// GollumEvent is triggered when a Wiki page is created or updated. -// The Webhook event name is "gollum". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#gollumevent -type GollumEvent struct { - Pages []*Page `json:"pages,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// EditChange represents the changes when an issue, pull request, or comment has -// been edited. -type EditChange struct { - Title *struct { - From *string `json:"from,omitempty"` - } `json:"title,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectChange represents the changes when a project has been edited. -type ProjectChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectCardChange represents the changes when a project card has been edited. -type ProjectCardChange struct { - Note *struct { - From *string `json:"from,omitempty"` - } `json:"note,omitempty"` -} - -// ProjectColumnChange represents the changes when a project column has been edited. -type ProjectColumnChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` -} - -// TeamChange represents the changes when a team has been edited. -type TeamChange struct { - Description *struct { - From *string `json:"from,omitempty"` - } `json:"description,omitempty"` - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Privacy *struct { - From *string `json:"from,omitempty"` - } `json:"privacy,omitempty"` - Repository *struct { - Permissions *struct { - From *struct { - Admin *bool `json:"admin,omitempty"` - Pull *bool `json:"pull,omitempty"` - Push *bool `json:"push,omitempty"` - } `json:"from,omitempty"` - } `json:"permissions,omitempty"` - } `json:"repository,omitempty"` -} - -// InstallationEvent is triggered when a GitHub App has been installed or uninstalled. -// The Webhook event name is "installation". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationevent -type InstallationEvent struct { - // The action that was performed. Can be either "created" or "deleted". - Action *string `json:"action,omitempty"` - Repositories []*Repository `json:"repositories,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// InstallationRepositoriesEvent is triggered when a repository is added or -// removed from an installation. The Webhook event name is "installation_repositories". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationrepositoriesevent -type InstallationRepositoriesEvent struct { - // The action that was performed. Can be either "added" or "removed". - Action *string `json:"action,omitempty"` - RepositoriesAdded []*Repository `json:"repositories_added,omitempty"` - RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"` - RepositorySelection *string `json:"repository_selection,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssueCommentEvent is triggered when an issue comment is created on an issue -// or pull request. -// The Webhook event name is "issue_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent -type IssueCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Comment *IssueComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssuesEvent is triggered when an issue is assigned, unassigned, labeled, -// unlabeled, opened, closed, or reopened. -// The Webhook event name is "issues". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuesevent -type IssuesEvent struct { - // Action is the action that was performed. Possible values are: "assigned", - // "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// LabelEvent is triggered when a repository's label is created, edited, or deleted. -// The Webhook event name is "label" -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#labelevent -type LabelEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "edited", "deleted" - Action *string `json:"action,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MarketplacePurchaseEvent is triggered when a user purchases, cancels, or changes -// their GitHub Marketplace plan. -// Webhook event name "marketplace_purchase". -// -// Github API docs: https://developer.github.com/v3/activity/events/types/#marketplacepurchaseevent -type MarketplacePurchaseEvent struct { - // Action is the action that was performed. Possible values are: - // "purchased", "cancelled", "changed". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - EffectiveDate *Timestamp `json:"effective_date,omitempty"` - MarketplacePurchase *MarketplacePurchase `json:"marketplace_purchase,omitempty"` - PreviousMarketplacePurchase *MarketplacePurchase `json:"previous_marketplace_purchase,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MemberEvent is triggered when a user is added as a collaborator to a repository. -// The Webhook event name is "member". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#memberevent -type MemberEvent struct { - // Action is the action that was performed. Possible value is: "added". - Action *string `json:"action,omitempty"` - Member *User `json:"member,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MembershipEvent is triggered when a user is added or removed from a team. -// The Webhook event name is "membership". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#membershipevent -type MembershipEvent struct { - // Action is the action that was performed. Possible values are: "added", "removed". - Action *string `json:"action,omitempty"` - // Scope is the scope of the membership. Possible value is: "team". - Scope *string `json:"scope,omitempty"` - Member *User `json:"member,omitempty"` - Team *Team `json:"team,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MilestoneEvent is triggered when a milestone is created, closed, opened, edited, or deleted. -// The Webhook event name is "milestone". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#milestoneevent -type MilestoneEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "closed", "opened", "edited", "deleted" - Action *string `json:"action,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrganizationEvent is triggered when a user is added, removed, or invited to an organization. -// Events of this type are not visible in timelines. These events are only used to trigger organization hooks. -// Webhook event name is "organization". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#organizationevent -type OrganizationEvent struct { - // Action is the action that was performed. - // Can be one of "member_added", "member_removed", or "member_invited". - Action *string `json:"action,omitempty"` - - // Invitaion is the invitation for the user or email if the action is "member_invited". - Invitation *Invitation `json:"invitation,omitempty"` - - // Membership is the membership between the user and the organization. - // Not present when the action is "member_invited". - Membership *Membership `json:"membership,omitempty"` - - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrgBlockEvent is triggered when an organization blocks or unblocks a user. -// The Webhook event name is "org_block". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#orgblockevent -type OrgBlockEvent struct { - // Action is the action that was performed. - // Can be "blocked" or "unblocked". - Action *string `json:"action,omitempty"` - BlockedUser *User `json:"blocked_user,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - - // The following fields are only populated by Webhook events. - Installation *Installation `json:"installation,omitempty"` -} - -// PageBuildEvent represents an attempted build of a GitHub Pages site, whether -// successful or not. -// The Webhook event name is "page_build". -// -// This event is triggered on push to a GitHub Pages enabled branch (gh-pages -// for project pages, master for user and organization pages). -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent -type PageBuildEvent struct { - Build *PagesBuild `json:"build,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int64 `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PingEvent is triggered when a Webhook is added to GitHub. -// -// GitHub API docs: https://developer.github.com/webhooks/#ping-event -type PingEvent struct { - // Random string of GitHub zen. - Zen *string `json:"zen,omitempty"` - // The ID of the webhook that triggered the ping. - HookID *int64 `json:"hook_id,omitempty"` - // The webhook configuration. - Hook *Hook `json:"hook,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectEvent is triggered when project is created, modified or deleted. -// The webhook event name is "project". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectevent -type ProjectEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectChange `json:"changes,omitempty"` - Project *Project `json:"project,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectCardEvent is triggered when a project card is created, updated, moved, converted to an issue, or deleted. -// The webhook event name is "project_card". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcardevent -type ProjectCardEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectCardChange `json:"changes,omitempty"` - AfterID *int64 `json:"after_id,omitempty"` - ProjectCard *ProjectCard `json:"project_card,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectColumnEvent is triggered when a project column is created, updated, moved, or deleted. -// The webhook event name is "project_column". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcolumnevent -type ProjectColumnEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectColumnChange `json:"changes,omitempty"` - AfterID *int64 `json:"after_id,omitempty"` - ProjectColumn *ProjectColumn `json:"project_column,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PublicEvent is triggered when a private repository is open sourced. -// According to GitHub: "Without a doubt: the best GitHub event." -// The Webhook event name is "public". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#publicevent -type PublicEvent struct { - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PullRequestEvent is triggered when a pull request is assigned, unassigned, -// labeled, unlabeled, opened, closed, reopened, or synchronized. -// The Webhook event name is "pull_request". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent -type PullRequestEvent struct { - // Action is the action that was performed. Possible values are: - // "assigned", "unassigned", "review_requested", "review_request_removed", "labeled", "unlabeled", - // "opened", "closed", "reopened", "synchronize", "edited". - // If the action is "closed" and the merged key is false, - // the pull request was closed with unmerged commits. If the action is "closed" - // and the merged key is true, the pull request was merged. - Action *string `json:"action,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Number *int `json:"number,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - // RequestedReviewer is populated in "review_requested", "review_request_removed" event deliveries. - // A request affecting multiple reviewers at once is split into multiple - // such event deliveries, each with a single, different RequestedReviewer. - RequestedReviewer *User `json:"requested_reviewer,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` - Label *Label `json:"label,omitempty"` // Populated in "labeled" event deliveries. -} - -// PullRequestReviewEvent is triggered when a review is submitted on a pull -// request. -// The Webhook event name is "pull_request_review". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent -type PullRequestReviewEvent struct { - // Action is always "submitted". - Action *string `json:"action,omitempty"` - Review *PullRequestReview `json:"review,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` - - // The following field is only present when the webhook is triggered on - // a repository belonging to an organization. - Organization *Organization `json:"organization,omitempty"` -} - -// PullRequestReviewCommentEvent is triggered when a comment is created on a -// portion of the unified diff of a pull request. -// The Webhook event name is "pull_request_review_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent -type PullRequestReviewCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - Comment *PullRequestComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PushEvent represents a git push to a GitHub repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pushevent -type PushEvent struct { - PushID *int64 `json:"push_id,omitempty"` - Head *string `json:"head,omitempty"` - Ref *string `json:"ref,omitempty"` - Size *int `json:"size,omitempty"` - Commits []PushEventCommit `json:"commits,omitempty"` - Before *string `json:"before,omitempty"` - DistinctSize *int `json:"distinct_size,omitempty"` - - // The following fields are only populated by Webhook events. - After *string `json:"after,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - BaseRef *string `json:"base_ref,omitempty"` - Compare *string `json:"compare,omitempty"` - Repo *PushEventRepository `json:"repository,omitempty"` - HeadCommit *PushEventCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -func (p PushEvent) String() string { - return Stringify(p) -} - -// PushEventCommit represents a git commit in a GitHub PushEvent. -type PushEventCommit struct { - Message *string `json:"message,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - URL *string `json:"url,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - - // The following fields are only populated by Events API. - SHA *string `json:"sha,omitempty"` - - // The following fields are only populated by Webhook events. - ID *string `json:"id,omitempty"` - TreeID *string `json:"tree_id,omitempty"` - Timestamp *Timestamp `json:"timestamp,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Added []string `json:"added,omitempty"` - Removed []string `json:"removed,omitempty"` - Modified []string `json:"modified,omitempty"` -} - -func (p PushEventCommit) String() string { - return Stringify(p) -} - -// PushEventRepository represents the repo object in a PushEvent payload. -type PushEventRepository struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Owner *User `json:"owner,omitempty"` - Private *bool `json:"private,omitempty"` - Description *string `json:"description,omitempty"` - Fork *bool `json:"fork,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Homepage *string `json:"homepage,omitempty"` - Size *int `json:"size,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Language *string `json:"language,omitempty"` - HasIssues *bool `json:"has_issues,omitempty"` - HasDownloads *bool `json:"has_downloads,omitempty"` - HasWiki *bool `json:"has_wiki,omitempty"` - HasPages *bool `json:"has_pages,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Organization *string `json:"organization,omitempty"` - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` -} - -// PushEventRepoOwner is a basic representation of user/org in a PushEvent payload. -type PushEventRepoOwner struct { - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` -} - -// ReleaseEvent is triggered when a release is published. -// The Webhook event name is "release". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#releaseevent -type ReleaseEvent struct { - // Action is the action that was performed. Possible value is: "published". - Action *string `json:"action,omitempty"` - Release *RepositoryRelease `json:"release,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// RepositoryEvent is triggered when a repository is created. -// The Webhook event name is "repository". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#repositoryevent -type RepositoryEvent struct { - // Action is the action that was performed. Possible values are: "created", "deleted", - // "publicized", "privatized". - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// StatusEvent is triggered when the status of a Git commit changes. -// The Webhook event name is "status". -// -// Events of this type are not visible in timelines, they are only used to -// trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#statusevent -type StatusEvent struct { - SHA *string `json:"sha,omitempty"` - // State is the new state. Possible values are: "pending", "success", "failure", "error". - State *string `json:"state,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - Branches []*Branch `json:"branches,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Context *string `json:"context,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamEvent is triggered when an organization's team is created, modified or deleted. -// The Webhook event name is "team". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamevent -type TeamEvent struct { - Action *string `json:"action,omitempty"` - Team *Team `json:"team,omitempty"` - Changes *TeamChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamAddEvent is triggered when a repository is added to a team. -// The Webhook event name is "team_add". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamaddevent -type TeamAddEvent struct { - Team *Team `json:"team,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// WatchEvent is related to starring a repository, not watching. See this API -// blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/ -// -// The event’s actor is the user who starred a repository, and the event’s -// repository is the repository that was starred. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#watchevent -type WatchEvent struct { - // Action is the action that was performed. Possible value is: "started". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} diff --git a/vendor/github.com/google/go-github/github/gists.go b/vendor/github.com/google/go-github/github/gists.go deleted file mode 100644 index 15e0bc2cd..000000000 --- a/vendor/github.com/google/go-github/github/gists.go +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GistsService handles communication with the Gist related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gists/ -type GistsService service - -// Gist represents a GitHub's gist. -type Gist struct { - ID *string `json:"id,omitempty"` - Description *string `json:"description,omitempty"` - Public *bool `json:"public,omitempty"` - Owner *User `json:"owner,omitempty"` - Files map[GistFilename]GistFile `json:"files,omitempty"` - Comments *int `json:"comments,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitPullURL *string `json:"git_pull_url,omitempty"` - GitPushURL *string `json:"git_push_url,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (g Gist) String() string { - return Stringify(g) -} - -// GistFilename represents filename on a gist. -type GistFilename string - -// GistFile represents a file on a gist. -type GistFile struct { - Size *int `json:"size,omitempty"` - Filename *string `json:"filename,omitempty"` - Language *string `json:"language,omitempty"` - Type *string `json:"type,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - Content *string `json:"content,omitempty"` -} - -func (g GistFile) String() string { - return Stringify(g) -} - -// GistCommit represents a commit on a gist. -type GistCommit struct { - URL *string `json:"url,omitempty"` - Version *string `json:"version,omitempty"` - User *User `json:"user,omitempty"` - ChangeStatus *CommitStats `json:"change_status,omitempty"` - CommittedAt *Timestamp `json:"committed_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (gc GistCommit) String() string { - return Stringify(gc) -} - -// GistFork represents a fork of a gist. -type GistFork struct { - URL *string `json:"url,omitempty"` - User *User `json:"user,omitempty"` - ID *string `json:"id,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (gf GistFork) String() string { - return Stringify(gf) -} - -// GistListOptions specifies the optional parameters to the -// GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods. -type GistListOptions struct { - // Since filters Gists by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// List gists for a user. Passing the empty string will list -// all public gists if called anonymously. However, if the call -// is authenticated, it will returns all gists for the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) List(ctx context.Context, user string, opt *GistListOptions) ([]*Gist, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gists", user) - } else { - u = "gists" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListAll lists all public gists. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListAll(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/public", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListStarred lists starred gists of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListStarred(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/starred", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// Get a single gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-single-gist -func (s *GistsService) Get(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// GetRevision gets a specific revision of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist -func (s *GistsService) GetRevision(ctx context.Context, id, sha string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/%v", id, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// Create a gist for authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#create-a-gist -func (s *GistsService) Create(ctx context.Context, gist *Gist) (*Gist, *Response, error) { - u := "gists" - req, err := s.client.NewRequest("POST", u, gist) - if err != nil { - return nil, nil, err - } - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// Edit a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#edit-a-gist -func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("PATCH", u, gist) - if err != nil { - return nil, nil, err - } - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListCommits lists commits of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-commits -func (s *GistsService) ListCommits(ctx context.Context, id string, opt *ListOptions) ([]*GistCommit, *Response, error) { - u := fmt.Sprintf("gists/%v/commits", id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gistCommits []*GistCommit - resp, err := s.client.Do(ctx, req, &gistCommits) - if err != nil { - return nil, resp, err - } - - return gistCommits, resp, nil -} - -// Delete a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#delete-a-gist -func (s *GistsService) Delete(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Star a gist on behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#star-a-gist -func (s *GistsService) Star(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a gist on a behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#unstar-a-gist -func (s *GistsService) Unstar(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// IsStarred checks if a gist is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#check-if-a-gist-is-starred -func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Fork a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#fork-a-gist -func (s *GistsService) Fork(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListForks lists forks of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-forks -func (s *GistsService) ListForks(ctx context.Context, id string) ([]*GistFork, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gistForks []*GistFork - resp, err := s.client.Do(ctx, req, &gistForks) - if err != nil { - return nil, resp, err - } - - return gistForks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/gists_comments.go b/vendor/github.com/google/go-github/github/gists_comments.go deleted file mode 100644 index d5322e3d8..000000000 --- a/vendor/github.com/google/go-github/github/gists_comments.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GistComment represents a Gist comment. -type GistComment struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -func (g GistComment) String() string { - return Stringify(g) -} - -// ListComments lists all comments for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist -func (s *GistsService) ListComments(ctx context.Context, gistID string, opt *ListOptions) ([]*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*GistComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment retrieves a single comment from a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#get-a-single-comment -func (s *GistsService) GetComment(ctx context.Context, gistID string, commentID int64) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// CreateComment creates a comment for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#create-a-comment -func (s *GistsService) CreateComment(ctx context.Context, gistID string, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment edits an existing gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#edit-a-comment -func (s *GistsService) EditComment(ctx context.Context, gistID string, commentID int64, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#delete-a-comment -func (s *GistsService) DeleteComment(ctx context.Context, gistID string, commentID int64) (*Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git.go b/vendor/github.com/google/go-github/github/git.go deleted file mode 100644 index 1ce47437b..000000000 --- a/vendor/github.com/google/go-github/github/git.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -// GitService handles communication with the git data related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/git/ -type GitService service diff --git a/vendor/github.com/google/go-github/github/git_blobs.go b/vendor/github.com/google/go-github/github/git_blobs.go deleted file mode 100644 index 70aee14a7..000000000 --- a/vendor/github.com/google/go-github/github/git_blobs.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" -) - -// Blob represents a blob object. -type Blob struct { - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// GetBlob fetches a blob from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob -func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha string) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - blob := new(Blob) - resp, err := s.client.Do(ctx, req, blob) - return blob, resp, err -} - -// GetBlobRaw fetches a blob's contents from a repo. -// Unlike GetBlob, it returns the raw bytes rather than the base64-encoded data. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob -func (s *GitService) GetBlobRaw(ctx context.Context, owner, repo, sha string) ([]byte, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - req.Header.Set("Accept", "application/vnd.github.v3.raw") - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - return buf.Bytes(), resp, err -} - -// CreateBlob creates a blob object. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob -func (s *GitService) CreateBlob(ctx context.Context, owner string, repo string, blob *Blob) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs", owner, repo) - req, err := s.client.NewRequest("POST", u, blob) - if err != nil { - return nil, nil, err - } - - t := new(Blob) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_commits.go b/vendor/github.com/google/go-github/github/git_commits.go deleted file mode 100644 index 1eb48a8e2..000000000 --- a/vendor/github.com/google/go-github/github/git_commits.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// SignatureVerification represents GPG signature verification. -type SignatureVerification struct { - Verified *bool `json:"verified,omitempty"` - Reason *string `json:"reason,omitempty"` - Signature *string `json:"signature,omitempty"` - Payload *string `json:"payload,omitempty"` -} - -// Commit represents a GitHub commit. -type Commit struct { - SHA *string `json:"sha,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *Tree `json:"tree,omitempty"` - Parents []Commit `json:"parents,omitempty"` - Stats *CommitStats `json:"stats,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // CommentCount is the number of GitHub comments on the commit. This - // is only populated for requests that fetch GitHub data like - // Pulls.ListCommits, Repositories.ListCommits, etc. - CommentCount *int `json:"comment_count,omitempty"` -} - -func (c Commit) String() string { - return Stringify(c) -} - -// CommitAuthor represents the author or committer of a commit. The commit -// author may not correspond to a GitHub User. -type CommitAuthor struct { - Date *time.Time `json:"date,omitempty"` - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` - - // The following fields are only populated by Webhook events. - Login *string `json:"username,omitempty"` // Renamed for go-github consistency. -} - -func (c CommitAuthor) String() string { - return Stringify(c) -} - -// GetCommit fetchs the Commit object for a given SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#get-a-commit -func (s *GitService) GetCommit(ctx context.Context, owner string, repo string, sha string) (*Commit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/commits/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// createCommit represents the body of a CreateCommit request. -type createCommit struct { - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *string `json:"tree,omitempty"` - Parents []string `json:"parents,omitempty"` -} - -// CreateCommit creates a new commit in a repository. -// commit must not be nil. -// -// The commit.Committer is optional and will be filled with the commit.Author -// data if omitted. If the commit.Author is omitted, it will be filled in with -// the authenticated user’s information and the current date. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#create-a-commit -func (s *GitService) CreateCommit(ctx context.Context, owner string, repo string, commit *Commit) (*Commit, *Response, error) { - if commit == nil { - return nil, nil, fmt.Errorf("commit must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/git/commits", owner, repo) - - parents := make([]string, len(commit.Parents)) - for i, parent := range commit.Parents { - parents[i] = *parent.SHA - } - - body := &createCommit{ - Author: commit.Author, - Committer: commit.Committer, - Message: commit.Message, - Parents: parents, - } - if commit.Tree != nil { - body.Tree = commit.Tree.SHA - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/git_refs.go b/vendor/github.com/google/go-github/github/git_refs.go deleted file mode 100644 index 3b2ced233..000000000 --- a/vendor/github.com/google/go-github/github/git_refs.go +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" -) - -// Reference represents a GitHub reference. -type Reference struct { - Ref *string `json:"ref"` - URL *string `json:"url"` - Object *GitObject `json:"object"` - NodeID *string `json:"node_id,omitempty"` -} - -func (r Reference) String() string { - return Stringify(r) -} - -// GitObject represents a Git object. -type GitObject struct { - Type *string `json:"type"` - SHA *string `json:"sha"` - URL *string `json:"url"` -} - -func (o GitObject) String() string { - return Stringify(o) -} - -// createRefRequest represents the payload for creating a reference. -type createRefRequest struct { - Ref *string `json:"ref"` - SHA *string `json:"sha"` -} - -// updateRefRequest represents the payload for updating a reference. -type updateRefRequest struct { - SHA *string `json:"sha"` - Force *bool `json:"force"` -} - -// GetRef fetches a single Reference object for a given Git ref. -// If there is no exact match, GetRef will return an error. -// -// Note: The GitHub API can return multiple matches. -// If you wish to use this functionality please use the GetRefs() method. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref string) (*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if _, ok := err.(*json.UnmarshalTypeError); ok { - // Multiple refs, means there wasn't an exact match. - return nil, resp, errors.New("no exact match found for this ref") - } else if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetRefs fetches a slice of Reference objects for a given Git ref. -// If there is an exact match, only that ref is returned. -// If there is no exact match, GitHub returns all refs that start with ref. -// If returned error is nil, there will be at least 1 ref returned. -// For example: -// -// "heads/featureA" -> ["refs/heads/featureA"] // Exact match, single ref is returned. -// "heads/feature" -> ["refs/heads/featureA", "refs/heads/featureB"] // All refs that start with ref. -// "heads/notexist" -> [] // Returns an error. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRefs(ctx context.Context, owner string, repo string, ref string) ([]*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var rawJSON json.RawMessage - resp, err := s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, resp, err - } - - // Prioritize the most common case: a single returned ref. - r := new(Reference) - singleUnmarshalError := json.Unmarshal(rawJSON, r) - if singleUnmarshalError == nil { - return []*Reference{r}, resp, nil - } - - // Attempt to unmarshal multiple refs. - var rs []*Reference - multipleUnmarshalError := json.Unmarshal(rawJSON, &rs) - if multipleUnmarshalError == nil { - if len(rs) == 0 { - return nil, resp, fmt.Errorf("unexpected response from GitHub API: an array of refs with length 0") - } - return rs, resp, nil - } - - return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", singleUnmarshalError, multipleUnmarshalError) -} - -// ReferenceListOptions specifies optional parameters to the -// GitService.ListRefs method. -type ReferenceListOptions struct { - Type string `url:"-"` - - ListOptions -} - -// ListRefs lists all refs in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-all-references -func (s *GitService) ListRefs(ctx context.Context, owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error) { - var u string - if opt != nil && opt.Type != "" { - u = fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, opt.Type) - } else { - u = fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var rs []*Reference - resp, err := s.client.Do(ctx, req, &rs) - if err != nil { - return nil, resp, err - } - - return rs, resp, nil -} - -// CreateRef creates a new ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#create-a-reference -func (s *GitService) CreateRef(ctx context.Context, owner string, repo string, ref *Reference) (*Reference, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - req, err := s.client.NewRequest("POST", u, &createRefRequest{ - // back-compat with previous behavior that didn't require 'refs/' prefix - Ref: String("refs/" + strings.TrimPrefix(*ref.Ref, "refs/")), - SHA: ref.Object.SHA, - }) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdateRef updates an existing ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#update-a-reference -func (s *GitService) UpdateRef(ctx context.Context, owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error) { - refPath := strings.TrimPrefix(*ref.Ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refPath) - req, err := s.client.NewRequest("PATCH", u, &updateRefRequest{ - SHA: ref.Object.SHA, - Force: &force, - }) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DeleteRef deletes a ref from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#delete-a-reference -func (s *GitService) DeleteRef(ctx context.Context, owner string, repo string, ref string) (*Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git_tags.go b/vendor/github.com/google/go-github/github/git_tags.go deleted file mode 100644 index 90398b380..000000000 --- a/vendor/github.com/google/go-github/github/git_tags.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Tag represents a tag object. -type Tag struct { - Tag *string `json:"tag,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - Message *string `json:"message,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` - Object *GitObject `json:"object,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// createTagRequest represents the body of a CreateTag request. This is mostly -// identical to Tag with the exception that the object SHA and Type are -// top-level fields, rather than being nested inside a JSON object. -type createTagRequest struct { - Tag *string `json:"tag,omitempty"` - Message *string `json:"message,omitempty"` - Object *string `json:"object,omitempty"` - Type *string `json:"type,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` -} - -// GetTag fetchs a tag from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#get-a-tag -func (s *GitService) GetTag(ctx context.Context, owner string, repo string, sha string) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - tag := new(Tag) - resp, err := s.client.Do(ctx, req, tag) - return tag, resp, err -} - -// CreateTag creates a tag object. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#create-a-tag-object -func (s *GitService) CreateTag(ctx context.Context, owner string, repo string, tag *Tag) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags", owner, repo) - - // convert Tag into a createTagRequest - tagRequest := &createTagRequest{ - Tag: tag.Tag, - Message: tag.Message, - Tagger: tag.Tagger, - } - if tag.Object != nil { - tagRequest.Object = tag.Object.SHA - tagRequest.Type = tag.Object.Type - } - - req, err := s.client.NewRequest("POST", u, tagRequest) - if err != nil { - return nil, nil, err - } - - t := new(Tag) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_trees.go b/vendor/github.com/google/go-github/github/git_trees.go deleted file mode 100644 index 4bc291354..000000000 --- a/vendor/github.com/google/go-github/github/git_trees.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Tree represents a GitHub tree. -type Tree struct { - SHA *string `json:"sha,omitempty"` - Entries []TreeEntry `json:"tree,omitempty"` - - // Truncated is true if the number of items in the tree - // exceeded GitHub's maximum limit and the Entries were truncated - // in the response. Only populated for requests that fetch - // trees like Git.GetTree. - Truncated *bool `json:"truncated,omitempty"` -} - -func (t Tree) String() string { - return Stringify(t) -} - -// TreeEntry represents the contents of a tree structure. TreeEntry can -// represent either a blob, a commit (in the case of a submodule), or another -// tree. -type TreeEntry struct { - SHA *string `json:"sha,omitempty"` - Path *string `json:"path,omitempty"` - Mode *string `json:"mode,omitempty"` - Type *string `json:"type,omitempty"` - Size *int `json:"size,omitempty"` - Content *string `json:"content,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (t TreeEntry) String() string { - return Stringify(t) -} - -// GetTree fetches the Tree object for a given sha hash from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#get-a-tree -func (s *GitService) GetTree(ctx context.Context, owner string, repo string, sha string, recursive bool) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees/%v", owner, repo, sha) - if recursive { - u += "?recursive=1" - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// createTree represents the body of a CreateTree request. -type createTree struct { - BaseTree string `json:"base_tree,omitempty"` - Entries []TreeEntry `json:"tree"` -} - -// CreateTree creates a new tree in a repository. If both a tree and a nested -// path modifying that tree are specified, it will overwrite the contents of -// that tree with the new path contents and write a new tree out. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#create-a-tree -func (s *GitService) CreateTree(ctx context.Context, owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees", owner, repo) - - body := &createTree{ - BaseTree: baseTree, - Entries: entries, - } - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/github-accessors.go b/vendor/github.com/google/go-github/github/github-accessors.go deleted file mode 100644 index 10ee831a8..000000000 --- a/vendor/github.com/google/go-github/github/github-accessors.go +++ /dev/null @@ -1,11981 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by gen-accessors; DO NOT EDIT. - -package github - -import ( - "encoding/json" - "time" -) - -// GetRetryAfter returns the RetryAfter field if it's non-nil, zero value otherwise. -func (a *AbuseRateLimitError) GetRetryAfter() time.Duration { - if a == nil || a.RetryAfter == nil { - return 0 - } - return *a.RetryAfter -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AdminEnforcement) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetComments returns the Comments field. -func (a *AdminStats) GetComments() *CommentStats { - if a == nil { - return nil - } - return a.Comments -} - -// GetGists returns the Gists field. -func (a *AdminStats) GetGists() *GistStats { - if a == nil { - return nil - } - return a.Gists -} - -// GetHooks returns the Hooks field. -func (a *AdminStats) GetHooks() *HookStats { - if a == nil { - return nil - } - return a.Hooks -} - -// GetIssues returns the Issues field. -func (a *AdminStats) GetIssues() *IssueStats { - if a == nil { - return nil - } - return a.Issues -} - -// GetMilestones returns the Milestones field. -func (a *AdminStats) GetMilestones() *MilestoneStats { - if a == nil { - return nil - } - return a.Milestones -} - -// GetOrgs returns the Orgs field. -func (a *AdminStats) GetOrgs() *OrgStats { - if a == nil { - return nil - } - return a.Orgs -} - -// GetPages returns the Pages field. -func (a *AdminStats) GetPages() *PageStats { - if a == nil { - return nil - } - return a.Pages -} - -// GetPulls returns the Pulls field. -func (a *AdminStats) GetPulls() *PullStats { - if a == nil { - return nil - } - return a.Pulls -} - -// GetRepos returns the Repos field. -func (a *AdminStats) GetRepos() *RepoStats { - if a == nil { - return nil - } - return a.Repos -} - -// GetUsers returns the Users field. -func (a *AdminStats) GetUsers() *UserStats { - if a == nil { - return nil - } - return a.Users -} - -// GetVerifiablePasswordAuthentication returns the VerifiablePasswordAuthentication field if it's non-nil, zero value otherwise. -func (a *APIMeta) GetVerifiablePasswordAuthentication() bool { - if a == nil || a.VerifiablePasswordAuthentication == nil { - return false - } - return *a.VerifiablePasswordAuthentication -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (a *App) GetCreatedAt() time.Time { - if a == nil || a.CreatedAt == nil { - return time.Time{} - } - return *a.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (a *App) GetDescription() string { - if a == nil || a.Description == nil { - return "" - } - return *a.Description -} - -// GetExternalURL returns the ExternalURL field if it's non-nil, zero value otherwise. -func (a *App) GetExternalURL() string { - if a == nil || a.ExternalURL == nil { - return "" - } - return *a.ExternalURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (a *App) GetHTMLURL() string { - if a == nil || a.HTMLURL == nil { - return "" - } - return *a.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (a *App) GetID() int64 { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (a *App) GetName() string { - if a == nil || a.Name == nil { - return "" - } - return *a.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (a *App) GetNodeID() string { - if a == nil || a.NodeID == nil { - return "" - } - return *a.NodeID -} - -// GetOwner returns the Owner field. -func (a *App) GetOwner() *User { - if a == nil { - return nil - } - return a.Owner -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (a *App) GetUpdatedAt() time.Time { - if a == nil || a.UpdatedAt == nil { - return time.Time{} - } - return *a.UpdatedAt -} - -// GetApp returns the App field. -func (a *Authorization) GetApp() *AuthorizationApp { - if a == nil { - return nil - } - return a.App -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetCreatedAt() Timestamp { - if a == nil || a.CreatedAt == nil { - return Timestamp{} - } - return *a.CreatedAt -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *Authorization) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetHashedToken returns the HashedToken field if it's non-nil, zero value otherwise. -func (a *Authorization) GetHashedToken() string { - if a == nil || a.HashedToken == nil { - return "" - } - return *a.HashedToken -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (a *Authorization) GetID() int64 { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetToken returns the Token field if it's non-nil, zero value otherwise. -func (a *Authorization) GetToken() string { - if a == nil || a.Token == nil { - return "" - } - return *a.Token -} - -// GetTokenLastEight returns the TokenLastEight field if it's non-nil, zero value otherwise. -func (a *Authorization) GetTokenLastEight() string { - if a == nil || a.TokenLastEight == nil { - return "" - } - return *a.TokenLastEight -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetUpdatedAt() Timestamp { - if a == nil || a.UpdatedAt == nil { - return Timestamp{} - } - return *a.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetUser returns the User field. -func (a *Authorization) GetUser() *User { - if a == nil { - return nil - } - return a.User -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetName() string { - if a == nil || a.Name == nil { - return "" - } - return *a.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetClientSecret returns the ClientSecret field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientSecret() string { - if a == nil || a.ClientSecret == nil { - return "" - } - return *a.ClientSecret -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetAppID returns the AppID field if it's non-nil, zero value otherwise. -func (a *AutoTriggerCheck) GetAppID() int64 { - if a == nil || a.AppID == nil { - return 0 - } - return *a.AppID -} - -// GetSetting returns the Setting field if it's non-nil, zero value otherwise. -func (a *AutoTriggerCheck) GetSetting() bool { - if a == nil || a.Setting == nil { - return false - } - return *a.Setting -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (b *Blob) GetContent() string { - if b == nil || b.Content == nil { - return "" - } - return *b.Content -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (b *Blob) GetEncoding() string { - if b == nil || b.Encoding == nil { - return "" - } - return *b.Encoding -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (b *Blob) GetNodeID() string { - if b == nil || b.NodeID == nil { - return "" - } - return *b.NodeID -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (b *Blob) GetSHA() string { - if b == nil || b.SHA == nil { - return "" - } - return *b.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (b *Blob) GetSize() int { - if b == nil || b.Size == nil { - return 0 - } - return *b.Size -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (b *Blob) GetURL() string { - if b == nil || b.URL == nil { - return "" - } - return *b.URL -} - -// GetCommit returns the Commit field. -func (b *Branch) GetCommit() *RepositoryCommit { - if b == nil { - return nil - } - return b.Commit -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (b *Branch) GetName() string { - if b == nil || b.Name == nil { - return "" - } - return *b.Name -} - -// GetProtected returns the Protected field if it's non-nil, zero value otherwise. -func (b *Branch) GetProtected() bool { - if b == nil || b.Protected == nil { - return false - } - return *b.Protected -} - -// GetApp returns the App field. -func (c *CheckRun) GetApp() *App { - if c == nil { - return nil - } - return c.App -} - -// GetCheckSuite returns the CheckSuite field. -func (c *CheckRun) GetCheckSuite() *CheckSuite { - if c == nil { - return nil - } - return c.CheckSuite -} - -// GetCompletedAt returns the CompletedAt field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetCompletedAt() Timestamp { - if c == nil || c.CompletedAt == nil { - return Timestamp{} - } - return *c.CompletedAt -} - -// GetConclusion returns the Conclusion field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetConclusion() string { - if c == nil || c.Conclusion == nil { - return "" - } - return *c.Conclusion -} - -// GetExternalID returns the ExternalID field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetExternalID() string { - if c == nil || c.ExternalID == nil { - return "" - } - return *c.ExternalID -} - -// GetHeadSHA returns the HeadSHA field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetHeadSHA() string { - if c == nil || c.HeadSHA == nil { - return "" - } - return *c.HeadSHA -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetID() int64 { - if c == nil || c.ID == nil { - return 0 - } - return *c.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetNodeID() string { - if c == nil || c.NodeID == nil { - return "" - } - return *c.NodeID -} - -// GetOutput returns the Output field. -func (c *CheckRun) GetOutput() *CheckRunOutput { - if c == nil { - return nil - } - return c.Output -} - -// GetStartedAt returns the StartedAt field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetStartedAt() Timestamp { - if c == nil || c.StartedAt == nil { - return Timestamp{} - } - return *c.StartedAt -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CheckRun) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAnnotationLevel returns the AnnotationLevel field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetAnnotationLevel() string { - if c == nil || c.AnnotationLevel == nil { - return "" - } - return *c.AnnotationLevel -} - -// GetBlobHRef returns the BlobHRef field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetBlobHRef() string { - if c == nil || c.BlobHRef == nil { - return "" - } - return *c.BlobHRef -} - -// GetEndLine returns the EndLine field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetEndLine() int { - if c == nil || c.EndLine == nil { - return 0 - } - return *c.EndLine -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetPath() string { - if c == nil || c.Path == nil { - return "" - } - return *c.Path -} - -// GetRawDetails returns the RawDetails field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetRawDetails() string { - if c == nil || c.RawDetails == nil { - return "" - } - return *c.RawDetails -} - -// GetStartLine returns the StartLine field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetStartLine() int { - if c == nil || c.StartLine == nil { - return 0 - } - return *c.StartLine -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (c *CheckRunAnnotation) GetTitle() string { - if c == nil || c.Title == nil { - return "" - } - return *c.Title -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (c *CheckRunEvent) GetAction() string { - if c == nil || c.Action == nil { - return "" - } - return *c.Action -} - -// GetCheckRun returns the CheckRun field. -func (c *CheckRunEvent) GetCheckRun() *CheckRun { - if c == nil { - return nil - } - return c.CheckRun -} - -// GetInstallation returns the Installation field. -func (c *CheckRunEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetOrg returns the Org field. -func (c *CheckRunEvent) GetOrg() *Organization { - if c == nil { - return nil - } - return c.Org -} - -// GetRepo returns the Repo field. -func (c *CheckRunEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CheckRunEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetAlt returns the Alt field if it's non-nil, zero value otherwise. -func (c *CheckRunImage) GetAlt() string { - if c == nil || c.Alt == nil { - return "" - } - return *c.Alt -} - -// GetCaption returns the Caption field if it's non-nil, zero value otherwise. -func (c *CheckRunImage) GetCaption() string { - if c == nil || c.Caption == nil { - return "" - } - return *c.Caption -} - -// GetImageURL returns the ImageURL field if it's non-nil, zero value otherwise. -func (c *CheckRunImage) GetImageURL() string { - if c == nil || c.ImageURL == nil { - return "" - } - return *c.ImageURL -} - -// GetAnnotationsCount returns the AnnotationsCount field if it's non-nil, zero value otherwise. -func (c *CheckRunOutput) GetAnnotationsCount() int { - if c == nil || c.AnnotationsCount == nil { - return 0 - } - return *c.AnnotationsCount -} - -// GetAnnotationsURL returns the AnnotationsURL field if it's non-nil, zero value otherwise. -func (c *CheckRunOutput) GetAnnotationsURL() string { - if c == nil || c.AnnotationsURL == nil { - return "" - } - return *c.AnnotationsURL -} - -// GetSummary returns the Summary field if it's non-nil, zero value otherwise. -func (c *CheckRunOutput) GetSummary() string { - if c == nil || c.Summary == nil { - return "" - } - return *c.Summary -} - -// GetText returns the Text field if it's non-nil, zero value otherwise. -func (c *CheckRunOutput) GetText() string { - if c == nil || c.Text == nil { - return "" - } - return *c.Text -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (c *CheckRunOutput) GetTitle() string { - if c == nil || c.Title == nil { - return "" - } - return *c.Title -} - -// GetAfterSHA returns the AfterSHA field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetAfterSHA() string { - if c == nil || c.AfterSHA == nil { - return "" - } - return *c.AfterSHA -} - -// GetApp returns the App field. -func (c *CheckSuite) GetApp() *App { - if c == nil { - return nil - } - return c.App -} - -// GetBeforeSHA returns the BeforeSHA field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetBeforeSHA() string { - if c == nil || c.BeforeSHA == nil { - return "" - } - return *c.BeforeSHA -} - -// GetConclusion returns the Conclusion field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetConclusion() string { - if c == nil || c.Conclusion == nil { - return "" - } - return *c.Conclusion -} - -// GetHeadBranch returns the HeadBranch field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetHeadBranch() string { - if c == nil || c.HeadBranch == nil { - return "" - } - return *c.HeadBranch -} - -// GetHeadSHA returns the HeadSHA field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetHeadSHA() string { - if c == nil || c.HeadSHA == nil { - return "" - } - return *c.HeadSHA -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetID() int64 { - if c == nil || c.ID == nil { - return 0 - } - return *c.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetNodeID() string { - if c == nil || c.NodeID == nil { - return "" - } - return *c.NodeID -} - -// GetRepository returns the Repository field. -func (c *CheckSuite) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CheckSuite) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (c *CheckSuiteEvent) GetAction() string { - if c == nil || c.Action == nil { - return "" - } - return *c.Action -} - -// GetCheckSuite returns the CheckSuite field. -func (c *CheckSuiteEvent) GetCheckSuite() *CheckSuite { - if c == nil { - return nil - } - return c.CheckSuite -} - -// GetInstallation returns the Installation field. -func (c *CheckSuiteEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetOrg returns the Org field. -func (c *CheckSuiteEvent) GetOrg() *Organization { - if c == nil { - return nil - } - return c.Org -} - -// GetRepo returns the Repo field. -func (c *CheckSuiteEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CheckSuiteEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetPreferenceList returns the PreferenceList field. -func (c *CheckSuitePreferenceOptions) GetPreferenceList() *PreferenceList { - if c == nil { - return nil - } - return c.PreferenceList -} - -// GetPreferences returns the Preferences field. -func (c *CheckSuitePreferenceResults) GetPreferences() *PreferenceList { - if c == nil { - return nil - } - return c.Preferences -} - -// GetRepository returns the Repository field. -func (c *CheckSuitePreferenceResults) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetBody() string { - if c == nil || c.Body == nil { - return "" - } - return *c.Body -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetKey() string { - if c == nil || c.Key == nil { - return "" - } - return *c.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetPath() string { - if c == nil || c.Path == nil { - return "" - } - return *c.Path -} - -// GetRepository returns the Repository field. -func (c *CodeResult) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetCommitURL() string { - if c == nil || c.CommitURL == nil { - return "" - } - return *c.CommitURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetRepositoryURL() string { - if c == nil || c.RepositoryURL == nil { - return "" - } - return *c.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetState() string { - if c == nil || c.State == nil { - return "" - } - return *c.State -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetTotalCount() int { - if c == nil || c.TotalCount == nil { - return 0 - } - return *c.TotalCount -} - -// GetTotalCommitComments returns the TotalCommitComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalCommitComments() int { - if c == nil || c.TotalCommitComments == nil { - return 0 - } - return *c.TotalCommitComments -} - -// GetTotalGistComments returns the TotalGistComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalGistComments() int { - if c == nil || c.TotalGistComments == nil { - return 0 - } - return *c.TotalGistComments -} - -// GetTotalIssueComments returns the TotalIssueComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalIssueComments() int { - if c == nil || c.TotalIssueComments == nil { - return 0 - } - return *c.TotalIssueComments -} - -// GetTotalPullRequestComments returns the TotalPullRequestComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalPullRequestComments() int { - if c == nil || c.TotalPullRequestComments == nil { - return 0 - } - return *c.TotalPullRequestComments -} - -// GetAuthor returns the Author field. -func (c *Commit) GetAuthor() *CommitAuthor { - if c == nil { - return nil - } - return c.Author -} - -// GetCommentCount returns the CommentCount field if it's non-nil, zero value otherwise. -func (c *Commit) GetCommentCount() int { - if c == nil || c.CommentCount == nil { - return 0 - } - return *c.CommentCount -} - -// GetCommitter returns the Committer field. -func (c *Commit) GetCommitter() *CommitAuthor { - if c == nil { - return nil - } - return c.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Commit) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *Commit) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (c *Commit) GetNodeID() string { - if c == nil || c.NodeID == nil { - return "" - } - return *c.NodeID -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *Commit) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetStats returns the Stats field. -func (c *Commit) GetStats() *CommitStats { - if c == nil { - return nil - } - return c.Stats -} - -// GetTree returns the Tree field. -func (c *Commit) GetTree() *Tree { - if c == nil { - return nil - } - return c.Tree -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Commit) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetVerification returns the Verification field. -func (c *Commit) GetVerification() *SignatureVerification { - if c == nil { - return nil - } - return c.Verification -} - -// GetDate returns the Date field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetDate() time.Time { - if c == nil || c.Date == nil { - return time.Time{} - } - return *c.Date -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetEmail() string { - if c == nil || c.Email == nil { - return "" - } - return *c.Email -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (c *CommitCommentEvent) GetAction() string { - if c == nil || c.Action == nil { - return "" - } - return *c.Action -} - -// GetComment returns the Comment field. -func (c *CommitCommentEvent) GetComment() *RepositoryComment { - if c == nil { - return nil - } - return c.Comment -} - -// GetInstallation returns the Installation field. -func (c *CommitCommentEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetRepo returns the Repo field. -func (c *CommitCommentEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CommitCommentEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetBlobURL returns the BlobURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetBlobURL() string { - if c == nil || c.BlobURL == nil { - return "" - } - return *c.BlobURL -} - -// GetChanges returns the Changes field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetChanges() int { - if c == nil || c.Changes == nil { - return 0 - } - return *c.Changes -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetContentsURL() string { - if c == nil || c.ContentsURL == nil { - return "" - } - return *c.ContentsURL -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetFilename() string { - if c == nil || c.Filename == nil { - return "" - } - return *c.Filename -} - -// GetPatch returns the Patch field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetPatch() string { - if c == nil || c.Patch == nil { - return "" - } - return *c.Patch -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetRawURL() string { - if c == nil || c.RawURL == nil { - return "" - } - return *c.RawURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetAuthor returns the Author field. -func (c *CommitResult) GetAuthor() *User { - if c == nil { - return nil - } - return c.Author -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetCommentsURL() string { - if c == nil || c.CommentsURL == nil { - return "" - } - return *c.CommentsURL -} - -// GetCommit returns the Commit field. -func (c *CommitResult) GetCommit() *Commit { - if c == nil { - return nil - } - return c.Commit -} - -// GetCommitter returns the Committer field. -func (c *CommitResult) GetCommitter() *User { - if c == nil { - return nil - } - return c.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetRepository returns the Repository field. -func (c *CommitResult) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetScore returns the Score field. -func (c *CommitResult) GetScore() *float64 { - if c == nil { - return nil - } - return c.Score -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAheadBy returns the AheadBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetAheadBy() int { - if c == nil || c.AheadBy == nil { - return 0 - } - return *c.AheadBy -} - -// GetBaseCommit returns the BaseCommit field. -func (c *CommitsComparison) GetBaseCommit() *RepositoryCommit { - if c == nil { - return nil - } - return c.BaseCommit -} - -// GetBehindBy returns the BehindBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetBehindBy() int { - if c == nil || c.BehindBy == nil { - return 0 - } - return *c.BehindBy -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetDiffURL() string { - if c == nil || c.DiffURL == nil { - return "" - } - return *c.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetMergeBaseCommit returns the MergeBaseCommit field. -func (c *CommitsComparison) GetMergeBaseCommit() *RepositoryCommit { - if c == nil { - return nil - } - return c.MergeBaseCommit -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPatchURL() string { - if c == nil || c.PatchURL == nil { - return "" - } - return *c.PatchURL -} - -// GetPermalinkURL returns the PermalinkURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPermalinkURL() string { - if c == nil || c.PermalinkURL == nil { - return "" - } - return *c.PermalinkURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetTotalCommits returns the TotalCommits field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetTotalCommits() int { - if c == nil || c.TotalCommits == nil { - return 0 - } - return *c.TotalCommits -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCodeOfConduct returns the CodeOfConduct field. -func (c *CommunityHealthFiles) GetCodeOfConduct() *Metric { - if c == nil { - return nil - } - return c.CodeOfConduct -} - -// GetContributing returns the Contributing field. -func (c *CommunityHealthFiles) GetContributing() *Metric { - if c == nil { - return nil - } - return c.Contributing -} - -// GetIssueTemplate returns the IssueTemplate field. -func (c *CommunityHealthFiles) GetIssueTemplate() *Metric { - if c == nil { - return nil - } - return c.IssueTemplate -} - -// GetLicense returns the License field. -func (c *CommunityHealthFiles) GetLicense() *Metric { - if c == nil { - return nil - } - return c.License -} - -// GetPullRequestTemplate returns the PullRequestTemplate field. -func (c *CommunityHealthFiles) GetPullRequestTemplate() *Metric { - if c == nil { - return nil - } - return c.PullRequestTemplate -} - -// GetReadme returns the Readme field. -func (c *CommunityHealthFiles) GetReadme() *Metric { - if c == nil { - return nil - } - return c.Readme -} - -// GetFiles returns the Files field. -func (c *CommunityHealthMetrics) GetFiles() *CommunityHealthFiles { - if c == nil { - return nil - } - return c.Files -} - -// GetHealthPercentage returns the HealthPercentage field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetHealthPercentage() int { - if c == nil || c.HealthPercentage == nil { - return 0 - } - return *c.HealthPercentage -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetUpdatedAt() time.Time { - if c == nil || c.UpdatedAt == nil { - return time.Time{} - } - return *c.UpdatedAt -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetAvatarURL() string { - if c == nil || c.AvatarURL == nil { - return "" - } - return *c.AvatarURL -} - -// GetContributions returns the Contributions field if it's non-nil, zero value otherwise. -func (c *Contributor) GetContributions() int { - if c == nil || c.Contributions == nil { - return 0 - } - return *c.Contributions -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetEventsURL() string { - if c == nil || c.EventsURL == nil { - return "" - } - return *c.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowersURL() string { - if c == nil || c.FollowersURL == nil { - return "" - } - return *c.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowingURL() string { - if c == nil || c.FollowingURL == nil { - return "" - } - return *c.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGistsURL() string { - if c == nil || c.GistsURL == nil { - return "" - } - return *c.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGravatarID() string { - if c == nil || c.GravatarID == nil { - return "" - } - return *c.GravatarID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetID() int64 { - if c == nil || c.ID == nil { - return 0 - } - return *c.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *Contributor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetOrganizationsURL() string { - if c == nil || c.OrganizationsURL == nil { - return "" - } - return *c.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReceivedEventsURL() string { - if c == nil || c.ReceivedEventsURL == nil { - return "" - } - return *c.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReposURL() string { - if c == nil || c.ReposURL == nil { - return "" - } - return *c.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSiteAdmin() bool { - if c == nil || c.SiteAdmin == nil { - return false - } - return *c.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetStarredURL() string { - if c == nil || c.StarredURL == nil { - return "" - } - return *c.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSubscriptionsURL() string { - if c == nil || c.SubscriptionsURL == nil { - return "" - } - return *c.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (c *Contributor) GetType() string { - if c == nil || c.Type == nil { - return "" - } - return *c.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAuthor returns the Author field. -func (c *ContributorStats) GetAuthor() *Contributor { - if c == nil { - return nil - } - return c.Author -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *ContributorStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCompletedAt returns the CompletedAt field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetCompletedAt() Timestamp { - if c == nil || c.CompletedAt == nil { - return Timestamp{} - } - return *c.CompletedAt -} - -// GetConclusion returns the Conclusion field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetConclusion() string { - if c == nil || c.Conclusion == nil { - return "" - } - return *c.Conclusion -} - -// GetDetailsURL returns the DetailsURL field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetDetailsURL() string { - if c == nil || c.DetailsURL == nil { - return "" - } - return *c.DetailsURL -} - -// GetExternalID returns the ExternalID field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetExternalID() string { - if c == nil || c.ExternalID == nil { - return "" - } - return *c.ExternalID -} - -// GetOutput returns the Output field. -func (c *CreateCheckRunOptions) GetOutput() *CheckRunOutput { - if c == nil { - return nil - } - return c.Output -} - -// GetStartedAt returns the StartedAt field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetStartedAt() Timestamp { - if c == nil || c.StartedAt == nil { - return Timestamp{} - } - return *c.StartedAt -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CreateCheckRunOptions) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetHeadBranch returns the HeadBranch field if it's non-nil, zero value otherwise. -func (c *CreateCheckSuiteOptions) GetHeadBranch() string { - if c == nil || c.HeadBranch == nil { - return "" - } - return *c.HeadBranch -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetDescription() string { - if c == nil || c.Description == nil { - return "" - } - return *c.Description -} - -// GetInstallation returns the Installation field. -func (c *CreateEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetMasterBranch() string { - if c == nil || c.MasterBranch == nil { - return "" - } - return *c.MasterBranch -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetPusherType() string { - if c == nil || c.PusherType == nil { - return "" - } - return *c.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRef() string { - if c == nil || c.Ref == nil { - return "" - } - return *c.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRefType() string { - if c == nil || c.RefType == nil { - return "" - } - return *c.RefType -} - -// GetRepo returns the Repo field. -func (c *CreateEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CreateEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (c *CreateOrgInvitationOptions) GetEmail() string { - if c == nil || c.Email == nil { - return "" - } - return *c.Email -} - -// GetInviteeID returns the InviteeID field if it's non-nil, zero value otherwise. -func (c *CreateOrgInvitationOptions) GetInviteeID() int64 { - if c == nil || c.InviteeID == nil { - return 0 - } - return *c.InviteeID -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (c *CreateOrgInvitationOptions) GetRole() string { - if c == nil || c.Role == nil { - return "" - } - return *c.Role -} - -// GetInstallation returns the Installation field. -func (d *DeleteEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetPusherType() string { - if d == nil || d.PusherType == nil { - return "" - } - return *d.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRefType() string { - if d == nil || d.RefType == nil { - return "" - } - return *d.RefType -} - -// GetRepo returns the Repo field. -func (d *DeleteEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeleteEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetCreator returns the Creator field. -func (d *Deployment) GetCreator() *User { - if d == nil { - return nil - } - return d.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *Deployment) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *Deployment) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *Deployment) GetID() int64 { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (d *Deployment) GetNodeID() string { - if d == nil || d.NodeID == nil { - return "" - } - return *d.NodeID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (d *Deployment) GetSHA() string { - if d == nil || d.SHA == nil { - return "" - } - return *d.SHA -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetStatusesURL() string { - if d == nil || d.StatusesURL == nil { - return "" - } - return *d.StatusesURL -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *Deployment) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetURL() string { - if d == nil || d.URL == nil { - return "" - } - return *d.URL -} - -// GetDeployment returns the Deployment field. -func (d *DeploymentEvent) GetDeployment() *Deployment { - if d == nil { - return nil - } - return d.Deployment -} - -// GetInstallation returns the Installation field. -func (d *DeploymentEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetRepo returns the Repo field. -func (d *DeploymentEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeploymentEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetAutoMerge returns the AutoMerge field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetAutoMerge() bool { - if d == nil || d.AutoMerge == nil { - return false - } - return *d.AutoMerge -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetPayload() string { - if d == nil || d.Payload == nil { - return "" - } - return *d.Payload -} - -// GetProductionEnvironment returns the ProductionEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetProductionEnvironment() bool { - if d == nil || d.ProductionEnvironment == nil { - return false - } - return *d.ProductionEnvironment -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRequiredContexts returns the RequiredContexts field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRequiredContexts() []string { - if d == nil || d.RequiredContexts == nil { - return nil - } - return *d.RequiredContexts -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetTransientEnvironment returns the TransientEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTransientEnvironment() bool { - if d == nil || d.TransientEnvironment == nil { - return false - } - return *d.TransientEnvironment -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetCreator returns the Creator field. -func (d *DeploymentStatus) GetCreator() *User { - if d == nil { - return nil - } - return d.Creator -} - -// GetDeploymentURL returns the DeploymentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDeploymentURL() string { - if d == nil || d.DeploymentURL == nil { - return "" - } - return *d.DeploymentURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetID() int64 { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetNodeID() string { - if d == nil || d.NodeID == nil { - return "" - } - return *d.NodeID -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetTargetURL() string { - if d == nil || d.TargetURL == nil { - return "" - } - return *d.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetDeployment returns the Deployment field. -func (d *DeploymentStatusEvent) GetDeployment() *Deployment { - if d == nil { - return nil - } - return d.Deployment -} - -// GetDeploymentStatus returns the DeploymentStatus field. -func (d *DeploymentStatusEvent) GetDeploymentStatus() *DeploymentStatus { - if d == nil { - return nil - } - return d.DeploymentStatus -} - -// GetInstallation returns the Installation field. -func (d *DeploymentStatusEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetRepo returns the Repo field. -func (d *DeploymentStatusEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeploymentStatusEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetAutoInactive returns the AutoInactive field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetAutoInactive() bool { - if d == nil || d.AutoInactive == nil { - return false - } - return *d.AutoInactive -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironmentURL returns the EnvironmentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetEnvironmentURL() string { - if d == nil || d.EnvironmentURL == nil { - return "" - } - return *d.EnvironmentURL -} - -// GetLogURL returns the LogURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetLogURL() string { - if d == nil || d.LogURL == nil { - return "" - } - return *d.LogURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetAuthor returns the Author field. -func (d *DiscussionComment) GetAuthor() *User { - if d == nil { - return nil - } - return d.Author -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetBody() string { - if d == nil || d.Body == nil { - return "" - } - return *d.Body -} - -// GetBodyHTML returns the BodyHTML field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetBodyHTML() string { - if d == nil || d.BodyHTML == nil { - return "" - } - return *d.BodyHTML -} - -// GetBodyVersion returns the BodyVersion field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetBodyVersion() string { - if d == nil || d.BodyVersion == nil { - return "" - } - return *d.BodyVersion -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetDiscussionURL returns the DiscussionURL field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetDiscussionURL() string { - if d == nil || d.DiscussionURL == nil { - return "" - } - return *d.DiscussionURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetHTMLURL() string { - if d == nil || d.HTMLURL == nil { - return "" - } - return *d.HTMLURL -} - -// GetLastEditedAt returns the LastEditedAt field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetLastEditedAt() Timestamp { - if d == nil || d.LastEditedAt == nil { - return Timestamp{} - } - return *d.LastEditedAt -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetNodeID() string { - if d == nil || d.NodeID == nil { - return "" - } - return *d.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetNumber() int { - if d == nil || d.Number == nil { - return 0 - } - return *d.Number -} - -// GetReactions returns the Reactions field. -func (d *DiscussionComment) GetReactions() *Reactions { - if d == nil { - return nil - } - return d.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (d *DiscussionComment) GetURL() string { - if d == nil || d.URL == nil { - return "" - } - return *d.URL -} - -// GetTeams returns the Teams field if it's non-nil, zero value otherwise. -func (d *DismissalRestrictionsRequest) GetTeams() []string { - if d == nil || d.Teams == nil { - return nil - } - return *d.Teams -} - -// GetUsers returns the Users field if it's non-nil, zero value otherwise. -func (d *DismissalRestrictionsRequest) GetUsers() []string { - if d == nil || d.Users == nil { - return nil - } - return *d.Users -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetBody() string { - if d == nil || d.Body == nil { - return "" - } - return *d.Body -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPath() string { - if d == nil || d.Path == nil { - return "" - } - return *d.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPosition() int { - if d == nil || d.Position == nil { - return 0 - } - return *d.Position -} - -// GetActor returns the Actor field. -func (e *Event) GetActor() *User { - if e == nil { - return nil - } - return e.Actor -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (e *Event) GetCreatedAt() time.Time { - if e == nil || e.CreatedAt == nil { - return time.Time{} - } - return *e.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (e *Event) GetID() string { - if e == nil || e.ID == nil { - return "" - } - return *e.ID -} - -// GetOrg returns the Org field. -func (e *Event) GetOrg() *Organization { - if e == nil { - return nil - } - return e.Org -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (e *Event) GetPublic() bool { - if e == nil || e.Public == nil { - return false - } - return *e.Public -} - -// GetRawPayload returns the RawPayload field if it's non-nil, zero value otherwise. -func (e *Event) GetRawPayload() json.RawMessage { - if e == nil || e.RawPayload == nil { - return json.RawMessage{} - } - return *e.RawPayload -} - -// GetRepo returns the Repo field. -func (e *Event) GetRepo() *Repository { - if e == nil { - return nil - } - return e.Repo -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (e *Event) GetType() string { - if e == nil || e.Type == nil { - return "" - } - return *e.Type -} - -// GetHRef returns the HRef field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetHRef() string { - if f == nil || f.HRef == nil { - return "" - } - return *f.HRef -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetType() string { - if f == nil || f.Type == nil { - return "" - } - return *f.Type -} - -// GetCurrentUserActorURL returns the CurrentUserActorURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserActorURL() string { - if f == nil || f.CurrentUserActorURL == nil { - return "" - } - return *f.CurrentUserActorURL -} - -// GetCurrentUserOrganizationURL returns the CurrentUserOrganizationURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserOrganizationURL() string { - if f == nil || f.CurrentUserOrganizationURL == nil { - return "" - } - return *f.CurrentUserOrganizationURL -} - -// GetCurrentUserPublicURL returns the CurrentUserPublicURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserPublicURL() string { - if f == nil || f.CurrentUserPublicURL == nil { - return "" - } - return *f.CurrentUserPublicURL -} - -// GetCurrentUserURL returns the CurrentUserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserURL() string { - if f == nil || f.CurrentUserURL == nil { - return "" - } - return *f.CurrentUserURL -} - -// GetTimelineURL returns the TimelineURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetTimelineURL() string { - if f == nil || f.TimelineURL == nil { - return "" - } - return *f.TimelineURL -} - -// GetUserURL returns the UserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetUserURL() string { - if f == nil || f.UserURL == nil { - return "" - } - return *f.UserURL -} - -// GetForkee returns the Forkee field. -func (f *ForkEvent) GetForkee() *Repository { - if f == nil { - return nil - } - return f.Forkee -} - -// GetInstallation returns the Installation field. -func (f *ForkEvent) GetInstallation() *Installation { - if f == nil { - return nil - } - return f.Installation -} - -// GetRepo returns the Repo field. -func (f *ForkEvent) GetRepo() *Repository { - if f == nil { - return nil - } - return f.Repo -} - -// GetSender returns the Sender field. -func (f *ForkEvent) GetSender() *User { - if f == nil { - return nil - } - return f.Sender -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (g *Gist) GetComments() int { - if g == nil || g.Comments == nil { - return 0 - } - return *g.Comments -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (g *Gist) GetDescription() string { - if g == nil || g.Description == nil { - return "" - } - return *g.Description -} - -// GetGitPullURL returns the GitPullURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPullURL() string { - if g == nil || g.GitPullURL == nil { - return "" - } - return *g.GitPullURL -} - -// GetGitPushURL returns the GitPushURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPushURL() string { - if g == nil || g.GitPushURL == nil { - return "" - } - return *g.GitPushURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetHTMLURL() string { - if g == nil || g.HTMLURL == nil { - return "" - } - return *g.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Gist) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *Gist) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetOwner returns the Owner field. -func (g *Gist) GetOwner() *User { - if g == nil { - return nil - } - return g.Owner -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (g *Gist) GetPublic() bool { - if g == nil || g.Public == nil { - return false - } - return *g.Public -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetUpdatedAt() time.Time { - if g == nil || g.UpdatedAt == nil { - return time.Time{} - } - return *g.UpdatedAt -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (g *GistComment) GetBody() string { - if g == nil || g.Body == nil { - return "" - } - return *g.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistComment) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistComment) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistComment) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistComment) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetChangeStatus returns the ChangeStatus field. -func (g *GistCommit) GetChangeStatus() *CommitStats { - if g == nil { - return nil - } - return g.ChangeStatus -} - -// GetCommittedAt returns the CommittedAt field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetCommittedAt() Timestamp { - if g == nil || g.CommittedAt == nil { - return Timestamp{} - } - return *g.CommittedAt -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistCommit) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetVersion returns the Version field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetVersion() string { - if g == nil || g.Version == nil { - return "" - } - return *g.Version -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (g *GistFile) GetContent() string { - if g == nil || g.Content == nil { - return "" - } - return *g.Content -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (g *GistFile) GetFilename() string { - if g == nil || g.Filename == nil { - return "" - } - return *g.Filename -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (g *GistFile) GetLanguage() string { - if g == nil || g.Language == nil { - return "" - } - return *g.Language -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (g *GistFile) GetRawURL() string { - if g == nil || g.RawURL == nil { - return "" - } - return *g.RawURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (g *GistFile) GetSize() int { - if g == nil || g.Size == nil { - return 0 - } - return *g.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GistFile) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistFork) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *GistFork) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistFork) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistFork) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetPrivateGists() int { - if g == nil || g.PrivateGists == nil { - return 0 - } - return *g.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetPublicGists() int { - if g == nil || g.PublicGists == nil { - return 0 - } - return *g.PublicGists -} - -// GetTotalGists returns the TotalGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetTotalGists() int { - if g == nil || g.TotalGists == nil { - return 0 - } - return *g.TotalGists -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetName() string { - if g == nil || g.Name == nil { - return "" - } - return *g.Name -} - -// GetSource returns the Source field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetSource() string { - if g == nil || g.Source == nil { - return "" - } - return *g.Source -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (g *GitObject) GetSHA() string { - if g == nil || g.SHA == nil { - return "" - } - return *g.SHA -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GitObject) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GitObject) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetInstallation returns the Installation field. -func (g *GollumEvent) GetInstallation() *Installation { - if g == nil { - return nil - } - return g.Installation -} - -// GetRepo returns the Repo field. -func (g *GollumEvent) GetRepo() *Repository { - if g == nil { - return nil - } - return g.Repo -} - -// GetSender returns the Sender field. -func (g *GollumEvent) GetSender() *User { - if g == nil { - return nil - } - return g.Sender -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetEmail() string { - if g == nil || g.Email == nil { - return "" - } - return *g.Email -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetVerified() bool { - if g == nil || g.Verified == nil { - return false - } - return *g.Verified -} - -// GetCanCertify returns the CanCertify field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanCertify() bool { - if g == nil || g.CanCertify == nil { - return false - } - return *g.CanCertify -} - -// GetCanEncryptComms returns the CanEncryptComms field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptComms() bool { - if g == nil || g.CanEncryptComms == nil { - return false - } - return *g.CanEncryptComms -} - -// GetCanEncryptStorage returns the CanEncryptStorage field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptStorage() bool { - if g == nil || g.CanEncryptStorage == nil { - return false - } - return *g.CanEncryptStorage -} - -// GetCanSign returns the CanSign field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanSign() bool { - if g == nil || g.CanSign == nil { - return false - } - return *g.CanSign -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetExpiresAt returns the ExpiresAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetExpiresAt() time.Time { - if g == nil || g.ExpiresAt == nil { - return time.Time{} - } - return *g.ExpiresAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetKeyID returns the KeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetKeyID() string { - if g == nil || g.KeyID == nil { - return "" - } - return *g.KeyID -} - -// GetPrimaryKeyID returns the PrimaryKeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPrimaryKeyID() int64 { - if g == nil || g.PrimaryKeyID == nil { - return 0 - } - return *g.PrimaryKeyID -} - -// GetPublicKey returns the PublicKey field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPublicKey() string { - if g == nil || g.PublicKey == nil { - return "" - } - return *g.PublicKey -} - -// GetApp returns the App field. -func (g *Grant) GetApp() *AuthorizationApp { - if g == nil { - return nil - } - return g.App -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Grant) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *Grant) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetActive returns the Active field if it's non-nil, zero value otherwise. -func (h *Hook) GetActive() bool { - if h == nil || h.Active == nil { - return false - } - return *h.Active -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetCreatedAt() time.Time { - if h == nil || h.CreatedAt == nil { - return time.Time{} - } - return *h.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (h *Hook) GetID() int64 { - if h == nil || h.ID == nil { - return 0 - } - return *h.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (h *Hook) GetName() string { - if h == nil || h.Name == nil { - return "" - } - return *h.Name -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetUpdatedAt() time.Time { - if h == nil || h.UpdatedAt == nil { - return time.Time{} - } - return *h.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (h *Hook) GetURL() string { - if h == nil || h.URL == nil { - return "" - } - return *h.URL -} - -// GetActiveHooks returns the ActiveHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetActiveHooks() int { - if h == nil || h.ActiveHooks == nil { - return 0 - } - return *h.ActiveHooks -} - -// GetInactiveHooks returns the InactiveHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetInactiveHooks() int { - if h == nil || h.InactiveHooks == nil { - return 0 - } - return *h.InactiveHooks -} - -// GetTotalHooks returns the TotalHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetTotalHooks() int { - if h == nil || h.TotalHooks == nil { - return 0 - } - return *h.TotalHooks -} - -// GetAuthorsCount returns the AuthorsCount field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsCount() int { - if i == nil || i.AuthorsCount == nil { - return 0 - } - return *i.AuthorsCount -} - -// GetAuthorsURL returns the AuthorsURL field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsURL() string { - if i == nil || i.AuthorsURL == nil { - return "" - } - return *i.AuthorsURL -} - -// GetCommitCount returns the CommitCount field if it's non-nil, zero value otherwise. -func (i *Import) GetCommitCount() int { - if i == nil || i.CommitCount == nil { - return 0 - } - return *i.CommitCount -} - -// GetFailedStep returns the FailedStep field if it's non-nil, zero value otherwise. -func (i *Import) GetFailedStep() string { - if i == nil || i.FailedStep == nil { - return "" - } - return *i.FailedStep -} - -// GetHasLargeFiles returns the HasLargeFiles field if it's non-nil, zero value otherwise. -func (i *Import) GetHasLargeFiles() bool { - if i == nil || i.HasLargeFiles == nil { - return false - } - return *i.HasLargeFiles -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Import) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetHumanName returns the HumanName field if it's non-nil, zero value otherwise. -func (i *Import) GetHumanName() string { - if i == nil || i.HumanName == nil { - return "" - } - return *i.HumanName -} - -// GetLargeFilesCount returns the LargeFilesCount field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesCount() int { - if i == nil || i.LargeFilesCount == nil { - return 0 - } - return *i.LargeFilesCount -} - -// GetLargeFilesSize returns the LargeFilesSize field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesSize() int { - if i == nil || i.LargeFilesSize == nil { - return 0 - } - return *i.LargeFilesSize -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (i *Import) GetMessage() string { - if i == nil || i.Message == nil { - return "" - } - return *i.Message -} - -// GetPercent returns the Percent field if it's non-nil, zero value otherwise. -func (i *Import) GetPercent() int { - if i == nil || i.Percent == nil { - return 0 - } - return *i.Percent -} - -// GetPushPercent returns the PushPercent field if it's non-nil, zero value otherwise. -func (i *Import) GetPushPercent() int { - if i == nil || i.PushPercent == nil { - return 0 - } - return *i.PushPercent -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (i *Import) GetRepositoryURL() string { - if i == nil || i.RepositoryURL == nil { - return "" - } - return *i.RepositoryURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (i *Import) GetStatus() string { - if i == nil || i.Status == nil { - return "" - } - return *i.Status -} - -// GetStatusText returns the StatusText field if it's non-nil, zero value otherwise. -func (i *Import) GetStatusText() string { - if i == nil || i.StatusText == nil { - return "" - } - return *i.StatusText -} - -// GetTFVCProject returns the TFVCProject field if it's non-nil, zero value otherwise. -func (i *Import) GetTFVCProject() string { - if i == nil || i.TFVCProject == nil { - return "" - } - return *i.TFVCProject -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Import) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUseLFS returns the UseLFS field if it's non-nil, zero value otherwise. -func (i *Import) GetUseLFS() string { - if i == nil || i.UseLFS == nil { - return "" - } - return *i.UseLFS -} - -// GetVCS returns the VCS field if it's non-nil, zero value otherwise. -func (i *Import) GetVCS() string { - if i == nil || i.VCS == nil { - return "" - } - return *i.VCS -} - -// GetVCSPassword returns the VCSPassword field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSPassword() string { - if i == nil || i.VCSPassword == nil { - return "" - } - return *i.VCSPassword -} - -// GetVCSURL returns the VCSURL field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSURL() string { - if i == nil || i.VCSURL == nil { - return "" - } - return *i.VCSURL -} - -// GetVCSUsername returns the VCSUsername field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSUsername() string { - if i == nil || i.VCSUsername == nil { - return "" - } - return *i.VCSUsername -} - -// GetAccessTokensURL returns the AccessTokensURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetAccessTokensURL() string { - if i == nil || i.AccessTokensURL == nil { - return "" - } - return *i.AccessTokensURL -} - -// GetAccount returns the Account field. -func (i *Installation) GetAccount() *User { - if i == nil { - return nil - } - return i.Account -} - -// GetAppID returns the AppID field if it's non-nil, zero value otherwise. -func (i *Installation) GetAppID() int64 { - if i == nil || i.AppID == nil { - return 0 - } - return *i.AppID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Installation) GetCreatedAt() Timestamp { - if i == nil || i.CreatedAt == nil { - return Timestamp{} - } - return *i.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Installation) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetPermissions returns the Permissions field. -func (i *Installation) GetPermissions() *InstallationPermissions { - if i == nil { - return nil - } - return i.Permissions -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetRepositoriesURL() string { - if i == nil || i.RepositoriesURL == nil { - return "" - } - return *i.RepositoriesURL -} - -// GetRepositorySelection returns the RepositorySelection field if it's non-nil, zero value otherwise. -func (i *Installation) GetRepositorySelection() string { - if i == nil || i.RepositorySelection == nil { - return "" - } - return *i.RepositorySelection -} - -// GetSingleFileName returns the SingleFileName field if it's non-nil, zero value otherwise. -func (i *Installation) GetSingleFileName() string { - if i == nil || i.SingleFileName == nil { - return "" - } - return *i.SingleFileName -} - -// GetTargetID returns the TargetID field if it's non-nil, zero value otherwise. -func (i *Installation) GetTargetID() int64 { - if i == nil || i.TargetID == nil { - return 0 - } - return *i.TargetID -} - -// GetTargetType returns the TargetType field if it's non-nil, zero value otherwise. -func (i *Installation) GetTargetType() string { - if i == nil || i.TargetType == nil { - return "" - } - return *i.TargetType -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *Installation) GetUpdatedAt() Timestamp { - if i == nil || i.UpdatedAt == nil { - return Timestamp{} - } - return *i.UpdatedAt -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetInstallation returns the Installation field. -func (i *InstallationEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetSender returns the Sender field. -func (i *InstallationEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetContents returns the Contents field if it's non-nil, zero value otherwise. -func (i *InstallationPermissions) GetContents() string { - if i == nil || i.Contents == nil { - return "" - } - return *i.Contents -} - -// GetIssues returns the Issues field if it's non-nil, zero value otherwise. -func (i *InstallationPermissions) GetIssues() string { - if i == nil || i.Issues == nil { - return "" - } - return *i.Issues -} - -// GetMetadata returns the Metadata field if it's non-nil, zero value otherwise. -func (i *InstallationPermissions) GetMetadata() string { - if i == nil || i.Metadata == nil { - return "" - } - return *i.Metadata -} - -// GetSingleFile returns the SingleFile field if it's non-nil, zero value otherwise. -func (i *InstallationPermissions) GetSingleFile() string { - if i == nil || i.SingleFile == nil { - return "" - } - return *i.SingleFile -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetInstallation returns the Installation field. -func (i *InstallationRepositoriesEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetRepositorySelection returns the RepositorySelection field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetRepositorySelection() string { - if i == nil || i.RepositorySelection == nil { - return "" - } - return *i.RepositorySelection -} - -// GetSender returns the Sender field. -func (i *InstallationRepositoriesEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetExpiresAt returns the ExpiresAt field if it's non-nil, zero value otherwise. -func (i *InstallationToken) GetExpiresAt() time.Time { - if i == nil || i.ExpiresAt == nil { - return time.Time{} - } - return *i.ExpiresAt -} - -// GetToken returns the Token field if it's non-nil, zero value otherwise. -func (i *InstallationToken) GetToken() string { - if i == nil || i.Token == nil { - return "" - } - return *i.Token -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Invitation) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (i *Invitation) GetEmail() string { - if i == nil || i.Email == nil { - return "" - } - return *i.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Invitation) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetInvitationTeamURL returns the InvitationTeamURL field if it's non-nil, zero value otherwise. -func (i *Invitation) GetInvitationTeamURL() string { - if i == nil || i.InvitationTeamURL == nil { - return "" - } - return *i.InvitationTeamURL -} - -// GetInviter returns the Inviter field. -func (i *Invitation) GetInviter() *User { - if i == nil { - return nil - } - return i.Inviter -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (i *Invitation) GetLogin() string { - if i == nil || i.Login == nil { - return "" - } - return *i.Login -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (i *Invitation) GetRole() string { - if i == nil || i.Role == nil { - return "" - } - return *i.Role -} - -// GetTeamCount returns the TeamCount field if it's non-nil, zero value otherwise. -func (i *Invitation) GetTeamCount() int { - if i == nil || i.TeamCount == nil { - return 0 - } - return *i.TeamCount -} - -// GetActiveLockReason returns the ActiveLockReason field if it's non-nil, zero value otherwise. -func (i *Issue) GetActiveLockReason() string { - if i == nil || i.ActiveLockReason == nil { - return "" - } - return *i.ActiveLockReason -} - -// GetAssignee returns the Assignee field. -func (i *Issue) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *Issue) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetClosedAt() time.Time { - if i == nil || i.ClosedAt == nil { - return time.Time{} - } - return *i.ClosedAt -} - -// GetClosedBy returns the ClosedBy field. -func (i *Issue) GetClosedBy() *User { - if i == nil { - return nil - } - return i.ClosedBy -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (i *Issue) GetComments() int { - if i == nil || i.Comments == nil { - return 0 - } - return *i.Comments -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetCommentsURL() string { - if i == nil || i.CommentsURL == nil { - return "" - } - return *i.CommentsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetEventsURL() string { - if i == nil || i.EventsURL == nil { - return "" - } - return *i.EventsURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Issue) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetLabelsURL() string { - if i == nil || i.LabelsURL == nil { - return "" - } - return *i.LabelsURL -} - -// GetLocked returns the Locked field if it's non-nil, zero value otherwise. -func (i *Issue) GetLocked() bool { - if i == nil || i.Locked == nil { - return false - } - return *i.Locked -} - -// GetMilestone returns the Milestone field. -func (i *Issue) GetMilestone() *Milestone { - if i == nil { - return nil - } - return i.Milestone -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (i *Issue) GetNodeID() string { - if i == nil || i.NodeID == nil { - return "" - } - return *i.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (i *Issue) GetNumber() int { - if i == nil || i.Number == nil { - return 0 - } - return *i.Number -} - -// GetPullRequestLinks returns the PullRequestLinks field. -func (i *Issue) GetPullRequestLinks() *PullRequestLinks { - if i == nil { - return nil - } - return i.PullRequestLinks -} - -// GetReactions returns the Reactions field. -func (i *Issue) GetReactions() *Reactions { - if i == nil { - return nil - } - return i.Reactions -} - -// GetRepository returns the Repository field. -func (i *Issue) GetRepository() *Repository { - if i == nil { - return nil - } - return i.Repository -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetRepositoryURL() string { - if i == nil || i.RepositoryURL == nil { - return "" - } - return *i.RepositoryURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *Issue) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *Issue) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Issue) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUser returns the User field. -func (i *Issue) GetUser() *User { - if i == nil { - return nil - } - return i.User -} - -// GetAuthorAssociation returns the AuthorAssociation field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetAuthorAssociation() string { - if i == nil || i.AuthorAssociation == nil { - return "" - } - return *i.AuthorAssociation -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetIssueURL() string { - if i == nil || i.IssueURL == nil { - return "" - } - return *i.IssueURL -} - -// GetReactions returns the Reactions field. -func (i *IssueComment) GetReactions() *Reactions { - if i == nil { - return nil - } - return i.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUser returns the User field. -func (i *IssueComment) GetUser() *User { - if i == nil { - return nil - } - return i.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssueCommentEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetChanges returns the Changes field. -func (i *IssueCommentEvent) GetChanges() *EditChange { - if i == nil { - return nil - } - return i.Changes -} - -// GetComment returns the Comment field. -func (i *IssueCommentEvent) GetComment() *IssueComment { - if i == nil { - return nil - } - return i.Comment -} - -// GetInstallation returns the Installation field. -func (i *IssueCommentEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetIssue returns the Issue field. -func (i *IssueCommentEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetRepo returns the Repo field. -func (i *IssueCommentEvent) GetRepo() *Repository { - if i == nil { - return nil - } - return i.Repo -} - -// GetSender returns the Sender field. -func (i *IssueCommentEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetActor returns the Actor field. -func (i *IssueEvent) GetActor() *User { - if i == nil { - return nil - } - return i.Actor -} - -// GetAssignee returns the Assignee field. -func (i *IssueEvent) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetAssigner returns the Assigner field. -func (i *IssueEvent) GetAssigner() *User { - if i == nil { - return nil - } - return i.Assigner -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCommitID() string { - if i == nil || i.CommitID == nil { - return "" - } - return *i.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetEvent() string { - if i == nil || i.Event == nil { - return "" - } - return *i.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetIssue returns the Issue field. -func (i *IssueEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetLabel returns the Label field. -func (i *IssueEvent) GetLabel() *Label { - if i == nil { - return nil - } - return i.Label -} - -// GetLockReason returns the LockReason field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetLockReason() string { - if i == nil || i.LockReason == nil { - return "" - } - return *i.LockReason -} - -// GetMilestone returns the Milestone field. -func (i *IssueEvent) GetMilestone() *Milestone { - if i == nil { - return nil - } - return i.Milestone -} - -// GetRename returns the Rename field. -func (i *IssueEvent) GetRename() *Rename { - if i == nil { - return nil - } - return i.Rename -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetAssignee returns the Assignee field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignee() string { - if i == nil || i.Assignee == nil { - return "" - } - return *i.Assignee -} - -// GetAssignees returns the Assignees field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignees() []string { - if i == nil || i.Assignees == nil { - return nil - } - return *i.Assignees -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetLabels returns the Labels field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetLabels() []string { - if i == nil || i.Labels == nil { - return nil - } - return *i.Labels -} - -// GetMilestone returns the Milestone field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetMilestone() int { - if i == nil || i.Milestone == nil { - return 0 - } - return *i.Milestone -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssuesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetAssignee returns the Assignee field. -func (i *IssuesEvent) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetChanges returns the Changes field. -func (i *IssuesEvent) GetChanges() *EditChange { - if i == nil { - return nil - } - return i.Changes -} - -// GetInstallation returns the Installation field. -func (i *IssuesEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetIssue returns the Issue field. -func (i *IssuesEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetLabel returns the Label field. -func (i *IssuesEvent) GetLabel() *Label { - if i == nil { - return nil - } - return i.Label -} - -// GetRepo returns the Repo field. -func (i *IssuesEvent) GetRepo() *Repository { - if i == nil { - return nil - } - return i.Repo -} - -// GetSender returns the Sender field. -func (i *IssuesEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetIncompleteResults() bool { - if i == nil || i.IncompleteResults == nil { - return false - } - return *i.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetTotal() int { - if i == nil || i.Total == nil { - return 0 - } - return *i.Total -} - -// GetClosedIssues returns the ClosedIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetClosedIssues() int { - if i == nil || i.ClosedIssues == nil { - return 0 - } - return *i.ClosedIssues -} - -// GetOpenIssues returns the OpenIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetOpenIssues() int { - if i == nil || i.OpenIssues == nil { - return 0 - } - return *i.OpenIssues -} - -// GetTotalIssues returns the TotalIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetTotalIssues() int { - if i == nil || i.TotalIssues == nil { - return 0 - } - return *i.TotalIssues -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (k *Key) GetID() int64 { - if k == nil || k.ID == nil { - return 0 - } - return *k.ID -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (k *Key) GetKey() string { - if k == nil || k.Key == nil { - return "" - } - return *k.Key -} - -// GetReadOnly returns the ReadOnly field if it's non-nil, zero value otherwise. -func (k *Key) GetReadOnly() bool { - if k == nil || k.ReadOnly == nil { - return false - } - return *k.ReadOnly -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (k *Key) GetTitle() string { - if k == nil || k.Title == nil { - return "" - } - return *k.Title -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (k *Key) GetURL() string { - if k == nil || k.URL == nil { - return "" - } - return *k.URL -} - -// GetColor returns the Color field if it's non-nil, zero value otherwise. -func (l *Label) GetColor() string { - if l == nil || l.Color == nil { - return "" - } - return *l.Color -} - -// GetDefault returns the Default field if it's non-nil, zero value otherwise. -func (l *Label) GetDefault() bool { - if l == nil || l.Default == nil { - return false - } - return *l.Default -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (l *Label) GetDescription() string { - if l == nil || l.Description == nil { - return "" - } - return *l.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (l *Label) GetID() int64 { - if l == nil || l.ID == nil { - return 0 - } - return *l.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *Label) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (l *Label) GetNodeID() string { - if l == nil || l.NodeID == nil { - return "" - } - return *l.NodeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *Label) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (l *LabelEvent) GetAction() string { - if l == nil || l.Action == nil { - return "" - } - return *l.Action -} - -// GetChanges returns the Changes field. -func (l *LabelEvent) GetChanges() *EditChange { - if l == nil { - return nil - } - return l.Changes -} - -// GetInstallation returns the Installation field. -func (l *LabelEvent) GetInstallation() *Installation { - if l == nil { - return nil - } - return l.Installation -} - -// GetLabel returns the Label field. -func (l *LabelEvent) GetLabel() *Label { - if l == nil { - return nil - } - return l.Label -} - -// GetOrg returns the Org field. -func (l *LabelEvent) GetOrg() *Organization { - if l == nil { - return nil - } - return l.Org -} - -// GetRepo returns the Repo field. -func (l *LabelEvent) GetRepo() *Repository { - if l == nil { - return nil - } - return l.Repo -} - -// GetColor returns the Color field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetColor() string { - if l == nil || l.Color == nil { - return "" - } - return *l.Color -} - -// GetDefault returns the Default field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetDefault() bool { - if l == nil || l.Default == nil { - return false - } - return *l.Default -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetDescription() string { - if l == nil || l.Description == nil { - return "" - } - return *l.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetID() int64 { - if l == nil || l.ID == nil { - return 0 - } - return *l.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetScore returns the Score field. -func (l *LabelResult) GetScore() *float64 { - if l == nil { - return nil - } - return l.Score -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *LabelResult) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (l *LabelsSearchResult) GetIncompleteResults() bool { - if l == nil || l.IncompleteResults == nil { - return false - } - return *l.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (l *LabelsSearchResult) GetTotal() int { - if l == nil || l.Total == nil { - return 0 - } - return *l.Total -} - -// GetOID returns the OID field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetOID() string { - if l == nil || l.OID == nil { - return "" - } - return *l.OID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetPath() string { - if l == nil || l.Path == nil { - return "" - } - return *l.Path -} - -// GetRefName returns the RefName field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetRefName() string { - if l == nil || l.RefName == nil { - return "" - } - return *l.RefName -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetSize() int { - if l == nil || l.Size == nil { - return 0 - } - return *l.Size -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (l *License) GetBody() string { - if l == nil || l.Body == nil { - return "" - } - return *l.Body -} - -// GetConditions returns the Conditions field if it's non-nil, zero value otherwise. -func (l *License) GetConditions() []string { - if l == nil || l.Conditions == nil { - return nil - } - return *l.Conditions -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (l *License) GetDescription() string { - if l == nil || l.Description == nil { - return "" - } - return *l.Description -} - -// GetFeatured returns the Featured field if it's non-nil, zero value otherwise. -func (l *License) GetFeatured() bool { - if l == nil || l.Featured == nil { - return false - } - return *l.Featured -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (l *License) GetHTMLURL() string { - if l == nil || l.HTMLURL == nil { - return "" - } - return *l.HTMLURL -} - -// GetImplementation returns the Implementation field if it's non-nil, zero value otherwise. -func (l *License) GetImplementation() string { - if l == nil || l.Implementation == nil { - return "" - } - return *l.Implementation -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (l *License) GetKey() string { - if l == nil || l.Key == nil { - return "" - } - return *l.Key -} - -// GetLimitations returns the Limitations field if it's non-nil, zero value otherwise. -func (l *License) GetLimitations() []string { - if l == nil || l.Limitations == nil { - return nil - } - return *l.Limitations -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *License) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (l *License) GetPermissions() []string { - if l == nil || l.Permissions == nil { - return nil - } - return *l.Permissions -} - -// GetSPDXID returns the SPDXID field if it's non-nil, zero value otherwise. -func (l *License) GetSPDXID() string { - if l == nil || l.SPDXID == nil { - return "" - } - return *l.SPDXID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *License) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetCheckName returns the CheckName field if it's non-nil, zero value otherwise. -func (l *ListCheckRunsOptions) GetCheckName() string { - if l == nil || l.CheckName == nil { - return "" - } - return *l.CheckName -} - -// GetFilter returns the Filter field if it's non-nil, zero value otherwise. -func (l *ListCheckRunsOptions) GetFilter() string { - if l == nil || l.Filter == nil { - return "" - } - return *l.Filter -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (l *ListCheckRunsOptions) GetStatus() string { - if l == nil || l.Status == nil { - return "" - } - return *l.Status -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (l *ListCheckRunsResults) GetTotal() int { - if l == nil || l.Total == nil { - return 0 - } - return *l.Total -} - -// GetAppID returns the AppID field if it's non-nil, zero value otherwise. -func (l *ListCheckSuiteOptions) GetAppID() int { - if l == nil || l.AppID == nil { - return 0 - } - return *l.AppID -} - -// GetCheckName returns the CheckName field if it's non-nil, zero value otherwise. -func (l *ListCheckSuiteOptions) GetCheckName() string { - if l == nil || l.CheckName == nil { - return "" - } - return *l.CheckName -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (l *ListCheckSuiteResults) GetTotal() int { - if l == nil || l.Total == nil { - return 0 - } - return *l.Total -} - -// GetAccountsURL returns the AccountsURL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetAccountsURL() string { - if m == nil || m.AccountsURL == nil { - return "" - } - return *m.AccountsURL -} - -// GetBullets returns the Bullets field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetBullets() []string { - if m == nil || m.Bullets == nil { - return nil - } - return *m.Bullets -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetDescription() string { - if m == nil || m.Description == nil { - return "" - } - return *m.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetMonthlyPriceInCents returns the MonthlyPriceInCents field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetMonthlyPriceInCents() int { - if m == nil || m.MonthlyPriceInCents == nil { - return 0 - } - return *m.MonthlyPriceInCents -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetName() string { - if m == nil || m.Name == nil { - return "" - } - return *m.Name -} - -// GetPriceModel returns the PriceModel field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetPriceModel() string { - if m == nil || m.PriceModel == nil { - return "" - } - return *m.PriceModel -} - -// GetUnitName returns the UnitName field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetUnitName() string { - if m == nil || m.UnitName == nil { - return "" - } - return *m.UnitName -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetYearlyPriceInCents returns the YearlyPriceInCents field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetYearlyPriceInCents() int { - if m == nil || m.YearlyPriceInCents == nil { - return 0 - } - return *m.YearlyPriceInCents -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetEmail() string { - if m == nil || m.Email == nil { - return "" - } - return *m.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetLogin() string { - if m == nil || m.Login == nil { - return "" - } - return *m.Login -} - -// GetMarketplacePurchase returns the MarketplacePurchase field. -func (m *MarketplacePlanAccount) GetMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.MarketplacePurchase -} - -// GetOrganizationBillingEmail returns the OrganizationBillingEmail field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetOrganizationBillingEmail() string { - if m == nil || m.OrganizationBillingEmail == nil { - return "" - } - return *m.OrganizationBillingEmail -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetType() string { - if m == nil || m.Type == nil { - return "" - } - return *m.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAccount returns the Account field. -func (m *MarketplacePurchase) GetAccount() *MarketplacePlanAccount { - if m == nil { - return nil - } - return m.Account -} - -// GetBillingCycle returns the BillingCycle field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetBillingCycle() string { - if m == nil || m.BillingCycle == nil { - return "" - } - return *m.BillingCycle -} - -// GetNextBillingDate returns the NextBillingDate field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetNextBillingDate() string { - if m == nil || m.NextBillingDate == nil { - return "" - } - return *m.NextBillingDate -} - -// GetPlan returns the Plan field. -func (m *MarketplacePurchase) GetPlan() *MarketplacePlan { - if m == nil { - return nil - } - return m.Plan -} - -// GetUnitCount returns the UnitCount field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetUnitCount() int { - if m == nil || m.UnitCount == nil { - return 0 - } - return *m.UnitCount -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchaseEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetEffectiveDate returns the EffectiveDate field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchaseEvent) GetEffectiveDate() Timestamp { - if m == nil || m.EffectiveDate == nil { - return Timestamp{} - } - return *m.EffectiveDate -} - -// GetInstallation returns the Installation field. -func (m *MarketplacePurchaseEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMarketplacePurchase returns the MarketplacePurchase field. -func (m *MarketplacePurchaseEvent) GetMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.MarketplacePurchase -} - -// GetPreviousMarketplacePurchase returns the PreviousMarketplacePurchase field. -func (m *MarketplacePurchaseEvent) GetPreviousMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.PreviousMarketplacePurchase -} - -// GetSender returns the Sender field. -func (m *MarketplacePurchaseEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetText returns the Text field if it's non-nil, zero value otherwise. -func (m *Match) GetText() string { - if m == nil || m.Text == nil { - return "" - } - return *m.Text -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MemberEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetInstallation returns the Installation field. -func (m *MemberEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMember returns the Member field. -func (m *MemberEvent) GetMember() *User { - if m == nil { - return nil - } - return m.Member -} - -// GetRepo returns the Repo field. -func (m *MemberEvent) GetRepo() *Repository { - if m == nil { - return nil - } - return m.Repo -} - -// GetSender returns the Sender field. -func (m *MemberEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetOrganization returns the Organization field. -func (m *Membership) GetOrganization() *Organization { - if m == nil { - return nil - } - return m.Organization -} - -// GetOrganizationURL returns the OrganizationURL field if it's non-nil, zero value otherwise. -func (m *Membership) GetOrganizationURL() string { - if m == nil || m.OrganizationURL == nil { - return "" - } - return *m.OrganizationURL -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (m *Membership) GetRole() string { - if m == nil || m.Role == nil { - return "" - } - return *m.Role -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Membership) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Membership) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetUser returns the User field. -func (m *Membership) GetUser() *User { - if m == nil { - return nil - } - return m.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetInstallation returns the Installation field. -func (m *MembershipEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMember returns the Member field. -func (m *MembershipEvent) GetMember() *User { - if m == nil { - return nil - } - return m.Member -} - -// GetOrg returns the Org field. -func (m *MembershipEvent) GetOrg() *Organization { - if m == nil { - return nil - } - return m.Org -} - -// GetScope returns the Scope field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetScope() string { - if m == nil || m.Scope == nil { - return "" - } - return *m.Scope -} - -// GetSender returns the Sender field. -func (m *MembershipEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetTeam returns the Team field. -func (m *MembershipEvent) GetTeam() *Team { - if m == nil { - return nil - } - return m.Team -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Metric) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (m *Metric) GetKey() string { - if m == nil || m.Key == nil { - return "" - } - return *m.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (m *Metric) GetName() string { - if m == nil || m.Name == nil { - return "" - } - return *m.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Metric) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetCreatedAt() string { - if m == nil || m.CreatedAt == nil { - return "" - } - return *m.CreatedAt -} - -// GetExcludeAttachments returns the ExcludeAttachments field if it's non-nil, zero value otherwise. -func (m *Migration) GetExcludeAttachments() bool { - if m == nil || m.ExcludeAttachments == nil { - return false - } - return *m.ExcludeAttachments -} - -// GetGUID returns the GUID field if it's non-nil, zero value otherwise. -func (m *Migration) GetGUID() string { - if m == nil || m.GUID == nil { - return "" - } - return *m.GUID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Migration) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLockRepositories returns the LockRepositories field if it's non-nil, zero value otherwise. -func (m *Migration) GetLockRepositories() bool { - if m == nil || m.LockRepositories == nil { - return false - } - return *m.LockRepositories -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Migration) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetUpdatedAt() string { - if m == nil || m.UpdatedAt == nil { - return "" - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Migration) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedAt() time.Time { - if m == nil || m.ClosedAt == nil { - return time.Time{} - } - return *m.ClosedAt -} - -// GetClosedIssues returns the ClosedIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedIssues() int { - if m == nil || m.ClosedIssues == nil { - return 0 - } - return *m.ClosedIssues -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetCreatedAt() time.Time { - if m == nil || m.CreatedAt == nil { - return time.Time{} - } - return *m.CreatedAt -} - -// GetCreator returns the Creator field. -func (m *Milestone) GetCreator() *User { - if m == nil { - return nil - } - return m.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDescription() string { - if m == nil || m.Description == nil { - return "" - } - return *m.Description -} - -// GetDueOn returns the DueOn field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDueOn() time.Time { - if m == nil || m.DueOn == nil { - return time.Time{} - } - return *m.DueOn -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Milestone) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetLabelsURL() string { - if m == nil || m.LabelsURL == nil { - return "" - } - return *m.LabelsURL -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (m *Milestone) GetNodeID() string { - if m == nil || m.NodeID == nil { - return "" - } - return *m.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (m *Milestone) GetNumber() int { - if m == nil || m.Number == nil { - return 0 - } - return *m.Number -} - -// GetOpenIssues returns the OpenIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetOpenIssues() int { - if m == nil || m.OpenIssues == nil { - return 0 - } - return *m.OpenIssues -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Milestone) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (m *Milestone) GetTitle() string { - if m == nil || m.Title == nil { - return "" - } - return *m.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetUpdatedAt() time.Time { - if m == nil || m.UpdatedAt == nil { - return time.Time{} - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MilestoneEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetChanges returns the Changes field. -func (m *MilestoneEvent) GetChanges() *EditChange { - if m == nil { - return nil - } - return m.Changes -} - -// GetInstallation returns the Installation field. -func (m *MilestoneEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMilestone returns the Milestone field. -func (m *MilestoneEvent) GetMilestone() *Milestone { - if m == nil { - return nil - } - return m.Milestone -} - -// GetOrg returns the Org field. -func (m *MilestoneEvent) GetOrg() *Organization { - if m == nil { - return nil - } - return m.Org -} - -// GetRepo returns the Repo field. -func (m *MilestoneEvent) GetRepo() *Repository { - if m == nil { - return nil - } - return m.Repo -} - -// GetSender returns the Sender field. -func (m *MilestoneEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetClosedMilestones returns the ClosedMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetClosedMilestones() int { - if m == nil || m.ClosedMilestones == nil { - return 0 - } - return *m.ClosedMilestones -} - -// GetOpenMilestones returns the OpenMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetOpenMilestones() int { - if m == nil || m.OpenMilestones == nil { - return 0 - } - return *m.OpenMilestones -} - -// GetTotalMilestones returns the TotalMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetTotalMilestones() int { - if m == nil || m.TotalMilestones == nil { - return 0 - } - return *m.TotalMilestones -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBase() string { - if n == nil || n.Base == nil { - return "" - } - return *n.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBody() string { - if n == nil || n.Body == nil { - return "" - } - return *n.Body -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetHead() string { - if n == nil || n.Head == nil { - return "" - } - return *n.Head -} - -// GetIssue returns the Issue field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetIssue() int { - if n == nil || n.Issue == nil { - return 0 - } - return *n.Issue -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetMaintainerCanModify() bool { - if n == nil || n.MaintainerCanModify == nil { - return false - } - return *n.MaintainerCanModify -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetDescription() string { - if n == nil || n.Description == nil { - return "" - } - return *n.Description -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetLDAPDN() string { - if n == nil || n.LDAPDN == nil { - return "" - } - return *n.LDAPDN -} - -// GetParentTeamID returns the ParentTeamID field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetParentTeamID() int64 { - if n == nil || n.ParentTeamID == nil { - return 0 - } - return *n.ParentTeamID -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetPermission() string { - if n == nil || n.Permission == nil { - return "" - } - return *n.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetPrivacy() string { - if n == nil || n.Privacy == nil { - return "" - } - return *n.Privacy -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (n *Notification) GetID() string { - if n == nil || n.ID == nil { - return "" - } - return *n.ID -} - -// GetLastReadAt returns the LastReadAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetLastReadAt() time.Time { - if n == nil || n.LastReadAt == nil { - return time.Time{} - } - return *n.LastReadAt -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (n *Notification) GetReason() string { - if n == nil || n.Reason == nil { - return "" - } - return *n.Reason -} - -// GetRepository returns the Repository field. -func (n *Notification) GetRepository() *Repository { - if n == nil { - return nil - } - return n.Repository -} - -// GetSubject returns the Subject field. -func (n *Notification) GetSubject() *NotificationSubject { - if n == nil { - return nil - } - return n.Subject -} - -// GetUnread returns the Unread field if it's non-nil, zero value otherwise. -func (n *Notification) GetUnread() bool { - if n == nil || n.Unread == nil { - return false - } - return *n.Unread -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetUpdatedAt() time.Time { - if n == nil || n.UpdatedAt == nil { - return time.Time{} - } - return *n.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *Notification) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetLatestCommentURL returns the LatestCommentURL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetLatestCommentURL() string { - if n == nil || n.LatestCommentURL == nil { - return "" - } - return *n.LatestCommentURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetType() string { - if n == nil || n.Type == nil { - return "" - } - return *n.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetAvatarURL() string { - if o == nil || o.AvatarURL == nil { - return "" - } - return *o.AvatarURL -} - -// GetBillingEmail returns the BillingEmail field if it's non-nil, zero value otherwise. -func (o *Organization) GetBillingEmail() string { - if o == nil || o.BillingEmail == nil { - return "" - } - return *o.BillingEmail -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (o *Organization) GetBlog() string { - if o == nil || o.Blog == nil { - return "" - } - return *o.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (o *Organization) GetCollaborators() int { - if o == nil || o.Collaborators == nil { - return 0 - } - return *o.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (o *Organization) GetCompany() string { - if o == nil || o.Company == nil { - return "" - } - return *o.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetCreatedAt() time.Time { - if o == nil || o.CreatedAt == nil { - return time.Time{} - } - return *o.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (o *Organization) GetDescription() string { - if o == nil || o.Description == nil { - return "" - } - return *o.Description -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (o *Organization) GetDiskUsage() int { - if o == nil || o.DiskUsage == nil { - return 0 - } - return *o.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (o *Organization) GetEmail() string { - if o == nil || o.Email == nil { - return "" - } - return *o.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetEventsURL() string { - if o == nil || o.EventsURL == nil { - return "" - } - return *o.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowers() int { - if o == nil || o.Followers == nil { - return 0 - } - return *o.Followers -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowing() int { - if o == nil || o.Following == nil { - return 0 - } - return *o.Following -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHooksURL() string { - if o == nil || o.HooksURL == nil { - return "" - } - return *o.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHTMLURL() string { - if o == nil || o.HTMLURL == nil { - return "" - } - return *o.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (o *Organization) GetID() int64 { - if o == nil || o.ID == nil { - return 0 - } - return *o.ID -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetIssuesURL() string { - if o == nil || o.IssuesURL == nil { - return "" - } - return *o.IssuesURL -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (o *Organization) GetLocation() string { - if o == nil || o.Location == nil { - return "" - } - return *o.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (o *Organization) GetLogin() string { - if o == nil || o.Login == nil { - return "" - } - return *o.Login -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetMembersURL() string { - if o == nil || o.MembersURL == nil { - return "" - } - return *o.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (o *Organization) GetName() string { - if o == nil || o.Name == nil { - return "" - } - return *o.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (o *Organization) GetNodeID() string { - if o == nil || o.NodeID == nil { - return "" - } - return *o.NodeID -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetOwnedPrivateRepos() int { - if o == nil || o.OwnedPrivateRepos == nil { - return 0 - } - return *o.OwnedPrivateRepos -} - -// GetPlan returns the Plan field. -func (o *Organization) GetPlan() *Plan { - if o == nil { - return nil - } - return o.Plan -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPrivateGists() int { - if o == nil || o.PrivateGists == nil { - return 0 - } - return *o.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicGists() int { - if o == nil || o.PublicGists == nil { - return 0 - } - return *o.PublicGists -} - -// GetPublicMembersURL returns the PublicMembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicMembersURL() string { - if o == nil || o.PublicMembersURL == nil { - return "" - } - return *o.PublicMembersURL -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicRepos() int { - if o == nil || o.PublicRepos == nil { - return 0 - } - return *o.PublicRepos -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetReposURL() string { - if o == nil || o.ReposURL == nil { - return "" - } - return *o.ReposURL -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetTotalPrivateRepos() int { - if o == nil || o.TotalPrivateRepos == nil { - return 0 - } - return *o.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (o *Organization) GetType() string { - if o == nil || o.Type == nil { - return "" - } - return *o.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetUpdatedAt() time.Time { - if o == nil || o.UpdatedAt == nil { - return time.Time{} - } - return *o.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (o *Organization) GetURL() string { - if o == nil || o.URL == nil { - return "" - } - return *o.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrganizationEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetInstallation returns the Installation field. -func (o *OrganizationEvent) GetInstallation() *Installation { - if o == nil { - return nil - } - return o.Installation -} - -// GetInvitation returns the Invitation field. -func (o *OrganizationEvent) GetInvitation() *Invitation { - if o == nil { - return nil - } - return o.Invitation -} - -// GetMembership returns the Membership field. -func (o *OrganizationEvent) GetMembership() *Membership { - if o == nil { - return nil - } - return o.Membership -} - -// GetOrganization returns the Organization field. -func (o *OrganizationEvent) GetOrganization() *Organization { - if o == nil { - return nil - } - return o.Organization -} - -// GetSender returns the Sender field. -func (o *OrganizationEvent) GetSender() *User { - if o == nil { - return nil - } - return o.Sender -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrgBlockEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetBlockedUser returns the BlockedUser field. -func (o *OrgBlockEvent) GetBlockedUser() *User { - if o == nil { - return nil - } - return o.BlockedUser -} - -// GetInstallation returns the Installation field. -func (o *OrgBlockEvent) GetInstallation() *Installation { - if o == nil { - return nil - } - return o.Installation -} - -// GetOrganization returns the Organization field. -func (o *OrgBlockEvent) GetOrganization() *Organization { - if o == nil { - return nil - } - return o.Organization -} - -// GetSender returns the Sender field. -func (o *OrgBlockEvent) GetSender() *User { - if o == nil { - return nil - } - return o.Sender -} - -// GetDisabledOrgs returns the DisabledOrgs field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetDisabledOrgs() int { - if o == nil || o.DisabledOrgs == nil { - return 0 - } - return *o.DisabledOrgs -} - -// GetTotalOrgs returns the TotalOrgs field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalOrgs() int { - if o == nil || o.TotalOrgs == nil { - return 0 - } - return *o.TotalOrgs -} - -// GetTotalTeamMembers returns the TotalTeamMembers field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalTeamMembers() int { - if o == nil || o.TotalTeamMembers == nil { - return 0 - } - return *o.TotalTeamMembers -} - -// GetTotalTeams returns the TotalTeams field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalTeams() int { - if o == nil || o.TotalTeams == nil { - return 0 - } - return *o.TotalTeams -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *Page) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Page) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPageName returns the PageName field if it's non-nil, zero value otherwise. -func (p *Page) GetPageName() string { - if p == nil || p.PageName == nil { - return "" - } - return *p.PageName -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *Page) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetSummary returns the Summary field if it's non-nil, zero value otherwise. -func (p *Page) GetSummary() string { - if p == nil || p.Summary == nil { - return "" - } - return *p.Summary -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *Page) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetBuild returns the Build field. -func (p *PageBuildEvent) GetBuild() *PagesBuild { - if p == nil { - return nil - } - return p.Build -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PageBuildEvent) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetInstallation returns the Installation field. -func (p *PageBuildEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetRepo returns the Repo field. -func (p *PageBuildEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PageBuildEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetCNAME returns the CNAME field if it's non-nil, zero value otherwise. -func (p *Pages) GetCNAME() string { - if p == nil || p.CNAME == nil { - return "" - } - return *p.CNAME -} - -// GetCustom404 returns the Custom404 field if it's non-nil, zero value otherwise. -func (p *Pages) GetCustom404() bool { - if p == nil || p.Custom404 == nil { - return false - } - return *p.Custom404 -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Pages) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *Pages) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Pages) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetCommit returns the Commit field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCommit() string { - if p == nil || p.Commit == nil { - return "" - } - return *p.Commit -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDuration returns the Duration field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetDuration() int { - if p == nil || p.Duration == nil { - return 0 - } - return *p.Duration -} - -// GetError returns the Error field. -func (p *PagesBuild) GetError() *PagesError { - if p == nil { - return nil - } - return p.Error -} - -// GetPusher returns the Pusher field. -func (p *PagesBuild) GetPusher() *User { - if p == nil { - return nil - } - return p.Pusher -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PagesError) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetTotalPages returns the TotalPages field if it's non-nil, zero value otherwise. -func (p *PageStats) GetTotalPages() int { - if p == nil || p.TotalPages == nil { - return 0 - } - return *p.TotalPages -} - -// GetHook returns the Hook field. -func (p *PingEvent) GetHook() *Hook { - if p == nil { - return nil - } - return p.Hook -} - -// GetHookID returns the HookID field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetHookID() int64 { - if p == nil || p.HookID == nil { - return 0 - } - return *p.HookID -} - -// GetInstallation returns the Installation field. -func (p *PingEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetZen returns the Zen field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetZen() string { - if p == nil || p.Zen == nil { - return "" - } - return *p.Zen -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (p *Plan) GetCollaborators() int { - if p == nil || p.Collaborators == nil { - return 0 - } - return *p.Collaborators -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Plan) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetPrivateRepos returns the PrivateRepos field if it's non-nil, zero value otherwise. -func (p *Plan) GetPrivateRepos() int { - if p == nil || p.PrivateRepos == nil { - return 0 - } - return *p.PrivateRepos -} - -// GetSpace returns the Space field if it's non-nil, zero value otherwise. -func (p *Plan) GetSpace() int { - if p == nil || p.Space == nil { - return 0 - } - return *p.Space -} - -// GetConfigURL returns the ConfigURL field if it's non-nil, zero value otherwise. -func (p *PreReceiveHook) GetConfigURL() string { - if p == nil || p.ConfigURL == nil { - return "" - } - return *p.ConfigURL -} - -// GetEnforcement returns the Enforcement field if it's non-nil, zero value otherwise. -func (p *PreReceiveHook) GetEnforcement() string { - if p == nil || p.Enforcement == nil { - return "" - } - return *p.Enforcement -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PreReceiveHook) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PreReceiveHook) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *Project) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetColumnsURL returns the ColumnsURL field if it's non-nil, zero value otherwise. -func (p *Project) GetColumnsURL() string { - if p == nil || p.ColumnsURL == nil { - return "" - } - return *p.ColumnsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetCreator returns the Creator field. -func (p *Project) GetCreator() *User { - if p == nil { - return nil - } - return p.Creator -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Project) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *Project) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Project) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *Project) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *Project) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetOwnerURL returns the OwnerURL field if it's non-nil, zero value otherwise. -func (p *Project) GetOwnerURL() string { - if p == nil || p.OwnerURL == nil { - return "" - } - return *p.OwnerURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *Project) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Project) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetArchived returns the Archived field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetArchived() bool { - if p == nil || p.Archived == nil { - return false - } - return *p.Archived -} - -// GetColumnID returns the ColumnID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnID() int64 { - if p == nil || p.ColumnID == nil { - return 0 - } - return *p.ColumnID -} - -// GetColumnURL returns the ColumnURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnURL() string { - if p == nil || p.ColumnURL == nil { - return "" - } - return *p.ColumnURL -} - -// GetContentURL returns the ContentURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetContentURL() string { - if p == nil || p.ContentURL == nil { - return "" - } - return *p.ContentURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetCreator returns the Creator field. -func (p *ProjectCard) GetCreator() *User { - if p == nil { - return nil - } - return p.Creator -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetNote() string { - if p == nil || p.Note == nil { - return "" - } - return *p.Note -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAfterID() int64 { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetChanges returns the Changes field. -func (p *ProjectCardEvent) GetChanges() *ProjectCardChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectCardEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectCardEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProjectCard returns the ProjectCard field. -func (p *ProjectCardEvent) GetProjectCard() *ProjectCard { - if p == nil { - return nil - } - return p.ProjectCard -} - -// GetRepo returns the Repo field. -func (p *ProjectCardEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectCardEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetArchivedState returns the ArchivedState field if it's non-nil, zero value otherwise. -func (p *ProjectCardListOptions) GetArchivedState() string { - if p == nil || p.ArchivedState == nil { - return "" - } - return *p.ArchivedState -} - -// GetArchived returns the Archived field if it's non-nil, zero value otherwise. -func (p *ProjectCardOptions) GetArchived() bool { - if p == nil || p.Archived == nil { - return false - } - return *p.Archived -} - -// GetCardsURL returns the CardsURL field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetCardsURL() string { - if p == nil || p.CardsURL == nil { - return "" - } - return *p.CardsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetProjectURL returns the ProjectURL field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetProjectURL() string { - if p == nil || p.ProjectURL == nil { - return "" - } - return *p.ProjectURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAfterID() int64 { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetChanges returns the Changes field. -func (p *ProjectColumnEvent) GetChanges() *ProjectColumnChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectColumnEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectColumnEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProjectColumn returns the ProjectColumn field. -func (p *ProjectColumnEvent) GetProjectColumn() *ProjectColumn { - if p == nil { - return nil - } - return p.ProjectColumn -} - -// GetRepo returns the Repo field. -func (p *ProjectColumnEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectColumnEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetChanges returns the Changes field. -func (p *ProjectEvent) GetChanges() *ProjectChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProject returns the Project field. -func (p *ProjectEvent) GetProject() *Project { - if p == nil { - return nil - } - return p.Project -} - -// GetRepo returns the Repo field. -func (p *ProjectEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *ProjectOptions) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *ProjectOptions) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetOrganizationPermission returns the OrganizationPermission field if it's non-nil, zero value otherwise. -func (p *ProjectOptions) GetOrganizationPermission() string { - if p == nil || p.OrganizationPermission == nil { - return "" - } - return *p.OrganizationPermission -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (p *ProjectOptions) GetPublic() bool { - if p == nil || p.Public == nil { - return false - } - return *p.Public -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *ProjectOptions) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetEnforceAdmins returns the EnforceAdmins field. -func (p *Protection) GetEnforceAdmins() *AdminEnforcement { - if p == nil { - return nil - } - return p.EnforceAdmins -} - -// GetRequiredPullRequestReviews returns the RequiredPullRequestReviews field. -func (p *Protection) GetRequiredPullRequestReviews() *PullRequestReviewsEnforcement { - if p == nil { - return nil - } - return p.RequiredPullRequestReviews -} - -// GetRequiredStatusChecks returns the RequiredStatusChecks field. -func (p *Protection) GetRequiredStatusChecks() *RequiredStatusChecks { - if p == nil { - return nil - } - return p.RequiredStatusChecks -} - -// GetRestrictions returns the Restrictions field. -func (p *Protection) GetRestrictions() *BranchRestrictions { - if p == nil { - return nil - } - return p.Restrictions -} - -// GetRequiredPullRequestReviews returns the RequiredPullRequestReviews field. -func (p *ProtectionRequest) GetRequiredPullRequestReviews() *PullRequestReviewsEnforcementRequest { - if p == nil { - return nil - } - return p.RequiredPullRequestReviews -} - -// GetRequiredStatusChecks returns the RequiredStatusChecks field. -func (p *ProtectionRequest) GetRequiredStatusChecks() *RequiredStatusChecks { - if p == nil { - return nil - } - return p.RequiredStatusChecks -} - -// GetRestrictions returns the Restrictions field. -func (p *ProtectionRequest) GetRestrictions() *BranchRestrictionsRequest { - if p == nil { - return nil - } - return p.Restrictions -} - -// GetInstallation returns the Installation field. -func (p *PublicEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetRepo returns the Repo field. -func (p *PublicEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PublicEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetActiveLockReason returns the ActiveLockReason field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetActiveLockReason() string { - if p == nil || p.ActiveLockReason == nil { - return "" - } - return *p.ActiveLockReason -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetAdditions() int { - if p == nil || p.Additions == nil { - return 0 - } - return *p.Additions -} - -// GetAssignee returns the Assignee field. -func (p *PullRequest) GetAssignee() *User { - if p == nil { - return nil - } - return p.Assignee -} - -// GetAuthorAssociation returns the AuthorAssociation field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetAuthorAssociation() string { - if p == nil || p.AuthorAssociation == nil { - return "" - } - return *p.AuthorAssociation -} - -// GetBase returns the Base field. -func (p *PullRequest) GetBase() *PullRequestBranch { - if p == nil { - return nil - } - return p.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetChangedFiles returns the ChangedFiles field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetChangedFiles() int { - if p == nil || p.ChangedFiles == nil { - return 0 - } - return *p.ChangedFiles -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetClosedAt() time.Time { - if p == nil || p.ClosedAt == nil { - return time.Time{} - } - return *p.ClosedAt -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetComments() int { - if p == nil || p.Comments == nil { - return 0 - } - return *p.Comments -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCommentsURL() string { - if p == nil || p.CommentsURL == nil { - return "" - } - return *p.CommentsURL -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetCommitsURL returns the CommitsURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCommitsURL() string { - if p == nil || p.CommitsURL == nil { - return "" - } - return *p.CommitsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDeletions() int { - if p == nil || p.Deletions == nil { - return 0 - } - return *p.Deletions -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHead returns the Head field. -func (p *PullRequest) GetHead() *PullRequestBranch { - if p == nil { - return nil - } - return p.Head -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetIssueURL() string { - if p == nil || p.IssueURL == nil { - return "" - } - return *p.IssueURL -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMaintainerCanModify() bool { - if p == nil || p.MaintainerCanModify == nil { - return false - } - return *p.MaintainerCanModify -} - -// GetMergeable returns the Mergeable field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeable() bool { - if p == nil || p.Mergeable == nil { - return false - } - return *p.Mergeable -} - -// GetMergeableState returns the MergeableState field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeableState() string { - if p == nil || p.MergeableState == nil { - return "" - } - return *p.MergeableState -} - -// GetMergeCommitSHA returns the MergeCommitSHA field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeCommitSHA() string { - if p == nil || p.MergeCommitSHA == nil { - return "" - } - return *p.MergeCommitSHA -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMergedAt returns the MergedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergedAt() time.Time { - if p == nil || p.MergedAt == nil { - return time.Time{} - } - return *p.MergedAt -} - -// GetMergedBy returns the MergedBy field. -func (p *PullRequest) GetMergedBy() *User { - if p == nil { - return nil - } - return p.MergedBy -} - -// GetMilestone returns the Milestone field. -func (p *PullRequest) GetMilestone() *Milestone { - if p == nil { - return nil - } - return p.Milestone -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetReviewCommentsURL returns the ReviewCommentsURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentsURL() string { - if p == nil || p.ReviewCommentsURL == nil { - return "" - } - return *p.ReviewCommentsURL -} - -// GetReviewCommentURL returns the ReviewCommentURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentURL() string { - if p == nil || p.ReviewCommentURL == nil { - return "" - } - return *p.ReviewCommentURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetUser returns the User field. -func (p *PullRequest) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetLabel() string { - if p == nil || p.Label == nil { - return "" - } - return *p.Label -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetRepo returns the Repo field. -func (p *PullRequestBranch) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetUser returns the User field. -func (p *PullRequestBranch) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetAuthorAssociation returns the AuthorAssociation field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetAuthorAssociation() string { - if p == nil || p.AuthorAssociation == nil { - return "" - } - return *p.AuthorAssociation -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDiffHunk returns the DiffHunk field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetDiffHunk() string { - if p == nil || p.DiffHunk == nil { - return "" - } - return *p.DiffHunk -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetInReplyTo returns the InReplyTo field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetInReplyTo() int64 { - if p == nil || p.InReplyTo == nil { - return 0 - } - return *p.InReplyTo -} - -// GetOriginalCommitID returns the OriginalCommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalCommitID() string { - if p == nil || p.OriginalCommitID == nil { - return "" - } - return *p.OriginalCommitID -} - -// GetOriginalPosition returns the OriginalPosition field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalPosition() int { - if p == nil || p.OriginalPosition == nil { - return 0 - } - return *p.OriginalPosition -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPath() string { - if p == nil || p.Path == nil { - return "" - } - return *p.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPosition() int { - if p == nil || p.Position == nil { - return 0 - } - return *p.Position -} - -// GetPullRequestReviewID returns the PullRequestReviewID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPullRequestReviewID() int64 { - if p == nil || p.PullRequestReviewID == nil { - return 0 - } - return *p.PullRequestReviewID -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetReactions returns the Reactions field. -func (p *PullRequestComment) GetReactions() *Reactions { - if p == nil { - return nil - } - return p.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetUser returns the User field. -func (p *PullRequestComment) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAssignee returns the Assignee field. -func (p *PullRequestEvent) GetAssignee() *User { - if p == nil { - return nil - } - return p.Assignee -} - -// GetChanges returns the Changes field. -func (p *PullRequestEvent) GetChanges() *EditChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *PullRequestEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetLabel returns the Label field. -func (p *PullRequestEvent) GetLabel() *Label { - if p == nil { - return nil - } - return p.Label -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetRequestedReviewer returns the RequestedReviewer field. -func (p *PullRequestEvent) GetRequestedReviewer() *User { - if p == nil { - return nil - } - return p.RequestedReviewer -} - -// GetSender returns the Sender field. -func (p *PullRequestEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetSubmittedAt returns the SubmittedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetSubmittedAt() time.Time { - if p == nil || p.SubmittedAt == nil { - return time.Time{} - } - return *p.SubmittedAt -} - -// GetUser returns the User field. -func (p *PullRequestReview) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewCommentEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetChanges returns the Changes field. -func (p *PullRequestReviewCommentEvent) GetChanges() *EditChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetComment returns the Comment field. -func (p *PullRequestReviewCommentEvent) GetComment() *PullRequestComment { - if p == nil { - return nil - } - return p.Comment -} - -// GetInstallation returns the Installation field. -func (p *PullRequestReviewCommentEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestReviewCommentEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestReviewCommentEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PullRequestReviewCommentEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewDismissalRequest) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetInstallation returns the Installation field. -func (p *PullRequestReviewEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrganization returns the Organization field. -func (p *PullRequestReviewEvent) GetOrganization() *Organization { - if p == nil { - return nil - } - return p.Organization -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestReviewEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestReviewEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetReview returns the Review field. -func (p *PullRequestReviewEvent) GetReview() *PullRequestReview { - if p == nil { - return nil - } - return p.Review -} - -// GetSender returns the Sender field. -func (p *PullRequestReviewEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetEvent() string { - if p == nil || p.Event == nil { - return "" - } - return *p.Event -} - -// GetDismissalRestrictionsRequest returns the DismissalRestrictionsRequest field. -func (p *PullRequestReviewsEnforcementRequest) GetDismissalRestrictionsRequest() *DismissalRestrictionsRequest { - if p == nil { - return nil - } - return p.DismissalRestrictionsRequest -} - -// GetDismissalRestrictionsRequest returns the DismissalRestrictionsRequest field. -func (p *PullRequestReviewsEnforcementUpdate) GetDismissalRestrictionsRequest() *DismissalRestrictionsRequest { - if p == nil { - return nil - } - return p.DismissalRestrictionsRequest -} - -// GetDismissStaleReviews returns the DismissStaleReviews field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewsEnforcementUpdate) GetDismissStaleReviews() bool { - if p == nil || p.DismissStaleReviews == nil { - return false - } - return *p.DismissStaleReviews -} - -// GetMergablePulls returns the MergablePulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetMergablePulls() int { - if p == nil || p.MergablePulls == nil { - return 0 - } - return *p.MergablePulls -} - -// GetMergedPulls returns the MergedPulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetMergedPulls() int { - if p == nil || p.MergedPulls == nil { - return 0 - } - return *p.MergedPulls -} - -// GetTotalPulls returns the TotalPulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetTotalPulls() int { - if p == nil || p.TotalPulls == nil { - return 0 - } - return *p.TotalPulls -} - -// GetUnmergablePulls returns the UnmergablePulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetUnmergablePulls() int { - if p == nil || p.UnmergablePulls == nil { - return 0 - } - return *p.UnmergablePulls -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetDay returns the Day field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetDay() int { - if p == nil || p.Day == nil { - return 0 - } - return *p.Day -} - -// GetHour returns the Hour field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetHour() int { - if p == nil || p.Hour == nil { - return 0 - } - return *p.Hour -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetAfter() string { - if p == nil || p.After == nil { - return "" - } - return *p.After -} - -// GetBaseRef returns the BaseRef field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBaseRef() string { - if p == nil || p.BaseRef == nil { - return "" - } - return *p.BaseRef -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBefore() string { - if p == nil || p.Before == nil { - return "" - } - return *p.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCompare() string { - if p == nil || p.Compare == nil { - return "" - } - return *p.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCreated() bool { - if p == nil || p.Created == nil { - return false - } - return *p.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDeleted() bool { - if p == nil || p.Deleted == nil { - return false - } - return *p.Deleted -} - -// GetDistinctSize returns the DistinctSize field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDistinctSize() int { - if p == nil || p.DistinctSize == nil { - return 0 - } - return *p.DistinctSize -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetForced() bool { - if p == nil || p.Forced == nil { - return false - } - return *p.Forced -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetHead() string { - if p == nil || p.Head == nil { - return "" - } - return *p.Head -} - -// GetHeadCommit returns the HeadCommit field. -func (p *PushEvent) GetHeadCommit() *PushEventCommit { - if p == nil { - return nil - } - return p.HeadCommit -} - -// GetInstallation returns the Installation field. -func (p *PushEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetPusher returns the Pusher field. -func (p *PushEvent) GetPusher() *User { - if p == nil { - return nil - } - return p.Pusher -} - -// GetPushID returns the PushID field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetPushID() int64 { - if p == nil || p.PushID == nil { - return 0 - } - return *p.PushID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetRepo returns the Repo field. -func (p *PushEvent) GetRepo() *PushEventRepository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PushEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetAuthor returns the Author field. -func (p *PushEventCommit) GetAuthor() *CommitAuthor { - if p == nil { - return nil - } - return p.Author -} - -// GetCommitter returns the Committer field. -func (p *PushEventCommit) GetCommitter() *CommitAuthor { - if p == nil { - return nil - } - return p.Committer -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetDistinct() bool { - if p == nil || p.Distinct == nil { - return false - } - return *p.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetID() string { - if p == nil || p.ID == nil { - return "" - } - return *p.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTimestamp() Timestamp { - if p == nil || p.Timestamp == nil { - return Timestamp{} - } - return *p.Timestamp -} - -// GetTreeID returns the TreeID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTreeID() string { - if p == nil || p.TreeID == nil { - return "" - } - return *p.TreeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetEmail() string { - if p == nil || p.Email == nil { - return "" - } - return *p.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetArchiveURL() string { - if p == nil || p.ArchiveURL == nil { - return "" - } - return *p.ArchiveURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCloneURL() string { - if p == nil || p.CloneURL == nil { - return "" - } - return *p.CloneURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDefaultBranch() string { - if p == nil || p.DefaultBranch == nil { - return "" - } - return *p.DefaultBranch -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDescription() string { - if p == nil || p.Description == nil { - return "" - } - return *p.Description -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFork() bool { - if p == nil || p.Fork == nil { - return false - } - return *p.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetForksCount() int { - if p == nil || p.ForksCount == nil { - return 0 - } - return *p.ForksCount -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFullName() string { - if p == nil || p.FullName == nil { - return "" - } - return *p.FullName -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetGitURL() string { - if p == nil || p.GitURL == nil { - return "" - } - return *p.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasDownloads() bool { - if p == nil || p.HasDownloads == nil { - return false - } - return *p.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasIssues() bool { - if p == nil || p.HasIssues == nil { - return false - } - return *p.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasPages() bool { - if p == nil || p.HasPages == nil { - return false - } - return *p.HasPages -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasWiki() bool { - if p == nil || p.HasWiki == nil { - return false - } - return *p.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHomepage() string { - if p == nil || p.Homepage == nil { - return "" - } - return *p.Homepage -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetLanguage() string { - if p == nil || p.Language == nil { - return "" - } - return *p.Language -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetMasterBranch() string { - if p == nil || p.MasterBranch == nil { - return "" - } - return *p.MasterBranch -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOpenIssuesCount() int { - if p == nil || p.OpenIssuesCount == nil { - return 0 - } - return *p.OpenIssuesCount -} - -// GetOrganization returns the Organization field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOrganization() string { - if p == nil || p.Organization == nil { - return "" - } - return *p.Organization -} - -// GetOwner returns the Owner field. -func (p *PushEventRepository) GetOwner() *User { - if p == nil { - return nil - } - return p.Owner -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPrivate() bool { - if p == nil || p.Private == nil { - return false - } - return *p.Private -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPushedAt() Timestamp { - if p == nil || p.PushedAt == nil { - return Timestamp{} - } - return *p.PushedAt -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSSHURL() string { - if p == nil || p.SSHURL == nil { - return "" - } - return *p.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStargazersCount() int { - if p == nil || p.StargazersCount == nil { - return 0 - } - return *p.StargazersCount -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSVNURL() string { - if p == nil || p.SVNURL == nil { - return "" - } - return *p.SVNURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetWatchersCount() int { - if p == nil || p.WatchersCount == nil { - return 0 - } - return *p.WatchersCount -} - -// GetCore returns the Core field. -func (r *RateLimits) GetCore() *Rate { - if r == nil { - return nil - } - return r.Core -} - -// GetSearch returns the Search field. -func (r *RateLimits) GetSearch() *Rate { - if r == nil { - return nil - } - return r.Search -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *Reaction) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Reaction) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *Reaction) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetUser returns the User field. -func (r *Reaction) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetConfused returns the Confused field if it's non-nil, zero value otherwise. -func (r *Reactions) GetConfused() int { - if r == nil || r.Confused == nil { - return 0 - } - return *r.Confused -} - -// GetHeart returns the Heart field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHeart() int { - if r == nil || r.Heart == nil { - return 0 - } - return *r.Heart -} - -// GetHooray returns the Hooray field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHooray() int { - if r == nil || r.Hooray == nil { - return 0 - } - return *r.Hooray -} - -// GetLaugh returns the Laugh field if it's non-nil, zero value otherwise. -func (r *Reactions) GetLaugh() int { - if r == nil || r.Laugh == nil { - return 0 - } - return *r.Laugh -} - -// GetMinusOne returns the MinusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetMinusOne() int { - if r == nil || r.MinusOne == nil { - return 0 - } - return *r.MinusOne -} - -// GetPlusOne returns the PlusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetPlusOne() int { - if r == nil || r.PlusOne == nil { - return 0 - } - return *r.PlusOne -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (r *Reactions) GetTotalCount() int { - if r == nil || r.TotalCount == nil { - return 0 - } - return *r.TotalCount -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reactions) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *Reference) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetObject returns the Object field. -func (r *Reference) GetObject() *GitObject { - if r == nil { - return nil - } - return r.Object -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (r *Reference) GetRef() string { - if r == nil || r.Ref == nil { - return "" - } - return *r.Ref -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reference) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBrowserDownloadURL returns the BrowserDownloadURL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetBrowserDownloadURL() string { - if r == nil || r.BrowserDownloadURL == nil { - return "" - } - return *r.BrowserDownloadURL -} - -// GetContentType returns the ContentType field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetContentType() string { - if r == nil || r.ContentType == nil { - return "" - } - return *r.ContentType -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDownloadCount returns the DownloadCount field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetDownloadCount() int { - if r == nil || r.DownloadCount == nil { - return 0 - } - return *r.DownloadCount -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetLabel() string { - if r == nil || r.Label == nil { - return "" - } - return *r.Label -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetUploader returns the Uploader field. -func (r *ReleaseAsset) GetUploader() *User { - if r == nil { - return nil - } - return r.Uploader -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *ReleaseEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetInstallation returns the Installation field. -func (r *ReleaseEvent) GetInstallation() *Installation { - if r == nil { - return nil - } - return r.Installation -} - -// GetRelease returns the Release field. -func (r *ReleaseEvent) GetRelease() *RepositoryRelease { - if r == nil { - return nil - } - return r.Release -} - -// GetRepo returns the Repo field. -func (r *ReleaseEvent) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetSender returns the Sender field. -func (r *ReleaseEvent) GetSender() *User { - if r == nil { - return nil - } - return r.Sender -} - -// GetFrom returns the From field if it's non-nil, zero value otherwise. -func (r *Rename) GetFrom() string { - if r == nil || r.From == nil { - return "" - } - return *r.From -} - -// GetTo returns the To field if it's non-nil, zero value otherwise. -func (r *Rename) GetTo() string { - if r == nil || r.To == nil { - return "" - } - return *r.To -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetIncompleteResults() bool { - if r == nil || r.IncompleteResults == nil { - return false - } - return *r.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetTotal() int { - if r == nil || r.Total == nil { - return 0 - } - return *r.Total -} - -// GetAllowMergeCommit returns the AllowMergeCommit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowMergeCommit() bool { - if r == nil || r.AllowMergeCommit == nil { - return false - } - return *r.AllowMergeCommit -} - -// GetAllowRebaseMerge returns the AllowRebaseMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowRebaseMerge() bool { - if r == nil || r.AllowRebaseMerge == nil { - return false - } - return *r.AllowRebaseMerge -} - -// GetAllowSquashMerge returns the AllowSquashMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowSquashMerge() bool { - if r == nil || r.AllowSquashMerge == nil { - return false - } - return *r.AllowSquashMerge -} - -// GetArchived returns the Archived field if it's non-nil, zero value otherwise. -func (r *Repository) GetArchived() bool { - if r == nil || r.Archived == nil { - return false - } - return *r.Archived -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetArchiveURL() string { - if r == nil || r.ArchiveURL == nil { - return "" - } - return *r.ArchiveURL -} - -// GetAssigneesURL returns the AssigneesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetAssigneesURL() string { - if r == nil || r.AssigneesURL == nil { - return "" - } - return *r.AssigneesURL -} - -// GetAutoInit returns the AutoInit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAutoInit() bool { - if r == nil || r.AutoInit == nil { - return false - } - return *r.AutoInit -} - -// GetBlobsURL returns the BlobsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBlobsURL() string { - if r == nil || r.BlobsURL == nil { - return "" - } - return *r.BlobsURL -} - -// GetBranchesURL returns the BranchesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBranchesURL() string { - if r == nil || r.BranchesURL == nil { - return "" - } - return *r.BranchesURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCloneURL() string { - if r == nil || r.CloneURL == nil { - return "" - } - return *r.CloneURL -} - -// GetCodeOfConduct returns the CodeOfConduct field. -func (r *Repository) GetCodeOfConduct() *CodeOfConduct { - if r == nil { - return nil - } - return r.CodeOfConduct -} - -// GetCollaboratorsURL returns the CollaboratorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCollaboratorsURL() string { - if r == nil || r.CollaboratorsURL == nil { - return "" - } - return *r.CollaboratorsURL -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetCommitsURL returns the CommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommitsURL() string { - if r == nil || r.CommitsURL == nil { - return "" - } - return *r.CommitsURL -} - -// GetCompareURL returns the CompareURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCompareURL() string { - if r == nil || r.CompareURL == nil { - return "" - } - return *r.CompareURL -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContentsURL() string { - if r == nil || r.ContentsURL == nil { - return "" - } - return *r.ContentsURL -} - -// GetContributorsURL returns the ContributorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContributorsURL() string { - if r == nil || r.ContributorsURL == nil { - return "" - } - return *r.ContributorsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetDefaultBranch() string { - if r == nil || r.DefaultBranch == nil { - return "" - } - return *r.DefaultBranch -} - -// GetDeploymentsURL returns the DeploymentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDeploymentsURL() string { - if r == nil || r.DeploymentsURL == nil { - return "" - } - return *r.DeploymentsURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *Repository) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetDownloadsURL returns the DownloadsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDownloadsURL() string { - if r == nil || r.DownloadsURL == nil { - return "" - } - return *r.DownloadsURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetEventsURL() string { - if r == nil || r.EventsURL == nil { - return "" - } - return *r.EventsURL -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (r *Repository) GetFork() bool { - if r == nil || r.Fork == nil { - return false - } - return *r.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksCount() int { - if r == nil || r.ForksCount == nil { - return 0 - } - return *r.ForksCount -} - -// GetForksURL returns the ForksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksURL() string { - if r == nil || r.ForksURL == nil { - return "" - } - return *r.ForksURL -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (r *Repository) GetFullName() string { - if r == nil || r.FullName == nil { - return "" - } - return *r.FullName -} - -// GetGitCommitsURL returns the GitCommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitCommitsURL() string { - if r == nil || r.GitCommitsURL == nil { - return "" - } - return *r.GitCommitsURL -} - -// GetGitignoreTemplate returns the GitignoreTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitignoreTemplate() string { - if r == nil || r.GitignoreTemplate == nil { - return "" - } - return *r.GitignoreTemplate -} - -// GetGitRefsURL returns the GitRefsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitRefsURL() string { - if r == nil || r.GitRefsURL == nil { - return "" - } - return *r.GitRefsURL -} - -// GetGitTagsURL returns the GitTagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitTagsURL() string { - if r == nil || r.GitTagsURL == nil { - return "" - } - return *r.GitTagsURL -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasDownloads() bool { - if r == nil || r.HasDownloads == nil { - return false - } - return *r.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasIssues() bool { - if r == nil || r.HasIssues == nil { - return false - } - return *r.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasPages() bool { - if r == nil || r.HasPages == nil { - return false - } - return *r.HasPages -} - -// GetHasProjects returns the HasProjects field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasProjects() bool { - if r == nil || r.HasProjects == nil { - return false - } - return *r.HasProjects -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasWiki() bool { - if r == nil || r.HasWiki == nil { - return false - } - return *r.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (r *Repository) GetHomepage() string { - if r == nil || r.Homepage == nil { - return "" - } - return *r.Homepage -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHooksURL() string { - if r == nil || r.HooksURL == nil { - return "" - } - return *r.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Repository) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetIssueCommentURL returns the IssueCommentURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueCommentURL() string { - if r == nil || r.IssueCommentURL == nil { - return "" - } - return *r.IssueCommentURL -} - -// GetIssueEventsURL returns the IssueEventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueEventsURL() string { - if r == nil || r.IssueEventsURL == nil { - return "" - } - return *r.IssueEventsURL -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssuesURL() string { - if r == nil || r.IssuesURL == nil { - return "" - } - return *r.IssuesURL -} - -// GetKeysURL returns the KeysURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetKeysURL() string { - if r == nil || r.KeysURL == nil { - return "" - } - return *r.KeysURL -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLabelsURL() string { - if r == nil || r.LabelsURL == nil { - return "" - } - return *r.LabelsURL -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguage() string { - if r == nil || r.Language == nil { - return "" - } - return *r.Language -} - -// GetLanguagesURL returns the LanguagesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguagesURL() string { - if r == nil || r.LanguagesURL == nil { - return "" - } - return *r.LanguagesURL -} - -// GetLicense returns the License field. -func (r *Repository) GetLicense() *License { - if r == nil { - return nil - } - return r.License -} - -// GetLicenseTemplate returns the LicenseTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetLicenseTemplate() string { - if r == nil || r.LicenseTemplate == nil { - return "" - } - return *r.LicenseTemplate -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetMasterBranch() string { - if r == nil || r.MasterBranch == nil { - return "" - } - return *r.MasterBranch -} - -// GetMergesURL returns the MergesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMergesURL() string { - if r == nil || r.MergesURL == nil { - return "" - } - return *r.MergesURL -} - -// GetMilestonesURL returns the MilestonesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMilestonesURL() string { - if r == nil || r.MilestonesURL == nil { - return "" - } - return *r.MilestonesURL -} - -// GetMirrorURL returns the MirrorURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMirrorURL() string { - if r == nil || r.MirrorURL == nil { - return "" - } - return *r.MirrorURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *Repository) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNetworkCount returns the NetworkCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetNetworkCount() int { - if r == nil || r.NetworkCount == nil { - return 0 - } - return *r.NetworkCount -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *Repository) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetNotificationsURL returns the NotificationsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetNotificationsURL() string { - if r == nil || r.NotificationsURL == nil { - return "" - } - return *r.NotificationsURL -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetOpenIssuesCount() int { - if r == nil || r.OpenIssuesCount == nil { - return 0 - } - return *r.OpenIssuesCount -} - -// GetOrganization returns the Organization field. -func (r *Repository) GetOrganization() *Organization { - if r == nil { - return nil - } - return r.Organization -} - -// GetOwner returns the Owner field. -func (r *Repository) GetOwner() *User { - if r == nil { - return nil - } - return r.Owner -} - -// GetParent returns the Parent field. -func (r *Repository) GetParent() *Repository { - if r == nil { - return nil - } - return r.Parent -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *Repository) GetPermissions() map[string]bool { - if r == nil || r.Permissions == nil { - return map[string]bool{} - } - return *r.Permissions -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (r *Repository) GetPrivate() bool { - if r == nil || r.Private == nil { - return false - } - return *r.Private -} - -// GetPullsURL returns the PullsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetPullsURL() string { - if r == nil || r.PullsURL == nil { - return "" - } - return *r.PullsURL -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetPushedAt() Timestamp { - if r == nil || r.PushedAt == nil { - return Timestamp{} - } - return *r.PushedAt -} - -// GetReleasesURL returns the ReleasesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetReleasesURL() string { - if r == nil || r.ReleasesURL == nil { - return "" - } - return *r.ReleasesURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *Repository) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetSource returns the Source field. -func (r *Repository) GetSource() *Repository { - if r == nil { - return nil - } - return r.Source -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSSHURL() string { - if r == nil || r.SSHURL == nil { - return "" - } - return *r.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersCount() int { - if r == nil || r.StargazersCount == nil { - return 0 - } - return *r.StargazersCount -} - -// GetStargazersURL returns the StargazersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersURL() string { - if r == nil || r.StargazersURL == nil { - return "" - } - return *r.StargazersURL -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStatusesURL() string { - if r == nil || r.StatusesURL == nil { - return "" - } - return *r.StatusesURL -} - -// GetSubscribersCount returns the SubscribersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersCount() int { - if r == nil || r.SubscribersCount == nil { - return 0 - } - return *r.SubscribersCount -} - -// GetSubscribersURL returns the SubscribersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersURL() string { - if r == nil || r.SubscribersURL == nil { - return "" - } - return *r.SubscribersURL -} - -// GetSubscriptionURL returns the SubscriptionURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscriptionURL() string { - if r == nil || r.SubscriptionURL == nil { - return "" - } - return *r.SubscriptionURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSVNURL() string { - if r == nil || r.SVNURL == nil { - return "" - } - return *r.SVNURL -} - -// GetTagsURL returns the TagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTagsURL() string { - if r == nil || r.TagsURL == nil { - return "" - } - return *r.TagsURL -} - -// GetTeamID returns the TeamID field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamID() int64 { - if r == nil || r.TeamID == nil { - return 0 - } - return *r.TeamID -} - -// GetTeamsURL returns the TeamsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamsURL() string { - if r == nil || r.TeamsURL == nil { - return "" - } - return *r.TeamsURL -} - -// GetTreesURL returns the TreesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTreesURL() string { - if r == nil || r.TreesURL == nil { - return "" - } - return *r.TreesURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Repository) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetWatchersCount() int { - if r == nil || r.WatchersCount == nil { - return 0 - } - return *r.WatchersCount -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCommitID() string { - if r == nil || r.CommitID == nil { - return "" - } - return *r.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPosition() int { - if r == nil || r.Position == nil { - return 0 - } - return *r.Position -} - -// GetReactions returns the Reactions field. -func (r *RepositoryComment) GetReactions() *Reactions { - if r == nil { - return nil - } - return r.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetUser returns the User field. -func (r *RepositoryComment) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetAuthor returns the Author field. -func (r *RepositoryCommit) GetAuthor() *User { - if r == nil { - return nil - } - return r.Author -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetCommit returns the Commit field. -func (r *RepositoryCommit) GetCommit() *Commit { - if r == nil { - return nil - } - return r.Commit -} - -// GetCommitter returns the Committer field. -func (r *RepositoryCommit) GetCommitter() *User { - if r == nil { - return nil - } - return r.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetStats returns the Stats field. -func (r *RepositoryCommit) GetStats() *CommitStats { - if r == nil { - return nil - } - return r.Stats -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetAuthor returns the Author field. -func (r *RepositoryContentFileOptions) GetAuthor() *CommitAuthor { - if r == nil { - return nil - } - return r.Author -} - -// GetBranch returns the Branch field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetBranch() string { - if r == nil || r.Branch == nil { - return "" - } - return *r.Branch -} - -// GetCommitter returns the Committer field. -func (r *RepositoryContentFileOptions) GetCommitter() *CommitAuthor { - if r == nil { - return nil - } - return r.Committer -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetMessage() string { - if r == nil || r.Message == nil { - return "" - } - return *r.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetContent returns the Content field. -func (r *RepositoryContentResponse) GetContent() *RepositoryContent { - if r == nil { - return nil - } - return r.Content -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *RepositoryEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetInstallation returns the Installation field. -func (r *RepositoryEvent) GetInstallation() *Installation { - if r == nil { - return nil - } - return r.Installation -} - -// GetOrg returns the Org field. -func (r *RepositoryEvent) GetOrg() *Organization { - if r == nil { - return nil - } - return r.Org -} - -// GetRepo returns the Repo field. -func (r *RepositoryEvent) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetSender returns the Sender field. -func (r *RepositoryEvent) GetSender() *User { - if r == nil { - return nil - } - return r.Sender -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetInvitee returns the Invitee field. -func (r *RepositoryInvitation) GetInvitee() *User { - if r == nil { - return nil - } - return r.Invitee -} - -// GetInviter returns the Inviter field. -func (r *RepositoryInvitation) GetInviter() *User { - if r == nil { - return nil - } - return r.Inviter -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetPermissions() string { - if r == nil || r.Permissions == nil { - return "" - } - return *r.Permissions -} - -// GetRepo returns the Repo field. -func (r *RepositoryInvitation) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetLicense returns the License field. -func (r *RepositoryLicense) GetLicense() *License { - if r == nil { - return nil - } - return r.License -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetBase() string { - if r == nil || r.Base == nil { - return "" - } - return *r.Base -} - -// GetCommitMessage returns the CommitMessage field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetCommitMessage() string { - if r == nil || r.CommitMessage == nil { - return "" - } - return *r.CommitMessage -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetHead() string { - if r == nil || r.Head == nil { - return "" - } - return *r.Head -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (r *RepositoryPermissionLevel) GetPermission() string { - if r == nil || r.Permission == nil { - return "" - } - return *r.Permission -} - -// GetUser returns the User field. -func (r *RepositoryPermissionLevel) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetAssetsURL returns the AssetsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetAssetsURL() string { - if r == nil || r.AssetsURL == nil { - return "" - } - return *r.AssetsURL -} - -// GetAuthor returns the Author field. -func (r *RepositoryRelease) GetAuthor() *User { - if r == nil { - return nil - } - return r.Author -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDraft returns the Draft field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetDraft() bool { - if r == nil || r.Draft == nil { - return false - } - return *r.Draft -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetPrerelease returns the Prerelease field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPrerelease() bool { - if r == nil || r.Prerelease == nil { - return false - } - return *r.Prerelease -} - -// GetPublishedAt returns the PublishedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPublishedAt() Timestamp { - if r == nil || r.PublishedAt == nil { - return Timestamp{} - } - return *r.PublishedAt -} - -// GetTagName returns the TagName field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTagName() string { - if r == nil || r.TagName == nil { - return "" - } - return *r.TagName -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetTargetCommitish returns the TargetCommitish field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTargetCommitish() string { - if r == nil || r.TargetCommitish == nil { - return "" - } - return *r.TargetCommitish -} - -// GetUploadURL returns the UploadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetUploadURL() string { - if r == nil || r.UploadURL == nil { - return "" - } - return *r.UploadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetCommit returns the Commit field. -func (r *RepositoryTag) GetCommit() *Commit { - if r == nil { - return nil - } - return r.Commit -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetForkRepos returns the ForkRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetForkRepos() int { - if r == nil || r.ForkRepos == nil { - return 0 - } - return *r.ForkRepos -} - -// GetOrgRepos returns the OrgRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetOrgRepos() int { - if r == nil || r.OrgRepos == nil { - return 0 - } - return *r.OrgRepos -} - -// GetRootRepos returns the RootRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetRootRepos() int { - if r == nil || r.RootRepos == nil { - return 0 - } - return *r.RootRepos -} - -// GetTotalPushes returns the TotalPushes field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalPushes() int { - if r == nil || r.TotalPushes == nil { - return 0 - } - return *r.TotalPushes -} - -// GetTotalRepos returns the TotalRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalRepos() int { - if r == nil || r.TotalRepos == nil { - return 0 - } - return *r.TotalRepos -} - -// GetTotalWikis returns the TotalWikis field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalWikis() int { - if r == nil || r.TotalWikis == nil { - return 0 - } - return *r.TotalWikis -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetContext() string { - if r == nil || r.Context == nil { - return "" - } - return *r.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetCreator returns the Creator field. -func (r *RepoStatus) GetCreator() *User { - if r == nil { - return nil - } - return r.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetTargetURL() string { - if r == nil || r.TargetURL == nil { - return "" - } - return *r.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetStrict returns the Strict field if it's non-nil, zero value otherwise. -func (r *RequiredStatusChecksRequest) GetStrict() bool { - if r == nil || r.Strict == nil { - return false - } - return *r.Strict -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *ServiceHook) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetPayload() string { - if s == nil || s.Payload == nil { - return "" - } - return *s.Payload -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetSignature returns the Signature field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetSignature() string { - if s == nil || s.Signature == nil { - return "" - } - return *s.Signature -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetVerified() bool { - if s == nil || s.Verified == nil { - return false - } - return *s.Verified -} - -// GetActor returns the Actor field. -func (s *Source) GetActor() *User { - if s == nil { - return nil - } - return s.Actor -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *Source) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Source) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetEmail() string { - if s == nil || s.Email == nil { - return "" - } - return *s.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetImportURL returns the ImportURL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetImportURL() string { - if s == nil || s.ImportURL == nil { - return "" - } - return *s.ImportURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetRemoteID returns the RemoteID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteID() string { - if s == nil || s.RemoteID == nil { - return "" - } - return *s.RemoteID -} - -// GetRemoteName returns the RemoteName field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteName() string { - if s == nil || s.RemoteName == nil { - return "" - } - return *s.RemoteName -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *Stargazer) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetUser returns the User field. -func (s *Stargazer) GetUser() *User { - if s == nil { - return nil - } - return s.User -} - -// GetRepository returns the Repository field. -func (s *StarredRepository) GetRepository() *Repository { - if s == nil { - return nil - } - return s.Repository -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *StarredRepository) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetCommit returns the Commit field. -func (s *StatusEvent) GetCommit() *RepositoryCommit { - if s == nil { - return nil - } - return s.Commit -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetContext() string { - if s == nil || s.Context == nil { - return "" - } - return *s.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetDescription() string { - if s == nil || s.Description == nil { - return "" - } - return *s.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetInstallation returns the Installation field. -func (s *StatusEvent) GetInstallation() *Installation { - if s == nil { - return nil - } - return s.Installation -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetRepo returns the Repo field. -func (s *StatusEvent) GetRepo() *Repository { - if s == nil { - return nil - } - return s.Repo -} - -// GetSender returns the Sender field. -func (s *StatusEvent) GetSender() *User { - if s == nil { - return nil - } - return s.Sender -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetSHA() string { - if s == nil || s.SHA == nil { - return "" - } - return *s.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetState() string { - if s == nil || s.State == nil { - return "" - } - return *s.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetTargetURL() string { - if s == nil || s.TargetURL == nil { - return "" - } - return *s.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetUpdatedAt() Timestamp { - if s == nil || s.UpdatedAt == nil { - return Timestamp{} - } - return *s.UpdatedAt -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *Subscription) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetIgnored returns the Ignored field if it's non-nil, zero value otherwise. -func (s *Subscription) GetIgnored() bool { - if s == nil || s.Ignored == nil { - return false - } - return *s.Ignored -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *Subscription) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetRepositoryURL() string { - if s == nil || s.RepositoryURL == nil { - return "" - } - return *s.RepositoryURL -} - -// GetSubscribed returns the Subscribed field if it's non-nil, zero value otherwise. -func (s *Subscription) GetSubscribed() bool { - if s == nil || s.Subscribed == nil { - return false - } - return *s.Subscribed -} - -// GetThreadURL returns the ThreadURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetThreadURL() string { - if s == nil || s.ThreadURL == nil { - return "" - } - return *s.ThreadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (t *Tag) GetMessage() string { - if t == nil || t.Message == nil { - return "" - } - return *t.Message -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (t *Tag) GetNodeID() string { - if t == nil || t.NodeID == nil { - return "" - } - return *t.NodeID -} - -// GetObject returns the Object field. -func (t *Tag) GetObject() *GitObject { - if t == nil { - return nil - } - return t.Object -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tag) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetTag returns the Tag field if it's non-nil, zero value otherwise. -func (t *Tag) GetTag() string { - if t == nil || t.Tag == nil { - return "" - } - return *t.Tag -} - -// GetTagger returns the Tagger field. -func (t *Tag) GetTagger() *CommitAuthor { - if t == nil { - return nil - } - return t.Tagger -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Tag) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetVerification returns the Verification field. -func (t *Tag) GetVerification() *SignatureVerification { - if t == nil { - return nil - } - return t.Verification -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *Team) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Team) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *Team) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersCount returns the MembersCount field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersCount() int { - if t == nil || t.MembersCount == nil { - return 0 - } - return *t.MembersCount -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *Team) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetOrganization returns the Organization field. -func (t *Team) GetOrganization() *Organization { - if t == nil { - return nil - } - return t.Organization -} - -// GetParent returns the Parent field. -func (t *Team) GetParent() *Team { - if t == nil { - return nil - } - return t.Parent -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *Team) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *Team) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetReposCount returns the ReposCount field if it's non-nil, zero value otherwise. -func (t *Team) GetReposCount() int { - if t == nil || t.ReposCount == nil { - return 0 - } - return *t.ReposCount -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *Team) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *Team) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Team) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetInstallation returns the Installation field. -func (t *TeamAddEvent) GetInstallation() *Installation { - if t == nil { - return nil - } - return t.Installation -} - -// GetOrg returns the Org field. -func (t *TeamAddEvent) GetOrg() *Organization { - if t == nil { - return nil - } - return t.Org -} - -// GetRepo returns the Repo field. -func (t *TeamAddEvent) GetRepo() *Repository { - if t == nil { - return nil - } - return t.Repo -} - -// GetSender returns the Sender field. -func (t *TeamAddEvent) GetSender() *User { - if t == nil { - return nil - } - return t.Sender -} - -// GetTeam returns the Team field. -func (t *TeamAddEvent) GetTeam() *Team { - if t == nil { - return nil - } - return t.Team -} - -// GetAuthor returns the Author field. -func (t *TeamDiscussion) GetAuthor() *User { - if t == nil { - return nil - } - return t.Author -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetBody() string { - if t == nil || t.Body == nil { - return "" - } - return *t.Body -} - -// GetBodyHTML returns the BodyHTML field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetBodyHTML() string { - if t == nil || t.BodyHTML == nil { - return "" - } - return *t.BodyHTML -} - -// GetBodyVersion returns the BodyVersion field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetBodyVersion() string { - if t == nil || t.BodyVersion == nil { - return "" - } - return *t.BodyVersion -} - -// GetCommentsCount returns the CommentsCount field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetCommentsCount() int { - if t == nil || t.CommentsCount == nil { - return 0 - } - return *t.CommentsCount -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetCommentsURL() string { - if t == nil || t.CommentsURL == nil { - return "" - } - return *t.CommentsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetCreatedAt() Timestamp { - if t == nil || t.CreatedAt == nil { - return Timestamp{} - } - return *t.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetHTMLURL() string { - if t == nil || t.HTMLURL == nil { - return "" - } - return *t.HTMLURL -} - -// GetLastEditedAt returns the LastEditedAt field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetLastEditedAt() Timestamp { - if t == nil || t.LastEditedAt == nil { - return Timestamp{} - } - return *t.LastEditedAt -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetNodeID() string { - if t == nil || t.NodeID == nil { - return "" - } - return *t.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetNumber() int { - if t == nil || t.Number == nil { - return 0 - } - return *t.Number -} - -// GetPinned returns the Pinned field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetPinned() bool { - if t == nil || t.Pinned == nil { - return false - } - return *t.Pinned -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetPrivate() bool { - if t == nil || t.Private == nil { - return false - } - return *t.Private -} - -// GetReactions returns the Reactions field. -func (t *TeamDiscussion) GetReactions() *Reactions { - if t == nil { - return nil - } - return t.Reactions -} - -// GetTeamURL returns the TeamURL field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetTeamURL() string { - if t == nil || t.TeamURL == nil { - return "" - } - return *t.TeamURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetTitle() string { - if t == nil || t.Title == nil { - return "" - } - return *t.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetUpdatedAt() Timestamp { - if t == nil || t.UpdatedAt == nil { - return Timestamp{} - } - return *t.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TeamDiscussion) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (t *TeamEvent) GetAction() string { - if t == nil || t.Action == nil { - return "" - } - return *t.Action -} - -// GetChanges returns the Changes field. -func (t *TeamEvent) GetChanges() *TeamChange { - if t == nil { - return nil - } - return t.Changes -} - -// GetInstallation returns the Installation field. -func (t *TeamEvent) GetInstallation() *Installation { - if t == nil { - return nil - } - return t.Installation -} - -// GetOrg returns the Org field. -func (t *TeamEvent) GetOrg() *Organization { - if t == nil { - return nil - } - return t.Org -} - -// GetRepo returns the Repo field. -func (t *TeamEvent) GetRepo() *Repository { - if t == nil { - return nil - } - return t.Repo -} - -// GetSender returns the Sender field. -func (t *TeamEvent) GetSender() *User { - if t == nil { - return nil - } - return t.Sender -} - -// GetTeam returns the Team field. -func (t *TeamEvent) GetTeam() *Team { - if t == nil { - return nil - } - return t.Team -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetFragment returns the Fragment field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetFragment() string { - if t == nil || t.Fragment == nil { - return "" - } - return *t.Fragment -} - -// GetObjectType returns the ObjectType field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectType() string { - if t == nil || t.ObjectType == nil { - return "" - } - return *t.ObjectType -} - -// GetObjectURL returns the ObjectURL field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectURL() string { - if t == nil || t.ObjectURL == nil { - return "" - } - return *t.ObjectURL -} - -// GetProperty returns the Property field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetProperty() string { - if t == nil || t.Property == nil { - return "" - } - return *t.Property -} - -// GetActor returns the Actor field. -func (t *Timeline) GetActor() *User { - if t == nil { - return nil - } - return t.Actor -} - -// GetAssignee returns the Assignee field. -func (t *Timeline) GetAssignee() *User { - if t == nil { - return nil - } - return t.Assignee -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitID() string { - if t == nil || t.CommitID == nil { - return "" - } - return *t.CommitID -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitURL() string { - if t == nil || t.CommitURL == nil { - return "" - } - return *t.CommitURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCreatedAt() time.Time { - if t == nil || t.CreatedAt == nil { - return time.Time{} - } - return *t.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (t *Timeline) GetEvent() string { - if t == nil || t.Event == nil { - return "" - } - return *t.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLabel returns the Label field. -func (t *Timeline) GetLabel() *Label { - if t == nil { - return nil - } - return t.Label -} - -// GetMilestone returns the Milestone field. -func (t *Timeline) GetMilestone() *Milestone { - if t == nil { - return nil - } - return t.Milestone -} - -// GetRename returns the Rename field. -func (t *Timeline) GetRename() *Rename { - if t == nil { - return nil - } - return t.Rename -} - -// GetSource returns the Source field. -func (t *Timeline) GetSource() *Source { - if t == nil { - return nil - } - return t.Source -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetTimestamp() Timestamp { - if t == nil || t.Timestamp == nil { - return Timestamp{} - } - return *t.Timestamp -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetTitle() string { - if t == nil || t.Title == nil { - return "" - } - return *t.Title -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetReferrer returns the Referrer field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetReferrer() string { - if t == nil || t.Referrer == nil { - return "" - } - return *t.Referrer -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tree) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetTruncated returns the Truncated field if it's non-nil, zero value otherwise. -func (t *Tree) GetTruncated() bool { - if t == nil || t.Truncated == nil { - return false - } - return *t.Truncated -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetContent() string { - if t == nil || t.Content == nil { - return "" - } - return *t.Content -} - -// GetMode returns the Mode field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetMode() string { - if t == nil || t.Mode == nil { - return "" - } - return *t.Mode -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSize() int { - if t == nil || t.Size == nil { - return 0 - } - return *t.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetType() string { - if t == nil || t.Type == nil { - return "" - } - return *t.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetCompletedAt returns the CompletedAt field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetCompletedAt() Timestamp { - if u == nil || u.CompletedAt == nil { - return Timestamp{} - } - return *u.CompletedAt -} - -// GetConclusion returns the Conclusion field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetConclusion() string { - if u == nil || u.Conclusion == nil { - return "" - } - return *u.Conclusion -} - -// GetDetailsURL returns the DetailsURL field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetDetailsURL() string { - if u == nil || u.DetailsURL == nil { - return "" - } - return *u.DetailsURL -} - -// GetExternalID returns the ExternalID field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetExternalID() string { - if u == nil || u.ExternalID == nil { - return "" - } - return *u.ExternalID -} - -// GetHeadBranch returns the HeadBranch field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetHeadBranch() string { - if u == nil || u.HeadBranch == nil { - return "" - } - return *u.HeadBranch -} - -// GetHeadSHA returns the HeadSHA field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetHeadSHA() string { - if u == nil || u.HeadSHA == nil { - return "" - } - return *u.HeadSHA -} - -// GetOutput returns the Output field. -func (u *UpdateCheckRunOptions) GetOutput() *CheckRunOutput { - if u == nil { - return nil - } - return u.Output -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (u *UpdateCheckRunOptions) GetStatus() string { - if u == nil || u.Status == nil { - return "" - } - return *u.Status -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *User) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetBio returns the Bio field if it's non-nil, zero value otherwise. -func (u *User) GetBio() string { - if u == nil || u.Bio == nil { - return "" - } - return *u.Bio -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (u *User) GetBlog() string { - if u == nil || u.Blog == nil { - return "" - } - return *u.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (u *User) GetCollaborators() int { - if u == nil || u.Collaborators == nil { - return 0 - } - return *u.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (u *User) GetCompany() string { - if u == nil || u.Company == nil { - return "" - } - return *u.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetCreatedAt() Timestamp { - if u == nil || u.CreatedAt == nil { - return Timestamp{} - } - return *u.CreatedAt -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (u *User) GetDiskUsage() int { - if u == nil || u.DiskUsage == nil { - return 0 - } - return *u.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *User) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (u *User) GetFollowers() int { - if u == nil || u.Followers == nil { - return 0 - } - return *u.Followers -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (u *User) GetFollowing() int { - if u == nil || u.Following == nil { - return 0 - } - return *u.Following -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *User) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *User) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetHireable returns the Hireable field if it's non-nil, zero value otherwise. -func (u *User) GetHireable() bool { - if u == nil || u.Hireable == nil { - return false - } - return *u.Hireable -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (u *User) GetHTMLURL() string { - if u == nil || u.HTMLURL == nil { - return "" - } - return *u.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *User) GetID() int64 { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (u *User) GetLocation() string { - if u == nil || u.Location == nil { - return "" - } - return *u.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *User) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (u *User) GetName() string { - if u == nil || u.Name == nil { - return "" - } - return *u.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (u *User) GetNodeID() string { - if u == nil || u.NodeID == nil { - return "" - } - return *u.NodeID -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *User) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetOwnedPrivateRepos() int { - if u == nil || u.OwnedPrivateRepos == nil { - return 0 - } - return *u.OwnedPrivateRepos -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (u *User) GetPermissions() map[string]bool { - if u == nil || u.Permissions == nil { - return map[string]bool{} - } - return *u.Permissions -} - -// GetPlan returns the Plan field. -func (u *User) GetPlan() *Plan { - if u == nil { - return nil - } - return u.Plan -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (u *User) GetPrivateGists() int { - if u == nil || u.PrivateGists == nil { - return 0 - } - return *u.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (u *User) GetPublicGists() int { - if u == nil || u.PublicGists == nil { - return 0 - } - return *u.PublicGists -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (u *User) GetPublicRepos() int { - if u == nil || u.PublicRepos == nil { - return 0 - } - return *u.PublicRepos -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *User) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *User) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *User) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *User) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetSuspendedAt returns the SuspendedAt field if it's non-nil, zero value otherwise. -func (u *User) GetSuspendedAt() Timestamp { - if u == nil || u.SuspendedAt == nil { - return Timestamp{} - } - return *u.SuspendedAt -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetTotalPrivateRepos() int { - if u == nil || u.TotalPrivateRepos == nil { - return 0 - } - return *u.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *User) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetUpdatedAt() Timestamp { - if u == nil || u.UpdatedAt == nil { - return Timestamp{} - } - return *u.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *User) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (u *UserContext) GetMessage() string { - if u == nil || u.Message == nil { - return "" - } - return *u.Message -} - -// GetOcticon returns the Octicon field if it's non-nil, zero value otherwise. -func (u *UserContext) GetOcticon() string { - if u == nil || u.Octicon == nil { - return "" - } - return *u.Octicon -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetPrimary returns the Primary field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetPrimary() bool { - if u == nil || u.Primary == nil { - return false - } - return *u.Primary -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetVerified() bool { - if u == nil || u.Verified == nil { - return false - } - return *u.Verified -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetID() int64 { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLDAPDN() string { - if u == nil || u.LDAPDN == nil { - return "" - } - return *u.LDAPDN -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetCreatedAt() string { - if u == nil || u.CreatedAt == nil { - return "" - } - return *u.CreatedAt -} - -// GetExcludeAttachments returns the ExcludeAttachments field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetExcludeAttachments() bool { - if u == nil || u.ExcludeAttachments == nil { - return false - } - return *u.ExcludeAttachments -} - -// GetGUID returns the GUID field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetGUID() string { - if u == nil || u.GUID == nil { - return "" - } - return *u.GUID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetID() int64 { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLockRepositories returns the LockRepositories field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetLockRepositories() bool { - if u == nil || u.LockRepositories == nil { - return false - } - return *u.LockRepositories -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetState() string { - if u == nil || u.State == nil { - return "" - } - return *u.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetUpdatedAt() string { - if u == nil || u.UpdatedAt == nil { - return "" - } - return *u.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *UserMigration) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetIncompleteResults() bool { - if u == nil || u.IncompleteResults == nil { - return false - } - return *u.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetTotal() int { - if u == nil || u.Total == nil { - return 0 - } - return *u.Total -} - -// GetAdminUsers returns the AdminUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetAdminUsers() int { - if u == nil || u.AdminUsers == nil { - return 0 - } - return *u.AdminUsers -} - -// GetSuspendedUsers returns the SuspendedUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetSuspendedUsers() int { - if u == nil || u.SuspendedUsers == nil { - return 0 - } - return *u.SuspendedUsers -} - -// GetTotalUsers returns the TotalUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetTotalUsers() int { - if u == nil || u.TotalUsers == nil { - return 0 - } - return *u.TotalUsers -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (w *WatchEvent) GetAction() string { - if w == nil || w.Action == nil { - return "" - } - return *w.Action -} - -// GetInstallation returns the Installation field. -func (w *WatchEvent) GetInstallation() *Installation { - if w == nil { - return nil - } - return w.Installation -} - -// GetRepo returns the Repo field. -func (w *WatchEvent) GetRepo() *Repository { - if w == nil { - return nil - } - return w.Repo -} - -// GetSender returns the Sender field. -func (w *WatchEvent) GetSender() *User { - if w == nil { - return nil - } - return w.Sender -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetEmail() string { - if w == nil || w.Email == nil { - return "" - } - return *w.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetName() string { - if w == nil || w.Name == nil { - return "" - } - return *w.Name -} - -// GetUsername returns the Username field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetUsername() string { - if w == nil || w.Username == nil { - return "" - } - return *w.Username -} - -// GetAuthor returns the Author field. -func (w *WebHookCommit) GetAuthor() *WebHookAuthor { - if w == nil { - return nil - } - return w.Author -} - -// GetCommitter returns the Committer field. -func (w *WebHookCommit) GetCommitter() *WebHookAuthor { - if w == nil { - return nil - } - return w.Committer -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetDistinct() bool { - if w == nil || w.Distinct == nil { - return false - } - return *w.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetID() string { - if w == nil || w.ID == nil { - return "" - } - return *w.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetMessage() string { - if w == nil || w.Message == nil { - return "" - } - return *w.Message -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetTimestamp() time.Time { - if w == nil || w.Timestamp == nil { - return time.Time{} - } - return *w.Timestamp -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetAfter() string { - if w == nil || w.After == nil { - return "" - } - return *w.After -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetBefore() string { - if w == nil || w.Before == nil { - return "" - } - return *w.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCompare() string { - if w == nil || w.Compare == nil { - return "" - } - return *w.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCreated() bool { - if w == nil || w.Created == nil { - return false - } - return *w.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetDeleted() bool { - if w == nil || w.Deleted == nil { - return false - } - return *w.Deleted -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetForced() bool { - if w == nil || w.Forced == nil { - return false - } - return *w.Forced -} - -// GetHeadCommit returns the HeadCommit field. -func (w *WebHookPayload) GetHeadCommit() *WebHookCommit { - if w == nil { - return nil - } - return w.HeadCommit -} - -// GetPusher returns the Pusher field. -func (w *WebHookPayload) GetPusher() *User { - if w == nil { - return nil - } - return w.Pusher -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetRef() string { - if w == nil || w.Ref == nil { - return "" - } - return *w.Ref -} - -// GetRepo returns the Repo field. -func (w *WebHookPayload) GetRepo() *Repository { - if w == nil { - return nil - } - return w.Repo -} - -// GetSender returns the Sender field. -func (w *WebHookPayload) GetSender() *User { - if w == nil { - return nil - } - return w.Sender -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetTotal() int { - if w == nil || w.Total == nil { - return 0 - } - return *w.Total -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetAdditions() int { - if w == nil || w.Additions == nil { - return 0 - } - return *w.Additions -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetCommits() int { - if w == nil || w.Commits == nil { - return 0 - } - return *w.Commits -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetDeletions() int { - if w == nil || w.Deletions == nil { - return 0 - } - return *w.Deletions -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} diff --git a/vendor/github.com/google/go-github/github/github.go b/vendor/github.com/google/go-github/github/github.go deleted file mode 100644 index af1f1b23e..000000000 --- a/vendor/github.com/google/go-github/github/github.go +++ /dev/null @@ -1,996 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run gen-accessors.go - -package github - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/google/go-querystring/query" -) - -const ( - defaultBaseURL = "https://api.github.com/" - uploadBaseURL = "https://uploads.github.com/" - userAgent = "go-github" - - headerRateLimit = "X-RateLimit-Limit" - headerRateRemaining = "X-RateLimit-Remaining" - headerRateReset = "X-RateLimit-Reset" - headerOTP = "X-GitHub-OTP" - - mediaTypeV3 = "application/vnd.github.v3+json" - defaultMediaType = "application/octet-stream" - mediaTypeV3SHA = "application/vnd.github.v3.sha" - mediaTypeV3Diff = "application/vnd.github.v3.diff" - mediaTypeV3Patch = "application/vnd.github.v3.patch" - mediaTypeOrgPermissionRepo = "application/vnd.github.v3.repository+json" - - // Media Type values to access preview APIs - - // https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/ - mediaTypeStarringPreview = "application/vnd.github.v3.star+json" - - // https://help.github.com/enterprise/2.4/admin/guides/migrations/exporting-the-github-com-organization-s-repositories/ - mediaTypeMigrationsPreview = "application/vnd.github.wyandotte-preview+json" - - // https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements/ - mediaTypeDeploymentStatusPreview = "application/vnd.github.ant-man-preview+json" - - // https://developer.github.com/changes/2016-02-19-source-import-preview-api/ - mediaTypeImportPreview = "application/vnd.github.barred-rock-preview" - - // https://developer.github.com/changes/2016-05-12-reactions-api-preview/ - mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview" - - // https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ - mediaTypeGitSigningPreview = "application/vnd.github.cryptographer-preview+json" - - // https://developer.github.com/changes/2016-05-23-timeline-preview-api/ - mediaTypeTimelinePreview = "application/vnd.github.mockingbird-preview+json" - - // https://developer.github.com/changes/2016-06-14-repository-invitations/ - mediaTypeRepositoryInvitationsPreview = "application/vnd.github.swamp-thing-preview+json" - - // https://developer.github.com/changes/2016-07-06-github-pages-preiew-api/ - mediaTypePagesPreview = "application/vnd.github.mister-fantastic-preview+json" - - // https://developer.github.com/changes/2016-09-14-projects-api/ - mediaTypeProjectsPreview = "application/vnd.github.inertia-preview+json" - - // https://developer.github.com/changes/2016-09-14-Integrations-Early-Access/ - mediaTypeIntegrationPreview = "application/vnd.github.machine-man-preview+json" - - // https://developer.github.com/changes/2017-01-05-commit-search-api/ - mediaTypeCommitSearchPreview = "application/vnd.github.cloak-preview+json" - - // https://developer.github.com/changes/2017-02-28-user-blocking-apis-and-webhook/ - mediaTypeBlockUsersPreview = "application/vnd.github.giant-sentry-fist-preview+json" - - // https://developer.github.com/changes/2017-02-09-community-health/ - mediaTypeRepositoryCommunityHealthMetricsPreview = "application/vnd.github.black-panther-preview+json" - - // https://developer.github.com/changes/2017-05-23-coc-api/ - mediaTypeCodesOfConductPreview = "application/vnd.github.scarlet-witch-preview+json" - - // https://developer.github.com/changes/2017-07-17-update-topics-on-repositories/ - mediaTypeTopicsPreview = "application/vnd.github.mercy-preview+json" - - // https://developer.github.com/changes/2017-08-30-preview-nested-teams/ - mediaTypeNestedTeamsPreview = "application/vnd.github.hellcat-preview+json" - - // https://developer.github.com/changes/2017-11-09-repository-transfer-api-preview/ - mediaTypeRepositoryTransferPreview = "application/vnd.github.nightshade-preview+json" - - // https://developer.github.com/changes/2018-01-25-organization-invitation-api-preview/ - mediaTypeOrganizationInvitationPreview = "application/vnd.github.dazzler-preview+json" - - // https://developer.github.com/changes/2018-03-16-protected-branches-required-approving-reviews/ - mediaTypeRequiredApprovingReviewsPreview = "application/vnd.github.luke-cage-preview+json" - - // https://developer.github.com/changes/2018-02-22-label-description-search-preview/ - mediaTypeLabelDescriptionSearchPreview = "application/vnd.github.symmetra-preview+json" - - // https://developer.github.com/changes/2018-02-07-team-discussions-api/ - mediaTypeTeamDiscussionsPreview = "application/vnd.github.echo-preview+json" - - // https://developer.github.com/changes/2018-03-21-hovercard-api-preview/ - mediaTypeHovercardPreview = "application/vnd.github.hagar-preview+json" - - // https://developer.github.com/changes/2018-01-10-lock-reason-api-preview/ - mediaTypeLockReasonPreview = "application/vnd.github.sailor-v-preview+json" - - // https://developer.github.com/changes/2018-05-07-new-checks-api-public-beta/ - mediaTypeCheckRunsPreview = "application/vnd.github.antiope-preview+json" - - // https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/ - mediaTypePreReceiveHooksPreview = "application/vnd.github.eye-scream-preview" -) - -// A Client manages communication with the GitHub API. -type Client struct { - clientMu sync.Mutex // clientMu protects the client during calls that modify the CheckRedirect func. - client *http.Client // HTTP client used to communicate with the API. - - // Base URL for API requests. Defaults to the public GitHub API, but can be - // set to a domain endpoint to use with GitHub Enterprise. BaseURL should - // always be specified with a trailing slash. - BaseURL *url.URL - - // Base URL for uploading files. - UploadURL *url.URL - - // User agent used when communicating with the GitHub API. - UserAgent string - - rateMu sync.Mutex - rateLimits [categories]Rate // Rate limits for the client as determined by the most recent API calls. - - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // Services used for talking to different parts of the GitHub API. - Activity *ActivityService - Admin *AdminService - Apps *AppsService - Authorizations *AuthorizationsService - Checks *ChecksService - Gists *GistsService - Git *GitService - Gitignores *GitignoresService - Issues *IssuesService - Licenses *LicensesService - Marketplace *MarketplaceService - Migrations *MigrationService - Organizations *OrganizationsService - Projects *ProjectsService - PullRequests *PullRequestsService - Reactions *ReactionsService - Repositories *RepositoriesService - Search *SearchService - Teams *TeamsService - Users *UsersService -} - -type service struct { - client *Client -} - -// ListOptions specifies the optional parameters to various List methods that -// support pagination. -type ListOptions struct { - // For paginated result sets, page of results to retrieve. - Page int `url:"page,omitempty"` - - // For paginated result sets, the number of results to include per page. - PerPage int `url:"per_page,omitempty"` -} - -// UploadOptions specifies the parameters to methods that support uploads. -type UploadOptions struct { - Name string `url:"name,omitempty"` -} - -// RawType represents type of raw format of a request instead of JSON. -type RawType uint8 - -const ( - // Diff format. - Diff RawType = 1 + iota - // Patch format. - Patch -) - -// RawOptions specifies parameters when user wants to get raw format of -// a response instead of JSON. -type RawOptions struct { - Type RawType -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) - if v.Kind() == reflect.Ptr && v.IsNil() { - return s, nil - } - - u, err := url.Parse(s) - if err != nil { - return s, err - } - - qs, err := query.Values(opt) - if err != nil { - return s, err - } - - u.RawQuery = qs.Encode() - return u.String(), nil -} - -// NewClient returns a new GitHub API client. If a nil httpClient is -// provided, http.DefaultClient will be used. To use API methods which require -// authentication, provide an http.Client that will perform the authentication -// for you (such as that provided by the golang.org/x/oauth2 library). -func NewClient(httpClient *http.Client) *Client { - if httpClient == nil { - httpClient = http.DefaultClient - } - baseURL, _ := url.Parse(defaultBaseURL) - uploadURL, _ := url.Parse(uploadBaseURL) - - c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent, UploadURL: uploadURL} - c.common.client = c - c.Activity = (*ActivityService)(&c.common) - c.Admin = (*AdminService)(&c.common) - c.Apps = (*AppsService)(&c.common) - c.Authorizations = (*AuthorizationsService)(&c.common) - c.Checks = (*ChecksService)(&c.common) - c.Gists = (*GistsService)(&c.common) - c.Git = (*GitService)(&c.common) - c.Gitignores = (*GitignoresService)(&c.common) - c.Issues = (*IssuesService)(&c.common) - c.Licenses = (*LicensesService)(&c.common) - c.Marketplace = &MarketplaceService{client: c} - c.Migrations = (*MigrationService)(&c.common) - c.Organizations = (*OrganizationsService)(&c.common) - c.Projects = (*ProjectsService)(&c.common) - c.PullRequests = (*PullRequestsService)(&c.common) - c.Reactions = (*ReactionsService)(&c.common) - c.Repositories = (*RepositoriesService)(&c.common) - c.Search = (*SearchService)(&c.common) - c.Teams = (*TeamsService)(&c.common) - c.Users = (*UsersService)(&c.common) - return c -} - -// NewEnterpriseClient returns a new GitHub API client with provided -// base URL and upload URL (often the same URL). -// If either URL does not have a trailing slash, one is added automatically. -// If a nil httpClient is provided, http.DefaultClient will be used. -// -// Note that NewEnterpriseClient is a convenience helper only; -// its behavior is equivalent to using NewClient, followed by setting -// the BaseURL and UploadURL fields. -func NewEnterpriseClient(baseURL, uploadURL string, httpClient *http.Client) (*Client, error) { - baseEndpoint, err := url.Parse(baseURL) - if err != nil { - return nil, err - } - if !strings.HasSuffix(baseEndpoint.Path, "/") { - baseEndpoint.Path += "/" - } - - uploadEndpoint, err := url.Parse(uploadURL) - if err != nil { - return nil, err - } - if !strings.HasSuffix(uploadEndpoint.Path, "/") { - uploadEndpoint.Path += "/" - } - - c := NewClient(httpClient) - c.BaseURL = baseEndpoint - c.UploadURL = uploadEndpoint - return c, nil -} - -// NewRequest creates an API request. A relative URL can be provided in urlStr, -// in which case it is resolved relative to the BaseURL of the Client. -// Relative URLs should always be specified without a preceding slash. If -// specified, the value pointed to by body is JSON encoded and included as the -// request body. -func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { - if !strings.HasSuffix(c.BaseURL.Path, "/") { - return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL) - } - u, err := c.BaseURL.Parse(urlStr) - if err != nil { - return nil, err - } - - var buf io.ReadWriter - if body != nil { - buf = new(bytes.Buffer) - enc := json.NewEncoder(buf) - enc.SetEscapeHTML(false) - err := enc.Encode(body) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, u.String(), buf) - if err != nil { - return nil, err - } - - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - req.Header.Set("Accept", mediaTypeV3) - if c.UserAgent != "" { - req.Header.Set("User-Agent", c.UserAgent) - } - return req, nil -} - -// NewUploadRequest creates an upload request. A relative URL can be provided in -// urlStr, in which case it is resolved relative to the UploadURL of the Client. -// Relative URLs should always be specified without a preceding slash. -func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error) { - if !strings.HasSuffix(c.UploadURL.Path, "/") { - return nil, fmt.Errorf("UploadURL must have a trailing slash, but %q does not", c.UploadURL) - } - u, err := c.UploadURL.Parse(urlStr) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", u.String(), reader) - if err != nil { - return nil, err - } - req.ContentLength = size - - if mediaType == "" { - mediaType = defaultMediaType - } - req.Header.Set("Content-Type", mediaType) - req.Header.Set("Accept", mediaTypeV3) - req.Header.Set("User-Agent", c.UserAgent) - return req, nil -} - -// Response is a GitHub API response. This wraps the standard http.Response -// returned from GitHub and provides convenient access to things like -// pagination links. -type Response struct { - *http.Response - - // These fields provide the page values for paginating through a set of - // results. Any or all of these may be set to the zero value for - // responses that are not part of a paginated set, or for which there - // are no additional pages. - - NextPage int - PrevPage int - FirstPage int - LastPage int - - // Explicitly specify the Rate type so Rate's String() receiver doesn't - // propagate to Response. - Rate Rate -} - -// newResponse creates a new Response for the provided http.Response. -// r must not be nil. -func newResponse(r *http.Response) *Response { - response := &Response{Response: r} - response.populatePageValues() - response.Rate = parseRate(r) - return response -} - -// populatePageValues parses the HTTP Link response headers and populates the -// various pagination link values in the Response. -func (r *Response) populatePageValues() { - if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 { - for _, link := range strings.Split(links[0], ",") { - segments := strings.Split(strings.TrimSpace(link), ";") - - // link must at least have href and rel - if len(segments) < 2 { - continue - } - - // ensure href is properly formatted - if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") { - continue - } - - // try to pull out page parameter - url, err := url.Parse(segments[0][1 : len(segments[0])-1]) - if err != nil { - continue - } - page := url.Query().Get("page") - if page == "" { - continue - } - - for _, segment := range segments[1:] { - switch strings.TrimSpace(segment) { - case `rel="next"`: - r.NextPage, _ = strconv.Atoi(page) - case `rel="prev"`: - r.PrevPage, _ = strconv.Atoi(page) - case `rel="first"`: - r.FirstPage, _ = strconv.Atoi(page) - case `rel="last"`: - r.LastPage, _ = strconv.Atoi(page) - } - - } - } - } -} - -// parseRate parses the rate related headers. -func parseRate(r *http.Response) Rate { - var rate Rate - if limit := r.Header.Get(headerRateLimit); limit != "" { - rate.Limit, _ = strconv.Atoi(limit) - } - if remaining := r.Header.Get(headerRateRemaining); remaining != "" { - rate.Remaining, _ = strconv.Atoi(remaining) - } - if reset := r.Header.Get(headerRateReset); reset != "" { - if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { - rate.Reset = Timestamp{time.Unix(v, 0)} - } - } - return rate -} - -// Do sends an API request and returns the API response. The API response is -// JSON decoded and stored in the value pointed to by v, or returned as an -// error if an API error has occurred. If v implements the io.Writer -// interface, the raw response body will be written to v, without attempting to -// first decode it. If rate limit is exceeded and reset time is in the future, -// Do returns *RateLimitError immediately without making a network API call. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) { - req = withContext(ctx, req) - - rateLimitCategory := category(req.URL.Path) - - // If we've hit rate limit, don't make further requests before Reset time. - if err := c.checkRateLimitBeforeDo(req, rateLimitCategory); err != nil { - return &Response{ - Response: err.Response, - Rate: err.Rate, - }, err - } - - resp, err := c.client.Do(req) - if err != nil { - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - // If the error type is *url.Error, sanitize its URL before returning. - if e, ok := err.(*url.Error); ok { - if url, err := url.Parse(e.URL); err == nil { - e.URL = sanitizeURL(url).String() - return nil, e - } - } - - return nil, err - } - defer resp.Body.Close() - - response := newResponse(resp) - - c.rateMu.Lock() - c.rateLimits[rateLimitCategory] = response.Rate - c.rateMu.Unlock() - - err = CheckResponse(resp) - if err != nil { - // Even though there was an error, we still return the response - // in case the caller wants to inspect it further. - // However, if the error is AcceptedError, decode it below before - // returning from this function and closing the response body. - if _, ok := err.(*AcceptedError); !ok { - return response, err - } - } - - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, resp.Body) - } else { - decErr := json.NewDecoder(resp.Body).Decode(v) - if decErr == io.EOF { - decErr = nil // ignore EOF errors caused by empty response body - } - if decErr != nil { - err = decErr - } - } - } - - return response, err -} - -// checkRateLimitBeforeDo does not make any network calls, but uses existing knowledge from -// current client state in order to quickly check if *RateLimitError can be immediately returned -// from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. -// Otherwise it returns nil, and Client.Do should proceed normally. -func (c *Client) checkRateLimitBeforeDo(req *http.Request, rateLimitCategory rateLimitCategory) *RateLimitError { - c.rateMu.Lock() - rate := c.rateLimits[rateLimitCategory] - c.rateMu.Unlock() - if !rate.Reset.Time.IsZero() && rate.Remaining == 0 && time.Now().Before(rate.Reset.Time) { - // Create a fake response. - resp := &http.Response{ - Status: http.StatusText(http.StatusForbidden), - StatusCode: http.StatusForbidden, - Request: req, - Header: make(http.Header), - Body: ioutil.NopCloser(strings.NewReader("")), - } - return &RateLimitError{ - Rate: rate, - Response: resp, - Message: fmt.Sprintf("API rate limit of %v still exceeded until %v, not making remote request.", rate.Limit, rate.Reset.Time), - } - } - - return nil -} - -/* -An ErrorResponse reports one or more errors caused by an API request. - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type ErrorResponse struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - Errors []Error `json:"errors"` // more detail on individual errors - // Block is only populated on certain types of errors such as code 451. - // See https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/ - // for more information. - Block *struct { - Reason string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - } `json:"block,omitempty"` - // Most errors will also include a documentation_url field pointing - // to some content that might help you resolve the error, see - // https://developer.github.com/v3/#client-errors - DocumentationURL string `json:"documentation_url,omitempty"` -} - -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v %+v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, r.Errors) -} - -// TwoFactorAuthError occurs when using HTTP Basic Authentication for a user -// that has two-factor authentication enabled. The request can be reattempted -// by providing a one-time password in the request. -type TwoFactorAuthError ErrorResponse - -func (r *TwoFactorAuthError) Error() string { return (*ErrorResponse)(r).Error() } - -// RateLimitError occurs when GitHub returns 403 Forbidden response with a rate limit -// remaining value of 0, and error message starts with "API rate limit exceeded for ". -type RateLimitError struct { - Rate Rate // Rate specifies last known rate limit for the client - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message -} - -func (r *RateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, formatRateReset(r.Rate.Reset.Time.Sub(time.Now()))) -} - -// AcceptedError occurs when GitHub returns 202 Accepted response with an -// empty body, which means a job was scheduled on the GitHub side to process -// the information needed and cache it. -// Technically, 202 Accepted is not a real error, it's just used to -// indicate that results are not ready yet, but should be available soon. -// The request can be repeated after some time. -type AcceptedError struct{} - -func (*AcceptedError) Error() string { - return "job scheduled on GitHub side; try again later" -} - -// AbuseRateLimitError occurs when GitHub returns 403 Forbidden response with the -// "documentation_url" field value equal to "https://developer.github.com/v3/#abuse-rate-limits". -type AbuseRateLimitError struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - - // RetryAfter is provided with some abuse rate limit errors. If present, - // it is the amount of time that the client should wait before retrying. - // Otherwise, the client should try again later (after an unspecified amount of time). - RetryAfter *time.Duration -} - -func (r *AbuseRateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message) -} - -// sanitizeURL redacts the client_secret parameter from the URL which may be -// exposed to the user. -func sanitizeURL(uri *url.URL) *url.URL { - if uri == nil { - return nil - } - params := uri.Query() - if len(params.Get("client_secret")) > 0 { - params.Set("client_secret", "REDACTED") - uri.RawQuery = params.Encode() - } - return uri -} - -/* -An Error reports more details on an individual error in an ErrorResponse. -These are the possible validation error codes: - - missing: - resource does not exist - missing_field: - a required field on a resource has not been set - invalid: - the formatting of a field is invalid - already_exists: - another resource has the same valid as this field - custom: - some resources return this (e.g. github.User.CreateKey()), additional - information is set in the Message field of the Error - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type Error struct { - Resource string `json:"resource"` // resource on which the error occurred - Field string `json:"field"` // field on which the error occurred - Code string `json:"code"` // validation error code - Message string `json:"message"` // Message describing the error. Errors with Code == "custom" will always have this set. -} - -func (e *Error) Error() string { - return fmt.Sprintf("%v error caused by %v field on %v resource", - e.Code, e.Field, e.Resource) -} - -// CheckResponse checks the API response for errors, and returns them if -// present. A response is considered an error if it has a status code outside -// the 200 range or equal to 202 Accepted. -// API error responses are expected to have either no response -// body, or a JSON response body that maps to ErrorResponse. Any other -// response body will be silently ignored. -// -// The error type will be *RateLimitError for rate limit exceeded errors, -// *AcceptedError for 202 Accepted status codes, -// and *TwoFactorAuthError for two-factor authentication errors. -func CheckResponse(r *http.Response) error { - if r.StatusCode == http.StatusAccepted { - return &AcceptedError{} - } - if c := r.StatusCode; 200 <= c && c <= 299 { - return nil - } - errorResponse := &ErrorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) - if err == nil && data != nil { - json.Unmarshal(data, errorResponse) - } - switch { - case r.StatusCode == http.StatusUnauthorized && strings.HasPrefix(r.Header.Get(headerOTP), "required"): - return (*TwoFactorAuthError)(errorResponse) - case r.StatusCode == http.StatusForbidden && r.Header.Get(headerRateRemaining) == "0" && strings.HasPrefix(errorResponse.Message, "API rate limit exceeded for "): - return &RateLimitError{ - Rate: parseRate(r), - Response: errorResponse.Response, - Message: errorResponse.Message, - } - case r.StatusCode == http.StatusForbidden && strings.HasSuffix(errorResponse.DocumentationURL, "/v3/#abuse-rate-limits"): - abuseRateLimitError := &AbuseRateLimitError{ - Response: errorResponse.Response, - Message: errorResponse.Message, - } - if v := r.Header["Retry-After"]; len(v) > 0 { - // According to GitHub support, the "Retry-After" header value will be - // an integer which represents the number of seconds that one should - // wait before resuming making requests. - retryAfterSeconds, _ := strconv.ParseInt(v[0], 10, 64) // Error handling is noop. - retryAfter := time.Duration(retryAfterSeconds) * time.Second - abuseRateLimitError.RetryAfter = &retryAfter - } - return abuseRateLimitError - default: - return errorResponse - } -} - -// parseBoolResponse determines the boolean result from a GitHub API response. -// Several GitHub API methods return boolean responses indicated by the HTTP -// status code in the response (true indicated by a 204, false indicated by a -// 404). This helper function will determine that result and hide the 404 -// error if present. Any other error will be returned through as-is. -func parseBoolResponse(err error) (bool, error) { - if err == nil { - return true, nil - } - - if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { - // Simply false. In this one case, we do not pass the error through. - return false, nil - } - - // some other real error occurred - return false, err -} - -// Rate represents the rate limit for the current client. -type Rate struct { - // The number of requests per hour the client is currently limited to. - Limit int `json:"limit"` - - // The number of remaining requests the client can make this hour. - Remaining int `json:"remaining"` - - // The time at which the current rate limit will reset. - Reset Timestamp `json:"reset"` -} - -func (r Rate) String() string { - return Stringify(r) -} - -// RateLimits represents the rate limits for the current client. -type RateLimits struct { - // The rate limit for non-search API requests. Unauthenticated - // requests are limited to 60 per hour. Authenticated requests are - // limited to 5,000 per hour. - // - // GitHub API docs: https://developer.github.com/v3/#rate-limiting - Core *Rate `json:"core"` - - // The rate limit for search API requests. Unauthenticated requests - // are limited to 10 requests per minutes. Authenticated requests are - // limited to 30 per minute. - // - // GitHub API docs: https://developer.github.com/v3/search/#rate-limit - Search *Rate `json:"search"` -} - -func (r RateLimits) String() string { - return Stringify(r) -} - -type rateLimitCategory uint8 - -const ( - coreCategory rateLimitCategory = iota - searchCategory - - categories // An array of this length will be able to contain all rate limit categories. -) - -// category returns the rate limit category of the endpoint, determined by Request.URL.Path. -func category(path string) rateLimitCategory { - switch { - default: - return coreCategory - case strings.HasPrefix(path, "/search/"): - return searchCategory - } -} - -// RateLimits returns the rate limits for the current client. -func (c *Client) RateLimits(ctx context.Context) (*RateLimits, *Response, error) { - req, err := c.NewRequest("GET", "rate_limit", nil) - if err != nil { - return nil, nil, err - } - - response := new(struct { - Resources *RateLimits `json:"resources"` - }) - resp, err := c.Do(ctx, req, response) - if err != nil { - return nil, nil, err - } - - if response.Resources != nil { - c.rateMu.Lock() - if response.Resources.Core != nil { - c.rateLimits[coreCategory] = *response.Resources.Core - } - if response.Resources.Search != nil { - c.rateLimits[searchCategory] = *response.Resources.Search - } - c.rateMu.Unlock() - } - - return response.Resources, resp, nil -} - -/* -UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls -that need to use a higher rate limit associated with your OAuth application. - - t := &github.UnauthenticatedRateLimitedTransport{ - ClientID: "your app's client ID", - ClientSecret: "your app's client secret", - } - client := github.NewClient(t.Client()) - -This will append the querystring params client_id=xxx&client_secret=yyy to all -requests. - -See https://developer.github.com/v3/#unauthenticated-rate-limited-requests for -more information. -*/ -type UnauthenticatedRateLimitedTransport struct { - // ClientID is the GitHub OAuth client ID of the current application, which - // can be found by selecting its entry in the list at - // https://github.com/settings/applications. - ClientID string - - // ClientSecret is the GitHub OAuth client secret of the current - // application. - ClientSecret string - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if t.ClientID == "" { - return nil, errors.New("t.ClientID is empty") - } - if t.ClientSecret == "" { - return nil, errors.New("t.ClientSecret is empty") - } - - // To set extra querystring params, we must make a copy of the Request so - // that we don't modify the Request we were given. This is required by the - // specification of http.RoundTripper. - // - // Since we are going to modify only req.URL here, we only need a deep copy - // of req.URL. - req2 := new(http.Request) - *req2 = *req - req2.URL = new(url.URL) - *req2.URL = *req.URL - - q := req2.URL.Query() - q.Set("client_id", t.ClientID) - q.Set("client_secret", t.ClientSecret) - req2.URL.RawQuery = q.Encode() - - // Make the HTTP request. - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that makes requests which are subject to the -// rate limit of your OAuth application. -func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *UnauthenticatedRateLimitedTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// BasicAuthTransport is an http.RoundTripper that authenticates all requests -// using HTTP Basic Authentication with the provided username and password. It -// additionally supports users who have two-factor authentication enabled on -// their GitHub account. -type BasicAuthTransport struct { - Username string // GitHub username - Password string // GitHub password - OTP string // one-time password for users with two-factor auth enabled - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - // To set extra headers, we must make a copy of the Request so - // that we don't modify the Request we were given. This is required by the - // specification of http.RoundTripper. - // - // Since we are going to modify only req.Header here, we only need a deep copy - // of req.Header. - req2 := new(http.Request) - *req2 = *req - req2.Header = make(http.Header, len(req.Header)) - for k, s := range req.Header { - req2.Header[k] = append([]string(nil), s...) - } - - req2.SetBasicAuth(t.Username, t.Password) - if t.OTP != "" { - req2.Header.Set(headerOTP, t.OTP) - } - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that makes requests that are authenticated -// using HTTP Basic Authentication. -func (t *BasicAuthTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *BasicAuthTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// formatRateReset formats d to look like "[rate reset in 2s]" or -// "[rate reset in 87m02s]" for the positive durations. And like "[rate limit was reset 87m02s ago]" -// for the negative cases. -func formatRateReset(d time.Duration) string { - isNegative := d < 0 - if isNegative { - d *= -1 - } - secondsTotal := int(0.5 + d.Seconds()) - minutes := secondsTotal / 60 - seconds := secondsTotal - minutes*60 - - var timeString string - if minutes > 0 { - timeString = fmt.Sprintf("%dm%02ds", minutes, seconds) - } else { - timeString = fmt.Sprintf("%ds", seconds) - } - - if isNegative { - return fmt.Sprintf("[rate limit was reset %v ago]", timeString) - } - return fmt.Sprintf("[rate reset in %v]", timeString) -} - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int is a helper routine that allocates a new int value -// to store v and returns a pointer to it. -func Int(v int) *int { return &v } - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { return &v } - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/vendor/github.com/google/go-github/github/gitignore.go b/vendor/github.com/google/go-github/github/gitignore.go deleted file mode 100644 index 2f691bc32..000000000 --- a/vendor/github.com/google/go-github/github/gitignore.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// GitignoresService provides access to the gitignore related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/ -type GitignoresService service - -// Gitignore represents a .gitignore file as returned by the GitHub API. -type Gitignore struct { - Name *string `json:"name,omitempty"` - Source *string `json:"source,omitempty"` -} - -func (g Gitignore) String() string { - return Stringify(g) -} - -// List all available Gitignore templates. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#listing-available-templates -func (s GitignoresService) List(ctx context.Context) ([]string, *Response, error) { - req, err := s.client.NewRequest("GET", "gitignore/templates", nil) - if err != nil { - return nil, nil, err - } - - var availableTemplates []string - resp, err := s.client.Do(ctx, req, &availableTemplates) - if err != nil { - return nil, resp, err - } - - return availableTemplates, resp, nil -} - -// Get a Gitignore by name. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#get-a-single-template -func (s GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) { - u := fmt.Sprintf("gitignore/templates/%v", name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - gitignore := new(Gitignore) - resp, err := s.client.Do(ctx, req, gitignore) - if err != nil { - return nil, resp, err - } - - return gitignore, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues.go b/vendor/github.com/google/go-github/github/issues.go deleted file mode 100644 index 1e0991ce4..000000000 --- a/vendor/github.com/google/go-github/github/issues.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" - "time" -) - -// IssuesService handles communication with the issue related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/issues/ -type IssuesService service - -// Issue represents a GitHub issue on a repository. -// -// Note: As far as the GitHub API is concerned, every pull request is an issue, -// but not every issue is a pull request. Some endpoints, events, and webhooks -// may also return pull requests via this struct. If PullRequestLinks is nil, -// this is an issue, and if PullRequestLinks is not nil, this is a pull request. -// The IsPullRequest helper method can be used to check that. -type Issue struct { - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Locked *bool `json:"locked,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Labels []Label `json:"labels,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Comments *int `json:"comments,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedBy *User `json:"closed_by,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` - - // ActiveLockReason is populated only when LockReason is provided while locking the issue. - // Possible values are: "off-topic", "too heated", "resolved", and "spam". - ActiveLockReason *string `json:"active_lock_reason,omitempty"` -} - -func (i Issue) String() string { - return Stringify(i) -} - -// IsPullRequest reports whether the issue is also a pull request. It uses the -// method recommended by GitHub's API documentation, which is to check whether -// PullRequestLinks is non-nil. -func (i Issue) IsPullRequest() bool { - return i.PullRequestLinks != nil -} - -// IssueRequest represents a request to create/edit an issue. -// It is separate from Issue above because otherwise Labels -// and Assignee fail to serialize to the correct JSON. -type IssueRequest struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - Labels *[]string `json:"labels,omitempty"` - Assignee *string `json:"assignee,omitempty"` - State *string `json:"state,omitempty"` - Milestone *int `json:"milestone,omitempty"` - Assignees *[]string `json:"assignees,omitempty"` -} - -// IssueListOptions specifies the optional parameters to the IssuesService.List -// and IssuesService.ListByOrg methods. -type IssueListOptions struct { - // Filter specifies which issues to list. Possible values are: assigned, - // created, mentioned, subscribed, all. Default is "assigned". - Filter string `url:"filter,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,comma,omitempty"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// PullRequestLinks object is added to the Issue object when it's an issue included -// in the IssueCommentEvent webhook payload, if the webhook is fired by a comment on a PR. -type PullRequestLinks struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` -} - -// List the issues for the authenticated user. If all is true, list issues -// across all the user's visible repositories including owned, member, and -// organization repositories; if false, list only owned and member -// repositories. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) List(ctx context.Context, all bool, opt *IssueListOptions) ([]*Issue, *Response, error) { - var u string - if all { - u = "issues" - } else { - u = "user/issues" - } - return s.listIssues(ctx, u, opt) -} - -// ListByOrg fetches the issues in the specified organization for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) ListByOrg(ctx context.Context, org string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("orgs/%v/issues", org) - return s.listIssues(ctx, u, opt) -} - -func (s *IssuesService) listIssues(ctx context.Context, u string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// IssueListByRepoOptions specifies the optional parameters to the -// IssuesService.ListByRepo method. -type IssueListByRepoOptions struct { - // Milestone limits issues for the specified milestone. Possible values are - // a milestone number, "none" for issues with no milestone, "*" for issues - // with any milestone. - Milestone string `url:"milestone,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Assignee filters issues based on their assignee. Possible values are a - // user name, "none" for issues that are not assigned, "*" for issues with - // any assigned user. - Assignee string `url:"assignee,omitempty"` - - // Creator filters issues based on their creator. - Creator string `url:"creator,omitempty"` - - // Mentioned filters issues to those mentioned a specific user. - Mentioned string `url:"mentioned,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,omitempty,comma"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListByRepo lists the issues for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues-for-a-repository -func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeIntegrationPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// Get a single issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#get-a-single-issue -func (s *IssuesService) Get(ctx context.Context, owner string, repo string, number int) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - issue := new(Issue) - resp, err := s.client.Do(ctx, req, issue) - if err != nil { - return nil, resp, err - } - - return issue, resp, nil -} - -// Create a new issue on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#create-an-issue -func (s *IssuesService) Create(ctx context.Context, owner string, repo string, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - req, err := s.client.NewRequest("POST", u, issue) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// Edit an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#edit-an-issue -func (s *IssuesService) Edit(ctx context.Context, owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, issue) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// LockIssueOptions specifies the optional parameters to the -// IssuesService.Lock method. -type LockIssueOptions struct { - // LockReason specifies the reason to lock this issue. - // Providing a lock reason can help make it clearer to contributors why an issue - // was locked. Possible values are: "off-topic", "too heated", "resolved", and "spam". - LockReason string `json:"lock_reason,omitempty"` -} - -// Lock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue -func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int, opt *LockIssueOptions) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - if opt != nil { - req.Header.Set("Accept", mediaTypeLockReasonPreview) - } - - return s.client.Do(ctx, req, nil) -} - -// Unlock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue -func (s *IssuesService) Unlock(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_assignees.go b/vendor/github.com/google/go-github/github/issues_assignees.go deleted file mode 100644 index 9cb366f50..000000000 --- a/vendor/github.com/google/go-github/github/issues_assignees.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListAssignees fetches all available assignees (owners and collaborators) to -// which issues may be assigned. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#list-assignees -func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var assignees []*User - resp, err := s.client.Do(ctx, req, &assignees) - if err != nil { - return nil, resp, err - } - - return assignees, resp, nil -} - -// IsAssignee checks if a user is an assignee for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#check-assignee -func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - assignee, err := parseBoolResponse(err) - return assignee, resp, err -} - -// AddAssignees adds the provided GitHub users as assignees to the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue -func (s *IssuesService) AddAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("POST", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} - -// RemoveAssignees removes the provided GitHub users as assignees from the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue -func (s *IssuesService) RemoveAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} diff --git a/vendor/github.com/google/go-github/github/issues_comments.go b/vendor/github.com/google/go-github/github/issues_comments.go deleted file mode 100644 index e6f6f2190..000000000 --- a/vendor/github.com/google/go-github/github/issues_comments.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// IssueComment represents a comment left on an issue. -type IssueComment struct { - ID *int64 `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // AuthorAssociation is the comment author's relationship to the issue's repository. - // Possible values are "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MEMBER", "OWNER", or "NONE". - AuthorAssociation *string `json:"author_association,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` -} - -func (i IssueComment) String() string { - return Stringify(i) -} - -// IssueListCommentsOptions specifies the optional parameters to the -// IssuesService.ListComments method. -type IssueListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified issue. Specifying an issue -// number of 0 will return all comments on all issues for the repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue -func (s *IssuesService) ListComments(ctx context.Context, owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/issues/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*IssueComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#get-a-single-comment -func (s *IssuesService) GetComment(ctx context.Context, owner string, repo string, commentID int64) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, commentID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(IssueComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#create-a-comment -func (s *IssuesService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates an issue comment. -// A non-nil comment.Body must be provided. Other comment fields should be left nil. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#edit-a-comment -func (s *IssuesService) EditComment(ctx context.Context, owner string, repo string, commentID int64, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, commentID) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#delete-a-comment -func (s *IssuesService) DeleteComment(ctx context.Context, owner string, repo string, commentID int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, commentID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_events.go b/vendor/github.com/google/go-github/github/issues_events.go deleted file mode 100644 index f71e46361..000000000 --- a/vendor/github.com/google/go-github/github/issues_events.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// IssueEvent represents an event that occurred around an Issue or Pull Request. -type IssueEvent struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // The User that generated this event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible - // values are: - // - // closed - // The Actor closed the issue. - // If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit. - // - // merged - // The Actor merged into master a branch containing a commit mentioning the issue. - // CommitID holds the SHA1 of the merge commit. - // - // referenced - // The Actor committed to master a commit mentioning the issue in its commit message. - // CommitID holds the SHA1 of the commit. - // - // reopened, unlocked - // The Actor did that to the issue. - // - // locked - // The Actor locked the issue. - // LockReason holds the reason of locking the issue (if provided while locking). - // - // renamed - // The Actor changed the issue title from Rename.From to Rename.To. - // - // mentioned - // Someone unspecified @mentioned the Actor [sic] in an issue comment body. - // - // assigned, unassigned - // The Assigner assigned the issue to or removed the assignment from the Assignee. - // - // labeled, unlabeled - // The Actor added or removed the Label from the issue. - // - // milestoned, demilestoned - // The Actor added or removed the issue from the Milestone. - // - // subscribed, unsubscribed - // The Actor subscribed to or unsubscribed from notifications for an issue. - // - // head_ref_deleted, head_ref_restored - // The pull request’s branch was deleted or restored. - // - Event *string `json:"event,omitempty"` - - CreatedAt *time.Time `json:"created_at,omitempty"` - Issue *Issue `json:"issue,omitempty"` - - // Only present on certain events; see above. - Assignee *User `json:"assignee,omitempty"` - Assigner *User `json:"assigner,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - Label *Label `json:"label,omitempty"` - Rename *Rename `json:"rename,omitempty"` - LockReason *string `json:"lock_reason,omitempty"` -} - -// ListIssueEvents lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue -func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/events", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeLockReasonPreview) - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository -func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// GetEvent returns the specified issue event. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event -func (s *IssuesService) GetEvent(ctx context.Context, owner, repo string, id int64) (*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - event := new(IssueEvent) - resp, err := s.client.Do(ctx, req, event) - if err != nil { - return nil, resp, err - } - - return event, resp, nil -} - -// Rename contains details for 'renamed' events. -type Rename struct { - From *string `json:"from,omitempty"` - To *string `json:"to,omitempty"` -} - -func (r Rename) String() string { - return Stringify(r) -} diff --git a/vendor/github.com/google/go-github/github/issues_labels.go b/vendor/github.com/google/go-github/github/issues_labels.go deleted file mode 100644 index adcbe0683..000000000 --- a/vendor/github.com/google/go-github/github/issues_labels.go +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Label represents a GitHub label on an Issue -type Label struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Color *string `json:"color,omitempty"` - Description *string `json:"description,omitempty"` - Default *bool `json:"default,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (l Label) String() string { - return Stringify(l) -} - -// ListLabels lists all labels for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository -func (s *IssuesService) ListLabels(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// GetLabel gets a single label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-a-single-label -func (s *IssuesService) GetLabel(ctx context.Context, owner string, repo string, name string) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - label := new(Label) - resp, err := s.client.Do(ctx, req, label) - if err != nil { - return nil, resp, err - } - - return label, resp, nil -} - -// CreateLabel creates a new label on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#create-a-label -func (s *IssuesService) CreateLabel(ctx context.Context, owner string, repo string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - req, err := s.client.NewRequest("POST", u, label) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// EditLabel edits a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#update-a-label -func (s *IssuesService) EditLabel(ctx context.Context, owner string, repo string, name string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("PATCH", u, label) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// DeleteLabel deletes a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#delete-a-label -func (s *IssuesService) DeleteLabel(ctx context.Context, owner string, repo string, name string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListLabelsByIssue lists all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-labels-on-an-issue -func (s *IssuesService) ListLabelsByIssue(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// AddLabelsToIssue adds labels to an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue -func (s *IssuesService) AddLabelsToIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("POST", u, labels) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelForIssue removes a label for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue -func (s *IssuesService) RemoveLabelForIssue(ctx context.Context, owner string, repo string, number int, label string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels/%v", owner, repo, number, label) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - return s.client.Do(ctx, req, nil) -} - -// ReplaceLabelsForIssue replaces all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#replace-all-labels-for-an-issue -func (s *IssuesService) ReplaceLabelsForIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, labels) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelsForIssue removes all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-all-labels-from-an-issue -func (s *IssuesService) RemoveLabelsForIssue(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - return s.client.Do(ctx, req, nil) -} - -// ListLabelsForMilestone lists labels for every issue in a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone -func (s *IssuesService) ListLabelsForMilestone(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues_milestones.go b/vendor/github.com/google/go-github/github/issues_milestones.go deleted file mode 100644 index ffe9aae14..000000000 --- a/vendor/github.com/google/go-github/github/issues_milestones.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Milestone represents a GitHub repository milestone. -type Milestone struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - OpenIssues *int `json:"open_issues,omitempty"` - ClosedIssues *int `json:"closed_issues,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - DueOn *time.Time `json:"due_on,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (m Milestone) String() string { - return Stringify(m) -} - -// MilestoneListOptions specifies the optional parameters to the -// IssuesService.ListMilestones method. -type MilestoneListOptions struct { - // State filters milestones based on their state. Possible values are: - // open, closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Sort specifies how to sort milestones. Possible values are: due_on, completeness. - // Default value is "due_on". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort milestones. Possible values are: asc, desc. - // Default is "asc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListMilestones lists all milestones for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository -func (s *IssuesService) ListMilestones(ctx context.Context, owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var milestones []*Milestone - resp, err := s.client.Do(ctx, req, &milestones) - if err != nil { - return nil, resp, err - } - - return milestones, resp, nil -} - -// GetMilestone gets a single milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone -func (s *IssuesService) GetMilestone(ctx context.Context, owner string, repo string, number int) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - milestone := new(Milestone) - resp, err := s.client.Do(ctx, req, milestone) - if err != nil { - return nil, resp, err - } - - return milestone, resp, nil -} - -// CreateMilestone creates a new milestone on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone -func (s *IssuesService) CreateMilestone(ctx context.Context, owner string, repo string, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - req, err := s.client.NewRequest("POST", u, milestone) - if err != nil { - return nil, nil, err - } - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// EditMilestone edits a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#update-a-milestone -func (s *IssuesService) EditMilestone(ctx context.Context, owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, milestone) - if err != nil { - return nil, nil, err - } - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteMilestone deletes a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#delete-a-milestone -func (s *IssuesService) DeleteMilestone(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_timeline.go b/vendor/github.com/google/go-github/github/issues_timeline.go deleted file mode 100644 index 9cfda8320..000000000 --- a/vendor/github.com/google/go-github/github/issues_timeline.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Timeline represents an event that occurred around an Issue or Pull Request. -// -// It is similar to an IssueEvent but may contain more information. -// GitHub API docs: https://developer.github.com/v3/issues/timeline/ -type Timeline struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - CommitURL *string `json:"commit_url,omitempty"` - - // The User object that generated the event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible values - // are: - // - // assigned - // The issue was assigned to the assignee. - // - // closed - // The issue was closed by the actor. When the commit_id is present, it - // identifies the commit that closed the issue using "closes / fixes #NN" - // syntax. - // - // commented - // A comment was added to the issue. - // - // committed - // A commit was added to the pull request's 'HEAD' branch. Only provided - // for pull requests. - // - // cross-referenced - // The issue was referenced from another issue. The 'source' attribute - // contains the 'id', 'actor', and 'url' of the reference's source. - // - // demilestoned - // The issue was removed from a milestone. - // - // head_ref_deleted - // The pull request's branch was deleted. - // - // head_ref_restored - // The pull request's branch was restored. - // - // labeled - // A label was added to the issue. - // - // locked - // The issue was locked by the actor. - // - // mentioned - // The actor was @mentioned in an issue body. - // - // merged - // The issue was merged by the actor. The 'commit_id' attribute is the - // SHA1 of the HEAD commit that was merged. - // - // milestoned - // The issue was added to a milestone. - // - // referenced - // The issue was referenced from a commit message. The 'commit_id' - // attribute is the commit SHA1 of where that happened. - // - // renamed - // The issue title was changed. - // - // reopened - // The issue was reopened by the actor. - // - // subscribed - // The actor subscribed to receive notifications for an issue. - // - // unassigned - // The assignee was unassigned from the issue. - // - // unlabeled - // A label was removed from the issue. - // - // unlocked - // The issue was unlocked by the actor. - // - // unsubscribed - // The actor unsubscribed to stop receiving notifications for an issue. - // - Event *string `json:"event,omitempty"` - - // The string SHA of a commit that referenced this Issue or Pull Request. - CommitID *string `json:"commit_id,omitempty"` - // The timestamp indicating when the event occurred. - CreatedAt *time.Time `json:"created_at,omitempty"` - // The Label object including `name` and `color` attributes. Only provided for - // 'labeled' and 'unlabeled' events. - Label *Label `json:"label,omitempty"` - // The User object which was assigned to (or unassigned from) this Issue or - // Pull Request. Only provided for 'assigned' and 'unassigned' events. - Assignee *User `json:"assignee,omitempty"` - // The Milestone object including a 'title' attribute. - // Only provided for 'milestoned' and 'demilestoned' events. - Milestone *Milestone `json:"milestone,omitempty"` - // The 'id', 'actor', and 'url' for the source of a reference from another issue. - // Only provided for 'cross-referenced' events. - Source *Source `json:"source,omitempty"` - // An object containing rename details including 'from' and 'to' attributes. - // Only provided for 'renamed' events. - Rename *Rename `json:"rename,omitempty"` -} - -// Source represents a reference's source. -type Source struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Actor *User `json:"actor,omitempty"` -} - -// ListIssueTimeline lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue -func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/timeline", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTimelinePreview) - - var events []*Timeline - resp, err := s.client.Do(ctx, req, &events) - return events, resp, err -} diff --git a/vendor/github.com/google/go-github/github/licenses.go b/vendor/github.com/google/go-github/github/licenses.go deleted file mode 100644 index 1176d3a8b..000000000 --- a/vendor/github.com/google/go-github/github/licenses.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// LicensesService handles communication with the license related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/licenses/ -type LicensesService service - -// RepositoryLicense represents the license for a repository. -type RepositoryLicense struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` - Type *string `json:"type,omitempty"` - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - License *License `json:"license,omitempty"` -} - -func (l RepositoryLicense) String() string { - return Stringify(l) -} - -// License represents an open source license. -type License struct { - Key *string `json:"key,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - - SPDXID *string `json:"spdx_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Featured *bool `json:"featured,omitempty"` - Description *string `json:"description,omitempty"` - Implementation *string `json:"implementation,omitempty"` - Permissions *[]string `json:"permissions,omitempty"` - Conditions *[]string `json:"conditions,omitempty"` - Limitations *[]string `json:"limitations,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (l License) String() string { - return Stringify(l) -} - -// List popular open source licenses. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses -func (s *LicensesService) List(ctx context.Context) ([]*License, *Response, error) { - req, err := s.client.NewRequest("GET", "licenses", nil) - if err != nil { - return nil, nil, err - } - - var licenses []*License - resp, err := s.client.Do(ctx, req, &licenses) - if err != nil { - return nil, resp, err - } - - return licenses, resp, nil -} - -// Get extended metadata for one license. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license -func (s *LicensesService) Get(ctx context.Context, licenseName string) (*License, *Response, error) { - u := fmt.Sprintf("licenses/%s", licenseName) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - license := new(License) - resp, err := s.client.Do(ctx, req, license) - if err != nil { - return nil, resp, err - } - - return license, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/messages.go b/vendor/github.com/google/go-github/github/messages.go deleted file mode 100644 index 519c1c03d..000000000 --- a/vendor/github.com/google/go-github/github/messages.go +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file provides functions for validating payloads from GitHub Webhooks. -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github - -package github - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -const ( - // sha1Prefix is the prefix used by GitHub before the HMAC hexdigest. - sha1Prefix = "sha1" - // sha256Prefix and sha512Prefix are provided for future compatibility. - sha256Prefix = "sha256" - sha512Prefix = "sha512" - // signatureHeader is the GitHub header key used to pass the HMAC hexdigest. - signatureHeader = "X-Hub-Signature" - // eventTypeHeader is the GitHub header key used to pass the event type. - eventTypeHeader = "X-Github-Event" - // deliveryIDHeader is the GitHub header key used to pass the unique ID for the webhook event. - deliveryIDHeader = "X-Github-Delivery" -) - -var ( - // eventTypeMapping maps webhooks types to their corresponding go-github struct types. - eventTypeMapping = map[string]string{ - "check_run": "CheckRunEvent", - "check_suite": "CheckSuiteEvent", - "commit_comment": "CommitCommentEvent", - "create": "CreateEvent", - "delete": "DeleteEvent", - "deployment": "DeploymentEvent", - "deployment_status": "DeploymentStatusEvent", - "fork": "ForkEvent", - "gollum": "GollumEvent", - "installation": "InstallationEvent", - "installation_repositories": "InstallationRepositoriesEvent", - "issue_comment": "IssueCommentEvent", - "issues": "IssuesEvent", - "label": "LabelEvent", - "marketplace_purchase": "MarketplacePurchaseEvent", - "member": "MemberEvent", - "membership": "MembershipEvent", - "milestone": "MilestoneEvent", - "organization": "OrganizationEvent", - "org_block": "OrgBlockEvent", - "page_build": "PageBuildEvent", - "ping": "PingEvent", - "project": "ProjectEvent", - "project_card": "ProjectCardEvent", - "project_column": "ProjectColumnEvent", - "public": "PublicEvent", - "pull_request_review": "PullRequestReviewEvent", - "pull_request_review_comment": "PullRequestReviewCommentEvent", - "pull_request": "PullRequestEvent", - "push": "PushEvent", - "repository": "RepositoryEvent", - "release": "ReleaseEvent", - "status": "StatusEvent", - "team": "TeamEvent", - "team_add": "TeamAddEvent", - "watch": "WatchEvent", - } -) - -// genMAC generates the HMAC signature for a message provided the secret key -// and hashFunc. -func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte { - mac := hmac.New(hashFunc, key) - mac.Write(message) - return mac.Sum(nil) -} - -// checkMAC reports whether messageMAC is a valid HMAC tag for message. -func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool { - expectedMAC := genMAC(message, key, hashFunc) - return hmac.Equal(messageMAC, expectedMAC) -} - -// messageMAC returns the hex-decoded HMAC tag from the signature and its -// corresponding hash function. -func messageMAC(signature string) ([]byte, func() hash.Hash, error) { - if signature == "" { - return nil, nil, errors.New("missing signature") - } - sigParts := strings.SplitN(signature, "=", 2) - if len(sigParts) != 2 { - return nil, nil, fmt.Errorf("error parsing signature %q", signature) - } - - var hashFunc func() hash.Hash - switch sigParts[0] { - case sha1Prefix: - hashFunc = sha1.New - case sha256Prefix: - hashFunc = sha256.New - case sha512Prefix: - hashFunc = sha512.New - default: - return nil, nil, fmt.Errorf("unknown hash type prefix: %q", sigParts[0]) - } - - buf, err := hex.DecodeString(sigParts[1]) - if err != nil { - return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err) - } - return buf, hashFunc, nil -} - -// ValidatePayload validates an incoming GitHub Webhook event request -// and returns the (JSON) payload. -// The Content-Type header of the payload can be "application/json" or "application/x-www-form-urlencoded". -// If the Content-Type is neither then an error is returned. -// secretKey is the GitHub Webhook secret message. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// // Process payload... -// } -// -func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error) { - var body []byte // Raw body that GitHub uses to calculate the signature. - - switch ct := r.Header.Get("Content-Type"); ct { - case "application/json": - var err error - if body, err = ioutil.ReadAll(r.Body); err != nil { - return nil, err - } - - // If the content type is application/json, - // the JSON payload is just the original body. - payload = body - - case "application/x-www-form-urlencoded": - // payloadFormParam is the name of the form parameter that the JSON payload - // will be in if a webhook has its content type set to application/x-www-form-urlencoded. - const payloadFormParam = "payload" - - var err error - if body, err = ioutil.ReadAll(r.Body); err != nil { - return nil, err - } - - // If the content type is application/x-www-form-urlencoded, - // the JSON payload will be under the "payload" form param. - form, err := url.ParseQuery(string(body)) - if err != nil { - return nil, err - } - payload = []byte(form.Get(payloadFormParam)) - - default: - return nil, fmt.Errorf("Webhook request has unsupported Content-Type %q", ct) - } - - sig := r.Header.Get(signatureHeader) - if err := ValidateSignature(sig, body, secretKey); err != nil { - return nil, err - } - return payload, nil -} - -// ValidateSignature validates the signature for the given payload. -// signature is the GitHub hash signature delivered in the X-Hub-Signature header. -// payload is the JSON payload sent by GitHub Webhooks. -// secretKey is the GitHub Webhook secret message. -// -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github -func ValidateSignature(signature string, payload, secretKey []byte) error { - messageMAC, hashFunc, err := messageMAC(signature) - if err != nil { - return err - } - if !checkMAC(payload, messageMAC, secretKey, hashFunc) { - return errors.New("payload signature check failed") - } - return nil -} - -// WebHookType returns the event type of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func WebHookType(r *http.Request) string { - return r.Header.Get(eventTypeHeader) -} - -// DeliveryID returns the unique delivery ID of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func DeliveryID(r *http.Request) string { - return r.Header.Get(deliveryIDHeader) -} - -// ParseWebHook parses the event payload. For recognized event types, a -// value of the corresponding struct type will be returned (as returned -// by Event.ParsePayload()). An error will be returned for unrecognized event -// types. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// event, err := github.ParseWebHook(github.WebHookType(r), payload) -// if err != nil { ... } -// switch event := event.(type) { -// case *github.CommitCommentEvent: -// processCommitCommentEvent(event) -// case *github.CreateEvent: -// processCreateEvent(event) -// ... -// } -// } -// -func ParseWebHook(messageType string, payload []byte) (interface{}, error) { - eventType, ok := eventTypeMapping[messageType] - if !ok { - return nil, fmt.Errorf("unknown X-Github-Event in message: %v", messageType) - } - - event := Event{ - Type: &eventType, - RawPayload: (*json.RawMessage)(&payload), - } - return event.ParsePayload() -} diff --git a/vendor/github.com/google/go-github/github/migrations.go b/vendor/github.com/google/go-github/github/migrations.go deleted file mode 100644 index 90cc1fae8..000000000 --- a/vendor/github.com/google/go-github/github/migrations.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "errors" - "fmt" - "net/http" - "strings" -) - -// MigrationService provides access to the migration related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/migration/ -type MigrationService service - -// Migration represents a GitHub migration (archival). -type Migration struct { - ID *int64 `json:"id,omitempty"` - GUID *string `json:"guid,omitempty"` - // State is the current state of a migration. - // Possible values are: - // "pending" which means the migration hasn't started yet, - // "exporting" which means the migration is in progress, - // "exported" which means the migration finished successfully, or - // "failed" which means the migration failed. - State *string `json:"state,omitempty"` - // LockRepositories indicates whether repositories are locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` - URL *string `json:"url,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Repositories []*Repository `json:"repositories,omitempty"` -} - -func (m Migration) String() string { - return Stringify(m) -} - -// MigrationOptions specifies the optional parameters to Migration methods. -type MigrationOptions struct { - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories bool - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments bool -} - -// startMigration represents the body of a StartMigration request. -type startMigration struct { - // Repositories is a slice of repository names to migrate. - Repositories []string `json:"repositories,omitempty"` - - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` -} - -// StartMigration starts the generation of a migration archive. -// repos is a slice of repository names to migrate. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration -func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - body := &startMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListMigrations lists the most recent migrations. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-a-list-of-migrations -func (s *MigrationService) ListMigrations(ctx context.Context, org string) ([]*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - var m []*Migration - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationStatus gets the status of a specific migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-the-status-of-a-migration -func (s *MigrationService) MigrationStatus(ctx context.Context, org string, id int64) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationArchiveURL fetches a migration archive URL. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#download-a-migration-archive -func (s *MigrationService) MigrationArchiveURL(ctx context.Context, org string, id int64) (url string, err error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - // Disable the redirect mechanism because AWS fails if the GitHub auth token is provided. - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - _, err = s.client.Do(ctx, req, nil) // expect error from disable redirect - if err == nil { - return "", errors.New("expected redirect, none provided") - } - if !strings.Contains(err.Error(), "disable redirect") { - return "", err - } - return loc, nil -} - -// DeleteMigration deletes a previous migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#delete-a-migration-archive -func (s *MigrationService) DeleteMigration(ctx context.Context, org string, id int64) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnlockRepo unlocks a repository that was locked for migration. -// id is the migration ID. -// You should unlock each migrated repository and delete them when the migration -// is complete and you no longer need the source data. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#unlock-a-repository -func (s *MigrationService) UnlockRepo(ctx context.Context, org string, id int64, repo string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/repos/%v/lock", org, id, repo) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/migrations_source_import.go b/vendor/github.com/google/go-github/github/migrations_source_import.go deleted file mode 100644 index fd45e7800..000000000 --- a/vendor/github.com/google/go-github/github/migrations_source_import.go +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Import represents a repository import request. -type Import struct { - // The URL of the originating repository. - VCSURL *string `json:"vcs_url,omitempty"` - // The originating VCS type. Can be one of 'subversion', 'git', - // 'mercurial', or 'tfvc'. Without this parameter, the import job will - // take additional time to detect the VCS type before beginning the - // import. This detection step will be reflected in the response. - VCS *string `json:"vcs,omitempty"` - // VCSUsername and VCSPassword are only used for StartImport calls that - // are importing a password-protected repository. - VCSUsername *string `json:"vcs_username,omitempty"` - VCSPassword *string `json:"vcs_password,omitempty"` - // For a tfvc import, the name of the project that is being imported. - TFVCProject *string `json:"tfvc_project,omitempty"` - - // LFS related fields that may be preset in the Import Progress response - - // Describes whether the import has been opted in or out of using Git - // LFS. The value can be 'opt_in', 'opt_out', or 'undecided' if no - // action has been taken. - UseLFS *string `json:"use_lfs,omitempty"` - // Describes whether files larger than 100MB were found during the - // importing step. - HasLargeFiles *bool `json:"has_large_files,omitempty"` - // The total size in gigabytes of files larger than 100MB found in the - // originating repository. - LargeFilesSize *int `json:"large_files_size,omitempty"` - // The total number of files larger than 100MB found in the originating - // repository. To see a list of these files, call LargeFiles. - LargeFilesCount *int `json:"large_files_count,omitempty"` - - // Identifies the current status of an import. An import that does not - // have errors will progress through these steps: - // - // detecting - the "detection" step of the import is in progress - // because the request did not include a VCS parameter. The - // import is identifying the type of source control present at - // the URL. - // importing - the "raw" step of the import is in progress. This is - // where commit data is fetched from the original repository. - // The import progress response will include CommitCount (the - // total number of raw commits that will be imported) and - // Percent (0 - 100, the current progress through the import). - // mapping - the "rewrite" step of the import is in progress. This - // is where SVN branches are converted to Git branches, and - // where author updates are applied. The import progress - // response does not include progress information. - // pushing - the "push" step of the import is in progress. This is - // where the importer updates the repository on GitHub. The - // import progress response will include PushPercent, which is - // the percent value reported by git push when it is "Writing - // objects". - // complete - the import is complete, and the repository is ready - // on GitHub. - // - // If there are problems, you will see one of these in the status field: - // - // auth_failed - the import requires authentication in order to - // connect to the original repository. Make an UpdateImport - // request, and include VCSUsername and VCSPassword. - // error - the import encountered an error. The import progress - // response will include the FailedStep and an error message. - // Contact GitHub support for more information. - // detection_needs_auth - the importer requires authentication for - // the originating repository to continue detection. Make an - // UpdatImport request, and include VCSUsername and - // VCSPassword. - // detection_found_nothing - the importer didn't recognize any - // source control at the URL. - // detection_found_multiple - the importer found several projects - // or repositories at the provided URL. When this is the case, - // the Import Progress response will also include a - // ProjectChoices field with the possible project choices as - // values. Make an UpdateImport request, and include VCS and - // (if applicable) TFVCProject. - Status *string `json:"status,omitempty"` - CommitCount *int `json:"commit_count,omitempty"` - StatusText *string `json:"status_text,omitempty"` - AuthorsCount *int `json:"authors_count,omitempty"` - Percent *int `json:"percent,omitempty"` - PushPercent *int `json:"push_percent,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AuthorsURL *string `json:"authors_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - Message *string `json:"message,omitempty"` - FailedStep *string `json:"failed_step,omitempty"` - - // Human readable display name, provided when the Import appears as - // part of ProjectChoices. - HumanName *string `json:"human_name,omitempty"` - - // When the importer finds several projects or repositories at the - // provided URLs, this will identify the available choices. Call - // UpdateImport with the selected Import value. - ProjectChoices []Import `json:"project_choices,omitempty"` -} - -func (i Import) String() string { - return Stringify(i) -} - -// SourceImportAuthor identifies an author imported from a source repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -type SourceImportAuthor struct { - ID *int64 `json:"id,omitempty"` - RemoteID *string `json:"remote_id,omitempty"` - RemoteName *string `json:"remote_name,omitempty"` - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - ImportURL *string `json:"import_url,omitempty"` -} - -func (a SourceImportAuthor) String() string { - return Stringify(a) -} - -// LargeFile identifies a file larger than 100MB found during a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -type LargeFile struct { - RefName *string `json:"ref_name,omitempty"` - Path *string `json:"path,omitempty"` - OID *string `json:"oid,omitempty"` - Size *int `json:"size,omitempty"` -} - -func (f LargeFile) String() string { - return Stringify(f) -} - -// StartImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#start-an-import -func (s *MigrationService) StartImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PUT", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// ImportProgress queries for the status and progress of an ongoing repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-import-progress -func (s *MigrationService) ImportProgress(ctx context.Context, owner, repo string) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// UpdateImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#update-existing-import -func (s *MigrationService) UpdateImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// CommitAuthors gets the authors mapped from the original repository. -// -// Each type of source control system represents authors in a different way. -// For example, a Git commit author has a display name and an email address, -// but a Subversion commit author just has a username. The GitHub Importer will -// make the author information valid, but the author might not be correct. For -// example, it will change the bare Subversion username "hubot" into something -// like "hubot ". -// -// This method and MapCommitAuthor allow you to provide correct Git author -// information. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -func (s *MigrationService) CommitAuthors(ctx context.Context, owner, repo string) ([]*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var authors []*SourceImportAuthor - resp, err := s.client.Do(ctx, req, &authors) - if err != nil { - return nil, resp, err - } - - return authors, resp, nil -} - -// MapCommitAuthor updates an author's identity for the import. Your -// application can continue updating authors any time before you push new -// commits to the repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#map-a-commit-author -func (s *MigrationService) MapCommitAuthor(ctx context.Context, owner, repo string, id int64, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, author) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(SourceImportAuthor) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// SetLFSPreference sets whether imported repositories should use Git LFS for -// files larger than 100MB. Only the UseLFS field on the provided Import is -// used. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#set-git-lfs-preference -func (s *MigrationService) SetLFSPreference(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/lfs", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// LargeFiles lists files larger than 100MB found during the import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -func (s *MigrationService) LargeFiles(ctx context.Context, owner, repo string) ([]*LargeFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/large_files", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var files []*LargeFile - resp, err := s.client.Do(ctx, req, &files) - if err != nil { - return nil, resp, err - } - - return files, resp, nil -} - -// CancelImport stops an import for a repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#cancel-an-import -func (s *MigrationService) CancelImport(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/migrations_user.go b/vendor/github.com/google/go-github/github/migrations_user.go deleted file mode 100644 index ae53e6870..000000000 --- a/vendor/github.com/google/go-github/github/migrations_user.go +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "errors" - "fmt" - "net/http" -) - -// UserMigration represents a GitHub migration (archival). -type UserMigration struct { - ID *int64 `json:"id,omitempty"` - GUID *string `json:"guid,omitempty"` - // State is the current state of a migration. - // Possible values are: - // "pending" which means the migration hasn't started yet, - // "exporting" which means the migration is in progress, - // "exported" which means the migration finished successfully, or - // "failed" which means the migration failed. - State *string `json:"state,omitempty"` - // LockRepositories indicates whether repositories are locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` - URL *string `json:"url,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Repositories []*Repository `json:"repositories,omitempty"` -} - -func (m UserMigration) String() string { - return Stringify(m) -} - -// UserMigrationOptions specifies the optional parameters to Migration methods. -type UserMigrationOptions struct { - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories bool - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments bool -} - -// startUserMigration represents the body of a StartMigration request. -type startUserMigration struct { - // Repositories is a slice of repository names to migrate. - Repositories []string `json:"repositories,omitempty"` - - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` -} - -// StartUserMigration starts the generation of a migration archive. -// repos is a slice of repository names to migrate. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#start-a-user-migration -func (s *MigrationService) StartUserMigration(ctx context.Context, repos []string, opt *UserMigrationOptions) (*UserMigration, *Response, error) { - u := "user/migrations" - - body := &startUserMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &UserMigration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListUserMigrations lists the most recent migrations. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#get-a-list-of-user-migrations -func (s *MigrationService) ListUserMigrations(ctx context.Context) ([]*UserMigration, *Response, error) { - u := "user/migrations" - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - var m []*UserMigration - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// UserMigrationStatus gets the status of a specific migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#get-the-status-of-a-user-migration -func (s *MigrationService) UserMigrationStatus(ctx context.Context, id int64) (*UserMigration, *Response, error) { - u := fmt.Sprintf("user/migrations/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &UserMigration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// UserMigrationArchiveURL gets the URL for a specific migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#download-a-user-migration-archive -func (s *MigrationService) UserMigrationArchiveURL(ctx context.Context, id int64) (string, error) { - url := fmt.Sprintf("user/migrations/%v/archive", id) - - req, err := s.client.NewRequest("GET", url, nil) - if err != nil { - return "", err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &UserMigration{} - - var loc string - originalRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return http.ErrUseLastResponse - } - defer func() { - s.client.client.CheckRedirect = originalRedirect - }() - resp, err := s.client.Do(ctx, req, m) - if err == nil { - return "", errors.New("expected redirect, none provided") - } - loc = resp.Header.Get("Location") - return loc, nil -} - -// DeleteUserMigration will delete a previous migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#delete-a-user-migration-archive -func (s *MigrationService) DeleteUserMigration(ctx context.Context, id int64) (*Response, error) { - url := fmt.Sprintf("user/migrations/%v/archive", id) - - req, err := s.client.NewRequest("DELETE", url, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnlockUserRepository will unlock a repo that was locked for migration. -// id is migration ID. -// You should unlock each migrated repository and delete them when the migration -// is complete and you no longer need the source data. -// -// GitHub API docs: https://developer.github.com/v3/migrations/users/#unlock-a-user-repository -func (s *MigrationService) UnlockUserRepo(ctx context.Context, id int64, repo string) (*Response, error) { - url := fmt.Sprintf("user/migrations/%v/repos/%v/lock", id, repo) - - req, err := s.client.NewRequest("DELETE", url, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/misc.go b/vendor/github.com/google/go-github/github/misc.go deleted file mode 100644 index e9b0ea22a..000000000 --- a/vendor/github.com/google/go-github/github/misc.go +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "net/url" -) - -// MarkdownOptions specifies optional parameters to the Markdown method. -type MarkdownOptions struct { - // Mode identifies the rendering mode. Possible values are: - // markdown - render a document as plain Markdown, just like - // README files are rendered. - // - // gfm - to render a document as user-content, e.g. like user - // comments or issues are rendered. In GFM mode, hard line breaks are - // always taken into account, and issue and user mentions are linked - // accordingly. - // - // Default is "markdown". - Mode string - - // Context identifies the repository context. Only taken into account - // when rendering as "gfm". - Context string -} - -type markdownRequest struct { - Text *string `json:"text,omitempty"` - Mode *string `json:"mode,omitempty"` - Context *string `json:"context,omitempty"` -} - -// Markdown renders an arbitrary Markdown document. -// -// GitHub API docs: https://developer.github.com/v3/markdown/ -func (c *Client) Markdown(ctx context.Context, text string, opt *MarkdownOptions) (string, *Response, error) { - request := &markdownRequest{Text: String(text)} - if opt != nil { - if opt.Mode != "" { - request.Mode = String(opt.Mode) - } - if opt.Context != "" { - request.Context = String(opt.Context) - } - } - - req, err := c.NewRequest("POST", "markdown", request) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ListEmojis returns the emojis available to use on GitHub. -// -// GitHub API docs: https://developer.github.com/v3/emojis/ -func (c *Client) ListEmojis(ctx context.Context) (map[string]string, *Response, error) { - req, err := c.NewRequest("GET", "emojis", nil) - if err != nil { - return nil, nil, err - } - - var emoji map[string]string - resp, err := c.Do(ctx, req, &emoji) - if err != nil { - return nil, resp, err - } - - return emoji, resp, nil -} - -// CodeOfConduct represents a code of conduct. -type CodeOfConduct struct { - Name *string `json:"name,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c *CodeOfConduct) String() string { - return Stringify(c) -} - -// ListCodesOfConduct returns all codes of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#list-all-codes-of-conduct -func (c *Client) ListCodesOfConduct(ctx context.Context) ([]*CodeOfConduct, *Response, error) { - req, err := c.NewRequest("GET", "codes_of_conduct", nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - var cs []*CodeOfConduct - resp, err := c.Do(ctx, req, &cs) - if err != nil { - return nil, resp, err - } - - return cs, resp, nil -} - -// GetCodeOfConduct returns an individual code of conduct. -// -// https://developer.github.com/v3/codes_of_conduct/#get-an-individual-code-of-conduct -func (c *Client) GetCodeOfConduct(ctx context.Context, key string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("codes_of_conduct/%s", key) - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := c.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// APIMeta represents metadata about the GitHub API. -type APIMeta struct { - // An Array of IP addresses in CIDR format specifying the addresses - // that incoming service hooks will originate from on GitHub.com. - Hooks []string `json:"hooks,omitempty"` - - // An Array of IP addresses in CIDR format specifying the Git servers - // for GitHub.com. - Git []string `json:"git,omitempty"` - - // Whether authentication with username and password is supported. - // (GitHub Enterprise instances using CAS or OAuth for authentication - // will return false. Features like Basic Authentication with a - // username and password, sudo mode, and two-factor authentication are - // not supported on these servers.) - VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"` - - // An array of IP addresses in CIDR format specifying the addresses - // which serve GitHub Pages websites. - Pages []string `json:"pages,omitempty"` - - // An Array of IP addresses specifying the addresses that source imports - // will originate from on GitHub.com. - Importer []string `json:"importer,omitempty"` -} - -// APIMeta returns information about GitHub.com, the service. Or, if you access -// this endpoint on your organization’s GitHub Enterprise installation, this -// endpoint provides information about that installation. -// -// GitHub API docs: https://developer.github.com/v3/meta/ -func (c *Client) APIMeta(ctx context.Context) (*APIMeta, *Response, error) { - req, err := c.NewRequest("GET", "meta", nil) - if err != nil { - return nil, nil, err - } - - meta := new(APIMeta) - resp, err := c.Do(ctx, req, meta) - if err != nil { - return nil, resp, err - } - - return meta, resp, nil -} - -// Octocat returns an ASCII art octocat with the specified message in a speech -// bubble. If message is empty, a random zen phrase is used. -func (c *Client) Octocat(ctx context.Context, message string) (string, *Response, error) { - u := "octocat" - if message != "" { - u = fmt.Sprintf("%s?s=%s", u, url.QueryEscape(message)) - } - - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// Zen returns a random line from The Zen of GitHub. -// -// see also: http://warpspire.com/posts/taste/ -func (c *Client) Zen(ctx context.Context) (string, *Response, error) { - req, err := c.NewRequest("GET", "zen", nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ServiceHook represents a hook that has configuration settings, a list of -// available events, and default events. -type ServiceHook struct { - Name *string `json:"name,omitempty"` - Events []string `json:"events,omitempty"` - SupportedEvents []string `json:"supported_events,omitempty"` - Schema [][]string `json:"schema,omitempty"` -} - -func (s *ServiceHook) String() string { - return Stringify(s) -} - -// ListServiceHooks lists all of the available service hooks. -// -// GitHub API docs: https://developer.github.com/webhooks/#services -func (c *Client) ListServiceHooks(ctx context.Context) ([]*ServiceHook, *Response, error) { - u := "hooks" - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*ServiceHook - resp, err := c.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs.go b/vendor/github.com/google/go-github/github/orgs.go deleted file mode 100644 index 044dff57a..000000000 --- a/vendor/github.com/google/go-github/github/orgs.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// OrganizationsService provides access to the organization related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/orgs/ -type OrganizationsService service - -// Organization represents a GitHub organization account. -type Organization struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Description *string `json:"description,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - BillingEmail *string `json:"billing_email,omitempty"` - Type *string `json:"type,omitempty"` - Plan *Plan `json:"plan,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - PublicMembersURL *string `json:"public_members_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` -} - -func (o Organization) String() string { - return Stringify(o) -} - -// Plan represents the payment plan for an account. See plans at https://github.com/plans. -type Plan struct { - Name *string `json:"name,omitempty"` - Space *int `json:"space,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - PrivateRepos *int `json:"private_repos,omitempty"` -} - -func (p Plan) String() string { - return Stringify(p) -} - -// OrganizationsListOptions specifies the optional parameters to the -// OrganizationsService.ListAll method. -type OrganizationsListOptions struct { - // Since filters Organizations by ID. - Since int64 `url:"since,omitempty"` - - // Note: Pagination is powered exclusively by the Since parameter, - // ListOptions.Page has no effect. - // ListOptions.PerPage controls an undocumented GitHub API parameter. - ListOptions -} - -// ListAll lists all organizations, in the order that they were created on GitHub. -// -// Note: Pagination is powered exclusively by the since parameter. To continue -// listing the next set of organizations, use the ID of the last-returned organization -// as the opts.Since parameter for the next call. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations -func (s *OrganizationsService) ListAll(ctx context.Context, opt *OrganizationsListOptions) ([]*Organization, *Response, error) { - u, err := addOptions("organizations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - orgs := []*Organization{} - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - return orgs, resp, nil -} - -// List the organizations for a user. Passing the empty string will list -// organizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-user-organizations -func (s *OrganizationsService) List(ctx context.Context, user string, opt *ListOptions) ([]*Organization, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/orgs", user) - } else { - u = "user/orgs" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var orgs []*Organization - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - - return orgs, resp, nil -} - -// Get fetches an organization by name. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#get-an-organization -func (s *OrganizationsService) Get(ctx context.Context, org string) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", org) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// GetByID fetches an organization. -// -// Note: GetByID uses the undocumented GitHub API endpoint /organizations/:id. -func (s *OrganizationsService) GetByID(ctx context.Context, id int64) (*Organization, *Response, error) { - u := fmt.Sprintf("organizations/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// Edit an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#edit-an-organization -func (s *OrganizationsService) Edit(ctx context.Context, name string, org *Organization) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", name) - req, err := s.client.NewRequest("PATCH", u, org) - if err != nil { - return nil, nil, err - } - - o := new(Organization) - resp, err := s.client.Do(ctx, req, o) - if err != nil { - return nil, resp, err - } - - return o, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_hooks.go b/vendor/github.com/google/go-github/github/orgs_hooks.go deleted file mode 100644 index ab1d02da7..000000000 --- a/vendor/github.com/google/go-github/github/orgs_hooks.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListHooks lists all Hooks for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks -func (s *OrganizationsService) ListHooks(ctx context.Context, org string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook -func (s *OrganizationsService) GetHook(ctx context.Context, org string, id int64) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - hook := new(Hook) - resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err -} - -// CreateHook creates a Hook for the specified org. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook -func (s *OrganizationsService) CreateHook(ctx context.Context, org string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook -func (s *OrganizationsService) EditHook(ctx context.Context, org string, id int64, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - return h, resp, err -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook -func (s *OrganizationsService) PingHook(ctx context.Context, org string, id int64) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d/pings", org, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook -func (s *OrganizationsService) DeleteHook(ctx context.Context, org string, id int64) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/orgs_members.go b/vendor/github.com/google/go-github/github/orgs_members.go deleted file mode 100644 index d18435999..000000000 --- a/vendor/github.com/google/go-github/github/orgs_members.go +++ /dev/null @@ -1,370 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Membership represents the status of a user's membership in an organization or team. -type Membership struct { - URL *string `json:"url,omitempty"` - - // State is the user's status within the organization or team. - // Possible values are: "active", "pending" - State *string `json:"state,omitempty"` - - // Role identifies the user's role within the organization or team. - // Possible values for organization membership: - // member - non-owner organization member - // admin - organization owner - // - // Possible values for team membership are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - Role *string `json:"role,omitempty"` - - // For organization membership, the API URL of the organization. - OrganizationURL *string `json:"organization_url,omitempty"` - - // For organization membership, the organization the membership is for. - Organization *Organization `json:"organization,omitempty"` - - // For organization membership, the user the membership is for. - User *User `json:"user,omitempty"` -} - -func (m Membership) String() string { - return Stringify(m) -} - -// ListMembersOptions specifies optional parameters to the -// OrganizationsService.ListMembers method. -type ListMembersOptions struct { - // If true (or if the authenticated user is not an owner of the - // organization), list only publicly visible members. - PublicOnly bool `url:"-"` - - // Filter members returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - // Role filters members returned by their role in the organization. - // Possible values are: - // all - all members of the organization, regardless of role - // admin - organization owners - // member - non-owner organization members - // - // Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListMembers lists the members for an organization. If the authenticated -// user is an owner of the organization, this will return both concealed and -// public members, otherwise it will only return public members. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#members-list -func (s *OrganizationsService) ListMembers(ctx context.Context, org string, opt *ListMembersOptions) ([]*User, *Response, error) { - var u string - if opt != nil && opt.PublicOnly { - u = fmt.Sprintf("orgs/%v/public_members", org) - } else { - u = fmt.Sprintf("orgs/%v/members", org) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsMember checks if a user is a member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-membership -func (s *OrganizationsService) IsMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// IsPublicMember checks if a user is a public member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-public-membership -func (s *OrganizationsService) IsPublicMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// RemoveMember removes a user from all teams of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-a-member -func (s *OrganizationsService) RemoveMember(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// PublicizeMembership publicizes a user's membership in an organization. (A -// user cannot publicize the membership for another user.) -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#publicize-a-users-membership -func (s *OrganizationsService) PublicizeMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ConcealMembership conceals a user's membership in an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#conceal-a-users-membership -func (s *OrganizationsService) ConcealMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListOrgMembershipsOptions specifies optional parameters to the -// OrganizationsService.ListOrgMemberships method. -type ListOrgMembershipsOptions struct { - // Filter memberships to include only those with the specified state. - // Possible values are: "active", "pending". - State string `url:"state,omitempty"` - - ListOptions -} - -// ListOrgMemberships lists the organization memberships for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships -func (s *OrganizationsService) ListOrgMemberships(ctx context.Context, opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error) { - u := "user/memberships/orgs" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var memberships []*Membership - resp, err := s.client.Do(ctx, req, &memberships) - if err != nil { - return nil, resp, err - } - - return memberships, resp, nil -} - -// GetOrgMembership gets the membership for a user in a specified organization. -// Passing an empty string for user will get the membership for the -// authenticated user. -// -// GitHub API docs: -// https://developer.github.com/v3/orgs/members/#get-organization-membership -// https://developer.github.com/v3/orgs/members/#get-your-organization-membership -func (s *OrganizationsService) GetOrgMembership(ctx context.Context, user, org string) (*Membership, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - membership := new(Membership) - resp, err := s.client.Do(ctx, req, membership) - if err != nil { - return nil, resp, err - } - - return membership, resp, nil -} - -// EditOrgMembership edits the membership for user in specified organization. -// Passing an empty string for user will edit the membership for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership -// GitHub API docs: https://developer.github.com/v3/orgs/members/#edit-your-organization-membership -func (s *OrganizationsService) EditOrgMembership(ctx context.Context, user, org string, membership *Membership) (*Membership, *Response, error) { - var u, method string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - method = "PUT" - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - method = "PATCH" - } - - req, err := s.client.NewRequest(method, u, membership) - if err != nil { - return nil, nil, err - } - - m := new(Membership) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// RemoveOrgMembership removes user from the specified organization. If the -// user has been invited to the organization, this will cancel their invitation. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-organization-membership -func (s *OrganizationsService) RemoveOrgMembership(ctx context.Context, user, org string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/memberships/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingOrgInvitations returns a list of pending invitations. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations -func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, org string, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("orgs/%v/invitations", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - return pendingInvitations, resp, nil -} - -// CreateOrgInvitationOptions specifies the parameters to the OrganizationService.Invite -// method. -type CreateOrgInvitationOptions struct { - // GitHub user ID for the person you are inviting. Not required if you provide Email. - InviteeID *int64 `json:"invitee_id,omitempty"` - // Email address of the person you are inviting, which can be an existing GitHub user. - // Not required if you provide InviteeID - Email *string `json:"email,omitempty"` - // Specify role for new member. Can be one of: - // * admin - Organization owners with full administrative rights to the - // organization and complete access to all repositories and teams. - // * direct_member - Non-owner organization members with ability to see - // other members and join teams by invitation. - // * billing_manager - Non-owner organization members with ability to - // manage the billing settings of your organization. - // Default is "direct_member". - Role *string `json:"role"` - TeamID []int64 `json:"team_ids"` -} - -// CreateOrgInvitation invites people to an organization by using their GitHub user ID or their email address. -// In order to create invitations in an organization, -// the authenticated user must be an organization owner. -// -// https://developer.github.com/v3/orgs/members/#create-organization-invitation -func (s *OrganizationsService) CreateOrgInvitation(ctx context.Context, org string, opt *CreateOrgInvitationOptions) (*Invitation, *Response, error) { - u := fmt.Sprintf("orgs/%v/invitations", org) - - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeOrganizationInvitationPreview) - - var invitation *Invitation - resp, err := s.client.Do(ctx, req, &invitation) - if err != nil { - return nil, resp, err - } - return invitation, resp, nil -} - -// ListOrgInvitationTeams lists all teams associated with an invitation. In order to see invitations in an organization, -// the authenticated user must be an organization owner. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-organization-invitation-teams -func (s *OrganizationsService) ListOrgInvitationTeams(ctx context.Context, org, invitationID string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/invitations/%v/teams", org, invitationID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeOrganizationInvitationPreview) - - var orgInvitationTeams []*Team - resp, err := s.client.Do(ctx, req, &orgInvitationTeams) - if err != nil { - return nil, resp, err - } - return orgInvitationTeams, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go b/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go deleted file mode 100644 index 85ffd05f6..000000000 --- a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListOutsideCollaboratorsOptions specifies optional parameters to the -// OrganizationsService.ListOutsideCollaborators method. -type ListOutsideCollaboratorsOptions struct { - // Filter outside collaborators returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - ListOptions -} - -// ListOutsideCollaborators lists outside collaborators of organization's repositories. -// This will only work if the authenticated -// user is an owner of the organization. -// -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#list-outside-collaborators -func (s *OrganizationsService) ListOutsideCollaborators(ctx context.Context, org string, opt *ListOutsideCollaboratorsOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// RemoveOutsideCollaborator removes a user from the list of outside collaborators; -// consequently, removing them from all the organization's repositories. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#remove-outside-collaborator -func (s *OrganizationsService) RemoveOutsideCollaborator(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ConvertMemberToOutsideCollaborator reduces the permission level of a member of the -// organization to that of an outside collaborator. Therefore, they will only -// have access to the repositories that their current team membership allows. -// Responses for converting a non-member or the last owner to an outside collaborator -// are listed in GitHub API docs. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#convert-member-to-outside-collaborator -func (s *OrganizationsService) ConvertMemberToOutsideCollaborator(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators/%v", org, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/orgs_projects.go b/vendor/github.com/google/go-github/github/orgs_projects.go deleted file mode 100644 index e57cba978..000000000 --- a/vendor/github.com/google/go-github/github/orgs_projects.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListProjects lists the projects for an organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-organization-projects -func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-an-organization-project -func (s *OrganizationsService) CreateProject(ctx context.Context, org string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_users_blocking.go b/vendor/github.com/google/go-github/github/orgs_users_blocking.go deleted file mode 100644 index b1aecf445..000000000 --- a/vendor/github.com/google/go-github/github/orgs_users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the users blocked by an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#list-blocked-users -func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#check-whether-a-user-is-blocked-from-an-organization -func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#block-a-user -func (s *OrganizationsService) BlockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#unblock-a-user -func (s *OrganizationsService) UnblockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/projects.go b/vendor/github.com/google/go-github/github/projects.go deleted file mode 100644 index 76ef1e0a3..000000000 --- a/vendor/github.com/google/go-github/github/projects.go +++ /dev/null @@ -1,462 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ProjectsService provides access to the projects functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/projects/ -type ProjectsService service - -// Project represents a GitHub Project. -type Project struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - ColumnsURL *string `json:"columns_url,omitempty"` - OwnerURL *string `json:"owner_url,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // The User object that generated the project. - Creator *User `json:"creator,omitempty"` -} - -func (p Project) String() string { - return Stringify(p) -} - -// GetProject gets a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#get-a-project -func (s *ProjectsService) GetProject(ctx context.Context, id int64) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// ProjectOptions specifies the parameters to the -// RepositoriesService.CreateProject and -// ProjectsService.UpdateProject methods. -type ProjectOptions struct { - // The name of the project. (Required for creation; optional for update.) - Name *string `json:"name,omitempty"` - // The body of the project. (Optional.) - Body *string `json:"body,omitempty"` - - // The following field(s) are only applicable for update. - // They should be left with zero values for creation. - - // State of the project. Either "open" or "closed". (Optional.) - State *string `json:"state,omitempty"` - // The permission level that all members of the project's organization - // will have on this project. - // Setting the organization permission is only available - // for organization projects. (Optional.) - OrganizationPermission *string `json:"organization_permission,omitempty"` - // Sets visibility of the project within the organization. - // Setting visibility is only available - // for organization projects.(Optional.) - Public *bool `json:"public,omitempty"` -} - -// UpdateProject updates a repository project. -// -// GitHub API docs: https://developer.github.com/v3/projects/#update-a-project -func (s *ProjectsService) UpdateProject(ctx context.Context, id int64, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// DeleteProject deletes a GitHub Project from a repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#delete-a-project -func (s *ProjectsService) DeleteProject(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumn represents a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/repos/projects/ -type ProjectColumn struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - ProjectURL *string `json:"project_url,omitempty"` - CardsURL *string `json:"cards_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// ListProjectColumns lists the columns of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#list-project-columns -func (s *ProjectsService) ListProjectColumns(ctx context.Context, projectID int64, opt *ListOptions) ([]*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - columns := []*ProjectColumn{} - resp, err := s.client.Do(ctx, req, &columns) - if err != nil { - return nil, resp, err - } - - return columns, resp, nil -} - -// GetProjectColumn gets a column of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#get-a-project-column -func (s *ProjectsService) GetProjectColumn(ctx context.Context, id int64) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// ProjectColumnOptions specifies the parameters to the -// ProjectsService.CreateProjectColumn and -// ProjectsService.UpdateProjectColumn methods. -type ProjectColumnOptions struct { - // The name of the project column. (Required for creation and update.) - Name string `json:"name"` -} - -// CreateProjectColumn creates a column for the specified (by number) project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#create-a-project-column -func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// UpdateProjectColumn updates a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#update-a-project-column -func (s *ProjectsService) UpdateProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// DeleteProjectColumn deletes a column from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#delete-a-project-column -func (s *ProjectsService) DeleteProjectColumn(ctx context.Context, columnID int64) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumnMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectColumn method. -type ProjectColumnMoveOptions struct { - // Position can be one of "first", "last", or "after:", where - // is the ID of a column in the same project. (Required.) - Position string `json:"position"` -} - -// MoveProjectColumn moves a column within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#move-a-project-column -func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v/moves", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCard represents a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -type ProjectCard struct { - URL *string `json:"url,omitempty"` - ColumnURL *string `json:"column_url,omitempty"` - ContentURL *string `json:"content_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Note *string `json:"note,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Archived *bool `json:"archived,omitempty"` - - // The following fields are only populated by Webhook events. - ColumnID *int64 `json:"column_id,omitempty"` -} - -// ProjectCardListOptions specifies the optional parameters to the -// ProjectsService.ListProjectCards method. -type ProjectCardListOptions struct { - // ArchivedState is used to list all, archived, or not_archived project cards. - // Defaults to not_archived when you omit this parameter. - ArchivedState *string `url:"archived_state,omitempty"` - - ListOptions -} - -// ListProjectCards lists the cards in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#list-project-cards -func (s *ProjectsService) ListProjectCards(ctx context.Context, columnID int64, opt *ProjectCardListOptions) ([]*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - cards := []*ProjectCard{} - resp, err := s.client.Do(ctx, req, &cards) - if err != nil { - return nil, resp, err - } - - return cards, resp, nil -} - -// GetProjectCard gets a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -func (s *ProjectsService) GetProjectCard(ctx context.Context, columnID int64) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", columnID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// ProjectCardOptions specifies the parameters to the -// ProjectsService.CreateProjectCard and -// ProjectsService.UpdateProjectCard methods. -type ProjectCardOptions struct { - // The note of the card. Note and ContentID are mutually exclusive. - Note string `json:"note,omitempty"` - // The ID (not Number) of the Issue to associate with this card. - // Note and ContentID are mutually exclusive. - ContentID int64 `json:"content_id,omitempty"` - // The type of content to associate with this card. Possible values are: "Issue". - ContentType string `json:"content_type,omitempty"` - // Use true to archive a project card. - // Specify false if you need to restore a previously archived project card. - Archived *bool `json:"archived,omitempty"` -} - -// CreateProjectCard creates a card in the specified column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#create-a-project-card -func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// UpdateProjectCard updates a card of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#update-a-project-card -func (s *ProjectsService) UpdateProjectCard(ctx context.Context, cardID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// DeleteProjectCard deletes a card from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#delete-a-project-card -func (s *ProjectsService) DeleteProjectCard(ctx context.Context, cardID int64) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCardMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectCard method. -type ProjectCardMoveOptions struct { - // Position can be one of "top", "bottom", or "after:", where - // is the ID of a card in the same project. - Position string `json:"position"` - // ColumnID is the ID of a column in the same project. Note that ColumnID - // is required when using Position "after:" when that card is in - // another column; otherwise it is optional. - ColumnID int64 `json:"column_id,omitempty"` -} - -// MoveProjectCard moves a card within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#move-a-project-card -func (s *ProjectsService) MoveProjectCard(ctx context.Context, cardID int64, opt *ProjectCardMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v/moves", cardID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls.go b/vendor/github.com/google/go-github/github/pulls.go deleted file mode 100644 index a123ec568..000000000 --- a/vendor/github.com/google/go-github/github/pulls.go +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "strings" - "time" -) - -// PullRequestsService handles communication with the pull request related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/pulls/ -type PullRequestsService service - -// PullRequest represents a GitHub pull request on a repository. -type PullRequest struct { - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - MergedAt *time.Time `json:"merged_at,omitempty"` - Labels []*Label `json:"labels,omitempty"` - User *User `json:"user,omitempty"` - Merged *bool `json:"merged,omitempty"` - Mergeable *bool `json:"mergeable,omitempty"` - MergeableState *string `json:"mergeable_state,omitempty"` - MergedBy *User `json:"merged_by,omitempty"` - MergeCommitSHA *string `json:"merge_commit_sha,omitempty"` - Comments *int `json:"comments,omitempty"` - Commits *int `json:"commits,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - ChangedFiles *int `json:"changed_files,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - CommitsURL *string `json:"commits_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - ReviewCommentsURL *string `json:"review_comments_url,omitempty"` - ReviewCommentURL *string `json:"review_comment_url,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` - AuthorAssociation *string `json:"author_association,omitempty"` - NodeID *string `json:"node_id,omitempty"` - RequestedReviewers []*User `json:"requested_reviewers,omitempty"` - - Head *PullRequestBranch `json:"head,omitempty"` - Base *PullRequestBranch `json:"base,omitempty"` - - // ActiveLockReason is populated only when LockReason is provided while locking the pull request. - // Possible values are: "off-topic", "too heated", "resolved", and "spam". - ActiveLockReason *string `json:"active_lock_reason,omitempty"` -} - -func (p PullRequest) String() string { - return Stringify(p) -} - -// PullRequestBranch represents a base or head branch in a GitHub pull request. -type PullRequestBranch struct { - Label *string `json:"label,omitempty"` - Ref *string `json:"ref,omitempty"` - SHA *string `json:"sha,omitempty"` - Repo *Repository `json:"repo,omitempty"` - User *User `json:"user,omitempty"` -} - -// PullRequestListOptions specifies the optional parameters to the -// PullRequestsService.List method. -type PullRequestListOptions struct { - // State filters pull requests based on their state. Possible values are: - // open, closed. Default is "open". - State string `url:"state,omitempty"` - - // Head filters pull requests by head user and branch name in the format of: - // "user:ref-name". - Head string `url:"head,omitempty"` - - // Base filters pull requests by base branch name. - Base string `url:"base,omitempty"` - - // Sort specifies how to sort pull requests. Possible values are: created, - // updated, popularity, long-running. Default is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort pull requests. Possible values are: asc, desc. - // If Sort is "created" or not specified, Default is "desc", otherwise Default - // is "asc" - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the pull requests for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests -func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - acceptHeaders := []string{mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var pulls []*PullRequest - resp, err := s.client.Do(ctx, req, &pulls) - if err != nil { - return nil, resp, err - } - - return pulls, resp, nil -} - -// Get a single pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-a-single-pull-request -func (s *PullRequestsService) Get(ctx context.Context, owner string, repo string, number int) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - acceptHeaders := []string{mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - pull := new(PullRequest) - resp, err := s.client.Do(ctx, req, pull) - if err != nil { - return nil, resp, err - } - - return pull, resp, nil -} - -// GetRaw gets a single pull request in raw (diff or patch) format. -func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opt RawOptions) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - switch opt.Type { - case Diff: - req.Header.Set("Accept", mediaTypeV3Diff) - case Patch: - req.Header.Set("Accept", mediaTypeV3Patch) - default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) - } - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// NewPullRequest represents a new pull request to be created. -type NewPullRequest struct { - Title *string `json:"title,omitempty"` - Head *string `json:"head,omitempty"` - Base *string `json:"base,omitempty"` - Body *string `json:"body,omitempty"` - Issue *int `json:"issue,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Create a new pull request on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#create-a-pull-request -func (s *PullRequestsService) Create(ctx context.Context, owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - req, err := s.client.NewRequest("POST", u, pull) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -type pullRequestUpdate struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - State *string `json:"state,omitempty"` - Base *string `json:"base,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Edit a pull request. -// pull must not be nil. -// -// The following fields are editable: Title, Body, State, Base.Ref and MaintainerCanModify. -// Base.Ref updates the base branch of the pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#update-a-pull-request -func (s *PullRequestsService) Edit(ctx context.Context, owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error) { - if pull == nil { - return nil, nil, fmt.Errorf("pull must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - - update := &pullRequestUpdate{ - Title: pull.Title, - Body: pull.Body, - State: pull.State, - MaintainerCanModify: pull.MaintainerCanModify, - } - if pull.Base != nil { - update.Base = pull.Base.Ref - } - - req, err := s.client.NewRequest("PATCH", u, update) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - acceptHeaders := []string{mediaTypeLabelDescriptionSearchPreview, mediaTypeLockReasonPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListCommits lists the commits in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request -func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/commits", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// ListFiles lists the files in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files -func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/files", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var commitFiles []*CommitFile - resp, err := s.client.Do(ctx, req, &commitFiles) - if err != nil { - return nil, resp, err - } - - return commitFiles, resp, nil -} - -// IsMerged checks if a pull request has been merged. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged -func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo string, number int) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - merged, err := parseBoolResponse(err) - return merged, resp, err -} - -// PullRequestMergeResult represents the result of merging a pull request. -type PullRequestMergeResult struct { - SHA *string `json:"sha,omitempty"` - Merged *bool `json:"merged,omitempty"` - Message *string `json:"message,omitempty"` -} - -// PullRequestOptions lets you define how a pull request will be merged. -type PullRequestOptions struct { - CommitTitle string // Extra detail to append to automatic commit message. (Optional.) - SHA string // SHA that pull request head must match to allow merge. (Optional.) - - // The merge method to use. Possible values include: "merge", "squash", and "rebase" with the default being merge. (Optional.) - MergeMethod string -} - -type pullRequestMergeRequest struct { - CommitMessage string `json:"commit_message"` - CommitTitle string `json:"commit_title,omitempty"` - MergeMethod string `json:"merge_method,omitempty"` - SHA string `json:"sha,omitempty"` -} - -// Merge a pull request (Merge Button™). -// commitMessage is the title for the automatic commit message. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade -func (s *PullRequestsService) Merge(ctx context.Context, owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - - pullRequestBody := &pullRequestMergeRequest{CommitMessage: commitMessage} - if options != nil { - pullRequestBody.CommitTitle = options.CommitTitle - pullRequestBody.MergeMethod = options.MergeMethod - pullRequestBody.SHA = options.SHA - } - req, err := s.client.NewRequest("PUT", u, pullRequestBody) - if err != nil { - return nil, nil, err - } - - mergeResult := new(PullRequestMergeResult) - resp, err := s.client.Do(ctx, req, mergeResult) - if err != nil { - return nil, resp, err - } - - return mergeResult, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/pulls_comments.go b/vendor/github.com/google/go-github/github/pulls_comments.go deleted file mode 100644 index f30677625..000000000 --- a/vendor/github.com/google/go-github/github/pulls_comments.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestComment represents a comment left on a pull request. -type PullRequestComment struct { - ID *int64 `json:"id,omitempty"` - InReplyTo *int64 `json:"in_reply_to_id,omitempty"` - Body *string `json:"body,omitempty"` - Path *string `json:"path,omitempty"` - DiffHunk *string `json:"diff_hunk,omitempty"` - PullRequestReviewID *int64 `json:"pull_request_review_id,omitempty"` - Position *int `json:"position,omitempty"` - OriginalPosition *int `json:"original_position,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - OriginalCommitID *string `json:"original_commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // AuthorAssociation is the comment author's relationship to the pull request's repository. - // Possible values are "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MEMBER", "OWNER", or "NONE". - AuthorAssociation *string `json:"author_association,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` -} - -func (p PullRequestComment) String() string { - return Stringify(p) -} - -// PullRequestListCommentsOptions specifies the optional parameters to the -// PullRequestsService.ListComments method. -type PullRequestListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified pull request. Specifying a -// pull request number of 0 will return all comments on all pull requests for -// the repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request -func (s *PullRequestsService) ListComments(ctx context.Context, owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/pulls/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment -func (s *PullRequestsService) GetComment(ctx context.Context, owner string, repo string, commentID int64) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, commentID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment -func (s *PullRequestsService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// CreateCommentInReplyTo creates a new comment as a reply to an existing pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#alternative-input -func (s *PullRequestsService) CreateCommentInReplyTo(ctx context.Context, owner string, repo string, number int, body string, commentID int64) (*PullRequestComment, *Response, error) { - comment := &struct { - Body string `json:"body,omitempty"` - InReplyTo int64 `json:"in_reply_to,omitempty"` - }{ - Body: body, - InReplyTo: commentID, - } - u := fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates a pull request comment. -// A non-nil comment.Body must be provided. Other comment fields should be left nil. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#edit-a-comment -func (s *PullRequestsService) EditComment(ctx context.Context, owner string, repo string, commentID int64, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, commentID) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#delete-a-comment -func (s *PullRequestsService) DeleteComment(ctx context.Context, owner string, repo string, commentID int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, commentID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviewers.go b/vendor/github.com/google/go-github/github/pulls_reviewers.go deleted file mode 100644 index a1d785315..000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviewers.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ReviewersRequest specifies users and teams for a pull request review request. -type ReviewersRequest struct { - Reviewers []string `json:"reviewers,omitempty"` - TeamReviewers []string `json:"team_reviewers,omitempty"` -} - -// Reviewers represents reviewers of a pull request. -type Reviewers struct { - Users []*User `json:"users,omitempty"` - Teams []*Team `json:"teams,omitempty"` -} - -// RequestReviewers creates a review request for the provided reviewers for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#create-a-review-request -func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - req, err := s.client.NewRequest("POST", u, &reviewers) - if err != nil { - return nil, nil, err - } - - r := new(PullRequest) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// ListReviewers lists reviewers whose reviews have been requested on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#list-review-requests -func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opt *ListOptions) (*Reviewers, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/requested_reviewers", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - reviewers := new(Reviewers) - resp, err := s.client.Do(ctx, req, reviewers) - if err != nil { - return nil, resp, err - } - - return reviewers, resp, nil -} - -// RemoveReviewers removes the review request for the provided reviewers for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#delete-a-review-request -func (s *PullRequestsService) RemoveReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, &reviewers) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviews.go b/vendor/github.com/google/go-github/github/pulls_reviews.go deleted file mode 100644 index 57d3c635e..000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviews.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestReview represents a review of a pull request. -type PullRequestReview struct { - ID *int64 `json:"id,omitempty"` - User *User `json:"user,omitempty"` - Body *string `json:"body,omitempty"` - SubmittedAt *time.Time `json:"submitted_at,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` - State *string `json:"state,omitempty"` -} - -func (p PullRequestReview) String() string { - return Stringify(p) -} - -// DraftReviewComment represents a comment part of the review. -type DraftReviewComment struct { - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c DraftReviewComment) String() string { - return Stringify(c) -} - -// PullRequestReviewRequest represents a request to create a review. -type PullRequestReviewRequest struct { - CommitID *string `json:"commit_id,omitempty"` - Body *string `json:"body,omitempty"` - Event *string `json:"event,omitempty"` - Comments []*DraftReviewComment `json:"comments,omitempty"` -} - -func (r PullRequestReviewRequest) String() string { - return Stringify(r) -} - -// PullRequestReviewDismissalRequest represents a request to dismiss a review. -type PullRequestReviewDismissalRequest struct { - Message *string `json:"message,omitempty"` -} - -func (r PullRequestReviewDismissalRequest) String() string { - return Stringify(r) -} - -// ListReviews lists all reviews on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request -func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var reviews []*PullRequestReview - resp, err := s.client.Do(ctx, req, &reviews) - if err != nil { - return nil, resp, err - } - - return reviews, resp, nil -} - -// GetReview fetches the specified pull request review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-a-single-review -func (s *PullRequestsService) GetReview(ctx context.Context, owner, repo string, number int, reviewID int64) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// DeletePendingReview deletes the specified pull request pending review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#delete-a-pending-review -func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, repo string, number int, reviewID int64) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// ListReviewComments lists all the comments for the specified review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review -func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number int, reviewID int64, opt *ListOptions) ([]*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/comments", owner, repo, number, reviewID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateReview creates a new review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review -func (s *PullRequestsService) CreateReview(ctx context.Context, owner, repo string, number int, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// SubmitReview submits a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#submit-a-pull-request-review -func (s *PullRequestsService) SubmitReview(ctx context.Context, owner, repo string, number int, reviewID int64, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/events", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DismissReview dismisses a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#dismiss-a-pull-request-review -func (s *PullRequestsService) DismissReview(ctx context.Context, owner, repo string, number int, reviewID int64, review *PullRequestReviewDismissalRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/dismissals", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("PUT", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/reactions.go b/vendor/github.com/google/go-github/github/reactions.go deleted file mode 100644 index ddc055cb1..000000000 --- a/vendor/github.com/google/go-github/github/reactions.go +++ /dev/null @@ -1,375 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ReactionsService provides access to the reactions-related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/reactions/ -type ReactionsService service - -// Reaction represents a GitHub reaction. -type Reaction struct { - // ID is the Reaction ID. - ID *int64 `json:"id,omitempty"` - User *User `json:"user,omitempty"` - NodeID *string `json:"node_id,omitempty"` - // Content is the type of reaction. - // Possible values are: - // "+1", "-1", "laugh", "confused", "heart", "hooray". - Content *string `json:"content,omitempty"` -} - -// Reactions represents a summary of GitHub reactions. -type Reactions struct { - TotalCount *int `json:"total_count,omitempty"` - PlusOne *int `json:"+1,omitempty"` - MinusOne *int `json:"-1,omitempty"` - Laugh *int `json:"laugh,omitempty"` - Confused *int `json:"confused,omitempty"` - Heart *int `json:"heart,omitempty"` - Hooray *int `json:"hooray,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (r Reaction) String() string { - return Stringify(r) -} - -// ListCommentReactions lists the reactions for a commit comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment -func (s *ReactionsService) ListCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateCommentReaction creates a reaction for a commit comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-commit-comment -func (s ReactionsService) CreateCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueReactions lists the reactions for an issue. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue -func (s *ReactionsService) ListIssueReactions(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueReaction creates a reaction for an issue. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue -func (s ReactionsService) CreateIssueReaction(ctx context.Context, owner, repo string, number int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueCommentReactions lists the reactions for an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListIssueCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueCommentReaction creates a reaction for an issue comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreateIssueCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListPullRequestCommentReactions lists the reactions for a pull request review comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListPullRequestCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreatePullRequestCommentReaction creates a reaction for a pull request review comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreatePullRequestCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListTeamDiscussionReactions lists the reactions for a team discussion. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion -func (s *ReactionsService) ListTeamDiscussionReactions(ctx context.Context, teamID int64, discussionNumber int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/reactions", teamID, discussionNumber) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateTeamDiscussionReaction creates a reaction for a team discussion. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-team-discussion -func (s *ReactionsService) CreateTeamDiscussionReaction(ctx context.Context, teamID int64, discussionNumber int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/reactions", teamID, discussionNumber) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListTeamDiscussionCommentReactions lists the reactions for a team discussion comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment -func (s *ReactionsService) ListTeamDiscussionCommentReactions(ctx context.Context, teamID int64, discussionNumber, commentNumber int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v/reactions", teamID, discussionNumber, commentNumber) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - - return m, resp, nil -} - -// CreateTeamDiscussionCommentReaction creates a reaction for a team discussion comment. -// The content should have one of the following values: "+1", "-1", "laugh", "confused", "heart", "hooray". -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-team-discussion-comment -func (s *ReactionsService) CreateTeamDiscussionCommentReaction(ctx context.Context, teamID int64, discussionNumber, commentNumber int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v/reactions", teamID, discussionNumber, commentNumber) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteReaction deletes a reaction. -// -// GitHub API docs: https://developer.github.com/v3/reaction/reactions/#delete-a-reaction-archive -func (s *ReactionsService) DeleteReaction(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("reactions/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos.go b/vendor/github.com/google/go-github/github/repos.go deleted file mode 100644 index fe05272a9..000000000 --- a/vendor/github.com/google/go-github/github/repos.go +++ /dev/null @@ -1,1082 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" -) - -// RepositoriesService handles communication with the repository related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/repos/ -type RepositoriesService service - -// Repository represents a GitHub repository. -type Repository struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Description *string `json:"description,omitempty"` - Homepage *string `json:"homepage,omitempty"` - CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - MirrorURL *string `json:"mirror_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` - Language *string `json:"language,omitempty"` - Fork *bool `json:"fork,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - NetworkCount *int `json:"network_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - SubscribersCount *int `json:"subscribers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Size *int `json:"size,omitempty"` - AutoInit *bool `json:"auto_init,omitempty"` - Parent *Repository `json:"parent,omitempty"` - Source *Repository `json:"source,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Permissions *map[string]bool `json:"permissions,omitempty"` - AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` - AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` - AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` - Topics []string `json:"topics,omitempty"` - - // Only provided when using RepositoriesService.Get while in preview - License *License `json:"license,omitempty"` - - // Additional mutable fields when creating and editing a repository - Private *bool `json:"private,omitempty"` - HasIssues *bool `json:"has_issues,omitempty"` - HasWiki *bool `json:"has_wiki,omitempty"` - HasPages *bool `json:"has_pages,omitempty"` - HasProjects *bool `json:"has_projects,omitempty"` - HasDownloads *bool `json:"has_downloads,omitempty"` - LicenseTemplate *string `json:"license_template,omitempty"` - GitignoreTemplate *string `json:"gitignore_template,omitempty"` - Archived *bool `json:"archived,omitempty"` - - // Creating an organization repository. Required for non-owners. - TeamID *int64 `json:"team_id,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - AssigneesURL *string `json:"assignees_url,omitempty"` - BlobsURL *string `json:"blobs_url,omitempty"` - BranchesURL *string `json:"branches_url,omitempty"` - CollaboratorsURL *string `json:"collaborators_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - CommitsURL *string `json:"commits_url,omitempty"` - CompareURL *string `json:"compare_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` - ContributorsURL *string `json:"contributors_url,omitempty"` - DeploymentsURL *string `json:"deployments_url,omitempty"` - DownloadsURL *string `json:"downloads_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ForksURL *string `json:"forks_url,omitempty"` - GitCommitsURL *string `json:"git_commits_url,omitempty"` - GitRefsURL *string `json:"git_refs_url,omitempty"` - GitTagsURL *string `json:"git_tags_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssueCommentURL *string `json:"issue_comment_url,omitempty"` - IssueEventsURL *string `json:"issue_events_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - KeysURL *string `json:"keys_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - LanguagesURL *string `json:"languages_url,omitempty"` - MergesURL *string `json:"merges_url,omitempty"` - MilestonesURL *string `json:"milestones_url,omitempty"` - NotificationsURL *string `json:"notifications_url,omitempty"` - PullsURL *string `json:"pulls_url,omitempty"` - ReleasesURL *string `json:"releases_url,omitempty"` - StargazersURL *string `json:"stargazers_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - SubscribersURL *string `json:"subscribers_url,omitempty"` - SubscriptionURL *string `json:"subscription_url,omitempty"` - TagsURL *string `json:"tags_url,omitempty"` - TreesURL *string `json:"trees_url,omitempty"` - TeamsURL *string `json:"teams_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (r Repository) String() string { - return Stringify(r) -} - -// RepositoryListOptions specifies the optional parameters to the -// RepositoriesService.List method. -type RepositoryListOptions struct { - // Visibility of repositories to list. Can be one of all, public, or private. - // Default: all - Visibility string `url:"visibility,omitempty"` - - // List repos of given affiliation[s]. - // Comma-separated list of values. Can include: - // * owner: Repositories that are owned by the authenticated user. - // * collaborator: Repositories that the user has been added to as a - // collaborator. - // * organization_member: Repositories that the user has access to through - // being a member of an organization. This includes every repository on - // every team that the user is on. - // Default: owner,collaborator,organization_member - Affiliation string `url:"affiliation,omitempty"` - - // Type of repositories to list. - // Can be one of all, owner, public, private, member. Default: all - // Will cause a 422 error if used in the same request as visibility or - // affiliation. - Type string `url:"type,omitempty"` - - // How to sort the repository list. Can be one of created, updated, pushed, - // full_name. Default: full_name - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Can be one of asc or desc. - // Default: when using full_name: asc; otherwise desc - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the repositories for a user. Passing the empty string will list -// repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-user-repositories -func (s *RepositoriesService) List(ctx context.Context, user string, opt *RepositoryListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/repos", user) - } else { - u = "user/repos" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListByOrgOptions specifies the optional parameters to the -// RepositoriesService.ListByOrg method. -type RepositoryListByOrgOptions struct { - // Type of repositories to list. Possible values are: all, public, private, - // forks, sources, member. Default is "all". - Type string `url:"type,omitempty"` - - ListOptions -} - -// ListByOrg lists the repositories for an organization. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-organization-repositories -func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("orgs/%v/repos", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListAllOptions specifies the optional parameters to the -// RepositoriesService.ListAll method. -type RepositoryListAllOptions struct { - // ID of the last repository seen - Since int64 `url:"since,omitempty"` -} - -// ListAll lists all GitHub repositories in the order that they were created. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-public-repositories -func (s *RepositoriesService) ListAll(ctx context.Context, opt *RepositoryListAllOptions) ([]*Repository, *Response, error) { - u, err := addOptions("repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// Create a new repository. If an organization is specified, the new -// repository will be created under that org. If the empty string is -// specified, it will be created for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#create -func (s *RepositoriesService) Create(ctx context.Context, org string, repo *Repository) (*Repository, *Response, error) { - var u string - if org != "" { - u = fmt.Sprintf("orgs/%v/repos", org) - } else { - u = "user/repos" - } - - req, err := s.client.NewRequest("POST", u, repo) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Get fetches a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get -func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when the license support fully launches - // https://developer.github.com/v3/licenses/#get-a-repositorys-license - acceptHeaders := []string{mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// GetCodeOfConduct gets the contents of a repository's code of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#get-the-contents-of-a-repositorys-code-of-conduct -func (s *RepositoriesService) GetCodeOfConduct(ctx context.Context, owner, repo string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/code_of_conduct", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := s.client.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// GetByID fetches a repository. -// -// Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. -func (s *RepositoriesService) GetByID(ctx context.Context, id int64) (*Repository, *Response, error) { - u := fmt.Sprintf("repositories/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// Edit updates a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#edit -func (s *RepositoriesService) Edit(ctx context.Context, owner, repo string, repository *Repository) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("PATCH", u, repository) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Delete a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#delete-a-repository -func (s *RepositoriesService) Delete(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Contributor represents a repository contributor -type Contributor struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - Contributions *int `json:"contributions,omitempty"` -} - -// ListContributorsOptions specifies the optional parameters to the -// RepositoriesService.ListContributors method. -type ListContributorsOptions struct { - // Include anonymous contributors in results or not - Anon string `url:"anon,omitempty"` - - ListOptions -} - -// ListContributors lists contributors for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-contributors -func (s *RepositoriesService) ListContributors(ctx context.Context, owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/contributors", owner, repository) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributor []*Contributor - resp, err := s.client.Do(ctx, req, &contributor) - if err != nil { - return nil, nil, err - } - - return contributor, resp, nil -} - -// ListLanguages lists languages for the specified repository. The returned map -// specifies the languages and the number of bytes of code written in that -// language. For example: -// -// { -// "C": 78769, -// "Python": 7769 -// } -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-languages -func (s *RepositoriesService) ListLanguages(ctx context.Context, owner string, repo string) (map[string]int, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/languages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - languages := make(map[string]int) - resp, err := s.client.Do(ctx, req, &languages) - if err != nil { - return nil, resp, err - } - - return languages, resp, nil -} - -// ListTeams lists the teams for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-teams -func (s *RepositoriesService) ListTeams(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/teams", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// RepositoryTag represents a repository tag. -type RepositoryTag struct { - Name *string `json:"name,omitempty"` - Commit *Commit `json:"commit,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` -} - -// ListTags lists tags for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-tags -func (s *RepositoriesService) ListTags(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/tags", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var tags []*RepositoryTag - resp, err := s.client.Do(ctx, req, &tags) - if err != nil { - return nil, resp, err - } - - return tags, resp, nil -} - -// Branch represents a repository branch -type Branch struct { - Name *string `json:"name,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - Protected *bool `json:"protected,omitempty"` -} - -// Protection represents a repository branch's protection. -type Protection struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcement `json:"required_pull_request_reviews"` - EnforceAdmins *AdminEnforcement `json:"enforce_admins"` - Restrictions *BranchRestrictions `json:"restrictions"` -} - -// ProtectionRequest represents a request to create/edit a branch's protection. -type ProtectionRequest struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcementRequest `json:"required_pull_request_reviews"` - EnforceAdmins bool `json:"enforce_admins"` - Restrictions *BranchRestrictionsRequest `json:"restrictions"` -} - -// RequiredStatusChecks represents the protection status of a individual branch. -type RequiredStatusChecks struct { - // Require branches to be up to date before merging. (Required.) - Strict bool `json:"strict"` - // The list of status checks to require in order to merge into this - // branch. (Required; use []string{} instead of nil for empty list.) - Contexts []string `json:"contexts"` -} - -// RequiredStatusChecksRequest represents a request to edit a protected branch's status checks. -type RequiredStatusChecksRequest struct { - Strict *bool `json:"strict,omitempty"` - Contexts []string `json:"contexts,omitempty"` -} - -// PullRequestReviewsEnforcement represents the pull request reviews enforcement of a protected branch. -type PullRequestReviewsEnforcement struct { - // Specifies which users and teams can dismiss pull request reviews. - DismissalRestrictions DismissalRestrictions `json:"dismissal_restrictions"` - // Specifies if approved reviews are dismissed automatically, when a new commit is pushed. - DismissStaleReviews bool `json:"dismiss_stale_reviews"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"` - // RequiredApprovingReviewCount specifies the number of approvals required before the pull request can be merged. - // Valid values are 1-6. - RequiredApprovingReviewCount int `json:"required_approving_review_count"` -} - -// PullRequestReviewsEnforcementRequest represents request to set the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcement above -// because the request structure is different from the response structure. -type PullRequestReviewsEnforcementRequest struct { - // Specifies which users and teams should be allowed to dismiss pull request reviews. - // User and team dismissal restrictions are only available for - // organization-owned repositories. Must be nil for personal repositories. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions,omitempty"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. (Required) - DismissStaleReviews bool `json:"dismiss_stale_reviews"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"` - // RequiredApprovingReviewCount specifies the number of approvals required before the pull request can be merged. - // Valid values are 1-6. - RequiredApprovingReviewCount int `json:"required_approving_review_count"` -} - -// PullRequestReviewsEnforcementUpdate represents request to patch the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcementRequest above -// because the patch request does not require all fields to be initialized. -type PullRequestReviewsEnforcementUpdate struct { - // Specifies which users and teams can dismiss pull request reviews. Can be omitted. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions,omitempty"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. Can be omitted. - DismissStaleReviews *bool `json:"dismiss_stale_reviews,omitempty"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews,omitempty"` - // RequiredApprovingReviewCount specifies the number of approvals required before the pull request can be merged. - // Valid values are 1 - 6. - RequiredApprovingReviewCount int `json:"required_approving_review_count"` -} - -// AdminEnforcement represents the configuration to enforce required status checks for repository administrators. -type AdminEnforcement struct { - URL *string `json:"url,omitempty"` - Enabled bool `json:"enabled"` -} - -// BranchRestrictions represents the restriction that only certain users or -// teams may push to a branch. -type BranchRestrictions struct { - // The list of user logins with push access. - Users []*User `json:"users"` - // The list of team slugs with push access. - Teams []*Team `json:"teams"` -} - -// BranchRestrictionsRequest represents the request to create/edit the -// restriction that only certain users or teams may push to a branch. It is -// separate from BranchRestrictions above because the request structure is -// different from the response structure. -type BranchRestrictionsRequest struct { - // The list of user logins with push access. (Required; use []string{} instead of nil for empty list.) - Users []string `json:"users"` - // The list of team slugs with push access. (Required; use []string{} instead of nil for empty list.) - Teams []string `json:"teams"` -} - -// DismissalRestrictions specifies which users and teams can dismiss pull request reviews. -type DismissalRestrictions struct { - // The list of users who can dimiss pull request reviews. - Users []*User `json:"users"` - // The list of teams which can dismiss pull request reviews. - Teams []*Team `json:"teams"` -} - -// DismissalRestrictionsRequest represents the request to create/edit the -// restriction to allows only specific users or teams to dimiss pull request reviews. It is -// separate from DismissalRestrictions above because the request structure is -// different from the response structure. -// Note: Both Users and Teams must be nil, or both must be non-nil. -type DismissalRestrictionsRequest struct { - // The list of user logins who can dismiss pull request reviews. (Required; use nil to disable dismissal_restrictions or &[]string{} otherwise.) - Users *[]string `json:"users,omitempty"` - // The list of team slugs which can dismiss pull request reviews. (Required; use nil to disable dismissal_restrictions or &[]string{} otherwise.) - Teams *[]string `json:"teams,omitempty"` -} - -// ListBranches lists branches for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-branches -func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - var branches []*Branch - resp, err := s.client.Do(ctx, req, &branches) - if err != nil { - return nil, resp, err - } - - return branches, resp, nil -} - -// GetBranch gets the specified branch for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get-branch -func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch string) (*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - b := new(Branch) - resp, err := s.client.Do(ctx, req, b) - if err != nil { - return nil, resp, err - } - - return b, resp, nil -} - -// GetBranchProtection gets the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-branch-protection -func (s *RepositoriesService) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// GetRequiredStatusChecks gets the required status checks for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch -func (s *RepositoriesService) GetRequiredStatusChecks(ctx context.Context, owner, repo, branch string) (*RequiredStatusChecks, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - p := new(RequiredStatusChecks) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListRequiredStatusChecksContexts lists the required status checks contexts for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch -func (s *RepositoriesService) ListRequiredStatusChecksContexts(ctx context.Context, owner, repo, branch string) (contexts []string, resp *Response, err error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks/contexts", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - resp, err = s.client.Do(ctx, req, &contexts) - if err != nil { - return nil, resp, err - } - - return contexts, resp, nil -} - -// UpdateBranchProtection updates the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-branch-protection -func (s *RepositoriesService) UpdateBranchProtection(ctx context.Context, owner, repo, branch string, preq *ProtectionRequest) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("PUT", u, preq) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// RemoveBranchProtection removes the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-branch-protection -func (s *RepositoriesService) RemoveBranchProtection(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UpdateRequiredStatusChecks updates the required status checks for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch -func (s *RepositoriesService) UpdateRequiredStatusChecks(ctx context.Context, owner, repo, branch string, sreq *RequiredStatusChecksRequest) (*RequiredStatusChecks, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks", owner, repo, branch) - req, err := s.client.NewRequest("PATCH", u, sreq) - if err != nil { - return nil, nil, err - } - - sc := new(RequiredStatusChecks) - resp, err := s.client.Do(ctx, req, sc) - if err != nil { - return nil, resp, err - } - - return sc, resp, nil -} - -// License gets the contents of a repository's license if one is detected. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license -func (s *RepositoriesService) License(ctx context.Context, owner, repo string) (*RepositoryLicense, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/license", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - r := &RepositoryLicense{} - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetPullRequestReviewEnforcement gets pull request review enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) GetPullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdatePullRequestReviewEnforcement patches pull request review enforcement of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) UpdatePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string, patch *PullRequestReviewsEnforcementUpdate) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("PATCH", u, patch) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// DisableDismissalRestrictions disables dismissal restrictions of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) DisableDismissalRestrictions(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - - data := struct { - R []interface{} `json:"dismissal_restrictions"` - }{[]interface{}{}} - - req, err := s.client.NewRequest("PATCH", u, data) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemovePullRequestReviewEnforcement removes pull request enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) RemovePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - return s.client.Do(ctx, req, nil) -} - -// GetAdminEnforcement gets admin enforcement information of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch -func (s *RepositoriesService) GetAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// AddAdminEnforcement adds admin enforcement to a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch -func (s *RepositoriesService) AddAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemoveAdminEnforcement removes admin enforcement from a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch -func (s *RepositoriesService) RemoveAdminEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeRequiredApprovingReviewsPreview) - - return s.client.Do(ctx, req, nil) -} - -// repositoryTopics represents a collection of repository topics. -type repositoryTopics struct { - Names []string `json:"names"` -} - -// ListAllTopics lists topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-topics-for-a-repository -func (s *RepositoriesService) ListAllTopics(ctx context.Context, owner, repo string) ([]string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - topics := new(repositoryTopics) - resp, err := s.client.Do(ctx, req, topics) - if err != nil { - return nil, resp, err - } - - return topics.Names, resp, nil -} - -// ReplaceAllTopics replaces topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository -func (s *RepositoriesService) ReplaceAllTopics(ctx context.Context, owner, repo string, topics []string) ([]string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - t := &repositoryTopics{ - Names: topics, - } - if t.Names == nil { - t.Names = []string{} - } - req, err := s.client.NewRequest("PUT", u, t) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - t = new(repositoryTopics) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t.Names, resp, nil -} - -// TransferRequest represents a request to transfer a repository. -type TransferRequest struct { - NewOwner string `json:"new_owner"` - TeamID []int64 `json:"team_ids,omitempty"` -} - -// Transfer transfers a repository from one account or organization to another. -// -// This method might return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it has now scheduled the transfer of the repository in a background task. -// A follow up request, after a delay of a second or so, should result -// in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/#transfer-a-repository -func (s *RepositoriesService) Transfer(ctx context.Context, owner, repo string, transfer TransferRequest) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/transfer", owner, repo) - - req, err := s.client.NewRequest("POST", u, &transfer) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryTransferPreview) - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_collaborators.go b/vendor/github.com/google/go-github/github/repos_collaborators.go deleted file mode 100644 index 61ee9d39c..000000000 --- a/vendor/github.com/google/go-github/github/repos_collaborators.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListCollaboratorsOptions specifies the optional parameters to the -// RepositoriesService.ListCollaborators method. -type ListCollaboratorsOptions struct { - // Affiliation specifies how collaborators should be filtered by their affiliation. - // Possible values are: - // outside - All outside collaborators of an organization-owned repository - // direct - All collaborators with permissions to an organization-owned repository, - // regardless of organization membership status - // all - All collaborators the authenticated user can see - // - // Default value is "all". - Affiliation string `url:"affiliation,omitempty"` - - ListOptions -} - -// ListCollaborators lists the GitHub users that have access to the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list-collaborators -func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListCollaboratorsOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsCollaborator checks whether the specified GitHub user has collaborator -// access to the given repo. -// Note: This will return false if the user is not a collaborator OR the user -// is not a GitHub user. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#get -func (s *RepositoriesService) IsCollaborator(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - isCollab, err := parseBoolResponse(err) - return isCollab, resp, err -} - -// RepositoryPermissionLevel represents the permission level an organization -// member has for a given repository. -type RepositoryPermissionLevel struct { - // Possible values: "admin", "write", "read", "none" - Permission *string `json:"permission,omitempty"` - - User *User `json:"user,omitempty"` -} - -// GetPermissionLevel retrieves the specific permission level a collaborator has for a given repository. -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level -func (s *RepositoriesService) GetPermissionLevel(ctx context.Context, owner, repo, user string) (*RepositoryPermissionLevel, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v/permission", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - rpl := new(RepositoryPermissionLevel) - resp, err := s.client.Do(ctx, req, rpl) - if err != nil { - return nil, resp, err - } - return rpl, resp, nil -} - -// RepositoryAddCollaboratorOptions specifies the optional parameters to the -// RepositoriesService.AddCollaborator method. -type RepositoryAddCollaboratorOptions struct { - // Permission specifies the permission to grant the user on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // Default value is "push". This option is only valid for organization-owned repositories. - Permission string `json:"permission,omitempty"` -} - -// AddCollaborator sends an invitation to the specified GitHub user -// to become a collaborator to the given repo. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator -func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// RemoveCollaborator removes the specified GitHub user as collaborator from the given repo. -// Note: Does not return error if a valid user that is not a collaborator is removed. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#remove-collaborator -func (s *RepositoriesService) RemoveCollaborator(ctx context.Context, owner, repo, user string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_comments.go b/vendor/github.com/google/go-github/github/repos_comments.go deleted file mode 100644 index fa2377d40..000000000 --- a/vendor/github.com/google/go-github/github/repos_comments.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// RepositoryComment represents a comment for a commit, file, or line in a repository. -type RepositoryComment struct { - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - ID *int64 `json:"id,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - - // User-mutable fields - Body *string `json:"body"` - // User-initialized fields - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` -} - -func (r RepositoryComment) String() string { - return Stringify(r) -} - -// ListComments lists all the comments for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository -func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// ListCommitComments lists all the comments for a given commit SHA. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit -func (s *RepositoriesService) ListCommitComments(ctx context.Context, owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateComment creates a comment for the given commit. -// Note: GitHub allows for comments to be created for non-existing files and positions. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#create-a-commit-comment -func (s *RepositoriesService) CreateComment(ctx context.Context, owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// GetComment gets a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#get-a-single-commit-comment -func (s *RepositoriesService) GetComment(ctx context.Context, owner, repo string, id int64) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// UpdateComment updates the body of a single comment. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#update-a-commit-comment -func (s *RepositoriesService) UpdateComment(ctx context.Context, owner, repo string, id int64, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#delete-a-commit-comment -func (s *RepositoriesService) DeleteComment(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_commits.go b/vendor/github.com/google/go-github/github/repos_commits.go deleted file mode 100644 index 04faa3ea9..000000000 --- a/vendor/github.com/google/go-github/github/repos_commits.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "time" -) - -// RepositoryCommit represents a commit in a repo. -// Note that it's wrapping a Commit, so author/committer information is in two places, -// but contain different details about them: in RepositoryCommit "github details", in Commit - "git details". -type RepositoryCommit struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - // Details about how many changes were made in this commit. Only filled in during GetCommit! - Stats *CommitStats `json:"stats,omitempty"` - // Details about which files, and how this commit touched. Only filled in during GetCommit! - Files []CommitFile `json:"files,omitempty"` -} - -func (r RepositoryCommit) String() string { - return Stringify(r) -} - -// CommitStats represents the number of additions / deletions from a file in a given RepositoryCommit or GistCommit. -type CommitStats struct { - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Total *int `json:"total,omitempty"` -} - -func (c CommitStats) String() string { - return Stringify(c) -} - -// CommitFile represents a file modified in a commit. -type CommitFile struct { - SHA *string `json:"sha,omitempty"` - Filename *string `json:"filename,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Changes *int `json:"changes,omitempty"` - Status *string `json:"status,omitempty"` - Patch *string `json:"patch,omitempty"` - BlobURL *string `json:"blob_url,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` -} - -func (c CommitFile) String() string { - return Stringify(c) -} - -// CommitsComparison is the result of comparing two commits. -// See CompareCommits() for details. -type CommitsComparison struct { - BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` - MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"` - - // Head can be 'behind' or 'ahead' - Status *string `json:"status,omitempty"` - AheadBy *int `json:"ahead_by,omitempty"` - BehindBy *int `json:"behind_by,omitempty"` - TotalCommits *int `json:"total_commits,omitempty"` - - Commits []RepositoryCommit `json:"commits,omitempty"` - - Files []CommitFile `json:"files,omitempty"` - - HTMLURL *string `json:"html_url,omitempty"` - PermalinkURL *string `json:"permalink_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - URL *string `json:"url,omitempty"` // API URL. -} - -func (c CommitsComparison) String() string { - return Stringify(c) -} - -// CommitsListOptions specifies the optional parameters to the -// RepositoriesService.ListCommits method. -type CommitsListOptions struct { - // SHA or branch to start listing Commits from. - SHA string `url:"sha,omitempty"` - - // Path that should be touched by the returned Commits. - Path string `url:"path,omitempty"` - - // Author of by which to filter Commits. - Author string `url:"author,omitempty"` - - // Since when should Commits be included in the response. - Since time.Time `url:"since,omitempty"` - - // Until when should Commits be included in the response. - Until time.Time `url:"until,omitempty"` - - ListOptions -} - -// ListCommits lists the commits of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#list -func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// GetCommit fetches the specified commit, including all details about it. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-a-single-commit -// See also: https://developer.github.com/v3/git/commits/#get-a-single-commit provides the same functionality -func (s *RepositoriesService) GetCommit(ctx context.Context, owner, repo, sha string) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} - -// GetCommitRaw fetches the specified commit in raw (diff or patch) format. -func (s *RepositoriesService) GetCommitRaw(ctx context.Context, owner string, repo string, sha string, opt RawOptions) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - switch opt.Type { - case Diff: - req.Header.Set("Accept", mediaTypeV3Diff) - case Patch: - req.Header.Set("Accept", mediaTypeV3Patch) - default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) - } - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// GetCommitSHA1 gets the SHA-1 of a commit reference. If a last-known SHA1 is -// supplied and no new commits have occurred, a 304 Unmodified response is returned. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference -func (s *RepositoriesService) GetCommitSHA1(ctx context.Context, owner, repo, ref, lastSHA string) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, ref) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - if lastSHA != "" { - req.Header.Set("If-None-Match", `"`+lastSHA+`"`) - } - - req.Header.Set("Accept", mediaTypeV3SHA) - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// CompareCommits compares a range of commits with each other. -// todo: support media formats - https://github.com/google/go-github/issues/6 -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#compare-two-commits -func (s *RepositoriesService) CompareCommits(ctx context.Context, owner, repo string, base, head string) (*CommitsComparison, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/compare/%v...%v", owner, repo, base, head) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - comp := new(CommitsComparison) - resp, err := s.client.Do(ctx, req, comp) - if err != nil { - return nil, resp, err - } - - return comp, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_community_health.go b/vendor/github.com/google/go-github/github/repos_community_health.go deleted file mode 100644 index 73d1d573b..000000000 --- a/vendor/github.com/google/go-github/github/repos_community_health.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Metric represents the different fields for one file in community health files. -type Metric struct { - Name *string `json:"name"` - Key *string `json:"key"` - URL *string `json:"url"` - HTMLURL *string `json:"html_url"` -} - -// CommunityHealthFiles represents the different files in the community health metrics response. -type CommunityHealthFiles struct { - CodeOfConduct *Metric `json:"code_of_conduct"` - Contributing *Metric `json:"contributing"` - IssueTemplate *Metric `json:"issue_template"` - PullRequestTemplate *Metric `json:"pull_request_template"` - License *Metric `json:"license"` - Readme *Metric `json:"readme"` -} - -// CommunityHealthMetrics represents a response containing the community metrics of a repository. -type CommunityHealthMetrics struct { - HealthPercentage *int `json:"health_percentage"` - Files *CommunityHealthFiles `json:"files"` - UpdatedAt *time.Time `json:"updated_at"` -} - -// GetCommunityHealthMetrics retrieves all the community health metrics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/community/#retrieve-community-health-metrics -func (s *RepositoriesService) GetCommunityHealthMetrics(ctx context.Context, owner, repo string) (*CommunityHealthMetrics, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/profile", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryCommunityHealthMetricsPreview) - - metrics := &CommunityHealthMetrics{} - resp, err := s.client.Do(ctx, req, metrics) - if err != nil { - return nil, resp, err - } - - return metrics, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_contents.go b/vendor/github.com/google/go-github/github/repos_contents.go deleted file mode 100644 index ffb56b90d..000000000 --- a/vendor/github.com/google/go-github/github/repos_contents.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Repository contents API methods. -// GitHub API docs: https://developer.github.com/v3/repos/contents/ - -package github - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" -) - -// RepositoryContent represents a file or directory in a github repository. -type RepositoryContent struct { - Type *string `json:"type,omitempty"` - Encoding *string `json:"encoding,omitempty"` - Size *int `json:"size,omitempty"` - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - // Content contains the actual file content, which may be encoded. - // Callers should call GetContent which will decode the content if - // necessary. - Content *string `json:"content,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` -} - -// RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentResponse struct { - Content *RepositoryContent `json:"content,omitempty"` - Commit `json:"commit,omitempty"` -} - -// RepositoryContentFileOptions specifies optional parameters for CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentFileOptions struct { - Message *string `json:"message,omitempty"` - Content []byte `json:"content,omitempty"` // unencoded - SHA *string `json:"sha,omitempty"` - Branch *string `json:"branch,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` -} - -// RepositoryContentGetOptions represents an optional ref parameter, which can be a SHA, -// branch, or tag -type RepositoryContentGetOptions struct { - Ref string `url:"ref,omitempty"` -} - -// String converts RepositoryContent to a string. It's primarily for testing. -func (r RepositoryContent) String() string { - return Stringify(r) -} - -// GetContent returns the content of r, decoding it if necessary. -func (r *RepositoryContent) GetContent() (string, error) { - var encoding string - if r.Encoding != nil { - encoding = *r.Encoding - } - - switch encoding { - case "base64": - c, err := base64.StdEncoding.DecodeString(*r.Content) - return string(c), err - case "": - if r.Content == nil { - return "", nil - } - return *r.Content, nil - default: - return "", fmt.Errorf("unsupported content encoding: %v", encoding) - } -} - -// GetReadme gets the Readme file for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-the-readme -func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/readme", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - readme := new(RepositoryContent) - resp, err := s.client.Do(ctx, req, readme) - if err != nil { - return nil, resp, err - } - return readme, resp, nil -} - -// DownloadContents returns an io.ReadCloser that reads the contents of the -// specified file. This function will work with files of any size, as opposed -// to GetContents which is limited to 1 Mb files. It is the caller's -// responsibility to close the ReadCloser. -func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) { - dir := path.Dir(filepath) - filename := path.Base(filepath) - _, dirContents, _, err := s.GetContents(ctx, owner, repo, dir, opt) - if err != nil { - return nil, err - } - for _, contents := range dirContents { - if *contents.Name == filename { - if contents.DownloadURL == nil || *contents.DownloadURL == "" { - return nil, fmt.Errorf("No download link found for %s", filepath) - } - resp, err := s.client.client.Get(*contents.DownloadURL) - if err != nil { - return nil, err - } - return resp.Body, nil - } - } - return nil, fmt.Errorf("No file named %s found in %s", filename, dir) -} - -// GetContents can return either the metadata and content of a single file -// (when path references a file) or the metadata of all the files and/or -// subdirectories of a directory (when path references a directory). To make it -// easy to distinguish between both result types and to mimic the API as much -// as possible, both result types will be returned but only one will contain a -// value and the other will be nil. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-contents -func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error) { - escapedPath := (&url.URL{Path: path}).String() - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, escapedPath) - u, err = addOptions(u, opt) - if err != nil { - return nil, nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, nil, err - } - var rawJSON json.RawMessage - resp, err = s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, nil, resp, err - } - fileUnmarshalError := json.Unmarshal(rawJSON, &fileContent) - if fileUnmarshalError == nil { - return fileContent, nil, resp, nil - } - directoryUnmarshalError := json.Unmarshal(rawJSON, &directoryContent) - if directoryUnmarshalError == nil { - return nil, directoryContent, resp, nil - } - return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s", fileUnmarshalError, directoryUnmarshalError) -} - -// CreateFile creates a new file in a repository at the given path and returns -// the commit and file metadata. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#create-a-file -func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - createResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, createResponse) - if err != nil { - return nil, resp, err - } - return createResponse, resp, nil -} - -// UpdateFile updates a file in a repository at the given path and returns the -// commit and file metadata. Requires the blob SHA of the file being updated. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#update-a-file -func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - updateResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, updateResponse) - if err != nil { - return nil, resp, err - } - return updateResponse, resp, nil -} - -// DeleteFile deletes a file from a repository and returns the commit. -// Requires the blob SHA of the file to be deleted. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#delete-a-file -func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("DELETE", u, opt) - if err != nil { - return nil, nil, err - } - deleteResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, deleteResponse) - if err != nil { - return nil, resp, err - } - return deleteResponse, resp, nil -} - -// archiveFormat is used to define the archive type when calling GetArchiveLink. -type archiveFormat string - -const ( - // Tarball specifies an archive in gzipped tar format. - Tarball archiveFormat = "tarball" - - // Zipball specifies an archive in zip format. - Zipball archiveFormat = "zipball" -) - -// GetArchiveLink returns an URL to download a tarball or zipball archive for a -// repository. The archiveFormat can be specified by either the github.Tarball -// or github.Zipball constant. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-archive-link -func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/%s", owner, repo, archiveformat) - if opt != nil && opt.Ref != "" { - u += fmt.Sprintf("/%s", opt.Ref) - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, nil, err - } - resp.Body.Close() - if resp.StatusCode != http.StatusFound { - return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) - } - parsedURL, err := url.Parse(resp.Header.Get("Location")) - return parsedURL, newResponse(resp), err -} diff --git a/vendor/github.com/google/go-github/github/repos_deployments.go b/vendor/github.com/google/go-github/github/repos_deployments.go deleted file mode 100644 index 794c3232e..000000000 --- a/vendor/github.com/google/go-github/github/repos_deployments.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" -) - -// Deployment represents a deployment in a repo -type Deployment struct { - URL *string `json:"url,omitempty"` - ID *int64 `json:"id,omitempty"` - SHA *string `json:"sha,omitempty"` - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - Payload json.RawMessage `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// DeploymentRequest represents a deployment request -type DeploymentRequest struct { - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - AutoMerge *bool `json:"auto_merge,omitempty"` - RequiredContexts *[]string `json:"required_contexts,omitempty"` - Payload *string `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - TransientEnvironment *bool `json:"transient_environment,omitempty"` - ProductionEnvironment *bool `json:"production_environment,omitempty"` -} - -// DeploymentsListOptions specifies the optional parameters to the -// RepositoriesService.ListDeployments method. -type DeploymentsListOptions struct { - // SHA of the Deployment. - SHA string `url:"sha,omitempty"` - - // List deployments for a given ref. - Ref string `url:"ref,omitempty"` - - // List deployments for a given task. - Task string `url:"task,omitempty"` - - // List deployments for a given environment. - Environment string `url:"environment,omitempty"` - - ListOptions -} - -// ListDeployments lists the deployments of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments -func (s *RepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var deployments []*Deployment - resp, err := s.client.Do(ctx, req, &deployments) - if err != nil { - return nil, resp, err - } - - return deployments, resp, nil -} - -// GetDeployment returns a single deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment -func (s *RepositoriesService) GetDeployment(ctx context.Context, owner, repo string, deploymentID int64) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v", owner, repo, deploymentID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - deployment := new(Deployment) - resp, err := s.client.Do(ctx, req, deployment) - if err != nil { - return nil, resp, err - } - - return deployment, resp, nil -} - -// CreateDeployment creates a new deployment for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment -func (s *RepositoriesService) CreateDeployment(ctx context.Context, owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(Deployment) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// DeploymentStatus represents the status of a -// particular deployment. -type DeploymentStatus struct { - ID *int64 `json:"id,omitempty"` - // State is the deployment state. - // Possible values are: "pending", "success", "failure", "error", "inactive". - State *string `json:"state,omitempty"` - Creator *User `json:"creator,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - DeploymentURL *string `json:"deployment_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// DeploymentStatusRequest represents a deployment request -type DeploymentStatusRequest struct { - State *string `json:"state,omitempty"` - LogURL *string `json:"log_url,omitempty"` - Description *string `json:"description,omitempty"` - EnvironmentURL *string `json:"environment_url,omitempty"` - AutoInactive *bool `json:"auto_inactive,omitempty"` -} - -// ListDeploymentStatuses lists the statuses of a given deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses -func (s *RepositoriesService) ListDeploymentStatuses(ctx context.Context, owner, repo string, deployment int64, opt *ListOptions) ([]*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var statuses []*DeploymentStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// GetDeploymentStatus returns a single deployment status of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment-status -func (s *RepositoriesService) GetDeploymentStatus(ctx context.Context, owner, repo string, deploymentID, deploymentStatusID int64) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses/%v", owner, repo, deploymentID, deploymentStatusID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// CreateDeploymentStatus creates a new status for a deployment. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment-status -func (s *RepositoriesService) CreateDeploymentStatus(ctx context.Context, owner, repo string, deployment int64, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_forks.go b/vendor/github.com/google/go-github/github/repos_forks.go deleted file mode 100644 index d0bff5447..000000000 --- a/vendor/github.com/google/go-github/github/repos_forks.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryListForksOptions specifies the optional parameters to the -// RepositoriesService.ListForks method. -type RepositoryListForksOptions struct { - // How to sort the forks list. Possible values are: newest, oldest, - // watchers. Default is "newest". - Sort string `url:"sort,omitempty"` - - ListOptions -} - -// ListForks lists the forks of the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#list-forks -func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryCreateForkOptions specifies the optional parameters to the -// RepositoriesService.CreateFork method. -type RepositoryCreateForkOptions struct { - // The organization to fork the repository into. - Organization string `url:"organization,omitempty"` -} - -// CreateFork creates a fork of the specified repository. -// -// This method might return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing creating the fork in a background task. In this event, -// the Repository value will be returned, which includes the details about the pending fork. -// A follow up request, after a delay of a second or so, should result -// in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#create-a-fork -func (s *RepositoriesService) CreateFork(ctx context.Context, owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - fork := new(Repository) - resp, err := s.client.Do(ctx, req, fork) - if _, ok := err.(*AcceptedError); ok { - return fork, resp, err - } - if err != nil { - return nil, resp, err - } - - return fork, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_hooks.go b/vendor/github.com/google/go-github/github/repos_hooks.go deleted file mode 100644 index 1e9e88480..000000000 --- a/vendor/github.com/google/go-github/github/repos_hooks.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// WebHookPayload represents the data that is received from GitHub when a push -// event hook is triggered. The format of these payloads pre-date most of the -// GitHub v3 API, so there are lots of minor incompatibilities with the types -// defined in the rest of the API. Therefore, several types are duplicated -// here to account for these differences. -// -// GitHub API docs: https://help.github.com/articles/post-receive-hooks -type WebHookPayload struct { - After *string `json:"after,omitempty"` - Before *string `json:"before,omitempty"` - Commits []WebHookCommit `json:"commits,omitempty"` - Compare *string `json:"compare,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - HeadCommit *WebHookCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Ref *string `json:"ref,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` -} - -func (w WebHookPayload) String() string { - return Stringify(w) -} - -// WebHookCommit represents the commit variant we receive from GitHub in a -// WebHookPayload. -type WebHookCommit struct { - Added []string `json:"added,omitempty"` - Author *WebHookAuthor `json:"author,omitempty"` - Committer *WebHookAuthor `json:"committer,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - ID *string `json:"id,omitempty"` - Message *string `json:"message,omitempty"` - Modified []string `json:"modified,omitempty"` - Removed []string `json:"removed,omitempty"` - Timestamp *time.Time `json:"timestamp,omitempty"` -} - -func (w WebHookCommit) String() string { - return Stringify(w) -} - -// WebHookAuthor represents the author or committer of a commit, as specified -// in a WebHookCommit. The commit author may not correspond to a GitHub User. -type WebHookAuthor struct { - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - Username *string `json:"username,omitempty"` -} - -func (w WebHookAuthor) String() string { - return Stringify(w) -} - -// Hook represents a GitHub (web and service) hook for a repository. -type Hook struct { - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - Events []string `json:"events,omitempty"` - Active *bool `json:"active,omitempty"` - Config map[string]interface{} `json:"config,omitempty"` - ID *int64 `json:"id,omitempty"` -} - -func (h Hook) String() string { - return Stringify(h) -} - -// CreateHook creates a Hook for the specified repository. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#create-a-hook -func (s *RepositoriesService) CreateHook(ctx context.Context, owner, repo string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// ListHooks lists all Hooks for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#list -func (s *RepositoriesService) ListHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#get-single-hook -func (s *RepositoriesService) GetHook(ctx context.Context, owner, repo string, id int64) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#edit-a-hook -func (s *RepositoriesService) EditHook(ctx context.Context, owner, repo string, id int64, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#delete-a-hook -func (s *RepositoriesService) DeleteHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook -func (s *RepositoriesService) PingHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/pings", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// TestHook triggers a test Hook by github. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#test-a-push-hook -func (s *RepositoriesService) TestHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/tests", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_invitations.go b/vendor/github.com/google/go-github/github/repos_invitations.go deleted file mode 100644 index 34bf3830f..000000000 --- a/vendor/github.com/google/go-github/github/repos_invitations.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryInvitation represents an invitation to collaborate on a repo. -type RepositoryInvitation struct { - ID *int64 `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Invitee *User `json:"invitee,omitempty"` - Inviter *User `json:"inviter,omitempty"` - - // Permissions represents the permissions that the associated user will have - // on the repository. Possible values are: "read", "write", "admin". - Permissions *string `json:"permissions,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// ListInvitations lists all currently-open repository invitations. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository -func (s *RepositoriesService) ListInvitations(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// DeleteInvitation deletes a repository invitation. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#delete-a-repository-invitation -func (s *RepositoriesService) DeleteInvitation(ctx context.Context, owner, repo string, invitationID int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UpdateInvitation updates the permissions associated with a repository -// invitation. -// -// permissions represents the permissions that the associated user will have -// on the repository. Possible values are: "read", "write", "admin". -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#update-a-repository-invitation -func (s *RepositoriesService) UpdateInvitation(ctx context.Context, owner, repo string, invitationID int64, permissions string) (*RepositoryInvitation, *Response, error) { - opts := &struct { - Permissions string `json:"permissions"` - }{Permissions: permissions} - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("PATCH", u, opts) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invite := &RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, invite) - if err != nil { - return nil, resp, err - } - - return invite, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_keys.go b/vendor/github.com/google/go-github/github/repos_keys.go deleted file mode 100644 index b484f8444..000000000 --- a/vendor/github.com/google/go-github/github/repos_keys.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// The Key type is defined in users_keys.go - -// ListKeys lists the deploy keys for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#list -func (s *RepositoriesService) ListKeys(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#get -func (s *RepositoriesService) GetKey(ctx context.Context, owner string, repo string, id int64) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a deploy key for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#create -func (s *RepositoriesService) CreateKey(ctx context.Context, owner string, repo string, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// EditKey edits a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#edit -func (s *RepositoriesService) EditKey(ctx context.Context, owner string, repo string, id int64, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#delete -func (s *RepositoriesService) DeleteKey(ctx context.Context, owner string, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_merging.go b/vendor/github.com/google/go-github/github/repos_merging.go deleted file mode 100644 index 04383c1ae..000000000 --- a/vendor/github.com/google/go-github/github/repos_merging.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryMergeRequest represents a request to merge a branch in a -// repository. -type RepositoryMergeRequest struct { - Base *string `json:"base,omitempty"` - Head *string `json:"head,omitempty"` - CommitMessage *string `json:"commit_message,omitempty"` -} - -// Merge a branch in the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/merging/#perform-a-merge -func (s *RepositoriesService) Merge(ctx context.Context, owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/merges", owner, repo) - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_pages.go b/vendor/github.com/google/go-github/github/repos_pages.go deleted file mode 100644 index 94a95f2b8..000000000 --- a/vendor/github.com/google/go-github/github/repos_pages.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Pages represents a GitHub Pages site configuration. -type Pages struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - CNAME *string `json:"cname,omitempty"` - Custom404 *bool `json:"custom_404,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// PagesError represents a build error for a GitHub Pages site. -type PagesError struct { - Message *string `json:"message,omitempty"` -} - -// PagesBuild represents the build information for a GitHub Pages site. -type PagesBuild struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - Error *PagesError `json:"error,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Commit *string `json:"commit,omitempty"` - Duration *int `json:"duration,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// GetPagesInfo fetches information about a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#get-information-about-a-pages-site -func (s *RepositoriesService) GetPagesInfo(ctx context.Context, owner, repo string) (*Pages, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - site := new(Pages) - resp, err := s.client.Do(ctx, req, site) - if err != nil { - return nil, resp, err - } - - return site, resp, nil -} - -// ListPagesBuilds lists the builds for a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds -func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pages []*PagesBuild - resp, err := s.client.Do(ctx, req, &pages) - if err != nil { - return nil, resp, err - } - - return pages, resp, nil -} - -// GetLatestPagesBuild fetches the latest build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-latest-pages-build -func (s *RepositoriesService) GetLatestPagesBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/latest", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// GetPageBuild fetches the specific build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-a-specific-pages-build -func (s *RepositoriesService) GetPageBuild(ctx context.Context, owner, repo string, id int64) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// RequestPageBuild requests a build of a GitHub Pages site without needing to push new commit. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#request-a-page-build -func (s *RepositoriesService) RequestPageBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_prereceive_hooks.go b/vendor/github.com/google/go-github/github/repos_prereceive_hooks.go deleted file mode 100644 index cab09f747..000000000 --- a/vendor/github.com/google/go-github/github/repos_prereceive_hooks.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// PreReceiveHook represents a GitHub pre-receive hook for a repository. -type PreReceiveHook struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Enforcement *string `json:"enforcement,omitempty"` - ConfigURL *string `json:"configuration_url,omitempty"` -} - -func (p PreReceiveHook) String() string { - return Stringify(p) -} - -// ListPreReceiveHooks lists all pre-receive hooks for the specified repository. -// -// GitHub API docs: https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/#list-pre-receive-hooks -func (s *RepositoriesService) ListPreReceiveHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PreReceiveHook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pre-receive-hooks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePreReceiveHooksPreview) - - var hooks []*PreReceiveHook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetPreReceiveHook returns a single specified pre-receive hook. -// -// GitHub API docs: https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/#get-a-single-pre-receive-hook -func (s *RepositoriesService) GetPreReceiveHook(ctx context.Context, owner, repo string, id int64) (*PreReceiveHook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pre-receive-hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePreReceiveHooksPreview) - - h := new(PreReceiveHook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// UpdatePreReceiveHook updates a specified pre-receive hook. -// -// GitHub API docs: https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/#update-pre-receive-hook-enforcement -func (s *RepositoriesService) UpdatePreReceiveHook(ctx context.Context, owner, repo string, id int64, hook *PreReceiveHook) (*PreReceiveHook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pre-receive-hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePreReceiveHooksPreview) - - h := new(PreReceiveHook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// DeletePreReceiveHook deletes a specified pre-receive hook. -// -// GitHub API docs: https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/#remove-enforcement-overrides-for-a-pre-receive-hook -func (s *RepositoriesService) DeletePreReceiveHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/pre-receive-hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePreReceiveHooksPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_projects.go b/vendor/github.com/google/go-github/github/repos_projects.go deleted file mode 100644 index d6486d293..000000000 --- a/vendor/github.com/google/go-github/github/repos_projects.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ProjectListOptions specifies the optional parameters to the -// OrganizationsService.ListProjects and RepositoriesService.ListProjects methods. -type ProjectListOptions struct { - // Indicates the state of the projects to return. Can be either open, closed, or all. Default: open - State string `url:"state,omitempty"` - - ListOptions -} - -// ListProjects lists the projects for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-repository-projects -func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-a-repository-project -func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_releases.go b/vendor/github.com/google/go-github/github/repos_releases.go deleted file mode 100644 index bf58743eb..000000000 --- a/vendor/github.com/google/go-github/github/repos_releases.go +++ /dev/null @@ -1,370 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "errors" - "fmt" - "io" - "mime" - "net/http" - "os" - "path/filepath" - "strings" -) - -// RepositoryRelease represents a GitHub release in a repository. -type RepositoryRelease struct { - TagName *string `json:"tag_name,omitempty"` - TargetCommitish *string `json:"target_commitish,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Draft *bool `json:"draft,omitempty"` - Prerelease *bool `json:"prerelease,omitempty"` - - // The following fields are not used in CreateRelease or EditRelease: - ID *int64 `json:"id,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PublishedAt *Timestamp `json:"published_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AssetsURL *string `json:"assets_url,omitempty"` - Assets []ReleaseAsset `json:"assets,omitempty"` - UploadURL *string `json:"upload_url,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` - Author *User `json:"author,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (r RepositoryRelease) String() string { - return Stringify(r) -} - -// ReleaseAsset represents a GitHub release asset in a repository. -type ReleaseAsset struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Label *string `json:"label,omitempty"` - State *string `json:"state,omitempty"` - ContentType *string `json:"content_type,omitempty"` - Size *int `json:"size,omitempty"` - DownloadCount *int `json:"download_count,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - BrowserDownloadURL *string `json:"browser_download_url,omitempty"` - Uploader *User `json:"uploader,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (r ReleaseAsset) String() string { - return Stringify(r) -} - -// ListReleases lists the releases for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository -func (s *RepositoriesService) ListReleases(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var releases []*RepositoryRelease - resp, err := s.client.Do(ctx, req, &releases) - if err != nil { - return nil, resp, err - } - return releases, resp, nil -} - -// GetRelease fetches a single release. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release -func (s *RepositoriesService) GetRelease(ctx context.Context, owner, repo string, id int64) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - return s.getSingleRelease(ctx, u) -} - -// GetLatestRelease fetches the latest published release for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release -func (s *RepositoriesService) GetLatestRelease(ctx context.Context, owner, repo string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/latest", owner, repo) - return s.getSingleRelease(ctx, u) -} - -// GetReleaseByTag fetches a release with the specified tag. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name -func (s *RepositoriesService) GetReleaseByTag(ctx context.Context, owner, repo, tag string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/tags/%s", owner, repo, tag) - return s.getSingleRelease(ctx, u) -} - -func (s *RepositoriesService) getSingleRelease(ctx context.Context, url string) (*RepositoryRelease, *Response, error) { - req, err := s.client.NewRequest("GET", url, nil) - if err != nil { - return nil, nil, err - } - - release := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, release) - if err != nil { - return nil, resp, err - } - return release, resp, nil -} - -// repositoryReleaseRequest is a subset of RepositoryRelease and -// is used internally by CreateRelease and EditRelease to pass -// only the known fields for these endpoints. -// -// See https://github.com/google/go-github/issues/992 for more -// information. -type repositoryReleaseRequest struct { - TagName *string `json:"tag_name,omitempty"` - TargetCommitish *string `json:"target_commitish,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Draft *bool `json:"draft,omitempty"` - Prerelease *bool `json:"prerelease,omitempty"` -} - -// CreateRelease adds a new release for a repository. -// -// Note that only a subset of the release fields are used. -// See RepositoryRelease for more information. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#create-a-release -func (s *RepositoriesService) CreateRelease(ctx context.Context, owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - - releaseReq := &repositoryReleaseRequest{ - TagName: release.TagName, - TargetCommitish: release.TargetCommitish, - Name: release.Name, - Body: release.Body, - Draft: release.Draft, - Prerelease: release.Prerelease, - } - - req, err := s.client.NewRequest("POST", u, releaseReq) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// EditRelease edits a repository release. -// -// Note that only a subset of the release fields are used. -// See RepositoryRelease for more information. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release -func (s *RepositoriesService) EditRelease(ctx context.Context, owner, repo string, id int64, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - releaseReq := &repositoryReleaseRequest{ - TagName: release.TagName, - TargetCommitish: release.TargetCommitish, - Name: release.Name, - Body: release.Body, - Draft: release.Draft, - Prerelease: release.Prerelease, - } - - req, err := s.client.NewRequest("PATCH", u, releaseReq) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// DeleteRelease delete a single release from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release -func (s *RepositoriesService) DeleteRelease(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListReleaseAssets lists the release's assets. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-assets-for-a-release -func (s *RepositoriesService) ListReleaseAssets(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var assets []*ReleaseAsset - resp, err := s.client.Do(ctx, req, &assets) - if err != nil { - return nil, resp, err - } - return assets, resp, nil -} - -// GetReleaseAsset fetches a single release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) GetReleaseAsset(ctx context.Context, owner, repo string, id int64) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DownloadReleaseAsset downloads a release asset or returns a redirect URL. -// -// DownloadReleaseAsset returns an io.ReadCloser that reads the contents of the -// specified release asset. It is the caller's responsibility to close the ReadCloser. -// If a redirect is returned, the redirect URL will be returned as a string instead -// of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, repo string, id int64) (rc io.ReadCloser, redirectURL string, err error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, "", err - } - req.Header.Set("Accept", defaultMediaType) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - req = withContext(ctx, req) - resp, err := s.client.client.Do(req) - if err != nil { - if !strings.Contains(err.Error(), "disable redirect") { - return nil, "", err - } - return nil, loc, nil // Intentionally return no error with valid redirect URL. - } - - if err := CheckResponse(resp); err != nil { - resp.Body.Close() - return nil, "", err - } - - return resp.Body, "", nil -} - -// EditReleaseAsset edits a repository release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release-asset -func (s *RepositoriesService) EditReleaseAsset(ctx context.Context, owner, repo string, id int64, release *ReleaseAsset) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, release) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DeleteReleaseAsset delete a single release asset from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release-asset -func (s *RepositoriesService) DeleteReleaseAsset(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// UploadReleaseAsset creates an asset by uploading a file into a release repository. -// To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#upload-a-release-asset -func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, repo string, id int64, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - stat, err := file.Stat() - if err != nil { - return nil, nil, err - } - if stat.IsDir() { - return nil, nil, errors.New("the asset to upload can't be a directory") - } - - mediaType := mime.TypeByExtension(filepath.Ext(file.Name())) - req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_stats.go b/vendor/github.com/google/go-github/github/repos_stats.go deleted file mode 100644 index bb355aead..000000000 --- a/vendor/github.com/google/go-github/github/repos_stats.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// ContributorStats represents a contributor to a repository and their -// weekly contributions to a given repo. -type ContributorStats struct { - Author *Contributor `json:"author,omitempty"` - Total *int `json:"total,omitempty"` - Weeks []WeeklyStats `json:"weeks,omitempty"` -} - -func (c ContributorStats) String() string { - return Stringify(c) -} - -// WeeklyStats represents the number of additions, deletions and commits -// a Contributor made in a given week. -type WeeklyStats struct { - Week *Timestamp `json:"w,omitempty"` - Additions *int `json:"a,omitempty"` - Deletions *int `json:"d,omitempty"` - Commits *int `json:"c,omitempty"` -} - -func (w WeeklyStats) String() string { - return Stringify(w) -} - -// ListContributorsStats gets a repo's contributor list with additions, -// deletions and commit counts. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#contributors -func (s *RepositoriesService) ListContributorsStats(ctx context.Context, owner, repo string) ([]*ContributorStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/contributors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributorStats []*ContributorStats - resp, err := s.client.Do(ctx, req, &contributorStats) - if err != nil { - return nil, resp, err - } - - return contributorStats, resp, nil -} - -// WeeklyCommitActivity represents the weekly commit activity for a repository. -// The days array is a group of commits per day, starting on Sunday. -type WeeklyCommitActivity struct { - Days []int `json:"days,omitempty"` - Total *int `json:"total,omitempty"` - Week *Timestamp `json:"week,omitempty"` -} - -func (w WeeklyCommitActivity) String() string { - return Stringify(w) -} - -// ListCommitActivity returns the last year of commit activity -// grouped by week. The days array is a group of commits per day, -// starting on Sunday. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#commit-activity -func (s *RepositoriesService) ListCommitActivity(ctx context.Context, owner, repo string) ([]*WeeklyCommitActivity, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/commit_activity", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeklyCommitActivity []*WeeklyCommitActivity - resp, err := s.client.Do(ctx, req, &weeklyCommitActivity) - if err != nil { - return nil, resp, err - } - - return weeklyCommitActivity, resp, nil -} - -// ListCodeFrequency returns a weekly aggregate of the number of additions and -// deletions pushed to a repository. Returned WeeklyStats will contain -// additions and deletions, but not total commits. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#code-frequency -func (s *RepositoriesService) ListCodeFrequency(ctx context.Context, owner, repo string) ([]*WeeklyStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/code_frequency", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeks [][]int - resp, err := s.client.Do(ctx, req, &weeks) - - // convert int slices into WeeklyStats - var stats []*WeeklyStats - for _, week := range weeks { - if len(week) != 3 { - continue - } - stat := &WeeklyStats{ - Week: &Timestamp{time.Unix(int64(week[0]), 0)}, - Additions: Int(week[1]), - Deletions: Int(week[2]), - } - stats = append(stats, stat) - } - - return stats, resp, err -} - -// RepositoryParticipation is the number of commits by everyone -// who has contributed to the repository (including the owner) -// as well as the number of commits by the owner themself. -type RepositoryParticipation struct { - All []int `json:"all,omitempty"` - Owner []int `json:"owner,omitempty"` -} - -func (r RepositoryParticipation) String() string { - return Stringify(r) -} - -// ListParticipation returns the total commit counts for the 'owner' -// and total commit counts in 'all'. 'all' is everyone combined, -// including the 'owner' in the last 52 weeks. If you’d like to get -// the commit counts for non-owners, you can subtract 'all' from 'owner'. -// -// The array order is oldest week (index 0) to most recent week. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#participation -func (s *RepositoriesService) ListParticipation(ctx context.Context, owner, repo string) (*RepositoryParticipation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/participation", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - participation := new(RepositoryParticipation) - resp, err := s.client.Do(ctx, req, participation) - if err != nil { - return nil, resp, err - } - - return participation, resp, nil -} - -// PunchCard represents the number of commits made during a given hour of a -// day of the week. -type PunchCard struct { - Day *int // Day of the week (0-6: =Sunday - Saturday). - Hour *int // Hour of day (0-23). - Commits *int // Number of commits. -} - -// ListPunchCard returns the number of commits per hour in each day. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#punch-card -func (s *RepositoriesService) ListPunchCard(ctx context.Context, owner, repo string) ([]*PunchCard, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/punch_card", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var results [][]int - resp, err := s.client.Do(ctx, req, &results) - - // convert int slices into Punchcards - var cards []*PunchCard - for _, result := range results { - if len(result) != 3 { - continue - } - card := &PunchCard{ - Day: Int(result[0]), - Hour: Int(result[1]), - Commits: Int(result[2]), - } - cards = append(cards, card) - } - - return cards, resp, err -} diff --git a/vendor/github.com/google/go-github/github/repos_statuses.go b/vendor/github.com/google/go-github/github/repos_statuses.go deleted file mode 100644 index f94fdc858..000000000 --- a/vendor/github.com/google/go-github/github/repos_statuses.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// RepoStatus represents the status of a repository at a particular reference. -type RepoStatus struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // State is the current state of the repository. Possible values are: - // pending, success, error, or failure. - State *string `json:"state,omitempty"` - - // TargetURL is the URL of the page representing this status. It will be - // linked from the GitHub UI to allow users to see the source of the status. - TargetURL *string `json:"target_url,omitempty"` - - // Description is a short high level summary of the status. - Description *string `json:"description,omitempty"` - - // A string label to differentiate this status from the statuses of other systems. - Context *string `json:"context,omitempty"` - - Creator *User `json:"creator,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -func (r RepoStatus) String() string { - return Stringify(r) -} - -// ListStatuses lists the statuses of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref -func (s *RepositoriesService) ListStatuses(ctx context.Context, owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/statuses", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var statuses []*RepoStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// CreateStatus creates a new status for a repository at the specified -// reference. Ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#create-a-status -func (s *RepositoriesService) CreateStatus(ctx context.Context, owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/statuses/%v", owner, repo, ref) - req, err := s.client.NewRequest("POST", u, status) - if err != nil { - return nil, nil, err - } - - repoStatus := new(RepoStatus) - resp, err := s.client.Do(ctx, req, repoStatus) - if err != nil { - return nil, resp, err - } - - return repoStatus, resp, nil -} - -// CombinedStatus represents the combined status of a repository at a particular reference. -type CombinedStatus struct { - // State is the combined state of the repository. Possible values are: - // failure, pending, or success. - State *string `json:"state,omitempty"` - - Name *string `json:"name,omitempty"` - SHA *string `json:"sha,omitempty"` - TotalCount *int `json:"total_count,omitempty"` - Statuses []RepoStatus `json:"statuses,omitempty"` - - CommitURL *string `json:"commit_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` -} - -func (s CombinedStatus) String() string { - return Stringify(s) -} - -// GetCombinedStatus returns the combined status of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref -func (s *RepositoriesService) GetCombinedStatus(ctx context.Context, owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/status", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - status := new(CombinedStatus) - resp, err := s.client.Do(ctx, req, status) - if err != nil { - return nil, resp, err - } - - return status, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_traffic.go b/vendor/github.com/google/go-github/github/repos_traffic.go deleted file mode 100644 index fb1c97648..000000000 --- a/vendor/github.com/google/go-github/github/repos_traffic.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// TrafficReferrer represent information about traffic from a referrer . -type TrafficReferrer struct { - Referrer *string `json:"referrer,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficPath represent information about the traffic on a path of the repo. -type TrafficPath struct { - Path *string `json:"path,omitempty"` - Title *string `json:"title,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficData represent information about a specific timestamp in views or clones list. -type TrafficData struct { - Timestamp *Timestamp `json:"timestamp,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficViews represent information about the number of views in the last 14 days. -type TrafficViews struct { - Views []*TrafficData `json:"views,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficClones represent information about the number of clones in the last 14 days. -type TrafficClones struct { - Clones []*TrafficData `json:"clones,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficBreakdownOptions specifies the parameters to methods that support breakdown per day or week. -// Can be one of: day, week. Default: day. -type TrafficBreakdownOptions struct { - Per string `url:"per,omitempty"` -} - -// ListTrafficReferrers list the top 10 referrers over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-referrers -func (s *RepositoriesService) ListTrafficReferrers(ctx context.Context, owner, repo string) ([]*TrafficReferrer, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/referrers", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var trafficReferrers []*TrafficReferrer - resp, err := s.client.Do(ctx, req, &trafficReferrers) - if err != nil { - return nil, resp, err - } - - return trafficReferrers, resp, nil -} - -// ListTrafficPaths list the top 10 popular content over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-paths -func (s *RepositoriesService) ListTrafficPaths(ctx context.Context, owner, repo string) ([]*TrafficPath, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/paths", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var paths []*TrafficPath - resp, err := s.client.Do(ctx, req, &paths) - if err != nil { - return nil, resp, err - } - - return paths, resp, nil -} - -// ListTrafficViews get total number of views for the last 14 days and breaks it down either per day or week. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficViews, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/views", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficViews := new(TrafficViews) - resp, err := s.client.Do(ctx, req, &trafficViews) - if err != nil { - return nil, resp, err - } - - return trafficViews, resp, nil -} - -// ListTrafficClones get total number of clones for the last 14 days and breaks it down either per day or week for the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficClones(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficClones, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/clones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficClones := new(TrafficClones) - resp, err := s.client.Do(ctx, req, &trafficClones) - if err != nil { - return nil, resp, err - } - - return trafficClones, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/search.go b/vendor/github.com/google/go-github/github/search.go deleted file mode 100644 index abaf5e1f0..000000000 --- a/vendor/github.com/google/go-github/github/search.go +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/url" - "strconv" - "strings" - - qs "github.com/google/go-querystring/query" -) - -// SearchService provides access to the search related functions -// in the GitHub API. -// -// Each method takes a query string defining the search keywords and any search qualifiers. -// For example, when searching issues, the query "gopher is:issue language:go" will search -// for issues containing the word "gopher" in Go repositories. The method call -// opts := &github.SearchOptions{Sort: "created", Order: "asc"} -// cl.Search.Issues(ctx, "gopher is:issue language:go", opts) -// will search for such issues, sorting by creation date in ascending order -// (i.e., oldest first). -// -// GitHub API docs: https://developer.github.com/v3/search/ -type SearchService service - -// SearchOptions specifies optional parameters to the SearchService methods. -type SearchOptions struct { - // How to sort the search results. Possible values are: - // - for repositories: stars, fork, updated - // - for commits: author-date, committer-date - // - for code: indexed - // - for issues: comments, created, updated - // - for users: followers, repositories, joined - // - // Default is to sort by best match. - Sort string `url:"sort,omitempty"` - - // Sort order if sort parameter is provided. Possible values are: asc, - // desc. Default is desc. - Order string `url:"order,omitempty"` - - // Whether to retrieve text match metadata with a query - TextMatch bool `url:"-"` - - ListOptions -} - -// Common search parameters. -type searchParameters struct { - Query string - RepositoryID *int64 // Sent if non-nil. -} - -// RepositoriesSearchResult represents the result of a repositories search. -type RepositoriesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Repositories []Repository `json:"items,omitempty"` -} - -// Repositories searches repositories via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-repositories -func (s *SearchService) Repositories(ctx context.Context, query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error) { - result := new(RepositoriesSearchResult) - resp, err := s.search(ctx, "repositories", &searchParameters{Query: query}, opt, result) - return result, resp, err -} - -// CommitsSearchResult represents the result of a commits search. -type CommitsSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Commits []*CommitResult `json:"items,omitempty"` -} - -// CommitResult represents a commit object as returned in commit search endpoint response. -type CommitResult struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []*Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - Repository *Repository `json:"repository,omitempty"` - Score *float64 `json:"score,omitempty"` -} - -// Commits searches commits via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-commits -func (s *SearchService) Commits(ctx context.Context, query string, opt *SearchOptions) (*CommitsSearchResult, *Response, error) { - result := new(CommitsSearchResult) - resp, err := s.search(ctx, "commits", &searchParameters{Query: query}, opt, result) - return result, resp, err -} - -// IssuesSearchResult represents the result of an issues search. -type IssuesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Issues []Issue `json:"items,omitempty"` -} - -// Issues searches issues via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-issues -func (s *SearchService) Issues(ctx context.Context, query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error) { - result := new(IssuesSearchResult) - resp, err := s.search(ctx, "issues", &searchParameters{Query: query}, opt, result) - return result, resp, err -} - -// UsersSearchResult represents the result of a users search. -type UsersSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Users []User `json:"items,omitempty"` -} - -// Users searches users via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-users -func (s *SearchService) Users(ctx context.Context, query string, opt *SearchOptions) (*UsersSearchResult, *Response, error) { - result := new(UsersSearchResult) - resp, err := s.search(ctx, "users", &searchParameters{Query: query}, opt, result) - return result, resp, err -} - -// Match represents a single text match. -type Match struct { - Text *string `json:"text,omitempty"` - Indices []int `json:"indices,omitempty"` -} - -// TextMatch represents a text match for a SearchResult -type TextMatch struct { - ObjectURL *string `json:"object_url,omitempty"` - ObjectType *string `json:"object_type,omitempty"` - Property *string `json:"property,omitempty"` - Fragment *string `json:"fragment,omitempty"` - Matches []Match `json:"matches,omitempty"` -} - -func (tm TextMatch) String() string { - return Stringify(tm) -} - -// CodeSearchResult represents the result of a code search. -type CodeSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - CodeResults []CodeResult `json:"items,omitempty"` -} - -// CodeResult represents a single search result. -type CodeResult struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Repository *Repository `json:"repository,omitempty"` - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (c CodeResult) String() string { - return Stringify(c) -} - -// Code searches code via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-code -func (s *SearchService) Code(ctx context.Context, query string, opt *SearchOptions) (*CodeSearchResult, *Response, error) { - result := new(CodeSearchResult) - resp, err := s.search(ctx, "code", &searchParameters{Query: query}, opt, result) - return result, resp, err -} - -// LabelsSearchResult represents the result of a code search. -type LabelsSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Labels []*LabelResult `json:"items,omitempty"` -} - -// LabelResult represents a single search result. -type LabelResult struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Color *string `json:"color,omitempty"` - Default *bool `json:"default,omitempty"` - Description *string `json:"description,omitempty"` - Score *float64 `json:"score,omitempty"` -} - -func (l LabelResult) String() string { - return Stringify(l) -} - -// Labels searches labels in the repository with ID repoID via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-labels -func (s *SearchService) Labels(ctx context.Context, repoID int64, query string, opt *SearchOptions) (*LabelsSearchResult, *Response, error) { - result := new(LabelsSearchResult) - resp, err := s.search(ctx, "labels", &searchParameters{RepositoryID: &repoID, Query: query}, opt, result) - return result, resp, err -} - -// Helper function that executes search queries against different -// GitHub search types (repositories, commits, code, issues, users, labels) -func (s *SearchService) search(ctx context.Context, searchType string, parameters *searchParameters, opt *SearchOptions, result interface{}) (*Response, error) { - params, err := qs.Values(opt) - if err != nil { - return nil, err - } - q := strings.Replace(parameters.Query, " ", "+", -1) - if parameters.RepositoryID != nil { - params.Set("repository_id", strconv.FormatInt(*parameters.RepositoryID, 10)) - } - query := "q=" + url.PathEscape(q) - if v := params.Encode(); v != "" { - query = query + "&" + v - } - u := fmt.Sprintf("search/%s?%s", searchType, query) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - switch { - case searchType == "commits": - // Accept header for search commits preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCommitSearchPreview) - case searchType == "repositories": - // Accept header for search repositories based on topics preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - case searchType == "labels": - // Accept header for search labels based on label description preview endpoint. - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeLabelDescriptionSearchPreview) - case opt != nil && opt.TextMatch: - // Accept header defaults to "application/vnd.github.v3+json" - // We change it here to fetch back text-match metadata - req.Header.Set("Accept", "application/vnd.github.v3.text-match+json") - } - - return s.client.Do(ctx, req, result) -} diff --git a/vendor/github.com/google/go-github/github/strings.go b/vendor/github.com/google/go-github/github/strings.go deleted file mode 100644 index 431e1cc6c..000000000 --- a/vendor/github.com/google/go-github/github/strings.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "fmt" - "io" - - "reflect" -) - -var timestampType = reflect.TypeOf(Timestamp{}) - -// Stringify attempts to create a reasonable string representation of types in -// the GitHub library. It does things like resolve pointers to their values -// and omits struct fields with nil values. -func Stringify(message interface{}) string { - var buf bytes.Buffer - v := reflect.ValueOf(message) - stringifyValue(&buf, v) - return buf.String() -} - -// stringifyValue was heavily inspired by the goprotobuf library. - -func stringifyValue(w io.Writer, val reflect.Value) { - if val.Kind() == reflect.Ptr && val.IsNil() { - w.Write([]byte("")) - return - } - - v := reflect.Indirect(val) - - switch v.Kind() { - case reflect.String: - fmt.Fprintf(w, `"%s"`, v) - case reflect.Slice: - w.Write([]byte{'['}) - for i := 0; i < v.Len(); i++ { - if i > 0 { - w.Write([]byte{' '}) - } - - stringifyValue(w, v.Index(i)) - } - - w.Write([]byte{']'}) - return - case reflect.Struct: - if v.Type().Name() != "" { - w.Write([]byte(v.Type().String())) - } - - // special handling of Timestamp values - if v.Type() == timestampType { - fmt.Fprintf(w, "{%s}", v.Interface()) - return - } - - w.Write([]byte{'{'}) - - var sep bool - for i := 0; i < v.NumField(); i++ { - fv := v.Field(i) - if fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - continue - } - - if sep { - w.Write([]byte(", ")) - } else { - sep = true - } - - w.Write([]byte(v.Type().Field(i).Name)) - w.Write([]byte{':'}) - stringifyValue(w, fv) - } - - w.Write([]byte{'}'}) - default: - if v.CanInterface() { - fmt.Fprint(w, v.Interface()) - } - } -} diff --git a/vendor/github.com/google/go-github/github/teams.go b/vendor/github.com/google/go-github/github/teams.go deleted file mode 100644 index c3773e00e..000000000 --- a/vendor/github.com/google/go-github/github/teams.go +++ /dev/null @@ -1,357 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" - "time" -) - -// TeamsService provides access to the team-related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/teams/ -type TeamsService service - -// Team represents a team within a GitHub organization. Teams are used to -// manage access to an organization's repositories. -type Team struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - URL *string `json:"url,omitempty"` - Slug *string `json:"slug,omitempty"` - - // Permission specifies the default permission for repositories owned by the team. - Permission *string `json:"permission,omitempty"` - - // Privacy identifies the level of privacy this team should have. - // Possible values are: - // secret - only visible to organization owners and members of this team - // closed - visible to all members of this organization - // Default is "secret". - Privacy *string `json:"privacy,omitempty"` - - MembersCount *int `json:"members_count,omitempty"` - ReposCount *int `json:"repos_count,omitempty"` - Organization *Organization `json:"organization,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - Parent *Team `json:"parent,omitempty"` - - // LDAPDN is only available in GitHub Enterprise and when the team - // membership is synchronized with LDAP. - LDAPDN *string `json:"ldap_dn,omitempty"` -} - -func (t Team) String() string { - return Stringify(t) -} - -// Invitation represents a team member's invitation status. -type Invitation struct { - ID *int64 `json:"id,omitempty"` - Login *string `json:"login,omitempty"` - Email *string `json:"email,omitempty"` - // Role can be one of the values - 'direct_member', 'admin', 'billing_manager', 'hiring_manager', or 'reinstate'. - Role *string `json:"role,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - Inviter *User `json:"inviter,omitempty"` - TeamCount *int `json:"team_count,omitempty"` - InvitationTeamURL *string `json:"invitation_team_url,omitempty"` -} - -func (i Invitation) String() string { - return Stringify(i) -} - -// ListTeams lists all of the teams for an organization. -// -// GitHub API docs: https://developer.github.com/v3/teams/#list-teams -func (s *TeamsService) ListTeams(ctx context.Context, org string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// GetTeam fetches a team by ID. -// -// GitHub API docs: https://developer.github.com/v3/teams/#get-team -func (s *TeamsService) GetTeam(ctx context.Context, team int64) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// NewTeam represents a team to be created or modified. -type NewTeam struct { - Name string `json:"name"` // Name of the team. (Required.) - Description *string `json:"description,omitempty"` - Maintainers []string `json:"maintainers,omitempty"` - RepoNames []string `json:"repo_names,omitempty"` - ParentTeamID *int64 `json:"parent_team_id,omitempty"` - - // Deprecated: Permission is deprecated when creating or editing a team in an org - // using the new GitHub permission model. It no longer identifies the - // permission a team has on its repos, but only specifies the default - // permission a repo is initially added with. Avoid confusion by - // specifying a permission value when calling AddTeamRepo. - Permission *string `json:"permission,omitempty"` - - // Privacy identifies the level of privacy this team should have. - // Possible values are: - // secret - only visible to organization owners and members of this team - // closed - visible to all members of this organization - // Default is "secret". - Privacy *string `json:"privacy,omitempty"` - - // LDAPDN may be used in GitHub Enterprise when the team membership - // is synchronized with LDAP. - LDAPDN *string `json:"ldap_dn,omitempty"` -} - -func (s NewTeam) String() string { - return Stringify(s) -} - -// CreateTeam creates a new team within an organization. -// -// GitHub API docs: https://developer.github.com/v3/teams/#create-team -func (s *TeamsService) CreateTeam(ctx context.Context, org string, team NewTeam) (*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - req, err := s.client.NewRequest("POST", u, team) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// EditTeam edits a team. -// -// GitHub API docs: https://developer.github.com/v3/teams/#edit-team -func (s *TeamsService) EditTeam(ctx context.Context, id int64, team NewTeam) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", id) - req, err := s.client.NewRequest("PATCH", u, team) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// DeleteTeam deletes a team. -// -// GitHub API docs: https://developer.github.com/v3/teams/#delete-team -func (s *TeamsService) DeleteTeam(ctx context.Context, team int64) (*Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ListChildTeams lists child teams for a team. -// -// GitHub API docs: https://developer.github.com/v3/teams/#list-child-teams -func (s *TeamsService) ListChildTeams(ctx context.Context, teamID int64, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("teams/%v/teams", teamID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// ListTeamRepos lists the repositories that the specified team has access to. -// -// GitHub API docs: https://developer.github.com/v3/teams/#list-team-repos -func (s *TeamsService) ListTeamRepos(ctx context.Context, team int64, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - headers := []string{mediaTypeTopicsPreview, mediaTypeNestedTeamsPreview} - req.Header.Set("Accept", strings.Join(headers, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsTeamRepo checks if a team manages the specified repository. If the -// repository is managed by team, a Repository is returned which includes the -// permissions team has for that repo. -// -// GitHub API docs: https://developer.github.com/v3/teams/#check-if-a-team-manages-a-repository -func (s *TeamsService) IsTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - headers := []string{mediaTypeOrgPermissionRepo, mediaTypeNestedTeamsPreview} - req.Header.Set("Accept", strings.Join(headers, ", ")) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// TeamAddTeamRepoOptions specifies the optional parameters to the -// TeamsService.AddTeamRepo method. -type TeamAddTeamRepoOptions struct { - // Permission specifies the permission to grant the team on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // If not specified, the team's permission attribute will be used. - Permission string `json:"permission,omitempty"` -} - -// AddTeamRepo adds a repository to be managed by the specified team. The -// specified repository must be owned by the organization to which the team -// belongs, or a direct fork of a repository owned by the organization. -// -// GitHub API docs: https://developer.github.com/v3/teams/#add-team-repo -func (s *TeamsService) AddTeamRepo(ctx context.Context, team int64, owner string, repo string, opt *TeamAddTeamRepoOptions) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// RemoveTeamRepo removes a repository from being managed by the specified -// team. Note that this does not delete the repository, it just removes it -// from the team. -// -// GitHub API docs: https://developer.github.com/v3/teams/#remove-team-repo -func (s *TeamsService) RemoveTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListUserTeams lists a user's teams -// GitHub API docs: https://developer.github.com/v3/teams/#list-user-teams -func (s *TeamsService) ListUserTeams(ctx context.Context, opt *ListOptions) ([]*Team, *Response, error) { - u := "user/teams" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/teams_discussion_comments.go b/vendor/github.com/google/go-github/github/teams_discussion_comments.go deleted file mode 100644 index a0206b9c9..000000000 --- a/vendor/github.com/google/go-github/github/teams_discussion_comments.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// DiscussionComment represents a GitHub dicussion in a team. -type DiscussionComment struct { - Author *User `json:"author,omitempty"` - Body *string `json:"body,omitempty"` - BodyHTML *string `json:"body_html,omitempty"` - BodyVersion *string `json:"body_version,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - LastEditedAt *Timestamp `json:"last_edited_at,omitempty"` - DiscussionURL *string `json:"discussion_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Number *int `json:"number,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` -} - -func (c DiscussionComment) String() string { - return Stringify(c) -} - -// DiscussionCommentListOptions specifies optional parameters to the -// TeamServices.ListComments method. -type DiscussionCommentListOptions struct { - // Sorts the discussion comments by the date they were created. - // Accepted values are asc and desc. Default is desc. - Direction string `url:"direction,omitempty"` -} - -// ListComments lists all comments on a team discussion. -// Authenticated user must grant read:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussion_comments/#list-comments -func (s *TeamsService) ListComments(ctx context.Context, teamID int64, discussionNumber int, options *DiscussionCommentListOptions) ([]*DiscussionComment, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments", teamID, discussionNumber) - u, err := addOptions(u, options) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - var comments []*DiscussionComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment gets a specific comment on a team discussion. -// Authenticated user must grant read:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussion_comments/#get-a-single-comment -func (s *TeamsService) GetComment(ctx context.Context, teamID int64, discussionNumber, commentNumber int) (*DiscussionComment, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v", teamID, discussionNumber, commentNumber) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - discussionComment := &DiscussionComment{} - resp, err := s.client.Do(ctx, req, discussionComment) - if err != nil { - return nil, resp, err - } - - return discussionComment, resp, nil -} - -// CreateComment creates a new discussion post on a team discussion. -// Authenticated user must grant write:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussion_comments/#create-a-comment -func (s *TeamsService) CreateComment(ctx context.Context, teamID int64, discsusionNumber int, comment DiscussionComment) (*DiscussionComment, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments", teamID, discsusionNumber) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - discussionComment := &DiscussionComment{} - resp, err := s.client.Do(ctx, req, discussionComment) - if err != nil { - return nil, resp, err - } - - return discussionComment, resp, nil -} - -// EditComment edits the body text of a discussion comment. -// Authenticated user must grant write:discussion scope. -// User is allowed to edit body of a comment only. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussion_comments/#edit-a-comment -func (s *TeamsService) EditComment(ctx context.Context, teamID int64, discussionNumber, commentNumber int, comment DiscussionComment) (*DiscussionComment, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v", teamID, discussionNumber, commentNumber) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - discussionComment := &DiscussionComment{} - resp, err := s.client.Do(ctx, req, discussionComment) - if err != nil { - return nil, resp, err - } - - return discussionComment, resp, nil -} - -// DeleteComment deletes a comment on a team discussion. -// Authenticated user must grant write:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussion_comments/#delete-a-comment -func (s *TeamsService) DeleteComment(ctx context.Context, teamID int64, discussionNumber, commentNumber int) (*Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v", teamID, discussionNumber, commentNumber) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/teams_discussions.go b/vendor/github.com/google/go-github/github/teams_discussions.go deleted file mode 100644 index f491c9d1d..000000000 --- a/vendor/github.com/google/go-github/github/teams_discussions.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// TeamDiscussion represents a GitHub dicussion in a team. -type TeamDiscussion struct { - Author *User `json:"author,omitempty"` - Body *string `json:"body,omitempty"` - BodyHTML *string `json:"body_html,omitempty"` - BodyVersion *string `json:"body_version,omitempty"` - CommentsCount *int `json:"comments_count,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - LastEditedAt *Timestamp `json:"last_edited_at,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Number *int `json:"number,omitempty"` - Pinned *bool `json:"pinned,omitempty"` - Private *bool `json:"private,omitempty"` - TeamURL *string `json:"team_url,omitempty"` - Title *string `json:"title,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` -} - -func (d TeamDiscussion) String() string { - return Stringify(d) -} - -// DiscussionListOptions specifies optional parameters to the -// TeamServices.ListDiscussions method. -type DiscussionListOptions struct { - // Sorts the discussion by the date they were created. - // Accepted values are asc and desc. Default is desc. - Direction string `url:"direction,omitempty"` -} - -// ListDiscussions lists all discussions on team's page. -// Authenticated user must grant read:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussions/#list-discussions -func (s *TeamsService) ListDiscussions(ctx context.Context, teamID int64, options *DiscussionListOptions) ([]*TeamDiscussion, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions", teamID) - u, err := addOptions(u, options) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - var teamDiscussions []*TeamDiscussion - resp, err := s.client.Do(ctx, req, &teamDiscussions) - if err != nil { - return nil, resp, err - } - - return teamDiscussions, resp, nil -} - -// GetDiscussion gets a specific discussion on a team's page. -// Authenticated user must grant read:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussions/#get-a-single-discussion -func (s *TeamsService) GetDiscussion(ctx context.Context, teamID int64, discussionNumber int) (*TeamDiscussion, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v", teamID, discussionNumber) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - teamDiscussion := &TeamDiscussion{} - resp, err := s.client.Do(ctx, req, teamDiscussion) - if err != nil { - return nil, resp, err - } - - return teamDiscussion, resp, nil -} - -// CreateDiscussion creates a new discussion post on a team's page. -// Authenticated user must grant write:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussions/#create-a-discussion -func (s *TeamsService) CreateDiscussion(ctx context.Context, teamID int64, discussion TeamDiscussion) (*TeamDiscussion, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions", teamID) - req, err := s.client.NewRequest("POST", u, discussion) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - teamDiscussion := &TeamDiscussion{} - resp, err := s.client.Do(ctx, req, teamDiscussion) - if err != nil { - return nil, resp, err - } - - return teamDiscussion, resp, nil -} - -// EditDiscussion edits the title and body text of a discussion post. -// Authenticated user must grant write:discussion scope. -// User is allowed to change Title and Body of a discussion only. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussions/#edit-a-discussion -func (s *TeamsService) EditDiscussion(ctx context.Context, teamID int64, discussionNumber int, discussion TeamDiscussion) (*TeamDiscussion, *Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v", teamID, discussionNumber) - req, err := s.client.NewRequest("PATCH", u, discussion) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - teamDiscussion := &TeamDiscussion{} - resp, err := s.client.Do(ctx, req, teamDiscussion) - if err != nil { - return nil, resp, err - } - - return teamDiscussion, resp, nil -} - -// DeleteDiscussion deletes a discussion from team's page. -// Authenticated user must grant write:discussion scope. -// -// GitHub API docs: https://developer.github.com/v3/teams/discussions/#delete-a-discussion -func (s *TeamsService) DeleteDiscussion(ctx context.Context, teamID int64, discussionNumber int) (*Response, error) { - u := fmt.Sprintf("teams/%v/discussions/%v", teamID, discussionNumber) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamDiscussionsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/teams_members.go b/vendor/github.com/google/go-github/github/teams_members.go deleted file mode 100644 index d5cfa0dc7..000000000 --- a/vendor/github.com/google/go-github/github/teams_members.go +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2018 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// TeamListTeamMembersOptions specifies the optional parameters to the -// TeamsService.ListTeamMembers method. -type TeamListTeamMembersOptions struct { - // Role filters members returned by their role in the team. Possible - // values are "all", "member", "maintainer". Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListTeamMembers lists all of the users who are members of the specified -// team. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#list-team-members -func (s *TeamsService) ListTeamMembers(ctx context.Context, team int64, opt *TeamListTeamMembersOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("teams/%v/members", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsTeamMember checks if a user is a member of the specified team. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#get-team-member -// -// Deprecated: This API has been marked as deprecated in the Github API docs, -// TeamsService.GetTeamMembership method should be used instead. -func (s *TeamsService) IsTeamMember(ctx context.Context, team int64, user string) (bool, *Response, error) { - u := fmt.Sprintf("teams/%v/members/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// GetTeamMembership returns the membership status for a user in a team. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#get-team-membership -func (s *TeamsService) GetTeamMembership(ctx context.Context, team int64, user string) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// TeamAddTeamMembershipOptions specifies the optional -// parameters to the TeamsService.AddTeamMembership method. -type TeamAddTeamMembershipOptions struct { - // Role specifies the role the user should have in the team. Possible - // values are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - // - // Default value is "member". - Role string `json:"role,omitempty"` -} - -// AddTeamMembership adds or invites a user to a team. -// -// In order to add a membership between a user and a team, the authenticated -// user must have 'admin' permissions to the team or be an owner of the -// organization that the team is associated with. -// -// If the user is already a part of the team's organization (meaning they're on -// at least one other team in the organization), this endpoint will add the -// user to the team. -// -// If the user is completely unaffiliated with the team's organization (meaning -// they're on none of the organization's teams), this endpoint will send an -// invitation to the user via email. This newly-created membership will be in -// the "pending" state until the user accepts the invitation, at which point -// the membership will transition to the "active" state and the user will be -// added as a member of the team. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#add-or-update-team-membership -func (s *TeamsService) AddTeamMembership(ctx context.Context, team int64, user string, opt *TeamAddTeamMembershipOptions) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// RemoveTeamMembership removes a user from a team. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#remove-team-membership -func (s *TeamsService) RemoveTeamMembership(ctx context.Context, team int64, user string) (*Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingTeamInvitations get pending invitaion list in team. -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/teams/members/#list-pending-team-invitations -func (s *TeamsService) ListPendingTeamInvitations(ctx context.Context, team int64, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("teams/%v/invitations", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - - return pendingInvitations, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/timestamp.go b/vendor/github.com/google/go-github/github/timestamp.go deleted file mode 100644 index 90929d575..000000000 --- a/vendor/github.com/google/go-github/github/timestamp.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "strconv" - "time" -) - -// Timestamp represents a time that can be unmarshalled from a JSON string -// formatted as either an RFC3339 or Unix timestamp. This is necessary for some -// fields since the GitHub API is inconsistent in how it represents times. All -// exported methods of time.Time can be called on Timestamp. -type Timestamp struct { - time.Time -} - -func (t Timestamp) String() string { - return t.Time.String() -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -// Time is expected in RFC3339 or Unix format. -func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { - str := string(data) - i, err := strconv.ParseInt(str, 10, 64) - if err == nil { - t.Time = time.Unix(i, 0) - } else { - t.Time, err = time.Parse(`"`+time.RFC3339+`"`, str) - } - return -} - -// Equal reports whether t and u are equal based on time.Equal -func (t Timestamp) Equal(u Timestamp) bool { - return t.Time.Equal(u.Time) -} diff --git a/vendor/github.com/google/go-github/github/users.go b/vendor/github.com/google/go-github/github/users.go deleted file mode 100644 index f164d559e..000000000 --- a/vendor/github.com/google/go-github/github/users.go +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// UsersService handles communication with the user related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/users/ -type UsersService service - -// User represents a GitHub user. -type User struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Hireable *bool `json:"hireable,omitempty"` - Bio *string `json:"bio,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - SuspendedAt *Timestamp `json:"suspended_at,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - Plan *Plan `json:"plan,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` - - // Permissions identifies the permissions that a user has on a given - // repository. This is only populated when calling Repositories.ListCollaborators. - Permissions *map[string]bool `json:"permissions,omitempty"` -} - -func (u User) String() string { - return Stringify(u) -} - -// Get fetches a user. Passing the empty string will fetch the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-a-single-user -func (s *UsersService) Get(ctx context.Context, user string) (*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v", user) - } else { - u = "user" - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// GetByID fetches a user. -// -// Note: GetByID uses the undocumented GitHub API endpoint /user/:id. -func (s *UsersService) GetByID(ctx context.Context, id int64) (*User, *Response, error) { - u := fmt.Sprintf("user/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - user := new(User) - resp, err := s.client.Do(ctx, req, user) - if err != nil { - return nil, resp, err - } - - return user, resp, nil -} - -// Edit the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/#update-the-authenticated-user -func (s *UsersService) Edit(ctx context.Context, user *User) (*User, *Response, error) { - u := "user" - req, err := s.client.NewRequest("PATCH", u, user) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// HovercardOptions specifies optional parameters to the UsersService.GetHovercard -// method. -type HovercardOptions struct { - // SubjectType specifies the additional information to be received about the hovercard. - // Possible values are: organization, repository, issue, pull_request. (Required when using subject_id.) - SubjectType string `url:"subject_type"` - - // SubjectID specifies the ID for the SubjectType. (Required when using subject_type.) - SubjectID string `url:"subject_id"` -} - -// Hovercard represents hovercard information about a user. -type Hovercard struct { - Contexts []*UserContext `json:"contexts,omitempty"` -} - -// UserContext represents the contextual information about user. -type UserContext struct { - Message *string `json:"message,omitempty"` - Octicon *string `json:"octicon,omitempty"` -} - -// GetHovercard fetches contextual information about user. It requires authentication -// via Basic Auth or via OAuth with the repo scope. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-contextual-information-about-a-user -func (s *UsersService) GetHovercard(ctx context.Context, user string, opt *HovercardOptions) (*Hovercard, *Response, error) { - u := fmt.Sprintf("users/%v/hovercard", user) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeHovercardPreview) - - hc := new(Hovercard) - resp, err := s.client.Do(ctx, req, hc) - if err != nil { - return nil, resp, err - } - - return hc, resp, nil -} - -// UserListOptions specifies optional parameters to the UsersService.ListAll -// method. -type UserListOptions struct { - // ID of the last user seen - Since int64 `url:"since,omitempty"` - - // Note: Pagination is powered exclusively by the Since parameter, - // ListOptions.Page has no effect. - // ListOptions.PerPage controls an undocumented GitHub API parameter. - ListOptions -} - -// ListAll lists all GitHub users. -// -// To paginate through all users, populate 'Since' with the ID of the last user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-all-users -func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*User, *Response, error) { - u, err := addOptions("users", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListInvitations lists all currently-open repository invitations for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations -func (s *UsersService) ListInvitations(ctx context.Context, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u, err := addOptions("user/repository_invitations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// AcceptInvitation accepts the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#accept-a-repository-invitation -func (s *UsersService) AcceptInvitation(ctx context.Context, invitationID int64) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// DeclineInvitation declines the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#decline-a-repository-invitation -func (s *UsersService) DeclineInvitation(ctx context.Context, invitationID int64) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_administration.go b/vendor/github.com/google/go-github/github/users_administration.go deleted file mode 100644 index e042398d8..000000000 --- a/vendor/github.com/google/go-github/github/users_administration.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// PromoteSiteAdmin promotes a user to a site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#promote-an-ordinary-user-to-a-site-administrator -func (s *UsersService) PromoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// DemoteSiteAdmin demotes a user from site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#demote-a-site-administrator-to-an-ordinary-user -func (s *UsersService) DemoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Suspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#suspend-a-user -func (s *UsersService) Suspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unsuspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#unsuspend-a-user -func (s *UsersService) Unsuspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_blocking.go b/vendor/github.com/google/go-github/github/users_blocking.go deleted file mode 100644 index 39e45601c..000000000 --- a/vendor/github.com/google/go-github/github/users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the blocked users by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#list-blocked-users -func (s *UsersService) ListBlockedUsers(ctx context.Context, opt *ListOptions) ([]*User, *Response, error) { - u := "user/blocks" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#check-whether-youve-blocked-a-user -func (s *UsersService) IsBlocked(ctx context.Context, user string) (bool, *Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#block-a-user -func (s *UsersService) BlockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#unblock-a-user -func (s *UsersService) UnblockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_emails.go b/vendor/github.com/google/go-github/github/users_emails.go deleted file mode 100644 index 0bbd4627e..000000000 --- a/vendor/github.com/google/go-github/github/users_emails.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import "context" - -// UserEmail represents user's email address -type UserEmail struct { - Email *string `json:"email,omitempty"` - Primary *bool `json:"primary,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListEmails lists all email addresses for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user -func (s *UsersService) ListEmails(ctx context.Context, opt *ListOptions) ([]*UserEmail, *Response, error) { - u := "user/emails" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var emails []*UserEmail - resp, err := s.client.Do(ctx, req, &emails) - if err != nil { - return nil, resp, err - } - - return emails, resp, nil -} - -// AddEmails adds email addresses of the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#add-email-addresses -func (s *UsersService) AddEmails(ctx context.Context, emails []string) ([]*UserEmail, *Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("POST", u, emails) - if err != nil { - return nil, nil, err - } - - var e []*UserEmail - resp, err := s.client.Do(ctx, req, &e) - if err != nil { - return nil, resp, err - } - - return e, resp, nil -} - -// DeleteEmails deletes email addresses from authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#delete-email-addresses -func (s *UsersService) DeleteEmails(ctx context.Context, emails []string) (*Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("DELETE", u, emails) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_followers.go b/vendor/github.com/google/go-github/github/users_followers.go deleted file mode 100644 index c2224096a..000000000 --- a/vendor/github.com/google/go-github/github/users_followers.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListFollowers lists the followers for a user. Passing the empty string will -// fetch followers for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-followers-of-a-user -func (s *UsersService) ListFollowers(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/followers", user) - } else { - u = "user/followers" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListFollowing lists the people that a user is following. Passing the empty -// string will list people the authenticated user is following. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-users-followed-by-another-user -func (s *UsersService) ListFollowing(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following", user) - } else { - u = "user/following" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsFollowing checks if "user" is following "target". Passing the empty -// string for "user" will check if the authenticated user is following "target". -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#check-if-you-are-following-a-user -func (s *UsersService) IsFollowing(ctx context.Context, user, target string) (bool, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following/%v", user, target) - } else { - u = fmt.Sprintf("user/following/%v", target) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - following, err := parseBoolResponse(err) - return following, resp, err -} - -// Follow will cause the authenticated user to follow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#follow-a-user -func (s *UsersService) Follow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unfollow will cause the authenticated user to unfollow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#unfollow-a-user -func (s *UsersService) Unfollow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_gpg_keys.go b/vendor/github.com/google/go-github/github/users_gpg_keys.go deleted file mode 100644 index d8bbc5201..000000000 --- a/vendor/github.com/google/go-github/github/users_gpg_keys.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GPGKey represents a GitHub user's public GPG key used to verify GPG signed commits and tags. -// -// https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ -type GPGKey struct { - ID *int64 `json:"id,omitempty"` - PrimaryKeyID *int64 `json:"primary_key_id,omitempty"` - KeyID *string `json:"key_id,omitempty"` - PublicKey *string `json:"public_key,omitempty"` - Emails []GPGEmail `json:"emails,omitempty"` - Subkeys []GPGKey `json:"subkeys,omitempty"` - CanSign *bool `json:"can_sign,omitempty"` - CanEncryptComms *bool `json:"can_encrypt_comms,omitempty"` - CanEncryptStorage *bool `json:"can_encrypt_storage,omitempty"` - CanCertify *bool `json:"can_certify,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// String stringifies a GPGKey. -func (k GPGKey) String() string { - return Stringify(k) -} - -// GPGEmail represents an email address associated to a GPG key. -type GPGEmail struct { - Email *string `json:"email,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListGPGKeys lists the public GPG keys for a user. Passing the empty -// string will fetch keys for the authenticated user. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user -func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opt *ListOptions) ([]*GPGKey, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gpg_keys", user) - } else { - u = "user/gpg_keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var keys []*GPGKey - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetGPGKey gets extended details for a single GPG key. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#get-a-single-gpg-key -func (s *UsersService) GetGPGKey(ctx context.Context, id int64) (*GPGKey, *Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateGPGKey creates a GPG key. It requires authenticatation via Basic Auth -// or OAuth with at least write:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#create-a-gpg-key -func (s *UsersService) CreateGPGKey(ctx context.Context, armoredPublicKey string) (*GPGKey, *Response, error) { - gpgKey := &struct { - ArmoredPublicKey string `json:"armored_public_key"` - }{ArmoredPublicKey: armoredPublicKey} - req, err := s.client.NewRequest("POST", "user/gpg_keys", gpgKey) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// DeleteGPGKey deletes a GPG key. It requires authentication via Basic Auth or -// via OAuth with at least admin:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#delete-a-gpg-key -func (s *UsersService) DeleteGPGKey(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_keys.go b/vendor/github.com/google/go-github/github/users_keys.go deleted file mode 100644 index ddc832a1e..000000000 --- a/vendor/github.com/google/go-github/github/users_keys.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Key represents a public SSH key used to authenticate a user or deploy script. -type Key struct { - ID *int64 `json:"id,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Title *string `json:"title,omitempty"` - ReadOnly *bool `json:"read_only,omitempty"` -} - -func (k Key) String() string { - return Stringify(k) -} - -// ListKeys lists the verified public keys for a user. Passing the empty -// string will fetch keys for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#list-public-keys-for-a-user -func (s *UsersService) ListKeys(ctx context.Context, user string, opt *ListOptions) ([]*Key, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/keys", user) - } else { - u = "user/keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#get-a-single-public-key -func (s *UsersService) GetKey(ctx context.Context, id int64) (*Key, *Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a public key for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#create-a-public-key -func (s *UsersService) CreateKey(ctx context.Context, key *Key) (*Key, *Response, error) { - u := "user/keys" - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#delete-a-public-key -func (s *UsersService) DeleteKey(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/without_appengine.go b/vendor/github.com/google/go-github/github/without_appengine.go deleted file mode 100644 index 6f8fdac56..000000000 --- a/vendor/github.com/google/go-github/github/without_appengine.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine - -// This file provides glue for making github work without App Engine. - -package github - -import ( - "context" - "net/http" -) - -func withContext(ctx context.Context, req *http.Request) *http.Request { - return req.WithContext(ctx) -} diff --git a/vendor/github.com/googleapis/gax-go/LICENSE b/vendor/github.com/googleapis/gax-go/v2/LICENSE similarity index 100% rename from vendor/github.com/googleapis/gax-go/LICENSE rename to vendor/github.com/googleapis/gax-go/v2/LICENSE diff --git a/vendor/github.com/gosimple/slug/.gitignore b/vendor/github.com/gosimple/slug/.gitignore new file mode 100644 index 000000000..25d190e2b --- /dev/null +++ b/vendor/github.com/gosimple/slug/.gitignore @@ -0,0 +1,2 @@ +_* +cover*.out diff --git a/vendor/github.com/gosimple/slug/.travis.yml b/vendor/github.com/gosimple/slug/.travis.yml new file mode 100644 index 000000000..0ab4df4f4 --- /dev/null +++ b/vendor/github.com/gosimple/slug/.travis.yml @@ -0,0 +1,20 @@ +language: go + +go: + - "1.x" + - master +matrix: + allow_failures: + - go: master + fast_finish: true + +before_script: + - go get -t -v ./... + - go get -v golang.org/x/lint/golint + - go get -v honnef.co/go/tools/cmd/megacheck + - go vet ./... +script: + # run all our tests with race detector + - go test -v -race ./... + # "go vet on steroids" + linter + - megacheck ./... diff --git a/vendor/github.com/hashicorp/consul/LICENSE b/vendor/github.com/hashicorp/consul/LICENSE deleted file mode 100644 index c33dcc7c9..000000000 --- a/vendor/github.com/hashicorp/consul/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/consul/NOTICE.md b/vendor/github.com/hashicorp/consul/NOTICE.md deleted file mode 100644 index fe34b5e57..000000000 --- a/vendor/github.com/hashicorp/consul/NOTICE.md +++ /dev/null @@ -1,3 +0,0 @@ -Copyright © 2014-2018 HashiCorp, Inc. - -This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this project, you can obtain one at http://mozilla.org/MPL/2.0/. diff --git a/vendor/github.com/hashicorp/consul/api/README.md b/vendor/github.com/hashicorp/consul/api/README.md deleted file mode 100644 index 3255cbb24..000000000 --- a/vendor/github.com/hashicorp/consul/api/README.md +++ /dev/null @@ -1,67 +0,0 @@ -Consul API client -================= - -This package provides the `api` package which attempts to -provide programmatic access to the full Consul API. - -Currently, all of the Consul APIs included in version 0.6.0 are supported. - -Documentation -============= - -The full documentation is available on [Godoc](https://godoc.org/github.com/hashicorp/consul/api) - -Usage -===== - -Below is an example of using the Consul client: - -```go -package main - -import "github.com/hashicorp/consul/api" -import "fmt" - -func main() { - // Get a new client - client, err := api.NewClient(api.DefaultConfig()) - if err != nil { - panic(err) - } - - // Get a handle to the KV API - kv := client.KV() - - // PUT a new KV pair - p := &api.KVPair{Key: "REDIS_MAXCLIENTS", Value: []byte("1000")} - _, err = kv.Put(p, nil) - if err != nil { - panic(err) - } - - // Lookup the pair - pair, _, err := kv.Get("REDIS_MAXCLIENTS", nil) - if err != nil { - panic(err) - } - fmt.Printf("KV: %v %s\n", pair.Key, pair.Value) -} -``` - -To run this example, start a Consul server: - -```bash -consul agent -dev -``` - -Copy the code above into a file such as `main.go`. - -Install and run. You'll see a key (`REDIS_MAXCLIENTS`) and value (`1000`) printed. - -```bash -$ go get -$ go run main.go -KV: REDIS_MAXCLIENTS 1000 -``` - -After running the code, you can also view the values in the Consul UI on your local machine at http://localhost:8500/ui/dc1/kv diff --git a/vendor/github.com/hashicorp/consul/api/acl.go b/vendor/github.com/hashicorp/consul/api/acl.go deleted file mode 100644 index 8ec9aa585..000000000 --- a/vendor/github.com/hashicorp/consul/api/acl.go +++ /dev/null @@ -1,193 +0,0 @@ -package api - -import ( - "time" -) - -const ( - // ACLClientType is the client type token - ACLClientType = "client" - - // ACLManagementType is the management type token - ACLManagementType = "management" -) - -// ACLEntry is used to represent an ACL entry -type ACLEntry struct { - CreateIndex uint64 - ModifyIndex uint64 - ID string - Name string - Type string - Rules string -} - -// ACLReplicationStatus is used to represent the status of ACL replication. -type ACLReplicationStatus struct { - Enabled bool - Running bool - SourceDatacenter string - ReplicatedIndex uint64 - LastSuccess time.Time - LastError time.Time -} - -// ACL can be used to query the ACL endpoints -type ACL struct { - c *Client -} - -// ACL returns a handle to the ACL endpoints -func (c *Client) ACL() *ACL { - return &ACL{c} -} - -// Bootstrap is used to perform a one-time ACL bootstrap operation on a cluster -// to get the first management token. -func (a *ACL) Bootstrap() (string, *WriteMeta, error) { - r := a.c.newRequest("PUT", "/v1/acl/bootstrap") - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// Create is used to generate a new token with the given parameters -func (a *ACL) Create(acl *ACLEntry, q *WriteOptions) (string, *WriteMeta, error) { - r := a.c.newRequest("PUT", "/v1/acl/create") - r.setWriteOptions(q) - r.obj = acl - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// Update is used to update the rules of an existing token -func (a *ACL) Update(acl *ACLEntry, q *WriteOptions) (*WriteMeta, error) { - r := a.c.newRequest("PUT", "/v1/acl/update") - r.setWriteOptions(q) - r.obj = acl - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - return wm, nil -} - -// Destroy is used to destroy a given ACL token ID -func (a *ACL) Destroy(id string, q *WriteOptions) (*WriteMeta, error) { - r := a.c.newRequest("PUT", "/v1/acl/destroy/"+id) - r.setWriteOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - return wm, nil -} - -// Clone is used to return a new token cloned from an existing one -func (a *ACL) Clone(id string, q *WriteOptions) (string, *WriteMeta, error) { - r := a.c.newRequest("PUT", "/v1/acl/clone/"+id) - r.setWriteOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// Info is used to query for information about an ACL token -func (a *ACL) Info(id string, q *QueryOptions) (*ACLEntry, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/acl/info/"+id) - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var entries []*ACLEntry - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - if len(entries) > 0 { - return entries[0], qm, nil - } - return nil, qm, nil -} - -// List is used to get all the ACL tokens -func (a *ACL) List(q *QueryOptions) ([]*ACLEntry, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/acl/list") - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var entries []*ACLEntry - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - return entries, qm, nil -} - -// Replication returns the status of the ACL replication process in the datacenter -func (a *ACL) Replication(q *QueryOptions) (*ACLReplicationStatus, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/acl/replication") - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var entries *ACLReplicationStatus - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - return entries, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/agent.go b/vendor/github.com/hashicorp/consul/api/agent.go deleted file mode 100644 index 41505e769..000000000 --- a/vendor/github.com/hashicorp/consul/api/agent.go +++ /dev/null @@ -1,799 +0,0 @@ -package api - -import ( - "bufio" - "fmt" -) - -// ServiceKind is the kind of service being registered. -type ServiceKind string - -const ( - // ServiceKindTypical is a typical, classic Consul service. This is - // represented by the absence of a value. This was chosen for ease of - // backwards compatibility: existing services in the catalog would - // default to the typical service. - ServiceKindTypical ServiceKind = "" - - // ServiceKindConnectProxy is a proxy for the Connect feature. This - // service proxies another service within Consul and speaks the connect - // protocol. - ServiceKindConnectProxy ServiceKind = "connect-proxy" -) - -// ProxyExecMode is the execution mode for a managed Connect proxy. -type ProxyExecMode string - -const ( - // ProxyExecModeDaemon indicates that the proxy command should be long-running - // and should be started and supervised by the agent until it's target service - // is deregistered. - ProxyExecModeDaemon ProxyExecMode = "daemon" - - // ProxyExecModeScript indicates that the proxy command should be invoke to - // completion on each change to the configuration of lifecycle event. The - // script typically fetches the config and certificates from the agent API and - // then configures an externally managed daemon, perhaps starting and stopping - // it if necessary. - ProxyExecModeScript ProxyExecMode = "script" -) - -// AgentCheck represents a check known to the agent -type AgentCheck struct { - Node string - CheckID string - Name string - Status string - Notes string - Output string - ServiceID string - ServiceName string - Definition HealthCheckDefinition -} - -// AgentWeights represent optional weights for a service -type AgentWeights struct { - Passing int - Warning int -} - -// AgentService represents a service known to the agent -type AgentService struct { - Kind ServiceKind - ID string - Service string - Tags []string - Meta map[string]string - Port int - Address string - Weights AgentWeights - EnableTagOverride bool - CreateIndex uint64 - ModifyIndex uint64 - ProxyDestination string - Connect *AgentServiceConnect -} - -// AgentServiceConnect represents the Connect configuration of a service. -type AgentServiceConnect struct { - Native bool - Proxy *AgentServiceConnectProxy -} - -// AgentServiceConnectProxy represents the Connect Proxy configuration of a -// service. -type AgentServiceConnectProxy struct { - ExecMode ProxyExecMode - Command []string - Config map[string]interface{} -} - -// AgentMember represents a cluster member known to the agent -type AgentMember struct { - Name string - Addr string - Port uint16 - Tags map[string]string - Status int - ProtocolMin uint8 - ProtocolMax uint8 - ProtocolCur uint8 - DelegateMin uint8 - DelegateMax uint8 - DelegateCur uint8 -} - -// AllSegments is used to select for all segments in MembersOpts. -const AllSegments = "_all" - -// MembersOpts is used for querying member information. -type MembersOpts struct { - // WAN is whether to show members from the WAN. - WAN bool - - // Segment is the LAN segment to show members for. Setting this to the - // AllSegments value above will show members in all segments. - Segment string -} - -// AgentServiceRegistration is used to register a new service -type AgentServiceRegistration struct { - Kind ServiceKind `json:",omitempty"` - ID string `json:",omitempty"` - Name string `json:",omitempty"` - Tags []string `json:",omitempty"` - Port int `json:",omitempty"` - Address string `json:",omitempty"` - EnableTagOverride bool `json:",omitempty"` - Meta map[string]string `json:",omitempty"` - Weights *AgentWeights `json:",omitempty"` - Check *AgentServiceCheck - Checks AgentServiceChecks - ProxyDestination string `json:",omitempty"` - Connect *AgentServiceConnect `json:",omitempty"` -} - -// AgentCheckRegistration is used to register a new check -type AgentCheckRegistration struct { - ID string `json:",omitempty"` - Name string `json:",omitempty"` - Notes string `json:",omitempty"` - ServiceID string `json:",omitempty"` - AgentServiceCheck -} - -// AgentServiceCheck is used to define a node or service level check -type AgentServiceCheck struct { - CheckID string `json:",omitempty"` - Name string `json:",omitempty"` - Args []string `json:"ScriptArgs,omitempty"` - DockerContainerID string `json:",omitempty"` - Shell string `json:",omitempty"` // Only supported for Docker. - Interval string `json:",omitempty"` - Timeout string `json:",omitempty"` - TTL string `json:",omitempty"` - HTTP string `json:",omitempty"` - Header map[string][]string `json:",omitempty"` - Method string `json:",omitempty"` - TCP string `json:",omitempty"` - Status string `json:",omitempty"` - Notes string `json:",omitempty"` - TLSSkipVerify bool `json:",omitempty"` - GRPC string `json:",omitempty"` - GRPCUseTLS bool `json:",omitempty"` - - // In Consul 0.7 and later, checks that are associated with a service - // may also contain this optional DeregisterCriticalServiceAfter field, - // which is a timeout in the same Go time format as Interval and TTL. If - // a check is in the critical state for more than this configured value, - // then its associated service (and all of its associated checks) will - // automatically be deregistered. - DeregisterCriticalServiceAfter string `json:",omitempty"` -} -type AgentServiceChecks []*AgentServiceCheck - -// AgentToken is used when updating ACL tokens for an agent. -type AgentToken struct { - Token string -} - -// Metrics info is used to store different types of metric values from the agent. -type MetricsInfo struct { - Timestamp string - Gauges []GaugeValue - Points []PointValue - Counters []SampledValue - Samples []SampledValue -} - -// GaugeValue stores one value that is updated as time goes on, such as -// the amount of memory allocated. -type GaugeValue struct { - Name string - Value float32 - Labels map[string]string -} - -// PointValue holds a series of points for a metric. -type PointValue struct { - Name string - Points []float32 -} - -// SampledValue stores info about a metric that is incremented over time, -// such as the number of requests to an HTTP endpoint. -type SampledValue struct { - Name string - Count int - Sum float64 - Min float64 - Max float64 - Mean float64 - Stddev float64 - Labels map[string]string -} - -// AgentAuthorizeParams are the request parameters for authorizing a request. -type AgentAuthorizeParams struct { - Target string - ClientCertURI string - ClientCertSerial string -} - -// AgentAuthorize is the response structure for Connect authorization. -type AgentAuthorize struct { - Authorized bool - Reason string -} - -// ConnectProxyConfig is the response structure for agent-local proxy -// configuration. -type ConnectProxyConfig struct { - ProxyServiceID string - TargetServiceID string - TargetServiceName string - ContentHash string - ExecMode ProxyExecMode - Command []string - Config map[string]interface{} -} - -// Agent can be used to query the Agent endpoints -type Agent struct { - c *Client - - // cache the node name - nodeName string -} - -// Agent returns a handle to the agent endpoints -func (c *Client) Agent() *Agent { - return &Agent{c: c} -} - -// Self is used to query the agent we are speaking to for -// information about itself -func (a *Agent) Self() (map[string]map[string]interface{}, error) { - r := a.c.newRequest("GET", "/v1/agent/self") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out map[string]map[string]interface{} - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// Metrics is used to query the agent we are speaking to for -// its current internal metric data -func (a *Agent) Metrics() (*MetricsInfo, error) { - r := a.c.newRequest("GET", "/v1/agent/metrics") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out *MetricsInfo - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// Reload triggers a configuration reload for the agent we are connected to. -func (a *Agent) Reload() error { - r := a.c.newRequest("PUT", "/v1/agent/reload") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// NodeName is used to get the node name of the agent -func (a *Agent) NodeName() (string, error) { - if a.nodeName != "" { - return a.nodeName, nil - } - info, err := a.Self() - if err != nil { - return "", err - } - name := info["Config"]["NodeName"].(string) - a.nodeName = name - return name, nil -} - -// Checks returns the locally registered checks -func (a *Agent) Checks() (map[string]*AgentCheck, error) { - r := a.c.newRequest("GET", "/v1/agent/checks") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out map[string]*AgentCheck - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// Services returns the locally registered services -func (a *Agent) Services() (map[string]*AgentService, error) { - r := a.c.newRequest("GET", "/v1/agent/services") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out map[string]*AgentService - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - - return out, nil -} - -// Members returns the known gossip members. The WAN -// flag can be used to query a server for WAN members. -func (a *Agent) Members(wan bool) ([]*AgentMember, error) { - r := a.c.newRequest("GET", "/v1/agent/members") - if wan { - r.params.Set("wan", "1") - } - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out []*AgentMember - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// MembersOpts returns the known gossip members and can be passed -// additional options for WAN/segment filtering. -func (a *Agent) MembersOpts(opts MembersOpts) ([]*AgentMember, error) { - r := a.c.newRequest("GET", "/v1/agent/members") - r.params.Set("segment", opts.Segment) - if opts.WAN { - r.params.Set("wan", "1") - } - - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out []*AgentMember - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// ServiceRegister is used to register a new service with -// the local agent -func (a *Agent) ServiceRegister(service *AgentServiceRegistration) error { - r := a.c.newRequest("PUT", "/v1/agent/service/register") - r.obj = service - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// ServiceDeregister is used to deregister a service with -// the local agent -func (a *Agent) ServiceDeregister(serviceID string) error { - r := a.c.newRequest("PUT", "/v1/agent/service/deregister/"+serviceID) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// PassTTL is used to set a TTL check to the passing state. -// -// DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). -// The client interface will be removed in 0.8 or changed to use -// UpdateTTL()'s endpoint and the server endpoints will be removed in 0.9. -func (a *Agent) PassTTL(checkID, note string) error { - return a.updateTTL(checkID, note, "pass") -} - -// WarnTTL is used to set a TTL check to the warning state. -// -// DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). -// The client interface will be removed in 0.8 or changed to use -// UpdateTTL()'s endpoint and the server endpoints will be removed in 0.9. -func (a *Agent) WarnTTL(checkID, note string) error { - return a.updateTTL(checkID, note, "warn") -} - -// FailTTL is used to set a TTL check to the failing state. -// -// DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). -// The client interface will be removed in 0.8 or changed to use -// UpdateTTL()'s endpoint and the server endpoints will be removed in 0.9. -func (a *Agent) FailTTL(checkID, note string) error { - return a.updateTTL(checkID, note, "fail") -} - -// updateTTL is used to update the TTL of a check. This is the internal -// method that uses the old API that's present in Consul versions prior to -// 0.6.4. Since Consul didn't have an analogous "update" API before it seemed -// ok to break this (former) UpdateTTL in favor of the new UpdateTTL below, -// but keep the old Pass/Warn/Fail methods using the old API under the hood. -// -// DEPRECATION NOTICE: This interface is deprecated in favor of UpdateTTL(). -// The client interface will be removed in 0.8 and the server endpoints will -// be removed in 0.9. -func (a *Agent) updateTTL(checkID, note, status string) error { - switch status { - case "pass": - case "warn": - case "fail": - default: - return fmt.Errorf("Invalid status: %s", status) - } - endpoint := fmt.Sprintf("/v1/agent/check/%s/%s", status, checkID) - r := a.c.newRequest("PUT", endpoint) - r.params.Set("note", note) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// checkUpdate is the payload for a PUT for a check update. -type checkUpdate struct { - // Status is one of the api.Health* states: HealthPassing - // ("passing"), HealthWarning ("warning"), or HealthCritical - // ("critical"). - Status string - - // Output is the information to post to the UI for operators as the - // output of the process that decided to hit the TTL check. This is - // different from the note field that's associated with the check - // itself. - Output string -} - -// UpdateTTL is used to update the TTL of a check. This uses the newer API -// that was introduced in Consul 0.6.4 and later. We translate the old status -// strings for compatibility (though a newer version of Consul will still be -// required to use this API). -func (a *Agent) UpdateTTL(checkID, output, status string) error { - switch status { - case "pass", HealthPassing: - status = HealthPassing - case "warn", HealthWarning: - status = HealthWarning - case "fail", HealthCritical: - status = HealthCritical - default: - return fmt.Errorf("Invalid status: %s", status) - } - - endpoint := fmt.Sprintf("/v1/agent/check/update/%s", checkID) - r := a.c.newRequest("PUT", endpoint) - r.obj = &checkUpdate{ - Status: status, - Output: output, - } - - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// CheckRegister is used to register a new check with -// the local agent -func (a *Agent) CheckRegister(check *AgentCheckRegistration) error { - r := a.c.newRequest("PUT", "/v1/agent/check/register") - r.obj = check - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// CheckDeregister is used to deregister a check with -// the local agent -func (a *Agent) CheckDeregister(checkID string) error { - r := a.c.newRequest("PUT", "/v1/agent/check/deregister/"+checkID) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// Join is used to instruct the agent to attempt a join to -// another cluster member -func (a *Agent) Join(addr string, wan bool) error { - r := a.c.newRequest("PUT", "/v1/agent/join/"+addr) - if wan { - r.params.Set("wan", "1") - } - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// Leave is used to have the agent gracefully leave the cluster and shutdown -func (a *Agent) Leave() error { - r := a.c.newRequest("PUT", "/v1/agent/leave") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// ForceLeave is used to have the agent eject a failed node -func (a *Agent) ForceLeave(node string) error { - r := a.c.newRequest("PUT", "/v1/agent/force-leave/"+node) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// ConnectAuthorize is used to authorize an incoming connection -// to a natively integrated Connect service. -func (a *Agent) ConnectAuthorize(auth *AgentAuthorizeParams) (*AgentAuthorize, error) { - r := a.c.newRequest("POST", "/v1/agent/connect/authorize") - r.obj = auth - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out AgentAuthorize - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return &out, nil -} - -// ConnectCARoots returns the list of roots. -func (a *Agent) ConnectCARoots(q *QueryOptions) (*CARootList, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/agent/connect/ca/roots") - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out CARootList - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// ConnectCALeaf gets the leaf certificate for the given service ID. -func (a *Agent) ConnectCALeaf(serviceID string, q *QueryOptions) (*LeafCert, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/agent/connect/ca/leaf/"+serviceID) - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out LeafCert - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// ConnectProxyConfig gets the configuration for a local managed proxy instance. -// -// Note that this uses an unconventional blocking mechanism since it's -// agent-local state. That means there is no persistent raft index so we block -// based on object hash instead. -func (a *Agent) ConnectProxyConfig(proxyServiceID string, q *QueryOptions) (*ConnectProxyConfig, *QueryMeta, error) { - r := a.c.newRequest("GET", "/v1/agent/connect/proxy/"+proxyServiceID) - r.setQueryOptions(q) - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out ConnectProxyConfig - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// EnableServiceMaintenance toggles service maintenance mode on -// for the given service ID. -func (a *Agent) EnableServiceMaintenance(serviceID, reason string) error { - r := a.c.newRequest("PUT", "/v1/agent/service/maintenance/"+serviceID) - r.params.Set("enable", "true") - r.params.Set("reason", reason) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// DisableServiceMaintenance toggles service maintenance mode off -// for the given service ID. -func (a *Agent) DisableServiceMaintenance(serviceID string) error { - r := a.c.newRequest("PUT", "/v1/agent/service/maintenance/"+serviceID) - r.params.Set("enable", "false") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// EnableNodeMaintenance toggles node maintenance mode on for the -// agent we are connected to. -func (a *Agent) EnableNodeMaintenance(reason string) error { - r := a.c.newRequest("PUT", "/v1/agent/maintenance") - r.params.Set("enable", "true") - r.params.Set("reason", reason) - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// DisableNodeMaintenance toggles node maintenance mode off for the -// agent we are connected to. -func (a *Agent) DisableNodeMaintenance() error { - r := a.c.newRequest("PUT", "/v1/agent/maintenance") - r.params.Set("enable", "false") - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// Monitor returns a channel which will receive streaming logs from the agent -// Providing a non-nil stopCh can be used to close the connection and stop the -// log stream. An empty string will be sent down the given channel when there's -// nothing left to stream, after which the caller should close the stopCh. -func (a *Agent) Monitor(loglevel string, stopCh <-chan struct{}, q *QueryOptions) (chan string, error) { - r := a.c.newRequest("GET", "/v1/agent/monitor") - r.setQueryOptions(q) - if loglevel != "" { - r.params.Add("loglevel", loglevel) - } - _, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - - logCh := make(chan string, 64) - go func() { - defer resp.Body.Close() - - scanner := bufio.NewScanner(resp.Body) - for { - select { - case <-stopCh: - close(logCh) - return - default: - } - if scanner.Scan() { - // An empty string signals to the caller that - // the scan is done, so make sure we only emit - // that when the scanner says it's done, not if - // we happen to ingest an empty line. - if text := scanner.Text(); text != "" { - logCh <- text - } else { - logCh <- " " - } - } else { - logCh <- "" - } - } - }() - - return logCh, nil -} - -// UpdateACLToken updates the agent's "acl_token". See updateToken for more -// details. -func (a *Agent) UpdateACLToken(token string, q *WriteOptions) (*WriteMeta, error) { - return a.updateToken("acl_token", token, q) -} - -// UpdateACLAgentToken updates the agent's "acl_agent_token". See updateToken -// for more details. -func (a *Agent) UpdateACLAgentToken(token string, q *WriteOptions) (*WriteMeta, error) { - return a.updateToken("acl_agent_token", token, q) -} - -// UpdateACLAgentMasterToken updates the agent's "acl_agent_master_token". See -// updateToken for more details. -func (a *Agent) UpdateACLAgentMasterToken(token string, q *WriteOptions) (*WriteMeta, error) { - return a.updateToken("acl_agent_master_token", token, q) -} - -// UpdateACLReplicationToken updates the agent's "acl_replication_token". See -// updateToken for more details. -func (a *Agent) UpdateACLReplicationToken(token string, q *WriteOptions) (*WriteMeta, error) { - return a.updateToken("acl_replication_token", token, q) -} - -// updateToken can be used to update an agent's ACL token after the agent has -// started. The tokens are not persisted, so will need to be updated again if -// the agent is restarted. -func (a *Agent) updateToken(target, token string, q *WriteOptions) (*WriteMeta, error) { - r := a.c.newRequest("PUT", fmt.Sprintf("/v1/agent/token/%s", target)) - r.setWriteOptions(q) - r.obj = &AgentToken{Token: token} - rtt, resp, err := requireOK(a.c.doRequest(r)) - if err != nil { - return nil, err - } - resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - return wm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/api.go b/vendor/github.com/hashicorp/consul/api/api.go deleted file mode 100644 index 649238302..000000000 --- a/vendor/github.com/hashicorp/consul/api/api.go +++ /dev/null @@ -1,839 +0,0 @@ -package api - -import ( - "bytes" - "context" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-rootcerts" -) - -const ( - // HTTPAddrEnvName defines an environment variable name which sets - // the HTTP address if there is no -http-addr specified. - HTTPAddrEnvName = "CONSUL_HTTP_ADDR" - - // HTTPTokenEnvName defines an environment variable name which sets - // the HTTP token. - HTTPTokenEnvName = "CONSUL_HTTP_TOKEN" - - // HTTPAuthEnvName defines an environment variable name which sets - // the HTTP authentication header. - HTTPAuthEnvName = "CONSUL_HTTP_AUTH" - - // HTTPSSLEnvName defines an environment variable name which sets - // whether or not to use HTTPS. - HTTPSSLEnvName = "CONSUL_HTTP_SSL" - - // HTTPCAFile defines an environment variable name which sets the - // CA file to use for talking to Consul over TLS. - HTTPCAFile = "CONSUL_CACERT" - - // HTTPCAPath defines an environment variable name which sets the - // path to a directory of CA certs to use for talking to Consul over TLS. - HTTPCAPath = "CONSUL_CAPATH" - - // HTTPClientCert defines an environment variable name which sets the - // client cert file to use for talking to Consul over TLS. - HTTPClientCert = "CONSUL_CLIENT_CERT" - - // HTTPClientKey defines an environment variable name which sets the - // client key file to use for talking to Consul over TLS. - HTTPClientKey = "CONSUL_CLIENT_KEY" - - // HTTPTLSServerName defines an environment variable name which sets the - // server name to use as the SNI host when connecting via TLS - HTTPTLSServerName = "CONSUL_TLS_SERVER_NAME" - - // HTTPSSLVerifyEnvName defines an environment variable name which sets - // whether or not to disable certificate checking. - HTTPSSLVerifyEnvName = "CONSUL_HTTP_SSL_VERIFY" -) - -// QueryOptions are used to parameterize a query -type QueryOptions struct { - // Providing a datacenter overwrites the DC provided - // by the Config - Datacenter string - - // AllowStale allows any Consul server (non-leader) to service - // a read. This allows for lower latency and higher throughput - AllowStale bool - - // RequireConsistent forces the read to be fully consistent. - // This is more expensive but prevents ever performing a stale - // read. - RequireConsistent bool - - // WaitIndex is used to enable a blocking query. Waits - // until the timeout or the next index is reached - WaitIndex uint64 - - // WaitHash is used by some endpoints instead of WaitIndex to perform blocking - // on state based on a hash of the response rather than a monotonic index. - // This is required when the state being blocked on is not stored in Raft, for - // example agent-local proxy configuration. - WaitHash string - - // WaitTime is used to bound the duration of a wait. - // Defaults to that of the Config, but can be overridden. - WaitTime time.Duration - - // Token is used to provide a per-request ACL token - // which overrides the agent's default token. - Token string - - // Near is used to provide a node name that will sort the results - // in ascending order based on the estimated round trip time from - // that node. Setting this to "_agent" will use the agent's node - // for the sort. - Near string - - // NodeMeta is used to filter results by nodes with the given - // metadata key/value pairs. Currently, only one key/value pair can - // be provided for filtering. - NodeMeta map[string]string - - // RelayFactor is used in keyring operations to cause responses to be - // relayed back to the sender through N other random nodes. Must be - // a value from 0 to 5 (inclusive). - RelayFactor uint8 - - // Connect filters prepared query execution to only include Connect-capable - // services. This currently affects prepared query execution. - Connect bool - - // ctx is an optional context pass through to the underlying HTTP - // request layer. Use Context() and WithContext() to manage this. - ctx context.Context -} - -func (o *QueryOptions) Context() context.Context { - if o != nil && o.ctx != nil { - return o.ctx - } - return context.Background() -} - -func (o *QueryOptions) WithContext(ctx context.Context) *QueryOptions { - o2 := new(QueryOptions) - if o != nil { - *o2 = *o - } - o2.ctx = ctx - return o2 -} - -// WriteOptions are used to parameterize a write -type WriteOptions struct { - // Providing a datacenter overwrites the DC provided - // by the Config - Datacenter string - - // Token is used to provide a per-request ACL token - // which overrides the agent's default token. - Token string - - // RelayFactor is used in keyring operations to cause responses to be - // relayed back to the sender through N other random nodes. Must be - // a value from 0 to 5 (inclusive). - RelayFactor uint8 - - // ctx is an optional context pass through to the underlying HTTP - // request layer. Use Context() and WithContext() to manage this. - ctx context.Context -} - -func (o *WriteOptions) Context() context.Context { - if o != nil && o.ctx != nil { - return o.ctx - } - return context.Background() -} - -func (o *WriteOptions) WithContext(ctx context.Context) *WriteOptions { - o2 := new(WriteOptions) - if o != nil { - *o2 = *o - } - o2.ctx = ctx - return o2 -} - -// QueryMeta is used to return meta data about a query -type QueryMeta struct { - // LastIndex. This can be used as a WaitIndex to perform - // a blocking query - LastIndex uint64 - - // LastContentHash. This can be used as a WaitHash to perform a blocking query - // for endpoints that support hash-based blocking. Endpoints that do not - // support it will return an empty hash. - LastContentHash string - - // Time of last contact from the leader for the - // server servicing the request - LastContact time.Duration - - // Is there a known leader - KnownLeader bool - - // How long did the request take - RequestTime time.Duration - - // Is address translation enabled for HTTP responses on this agent - AddressTranslationEnabled bool -} - -// WriteMeta is used to return meta data about a write -type WriteMeta struct { - // How long did the request take - RequestTime time.Duration -} - -// HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication -type HttpBasicAuth struct { - // Username to use for HTTP Basic Authentication - Username string - - // Password to use for HTTP Basic Authentication - Password string -} - -// Config is used to configure the creation of a client -type Config struct { - // Address is the address of the Consul server - Address string - - // Scheme is the URI scheme for the Consul server - Scheme string - - // Datacenter to use. If not provided, the default agent datacenter is used. - Datacenter string - - // Transport is the Transport to use for the http client. - Transport *http.Transport - - // HttpClient is the client to use. Default will be - // used if not provided. - HttpClient *http.Client - - // HttpAuth is the auth info to use for http access. - HttpAuth *HttpBasicAuth - - // WaitTime limits how long a Watch will block. If not provided, - // the agent default values will be used. - WaitTime time.Duration - - // Token is used to provide a per-request ACL token - // which overrides the agent's default token. - Token string - - TLSConfig TLSConfig -} - -// TLSConfig is used to generate a TLSClientConfig that's useful for talking to -// Consul using TLS. -type TLSConfig struct { - // Address is the optional address of the Consul server. The port, if any - // will be removed from here and this will be set to the ServerName of the - // resulting config. - Address string - - // CAFile is the optional path to the CA certificate used for Consul - // communication, defaults to the system bundle if not specified. - CAFile string - - // CAPath is the optional path to a directory of CA certificates to use for - // Consul communication, defaults to the system bundle if not specified. - CAPath string - - // CertFile is the optional path to the certificate for Consul - // communication. If this is set then you need to also set KeyFile. - CertFile string - - // KeyFile is the optional path to the private key for Consul communication. - // If this is set then you need to also set CertFile. - KeyFile string - - // InsecureSkipVerify if set to true will disable TLS host verification. - InsecureSkipVerify bool -} - -// DefaultConfig returns a default configuration for the client. By default this -// will pool and reuse idle connections to Consul. If you have a long-lived -// client object, this is the desired behavior and should make the most efficient -// use of the connections to Consul. If you don't reuse a client object , which -// is not recommended, then you may notice idle connections building up over -// time. To avoid this, use the DefaultNonPooledConfig() instead. -func DefaultConfig() *Config { - return defaultConfig(cleanhttp.DefaultPooledTransport) -} - -// DefaultNonPooledConfig returns a default configuration for the client which -// does not pool connections. This isn't a recommended configuration because it -// will reconnect to Consul on every request, but this is useful to avoid the -// accumulation of idle connections if you make many client objects during the -// lifetime of your application. -func DefaultNonPooledConfig() *Config { - return defaultConfig(cleanhttp.DefaultTransport) -} - -// defaultConfig returns the default configuration for the client, using the -// given function to make the transport. -func defaultConfig(transportFn func() *http.Transport) *Config { - config := &Config{ - Address: "127.0.0.1:8500", - Scheme: "http", - Transport: transportFn(), - } - - if addr := os.Getenv(HTTPAddrEnvName); addr != "" { - config.Address = addr - } - - if token := os.Getenv(HTTPTokenEnvName); token != "" { - config.Token = token - } - - if auth := os.Getenv(HTTPAuthEnvName); auth != "" { - var username, password string - if strings.Contains(auth, ":") { - split := strings.SplitN(auth, ":", 2) - username = split[0] - password = split[1] - } else { - username = auth - } - - config.HttpAuth = &HttpBasicAuth{ - Username: username, - Password: password, - } - } - - if ssl := os.Getenv(HTTPSSLEnvName); ssl != "" { - enabled, err := strconv.ParseBool(ssl) - if err != nil { - log.Printf("[WARN] client: could not parse %s: %s", HTTPSSLEnvName, err) - } - - if enabled { - config.Scheme = "https" - } - } - - if v := os.Getenv(HTTPTLSServerName); v != "" { - config.TLSConfig.Address = v - } - if v := os.Getenv(HTTPCAFile); v != "" { - config.TLSConfig.CAFile = v - } - if v := os.Getenv(HTTPCAPath); v != "" { - config.TLSConfig.CAPath = v - } - if v := os.Getenv(HTTPClientCert); v != "" { - config.TLSConfig.CertFile = v - } - if v := os.Getenv(HTTPClientKey); v != "" { - config.TLSConfig.KeyFile = v - } - if v := os.Getenv(HTTPSSLVerifyEnvName); v != "" { - doVerify, err := strconv.ParseBool(v) - if err != nil { - log.Printf("[WARN] client: could not parse %s: %s", HTTPSSLVerifyEnvName, err) - } - if !doVerify { - config.TLSConfig.InsecureSkipVerify = true - } - } - - return config -} - -// TLSConfig is used to generate a TLSClientConfig that's useful for talking to -// Consul using TLS. -func SetupTLSConfig(tlsConfig *TLSConfig) (*tls.Config, error) { - tlsClientConfig := &tls.Config{ - InsecureSkipVerify: tlsConfig.InsecureSkipVerify, - } - - if tlsConfig.Address != "" { - server := tlsConfig.Address - hasPort := strings.LastIndex(server, ":") > strings.LastIndex(server, "]") - if hasPort { - var err error - server, _, err = net.SplitHostPort(server) - if err != nil { - return nil, err - } - } - tlsClientConfig.ServerName = server - } - - if tlsConfig.CertFile != "" && tlsConfig.KeyFile != "" { - tlsCert, err := tls.LoadX509KeyPair(tlsConfig.CertFile, tlsConfig.KeyFile) - if err != nil { - return nil, err - } - tlsClientConfig.Certificates = []tls.Certificate{tlsCert} - } - - if tlsConfig.CAFile != "" || tlsConfig.CAPath != "" { - rootConfig := &rootcerts.Config{ - CAFile: tlsConfig.CAFile, - CAPath: tlsConfig.CAPath, - } - if err := rootcerts.ConfigureTLS(tlsClientConfig, rootConfig); err != nil { - return nil, err - } - } - - return tlsClientConfig, nil -} - -func (c *Config) GenerateEnv() []string { - env := make([]string, 0, 10) - - env = append(env, - fmt.Sprintf("%s=%s", HTTPAddrEnvName, c.Address), - fmt.Sprintf("%s=%s", HTTPTokenEnvName, c.Token), - fmt.Sprintf("%s=%t", HTTPSSLEnvName, c.Scheme == "https"), - fmt.Sprintf("%s=%s", HTTPCAFile, c.TLSConfig.CAFile), - fmt.Sprintf("%s=%s", HTTPCAPath, c.TLSConfig.CAPath), - fmt.Sprintf("%s=%s", HTTPClientCert, c.TLSConfig.CertFile), - fmt.Sprintf("%s=%s", HTTPClientKey, c.TLSConfig.KeyFile), - fmt.Sprintf("%s=%s", HTTPTLSServerName, c.TLSConfig.Address), - fmt.Sprintf("%s=%t", HTTPSSLVerifyEnvName, !c.TLSConfig.InsecureSkipVerify)) - - if c.HttpAuth != nil { - env = append(env, fmt.Sprintf("%s=%s:%s", HTTPAuthEnvName, c.HttpAuth.Username, c.HttpAuth.Password)) - } else { - env = append(env, fmt.Sprintf("%s=", HTTPAuthEnvName)) - } - - return env -} - -// Client provides a client to the Consul API -type Client struct { - config Config -} - -// NewClient returns a new client -func NewClient(config *Config) (*Client, error) { - // bootstrap the config - defConfig := DefaultConfig() - - if len(config.Address) == 0 { - config.Address = defConfig.Address - } - - if len(config.Scheme) == 0 { - config.Scheme = defConfig.Scheme - } - - if config.Transport == nil { - config.Transport = defConfig.Transport - } - - if config.TLSConfig.Address == "" { - config.TLSConfig.Address = defConfig.TLSConfig.Address - } - - if config.TLSConfig.CAFile == "" { - config.TLSConfig.CAFile = defConfig.TLSConfig.CAFile - } - - if config.TLSConfig.CAPath == "" { - config.TLSConfig.CAPath = defConfig.TLSConfig.CAPath - } - - if config.TLSConfig.CertFile == "" { - config.TLSConfig.CertFile = defConfig.TLSConfig.CertFile - } - - if config.TLSConfig.KeyFile == "" { - config.TLSConfig.KeyFile = defConfig.TLSConfig.KeyFile - } - - if !config.TLSConfig.InsecureSkipVerify { - config.TLSConfig.InsecureSkipVerify = defConfig.TLSConfig.InsecureSkipVerify - } - - if config.HttpClient == nil { - var err error - config.HttpClient, err = NewHttpClient(config.Transport, config.TLSConfig) - if err != nil { - return nil, err - } - } - - parts := strings.SplitN(config.Address, "://", 2) - if len(parts) == 2 { - switch parts[0] { - case "http": - config.Scheme = "http" - case "https": - config.Scheme = "https" - case "unix": - trans := cleanhttp.DefaultTransport() - trans.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) { - return net.Dial("unix", parts[1]) - } - config.HttpClient = &http.Client{ - Transport: trans, - } - default: - return nil, fmt.Errorf("Unknown protocol scheme: %s", parts[0]) - } - config.Address = parts[1] - } - - if config.Token == "" { - config.Token = defConfig.Token - } - - return &Client{config: *config}, nil -} - -// NewHttpClient returns an http client configured with the given Transport and TLS -// config. -func NewHttpClient(transport *http.Transport, tlsConf TLSConfig) (*http.Client, error) { - client := &http.Client{ - Transport: transport, - } - - // TODO (slackpad) - Once we get some run time on the HTTP/2 support we - // should turn it on by default if TLS is enabled. We would basically - // just need to call http2.ConfigureTransport(transport) here. We also - // don't want to introduce another external dependency on - // golang.org/x/net/http2 at this time. For a complete recipe for how - // to enable HTTP/2 support on a transport suitable for the API client - // library see agent/http_test.go:TestHTTPServer_H2. - - if transport.TLSClientConfig == nil { - tlsClientConfig, err := SetupTLSConfig(&tlsConf) - - if err != nil { - return nil, err - } - - transport.TLSClientConfig = tlsClientConfig - } - - return client, nil -} - -// request is used to help build up a request -type request struct { - config *Config - method string - url *url.URL - params url.Values - body io.Reader - header http.Header - obj interface{} - ctx context.Context -} - -// setQueryOptions is used to annotate the request with -// additional query options -func (r *request) setQueryOptions(q *QueryOptions) { - if q == nil { - return - } - if q.Datacenter != "" { - r.params.Set("dc", q.Datacenter) - } - if q.AllowStale { - r.params.Set("stale", "") - } - if q.RequireConsistent { - r.params.Set("consistent", "") - } - if q.WaitIndex != 0 { - r.params.Set("index", strconv.FormatUint(q.WaitIndex, 10)) - } - if q.WaitTime != 0 { - r.params.Set("wait", durToMsec(q.WaitTime)) - } - if q.WaitHash != "" { - r.params.Set("hash", q.WaitHash) - } - if q.Token != "" { - r.header.Set("X-Consul-Token", q.Token) - } - if q.Near != "" { - r.params.Set("near", q.Near) - } - if len(q.NodeMeta) > 0 { - for key, value := range q.NodeMeta { - r.params.Add("node-meta", key+":"+value) - } - } - if q.RelayFactor != 0 { - r.params.Set("relay-factor", strconv.Itoa(int(q.RelayFactor))) - } - if q.Connect { - r.params.Set("connect", "true") - } - r.ctx = q.ctx -} - -// durToMsec converts a duration to a millisecond specified string. If the -// user selected a positive value that rounds to 0 ms, then we will use 1 ms -// so they get a short delay, otherwise Consul will translate the 0 ms into -// a huge default delay. -func durToMsec(dur time.Duration) string { - ms := dur / time.Millisecond - if dur > 0 && ms == 0 { - ms = 1 - } - return fmt.Sprintf("%dms", ms) -} - -// serverError is a string we look for to detect 500 errors. -const serverError = "Unexpected response code: 500" - -// IsRetryableError returns true for 500 errors from the Consul servers, and -// network connection errors. These are usually retryable at a later time. -// This applies to reads but NOT to writes. This may return true for errors -// on writes that may have still gone through, so do not use this to retry -// any write operations. -func IsRetryableError(err error) bool { - if err == nil { - return false - } - - if _, ok := err.(net.Error); ok { - return true - } - - // TODO (slackpad) - Make a real error type here instead of using - // a string check. - return strings.Contains(err.Error(), serverError) -} - -// setWriteOptions is used to annotate the request with -// additional write options -func (r *request) setWriteOptions(q *WriteOptions) { - if q == nil { - return - } - if q.Datacenter != "" { - r.params.Set("dc", q.Datacenter) - } - if q.Token != "" { - r.header.Set("X-Consul-Token", q.Token) - } - if q.RelayFactor != 0 { - r.params.Set("relay-factor", strconv.Itoa(int(q.RelayFactor))) - } - r.ctx = q.ctx -} - -// toHTTP converts the request to an HTTP request -func (r *request) toHTTP() (*http.Request, error) { - // Encode the query parameters - r.url.RawQuery = r.params.Encode() - - // Check if we should encode the body - if r.body == nil && r.obj != nil { - b, err := encodeBody(r.obj) - if err != nil { - return nil, err - } - r.body = b - } - - // Create the HTTP request - req, err := http.NewRequest(r.method, r.url.RequestURI(), r.body) - if err != nil { - return nil, err - } - - req.URL.Host = r.url.Host - req.URL.Scheme = r.url.Scheme - req.Host = r.url.Host - req.Header = r.header - - // Setup auth - if r.config.HttpAuth != nil { - req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password) - } - if r.ctx != nil { - return req.WithContext(r.ctx), nil - } - - return req, nil -} - -// newRequest is used to create a new request -func (c *Client) newRequest(method, path string) *request { - r := &request{ - config: &c.config, - method: method, - url: &url.URL{ - Scheme: c.config.Scheme, - Host: c.config.Address, - Path: path, - }, - params: make(map[string][]string), - header: make(http.Header), - } - if c.config.Datacenter != "" { - r.params.Set("dc", c.config.Datacenter) - } - if c.config.WaitTime != 0 { - r.params.Set("wait", durToMsec(r.config.WaitTime)) - } - if c.config.Token != "" { - r.header.Set("X-Consul-Token", r.config.Token) - } - return r -} - -// doRequest runs a request with our client -func (c *Client) doRequest(r *request) (time.Duration, *http.Response, error) { - req, err := r.toHTTP() - if err != nil { - return 0, nil, err - } - start := time.Now() - resp, err := c.config.HttpClient.Do(req) - diff := time.Since(start) - return diff, resp, err -} - -// Query is used to do a GET request against an endpoint -// and deserialize the response into an interface using -// standard Consul conventions. -func (c *Client) query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) { - r := c.newRequest("GET", endpoint) - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - if err := decodeBody(resp, out); err != nil { - return nil, err - } - return qm, nil -} - -// write is used to do a PUT request against an endpoint -// and serialize/deserialized using the standard Consul conventions. -func (c *Client) write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) { - r := c.newRequest("PUT", endpoint) - r.setWriteOptions(q) - r.obj = in - rtt, resp, err := requireOK(c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - if out != nil { - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - } else if _, err := ioutil.ReadAll(resp.Body); err != nil { - return nil, err - } - return wm, nil -} - -// parseQueryMeta is used to help parse query meta-data -func parseQueryMeta(resp *http.Response, q *QueryMeta) error { - header := resp.Header - - // Parse the X-Consul-Index (if it's set - hash based blocking queries don't - // set this) - if indexStr := header.Get("X-Consul-Index"); indexStr != "" { - index, err := strconv.ParseUint(indexStr, 10, 64) - if err != nil { - return fmt.Errorf("Failed to parse X-Consul-Index: %v", err) - } - q.LastIndex = index - } - q.LastContentHash = header.Get("X-Consul-ContentHash") - - // Parse the X-Consul-LastContact - last, err := strconv.ParseUint(header.Get("X-Consul-LastContact"), 10, 64) - if err != nil { - return fmt.Errorf("Failed to parse X-Consul-LastContact: %v", err) - } - q.LastContact = time.Duration(last) * time.Millisecond - - // Parse the X-Consul-KnownLeader - switch header.Get("X-Consul-KnownLeader") { - case "true": - q.KnownLeader = true - default: - q.KnownLeader = false - } - - // Parse X-Consul-Translate-Addresses - switch header.Get("X-Consul-Translate-Addresses") { - case "true": - q.AddressTranslationEnabled = true - default: - q.AddressTranslationEnabled = false - } - - return nil -} - -// decodeBody is used to JSON decode a body -func decodeBody(resp *http.Response, out interface{}) error { - dec := json.NewDecoder(resp.Body) - return dec.Decode(out) -} - -// encodeBody is used to encode a request body -func encodeBody(obj interface{}) (io.Reader, error) { - buf := bytes.NewBuffer(nil) - enc := json.NewEncoder(buf) - if err := enc.Encode(obj); err != nil { - return nil, err - } - return buf, nil -} - -// requireOK is used to wrap doRequest and check for a 200 -func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { - if e != nil { - if resp != nil { - resp.Body.Close() - } - return d, nil, e - } - if resp.StatusCode != 200 { - var buf bytes.Buffer - io.Copy(&buf, resp.Body) - resp.Body.Close() - return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes()) - } - return d, resp, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/catalog.go b/vendor/github.com/hashicorp/consul/api/catalog.go deleted file mode 100644 index 6cb745c36..000000000 --- a/vendor/github.com/hashicorp/consul/api/catalog.go +++ /dev/null @@ -1,219 +0,0 @@ -package api - -type Weights struct { - Passing int - Warning int -} - -type Node struct { - ID string - Node string - Address string - Datacenter string - TaggedAddresses map[string]string - Meta map[string]string - CreateIndex uint64 - ModifyIndex uint64 -} - -type CatalogService struct { - ID string - Node string - Address string - Datacenter string - TaggedAddresses map[string]string - NodeMeta map[string]string - ServiceID string - ServiceName string - ServiceAddress string - ServiceTags []string - ServiceMeta map[string]string - ServicePort int - ServiceWeights Weights - ServiceEnableTagOverride bool - CreateIndex uint64 - ModifyIndex uint64 -} - -type CatalogNode struct { - Node *Node - Services map[string]*AgentService -} - -type CatalogRegistration struct { - ID string - Node string - Address string - TaggedAddresses map[string]string - NodeMeta map[string]string - Datacenter string - Service *AgentService - Check *AgentCheck - SkipNodeUpdate bool -} - -type CatalogDeregistration struct { - Node string - Address string // Obsolete. - Datacenter string - ServiceID string - CheckID string -} - -// Catalog can be used to query the Catalog endpoints -type Catalog struct { - c *Client -} - -// Catalog returns a handle to the catalog endpoints -func (c *Client) Catalog() *Catalog { - return &Catalog{c} -} - -func (c *Catalog) Register(reg *CatalogRegistration, q *WriteOptions) (*WriteMeta, error) { - r := c.c.newRequest("PUT", "/v1/catalog/register") - r.setWriteOptions(q) - r.obj = reg - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - return wm, nil -} - -func (c *Catalog) Deregister(dereg *CatalogDeregistration, q *WriteOptions) (*WriteMeta, error) { - r := c.c.newRequest("PUT", "/v1/catalog/deregister") - r.setWriteOptions(q) - r.obj = dereg - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - return wm, nil -} - -// Datacenters is used to query for all the known datacenters -func (c *Catalog) Datacenters() ([]string, error) { - r := c.c.newRequest("GET", "/v1/catalog/datacenters") - _, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out []string - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// Nodes is used to query all the known nodes -func (c *Catalog) Nodes(q *QueryOptions) ([]*Node, *QueryMeta, error) { - r := c.c.newRequest("GET", "/v1/catalog/nodes") - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*Node - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Services is used to query for all known services -func (c *Catalog) Services(q *QueryOptions) (map[string][]string, *QueryMeta, error) { - r := c.c.newRequest("GET", "/v1/catalog/services") - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out map[string][]string - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Service is used to query catalog entries for a given service -func (c *Catalog) Service(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error) { - return c.service(service, tag, q, false) -} - -// Connect is used to query catalog entries for a given Connect-enabled service -func (c *Catalog) Connect(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error) { - return c.service(service, tag, q, true) -} - -func (c *Catalog) service(service, tag string, q *QueryOptions, connect bool) ([]*CatalogService, *QueryMeta, error) { - path := "/v1/catalog/service/" + service - if connect { - path = "/v1/catalog/connect/" + service - } - r := c.c.newRequest("GET", path) - r.setQueryOptions(q) - if tag != "" { - r.params.Set("tag", tag) - } - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*CatalogService - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Node is used to query for service information about a single node -func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error) { - r := c.c.newRequest("GET", "/v1/catalog/node/"+node) - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out *CatalogNode - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/connect.go b/vendor/github.com/hashicorp/consul/api/connect.go deleted file mode 100644 index a40d1e232..000000000 --- a/vendor/github.com/hashicorp/consul/api/connect.go +++ /dev/null @@ -1,12 +0,0 @@ -package api - -// Connect can be used to work with endpoints related to Connect, the -// feature for securely connecting services within Consul. -type Connect struct { - c *Client -} - -// Connect returns a handle to the connect-related endpoints -func (c *Client) Connect() *Connect { - return &Connect{c} -} diff --git a/vendor/github.com/hashicorp/consul/api/connect_ca.go b/vendor/github.com/hashicorp/consul/api/connect_ca.go deleted file mode 100644 index a863d21d4..000000000 --- a/vendor/github.com/hashicorp/consul/api/connect_ca.go +++ /dev/null @@ -1,172 +0,0 @@ -package api - -import ( - "fmt" - "time" - - "github.com/mitchellh/mapstructure" -) - -// CAConfig is the structure for the Connect CA configuration. -type CAConfig struct { - // Provider is the CA provider implementation to use. - Provider string - - // Configuration is arbitrary configuration for the provider. This - // should only contain primitive values and containers (such as lists - // and maps). - Config map[string]interface{} - - CreateIndex uint64 - ModifyIndex uint64 -} - -// CommonCAProviderConfig is the common options available to all CA providers. -type CommonCAProviderConfig struct { - LeafCertTTL time.Duration -} - -// ConsulCAProviderConfig is the config for the built-in Consul CA provider. -type ConsulCAProviderConfig struct { - CommonCAProviderConfig `mapstructure:",squash"` - - PrivateKey string - RootCert string - RotationPeriod time.Duration -} - -// ParseConsulCAConfig takes a raw config map and returns a parsed -// ConsulCAProviderConfig. -func ParseConsulCAConfig(raw map[string]interface{}) (*ConsulCAProviderConfig, error) { - var config ConsulCAProviderConfig - decodeConf := &mapstructure.DecoderConfig{ - DecodeHook: mapstructure.StringToTimeDurationHookFunc(), - ErrorUnused: true, - Result: &config, - WeaklyTypedInput: true, - } - - decoder, err := mapstructure.NewDecoder(decodeConf) - if err != nil { - return nil, err - } - - if err := decoder.Decode(raw); err != nil { - return nil, fmt.Errorf("error decoding config: %s", err) - } - - return &config, nil -} - -// CARootList is the structure for the results of listing roots. -type CARootList struct { - ActiveRootID string - TrustDomain string - Roots []*CARoot -} - -// CARoot represents a root CA certificate that is trusted. -type CARoot struct { - // ID is a globally unique ID (UUID) representing this CA root. - ID string - - // Name is a human-friendly name for this CA root. This value is - // opaque to Consul and is not used for anything internally. - Name string - - // RootCertPEM is the PEM-encoded public certificate. - RootCertPEM string `json:"RootCert"` - - // Active is true if this is the current active CA. This must only - // be true for exactly one CA. For any method that modifies roots in the - // state store, tests should be written to verify that multiple roots - // cannot be active. - Active bool - - CreateIndex uint64 - ModifyIndex uint64 -} - -// LeafCert is a certificate that has been issued by a Connect CA. -type LeafCert struct { - // SerialNumber is the unique serial number for this certificate. - // This is encoded in standard hex separated by :. - SerialNumber string - - // CertPEM and PrivateKeyPEM are the PEM-encoded certificate and private - // key for that cert, respectively. This should not be stored in the - // state store, but is present in the sign API response. - CertPEM string `json:",omitempty"` - PrivateKeyPEM string `json:",omitempty"` - - // Service is the name of the service for which the cert was issued. - // ServiceURI is the cert URI value. - Service string - ServiceURI string - - // ValidAfter and ValidBefore are the validity periods for the - // certificate. - ValidAfter time.Time - ValidBefore time.Time - - CreateIndex uint64 - ModifyIndex uint64 -} - -// CARoots queries the list of available roots. -func (h *Connect) CARoots(q *QueryOptions) (*CARootList, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/ca/roots") - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out CARootList - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// CAGetConfig returns the current CA configuration. -func (h *Connect) CAGetConfig(q *QueryOptions) (*CAConfig, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/ca/configuration") - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out CAConfig - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// CASetConfig sets the current CA configuration. -func (h *Connect) CASetConfig(conf *CAConfig, q *WriteOptions) (*WriteMeta, error) { - r := h.c.newRequest("PUT", "/v1/connect/ca/configuration") - r.setWriteOptions(q) - r.obj = conf - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - return wm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/connect_intention.go b/vendor/github.com/hashicorp/consul/api/connect_intention.go deleted file mode 100644 index a996c03e5..000000000 --- a/vendor/github.com/hashicorp/consul/api/connect_intention.go +++ /dev/null @@ -1,302 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "time" -) - -// Intention defines an intention for the Connect Service Graph. This defines -// the allowed or denied behavior of a connection between two services using -// Connect. -type Intention struct { - // ID is the UUID-based ID for the intention, always generated by Consul. - ID string - - // Description is a human-friendly description of this intention. - // It is opaque to Consul and is only stored and transferred in API - // requests. - Description string - - // SourceNS, SourceName are the namespace and name, respectively, of - // the source service. Either of these may be the wildcard "*", but only - // the full value can be a wildcard. Partial wildcards are not allowed. - // The source may also be a non-Consul service, as specified by SourceType. - // - // DestinationNS, DestinationName is the same, but for the destination - // service. The same rules apply. The destination is always a Consul - // service. - SourceNS, SourceName string - DestinationNS, DestinationName string - - // SourceType is the type of the value for the source. - SourceType IntentionSourceType - - // Action is whether this is a whitelist or blacklist intention. - Action IntentionAction - - // DefaultAddr, DefaultPort of the local listening proxy (if any) to - // make this connection. - DefaultAddr string - DefaultPort int - - // Meta is arbitrary metadata associated with the intention. This is - // opaque to Consul but is served in API responses. - Meta map[string]string - - // Precedence is the order that the intention will be applied, with - // larger numbers being applied first. This is a read-only field, on - // any intention update it is updated. - Precedence int - - // CreatedAt and UpdatedAt keep track of when this record was created - // or modified. - CreatedAt, UpdatedAt time.Time - - CreateIndex uint64 - ModifyIndex uint64 -} - -// String returns human-friendly output describing ths intention. -func (i *Intention) String() string { - return fmt.Sprintf("%s => %s (%s)", - i.SourceString(), - i.DestinationString(), - i.Action) -} - -// SourceString returns the namespace/name format for the source, or -// just "name" if the namespace is the default namespace. -func (i *Intention) SourceString() string { - return i.partString(i.SourceNS, i.SourceName) -} - -// DestinationString returns the namespace/name format for the source, or -// just "name" if the namespace is the default namespace. -func (i *Intention) DestinationString() string { - return i.partString(i.DestinationNS, i.DestinationName) -} - -func (i *Intention) partString(ns, n string) string { - // For now we omit the default namespace from the output. In the future - // we might want to look at this and show this in a multi-namespace world. - if ns != "" && ns != IntentionDefaultNamespace { - n = ns + "/" + n - } - - return n -} - -// IntentionDefaultNamespace is the default namespace value. -const IntentionDefaultNamespace = "default" - -// IntentionAction is the action that the intention represents. This -// can be "allow" or "deny" to whitelist or blacklist intentions. -type IntentionAction string - -const ( - IntentionActionAllow IntentionAction = "allow" - IntentionActionDeny IntentionAction = "deny" -) - -// IntentionSourceType is the type of the source within an intention. -type IntentionSourceType string - -const ( - // IntentionSourceConsul is a service within the Consul catalog. - IntentionSourceConsul IntentionSourceType = "consul" -) - -// IntentionMatch are the arguments for the intention match API. -type IntentionMatch struct { - By IntentionMatchType - Names []string -} - -// IntentionMatchType is the target for a match request. For example, -// matching by source will look for all intentions that match the given -// source value. -type IntentionMatchType string - -const ( - IntentionMatchSource IntentionMatchType = "source" - IntentionMatchDestination IntentionMatchType = "destination" -) - -// IntentionCheck are the arguments for the intention check API. For -// more documentation see the IntentionCheck function. -type IntentionCheck struct { - // Source and Destination are the source and destination values to - // check. The destination is always a Consul service, but the source - // may be other values as defined by the SourceType. - Source, Destination string - - // SourceType is the type of the value for the source. - SourceType IntentionSourceType -} - -// Intentions returns the list of intentions. -func (h *Connect) Intentions(q *QueryOptions) ([]*Intention, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/intentions") - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*Intention - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// IntentionGet retrieves a single intention. -func (h *Connect) IntentionGet(id string, q *QueryOptions) (*Intention, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/intentions/"+id) - r.setQueryOptions(q) - rtt, resp, err := h.c.doRequest(r) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - if resp.StatusCode == 404 { - return nil, qm, nil - } else if resp.StatusCode != 200 { - var buf bytes.Buffer - io.Copy(&buf, resp.Body) - return nil, nil, fmt.Errorf( - "Unexpected response %d: %s", resp.StatusCode, buf.String()) - } - - var out Intention - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return &out, qm, nil -} - -// IntentionDelete deletes a single intention. -func (h *Connect) IntentionDelete(id string, q *WriteOptions) (*WriteMeta, error) { - r := h.c.newRequest("DELETE", "/v1/connect/intentions/"+id) - r.setWriteOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - qm := &WriteMeta{} - qm.RequestTime = rtt - - return qm, nil -} - -// IntentionMatch returns the list of intentions that match a given source -// or destination. The returned intentions are ordered by precedence where -// result[0] is the highest precedence (if that matches, then that rule overrides -// all other rules). -// -// Matching can be done for multiple names at the same time. The resulting -// map is keyed by the given names. Casing is preserved. -func (h *Connect) IntentionMatch(args *IntentionMatch, q *QueryOptions) (map[string][]*Intention, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/intentions/match") - r.setQueryOptions(q) - r.params.Set("by", string(args.By)) - for _, name := range args.Names { - r.params.Add("name", name) - } - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out map[string][]*Intention - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// IntentionCheck returns whether a given source/destination would be allowed -// or not given the current set of intentions and the configuration of Consul. -func (h *Connect) IntentionCheck(args *IntentionCheck, q *QueryOptions) (bool, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/connect/intentions/check") - r.setQueryOptions(q) - r.params.Set("source", args.Source) - r.params.Set("destination", args.Destination) - if args.SourceType != "" { - r.params.Set("source-type", string(args.SourceType)) - } - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return false, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out struct{ Allowed bool } - if err := decodeBody(resp, &out); err != nil { - return false, nil, err - } - return out.Allowed, qm, nil -} - -// IntentionCreate will create a new intention. The ID in the given -// structure must be empty and a generate ID will be returned on -// success. -func (c *Connect) IntentionCreate(ixn *Intention, q *WriteOptions) (string, *WriteMeta, error) { - r := c.c.newRequest("POST", "/v1/connect/intentions") - r.setWriteOptions(q) - r.obj = ixn - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// IntentionUpdate will update an existing intention. The ID in the given -// structure must be non-empty. -func (c *Connect) IntentionUpdate(ixn *Intention, q *WriteOptions) (*WriteMeta, error) { - r := c.c.newRequest("PUT", "/v1/connect/intentions/"+ixn.ID) - r.setWriteOptions(q) - r.obj = ixn - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - return wm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/coordinate.go b/vendor/github.com/hashicorp/consul/api/coordinate.go deleted file mode 100644 index 53318f11d..000000000 --- a/vendor/github.com/hashicorp/consul/api/coordinate.go +++ /dev/null @@ -1,106 +0,0 @@ -package api - -import ( - "github.com/hashicorp/serf/coordinate" -) - -// CoordinateEntry represents a node and its associated network coordinate. -type CoordinateEntry struct { - Node string - Segment string - Coord *coordinate.Coordinate -} - -// CoordinateDatacenterMap has the coordinates for servers in a given datacenter -// and area. Network coordinates are only compatible within the same area. -type CoordinateDatacenterMap struct { - Datacenter string - AreaID string - Coordinates []CoordinateEntry -} - -// Coordinate can be used to query the coordinate endpoints -type Coordinate struct { - c *Client -} - -// Coordinate returns a handle to the coordinate endpoints -func (c *Client) Coordinate() *Coordinate { - return &Coordinate{c} -} - -// Datacenters is used to return the coordinates of all the servers in the WAN -// pool. -func (c *Coordinate) Datacenters() ([]*CoordinateDatacenterMap, error) { - r := c.c.newRequest("GET", "/v1/coordinate/datacenters") - _, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out []*CoordinateDatacenterMap - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// Nodes is used to return the coordinates of all the nodes in the LAN pool. -func (c *Coordinate) Nodes(q *QueryOptions) ([]*CoordinateEntry, *QueryMeta, error) { - r := c.c.newRequest("GET", "/v1/coordinate/nodes") - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*CoordinateEntry - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Update inserts or updates the LAN coordinate of a node. -func (c *Coordinate) Update(coord *CoordinateEntry, q *WriteOptions) (*WriteMeta, error) { - r := c.c.newRequest("PUT", "/v1/coordinate/update") - r.setWriteOptions(q) - r.obj = coord - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - return wm, nil -} - -// Node is used to return the coordinates of a single in the LAN pool. -func (c *Coordinate) Node(node string, q *QueryOptions) ([]*CoordinateEntry, *QueryMeta, error) { - r := c.c.newRequest("GET", "/v1/coordinate/node/"+node) - r.setQueryOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*CoordinateEntry - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/event.go b/vendor/github.com/hashicorp/consul/api/event.go deleted file mode 100644 index 85b5b069b..000000000 --- a/vendor/github.com/hashicorp/consul/api/event.go +++ /dev/null @@ -1,104 +0,0 @@ -package api - -import ( - "bytes" - "strconv" -) - -// Event can be used to query the Event endpoints -type Event struct { - c *Client -} - -// UserEvent represents an event that was fired by the user -type UserEvent struct { - ID string - Name string - Payload []byte - NodeFilter string - ServiceFilter string - TagFilter string - Version int - LTime uint64 -} - -// Event returns a handle to the event endpoints -func (c *Client) Event() *Event { - return &Event{c} -} - -// Fire is used to fire a new user event. Only the Name, Payload and Filters -// are respected. This returns the ID or an associated error. Cross DC requests -// are supported. -func (e *Event) Fire(params *UserEvent, q *WriteOptions) (string, *WriteMeta, error) { - r := e.c.newRequest("PUT", "/v1/event/fire/"+params.Name) - r.setWriteOptions(q) - if params.NodeFilter != "" { - r.params.Set("node", params.NodeFilter) - } - if params.ServiceFilter != "" { - r.params.Set("service", params.ServiceFilter) - } - if params.TagFilter != "" { - r.params.Set("tag", params.TagFilter) - } - if params.Payload != nil { - r.body = bytes.NewReader(params.Payload) - } - - rtt, resp, err := requireOK(e.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - var out UserEvent - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// List is used to get the most recent events an agent has received. -// This list can be optionally filtered by the name. This endpoint supports -// quasi-blocking queries. The index is not monotonic, nor does it provide provide -// LastContact or KnownLeader. -func (e *Event) List(name string, q *QueryOptions) ([]*UserEvent, *QueryMeta, error) { - r := e.c.newRequest("GET", "/v1/event/list") - r.setQueryOptions(q) - if name != "" { - r.params.Set("name", name) - } - rtt, resp, err := requireOK(e.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var entries []*UserEvent - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - return entries, qm, nil -} - -// IDToIndex is a bit of a hack. This simulates the index generation to -// convert an event ID into a WaitIndex. -func (e *Event) IDToIndex(uuid string) uint64 { - lower := uuid[0:8] + uuid[9:13] + uuid[14:18] - upper := uuid[19:23] + uuid[24:36] - lowVal, err := strconv.ParseUint(lower, 16, 64) - if err != nil { - panic("Failed to convert " + lower) - } - highVal, err := strconv.ParseUint(upper, 16, 64) - if err != nil { - panic("Failed to convert " + upper) - } - return lowVal ^ highVal -} diff --git a/vendor/github.com/hashicorp/consul/api/health.go b/vendor/github.com/hashicorp/consul/api/health.go deleted file mode 100644 index 1835da559..000000000 --- a/vendor/github.com/hashicorp/consul/api/health.go +++ /dev/null @@ -1,232 +0,0 @@ -package api - -import ( - "fmt" - "strings" -) - -const ( - // HealthAny is special, and is used as a wild card, - // not as a specific state. - HealthAny = "any" - HealthPassing = "passing" - HealthWarning = "warning" - HealthCritical = "critical" - HealthMaint = "maintenance" -) - -const ( - // NodeMaint is the special key set by a node in maintenance mode. - NodeMaint = "_node_maintenance" - - // ServiceMaintPrefix is the prefix for a service in maintenance mode. - ServiceMaintPrefix = "_service_maintenance:" -) - -// HealthCheck is used to represent a single check -type HealthCheck struct { - Node string - CheckID string - Name string - Status string - Notes string - Output string - ServiceID string - ServiceName string - ServiceTags []string - - Definition HealthCheckDefinition -} - -// HealthCheckDefinition is used to store the details about -// a health check's execution. -type HealthCheckDefinition struct { - HTTP string - Header map[string][]string - Method string - TLSSkipVerify bool - TCP string - Interval ReadableDuration - Timeout ReadableDuration - DeregisterCriticalServiceAfter ReadableDuration -} - -// HealthChecks is a collection of HealthCheck structs. -type HealthChecks []*HealthCheck - -// AggregatedStatus returns the "best" status for the list of health checks. -// Because a given entry may have many service and node-level health checks -// attached, this function determines the best representative of the status as -// as single string using the following heuristic: -// -// maintenance > critical > warning > passing -// -func (c HealthChecks) AggregatedStatus() string { - var passing, warning, critical, maintenance bool - for _, check := range c { - id := string(check.CheckID) - if id == NodeMaint || strings.HasPrefix(id, ServiceMaintPrefix) { - maintenance = true - continue - } - - switch check.Status { - case HealthPassing: - passing = true - case HealthWarning: - warning = true - case HealthCritical: - critical = true - default: - return "" - } - } - - switch { - case maintenance: - return HealthMaint - case critical: - return HealthCritical - case warning: - return HealthWarning - case passing: - return HealthPassing - default: - return HealthPassing - } -} - -// ServiceEntry is used for the health service endpoint -type ServiceEntry struct { - Node *Node - Service *AgentService - Checks HealthChecks -} - -// Health can be used to query the Health endpoints -type Health struct { - c *Client -} - -// Health returns a handle to the health endpoints -func (c *Client) Health() *Health { - return &Health{c} -} - -// Node is used to query for checks belonging to a given node -func (h *Health) Node(node string, q *QueryOptions) (HealthChecks, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/health/node/"+node) - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out HealthChecks - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Checks is used to return the checks associated with a service -func (h *Health) Checks(service string, q *QueryOptions) (HealthChecks, *QueryMeta, error) { - r := h.c.newRequest("GET", "/v1/health/checks/"+service) - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out HealthChecks - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Service is used to query health information along with service info -// for a given service. It can optionally do server-side filtering on a tag -// or nodes with passing health checks only. -func (h *Health) Service(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error) { - return h.service(service, tag, passingOnly, q, false) -} - -// Connect is equivalent to Service except that it will only return services -// which are Connect-enabled and will returns the connection address for Connect -// client's to use which may be a proxy in front of the named service. If -// passingOnly is true only instances where both the service and any proxy are -// healthy will be returned. -func (h *Health) Connect(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error) { - return h.service(service, tag, passingOnly, q, true) -} - -func (h *Health) service(service, tag string, passingOnly bool, q *QueryOptions, connect bool) ([]*ServiceEntry, *QueryMeta, error) { - path := "/v1/health/service/" + service - if connect { - path = "/v1/health/connect/" + service - } - r := h.c.newRequest("GET", path) - r.setQueryOptions(q) - if tag != "" { - r.params.Set("tag", tag) - } - if passingOnly { - r.params.Set(HealthPassing, "1") - } - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out []*ServiceEntry - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// State is used to retrieve all the checks in a given state. -// The wildcard "any" state can also be used for all checks. -func (h *Health) State(state string, q *QueryOptions) (HealthChecks, *QueryMeta, error) { - switch state { - case HealthAny: - case HealthWarning: - case HealthCritical: - case HealthPassing: - default: - return nil, nil, fmt.Errorf("Unsupported state: %v", state) - } - r := h.c.newRequest("GET", "/v1/health/state/"+state) - r.setQueryOptions(q) - rtt, resp, err := requireOK(h.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - var out HealthChecks - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/kv.go b/vendor/github.com/hashicorp/consul/api/kv.go deleted file mode 100644 index 97f515685..000000000 --- a/vendor/github.com/hashicorp/consul/api/kv.go +++ /dev/null @@ -1,420 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "net/http" - "strconv" - "strings" -) - -// KVPair is used to represent a single K/V entry -type KVPair struct { - // Key is the name of the key. It is also part of the URL path when accessed - // via the API. - Key string - - // CreateIndex holds the index corresponding the creation of this KVPair. This - // is a read-only field. - CreateIndex uint64 - - // ModifyIndex is used for the Check-And-Set operations and can also be fed - // back into the WaitIndex of the QueryOptions in order to perform blocking - // queries. - ModifyIndex uint64 - - // LockIndex holds the index corresponding to a lock on this key, if any. This - // is a read-only field. - LockIndex uint64 - - // Flags are any user-defined flags on the key. It is up to the implementer - // to check these values, since Consul does not treat them specially. - Flags uint64 - - // Value is the value for the key. This can be any value, but it will be - // base64 encoded upon transport. - Value []byte - - // Session is a string representing the ID of the session. Any other - // interactions with this key over the same session must specify the same - // session ID. - Session string -} - -// KVPairs is a list of KVPair objects -type KVPairs []*KVPair - -// KVOp constants give possible operations available in a KVTxn. -type KVOp string - -const ( - KVSet KVOp = "set" - KVDelete KVOp = "delete" - KVDeleteCAS KVOp = "delete-cas" - KVDeleteTree KVOp = "delete-tree" - KVCAS KVOp = "cas" - KVLock KVOp = "lock" - KVUnlock KVOp = "unlock" - KVGet KVOp = "get" - KVGetTree KVOp = "get-tree" - KVCheckSession KVOp = "check-session" - KVCheckIndex KVOp = "check-index" - KVCheckNotExists KVOp = "check-not-exists" -) - -// KVTxnOp defines a single operation inside a transaction. -type KVTxnOp struct { - Verb KVOp - Key string - Value []byte - Flags uint64 - Index uint64 - Session string -} - -// KVTxnOps defines a set of operations to be performed inside a single -// transaction. -type KVTxnOps []*KVTxnOp - -// KVTxnResponse has the outcome of a transaction. -type KVTxnResponse struct { - Results []*KVPair - Errors TxnErrors -} - -// KV is used to manipulate the K/V API -type KV struct { - c *Client -} - -// KV is used to return a handle to the K/V apis -func (c *Client) KV() *KV { - return &KV{c} -} - -// Get is used to lookup a single key. The returned pointer -// to the KVPair will be nil if the key does not exist. -func (k *KV) Get(key string, q *QueryOptions) (*KVPair, *QueryMeta, error) { - resp, qm, err := k.getInternal(key, nil, q) - if err != nil { - return nil, nil, err - } - if resp == nil { - return nil, qm, nil - } - defer resp.Body.Close() - - var entries []*KVPair - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - if len(entries) > 0 { - return entries[0], qm, nil - } - return nil, qm, nil -} - -// List is used to lookup all keys under a prefix -func (k *KV) List(prefix string, q *QueryOptions) (KVPairs, *QueryMeta, error) { - resp, qm, err := k.getInternal(prefix, map[string]string{"recurse": ""}, q) - if err != nil { - return nil, nil, err - } - if resp == nil { - return nil, qm, nil - } - defer resp.Body.Close() - - var entries []*KVPair - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - return entries, qm, nil -} - -// Keys is used to list all the keys under a prefix. Optionally, -// a separator can be used to limit the responses. -func (k *KV) Keys(prefix, separator string, q *QueryOptions) ([]string, *QueryMeta, error) { - params := map[string]string{"keys": ""} - if separator != "" { - params["separator"] = separator - } - resp, qm, err := k.getInternal(prefix, params, q) - if err != nil { - return nil, nil, err - } - if resp == nil { - return nil, qm, nil - } - defer resp.Body.Close() - - var entries []string - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, err - } - return entries, qm, nil -} - -func (k *KV) getInternal(key string, params map[string]string, q *QueryOptions) (*http.Response, *QueryMeta, error) { - r := k.c.newRequest("GET", "/v1/kv/"+strings.TrimPrefix(key, "/")) - r.setQueryOptions(q) - for param, val := range params { - r.params.Set(param, val) - } - rtt, resp, err := k.c.doRequest(r) - if err != nil { - return nil, nil, err - } - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - if resp.StatusCode == 404 { - resp.Body.Close() - return nil, qm, nil - } else if resp.StatusCode != 200 { - resp.Body.Close() - return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode) - } - return resp, qm, nil -} - -// Put is used to write a new value. Only the -// Key, Flags and Value is respected. -func (k *KV) Put(p *KVPair, q *WriteOptions) (*WriteMeta, error) { - params := make(map[string]string, 1) - if p.Flags != 0 { - params["flags"] = strconv.FormatUint(p.Flags, 10) - } - _, wm, err := k.put(p.Key, params, p.Value, q) - return wm, err -} - -// CAS is used for a Check-And-Set operation. The Key, -// ModifyIndex, Flags and Value are respected. Returns true -// on success or false on failures. -func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { - params := make(map[string]string, 2) - if p.Flags != 0 { - params["flags"] = strconv.FormatUint(p.Flags, 10) - } - params["cas"] = strconv.FormatUint(p.ModifyIndex, 10) - return k.put(p.Key, params, p.Value, q) -} - -// Acquire is used for a lock acquisition operation. The Key, -// Flags, Value and Session are respected. Returns true -// on success or false on failures. -func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { - params := make(map[string]string, 2) - if p.Flags != 0 { - params["flags"] = strconv.FormatUint(p.Flags, 10) - } - params["acquire"] = p.Session - return k.put(p.Key, params, p.Value, q) -} - -// Release is used for a lock release operation. The Key, -// Flags, Value and Session are respected. Returns true -// on success or false on failures. -func (k *KV) Release(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { - params := make(map[string]string, 2) - if p.Flags != 0 { - params["flags"] = strconv.FormatUint(p.Flags, 10) - } - params["release"] = p.Session - return k.put(p.Key, params, p.Value, q) -} - -func (k *KV) put(key string, params map[string]string, body []byte, q *WriteOptions) (bool, *WriteMeta, error) { - if len(key) > 0 && key[0] == '/' { - return false, nil, fmt.Errorf("Invalid key. Key must not begin with a '/': %s", key) - } - - r := k.c.newRequest("PUT", "/v1/kv/"+key) - r.setWriteOptions(q) - for param, val := range params { - r.params.Set(param, val) - } - r.body = bytes.NewReader(body) - rtt, resp, err := requireOK(k.c.doRequest(r)) - if err != nil { - return false, nil, err - } - defer resp.Body.Close() - - qm := &WriteMeta{} - qm.RequestTime = rtt - - var buf bytes.Buffer - if _, err := io.Copy(&buf, resp.Body); err != nil { - return false, nil, fmt.Errorf("Failed to read response: %v", err) - } - res := strings.Contains(buf.String(), "true") - return res, qm, nil -} - -// Delete is used to delete a single key -func (k *KV) Delete(key string, w *WriteOptions) (*WriteMeta, error) { - _, qm, err := k.deleteInternal(key, nil, w) - return qm, err -} - -// DeleteCAS is used for a Delete Check-And-Set operation. The Key -// and ModifyIndex are respected. Returns true on success or false on failures. -func (k *KV) DeleteCAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { - params := map[string]string{ - "cas": strconv.FormatUint(p.ModifyIndex, 10), - } - return k.deleteInternal(p.Key, params, q) -} - -// DeleteTree is used to delete all keys under a prefix -func (k *KV) DeleteTree(prefix string, w *WriteOptions) (*WriteMeta, error) { - _, qm, err := k.deleteInternal(prefix, map[string]string{"recurse": ""}, w) - return qm, err -} - -func (k *KV) deleteInternal(key string, params map[string]string, q *WriteOptions) (bool, *WriteMeta, error) { - r := k.c.newRequest("DELETE", "/v1/kv/"+strings.TrimPrefix(key, "/")) - r.setWriteOptions(q) - for param, val := range params { - r.params.Set(param, val) - } - rtt, resp, err := requireOK(k.c.doRequest(r)) - if err != nil { - return false, nil, err - } - defer resp.Body.Close() - - qm := &WriteMeta{} - qm.RequestTime = rtt - - var buf bytes.Buffer - if _, err := io.Copy(&buf, resp.Body); err != nil { - return false, nil, fmt.Errorf("Failed to read response: %v", err) - } - res := strings.Contains(buf.String(), "true") - return res, qm, nil -} - -// TxnOp is the internal format we send to Consul. It's not specific to KV, -// though currently only KV operations are supported. -type TxnOp struct { - KV *KVTxnOp -} - -// TxnOps is a list of transaction operations. -type TxnOps []*TxnOp - -// TxnResult is the internal format we receive from Consul. -type TxnResult struct { - KV *KVPair -} - -// TxnResults is a list of TxnResult objects. -type TxnResults []*TxnResult - -// TxnError is used to return information about an operation in a transaction. -type TxnError struct { - OpIndex int - What string -} - -// TxnErrors is a list of TxnError objects. -type TxnErrors []*TxnError - -// TxnResponse is the internal format we receive from Consul. -type TxnResponse struct { - Results TxnResults - Errors TxnErrors -} - -// Txn is used to apply multiple KV operations in a single, atomic transaction. -// -// Note that Go will perform the required base64 encoding on the values -// automatically because the type is a byte slice. Transactions are defined as a -// list of operations to perform, using the KVOp constants and KVTxnOp structure -// to define operations. If any operation fails, none of the changes are applied -// to the state store. Note that this hides the internal raw transaction interface -// and munges the input and output types into KV-specific ones for ease of use. -// If there are more non-KV operations in the future we may break out a new -// transaction API client, but it will be easy to keep this KV-specific variant -// supported. -// -// Even though this is generally a write operation, we take a QueryOptions input -// and return a QueryMeta output. If the transaction contains only read ops, then -// Consul will fast-path it to a different endpoint internally which supports -// consistency controls, but not blocking. If there are write operations then -// the request will always be routed through raft and any consistency settings -// will be ignored. -// -// Here's an example: -// -// ops := KVTxnOps{ -// &KVTxnOp{ -// Verb: KVLock, -// Key: "test/lock", -// Session: "adf4238a-882b-9ddc-4a9d-5b6758e4159e", -// Value: []byte("hello"), -// }, -// &KVTxnOp{ -// Verb: KVGet, -// Key: "another/key", -// }, -// } -// ok, response, _, err := kv.Txn(&ops, nil) -// -// If there is a problem making the transaction request then an error will be -// returned. Otherwise, the ok value will be true if the transaction succeeded -// or false if it was rolled back. The response is a structured return value which -// will have the outcome of the transaction. Its Results member will have entries -// for each operation. Deleted keys will have a nil entry in the, and to save -// space, the Value of each key in the Results will be nil unless the operation -// is a KVGet. If the transaction was rolled back, the Errors member will have -// entries referencing the index of the operation that failed along with an error -// message. -func (k *KV) Txn(txn KVTxnOps, q *QueryOptions) (bool, *KVTxnResponse, *QueryMeta, error) { - r := k.c.newRequest("PUT", "/v1/txn") - r.setQueryOptions(q) - - // Convert into the internal format since this is an all-KV txn. - ops := make(TxnOps, 0, len(txn)) - for _, kvOp := range txn { - ops = append(ops, &TxnOp{KV: kvOp}) - } - r.obj = ops - rtt, resp, err := k.c.doRequest(r) - if err != nil { - return false, nil, nil, err - } - defer resp.Body.Close() - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - - if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusConflict { - var txnResp TxnResponse - if err := decodeBody(resp, &txnResp); err != nil { - return false, nil, nil, err - } - - // Convert from the internal format. - kvResp := KVTxnResponse{ - Errors: txnResp.Errors, - } - for _, result := range txnResp.Results { - kvResp.Results = append(kvResp.Results, result.KV) - } - return resp.StatusCode == http.StatusOK, &kvResp, qm, nil - } - - var buf bytes.Buffer - if _, err := io.Copy(&buf, resp.Body); err != nil { - return false, nil, nil, fmt.Errorf("Failed to read response: %v", err) - } - return false, nil, nil, fmt.Errorf("Failed request: %s", buf.String()) -} diff --git a/vendor/github.com/hashicorp/consul/api/lock.go b/vendor/github.com/hashicorp/consul/api/lock.go deleted file mode 100644 index 82339cb74..000000000 --- a/vendor/github.com/hashicorp/consul/api/lock.go +++ /dev/null @@ -1,386 +0,0 @@ -package api - -import ( - "fmt" - "sync" - "time" -) - -const ( - // DefaultLockSessionName is the Session Name we assign if none is provided - DefaultLockSessionName = "Consul API Lock" - - // DefaultLockSessionTTL is the default session TTL if no Session is provided - // when creating a new Lock. This is used because we do not have another - // other check to depend upon. - DefaultLockSessionTTL = "15s" - - // DefaultLockWaitTime is how long we block for at a time to check if lock - // acquisition is possible. This affects the minimum time it takes to cancel - // a Lock acquisition. - DefaultLockWaitTime = 15 * time.Second - - // DefaultLockRetryTime is how long we wait after a failed lock acquisition - // before attempting to do the lock again. This is so that once a lock-delay - // is in effect, we do not hot loop retrying the acquisition. - DefaultLockRetryTime = 5 * time.Second - - // DefaultMonitorRetryTime is how long we wait after a failed monitor check - // of a lock (500 response code). This allows the monitor to ride out brief - // periods of unavailability, subject to the MonitorRetries setting in the - // lock options which is by default set to 0, disabling this feature. This - // affects locks and semaphores. - DefaultMonitorRetryTime = 2 * time.Second - - // LockFlagValue is a magic flag we set to indicate a key - // is being used for a lock. It is used to detect a potential - // conflict with a semaphore. - LockFlagValue = 0x2ddccbc058a50c18 -) - -var ( - // ErrLockHeld is returned if we attempt to double lock - ErrLockHeld = fmt.Errorf("Lock already held") - - // ErrLockNotHeld is returned if we attempt to unlock a lock - // that we do not hold. - ErrLockNotHeld = fmt.Errorf("Lock not held") - - // ErrLockInUse is returned if we attempt to destroy a lock - // that is in use. - ErrLockInUse = fmt.Errorf("Lock in use") - - // ErrLockConflict is returned if the flags on a key - // used for a lock do not match expectation - ErrLockConflict = fmt.Errorf("Existing key does not match lock use") -) - -// Lock is used to implement client-side leader election. It is follows the -// algorithm as described here: https://www.consul.io/docs/guides/leader-election.html. -type Lock struct { - c *Client - opts *LockOptions - - isHeld bool - sessionRenew chan struct{} - lockSession string - l sync.Mutex -} - -// LockOptions is used to parameterize the Lock behavior. -type LockOptions struct { - Key string // Must be set and have write permissions - Value []byte // Optional, value to associate with the lock - Session string // Optional, created if not specified - SessionOpts *SessionEntry // Optional, options to use when creating a session - SessionName string // Optional, defaults to DefaultLockSessionName (ignored if SessionOpts is given) - SessionTTL string // Optional, defaults to DefaultLockSessionTTL (ignored if SessionOpts is given) - MonitorRetries int // Optional, defaults to 0 which means no retries - MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime - LockWaitTime time.Duration // Optional, defaults to DefaultLockWaitTime - LockTryOnce bool // Optional, defaults to false which means try forever -} - -// LockKey returns a handle to a lock struct which can be used -// to acquire and release the mutex. The key used must have -// write permissions. -func (c *Client) LockKey(key string) (*Lock, error) { - opts := &LockOptions{ - Key: key, - } - return c.LockOpts(opts) -} - -// LockOpts returns a handle to a lock struct which can be used -// to acquire and release the mutex. The key used must have -// write permissions. -func (c *Client) LockOpts(opts *LockOptions) (*Lock, error) { - if opts.Key == "" { - return nil, fmt.Errorf("missing key") - } - if opts.SessionName == "" { - opts.SessionName = DefaultLockSessionName - } - if opts.SessionTTL == "" { - opts.SessionTTL = DefaultLockSessionTTL - } else { - if _, err := time.ParseDuration(opts.SessionTTL); err != nil { - return nil, fmt.Errorf("invalid SessionTTL: %v", err) - } - } - if opts.MonitorRetryTime == 0 { - opts.MonitorRetryTime = DefaultMonitorRetryTime - } - if opts.LockWaitTime == 0 { - opts.LockWaitTime = DefaultLockWaitTime - } - l := &Lock{ - c: c, - opts: opts, - } - return l, nil -} - -// Lock attempts to acquire the lock and blocks while doing so. -// Providing a non-nil stopCh can be used to abort the lock attempt. -// Returns a channel that is closed if our lock is lost or an error. -// This channel could be closed at any time due to session invalidation, -// communication errors, operator intervention, etc. It is NOT safe to -// assume that the lock is held until Unlock() unless the Session is specifically -// created without any associated health checks. By default Consul sessions -// prefer liveness over safety and an application must be able to handle -// the lock being lost. -func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - // Hold the lock as we try to acquire - l.l.Lock() - defer l.l.Unlock() - - // Check if we already hold the lock - if l.isHeld { - return nil, ErrLockHeld - } - - // Check if we need to create a session first - l.lockSession = l.opts.Session - if l.lockSession == "" { - s, err := l.createSession() - if err != nil { - return nil, fmt.Errorf("failed to create session: %v", err) - } - - l.sessionRenew = make(chan struct{}) - l.lockSession = s - session := l.c.Session() - go session.RenewPeriodic(l.opts.SessionTTL, s, nil, l.sessionRenew) - - // If we fail to acquire the lock, cleanup the session - defer func() { - if !l.isHeld { - close(l.sessionRenew) - l.sessionRenew = nil - } - }() - } - - // Setup the query options - kv := l.c.KV() - qOpts := &QueryOptions{ - WaitTime: l.opts.LockWaitTime, - } - - start := time.Now() - attempts := 0 -WAIT: - // Check if we should quit - select { - case <-stopCh: - return nil, nil - default: - } - - // Handle the one-shot mode. - if l.opts.LockTryOnce && attempts > 0 { - elapsed := time.Since(start) - if elapsed > l.opts.LockWaitTime { - return nil, nil - } - - // Query wait time should not exceed the lock wait time - qOpts.WaitTime = l.opts.LockWaitTime - elapsed - } - attempts++ - - // Look for an existing lock, blocking until not taken - pair, meta, err := kv.Get(l.opts.Key, qOpts) - if err != nil { - return nil, fmt.Errorf("failed to read lock: %v", err) - } - if pair != nil && pair.Flags != LockFlagValue { - return nil, ErrLockConflict - } - locked := false - if pair != nil && pair.Session == l.lockSession { - goto HELD - } - if pair != nil && pair.Session != "" { - qOpts.WaitIndex = meta.LastIndex - goto WAIT - } - - // Try to acquire the lock - pair = l.lockEntry(l.lockSession) - locked, _, err = kv.Acquire(pair, nil) - if err != nil { - return nil, fmt.Errorf("failed to acquire lock: %v", err) - } - - // Handle the case of not getting the lock - if !locked { - // Determine why the lock failed - qOpts.WaitIndex = 0 - pair, meta, err = kv.Get(l.opts.Key, qOpts) - if pair != nil && pair.Session != "" { - //If the session is not null, this means that a wait can safely happen - //using a long poll - qOpts.WaitIndex = meta.LastIndex - goto WAIT - } else { - // If the session is empty and the lock failed to acquire, then it means - // a lock-delay is in effect and a timed wait must be used - select { - case <-time.After(DefaultLockRetryTime): - goto WAIT - case <-stopCh: - return nil, nil - } - } - } - -HELD: - // Watch to ensure we maintain leadership - leaderCh := make(chan struct{}) - go l.monitorLock(l.lockSession, leaderCh) - - // Set that we own the lock - l.isHeld = true - - // Locked! All done - return leaderCh, nil -} - -// Unlock released the lock. It is an error to call this -// if the lock is not currently held. -func (l *Lock) Unlock() error { - // Hold the lock as we try to release - l.l.Lock() - defer l.l.Unlock() - - // Ensure the lock is actually held - if !l.isHeld { - return ErrLockNotHeld - } - - // Set that we no longer own the lock - l.isHeld = false - - // Stop the session renew - if l.sessionRenew != nil { - defer func() { - close(l.sessionRenew) - l.sessionRenew = nil - }() - } - - // Get the lock entry, and clear the lock session - lockEnt := l.lockEntry(l.lockSession) - l.lockSession = "" - - // Release the lock explicitly - kv := l.c.KV() - _, _, err := kv.Release(lockEnt, nil) - if err != nil { - return fmt.Errorf("failed to release lock: %v", err) - } - return nil -} - -// Destroy is used to cleanup the lock entry. It is not necessary -// to invoke. It will fail if the lock is in use. -func (l *Lock) Destroy() error { - // Hold the lock as we try to release - l.l.Lock() - defer l.l.Unlock() - - // Check if we already hold the lock - if l.isHeld { - return ErrLockHeld - } - - // Look for an existing lock - kv := l.c.KV() - pair, _, err := kv.Get(l.opts.Key, nil) - if err != nil { - return fmt.Errorf("failed to read lock: %v", err) - } - - // Nothing to do if the lock does not exist - if pair == nil { - return nil - } - - // Check for possible flag conflict - if pair.Flags != LockFlagValue { - return ErrLockConflict - } - - // Check if it is in use - if pair.Session != "" { - return ErrLockInUse - } - - // Attempt the delete - didRemove, _, err := kv.DeleteCAS(pair, nil) - if err != nil { - return fmt.Errorf("failed to remove lock: %v", err) - } - if !didRemove { - return ErrLockInUse - } - return nil -} - -// createSession is used to create a new managed session -func (l *Lock) createSession() (string, error) { - session := l.c.Session() - se := l.opts.SessionOpts - if se == nil { - se = &SessionEntry{ - Name: l.opts.SessionName, - TTL: l.opts.SessionTTL, - } - } - id, _, err := session.Create(se, nil) - if err != nil { - return "", err - } - return id, nil -} - -// lockEntry returns a formatted KVPair for the lock -func (l *Lock) lockEntry(session string) *KVPair { - return &KVPair{ - Key: l.opts.Key, - Value: l.opts.Value, - Session: session, - Flags: LockFlagValue, - } -} - -// monitorLock is a long running routine to monitor a lock ownership -// It closes the stopCh if we lose our leadership. -func (l *Lock) monitorLock(session string, stopCh chan struct{}) { - defer close(stopCh) - kv := l.c.KV() - opts := &QueryOptions{RequireConsistent: true} -WAIT: - retries := l.opts.MonitorRetries -RETRY: - pair, meta, err := kv.Get(l.opts.Key, opts) - if err != nil { - // If configured we can try to ride out a brief Consul unavailability - // by doing retries. Note that we have to attempt the retry in a non- - // blocking fashion so that we have a clean place to reset the retry - // counter if service is restored. - if retries > 0 && IsRetryableError(err) { - time.Sleep(l.opts.MonitorRetryTime) - retries-- - opts.WaitIndex = 0 - goto RETRY - } - return - } - if pair != nil && pair.Session == session { - opts.WaitIndex = meta.LastIndex - goto WAIT - } -} diff --git a/vendor/github.com/hashicorp/consul/api/operator.go b/vendor/github.com/hashicorp/consul/api/operator.go deleted file mode 100644 index 079e22486..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// Operator can be used to perform low-level operator tasks for Consul. -type Operator struct { - c *Client -} - -// Operator returns a handle to the operator endpoints. -func (c *Client) Operator() *Operator { - return &Operator{c} -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_area.go b/vendor/github.com/hashicorp/consul/api/operator_area.go deleted file mode 100644 index 5cf7e4973..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_area.go +++ /dev/null @@ -1,194 +0,0 @@ -package api - -// The /v1/operator/area endpoints are available only in Consul Enterprise and -// interact with its network area subsystem. Network areas are used to link -// together Consul servers in different Consul datacenters. With network areas, -// Consul datacenters can be linked together in ways other than a fully-connected -// mesh, as is required for Consul's WAN. - -import ( - "net" - "time" -) - -// Area defines a network area. -type Area struct { - // ID is this identifier for an area (a UUID). This must be left empty - // when creating a new area. - ID string - - // PeerDatacenter is the peer Consul datacenter that will make up the - // other side of this network area. Network areas always involve a pair - // of datacenters: the datacenter where the area was created, and the - // peer datacenter. This is required. - PeerDatacenter string - - // RetryJoin specifies the address of Consul servers to join to, such as - // an IPs or hostnames with an optional port number. This is optional. - RetryJoin []string - - // UseTLS specifies whether gossip over this area should be encrypted with TLS - // if possible. - UseTLS bool -} - -// AreaJoinResponse is returned when a join occurs and gives the result for each -// address. -type AreaJoinResponse struct { - // The address that was joined. - Address string - - // Whether or not the join was a success. - Joined bool - - // If we couldn't join, this is the message with information. - Error string -} - -// SerfMember is a generic structure for reporting information about members in -// a Serf cluster. This is only used by the area endpoints right now, but this -// could be expanded to other endpoints in the future. -type SerfMember struct { - // ID is the node identifier (a UUID). - ID string - - // Name is the node name. - Name string - - // Addr has the IP address. - Addr net.IP - - // Port is the RPC port. - Port uint16 - - // Datacenter is the DC name. - Datacenter string - - // Role is "client", "server", or "unknown". - Role string - - // Build has the version of the Consul agent. - Build string - - // Protocol is the protocol of the Consul agent. - Protocol int - - // Status is the Serf health status "none", "alive", "leaving", "left", - // or "failed". - Status string - - // RTT is the estimated round trip time from the server handling the - // request to the this member. This will be negative if no RTT estimate - // is available. - RTT time.Duration -} - -// AreaCreate will create a new network area. The ID in the given structure must -// be empty and a generated ID will be returned on success. -func (op *Operator) AreaCreate(area *Area, q *WriteOptions) (string, *WriteMeta, error) { - r := op.c.newRequest("POST", "/v1/operator/area") - r.setWriteOptions(q) - r.obj = area - rtt, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// AreaUpdate will update the configuration of the network area with the given ID. -func (op *Operator) AreaUpdate(areaID string, area *Area, q *WriteOptions) (string, *WriteMeta, error) { - r := op.c.newRequest("PUT", "/v1/operator/area/"+areaID) - r.setWriteOptions(q) - r.obj = area - rtt, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// AreaGet returns a single network area. -func (op *Operator) AreaGet(areaID string, q *QueryOptions) ([]*Area, *QueryMeta, error) { - var out []*Area - qm, err := op.c.query("/v1/operator/area/"+areaID, &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// AreaList returns all the available network areas. -func (op *Operator) AreaList(q *QueryOptions) ([]*Area, *QueryMeta, error) { - var out []*Area - qm, err := op.c.query("/v1/operator/area", &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// AreaDelete deletes the given network area. -func (op *Operator) AreaDelete(areaID string, q *WriteOptions) (*WriteMeta, error) { - r := op.c.newRequest("DELETE", "/v1/operator/area/"+areaID) - r.setWriteOptions(q) - rtt, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - return wm, nil -} - -// AreaJoin attempts to join the given set of join addresses to the given -// network area. See the Area structure for details about join addresses. -func (op *Operator) AreaJoin(areaID string, addresses []string, q *WriteOptions) ([]*AreaJoinResponse, *WriteMeta, error) { - r := op.c.newRequest("PUT", "/v1/operator/area/"+areaID+"/join") - r.setWriteOptions(q) - r.obj = addresses - rtt, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - var out []*AreaJoinResponse - if err := decodeBody(resp, &out); err != nil { - return nil, nil, err - } - return out, wm, nil -} - -// AreaMembers lists the Serf information about the members in the given area. -func (op *Operator) AreaMembers(areaID string, q *QueryOptions) ([]*SerfMember, *QueryMeta, error) { - var out []*SerfMember - qm, err := op.c.query("/v1/operator/area/"+areaID+"/members", &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_autopilot.go b/vendor/github.com/hashicorp/consul/api/operator_autopilot.go deleted file mode 100644 index b179406dc..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_autopilot.go +++ /dev/null @@ -1,219 +0,0 @@ -package api - -import ( - "bytes" - "fmt" - "io" - "strconv" - "strings" - "time" -) - -// AutopilotConfiguration is used for querying/setting the Autopilot configuration. -// Autopilot helps manage operator tasks related to Consul servers like removing -// failed servers from the Raft quorum. -type AutopilotConfiguration struct { - // CleanupDeadServers controls whether to remove dead servers from the Raft - // peer list when a new server joins - CleanupDeadServers bool - - // LastContactThreshold is the limit on the amount of time a server can go - // without leader contact before being considered unhealthy. - LastContactThreshold *ReadableDuration - - // MaxTrailingLogs is the amount of entries in the Raft Log that a server can - // be behind before being considered unhealthy. - MaxTrailingLogs uint64 - - // ServerStabilizationTime is the minimum amount of time a server must be - // in a stable, healthy state before it can be added to the cluster. Only - // applicable with Raft protocol version 3 or higher. - ServerStabilizationTime *ReadableDuration - - // (Enterprise-only) RedundancyZoneTag is the node tag to use for separating - // servers into zones for redundancy. If left blank, this feature will be disabled. - RedundancyZoneTag string - - // (Enterprise-only) DisableUpgradeMigration will disable Autopilot's upgrade migration - // strategy of waiting until enough newer-versioned servers have been added to the - // cluster before promoting them to voters. - DisableUpgradeMigration bool - - // (Enterprise-only) UpgradeVersionTag is the node tag to use for version info when - // performing upgrade migrations. If left blank, the Consul version will be used. - UpgradeVersionTag string - - // CreateIndex holds the index corresponding the creation of this configuration. - // This is a read-only field. - CreateIndex uint64 - - // ModifyIndex will be set to the index of the last update when retrieving the - // Autopilot configuration. Resubmitting a configuration with - // AutopilotCASConfiguration will perform a check-and-set operation which ensures - // there hasn't been a subsequent update since the configuration was retrieved. - ModifyIndex uint64 -} - -// ServerHealth is the health (from the leader's point of view) of a server. -type ServerHealth struct { - // ID is the raft ID of the server. - ID string - - // Name is the node name of the server. - Name string - - // Address is the address of the server. - Address string - - // The status of the SerfHealth check for the server. - SerfStatus string - - // Version is the Consul version of the server. - Version string - - // Leader is whether this server is currently the leader. - Leader bool - - // LastContact is the time since this node's last contact with the leader. - LastContact *ReadableDuration - - // LastTerm is the highest leader term this server has a record of in its Raft log. - LastTerm uint64 - - // LastIndex is the last log index this server has a record of in its Raft log. - LastIndex uint64 - - // Healthy is whether or not the server is healthy according to the current - // Autopilot config. - Healthy bool - - // Voter is whether this is a voting server. - Voter bool - - // StableSince is the last time this server's Healthy value changed. - StableSince time.Time -} - -// OperatorHealthReply is a representation of the overall health of the cluster -type OperatorHealthReply struct { - // Healthy is true if all the servers in the cluster are healthy. - Healthy bool - - // FailureTolerance is the number of healthy servers that could be lost without - // an outage occurring. - FailureTolerance int - - // Servers holds the health of each server. - Servers []ServerHealth -} - -// ReadableDuration is a duration type that is serialized to JSON in human readable format. -type ReadableDuration time.Duration - -func NewReadableDuration(dur time.Duration) *ReadableDuration { - d := ReadableDuration(dur) - return &d -} - -func (d *ReadableDuration) String() string { - return d.Duration().String() -} - -func (d *ReadableDuration) Duration() time.Duration { - if d == nil { - return time.Duration(0) - } - return time.Duration(*d) -} - -func (d *ReadableDuration) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"%s"`, d.Duration().String())), nil -} - -func (d *ReadableDuration) UnmarshalJSON(raw []byte) error { - if d == nil { - return fmt.Errorf("cannot unmarshal to nil pointer") - } - - str := string(raw) - if len(str) < 2 || str[0] != '"' || str[len(str)-1] != '"' { - return fmt.Errorf("must be enclosed with quotes: %s", str) - } - dur, err := time.ParseDuration(str[1 : len(str)-1]) - if err != nil { - return err - } - *d = ReadableDuration(dur) - return nil -} - -// AutopilotGetConfiguration is used to query the current Autopilot configuration. -func (op *Operator) AutopilotGetConfiguration(q *QueryOptions) (*AutopilotConfiguration, error) { - r := op.c.newRequest("GET", "/v1/operator/autopilot/configuration") - r.setQueryOptions(q) - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out AutopilotConfiguration - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - - return &out, nil -} - -// AutopilotSetConfiguration is used to set the current Autopilot configuration. -func (op *Operator) AutopilotSetConfiguration(conf *AutopilotConfiguration, q *WriteOptions) error { - r := op.c.newRequest("PUT", "/v1/operator/autopilot/configuration") - r.setWriteOptions(q) - r.obj = conf - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// AutopilotCASConfiguration is used to perform a Check-And-Set update on the -// Autopilot configuration. The ModifyIndex value will be respected. Returns -// true on success or false on failures. -func (op *Operator) AutopilotCASConfiguration(conf *AutopilotConfiguration, q *WriteOptions) (bool, error) { - r := op.c.newRequest("PUT", "/v1/operator/autopilot/configuration") - r.setWriteOptions(q) - r.params.Set("cas", strconv.FormatUint(conf.ModifyIndex, 10)) - r.obj = conf - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return false, err - } - defer resp.Body.Close() - - var buf bytes.Buffer - if _, err := io.Copy(&buf, resp.Body); err != nil { - return false, fmt.Errorf("Failed to read response: %v", err) - } - res := strings.Contains(buf.String(), "true") - - return res, nil -} - -// AutopilotServerHealth -func (op *Operator) AutopilotServerHealth(q *QueryOptions) (*OperatorHealthReply, error) { - r := op.c.newRequest("GET", "/v1/operator/autopilot/health") - r.setQueryOptions(q) - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out OperatorHealthReply - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return &out, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_keyring.go b/vendor/github.com/hashicorp/consul/api/operator_keyring.go deleted file mode 100644 index 6b614296c..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_keyring.go +++ /dev/null @@ -1,86 +0,0 @@ -package api - -// keyringRequest is used for performing Keyring operations -type keyringRequest struct { - Key string -} - -// KeyringResponse is returned when listing the gossip encryption keys -type KeyringResponse struct { - // Whether this response is for a WAN ring - WAN bool - - // The datacenter name this request corresponds to - Datacenter string - - // Segment has the network segment this request corresponds to. - Segment string - - // A map of the encryption keys to the number of nodes they're installed on - Keys map[string]int - - // The total number of nodes in this ring - NumNodes int -} - -// KeyringInstall is used to install a new gossip encryption key into the cluster -func (op *Operator) KeyringInstall(key string, q *WriteOptions) error { - r := op.c.newRequest("POST", "/v1/operator/keyring") - r.setWriteOptions(q) - r.obj = keyringRequest{ - Key: key, - } - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// KeyringList is used to list the gossip keys installed in the cluster -func (op *Operator) KeyringList(q *QueryOptions) ([]*KeyringResponse, error) { - r := op.c.newRequest("GET", "/v1/operator/keyring") - r.setQueryOptions(q) - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out []*KeyringResponse - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return out, nil -} - -// KeyringRemove is used to remove a gossip encryption key from the cluster -func (op *Operator) KeyringRemove(key string, q *WriteOptions) error { - r := op.c.newRequest("DELETE", "/v1/operator/keyring") - r.setWriteOptions(q) - r.obj = keyringRequest{ - Key: key, - } - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} - -// KeyringUse is used to change the active gossip encryption key -func (op *Operator) KeyringUse(key string, q *WriteOptions) error { - r := op.c.newRequest("PUT", "/v1/operator/keyring") - r.setWriteOptions(q) - r.obj = keyringRequest{ - Key: key, - } - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - resp.Body.Close() - return nil -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_raft.go b/vendor/github.com/hashicorp/consul/api/operator_raft.go deleted file mode 100644 index a9844df2d..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_raft.go +++ /dev/null @@ -1,89 +0,0 @@ -package api - -// RaftServer has information about a server in the Raft configuration. -type RaftServer struct { - // ID is the unique ID for the server. These are currently the same - // as the address, but they will be changed to a real GUID in a future - // release of Consul. - ID string - - // Node is the node name of the server, as known by Consul, or this - // will be set to "(unknown)" otherwise. - Node string - - // Address is the IP:port of the server, used for Raft communications. - Address string - - // Leader is true if this server is the current cluster leader. - Leader bool - - // Protocol version is the raft protocol version used by the server - ProtocolVersion string - - // Voter is true if this server has a vote in the cluster. This might - // be false if the server is staging and still coming online, or if - // it's a non-voting server, which will be added in a future release of - // Consul. - Voter bool -} - -// RaftConfiguration is returned when querying for the current Raft configuration. -type RaftConfiguration struct { - // Servers has the list of servers in the Raft configuration. - Servers []*RaftServer - - // Index has the Raft index of this configuration. - Index uint64 -} - -// RaftGetConfiguration is used to query the current Raft peer set. -func (op *Operator) RaftGetConfiguration(q *QueryOptions) (*RaftConfiguration, error) { - r := op.c.newRequest("GET", "/v1/operator/raft/configuration") - r.setQueryOptions(q) - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var out RaftConfiguration - if err := decodeBody(resp, &out); err != nil { - return nil, err - } - return &out, nil -} - -// RaftRemovePeerByAddress is used to kick a stale peer (one that it in the Raft -// quorum but no longer known to Serf or the catalog) by address in the form of -// "IP:port". -func (op *Operator) RaftRemovePeerByAddress(address string, q *WriteOptions) error { - r := op.c.newRequest("DELETE", "/v1/operator/raft/peer") - r.setWriteOptions(q) - - r.params.Set("address", string(address)) - - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - - resp.Body.Close() - return nil -} - -// RaftRemovePeerByID is used to kick a stale peer (one that it in the Raft -// quorum but no longer known to Serf or the catalog) by ID. -func (op *Operator) RaftRemovePeerByID(id string, q *WriteOptions) error { - r := op.c.newRequest("DELETE", "/v1/operator/raft/peer") - r.setWriteOptions(q) - - r.params.Set("id", string(id)) - - _, resp, err := requireOK(op.c.doRequest(r)) - if err != nil { - return err - } - - resp.Body.Close() - return nil -} diff --git a/vendor/github.com/hashicorp/consul/api/operator_segment.go b/vendor/github.com/hashicorp/consul/api/operator_segment.go deleted file mode 100644 index 92b05d3c0..000000000 --- a/vendor/github.com/hashicorp/consul/api/operator_segment.go +++ /dev/null @@ -1,11 +0,0 @@ -package api - -// SegmentList returns all the available LAN segments. -func (op *Operator) SegmentList(q *QueryOptions) ([]string, *QueryMeta, error) { - var out []string - qm, err := op.c.query("/v1/operator/segment", &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/prepared_query.go b/vendor/github.com/hashicorp/consul/api/prepared_query.go deleted file mode 100644 index 8bb1004ee..000000000 --- a/vendor/github.com/hashicorp/consul/api/prepared_query.go +++ /dev/null @@ -1,212 +0,0 @@ -package api - -// QueryDatacenterOptions sets options about how we fail over if there are no -// healthy nodes in the local datacenter. -type QueryDatacenterOptions struct { - // NearestN is set to the number of remote datacenters to try, based on - // network coordinates. - NearestN int - - // Datacenters is a fixed list of datacenters to try after NearestN. We - // never try a datacenter multiple times, so those are subtracted from - // this list before proceeding. - Datacenters []string -} - -// QueryDNSOptions controls settings when query results are served over DNS. -type QueryDNSOptions struct { - // TTL is the time to live for the served DNS results. - TTL string -} - -// ServiceQuery is used to query for a set of healthy nodes offering a specific -// service. -type ServiceQuery struct { - // Service is the service to query. - Service string - - // Near allows baking in the name of a node to automatically distance- - // sort from. The magic "_agent" value is supported, which sorts near - // the agent which initiated the request by default. - Near string - - // Failover controls what we do if there are no healthy nodes in the - // local datacenter. - Failover QueryDatacenterOptions - - // IgnoreCheckIDs is an optional list of health check IDs to ignore when - // considering which nodes are healthy. It is useful as an emergency measure - // to temporarily override some health check that is producing false negatives - // for example. - IgnoreCheckIDs []string - - // If OnlyPassing is true then we will only include nodes with passing - // health checks (critical AND warning checks will cause a node to be - // discarded) - OnlyPassing bool - - // Tags are a set of required and/or disallowed tags. If a tag is in - // this list it must be present. If the tag is preceded with "!" then - // it is disallowed. - Tags []string - - // NodeMeta is a map of required node metadata fields. If a key/value - // pair is in this map it must be present on the node in order for the - // service entry to be returned. - NodeMeta map[string]string - - // Connect if true will filter the prepared query results to only - // include Connect-capable services. These include both native services - // and proxies for matching services. Note that if a proxy matches, - // the constraints in the query above (Near, OnlyPassing, etc.) apply - // to the _proxy_ and not the service being proxied. In practice, proxies - // should be directly next to their services so this isn't an issue. - Connect bool -} - -// QueryTemplate carries the arguments for creating a templated query. -type QueryTemplate struct { - // Type specifies the type of the query template. Currently only - // "name_prefix_match" is supported. This field is required. - Type string - - // Regexp allows specifying a regex pattern to match against the name - // of the query being executed. - Regexp string -} - -// PreparedQueryDefinition defines a complete prepared query. -type PreparedQueryDefinition struct { - // ID is this UUID-based ID for the query, always generated by Consul. - ID string - - // Name is an optional friendly name for the query supplied by the - // user. NOTE - if this feature is used then it will reduce the security - // of any read ACL associated with this query/service since this name - // can be used to locate nodes with supplying any ACL. - Name string - - // Session is an optional session to tie this query's lifetime to. If - // this is omitted then the query will not expire. - Session string - - // Token is the ACL token used when the query was created, and it is - // used when a query is subsequently executed. This token, or a token - // with management privileges, must be used to change the query later. - Token string - - // Service defines a service query (leaving things open for other types - // later). - Service ServiceQuery - - // DNS has options that control how the results of this query are - // served over DNS. - DNS QueryDNSOptions - - // Template is used to pass through the arguments for creating a - // prepared query with an attached template. If a template is given, - // interpolations are possible in other struct fields. - Template QueryTemplate -} - -// PreparedQueryExecuteResponse has the results of executing a query. -type PreparedQueryExecuteResponse struct { - // Service is the service that was queried. - Service string - - // Nodes has the nodes that were output by the query. - Nodes []ServiceEntry - - // DNS has the options for serving these results over DNS. - DNS QueryDNSOptions - - // Datacenter is the datacenter that these results came from. - Datacenter string - - // Failovers is a count of how many times we had to query a remote - // datacenter. - Failovers int -} - -// PreparedQuery can be used to query the prepared query endpoints. -type PreparedQuery struct { - c *Client -} - -// PreparedQuery returns a handle to the prepared query endpoints. -func (c *Client) PreparedQuery() *PreparedQuery { - return &PreparedQuery{c} -} - -// Create makes a new prepared query. The ID of the new query is returned. -func (c *PreparedQuery) Create(query *PreparedQueryDefinition, q *WriteOptions) (string, *WriteMeta, error) { - r := c.c.newRequest("POST", "/v1/query") - r.setWriteOptions(q) - r.obj = query - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return "", nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - - var out struct{ ID string } - if err := decodeBody(resp, &out); err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// Update makes updates to an existing prepared query. -func (c *PreparedQuery) Update(query *PreparedQueryDefinition, q *WriteOptions) (*WriteMeta, error) { - return c.c.write("/v1/query/"+query.ID, query, nil, q) -} - -// List is used to fetch all the prepared queries (always requires a management -// token). -func (c *PreparedQuery) List(q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error) { - var out []*PreparedQueryDefinition - qm, err := c.c.query("/v1/query", &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Get is used to fetch a specific prepared query. -func (c *PreparedQuery) Get(queryID string, q *QueryOptions) ([]*PreparedQueryDefinition, *QueryMeta, error) { - var out []*PreparedQueryDefinition - qm, err := c.c.query("/v1/query/"+queryID, &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} - -// Delete is used to delete a specific prepared query. -func (c *PreparedQuery) Delete(queryID string, q *WriteOptions) (*WriteMeta, error) { - r := c.c.newRequest("DELETE", "/v1/query/"+queryID) - r.setWriteOptions(q) - rtt, resp, err := requireOK(c.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{} - wm.RequestTime = rtt - return wm, nil -} - -// Execute is used to execute a specific prepared query. You can execute using -// a query ID or name. -func (c *PreparedQuery) Execute(queryIDOrName string, q *QueryOptions) (*PreparedQueryExecuteResponse, *QueryMeta, error) { - var out *PreparedQueryExecuteResponse - qm, err := c.c.query("/v1/query/"+queryIDOrName+"/execute", &out, q) - if err != nil { - return nil, nil, err - } - return out, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/raw.go b/vendor/github.com/hashicorp/consul/api/raw.go deleted file mode 100644 index 745a208c9..000000000 --- a/vendor/github.com/hashicorp/consul/api/raw.go +++ /dev/null @@ -1,24 +0,0 @@ -package api - -// Raw can be used to do raw queries against custom endpoints -type Raw struct { - c *Client -} - -// Raw returns a handle to query endpoints -func (c *Client) Raw() *Raw { - return &Raw{c} -} - -// Query is used to do a GET request against an endpoint -// and deserialize the response into an interface using -// standard Consul conventions. -func (raw *Raw) Query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) { - return raw.c.query(endpoint, out, q) -} - -// Write is used to do a PUT request against an endpoint -// and serialize/deserialized using the standard Consul conventions. -func (raw *Raw) Write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) { - return raw.c.write(endpoint, in, out, q) -} diff --git a/vendor/github.com/hashicorp/consul/api/semaphore.go b/vendor/github.com/hashicorp/consul/api/semaphore.go deleted file mode 100644 index bc4f885fe..000000000 --- a/vendor/github.com/hashicorp/consul/api/semaphore.go +++ /dev/null @@ -1,514 +0,0 @@ -package api - -import ( - "encoding/json" - "fmt" - "path" - "sync" - "time" -) - -const ( - // DefaultSemaphoreSessionName is the Session Name we assign if none is provided - DefaultSemaphoreSessionName = "Consul API Semaphore" - - // DefaultSemaphoreSessionTTL is the default session TTL if no Session is provided - // when creating a new Semaphore. This is used because we do not have another - // other check to depend upon. - DefaultSemaphoreSessionTTL = "15s" - - // DefaultSemaphoreWaitTime is how long we block for at a time to check if semaphore - // acquisition is possible. This affects the minimum time it takes to cancel - // a Semaphore acquisition. - DefaultSemaphoreWaitTime = 15 * time.Second - - // DefaultSemaphoreKey is the key used within the prefix to - // use for coordination between all the contenders. - DefaultSemaphoreKey = ".lock" - - // SemaphoreFlagValue is a magic flag we set to indicate a key - // is being used for a semaphore. It is used to detect a potential - // conflict with a lock. - SemaphoreFlagValue = 0xe0f69a2baa414de0 -) - -var ( - // ErrSemaphoreHeld is returned if we attempt to double lock - ErrSemaphoreHeld = fmt.Errorf("Semaphore already held") - - // ErrSemaphoreNotHeld is returned if we attempt to unlock a semaphore - // that we do not hold. - ErrSemaphoreNotHeld = fmt.Errorf("Semaphore not held") - - // ErrSemaphoreInUse is returned if we attempt to destroy a semaphore - // that is in use. - ErrSemaphoreInUse = fmt.Errorf("Semaphore in use") - - // ErrSemaphoreConflict is returned if the flags on a key - // used for a semaphore do not match expectation - ErrSemaphoreConflict = fmt.Errorf("Existing key does not match semaphore use") -) - -// Semaphore is used to implement a distributed semaphore -// using the Consul KV primitives. -type Semaphore struct { - c *Client - opts *SemaphoreOptions - - isHeld bool - sessionRenew chan struct{} - lockSession string - l sync.Mutex -} - -// SemaphoreOptions is used to parameterize the Semaphore -type SemaphoreOptions struct { - Prefix string // Must be set and have write permissions - Limit int // Must be set, and be positive - Value []byte // Optional, value to associate with the contender entry - Session string // Optional, created if not specified - SessionName string // Optional, defaults to DefaultLockSessionName - SessionTTL string // Optional, defaults to DefaultLockSessionTTL - MonitorRetries int // Optional, defaults to 0 which means no retries - MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime - SemaphoreWaitTime time.Duration // Optional, defaults to DefaultSemaphoreWaitTime - SemaphoreTryOnce bool // Optional, defaults to false which means try forever -} - -// semaphoreLock is written under the DefaultSemaphoreKey and -// is used to coordinate between all the contenders. -type semaphoreLock struct { - // Limit is the integer limit of holders. This is used to - // verify that all the holders agree on the value. - Limit int - - // Holders is a list of all the semaphore holders. - // It maps the session ID to true. It is used as a set effectively. - Holders map[string]bool -} - -// SemaphorePrefix is used to created a Semaphore which will operate -// at the given KV prefix and uses the given limit for the semaphore. -// The prefix must have write privileges, and the limit must be agreed -// upon by all contenders. -func (c *Client) SemaphorePrefix(prefix string, limit int) (*Semaphore, error) { - opts := &SemaphoreOptions{ - Prefix: prefix, - Limit: limit, - } - return c.SemaphoreOpts(opts) -} - -// SemaphoreOpts is used to create a Semaphore with the given options. -// The prefix must have write privileges, and the limit must be agreed -// upon by all contenders. If a Session is not provided, one will be created. -func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error) { - if opts.Prefix == "" { - return nil, fmt.Errorf("missing prefix") - } - if opts.Limit <= 0 { - return nil, fmt.Errorf("semaphore limit must be positive") - } - if opts.SessionName == "" { - opts.SessionName = DefaultSemaphoreSessionName - } - if opts.SessionTTL == "" { - opts.SessionTTL = DefaultSemaphoreSessionTTL - } else { - if _, err := time.ParseDuration(opts.SessionTTL); err != nil { - return nil, fmt.Errorf("invalid SessionTTL: %v", err) - } - } - if opts.MonitorRetryTime == 0 { - opts.MonitorRetryTime = DefaultMonitorRetryTime - } - if opts.SemaphoreWaitTime == 0 { - opts.SemaphoreWaitTime = DefaultSemaphoreWaitTime - } - s := &Semaphore{ - c: c, - opts: opts, - } - return s, nil -} - -// Acquire attempts to reserve a slot in the semaphore, blocking until -// success, interrupted via the stopCh or an error is encountered. -// Providing a non-nil stopCh can be used to abort the attempt. -// On success, a channel is returned that represents our slot. -// This channel could be closed at any time due to session invalidation, -// communication errors, operator intervention, etc. It is NOT safe to -// assume that the slot is held until Release() unless the Session is specifically -// created without any associated health checks. By default Consul sessions -// prefer liveness over safety and an application must be able to handle -// the session being lost. -func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) { - // Hold the lock as we try to acquire - s.l.Lock() - defer s.l.Unlock() - - // Check if we already hold the semaphore - if s.isHeld { - return nil, ErrSemaphoreHeld - } - - // Check if we need to create a session first - s.lockSession = s.opts.Session - if s.lockSession == "" { - sess, err := s.createSession() - if err != nil { - return nil, fmt.Errorf("failed to create session: %v", err) - } - - s.sessionRenew = make(chan struct{}) - s.lockSession = sess - session := s.c.Session() - go session.RenewPeriodic(s.opts.SessionTTL, sess, nil, s.sessionRenew) - - // If we fail to acquire the lock, cleanup the session - defer func() { - if !s.isHeld { - close(s.sessionRenew) - s.sessionRenew = nil - } - }() - } - - // Create the contender entry - kv := s.c.KV() - made, _, err := kv.Acquire(s.contenderEntry(s.lockSession), nil) - if err != nil || !made { - return nil, fmt.Errorf("failed to make contender entry: %v", err) - } - - // Setup the query options - qOpts := &QueryOptions{ - WaitTime: s.opts.SemaphoreWaitTime, - } - - start := time.Now() - attempts := 0 -WAIT: - // Check if we should quit - select { - case <-stopCh: - return nil, nil - default: - } - - // Handle the one-shot mode. - if s.opts.SemaphoreTryOnce && attempts > 0 { - elapsed := time.Since(start) - if elapsed > s.opts.SemaphoreWaitTime { - return nil, nil - } - - // Query wait time should not exceed the semaphore wait time - qOpts.WaitTime = s.opts.SemaphoreWaitTime - elapsed - } - attempts++ - - // Read the prefix - pairs, meta, err := kv.List(s.opts.Prefix, qOpts) - if err != nil { - return nil, fmt.Errorf("failed to read prefix: %v", err) - } - - // Decode the lock - lockPair := s.findLock(pairs) - if lockPair.Flags != SemaphoreFlagValue { - return nil, ErrSemaphoreConflict - } - lock, err := s.decodeLock(lockPair) - if err != nil { - return nil, err - } - - // Verify we agree with the limit - if lock.Limit != s.opts.Limit { - return nil, fmt.Errorf("semaphore limit conflict (lock: %d, local: %d)", - lock.Limit, s.opts.Limit) - } - - // Prune the dead holders - s.pruneDeadHolders(lock, pairs) - - // Check if the lock is held - if len(lock.Holders) >= lock.Limit { - qOpts.WaitIndex = meta.LastIndex - goto WAIT - } - - // Create a new lock with us as a holder - lock.Holders[s.lockSession] = true - newLock, err := s.encodeLock(lock, lockPair.ModifyIndex) - if err != nil { - return nil, err - } - - // Attempt the acquisition - didSet, _, err := kv.CAS(newLock, nil) - if err != nil { - return nil, fmt.Errorf("failed to update lock: %v", err) - } - if !didSet { - // Update failed, could have been a race with another contender, - // retry the operation - goto WAIT - } - - // Watch to ensure we maintain ownership of the slot - lockCh := make(chan struct{}) - go s.monitorLock(s.lockSession, lockCh) - - // Set that we own the lock - s.isHeld = true - - // Acquired! All done - return lockCh, nil -} - -// Release is used to voluntarily give up our semaphore slot. It is -// an error to call this if the semaphore has not been acquired. -func (s *Semaphore) Release() error { - // Hold the lock as we try to release - s.l.Lock() - defer s.l.Unlock() - - // Ensure the lock is actually held - if !s.isHeld { - return ErrSemaphoreNotHeld - } - - // Set that we no longer own the lock - s.isHeld = false - - // Stop the session renew - if s.sessionRenew != nil { - defer func() { - close(s.sessionRenew) - s.sessionRenew = nil - }() - } - - // Get and clear the lock session - lockSession := s.lockSession - s.lockSession = "" - - // Remove ourselves as a lock holder - kv := s.c.KV() - key := path.Join(s.opts.Prefix, DefaultSemaphoreKey) -READ: - pair, _, err := kv.Get(key, nil) - if err != nil { - return err - } - if pair == nil { - pair = &KVPair{} - } - lock, err := s.decodeLock(pair) - if err != nil { - return err - } - - // Create a new lock without us as a holder - if _, ok := lock.Holders[lockSession]; ok { - delete(lock.Holders, lockSession) - newLock, err := s.encodeLock(lock, pair.ModifyIndex) - if err != nil { - return err - } - - // Swap the locks - didSet, _, err := kv.CAS(newLock, nil) - if err != nil { - return fmt.Errorf("failed to update lock: %v", err) - } - if !didSet { - goto READ - } - } - - // Destroy the contender entry - contenderKey := path.Join(s.opts.Prefix, lockSession) - if _, err := kv.Delete(contenderKey, nil); err != nil { - return err - } - return nil -} - -// Destroy is used to cleanup the semaphore entry. It is not necessary -// to invoke. It will fail if the semaphore is in use. -func (s *Semaphore) Destroy() error { - // Hold the lock as we try to acquire - s.l.Lock() - defer s.l.Unlock() - - // Check if we already hold the semaphore - if s.isHeld { - return ErrSemaphoreHeld - } - - // List for the semaphore - kv := s.c.KV() - pairs, _, err := kv.List(s.opts.Prefix, nil) - if err != nil { - return fmt.Errorf("failed to read prefix: %v", err) - } - - // Find the lock pair, bail if it doesn't exist - lockPair := s.findLock(pairs) - if lockPair.ModifyIndex == 0 { - return nil - } - if lockPair.Flags != SemaphoreFlagValue { - return ErrSemaphoreConflict - } - - // Decode the lock - lock, err := s.decodeLock(lockPair) - if err != nil { - return err - } - - // Prune the dead holders - s.pruneDeadHolders(lock, pairs) - - // Check if there are any holders - if len(lock.Holders) > 0 { - return ErrSemaphoreInUse - } - - // Attempt the delete - didRemove, _, err := kv.DeleteCAS(lockPair, nil) - if err != nil { - return fmt.Errorf("failed to remove semaphore: %v", err) - } - if !didRemove { - return ErrSemaphoreInUse - } - return nil -} - -// createSession is used to create a new managed session -func (s *Semaphore) createSession() (string, error) { - session := s.c.Session() - se := &SessionEntry{ - Name: s.opts.SessionName, - TTL: s.opts.SessionTTL, - Behavior: SessionBehaviorDelete, - } - id, _, err := session.Create(se, nil) - if err != nil { - return "", err - } - return id, nil -} - -// contenderEntry returns a formatted KVPair for the contender -func (s *Semaphore) contenderEntry(session string) *KVPair { - return &KVPair{ - Key: path.Join(s.opts.Prefix, session), - Value: s.opts.Value, - Session: session, - Flags: SemaphoreFlagValue, - } -} - -// findLock is used to find the KV Pair which is used for coordination -func (s *Semaphore) findLock(pairs KVPairs) *KVPair { - key := path.Join(s.opts.Prefix, DefaultSemaphoreKey) - for _, pair := range pairs { - if pair.Key == key { - return pair - } - } - return &KVPair{Flags: SemaphoreFlagValue} -} - -// decodeLock is used to decode a semaphoreLock from an -// entry in Consul -func (s *Semaphore) decodeLock(pair *KVPair) (*semaphoreLock, error) { - // Handle if there is no lock - if pair == nil || pair.Value == nil { - return &semaphoreLock{ - Limit: s.opts.Limit, - Holders: make(map[string]bool), - }, nil - } - - l := &semaphoreLock{} - if err := json.Unmarshal(pair.Value, l); err != nil { - return nil, fmt.Errorf("lock decoding failed: %v", err) - } - return l, nil -} - -// encodeLock is used to encode a semaphoreLock into a KVPair -// that can be PUT -func (s *Semaphore) encodeLock(l *semaphoreLock, oldIndex uint64) (*KVPair, error) { - enc, err := json.Marshal(l) - if err != nil { - return nil, fmt.Errorf("lock encoding failed: %v", err) - } - pair := &KVPair{ - Key: path.Join(s.opts.Prefix, DefaultSemaphoreKey), - Value: enc, - Flags: SemaphoreFlagValue, - ModifyIndex: oldIndex, - } - return pair, nil -} - -// pruneDeadHolders is used to remove all the dead lock holders -func (s *Semaphore) pruneDeadHolders(lock *semaphoreLock, pairs KVPairs) { - // Gather all the live holders - alive := make(map[string]struct{}, len(pairs)) - for _, pair := range pairs { - if pair.Session != "" { - alive[pair.Session] = struct{}{} - } - } - - // Remove any holders that are dead - for holder := range lock.Holders { - if _, ok := alive[holder]; !ok { - delete(lock.Holders, holder) - } - } -} - -// monitorLock is a long running routine to monitor a semaphore ownership -// It closes the stopCh if we lose our slot. -func (s *Semaphore) monitorLock(session string, stopCh chan struct{}) { - defer close(stopCh) - kv := s.c.KV() - opts := &QueryOptions{RequireConsistent: true} -WAIT: - retries := s.opts.MonitorRetries -RETRY: - pairs, meta, err := kv.List(s.opts.Prefix, opts) - if err != nil { - // If configured we can try to ride out a brief Consul unavailability - // by doing retries. Note that we have to attempt the retry in a non- - // blocking fashion so that we have a clean place to reset the retry - // counter if service is restored. - if retries > 0 && IsRetryableError(err) { - time.Sleep(s.opts.MonitorRetryTime) - retries-- - opts.WaitIndex = 0 - goto RETRY - } - return - } - lockPair := s.findLock(pairs) - lock, err := s.decodeLock(lockPair) - if err != nil { - return - } - s.pruneDeadHolders(lock, pairs) - if _, ok := lock.Holders[session]; ok { - opts.WaitIndex = meta.LastIndex - goto WAIT - } -} diff --git a/vendor/github.com/hashicorp/consul/api/session.go b/vendor/github.com/hashicorp/consul/api/session.go deleted file mode 100644 index 1613f11a6..000000000 --- a/vendor/github.com/hashicorp/consul/api/session.go +++ /dev/null @@ -1,224 +0,0 @@ -package api - -import ( - "errors" - "fmt" - "time" -) - -const ( - // SessionBehaviorRelease is the default behavior and causes - // all associated locks to be released on session invalidation. - SessionBehaviorRelease = "release" - - // SessionBehaviorDelete is new in Consul 0.5 and changes the - // behavior to delete all associated locks on session invalidation. - // It can be used in a way similar to Ephemeral Nodes in ZooKeeper. - SessionBehaviorDelete = "delete" -) - -var ErrSessionExpired = errors.New("session expired") - -// SessionEntry represents a session in consul -type SessionEntry struct { - CreateIndex uint64 - ID string - Name string - Node string - Checks []string - LockDelay time.Duration - Behavior string - TTL string -} - -// Session can be used to query the Session endpoints -type Session struct { - c *Client -} - -// Session returns a handle to the session endpoints -func (c *Client) Session() *Session { - return &Session{c} -} - -// CreateNoChecks is like Create but is used specifically to create -// a session with no associated health checks. -func (s *Session) CreateNoChecks(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error) { - body := make(map[string]interface{}) - body["Checks"] = []string{} - if se != nil { - if se.Name != "" { - body["Name"] = se.Name - } - if se.Node != "" { - body["Node"] = se.Node - } - if se.LockDelay != 0 { - body["LockDelay"] = durToMsec(se.LockDelay) - } - if se.Behavior != "" { - body["Behavior"] = se.Behavior - } - if se.TTL != "" { - body["TTL"] = se.TTL - } - } - return s.create(body, q) - -} - -// Create makes a new session. Providing a session entry can -// customize the session. It can also be nil to use defaults. -func (s *Session) Create(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error) { - var obj interface{} - if se != nil { - body := make(map[string]interface{}) - obj = body - if se.Name != "" { - body["Name"] = se.Name - } - if se.Node != "" { - body["Node"] = se.Node - } - if se.LockDelay != 0 { - body["LockDelay"] = durToMsec(se.LockDelay) - } - if len(se.Checks) > 0 { - body["Checks"] = se.Checks - } - if se.Behavior != "" { - body["Behavior"] = se.Behavior - } - if se.TTL != "" { - body["TTL"] = se.TTL - } - } - return s.create(obj, q) -} - -func (s *Session) create(obj interface{}, q *WriteOptions) (string, *WriteMeta, error) { - var out struct{ ID string } - wm, err := s.c.write("/v1/session/create", obj, &out, q) - if err != nil { - return "", nil, err - } - return out.ID, wm, nil -} - -// Destroy invalidates a given session -func (s *Session) Destroy(id string, q *WriteOptions) (*WriteMeta, error) { - wm, err := s.c.write("/v1/session/destroy/"+id, nil, nil, q) - if err != nil { - return nil, err - } - return wm, nil -} - -// Renew renews the TTL on a given session -func (s *Session) Renew(id string, q *WriteOptions) (*SessionEntry, *WriteMeta, error) { - r := s.c.newRequest("PUT", "/v1/session/renew/"+id) - r.setWriteOptions(q) - rtt, resp, err := s.c.doRequest(r) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - wm := &WriteMeta{RequestTime: rtt} - - if resp.StatusCode == 404 { - return nil, wm, nil - } else if resp.StatusCode != 200 { - return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode) - } - - var entries []*SessionEntry - if err := decodeBody(resp, &entries); err != nil { - return nil, nil, fmt.Errorf("Failed to read response: %v", err) - } - if len(entries) > 0 { - return entries[0], wm, nil - } - return nil, wm, nil -} - -// RenewPeriodic is used to periodically invoke Session.Renew on a -// session until a doneCh is closed. This is meant to be used in a long running -// goroutine to ensure a session stays valid. -func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh <-chan struct{}) error { - ctx := q.Context() - - ttl, err := time.ParseDuration(initialTTL) - if err != nil { - return err - } - - waitDur := ttl / 2 - lastRenewTime := time.Now() - var lastErr error - for { - if time.Since(lastRenewTime) > ttl { - return lastErr - } - select { - case <-time.After(waitDur): - entry, _, err := s.Renew(id, q) - if err != nil { - waitDur = time.Second - lastErr = err - continue - } - if entry == nil { - return ErrSessionExpired - } - - // Handle the server updating the TTL - ttl, _ = time.ParseDuration(entry.TTL) - waitDur = ttl / 2 - lastRenewTime = time.Now() - - case <-doneCh: - // Attempt a session destroy - s.Destroy(id, q) - return nil - - case <-ctx.Done(): - // Bail immediately since attempting the destroy would - // use the canceled context in q, which would just bail. - return ctx.Err() - } - } -} - -// Info looks up a single session -func (s *Session) Info(id string, q *QueryOptions) (*SessionEntry, *QueryMeta, error) { - var entries []*SessionEntry - qm, err := s.c.query("/v1/session/info/"+id, &entries, q) - if err != nil { - return nil, nil, err - } - if len(entries) > 0 { - return entries[0], qm, nil - } - return nil, qm, nil -} - -// List gets sessions for a node -func (s *Session) Node(node string, q *QueryOptions) ([]*SessionEntry, *QueryMeta, error) { - var entries []*SessionEntry - qm, err := s.c.query("/v1/session/node/"+node, &entries, q) - if err != nil { - return nil, nil, err - } - return entries, qm, nil -} - -// List gets all active sessions -func (s *Session) List(q *QueryOptions) ([]*SessionEntry, *QueryMeta, error) { - var entries []*SessionEntry - qm, err := s.c.query("/v1/session/list", &entries, q) - if err != nil { - return nil, nil, err - } - return entries, qm, nil -} diff --git a/vendor/github.com/hashicorp/consul/api/snapshot.go b/vendor/github.com/hashicorp/consul/api/snapshot.go deleted file mode 100644 index e902377dd..000000000 --- a/vendor/github.com/hashicorp/consul/api/snapshot.go +++ /dev/null @@ -1,47 +0,0 @@ -package api - -import ( - "io" -) - -// Snapshot can be used to query the /v1/snapshot endpoint to take snapshots of -// Consul's internal state and restore snapshots for disaster recovery. -type Snapshot struct { - c *Client -} - -// Snapshot returns a handle that exposes the snapshot endpoints. -func (c *Client) Snapshot() *Snapshot { - return &Snapshot{c} -} - -// Save requests a new snapshot and provides an io.ReadCloser with the snapshot -// data to save. If this doesn't return an error, then it's the responsibility -// of the caller to close it. Only a subset of the QueryOptions are supported: -// Datacenter, AllowStale, and Token. -func (s *Snapshot) Save(q *QueryOptions) (io.ReadCloser, *QueryMeta, error) { - r := s.c.newRequest("GET", "/v1/snapshot") - r.setQueryOptions(q) - - rtt, resp, err := requireOK(s.c.doRequest(r)) - if err != nil { - return nil, nil, err - } - - qm := &QueryMeta{} - parseQueryMeta(resp, qm) - qm.RequestTime = rtt - return resp.Body, qm, nil -} - -// Restore streams in an existing snapshot and attempts to restore it. -func (s *Snapshot) Restore(q *WriteOptions, in io.Reader) error { - r := s.c.newRequest("PUT", "/v1/snapshot") - r.body = in - r.setWriteOptions(q) - _, _, err := requireOK(s.c.doRequest(r)) - if err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/hashicorp/consul/api/status.go b/vendor/github.com/hashicorp/consul/api/status.go deleted file mode 100644 index 74ef61a67..000000000 --- a/vendor/github.com/hashicorp/consul/api/status.go +++ /dev/null @@ -1,43 +0,0 @@ -package api - -// Status can be used to query the Status endpoints -type Status struct { - c *Client -} - -// Status returns a handle to the status endpoints -func (c *Client) Status() *Status { - return &Status{c} -} - -// Leader is used to query for a known leader -func (s *Status) Leader() (string, error) { - r := s.c.newRequest("GET", "/v1/status/leader") - _, resp, err := requireOK(s.c.doRequest(r)) - if err != nil { - return "", err - } - defer resp.Body.Close() - - var leader string - if err := decodeBody(resp, &leader); err != nil { - return "", err - } - return leader, nil -} - -// Peers is used to query for a known raft peers -func (s *Status) Peers() ([]string, error) { - r := s.c.newRequest("GET", "/v1/status/peers") - _, resp, err := requireOK(s.c.doRequest(r)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var peers []string - if err := decodeBody(resp, &peers); err != nil { - return nil, err - } - return peers, nil -} diff --git a/vendor/github.com/hashicorp/errwrap/README.md b/vendor/github.com/hashicorp/errwrap/README.md index 1c95f5978..444df08f8 100644 --- a/vendor/github.com/hashicorp/errwrap/README.md +++ b/vendor/github.com/hashicorp/errwrap/README.md @@ -48,7 +48,7 @@ func main() { // We can use the Contains helpers to check if an error contains // another error. It is safe to do this with a nil error, or with // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, ErrNotExist) { + if errwrap.Contains(err, "does not exist") { // Do something } if errwrap.ContainsType(err, new(os.PathError)) { diff --git a/vendor/github.com/hashicorp/errwrap/go.mod b/vendor/github.com/hashicorp/errwrap/go.mod new file mode 100644 index 000000000..c9b84022c --- /dev/null +++ b/vendor/github.com/hashicorp/errwrap/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/errwrap diff --git a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go b/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go index 7d8a57c28..8d306bf51 100644 --- a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go +++ b/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go @@ -26,6 +26,7 @@ func DefaultPooledTransport() *http.Transport { DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, + DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, diff --git a/vendor/github.com/hashicorp/go-cleanhttp/go.mod b/vendor/github.com/hashicorp/go-cleanhttp/go.mod new file mode 100644 index 000000000..310f07569 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cleanhttp/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/go-cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go b/vendor/github.com/hashicorp/go-cleanhttp/handlers.go new file mode 100644 index 000000000..3c845dc0d --- /dev/null +++ b/vendor/github.com/hashicorp/go-cleanhttp/handlers.go @@ -0,0 +1,48 @@ +package cleanhttp + +import ( + "net/http" + "strings" + "unicode" +) + +// HandlerInput provides input options to cleanhttp's handlers +type HandlerInput struct { + ErrStatus int +} + +// PrintablePathCheckHandler is a middleware that ensures the request path +// contains only printable runes. +func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { + // Nil-check on input to make it optional + if input == nil { + input = &HandlerInput{ + ErrStatus: http.StatusBadRequest, + } + } + + // Default to http.StatusBadRequest on error + if input.ErrStatus == 0 { + input.ErrStatus = http.StatusBadRequest + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r != nil { + // Check URL path for non-printable characters + idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { + return !unicode.IsPrint(c) + }) + + if idx != -1 { + w.WriteHeader(input.ErrStatus) + return + } + + if next != nil { + next.ServeHTTP(w, r) + } + } + + return + }) +} diff --git a/vendor/github.com/hashicorp/go-gcp-common/LICENSE b/vendor/github.com/hashicorp/go-gcp-common/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/go-gcp-common/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-gcp-common/gcputil/compute.go b/vendor/github.com/hashicorp/go-gcp-common/gcputil/compute.go deleted file mode 100644 index f318ecef9..000000000 --- a/vendor/github.com/hashicorp/go-gcp-common/gcputil/compute.go +++ /dev/null @@ -1,111 +0,0 @@ -package gcputil - -import ( - "fmt" - "google.golang.org/api/compute/v1" - "regexp" - "time" -) - -func ParseGcpLabels(labels []string) (parsed map[string]string, invalid []string) { - parsed = map[string]string{} - invalid = []string{} - - re := regexp.MustCompile(labelRegex) - for _, labelStr := range labels { - matches := re.FindStringSubmatch(labelStr) - if len(matches) == 0 { - invalid = append(invalid, labelStr) - continue - } - - captureNames := re.SubexpNames() - var keyPtr, valPtr *string - for i, name := range captureNames { - if name == "key" { - keyPtr = &matches[i] - } else if name == "value" { - valPtr = &matches[i] - } - } - - if keyPtr == nil || valPtr == nil || len(*keyPtr) < 1 { - invalid = append(invalid, labelStr) - continue - } else { - parsed[*keyPtr] = *valPtr - } - } - - return parsed, invalid -} - -type CustomJWTClaims struct { - Google *GoogleJWTClaims `json:"google,omitempty"` -} - -type GoogleJWTClaims struct { - Compute *GCEIdentityMetadata `json:"compute_engine,omitempty"` -} - -type GCEIdentityMetadata struct { - // ProjectId is the ID for the project where you created the instance. - ProjectId string `json:"project_id" structs:"project_id" mapstructure:"project_id"` - - // ProjectNumber is the unique ID for the project where you created the instance. - ProjectNumber int64 `json:"project_number" structs:"project_number" mapstructure:"project_number"` - - // Zone is the zone where the instance is located. - Zone string `json:"zone" structs:"zone" mapstructure:"zone"` - - // InstanceId is the unique ID for the instance to which this token belongs. This ID is unique and never reused. - InstanceId string `json:"instance_id" structs:"instance_id" mapstructure:"instance_id"` - - // InstanceName is the name of the instance to which this token belongs. This name can be reused by several - // instances over time, so use the instance_id value to identify a unique instance ID. - InstanceName string `json:"instance_name" structs:"instance_name" mapstructure:"instance_name"` - - // CreatedAt is a unix timestamp indicating when you created the instance. - CreatedAt int64 `json:"instance_creation_timestamp" structs:"instance_creation_timestamp" mapstructure:"instance_creation_timestamp"` -} - -// GetVerifiedInstance returns the Instance as described by the identity metadata or an error. -// If the instance has an invalid status or its creation timestamp does not match the metadata value, -// this will return nil and an error. -func (meta *GCEIdentityMetadata) GetVerifiedInstance(gceClient *compute.Service) (*compute.Instance, error) { - instance, err := gceClient.Instances.Get(meta.ProjectId, meta.Zone, meta.InstanceName).Do() - if err != nil { - return nil, fmt.Errorf("unable to find instance associated with token: %v", err) - } - - if !IsValidInstanceStatus(instance.Status) { - return nil, fmt.Errorf("authenticating instance %s found but has invalid status '%s'", instance.Name, instance.Status) - } - - // Parse the metadata CreatedAt into time. - metaTime := time.Unix(meta.CreatedAt, 0) - - // Parse instance creationTimestamp into time. - actualTime, err := time.Parse(time.RFC3339Nano, instance.CreationTimestamp) - if err != nil { - return nil, fmt.Errorf("instance 'creationTimestamp' field could not be parsed into time: %s", instance.CreationTimestamp) - } - - // Return an error if the metadata creation timestamp is before the instance creation timestamp. - delta := float64(metaTime.Sub(actualTime)) / float64(time.Second) - if delta < -1 { - return nil, fmt.Errorf("metadata instance_creation_timestamp %d is before instance's creation time %d", actualTime.Unix(), metaTime.Unix()) - } - return instance, nil -} - -var validInstanceStates map[string]struct{} = map[string]struct{}{ - "PROVISIONING": struct{}{}, - "RUNNING": struct{}{}, - "STAGING": struct{}{}, -} - -func IsValidInstanceStatus(status string) bool { - _, ok := validInstanceStates[status] - return ok -} diff --git a/vendor/github.com/hashicorp/go-gcp-common/gcputil/credentials.go b/vendor/github.com/hashicorp/go-gcp-common/gcputil/credentials.go deleted file mode 100644 index fc902eef3..000000000 --- a/vendor/github.com/hashicorp/go-gcp-common/gcputil/credentials.go +++ /dev/null @@ -1,178 +0,0 @@ -package gcputil - -import ( - "context" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "github.com/hashicorp/go-cleanhttp" - "github.com/mitchellh/go-homedir" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - googleoauth2 "google.golang.org/api/oauth2/v2" - "gopkg.in/square/go-jose.v2" - "io/ioutil" - "net/http" - "os" - "path/filepath" - "strings" -) - -const ( - labelRegex string = "^(?P[a-z]([\\w-]+)?):(?P[\\w-]*)$" - defaultHomeCredentialsFile = ".gcp/credentials" -) - -// GcpCredentials represents a simplified version of the Google Cloud Platform credentials file format. -type GcpCredentials struct { - ClientEmail string `json:"client_email" structs:"client_email" mapstructure:"client_email"` - ClientId string `json:"client_id" structs:"client_id" mapstructure:"client_id"` - PrivateKeyId string `json:"private_key_id" structs:"private_key_id" mapstructure:"private_key_id"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` - ProjectId string `json:"project_id" structs:"project_id" mapstructure:"project_id"` -} - -// FindCredentials attempts to obtain GCP credentials in the -// following ways: -// * Parse JSON from provided credentialsJson -// * Parse JSON from the environment variables GOOGLE_CREDENTIALS or GOOGLE_CLOUD_KEYFILE_JSON -// * Parse JSON file ~/.gcp/credentials -// * Google Application Default Credentials (see https://developers.google.com/identity/protocols/application-default-credentials) -func FindCredentials(credsJson string, ctx context.Context, scopes ...string) (*GcpCredentials, oauth2.TokenSource, error) { - var creds *GcpCredentials - var err error - // 1. Parse JSON from provided credentialsJson - if credsJson == "" { - // 2. JSON from env var GOOGLE_CREDENTIALS - credsJson = os.Getenv("GOOGLE_CREDENTIALS") - } - - if credsJson == "" { - // 3. JSON from env var GOOGLE_CLOUD_KEYFILE_JSON - credsJson = os.Getenv("GOOGLE_CLOUD_KEYFILE_JSON") - } - - if credsJson == "" { - // 4. JSON from ~/.gcp/credentials - home, err := homedir.Dir() - if err != nil { - return nil, nil, errors.New("could not find home directory") - } - credBytes, err := ioutil.ReadFile(filepath.Join(home, defaultHomeCredentialsFile)) - if err == nil { - credsJson = string(credBytes) - } - } - - // Parse JSON into credentials. - if credsJson != "" { - creds, err = Credentials(credsJson) - if err == nil { - conf := jwt.Config{ - Email: creds.ClientEmail, - PrivateKey: []byte(creds.PrivateKey), - Scopes: scopes, - TokenURL: "https://accounts.google.com/o/oauth2/token", - } - return creds, conf.TokenSource(ctx), nil - } - } - - // 5. Use Application default credentials. - defaultCreds, err := google.FindDefaultCredentials(ctx, scopes...) - if err != nil { - return nil, nil, err - } - - if defaultCreds.JSON != nil { - creds, err = Credentials(string(defaultCreds.JSON)) - if err != nil { - return nil, nil, errors.New("could not read credentials from application default credential JSON") - } - } - - return creds, defaultCreds.TokenSource, nil -} - -// Credentials attempts to parse GcpCredentials from a JSON string. -func Credentials(credentialsJson string) (*GcpCredentials, error) { - credentials := &GcpCredentials{} - if err := json.Unmarshal([]byte(credentialsJson), &credentials); err != nil { - return nil, err - } - return credentials, nil -} - -// GetHttpClient creates an HTTP client from the given Google credentials and scopes. -func GetHttpClient(credentials *GcpCredentials, clientScopes ...string) (*http.Client, error) { - conf := jwt.Config{ - Email: credentials.ClientEmail, - PrivateKey: []byte(credentials.PrivateKey), - Scopes: clientScopes, - TokenURL: "https://accounts.google.com/o/oauth2/token", - } - - ctx := context.WithValue(context.Background(), oauth2.HTTPClient, cleanhttp.DefaultClient()) - client := conf.Client(ctx) - return client, nil -} - -// PublicKey returns a public key from a Google PEM key file (type TYPE_X509_PEM_FILE). -func PublicKey(pemString string) (interface{}, error) { - pemBytes, err := base64.StdEncoding.DecodeString(pemString) - if err != nil { - return nil, err - } - - block, _ := pem.Decode(pemBytes) - if block == nil { - return nil, errors.New("Unable to find pem block in key") - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - - return cert.PublicKey, nil -} - -// OAuth2RSAPublicKey returns the PEM key file string for Google Oauth2 public cert for the given 'kid' id. -func OAuth2RSAPublicKey(kid, oauth2BasePath string) (interface{}, error) { - oauth2Client, err := googleoauth2.New(cleanhttp.DefaultClient()) - if err != nil { - return "", err - } - - if len(oauth2BasePath) > 0 { - oauth2Client.BasePath = oauth2BasePath - } - - jwks, err := oauth2Client.GetCertForOpenIdConnect().Do() - if err != nil { - return nil, err - } - - for _, key := range jwks.Keys { - if key.Kid == kid && jose.SignatureAlgorithm(key.Alg) == jose.RS256 { - // Trim extra '=' from key so it can be parsed. - key.N = strings.TrimRight(key.N, "=") - js, err := key.MarshalJSON() - if err != nil { - return nil, fmt.Errorf("unable to marshal json %v", err) - } - key := &jose.JSONWebKey{} - if err := key.UnmarshalJSON(js); err != nil { - return nil, fmt.Errorf("unable to unmarshal json %v", err) - } - - return key.Key, nil - } - } - - return nil, fmt.Errorf("could not find public key with kid '%s'", kid) -} diff --git a/vendor/github.com/hashicorp/go-gcp-common/gcputil/iam_admin.go b/vendor/github.com/hashicorp/go-gcp-common/gcputil/iam_admin.go deleted file mode 100644 index 59baf3866..000000000 --- a/vendor/github.com/hashicorp/go-gcp-common/gcputil/iam_admin.go +++ /dev/null @@ -1,51 +0,0 @@ -package gcputil - -import ( - "fmt" - "google.golang.org/api/iam/v1" -) - -const ( - ServiceAccountTemplate = "projects/%s/serviceAccounts/%s" - ServiceAccountKeyTemplate = "projects/%s/serviceAccounts/%s/keys/%s" - ServiceAccountKeyFileType = "TYPE_X509_PEM_FILE" -) - -type ServiceAccountId struct { - Project string - EmailOrId string -} - -func (id *ServiceAccountId) ResourceName() string { - return fmt.Sprintf(ServiceAccountTemplate, id.Project, id.EmailOrId) -} - -type ServiceAccountKeyId struct { - Project string - EmailOrId string - Key string -} - -func (id *ServiceAccountKeyId) ResourceName() string { - return fmt.Sprintf(ServiceAccountKeyTemplate, id.Project, id.EmailOrId, id.Key) -} - -// ServiceAccount wraps a call to the GCP IAM API to get a service account. -func ServiceAccount(iamClient *iam.Service, accountId *ServiceAccountId) (*iam.ServiceAccount, error) { - account, err := iamClient.Projects.ServiceAccounts.Get(accountId.ResourceName()).Do() - if err != nil { - return nil, fmt.Errorf("could not find service account '%s': %v", accountId.ResourceName(), err) - } - - return account, nil -} - -// ServiceAccountKey wraps a call to the GCP IAM API to get a service account key. -func ServiceAccountKey(iamClient *iam.Service, keyId *ServiceAccountKeyId) (*iam.ServiceAccountKey, error) { - keyResource := keyId.ResourceName() - key, err := iamClient.Projects.ServiceAccounts.Keys.Get(keyId.ResourceName()).PublicKeyType(ServiceAccountKeyFileType).Do() - if err != nil { - return nil, fmt.Errorf("could not find service account key '%s': %v", keyResource, err) - } - return key, nil -} diff --git a/vendor/github.com/hashicorp/go-gcp-common/gcputil/resource_name.go b/vendor/github.com/hashicorp/go-gcp-common/gcputil/resource_name.go deleted file mode 100644 index 8ba03b044..000000000 --- a/vendor/github.com/hashicorp/go-gcp-common/gcputil/resource_name.go +++ /dev/null @@ -1,128 +0,0 @@ -package gcputil - -import ( - "fmt" - "net/url" - "regexp" - "strings" -) - -const ( - resourceIdRegex = "^[^\t\n\f\r]+$" - collectionIdRegex = "^[a-z][a-zA-Z]*$" - - fullResourceNameRegex = "^//([a-z]+).googleapis.com/(.+)$" - selfLinkMarker = "projects/" -) - -var singleCollectionIds = map[string]struct{}{ - "global": {}, -} - -type RelativeResourceName struct { - Name string - TypeKey string - IdTuples map[string]string - OrderedCollectionIds []string -} - -func ParseRelativeName(resource string) (*RelativeResourceName, error) { - resourceRe := regexp.MustCompile(resourceIdRegex) - collectionRe := regexp.MustCompile(collectionIdRegex) - - tokens := strings.Split(resource, "/") - if len(tokens) < 2 { - return nil, fmt.Errorf("invalid relative resource name %s (too few tokens)", resource) - } - - ids := map[string]string{} - typeKey := "" - currColId := "" - for idx, v := range tokens { - if len(currColId) == 0 { - if _, ok := singleCollectionIds[v]; ok { - // Ignore 'single' collectionIds like Global, but error if they are the last ID - if idx == len(tokens)-1 { - return nil, fmt.Errorf("invalid relative resource name %s (last collection '%s' has no ID)", resource, currColId) - } - continue - } - if len(collectionRe.FindAllString(v, 1)) == 0 { - return nil, fmt.Errorf("invalid relative resource name %s (invalid collection ID %s)", resource, v) - } - currColId = v - typeKey += currColId + "/" - } else { - if len(resourceRe.FindAllString(v, 1)) == 0 { - return nil, fmt.Errorf("invalid relative resource name %s (invalid resource sub-ID %s)", resource, v) - } - ids[currColId] = v - currColId = "" - } - } - - typeKey = typeKey[:len(typeKey)-1] - collectionIds := strings.Split(typeKey, "/") - resourceName := tokens[len(tokens)-2] - return &RelativeResourceName{ - Name: resourceName, - TypeKey: typeKey, - OrderedCollectionIds: collectionIds, - IdTuples: ids, - }, nil -} - -type FullResourceName struct { - Service string - *RelativeResourceName -} - -func ParseFullResourceName(name string) (*FullResourceName, error) { - fullRe := regexp.MustCompile(fullResourceNameRegex) - matches := fullRe.FindAllStringSubmatch(name, 1) - if len(matches) == 0 { - return nil, fmt.Errorf("invalid full name '%s'", name) - } - - if len(matches[0]) != 3 { - return nil, fmt.Errorf("invalid full name '%s'", name) - } - - serviceName := matches[0][1] - relName, err := ParseRelativeName(strings.Trim(matches[0][2], "/")) - if err != nil { - return nil, fmt.Errorf("error parsing relative resource path in full resource name '%s': %v", name, err) - } - - return &FullResourceName{ - Service: serviceName, - RelativeResourceName: relName, - }, nil -} - -type SelfLink struct { - Prefix string - *RelativeResourceName -} - -func ParseProjectResourceSelfLink(link string) (*SelfLink, error) { - u, err := url.Parse(link) - if err != nil || u.Scheme == "" || u.Host == "" { - return nil, fmt.Errorf("invalid self link '%s' must have scheme/host", link) - } - - split := strings.SplitAfterN(link, selfLinkMarker, 2) - if len(split) != 2 { - return nil, fmt.Errorf("self link '%s' is not for project-level resource, must contain '%s')", link, selfLinkMarker) - } - - relName, err := ParseRelativeName(selfLinkMarker + split[1]) - if err != nil { - return nil, fmt.Errorf("error parsing relative resource path in self-link '%s': %v", link, err) - } - - return &SelfLink{ - Prefix: strings.TrimSuffix(split[0], selfLinkMarker), - RelativeResourceName: relName, - }, nil -} diff --git a/vendor/github.com/hashicorp/go-getter/.travis.yml b/vendor/github.com/hashicorp/go-getter/.travis.yml new file mode 100644 index 000000000..4fe9176aa --- /dev/null +++ b/vendor/github.com/hashicorp/go-getter/.travis.yml @@ -0,0 +1,24 @@ +sudo: false + +addons: + apt: + sources: + - sourceline: 'ppa:git-core/ppa' + packages: + - git + +language: go + +os: + - linux + - osx + +go: + - "1.11.x" + +before_script: + - go build ./cmd/go-getter + +branches: + only: + - master diff --git a/vendor/github.com/hashicorp/go-hclog/.gitignore b/vendor/github.com/hashicorp/go-hclog/.gitignore new file mode 100644 index 000000000..42cc4105f --- /dev/null +++ b/vendor/github.com/hashicorp/go-hclog/.gitignore @@ -0,0 +1 @@ +.idea* \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-hclog/README.md b/vendor/github.com/hashicorp/go-hclog/README.md index 1153e2853..9b6845e98 100644 --- a/vendor/github.com/hashicorp/go-hclog/README.md +++ b/vendor/github.com/hashicorp/go-hclog/README.md @@ -128,6 +128,21 @@ stdLogger.Printf("[DEBUG] %+v", stdLogger) ... [DEBUG] my-app: &{mu:{state:0 sema:0} prefix: flag:0 out:0xc42000a0a0 buf:[]} ``` +Alternatively, you may configure the system-wide logger: + +```go +// log the standard logger from 'import "log"' +log.SetOutput(appLogger.Writer(&hclog.StandardLoggerOptions{InferLevels: true})) +log.SetPrefix("") +log.SetFlags(0) + +log.Printf("[DEBUG] %d", 42) +``` + +```text +... [DEBUG] my-app: 42 +``` + Notice that if `appLogger` is initialized with the `INFO` log level _and_ you specify `InferLevels: true`, you will not see any output here. You must change `appLogger` to `DEBUG` to see output. See the docs for more information. diff --git a/vendor/github.com/hashicorp/go-hclog/global.go b/vendor/github.com/hashicorp/go-hclog/global.go index 55ce43960..e5f7f95ff 100644 --- a/vendor/github.com/hashicorp/go-hclog/global.go +++ b/vendor/github.com/hashicorp/go-hclog/global.go @@ -8,16 +8,16 @@ var ( protect sync.Once def Logger - // The options used to create the Default logger. These are - // read only when the Default logger is created, so set them - // as soon as the process starts. + // DefaultOptions is used to create the Default logger. These are read + // only when the Default logger is created, so set them as soon as the + // process starts. DefaultOptions = &LoggerOptions{ Level: DefaultLevel, Output: DefaultOutput, } ) -// Return a logger that is held globally. This can be a good starting +// Default returns a globally held logger. This can be a good starting // place, and then you can use .With() and .Name() to create sub-loggers // to be used in more specific contexts. func Default() Logger { @@ -28,7 +28,7 @@ func Default() Logger { return def } -// A short alias for Default() +// L is a short alias for Default(). func L() Logger { return Default() } diff --git a/vendor/github.com/hashicorp/go-hclog/int.go b/vendor/github.com/hashicorp/go-hclog/intlogger.go similarity index 57% rename from vendor/github.com/hashicorp/go-hclog/int.go rename to vendor/github.com/hashicorp/go-hclog/intlogger.go index 7d17d81cb..d32630c29 100644 --- a/vendor/github.com/hashicorp/go-hclog/int.go +++ b/vendor/github.com/hashicorp/go-hclog/intlogger.go @@ -1,12 +1,13 @@ package hclog import ( - "bufio" + "bytes" "encoding" "encoding/json" "fmt" + "io" "log" - "os" + "reflect" "runtime" "sort" "strconv" @@ -16,17 +17,41 @@ import ( "time" ) +// TimeFormat to use for logging. This is a version of RFC3339 that contains +// contains millisecond precision +const TimeFormat = "2006-01-02T15:04:05.000Z0700" + var ( _levelToBracket = map[Level]string{ Debug: "[DEBUG]", Trace: "[TRACE]", - Info: "[INFO ]", - Warn: "[WARN ]", + Info: "[INFO] ", + Warn: "[WARN] ", Error: "[ERROR]", } ) -// Given the options (nil for defaults), create a new Logger +// Make sure that intLogger is a Logger +var _ Logger = &intLogger{} + +// intLogger is an internal logger implementation. Internal in that it is +// defined entirely by this package. +type intLogger struct { + json bool + caller bool + name string + timeFormat string + + // This is a pointer so that it's shared by any derived loggers, since + // those derived loggers share the bufio.Writer as well. + mutex *sync.Mutex + writer *writer + level *int32 + + implied []interface{} +} + +// New returns a configured logger. func New(opts *LoggerOptions) Logger { if opts == nil { opts = &LoggerOptions{} @@ -34,7 +59,7 @@ func New(opts *LoggerOptions) Logger { output := opts.Output if output == nil { - output = os.Stderr + output = DefaultOutput } level := opts.Level @@ -42,70 +67,49 @@ func New(opts *LoggerOptions) Logger { level = DefaultLevel } - mtx := opts.Mutex - if mtx == nil { - mtx = new(sync.Mutex) + mutex := opts.Mutex + if mutex == nil { + mutex = new(sync.Mutex) } - ret := &intLogger{ - m: mtx, + l := &intLogger{ json: opts.JSONFormat, caller: opts.IncludeLocation, name: opts.Name, timeFormat: TimeFormat, - w: bufio.NewWriter(output), + mutex: mutex, + writer: newWriter(output), level: new(int32), } + if opts.TimeFormat != "" { - ret.timeFormat = opts.TimeFormat + l.timeFormat = opts.TimeFormat } - atomic.StoreInt32(ret.level, int32(level)) - return ret -} -// The internal logger implementation. Internal in that it is defined entirely -// by this package. -type intLogger struct { - json bool - caller bool - name string - timeFormat string - - // this is a pointer so that it's shared by any derived loggers, since - // those derived loggers share the bufio.Writer as well. - m *sync.Mutex - w *bufio.Writer - level *int32 + atomic.StoreInt32(l.level, int32(level)) - implied []interface{} + return l } -// Make sure that intLogger is a Logger -var _ Logger = &intLogger{} - -// The time format to use for logging. This is a version of RFC3339 that -// contains millisecond precision -const TimeFormat = "2006-01-02T15:04:05.000Z0700" - // Log a message and a set of key/value pairs if the given level is at // or more severe that the threshold configured in the Logger. -func (z *intLogger) Log(level Level, msg string, args ...interface{}) { - if level < Level(atomic.LoadInt32(z.level)) { +func (l *intLogger) Log(level Level, msg string, args ...interface{}) { + if level < Level(atomic.LoadInt32(l.level)) { return } t := time.Now() - z.m.Lock() - defer z.m.Unlock() + l.mutex.Lock() + defer l.mutex.Unlock() - if z.json { - z.logJson(t, level, msg, args...) + if l.json { + l.logJSON(t, level, msg, args...) } else { - z.log(t, level, msg, args...) + l.log(t, level, msg, args...) } - z.w.Flush() + l.writer.Flush(level) } // Cleanup a path by returning the last 2 segments of the path only. @@ -121,10 +125,8 @@ func trimCallerPath(path string) string { // and https://github.com/golang/go/issues/18151 // // for discussion on the issue on Go side. - // // Find the last separator. - // idx := strings.LastIndexByte(path, '/') if idx == -1 { return path @@ -140,37 +142,37 @@ func trimCallerPath(path string) string { } // Non-JSON logging format function -func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { - z.w.WriteString(t.Format(z.timeFormat)) - z.w.WriteByte(' ') +func (l *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { + l.writer.WriteString(t.Format(l.timeFormat)) + l.writer.WriteByte(' ') s, ok := _levelToBracket[level] if ok { - z.w.WriteString(s) + l.writer.WriteString(s) } else { - z.w.WriteString("[UNKN ]") + l.writer.WriteString("[?????]") } - if z.caller { + if l.caller { if _, file, line, ok := runtime.Caller(3); ok { - z.w.WriteByte(' ') - z.w.WriteString(trimCallerPath(file)) - z.w.WriteByte(':') - z.w.WriteString(strconv.Itoa(line)) - z.w.WriteByte(':') + l.writer.WriteByte(' ') + l.writer.WriteString(trimCallerPath(file)) + l.writer.WriteByte(':') + l.writer.WriteString(strconv.Itoa(line)) + l.writer.WriteByte(':') } } - z.w.WriteByte(' ') + l.writer.WriteByte(' ') - if z.name != "" { - z.w.WriteString(z.name) - z.w.WriteString(": ") + if l.name != "" { + l.writer.WriteString(l.name) + l.writer.WriteString(": ") } - z.w.WriteString(msg) + l.writer.WriteString(msg) - args = append(z.implied, args...) + args = append(l.implied, args...) var stacktrace CapturedStacktrace @@ -185,11 +187,14 @@ func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{ } } - z.w.WriteByte(':') + l.writer.WriteByte(':') FOR: for i := 0; i < len(args); i = i + 2 { - var val string + var ( + val string + raw bool + ) switch st := args[i+1].(type) { case string: @@ -220,32 +225,77 @@ func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{ case Format: val = fmt.Sprintf(st[0].(string), st[1:]...) default: - val = fmt.Sprintf("%v", st) + v := reflect.ValueOf(st) + if v.Kind() == reflect.Slice { + val = l.renderSlice(v) + raw = true + } else { + val = fmt.Sprintf("%v", st) + } } - z.w.WriteByte(' ') - z.w.WriteString(args[i].(string)) - z.w.WriteByte('=') + l.writer.WriteByte(' ') + l.writer.WriteString(args[i].(string)) + l.writer.WriteByte('=') - if strings.ContainsAny(val, " \t\n\r") { - z.w.WriteByte('"') - z.w.WriteString(val) - z.w.WriteByte('"') + if !raw && strings.ContainsAny(val, " \t\n\r") { + l.writer.WriteByte('"') + l.writer.WriteString(val) + l.writer.WriteByte('"') } else { - z.w.WriteString(val) + l.writer.WriteString(val) } } } - z.w.WriteString("\n") + l.writer.WriteString("\n") if stacktrace != "" { - z.w.WriteString(string(stacktrace)) + l.writer.WriteString(string(stacktrace)) + } +} + +func (l *intLogger) renderSlice(v reflect.Value) string { + var buf bytes.Buffer + + buf.WriteRune('[') + + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteString(", ") + } + + sv := v.Index(i) + + var val string + + switch sv.Kind() { + case reflect.String: + val = sv.String() + case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: + val = strconv.FormatInt(sv.Int(), 10) + case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + val = strconv.FormatUint(sv.Uint(), 10) + default: + val = fmt.Sprintf("%v", sv.Interface()) + } + + if strings.ContainsAny(val, " \t\n\r") { + buf.WriteByte('"') + buf.WriteString(val) + buf.WriteByte('"') + } else { + buf.WriteString(val) + } } + + buf.WriteRune(']') + + return buf.String() } // JSON logging function -func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) { +func (l *intLogger) logJSON(t time.Time, level Level, msg string, args ...interface{}) { vals := map[string]interface{}{ "@message": msg, "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"), @@ -269,17 +319,17 @@ func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interf vals["@level"] = levelStr - if z.name != "" { - vals["@module"] = z.name + if l.name != "" { + vals["@module"] = l.name } - if z.caller { + if l.caller { if _, file, line, ok := runtime.Caller(3); ok { vals["@caller"] = fmt.Sprintf("%s:%d", file, line) } } - args = append(z.implied, args...) + args = append(l.implied, args...) if args != nil && len(args) > 0 { if len(args)%2 != 0 { @@ -317,80 +367,80 @@ func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interf } } - err := json.NewEncoder(z.w).Encode(vals) + err := json.NewEncoder(l.writer).Encode(vals) if err != nil { panic(err) } } // Emit the message and args at DEBUG level -func (z *intLogger) Debug(msg string, args ...interface{}) { - z.Log(Debug, msg, args...) +func (l *intLogger) Debug(msg string, args ...interface{}) { + l.Log(Debug, msg, args...) } // Emit the message and args at TRACE level -func (z *intLogger) Trace(msg string, args ...interface{}) { - z.Log(Trace, msg, args...) +func (l *intLogger) Trace(msg string, args ...interface{}) { + l.Log(Trace, msg, args...) } // Emit the message and args at INFO level -func (z *intLogger) Info(msg string, args ...interface{}) { - z.Log(Info, msg, args...) +func (l *intLogger) Info(msg string, args ...interface{}) { + l.Log(Info, msg, args...) } // Emit the message and args at WARN level -func (z *intLogger) Warn(msg string, args ...interface{}) { - z.Log(Warn, msg, args...) +func (l *intLogger) Warn(msg string, args ...interface{}) { + l.Log(Warn, msg, args...) } // Emit the message and args at ERROR level -func (z *intLogger) Error(msg string, args ...interface{}) { - z.Log(Error, msg, args...) +func (l *intLogger) Error(msg string, args ...interface{}) { + l.Log(Error, msg, args...) } // Indicate that the logger would emit TRACE level logs -func (z *intLogger) IsTrace() bool { - return Level(atomic.LoadInt32(z.level)) == Trace +func (l *intLogger) IsTrace() bool { + return Level(atomic.LoadInt32(l.level)) == Trace } // Indicate that the logger would emit DEBUG level logs -func (z *intLogger) IsDebug() bool { - return Level(atomic.LoadInt32(z.level)) <= Debug +func (l *intLogger) IsDebug() bool { + return Level(atomic.LoadInt32(l.level)) <= Debug } // Indicate that the logger would emit INFO level logs -func (z *intLogger) IsInfo() bool { - return Level(atomic.LoadInt32(z.level)) <= Info +func (l *intLogger) IsInfo() bool { + return Level(atomic.LoadInt32(l.level)) <= Info } // Indicate that the logger would emit WARN level logs -func (z *intLogger) IsWarn() bool { - return Level(atomic.LoadInt32(z.level)) <= Warn +func (l *intLogger) IsWarn() bool { + return Level(atomic.LoadInt32(l.level)) <= Warn } // Indicate that the logger would emit ERROR level logs -func (z *intLogger) IsError() bool { - return Level(atomic.LoadInt32(z.level)) <= Error +func (l *intLogger) IsError() bool { + return Level(atomic.LoadInt32(l.level)) <= Error } // Return a sub-Logger for which every emitted log message will contain // the given key/value pairs. This is used to create a context specific // Logger. -func (z *intLogger) With(args ...interface{}) Logger { +func (l *intLogger) With(args ...interface{}) Logger { if len(args)%2 != 0 { panic("With() call requires paired arguments") } - var nz intLogger = *z + sl := *l - result := make(map[string]interface{}, len(z.implied)+len(args)) - keys := make([]string, 0, len(z.implied)+len(args)) + result := make(map[string]interface{}, len(l.implied)+len(args)) + keys := make([]string, 0, len(l.implied)+len(args)) // Read existing args, store map and key for consistent sorting - for i := 0; i < len(z.implied); i += 2 { - key := z.implied[i].(string) + for i := 0; i < len(l.implied); i += 2 { + key := l.implied[i].(string) keys = append(keys, key) - result[key] = z.implied[i+1] + result[key] = l.implied[i+1] } // Read new args, store map and key for consistent sorting for i := 0; i < len(args); i += 2 { @@ -405,53 +455,57 @@ func (z *intLogger) With(args ...interface{}) Logger { // Sort keys to be consistent sort.Strings(keys) - nz.implied = make([]interface{}, 0, len(z.implied)+len(args)) + sl.implied = make([]interface{}, 0, len(l.implied)+len(args)) for _, k := range keys { - nz.implied = append(nz.implied, k) - nz.implied = append(nz.implied, result[k]) + sl.implied = append(sl.implied, k) + sl.implied = append(sl.implied, result[k]) } - return &nz + return &sl } // Create a new sub-Logger that a name decending from the current name. // This is used to create a subsystem specific Logger. -func (z *intLogger) Named(name string) Logger { - var nz intLogger = *z +func (l *intLogger) Named(name string) Logger { + sl := *l - if nz.name != "" { - nz.name = nz.name + "." + name + if sl.name != "" { + sl.name = sl.name + "." + name } else { - nz.name = name + sl.name = name } - return &nz + return &sl } // Create a new sub-Logger with an explicit name. This ignores the current // name. This is used to create a standalone logger that doesn't fall // within the normal hierarchy. -func (z *intLogger) ResetNamed(name string) Logger { - var nz intLogger = *z +func (l *intLogger) ResetNamed(name string) Logger { + sl := *l - nz.name = name + sl.name = name - return &nz + return &sl } // Update the logging level on-the-fly. This will affect all subloggers as // well. -func (z *intLogger) SetLevel(level Level) { - atomic.StoreInt32(z.level, int32(level)) +func (l *intLogger) SetLevel(level Level) { + atomic.StoreInt32(l.level, int32(level)) } // Create a *log.Logger that will send it's data through this Logger. This // allows packages that expect to be using the standard library log to actually // use this logger. -func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { +func (l *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { if opts == nil { opts = &StandardLoggerOptions{} } - return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0) + return log.New(l.StandardWriter(opts), "", 0) +} + +func (l *intLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer { + return &stdlogAdapter{l, opts.InferLevels} } diff --git a/vendor/github.com/hashicorp/go-hclog/log.go b/vendor/github.com/hashicorp/go-hclog/logger.go similarity index 77% rename from vendor/github.com/hashicorp/go-hclog/log.go rename to vendor/github.com/hashicorp/go-hclog/logger.go index d98714e0a..0f1f8264c 100644 --- a/vendor/github.com/hashicorp/go-hclog/log.go +++ b/vendor/github.com/hashicorp/go-hclog/logger.go @@ -9,38 +9,42 @@ import ( ) var ( - DefaultOutput = os.Stderr - DefaultLevel = Info + //DefaultOutput is used as the default log output. + DefaultOutput io.Writer = os.Stderr + + // DefaultLevel is used as the default log level. + DefaultLevel = Info ) +// Level represents a log level. type Level int32 const ( - // This is a special level used to indicate that no level has been + // NoLevel is a special level used to indicate that no level has been // set and allow for a default to be used. NoLevel Level = 0 - // The most verbose level. Intended to be used for the tracing of actions - // in code, such as function enters/exits, etc. + // Trace is the most verbose level. Intended to be used for the tracing + // of actions in code, such as function enters/exits, etc. Trace Level = 1 - // For programmer lowlevel analysis. + // Debug information for programmer lowlevel analysis. Debug Level = 2 - // For information about steady state operations. + // Info information about steady state operations. Info Level = 3 - // For information about rare but handled events. + // Warn information about rare but handled events. Warn Level = 4 - // For information about unrecoverable events. + // Error information about unrecoverable events. Error Level = 5 ) -// When processing a value of this type, the logger automatically treats the first -// argument as a Printf formatting string and passes the rest as the values to be -// formatted. For example: L.Info(Fmt{"%d beans/day", beans}). This is a simple -// convience type for when formatting is required. +// Format is a simple convience type for when formatting is required. When +// processing a value of this type, the logger automatically treats the first +// argument as a Printf formatting string and passes the rest as the values +// to be formatted. For example: L.Info(Fmt{"%d beans/day", beans}). type Format []interface{} // Fmt returns a Format type. This is a convience function for creating a Format @@ -53,7 +57,7 @@ func Fmt(str string, args ...interface{}) Format { // the level string is invalid. This facilitates setting the log level via // config or environment variable by name in a predictable way. func LevelFromString(levelStr string) Level { - // We don't care about case. Accept "INFO" or "info" + // We don't care about case. Accept both "INFO" and "info". levelStr = strings.ToLower(strings.TrimSpace(levelStr)) switch levelStr { case "trace": @@ -71,7 +75,7 @@ func LevelFromString(levelStr string) Level { } } -// The main Logger interface. All code should code against this interface only. +// Logger describes the interface that must be implemeted by all loggers. type Logger interface { // Args are alternating key, val pairs // keys must be strings @@ -127,8 +131,12 @@ type Logger interface { // Return a value that conforms to the stdlib log.Logger interface StandardLogger(opts *StandardLoggerOptions) *log.Logger + + // Return a value that conforms to io.Writer, which can be passed into log.SetOutput() + StandardWriter(opts *StandardLoggerOptions) io.Writer } +// StandardLoggerOptions can be used to configure a new standard logger. type StandardLoggerOptions struct { // Indicate that some minimal parsing should be done on strings to try // and detect their level and re-emit them. @@ -137,6 +145,7 @@ type StandardLoggerOptions struct { InferLevels bool } +// LoggerOptions can be used to configure a new logger. type LoggerOptions struct { // Name of the subsystem to prefix logs with Name string diff --git a/vendor/github.com/hashicorp/go-hclog/nulllogger.go b/vendor/github.com/hashicorp/go-hclog/nulllogger.go index 0942361a5..7ad6b351e 100644 --- a/vendor/github.com/hashicorp/go-hclog/nulllogger.go +++ b/vendor/github.com/hashicorp/go-hclog/nulllogger.go @@ -1,6 +1,7 @@ package hclog import ( + "io" "io/ioutil" "log" ) @@ -43,5 +44,9 @@ func (l *nullLogger) ResetNamed(name string) Logger { return l } func (l *nullLogger) SetLevel(level Level) {} func (l *nullLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { - return log.New(ioutil.Discard, "", log.LstdFlags) + return log.New(l.StandardWriter(opts), "", log.LstdFlags) +} + +func (l *nullLogger) StandardWriter(opts *StandardLoggerOptions) io.Writer { + return ioutil.Discard } diff --git a/vendor/github.com/hashicorp/go-hclog/stacktrace.go b/vendor/github.com/hashicorp/go-hclog/stacktrace.go index 8af1a3be4..9b27bd3d3 100644 --- a/vendor/github.com/hashicorp/go-hclog/stacktrace.go +++ b/vendor/github.com/hashicorp/go-hclog/stacktrace.go @@ -40,12 +40,13 @@ var ( } ) -// A stacktrace gathered by a previous call to log.Stacktrace. If passed -// to a logging function, the stacktrace will be appended. +// CapturedStacktrace represents a stacktrace captured by a previous call +// to log.Stacktrace. If passed to a logging function, the stacktrace +// will be appended. type CapturedStacktrace string -// Gather a stacktrace of the current goroutine and return it to be passed -// to a logging function. +// Stacktrace captures a stacktrace of the current goroutine and returns +// it to be passed to a logging function. func Stacktrace() CapturedStacktrace { return CapturedStacktrace(takeStacktrace()) } diff --git a/vendor/github.com/hashicorp/go-hclog/stdlog.go b/vendor/github.com/hashicorp/go-hclog/stdlog.go index 2bb927fc9..913d523b5 100644 --- a/vendor/github.com/hashicorp/go-hclog/stdlog.go +++ b/vendor/github.com/hashicorp/go-hclog/stdlog.go @@ -9,12 +9,12 @@ import ( // and back into our Logger. This is basically the only way to // build upon *log.Logger. type stdlogAdapter struct { - hl Logger + log Logger inferLevels bool } // Take the data, infer the levels if configured, and send it through -// a regular Logger +// a regular Logger. func (s *stdlogAdapter) Write(data []byte) (int, error) { str := string(bytes.TrimRight(data, " \t\n")) @@ -22,26 +22,26 @@ func (s *stdlogAdapter) Write(data []byte) (int, error) { level, str := s.pickLevel(str) switch level { case Trace: - s.hl.Trace(str) + s.log.Trace(str) case Debug: - s.hl.Debug(str) + s.log.Debug(str) case Info: - s.hl.Info(str) + s.log.Info(str) case Warn: - s.hl.Warn(str) + s.log.Warn(str) case Error: - s.hl.Error(str) + s.log.Error(str) default: - s.hl.Info(str) + s.log.Info(str) } } else { - s.hl.Info(str) + s.log.Info(str) } return len(data), nil } -// Detect, based on conventions, what log level this is +// Detect, based on conventions, what log level this is. func (s *stdlogAdapter) pickLevel(str string) (Level, string) { switch { case strings.HasPrefix(str, "[DEBUG]"): diff --git a/vendor/github.com/hashicorp/go-hclog/writer.go b/vendor/github.com/hashicorp/go-hclog/writer.go new file mode 100644 index 000000000..7e8ec729d --- /dev/null +++ b/vendor/github.com/hashicorp/go-hclog/writer.go @@ -0,0 +1,74 @@ +package hclog + +import ( + "bytes" + "io" +) + +type writer struct { + b bytes.Buffer + w io.Writer +} + +func newWriter(w io.Writer) *writer { + return &writer{w: w} +} + +func (w *writer) Flush(level Level) (err error) { + if lw, ok := w.w.(LevelWriter); ok { + _, err = lw.LevelWrite(level, w.b.Bytes()) + } else { + _, err = w.w.Write(w.b.Bytes()) + } + w.b.Reset() + return err +} + +func (w *writer) Write(p []byte) (int, error) { + return w.b.Write(p) +} + +func (w *writer) WriteByte(c byte) error { + return w.b.WriteByte(c) +} + +func (w *writer) WriteString(s string) (int, error) { + return w.b.WriteString(s) +} + +// LevelWriter is the interface that wraps the LevelWrite method. +type LevelWriter interface { + LevelWrite(level Level, p []byte) (n int, err error) +} + +// LeveledWriter writes all log messages to the standard writer, +// except for log levels that are defined in the overrides map. +type LeveledWriter struct { + standard io.Writer + overrides map[Level]io.Writer +} + +// NewLeveledWriter returns an initialized LeveledWriter. +// +// standard will be used as the default writer for all log levels, +// except for log levels that are defined in the overrides map. +func NewLeveledWriter(standard io.Writer, overrides map[Level]io.Writer) *LeveledWriter { + return &LeveledWriter{ + standard: standard, + overrides: overrides, + } +} + +// Write implements io.Writer. +func (lw *LeveledWriter) Write(p []byte) (int, error) { + return lw.standard.Write(p) +} + +// LevelWrite implements LevelWriter. +func (lw *LeveledWriter) LevelWrite(level Level, p []byte) (int, error) { + w, ok := lw.overrides[level] + if !ok { + w = lw.standard + } + return w.Write(p) +} diff --git a/vendor/github.com/hashicorp/go-memdb/LICENSE b/vendor/github.com/hashicorp/go-memdb/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/go-memdb/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-memdb/README.md b/vendor/github.com/hashicorp/go-memdb/README.md deleted file mode 100644 index 65e1eaefe..000000000 --- a/vendor/github.com/hashicorp/go-memdb/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# go-memdb - -Provides the `memdb` package that implements a simple in-memory database -built on immutable radix trees. The database provides Atomicity, Consistency -and Isolation from ACID. Being that it is in-memory, it does not provide durability. -The database is instantiated with a schema that specifies the tables and indices -that exist and allows transactions to be executed. - -The database provides the following: - -* Multi-Version Concurrency Control (MVCC) - By leveraging immutable radix trees - the database is able to support any number of concurrent readers without locking, - and allows a writer to make progress. - -* Transaction Support - The database allows for rich transactions, in which multiple - objects are inserted, updated or deleted. The transactions can span multiple tables, - and are applied atomically. The database provides atomicity and isolation in ACID - terminology, such that until commit the updates are not visible. - -* Rich Indexing - Tables can support any number of indexes, which can be simple like - a single field index, or more advanced compound field indexes. Certain types like - UUID can be efficiently compressed from strings into byte indexes for reduced - storage requirements. - -* Watches - Callers can populate a watch set as part of a query, which can be used to - detect when a modification has been made to the database which affects the query - results. This lets callers easily watch for changes in the database in a very general - way. - -For the underlying immutable radix trees, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix). - -Documentation -============= - -The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/go-memdb). - -Example -======= - -Below is a simple example of usage - -```go -// Create a sample struct -type Person struct { - Email string - Name string - Age int -} - -// Create the DB schema -schema := &memdb.DBSchema{ - Tables: map[string]*memdb.TableSchema{ - "person": &memdb.TableSchema{ - Name: "person", - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{Field: "Email"}, - }, - }, - }, - }, -} - -// Create a new data base -db, err := memdb.NewMemDB(schema) -if err != nil { - panic(err) -} - -// Create a write transaction -txn := db.Txn(true) - -// Insert a new person -p := &Person{"joe@aol.com", "Joe", 30} -if err := txn.Insert("person", p); err != nil { - panic(err) -} - -// Commit the transaction -txn.Commit() - -// Create read-only transaction -txn = db.Txn(false) -defer txn.Abort() - -// Lookup by email -raw, err := txn.First("person", "id", "joe@aol.com") -if err != nil { - panic(err) -} - -// Say hi! -fmt.Printf("Hello %s!", raw.(*Person).Name) - -``` - diff --git a/vendor/github.com/hashicorp/go-memdb/filter.go b/vendor/github.com/hashicorp/go-memdb/filter.go deleted file mode 100644 index 2e3a9b3f7..000000000 --- a/vendor/github.com/hashicorp/go-memdb/filter.go +++ /dev/null @@ -1,33 +0,0 @@ -package memdb - -// FilterFunc is a function that takes the results of an iterator and returns -// whether the result should be filtered out. -type FilterFunc func(interface{}) bool - -// FilterIterator is used to wrap a ResultIterator and apply a filter over it. -type FilterIterator struct { - // filter is the filter function applied over the base iterator. - filter FilterFunc - - // iter is the iterator that is being wrapped. - iter ResultIterator -} - -func NewFilterIterator(wrap ResultIterator, filter FilterFunc) *FilterIterator { - return &FilterIterator{ - filter: filter, - iter: wrap, - } -} - -// WatchCh returns the watch channel of the wrapped iterator. -func (f *FilterIterator) WatchCh() <-chan struct{} { return f.iter.WatchCh() } - -// Next returns the next non-filtered result from the wrapped iterator -func (f *FilterIterator) Next() interface{} { - for { - if value := f.iter.Next(); value == nil || !f.filter(value) { - return value - } - } -} diff --git a/vendor/github.com/hashicorp/go-memdb/index.go b/vendor/github.com/hashicorp/go-memdb/index.go deleted file mode 100644 index cca853c5a..000000000 --- a/vendor/github.com/hashicorp/go-memdb/index.go +++ /dev/null @@ -1,581 +0,0 @@ -package memdb - -import ( - "encoding/binary" - "encoding/hex" - "fmt" - "reflect" - "strings" -) - -// Indexer is an interface used for defining indexes. Indexes are used -// for efficient lookup of objects in a MemDB table. An Indexer must also -// implement one of SingleIndexer or MultiIndexer. -// -// Indexers are primarily responsible for returning the lookup key as -// a byte slice. The byte slice is the key data in the underlying data storage. -type Indexer interface { - // FromArgs is called to build the exact index key from a list of arguments. - FromArgs(args ...interface{}) ([]byte, error) -} - -// SingleIndexer is an interface used for defining indexes that generate a -// single value per object -type SingleIndexer interface { - // FromObject extracts the index value from an object. The return values - // are whether the index value was found, the index value, and any error - // while extracting the index value, respectively. - FromObject(raw interface{}) (bool, []byte, error) -} - -// MultiIndexer is an interface used for defining indexes that generate -// multiple values per object. Each value is stored as a seperate index -// pointing to the same object. -// -// For example, an index that extracts the first and last name of a person -// and allows lookup based on eitherd would be a MultiIndexer. The FromObject -// of this example would split the first and last name and return both as -// values. -type MultiIndexer interface { - // FromObject extracts index values from an object. The return values - // are the same as a SingleIndexer except there can be multiple index - // values. - FromObject(raw interface{}) (bool, [][]byte, error) -} - -// PrefixIndexer is an optional interface on top of an Indexer that allows -// indexes to support prefix-based iteration. -type PrefixIndexer interface { - // PrefixFromArgs is the same as FromArgs for an Indexer except that - // the index value returned should return all prefix-matched values. - PrefixFromArgs(args ...interface{}) ([]byte, error) -} - -// StringFieldIndex is used to extract a field from an object -// using reflection and builds an index on that field. -type StringFieldIndex struct { - Field string - Lowercase bool -} - -func (s *StringFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - val := fv.String() - if val == "" { - return false, nil, nil - } - - if s.Lowercase { - val = strings.ToLower(val) - } - - // Add the null character as a terminator - val += "\x00" - return true, []byte(val), nil -} - -func (s *StringFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - arg, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - arg = strings.ToLower(arg) - } - // Add the null character as a terminator - arg += "\x00" - return []byte(arg), nil -} - -func (s *StringFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - val, err := s.FromArgs(args...) - if err != nil { - return nil, err - } - - // Strip the null terminator, the rest is a prefix - n := len(val) - if n > 0 { - return val[:n-1], nil - } - return val, nil -} - -// StringSliceFieldIndex builds an index from a field on an object that is a -// string slice ([]string). Each value within the string slice can be used for -// lookup. -type StringSliceFieldIndex struct { - Field string - Lowercase bool -} - -func (s *StringSliceFieldIndex) FromObject(obj interface{}) (bool, [][]byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - if fv.Kind() != reflect.Slice || fv.Type().Elem().Kind() != reflect.String { - return false, nil, fmt.Errorf("field '%s' is not a string slice", s.Field) - } - - length := fv.Len() - vals := make([][]byte, 0, length) - for i := 0; i < fv.Len(); i++ { - val := fv.Index(i).String() - if val == "" { - continue - } - - if s.Lowercase { - val = strings.ToLower(val) - } - - // Add the null character as a terminator - val += "\x00" - vals = append(vals, []byte(val)) - } - if len(vals) == 0 { - return false, nil, nil - } - return true, vals, nil -} - -func (s *StringSliceFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - arg, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - arg = strings.ToLower(arg) - } - // Add the null character as a terminator - arg += "\x00" - return []byte(arg), nil -} - -func (s *StringSliceFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - val, err := s.FromArgs(args...) - if err != nil { - return nil, err - } - - // Strip the null terminator, the rest is a prefix - n := len(val) - if n > 0 { - return val[:n-1], nil - } - return val, nil -} - -// StringMapFieldIndex is used to extract a field of type map[string]string -// from an object using reflection and builds an index on that field. -type StringMapFieldIndex struct { - Field string - Lowercase bool -} - -var MapType = reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")).Kind() - -func (s *StringMapFieldIndex) FromObject(obj interface{}) (bool, [][]byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(s.Field) - if !fv.IsValid() { - return false, nil, fmt.Errorf("field '%s' for %#v is invalid", s.Field, obj) - } - - if fv.Kind() != MapType { - return false, nil, fmt.Errorf("field '%s' is not a map[string]string", s.Field) - } - - length := fv.Len() - vals := make([][]byte, 0, length) - for _, key := range fv.MapKeys() { - k := key.String() - if k == "" { - continue - } - val := fv.MapIndex(key).String() - - if s.Lowercase { - k = strings.ToLower(k) - val = strings.ToLower(val) - } - - // Add the null character as a terminator - k += "\x00" + val + "\x00" - - vals = append(vals, []byte(k)) - } - if len(vals) == 0 { - return false, nil, nil - } - return true, vals, nil -} - -func (s *StringMapFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) > 2 || len(args) == 0 { - return nil, fmt.Errorf("must provide one or two arguments") - } - key, ok := args[0].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[0]) - } - if s.Lowercase { - key = strings.ToLower(key) - } - // Add the null character as a terminator - key += "\x00" - - if len(args) == 2 { - val, ok := args[1].(string) - if !ok { - return nil, fmt.Errorf("argument must be a string: %#v", args[1]) - } - if s.Lowercase { - val = strings.ToLower(val) - } - // Add the null character as a terminator - key += val + "\x00" - } - - return []byte(key), nil -} - -// UintFieldIndex is used to extract a uint field from an object using -// reflection and builds an index on that field. -type UintFieldIndex struct { - Field string -} - -func (u *UintFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(u.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", u.Field, obj) - } - - // Check the type - k := fv.Kind() - size, ok := IsUintType(k) - if !ok { - return false, nil, fmt.Errorf("field %q is of type %v; want a uint", u.Field, k) - } - - // Get the value and encode it - val := fv.Uint() - buf := make([]byte, size) - binary.PutUvarint(buf, val) - - return true, buf, nil -} - -func (u *UintFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - - v := reflect.ValueOf(args[0]) - if !v.IsValid() { - return nil, fmt.Errorf("%#v is invalid", args[0]) - } - - k := v.Kind() - size, ok := IsUintType(k) - if !ok { - return nil, fmt.Errorf("arg is of type %v; want a uint", k) - } - - val := v.Uint() - buf := make([]byte, size) - binary.PutUvarint(buf, val) - - return buf, nil -} - -// IsUintType returns whether the passed type is a type of uint and the number -// of bytes needed to encode the type. -func IsUintType(k reflect.Kind) (size int, okay bool) { - switch k { - case reflect.Uint: - return binary.MaxVarintLen64, true - case reflect.Uint8: - return 2, true - case reflect.Uint16: - return binary.MaxVarintLen16, true - case reflect.Uint32: - return binary.MaxVarintLen32, true - case reflect.Uint64: - return binary.MaxVarintLen64, true - default: - return 0, false - } -} - -// UUIDFieldIndex is used to extract a field from an object -// using reflection and builds an index on that field by treating -// it as a UUID. This is an optimization to using a StringFieldIndex -// as the UUID can be more compactly represented in byte form. -type UUIDFieldIndex struct { - Field string -} - -func (u *UUIDFieldIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(u.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", u.Field, obj) - } - - val := fv.String() - if val == "" { - return false, nil, nil - } - - buf, err := u.parseString(val, true) - return true, buf, err -} - -func (u *UUIDFieldIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - switch arg := args[0].(type) { - case string: - return u.parseString(arg, true) - case []byte: - if len(arg) != 16 { - return nil, fmt.Errorf("byte slice must be 16 characters") - } - return arg, nil - default: - return nil, - fmt.Errorf("argument must be a string or byte slice: %#v", args[0]) - } -} - -func (u *UUIDFieldIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - switch arg := args[0].(type) { - case string: - return u.parseString(arg, false) - case []byte: - return arg, nil - default: - return nil, - fmt.Errorf("argument must be a string or byte slice: %#v", args[0]) - } -} - -// parseString parses a UUID from the string. If enforceLength is false, it will -// parse a partial UUID. An error is returned if the input, stripped of hyphens, -// is not even length. -func (u *UUIDFieldIndex) parseString(s string, enforceLength bool) ([]byte, error) { - // Verify the length - l := len(s) - if enforceLength && l != 36 { - return nil, fmt.Errorf("UUID must be 36 characters") - } else if l > 36 { - return nil, fmt.Errorf("Invalid UUID length. UUID have 36 characters; got %d", l) - } - - hyphens := strings.Count(s, "-") - if hyphens > 4 { - return nil, fmt.Errorf(`UUID should have maximum of 4 "-"; got %d`, hyphens) - } - - // The sanitized length is the length of the original string without the "-". - sanitized := strings.Replace(s, "-", "", -1) - sanitizedLength := len(sanitized) - if sanitizedLength%2 != 0 { - return nil, fmt.Errorf("Input (without hyphens) must be even length") - } - - dec, err := hex.DecodeString(sanitized) - if err != nil { - return nil, fmt.Errorf("Invalid UUID: %v", err) - } - - return dec, nil -} - -// FieldSetIndex is used to extract a field from an object using reflection and -// builds an index on whether the field is set by comparing it against its -// type's nil value. -type FieldSetIndex struct { - Field string -} - -func (f *FieldSetIndex) FromObject(obj interface{}) (bool, []byte, error) { - v := reflect.ValueOf(obj) - v = reflect.Indirect(v) // Dereference the pointer if any - - fv := v.FieldByName(f.Field) - if !fv.IsValid() { - return false, nil, - fmt.Errorf("field '%s' for %#v is invalid", f.Field, obj) - } - - if fv.Interface() == reflect.Zero(fv.Type()).Interface() { - return true, []byte{0}, nil - } - - return true, []byte{1}, nil -} - -func (f *FieldSetIndex) FromArgs(args ...interface{}) ([]byte, error) { - return fromBoolArgs(args) -} - -// ConditionalIndex builds an index based on a condition specified by a passed -// user function. This function may examine the passed object and return a -// boolean to encapsulate an arbitrarily complex conditional. -type ConditionalIndex struct { - Conditional ConditionalIndexFunc -} - -// ConditionalIndexFunc is the required function interface for a -// ConditionalIndex. -type ConditionalIndexFunc func(obj interface{}) (bool, error) - -func (c *ConditionalIndex) FromObject(obj interface{}) (bool, []byte, error) { - // Call the user's function - res, err := c.Conditional(obj) - if err != nil { - return false, nil, fmt.Errorf("ConditionalIndexFunc(%#v) failed: %v", obj, err) - } - - if res { - return true, []byte{1}, nil - } - - return true, []byte{0}, nil -} - -func (c *ConditionalIndex) FromArgs(args ...interface{}) ([]byte, error) { - return fromBoolArgs(args) -} - -// fromBoolArgs is a helper that expects only a single boolean argument and -// returns a single length byte array containing either a one or zero depending -// on whether the passed input is true or false respectively. -func fromBoolArgs(args []interface{}) ([]byte, error) { - if len(args) != 1 { - return nil, fmt.Errorf("must provide only a single argument") - } - - if val, ok := args[0].(bool); !ok { - return nil, fmt.Errorf("argument must be a boolean type: %#v", args[0]) - } else if val { - return []byte{1}, nil - } - - return []byte{0}, nil -} - -// CompoundIndex is used to build an index using multiple sub-indexes -// Prefix based iteration is supported as long as the appropriate prefix -// of indexers support it. All sub-indexers are only assumed to expect -// a single argument. -type CompoundIndex struct { - Indexes []Indexer - - // AllowMissing results in an index based on only the indexers - // that return data. If true, you may end up with 2/3 columns - // indexed which might be useful for an index scan. Otherwise, - // the CompoundIndex requires all indexers to be satisfied. - AllowMissing bool -} - -func (c *CompoundIndex) FromObject(raw interface{}) (bool, []byte, error) { - var out []byte - for i, idxRaw := range c.Indexes { - idx, ok := idxRaw.(SingleIndexer) - if !ok { - return false, nil, fmt.Errorf("sub-index %d error: %s", i, "sub-index must be a SingleIndexer") - } - ok, val, err := idx.FromObject(raw) - if err != nil { - return false, nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - if !ok { - if c.AllowMissing { - break - } else { - return false, nil, nil - } - } - out = append(out, val...) - } - return true, out, nil -} - -func (c *CompoundIndex) FromArgs(args ...interface{}) ([]byte, error) { - if len(args) != len(c.Indexes) { - return nil, fmt.Errorf("less arguments than index fields") - } - var out []byte - for i, arg := range args { - val, err := c.Indexes[i].FromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } - return out, nil -} - -func (c *CompoundIndex) PrefixFromArgs(args ...interface{}) ([]byte, error) { - if len(args) > len(c.Indexes) { - return nil, fmt.Errorf("more arguments than index fields") - } - var out []byte - for i, arg := range args { - if i+1 < len(args) { - val, err := c.Indexes[i].FromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } else { - prefixIndexer, ok := c.Indexes[i].(PrefixIndexer) - if !ok { - return nil, fmt.Errorf("sub-index %d does not support prefix scanning", i) - } - val, err := prefixIndexer.PrefixFromArgs(arg) - if err != nil { - return nil, fmt.Errorf("sub-index %d error: %v", i, err) - } - out = append(out, val...) - } - } - return out, nil -} diff --git a/vendor/github.com/hashicorp/go-memdb/memdb.go b/vendor/github.com/hashicorp/go-memdb/memdb.go deleted file mode 100644 index 65c920731..000000000 --- a/vendor/github.com/hashicorp/go-memdb/memdb.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package memdb provides an in-memory database that supports transactions -// and MVCC. -package memdb - -import ( - "sync" - "sync/atomic" - "unsafe" - - "github.com/hashicorp/go-immutable-radix" -) - -// MemDB is an in-memory database. -// -// MemDB provides a table abstraction to store objects (rows) with multiple -// indexes based on inserted values. The database makes use of immutable radix -// trees to provide transactions and MVCC. -type MemDB struct { - schema *DBSchema - root unsafe.Pointer // *iradix.Tree underneath - primary bool - - // There can only be a single writer at once - writer sync.Mutex -} - -// NewMemDB creates a new MemDB with the given schema -func NewMemDB(schema *DBSchema) (*MemDB, error) { - // Validate the schema - if err := schema.Validate(); err != nil { - return nil, err - } - - // Create the MemDB - db := &MemDB{ - schema: schema, - root: unsafe.Pointer(iradix.New()), - primary: true, - } - if err := db.initialize(); err != nil { - return nil, err - } - - return db, nil -} - -// getRoot is used to do an atomic load of the root pointer -func (db *MemDB) getRoot() *iradix.Tree { - root := (*iradix.Tree)(atomic.LoadPointer(&db.root)) - return root -} - -// Txn is used to start a new transaction, in either read or write mode. -// There can only be a single concurrent writer, but any number of readers. -func (db *MemDB) Txn(write bool) *Txn { - if write { - db.writer.Lock() - } - txn := &Txn{ - db: db, - write: write, - rootTxn: db.getRoot().Txn(), - } - return txn -} - -// Snapshot is used to capture a point-in-time snapshot -// of the database that will not be affected by any write -// operations to the existing DB. -func (db *MemDB) Snapshot() *MemDB { - clone := &MemDB{ - schema: db.schema, - root: unsafe.Pointer(db.getRoot()), - primary: false, - } - return clone -} - -// initialize is used to setup the DB for use after creation. This should -// be called only once after allocating a MemDB. -func (db *MemDB) initialize() error { - root := db.getRoot() - for tName, tableSchema := range db.schema.Tables { - for iName := range tableSchema.Indexes { - index := iradix.New() - path := indexPath(tName, iName) - root, _, _ = root.Insert(path, index) - } - } - db.root = unsafe.Pointer(root) - return nil -} - -// indexPath returns the path from the root to the given table index -func indexPath(table, index string) []byte { - return []byte(table + "." + index) -} diff --git a/vendor/github.com/hashicorp/go-memdb/schema.go b/vendor/github.com/hashicorp/go-memdb/schema.go deleted file mode 100644 index e6a9b526b..000000000 --- a/vendor/github.com/hashicorp/go-memdb/schema.go +++ /dev/null @@ -1,114 +0,0 @@ -package memdb - -import "fmt" - -// DBSchema is the schema to use for the full database with a MemDB instance. -// -// MemDB will require a valid schema. Schema validation can be tested using -// the Validate function. Calling this function is recommended in unit tests. -type DBSchema struct { - // Tables is the set of tables within this database. The key is the - // table name and must match the Name in TableSchema. - Tables map[string]*TableSchema -} - -// Validate validates the schema. -func (s *DBSchema) Validate() error { - if s == nil { - return fmt.Errorf("schema is nil") - } - - if len(s.Tables) == 0 { - return fmt.Errorf("schema has no tables defined") - } - - for name, table := range s.Tables { - if name != table.Name { - return fmt.Errorf("table name mis-match for '%s'", name) - } - - if err := table.Validate(); err != nil { - return fmt.Errorf("table %q: %s", name, err) - } - } - - return nil -} - -// TableSchema is the schema for a single table. -type TableSchema struct { - // Name of the table. This must match the key in the Tables map in DBSchema. - Name string - - // Indexes is the set of indexes for querying this table. The key - // is a unique name for the index and must match the Name in the - // IndexSchema. - Indexes map[string]*IndexSchema -} - -// Validate is used to validate the table schema -func (s *TableSchema) Validate() error { - if s.Name == "" { - return fmt.Errorf("missing table name") - } - - if len(s.Indexes) == 0 { - return fmt.Errorf("missing table indexes for '%s'", s.Name) - } - - if _, ok := s.Indexes["id"]; !ok { - return fmt.Errorf("must have id index") - } - - if !s.Indexes["id"].Unique { - return fmt.Errorf("id index must be unique") - } - - if _, ok := s.Indexes["id"].Indexer.(SingleIndexer); !ok { - return fmt.Errorf("id index must be a SingleIndexer") - } - - for name, index := range s.Indexes { - if name != index.Name { - return fmt.Errorf("index name mis-match for '%s'", name) - } - - if err := index.Validate(); err != nil { - return fmt.Errorf("index %q: %s", name, err) - } - } - - return nil -} - -// IndexSchema is the schema for an index. An index defines how a table is -// queried. -type IndexSchema struct { - // Name of the index. This must be unique among a tables set of indexes. - // This must match the key in the map of Indexes for a TableSchema. - Name string - - // AllowMissing if true ignores this index if it doesn't produce a - // value. For example, an index that extracts a field that doesn't - // exist from a structure. - AllowMissing bool - - Unique bool - Indexer Indexer -} - -func (s *IndexSchema) Validate() error { - if s.Name == "" { - return fmt.Errorf("missing index name") - } - if s.Indexer == nil { - return fmt.Errorf("missing index function for '%s'", s.Name) - } - switch s.Indexer.(type) { - case SingleIndexer: - case MultiIndexer: - default: - return fmt.Errorf("indexer for '%s' must be a SingleIndexer or MultiIndexer", s.Name) - } - return nil -} diff --git a/vendor/github.com/hashicorp/go-memdb/txn.go b/vendor/github.com/hashicorp/go-memdb/txn.go deleted file mode 100644 index 2b85087ea..000000000 --- a/vendor/github.com/hashicorp/go-memdb/txn.go +++ /dev/null @@ -1,644 +0,0 @@ -package memdb - -import ( - "bytes" - "fmt" - "strings" - "sync/atomic" - "unsafe" - - "github.com/hashicorp/go-immutable-radix" -) - -const ( - id = "id" -) - -var ( - // ErrNotFound is returned when the requested item is not found - ErrNotFound = fmt.Errorf("not found") -) - -// tableIndex is a tuple of (Table, Index) used for lookups -type tableIndex struct { - Table string - Index string -} - -// Txn is a transaction against a MemDB. -// This can be a read or write transaction. -type Txn struct { - db *MemDB - write bool - rootTxn *iradix.Txn - after []func() - - modified map[tableIndex]*iradix.Txn -} - -// readableIndex returns a transaction usable for reading the given -// index in a table. If a write transaction is in progress, we may need -// to use an existing modified txn. -func (txn *Txn) readableIndex(table, index string) *iradix.Txn { - // Look for existing transaction - if txn.write && txn.modified != nil { - key := tableIndex{table, index} - exist, ok := txn.modified[key] - if ok { - return exist - } - } - - // Create a read transaction - path := indexPath(table, index) - raw, _ := txn.rootTxn.Get(path) - indexTxn := raw.(*iradix.Tree).Txn() - return indexTxn -} - -// writableIndex returns a transaction usable for modifying the -// given index in a table. -func (txn *Txn) writableIndex(table, index string) *iradix.Txn { - if txn.modified == nil { - txn.modified = make(map[tableIndex]*iradix.Txn) - } - - // Look for existing transaction - key := tableIndex{table, index} - exist, ok := txn.modified[key] - if ok { - return exist - } - - // Start a new transaction - path := indexPath(table, index) - raw, _ := txn.rootTxn.Get(path) - indexTxn := raw.(*iradix.Tree).Txn() - - // If we are the primary DB, enable mutation tracking. Snapshots should - // not notify, otherwise we will trigger watches on the primary DB when - // the writes will not be visible. - indexTxn.TrackMutate(txn.db.primary) - - // Keep this open for the duration of the txn - txn.modified[key] = indexTxn - return indexTxn -} - -// Abort is used to cancel this transaction. -// This is a noop for read transactions. -func (txn *Txn) Abort() { - // Noop for a read transaction - if !txn.write { - return - } - - // Check if already aborted or committed - if txn.rootTxn == nil { - return - } - - // Clear the txn - txn.rootTxn = nil - txn.modified = nil - - // Release the writer lock since this is invalid - txn.db.writer.Unlock() -} - -// Commit is used to finalize this transaction. -// This is a noop for read transactions. -func (txn *Txn) Commit() { - // Noop for a read transaction - if !txn.write { - return - } - - // Check if already aborted or committed - if txn.rootTxn == nil { - return - } - - // Commit each sub-transaction scoped to (table, index) - for key, subTxn := range txn.modified { - path := indexPath(key.Table, key.Index) - final := subTxn.CommitOnly() - txn.rootTxn.Insert(path, final) - } - - // Update the root of the DB - newRoot := txn.rootTxn.CommitOnly() - atomic.StorePointer(&txn.db.root, unsafe.Pointer(newRoot)) - - // Now issue all of the mutation updates (this is safe to call - // even if mutation tracking isn't enabled); we do this after - // the root pointer is swapped so that waking responders will - // see the new state. - for _, subTxn := range txn.modified { - subTxn.Notify() - } - txn.rootTxn.Notify() - - // Clear the txn - txn.rootTxn = nil - txn.modified = nil - - // Release the writer lock since this is invalid - txn.db.writer.Unlock() - - // Run the deferred functions, if any - for i := len(txn.after); i > 0; i-- { - fn := txn.after[i-1] - fn() - } -} - -// Insert is used to add or update an object into the given table -func (txn *Txn) Insert(table string, obj interface{}) error { - if !txn.write { - return fmt.Errorf("cannot insert in read-only transaction") - } - - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return fmt.Errorf("invalid table '%s'", table) - } - - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(obj) - if err != nil { - return fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return fmt.Errorf("object missing primary index") - } - - // Lookup the object by ID first, to see if this is an update - idTxn := txn.writableIndex(table, id) - existing, update := idTxn.Get(idVal) - - // On an update, there is an existing object with the given - // primary ID. We do the update by deleting the current object - // and inserting the new object. - for name, indexSchema := range tableSchema.Indexes { - indexTxn := txn.writableIndex(table, name) - - // Determine the new index value - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(obj) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(obj) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - if ok && !indexSchema.Unique { - for i := range vals { - vals[i] = append(vals[i], idVal...) - } - } - - // Handle the update by deleting from the index first - if update { - var ( - okExist bool - valsExist [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var valExist []byte - okExist, valExist, err = indexer.FromObject(existing) - valsExist = [][]byte{valExist} - case MultiIndexer: - okExist, valsExist, err = indexer.FromObject(existing) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - if okExist { - for i, valExist := range valsExist { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - if !indexSchema.Unique { - valExist = append(valExist, idVal...) - } - - // If we are writing to the same index with the same value, - // we can avoid the delete as the insert will overwrite the - // value anyways. - if i >= len(vals) || !bytes.Equal(valExist, vals[i]) { - indexTxn.Delete(valExist) - } - } - } - } - - // If there is no index value, either this is an error or an expected - // case and we can skip updating - if !ok { - if indexSchema.AllowMissing { - continue - } else { - return fmt.Errorf("missing value for index '%s'", name) - } - } - - // Update the value of the index - for _, val := range vals { - indexTxn.Insert(val, obj) - } - } - return nil -} - -// Delete is used to delete a single object from the given table -// This object must already exist in the table -func (txn *Txn) Delete(table string, obj interface{}) error { - if !txn.write { - return fmt.Errorf("cannot delete in read-only transaction") - } - - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return fmt.Errorf("invalid table '%s'", table) - } - - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(obj) - if err != nil { - return fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return fmt.Errorf("object missing primary index") - } - - // Lookup the object by ID first, check fi we should continue - idTxn := txn.writableIndex(table, id) - existing, ok := idTxn.Get(idVal) - if !ok { - return ErrNotFound - } - - // Remove the object from all the indexes - for name, indexSchema := range tableSchema.Indexes { - indexTxn := txn.writableIndex(table, name) - - // Handle the update by deleting from the index first - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(existing) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(existing) - } - if err != nil { - return fmt.Errorf("failed to build index '%s': %v", name, err) - } - if ok { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - for _, val := range vals { - if !indexSchema.Unique { - val = append(val, idVal...) - } - indexTxn.Delete(val) - } - } - } - return nil -} - -// DeletePrefix is used to delete an entire subtree based on a prefix. -// The given index must be a prefix index, and will be used to perform a scan and enumerate the set of objects to delete. -// These will be removed from all other indexes, and then a special prefix operation will delete the objects from the given index in an efficient subtree delete operation. -// This is useful when you have a very large number of objects indexed by the given index, along with a much smaller number of entries in the other indexes for those objects. -func (txn *Txn) DeletePrefix(table string, prefix_index string, prefix string) (bool, error) { - if !txn.write { - return false, fmt.Errorf("cannot delete in read-only transaction") - } - - if !strings.HasSuffix(prefix_index, "_prefix") { - return false, fmt.Errorf("Index name for DeletePrefix must be a prefix index, Got %v ", prefix_index) - } - - deletePrefixIndex := strings.TrimSuffix(prefix_index, "_prefix") - - // Get an iterator over all of the keys with the given prefix. - entries, err := txn.Get(table, prefix_index, prefix) - if err != nil { - return false, fmt.Errorf("failed kvs lookup: %s", err) - } - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return false, fmt.Errorf("invalid table '%s'", table) - } - - foundAny := false - for entry := entries.Next(); entry != nil; entry = entries.Next() { - if !foundAny { - foundAny = true - } - // Get the primary ID of the object - idSchema := tableSchema.Indexes[id] - idIndexer := idSchema.Indexer.(SingleIndexer) - ok, idVal, err := idIndexer.FromObject(entry) - if err != nil { - return false, fmt.Errorf("failed to build primary index: %v", err) - } - if !ok { - return false, fmt.Errorf("object missing primary index") - } - // Remove the object from all the indexes except the given prefix index - for name, indexSchema := range tableSchema.Indexes { - if name == deletePrefixIndex { - continue - } - indexTxn := txn.writableIndex(table, name) - - // Handle the update by deleting from the index first - var ( - ok bool - vals [][]byte - err error - ) - switch indexer := indexSchema.Indexer.(type) { - case SingleIndexer: - var val []byte - ok, val, err = indexer.FromObject(entry) - vals = [][]byte{val} - case MultiIndexer: - ok, vals, err = indexer.FromObject(entry) - } - if err != nil { - return false, fmt.Errorf("failed to build index '%s': %v", name, err) - } - - if ok { - // Handle non-unique index by computing a unique index. - // This is done by appending the primary key which must - // be unique anyways. - for _, val := range vals { - if !indexSchema.Unique { - val = append(val, idVal...) - } - indexTxn.Delete(val) - } - } - } - } - if foundAny { - indexTxn := txn.writableIndex(table, deletePrefixIndex) - ok = indexTxn.DeletePrefix([]byte(prefix)) - if !ok { - panic(fmt.Errorf("prefix %v matched some entries but DeletePrefix did not delete any ", prefix)) - } - return true, nil - } - return false, nil -} - -// DeleteAll is used to delete all the objects in a given table -// matching the constraints on the index -func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) { - if !txn.write { - return 0, fmt.Errorf("cannot delete in read-only transaction") - } - - // Get all the objects - iter, err := txn.Get(table, index, args...) - if err != nil { - return 0, err - } - - // Put them into a slice so there are no safety concerns while actually - // performing the deletes - var objs []interface{} - for { - obj := iter.Next() - if obj == nil { - break - } - - objs = append(objs, obj) - } - - // Do the deletes - num := 0 - for _, obj := range objs { - if err := txn.Delete(table, obj); err != nil { - return num, err - } - num++ - } - return num, nil -} - -// FirstWatch is used to return the first matching object for -// the given constraints on the index along with the watch channel -func (txn *Txn) FirstWatch(table, index string, args ...interface{}) (<-chan struct{}, interface{}, error) { - // Get the index value - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, nil, err - } - - // Get the index itself - indexTxn := txn.readableIndex(table, indexSchema.Name) - - // Do an exact lookup - if indexSchema.Unique && val != nil && indexSchema.Name == index { - watch, obj, ok := indexTxn.GetWatch(val) - if !ok { - return watch, nil, nil - } - return watch, obj, nil - } - - // Handle non-unique index by using an iterator and getting the first value - iter := indexTxn.Root().Iterator() - watch := iter.SeekPrefixWatch(val) - _, value, _ := iter.Next() - return watch, value, nil -} - -// First is used to return the first matching object for -// the given constraints on the index -func (txn *Txn) First(table, index string, args ...interface{}) (interface{}, error) { - _, val, err := txn.FirstWatch(table, index, args...) - return val, err -} - -// LongestPrefix is used to fetch the longest prefix match for the given -// constraints on the index. Note that this will not work with the memdb -// StringFieldIndex because it adds null terminators which prevent the -// algorithm from correctly finding a match (it will get to right before the -// null and fail to find a leaf node). This should only be used where the prefix -// given is capable of matching indexed entries directly, which typically only -// applies to a custom indexer. See the unit test for an example. -func (txn *Txn) LongestPrefix(table, index string, args ...interface{}) (interface{}, error) { - // Enforce that this only works on prefix indexes. - if !strings.HasSuffix(index, "_prefix") { - return nil, fmt.Errorf("must use '%s_prefix' on index", index) - } - - // Get the index value. - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, err - } - - // This algorithm only makes sense against a unique index, otherwise the - // index keys will have the IDs appended to them. - if !indexSchema.Unique { - return nil, fmt.Errorf("index '%s' is not unique", index) - } - - // Find the longest prefix match with the given index. - indexTxn := txn.readableIndex(table, indexSchema.Name) - if _, value, ok := indexTxn.Root().LongestPrefix(val); ok { - return value, nil - } - return nil, nil -} - -// getIndexValue is used to get the IndexSchema and the value -// used to scan the index given the parameters. This handles prefix based -// scans when the index has the "_prefix" suffix. The index must support -// prefix iteration. -func (txn *Txn) getIndexValue(table, index string, args ...interface{}) (*IndexSchema, []byte, error) { - // Get the table schema - tableSchema, ok := txn.db.schema.Tables[table] - if !ok { - return nil, nil, fmt.Errorf("invalid table '%s'", table) - } - - // Check for a prefix scan - prefixScan := false - if strings.HasSuffix(index, "_prefix") { - index = strings.TrimSuffix(index, "_prefix") - prefixScan = true - } - - // Get the index schema - indexSchema, ok := tableSchema.Indexes[index] - if !ok { - return nil, nil, fmt.Errorf("invalid index '%s'", index) - } - - // Hot-path for when there are no arguments - if len(args) == 0 { - return indexSchema, nil, nil - } - - // Special case the prefix scanning - if prefixScan { - prefixIndexer, ok := indexSchema.Indexer.(PrefixIndexer) - if !ok { - return indexSchema, nil, - fmt.Errorf("index '%s' does not support prefix scanning", index) - } - - val, err := prefixIndexer.PrefixFromArgs(args...) - if err != nil { - return indexSchema, nil, fmt.Errorf("index error: %v", err) - } - return indexSchema, val, err - } - - // Get the exact match index - val, err := indexSchema.Indexer.FromArgs(args...) - if err != nil { - return indexSchema, nil, fmt.Errorf("index error: %v", err) - } - return indexSchema, val, err -} - -// ResultIterator is used to iterate over a list of results -// from a Get query on a table. -type ResultIterator interface { - WatchCh() <-chan struct{} - Next() interface{} -} - -// Get is used to construct a ResultIterator over all the -// rows that match the given constraints of an index. -func (txn *Txn) Get(table, index string, args ...interface{}) (ResultIterator, error) { - // Get the index value to scan - indexSchema, val, err := txn.getIndexValue(table, index, args...) - if err != nil { - return nil, err - } - - // Get the index itself - indexTxn := txn.readableIndex(table, indexSchema.Name) - indexRoot := indexTxn.Root() - - // Get an interator over the index - indexIter := indexRoot.Iterator() - - // Seek the iterator to the appropriate sub-set - watchCh := indexIter.SeekPrefixWatch(val) - - // Create an iterator - iter := &radixIterator{ - iter: indexIter, - watchCh: watchCh, - } - return iter, nil -} - -// Defer is used to push a new arbitrary function onto a stack which -// gets called when a transaction is committed and finished. Deferred -// functions are called in LIFO order, and only invoked at the end of -// write transactions. -func (txn *Txn) Defer(fn func()) { - txn.after = append(txn.after, fn) -} - -// radixIterator is used to wrap an underlying iradix iterator. -// This is much more efficient than a sliceIterator as we are not -// materializing the entire view. -type radixIterator struct { - iter *iradix.Iterator - watchCh <-chan struct{} -} - -func (r *radixIterator) WatchCh() <-chan struct{} { - return r.watchCh -} - -func (r *radixIterator) Next() interface{} { - _, value, ok := r.iter.Next() - if !ok { - return nil - } - return value -} diff --git a/vendor/github.com/hashicorp/go-memdb/watch.go b/vendor/github.com/hashicorp/go-memdb/watch.go deleted file mode 100644 index a6f01213b..000000000 --- a/vendor/github.com/hashicorp/go-memdb/watch.go +++ /dev/null @@ -1,129 +0,0 @@ -package memdb - -import ( - "context" - "time" -) - -// WatchSet is a collection of watch channels. -type WatchSet map[<-chan struct{}]struct{} - -// NewWatchSet constructs a new watch set. -func NewWatchSet() WatchSet { - return make(map[<-chan struct{}]struct{}) -} - -// Add appends a watchCh to the WatchSet if non-nil. -func (w WatchSet) Add(watchCh <-chan struct{}) { - if w == nil { - return - } - - if _, ok := w[watchCh]; !ok { - w[watchCh] = struct{}{} - } -} - -// AddWithLimit appends a watchCh to the WatchSet if non-nil, and if the given -// softLimit hasn't been exceeded. Otherwise, it will watch the given alternate -// channel. It's expected that the altCh will be the same on many calls to this -// function, so you will exceed the soft limit a little bit if you hit this, but -// not by much. -// -// This is useful if you want to track individual items up to some limit, after -// which you watch a higher-level channel (usually a channel from start start of -// an iterator higher up in the radix tree) that will watch a superset of items. -func (w WatchSet) AddWithLimit(softLimit int, watchCh <-chan struct{}, altCh <-chan struct{}) { - // This is safe for a nil WatchSet so we don't need to check that here. - if len(w) < softLimit { - w.Add(watchCh) - } else { - w.Add(altCh) - } -} - -// Watch is used to wait for either the watch set to trigger or a timeout. -// Returns true on timeout. -func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { - if w == nil { - return false - } - - // Create a context that gets cancelled when the timeout is triggered - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - go func() { - select { - case <-timeoutCh: - cancel() - case <-ctx.Done(): - } - }() - - return w.WatchCtx(ctx) == context.Canceled -} - -// WatchCtx is used to wait for either the watch set to trigger or for the -// context to be cancelled. Watch with a timeout channel can be mimicked by -// creating a context with a deadline. WatchCtx should be preferred over Watch. -func (w WatchSet) WatchCtx(ctx context.Context) error { - if w == nil { - return nil - } - - if n := len(w); n <= aFew { - idx := 0 - chunk := make([]<-chan struct{}, aFew) - for watchCh := range w { - chunk[idx] = watchCh - idx++ - } - return watchFew(ctx, chunk) - } - - return w.watchMany(ctx) -} - -// watchMany is used if there are many watchers. -func (w WatchSet) watchMany(ctx context.Context) error { - // Set up a goroutine for each watcher. - triggerCh := make(chan struct{}, 1) - watcher := func(chunk []<-chan struct{}) { - if err := watchFew(ctx, chunk); err == nil { - select { - case triggerCh <- struct{}{}: - default: - } - } - } - - // Apportion the watch channels into chunks we can feed into the - // watchFew helper. - idx := 0 - chunk := make([]<-chan struct{}, aFew) - for watchCh := range w { - subIdx := idx % aFew - chunk[subIdx] = watchCh - idx++ - - // Fire off this chunk and start a fresh one. - if idx%aFew == 0 { - go watcher(chunk) - chunk = make([]<-chan struct{}, aFew) - } - } - - // Make sure to watch any residual channels in the last chunk. - if idx%aFew != 0 { - go watcher(chunk) - } - - // Wait for a channel to trigger or timeout. - select { - case <-triggerCh: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} diff --git a/vendor/github.com/hashicorp/go-memdb/watch_few.go b/vendor/github.com/hashicorp/go-memdb/watch_few.go deleted file mode 100644 index 880f098b7..000000000 --- a/vendor/github.com/hashicorp/go-memdb/watch_few.go +++ /dev/null @@ -1,117 +0,0 @@ -package memdb - -//go:generate sh -c "go run watch-gen/main.go >watch_few.go" - -import( - "context" -) - -// aFew gives how many watchers this function is wired to support. You must -// always pass a full slice of this length, but unused channels can be nil. -const aFew = 32 - -// watchFew is used if there are only a few watchers as a performance -// optimization. -func watchFew(ctx context.Context, ch []<-chan struct{}) error { - select { - - case <-ch[0]: - return nil - - case <-ch[1]: - return nil - - case <-ch[2]: - return nil - - case <-ch[3]: - return nil - - case <-ch[4]: - return nil - - case <-ch[5]: - return nil - - case <-ch[6]: - return nil - - case <-ch[7]: - return nil - - case <-ch[8]: - return nil - - case <-ch[9]: - return nil - - case <-ch[10]: - return nil - - case <-ch[11]: - return nil - - case <-ch[12]: - return nil - - case <-ch[13]: - return nil - - case <-ch[14]: - return nil - - case <-ch[15]: - return nil - - case <-ch[16]: - return nil - - case <-ch[17]: - return nil - - case <-ch[18]: - return nil - - case <-ch[19]: - return nil - - case <-ch[20]: - return nil - - case <-ch[21]: - return nil - - case <-ch[22]: - return nil - - case <-ch[23]: - return nil - - case <-ch[24]: - return nil - - case <-ch[25]: - return nil - - case <-ch[26]: - return nil - - case <-ch[27]: - return nil - - case <-ch[28]: - return nil - - case <-ch[29]: - return nil - - case <-ch[30]: - return nil - - case <-ch[31]: - return nil - - case <-ctx.Done(): - return ctx.Err() - } -} diff --git a/vendor/github.com/hashicorp/go-multierror/.travis.yml b/vendor/github.com/hashicorp/go-multierror/.travis.yml new file mode 100644 index 000000000..304a83595 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/.travis.yml @@ -0,0 +1,12 @@ +sudo: false + +language: go + +go: + - 1.x + +branches: + only: + - master + +script: make test testrace diff --git a/vendor/github.com/hashicorp/go-multierror/Makefile b/vendor/github.com/hashicorp/go-multierror/Makefile new file mode 100644 index 000000000..b97cd6ed0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/Makefile @@ -0,0 +1,31 @@ +TEST?=./... + +default: test + +# test runs the test suite and vets the code. +test: generate + @echo "==> Running tests..." + @go list $(TEST) \ + | grep -v "/vendor/" \ + | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} + +# testrace runs the race checker +testrace: generate + @echo "==> Running tests (race)..." + @go list $(TEST) \ + | grep -v "/vendor/" \ + | xargs -n1 go test -timeout=60s -race ${TESTARGS} + +# updatedeps installs all the dependencies needed to run and build. +updatedeps: + @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" + +# generate runs `go generate` to build the dynamically generated source files. +generate: + @echo "==> Generating..." + @find . -type f -name '.DS_Store' -delete + @go list ./... \ + | grep -v "/vendor/" \ + | xargs -n1 go generate + +.PHONY: default test testrace updatedeps generate diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md index e81be50e0..ead5830f7 100644 --- a/vendor/github.com/hashicorp/go-multierror/README.md +++ b/vendor/github.com/hashicorp/go-multierror/README.md @@ -1,5 +1,11 @@ # go-multierror +[![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis] +[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] + +[travis]: https://travis-ci.org/hashicorp/go-multierror +[godocs]: https://godoc.org/github.com/hashicorp/go-multierror + `go-multierror` is a package for Go that provides a mechanism for representing a list of `error` values as a single `error`. diff --git a/vendor/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/hashicorp/go-multierror/append.go index 00afa9b35..775b6e753 100644 --- a/vendor/github.com/hashicorp/go-multierror/append.go +++ b/vendor/github.com/hashicorp/go-multierror/append.go @@ -18,9 +18,13 @@ func Append(err error, errs ...error) *Error { for _, e := range errs { switch e := e.(type) { case *Error: - err.Errors = append(err.Errors, e.Errors...) + if e != nil { + err.Errors = append(err.Errors, e.Errors...) + } default: - err.Errors = append(err.Errors, e) + if e != nil { + err.Errors = append(err.Errors, e) + } } } diff --git a/vendor/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/hashicorp/go-multierror/format.go index bb65a12e7..47f13c49a 100644 --- a/vendor/github.com/hashicorp/go-multierror/format.go +++ b/vendor/github.com/hashicorp/go-multierror/format.go @@ -12,12 +12,16 @@ type ErrorFormatFunc func([]error) string // ListFormatFunc is a basic formatter that outputs the number of errors // that occurred along with a bullet point list of the errors. func ListFormatFunc(es []error) string { + if len(es) == 1 { + return fmt.Sprintf("1 error occurred:\n\t* %s\n\n", es[0]) + } + points := make([]string, len(es)) for i, err := range es { points[i] = fmt.Sprintf("* %s", err) } return fmt.Sprintf( - "%d error(s) occurred:\n\n%s", - len(es), strings.Join(points, "\n")) + "%d errors occurred:\n\t%s\n\n", + len(es), strings.Join(points, "\n\t")) } diff --git a/vendor/github.com/hashicorp/go-multierror/go.mod b/vendor/github.com/hashicorp/go-multierror/go.mod new file mode 100644 index 000000000..2534331d5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/go.mod @@ -0,0 +1,3 @@ +module github.com/hashicorp/go-multierror + +require github.com/hashicorp/errwrap v1.0.0 diff --git a/vendor/github.com/hashicorp/go-multierror/go.sum b/vendor/github.com/hashicorp/go-multierror/go.sum new file mode 100644 index 000000000..85b1f8ff3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/go.sum @@ -0,0 +1,4 @@ +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4= +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go index 2ea082732..89b1422d1 100644 --- a/vendor/github.com/hashicorp/go-multierror/multierror.go +++ b/vendor/github.com/hashicorp/go-multierror/multierror.go @@ -40,11 +40,11 @@ func (e *Error) GoString() string { } // WrappedErrors returns the list of errors that this Error is wrapping. -// It is an implementatin of the errwrap.Wrapper interface so that +// It is an implementation of the errwrap.Wrapper interface so that // multierror.Error can be used with that library. // // This method is not safe to be called concurrently and is no different -// than accessing the Errors field directly. It is implementd only to +// than accessing the Errors field directly. It is implemented only to // satisfy the errwrap.Wrapper interface. func (e *Error) WrappedErrors() []error { return e.Errors diff --git a/vendor/github.com/hashicorp/go-multierror/sort.go b/vendor/github.com/hashicorp/go-multierror/sort.go new file mode 100644 index 000000000..fecb14e81 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/sort.go @@ -0,0 +1,16 @@ +package multierror + +// Len implements sort.Interface function for length +func (err Error) Len() int { + return len(err.Errors) +} + +// Swap implements sort.Interface function for swapping elements +func (err Error) Swap(i, j int) { + err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i] +} + +// Less implements sort.Interface function for determining order +func (err Error) Less(i, j int) bool { + return err.Errors[i].Error() < err.Errors[j].Error() +} diff --git a/vendor/github.com/hashicorp/go-plugin/.gitignore b/vendor/github.com/hashicorp/go-plugin/.gitignore new file mode 100644 index 000000000..e43b0f988 --- /dev/null +++ b/vendor/github.com/hashicorp/go-plugin/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore b/vendor/github.com/hashicorp/go-retryablehttp/.gitignore new file mode 100644 index 000000000..caab963a3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/.gitignore @@ -0,0 +1,3 @@ +.idea/ +*.iml +*.test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml b/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml new file mode 100644 index 000000000..2df4e7dfa --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/.travis.yml @@ -0,0 +1,12 @@ +sudo: false + +language: go + +go: + - 1.8.1 + +branches: + only: + - master + +script: make updatedeps test diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go index 21f45e5ed..e54c3cec1 100644 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ b/vendor/github.com/hashicorp/go-retryablehttp/client.go @@ -183,18 +183,24 @@ func NewRequest(method, url string, rawBody interface{}) (*Request, error) { return &Request{body, httpReq}, nil } +// Logger interface allows to use other loggers than +// standard log.Logger. +type Logger interface { + Printf(string, ...interface{}) +} + // RequestLogHook allows a function to run before each retry. The HTTP // request which will be made, and the retry number (0 for the initial // request) are available to users. The internal logger is exposed to // consumers. -type RequestLogHook func(*log.Logger, *http.Request, int) +type RequestLogHook func(Logger, *http.Request, int) // ResponseLogHook is like RequestLogHook, but allows running a function // on each HTTP response. This function will be invoked at the end of // every HTTP request executed, regardless of whether a subsequent retry // needs to be performed or not. If the response body is read or closed // from this method, this will affect the response returned from Do(). -type ResponseLogHook func(*log.Logger, *http.Response) +type ResponseLogHook func(Logger, *http.Response) // CheckRetry specifies a policy for handling retries. It is called // following each request with the response and error values returned by @@ -221,7 +227,7 @@ type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Resp // like automatic retries to tolerate minor outages. type Client struct { HTTPClient *http.Client // Internal HTTP client. - Logger *log.Logger // Customer logger instance. + Logger Logger // Customer logger instance. RetryWaitMin time.Duration // Minimum time to wait RetryWaitMax time.Duration // Maximum time to wait diff --git a/vendor/github.com/hashicorp/go-retryablehttp/go.mod b/vendor/github.com/hashicorp/go-retryablehttp/go.mod new file mode 100644 index 000000000..d28c8c8eb --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/go.mod @@ -0,0 +1,3 @@ +module github.com/hashicorp/go-retryablehttp + +require github.com/hashicorp/go-cleanhttp v0.5.0 diff --git a/vendor/github.com/hashicorp/go-retryablehttp/go.sum b/vendor/github.com/hashicorp/go-retryablehttp/go.sum new file mode 100644 index 000000000..3ed0fd98e --- /dev/null +++ b/vendor/github.com/hashicorp/go-retryablehttp/go.sum @@ -0,0 +1,2 @@ +github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= diff --git a/vendor/github.com/hashicorp/go-rootcerts/.travis.yml b/vendor/github.com/hashicorp/go-rootcerts/.travis.yml new file mode 100644 index 000000000..80e1de44e --- /dev/null +++ b/vendor/github.com/hashicorp/go-rootcerts/.travis.yml @@ -0,0 +1,12 @@ +sudo: false + +language: go + +go: + - 1.6 + +branches: + only: + - master + +script: make test diff --git a/vendor/github.com/hashicorp/go-sockaddr/.gitignore b/vendor/github.com/hashicorp/go-sockaddr/.gitignore new file mode 100644 index 000000000..41720b86e --- /dev/null +++ b/vendor/github.com/hashicorp/go-sockaddr/.gitignore @@ -0,0 +1,26 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +.cover.out* +coverage.html diff --git a/vendor/github.com/hashicorp/go-sockaddr/go.mod b/vendor/github.com/hashicorp/go-sockaddr/go.mod new file mode 100644 index 000000000..7c07b5bad --- /dev/null +++ b/vendor/github.com/hashicorp/go-sockaddr/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/go-sockaddr diff --git a/vendor/github.com/hashicorp/go-syslog/LICENSE b/vendor/github.com/hashicorp/go-syslog/LICENSE deleted file mode 100644 index a5df10e67..000000000 --- a/vendor/github.com/hashicorp/go-syslog/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Armon Dadgar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/hashicorp/go-syslog/README.md b/vendor/github.com/hashicorp/go-syslog/README.md deleted file mode 100644 index bbfae8f9b..000000000 --- a/vendor/github.com/hashicorp/go-syslog/README.md +++ /dev/null @@ -1,11 +0,0 @@ -go-syslog -========= - -This repository provides a very simple `gsyslog` package. The point of this -package is to allow safe importing of syslog without introducing cross-compilation -issues. The stdlib `log/syslog` cannot be imported on Windows systems, and without -conditional compilation this adds complications. - -Instead, `gsyslog` provides a very simple wrapper around `log/syslog` but returns -a runtime error if attempting to initialize on a non Linux or OSX system. - diff --git a/vendor/github.com/hashicorp/go-syslog/builtin.go b/vendor/github.com/hashicorp/go-syslog/builtin.go deleted file mode 100644 index 72bdd61c9..000000000 --- a/vendor/github.com/hashicorp/go-syslog/builtin.go +++ /dev/null @@ -1,214 +0,0 @@ -// This file is taken from the log/syslog in the standard lib. -// However, there is a bug with overwhelming syslog that causes writes -// to block indefinitely. This is fixed by adding a write deadline. -// -// +build !windows,!nacl,!plan9 - -package gsyslog - -import ( - "errors" - "fmt" - "log/syslog" - "net" - "os" - "strings" - "sync" - "time" -) - -const severityMask = 0x07 -const facilityMask = 0xf8 -const localDeadline = 20 * time.Millisecond -const remoteDeadline = 50 * time.Millisecond - -// A builtinWriter is a connection to a syslog server. -type builtinWriter struct { - priority syslog.Priority - tag string - hostname string - network string - raddr string - - mu sync.Mutex // guards conn - conn serverConn -} - -// This interface and the separate syslog_unix.go file exist for -// Solaris support as implemented by gccgo. On Solaris you can not -// simply open a TCP connection to the syslog daemon. The gccgo -// sources have a syslog_solaris.go file that implements unixSyslog to -// return a type that satisfies this interface and simply calls the C -// library syslog function. -type serverConn interface { - writeString(p syslog.Priority, hostname, tag, s, nl string) error - close() error -} - -type netConn struct { - local bool - conn net.Conn -} - -// New establishes a new connection to the system log daemon. Each -// write to the returned writer sends a log message with the given -// priority and prefix. -func newBuiltin(priority syslog.Priority, tag string) (w *builtinWriter, err error) { - return dialBuiltin("", "", priority, tag) -} - -// Dial establishes a connection to a log daemon by connecting to -// address raddr on the specified network. Each write to the returned -// writer sends a log message with the given facility, severity and -// tag. -// If network is empty, Dial will connect to the local syslog server. -func dialBuiltin(network, raddr string, priority syslog.Priority, tag string) (*builtinWriter, error) { - if priority < 0 || priority > syslog.LOG_LOCAL7|syslog.LOG_DEBUG { - return nil, errors.New("log/syslog: invalid priority") - } - - if tag == "" { - tag = os.Args[0] - } - hostname, _ := os.Hostname() - - w := &builtinWriter{ - priority: priority, - tag: tag, - hostname: hostname, - network: network, - raddr: raddr, - } - - w.mu.Lock() - defer w.mu.Unlock() - - err := w.connect() - if err != nil { - return nil, err - } - return w, err -} - -// connect makes a connection to the syslog server. -// It must be called with w.mu held. -func (w *builtinWriter) connect() (err error) { - if w.conn != nil { - // ignore err from close, it makes sense to continue anyway - w.conn.close() - w.conn = nil - } - - if w.network == "" { - w.conn, err = unixSyslog() - if w.hostname == "" { - w.hostname = "localhost" - } - } else { - var c net.Conn - c, err = net.DialTimeout(w.network, w.raddr, remoteDeadline) - if err == nil { - w.conn = &netConn{conn: c} - if w.hostname == "" { - w.hostname = c.LocalAddr().String() - } - } - } - return -} - -// Write sends a log message to the syslog daemon. -func (w *builtinWriter) Write(b []byte) (int, error) { - return w.writeAndRetry(w.priority, string(b)) -} - -// Close closes a connection to the syslog daemon. -func (w *builtinWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - - if w.conn != nil { - err := w.conn.close() - w.conn = nil - return err - } - return nil -} - -func (w *builtinWriter) writeAndRetry(p syslog.Priority, s string) (int, error) { - pr := (w.priority & facilityMask) | (p & severityMask) - - w.mu.Lock() - defer w.mu.Unlock() - - if w.conn != nil { - if n, err := w.write(pr, s); err == nil { - return n, err - } - } - if err := w.connect(); err != nil { - return 0, err - } - return w.write(pr, s) -} - -// write generates and writes a syslog formatted string. The -// format is as follows: TIMESTAMP HOSTNAME TAG[PID]: MSG -func (w *builtinWriter) write(p syslog.Priority, msg string) (int, error) { - // ensure it ends in a \n - nl := "" - if !strings.HasSuffix(msg, "\n") { - nl = "\n" - } - - err := w.conn.writeString(p, w.hostname, w.tag, msg, nl) - if err != nil { - return 0, err - } - // Note: return the length of the input, not the number of - // bytes printed by Fprintf, because this must behave like - // an io.Writer. - return len(msg), nil -} - -func (n *netConn) writeString(p syslog.Priority, hostname, tag, msg, nl string) error { - if n.local { - // Compared to the network form below, the changes are: - // 1. Use time.Stamp instead of time.RFC3339. - // 2. Drop the hostname field from the Fprintf. - timestamp := time.Now().Format(time.Stamp) - n.conn.SetWriteDeadline(time.Now().Add(localDeadline)) - _, err := fmt.Fprintf(n.conn, "<%d>%s %s[%d]: %s%s", - p, timestamp, - tag, os.Getpid(), msg, nl) - return err - } - timestamp := time.Now().Format(time.RFC3339) - n.conn.SetWriteDeadline(time.Now().Add(remoteDeadline)) - _, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s%s", - p, timestamp, hostname, - tag, os.Getpid(), msg, nl) - return err -} - -func (n *netConn) close() error { - return n.conn.Close() -} - -// unixSyslog opens a connection to the syslog daemon running on the -// local machine using a Unix domain socket. -func unixSyslog() (conn serverConn, err error) { - logTypes := []string{"unixgram", "unix"} - logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"} - for _, network := range logTypes { - for _, path := range logPaths { - conn, err := net.DialTimeout(network, path, localDeadline) - if err != nil { - continue - } else { - return &netConn{conn: conn, local: true}, nil - } - } - } - return nil, errors.New("Unix syslog delivery error") -} diff --git a/vendor/github.com/hashicorp/go-syslog/syslog.go b/vendor/github.com/hashicorp/go-syslog/syslog.go deleted file mode 100644 index 3f5a6f3fb..000000000 --- a/vendor/github.com/hashicorp/go-syslog/syslog.go +++ /dev/null @@ -1,27 +0,0 @@ -package gsyslog - -// Priority maps to the syslog priority levels -type Priority int - -const ( - LOG_EMERG Priority = iota - LOG_ALERT - LOG_CRIT - LOG_ERR - LOG_WARNING - LOG_NOTICE - LOG_INFO - LOG_DEBUG -) - -// Syslogger interface is used to write log messages to syslog -type Syslogger interface { - // WriteLevel is used to write a message at a given level - WriteLevel(Priority, []byte) error - - // Write is used to write a message at the default level - Write([]byte) (int, error) - - // Close is used to close the connection to the logger - Close() error -} diff --git a/vendor/github.com/hashicorp/go-syslog/unix.go b/vendor/github.com/hashicorp/go-syslog/unix.go deleted file mode 100644 index 70b71802e..000000000 --- a/vendor/github.com/hashicorp/go-syslog/unix.go +++ /dev/null @@ -1,123 +0,0 @@ -// +build linux darwin dragonfly freebsd netbsd openbsd solaris - -package gsyslog - -import ( - "fmt" - "log/syslog" - "strings" -) - -// builtinLogger wraps the Golang implementation of a -// syslog.Writer to provide the Syslogger interface -type builtinLogger struct { - *builtinWriter -} - -// NewLogger is used to construct a new Syslogger -func NewLogger(p Priority, facility, tag string) (Syslogger, error) { - fPriority, err := facilityPriority(facility) - if err != nil { - return nil, err - } - priority := syslog.Priority(p) | fPriority - l, err := newBuiltin(priority, tag) - if err != nil { - return nil, err - } - return &builtinLogger{l}, nil -} - -// DialLogger is used to construct a new Syslogger that establishes connection to remote syslog server -func DialLogger(network, raddr string, p Priority, facility, tag string) (Syslogger, error) { - fPriority, err := facilityPriority(facility) - if err != nil { - return nil, err - } - - priority := syslog.Priority(p) | fPriority - - l, err := dialBuiltin(network, raddr, priority, tag) - if err != nil { - return nil, err - } - - return &builtinLogger{l}, nil -} - -// WriteLevel writes out a message at the given priority -func (b *builtinLogger) WriteLevel(p Priority, buf []byte) error { - var err error - m := string(buf) - switch p { - case LOG_EMERG: - _, err = b.writeAndRetry(syslog.LOG_EMERG, m) - case LOG_ALERT: - _, err = b.writeAndRetry(syslog.LOG_ALERT, m) - case LOG_CRIT: - _, err = b.writeAndRetry(syslog.LOG_CRIT, m) - case LOG_ERR: - _, err = b.writeAndRetry(syslog.LOG_ERR, m) - case LOG_WARNING: - _, err = b.writeAndRetry(syslog.LOG_WARNING, m) - case LOG_NOTICE: - _, err = b.writeAndRetry(syslog.LOG_NOTICE, m) - case LOG_INFO: - _, err = b.writeAndRetry(syslog.LOG_INFO, m) - case LOG_DEBUG: - _, err = b.writeAndRetry(syslog.LOG_DEBUG, m) - default: - err = fmt.Errorf("Unknown priority: %v", p) - } - return err -} - -// facilityPriority converts a facility string into -// an appropriate priority level or returns an error -func facilityPriority(facility string) (syslog.Priority, error) { - facility = strings.ToUpper(facility) - switch facility { - case "KERN": - return syslog.LOG_KERN, nil - case "USER": - return syslog.LOG_USER, nil - case "MAIL": - return syslog.LOG_MAIL, nil - case "DAEMON": - return syslog.LOG_DAEMON, nil - case "AUTH": - return syslog.LOG_AUTH, nil - case "SYSLOG": - return syslog.LOG_SYSLOG, nil - case "LPR": - return syslog.LOG_LPR, nil - case "NEWS": - return syslog.LOG_NEWS, nil - case "UUCP": - return syslog.LOG_UUCP, nil - case "CRON": - return syslog.LOG_CRON, nil - case "AUTHPRIV": - return syslog.LOG_AUTHPRIV, nil - case "FTP": - return syslog.LOG_FTP, nil - case "LOCAL0": - return syslog.LOG_LOCAL0, nil - case "LOCAL1": - return syslog.LOG_LOCAL1, nil - case "LOCAL2": - return syslog.LOG_LOCAL2, nil - case "LOCAL3": - return syslog.LOG_LOCAL3, nil - case "LOCAL4": - return syslog.LOG_LOCAL4, nil - case "LOCAL5": - return syslog.LOG_LOCAL5, nil - case "LOCAL6": - return syslog.LOG_LOCAL6, nil - case "LOCAL7": - return syslog.LOG_LOCAL7, nil - default: - return 0, fmt.Errorf("invalid syslog facility: %s", facility) - } -} diff --git a/vendor/github.com/hashicorp/go-syslog/unsupported.go b/vendor/github.com/hashicorp/go-syslog/unsupported.go deleted file mode 100644 index b8ca3a5c7..000000000 --- a/vendor/github.com/hashicorp/go-syslog/unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build windows plan9 nacl - -package gsyslog - -import ( - "fmt" -) - -// NewLogger is used to construct a new Syslogger -func NewLogger(p Priority, facility, tag string) (Syslogger, error) { - return nil, fmt.Errorf("Platform does not support syslog") -} - -// DialLogger is used to construct a new Syslogger that establishes connection to remote syslog server -func DialLogger(network, raddr string, p Priority, facility, tag string) (Syslogger, error) { - return nil, fmt.Errorf("Platform does not support syslog") -} diff --git a/vendor/github.com/hashicorp/go-uuid/.travis.yml b/vendor/github.com/hashicorp/go-uuid/.travis.yml new file mode 100644 index 000000000..769849071 --- /dev/null +++ b/vendor/github.com/hashicorp/go-uuid/.travis.yml @@ -0,0 +1,12 @@ +language: go + +sudo: false + +go: + - 1.4 + - 1.5 + - 1.6 + - tip + +script: + - go test -bench . -benchmem -v ./... diff --git a/vendor/github.com/hashicorp/go-uuid/README.md b/vendor/github.com/hashicorp/go-uuid/README.md index 21fdda4ad..fbde8b9ae 100644 --- a/vendor/github.com/hashicorp/go-uuid/README.md +++ b/vendor/github.com/hashicorp/go-uuid/README.md @@ -1,6 +1,6 @@ -# uuid +# uuid [![Build Status](https://travis-ci.org/hashicorp/go-uuid.svg?branch=master)](https://travis-ci.org/hashicorp/go-uuid) -Generates UUID-format strings using purely high quality random bytes. +Generates UUID-format strings using high quality, _purely random_ bytes. It is **not** intended to be RFC compliant, merely to use a well-understood string representation of a 128-bit value. It can also parse UUID-format strings into their component bytes. Documentation ============= diff --git a/vendor/github.com/hashicorp/go-uuid/go.mod b/vendor/github.com/hashicorp/go-uuid/go.mod new file mode 100644 index 000000000..dd57f9d21 --- /dev/null +++ b/vendor/github.com/hashicorp/go-uuid/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/go-uuid diff --git a/vendor/github.com/hashicorp/go-uuid/uuid.go b/vendor/github.com/hashicorp/go-uuid/uuid.go index 322b522c2..911227f61 100644 --- a/vendor/github.com/hashicorp/go-uuid/uuid.go +++ b/vendor/github.com/hashicorp/go-uuid/uuid.go @@ -6,22 +6,32 @@ import ( "fmt" ) -// GenerateUUID is used to generate a random UUID -func GenerateUUID() (string, error) { - buf := make([]byte, 16) +// GenerateRandomBytes is used to generate random bytes of given size. +func GenerateRandomBytes(size int) ([]byte, error) { + buf := make([]byte, size) if _, err := rand.Read(buf); err != nil { - return "", fmt.Errorf("failed to read random bytes: %v", err) + return nil, fmt.Errorf("failed to read random bytes: %v", err) } + return buf, nil +} +const uuidLen = 16 + +// GenerateUUID is used to generate a random UUID +func GenerateUUID() (string, error) { + buf, err := GenerateRandomBytes(uuidLen) + if err != nil { + return "", err + } return FormatUUID(buf) } func FormatUUID(buf []byte) (string, error) { - if len(buf) != 16 { - return "", fmt.Errorf("wrong length byte slice (%d)", len(buf)) + if buflen := len(buf); buflen != uuidLen { + return "", fmt.Errorf("wrong length byte slice (%d)", buflen) } - return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x", + return fmt.Sprintf("%x-%x-%x-%x-%x", buf[0:4], buf[4:6], buf[6:8], @@ -30,16 +40,14 @@ func FormatUUID(buf []byte) (string, error) { } func ParseUUID(uuid string) ([]byte, error) { - if len(uuid) != 36 { + if len(uuid) != 2 * uuidLen + 4 { return nil, fmt.Errorf("uuid string is wrong length") } - hyph := []byte("-") - - if uuid[8] != hyph[0] || - uuid[13] != hyph[0] || - uuid[18] != hyph[0] || - uuid[23] != hyph[0] { + if uuid[8] != '-' || + uuid[13] != '-' || + uuid[18] != '-' || + uuid[23] != '-' { return nil, fmt.Errorf("uuid is improperly formatted") } @@ -49,7 +57,7 @@ func ParseUUID(uuid string) ([]byte, error) { if err != nil { return nil, err } - if len(ret) != 16 { + if len(ret) != uuidLen { return nil, fmt.Errorf("decoded hex is the wrong length") } diff --git a/vendor/github.com/hashicorp/go-version/.travis.yml b/vendor/github.com/hashicorp/go-version/.travis.yml new file mode 100644 index 000000000..542ca8b7f --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - 1.0 + - 1.1 + - 1.2 + - 1.3 + - 1.4 + - 1.9 + - "1.10" + +script: + - go test diff --git a/vendor/github.com/hashicorp/golang-lru/2q.go b/vendor/github.com/hashicorp/golang-lru/2q.go deleted file mode 100644 index e474cd075..000000000 --- a/vendor/github.com/hashicorp/golang-lru/2q.go +++ /dev/null @@ -1,223 +0,0 @@ -package lru - -import ( - "fmt" - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -const ( - // Default2QRecentRatio is the ratio of the 2Q cache dedicated - // to recently added entries that have only been accessed once. - Default2QRecentRatio = 0.25 - - // Default2QGhostEntries is the default ratio of ghost - // entries kept to track entries recently evicted - Default2QGhostEntries = 0.50 -) - -// TwoQueueCache is a thread-safe fixed size 2Q cache. -// 2Q is an enhancement over the standard LRU cache -// in that it tracks both frequently and recently used -// entries separately. This avoids a burst in access to new -// entries from evicting frequently used entries. It adds some -// additional tracking overhead to the standard LRU cache, and is -// computationally about 2x the cost, and adds some metadata over -// head. The ARCCache is similar, but does not require setting any -// parameters. -type TwoQueueCache struct { - size int - recentSize int - - recent simplelru.LRUCache - frequent simplelru.LRUCache - recentEvict simplelru.LRUCache - lock sync.RWMutex -} - -// New2Q creates a new TwoQueueCache using the default -// values for the parameters. -func New2Q(size int) (*TwoQueueCache, error) { - return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries) -} - -// New2QParams creates a new TwoQueueCache using the provided -// parameter values. -func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) { - if size <= 0 { - return nil, fmt.Errorf("invalid size") - } - if recentRatio < 0.0 || recentRatio > 1.0 { - return nil, fmt.Errorf("invalid recent ratio") - } - if ghostRatio < 0.0 || ghostRatio > 1.0 { - return nil, fmt.Errorf("invalid ghost ratio") - } - - // Determine the sub-sizes - recentSize := int(float64(size) * recentRatio) - evictSize := int(float64(size) * ghostRatio) - - // Allocate the LRUs - recent, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - frequent, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - recentEvict, err := simplelru.NewLRU(evictSize, nil) - if err != nil { - return nil, err - } - - // Initialize the cache - c := &TwoQueueCache{ - size: size, - recentSize: recentSize, - recent: recent, - frequent: frequent, - recentEvict: recentEvict, - } - return c, nil -} - -// Get looks up a key's value from the cache. -func (c *TwoQueueCache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if this is a frequent value - if val, ok := c.frequent.Get(key); ok { - return val, ok - } - - // If the value is contained in recent, then we - // promote it to frequent - if val, ok := c.recent.Peek(key); ok { - c.recent.Remove(key) - c.frequent.Add(key, val) - return val, ok - } - - // No hit - return nil, false -} - -// Add adds a value to the cache. -func (c *TwoQueueCache) Add(key, value interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the value is frequently used already, - // and just update the value - if c.frequent.Contains(key) { - c.frequent.Add(key, value) - return - } - - // Check if the value is recently used, and promote - // the value into the frequent list - if c.recent.Contains(key) { - c.recent.Remove(key) - c.frequent.Add(key, value) - return - } - - // If the value was recently evicted, add it to the - // frequently used list - if c.recentEvict.Contains(key) { - c.ensureSpace(true) - c.recentEvict.Remove(key) - c.frequent.Add(key, value) - return - } - - // Add to the recently seen list - c.ensureSpace(false) - c.recent.Add(key, value) - return -} - -// ensureSpace is used to ensure we have space in the cache -func (c *TwoQueueCache) ensureSpace(recentEvict bool) { - // If we have space, nothing to do - recentLen := c.recent.Len() - freqLen := c.frequent.Len() - if recentLen+freqLen < c.size { - return - } - - // If the recent buffer is larger than - // the target, evict from there - if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) { - k, _, _ := c.recent.RemoveOldest() - c.recentEvict.Add(k, nil) - return - } - - // Remove from the frequent list otherwise - c.frequent.RemoveOldest() -} - -// Len returns the number of items in the cache. -func (c *TwoQueueCache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.recent.Len() + c.frequent.Len() -} - -// Keys returns a slice of the keys in the cache. -// The frequently used keys are first in the returned slice. -func (c *TwoQueueCache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - k1 := c.frequent.Keys() - k2 := c.recent.Keys() - return append(k1, k2...) -} - -// Remove removes the provided key from the cache. -func (c *TwoQueueCache) Remove(key interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - if c.frequent.Remove(key) { - return - } - if c.recent.Remove(key) { - return - } - if c.recentEvict.Remove(key) { - return - } -} - -// Purge is used to completely clear the cache. -func (c *TwoQueueCache) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - c.recent.Purge() - c.frequent.Purge() - c.recentEvict.Purge() -} - -// Contains is used to check if the cache contains a key -// without updating recency or frequency. -func (c *TwoQueueCache) Contains(key interface{}) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.frequent.Contains(key) || c.recent.Contains(key) -} - -// Peek is used to inspect the cache value of a key -// without updating recency or frequency. -func (c *TwoQueueCache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - if val, ok := c.frequent.Peek(key); ok { - return val, ok - } - return c.recent.Peek(key) -} diff --git a/vendor/github.com/hashicorp/golang-lru/README.md b/vendor/github.com/hashicorp/golang-lru/README.md deleted file mode 100644 index 33e58cfaf..000000000 --- a/vendor/github.com/hashicorp/golang-lru/README.md +++ /dev/null @@ -1,25 +0,0 @@ -golang-lru -========== - -This provides the `lru` package which implements a fixed-size -thread safe LRU cache. It is based on the cache in Groupcache. - -Documentation -============= - -Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru) - -Example -======= - -Using the LRU is very simple: - -```go -l, _ := New(128) -for i := 0; i < 256; i++ { - l.Add(i, nil) -} -if l.Len() != 128 { - panic(fmt.Sprintf("bad len: %v", l.Len())) -} -``` diff --git a/vendor/github.com/hashicorp/golang-lru/arc.go b/vendor/github.com/hashicorp/golang-lru/arc.go deleted file mode 100644 index 555225a21..000000000 --- a/vendor/github.com/hashicorp/golang-lru/arc.go +++ /dev/null @@ -1,257 +0,0 @@ -package lru - -import ( - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC). -// ARC is an enhancement over the standard LRU cache in that tracks both -// frequency and recency of use. This avoids a burst in access to new -// entries from evicting the frequently used older entries. It adds some -// additional tracking overhead to a standard LRU cache, computationally -// it is roughly 2x the cost, and the extra memory overhead is linear -// with the size of the cache. ARC has been patented by IBM, but is -// similar to the TwoQueueCache (2Q) which requires setting parameters. -type ARCCache struct { - size int // Size is the total capacity of the cache - p int // P is the dynamic preference towards T1 or T2 - - t1 simplelru.LRUCache // T1 is the LRU for recently accessed items - b1 simplelru.LRUCache // B1 is the LRU for evictions from t1 - - t2 simplelru.LRUCache // T2 is the LRU for frequently accessed items - b2 simplelru.LRUCache // B2 is the LRU for evictions from t2 - - lock sync.RWMutex -} - -// NewARC creates an ARC of the given size -func NewARC(size int) (*ARCCache, error) { - // Create the sub LRUs - b1, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - b2, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - t1, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - t2, err := simplelru.NewLRU(size, nil) - if err != nil { - return nil, err - } - - // Initialize the ARC - c := &ARCCache{ - size: size, - p: 0, - t1: t1, - b1: b1, - t2: t2, - b2: b2, - } - return c, nil -} - -// Get looks up a key's value from the cache. -func (c *ARCCache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - - // If the value is contained in T1 (recent), then - // promote it to T2 (frequent) - if val, ok := c.t1.Peek(key); ok { - c.t1.Remove(key) - c.t2.Add(key, val) - return val, ok - } - - // Check if the value is contained in T2 (frequent) - if val, ok := c.t2.Get(key); ok { - return val, ok - } - - // No hit - return nil, false -} - -// Add adds a value to the cache. -func (c *ARCCache) Add(key, value interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the value is contained in T1 (recent), and potentially - // promote it to frequent T2 - if c.t1.Contains(key) { - c.t1.Remove(key) - c.t2.Add(key, value) - return - } - - // Check if the value is already in T2 (frequent) and update it - if c.t2.Contains(key) { - c.t2.Add(key, value) - return - } - - // Check if this value was recently evicted as part of the - // recently used list - if c.b1.Contains(key) { - // T1 set is too small, increase P appropriately - delta := 1 - b1Len := c.b1.Len() - b2Len := c.b2.Len() - if b2Len > b1Len { - delta = b2Len / b1Len - } - if c.p+delta >= c.size { - c.p = c.size - } else { - c.p += delta - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(false) - } - - // Remove from B1 - c.b1.Remove(key) - - // Add the key to the frequently used list - c.t2.Add(key, value) - return - } - - // Check if this value was recently evicted as part of the - // frequently used list - if c.b2.Contains(key) { - // T2 set is too small, decrease P appropriately - delta := 1 - b1Len := c.b1.Len() - b2Len := c.b2.Len() - if b1Len > b2Len { - delta = b1Len / b2Len - } - if delta >= c.p { - c.p = 0 - } else { - c.p -= delta - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(true) - } - - // Remove from B2 - c.b2.Remove(key) - - // Add the key to the frequently used list - c.t2.Add(key, value) - return - } - - // Potentially need to make room in the cache - if c.t1.Len()+c.t2.Len() >= c.size { - c.replace(false) - } - - // Keep the size of the ghost buffers trim - if c.b1.Len() > c.size-c.p { - c.b1.RemoveOldest() - } - if c.b2.Len() > c.p { - c.b2.RemoveOldest() - } - - // Add to the recently seen list - c.t1.Add(key, value) - return -} - -// replace is used to adaptively evict from either T1 or T2 -// based on the current learned value of P -func (c *ARCCache) replace(b2ContainsKey bool) { - t1Len := c.t1.Len() - if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) { - k, _, ok := c.t1.RemoveOldest() - if ok { - c.b1.Add(k, nil) - } - } else { - k, _, ok := c.t2.RemoveOldest() - if ok { - c.b2.Add(k, nil) - } - } -} - -// Len returns the number of cached entries -func (c *ARCCache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.t1.Len() + c.t2.Len() -} - -// Keys returns all the cached keys -func (c *ARCCache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - k1 := c.t1.Keys() - k2 := c.t2.Keys() - return append(k1, k2...) -} - -// Remove is used to purge a key from the cache -func (c *ARCCache) Remove(key interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - if c.t1.Remove(key) { - return - } - if c.t2.Remove(key) { - return - } - if c.b1.Remove(key) { - return - } - if c.b2.Remove(key) { - return - } -} - -// Purge is used to clear the cache -func (c *ARCCache) Purge() { - c.lock.Lock() - defer c.lock.Unlock() - c.t1.Purge() - c.t2.Purge() - c.b1.Purge() - c.b2.Purge() -} - -// Contains is used to check if the cache contains a key -// without updating recency or frequency. -func (c *ARCCache) Contains(key interface{}) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.t1.Contains(key) || c.t2.Contains(key) -} - -// Peek is used to inspect the cache value of a key -// without updating recency or frequency. -func (c *ARCCache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - if val, ok := c.t1.Peek(key); ok { - return val, ok - } - return c.t2.Peek(key) -} diff --git a/vendor/github.com/hashicorp/golang-lru/doc.go b/vendor/github.com/hashicorp/golang-lru/doc.go deleted file mode 100644 index 2547df979..000000000 --- a/vendor/github.com/hashicorp/golang-lru/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package lru provides three different LRU caches of varying sophistication. -// -// Cache is a simple LRU cache. It is based on the -// LRU implementation in groupcache: -// https://github.com/golang/groupcache/tree/master/lru -// -// TwoQueueCache tracks frequently used and recently used entries separately. -// This avoids a burst of accesses from taking out frequently used entries, -// at the cost of about 2x computational overhead and some extra bookkeeping. -// -// ARCCache is an adaptive replacement cache. It tracks recent evictions as -// well as recent usage in both the frequent and recent caches. Its -// computational overhead is comparable to TwoQueueCache, but the memory -// overhead is linear with the size of the cache. -// -// ARC has been patented by IBM, so do not use it if that is problematic for -// your program. -// -// All caches in this package take locks while operating, and are therefore -// thread-safe for consumers. -package lru diff --git a/vendor/github.com/hashicorp/golang-lru/go.mod b/vendor/github.com/hashicorp/golang-lru/go.mod deleted file mode 100644 index 824cb97e8..000000000 --- a/vendor/github.com/hashicorp/golang-lru/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/golang-lru diff --git a/vendor/github.com/hashicorp/golang-lru/lru.go b/vendor/github.com/hashicorp/golang-lru/lru.go deleted file mode 100644 index c8d9b0a23..000000000 --- a/vendor/github.com/hashicorp/golang-lru/lru.go +++ /dev/null @@ -1,110 +0,0 @@ -package lru - -import ( - "sync" - - "github.com/hashicorp/golang-lru/simplelru" -) - -// Cache is a thread-safe fixed size LRU cache. -type Cache struct { - lru simplelru.LRUCache - lock sync.RWMutex -} - -// New creates an LRU of the given size. -func New(size int) (*Cache, error) { - return NewWithEvict(size, nil) -} - -// NewWithEvict constructs a fixed size cache with the given eviction -// callback. -func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) { - lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted)) - if err != nil { - return nil, err - } - c := &Cache{ - lru: lru, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *Cache) Purge() { - c.lock.Lock() - c.lru.Purge() - c.lock.Unlock() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *Cache) Add(key, value interface{}) (evicted bool) { - c.lock.Lock() - defer c.lock.Unlock() - return c.lru.Add(key, value) -} - -// Get looks up a key's value from the cache. -func (c *Cache) Get(key interface{}) (value interface{}, ok bool) { - c.lock.Lock() - defer c.lock.Unlock() - return c.lru.Get(key) -} - -// Contains checks if a key is in the cache, without updating the -// recent-ness or deleting it for being stale. -func (c *Cache) Contains(key interface{}) bool { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Contains(key) -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Peek(key) -} - -// ContainsOrAdd checks if a key is in the cache without updating the -// recent-ness or deleting it for being stale, and if not, adds the value. -// Returns whether found and whether an eviction occurred. -func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) { - c.lock.Lock() - defer c.lock.Unlock() - - if c.lru.Contains(key) { - return true, false - } - evicted = c.lru.Add(key, value) - return false, evicted -} - -// Remove removes the provided key from the cache. -func (c *Cache) Remove(key interface{}) { - c.lock.Lock() - c.lru.Remove(key) - c.lock.Unlock() -} - -// RemoveOldest removes the oldest item from the cache. -func (c *Cache) RemoveOldest() { - c.lock.Lock() - c.lru.RemoveOldest() - c.lock.Unlock() -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *Cache) Keys() []interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Keys() -} - -// Len returns the number of items in the cache. -func (c *Cache) Len() int { - c.lock.RLock() - defer c.lock.RUnlock() - return c.lru.Len() -} diff --git a/vendor/github.com/hashicorp/hcl/.gitignore b/vendor/github.com/hashicorp/hcl/.gitignore new file mode 100644 index 000000000..15586a2b5 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/.gitignore @@ -0,0 +1,9 @@ +y.output + +# ignore intellij files +.idea +*.iml +*.ipr +*.iws + +*.test diff --git a/vendor/github.com/hashicorp/hcl/.travis.yml b/vendor/github.com/hashicorp/hcl/.travis.yml new file mode 100644 index 000000000..cb63a3216 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/.travis.yml @@ -0,0 +1,13 @@ +sudo: false + +language: go + +go: + - 1.x + - tip + +branches: + only: + - master + +script: make test diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go index 0b39c1b95..bed9ebbe1 100644 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ b/vendor/github.com/hashicorp/hcl/decoder.go @@ -89,7 +89,7 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error switch k.Kind() { case reflect.Bool: return d.decodeBool(name, node, result) - case reflect.Float64: + case reflect.Float32, reflect.Float64: return d.decodeFloat(name, node, result) case reflect.Int, reflect.Int32, reflect.Int64: return d.decodeInt(name, node, result) @@ -137,13 +137,13 @@ func (d *decoder) decodeBool(name string, node ast.Node, result reflect.Value) e func (d *decoder) decodeFloat(name string, node ast.Node, result reflect.Value) error { switch n := node.(type) { case *ast.LiteralType: - if n.Token.Type == token.FLOAT { + if n.Token.Type == token.FLOAT || n.Token.Type == token.NUMBER { v, err := strconv.ParseFloat(n.Token.Text, 64) if err != nil { return err } - result.Set(reflect.ValueOf(v)) + result.Set(reflect.ValueOf(v).Convert(result.Type())) return nil } } @@ -573,7 +573,11 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) // Compile the list of all the fields that we're going to be decoding // from all the structs. - fields := make(map[*reflect.StructField]reflect.Value) + type field struct { + field reflect.StructField + val reflect.Value + } + fields := []field{} for len(structs) > 0 { structVal := structs[0] structs = structs[1:] @@ -616,7 +620,7 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) } // Normal struct field, store it away - fields[&fieldType] = structVal.Field(i) + fields = append(fields, field{fieldType, structVal.Field(i)}) } } @@ -624,26 +628,27 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) decodedFields := make([]string, 0, len(fields)) decodedFieldsVal := make([]reflect.Value, 0) unusedKeysVal := make([]reflect.Value, 0) - for fieldType, field := range fields { - if !field.IsValid() { + for _, f := range fields { + field, fieldValue := f.field, f.val + if !fieldValue.IsValid() { // This should never happen panic("field is not valid") } // If we can't set the field, then it is unexported or something, // and we just continue onwards. - if !field.CanSet() { + if !fieldValue.CanSet() { continue } - fieldName := fieldType.Name + fieldName := field.Name - tagValue := fieldType.Tag.Get(tagName) + tagValue := field.Tag.Get(tagName) tagParts := strings.SplitN(tagValue, ",", 2) if len(tagParts) >= 2 { switch tagParts[1] { case "decodedFields": - decodedFieldsVal = append(decodedFieldsVal, field) + decodedFieldsVal = append(decodedFieldsVal, fieldValue) continue case "key": if item == nil { @@ -654,10 +659,10 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) } } - field.SetString(item.Keys[0].Token.Value().(string)) + fieldValue.SetString(item.Keys[0].Token.Value().(string)) continue case "unusedKeys": - unusedKeysVal = append(unusedKeysVal, field) + unusedKeysVal = append(unusedKeysVal, fieldValue) continue } } @@ -684,7 +689,7 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) // because we actually want the value. fieldName = fmt.Sprintf("%s.%s", name, fieldName) if len(prefixMatches.Items) > 0 { - if err := d.decode(fieldName, prefixMatches, field); err != nil { + if err := d.decode(fieldName, prefixMatches, fieldValue); err != nil { return err } } @@ -694,12 +699,12 @@ func (d *decoder) decodeStruct(name string, node ast.Node, result reflect.Value) decodeNode = &ast.ObjectList{Items: ot.List.Items} } - if err := d.decode(fieldName, decodeNode, field); err != nil { + if err := d.decode(fieldName, decodeNode, fieldValue); err != nil { return err } } - decodedFields = append(decodedFields, fieldType.Name) + decodedFields = append(decodedFields, field.Name) } if len(decodedFieldsVal) > 0 { diff --git a/vendor/github.com/hashicorp/hcl/go.mod b/vendor/github.com/hashicorp/hcl/go.mod new file mode 100644 index 000000000..4debbbe35 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/go.mod @@ -0,0 +1,3 @@ +module github.com/hashicorp/hcl + +require github.com/davecgh/go-spew v1.1.1 diff --git a/vendor/github.com/hashicorp/hcl/go.sum b/vendor/github.com/hashicorp/hcl/go.sum new file mode 100644 index 000000000..b5e2922e8 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/go.sum @@ -0,0 +1,2 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index b4881806e..64c83bcfb 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -197,9 +197,18 @@ func (p *Parser) objectItem() (*ast.ObjectItem, error) { keyStr = append(keyStr, k.Token.Text) } - return nil, fmt.Errorf( - "key '%s' expected start of object ('{') or assignment ('=')", - strings.Join(keyStr, " ")) + return nil, &PosError{ + Pos: p.tok.Pos, + Err: fmt.Errorf( + "key '%s' expected start of object ('{') or assignment ('=')", + strings.Join(keyStr, " ")), + } + } + + // key=#comment + // val + if p.lineComment != nil { + o.LineComment, p.lineComment = p.lineComment, nil } // do a look-ahead for line comment @@ -319,7 +328,10 @@ func (p *Parser) objectType() (*ast.ObjectType, error) { // No error, scan and expect the ending to be a brace if tok := p.scan(); tok.Type != token.RBRACE { - return nil, fmt.Errorf("object expected closing RBRACE got: %s", tok.Type) + return nil, &PosError{ + Pos: tok.Pos, + Err: fmt.Errorf("object expected closing RBRACE got: %s", tok.Type), + } } o.List = l diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go b/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go deleted file mode 100644 index 7c038d12a..000000000 --- a/vendor/github.com/hashicorp/hcl/hcl/printer/nodes.go +++ /dev/null @@ -1,789 +0,0 @@ -package printer - -import ( - "bytes" - "fmt" - "sort" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/token" -) - -const ( - blank = byte(' ') - newline = byte('\n') - tab = byte('\t') - infinity = 1 << 30 // offset or line -) - -var ( - unindent = []byte("\uE123") // in the private use space -) - -type printer struct { - cfg Config - prev token.Pos - - comments []*ast.CommentGroup // may be nil, contains all comments - standaloneComments []*ast.CommentGroup // contains all standalone comments (not assigned to any node) - - enableTrace bool - indentTrace int -} - -type ByPosition []*ast.CommentGroup - -func (b ByPosition) Len() int { return len(b) } -func (b ByPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b ByPosition) Less(i, j int) bool { return b[i].Pos().Before(b[j].Pos()) } - -// collectComments comments all standalone comments which are not lead or line -// comment -func (p *printer) collectComments(node ast.Node) { - // first collect all comments. This is already stored in - // ast.File.(comments) - ast.Walk(node, func(nn ast.Node) (ast.Node, bool) { - switch t := nn.(type) { - case *ast.File: - p.comments = t.Comments - return nn, false - } - return nn, true - }) - - standaloneComments := make(map[token.Pos]*ast.CommentGroup, 0) - for _, c := range p.comments { - standaloneComments[c.Pos()] = c - } - - // next remove all lead and line comments from the overall comment map. - // This will give us comments which are standalone, comments which are not - // assigned to any kind of node. - ast.Walk(node, func(nn ast.Node) (ast.Node, bool) { - switch t := nn.(type) { - case *ast.LiteralType: - if t.LeadComment != nil { - for _, comment := range t.LeadComment.List { - if _, ok := standaloneComments[comment.Pos()]; ok { - delete(standaloneComments, comment.Pos()) - } - } - } - - if t.LineComment != nil { - for _, comment := range t.LineComment.List { - if _, ok := standaloneComments[comment.Pos()]; ok { - delete(standaloneComments, comment.Pos()) - } - } - } - case *ast.ObjectItem: - if t.LeadComment != nil { - for _, comment := range t.LeadComment.List { - if _, ok := standaloneComments[comment.Pos()]; ok { - delete(standaloneComments, comment.Pos()) - } - } - } - - if t.LineComment != nil { - for _, comment := range t.LineComment.List { - if _, ok := standaloneComments[comment.Pos()]; ok { - delete(standaloneComments, comment.Pos()) - } - } - } - } - - return nn, true - }) - - for _, c := range standaloneComments { - p.standaloneComments = append(p.standaloneComments, c) - } - - sort.Sort(ByPosition(p.standaloneComments)) -} - -// output prints creates b printable HCL output and returns it. -func (p *printer) output(n interface{}) []byte { - var buf bytes.Buffer - - switch t := n.(type) { - case *ast.File: - // File doesn't trace so we add the tracing here - defer un(trace(p, "File")) - return p.output(t.Node) - case *ast.ObjectList: - defer un(trace(p, "ObjectList")) - - var index int - for { - // Determine the location of the next actual non-comment - // item. If we're at the end, the next item is at "infinity" - var nextItem token.Pos - if index != len(t.Items) { - nextItem = t.Items[index].Pos() - } else { - nextItem = token.Pos{Offset: infinity, Line: infinity} - } - - // Go through the standalone comments in the file and print out - // the comments that we should be for this object item. - for _, c := range p.standaloneComments { - // Go through all the comments in the group. The group - // should be printed together, not separated by double newlines. - printed := false - newlinePrinted := false - for _, comment := range c.List { - // We only care about comments after the previous item - // we've printed so that comments are printed in the - // correct locations (between two objects for example). - // And before the next item. - if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) { - // if we hit the end add newlines so we can print the comment - // we don't do this if prev is invalid which means the - // beginning of the file since the first comment should - // be at the first line. - if !newlinePrinted && p.prev.IsValid() && index == len(t.Items) { - buf.Write([]byte{newline, newline}) - newlinePrinted = true - } - - // Write the actual comment. - buf.WriteString(comment.Text) - buf.WriteByte(newline) - - // Set printed to true to note that we printed something - printed = true - } - } - - // If we're not at the last item, write a new line so - // that there is a newline separating this comment from - // the next object. - if printed && index != len(t.Items) { - buf.WriteByte(newline) - } - } - - if index == len(t.Items) { - break - } - - buf.Write(p.output(t.Items[index])) - if index != len(t.Items)-1 { - // Always write a newline to separate us from the next item - buf.WriteByte(newline) - - // Need to determine if we're going to separate the next item - // with a blank line. The logic here is simple, though there - // are a few conditions: - // - // 1. The next object is more than one line away anyways, - // so we need an empty line. - // - // 2. The next object is not a "single line" object, so - // we need an empty line. - // - // 3. This current object is not a single line object, - // so we need an empty line. - current := t.Items[index] - next := t.Items[index+1] - if next.Pos().Line != t.Items[index].Pos().Line+1 || - !p.isSingleLineObject(next) || - !p.isSingleLineObject(current) { - buf.WriteByte(newline) - } - } - index++ - } - case *ast.ObjectKey: - buf.WriteString(t.Token.Text) - case *ast.ObjectItem: - p.prev = t.Pos() - buf.Write(p.objectItem(t)) - case *ast.LiteralType: - buf.Write(p.literalType(t)) - case *ast.ListType: - buf.Write(p.list(t)) - case *ast.ObjectType: - buf.Write(p.objectType(t)) - default: - fmt.Printf(" unknown type: %T\n", n) - } - - return buf.Bytes() -} - -func (p *printer) literalType(lit *ast.LiteralType) []byte { - result := []byte(lit.Token.Text) - switch lit.Token.Type { - case token.HEREDOC: - // Clear the trailing newline from heredocs - if result[len(result)-1] == '\n' { - result = result[:len(result)-1] - } - - // Poison lines 2+ so that we don't indent them - result = p.heredocIndent(result) - case token.STRING: - // If this is a multiline string, poison lines 2+ so we don't - // indent them. - if bytes.IndexRune(result, '\n') >= 0 { - result = p.heredocIndent(result) - } - } - - return result -} - -// objectItem returns the printable HCL form of an object item. An object type -// starts with one/multiple keys and has a value. The value might be of any -// type. -func (p *printer) objectItem(o *ast.ObjectItem) []byte { - defer un(trace(p, fmt.Sprintf("ObjectItem: %s", o.Keys[0].Token.Text))) - var buf bytes.Buffer - - if o.LeadComment != nil { - for _, comment := range o.LeadComment.List { - buf.WriteString(comment.Text) - buf.WriteByte(newline) - } - } - - // If key and val are on different lines, treat line comments like lead comments. - if o.LineComment != nil && o.Val.Pos().Line != o.Keys[0].Pos().Line { - for _, comment := range o.LineComment.List { - buf.WriteString(comment.Text) - buf.WriteByte(newline) - } - } - - for i, k := range o.Keys { - buf.WriteString(k.Token.Text) - buf.WriteByte(blank) - - // reach end of key - if o.Assign.IsValid() && i == len(o.Keys)-1 && len(o.Keys) == 1 { - buf.WriteString("=") - buf.WriteByte(blank) - } - } - - buf.Write(p.output(o.Val)) - - if o.LineComment != nil && o.Val.Pos().Line == o.Keys[0].Pos().Line { - buf.WriteByte(blank) - for _, comment := range o.LineComment.List { - buf.WriteString(comment.Text) - } - } - - return buf.Bytes() -} - -// objectType returns the printable HCL form of an object type. An object type -// begins with a brace and ends with a brace. -func (p *printer) objectType(o *ast.ObjectType) []byte { - defer un(trace(p, "ObjectType")) - var buf bytes.Buffer - buf.WriteString("{") - - var index int - var nextItem token.Pos - var commented, newlinePrinted bool - for { - // Determine the location of the next actual non-comment - // item. If we're at the end, the next item is the closing brace - if index != len(o.List.Items) { - nextItem = o.List.Items[index].Pos() - } else { - nextItem = o.Rbrace - } - - // Go through the standalone comments in the file and print out - // the comments that we should be for this object item. - for _, c := range p.standaloneComments { - printed := false - var lastCommentPos token.Pos - for _, comment := range c.List { - // We only care about comments after the previous item - // we've printed so that comments are printed in the - // correct locations (between two objects for example). - // And before the next item. - if comment.Pos().After(p.prev) && comment.Pos().Before(nextItem) { - // If there are standalone comments and the initial newline has not - // been printed yet, do it now. - if !newlinePrinted { - newlinePrinted = true - buf.WriteByte(newline) - } - - // add newline if it's between other printed nodes - if index > 0 { - commented = true - buf.WriteByte(newline) - } - - // Store this position - lastCommentPos = comment.Pos() - - // output the comment itself - buf.Write(p.indent(p.heredocIndent([]byte(comment.Text)))) - - // Set printed to true to note that we printed something - printed = true - - /* - if index != len(o.List.Items) { - buf.WriteByte(newline) // do not print on the end - } - */ - } - } - - // Stuff to do if we had comments - if printed { - // Always write a newline - buf.WriteByte(newline) - - // If there is another item in the object and our comment - // didn't hug it directly, then make sure there is a blank - // line separating them. - if nextItem != o.Rbrace && nextItem.Line != lastCommentPos.Line+1 { - buf.WriteByte(newline) - } - } - } - - if index == len(o.List.Items) { - p.prev = o.Rbrace - break - } - - // At this point we are sure that it's not a totally empty block: print - // the initial newline if it hasn't been printed yet by the previous - // block about standalone comments. - if !newlinePrinted { - buf.WriteByte(newline) - newlinePrinted = true - } - - // check if we have adjacent one liner items. If yes we'll going to align - // the comments. - var aligned []*ast.ObjectItem - for _, item := range o.List.Items[index:] { - // we don't group one line lists - if len(o.List.Items) == 1 { - break - } - - // one means a oneliner with out any lead comment - // two means a oneliner with lead comment - // anything else might be something else - cur := lines(string(p.objectItem(item))) - if cur > 2 { - break - } - - curPos := item.Pos() - - nextPos := token.Pos{} - if index != len(o.List.Items)-1 { - nextPos = o.List.Items[index+1].Pos() - } - - prevPos := token.Pos{} - if index != 0 { - prevPos = o.List.Items[index-1].Pos() - } - - // fmt.Println("DEBUG ----------------") - // fmt.Printf("prev = %+v prevPos: %s\n", prev, prevPos) - // fmt.Printf("cur = %+v curPos: %s\n", cur, curPos) - // fmt.Printf("next = %+v nextPos: %s\n", next, nextPos) - - if curPos.Line+1 == nextPos.Line { - aligned = append(aligned, item) - index++ - continue - } - - if curPos.Line-1 == prevPos.Line { - aligned = append(aligned, item) - index++ - - // finish if we have a new line or comment next. This happens - // if the next item is not adjacent - if curPos.Line+1 != nextPos.Line { - break - } - continue - } - - break - } - - // put newlines if the items are between other non aligned items. - // newlines are also added if there is a standalone comment already, so - // check it too - if !commented && index != len(aligned) { - buf.WriteByte(newline) - } - - if len(aligned) >= 1 { - p.prev = aligned[len(aligned)-1].Pos() - - items := p.alignedItems(aligned) - buf.Write(p.indent(items)) - } else { - p.prev = o.List.Items[index].Pos() - - buf.Write(p.indent(p.objectItem(o.List.Items[index]))) - index++ - } - - buf.WriteByte(newline) - } - - buf.WriteString("}") - return buf.Bytes() -} - -func (p *printer) alignedItems(items []*ast.ObjectItem) []byte { - var buf bytes.Buffer - - // find the longest key and value length, needed for alignment - var longestKeyLen int // longest key length - var longestValLen int // longest value length - for _, item := range items { - key := len(item.Keys[0].Token.Text) - val := len(p.output(item.Val)) - - if key > longestKeyLen { - longestKeyLen = key - } - - if val > longestValLen { - longestValLen = val - } - } - - for i, item := range items { - if item.LeadComment != nil { - for _, comment := range item.LeadComment.List { - buf.WriteString(comment.Text) - buf.WriteByte(newline) - } - } - - for i, k := range item.Keys { - keyLen := len(k.Token.Text) - buf.WriteString(k.Token.Text) - for i := 0; i < longestKeyLen-keyLen+1; i++ { - buf.WriteByte(blank) - } - - // reach end of key - if i == len(item.Keys)-1 && len(item.Keys) == 1 { - buf.WriteString("=") - buf.WriteByte(blank) - } - } - - val := p.output(item.Val) - valLen := len(val) - buf.Write(val) - - if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil { - for i := 0; i < longestValLen-valLen+1; i++ { - buf.WriteByte(blank) - } - - for _, comment := range item.LineComment.List { - buf.WriteString(comment.Text) - } - } - - // do not print for the last item - if i != len(items)-1 { - buf.WriteByte(newline) - } - } - - return buf.Bytes() -} - -// list returns the printable HCL form of an list type. -func (p *printer) list(l *ast.ListType) []byte { - if p.isSingleLineList(l) { - return p.singleLineList(l) - } - - var buf bytes.Buffer - buf.WriteString("[") - buf.WriteByte(newline) - - var longestLine int - for _, item := range l.List { - // for now we assume that the list only contains literal types - if lit, ok := item.(*ast.LiteralType); ok { - lineLen := len(lit.Token.Text) - if lineLen > longestLine { - longestLine = lineLen - } - } - } - - haveEmptyLine := false - for i, item := range l.List { - // If we have a lead comment, then we want to write that first - leadComment := false - if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil { - leadComment = true - - // Ensure an empty line before every element with a - // lead comment (except the first item in a list). - if !haveEmptyLine && i != 0 { - buf.WriteByte(newline) - } - - for _, comment := range lit.LeadComment.List { - buf.Write(p.indent([]byte(comment.Text))) - buf.WriteByte(newline) - } - } - - // also indent each line - val := p.output(item) - curLen := len(val) - buf.Write(p.indent(val)) - - // if this item is a heredoc, then we output the comma on - // the next line. This is the only case this happens. - comma := []byte{','} - if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC { - buf.WriteByte(newline) - comma = p.indent(comma) - } - - buf.Write(comma) - - if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil { - // if the next item doesn't have any comments, do not align - buf.WriteByte(blank) // align one space - for i := 0; i < longestLine-curLen; i++ { - buf.WriteByte(blank) - } - - for _, comment := range lit.LineComment.List { - buf.WriteString(comment.Text) - } - } - - buf.WriteByte(newline) - - // Ensure an empty line after every element with a - // lead comment (except the first item in a list). - haveEmptyLine = leadComment && i != len(l.List)-1 - if haveEmptyLine { - buf.WriteByte(newline) - } - } - - buf.WriteString("]") - return buf.Bytes() -} - -// isSingleLineList returns true if: -// * they were previously formatted entirely on one line -// * they consist entirely of literals -// * there are either no heredoc strings or the list has exactly one element -// * there are no line comments -func (printer) isSingleLineList(l *ast.ListType) bool { - for _, item := range l.List { - if item.Pos().Line != l.Lbrack.Line { - return false - } - - lit, ok := item.(*ast.LiteralType) - if !ok { - return false - } - - if lit.Token.Type == token.HEREDOC && len(l.List) != 1 { - return false - } - - if lit.LineComment != nil { - return false - } - } - - return true -} - -// singleLineList prints a simple single line list. -// For a definition of "simple", see isSingleLineList above. -func (p *printer) singleLineList(l *ast.ListType) []byte { - buf := &bytes.Buffer{} - - buf.WriteString("[") - for i, item := range l.List { - if i != 0 { - buf.WriteString(", ") - } - - // Output the item itself - buf.Write(p.output(item)) - - // The heredoc marker needs to be at the end of line. - if lit, ok := item.(*ast.LiteralType); ok && lit.Token.Type == token.HEREDOC { - buf.WriteByte(newline) - } - } - - buf.WriteString("]") - return buf.Bytes() -} - -// indent indents the lines of the given buffer for each non-empty line -func (p *printer) indent(buf []byte) []byte { - var prefix []byte - if p.cfg.SpacesWidth != 0 { - for i := 0; i < p.cfg.SpacesWidth; i++ { - prefix = append(prefix, blank) - } - } else { - prefix = []byte{tab} - } - - var res []byte - bol := true - for _, c := range buf { - if bol && c != '\n' { - res = append(res, prefix...) - } - - res = append(res, c) - bol = c == '\n' - } - return res -} - -// unindent removes all the indentation from the tombstoned lines -func (p *printer) unindent(buf []byte) []byte { - var res []byte - for i := 0; i < len(buf); i++ { - skip := len(buf)-i <= len(unindent) - if !skip { - skip = !bytes.Equal(unindent, buf[i:i+len(unindent)]) - } - if skip { - res = append(res, buf[i]) - continue - } - - // We have a marker. we have to backtrace here and clean out - // any whitespace ahead of our tombstone up to a \n - for j := len(res) - 1; j >= 0; j-- { - if res[j] == '\n' { - break - } - - res = res[:j] - } - - // Skip the entire unindent marker - i += len(unindent) - 1 - } - - return res -} - -// heredocIndent marks all the 2nd and further lines as unindentable -func (p *printer) heredocIndent(buf []byte) []byte { - var res []byte - bol := false - for _, c := range buf { - if bol && c != '\n' { - res = append(res, unindent...) - } - res = append(res, c) - bol = c == '\n' - } - return res -} - -// isSingleLineObject tells whether the given object item is a single -// line object such as "obj {}". -// -// A single line object: -// -// * has no lead comments (hence multi-line) -// * has no assignment -// * has no values in the stanza (within {}) -// -func (p *printer) isSingleLineObject(val *ast.ObjectItem) bool { - // If there is a lead comment, can't be one line - if val.LeadComment != nil { - return false - } - - // If there is assignment, we always break by line - if val.Assign.IsValid() { - return false - } - - // If it isn't an object type, then its not a single line object - ot, ok := val.Val.(*ast.ObjectType) - if !ok { - return false - } - - // If the object has no items, it is single line! - return len(ot.List.Items) == 0 -} - -func lines(txt string) int { - endline := 1 - for i := 0; i < len(txt); i++ { - if txt[i] == '\n' { - endline++ - } - } - return endline -} - -// ---------------------------------------------------------------------------- -// Tracing support - -func (p *printer) printTrace(a ...interface{}) { - if !p.enableTrace { - return - } - - const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " - const n = len(dots) - i := 2 * p.indentTrace - for i > n { - fmt.Print(dots) - i -= n - } - // i <= n - fmt.Print(dots[0:i]) - fmt.Println(a...) -} - -func trace(p *printer, msg string) *printer { - p.printTrace(msg, "(") - p.indentTrace++ - return p -} - -// Usage pattern: defer un(trace(p, "...")) -func un(p *printer) { - p.indentTrace-- - p.printTrace(")") -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go b/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go deleted file mode 100644 index 6617ab8e7..000000000 --- a/vendor/github.com/hashicorp/hcl/hcl/printer/printer.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package printer implements printing of AST nodes to HCL format. -package printer - -import ( - "bytes" - "io" - "text/tabwriter" - - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/hcl/hcl/parser" -) - -var DefaultConfig = Config{ - SpacesWidth: 2, -} - -// A Config node controls the output of Fprint. -type Config struct { - SpacesWidth int // if set, it will use spaces instead of tabs for alignment -} - -func (c *Config) Fprint(output io.Writer, node ast.Node) error { - p := &printer{ - cfg: *c, - comments: make([]*ast.CommentGroup, 0), - standaloneComments: make([]*ast.CommentGroup, 0), - // enableTrace: true, - } - - p.collectComments(node) - - if _, err := output.Write(p.unindent(p.output(node))); err != nil { - return err - } - - // flush tabwriter, if any - var err error - if tw, _ := output.(*tabwriter.Writer); tw != nil { - err = tw.Flush() - } - - return err -} - -// Fprint "pretty-prints" an HCL node to output -// It calls Config.Fprint with default settings. -func Fprint(output io.Writer, node ast.Node) error { - return DefaultConfig.Fprint(output, node) -} - -// Format formats src HCL and returns the result. -func Format(src []byte) ([]byte, error) { - node, err := parser.Parse(src) - if err != nil { - return nil, err - } - - var buf bytes.Buffer - if err := DefaultConfig.Fprint(&buf, node); err != nil { - return nil, err - } - - // Add trailing newline to result - buf.WriteString("\n") - return buf.Bytes(), nil -} diff --git a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go index 69662367f..624a18fe3 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go +++ b/vendor/github.com/hashicorp/hcl/hcl/scanner/scanner.go @@ -74,14 +74,6 @@ func (s *Scanner) next() rune { return eof } - if ch == utf8.RuneError && size == 1 { - s.srcPos.Column++ - s.srcPos.Offset += size - s.lastCharLen = size - s.err("illegal UTF-8 encoding") - return ch - } - // remember last position s.prevPos = s.srcPos @@ -89,18 +81,27 @@ func (s *Scanner) next() rune { s.lastCharLen = size s.srcPos.Offset += size + if ch == utf8.RuneError && size == 1 { + s.err("illegal UTF-8 encoding") + return ch + } + if ch == '\n' { s.srcPos.Line++ s.lastLineLen = s.srcPos.Column s.srcPos.Column = 0 } - // If we see a null character with data left, then that is an error - if ch == '\x00' && s.buf.Len() > 0 { + if ch == '\x00' { s.err("unexpected null character (0x00)") return eof } + if ch == '\uE123' { + s.err("unicode code point U+E123 reserved for internal use") + return utf8.RuneError + } + // debug // fmt.Printf("ch: %q, offset:column: %d:%d\n", ch, s.srcPos.Offset, s.srcPos.Column) return ch @@ -351,7 +352,7 @@ func (s *Scanner) scanNumber(ch rune) token.Type { return token.NUMBER } -// scanMantissa scans the mantissa begining from the rune. It returns the next +// scanMantissa scans the mantissa beginning from the rune. It returns the next // non decimal rune. It's used to determine wheter it's a fraction or exponent. func (s *Scanner) scanMantissa(ch rune) rune { scanned := false @@ -432,16 +433,16 @@ func (s *Scanner) scanHeredoc() { // Read the identifier identBytes := s.src[offs : s.srcPos.Offset-s.lastCharLen] - if len(identBytes) == 0 { + if len(identBytes) == 0 || (len(identBytes) == 1 && identBytes[0] == '-') { s.err("zero-length heredoc anchor") return } var identRegexp *regexp.Regexp if identBytes[0] == '-' { - identRegexp = regexp.MustCompile(fmt.Sprintf(`[[:space:]]*%s\z`, identBytes[1:])) + identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes[1:])) } else { - identRegexp = regexp.MustCompile(fmt.Sprintf(`[[:space:]]*%s\z`, identBytes)) + identRegexp = regexp.MustCompile(fmt.Sprintf(`^[[:space:]]*%s\r*\z`, identBytes)) } // Read the actual string value @@ -551,7 +552,7 @@ func (s *Scanner) scanDigits(ch rune, base, n int) rune { s.err("illegal char escape") } - if n != start { + if n != start && ch != eof { // we scanned all digits, put the last non digit char back, // only if we read anything at all s.unread() diff --git a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go index dd5c72bb3..fe3f0f095 100644 --- a/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go +++ b/vendor/github.com/hashicorp/hcl/json/scanner/scanner.go @@ -246,7 +246,7 @@ func (s *Scanner) scanNumber(ch rune) token.Type { return token.NUMBER } -// scanMantissa scans the mantissa begining from the rune. It returns the next +// scanMantissa scans the mantissa beginning from the rune. It returns the next // non decimal rune. It's used to determine wheter it's a fraction or exponent. func (s *Scanner) scanMantissa(ch rune) rune { scanned := false diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars.go old mode 100755 new mode 100644 diff --git a/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars_gen.go b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars_gen.go new file mode 100644 index 000000000..88f198009 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/expression_vars_gen.go @@ -0,0 +1,99 @@ +// This is a 'go generate'-oriented program for producing the "Variables" +// method on every Expression implementation found within this package. +// All expressions share the same implementation for this method, which +// just wraps the package-level function "Variables" and uses an AST walk +// to do its work. + +// +build ignore + +package main + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "sort" +) + +func main() { + fs := token.NewFileSet() + pkgs, err := parser.ParseDir(fs, ".", nil, 0) + if err != nil { + fmt.Fprintf(os.Stderr, "error while parsing: %s\n", err) + os.Exit(1) + } + pkg := pkgs["hclsyntax"] + + // Walk all the files and collect the receivers of any "Value" methods + // that look like they are trying to implement Expression. + var recvs []string + for _, f := range pkg.Files { + for _, decl := range f.Decls { + fd, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + if fd.Name.Name != "Value" { + continue + } + results := fd.Type.Results.List + if len(results) != 2 { + continue + } + valResult := fd.Type.Results.List[0].Type.(*ast.SelectorExpr).X.(*ast.Ident) + diagsResult := fd.Type.Results.List[1].Type.(*ast.SelectorExpr).X.(*ast.Ident) + + if valResult.Name != "cty" && diagsResult.Name != "hcl" { + continue + } + + // If we have a method called Value and it returns something in + // "cty" followed by something in "hcl" then that's specific enough + // for now, even though this is not 100% exact as a correct + // implementation of Value. + + recvTy := fd.Recv.List[0].Type + + switch rtt := recvTy.(type) { + case *ast.StarExpr: + name := rtt.X.(*ast.Ident).Name + recvs = append(recvs, fmt.Sprintf("*%s", name)) + default: + fmt.Fprintf(os.Stderr, "don't know what to do with a %T receiver\n", recvTy) + } + + } + } + + sort.Strings(recvs) + + of, err := os.OpenFile("expression_vars.go", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to open output file: %s\n", err) + os.Exit(1) + } + + fmt.Fprint(of, outputPreamble) + for _, recv := range recvs { + fmt.Fprintf(of, outputMethodFmt, recv) + } + fmt.Fprint(of, "\n") + +} + +const outputPreamble = `package hclsyntax + +// Generated by expression_vars_get.go. DO NOT EDIT. +// Run 'go generate' on this package to update the set of functions here. + +import ( + "github.com/hashicorp/hcl2/hcl" +)` + +const outputMethodFmt = ` + +func (e %s) Variables() []hcl.Traversal { + return Variables(e) +}` diff --git a/vendor/github.com/hashicorp/hil/.gitignore b/vendor/github.com/hashicorp/hil/.gitignore new file mode 100644 index 000000000..9d6e5df38 --- /dev/null +++ b/vendor/github.com/hashicorp/hil/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +.idea +*.iml diff --git a/vendor/github.com/hashicorp/hil/.travis.yml b/vendor/github.com/hashicorp/hil/.travis.yml new file mode 100644 index 000000000..a78544422 --- /dev/null +++ b/vendor/github.com/hashicorp/hil/.travis.yml @@ -0,0 +1,3 @@ +sudo: false +language: go +go: 1.7 diff --git a/vendor/github.com/hashicorp/hil/scanner/scanner.go b/vendor/github.com/hashicorp/hil/scanner/scanner.go index bab86c67a..86085de01 100644 --- a/vendor/github.com/hashicorp/hil/scanner/scanner.go +++ b/vendor/github.com/hashicorp/hil/scanner/scanner.go @@ -395,6 +395,12 @@ func scanLiteral(s string, startPos ast.Pos, nested bool) (string, *Token) { pos.Column = pos.Column + 2 litLen = litLen + 2 continue + } else if follow == '\\' { + // \\ escapes \ + // so we will consume both characters here. + pos.Column = pos.Column + 2 + litLen = litLen + 2 + continue } } } diff --git a/vendor/github.com/hashicorp/logutils/.gitignore b/vendor/github.com/hashicorp/logutils/.gitignore new file mode 100644 index 000000000..00268614f --- /dev/null +++ b/vendor/github.com/hashicorp/logutils/.gitignore @@ -0,0 +1,22 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.lock deleted file mode 100644 index 78c5a5f68..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.lock +++ /dev/null @@ -1,427 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:a69ab3f1445ffd4815add4bd31ba05b65b3b9fec1ade5057d5d717f30e6efd6d" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - digest = "1:cde027e8bb29425770dd8ddc87789e0139f2dc53a80e248c8d6a0698c7e3f0bc" - name = "github.com/aliyun/alibaba-cloud-sdk-go" - packages = [ - "sdk", - "sdk/auth", - "sdk/auth/credentials", - "sdk/auth/credentials/providers", - "sdk/auth/signers", - "sdk/endpoints", - "sdk/errors", - "sdk/requests", - "sdk/responses", - "sdk/utils", - "services/sts", - ] - pruneopts = "UT" - revision = "ef9535c490beb6b59620d93f6c7ba88e9b3b1ad0" - version = "1.26.2" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:c9caf8fc607b9b8fa503965eca966ae6f1fb96573a0a1c04017b9cd0a98adad3" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/cidrutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "8655d167084028d627f687ddc25d0c71307eb5be" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - digest = "1:b87714e57a511d88f307aba7d5b63522da12bed0a050889c81272fc50f71100e" - name = "github.com/jmespath/go-jmespath" - packages = ["."] - pruneopts = "UT" - revision = "3433f3ea46d9f8019119e7dd41274e112a2359a9" - version = "0.2.2" - -[[projects]] - digest = "1:3e551bbb3a7c0ab2a2bf4660e7fcad16db089fdcfbb44b0199e62838038623ea" - name = "github.com/json-iterator/go" - packages = ["."] - pruneopts = "UT" - revision = "1624edc4454b8682399def8740d46db5e4362ba4" - version = "1.1.5" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563" - name = "github.com/modern-go/concurrent" - packages = ["."] - pruneopts = "UT" - revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" - version = "1.0.3" - -[[projects]] - digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855" - name = "github.com/modern-go/reflect2" - packages = ["."] - pruneopts = "UT" - revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" - version = "1.0.1" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - digest = "1:274f67cb6fed9588ea2521ecdac05a6d62a8c51c074c1fccc6a49a40ba80e925" - name = "github.com/satori/go.uuid" - packages = ["."] - pruneopts = "UT" - revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3" - version = "v1.2.0" - -[[projects]] - branch = "master" - digest = "1:b5c3834d33445efdc5a8dcb154bed9e4c211edadbf02f6f5cc20c5e9be26a499" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:05662433b3a13c921587a6e622b5722072edff83211efd1cd79eeaeedfd83f07" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/aliyun/alibaba-cloud-sdk-go/sdk", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/providers", - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints", - "github.com/aliyun/alibaba-cloud-sdk-go/services/sts", - "github.com/hashicorp/errwrap", - "github.com/hashicorp/go-cleanhttp", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/go-sockaddr", - "github.com/hashicorp/vault/api", - "github.com/hashicorp/vault/helper/cidrutil", - "github.com/hashicorp/vault/helper/parseutil", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.toml deleted file mode 100644 index 83e808d79..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Gopkg.toml +++ /dev/null @@ -1,54 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - name = "github.com/aliyun/alibaba-cloud-sdk-go" - version = "1.25.5" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/errwrap" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-sockaddr" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/LICENSE deleted file mode 100644 index a612ad981..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Makefile b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Makefile deleted file mode 100644 index cf83a4db5..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -TOOL?=vault-plugin-auth-alibaba -TEST?=$$(go list ./... | grep -v /vendor/ | grep -v teamcity) -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox \ - github.com/golang/dep/cmd/dep -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin. -dev: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -# testshort runs the quick unit tests and vets the code -testshort: fmtcheck generate - CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -short -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -count=1 -timeout=20m -parallel=4 - -# test runs the unit tests and vets the code -test: fmtcheck generate - CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -v -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -count=1 -timeout=20m -parallel=4 - -testcompile: fmtcheck generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - gofmt -w $(GOFMT_FILES) - -proto: - protoc *.proto --go_out=plugins=grpc:. - -.PHONY: bin default generate test vet bootstrap fmt fmtcheck \ No newline at end of file diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/README.md b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/README.md deleted file mode 100644 index 49df877c4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Vault Plugin: AliCloud Auth Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-auth-alicloud.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-auth-alicloud) - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin allows authentication to Vault using Resource Access Management (RAM). - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - AliCloud Auth Docs: https://www.vaultproject.io/docs/auth/alicloud.html - - Main Project Github: https://www.github.com/hashicorp/vault - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Security Model - -This authentication model places Vault in the middle of a call between a client and AliCloud's "GetCallerIdentity" method. Based on AliCloud's response, it grants an access token based on pre-configured roles. - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/auth/alicloud.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `auth/alicloud`. To enable this in a running Vault server: - -```sh -$ vault auth enable alicloud -Successfully enabled 'alicloud' at 'alicloud'! -``` - -To see all the supported paths, see the [AliCloud auth backend docs](https://www.vaultproject.io/docs/auth/alicloud.html). - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine. - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-alicloud`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/alicloud \ - sha_256= \ - command="vault-plugin-auth-alicloud" -... -Success! Data written to: sys/plugins/catalog/alicloud -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-auth-alicloud -... -SHA256(.../go/bin/vault-plugin-auth-alicloud)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the AliCloud auth plugin: - -```sh -$ vault auth enable -plugin-name='alicloud' plugin -... - -Successfully enabled 'plugin' at 'alicloud'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/arn.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/arn.go deleted file mode 100644 index c728ac9a7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/arn.go +++ /dev/null @@ -1,94 +0,0 @@ -package alicloud - -import ( - "errors" - "fmt" - "strings" -) - -func parseARN(a string) (*arn, error) { - if a == "" { - return nil, errors.New("no arn provided") - } - - // Example: "acs:ram::5138828231865461:assumed-role/elk/vm-ram-i-rj978rorvlg76urhqh7q" - parsed := &arn{ - Full: a, - } - outerFields := strings.Split(a, ":") - if len(outerFields) != 5 { - return nil, fmt.Errorf("unrecognized arn: contains %d colon-separated fields, expected 5", len(outerFields)) - } - if outerFields[0] != "acs" { - return nil, errors.New(`unrecognized arn: does not begin with "acs:"`) - } - if outerFields[1] != "ram" { - return nil, fmt.Errorf("unrecognized service: %v, not ram", outerFields[1]) - } - parsed.AccountNumber = outerFields[3] - - roleFields := strings.Split(outerFields[4], "/") - if len(roleFields) < 2 { - return nil, fmt.Errorf("unrecognized arn: %q contains fewer than 2 slash-separated roleFields", outerFields[4]) - } - - entityType := roleFields[0] - switch entityType { - case "assumed-role": - parsed.Type = arnTypeAssumedRole - case "role": - parsed.Type = arnTypeRole - default: - return nil, fmt.Errorf("unsupported parsed type: %s", entityType) - } - - parsed.RoleName = roleFields[1] - if len(roleFields) > 2 { - parsed.RoleAssumerName = roleFields[2] - } - return parsed, nil -} - -type arnType int - -func (t arnType) String() string { - switch t { - case arnTypeRole: - return "role" - case arnTypeAssumedRole: - return "assumed-role" - default: - return "" - } -} - -const ( - arnTypeRole arnType = iota - arnTypeAssumedRole -) - -type arn struct { - AccountNumber string - Type arnType - RoleName string - RoleAssumerName string - Full string -} - -func (a *arn) IsMemberOf(possibleParent *arn) bool { - if possibleParent.Type != arnTypeRole || a.Type != arnTypeAssumedRole { - // We currently only support the relationship between roles and assumed roles. - return false - } - if possibleParent.AccountNumber != a.AccountNumber { - return false - } - if possibleParent.RoleName != a.RoleName { - return false - } - return true -} - -func (a *arn) String() string { - return a.Full -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/backend.go deleted file mode 100644 index e6811c7df..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/backend.go +++ /dev/null @@ -1,57 +0,0 @@ -package alicloud - -import ( - "context" - "net/http" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - client := cleanhttp.DefaultClient() - client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - } - b := newBackend(client) - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// newBackend exists for testability. It allows us to inject a fake client. -func newBackend(client *http.Client) *backend { - b := &backend{ - identityClient: client, - } - b.Backend = &framework.Backend{ - AuthRenew: b.pathLoginRenew, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - }, - Paths: []*framework.Path{ - pathLogin(b), - pathListRole(b), - pathListRoles(b), - pathRole(b), - }, - BackendType: logical.TypeCredential, - } - return b -} - -type backend struct { - *framework.Backend - - identityClient *http.Client -} - -const backendHelp = ` -That AliCloud RAM auth method allows entities to authenticate based on their -identity and pre-configured roles. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/cli.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/cli.go deleted file mode 100644 index a52630ea2..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/cli.go +++ /dev/null @@ -1,89 +0,0 @@ -package alicloud - -import ( - "errors" - "fmt" - "strings" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/providers" - "github.com/hashicorp/vault-plugin-auth-alicloud/tools" - "github.com/hashicorp/vault/api" -) - -type CLIHandler struct{} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "alicloud" - } - role := m["role"] - - credentialChain := []providers.Provider{ - providers.NewConfigurationCredentialProvider(&providers.Configuration{ - AccessKeyID: m["access_key"], - AccessKeySecret: m["secret_key"], - AccessKeyStsToken: m["security_token"], - }), - providers.NewEnvCredentialProvider(), - providers.NewInstanceMetadataProvider(), - } - creds, err := providers.NewChainProvider(credentialChain).Retrieve() - if err != nil { - return nil, err - } - - loginData, err := tools.GenerateLoginData(role, creds, m["region"]) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("auth/%s/login", mount) - - secret, err := c.Logical().Write(path, loginData) - if err != nil { - return nil, err - } - if secret == nil { - return nil, errors.New("empty response from credential provider") - } - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=alicloud [CONFIG K=V...] - - The AliCloud auth method allows users to authenticate with AliCloud RAM - credentials. - - The AliCloud RAM credentials may be specified explicitly via the command line: - - $ vault login -method=alicloud access_key=... secret_key=... security_token=... region=... - -Configuration: - - access_key= - Explicit AliCloud access key ID - - secret_key= - Explicit AliCloud secret access key - - security_token= - Explicit AliCloud security token - - region= - Explicit AliCloud region - - mount= - Path where the AliCloud credential method is mounted. This is usually provided - via the -path flag in the "vault login" command, but it can be specified - here as well. If specified here, it takes precedence over the value for - -path. The default value is "alicloud". - - role= - Name of the role to request a token against -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_login.go deleted file mode 100644 index 8af904bee..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_login.go +++ /dev/null @@ -1,248 +0,0 @@ -package alicloud - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints" - "github.com/aliyun/alibaba-cloud-sdk-go/services/sts" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeString, - Description: `Name of the role against which the login is being attempted. -If 'role' is not specified, then the login endpoint looks for a role name in the ARN returned by -the GetCallerIdentity request. If a matching role is not found, login fails.`, - }, - "identity_request_url": { - Type: framework.TypeString, - Description: "Base64-encoded full URL against which to make the AliCloud request.", - }, - "identity_request_headers": { - Type: framework.TypeHeader, - Description: `The request headers. This must include the headers over which AliCloud -has included a signature.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLoginUpdate, - }, - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - - b64URL := data.Get("identity_request_url").(string) - if b64URL == "" { - return nil, errors.New("missing identity_request_url") - } - identityReqURL, err := base64.StdEncoding.DecodeString(b64URL) - if err != nil { - return nil, errwrap.Wrapf("failed to base64 decode identity_request_url: {{err}}", err) - } - if _, err := url.Parse(string(identityReqURL)); err != nil { - return nil, errwrap.Wrapf("error parsing identity_request_url: {{err}}", err) - } - - header := data.Get("identity_request_headers").(http.Header) - if len(header) == 0 { - return nil, errors.New("missing identity_request_headers") - } - - callerIdentity, err := b.getCallerIdentity(header, string(identityReqURL)) - if err != nil { - return nil, errwrap.Wrapf("error making upstream request: {{err}}", err) - } - - parsedARN, err := parseARN(callerIdentity.Arn) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("unable to parse entity's arn %s due to {{err}}", callerIdentity.Arn), err) - } - if parsedARN.Type != arnTypeAssumedRole { - return nil, fmt.Errorf("only %s arn types are supported at this time, but %s was provided", arnTypeAssumedRole, parsedARN.Type) - } - - // If a role name was explicitly provided, use that, but otherwise fall back to using the role - // in the ARN returned by the GetCallerIdentity call. - roleName := "" - roleNameIfc, ok := data.GetOk("role") - if ok { - roleName = roleNameIfc.(string) - } else { - roleName = parsedARN.RoleName - } - - role, err := readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("entry for role %s not found", parsedARN.RoleName) - } - - if !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, role.BoundCIDRs) { - return nil, errors.New("login request originated from invalid CIDR") - } - if !parsedARN.IsMemberOf(role.ARN) { - return nil, errors.New("the caller's arn does not match the role's arn") - } - return &logical.Response{ - Auth: &logical.Auth{ - Period: role.Period, - Policies: role.Policies, - Metadata: map[string]string{ - "account_id": callerIdentity.AccountId, - "user_id": callerIdentity.UserId, - "role_id": callerIdentity.RoleId, - "arn": callerIdentity.Arn, - "identity_type": callerIdentity.IdentityType, - "principal_id": callerIdentity.PrincipalId, - "request_id": callerIdentity.RequestId, - "role_name": roleName, - }, - DisplayName: callerIdentity.PrincipalId, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - Alias: &logical.Alias{ - Name: callerIdentity.PrincipalId, - }, - BoundCIDRs: role.BoundCIDRs, - }, - }, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // The arn set in metadata earlier is the assumed-role arn. - arn := req.Auth.Metadata["arn"] - if arn == "" { - return nil, errors.New("unable to retrieve arn from metadata during renewal") - } - parsedARN, err := parseARN(arn) - if err != nil { - return nil, err - } - - roleName, ok := req.Auth.Metadata["role_name"] - if !ok { - return nil, errors.New("error retrieving role_name during renewal") - } - - role, err := readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, errors.New("role entry not found") - } - - if !parsedARN.IsMemberOf(role.ARN) { - return nil, errors.New("the caller's arn does not match the role's arn") - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = role.TTL - resp.Auth.MaxTTL = role.MaxTTL - resp.Auth.Period = role.Period - return resp, nil -} - -func (b *backend) getCallerIdentity(header http.Header, rawURL string) (*sts.GetCallerIdentityResponse, error) { - /* - Here we need to ensure we're actually hitting the AliCloud service, and that the caller didn't - inject a URL to their own service that will respond as desired. - */ - u, err := url.Parse(rawURL) - if err != nil { - return nil, err - } - if u.Scheme != "https" { - return nil, fmt.Errorf(`expected "https" url scheme but received "%s"`, u.Scheme) - } - stsEndpoint, err := getSTSEndpoint() - if err != nil { - return nil, err - } - if u.Host != stsEndpoint { - return nil, fmt.Errorf(`expected host of "sts.aliyuncs.com" but received "%s"`, u.Host) - } - q := u.Query() - if q.Get("Format") != "JSON" { - return nil, fmt.Errorf("query Format must be JSON but received %s", q.Get("Format")) - } - if q.Get("Action") != "GetCallerIdentity" { - return nil, fmt.Errorf("query Action must be GetCallerIdentity but received %s", q.Get("Action")) - } - - request, err := http.NewRequest(http.MethodPost, rawURL, nil) - if err != nil { - return nil, err - } - request.Header = header - - response, err := b.identityClient.Do(request) - if err != nil { - return nil, errwrap.Wrapf("error making request: {{err}}", err) - } - defer response.Body.Close() - - if response.StatusCode != 200 { - b, err := ioutil.ReadAll(response.Body) - if err != nil { - return nil, errwrap.Wrapf("error reading response body: {{err}}", err) - } - return nil, fmt.Errorf("received %d checking caller identity: %s", response.StatusCode, b) - } - - result := &sts.GetCallerIdentityResponse{} - if err := json.NewDecoder(response.Body).Decode(result); err != nil { - return nil, errwrap.Wrapf("error decoding response: {{err}}", err) - } - return result, nil -} - -func getSTSEndpoint() (string, error) { - r := &endpoints.LocalGlobalResolver{} - endpoint, supported, err := r.TryResolve(&endpoints.ResolveParam{ - Product: "sts", - }) - if err != nil { - return "", err - } - if !supported { - return "", errors.New("sts endpoint is no longer supported") - } - if endpoint == "" { - return "", errors.New("got an empty endpoint") - } - return endpoint, nil -} - -const pathLoginSyn = ` -Authenticates an RAM entity with Vault. -` - -const pathLoginDesc = ` -Authenticate AliCloud entities using an arbitrary RAM principal. - -RAM principals are authenticated by processing a signed sts:GetCallerIdentity -request and then parsing the response to see who signed the request. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_role.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_role.go deleted file mode 100644 index 2de8aa4d9..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/path_role.go +++ /dev/null @@ -1,228 +0,0 @@ -package alicloud - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathRole(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role"), - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeLowerCaseString, - Description: "The name of the role as it should appear in Vault.", - }, - "arn": { - Type: framework.TypeString, - Description: "ARN of the RAM to bind to this role.", - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be set on tokens issued using this role.", - }, - "ttl": { - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fallback to the system/mount defaults.`, - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: "The maximum allowed lifetime of tokens issued using this role.", - }, - "period": { - Type: framework.TypeDurationSecond, - Description: ` -If set, indicates that the token generated using this role should never expire. -The token should be renewed within the duration specified by this value. At -each renewal, the token's TTL will be set to the value of this parameter.`, - }, - "bound_cidrs": { - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - }, - ExistenceCheck: b.operationRoleExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.operationRoleCreateUpdate, - logical.UpdateOperation: b.operationRoleCreateUpdate, - logical.ReadOperation: b.operationRoleRead, - logical.DeleteOperation: b.operationRoleDelete, - }, - HelpSynopsis: pathRoleSyn, - HelpDescription: pathRoleDesc, - } -} - -func pathListRole(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.operationRoleList, - }, - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.operationRoleList, - }, - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) operationRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := readRole(ctx, req.Storage, data.Get("role").(string)) - if err != nil { - return false, err - } - return entry != nil, nil -} - -func (b *backend) operationRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - - roleName := data.Get("role").(string) - - role, err := readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil && req.Operation == logical.UpdateOperation { - return nil, fmt.Errorf("no role found to update for %s", roleName) - } else if role == nil { - role = &roleEntry{} - } - - if raw, ok := data.GetOk("arn"); ok { - arn, err := parseARN(raw.(string)) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("unable to parse arn %s: {{err}}", arn), err) - } - if arn.Type != arnTypeRole { - return nil, fmt.Errorf("only role arn types are supported at this time, but %s was provided", role.ARN) - } - role.ARN = arn - } else if req.Operation == logical.CreateOperation { - return nil, errors.New("the arn is required to create a role") - } - - // None of the remaining fields are required. - if raw, ok := data.GetOk("policies"); ok { - role.Policies = raw.([]string) - } - if raw, ok := data.GetOk("ttl"); ok { - role.TTL = time.Duration(raw.(int)) * time.Second - } - if raw, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(raw.(int)) * time.Second - } - if raw, ok := data.GetOk("period"); ok { - role.Period = time.Duration(raw.(int)) * time.Second - } - boundCIDRs, err := parseutil.ParseAddrs(data.Get("bound_cidrs")) - if err != nil { - return nil, err - } - role.BoundCIDRs = boundCIDRs - - if role.MaxTTL > 0 && role.TTL > role.MaxTTL { - return nil, errors.New("ttl exceeds max_ttl") - } - - entry, err := logical.StorageEntryJSON("role/"+roleName, role) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - if role.TTL > b.System().MaxLeaseTTL() { - resp := &logical.Response{} - resp.AddWarning(fmt.Sprintf("ttl of %d exceeds the system max ttl of %d, the latter will be used during login", role.TTL, b.System().MaxLeaseTTL())) - return resp, nil - } - return nil, nil -} - -func (b *backend) operationRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := readRole(ctx, req.Storage, data.Get("role").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - return &logical.Response{ - Data: role.ToResponseData(), - }, nil -} - -func (b *backend) operationRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if err := req.Storage.Delete(ctx, "role/"+data.Get("role").(string)); err != nil { - return nil, err - } - return nil, nil -} - -func (b *backend) operationRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleNames, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roleNames), nil -} - -func readRole(ctx context.Context, s logical.Storage, roleName string) (*roleEntry, error) { - role, err := s.Get(ctx, "role/"+roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - result := &roleEntry{} - if err := role.DecodeJSON(result); err != nil { - return nil, err - } - return result, nil -} - -const pathRoleSyn = ` -Create a role and associate policies to it. -` - -const pathRoleDesc = ` -A precondition for login is that a role should be created in the backend. -The login endpoint takes in the role name against which the instance -should be validated. After authenticating the instance, the authorization -for the instance to access Vault's resources is determined by the policies -that are associated to the role though this endpoint. - -Also, a 'max_ttl' can be configured in this endpoint that determines the maximum -duration for which a login can be renewed. Note that the 'max_ttl' has an upper -limit of the 'max_ttl' value on the backend's mount. The same applies to the 'ttl'. -` - -const pathListRolesHelpSyn = ` -Lists all the roles that are registered with Vault. -` - -const pathListRolesHelpDesc = ` -Roles will be listed by their respective role names. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/role_entry.go b/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/role_entry.go deleted file mode 100644 index a9240ace7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-alicloud/role_entry.go +++ /dev/null @@ -1,31 +0,0 @@ -package alicloud - -import ( - "time" - - "github.com/hashicorp/go-sockaddr" -) - -type roleEntry struct { - ARN *arn `json:"arn"` - Policies []string `json:"policies"` - TTL time.Duration `json:"ttl"` - MaxTTL time.Duration `json:"max_ttl"` - Period time.Duration `json:"period"` - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` -} - -func (r *roleEntry) ToResponseData() map[string]interface{} { - cidrs := make([]string, len(r.BoundCIDRs)) - for i, cidr := range r.BoundCIDRs { - cidrs[i] = cidr.String() - } - return map[string]interface{}{ - "arn": r.ARN.String(), - "policies": r.Policies, - "ttl": r.TTL / time.Second, - "max_ttl": r.MaxTTL / time.Second, - "period": r.Period / time.Second, - "bound_cidrs": cidrs, - } -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.lock deleted file mode 100644 index a8eb992af..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.lock +++ /dev/null @@ -1,484 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:bb4d5c2555cb0d2b09e657264bb9ae6e734a636cd62c7eb70b9d7f2fa01ed693" - name = "github.com/Azure/azure-sdk-for-go" - packages = [ - "services/compute/mgmt/2017-12-01/compute", - "version", - ] - pruneopts = "UT" - revision = "4e8cbbfb1aeab140cd0fa97fd16b64ee18c3ca6a" - version = "v19.1.0" - -[[projects]] - digest = "1:e782078a170a8f36451e2b6468d0cce2ac394d809054d8ec6820961fa58430fe" - name = "github.com/Azure/go-autorest" - packages = [ - "autorest", - "autorest/adal", - "autorest/azure", - "autorest/azure/auth", - "autorest/date", - "autorest/to", - "autorest/validation", - "logger", - "version", - ] - pruneopts = "UT" - revision = "39013ecb48eaf6ced3f4e3e1d95515140ce6b3cf" - version = "v10.15.2" - -[[projects]] - digest = "1:a69ab3f1445ffd4815add4bd31ba05b65b3b9fec1ade5057d5d717f30e6efd6d" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - digest = "1:f6e5e1bc64c2908167e6aa9a1fe0c084d515132a1c63ad5b6c84036aa06dc0c1" - name = "github.com/coreos/go-oidc" - packages = ["."] - pruneopts = "UT" - revision = "1180514eaf4d9f38d0d19eef639a1d695e066e72" - version = "v2.0.0" - -[[projects]] - digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "UT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - branch = "master" - digest = "1:e608bc2d867c3ded40ccea5417715393a50704ac24004afa87431a0e1976e50d" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "UT" - revision = "5448fe645cb1964ba70ac8f9f2ffe975e61a536c" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:450803219e484669ba680c777ecac629dac92abde2bc83009beaa630f5368e71" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/policyutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "8655d167084028d627f687ddc25d0c71307eb5be" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:bd9efe4e0b0f768302a1e2f0c22458149278de533e521206e5ddc71848c269a0" - name = "github.com/pquerna/cachecontrol" - packages = [ - ".", - "cacheobject", - ] - pruneopts = "UT" - revision = "1555304b9b35fdd2b425bccf1a5613677705e7d0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - digest = "1:7b96c8e8cb2c424889739f08eaaded640b0ef096fe4861ec28b3575ed4da7e77" - name = "golang.org/x/crypto" - packages = [ - "ed25519", - "ed25519/internal/edwards25519", - "pbkdf2", - "pkcs12", - "pkcs12/internal/rc2", - ] - pruneopts = "UT" - revision = "de0752318171da717af4ce24d0a2e8626afaeb11" - -[[projects]] - branch = "master" - digest = "1:3c4175c2711d67096567fc2d84a83464d6ff58119af3efc89983339d64144cb0" - name = "golang.org/x/net" - packages = [ - "context", - "context/ctxhttp", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:af19f6e6c369bf51ef226e989034cd88a45083173c02ac4d7ab74c9a90d356b7" - name = "golang.org/x/oauth2" - packages = [ - ".", - "internal", - ] - pruneopts = "UT" - revision = "3d292e4d0cdc3a0113e6d207bb137145ef1de42f" - -[[projects]] - branch = "master" - digest = "1:05662433b3a13c921587a6e622b5722072edff83211efd1cd79eeaeedfd83f07" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - digest = "1:328b5e4f197d928c444a51a75385f4b978915c0e75521f0ad6a3db976c97a7d3" - name = "google.golang.org/appengine" - packages = [ - "internal", - "internal/base", - "internal/datastore", - "internal/log", - "internal/remote_api", - "internal/urlfetch", - "urlfetch", - ] - pruneopts = "UT" - revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[[projects]] - digest = "1:02d2c5be9a35ce750536e74af0d98aca806f225913a3ab28f285843d6283c70d" - name = "gopkg.in/square/go-jose.v2" - packages = [ - ".", - "cipher", - "json", - ] - pruneopts = "UT" - revision = "8254d6c783765f38c8675fae4427a1fe73fbd09d" - version = "v2.1.8" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-12-01/compute", - "github.com/Azure/go-autorest/autorest", - "github.com/Azure/go-autorest/autorest/azure", - "github.com/Azure/go-autorest/autorest/azure/auth", - "github.com/Azure/go-autorest/autorest/to", - "github.com/coreos/go-oidc", - "github.com/hashicorp/errwrap", - "github.com/hashicorp/go-cleanhttp", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/helper/policyutil", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - "golang.org/x/oauth2", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.toml deleted file mode 100644 index 63116478b..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Gopkg.toml +++ /dev/null @@ -1,62 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - name = "github.com/Azure/azure-sdk-for-go" - version = "19.1.0" - -[[constraint]] - name = "github.com/Azure/go-autorest" - version = "10.15.2" - -[[constraint]] - name = "github.com/coreos/go-oidc" - version = "2.0.0" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/errwrap" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[[constraint]] - branch = "master" - name = "golang.org/x/oauth2" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-azure/LICENSE deleted file mode 100644 index be2cc4dfb..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/LICENSE +++ /dev/null @@ -1,362 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Makefile b/vendor/github.com/hashicorp/vault-plugin-auth-azure/Makefile deleted file mode 100644 index f07b972db..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -TOOL?=vault-plugin-auth-azure -TEST?=$$(go list ./... | grep -v /vendor/) -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin, except for quickdev which -# is only put into /bin/ -quickdev: generate - @CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/${TOOL} -dev: generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -testcompile: generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# test runs all tests -test: generate - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 10m - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - @go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmt: - gofmt -w $(GOFMT_FILES) - -# deps updates all dependencies for this project. -deps: - @echo "==> Updating deps for ${TOOL}" - @dep ensure -update - -.PHONY: bin default generate test bootstrap fmt deps diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/README.md b/vendor/github.com/hashicorp/vault-plugin-auth-azure/README.md deleted file mode 100644 index 1312cf96f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# Vault Plugin: Azure Auth Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-auth-azure.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-auth-azure) - - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin allows for Azure Managed Service Identities to authenticate with Vault. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - Azure Auth Docs: https://www.vaultproject.io/docs/auth/azure.html - - Main Project Github: https://www.github.com/hashicorp/vault - - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Security Model - -The current authentication model requires providing Vault with a token generated using Azure's Managed Service Identity, which can be used to make authenticated calls to Azure. This token should not typically be shared, but in order for Azure to be treated as a trusted third party, Vault must validate something that Azure has cryptographically signed and that conveys the identity of the token holder. - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/auth/azure.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `auth/azure`. To enable this in a running Vault server: - -```sh -$ vault auth enable azure -Successfully enabled 'azure' at 'azure'! -``` - -To see all the supported paths, see the [Azure auth backend docs](https://www.vaultproject.io/docs/auth/azure.html). - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine. - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-azure`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/azure \ - sha_256= \ - command="vault-plugin-auth-azure" -... -Success! Data written to: sys/plugins/catalog/azure -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-auth-azure -... -SHA256(.../go/bin/vault-plugin-auth-azure)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the Azure auth plugin: - -```sh -$ vault auth enable -plugin-name='azure' plugin -... - -Successfully enabled 'plugin' at 'azure'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/azure.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/azure.go deleted file mode 100644 index 179576537..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/azure.go +++ /dev/null @@ -1,239 +0,0 @@ -package azureauth - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "os" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-12-01/compute" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/azure/auth" - oidc "github.com/coreos/go-oidc" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "golang.org/x/oauth2" -) - -type computeClient interface { - Get(ctx context.Context, resourceGroup, vmName string, instanceView compute.InstanceViewTypes) (compute.VirtualMachine, error) -} - -type vmssClient interface { - Get(ctx context.Context, resourceGroup, vmssName string) (compute.VirtualMachineScaleSet, error) -} - -type tokenVerifier interface { - Verify(ctx context.Context, token string) (*oidc.IDToken, error) -} - -type provider interface { - Verifier() tokenVerifier - ComputeClient(subscriptionID string) (computeClient, error) - VMSSClient(subscriptionID string) (vmssClient, error) -} - -type azureProvider struct { - oidcVerifier *oidc.IDTokenVerifier - settings *azureSettings - httpClient *http.Client -} - -type oidcDiscoveryInfo struct { - Issuer string `json:"issuer"` - JWKSURL string `json:"jwks_uri"` -} - -func newAzureProvider(config *azureConfig) (*azureProvider, error) { - httpClient := cleanhttp.DefaultClient() - settings, err := getAzureSettings(config) - if err != nil { - return nil, err - } - - // In many OIDC providers, the discovery endpoint matches the issuer. For Azure AD, the discovery - // endpoint is the AD endpoint which does not match the issuer defined in the discovery payload. This - // makes a request to the discovery URL to determine the issuer and key set information to configure - // the OIDC verifier - discoveryURL := fmt.Sprintf("%s%s/.well-known/openid-configuration", settings.Environment.ActiveDirectoryEndpoint, settings.TenantID) - req, err := http.NewRequest("GET", discoveryURL, nil) - if err != nil { - return nil, err - } - req.Header.Set("User-Agent", userAgent()) - - resp, err := httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errwrap.Wrapf("unable to read response body: {{err}}", err) - } - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s: %s", resp.Status, body) - } - var discoveryInfo oidcDiscoveryInfo - if err := json.Unmarshal(body, &discoveryInfo); err != nil { - return nil, errwrap.Wrapf("unable to unmarshal discovery url: {{err}}", err) - } - - // Create a remote key set from the discovery endpoint - ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient) - remoteKeySet := oidc.NewRemoteKeySet(ctx, discoveryInfo.JWKSURL) - - verifierConfig := &oidc.Config{ - ClientID: settings.Resource, - SupportedSigningAlgs: []string{oidc.RS256}, - } - oidcVerifier := oidc.NewVerifier(discoveryInfo.Issuer, remoteKeySet, verifierConfig) - - // Ping the metadata service (if available) - go pingMetadataService() - - return &azureProvider{ - settings: settings, - oidcVerifier: oidcVerifier, - httpClient: httpClient, - }, nil -} - -func (p *azureProvider) Verifier() tokenVerifier { - return p.oidcVerifier -} - -func (p *azureProvider) ComputeClient(subscriptionID string) (computeClient, error) { - authorizer, err := p.getAuthorizer() - if err != nil { - return nil, err - } - - client := compute.NewVirtualMachinesClient(subscriptionID) - client.Authorizer = authorizer - client.Sender = p.httpClient - client.AddToUserAgent(userAgent()) - return client, nil -} - -func (p *azureProvider) VMSSClient(subscriptionID string) (vmssClient, error) { - authorizer, err := p.getAuthorizer() - if err != nil { - return nil, err - } - - client := compute.NewVirtualMachineScaleSetsClient(subscriptionID) - client.Authorizer = authorizer - client.Sender = p.httpClient - client.AddToUserAgent(userAgent()) - return client, nil -} - -func (p *azureProvider) getAuthorizer() (autorest.Authorizer, error) { - // Create an OAuth2 client for retrieving VM data - var authorizer autorest.Authorizer - var err error - switch { - // Use environment/config first - case p.settings.ClientSecret != "": - config := auth.NewClientCredentialsConfig(p.settings.ClientID, p.settings.ClientSecret, p.settings.TenantID) - config.AADEndpoint = p.settings.Environment.ActiveDirectoryEndpoint - config.Resource = p.settings.Environment.ResourceManagerEndpoint - authorizer, err = config.Authorizer() - if err != nil { - return nil, err - } - // By default use MSI - default: - config := auth.NewMSIConfig() - config.Resource = p.settings.Environment.ResourceManagerEndpoint - authorizer, err = config.Authorizer() - if err != nil { - return nil, err - } - } - return authorizer, nil -} - -type azureSettings struct { - TenantID string - ClientID string - ClientSecret string - Environment azure.Environment - Resource string -} - -func getAzureSettings(config *azureConfig) (*azureSettings, error) { - settings := new(azureSettings) - - envTenantID := os.Getenv("AZURE_TENANT_ID") - switch { - case envTenantID != "": - settings.TenantID = envTenantID - case config.TenantID != "": - settings.TenantID = config.TenantID - default: - return nil, errors.New("tenant_id is required") - } - - envResource := os.Getenv("AZURE_AD_RESOURCE") - switch { - case envResource != "": - settings.Resource = envResource - case config.Resource != "": - settings.Resource = config.Resource - default: - return nil, errors.New("resource is required") - } - - clientID := os.Getenv("AZURE_CLIENT_ID") - if clientID == "" { - clientID = config.ClientID - } - settings.ClientID = clientID - - clientSecret := os.Getenv("AZURE_CLIENT_SECRET") - if clientSecret == "" { - clientSecret = config.ClientSecret - } - settings.ClientSecret = clientSecret - - envName := os.Getenv("AZURE_ENVIRONMENT") - if envName == "" { - envName = config.Environment - } - if envName == "" { - settings.Environment = azure.PublicCloud - } else { - var err error - settings.Environment, err = azure.EnvironmentFromName(envName) - if err != nil { - return nil, err - } - } - - return settings, nil -} - -// This is simply to ping the Azure metadata service, if it is running -// in Azure -func pingMetadataService() { - client := cleanhttp.DefaultClient() - client.Timeout = 5 * time.Second - req, _ := http.NewRequest("GET", "http://169.254.169.254/metadata/instance", nil) - req.Header.Add("Metadata", "True") - req.Header.Set("User-Agent", userAgent()) - - q := req.URL.Query() - q.Add("format", "json") - q.Add("api-version", "2017-04-02") - req.URL.RawQuery = q.Encode() - - client.Do(req) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/backend.go deleted file mode 100644 index 02fdda1e7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/backend.go +++ /dev/null @@ -1,99 +0,0 @@ -package azureauth - -import ( - "context" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Factory is used by framework -func Factory(ctx context.Context, c *logical.BackendConfig) (logical.Backend, error) { - b := backend(c) - if err := b.Setup(ctx, c); err != nil { - return nil, err - } - return b, nil -} - -type azureAuthBackend struct { - *framework.Backend - - l sync.RWMutex - - provider provider -} - -func backend(c *logical.BackendConfig) *azureAuthBackend { - b := new(azureAuthBackend) - - b.Backend = &framework.Backend{ - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - Invalidate: b.invalidate, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - SealWrapStorage: []string{ - "config", - }, - }, - Paths: framework.PathAppend( - []*framework.Path{ - pathLogin(b), - pathConfig(b), - }, - pathsRole(b), - ), - } - - return b -} - -func (b *azureAuthBackend) invalidate(ctx context.Context, key string) { - switch key { - case "config": - b.reset() - } -} - -func (b *azureAuthBackend) getProvider(config *azureConfig) (provider, error) { - b.l.RLock() - unlockFunc := b.l.RUnlock - defer func() { unlockFunc() }() - - if b.provider != nil { - return b.provider, nil - } - - // Upgrade lock - b.l.RUnlock() - b.l.Lock() - unlockFunc = b.l.Unlock - - if b.provider != nil { - return b.provider, nil - } - - provider, err := newAzureProvider(config) - if err != nil { - return nil, err - } - - b.provider = provider - return b.provider, nil -} - -func (b *azureAuthBackend) reset() { - b.l.Lock() - defer b.l.Unlock() - - b.provider = nil -} - -const backendHelp = ` -The Azure backend plugin allows authentication for Azure . -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_config.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_config.go deleted file mode 100644 index 8b18cc906..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_config.go +++ /dev/null @@ -1,177 +0,0 @@ -package azureauth - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *azureAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "tenant_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The tenant id for the Azure Active Directory. This is sometimes - referred to as Directory ID in AD. This value can also be provided with the - AZURE_TENANT_ID environment variable.`, - }, - "resource": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The resource URL for the vault application in Azure Active Directory. - This value can also be provided with the AZURE_AD_RESOURCE environment variable.`, - }, - "environment": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The Azure environment name. If not provided, AzurePublicCloud is used. - This value can also be provided with the AZURE_ENVIRONMENT environment variable.`, - }, - "client_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The OAuth2 client id to connection to Azure. - This value can also be provided with the AZURE_CLIENT_ID environment variable.`, - }, - "client_secret": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The OAuth2 client secret to connection to Azure. - This value can also be provided with the AZURE_CLIENT_SECRET environment variable.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.CreateOperation: b.pathConfigWrite, - logical.UpdateOperation: b.pathConfigWrite, - logical.DeleteOperation: b.pathConfigDelete, - }, - ExistenceCheck: b.pathConfigExistenceCheck, - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -type azureConfig struct { - TenantID string `json:"tenant_id"` - Resource string `json:"resource"` - Environment string `json:"environment"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` -} - -func (b *azureAuthBackend) config(ctx context.Context, s logical.Storage) (*azureConfig, error) { - entry, err := s.Get(ctx, "config") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - config := new(azureConfig) - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - return config, nil -} - -func (b *azureAuthBackend) pathConfigExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return false, err - } - return config != nil, nil -} - -func (b *azureAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - config = new(azureConfig) - } - - tenantID, ok := data.GetOk("tenant_id") - if ok { - config.TenantID = tenantID.(string) - } - - resource, ok := data.GetOk("resource") - if ok { - config.Resource = resource.(string) - } - - environment, ok := data.GetOk("environment") - if ok { - config.Environment = environment.(string) - } - - clientID, ok := data.GetOk("client_id") - if ok { - config.ClientID = clientID.(string) - } - - clientSecret, ok := data.GetOk("client_secret") - if ok { - config.ClientSecret = clientSecret.(string) - } - - // Create a settings object to validate all required settings - // are available - if _, err := getAzureSettings(config); err != nil { - return nil, err - } - - entry, err := logical.StorageEntryJSON("config", config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset backend - b.reset() - - return nil, nil -} - -func (b *azureAuthBackend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "tenant_id": config.TenantID, - "resource": config.Resource, - "environment": config.Environment, - "client_id": config.ClientID, - }, - } - return resp, nil -} - -func (b *azureAuthBackend) pathConfigDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "config") - - if err == nil { - b.reset() - } - - return nil, err -} - -const confHelpSyn = `Configures the Azure authentication backend.` -const confHelpDesc = ` -The Azure authentication backend validates the login JWTs using the -configured credentials. In order to validate machine information, the -OAuth2 client id and secret are used to query the Azure API. The OAuth2 -credentials require Microsoft.Compute/virtualMachines/read permission on -the resource requesting credentials. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_login.go deleted file mode 100644 index 8d9fdd206..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_login.go +++ /dev/null @@ -1,309 +0,0 @@ -package azureauth - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-12-01/compute" - "github.com/Azure/go-autorest/autorest/to" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *azureAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The token role.`, - }, - "jwt": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `A signed JWT`, - }, - "subscription_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The subscription id for the instance.`, - }, - "resource_group_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The resource group from the instance.`, - }, - "vm_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The name of the virtual machine. This value is ignored if vmss_name is specified.`, - }, - "vmss_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The name of the virtual machine scale set the instance is in.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLogin, - }, - - HelpSynopsis: pathLoginHelpSyn, - HelpDescription: pathLoginHelpDesc, - } -} - -func (b *azureAuthBackend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - signedJwt := data.Get("jwt").(string) - if signedJwt == "" { - return logical.ErrorResponse("jwt is required"), nil - } - roleName := data.Get("role").(string) - if roleName == "" { - return logical.ErrorResponse("role is required"), nil - } - subscriptionID := data.Get("subscription_id").(string) - resourceGroupName := data.Get("resource_group_name").(string) - vmssName := data.Get("vmss_name").(string) - vmName := data.Get("vm_name").(string) - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, errwrap.Wrapf("unable to retrieve backend configuration: {{err}}", err) - } - if config == nil { - config = new(azureConfig) - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid role name %q", roleName)), nil - } - - provider, err := b.getProvider(config) - if err != nil { - return nil, err - } - - // The OIDC verifier verifies the signature and checks the 'aud' and 'iss' - // claims and expiration time - idToken, err := provider.Verifier().Verify(ctx, signedJwt) - if err != nil { - return nil, err - } - - claims := new(additionalClaims) - if err := idToken.Claims(claims); err != nil { - return nil, err - } - - // Check additional claims in token - if err := b.verifyClaims(claims, role); err != nil { - return nil, err - } - - if err := b.verifyResource(ctx, subscriptionID, resourceGroupName, vmName, vmssName, claims, role); err != nil { - return nil, err - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - Policies: role.Policies, - DisplayName: idToken.Subject, - Period: role.Period, - NumUses: role.NumUses, - Alias: &logical.Alias{ - Name: idToken.Subject, - }, - InternalData: map[string]interface{}{ - "role": roleName, - }, - Metadata: map[string]string{ - "role": roleName, - }, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - }, - } - - // Add groups to group aliases - for _, groupID := range claims.GroupIDs { - if groupID == "" { - continue - } - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: groupID, - }) - } - - return resp, nil -} - -func (b *azureAuthBackend) verifyClaims(claims *additionalClaims, role *azureRole) error { - notBefore := time.Time(claims.NotBefore) - if notBefore.After(time.Now()) { - return fmt.Errorf("token is not yet valid (Token Not Before: %v)", notBefore) - } - - switch { - case len(role.BoundServicePrincipalIDs) == 1 && role.BoundServicePrincipalIDs[0] == "*": - case len(role.BoundServicePrincipalIDs) > 0: - if !strListContains(role.BoundServicePrincipalIDs, claims.ObjectID) { - return fmt.Errorf("service principal not authorized: %s", claims.ObjectID) - } - } - - if len(role.BoundGroupIDs) > 0 { - var found bool - for _, group := range claims.GroupIDs { - if strListContains(role.BoundGroupIDs, group) { - found = true - break - } - } - if !found { - return fmt.Errorf("groups not authorized: %v", claims.GroupIDs) - } - } - - return nil -} - -func (b *azureAuthBackend) verifyResource(ctx context.Context, subscriptionID, resourceGroupName, vmName string, vmssName string, claims *additionalClaims, role *azureRole) error { - // If not checking anything with the resource id, exit early - if len(role.BoundResourceGroups) == 0 && len(role.BoundSubscriptionsIDs) == 0 && len(role.BoundLocations) == 0 && len(role.BoundScaleSets) == 0 { - return nil - } - - if subscriptionID == "" || resourceGroupName == "" { - return errors.New("subscription_id and resource_group_name are required") - } - - var principalID, location *string - - switch { - // If vmss name is specified, the vm name will be ignored and only the scale set - // will be verified since vm names are generated automatically for scale sets - case vmssName != "": - client, err := b.provider.VMSSClient(subscriptionID) - if err != nil { - return errwrap.Wrapf("unable to create vmss client: {{err}}", err) - } - - vmss, err := client.Get(ctx, resourceGroupName, vmssName) - if err != nil { - return errwrap.Wrapf("unable to retrieve virtual machine scale set metadata: {{err}}", err) - } - - if vmss.Identity == nil { - return errors.New("vmss client did not return identity information") - } - if vmss.Identity.PrincipalID == nil { - return errors.New("vmss principal id is empty") - } - - // Check bound scale sets - if len(role.BoundScaleSets) > 0 && !strListContains(role.BoundScaleSets, vmssName) { - return errors.New("scale set not authorized") - } - - principalID = vmss.Identity.PrincipalID - location = vmss.Location - - case vmName != "": - client, err := b.provider.ComputeClient(subscriptionID) - if err != nil { - return errwrap.Wrapf("unable to create compute client: {{err}}", err) - } - - vm, err := client.Get(ctx, resourceGroupName, vmName, compute.InstanceView) - if err != nil { - return errwrap.Wrapf("unable to retrieve virtual machine metadata: {{err}}", err) - } - - if vm.Identity == nil { - return errors.New("vm client did not return identity information") - } - - if vm.Identity.PrincipalID == nil { - return errors.New("vm principal id is empty") - } - - // Check bound scale sets - if len(role.BoundScaleSets) > 0 { - return errors.New("bound scale set defined but this vm isn't in a scale set") - } - - principalID = vm.Identity.PrincipalID - location = vm.Location - - default: - return errors.New("either vm_name or vmss_name is required") - } - - // Ensure the principal id for the VM matches the verified token OID - if to.String(principalID) != claims.ObjectID { - return errors.New("token object id does not match virtual machine principal id") - } - - // Check bound subscriptions - if len(role.BoundSubscriptionsIDs) > 0 && !strListContains(role.BoundSubscriptionsIDs, subscriptionID) { - return errors.New("subscription not authorized") - } - - // Check bound resource groups - if len(role.BoundResourceGroups) > 0 && !strListContains(role.BoundResourceGroups, resourceGroupName) { - return errors.New("resource group not authorized") - } - - // Check bound locations - if len(role.BoundLocations) > 0 { - if location == nil { - return errors.New("vm location is empty") - } - if !strListContains(role.BoundLocations, to.String(location)) { - return errors.New("location not authorized") - } - } - - return nil -} - -func (b *azureAuthBackend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := req.Auth.InternalData["role"].(string) - if roleName == "" { - return nil, errors.New("failed to fetch role_name during renewal") - } - - // Ensure that the Role still exists. - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %s during renewal: {{err}}", roleName), err) - } - if role == nil { - return nil, fmt.Errorf("role %s does not exist during renewal", roleName) - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = role.TTL - resp.Auth.MaxTTL = role.MaxTTL - resp.Auth.Period = role.Period - return resp, nil -} - -type additionalClaims struct { - NotBefore jsonTime `json:"nbf"` - ObjectID string `json:"oid"` - GroupIDs []string `json:"groups"` -} - -const pathLoginHelpSyn = `Authenticates Azure Managed Service Identities with Vault.` -const pathLoginHelpDesc = ` -Authenticate Azure Managed Service Identities. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_role.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_role.go deleted file mode 100644 index 996e43435..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/path_role.go +++ /dev/null @@ -1,355 +0,0 @@ -package azureauth - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathsRole returns the path configurations for the CRUD operations on roles -func pathsRole(b *azureAuthBackend) []*framework.Path { - return []*framework.Path{ - &framework.Path{ - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "List of policies on the role.", - }, - "num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of times issued tokens can be used`, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should not be allowed to -be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - "bound_subscription_ids": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of subscription ids that login -is restricted to.`, - }, - "bound_resource_groups": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of resource groups that login -is restricted to.`, - }, - "bound_group_ids": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of group ids that login -is restricted to.`, - }, - "bound_service_principal_ids": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of service principal ids that login -is restricted to.`, - }, - "bound_locations": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of locations that login -is restricted to.`, - }, - "bound_scale_sets": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of scale sets that login -is restricted to.`, - }, - }, - ExistenceCheck: b.pathRoleExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathRoleCreateUpdate, - logical.UpdateOperation: b.pathRoleCreateUpdate, - logical.ReadOperation: b.pathRoleRead, - logical.DeleteOperation: b.pathRoleDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role"][1]), - }, - } -} - -type azureRole struct { - // Policies that are to be required by the token to access this role - Policies []string `json:"policies"` - - // TokenNumUses defines the number of allowed uses of the token issued - NumUses int `json:"num_uses"` - - // Duration before which an issued token must be renewed - TTL time.Duration `json:"ttl"` - - // Duration after which an issued token should not be allowed to be renewed - MaxTTL time.Duration `json:"max_ttl"` - - // Period, if set, indicates that the token generated using this role - // should never expire. The token should be renewed within the duration - // specified by this value. The renewal duration will be fixed if the - // value is not modified on the role. If the `Period` in the role is modified, - // a token will pick up the new value during its next renewal. - Period time.Duration `json:"period"` - - // Role binding properties - BoundServicePrincipalIDs []string `json:"bound_service_principal_ids"` - BoundGroupIDs []string `json:"bound_group_ids"` - BoundResourceGroups []string `json:"bound_resource_groups"` - BoundSubscriptionsIDs []string `json:"bound_subscription_ids"` - BoundLocations []string `json:"bound_locations"` - BoundScaleSets []string `json:"bound_scale_sets"` -} - -// role takes a storage backend and the name and returns the role's storage -// entryÍ -func (b *azureAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*azureRole, error) { - raw, err := s.Get(ctx, "role/"+strings.ToLower(name)) - if err != nil { - return nil, err - } - if raw == nil { - return nil, nil - } - - role := new(azureRole) - if err := json.Unmarshal(raw.Value, role); err != nil { - return nil, err - } - - return role, nil -} - -// pathRoleExistenceCheck returns whether the role with the given name exists or not. -func (b *azureAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - role, err := b.role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - return role != nil, nil -} - -// pathRoleList is used to list all the Roles registered with the backend. -func (b *azureAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil -} - -// pathRoleRead grabs a read lock and reads the options set on the role from the storage -func (b *azureAuthBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing name"), nil - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Convert the 'time.Duration' values to second. - role.TTL /= time.Second - role.MaxTTL /= time.Second - role.Period /= time.Second - - // Create a map of data to be returned - resp := &logical.Response{ - Data: map[string]interface{}{ - "max_ttl": role.MaxTTL, - "num_uses": role.NumUses, - "policies": role.Policies, - "period": role.Period, - "ttl": role.TTL, - "bound_service_principal_ids": role.BoundServicePrincipalIDs, - "bound_group_ids": role.BoundGroupIDs, - "bound_subscription_ids": role.BoundSubscriptionsIDs, - "bound_resource_groups": role.BoundResourceGroups, - "bound_locations": role.BoundLocations, - "bound_scale_sets": role.BoundScaleSets, - }, - } - - return resp, nil -} - -// pathRoleDelete removes the role from storage -func (b *azureAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("role name required"), nil - } - - // Delete the role itself - if err := req.Storage.Delete(ctx, "role/"+strings.ToLower(roleName)); err != nil { - return nil, err - } - - return nil, nil -} - -// pathRoleCreateUpdate registers a new role with the backend or updates the options -// of an existing role -func (b *azureAuthBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - // Check if the role already exists - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - // Create a new entry object if this is a CreateOperation - if role == nil { - if req.Operation == logical.UpdateOperation { - return nil, errors.New("role entry not found during update operation") - } - role = new(azureRole) - } - - if policiesRaw, ok := data.GetOk("policies"); ok { - role.Policies = policyutil.ParsePolicies(policiesRaw) - } - - periodRaw, ok := data.GetOk("period") - if ok { - role.Period = time.Duration(periodRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.Period = time.Duration(data.Get("period").(int)) * time.Second - } - if role.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("'period' of '%q' is greater than the backend's maximum lease TTL of '%q'", role.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - - if tokenNumUsesRaw, ok := data.GetOk("num_uses"); ok { - role.NumUses = tokenNumUsesRaw.(int) - } else if req.Operation == logical.CreateOperation { - role.NumUses = data.Get("num_uses").(int) - } - if role.NumUses < 0 { - return logical.ErrorResponse("num_uses cannot be negative"), nil - } - - if tokenTTLRaw, ok := data.GetOk("ttl"); ok { - role.TTL = time.Duration(tokenTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.TTL = time.Duration(data.Get("ttl").(int)) * time.Second - } - - if tokenMaxTTLRaw, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(tokenMaxTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second - } - - if boundServicePrincipalIDs, ok := data.GetOk("bound_service_principal_ids"); ok { - role.BoundServicePrincipalIDs = boundServicePrincipalIDs.([]string) - } - - if boundGroupIDs, ok := data.GetOk("bound_group_ids"); ok { - role.BoundGroupIDs = boundGroupIDs.([]string) - } - - if boundSubscriptionsIDs, ok := data.GetOk("bound_subscription_ids"); ok { - role.BoundSubscriptionsIDs = boundSubscriptionsIDs.([]string) - } - - if boundResourceGroups, ok := data.GetOk("bound_resource_groups"); ok { - role.BoundResourceGroups = boundResourceGroups.([]string) - } - - if boundLocations, ok := data.GetOk("bound_locations"); ok { - role.BoundLocations = boundLocations.([]string) - } - - if boundScaleSets, ok := data.GetOk("bound_scale_sets"); ok { - role.BoundScaleSets = boundScaleSets.([]string) - } - - if len(role.BoundServicePrincipalIDs) == 0 && - len(role.BoundGroupIDs) == 0 && - len(role.BoundSubscriptionsIDs) == 0 && - len(role.BoundResourceGroups) == 0 && - len(role.BoundLocations) == 0 && - len(role.BoundScaleSets) == 0 { - return logical.ErrorResponse("must have at least one bound constraint when creating/updating a role"), nil - } - - // Check that the TTL value provided is less than the MaxTTL. - // Sanitizing the TTL and MaxTTL is not required now and can be performed - // at credential issue time. - if role.MaxTTL > 0 && role.TTL > role.MaxTTL { - return logical.ErrorResponse("ttl should not be greater than max_ttl"), nil - } - - var resp *logical.Response - if role.MaxTTL > b.System().MaxLeaseTTL() { - resp = &logical.Response{} - resp.AddWarning("max_ttl is greater than the system or backend mount's maximum TTL value; issued tokens' max TTL value will be truncated") - } - - // Store the entry. - entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), role) - if err != nil { - return nil, err - } - if entry == nil { - return nil, fmt.Errorf("failed to create storage entry for role %s", roleName) - } - if err = req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return resp, nil -} - -// roleStorageEntry stores all the options that are set on an role -var roleHelp = map[string][2]string{ - "role-list": { - "Lists all the roles registered with the backend.", - "The list will contain the names of the roles.", - }, - "role": { - "Register an role with the backend.", - `A role is required to authenticate with this backend. The role binds - Azure instance metadata with token policies and settings. - The bindings, token polices and token settings can all be configured - using this endpoint`, - }, -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-azure/util.go b/vendor/github.com/hashicorp/vault-plugin-auth-azure/util.go deleted file mode 100644 index 6dffdea3e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-azure/util.go +++ /dev/null @@ -1,57 +0,0 @@ -package azureauth - -import ( - "encoding/json" - "fmt" - "os" - "runtime" - "strings" - "time" - - "github.com/hashicorp/vault/helper/pluginutil" -) - -// Using the same time parsing logic from https://github.com/coreos/go-oidc -// This code is licensed under the Apache 2.0 license -type jsonTime time.Time - -func (j *jsonTime) UnmarshalJSON(b []byte) error { - var n json.Number - if err := json.Unmarshal(b, &n); err != nil { - return err - } - var unix int64 - - if t, err := n.Int64(); err == nil { - unix = t - } else { - f, err := n.Float64() - if err != nil { - return err - } - unix = int64(f) - } - *j = jsonTime(time.Unix(unix, 0)) - return nil -} - -// strListContains does a case-insensitive search of the string -// list for the value -func strListContains(haystack []string, needle string) bool { - for _, item := range haystack { - if strings.ToLower(item) == strings.ToLower(needle) { - return true - } - } - return false -} - -// userAgent determines the User Agent to send on HTTP requests. This is mostly copied -// from the useragent helper in vault and may get replaced with something more general -// for plugins -func userAgent() string { - version := os.Getenv(pluginutil.PluginVaultVersionEnv) - projectURL := "https://www.vaultproject.io/" - rt := runtime.Version() - return fmt.Sprintf("Vault/%s (+%s; %s)", version, projectURL, rt) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.lock deleted file mode 100644 index bcb25e301..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.lock +++ /dev/null @@ -1,385 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:a69ab3f1445ffd4815add4bd31ba05b65b3b9fec1ade5057d5d717f30e6efd6d" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - branch = "master" - digest = "1:2d63efae50509ea393d464e0623f7bb2a75e5d23004228c12c7a564181fd2882" - name = "github.com/centrify/cloud-golang-sdk" - packages = [ - "oauth", - "restapi", - ] - pruneopts = "UT" - revision = "7c97cc6fde16c41f82cace5cbba3e5f098065b9c" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:da3b11dddb283e412ccc5275fece4eeb6eb6b607e8c0120e7109859b3d5b530c" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/password", - "helper/pathmanager", - "helper/pluginutil", - "helper/policyutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "8655d167084028d627f687ddc25d0c71307eb5be" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - digest = "1:3f3a05ae0b95893d90b9b3b5afdb79a9b3d96e4e36e099d841ae602e4aca0da8" - name = "golang.org/x/crypto" - packages = ["ssh/terminal"] - pruneopts = "UT" - revision = "de0752318171da717af4ce24d0a2e8626afaeb11" - -[[projects]] - branch = "master" - digest = "1:b5c3834d33445efdc5a8dcb154bed9e4c211edadbf02f6f5cc20c5e9be26a499" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:2f71657f09ff05e4567909e9e0de7ad799828c96d402c540b41dc044a6590fb2" - name = "golang.org/x/sys" - packages = [ - "unix", - "windows", - ] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/centrify/cloud-golang-sdk/oauth", - "github.com/centrify/cloud-golang-sdk/restapi", - "github.com/hashicorp/go-cleanhttp", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/vault/api", - "github.com/hashicorp/vault/helper/password", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/helper/policyutil", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.toml deleted file mode 100644 index 0070cd8d0..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Gopkg.toml +++ /dev/null @@ -1,46 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - branch = "master" - name = "github.com/centrify/cloud-golang-sdk" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Makefile b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Makefile deleted file mode 100644 index 9559e069a..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -TOOL?=vault-plugin-auth-centrify -TEST?=$$(go list ./... | grep -v /vendor/) -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox \ - github.com/golang/dep/cmd/dep -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin, except for quickdev which -# is only put into /bin/ -quickdev: generate - @CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/vault-plugin-auth-kubernetes -dev: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" -dev-dynamic: generate - @CGO_ENABLED=1 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -# test runs the unit tests and vets the code -test: fmtcheck generate - CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -timeout=20m -parallel=4 - -testcompile: fmtcheck generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# testacc runs acceptance tests -testacc: fmtcheck generate - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 45m - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - gofmt -w $(GOFMT_FILES) - - -.PHONY: bin default generate test vet bootstrap fmt fmtcheck diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/README.md b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/README.md deleted file mode 100644 index 748019582..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/README.md +++ /dev/null @@ -1,165 +0,0 @@ -# Vault Plugin: Centrify Identity Platform Auth Backend - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin allows for Centrify Identity Platform users accounts to authenticate with Vault. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - Main Project Github: https://www.github.com/hashicorp/vault - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Security Model - -The current authentication model requires providing Vault with an OAuth2 Client ID and Secret, which can be used to make authenticated calls to the Centrify Identity Platform API. This token is scoped to allow only the required APIs for Vault integration, and cannot be used for interactive login directly. - -## Usage - -This plugin is currently built into Vault and by default is accessed -at `auth/centrify`. To enable this in a running Vault server: - -```sh -$ vault auth-enable centrify -Successfully enabled 'centrify' at 'centrify'! -``` - -Before the plugin can authenticate users, both the plugin and your cloud service tenant must be configured correctly. To configure your cloud tenant, sign in as an administrator and perform the following actions. Please note that this plugin requires the Centrify Cloud Identity Service version 17.11 or newer. - -### Create an OAuth2 Confidential Client - -An OAuth2 Confidentical Client is a Centrify Directory User. - -- Users -> Add User - - Login Name: vault_integration@ - - Display Name: Vault Integration Confidential Client - - Check the "Is OAuth confidentical client" box - - Password Type: Generated (be sure to copy the value, you will need it later) - - Create User - -### Create a Role - -To scope the users who can authenticate to vault, and to allow our Confidential Client access, we will create a role. - -- Roles -> Add Role - - Name: Vault Integration - - Members -> Add - - Search for and add the vault_integration@ user - - Additionally add any roles/groups/users who should be able to authenticate to vault - - Save - -### Create an OAuth2 Client Application -- Apps -> Add Web Apps -> Custom -> OAuth2 Client -- Configure the added application - - Description: - - Application ID: "vault_io_integration" - - Application Name: "Vault Integration" - - General Usage: - - Client ID Type -> Confidential (must be OAuth client) - - Tokens: - - Token Type: JwtRS256 - - Auth methods: Client Creds + Resource Owner - - Scope - - Add a single scope named "vault_io_integration" with the following regexes: - - usermgmt/getusersrolesandadministrativerights - - security/whoami - - User Access - - Add the previously created "Vault Integration" role - - Save - -### Configuring the Vault Plugin - -As an administrative vault user, you can read/write the centrify plugin configuration using the /auth/centrify/config path: - -```sh -$ vault write auth/centrify/config service_url=https://.my.centrify.com client_id=vault_integration@ client_secret= app_id=vault_io_integration scope=vault_io_integration -``` - -### Authenticating - -As a valid user of your tenant, in the appropriate role for accessing the Vault Integration app, you can now authenticate to the vault: - -```sh -$ vault auth -method=centrify username= -``` - -Your vault token will be valid for the length of time defined in the app's token lifetime configuration (default 5 hours). - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine -(version 1.9+ is *required*). - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-centrify`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/centrify \ - sha_256= \ - command="vault-plugin-auth-centrify" -... -Success! Data written to: sys/plugins/catalog/centrify -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-auth-centrify -... -SHA256(.../go/bin/vault-plugin-auth-centrify)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the Centrify auth plugin: - -```sh -$ vault auth-enable -plugin-name='centrify' plugin -... - -Successfully enabled 'plugin' at 'centrify'! -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/backend.go deleted file mode 100644 index eeb95e6d8..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/backend.go +++ /dev/null @@ -1,52 +0,0 @@ -package centrify - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - SealWrapStorage: []string{ - "config", - }, - }, - - Paths: []*framework.Path{ - pathConfig(&b), - pathLogin(&b), - }, - - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -const backendHelp = ` -The "centrify" credential provider allows authentication using -a combination of a username and password via the Centrify Identity -Services Platform. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/cli.go b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/cli.go deleted file mode 100644 index dd1a11c1f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/cli.go +++ /dev/null @@ -1,66 +0,0 @@ -package centrify - -import ( - "fmt" - "os" - "strings" - - "github.com/hashicorp/vault/api" - pwd "github.com/hashicorp/vault/helper/password" -) - -type CLIHandler struct{} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "centrify" - } - - username, ok := m["username"] - if !ok { - return nil, fmt.Errorf("'username' not supplied") - } - - password, ok := m["password"] - if !ok { - fmt.Printf("Password (will be hidden): ") - var err error - password, err = pwd.Read(os.Stdin) - fmt.Println() - if err != nil { - return nil, err - } - } - - data := map[string]interface{}{ - "username": username, - "password": password, - } - - mode, ok := m["mode"] - if ok { - data["mode"] = mode - } - - path := fmt.Sprintf("auth/%s/login", mount) - secret, err := c.Logical().Write(path, data) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -The "centrify" credential provider allows you to authenticate with -a username and password. To use it, specify the "username" and "password" -parameters. If password is not provided on the command line, it will be -read from stdin.` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_config.go b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_config.go deleted file mode 100644 index 4094ceedf..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_config.go +++ /dev/null @@ -1,208 +0,0 @@ -package centrify - -import ( - "context" - "fmt" - "net/url" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "client_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "OAuth2 Client ID", - }, - "client_secret": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "OAuth2 Client Secret", - }, - "service_url": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Service URL (https://.my.centrify.com)", - }, - "app_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "OAuth2 App ID", - Default: "vault_io_integration", - }, - "scope": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "OAuth2 App Scope", - Default: "vault_io_integration", - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies all authenticated users inherit", - }, - }, - - ExistenceCheck: b.pathConfigExistCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigCreateOrUpdate, - logical.CreateOperation: b.pathConfigCreateOrUpdate, - logical.ReadOperation: b.pathConfigRead, - }, - - HelpSynopsis: pathSyn, - } -} - -func (b *backend) pathConfigExistCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - config, err := b.Config(ctx, req.Storage) - if err != nil { - return false, err - } - - if config == nil { - return false, nil - } - - return true, nil -} - -func (b *backend) pathConfigCreateOrUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if cfg == nil { - cfg = &config{} - } - - val, ok := data.GetOk("client_id") - if ok { - cfg.ClientID = val.(string) - } else if req.Operation == logical.CreateOperation { - cfg.ClientID = data.Get("client_id").(string) - } - if cfg.ClientID == "" { - return logical.ErrorResponse("config parameter `client_id` cannot be empty"), nil - } - - val, ok = data.GetOk("client_secret") - if ok { - cfg.ClientSecret = val.(string) - } else if req.Operation == logical.CreateOperation { - cfg.ClientSecret = data.Get("client_secret").(string) - } - if cfg.ClientSecret == "" { - return logical.ErrorResponse("config parameter `client_secret` cannot be empty"), nil - } - - val, ok = data.GetOk("service_url") - if ok { - cfg.ServiceURL = val.(string) - } else if req.Operation == logical.CreateOperation { - cfg.ServiceURL = data.Get("service_url").(string) - } - if cfg.ServiceURL == "" { - return logical.ErrorResponse("config parameter `service_url` cannot be empty"), nil - } - - val, ok = data.GetOk("app_id") - if ok { - cfg.AppID = val.(string) - } else if req.Operation == logical.CreateOperation { - cfg.AppID = data.Get("app_id").(string) - } - - val, ok = data.GetOk("scope") - if ok { - cfg.Scope = val.(string) - } else if req.Operation == logical.CreateOperation { - cfg.Scope = data.Get("scope").(string) - } - - val, ok = data.GetOk("policies") - if ok { - cfg.Policies = policyutil.ParsePolicies(val) - } else if req.Operation == logical.CreateOperation { - cfg.Policies = policyutil.ParsePolicies(data.Get("policies")) - } - - // We want to normalize the service url to https:// - url, err := url.Parse(cfg.ServiceURL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("config parameter 'service_url' is not a valid url: %s", err)), nil - } - - // Its a proper url, just force the scheme to https, and strip any paths - url.Scheme = "https" - url.Path = "" - cfg.ServiceURL = url.String() - - entry, err := logical.StorageEntryJSON("config", cfg) - - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if config == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "client_id": config.ClientID, - "service_url": config.ServiceURL, - "app_id": config.AppID, - "scope": config.Scope, - "policies": config.Policies, - }, - } - return resp, nil -} - -// Config returns the configuration for this backend. -func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error) { - entry, err := s.Get(ctx, "config") - - if err != nil { - return nil, err - } - - var result config - if entry != nil { - if err := entry.DecodeJSON(&result); err != nil { - return nil, fmt.Errorf("error reading configuration: %s", err) - } - return &result, nil - } - - return nil, nil -} - -type config struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - ServiceURL string `json:"service_url"` - AppID string `json:"app_id"` - Scope string `json:"scope"` - Policies []string `json:"policies"` -} - -const pathSyn = ` -This path allows you to configure the centrify auth provider to interact with the Centrify Identity Services Platform -for authenticating users. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_login.go deleted file mode 100644 index 2d00ec6da..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-centrify/path_login.go +++ /dev/null @@ -1,201 +0,0 @@ -package centrify - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-cleanhttp" - - "github.com/centrify/cloud-golang-sdk/oauth" - "github.com/centrify/cloud-golang-sdk/restapi" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const sourceHeader string = "vault-plugin-auth-centrify" - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login", - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username of the user.", - }, - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - "mode": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Auth mode ('ro' for resource owner, 'cc' for credential client).", - Default: "ro", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := strings.ToLower(d.Get("username").(string)) - if username == "" { - return nil, fmt.Errorf("missing username") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: username, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := strings.ToLower(d.Get("username").(string)) - password := d.Get("password").(string) - mode := d.Get("mode").(string) - - if password == "" { - return nil, fmt.Errorf("missing password") - } - - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if config == nil { - return nil, errors.New("centrify auth plugin configuration not set") - } - - var token *oauth.TokenResponse - var failure *oauth.ErrorResponse - - switch mode { - case "cc": - oclient, err := oauth.GetNewConfidentialClient(config.ServiceURL, username, password, cleanhttp.DefaultClient) - oclient.SourceHeader = sourceHeader - if err != nil { - return nil, err - } - token, failure, err = oclient.ClientCredentials(config.AppID, config.Scope) - if err != nil { - return nil, err - } - case "ro": - oclient, err := oauth.GetNewConfidentialClient(config.ServiceURL, config.ClientID, config.ClientSecret, cleanhttp.DefaultClient) - oclient.SourceHeader = sourceHeader - if err != nil { - return nil, err - } - token, failure, err = oclient.ResourceOwner(config.AppID, config.Scope, username, password) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("Invalid mode or no mode provided: %s", mode) - } - - if failure != nil { - return nil, fmt.Errorf("OAuth2 token request failed: %v", failure) - } - - uinfo, err := b.getUserInfo(token, config.ServiceURL) - if err != nil { - return nil, err - } - b.Logger().Trace("centrify authenticated user", "userinfo", uinfo) - - resp := &logical.Response{ - Auth: &logical.Auth{ - Policies: config.Policies, - Metadata: map[string]string{ - "username": uinfo.username, - }, - DisplayName: username, - LeaseOptions: logical.LeaseOptions{ - TTL: time.Duration(token.ExpiresIn) * time.Second, - Renewable: false, - }, - Alias: &logical.Alias{ - Name: username, - }, - }, - } - - for _, role := range uinfo.roles { - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: role, - }) - } - - return resp, nil -} - -type userinfo struct { - uuid string - username string - roles []string -} - -// getUserInfo returns list of user's roles, user uuid, user name -func (b *backend) getUserInfo(accessToken *oauth.TokenResponse, serviceUrl string) (*userinfo, error) { - uinfo := &userinfo{} - - restClient, err := restapi.GetNewRestClient(serviceUrl, cleanhttp.DefaultClient) - if err != nil { - return nil, err - } - - restClient.Headers["Authorization"] = accessToken.TokenType + " " + accessToken.AccessToken - restClient.SourceHeader = sourceHeader - - // First call /security/whoami to get details on current user - whoami, err := restClient.CallGenericMapAPI("/security/whoami", nil) - if err != nil { - return nil, err - } - uinfo.username = whoami.Result["User"].(string) - uinfo.uuid = whoami.Result["UserUuid"].(string) - - // Now enumerate roles - rolesAndRightsResult, err := restClient.CallGenericMapAPI("/usermgmt/GetUsersRolesAndAdministrativeRights", nil) - if err != nil { - return nil, err - } - - uinfo.roles = make([]string, 0) - - if rolesAndRightsResult.Success { - // Results is an array of map[string]interface{} - var results = rolesAndRightsResult.Result["Results"].([]interface{}) - for _, v := range results { - var resultItem = v.(map[string]interface{}) - var row = resultItem["Row"].(map[string]interface{}) - uinfo.roles = append(uinfo.roles, row["Name"].(string)) - } - } else { - b.Logger().Error("centrify: failed to get user roles", "error", rolesAndRightsResult.Message) - } - - return uinfo, nil -} - -const pathLoginSyn = ` -Log in with a username and password. -` - -const pathLoginDesc = ` -This endpoint authenticates using a username and password against the Centrify Identity Services Platform. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/LICENSE deleted file mode 100644 index ea67120c5..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/LICENSE +++ /dev/null @@ -1,364 +0,0 @@ - -zilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_gcp.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_gcp.go deleted file mode 100644 index 8f10bed78..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_gcp.go +++ /dev/null @@ -1,78 +0,0 @@ -package gcpauth - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/helper/strutil" - "google.golang.org/api/compute/v1" - "google.golang.org/api/iam/v1" -) - -var _ client = (*gcpClient)(nil) - -// gcpClient implements client and communicates with the GCP API. It is -// abstracted as an interface for stubbing during testing. See stubbedClient for -// more details. -type gcpClient struct { - computeSvc *compute.Service - iamSvc *iam.Service -} - -func (c *gcpClient) InstanceGroups(ctx context.Context, project string, boundInstanceGroups []string) (map[string][]string, error) { - // map of zone names to a slice of instance group names in that zone. - igz := make(map[string][]string) - - if err := c.computeSvc.InstanceGroups. - AggregatedList(project). - Fields("items/*/instanceGroups/name"). - Pages(ctx, func(l *compute.InstanceGroupAggregatedList) error { - for k, v := range l.Items { - zone, err := zoneFromSelfLink(k) - if err != nil { - return err - } - - for _, g := range v.InstanceGroups { - if strutil.StrListContains(boundInstanceGroups, g.Name) { - igz[zone] = append(igz[zone], g.Name) - } - } - } - return nil - }); err != nil { - return nil, err - } - - return igz, nil -} - -func (c *gcpClient) InstanceGroupContainsInstance(ctx context.Context, project, zone, group, instanceSelfLink string) (bool, error) { - var req compute.InstanceGroupsListInstancesRequest - resp, err := c.computeSvc.InstanceGroups. - ListInstances(project, zone, group, &req). - Filter(fmt.Sprintf("instance eq %s", instanceSelfLink)). - Context(ctx). - Do() - if err != nil { - return false, err - } - - if resp != nil && len(resp.Items) > 0 { - return true, nil - } - return false, nil -} - -func (c *gcpClient) ServiceAccount(ctx context.Context, name string) (string, string, error) { - account, err := c.iamSvc.Projects.ServiceAccounts. - Get(name). - Fields("uniqueId", "email"). - Context(ctx). - Do() - if err != nil { - return "", "", err - } - - return account.UniqueId, account.Email, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_stubbed.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_stubbed.go deleted file mode 100644 index 8b0a69f46..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_client_stubbed.go +++ /dev/null @@ -1,25 +0,0 @@ -package gcpauth - -import "context" - -var _ client = (*stubbedClient)(nil) - -// stubbedClient is a simple client to use for testing where the API calls to -// GCP are "stubbed" instead of hitting the actual API. -type stubbedClient struct { - instanceGroupsByZone map[string][]string - instanceGroupContainsInstance bool - saId, saEmail string -} - -func (c *stubbedClient) InstanceGroups(_ context.Context, _ string, _ []string) (map[string][]string, error) { - return c.instanceGroupsByZone, nil -} - -func (c *stubbedClient) InstanceGroupContainsInstance(_ context.Context, _, _, _, _ string) (bool, error) { - return c.instanceGroupContainsInstance, nil -} - -func (c *stubbedClient) ServiceAccount(_ context.Context, _ string) (string, string, error) { - return c.saId, c.saEmail, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_gce.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_gce.go deleted file mode 100644 index d9346a9bb..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/authorizer_gce.go +++ /dev/null @@ -1,159 +0,0 @@ -package gcpauth - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/strutil" -) - -type client interface { - InstanceGroups(context.Context, string, []string) (map[string][]string, error) - InstanceGroupContainsInstance(context.Context, string, string, string, string) (bool, error) - ServiceAccount(context.Context, string) (string, string, error) -} - -type AuthorizeGCEInput struct { - client client - - project string - serviceAccount string - - instanceLabels map[string]string - instanceSelfLink string - instanceZone string - - boundLabels map[string]string - boundRegions []string - boundZones []string - - boundInstanceGroups []string - boundServiceAccounts []string -} - -func AuthorizeGCE(ctx context.Context, i *AuthorizeGCEInput) error { - // Verify instance has role labels if labels were set on role. - for k, v := range i.boundLabels { - if act, ok := i.instanceLabels[k]; !ok || act != v { - return fmt.Errorf("instance missing bound label \"%s:%s\"", k, v) - } - } - - // Parse the zone name from the self-link URI if given. - zone, err := zoneFromSelfLink(i.instanceZone) - if err != nil { - return err - } - - // Convert the zone to a region name. - region, err := zoneToRegion(zone) - if err != nil { - return err - } - - // Verify the instance is in the zone/region - switch { - case len(i.boundZones) > 0: - if !strutil.StrListContains(i.boundZones, zone) { - return fmt.Errorf("instance not in bound zones %q", i.boundZones) - } - case len(i.boundRegions) > 0: - if !strutil.StrListContains(i.boundRegions, region) { - return fmt.Errorf("instance not in bound regions %q", i.boundRegions) - } - } - - // For each bound instance group, verify the group exists and that the - // instance is a member of that group. - if len(i.boundInstanceGroups) > 0 { - igz, err := i.client.InstanceGroups(ctx, i.project, i.boundInstanceGroups) - if err != nil { - return fmt.Errorf("failed to list instance groups for project %q: %s", i.project, err) - } - - // Keep track of whether we've successfully found an instance group of - // which this instance is a member, which meets the zonal/regional criteria. - found := false - - for _, g := range i.boundInstanceGroups { - if found { - break - } - - var group, zone string - - switch { - case len(i.boundZones) > 0: - for _, z := range i.boundZones { - if groups, ok := igz[z]; ok && len(groups) > 0 { - for _, grp := range groups { - if grp == g { - group = g - zone = z - } - } - } - } - if group == "" { - return fmt.Errorf("instance group %q does not exist in zones %q for project %q", - g, i.boundZones, i.project) - } - case len(i.boundRegions) > 0: - for _, r := range i.boundRegions { - for z, groups := range igz { - if strings.HasPrefix(z, r) { // zone is prefixed with region - for _, grp := range groups { - if grp == g { - group = g - zone = z - } - } - } - } - } - if group == "" { - return fmt.Errorf("instance group %q does not exist in regions %q for project %q", - g, i.boundRegions, i.project) - } - default: - return fmt.Errorf("instance group %q is not bound to any zones or regions", g) - } - - ok, err := i.client.InstanceGroupContainsInstance(ctx, i.project, zone, group, i.instanceSelfLink) - if err != nil { - return fmt.Errorf("failed to list instances in instance group %q for project %q: %s", - group, i.project, err) - } - - if ok { - found = true - } - } - - if !found { - return fmt.Errorf("instance is not part of instance groups %q", - i.boundInstanceGroups) - } - } - - // Verify instance is running under one of the allowed service accounts. - if len(i.boundServiceAccounts) > 0 { - // ServiceAccount wraps a call to the GCP IAM API to get a service account. - name := fmt.Sprintf("projects/%s/serviceAccounts/%s", i.project, i.serviceAccount) - - saId, saEmail, err := i.client.ServiceAccount(ctx, name) - if err != nil { - return fmt.Errorf("could not find service account %q in project %q: %s", - i.serviceAccount, i.project, err) - } - - if !(strutil.StrListContains(i.boundServiceAccounts, saEmail) || - strutil.StrListContains(i.boundServiceAccounts, saId)) { - return fmt.Errorf("service account %q (%q) is not in bound service accounts %q", - saId, saEmail, i.boundServiceAccounts) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/backend.go deleted file mode 100644 index 037779551..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/backend.go +++ /dev/null @@ -1,190 +0,0 @@ -package gcpauth - -import ( - "context" - "fmt" - "net/http" - "runtime" - "sync" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/hashicorp/vault/version" - "golang.org/x/oauth2" - "google.golang.org/api/compute/v1" - "google.golang.org/api/iam/v1" -) - -type GcpAuthBackend struct { - *framework.Backend - - // OAuth scopes for generating HTTP and GCP service clients. - oauthScopes []string - - // Locks for guarding service clients - clientMutex sync.RWMutex - - // -- GCP service clients -- - iamClient *iam.Service - gceClient *compute.Service -} - -// Factory returns a new backend as logical.Backend. -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *GcpAuthBackend { - b := &GcpAuthBackend{ - oauthScopes: []string{ - iam.CloudPlatformScope, - compute.ComputeReadonlyScope, - }, - } - - b.Backend = &framework.Backend{ - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - Invalidate: b.invalidate, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - SealWrapStorage: []string{ - "config", - }, - }, - Paths: framework.PathAppend( - []*framework.Path{ - pathConfig(b), - pathLogin(b), - }, - pathsRole(b), - ), - } - return b -} - -func (b *GcpAuthBackend) invalidate(_ context.Context, key string) { - switch key { - case "config": - b.Close() - } -} - -// Close deletes created GCP clients in backend. -func (b *GcpAuthBackend) Close() { - b.clientMutex.Lock() - defer b.clientMutex.Unlock() - - b.iamClient = nil - b.gceClient = nil -} - -func (b *GcpAuthBackend) IAM(ctx context.Context, s logical.Storage) (*iam.Service, error) { - b.clientMutex.RLock() - if b.iamClient != nil { - defer b.clientMutex.RUnlock() - return b.iamClient, nil - } - - b.clientMutex.RUnlock() - b.clientMutex.Lock() - defer b.clientMutex.Unlock() - - // Check if client was created during lock switch. - if b.iamClient == nil { - err := b.initClients(ctx, s) - if err != nil { - return nil, err - } - } - - return b.iamClient, nil -} - -func (b *GcpAuthBackend) GCE(ctx context.Context, s logical.Storage) (*compute.Service, error) { - b.clientMutex.RLock() - if b.gceClient != nil { - defer b.clientMutex.RUnlock() - return b.gceClient, nil - } - - b.clientMutex.RUnlock() - b.clientMutex.Lock() - defer b.clientMutex.Unlock() - - // Check if client was created during lock switch. - if b.gceClient == nil { - err := b.initClients(ctx, s) - if err != nil { - return nil, err - } - } - - return b.gceClient, nil -} - -// Initialize attempts to create GCP clients from stored config. -// It does not attempt to claim the client lock. -func (b *GcpAuthBackend) initClients(ctx context.Context, s logical.Storage) (err error) { - config, err := b.config(ctx, s) - if err != nil { - return err - } - - var httpClient *http.Client - if config == nil || config.Credentials == nil { - _, tknSrc, err := gcputil.FindCredentials("", ctx, b.oauthScopes...) - if err != nil { - return fmt.Errorf("credentials were not configured and fallback to application default credentials failed: %v", err) - } - cleanCtx := context.WithValue(context.Background(), oauth2.HTTPClient, cleanhttp.DefaultClient()) - httpClient = oauth2.NewClient(cleanCtx, tknSrc) - } else { - httpClient, err = gcputil.GetHttpClient(config.Credentials, b.oauthScopes...) - if err != nil { - return err - } - } - - userAgentStr := fmt.Sprintf("(%s %s) Vault/%s", runtime.GOOS, runtime.GOARCH, version.GetVersion().FullVersionNumber(true)) - - b.iamClient, err = iam.New(httpClient) - if err != nil { - b.Close() - return err - } - b.iamClient.UserAgent = userAgentStr - - b.gceClient, err = compute.New(httpClient) - if err != nil { - b.Close() - return err - } - b.gceClient.UserAgent = userAgentStr - - return nil -} - -const backendHelp = ` -The GCP backend plugin allows authentication for Google Cloud Platform entities. -Currently, it supports authentication for: - -* IAM Service Accounts: - IAM service accounts provide a signed JSON Web Token (JWT), signed by - calling GCP APIs directly or via the Vault CL helper. - -* GCE VM Instances: - GCE provide a signed instance metadata JSON Web Token (JWT), obtained from the - GCE instance metadata server (http://metadata.google.internal/computeMetadata/v1/instance). - Using the /service-accounts//identity endpoint, the instance - can obtain this JWT and pass it to Vault on login. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/cli.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/cli.go deleted file mode 100644 index fb3b71f2e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/cli.go +++ /dev/null @@ -1,171 +0,0 @@ -package gcpauth - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/parseutil" - "golang.org/x/oauth2" - "google.golang.org/api/iam/v1" - "strings" - "time" -) - -type CLIHandler struct{} - -func getSignedJwt(role string, m map[string]string) (string, error) { - ctx := context.WithValue(context.Background(), oauth2.HTTPClient, cleanhttp.DefaultClient()) - - credentials, tokenSource, err := gcputil.FindCredentials(m["credentials"], ctx, iam.CloudPlatformScope) - if err != nil { - return "", fmt.Errorf("could not obtain credentials: %v", err) - } - - httpClient := oauth2.NewClient(ctx, tokenSource) - - serviceAccount, ok := m["service_account"] - if !ok && credentials != nil { - serviceAccount = credentials.ClientEmail - } - if serviceAccount == "" { - return "", errors.New("could not obtain service account from credentials (are you using Application Default Credentials?). You must provide a service account to authenticate as") - } - - project, ok := m["project"] - if !ok { - if credentials != nil { - project = credentials.ProjectId - } else { - project = "-" - } - } - - var ttl = time.Duration(defaultIamMaxJwtExpMinutes) * time.Minute - jwtExpStr, ok := m["jwt_exp"] - if ok { - ttl, err = parseutil.ParseDurationSecond(jwtExpStr) - if err != nil { - return "", fmt.Errorf("could not parse jwt_exp '%s' into integer value", jwtExpStr) - } - } - - jwtPayload := map[string]interface{}{ - "aud": fmt.Sprintf("http://vault/%s", role), - "sub": serviceAccount, - "exp": time.Now().Add(ttl).Unix(), - } - payloadBytes, err := json.Marshal(jwtPayload) - if err != nil { - return "", fmt.Errorf("could not convert JWT payload to JSON string: %v", err) - } - - jwtReq := &iam.SignJwtRequest{ - Payload: string(payloadBytes), - } - - iamClient, err := iam.New(httpClient) - if err != nil { - return "", fmt.Errorf("could not create IAM client: %v", err) - } - - resourceName := fmt.Sprintf("projects/%s/serviceAccounts/%s", project, serviceAccount) - resp, err := iamClient.Projects.ServiceAccounts.SignJwt(resourceName, jwtReq).Do() - if err != nil { - return "", fmt.Errorf("unable to sign JWT for %s using given Vault credentials: %v", resourceName, err) - } - - return resp.SignedJwt, nil -} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - role, ok := m["role"] - if !ok { - return nil, errors.New("role is required") - } - - mount, ok := m["mount"] - if !ok { - mount = "gcp" - } - - loginToken, err := getSignedJwt(role, m) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("auth/%s/login", mount) - secret, err := c.Logical().Write( - path, - map[string]interface{}{ - "role": role, - "jwt": loginToken, - }) - - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=gcp [CONFIG K=V...] - -The GCP credential provider allows you to authenticate with -a GCP IAM service account key. To use it, you provide a valid GCP IAM -credential JSON either explicitly on the command line (not recommended), -or through any GCP Application Default Credentials. - -Authenticate using Application Default Credentials: - - Example: vault login -method=gcp role=my-iam-role - -Authenticate using explicitly passed-in credentials: - - Example: - vault login -method=gcp role=my-iam-role -credentials=@path/to/creds role=my-iam-role - -This tool generates a signed JWT signed using the given credentials. - -Configuration: - - role - Required. The name of the role you're requesting a token for. - - mount=gcp - This is usually provided via the -path flag in the "vault login" command, - but it can be specified here as well. If specified here, it takes - precedence over the value for -path. - - credentials= - Explicitly specified GCP credentials in JSON string format (not recommended) - - jwt_exp= - Time until the generated JWT expires in minutes. - The given IAM role will have a max_jwt_exp field, the - time in minutes that all valid authentication JWTs - must expire within (from time of authentication). - Defaults to 15 minutes, the default max_jwt_exp for a role. - Must be less than an hour. - - service_account= - Service account to generate a JWT for. Defaults to credentials - "client_email" if "credentials" specified and this value is not. - The actual credential must have the "iam.serviceAccounts.signJWT" - permissions on this service account. - - project= - Project the service account belongs to. Defaults to credentials - "project_id" if "credentials" specified and this value is not. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/helpers.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/helpers.go deleted file mode 100644 index 69b3e8d9c..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/helpers.go +++ /dev/null @@ -1,67 +0,0 @@ -package gcpauth - -import ( - "fmt" - "sort" - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// validateFields verifies that no bad arguments were given to the request. -func validateFields(req *logical.Request, data *framework.FieldData) error { - var unknownFields []string - for k := range req.Data { - if _, ok := data.Schema[k]; !ok { - unknownFields = append(unknownFields, k) - } - } - - if len(unknownFields) > 0 { - // Sort since this is a human error - sort.Strings(unknownFields) - - return fmt.Errorf("unknown fields: %q", unknownFields) - } - - return nil -} - -// zoneToRegion converts a zone name to its corresponding region. From -// https://cloud.google.com/compute/docs/regions-zones/, the FQDN of a zone is -// always -. Instead of doing an API call, this function uses -// string parsing as an opimization. -// -// If the zone is a self-link, it is converted into a human name first. If the -// zone cannot be converted to a region, an error is returned. -func zoneToRegion(zone string) (string, error) { - zone, err := zoneFromSelfLink(zone) - if err != nil { - return "", err - } - - if i := strings.LastIndex(zone, "-"); i > -1 { - return zone[0:i], nil - } - return "", fmt.Errorf("failed to extract region from zone name %q", zone) -} - -// zoneFromSelfLink converts a zone self-link into the human zone name. -func zoneFromSelfLink(zone string) (string, error) { - prefix := "zones/" - - if zone == "" { - return "", fmt.Errorf("failed to extract zone from self-link %q", zone) - } - - if strings.Contains(zone, "/") { - if i := strings.LastIndex(zone, prefix); i > -1 { - zone = zone[i+len(prefix) : len(zone)] - } else { - return "", fmt.Errorf("failed to extract zone from self-link %q", zone) - } - } - - return zone, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/login_util.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/login_util.go deleted file mode 100644 index 5d6c85453..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/login_util.go +++ /dev/null @@ -1,27 +0,0 @@ -package gcpauth - -import ( - "encoding/json" - "fmt" - "github.com/hashicorp/go-gcp-common/gcputil" - "google.golang.org/api/iam/v1" - "time" -) - -func ServiceAccountLoginJwt( - iamClient *iam.Service, exp time.Time, aud, project, serviceAccount string) (*iam.SignJwtResponse, error) { - accountResource := fmt.Sprintf(gcputil.ServiceAccountTemplate, project, serviceAccount) - - payload, err := json.Marshal(map[string]interface{}{ - "sub": serviceAccount, - "aud": aud, - "exp": exp.Unix(), - }) - if err != nil { - return nil, err - } - jwtReq := &iam.SignJwtRequest{ - Payload: string(payload), - } - return iamClient.Projects.ServiceAccounts.SignJwt(accountResource, jwtReq).Do() -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_config.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_config.go deleted file mode 100644 index 00aa415f2..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_config.go +++ /dev/null @@ -1,161 +0,0 @@ -package gcpauth - -import ( - "context" - "errors" - "fmt" - - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *GcpAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "credentials": { - Type: framework.TypeString, - Description: ` -Google credentials JSON that Vault will use to verify users against GCP APIs. -If not specified, will use application default credentials`, - }, - "google_certs_endpoint": { - Type: framework.TypeString, - Description: ` -Base endpoint url that Vault will use to get Google certificates. -If not specified, will use the OAuth2 library default. Useful for testing.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.UpdateOperation: b.pathConfigWrite, - }, - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -func (b *GcpAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Validate we didn't get extraneous fields - if err := validateFields(req, data); err != nil { - return nil, logical.CodedError(422, err.Error()) - } - - config, err := b.config(ctx, req.Storage) - - if err != nil { - return nil, err - } - if config == nil { - config = &gcpConfig{} - } - - if err := config.Update(data); err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not update config: %v", err)), nil - } - - entry, err := logical.StorageEntryJSON("config", config) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Invalidate exisitng clients so they read the new configuration - b.Close() - - return nil, nil -} - -func (b *GcpAuthBackend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - resp := make(map[string]interface{}) - - if v := config.Credentials.ClientEmail; v != "" { - resp["client_email"] = v - } - if v := config.Credentials.ClientId; v != "" { - resp["client_id"] = v - } - if v := config.Credentials.PrivateKeyId; v != "" { - resp["private_key_id"] = v - } - if v := config.Credentials.ProjectId; v != "" { - resp["project_id"] = v - } - if v := config.GoogleCertsEndpoint; v != "" { - resp["google_certs_endpoint"] = v - } - - return &logical.Response{ - Data: resp, - }, nil -} - -const confHelpSyn = `Configure credentials used to query the GCP IAM API to verify authenticating service accounts` -const confHelpDesc = ` -The GCP IAM auth backend makes queries to the GCP IAM auth backend to verify a service account -attempting login. It verifies the service account exists and retrieves a public key to verify -signed JWT requests passed in on login. The credentials should have the following permissions: - -iam AUTH: -* iam.serviceAccountKeys.get -` - -// gcpConfig contains all config required for the GCP backend. -type gcpConfig struct { - Credentials *gcputil.GcpCredentials `json:"credentials"` - GoogleCertsEndpoint string `json:"google_certs_endpoint"` -} - -// Update sets gcpConfig values parsed from the FieldData. -func (config *gcpConfig) Update(data *framework.FieldData) error { - credentialsJson := data.Get("credentials").(string) - if credentialsJson != "" { - creds, err := gcputil.Credentials(credentialsJson) - if err != nil { - return fmt.Errorf("error reading google credentials from given JSON: %v", err) - } - if len(creds.PrivateKeyId) == 0 { - return errors.New("google credentials not found from given JSON") - } - config.Credentials = creds - } - - certsEndpoint := data.Get("google_certs_endpoint").(string) - if len(certsEndpoint) > 0 { - config.GoogleCertsEndpoint = certsEndpoint - } - - return nil -} - -// config reads the backend's gcpConfig from storage. -// This assumes the caller has already obtained the backend's config lock. -func (b *GcpAuthBackend) config(ctx context.Context, s logical.Storage) (*gcpConfig, error) { - config := &gcpConfig{} - entry, err := s.Get(ctx, "config") - - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - return config, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_login.go deleted file mode 100644 index 5561dcc3b..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_login.go +++ /dev/null @@ -1,622 +0,0 @@ -package gcpauth - -import ( - "context" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "google.golang.org/api/compute/v1" - "google.golang.org/api/iam/v1" - "gopkg.in/square/go-jose.v2/jwt" -) - -const ( - expectedJwtAudTemplate string = "vault/%s" - - clientErrorTemplate string = "backend not configured properly, could not create %s client: %v" -) - -func pathLogin(b *GcpAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeString, - Description: `Name of the role against which the login is being attempted. Required.`, - }, - "jwt": { - Type: framework.TypeString, - Description: ` -A signed JWT. This is either a self-signed service account JWT ('iam' roles only) or a -GCE identity metadata token ('iam', 'gce' roles).`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLogin, - }, - - HelpSynopsis: pathLoginHelpSyn, - HelpDescription: pathLoginHelpDesc, - } -} - -func (b *GcpAuthBackend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Validate we didn't get extraneous fields - if err := validateFields(req, data); err != nil { - return nil, logical.CodedError(422, err.Error()) - } - - loginInfo, err := b.parseAndValidateJwt(ctx, req, data) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - roleType := loginInfo.Role.RoleType - switch roleType { - case iamRoleType: - return b.pathIamLogin(ctx, req, loginInfo) - case gceRoleType: - return b.pathGceLogin(ctx, req, loginInfo) - default: - return logical.ErrorResponse(fmt.Sprintf("login against role type '%s' is unsupported", roleType)), nil - } -} - -func (b *GcpAuthBackend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Check role exists and allowed policies are still the same. - roleName := req.Auth.Metadata["role"] - if roleName == "" { - return logical.ErrorResponse("role name metadata not associated with auth token, invalid"), nil - } - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } else if role == nil { - return logical.ErrorResponse("role '%s' no longer exists"), nil - } else if !policyutil.EquivalentPolicies(role.Policies, req.Auth.Policies) { - return logical.ErrorResponse("policies on role '%s' have changed, cannot renew"), nil - } - - switch role.RoleType { - case iamRoleType: - if err := b.pathIamRenew(ctx, req, roleName, role); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - case gceRoleType: - if err := b.pathGceRenew(ctx, req, roleName, role); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - default: - return nil, fmt.Errorf("unexpected role type '%s' for login renewal", role.RoleType) - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.Period = role.Period - resp.Auth.TTL = role.TTL - resp.Auth.MaxTTL = role.MaxTTL - return resp, nil -} - -// gcpLoginInfo represents the data given to Vault for logging in using the IAM method. -type gcpLoginInfo struct { - // Name of the role being logged in against - RoleName string - - // Role being logged in against - Role *gcpRole - - // ID or email of an IAM service account or that inferred for a GCE VM. - ServiceAccountId string - - // Base JWT Claims (registered claims such as 'exp', 'iss', etc) - JWTClaims *jwt.Claims - - // Metadata from a GCE instance identity token. - GceMetadata *gcputil.GCEIdentityMetadata -} - -func (b *GcpAuthBackend) parseAndValidateJwt(ctx context.Context, req *logical.Request, data *framework.FieldData) (*gcpLoginInfo, error) { - loginInfo := &gcpLoginInfo{} - var err error - - loginInfo.RoleName = data.Get("role").(string) - if loginInfo.RoleName == "" { - return nil, errors.New("role is required") - } - - loginInfo.Role, err = b.role(ctx, req.Storage, loginInfo.RoleName) - if err != nil { - return nil, err - } - if loginInfo.Role == nil { - return nil, fmt.Errorf("role '%s' not found", loginInfo.RoleName) - } - - // Process JWT string. - signedJwt, ok := data.GetOk("jwt") - if !ok { - return nil, errors.New("jwt argument is required") - } - - // Parse 'kid' key id from headers. - jwtVal, err := jwt.ParseSigned(signedJwt.(string)) - if err != nil { - return nil, err - } - - key, err := b.getSigningKey(ctx, jwtVal, signedJwt.(string), loginInfo.Role, req.Storage) - if err != nil { - return nil, err - } - - // Parse claims and verify signature. - baseClaims := &jwt.Claims{} - customClaims := &gcputil.CustomJWTClaims{} - - if err = jwtVal.Claims(key, baseClaims, customClaims); err != nil { - return nil, err - } - - if err = validateBaseJWTClaims(baseClaims, loginInfo.RoleName); err != nil { - return nil, err - } - loginInfo.JWTClaims = baseClaims - - if len(baseClaims.Subject) == 0 { - return nil, errors.New("expected JWT to have non-empty 'sub' claim") - } - loginInfo.ServiceAccountId = baseClaims.Subject - - if customClaims.Google != nil && customClaims.Google.Compute != nil && len(customClaims.Google.Compute.InstanceId) > 0 { - loginInfo.GceMetadata = customClaims.Google.Compute - } - - if loginInfo.Role.RoleType == gceRoleType && loginInfo.GceMetadata == nil { - return nil, errors.New("expected JWT to have claims with GCE metadata") - } - - return loginInfo, nil -} - -func (b *GcpAuthBackend) getSigningKey(ctx context.Context, token *jwt.JSONWebToken, rawToken string, role *gcpRole, s logical.Storage) (interface{}, error) { - if len(token.Headers) != 1 { - return nil, errors.New("expected token to have exactly one header") - } - - keyId := token.Headers[0].KeyID - - switch role.RoleType { - case iamRoleType: - iamClient, err := b.IAM(ctx, s) - if err != nil { - return nil, err - } - - serviceAccountId, err := parseServiceAccountFromIAMJWT(rawToken) - if err != nil { - return nil, err - } - - accountKey, err := gcputil.ServiceAccountKey(iamClient, &gcputil.ServiceAccountKeyId{ - Project: role.ProjectId, - EmailOrId: serviceAccountId, - Key: keyId, - }) - if err != nil { - // Attempt to get a normal Google Oauth cert in case of GCE inferrence. - key, err := b.getGoogleOauthCert(ctx, keyId, s) - if err != nil { - return nil, errwrap.Wrapf( - fmt.Sprintf("could not find service account key or Google Oauth cert with given 'kid' id %s: {{err}}", keyId), - err) - } - return key, nil - } - return gcputil.PublicKey(accountKey.PublicKeyData) - case gceRoleType: - return b.getGoogleOauthCert(ctx, keyId, s) - default: - return nil, fmt.Errorf("unexpected role type %s", role.RoleType) - } -} - -// ParseServiceAccountFromIAMJWT parses the service account from the 'sub' claim given a serialized signed JWT. -func parseServiceAccountFromIAMJWT(signedJwt string) (string, error) { - jwtVal, err := jws.ParseJWT([]byte(signedJwt)) - if err != nil { - return "", fmt.Errorf("could not parse service account from JWT 'sub' claim: %v", err) - } - accountId, ok := jwtVal.Claims().Subject() - if !ok { - return "", errors.New("expected 'sub' claim with service account ID or name") - } - return accountId, nil -} - -func (b *GcpAuthBackend) getGoogleOauthCert(ctx context.Context, keyId string, s logical.Storage) (interface{}, error) { - var certsEndpoint string - conf, err := b.config(ctx, s) - if err != nil { - return nil, fmt.Errorf("could not read config for backend: %v", err) - } - if conf != nil { - certsEndpoint = conf.GoogleCertsEndpoint - } - - key, err := gcputil.OAuth2RSAPublicKey(keyId, certsEndpoint) - if err != nil { - return nil, err - } - return key, nil -} - -func validateBaseJWTClaims(c *jwt.Claims, roleName string) error { - exp := c.Expiry.Time() - if exp.IsZero() || exp.Before(time.Now()) { - return errors.New("JWT is expired or does not have proper 'exp' claim") - } else if exp.After(time.Now().Add(time.Minute * time.Duration(maxJwtExpMaxMinutes))) { - return fmt.Errorf("JWT must expire in %d minutes", maxJwtExpMaxMinutes) - } - - sub := c.Subject - if len(sub) < 0 { - return errors.New("expected JWT to have 'sub' claim with service account id or email") - } - - expectedAudSuffix := fmt.Sprintf(expectedJwtAudTemplate, roleName) - for _, aud := range c.Audience { - if !strings.HasSuffix(aud, expectedAudSuffix) { - return fmt.Errorf("at least one of the JWT claim 'aud' must end in '%s'", expectedAudSuffix) - } - } - - return nil -} - -// ---- IAM login domain ---- -// pathIamLogin attempts a login operation using the parsed login info. -func (b *GcpAuthBackend) pathIamLogin(ctx context.Context, req *logical.Request, loginInfo *gcpLoginInfo) (*logical.Response, error) { - iamClient, err := b.IAM(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf(clientErrorTemplate, "IAM", err)), nil - } - - role := loginInfo.Role - if !role.AllowGCEInference && loginInfo.GceMetadata != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Got GCE token but IAM role '%s' does not allow GCE inference", loginInfo.RoleName)), nil - } - - // TODO(emilymye): move to general JWT validation once custom expiry is supported for other JWT types. - if loginInfo.JWTClaims.Expiry.Time().After(time.Now().Add(role.MaxJwtExp)) { - return logical.ErrorResponse(fmt.Sprintf("role requires that JWTs must expire within %d seconds", int(role.MaxJwtExp/time.Second))), nil - } - - // Get service account and make sure it still exists. - accountId := &gcputil.ServiceAccountId{ - Project: role.ProjectId, - EmailOrId: loginInfo.ServiceAccountId, - } - serviceAccount, err := gcputil.ServiceAccount(iamClient, accountId) - if err != nil { - return nil, err - } - if serviceAccount == nil { - return nil, errors.New("service account is empty") - } - - if req.Operation == logical.AliasLookaheadOperation { - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: serviceAccount.UniqueId, - }, - }, - }, nil - } - - // Validate service account can login against role. - if err := b.authorizeIAMServiceAccount(serviceAccount, role); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - Period: role.Period, - Alias: &logical.Alias{ - Name: serviceAccount.UniqueId, - }, - Policies: role.Policies, - Metadata: authMetadata(loginInfo, serviceAccount), - DisplayName: serviceAccount.Email, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - }, - } - - return resp, nil -} - -// pathIamRenew returns an error if the service account referenced in the auth token metadata cannot renew the -// auth token for the given role. -func (b *GcpAuthBackend) pathIamRenew(ctx context.Context, req *logical.Request, roleName string, role *gcpRole) error { - iamClient, err := b.IAM(ctx, req.Storage) - if err != nil { - return fmt.Errorf(clientErrorTemplate, "IAM", err) - } - - serviceAccountId, ok := req.Auth.Metadata["service_account_id"] - if !ok { - return errors.New("service account id metadata not associated with auth token, invalid") - } - - serviceAccount, err := gcputil.ServiceAccount(iamClient, &gcputil.ServiceAccountId{ - Project: role.ProjectId, - EmailOrId: serviceAccountId, - }) - if err != nil { - return fmt.Errorf("cannot find service account %s", serviceAccountId) - } - - _, isGceInferred := req.Auth.Metadata["instance_id"] - if isGceInferred && !role.AllowGCEInference { - return fmt.Errorf("GCE inferrence is no longer allowed for role %s", roleName) - } - - if err := b.authorizeIAMServiceAccount(serviceAccount, role); err != nil { - return fmt.Errorf("service account is no longer authorized for role %s", roleName) - } - - return nil -} - -// validateAgainstIAMRole returns an error if the given IAM service account is not authorized for the role. -func (b *GcpAuthBackend) authorizeIAMServiceAccount(serviceAccount *iam.ServiceAccount, role *gcpRole) error { - // This is just in case - project should already be used to retrieve service account. - if role.ProjectId != serviceAccount.ProjectId { - return fmt.Errorf("service account %s does not belong to project %s", serviceAccount.Email, role.ProjectId) - } - - // Check if role has the wildcard as the only service account. - if len(role.BoundServiceAccounts) == 1 && role.BoundServiceAccounts[0] == serviceAccountsWildcard { - return nil - } - - // Check for service account id/email. - if strutil.StrListContains(role.BoundServiceAccounts, serviceAccount.Email) || - strutil.StrListContains(role.BoundServiceAccounts, serviceAccount.UniqueId) { - return nil - } - - return fmt.Errorf("service account %s (id: %s) is not authorized for role", - serviceAccount.Email, serviceAccount.UniqueId) -} - -// ---- GCE login domain ---- -// pathGceLogin attempts a login operation using the parsed login info. -func (b *GcpAuthBackend) pathGceLogin(ctx context.Context, req *logical.Request, loginInfo *gcpLoginInfo) (*logical.Response, error) { - role := loginInfo.Role - metadata := loginInfo.GceMetadata - if metadata == nil { - return logical.ErrorResponse("could not get GCE metadata from given JWT"), nil - } - - if role.ProjectId != metadata.ProjectId { - return logical.ErrorResponse(fmt.Sprintf( - "GCE instance must belong to project %s; metadata given has project %s", - role.ProjectId, metadata.ProjectId)), nil - } - - // Verify instance exists. - gceClient, err := b.GCE(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf(clientErrorTemplate, "GCE", err)), nil - } - - instance, err := metadata.GetVerifiedInstance(gceClient) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "error when attempting to find instance (project %s, zone: %s, instance: %s) :%v", - metadata.ProjectId, metadata.Zone, metadata.InstanceName, err)), nil - } - - if err := b.authorizeGCEInstance(ctx, instance, req.Storage, role, loginInfo.ServiceAccountId); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - iamClient, err := b.IAM(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf(clientErrorTemplate, "IAM", err)), nil - } - - serviceAccount, err := gcputil.ServiceAccount(iamClient, &gcputil.ServiceAccountId{ - Project: loginInfo.Role.ProjectId, - EmailOrId: loginInfo.ServiceAccountId, - }) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Could not find service account '%s' used for GCE metadata token: %s", - loginInfo.ServiceAccountId, err)), nil - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - InternalData: map[string]interface{}{}, - Period: role.Period, - Alias: &logical.Alias{ - Name: fmt.Sprintf("gce-%s", strconv.FormatUint(instance.Id, 10)), - }, - Policies: role.Policies, - Metadata: authMetadata(loginInfo, serviceAccount), - DisplayName: instance.Name, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - }, - } - - return resp, nil -} - -func authMetadata(loginInfo *gcpLoginInfo, serviceAccount *iam.ServiceAccount) map[string]string { - metadata := map[string]string{ - "role": loginInfo.RoleName, - "service_account_id": serviceAccount.UniqueId, - "service_account_email": serviceAccount.Email, - } - - if loginInfo.GceMetadata != nil { - gceMetadata := loginInfo.GceMetadata - metadata["project_id"] = gceMetadata.ProjectId - metadata["project_number"] = strconv.FormatInt(gceMetadata.ProjectNumber, 10) - metadata["zone"] = gceMetadata.Zone - metadata["instance_id"] = gceMetadata.InstanceId - metadata["instance_name"] = gceMetadata.InstanceName - metadata["instance_creation_timestamp"] = strconv.FormatInt(gceMetadata.CreatedAt, 10) - } - return metadata -} - -// pathGceRenew returns an error if the instance referenced in the auth token metadata cannot renew the -// auth token for the given role. -func (b *GcpAuthBackend) pathGceRenew(ctx context.Context, req *logical.Request, roleName string, role *gcpRole) error { - gceClient, err := b.GCE(ctx, req.Storage) - if err != nil { - return fmt.Errorf(clientErrorTemplate, "GCE", err) - } - - meta, err := getInstanceMetadataFromAuth(req.Auth.Metadata) - if err != nil { - return fmt.Errorf("invalid auth metadata: %v", err) - } - - instance, err := meta.GetVerifiedInstance(gceClient) - if err != nil { - return err - } - - serviceAccountId, ok := req.Auth.Metadata["service_account_id"] - if !ok { - return errors.New("invalid auth metadata: service_account_id not found") - } - if err := b.authorizeGCEInstance(ctx, instance, req.Storage, role, serviceAccountId); err != nil { - return fmt.Errorf("could not renew token for role %s: %v", roleName, err) - } - - return nil -} - -func getInstanceMetadataFromAuth(authMetadata map[string]string) (*gcputil.GCEIdentityMetadata, error) { - meta := &gcputil.GCEIdentityMetadata{} - var ok bool - var err error - - meta.ProjectId, ok = authMetadata["project_id"] - if !ok { - return nil, errors.New("expected 'project_id' field") - } - - meta.Zone, ok = authMetadata["zone"] - if !ok { - return nil, errors.New("expected 'zone' field") - } - - meta.InstanceId, ok = authMetadata["instance_id"] - if !ok { - return nil, errors.New("expected 'instance_id' field") - } - - meta.InstanceName, ok = authMetadata["instance_name"] - if !ok { - return nil, errors.New("expected 'instance_name' field") - } - - // Parse numbers back into int values. - projectNumber, ok := authMetadata["project_number"] - if !ok { - return nil, errors.New("expected 'project_number' field, got %v") - } - meta.ProjectNumber, err = strconv.ParseInt(projectNumber, 10, 64) - if err != nil { - return nil, fmt.Errorf("expected 'project_number' value '%s' to be a int64", projectNumber) - } - - createdAt, ok := authMetadata["instance_creation_timestamp"] - if !ok { - return nil, errors.New("expected 'instance_creation_timestamp' field") - } - meta.CreatedAt, err = strconv.ParseInt(createdAt, 10, 64) - if err != nil { - return nil, fmt.Errorf("expected 'instance_creation_timestamp' value '%s' to be int64", createdAt) - } - - return meta, nil -} - -// authorizeGCEInstance returns an error if the given GCE instance is not -// authorized for the role. -func (b *GcpAuthBackend) authorizeGCEInstance(ctx context.Context, instance *compute.Instance, s logical.Storage, role *gcpRole, serviceAccountId string) error { - computeSvc, err := b.GCE(ctx, s) - if err != nil { - return err - } - - iamSvc, err := b.IAM(ctx, s) - if err != nil { - return err - } - - return AuthorizeGCE(ctx, &AuthorizeGCEInput{ - client: &gcpClient{ - computeSvc: computeSvc, - iamSvc: iamSvc, - }, - - project: role.ProjectId, - serviceAccount: serviceAccountId, - - instanceLabels: instance.Labels, - instanceSelfLink: instance.SelfLink, - instanceZone: instance.Zone, - - boundLabels: role.BoundLabels, - boundRegions: role.BoundRegions, - boundZones: role.BoundZones, - - boundInstanceGroups: role.BoundInstanceGroups, - boundServiceAccounts: role.BoundServiceAccounts, - }) -} - -const pathLoginHelpSyn = `Authenticates Google Cloud Platform entities with Vault.` -const pathLoginHelpDesc = ` -Authenticate Google Cloud Platform (GCP) entities. - -Currently supports authentication for: - -IAM service accounts -===================== -IAM service accounts can use GCP APIs or tools to sign a JSON Web Token (JWT). -This JWT should contain the id (expected field 'client_id') or email -(expected field 'client_email') of the authenticating service account in its claims. -Vault verifies the signed JWT and parses the identity of the account. - -Renewal is rejected if the role, service account, or original signing key no longer exists. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_role.go b/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_role.go deleted file mode 100644 index 212b1d20c..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-gcp/plugin/path_role.go +++ /dev/null @@ -1,962 +0,0 @@ -package gcpauth - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-gcp-common/gcputil" - vaultconsts "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // Role types - iamRoleType = "iam" - gceRoleType = "gce" - - // Errors - errEmptyRoleName = "role name is required" - errEmptyRoleType = "role type cannot be empty" - errEmptyProjectId = "project id cannot be empty" - errEmptyIamServiceAccounts = "IAM role type must have at least one service account" - - errTemplateEditListWrongType = "role is type '%s', cannot edit attribute '%s' (expected role type: '%s')" - errTemplateInvalidRoleTypeArgs = "invalid args found for role of type %s: %s" - - // Other - serviceAccountsWildcard = "*" - - // Default duration that JWT tokens must expire within to be accepted (currently only IAM) - defaultIamMaxJwtExpMinutes int = 15 - - // Max allowed duration that all JWT tokens must expire within to be accepted - maxJwtExpMaxMinutes int = 60 -) - -var baseRoleFieldSchema = map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - "type": { - Type: framework.TypeString, - Description: "Type of the role. Currently supported: iam, gce", - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be set on tokens issued using this role.", - }, - // Token Limits - "ttl": { - Type: framework.TypeDurationSecond, - Default: 0, - Description: ` - Duration in seconds after which the issued token should expire. Defaults to 0, - in which case the value will fallback to the system/mount defaults.`, - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The maximum allowed lifetime of tokens issued using this role.", - }, - "period": { - Type: framework.TypeDurationSecond, - Default: 0, - Description: ` - If set, indicates that the token generated using this role should never expire. The token should be renewed within the - duration specified by this value. At each renewal, the token's TTL will be set to the value of this parameter.`, - }, - // -- GCP Information - "project_id": { - Type: framework.TypeString, - Description: `The id of the project that authorized instances must belong to for this role.`, - }, - "bound_service_accounts": { - Type: framework.TypeCommaStringSlice, - Description: ` - Can be set for both 'iam' and 'gce' roles (required for 'iam'). A comma-seperated list of authorized service accounts. - If the single value "*" is given, this is assumed to be all service accounts under the role's project. If this - is set on a GCE role, the inferred service account from the instance metadata token will be used.`, - }, - "service_accounts": { - Type: framework.TypeCommaStringSlice, - Description: `Deprecated, use bound_service_accounts instead.`, - }, -} - -var iamOnlyFieldSchema = map[string]*framework.FieldSchema{ - "max_jwt_exp": { - Type: framework.TypeDurationSecond, - Default: defaultIamMaxJwtExpMinutes * 60, - Description: `Currently enabled for 'iam' only. Duration in seconds from time of validation that a JWT must expire within.`, - }, - "allow_gce_inference": { - Type: framework.TypeBool, - Default: true, - Description: `'iam' roles only. If false, Vault will not not allow GCE instances to login in against this role`, - }, -} - -var gceOnlyFieldSchema = map[string]*framework.FieldSchema{ - "bound_zones": { - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of permitted zones to which the GCE " + - "instance must belong. If a group is provided, it is assumed to be a " + - "zonal group. This can be a self-link or zone name. This option only " + - "applies to \"gce\" roles.", - }, - - "bound_regions": { - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of permitted regions to which the GCE " + - "instance must belong. If a group is provided, it is assumed to be a " + - "regional group. If \"zone\" is provided, this option is ignored. This " + - "can be a self-link or region name. This option only applies to \"gce\" roles.", - }, - - "bound_instance_groups": { - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of permitted instance groups to which " + - "the GCE instance must belong. This option only applies to \"gce\" roles.", - }, - - "bound_labels": { - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of GCP labels formatted as" + - "\"key:value\" strings that must be present on the GCE instance " + - "in order to authenticate. This option only applies to \"gce\" roles.", - }, - - // Deprecated roles - "bound_zone": { - Type: framework.TypeString, - Description: "Deprecated: use \"bound_zones\" instead.", - }, - "bound_region": { - Type: framework.TypeString, - Description: "Deprecated: use \"bound_regions\" instead.", - }, - "bound_instance_group": { - Type: framework.TypeString, - Description: "Deprecated: use \"bound_instance_groups\" instead.", - }, -} - -// pathsRole creates paths for listing roles and CRUD operations. -func pathsRole(b *GcpAuthBackend) []*framework.Path { - roleFieldSchema := map[string]*framework.FieldSchema{} - for k, v := range baseRoleFieldSchema { - roleFieldSchema[k] = v - } - for k, v := range iamOnlyFieldSchema { - roleFieldSchema[k] = v - } - for k, v := range gceOnlyFieldSchema { - roleFieldSchema[k] = v - } - - paths := []*framework.Path{ - { - Pattern: fmt.Sprintf("role/%s", framework.GenericNameRegex("name")), - Fields: roleFieldSchema, - ExistenceCheck: b.pathRoleExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathRoleDelete, - logical.ReadOperation: b.pathRoleRead, - logical.CreateOperation: b.pathRoleCreateUpdate, - logical.UpdateOperation: b.pathRoleCreateUpdate, - }, - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - }, - // Paths for listing roles - { - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - }, - { - Pattern: "roles/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - }, - - // Edit service accounts on an IAM role - { - Pattern: fmt.Sprintf("role/%s/service-accounts", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - "add": { - Type: framework.TypeCommaStringSlice, - Description: "Service-account emails or IDs to add.", - }, - "remove": { - Type: framework.TypeCommaStringSlice, - Description: "Service-account emails or IDs to remove.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleEditIamServiceAccounts, - }, - HelpSynopsis: "Add or remove service accounts for an existing `iam` role", - HelpDescription: "Add or remove service accounts from the list bound to an existing `iam` role", - }, - - // Edit labels on an GCE role - { - Pattern: fmt.Sprintf("role/%s/labels", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - "add": { - Type: framework.TypeCommaStringSlice, - Description: "BoundLabels to add (in $key:$value)", - }, - "remove": { - Type: framework.TypeCommaStringSlice, - Description: "Label key values to remove", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleEditGceLabels, - }, - HelpSynopsis: "Add or remove labels for an existing 'gce' role", - HelpDescription: `Add or remove labels for an existing 'gce' role. 'add' labels should be - of format '$key:$value' and 'remove' labels should be a list of keys to remove.`, - }, - } - - return paths -} - -func (b *GcpAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - return entry != nil, nil -} - -func (b *GcpAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(errEmptyRoleName), nil - } - - if err := req.Storage.Delete(ctx, fmt.Sprintf("role/%s", name)); err != nil { - return nil, err - } - return nil, nil -} - -func (b *GcpAuthBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(errEmptyRoleName), nil - } - - role, err := b.role(ctx, req.Storage, name) - if err != nil { - return nil, err - } else if role == nil { - return nil, nil - } - - role.Period /= time.Second - role.TTL /= time.Second - role.MaxTTL /= time.Second - role.MaxJwtExp /= time.Second - - resp := make(map[string]interface{}) - - if role.RoleType != "" { - resp["role_type"] = role.RoleType - } - if role.ProjectId != "" { - resp["project_id"] = role.ProjectId - } - if len(role.Policies) > 0 { - resp["policies"] = role.Policies - } - if role.TTL != 0 { - resp["ttl"] = role.TTL - } - if role.MaxTTL != 0 { - resp["max_ttl"] = role.MaxTTL - } - if role.Period != 0 { - resp["period"] = role.Period - } - if len(role.BoundServiceAccounts) > 0 { - resp["bound_service_accounts"] = role.BoundServiceAccounts - } - - switch role.RoleType { - case iamRoleType: - if role.MaxJwtExp != 0 { - resp["max_jwt_exp"] = role.MaxJwtExp - } - resp["allow_gce_inference"] = role.AllowGCEInference - case gceRoleType: - if len(role.BoundRegions) > 0 { - resp["bound_regions"] = role.BoundRegions - } - if len(role.BoundZones) > 0 { - resp["bound_zones"] = role.BoundZones - } - if len(role.BoundInstanceGroups) > 0 { - resp["bound_instance_groups"] = role.BoundInstanceGroups - } - if len(role.BoundLabels) > 0 { - resp["bound_labels"] = role.BoundLabels - } - } - - return &logical.Response{ - Data: resp, - }, nil -} - -func (b *GcpAuthBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Validate we didn't get extraneous fields - if err := validateFields(req, data); err != nil { - return nil, logical.CodedError(422, err.Error()) - } - - name := strings.ToLower(data.Get("name").(string)) - if name == "" { - return logical.ErrorResponse(errEmptyRoleName), nil - } - - role, err := b.role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - role = &gcpRole{} - } - - warnings, err := role.updateRole(b.System(), req.Operation, data) - if err != nil { - resp := logical.ErrorResponse(err.Error()) - for _, w := range warnings { - resp.AddWarning(w) - } - return resp, nil - } - return b.storeRole(ctx, req.Storage, name, role, warnings) -} - -func (b *GcpAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil -} - -const pathRoleHelpSyn = `Create a GCP role with associated policies and required attributes.` -const pathRoleHelpDesc = ` -A role is required to login under the GCP auth backend. A role binds Vault policies and has -required attributes that an authenticating entity must fulfill to login against this role. -After authenticating the instance, Vault uses the bound policies to determine which resources -the authorization token for the instance can access. -` - -const pathListRolesHelpSyn = `Lists all the roles that are registered with Vault.` -const pathListRolesHelpDesc = `Lists all roles under the GCP backends by name.` - -func (b *GcpAuthBackend) pathRoleEditIamServiceAccounts(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Validate we didn't get extraneous fields - if err := validateFields(req, data); err != nil { - return nil, logical.CodedError(422, err.Error()) - } - - var warnings []string - - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse(errEmptyRoleName), nil - } - - toAdd := data.Get("add").([]string) - toRemove := data.Get("remove").([]string) - if len(toAdd) == 0 && len(toRemove) == 0 { - return logical.ErrorResponse("must provide at least one value to add or remove"), nil - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - if role.RoleType != iamRoleType { - return logical.ErrorResponse(fmt.Sprintf(errTemplateEditListWrongType, role.RoleType, "service_accounts", iamRoleType)), nil - } - role.BoundServiceAccounts = editStringValues(role.BoundServiceAccounts, toAdd, toRemove) - - return b.storeRole(ctx, req.Storage, roleName, role, warnings) -} - -func editStringValues(initial []string, toAdd []string, toRemove []string) []string { - strMap := map[string]struct{}{} - for _, name := range initial { - strMap[name] = struct{}{} - } - - for _, name := range toAdd { - strMap[name] = struct{}{} - } - - for _, name := range toRemove { - delete(strMap, name) - } - - updated := make([]string, len(strMap)) - - i := 0 - for k := range strMap { - updated[i] = k - i++ - } - - return updated -} - -func (b *GcpAuthBackend) pathRoleEditGceLabels(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Validate we didn't get extraneous fields - if err := validateFields(req, data); err != nil { - return nil, logical.CodedError(422, err.Error()) - } - - var warnings []string - - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse(errEmptyRoleName), nil - } - - toAdd := data.Get("add").([]string) - toRemove := data.Get("remove").([]string) - if len(toAdd) == 0 && len(toRemove) == 0 { - return logical.ErrorResponse("must provide at least one value to add or remove"), nil - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - if role.RoleType != gceRoleType { - return logical.ErrorResponse(fmt.Sprintf(errTemplateEditListWrongType, role.RoleType, "labels", gceRoleType)), nil - } - - labelsToAdd, invalidLabels := gcputil.ParseGcpLabels(toAdd) - if len(invalidLabels) > 0 { - return logical.ErrorResponse(fmt.Sprintf("given invalid labels to add: %q", invalidLabels)), nil - } - for k, v := range labelsToAdd { - if role.BoundLabels == nil { - role.BoundLabels = make(map[string]string, len(labelsToAdd)) - } - role.BoundLabels[k] = v - } - - for _, k := range toRemove { - delete(role.BoundLabels, k) - } - - return b.storeRole(ctx, req.Storage, roleName, role, warnings) -} - -// role reads a gcpRole from storage. This assumes the caller has already obtained the role lock. -func (b *GcpAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*gcpRole, error) { - name = strings.ToLower(name) - - entry, err := s.Get(ctx, "role/"+name) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var role gcpRole - if err := entry.DecodeJSON(&role); err != nil { - return nil, err - } - - // Keep track of whether we do an in-place upgrade of old fields - modified := false - - // Move old bindings to new fields. - if role.BoundRegion != "" && len(role.BoundRegions) == 0 { - role.BoundRegions = []string{role.BoundRegion} - role.BoundRegion = "" - modified = true - } - if role.BoundZone != "" && len(role.BoundZones) == 0 { - role.BoundZones = []string{role.BoundZone} - role.BoundZone = "" - modified = true - } - if role.BoundInstanceGroup != "" && len(role.BoundInstanceGroups) == 0 { - role.BoundInstanceGroups = []string{role.BoundInstanceGroup} - role.BoundInstanceGroup = "" - modified = true - } - - if modified && (b.System().LocalMount() || !b.System().ReplicationState().HasState(vaultconsts.ReplicationPerformanceSecondary)) { - b.Logger().Info("upgrading role to new schema", - "role", name) - - updatedRole, err := logical.StorageEntryJSON("role/"+name, &role) - if err != nil { - return nil, err - } - if err := s.Put(ctx, updatedRole); err != nil { - // Only perform upgrades on replication primary - if !strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return nil, err - } - } - } - - return &role, nil -} - -// storeRole saves the gcpRole to storage. -// The returned response may contain either warnings or an error response, -// but will be nil if error is not nil -func (b *GcpAuthBackend) storeRole(ctx context.Context, s logical.Storage, roleName string, role *gcpRole, warnings []string) (*logical.Response, error) { - var resp logical.Response - for _, w := range warnings { - resp.AddWarning(w) - } - - validateWarnings, err := role.validate(b.System()) - for _, w := range validateWarnings { - resp.AddWarning(w) - } - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - entry, err := logical.StorageEntryJSON(fmt.Sprintf("role/%s", roleName), role) - if err != nil { - return nil, err - } - if err := s.Put(ctx, entry); err != nil { - return nil, err - } - - return &resp, nil -} - -type gcpRole struct { - // Type of this role. See path_role constants for currently supported types. - RoleType string `json:"role_type,omitempty"` - - // Project ID in GCP for authorized entities. - ProjectId string `json:"project_id,omitempty"` - - // Policies for Vault to assign to authorized entities. - Policies []string `json:"policies,omitempty"` - - // TTL of Vault auth leases under this role. - TTL time.Duration `json:"ttl,omitempty"` - - // Max total TTL including renewals, of Vault auth leases under this role. - MaxTTL time.Duration `json:"max_ttl,omitempty"` - - // Period, If set, indicates that this token should not expire and - // should be automatically renewed within this time period - // with TTL equal to this value. - Period time.Duration `json:"period,omitempty"` - - // Service accounts allowed to login under this role. - BoundServiceAccounts []string `json:"bound_service_accounts,omitempty"` - - // --| IAM-only attributes |-- - // MaxJwtExp is the duration from time of authentication that a JWT used to authenticate to role must expire within. - // TODO(emilymye): Allow this to be updated for GCE roles once 'exp' parameter has been allowed for GCE metadata. - MaxJwtExp time.Duration `json:"max_jwt_exp,omitempty"` - - // AllowGCEInference, if false, does not allow a GCE instance to login under this 'iam' role. If true (default), - // a service account is inferred from the instance metadata and used as the authenticating instance. - AllowGCEInference bool `json:"allow_gce_inference,omitempty"` - - // --| GCE-only attributes |-- - // BoundRegions that instances must belong to in order to login under this role. - BoundRegions []string `json:"bound_regions,omitempty"` - - // BoundZones that instances must belong to in order to login under this role. - BoundZones []string `json:"bound_zones,omitempty"` - - // BoundInstanceGroups are the instance group that instances must belong to in order to login under this role. - BoundInstanceGroups []string `json:"bound_instance_groups,omitempty"` - - // BoundLabels that instances must currently have set in order to login under this role. - BoundLabels map[string]string `json:"bound_labels,omitempty"` - - // Deprecated fields - // TODO: Remove in 0.5.0+ - BoundRegion string `json:"bound_region,omitempty"` - BoundZone string `json:"bound_zone,omitempty"` - BoundInstanceGroup string `json:"bound_instance_group,omitempty"` -} - -// Update updates the given role with values parsed/validated from given FieldData. -// Exactly one of the response and error will be nil. The response is only used to pass back warnings. -// This method does not validate the role. Validation is done before storage. -func (role *gcpRole) updateRole(sys logical.SystemView, op logical.Operation, data *framework.FieldData) (warnings []string, err error) { - // Set role type - if rt, ok := data.GetOk("type"); ok { - roleType := rt.(string) - if role.RoleType != roleType && op == logical.UpdateOperation { - err = errors.New("role type cannot be changed for an existing role") - return - } - role.RoleType = roleType - } else if op == logical.CreateOperation { - err = errors.New(errEmptyRoleType) - return - } - - // Update policies - if policies, ok := data.GetOk("policies"); ok { - role.Policies = policyutil.ParsePolicies(policies) - } else if op == logical.CreateOperation { - // Force default policy - role.Policies = policyutil.ParsePolicies(nil) - } - - // Update GCP project id. - if projectId, ok := data.GetOk("project_id"); ok { - role.ProjectId = projectId.(string) - } else if op == logical.CreateOperation { - role.ProjectId = data.Get("project_id").(string) - } - - // Update token TTL. - if ttl, ok := data.GetOk("ttl"); ok { - role.TTL = time.Duration(ttl.(int)) * time.Second - - def := sys.DefaultLeaseTTL() - if role.TTL > def { - warnings = append(warnings, fmt.Sprintf(`Given "ttl" of %q is greater `+ - `than the maximum system/mount TTL of %q. The TTL will be capped at `+ - `%q during login.`, role.TTL, def, def)) - } - } else if op == logical.CreateOperation { - role.TTL = time.Duration(data.Get("ttl").(int)) * time.Second - } - - // Update token Max TTL. - if maxTTL, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(maxTTL.(int)) * time.Second - - def := sys.MaxLeaseTTL() - if role.MaxTTL > def { - warnings = append(warnings, fmt.Sprintf(`Given "max_ttl" of %q is greater `+ - `than the maximum system/mount MaxTTL of %q. The MaxTTL will be `+ - `capped at %q during login.`, role.MaxTTL, def, def)) - } - } else if op == logical.CreateOperation { - role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second - } - - // Update token period. - if period, ok := data.GetOk("period"); ok { - role.Period = time.Duration(period.(int)) * time.Second - - def := sys.MaxLeaseTTL() - if role.Period > def { - warnings = append(warnings, fmt.Sprintf(`Given "period" of %q is greater `+ - `than the maximum system/mount period of %q. The period will be `+ - `capped at %q during login.`, role.Period, def, def)) - } - } else if op == logical.CreateOperation { - role.Period = time.Duration(data.Get("period").(int)) * time.Second - } - - // Update bound GCP service accounts. - if sa, ok := data.GetOk("bound_service_accounts"); ok { - role.BoundServiceAccounts = sa.([]string) - } else { - // Check for older version of param name - if sa, ok := data.GetOk("service_accounts"); ok { - warnings = append(warnings, `The "service_accounts" field is deprecated. `+ - `Please use "bound_service_accounts" instead. The "service_accounts" `+ - `field will be removed in a later release, so please update accordingly.`) - role.BoundServiceAccounts = sa.([]string) - } - } - - if len(role.BoundServiceAccounts) > 0 { - role.BoundServiceAccounts = strutil.TrimStrings(role.BoundServiceAccounts) - role.BoundServiceAccounts = strutil.RemoveDuplicates(role.BoundServiceAccounts, false) - } - - // Update fields specific to this type - switch role.RoleType { - case iamRoleType: - if err = checkInvalidRoleTypeArgs(data, gceOnlyFieldSchema); err != nil { - return - } - if warnings, err = role.updateIamFields(data, op); err != nil { - return - } - case gceRoleType: - if err = checkInvalidRoleTypeArgs(data, iamOnlyFieldSchema); err != nil { - return - } - if warnings, err = role.updateGceFields(data, op); err != nil { - return - } - } - - return -} - -func (role *gcpRole) validate(sys logical.SystemView) (warnings []string, err error) { - warnings = []string{} - - switch role.RoleType { - case iamRoleType: - if warnings, err = role.validateForIAM(); err != nil { - return warnings, err - } - case gceRoleType: - if warnings, err = role.validateForGCE(); err != nil { - return warnings, err - } - case "": - return warnings, errors.New(errEmptyRoleType) - default: - return warnings, fmt.Errorf("role type '%s' is invalid", role.RoleType) - } - - if role.ProjectId == "" { - return warnings, errors.New(errEmptyProjectId) - } - - defaultLeaseTTL := sys.DefaultLeaseTTL() - if role.TTL > defaultLeaseTTL { - warnings = append(warnings, fmt.Sprintf( - "Given ttl of %d seconds greater than current mount/system default of %d seconds; ttl will be capped at login time", - role.TTL/time.Second, defaultLeaseTTL/time.Second)) - } - - defaultMaxTTL := sys.MaxLeaseTTL() - if role.MaxTTL > defaultMaxTTL { - warnings = append(warnings, fmt.Sprintf( - "Given max_ttl of %d seconds greater than current mount/system default of %d seconds; max_ttl will be capped at login time", - role.MaxTTL/time.Second, defaultMaxTTL/time.Second)) - } - if role.MaxTTL < time.Duration(0) { - return warnings, errors.New("max_ttl cannot be negative") - } - if role.MaxTTL != 0 && role.MaxTTL < role.TTL { - return warnings, errors.New("ttl should be shorter than max_ttl") - } - - if role.Period > sys.MaxLeaseTTL() { - return warnings, fmt.Errorf("'period' of '%s' is greater than the backend's maximum lease TTL of '%s'", role.Period.String(), sys.MaxLeaseTTL().String()) - } - - return warnings, nil -} - -// updateIamFields updates IAM-only fields for a role. -func (role *gcpRole) updateIamFields(data *framework.FieldData, op logical.Operation) (warnings []string, err error) { - if allowGCEInference, ok := data.GetOk("allow_gce_inference"); ok { - role.AllowGCEInference = allowGCEInference.(bool) - } else if op == logical.CreateOperation { - role.AllowGCEInference = data.Get("allow_gce_inference").(bool) - } - - if maxJwtExp, ok := data.GetOk("max_jwt_exp"); ok { - role.MaxJwtExp = time.Duration(maxJwtExp.(int)) * time.Second - } else if op == logical.CreateOperation { - role.MaxJwtExp = time.Duration(defaultIamMaxJwtExpMinutes) * time.Minute - } - - return -} - -// updateGceFields updates GCE-only fields for a role. -func (role *gcpRole) updateGceFields(data *framework.FieldData, op logical.Operation) (warnings []string, err error) { - if regions, ok := data.GetOk("bound_regions"); ok { - role.BoundRegions = regions.([]string) - } else if op == logical.CreateOperation { - role.BoundRegions = data.Get("bound_regions").([]string) - } - - if zones, ok := data.GetOk("bound_zones"); ok { - role.BoundZones = zones.([]string) - } else if op == logical.CreateOperation { - role.BoundZones = data.Get("bound_zones").([]string) - } - - if instanceGroups, ok := data.GetOk("bound_instance_groups"); ok { - role.BoundInstanceGroups = instanceGroups.([]string) - } else if op == logical.CreateOperation { - role.BoundInstanceGroups = data.Get("bound_instance_groups").([]string) - } - - if boundRegion, ok := data.GetOk("bound_region"); ok { - if _, ok := data.GetOk("bound_regions"); ok { - err = fmt.Errorf(`cannot specify both "bound_region" and "bound_regions"`) - return - } - - warnings = append(warnings, `The "bound_region" field is deprecated. `+ - `Please use "bound_regions" (plural) instead. You can still specify a `+ - `single region, but multiple regions are also now supported. The `+ - `"bound_region" field will be removed in a later release, so please `+ - `update accordingly.`) - role.BoundRegions = append(role.BoundRegions, boundRegion.(string)) - } - - if boundZone, ok := data.GetOk("bound_zone"); ok { - if _, ok := data.GetOk("bound_zones"); ok { - err = fmt.Errorf(`cannot specify both "bound_zone" and "bound_zones"`) - return - } - - warnings = append(warnings, `The "bound_zone" field is deprecated. `+ - `Please use "bound_zones" (plural) instead. You can still specify a `+ - `single zone, but multiple zones are also now supported. The `+ - `"bound_zone" field will be removed in a later release, so please `+ - `update accordingly.`) - role.BoundZones = append(role.BoundZones, boundZone.(string)) - } - - if boundInstanceGroup, ok := data.GetOk("bound_instance_group"); ok { - if _, ok := data.GetOk("bound_instance_groups"); ok { - err = fmt.Errorf(`cannot specify both "bound_instance_group" and "bound_instance_groups"`) - return - } - - warnings = append(warnings, `The "bound_instance_group" field is deprecated. `+ - `Please use "bound_instance_groups" (plural) instead. You can still specify a `+ - `single instance group, but multiple instance groups are also now supported. The `+ - `"bound_instance_group" field will be removed in a later release, so please `+ - `update accordingly.`) - role.BoundInstanceGroups = append(role.BoundInstanceGroups, boundInstanceGroup.(string)) - } - - if labelsRaw, ok := data.GetOk("bound_labels"); ok { - labels, invalidLabels := gcputil.ParseGcpLabels(labelsRaw.([]string)) - if len(invalidLabels) > 0 { - err = fmt.Errorf("invalid labels given: %q", invalidLabels) - return - } - role.BoundLabels = labels - } - - if len(role.Policies) > 0 { - role.Policies = strutil.TrimStrings(role.Policies) - role.Policies = strutil.RemoveDuplicates(role.Policies, false) - } - - if len(role.BoundRegions) > 0 { - role.BoundRegions = strutil.TrimStrings(role.BoundRegions) - role.BoundRegions = strutil.RemoveDuplicates(role.BoundRegions, false) - } - - if len(role.BoundZones) > 0 { - role.BoundZones = strutil.TrimStrings(role.BoundZones) - role.BoundZones = strutil.RemoveDuplicates(role.BoundZones, false) - } - - if len(role.BoundInstanceGroups) > 0 { - role.BoundInstanceGroups = strutil.TrimStrings(role.BoundInstanceGroups) - role.BoundInstanceGroups = strutil.RemoveDuplicates(role.BoundInstanceGroups, false) - } - - return -} - -// validateIamFields validates the IAM-only fields for a role. -func (role *gcpRole) validateForIAM() (warnings []string, err error) { - if len(role.BoundServiceAccounts) == 0 { - return []string{}, errors.New(errEmptyIamServiceAccounts) - } - - if len(role.BoundServiceAccounts) > 1 && strutil.StrListContains(role.BoundServiceAccounts, serviceAccountsWildcard) { - return []string{}, fmt.Errorf("cannot provide IAM service account wildcard '%s' (for all service accounts) with other service accounts", serviceAccountsWildcard) - } - - maxMaxJwtExp := time.Duration(maxJwtExpMaxMinutes) * time.Minute - if role.MaxJwtExp > maxMaxJwtExp { - return warnings, fmt.Errorf("max_jwt_exp cannot be more than %d minutes", maxJwtExpMaxMinutes) - } - - return []string{}, nil -} - -// validateGceFields validates the GCE-only fields for a role. -func (role *gcpRole) validateForGCE() (warnings []string, err error) { - warnings = []string{} - - hasRegion := len(role.BoundRegions) > 0 - hasZone := len(role.BoundZones) > 0 - hasRegionOrZone := hasRegion || hasZone - - hasInstanceGroup := len(role.BoundInstanceGroups) > 0 - - if hasInstanceGroup && !hasRegionOrZone { - return warnings, errors.New(`region or zone information must be specified if an instance group is given`) - } - - if hasRegion && hasZone { - warnings = append(warnings, `Given both "bound_regions" and "bound_zones" `+ - `fields for role type "gce", "bound_regions" will be ignored in favor `+ - `of the more specific "bound_zones" field. To fix this warning, update `+ - `the role to remove either the "bound_regions" or "bound_zones" field.`) - } - - return warnings, nil -} - -// checkInvalidRoleTypeArgs checks that the data provided does not contain arguments -// for a different role type. If it does find some, it will return an error with the -// invalid args. -func checkInvalidRoleTypeArgs(data *framework.FieldData, invalidSchema map[string]*framework.FieldSchema) error { - invalidArgs := []string{} - - for k := range data.Raw { - if _, ok := baseRoleFieldSchema[k]; ok { - continue - } - if _, ok := invalidSchema[k]; ok { - invalidArgs = append(invalidArgs, k) - } - } - - if len(invalidArgs) > 0 { - return fmt.Errorf(errTemplateInvalidRoleTypeArgs, data.Get("type"), strings.Join(invalidArgs, ",")) - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.lock deleted file mode 100644 index c936288aa..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.lock +++ /dev/null @@ -1,451 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:a69ab3f1445ffd4815add4bd31ba05b65b3b9fec1ade5057d5d717f30e6efd6d" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - digest = "1:f6e5e1bc64c2908167e6aa9a1fe0c084d515132a1c63ad5b6c84036aa06dc0c1" - name = "github.com/coreos/go-oidc" - packages = ["."] - pruneopts = "UT" - revision = "1180514eaf4d9f38d0d19eef639a1d695e066e72" - version = "v2.0.0" - -[[projects]] - digest = "1:7f89e0c888fb99c61055c646f5678aae645b0b0a1443d9b2dcd9964d850827ce" - name = "github.com/go-test/deep" - packages = ["."] - pruneopts = "UT" - revision = "6592d9cc0a499ad2d5f574fde80a2b5c5cc3b4f5" - version = "v1.0.1" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:d00de8725219a569ffbb5dd1042e4ced1f3b5ccee2b07218371f71026cc7609a" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/cidrutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/policyutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "8655d167084028d627f687ddc25d0c71307eb5be" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:bd9efe4e0b0f768302a1e2f0c22458149278de533e521206e5ddc71848c269a0" - name = "github.com/pquerna/cachecontrol" - packages = [ - ".", - "cacheobject", - ] - pruneopts = "UT" - revision = "1555304b9b35fdd2b425bccf1a5613677705e7d0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - digest = "1:b8fa1ff0fc20983395978b3f771bb10438accbfe19326b02e236c1d4bf1c91b2" - name = "golang.org/x/crypto" - packages = [ - "ed25519", - "ed25519/internal/edwards25519", - "pbkdf2", - ] - pruneopts = "UT" - revision = "de0752318171da717af4ce24d0a2e8626afaeb11" - -[[projects]] - branch = "master" - digest = "1:3c4175c2711d67096567fc2d84a83464d6ff58119af3efc89983339d64144cb0" - name = "golang.org/x/net" - packages = [ - "context", - "context/ctxhttp", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:af19f6e6c369bf51ef226e989034cd88a45083173c02ac4d7ab74c9a90d356b7" - name = "golang.org/x/oauth2" - packages = [ - ".", - "internal", - ] - pruneopts = "UT" - revision = "3d292e4d0cdc3a0113e6d207bb137145ef1de42f" - -[[projects]] - branch = "master" - digest = "1:05662433b3a13c921587a6e622b5722072edff83211efd1cd79eeaeedfd83f07" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - digest = "1:328b5e4f197d928c444a51a75385f4b978915c0e75521f0ad6a3db976c97a7d3" - name = "google.golang.org/appengine" - packages = [ - "internal", - "internal/base", - "internal/datastore", - "internal/log", - "internal/remote_api", - "internal/urlfetch", - "urlfetch", - ] - pruneopts = "UT" - revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[[projects]] - digest = "1:b57bb9a6a2a03558d63166f1afc3c0c4f91ad137f63bf2bee995e9baeb976a9c" - name = "gopkg.in/square/go-jose.v2" - packages = [ - ".", - "cipher", - "json", - "jwt", - ] - pruneopts = "UT" - revision = "8254d6c783765f38c8675fae4427a1fe73fbd09d" - version = "v2.1.8" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/coreos/go-oidc", - "github.com/go-test/deep", - "github.com/hashicorp/errwrap", - "github.com/hashicorp/go-cleanhttp", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/go-sockaddr", - "github.com/hashicorp/vault/helper/certutil", - "github.com/hashicorp/vault/helper/cidrutil", - "github.com/hashicorp/vault/helper/logging", - "github.com/hashicorp/vault/helper/parseutil", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/helper/policyutil", - "github.com/hashicorp/vault/helper/strutil", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - "golang.org/x/oauth2", - "gopkg.in/square/go-jose.v2", - "gopkg.in/square/go-jose.v2/jwt", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.toml deleted file mode 100644 index 1752d2434..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Gopkg.toml +++ /dev/null @@ -1,66 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - name = "github.com/coreos/go-oidc" - version = "2.0.0" - -[[constraint]] - name = "github.com/go-test/deep" - version = "1.0.1" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/errwrap" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-sockaddr" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[[constraint]] - branch = "master" - name = "golang.org/x/oauth2" - -[[constraint]] - name = "gopkg.in/square/go-jose.v2" - version = "2.1.8" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Makefile b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Makefile deleted file mode 100644 index bb9dd129b..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -TOOL?=vault-plugin-auth-jwt -TEST?=$$(go list ./... | grep -v /vendor/) -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin, except for quickdev which -# is only put into /bin/ -quickdev: generate - @CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/${TOOL} -dev: generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -testcompile: generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# test runs all tests -test: generate - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 10m - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - @go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmt: - gofmt -w $(GOFMT_FILES) - -# deps updates all dependencies for this project. -deps: - @echo "==> Updating deps for ${TOOL}" - @dep ensure -update - -.PHONY: bin default generate test bootstrap fmt deps diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/README.md b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/README.md deleted file mode 100644 index 442027430..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# Vault Plugin: JWT Auth Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-auth-jwt.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-auth-jwt) - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin allows for JWTs (including OIDC tokens) to authenticate with Vault. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - JWT Auth Docs: https://www.vaultproject.io/docs/auth/jwt.html - - Main Project Github: https://www.github.com/hashicorp/vault - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/auth/jwt.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `auth/jwt`. To enable this in a running Vault server: - -```sh -$ vault auth enable jwt -Successfully enabled 'jwt' at 'jwt'! -``` - -To see all the supported paths, see the [JWT auth backend docs](https://www.vaultproject.io/docs/auth/jwt.html). - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine. - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-jwt`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/jwt \ - sha_256= \ - command="vault-plugin-auth-jwt" -... -Success! Data written to: sys/plugins/catalog/jwt -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-auth-jwt -... -SHA256(.../go/bin/vault-plugin-auth-jwt)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the JWT auth plugin: - -```sh -$ vault auth enable -plugin-name='jwt' plugin -... - -Successfully enabled 'plugin' at 'jwt'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/backend.go deleted file mode 100644 index c906bd8c8..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/backend.go +++ /dev/null @@ -1,120 +0,0 @@ -package jwtauth - -import ( - "context" - "sync" - - oidc "github.com/coreos/go-oidc" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - configPath string = "config" - rolePrefix string = "role/" -) - -// Factory is used by framework -func Factory(ctx context.Context, c *logical.BackendConfig) (logical.Backend, error) { - b := backend(c) - if err := b.Setup(ctx, c); err != nil { - return nil, err - } - return b, nil -} - -type jwtAuthBackend struct { - *framework.Backend - - l sync.RWMutex - provider *oidc.Provider - cachedConfig *jwtConfig - - providerCtx context.Context - providerCtxCancel context.CancelFunc -} - -func backend(c *logical.BackendConfig) *jwtAuthBackend { - b := new(jwtAuthBackend) - b.providerCtx, b.providerCtxCancel = context.WithCancel(context.Background()) - - b.Backend = &framework.Backend{ - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - Invalidate: b.invalidate, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - SealWrapStorage: []string{ - "config", - }, - }, - Paths: framework.PathAppend( - []*framework.Path{ - pathLogin(b), - pathRoleList(b), - pathRole(b), - pathConfig(b), - }, - ), - Clean: b.cleanup, - } - - return b -} - -func (b *jwtAuthBackend) cleanup(_ context.Context) { - b.l.Lock() - if b.providerCtxCancel != nil { - b.providerCtxCancel() - } - b.l.Unlock() -} - -func (b *jwtAuthBackend) invalidate(ctx context.Context, key string) { - switch key { - case "config": - b.reset() - } -} - -func (b *jwtAuthBackend) reset() { - b.l.Lock() - b.provider = nil - b.cachedConfig = nil - b.l.Unlock() -} - -func (b *jwtAuthBackend) getProvider(ctx context.Context, config *jwtConfig) (*oidc.Provider, error) { - b.l.RLock() - unlockFunc := b.l.RUnlock - defer func() { unlockFunc() }() - - if b.provider != nil { - return b.provider, nil - } - - b.l.RUnlock() - b.l.Lock() - unlockFunc = b.l.Unlock - - if b.provider != nil { - return b.provider, nil - } - - provider, err := b.createProvider(config) - if err != nil { - return nil, err - } - - b.provider = provider - return provider, nil -} - -const ( - backendHelp = ` -The JWT backend plugin allows authentication using JWTs (including OIDC). -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_config.go b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_config.go deleted file mode 100644 index 2f13db15f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_config.go +++ /dev/null @@ -1,217 +0,0 @@ -package jwtauth - -import ( - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "net/http" - - "context" - - oidc "github.com/coreos/go-oidc" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/oauth2" -) - -func pathConfig(b *jwtAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: `config`, - Fields: map[string]*framework.FieldSchema{ - "oidc_discovery_url": { - Type: framework.TypeString, - Description: `OIDC Discovery URL, without any .well-known component (base path). Cannot be used with "jwt_validation_pubkeys".`, - }, - "oidc_discovery_ca_pem": { - Type: framework.TypeString, - Description: "The CA certificate or chain of certificates, in PEM format, to use to validate conections to the OIDC Discovery URL. If not set, system certificates are used.", - }, - "jwt_validation_pubkeys": { - Type: framework.TypeCommaStringSlice, - Description: `A list of PEM-encoded public keys to use to authenticate signatures locally. Cannot be used with "oidc_discovery_url".`, - }, - "jwt_supported_algs": { - Type: framework.TypeCommaStringSlice, - Description: `A list of supported signing algorithms. Defaults to RS256.`, - }, - "bound_issuer": { - Type: framework.TypeString, - Description: "The value against which to match the 'iss' claim in a JWT. Optional.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.UpdateOperation: b.pathConfigWrite, - }, - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -func (b *jwtAuthBackend) config(ctx context.Context, s logical.Storage) (*jwtConfig, error) { - b.l.RLock() - defer b.l.RUnlock() - - if b.cachedConfig != nil { - return b.cachedConfig, nil - } - - entry, err := s.Get(ctx, configPath) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - result := &jwtConfig{} - if entry != nil { - if err := entry.DecodeJSON(result); err != nil { - return nil, err - } - } - - for _, v := range result.JWTValidationPubKeys { - key, err := certutil.ParsePublicKeyPEM([]byte(v)) - if err != nil { - return nil, errwrap.Wrapf("error parsing public key: {{err}}", err) - } - result.ParsedJWTPubKeys = append(result.ParsedJWTPubKeys, key) - } - - b.cachedConfig = result - - return result, nil -} - -func (b *jwtAuthBackend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "oidc_discovery_url": config.OIDCDiscoveryURL, - "oidc_discovery_ca_pem": config.OIDCDiscoveryCAPEM, - "jwt_validation_pubkeys": config.JWTValidationPubKeys, - "jwt_supported_algs": config.JWTSupportedAlgs, - "bound_issuer": config.BoundIssuer, - }, - } - - return resp, nil -} - -func (b *jwtAuthBackend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - config := &jwtConfig{ - OIDCDiscoveryURL: d.Get("oidc_discovery_url").(string), - OIDCDiscoveryCAPEM: d.Get("oidc_discovery_ca_pem").(string), - JWTValidationPubKeys: d.Get("jwt_validation_pubkeys").([]string), - JWTSupportedAlgs: d.Get("jwt_supported_algs").([]string), - BoundIssuer: d.Get("bound_issuer").(string), - } - - // Run checks on values - switch { - case config.OIDCDiscoveryURL == "" && len(config.JWTValidationPubKeys) == 0, - config.OIDCDiscoveryURL != "" && len(config.JWTValidationPubKeys) != 0: - return logical.ErrorResponse("exactly one of 'oidc_discovery_url' and 'jwt_validation_pubkeys' must be set"), nil - - case config.OIDCDiscoveryURL != "": - _, err := b.createProvider(config) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error checking discovery URL: {{err}}", err).Error()), nil - } - - case len(config.JWTValidationPubKeys) != 0: - for _, v := range config.JWTValidationPubKeys { - if _, err := certutil.ParsePublicKeyPEM([]byte(v)); err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing public key: {{err}}", err).Error()), nil - } - } - - case len(config.JWTSupportedAlgs) != 0: - for _, a := range config.JWTSupportedAlgs { - switch a { - case oidc.RS256, oidc.RS384, oidc.RS512, oidc.ES256, oidc.ES384, oidc.ES512, oidc.PS256, oidc.PS384, oidc.PS512: - default: - return logical.ErrorResponse(fmt.Sprintf("Invalid supported algorithm: %s", a)), nil - } - } - - default: - return nil, errors.New("unknown condition") - } - - entry, err := logical.StorageEntryJSON(configPath, config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - b.reset() - - return nil, nil -} - -func (b *jwtAuthBackend) createProvider(config *jwtConfig) (*oidc.Provider, error) { - var certPool *x509.CertPool - if config.OIDCDiscoveryCAPEM != "" { - certPool = x509.NewCertPool() - if ok := certPool.AppendCertsFromPEM([]byte(config.OIDCDiscoveryCAPEM)); !ok { - return nil, errors.New("could not parse 'oidc_discovery_ca_pem' value successfully") - } - } - - tr := cleanhttp.DefaultPooledTransport() - if certPool != nil { - tr.TLSClientConfig = &tls.Config{ - RootCAs: certPool, - } - } - tc := &http.Client{ - Transport: tr, - } - oidcCtx := context.WithValue(b.providerCtx, oauth2.HTTPClient, tc) - - provider, err := oidc.NewProvider(oidcCtx, config.OIDCDiscoveryURL) - if err != nil { - return nil, errwrap.Wrapf("error creating provider with given values: {{err}}", err) - } - - return provider, nil -} - -type jwtConfig struct { - OIDCDiscoveryURL string `json:"oidc_discovery_url"` - OIDCDiscoveryCAPEM string `json:"oidc_discovery_ca_pem"` - JWTValidationPubKeys []string `json:"jwt_validation_pubkeys"` - JWTSupportedAlgs []string `json:"jwt_supported_algs"` - BoundIssuer string `json:"bound_issuer"` - - ParsedJWTPubKeys []interface{} `json:"-"` -} - -const ( - confHelpSyn = ` -Configures the JWT authentication backend. -` - confHelpDesc = ` -The JWT authentication backend validates JWTs (or OIDC) using the configured -credentials. If using OIDC Discovery, the URL must be provided, along -with (optionally) the CA cert to use for the connection. If performing JWT -validation locally, a set of public keys must be provided. -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_login.go deleted file mode 100644 index 0b515ab5f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_login.go +++ /dev/null @@ -1,287 +0,0 @@ -package jwtauth - -import ( - "context" - "errors" - "fmt" - "time" - - oidc "github.com/coreos/go-oidc" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "gopkg.in/square/go-jose.v2/jwt" -) - -func pathLogin(b *jwtAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: `login$`, - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeLowerCaseString, - Description: "The role to log in against.", - }, - "jwt": { - Type: framework.TypeString, - Description: "The signed JWT to validate.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLogin, - }, - - HelpSynopsis: pathLoginHelpSyn, - HelpDescription: pathLoginHelpDesc, - } -} - -func (b *jwtAuthBackend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - token := d.Get("jwt").(string) - if len(token) == 0 { - return logical.ErrorResponse("missing token"), nil - } - - roleName := d.Get("role").(string) - if len(roleName) == 0 { - return logical.ErrorResponse("missing role"), nil - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse("role could not be found"), nil - } - - if req.Connection != nil && !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, role.BoundCIDRs) { - return logical.ErrorResponse("request originated from invalid CIDR"), nil - } - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return logical.ErrorResponse("could not load configuration"), nil - } - - // Here is where things diverge. If it is using OIDC Discovery, validate - // that way; otherwise validate against the locally configured keys. Once - // things are validated, we re-unify the request path when evaluating the - // claims. - allClaims := map[string]interface{}{} - switch { - case len(config.ParsedJWTPubKeys) != 0: - parsedJWT, err := jwt.ParseSigned(token) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing token: {{err}}", err).Error()), nil - } - - claims := jwt.Claims{} - - var valid bool - for _, key := range config.ParsedJWTPubKeys { - if err := parsedJWT.Claims(key, &claims, &allClaims); err == nil { - valid = true - break - } - } - if !valid { - return logical.ErrorResponse("no known key successfully validated the token signature"), nil - } - - // We require notbefore or expiry; if only one is provided, we allow 5 minutes of leeway. - if claims.IssuedAt == 0 && claims.Expiry == 0 && claims.NotBefore == 0 { - return logical.ErrorResponse("no issue time, notbefore, or expiration time encoded in token"), nil - } - if claims.Expiry == 0 { - latestStart := claims.IssuedAt - if claims.NotBefore > claims.IssuedAt { - latestStart = claims.NotBefore - } - claims.Expiry = latestStart + 300 - } - if claims.NotBefore == 0 { - if claims.IssuedAt != 0 { - claims.NotBefore = claims.IssuedAt - } else { - claims.NotBefore = claims.Expiry - 300 - } - } - - if len(claims.Audience) > 0 && len(role.BoundAudiences) == 0 { - return logical.ErrorResponse("audience claim found in JWT but no audiences bound to the role"), nil - } - - expected := jwt.Expected{ - Issuer: config.BoundIssuer, - Subject: role.BoundSubject, - Audience: jwt.Audience(role.BoundAudiences), - Time: time.Now(), - } - - if err := claims.Validate(expected); err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error validating claims: {{err}}", err).Error()), nil - } - - case config.OIDCDiscoveryURL != "": - provider, err := b.getProvider(ctx, config) - if err != nil { - return nil, errwrap.Wrapf("error getting provider for login operation: {{err}}", err) - } - - verifier := provider.Verifier(&oidc.Config{ - SkipClientIDCheck: true, - SupportedSigningAlgs: config.JWTSupportedAlgs, - }) - - idToken, err := verifier.Verify(ctx, token) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error validating signature: {{err}}", err).Error()), nil - } - - if err := idToken.Claims(&allClaims); err != nil { - return logical.ErrorResponse(errwrap.Wrapf("unable to successfully parse all claims from token: {{err}}", err).Error()), nil - } - - if role.BoundSubject != "" && role.BoundSubject != idToken.Subject { - return logical.ErrorResponse("sub claim does not match bound subject"), nil - } - if len(role.BoundAudiences) != 0 { - var found bool - for _, v := range role.BoundAudiences { - if strutil.StrListContains(idToken.Audience, v) { - found = true - break - } - } - if !found { - return logical.ErrorResponse("aud claim does not match any bound audience"), nil - } - } - - default: - return nil, errors.New("unhandled case during login") - } - - userClaimRaw, ok := allClaims[role.UserClaim] - if !ok { - return logical.ErrorResponse(fmt.Sprintf("%q claim not found in token", role.UserClaim)), nil - } - userName, ok := userClaimRaw.(string) - if !ok { - return logical.ErrorResponse(fmt.Sprintf("%q claim could not be converted to string", role.UserClaim)), nil - } - - var groupAliases []*logical.Alias - if role.GroupsClaim != "" { - mapPath, err := parseClaimWithDelimiters(role.GroupsClaim, role.GroupsClaimDelimiterPattern) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing delimiters for groups claim: {{err}}", err).Error()), nil - } - if len(mapPath) < 1 { - return logical.ErrorResponse("unexpected length 0 of claims path after parsing groups claim against delimiters"), nil - } - var claimKey string - claimMap := allClaims - for i, key := range mapPath { - if i == len(mapPath)-1 { - claimKey = key - break - } - nextMapRaw, ok := claimMap[key] - if !ok { - return logical.ErrorResponse(fmt.Sprintf("map via key %q not found while navigating group claim delimiters", key)), nil - } - nextMap, ok := nextMapRaw.(map[string]interface{}) - if !ok { - return logical.ErrorResponse(fmt.Sprintf("key %q does not reference a map while navigating group claim delimiters", key)), nil - } - claimMap = nextMap - } - - groupsClaimRaw, ok := claimMap[claimKey] - if !ok { - return logical.ErrorResponse(fmt.Sprintf("%q claim not found in token", role.GroupsClaim)), nil - } - groups, ok := groupsClaimRaw.([]interface{}) - if !ok { - return logical.ErrorResponse(fmt.Sprintf("%q claim could not be converted to string list", role.GroupsClaim)), nil - } - for _, groupRaw := range groups { - group, ok := groupRaw.(string) - if !ok { - return logical.ErrorResponse(fmt.Sprintf("value %v in groups claim could not be parsed as string", groupRaw)), nil - } - if group == "" { - continue - } - groupAliases = append(groupAliases, &logical.Alias{ - Name: group, - }) - } - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - Policies: role.Policies, - DisplayName: userName, - Period: role.Period, - NumUses: role.NumUses, - Alias: &logical.Alias{ - Name: userName, - }, - GroupAliases: groupAliases, - InternalData: map[string]interface{}{ - "role": roleName, - }, - Metadata: map[string]string{ - "role": roleName, - }, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - BoundCIDRs: role.BoundCIDRs, - }, - } - - return resp, nil -} - -func (b *jwtAuthBackend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := req.Auth.InternalData["role"].(string) - if roleName == "" { - return nil, errors.New("failed to fetch role_name during renewal") - } - - // Ensure that the Role still exists. - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %s during renewal: {{err}}", roleName), err) - } - if role == nil { - return nil, fmt.Errorf("role %s does not exist during renewal", roleName) - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = role.TTL - resp.Auth.MaxTTL = role.MaxTTL - resp.Auth.Period = role.Period - return resp, nil -} - -const ( - pathLoginHelpSyn = ` - Authenticates to Vault using a JWT (or OIDC) token. - ` - pathLoginHelpDesc = ` -Authenticates JWTs. -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_role.go b/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_role.go deleted file mode 100644 index 9ca1fec41..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-jwt/path_role.go +++ /dev/null @@ -1,382 +0,0 @@ -package jwtauth - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathRoleList(b *jwtAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]), - } -} - -// pathRole returns the path configurations for the CRUD operations on roles -func pathRole(b *jwtAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeLowerCaseString, - Description: "Name of the role.", - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "List of policies on the role.", - }, - "num_uses": { - Type: framework.TypeInt, - Description: `Number of times issued tokens can be used`, - }, - "ttl": { - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should not be allowed to -be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "period": { - Type: framework.TypeDurationSecond, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - "bound_subject": { - Type: framework.TypeString, - Description: `The 'sub' claim that is valid for login. Optional.`, - }, - "bound_audiences": { - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of 'aud' claims that are valid for login; any match is sufficient`, - }, - "user_claim": { - Type: framework.TypeString, - Description: `The claim to use for the Identity entity alias name`, - }, - "groups_claim": { - Type: framework.TypeString, - Description: `The claim to use for the Identity group alias names`, - }, - "groups_claim_delimiter_pattern": { - Type: framework.TypeString, - Description: `A pattern of delimiters used to allow the groups_claim to live outside of the top-level JWT structure. For instance, a "groups_claim" of "meta/user.name/groups" with this field set to "//" will expect nested structures named "meta", "user.name", and "groups". If this field was set to "/./" the groups information would expect to be via nested structures of "meta", "user", "name", and "groups".`, - }, - "bound_cidrs": { - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of IP CIDRS that are allowed to -authenticate against this role`, - }, - }, - ExistenceCheck: b.pathRoleExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathRoleCreateUpdate, - logical.UpdateOperation: b.pathRoleCreateUpdate, - logical.ReadOperation: b.pathRoleRead, - logical.DeleteOperation: b.pathRoleDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role"][1]), - } -} - -type jwtRole struct { - // Policies that are to be required by the token to access this role - Policies []string `json:"policies"` - - // TokenNumUses defines the number of allowed uses of the token issued - NumUses int `json:"num_uses"` - - // Duration before which an issued token must be renewed - TTL time.Duration `json:"ttl"` - - // Duration after which an issued token should not be allowed to be renewed - MaxTTL time.Duration `json:"max_ttl"` - - // Period, if set, indicates that the token generated using this role - // should never expire. The token should be renewed within the duration - // specified by this value. The renewal duration will be fixed if the - // value is not modified on the role. If the `Period` in the role is modified, - // a token will pick up the new value during its next renewal. - Period time.Duration `json:"period"` - - // Role binding properties - BoundAudiences []string `json:"bound_audiences"` - BoundSubject string `json:"bound_subject"` - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` - UserClaim string `json:"user_claim"` - GroupsClaim string `json:"groups_claim"` - GroupsClaimDelimiterPattern string `json:"groups_claim_delimiter_pattern"` -} - -// role takes a storage backend and the name and returns the role's storage -// entry -func (b *jwtAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*jwtRole, error) { - raw, err := s.Get(ctx, rolePrefix+name) - if err != nil { - return nil, err - } - if raw == nil { - return nil, nil - } - - role := new(jwtRole) - if err := raw.DecodeJSON(role); err != nil { - return nil, err - } - - return role, nil -} - -// pathRoleExistenceCheck returns whether the role with the given name exists or not. -func (b *jwtAuthBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - role, err := b.role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - return role != nil, nil -} - -// pathRoleList is used to list all the Roles registered with the backend. -func (b *jwtAuthBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roles, err := req.Storage.List(ctx, rolePrefix) - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil -} - -// pathRoleRead grabs a read lock and reads the options set on the role from the storage -func (b *jwtAuthBackend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing name"), nil - } - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Create a map of data to be returned - resp := &logical.Response{ - Data: map[string]interface{}{ - "policies": role.Policies, - "num_uses": role.NumUses, - "period": int64(role.Period.Seconds()), - "ttl": int64(role.TTL.Seconds()), - "max_ttl": int64(role.MaxTTL.Seconds()), - "bound_audiences": role.BoundAudiences, - "bound_subject": role.BoundSubject, - "bound_cidrs": role.BoundCIDRs, - "user_claim": role.UserClaim, - "groups_claim": role.GroupsClaim, - "groups_claim_delimiter_pattern": role.GroupsClaimDelimiterPattern, - }, - } - - return resp, nil -} - -// pathRoleDelete removes the role from storage -func (b *jwtAuthBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("role name required"), nil - } - - // Delete the role itself - if err := req.Storage.Delete(ctx, rolePrefix+roleName); err != nil { - return nil, err - } - - return nil, nil -} - -// pathRoleCreateUpdate registers a new role with the backend or updates the options -// of an existing role -func (b *jwtAuthBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - // Check if the role already exists - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - // Create a new entry object if this is a CreateOperation - if role == nil { - if req.Operation == logical.UpdateOperation { - return nil, errors.New("role entry not found during update operation") - } - role = new(jwtRole) - } - - if policiesRaw, ok := data.GetOk("policies"); ok { - role.Policies = policyutil.ParsePolicies(policiesRaw) - } - - periodRaw, ok := data.GetOk("period") - if ok { - role.Period = time.Duration(periodRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.Period = time.Duration(data.Get("period").(int)) * time.Second - } - if role.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("'period' of '%q' is greater than the backend's maximum lease TTL of '%q'", role.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - - if tokenNumUsesRaw, ok := data.GetOk("num_uses"); ok { - role.NumUses = tokenNumUsesRaw.(int) - } else if req.Operation == logical.CreateOperation { - role.NumUses = data.Get("num_uses").(int) - } - if role.NumUses < 0 { - return logical.ErrorResponse("num_uses cannot be negative"), nil - } - - if tokenTTLRaw, ok := data.GetOk("ttl"); ok { - role.TTL = time.Duration(tokenTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.TTL = time.Duration(data.Get("ttl").(int)) * time.Second - } - - if tokenMaxTTLRaw, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(tokenMaxTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second - } - - if boundAudiences, ok := data.GetOk("bound_audiences"); ok { - role.BoundAudiences = boundAudiences.([]string) - } - - if boundSubject, ok := data.GetOk("bound_subject"); ok { - role.BoundSubject = boundSubject.(string) - } - - if boundCIDRs, ok := data.GetOk("bound_cidrs"); ok { - parsedCIDRs, err := parseutil.ParseAddrs(boundCIDRs) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - role.BoundCIDRs = parsedCIDRs - } - - if userClaim, ok := data.GetOk("user_claim"); ok { - role.UserClaim = userClaim.(string) - } - if role.UserClaim == "" { - return logical.ErrorResponse("a user claim must be defined on the role"), nil - } - - if groupsClaim, ok := data.GetOk("groups_claim"); ok { - role.GroupsClaim = groupsClaim.(string) - } - - if groupsClaimDelimiterPattern, ok := data.GetOk("groups_claim_delimiter_pattern"); ok { - role.GroupsClaimDelimiterPattern = groupsClaimDelimiterPattern.(string) - } - - // Validate claim/delims - if role.GroupsClaim != "" { - if _, err := parseClaimWithDelimiters(role.GroupsClaim, role.GroupsClaimDelimiterPattern); err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error validating delimiters for groups claim: {{err}}", err).Error()), nil - } - } - - if len(role.BoundAudiences) == 0 && - len(role.BoundCIDRs) == 0 && - role.BoundSubject == "" { - return logical.ErrorResponse("must have at least one bound constraint when creating/updating a role"), nil - } - - // Check that the TTL value provided is less than the MaxTTL. - // Sanitizing the TTL and MaxTTL is not required now and can be performed - // at credential issue time. - if role.MaxTTL > 0 && role.TTL > role.MaxTTL { - return logical.ErrorResponse("ttl should not be greater than max_ttl"), nil - } - - var resp *logical.Response - if role.MaxTTL > b.System().MaxLeaseTTL() { - resp = &logical.Response{} - resp.AddWarning("max_ttl is greater than the system or backend mount's maximum TTL value; issued tokens' max TTL value will be truncated") - } - - // Store the entry. - entry, err := logical.StorageEntryJSON(rolePrefix+roleName, role) - if err != nil { - return nil, err - } - if err = req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return resp, nil -} - -// parseClaimWithDelimiters parses a given claim string and ensures that we can -// separate it out into a "map path" -func parseClaimWithDelimiters(claim, delimiters string) ([]string, error) { - if delimiters == "" { - return []string{claim}, nil - } - var ret []string - for _, runeVal := range delimiters { - idx := strings.IndexRune(claim, runeVal) - switch idx { - case -1: - return nil, fmt.Errorf("could not find instance of %q delimiter in claim", string(runeVal)) - case 0: - return nil, fmt.Errorf("instance of %q delimiter in claim is at beginning of claim string", string(runeVal)) - case len(claim) - 1: - return nil, fmt.Errorf("instance of %q delimiter in claim is at end of claim string", string(runeVal)) - default: - ret = append(ret, claim[:idx]) - claim = claim[idx+1:] - } - } - ret = append(ret, claim) - - return ret, nil -} - -// roleStorageEntry stores all the options that are set on an role -var roleHelp = map[string][2]string{ - "role-list": { - "Lists all the roles registered with the backend.", - "The list will contain the names of the roles.", - }, - "role": { - "Register an role with the backend.", - `A role is required to authenticate with this backend. The role binds - JWT token information with token policies and settings. - The bindings, token polices and token settings can all be configured - using this endpoint`, - }, -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.lock deleted file mode 100644 index 447240e3d..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.lock +++ /dev/null @@ -1,462 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - digest = "1:e26170d7ec7d444d7b74a5b1dbd6437fd8e552d27efce9327f733311737c4ae9" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "803625baeddc3526d01d321b5066029f53eafc81" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - digest = "1:b12a893d64eb4c4c1980240c5706026032f505fef4ecd7d4cbfa2ed60ecd40c9" - name = "github.com/briankassouf/jose" - packages = [ - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - digest = "1:34e709f36fd4f868fb00dbaf8a6cab4c1ae685832d392874ba9d7c5dec2429d1" - name = "github.com/gogo/protobuf" - packages = [ - "proto", - "sortkeys", - ] - pruneopts = "UT" - revision = "636bf0302bc95575d69441b25a2603156ffdddf1" - version = "v1.1.1" - -[[projects]] - branch = "master" - digest = "1:1ba1d79f2810270045c328ae5d674321db34e3aae468eb4233883b473c5c0467" - name = "github.com/golang/glog" - packages = ["."] - pruneopts = "UT" - revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:3ee90c0d94da31b442dde97c99635aaafec68d0b8a3c12ee2075c6bdabeec6bb" - name = "github.com/google/gofuzz" - packages = ["."] - pruneopts = "UT" - revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:d00de8725219a569ffbb5dd1042e4ced1f3b5ccee2b07218371f71026cc7609a" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/cidrutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/policyutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "add60e6dc7ff7b94487f3b5b680d00d7c05fe621" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - digest = "1:b5c3834d33445efdc5a8dcb154bed9e4c211edadbf02f6f5cc20c5e9be26a499" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:05662433b3a13c921587a6e622b5722072edff83211efd1cd79eeaeedfd83f07" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[[projects]] - digest = "1:2d1fbdc6777e5408cabeb02bf336305e724b925ff4546ded0fa8715a7267922a" - name = "gopkg.in/inf.v0" - packages = ["."] - pruneopts = "UT" - revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf" - version = "v0.9.1" - -[[projects]] - branch = "master" - digest = "1:6012060ff3ab84c40e066fea24583fe1a33525af615acfac7308e932eb06479d" - name = "k8s.io/api" - packages = ["authentication/v1"] - pruneopts = "UT" - revision = "f5c295feaba2cbc946f0bbb8b535fc5f6a0345ee" - -[[projects]] - branch = "master" - digest = "1:7bb4ed855d9dde814f348b1a9d18a5996d800c47b98481e880a8612641468527" - name = "k8s.io/apimachinery" - packages = [ - "pkg/api/errors", - "pkg/api/resource", - "pkg/apis/meta/v1", - "pkg/conversion", - "pkg/conversion/queryparams", - "pkg/fields", - "pkg/labels", - "pkg/runtime", - "pkg/runtime/schema", - "pkg/selection", - "pkg/types", - "pkg/util/errors", - "pkg/util/intstr", - "pkg/util/json", - "pkg/util/naming", - "pkg/util/net", - "pkg/util/runtime", - "pkg/util/sets", - "pkg/util/validation", - "pkg/util/validation/field", - "pkg/watch", - "third_party/forked/golang/reflect", - ] - pruneopts = "UT" - revision = "ef51ab160544f9d05b68e132a4af0b0fab459954" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/SermoDigital/jose/jws", - "github.com/briankassouf/jose/crypto", - "github.com/briankassouf/jose/jws", - "github.com/briankassouf/jose/jwt", - "github.com/hashicorp/errwrap", - "github.com/hashicorp/go-cleanhttp", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/go-multierror", - "github.com/hashicorp/go-sockaddr", - "github.com/hashicorp/vault/helper/cidrutil", - "github.com/hashicorp/vault/helper/logging", - "github.com/hashicorp/vault/helper/parseutil", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/helper/policyutil", - "github.com/hashicorp/vault/helper/strutil", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - "github.com/mitchellh/mapstructure", - "k8s.io/api/authentication/v1", - "k8s.io/apimachinery/pkg/api/errors", - "k8s.io/apimachinery/pkg/apis/meta/v1", - "k8s.io/apimachinery/pkg/runtime", - "k8s.io/apimachinery/pkg/runtime/schema", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.toml deleted file mode 100644 index 769b63311..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Gopkg.toml +++ /dev/null @@ -1,74 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - branch = "master" - name = "github.com/SermoDigital/jose" - -[[constraint]] - name = "github.com/briankassouf/jose" - version = "1.1.0" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/errwrap" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-multierror" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-sockaddr" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[[constraint]] - branch = "master" - name = "github.com/mitchellh/mapstructure" - -[[constraint]] - branch = "master" - name = "k8s.io/api" - -[[constraint]] - branch = "master" - name = "k8s.io/apimachinery" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/LICENSE b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Makefile b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Makefile deleted file mode 100644 index 6ab3bdc77..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -TOOL?=vault-plugin-auth-kubernetes -TEST?=$$(go list ./... | grep -v /vendor/) -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox \ - github.com/golang/dep/cmd/dep -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin, except for quickdev which -# is only put into /bin/ -quickdev: generate - @CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/vault-plugin-auth-kubernetes -dev: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" -dev-dynamic: generate - @CGO_ENABLED=1 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -# test runs the unit tests and vets the code -test: fmtcheck generate - CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -timeout=20m -parallel=4 - -testcompile: fmtcheck generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# testacc runs acceptance tests -testacc: fmtcheck generate - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 45m - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - gofmt -w $(GOFMT_FILES) - - -.PHONY: bin default generate test vet bootstrap fmt fmtcheck diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/README.md b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/README.md deleted file mode 100644 index 0f40e061e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/README.md +++ /dev/null @@ -1,131 +0,0 @@ -# Vault Plugin: Kubernetes Auth Backend - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin allows for Kubernetes Service Accounts to authenticate with Vault. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - Kubernetes Auth Docs: https://www.vaultproject.io/docs/auth/kubernetes.html - - Main Project Github: https://www.github.com/hashicorp/vault - - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Security Model - -The current authentication model requires providing Vault with a Service Account token, which can be used to make authenticated calls to Kubernetes. This token should not typically be shared, but in order for Kubernetes to be treated as a trusted third party, Vault must validate something that Kubernetes has cryptographically signed and that conveys the identity of the token holder. - -We expect Kubernetes to support less sensitive mechanisms in the future, and the Vault integration will be updated to use those mechanisms when available. - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/auth/kubernetes.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `auth/kubernetes`. To enable this in a running Vault server: - -```sh -$ vault auth-enable kubernetes -Successfully enabled 'kubernetes' at 'kubernetes'! -``` - -To see all the supported paths, see the [Kubernetes auth backend docs](https://www.vaultproject.io/docs/auth/kubernetes.html). - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine -(version 1.8+ is *required*). - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-auth-kubernetes`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/kubernetes \ - sha_256= \ - command="vault-plugin-auth-kubernetes" -... -Success! Data written to: sys/plugins/catalog/kubernetes -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-auth-kubernetes -... -SHA256(.../go/bin/vault-plugin-auth-kubernetes)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the Kubernetes auth plugin: - -```sh -$ vault auth-enable -plugin-name='kubernetes' plugin -... - -Successfully enabled 'plugin' at 'kubernetes'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/backend.go b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/backend.go deleted file mode 100644 index 8d9ed2fc3..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/backend.go +++ /dev/null @@ -1,118 +0,0 @@ -package kubeauth - -import ( - "context" - "encoding/json" - "fmt" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - configPath string = "config" - rolePrefix string = "role/" -) - -// kubeAuthBackend implements logical.Backend -type kubeAuthBackend struct { - *framework.Backend - - // reviewFactory is used to configure the strategy for doing a token review. - // Currently the only options are using the kubernetes API or mocking the - // review. Mocks should only be used in tests. - reviewFactory tokenReviewFactory - - l sync.RWMutex -} - -// Factory returns a new backend as logical.Backend. -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *kubeAuthBackend { - b := &kubeAuthBackend{} - - b.Backend = &framework.Backend{ - AuthRenew: b.pathLoginRenew(), - BackendType: logical.TypeCredential, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - SealWrapStorage: []string{ - configPath, - }, - }, - Paths: framework.PathAppend( - []*framework.Path{ - pathConfig(b), - pathLogin(b), - }, - pathsRole(b), - ), - } - - // Set the review factory to default to calling into the kubernetes API. - b.reviewFactory = tokenReviewAPIFactory - - return b -} - -// config takes a storage object and returns a kubeConfig object -func (b *kubeAuthBackend) config(ctx context.Context, s logical.Storage) (*kubeConfig, error) { - raw, err := s.Get(ctx, configPath) - if err != nil { - return nil, err - } - if raw == nil { - return nil, nil - } - - conf := &kubeConfig{} - if err := json.Unmarshal(raw.Value, conf); err != nil { - return nil, err - } - - // Parse the public keys from the CertificatesBytes - conf.PublicKeys = make([]interface{}, len(conf.PEMKeys)) - for i, cert := range conf.PEMKeys { - conf.PublicKeys[i], err = parsePublicKeyPEM([]byte(cert)) - if err != nil { - return nil, err - } - } - - return conf, nil -} - -// role takes a storage backend and the name and returns the role's storage -// entry -func (b *kubeAuthBackend) role(ctx context.Context, s logical.Storage, name string) (*roleStorageEntry, error) { - raw, err := s.Get(ctx, fmt.Sprintf("%s%s", rolePrefix, strings.ToLower(name))) - if err != nil { - return nil, err - } - if raw == nil { - return nil, nil - } - - role := &roleStorageEntry{} - if err := json.Unmarshal(raw.Value, role); err != nil { - return nil, err - } - - return role, nil -} - -var backendHelp string = ` -The Kubernetes Auth Backend allows authentication for Kubernetes service accounts. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_config.go b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_config.go deleted file mode 100644 index 0156d47f8..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_config.go +++ /dev/null @@ -1,175 +0,0 @@ -package kubeauth - -import ( - "context" - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathConfig returns the path configuration for CRUD operations on the backend -// configuration. -func pathConfig(b *kubeAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "config$", - Fields: map[string]*framework.FieldSchema{ - "kubernetes_host": { - Type: framework.TypeString, - Description: "Host must be a host string, a host:port pair, or a URL to the base of the Kubernetes API server.", - }, - "kubernetes_ca_cert": { - Type: framework.TypeString, - Description: "PEM encoded CA cert for use by the TLS client used to talk with the API.", - }, - "token_reviewer_jwt": { - Type: framework.TypeString, - Description: `A service account JWT used to access the -TokenReview API to validate other JWTs during login. If not set -the JWT used for login will be used to access the API.`, - }, - "pem_keys": { - Type: framework.TypeCommaStringSlice, - Description: `Optional list of PEM-formated public keys or certificates -used to verify the signatures of kubernetes service account -JWTs. If a certificate is given, its public key will be -extracted. Not every installation of Kuberentes exposes these keys.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigWrite(), - logical.CreateOperation: b.pathConfigWrite(), - logical.ReadOperation: b.pathConfigRead(), - }, - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -// pathConfigWrite handles create and update commands to the config -func (b *kubeAuthBackend) pathConfigRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if config, err := b.config(ctx, req.Storage); err != nil { - return nil, err - } else if config == nil { - return nil, nil - } else { - // Create a map of data to be returned - resp := &logical.Response{ - Data: map[string]interface{}{ - "kubernetes_host": config.Host, - "kubernetes_ca_cert": config.CACert, - "pem_keys": config.PEMKeys, - }, - } - - return resp, nil - } - } -} - -// pathConfigWrite handles create and update commands to the config -func (b *kubeAuthBackend) pathConfigWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - host := data.Get("kubernetes_host").(string) - if host == "" { - return logical.ErrorResponse("no host provided"), nil - } - - pemList := data.Get("pem_keys").([]string) - caCert := data.Get("kubernetes_ca_cert").(string) - if len(pemList) == 0 && len(caCert) == 0 { - return logical.ErrorResponse("one of pem_keys or kubernetes_ca_cert must be set"), nil - } - - tokenReviewer := data.Get("token_reviewer_jwt").(string) - if len(tokenReviewer) > 0 { - // Validate it's a JWT - _, err := jws.ParseJWT([]byte(tokenReviewer)) - if err != nil { - return nil, err - } - } - - config := &kubeConfig{ - PublicKeys: make([]interface{}, len(pemList)), - PEMKeys: pemList, - Host: host, - CACert: caCert, - TokenReviewerJWT: tokenReviewer, - } - - var err error - for i, pem := range pemList { - config.PublicKeys[i], err = parsePublicKeyPEM([]byte(pem)) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - } - - entry, err := logical.StorageEntryJSON(configPath, config) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil - } -} - -// kubeConfig contains the public key certificate used to verify the signature -// on the service account JWTs -type kubeConfig struct { - // PublicKeys is the list of public key objects used to verify JWTs - PublicKeys []interface{} `json:"-"` - // PEMKeys is the list of public key PEMs used to store the keys - // in storage. - PEMKeys []string `json:"pem_keys"` - // Host is the url string for the kubernetes API - Host string `json:"host"` - // CACert is the CA Cert to use to call into the kubernetes API - CACert string `json:"ca_cert"` - // TokenReviewJWT is the bearer to use during the TokenReview API call - TokenReviewerJWT string `json:"token_reviewer_jwt"` -} - -// PasrsePublicKeyPEM is used to parse RSA and ECDSA public keys from PEMs -func parsePublicKeyPEM(data []byte) (interface{}, error) { - block, data := pem.Decode(data) - if block != nil { - var rawKey interface{} - var err error - if rawKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - rawKey = cert.PublicKey - } else { - return nil, err - } - } - - if rsaPublicKey, ok := rawKey.(*rsa.PublicKey); ok { - return rsaPublicKey, nil - } - if ecPublicKey, ok := rawKey.(*ecdsa.PublicKey); ok { - return ecPublicKey, nil - } - } - - return nil, errors.New("data does not contain any valid RSA or ECDSA public keys") -} - -const confHelpSyn = `Configures the JWT Public Key and Kubernetes API information.` -const confHelpDesc = ` -The Kubernetes Auth backend validates service account JWTs and verifies their -existence with the Kubernetes TokenReview API. This endpoint configures the -public key used to validate the JWT signature and the necessary information to -access the Kubernetes API. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_login.go b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_login.go deleted file mode 100644 index ac8a82017..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_login.go +++ /dev/null @@ -1,343 +0,0 @@ -package kubeauth - -import ( - "context" - "crypto/ecdsa" - "crypto/rsa" - "errors" - "fmt" - - "github.com/briankassouf/jose/crypto" - "github.com/briankassouf/jose/jws" - "github.com/briankassouf/jose/jwt" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -var ( - // expectedJWTIssuer is used to verify the iss header on the JWT. - expectedJWTIssuer string = "kubernetes/serviceaccount" - - uidJWTClaimKey string = "kubernetes.io/serviceaccount/service-account.uid" - - // errMismatchedSigningMethod is used if the certificate doesn't match the - // JWT's expected signing method. - errMismatchedSigningMethod = errors.New("invalid signing method") -) - -// pathLogin returns the path configurations for login endpoints -func pathLogin(b *kubeAuthBackend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeString, - Description: `Name of the role against which the login is being attempted. This field is required`, - }, - "jwt": { - Type: framework.TypeString, - Description: `A signed JWT for authenticating a service account. This field is required.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin(), - logical.AliasLookaheadOperation: b.aliasLookahead(), - }, - - HelpSynopsis: pathLoginHelpSyn, - HelpDescription: pathLoginHelpDesc, - } -} - -// pathLogin is used to authenticate to this backend -func (b *kubeAuthBackend) pathLogin() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role").(string) - if len(roleName) == 0 { - return logical.ErrorResponse("missing role"), nil - } - - jwtStr := data.Get("jwt").(string) - if len(jwtStr) == 0 { - return logical.ErrorResponse("missing jwt"), nil - } - - b.l.RLock() - defer b.l.RUnlock() - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid role name \"%s\"", roleName)), nil - } - - // Check for a CIDR match. - if req.Connection != nil && !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, role.BoundCIDRs) { - return logical.ErrorResponse("request originated from invalid CIDR"), nil - } - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, errors.New("could not load backend configuration") - } - - serviceAccount, err := b.parseAndValidateJWT(jwtStr, role, config) - if err != nil { - return nil, err - } - - // look up the JWT token in the kubernetes API - err = serviceAccount.lookup(jwtStr, b.reviewFactory(config)) - if err != nil { - return nil, err - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - NumUses: role.NumUses, - Period: role.Period, - Alias: &logical.Alias{ - Name: serviceAccount.UID, - }, - InternalData: map[string]interface{}{ - "role": roleName, - }, - Policies: role.Policies, - Metadata: map[string]string{ - "service_account_uid": serviceAccount.UID, - "service_account_name": serviceAccount.Name, - "service_account_namespace": serviceAccount.Namespace, - "service_account_secret_name": serviceAccount.SecretName, - "role": roleName, - }, - DisplayName: fmt.Sprintf("%s-%s", serviceAccount.Namespace, serviceAccount.Name), - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TTL, - MaxTTL: role.MaxTTL, - }, - BoundCIDRs: role.BoundCIDRs, - }, - } - - return resp, nil - } -} - -// aliasLookahead returns the alias object with the SA UID from the JWT -// Claims. -func (b *kubeAuthBackend) aliasLookahead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - jwtStr := data.Get("jwt").(string) - if len(jwtStr) == 0 { - return logical.ErrorResponse("missing jwt"), nil - } - - // Parse into JWT - parsedJWT, err := jws.ParseJWT([]byte(jwtStr)) - if err != nil { - return nil, err - } - - saUID, ok := parsedJWT.Claims().Get(uidJWTClaimKey).(string) - if !ok || saUID == "" { - return nil, errors.New("could not parse UID from claims") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: saUID, - }, - }, - }, nil - } -} - -// parseAndValidateJWT is used to parse, validate and lookup the JWT token. -func (b *kubeAuthBackend) parseAndValidateJWT(jwtStr string, role *roleStorageEntry, config *kubeConfig) (*serviceAccount, error) { - // Parse into JWT - parsedJWT, err := jws.ParseJWT([]byte(jwtStr)) - if err != nil { - return nil, err - } - - sa := &serviceAccount{} - validator := &jwt.Validator{ - Expected: jwt.Claims{ - "iss": expectedJWTIssuer, - }, - Fn: func(c jwt.Claims) error { - // Decode claims into a service account object - err := mapstructure.Decode(c, sa) - if err != nil { - return err - } - - // verify the namespace is allowed - if len(role.ServiceAccountNamespaces) > 1 || role.ServiceAccountNamespaces[0] != "*" { - if !strutil.StrListContains(role.ServiceAccountNamespaces, sa.Namespace) { - return errors.New("namespace not authorized") - } - } - - // verify the service account name is allowed - if len(role.ServiceAccountNames) > 1 || role.ServiceAccountNames[0] != "*" { - if !strutil.StrListContains(role.ServiceAccountNames, sa.Name) { - return errors.New("service account name not authorized") - } - } - - return nil - }, - } - - if err := validator.Validate(parsedJWT); err != nil { - return nil, err - } - - // If we don't have any public keys to verify, return the sa and end early. - if len(config.PublicKeys) == 0 { - return sa, nil - } - - // verifyFunc is called for each certificate that is configured in the - // backend until one of the certificates succeeds. - verifyFunc := func(cert interface{}) error { - // Parse Headers and verify the signing method matches the public key type - // configured. This is done in its own scope since we don't need most of - // these variables later. - var signingMethod crypto.SigningMethod - { - parsedJWS, err := jws.Parse([]byte(jwtStr)) - if err != nil { - return err - } - headers := parsedJWS.Protected() - - var algStr string - if headers.Has("alg") { - algStr = headers.Get("alg").(string) - } else { - return errors.New("provided JWT must have 'alg' header value") - } - - signingMethod = jws.GetSigningMethod(algStr) - switch signingMethod.(type) { - case *crypto.SigningMethodECDSA: - if _, ok := cert.(*ecdsa.PublicKey); !ok { - return errMismatchedSigningMethod - } - case *crypto.SigningMethodRSA: - if _, ok := cert.(*rsa.PublicKey); !ok { - return errMismatchedSigningMethod - } - default: - return errors.New("unsupported JWT signing method") - } - } - - // validates the signature and then runs the claim validation - if err := parsedJWT.Validate(cert, signingMethod); err != nil { - return err - } - - return nil - } - - var validationErr error - // for each configured certificate run the verifyFunc - for _, cert := range config.PublicKeys { - err := verifyFunc(cert) - switch err { - case nil: - return sa, nil - case rsa.ErrVerification, crypto.ErrECDSAVerification, errMismatchedSigningMethod: - // if the error is a failure to verify or a signing method mismatch - // continue onto the next cert, storing the error to be returned if - // this is the last cert. - validationErr = multierror.Append(validationErr, errwrap.Wrapf("failed to validate JWT: {{err}}", err)) - continue - default: - return nil, err - } - } - - return nil, validationErr -} - -// serviceAccount holds the metadata from the JWT token and is used to lookup -// the JWT in the kubernetes API and compare the results. -type serviceAccount struct { - Name string `mapstructure:"kubernetes.io/serviceaccount/service-account.name"` - UID string `mapstructure:"kubernetes.io/serviceaccount/service-account.uid"` - SecretName string `mapstructure:"kubernetes.io/serviceaccount/secret.name"` - Namespace string `mapstructure:"kubernetes.io/serviceaccount/namespace"` -} - -// lookup calls the TokenReview API in kubernetes to verify the token and secret -// still exist. -func (s *serviceAccount) lookup(jwtStr string, tr tokenReviewer) error { - r, err := tr.Review(jwtStr) - if err != nil { - return err - } - - // Verify the returned metadata matches the expected data from the service - // account. - if s.Name != r.Name { - return errors.New("JWT names did not match") - } - if s.UID != r.UID { - return errors.New("JWT UIDs did not match") - } - if s.Namespace != r.Namespace { - return errors.New("JWT namepaces did not match") - } - - return nil -} - -// Invoked when the token issued by this backend is attempting a renewal. -func (b *kubeAuthBackend) pathLoginRenew() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := req.Auth.InternalData["role"].(string) - if roleName == "" { - return nil, fmt.Errorf("failed to fetch role_name during renewal") - } - - b.l.RLock() - defer b.l.RUnlock() - - // Ensure that the Role still exists. - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, fmt.Errorf("failed to validate role %s during renewal:%s", roleName, err) - } - if role == nil { - return nil, fmt.Errorf("role %s does not exist during renewal", roleName) - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = role.TTL - resp.Auth.MaxTTL = role.MaxTTL - resp.Auth.Period = role.Period - return resp, nil - } -} - -const pathLoginHelpSyn = `Authenticates Kubernetes service accounts with Vault.` -const pathLoginHelpDesc = ` -Authenticate Kubernetes service accounts. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_role.go b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_role.go deleted file mode 100644 index 19f7a9faf..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/path_role.go +++ /dev/null @@ -1,354 +0,0 @@ -package kubeauth - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathsRole returns the path configurations for the CRUD operations on roles -func pathsRole(b *kubeAuthBackend) []*framework.Path { - return []*framework.Path{ - &framework.Path{ - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList(), - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "bound_service_account_names": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `List of service account names able to access this role. If set to "*" all names -are allowed, both this and bound_service_account_namespaces can not be "*"`, - }, - "bound_service_account_namespaces": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `List of namespaces allowed to access this role. If set to "*" all namespaces -are allowed, both this and bound_service_account_names can not be set to "*"`, - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "List of policies on the role.", - }, - "num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of times issued tokens can be used`, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should not be allowed to -be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - "bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - }, - ExistenceCheck: b.pathRoleExistenceCheck(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathRoleCreateUpdate(), - logical.UpdateOperation: b.pathRoleCreateUpdate(), - logical.ReadOperation: b.pathRoleRead(), - logical.DeleteOperation: b.pathRoleDelete(), - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role"][1]), - }, - } -} - -// pathRoleExistenceCheck returns whether the role with the given name exists or not. -func (b *kubeAuthBackend) pathRoleExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - b.l.RLock() - defer b.l.RUnlock() - - role, err := b.role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - return role != nil, nil - } -} - -// pathRoleList is used to list all the Roles registered with the backend. -func (b *kubeAuthBackend) pathRoleList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.l.RLock() - defer b.l.RUnlock() - - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil - } -} - -// pathRoleRead grabs a read lock and reads the options set on the role from the storage -func (b *kubeAuthBackend) pathRoleRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing name"), nil - } - - b.l.RLock() - defer b.l.RUnlock() - - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Convert the 'time.Duration' values to second. - role.TTL /= time.Second - role.MaxTTL /= time.Second - role.Period /= time.Second - - // Create a map of data to be returned - resp := &logical.Response{ - Data: map[string]interface{}{ - "bound_service_account_names": role.ServiceAccountNames, - "bound_service_account_namespaces": role.ServiceAccountNamespaces, - "max_ttl": role.MaxTTL, - "num_uses": role.NumUses, - "policies": role.Policies, - "period": role.Period, - "ttl": role.TTL, - "bound_cidrs": role.BoundCIDRs, - }, - } - - return resp, nil - } -} - -// pathRoleDelete removes the role from storage -func (b *kubeAuthBackend) pathRoleDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - // Acquire the lock before deleting the role. - b.l.Lock() - defer b.l.Unlock() - - // Delete the role itself - if err := req.Storage.Delete(ctx, "role/"+strings.ToLower(roleName)); err != nil { - return nil, err - } - - return nil, nil - } -} - -// pathRoleCreateUpdate registers a new role with the backend or updates the options -// of an existing role -func (b *kubeAuthBackend) pathRoleCreateUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - b.l.Lock() - defer b.l.Unlock() - - // Check if the role already exists - role, err := b.role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - // Create a new entry object if this is a CreateOperation - if role == nil && req.Operation == logical.CreateOperation { - role = &roleStorageEntry{} - } else if role == nil { - return nil, fmt.Errorf("role entry not found during update operation") - } - - if policiesRaw, ok := data.GetOk("policies"); ok { - role.Policies = policyutil.ParsePolicies(policiesRaw) - } - - periodRaw, ok := data.GetOk("period") - if ok { - role.Period = time.Second * time.Duration(periodRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.Period = time.Second * time.Duration(data.Get("period").(int)) - } - if role.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("'period' of '%q' is greater than the backend's maximum lease TTL of '%q'", role.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - - if tokenNumUsesRaw, ok := data.GetOk("num_uses"); ok { - role.NumUses = tokenNumUsesRaw.(int) - } else if req.Operation == logical.CreateOperation { - role.NumUses = data.Get("num_uses").(int) - } - if role.NumUses < 0 { - return logical.ErrorResponse("num_uses cannot be negative"), nil - } - - if tokenTTLRaw, ok := data.GetOk("ttl"); ok { - role.TTL = time.Second * time.Duration(tokenTTLRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.TTL = time.Second * time.Duration(data.Get("ttl").(int)) - } - - if tokenMaxTTLRaw, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Second * time.Duration(tokenMaxTTLRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.MaxTTL = time.Second * time.Duration(data.Get("max_ttl").(int)) - } - - // Check that the TTL value provided is less than the MaxTTL. - // Sanitizing the TTL and MaxTTL is not required now and can be performed - // at credential issue time. - if role.MaxTTL > time.Duration(0) && role.TTL > role.MaxTTL { - return logical.ErrorResponse("ttl should not be greater than max_ttl"), nil - } - - var resp *logical.Response - if role.MaxTTL > b.System().MaxLeaseTTL() { - resp = &logical.Response{} - resp.AddWarning("max_ttl is greater than the system or backend mount's maximum TTL value; issued tokens' max TTL value will be truncated") - } - - if serviceAccountUUIDs, ok := data.GetOk("bound_service_account_names"); ok { - role.ServiceAccountNames = serviceAccountUUIDs.([]string) - } else if req.Operation == logical.CreateOperation { - role.ServiceAccountNames = data.Get("bound_service_account_names").([]string) - } - // Verify names was not empty - if len(role.ServiceAccountNames) == 0 { - return logical.ErrorResponse("\"bound_service_account_names\" can not be empty"), nil - } - // Verify * was not set with other data - if len(role.ServiceAccountNames) > 1 && strutil.StrListContains(role.ServiceAccountNames, "*") { - return logical.ErrorResponse("can not mix \"*\" with values"), nil - } - - if namespaces, ok := data.GetOk("bound_service_account_namespaces"); ok { - role.ServiceAccountNamespaces = namespaces.([]string) - } else if req.Operation == logical.CreateOperation { - role.ServiceAccountNamespaces = data.Get("bound_service_account_namespaces").([]string) - } - // Verify namespaces is not empty - if len(role.ServiceAccountNamespaces) == 0 { - return logical.ErrorResponse("\"bound_service_account_namespaces\" can not be empty"), nil - } - // Verify * was not set with other data - if len(role.ServiceAccountNamespaces) > 1 && strutil.StrListContains(role.ServiceAccountNamespaces, "*") { - return logical.ErrorResponse("can not mix \"*\" with values"), nil - } - - // Verify that both names and namespaces are not set to "*" - if strutil.StrListContains(role.ServiceAccountNames, "*") && strutil.StrListContains(role.ServiceAccountNamespaces, "*") { - return logical.ErrorResponse("service_account_names and service_account_namespaces can not both be \"*\""), nil - } - - // Parse bound CIDRs. - boundCIDRs, err := parseutil.ParseAddrs(data.Get("bound_cidrs")) - if err != nil { - return logical.ErrorResponse("unable to parse bound_cidrs: " + err.Error()), nil - } - role.BoundCIDRs = boundCIDRs - - // Store the entry. - entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), role) - if err != nil { - return nil, err - } - if entry == nil { - return nil, fmt.Errorf("failed to create storage entry for role %s", roleName) - } - if err = req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return resp, nil - } -} - -// roleStorageEntry stores all the options that are set on an role -type roleStorageEntry struct { - // Policies that are to be required by the token to access this role - Policies []string `json:"policies" structs:"policies" mapstructure:"policies"` - - // TokenNumUses defines the number of allowed uses of the token issued - NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` - - // Duration before which an issued token must be renewed - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl"` - - // Duration after which an issued token should not be allowed to be renewed - MaxTTL time.Duration `json:"max_ttl" structs:"max_ttl" mapstructure:"max_ttl"` - - // Period, if set, indicates that the token generated using this role - // should never expire. The token should be renewed within the duration - // specified by this value. The renewal duration will be fixed if the - // value is not modified on the role. If the `Period` in the role is modified, - // a token will pick up the new value during its next renewal. - Period time.Duration `json:"period" mapstructure:"period" structs:"period"` - - // ServiceAccountNames is the array of service accounts able to - // access this role. - ServiceAccountNames []string `json:"bound_service_account_names" mapstructure:"bound_service_account_names" structs:"bound_service_account_names"` - - // ServiceAccountNamespaces is the array of namespaces able to access this - // role. - ServiceAccountNamespaces []string `json:"bound_service_account_namespaces" mapstructure:"bound_service_account_namespaces" structs:"bound_service_account_namespaces"` - - BoundCIDRs []*sockaddr.SockAddrMarshaler -} - -var roleHelp = map[string][2]string{ - "role-list": { - "Lists all the roles registered with the backend.", - "The list will contain the names of the roles.", - }, - "role": { - "Register an role with the backend.", - `A role is required to authenticate with this backend. The role binds - kubernetes service account metadata with token policies and settings. - The bindings, token polices and token settings can all be configured - using this endpoint`, - }, -} diff --git a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/token_review.go b/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/token_review.go deleted file mode 100644 index bdae3a7b2..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-auth-kubernetes/token_review.go +++ /dev/null @@ -1,193 +0,0 @@ -package kubeauth - -import ( - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - authv1 "k8s.io/api/authentication/v1" - kubeerrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// This is the result from the token review -type tokenReviewResult struct { - Name string - Namespace string - UID string -} - -// This exists so we can use a mock TokenReview when running tests -type tokenReviewer interface { - Review(string) (*tokenReviewResult, error) -} - -type tokenReviewFactory func(*kubeConfig) tokenReviewer - -// This is the real implementation that calls the kubernetes API -type tokenReviewAPI struct { - config *kubeConfig -} - -func tokenReviewAPIFactory(config *kubeConfig) tokenReviewer { - return &tokenReviewAPI{ - config: config, - } -} - -func (t *tokenReviewAPI) Review(jwt string) (*tokenReviewResult, error) { - - client := cleanhttp.DefaultClient() - - // If we have a CA cert build the TLSConfig - if len(t.config.CACert) > 0 { - certPool := x509.NewCertPool() - certPool.AppendCertsFromPEM([]byte(t.config.CACert)) - - tlsConfig := &tls.Config{ - MinVersion: tls.VersionTLS12, - RootCAs: certPool, - } - - client.Transport.(*http.Transport).TLSClientConfig = tlsConfig - } - - // Create the TokenReview Object and marshal it into json - trReq := &authv1.TokenReview{ - Spec: authv1.TokenReviewSpec{ - Token: jwt, - }, - } - trJSON, err := json.Marshal(trReq) - if err != nil { - return nil, err - } - - // Build the request to the token review API - url := fmt.Sprintf("%s/apis/authentication.k8s.io/v1/tokenreviews", t.config.Host) - req, err := http.NewRequest("POST", url, bytes.NewBuffer(trJSON)) - if err != nil { - return nil, err - } - - // If we have a configured TokenReviewer JWT use it as the bearer, otherwise - // try to use the passed in JWT. - bearer := fmt.Sprintf("Bearer %s", jwt) - if len(t.config.TokenReviewerJWT) > 0 { - bearer = fmt.Sprintf("Bearer %s", t.config.TokenReviewerJWT) - } - bearer = strings.TrimSpace(bearer) - - // Set the JWT as the Bearer token - req.Header.Set("Authorization", bearer) - - // Set the MIME type headers - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json") - - resp, err := client.Do(req) - if err != nil { - return nil, err - } - - // Parse the resp into a tokenreview object or a kubernetes error type - r, err := parseResponse(resp) - switch { - case kubeerrors.IsUnauthorized(err): - // If the err is unauthorized that means the token has since been deleted - return nil, errors.New("lookup failed: service account unauthorized; this could mean it has been deleted") - case err != nil: - return nil, err - } - - if r.Status.Error != "" { - return nil, fmt.Errorf("lookup failed: %s", r.Status.Error) - } - - if !r.Status.Authenticated { - return nil, errors.New("lookup failed: service account jwt not valid") - } - - // The username is of format: system:serviceaccount:(NAMESPACE):(SERVICEACCOUNT) - parts := strings.Split(r.Status.User.Username, ":") - if len(parts) != 4 { - return nil, errors.New("lookup failed: unexpected username format") - } - - // Validate the user that comes back from token review is a service account - if parts[0] != "system" || parts[1] != "serviceaccount" { - return nil, errors.New("lookup failed: username returned is not a service account") - } - - return &tokenReviewResult{ - Name: parts[3], - Namespace: parts[2], - UID: string(r.Status.User.UID), - }, nil -} - -// parseResponse takes the API response and either returns the appropriate error -// or the TokenReview Object. -func parseResponse(resp *http.Response) (*authv1.TokenReview, error) { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - // If the request was not a success create a kuberenets error - if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent { - return nil, kubeerrors.NewGenericServerResponse(resp.StatusCode, "POST", schema.GroupResource{}, "", strings.TrimSpace(string(body)), 0, true) - } - - // If we can succesfully Unmarshal into a status object that means there is - // an error to return - errStatus := &metav1.Status{} - err = json.Unmarshal(body, errStatus) - if err == nil && errStatus.Status != metav1.StatusSuccess { - return nil, kubeerrors.FromObject(runtime.Object(errStatus)) - } - - // Unmarshal the resp body into a TokenReview Object - trResp := &authv1.TokenReview{} - err = json.Unmarshal(body, trResp) - if err != nil { - return nil, err - } - - return trResp, nil -} - -// mock review is used while testing -type mockTokenReview struct { - saName string - saNamespace string - saUID string -} - -func mockTokenReviewFactory(name, namespace, UID string) tokenReviewFactory { - return func(config *kubeConfig) tokenReviewer { - return &mockTokenReview{ - saName: name, - saNamespace: namespace, - saUID: UID, - } - } -} - -func (t *mockTokenReview) Review(jwt string) (*tokenReviewResult, error) { - return &tokenReviewResult{ - Name: t.saName, - Namespace: t.saNamespace, - UID: t.saUID, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/LICENSE b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/LICENSE deleted file mode 100644 index a612ad981..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/backend.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/backend.go deleted file mode 100644 index 7145658ab..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/backend.go +++ /dev/null @@ -1,83 +0,0 @@ -package plugin - -import ( - "context" - "sync" - "time" - - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/client" - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/util" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/patrickmn/go-cache" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - backend := newBackend(util.NewSecretsClient(conf.Logger)) - backend.Setup(ctx, conf) - return backend, nil -} - -func newBackend(client secretsClient) *backend { - adBackend := &backend{ - client: client, - roleCache: cache.New(roleCacheExpiration, roleCacheCleanup), - credCache: cache.New(credCacheExpiration, credCacheCleanup), - rotateRootLock: new(int32), - } - adBackend.Backend = &framework.Backend{ - Help: backendHelp, - Paths: []*framework.Path{ - adBackend.pathConfig(), - adBackend.pathRoles(), - adBackend.pathListRoles(), - adBackend.pathCreds(), - adBackend.pathRotateCredentials(), - }, - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - configPath, - credPrefix, - }, - }, - Invalidate: adBackend.Invalidate, - BackendType: logical.TypeLogical, - } - return adBackend -} - -type backend struct { - logical.Backend - - client secretsClient - - roleCache *cache.Cache - credCache *cache.Cache - credLock sync.Mutex - rotateRootLock *int32 -} - -func (b *backend) Invalidate(ctx context.Context, key string) { - b.invalidateRole(ctx, key) - b.invalidateCred(ctx, key) -} - -// Wraps the *util.SecretsClient in an interface to support testing. -type secretsClient interface { - Get(conf *client.ADConf, serviceAccountName string) (*client.Entry, error) - GetPasswordLastSet(conf *client.ADConf, serviceAccountName string) (time.Time, error) - UpdatePassword(conf *client.ADConf, serviceAccountName string, newPassword string) error - UpdateRootPassword(conf *client.ADConf, bindDN string, newPassword string) error -} - -const backendHelp = ` -The Active Directory (AD) secrets engine rotates AD passwords dynamically, -and is designed for a high-load environment where many instances may be accessing -a shared password simultaneously. With a simple set up and a simple creds API, -it doesn't require instances to be manually registered in advance to gain access. -As long as access has been granted to the creds path via a method like -AppRole, they're available. - -Passwords are lazily rotated based on preset TTLs and can have a length configured to meet -your needs. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/client.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/client.go deleted file mode 100644 index 93fa4ded2..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/client.go +++ /dev/null @@ -1,172 +0,0 @@ -package client - -import ( - "fmt" - "math" - "strings" - "time" - - "github.com/go-errors/errors" - "github.com/go-ldap/ldap" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/ldaputil" - "golang.org/x/text/encoding/unicode" -) - -func NewClient(logger hclog.Logger) *Client { - return &Client{ - ldap: &ldaputil.Client{ - Logger: logger, - LDAP: ldaputil.NewLDAP(), - }, - } -} - -type Client struct { - ldap *ldaputil.Client -} - -func (c *Client) Search(cfg *ADConf, filters map[*Field][]string) ([]*Entry, error) { - req := &ldap.SearchRequest{ - BaseDN: cfg.UserDN, - Scope: ldap.ScopeWholeSubtree, - Filter: toString(filters), - SizeLimit: math.MaxInt32, - } - - conn, err := c.ldap.DialLDAP(cfg.ConfigEntry) - if err != nil { - return nil, err - } - defer conn.Close() - - if err := bind(cfg, conn); err != nil { - return nil, err - } - - result, err := conn.Search(req) - if err != nil { - return nil, err - } - - entries := make([]*Entry, len(result.Entries)) - for i, rawEntry := range result.Entries { - entries[i] = NewEntry(rawEntry) - } - return entries, nil -} - -func (c *Client) UpdateEntry(cfg *ADConf, filters map[*Field][]string, newValues map[*Field][]string) error { - entries, err := c.Search(cfg, filters) - if err != nil { - return err - } - if len(entries) != 1 { - return fmt.Errorf("filter of %s doesn't match just one entry: %s", filters, entries) - } - - modifyReq := &ldap.ModifyRequest{ - DN: entries[0].DN, - } - - for field, vals := range newValues { - modifyReq.Replace(field.String(), vals) - } - - conn, err := c.ldap.DialLDAP(cfg.ConfigEntry) - if err != nil { - return err - } - defer conn.Close() - - if err := bind(cfg, conn); err != nil { - return err - } - return conn.Modify(modifyReq) -} - -// UpdatePassword uses a Modify call under the hood because -// Active Directory doesn't recognize the passwordModify method. -// See https://github.com/go-ldap/ldap/issues/106 -// for more. -func (c *Client) UpdatePassword(cfg *ADConf, filters map[*Field][]string, newPassword string) error { - pwdEncoded, err := formatPassword(newPassword) - if err != nil { - return err - } - - newValues := map[*Field][]string{ - FieldRegistry.UnicodePassword: {pwdEncoded}, - } - - return c.UpdateEntry(cfg, filters, newValues) -} - -// According to the MS docs, the password needs to be utf16 and enclosed in quotes. -func formatPassword(original string) (string, error) { - utf16 := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM) - return utf16.NewEncoder().String("\"" + original + "\"") -} - -// Ex. "(cn=Ellen Jones)" -func toString(filters map[*Field][]string) string { - var fieldEquals []string - for f, values := range filters { - for _, v := range values { - fieldEquals = append(fieldEquals, fmt.Sprintf("%s=%s", f, v)) - } - } - result := strings.Join(fieldEquals, ",") - return "(" + result + ")" -} - -func bind(cfg *ADConf, conn ldaputil.Connection) error { - if cfg.BindPassword == "" { - return errors.New("unable to bind due to lack of configured password") - } - - if cfg.UPNDomain != "" { - origErr := conn.Bind(fmt.Sprintf("%s@%s", ldaputil.EscapeLDAPValue(cfg.BindDN), cfg.UPNDomain), cfg.BindPassword) - if origErr == nil { - return nil - } - if !shouldTryLastPwd(cfg.LastBindPassword, cfg.LastBindPasswordRotation) { - return origErr - } - if err := conn.Bind(fmt.Sprintf("%s@%s", ldaputil.EscapeLDAPValue(cfg.BindDN), cfg.UPNDomain), cfg.LastBindPassword); err != nil { - // Return the original error because it'll be more helpful for debugging. - return origErr - } - return nil - } - - if cfg.BindDN != "" { - origErr := conn.Bind(cfg.BindDN, cfg.BindPassword) - if origErr == nil { - return nil - } - if !shouldTryLastPwd(cfg.LastBindPassword, cfg.LastBindPasswordRotation) { - return origErr - } - if err := conn.Bind(cfg.BindDN, cfg.LastBindPassword); err != nil { - // Return the original error because it'll be more helpful for debugging. - return origErr - } - } - return errors.New("must provide binddn or upndomain") -} - -// shouldTryLastPwd determines if we should try a previous password. -// Active Directory can return a variety of errors when a password is invalid. -// Rather than attempting to catalogue these errors across multiple versions of -// AD, we simply try the last password if it's been less than a set amount of -// time since a rotation occurred. -func shouldTryLastPwd(lastPwd string, lastBindPasswordRotation time.Time) bool { - if lastPwd == "" { - return false - } - if lastBindPasswordRotation.Equal(time.Time{}) { - return false - } - return lastBindPasswordRotation.Add(10 * time.Minute).After(time.Now()) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/config.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/config.go deleted file mode 100644 index df26e9947..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/config.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - "time" - - "github.com/hashicorp/vault/helper/ldaputil" -) - -type ADConf struct { - *ldaputil.ConfigEntry - LastBindPassword string `json:"last_bind_password"` - LastBindPasswordRotation time.Time `json:"last_bind_password_rotation"` -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/entry.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/entry.go deleted file mode 100644 index a928ad050..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/entry.go +++ /dev/null @@ -1,41 +0,0 @@ -package client - -import ( - "strings" - - "github.com/go-ldap/ldap" -) - -// Entry is an Active Directory-specific construct -// to make knowing and grabbing fields more convenient, -// while retaining all original information. -func NewEntry(ldapEntry *ldap.Entry) *Entry { - fieldMap := make(map[string][]string) - for _, attribute := range ldapEntry.Attributes { - field := FieldRegistry.Parse(attribute.Name) - if field == nil { - // This field simply isn't in the registry, no big deal. - continue - } - fieldMap[field.String()] = attribute.Values - } - return &Entry{fieldMap: fieldMap, Entry: ldapEntry} -} - -type Entry struct { - *ldap.Entry - fieldMap map[string][]string -} - -func (e *Entry) Get(field *Field) ([]string, bool) { - values, found := e.fieldMap[field.String()] - return values, found -} - -func (e *Entry) GetJoined(field *Field) (string, bool) { - values, found := e.Get(field) - if !found { - return "", false - } - return strings.Join(values, ","), true -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/fieldregistry.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/fieldregistry.go deleted file mode 100644 index 4baf1e0a0..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/fieldregistry.go +++ /dev/null @@ -1,113 +0,0 @@ -package client - -import ( - "reflect" -) - -// FieldRegistry is designed to look and feel -// like an enum from another language like Python. -// -// Example: Accessing constants -// -// FieldRegistry.AccountExpires -// FieldRegistry.BadPasswordCount -// -// Example: Utility methods -// -// FieldRegistry.List() -// FieldRegistry.Parse("givenName") -// -var FieldRegistry = newFieldRegistry() - -// newFieldRegistry iterates through all the fields in the registry, -// pulls their ldap strings, and sets up each field to contain its ldap string -func newFieldRegistry() *fieldRegistry { - reg := &fieldRegistry{} - vOfReg := reflect.ValueOf(reg) - - registryFields := vOfReg.Elem() - for i := 0; i < registryFields.NumField(); i++ { - - if registryFields.Field(i).Kind() == reflect.Ptr { - - field := registryFields.Type().Field(i) - ldapString := field.Tag.Get("ldap") - ldapField := &Field{ldapString} - vOfLDAPField := reflect.ValueOf(ldapField) - - registryFields.FieldByName(field.Name).Set(vOfLDAPField) - - reg.fieldList = append(reg.fieldList, ldapField) - } - } - return reg -} - -// fieldRegistry isn't currently intended to be an exhaustive list - -// there are more fields in ActiveDirectory. However, these are the ones -// that may be useful to Vault. Feel free to add to this list! -type fieldRegistry struct { - AccountExpires *Field `ldap:"accountExpires"` - AdminCount *Field `ldap:"adminCount"` - BadPasswordCount *Field `ldap:"badPwdCount"` - BadPasswordTime *Field `ldap:"badPasswordTime"` - CodePage *Field `ldap:"codePage"` - CommonName *Field `ldap:"cn"` - CountryCode *Field `ldap:"countryCode"` - DisplayName *Field `ldap:"displayName"` - DistinguishedName *Field `ldap:"distinguishedName"` - DomainComponent *Field `ldap:"dc"` - DomainName *Field `ldap:"dn"` - DSCorePropogationData *Field `ldap:"dSCorePropagationData"` - GivenName *Field `ldap:"givenName"` - GroupType *Field `ldap:"groupType"` - Initials *Field `ldap:"initials"` - InstanceType *Field `ldap:"instanceType"` - LastLogoff *Field `ldap:"lastLogoff"` - LastLogon *Field `ldap:"lastLogon"` - LastLogonTimestamp *Field `ldap:"lastLogonTimestamp"` - LockoutTime *Field `ldap:"lockoutTime"` - LogonCount *Field `ldap:"logonCount"` - MemberOf *Field `ldap:"memberOf"` - Name *Field `ldap:"name"` - ObjectCategory *Field `ldap:"objectCategory"` - ObjectClass *Field `ldap:"objectClass"` - ObjectGUID *Field `ldap:"objectGUID"` - ObjectSID *Field `ldap:"objectSid"` - OrganizationalUnit *Field `ldap:"ou"` - PasswordLastSet *Field `ldap:"pwdLastSet"` - PrimaryGroupID *Field `ldap:"primaryGroupID"` - SAMAccountName *Field `ldap:"sAMAccountName"` - SAMAccountType *Field `ldap:"sAMAccountType"` - Surname *Field `ldap:"sn"` - UnicodePassword *Field `ldap:"unicodePwd"` - UpdateSequenceNumberChanged *Field `ldap:"uSNChanged"` - UpdateSequenceNumberCreated *Field `ldap:"uSNCreated"` - UserAccountControl *Field `ldap:"userAccountControl"` - UserPrincipalName *Field `ldap:"userPrincipalName"` - WhenCreated *Field `ldap:"whenCreated"` - WhenChanged *Field `ldap:"whenChanged"` - - fieldList []*Field -} - -func (r *fieldRegistry) List() []*Field { - return r.fieldList -} - -func (r *fieldRegistry) Parse(s string) *Field { - for _, f := range r.List() { - if f.String() == s { - return f - } - } - return nil -} - -type Field struct { - str string -} - -func (f *Field) String() string { - return f.str -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/time.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/time.go deleted file mode 100644 index c451ba473..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/client/time.go +++ /dev/null @@ -1,43 +0,0 @@ -package client - -import ( - "strconv" - "time" -) - -const ( - nanoSecondsPerSecond = 1000000000 - nanosInTick = 100 - ticksPerSecond = nanoSecondsPerSecond / nanosInTick -) - -// ParseTicks parses dates represented as Active Directory LargeInts into times. -// Not all time fields are represented this way, -// so be sure to test that your particular time returns expected results. -// Some time fields represented as LargeInts include accountExpires, lastLogon, lastLogonTimestamp, and pwdLastSet. -// More: https://social.technet.microsoft.com/wiki/contents/articles/31135.active-directory-large-integer-attributes.aspx -func ParseTicks(ticks string) (time.Time, error) { - i, err := strconv.ParseInt(ticks, 10, 64) - if err != nil { - return time.Time{}, err - } - return TicksToTime(i), nil -} - -// TicksToTime converts an ActiveDirectory time in ticks to a time. -// This algorithm is summarized as: -// -// Many dates are saved in Active Directory as Large Integer values. -// These attributes represent dates as the number of 100-nanosecond intervals since 12:00 AM January 1, 1601. -// 100-nanosecond intervals, equal to 0.0000001 seconds, are also called ticks. -// Dates in Active Directory are always saved in Coordinated Universal Time, or UTC. -// More: https://social.technet.microsoft.com/wiki/contents/articles/31135.active-directory-large-integer-attributes.aspx -// -// If we directly follow the above algorithm we encounter time.Duration limits of 290 years and int overflow issues. -// Thus below, we carefully sidestep those. -func TicksToTime(ticks int64) time.Time { - origin := time.Date(1601, time.January, 1, 0, 0, 0, 0, time.UTC).Unix() - secondsSinceOrigin := ticks / ticksPerSecond - remainingNanoseconds := ticks % ticksPerSecond * 100 - return time.Unix(origin+secondsSinceOrigin, remainingNanoseconds).UTC() -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/engineconf.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/engineconf.go deleted file mode 100644 index deda8d670..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/engineconf.go +++ /dev/null @@ -1,10 +0,0 @@ -package plugin - -import ( - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/client" -) - -type configuration struct { - PasswordConf *passwordConf - ADConf *client.ADConf -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/passwordconf.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/passwordconf.go deleted file mode 100644 index b43d4e12f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/passwordconf.go +++ /dev/null @@ -1,17 +0,0 @@ -package plugin - -type passwordConf struct { - TTL int `json:"ttl"` - MaxTTL int `json:"max_ttl"` - Length int `json:"length"` - Formatter string `json:"formatter"` -} - -func (c *passwordConf) Map() map[string]interface{} { - return map[string]interface{}{ - "ttl": c.TTL, - "max_ttl": c.MaxTTL, - "length": c.Length, - "formatter": c.Formatter, - } -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_config.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_config.go deleted file mode 100644 index 3f8e7f8f3..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_config.go +++ /dev/null @@ -1,212 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "time" - - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/client" - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/util" - "github.com/hashicorp/vault/helper/ldaputil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - configPath = "config" - configStorageKey = "config" - - // This length is arbitrarily chosen but should work for - // most Active Directory minimum and maximum length settings. - // A bit tongue-in-cheek since programmers love their base-2 exponents. - defaultPasswordLength = 64 - - defaultTLSVersion = "tls12" -) - -func (b *backend) readConfig(ctx context.Context, storage logical.Storage) (*configuration, error) { - entry, err := storage.Get(ctx, configStorageKey) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - config := &configuration{&passwordConf{}, &client.ADConf{}} - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - return config, nil -} - -func (b *backend) pathConfig() *framework.Path { - return &framework.Path{ - Pattern: configPath, - Fields: b.configFields(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.configUpdateOperation, - logical.ReadOperation: b.configReadOperation, - logical.DeleteOperation: b.configDeleteOperation, - }, - HelpSynopsis: configHelpSynopsis, - HelpDescription: configHelpDescription, - } -} - -func (b *backend) configFields() map[string]*framework.FieldSchema { - fields := ldaputil.ConfigFields() - fields["ttl"] = &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "In seconds, the default password time-to-live.", - } - fields["max_ttl"] = &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "In seconds, the maximum password time-to-live.", - } - fields["length"] = &framework.FieldSchema{ - Type: framework.TypeInt, - Default: defaultPasswordLength, - Description: "The desired length of passwords that Vault generates.", - } - fields["formatter"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Text to insert the password into, ex. "customPrefix{{PASSWORD}}customSuffix".`, - } - return fields -} - -func (b *backend) configUpdateOperation(ctx context.Context, req *logical.Request, fieldData *framework.FieldData) (*logical.Response, error) { - // Build and validate the ldap conf. - activeDirectoryConf, err := ldaputil.NewConfigEntry(fieldData) - if err != nil { - return nil, err - } - if err := activeDirectoryConf.Validate(); err != nil { - return nil, err - } - - // Build the password conf. - ttl := fieldData.Get("ttl").(int) - maxTTL := fieldData.Get("max_ttl").(int) - length := fieldData.Get("length").(int) - formatter := fieldData.Get("formatter").(string) - - if ttl == 0 { - ttl = int(b.System().DefaultLeaseTTL().Seconds()) - } - if maxTTL == 0 { - maxTTL = int(b.System().MaxLeaseTTL().Seconds()) - } - if ttl > maxTTL { - return nil, errors.New("ttl must be smaller than or equal to max_ttl") - } - if ttl < 1 { - return nil, errors.New("ttl must be positive") - } - if maxTTL < 1 { - return nil, errors.New("max_ttl must be positive") - } - if err := util.ValidatePwdSettings(formatter, length); err != nil { - return nil, err - } - - passwordConf := &passwordConf{ - TTL: ttl, - MaxTTL: maxTTL, - Length: length, - Formatter: formatter, - } - - config := &configuration{passwordConf, &client.ADConf{ConfigEntry: activeDirectoryConf}} - entry, err := logical.StorageEntryJSON(configStorageKey, config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Respond with a 204. - return nil, nil -} - -func (b *backend) configReadOperation(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { - config, err := b.readConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - // NOTE: - // "password" is intentionally not returned by this endpoint, - // as we lean away from returning sensitive information unless it's absolutely necessary. - // Also, we don't return the full ADConf here because not all parameters are used by this engine. - configMap := map[string]interface{}{ - "url": config.ADConf.Url, - "starttls": config.ADConf.StartTLS, - "insecure_tls": config.ADConf.InsecureTLS, - "certificate": config.ADConf.Certificate, - "binddn": config.ADConf.BindDN, - "userdn": config.ADConf.UserDN, - "upndomain": config.ADConf.UPNDomain, - "tls_min_version": config.ADConf.TLSMinVersion, - "tls_max_version": config.ADConf.TLSMaxVersion, - } - if !config.ADConf.LastBindPasswordRotation.Equal(time.Time{}) { - configMap["last_bind_password_rotation"] = config.ADConf.LastBindPasswordRotation - } - for k, v := range config.PasswordConf.Map() { - configMap[k] = v - } - - resp := &logical.Response{ - Data: configMap, - } - return resp, nil -} - -func (b *backend) configDeleteOperation(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { - if err := req.Storage.Delete(ctx, configStorageKey); err != nil { - return nil, err - } - return nil, nil -} - -const ( - configHelpSynopsis = ` -Configure the AD server to connect to, along with password options. -` - configHelpDescription = ` -This endpoint allows you to configure the AD server to connect to and its -configuration options. When you add, update, or delete a config, it takes -immediate effect on all subsequent actions. It does not apply itself to roles -or creds added in the past. - -The AD URL can use either the "ldap://" or "ldaps://" schema. In the former -case, an unencrypted connection will be made with a default port of 389, unless -the "starttls" parameter is set to true, in which case TLS will be used. In the -latter case, a SSL connection will be established with a default port of 636. - -## A NOTE ON ESCAPING - -It is up to the administrator to provide properly escaped DNs. This includes -the user DN, bind DN for search, and so on. - -The only DN escaping performed by this backend is on usernames given at login -time when they are inserted into the final bind DN, and uses escaping rules -defined in RFC 4514. - -Additionally, Active Directory has escaping rules that differ slightly from the -RFC; in particular it requires escaping of '#' regardless of position in the DN -(the RFC only requires it to be escaped when it is the first character), and -'=', which the RFC indicates can be escaped with a backslash, but does not -contain in its set of required escapes. If you are using Active Directory and -these appear in your usernames, please ensure that they are escaped, in -addition to being properly escaped in your configured DNs. - -For reference, see https://www.ietf.org/rfc/rfc4514.txt and -http://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_creds.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_creds.go deleted file mode 100644 index fa35df2dd..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_creds.go +++ /dev/null @@ -1,213 +0,0 @@ -package plugin - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/go-errors/errors" - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/util" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - credPrefix = "creds/" - storageKey = "creds" - - // Since Active Directory offers eventual consistency, in testing we found that sometimes - // Active Directory returned "password last set" times that were _later_ than our own, - // even though ours were captured after synchronously completing a password update operation. - // - // An example we captured was: - // last_vault_rotation 2018-04-18T22:29:57.385454779Z - // password_last_set 2018-04-18T22:29:57.3902786Z - // - // Thus we add a short time buffer when checking whether anyone _else_ updated the AD password - // since Vault last rotated it. - passwordLastSetBuffer = time.Second - - // Since password TTL can be set to as low as 1 second, - // we can't cache passwords for an entire second. - credCacheCleanup = time.Second / 3 - credCacheExpiration = time.Second / 2 -) - -// deleteCred fulfills the DeleteWatcher interface in roles. -// It allows the roleHandler to let us know when a role's been deleted so we can delete its associated creds too. -func (b *backend) deleteCred(ctx context.Context, storage logical.Storage, roleName string) error { - if err := storage.Delete(ctx, storageKey+"/"+roleName); err != nil { - return err - } - b.credCache.Delete(roleName) - return nil -} - -func (b *backend) invalidateCred(ctx context.Context, key string) { - if strings.HasPrefix(key, credPrefix) { - roleName := key[len(credPrefix):] - b.credCache.Delete(roleName) - } -} - -func (b *backend) pathCreds() *framework.Path { - return &framework.Path{ - Pattern: credPrefix + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.credReadOperation, - }, - HelpSynopsis: credHelpSynopsis, - HelpDescription: credHelpDescription, - } -} - -func (b *backend) credReadOperation(ctx context.Context, req *logical.Request, fieldData *framework.FieldData) (*logical.Response, error) { - cred := make(map[string]interface{}) - - roleName := fieldData.Get("name").(string) - - // We act upon quite a few things below that could be racy if not locked: - // - Roles. If a new cred is created, the role is updated to include the new LastVaultRotation time, - // effecting role storage (and the role cache, but that's already thread-safe). - // - Creds. New creds involve writing to cred storage and the cred cache (also already thread-safe). - // Rather than setting read locks of different types, and upgrading them to write locks, let's keep complexity - // low and use one simple mutex. - b.credLock.Lock() - defer b.credLock.Unlock() - - role, err := b.readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - var resp *logical.Response - var respErr error - var unset time.Time - - switch { - - case role.LastVaultRotation == unset: - // We've never managed this cred before. - // We need to rotate the password so Vault will know it. - resp, respErr = b.generateAndReturnCreds(ctx, req.Storage, roleName, role, cred) - - case role.PasswordLastSet.After(role.LastVaultRotation.Add(passwordLastSetBuffer)): - // Someone has manually rotated the password in Active Directory since we last rolled it. - // We need to rotate it now so Vault will know it and be able to return it. - resp, respErr = b.generateAndReturnCreds(ctx, req.Storage, roleName, role, cred) - - default: - // Since we should know the last password, let's retrieve it now so we can return it with the new one. - credIfc, found := b.credCache.Get(roleName) - if found { - cred = credIfc.(map[string]interface{}) - } else { - entry, err := req.Storage.Get(ctx, storageKey+"/"+roleName) - if err != nil { - return nil, err - } - if entry == nil { - // If the creds aren't in storage, but roles are and we've created creds before, - // this is an unexpected state and something has gone wrong. - // Let's be explicit and error about this. - return nil, fmt.Errorf("should have the creds for %+v but they're not found", role) - } - if err := entry.DecodeJSON(&cred); err != nil { - return nil, err - } - b.credCache.SetDefault(roleName, cred) - } - - // Is the password too old? - // If so, time for a new one! - now := time.Now().UTC() - shouldBeRolled := role.LastVaultRotation.Add(time.Duration(role.TTL) * time.Second) // already in UTC - if now.After(shouldBeRolled) { - resp, respErr = b.generateAndReturnCreds(ctx, req.Storage, roleName, role, cred) - } else { - resp = &logical.Response{ - Data: cred, - } - } - } - if respErr != nil { - return nil, respErr - } - return resp, nil -} - -func (b *backend) generateAndReturnCreds(ctx context.Context, storage logical.Storage, roleName string, role *backendRole, previousCred map[string]interface{}) (*logical.Response, error) { - engineConf, err := b.readConfig(ctx, storage) - if err != nil { - return nil, err - } - if engineConf == nil { - return nil, errors.New("the config is currently unset") - } - - newPassword, err := util.GeneratePassword(engineConf.PasswordConf.Formatter, engineConf.PasswordConf.Length) - if err != nil { - return nil, err - } - - if err := b.client.UpdatePassword(engineConf.ADConf, role.ServiceAccountName, newPassword); err != nil { - return nil, err - } - - // Time recorded is in UTC for easier user comparison to AD's last rotated time, which is set to UTC by Microsoft. - role.LastVaultRotation = time.Now().UTC() - if err := b.writeRole(ctx, storage, roleName, role); err != nil { - return nil, err - } - - // Although a service account name is typically my_app@example.com, - // the username it uses is just my_app, or everything before the @. - var username string - fields := strings.Split(role.ServiceAccountName, "@") - if len(fields) > 0 { - username = fields[0] - } else { - return nil, fmt.Errorf("unable to infer username from service account name: %s", role.ServiceAccountName) - } - - cred := map[string]interface{}{ - "username": username, - "current_password": newPassword, - } - if previousCred["current_password"] != nil { - cred["last_password"] = previousCred["current_password"] - } - - // Cache and save the cred. - entry, err := logical.StorageEntryJSON(storageKey+"/"+roleName, cred) - if err != nil { - return nil, err - } - if err := storage.Put(ctx, entry); err != nil { - return nil, err - } - b.credCache.SetDefault(roleName, cred) - - return &logical.Response{ - Data: cred, - }, nil -} - -const ( - credHelpSynopsis = ` -Retrieve a role's creds by role name. -` - credHelpDescription = ` -Read creds using a role's name to view the login, current password, and last password. -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_roles.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_roles.go deleted file mode 100644 index 52a481ba7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_roles.go +++ /dev/null @@ -1,254 +0,0 @@ -package plugin - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/go-errors/errors" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - rolePath = "roles" - rolePrefix = "roles/" - roleStorageKey = "roles" - - roleCacheCleanup = time.Second / 2 - roleCacheExpiration = time.Second -) - -func (b *backend) invalidateRole(ctx context.Context, key string) { - if strings.HasPrefix(key, rolePrefix) { - roleName := key[len(rolePrefix):] - b.roleCache.Delete(roleName) - } -} - -func (b *backend) pathListRoles() *framework.Path { - return &framework.Path{ - Pattern: rolePrefix + "?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.roleListOperation, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -func (b *backend) pathRoles() *framework.Path { - return &framework.Path{ - Pattern: rolePrefix + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeLowerCaseString, - Description: "Name of the role", - }, - "service_account_name": { - Type: framework.TypeString, - Description: "The username/logon name for the service account with which this role will be associated.", - }, - "ttl": { - Type: framework.TypeDurationSecond, - Description: "In seconds, the default password time-to-live.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.roleUpdateOperation, - logical.ReadOperation: b.roleReadOperation, - logical.DeleteOperation: b.roleDeleteOperation, - }, - HelpSynopsis: roleHelpSynopsis, - HelpDescription: roleHelpDescription, - } -} - -func (b *backend) readRole(ctx context.Context, storage logical.Storage, roleName string) (*backendRole, error) { - // If it's cached, return it from there. - roleIfc, found := b.roleCache.Get(roleName) - if found { - return roleIfc.(*backendRole), nil - } - - // It's not, read it from storage. - entry, err := storage.Get(ctx, roleStorageKey+"/"+roleName) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - role := &backendRole{} - if err := entry.DecodeJSON(role); err != nil { - return nil, err - } - - // Always check when ActiveDirectory shows the password as last set on the fly. - engineConf, err := b.readConfig(ctx, storage) - if err != nil { - return nil, err - } - if engineConf == nil { - return nil, errors.New("the config is currently unset") - } - - passwordLastSet, err := b.client.GetPasswordLastSet(engineConf.ADConf, role.ServiceAccountName) - if err != nil { - return nil, err - } - role.PasswordLastSet = passwordLastSet - - // Cache it. - b.roleCache.SetDefault(roleName, role) - return role, nil -} - -func (b *backend) writeRole(ctx context.Context, storage logical.Storage, roleName string, role *backendRole) error { - entry, err := logical.StorageEntryJSON(roleStorageKey+"/"+roleName, role) - if err != nil { - return err - } - if err := storage.Put(ctx, entry); err != nil { - return err - } - b.roleCache.SetDefault(roleName, role) - return nil -} - -func (b *backend) roleUpdateOperation(ctx context.Context, req *logical.Request, fieldData *framework.FieldData) (*logical.Response, error) { - // Get everything we need to construct the role. - roleName := fieldData.Get("name").(string) - - engineConf, err := b.readConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if engineConf == nil { - return nil, errors.New("the config is currently unset") - } - - // Actually construct it. - serviceAccountName, err := getServiceAccountName(fieldData) - if err != nil { - return nil, err - } - - // verify service account exists - _, err = b.client.Get(engineConf.ADConf, serviceAccountName) - if err != nil { - return nil, err - } - - ttl, err := getValidatedTTL(engineConf.PasswordConf, fieldData) - if err != nil { - return nil, err - } - role := &backendRole{ - ServiceAccountName: serviceAccountName, - TTL: ttl, - } - - // Was there already a role before that we're now overwriting? If so, let's carry forward the LastVaultRotation. - oldRole, err := b.readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } else { - if oldRole != nil { - role.LastVaultRotation = oldRole.LastVaultRotation - } - } - - // writeRole it to storage and the roleCache. - if err := b.writeRole(ctx, req.Storage, roleName, role); err != nil { - return nil, err - } - - // Return a 204. - return nil, nil -} - -func (b *backend) roleReadOperation(ctx context.Context, req *logical.Request, fieldData *framework.FieldData) (*logical.Response, error) { - roleName := fieldData.Get("name").(string) - - role, err := b.readRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: role.Map(), - }, nil -} - -func (b *backend) roleListOperation(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { - keys, err := req.Storage.List(ctx, roleStorageKey+"/") - if err != nil { - return nil, err - } - return logical.ListResponse(keys), nil -} - -func (b *backend) roleDeleteOperation(ctx context.Context, req *logical.Request, fieldData *framework.FieldData) (*logical.Response, error) { - roleName := fieldData.Get("name").(string) - - if err := req.Storage.Delete(ctx, roleStorageKey+"/"+roleName); err != nil { - return nil, err - } - - b.roleCache.Delete(roleName) - - if err := b.deleteCred(ctx, req.Storage, roleName); err != nil { - return nil, err - } - return nil, nil -} - -func getServiceAccountName(fieldData *framework.FieldData) (string, error) { - serviceAccountName := fieldData.Get("service_account_name").(string) - if serviceAccountName == "" { - return "", errors.New("\"service_account_name\" is required") - } - return serviceAccountName, nil -} - -func getValidatedTTL(passwordConf *passwordConf, fieldData *framework.FieldData) (int, error) { - ttl := fieldData.Get("ttl").(int) - if ttl == 0 { - ttl = passwordConf.TTL - } - if ttl > passwordConf.MaxTTL { - return 0, fmt.Errorf("requested ttl of %d seconds is over the max ttl of %d seconds", ttl, passwordConf.MaxTTL) - } - if ttl < 0 { - return 0, fmt.Errorf("ttl can't be negative") - } - return ttl, nil -} - -const ( - roleHelpSynopsis = ` -Manage roles to build links between Vault and Active Directory service accounts. -` - roleHelpDescription = ` -This endpoint allows you to read, write, and delete individual roles that are used for enabling password rotation. - -Deleting a role will not disable its current password. It will delete the role's associated creds in Vault. -` - - pathListRolesHelpSyn = ` -List the name of each role currently stored. -` - pathListRolesHelpDesc = ` -To learn which service accounts are being managed by Vault, list the role names using -this endpoint. Then read any individual role by name to learn more, like the name of -the service account it's associated with. -` -) diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_rotate_root_creds.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_rotate_root_creds.go deleted file mode 100644 index c26b5c5c0..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_rotate_root_creds.go +++ /dev/null @@ -1,108 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "fmt" - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/util" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "math" - "sync/atomic" - "time" -) - -func (b *backend) pathRotateCredentials() *framework.Path { - return &framework.Path{ - Pattern: "rotate-root", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRotateCredentialsUpdate, - }, - - HelpSynopsis: pathRotateCredentialsUpdateHelpSyn, - HelpDescription: pathRotateCredentialsUpdateHelpDesc, - } -} - -func (b *backend) pathRotateCredentialsUpdate(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { - engineConf, err := b.readConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if engineConf == nil { - return nil, errors.New("the config is currently unset") - } - - newPassword, err := util.GeneratePassword(engineConf.PasswordConf.Formatter, engineConf.PasswordConf.Length) - if err != nil { - return nil, err - } - oldPassword := engineConf.ADConf.BindPassword - - if !atomic.CompareAndSwapInt32(b.rotateRootLock, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Root password rotation is already in progress.") - return resp, nil - } - defer atomic.CompareAndSwapInt32(b.rotateRootLock, 1, 0) - - // Update the password remotely. - if err := b.client.UpdateRootPassword(engineConf.ADConf, engineConf.ADConf.BindDN, newPassword); err != nil { - return nil, err - } - engineConf.ADConf.BindPassword = newPassword - - // Update the password locally. - if pwdStoringErr := storePassword(ctx, req, engineConf); pwdStoringErr != nil { - // We were unable to store the new password locally. We can't continue in this state because we won't be able - // to roll any passwords, including our own to get back into a state of working. So, we need to roll back to - // the last password we successfully got into storage. - if rollbackErr := b.rollBackPassword(ctx, engineConf, oldPassword); rollbackErr != nil { - return nil, fmt.Errorf("unable to store new password due to %s and unable to return to previous password due to %s, configure a new binddn and bindpass to restore active directory function", pwdStoringErr, rollbackErr) - } - return nil, fmt.Errorf("unable to update password due to storage err: %s", pwdStoringErr) - } - // Respond with a 204. - return nil, nil -} - -// rollBackPassword uses naive exponential backoff to retry updating to an old password, -// because Active Directory may still be propagating the previous password change. -func (b *backend) rollBackPassword(ctx context.Context, engineConf *configuration, oldPassword string) error { - var err error - for i := 0; i < 10; i++ { - waitSeconds := math.Pow(float64(i), 2) - timer := time.NewTimer(time.Duration(waitSeconds) * time.Second) - select { - case <-timer.C: - case <-ctx.Done(): - // Outer environment is closing. - return fmt.Errorf("unable to roll back password because enclosing environment is shutting down") - } - if err = b.client.UpdateRootPassword(engineConf.ADConf, engineConf.ADConf.BindDN, oldPassword); err == nil { - // Success. - return nil - } - } - // Failure after looping. - return err -} - -func storePassword(ctx context.Context, req *logical.Request, engineConf *configuration) error { - entry, err := logical.StorageEntryJSON(configStorageKey, engineConf) - if err != nil { - return err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return err - } - return nil -} - -const pathRotateCredentialsUpdateHelpSyn = ` -Request to rotate the root credentials. -` - -const pathRotateCredentialsUpdateHelpDesc = ` -This path attempts to rotate the root credentials. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/role.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/role.go deleted file mode 100644 index 8f653d7b7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/role.go +++ /dev/null @@ -1,28 +0,0 @@ -package plugin - -import ( - "time" -) - -type backendRole struct { - ServiceAccountName string `json:"service_account_name"` - TTL int `json:"ttl"` - LastVaultRotation time.Time `json:"last_vault_rotation"` - PasswordLastSet time.Time `json:"password_last_set"` -} - -func (r *backendRole) Map() map[string]interface{} { - m := map[string]interface{}{ - "service_account_name": r.ServiceAccountName, - "ttl": r.TTL, - } - - var unset time.Time - if r.LastVaultRotation != unset { - m["last_vault_rotation"] = r.LastVaultRotation - } - if r.PasswordLastSet != unset { - m["password_last_set"] = r.PasswordLastSet - } - return m -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/passwords.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/passwords.go deleted file mode 100644 index 2133b7433..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/passwords.go +++ /dev/null @@ -1,77 +0,0 @@ -package util - -import ( - "encoding/base64" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" -) - -var ( - // Per https://en.wikipedia.org/wiki/Password_strength#Guidelines_for_strong_passwords - minimumLengthOfComplexString = 8 - - PasswordComplexityPrefix = "?@09AZ" - PwdFieldTmpl = "{{PASSWORD}}" -) - -func GeneratePassword(formatter string, totalLength int) (string, error) { - if err := ValidatePwdSettings(formatter, totalLength); err != nil { - return "", err - } - pwd, err := generatePassword(totalLength) - if err != nil { - return "", err - } - if formatter == "" { - pwd = PasswordComplexityPrefix + pwd - return pwd[:totalLength], nil - } - return strings.Replace(formatter, PwdFieldTmpl, pwd[:lengthOfPassword(formatter, totalLength)], 1), nil -} - -func ValidatePwdSettings(formatter string, totalLength int) error { - // Check for if there's no formatter. - if formatter == "" { - if totalLength < len(PasswordComplexityPrefix)+minimumLengthOfComplexString { - return fmt.Errorf("it's not possible to generate a _secure_ password of length %d, please boost length to %d, though Vault recommends higher", totalLength, minimumLengthOfComplexString) - } - return nil - } - - // Check for if there is a formatter. - if lengthOfPassword(formatter, totalLength) < minimumLengthOfComplexString { - return fmt.Errorf("since the desired length is %d, it isn't possible to generate a sufficiently complex password - please increase desired length or remove characters from the formatter", totalLength) - } - numPwdFields := strings.Count(formatter, PwdFieldTmpl) - if numPwdFields == 0 { - return fmt.Errorf("%s must contain password replacement field of %s", formatter, PwdFieldTmpl) - } - if numPwdFields > 1 { - return fmt.Errorf("%s must contain ONE password replacement field of %s", formatter, PwdFieldTmpl) - } - return nil -} - -func lengthOfPassword(formatter string, totalLength int) int { - lengthOfText := len(formatter) - len(PwdFieldTmpl) - return totalLength - lengthOfText -} - -// generatePassword returns a password of a length AT LEAST as long as the desired length, -// it may be longer. -func generatePassword(desiredLength int) (string, error) { - b, err := uuid.GenerateRandomBytes(desiredLength) - if err != nil { - return "", err - } - result := "" - // Though the result should immediately be longer than the desiredLength, - // do this in a loop to ensure there's absolutely no risk of a panic when slicing it down later. - for len(result) <= desiredLength { - // Encode to base64 because it's more complex. - result += base64.StdEncoding.EncodeToString(b) - } - return result, nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/secrets_client.go b/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/secrets_client.go deleted file mode 100644 index 29cfaad7e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/util/secrets_client.go +++ /dev/null @@ -1,79 +0,0 @@ -package util - -import ( - "fmt" - "time" - - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault-plugin-secrets-ad/plugin/client" -) - -func NewSecretsClient(logger hclog.Logger) *SecretsClient { - return &SecretsClient{adClient: client.NewClient(logger)} -} - -// SecretsClient wraps a *activeDirectory.activeDirectoryClient to expose just the common convenience methods needed by the ad secrets backend. -type SecretsClient struct { - adClient *client.Client -} - -func (c *SecretsClient) Get(conf *client.ADConf, serviceAccountName string) (*client.Entry, error) { - filters := map[*client.Field][]string{ - client.FieldRegistry.UserPrincipalName: {serviceAccountName}, - } - - entries, err := c.adClient.Search(conf, filters) - if err != nil { - return nil, err - } - - if len(entries) == 0 { - return nil, fmt.Errorf("unable to find service account named %s in active directory, searches are case sensitive", serviceAccountName) - } - if len(entries) > 1 { - return nil, fmt.Errorf("expected one matching service account, but received %s", entries) - } - return entries[0], nil -} - -func (c *SecretsClient) GetPasswordLastSet(conf *client.ADConf, serviceAccountName string) (time.Time, error) { - entry, err := c.Get(conf, serviceAccountName) - if err != nil { - return time.Time{}, err - } - - values, found := entry.Get(client.FieldRegistry.PasswordLastSet) - if !found { - return time.Time{}, fmt.Errorf("%+v lacks a PasswordLastSet field", entry) - } - - if len(values) != 1 { - return time.Time{}, fmt.Errorf("expected only one value for PasswordLastSet, but received %s", values) - } - - ticks := values[0] - if ticks == "0" { - // password has never been rolled in Active Directory, only created - return time.Time{}, nil - } - - t, err := client.ParseTicks(ticks) - if err != nil { - return time.Time{}, err - } - return t, nil -} - -func (c *SecretsClient) UpdatePassword(conf *client.ADConf, serviceAccountName string, newPassword string) error { - filters := map[*client.Field][]string{ - client.FieldRegistry.UserPrincipalName: {serviceAccountName}, - } - return c.adClient.UpdatePassword(conf, filters, newPassword) -} - -func (c *SecretsClient) UpdateRootPassword(conf *client.ADConf, bindDN string, newPassword string) error { - filters := map[*client.Field][]string{ - client.FieldRegistry.DistinguishedName: {bindDN}, - } - return c.adClient.UpdatePassword(conf, filters, newPassword) -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.lock deleted file mode 100644 index 1e84cb828..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.lock +++ /dev/null @@ -1,438 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:f5078e32d0c1c862293676ced1469027c4ad549d14b4ba36e10d45a24691b63f" - name = "github.com/Azure/azure-sdk-for-go" - packages = [ - "profiles/latest/compute/mgmt/compute", - "services/compute/mgmt/2018-04-01/compute", - "services/graphrbac/1.6/graphrbac", - "services/preview/authorization/mgmt/2018-01-01-preview/authorization", - "version", - ] - pruneopts = "UT" - revision = "4e8cbbfb1aeab140cd0fa97fd16b64ee18c3ca6a" - version = "v19.1.0" - -[[projects]] - digest = "1:e782078a170a8f36451e2b6468d0cce2ac394d809054d8ec6820961fa58430fe" - name = "github.com/Azure/go-autorest" - packages = [ - "autorest", - "autorest/adal", - "autorest/azure", - "autorest/azure/auth", - "autorest/date", - "autorest/to", - "autorest/validation", - "logger", - "version", - ] - pruneopts = "UT" - revision = "39013ecb48eaf6ced3f4e3e1d95515140ce6b3cf" - version = "v10.15.2" - -[[projects]] - digest = "1:a69ab3f1445ffd4815add4bd31ba05b65b3b9fec1ade5057d5d717f30e6efd6d" - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt", - ] - pruneopts = "UT" - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - branch = "master" - digest = "1:6bf6d532e503d9526d46e69aff04d11632c8c1e28b847dbd226babc1689aa723" - name = "github.com/armon/go-radix" - packages = ["."] - pruneopts = "UT" - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "UT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - branch = "master" - digest = "1:e608bc2d867c3ded40ccea5417715393a50704ac24004afa87431a0e1976e50d" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "UT" - revision = "5448fe645cb1964ba70ac8f9f2ffe975e61a536c" - -[[projects]] - digest = "1:7f89e0c888fb99c61055c646f5678aae645b0b0a1443d9b2dcd9964d850827ce" - name = "github.com/go-test/deep" - packages = ["."] - pruneopts = "UT" - revision = "6592d9cc0a499ad2d5f574fde80a2b5c5cc3b4f5" - version = "v1.0.1" - -[[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:4a0c6bb4805508a6287675fac876be2ac1182539ca8a32468d8128882e9d5009" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "UT" - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - digest = "1:d1971637b21871ec2033a44ca87c99c5608a7340cb34ec75fab8d2ab503276c9" - name = "github.com/hashicorp/errwrap" - packages = ["."] - pruneopts = "UT" - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - digest = "1:77cb3be9b21ba7f1a4701e870c84ea8b66e7d74c7c8951c58155fdadae9414ec" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - pruneopts = "UT" - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - digest = "1:e8d99882caa8c74d68f340ddb9bba3f7e433117ce57c3e52501edfa7e195d2c7" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - pruneopts = "UT" - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - digest = "1:2394f5a25132b3868eff44599cc28d44bdd0330806e34c495d754dd052df612b" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - pruneopts = "UT" - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - digest = "1:46fb6a9f1b9667f32ac93e08b1da118b2c666991424ea12e848b05d4fe5155ef" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - pruneopts = "UT" - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - digest = "1:20f78c1cf1b6fe6c55ba1407350d6fc7dc77d1591f8106ba693c28014a1a1b37" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - pruneopts = "UT" - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - digest = "1:183f00c472fb9b2446659618eebf4899872fa267b92f926539411abdc8b941df" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - pruneopts = "UT" - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - digest = "1:45aad874d3c7d5e8610427c81870fb54970b981692930ec2a319ce4cb89d7a00" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - pruneopts = "UT" - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - digest = "1:14f2005c31ddf99c4a0f36fc440f8d1ac43224194c7c4a904b3c8f4ba5654d0b" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - pruneopts = "UT" - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - digest = "1:354978aad16c56c27f57e5b152224806d87902e4935da3b03e18263d82ae77aa" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - pruneopts = "UT" - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - digest = "1:32c0e96a63bd093eccf37db757fb314be5996f34de93969321c2cbef893a7bd6" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "UT" - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "UT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - digest = "1:12247a2e99a060cc692f6680e5272c8adf0b8f572e6bce0d7095e624c958a240" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - digest = "1:eda2edac4eb0d58535d11624f1dfd04acb2db8c0cbce99cb65b13ce4ba87e144" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/certutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/salt", - "helper/strutil", - "helper/useragent", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version", - ] - pruneopts = "UT" - revision = "add60e6dc7ff7b94487f3b5b680d00d7c05fe621" - -[[projects]] - branch = "master" - digest = "1:89658943622e6bc5e76b4da027ee9583fa0b321db0c797bd554edab96c1ca2b1" - name = "github.com/hashicorp/yamux" - packages = ["."] - pruneopts = "UT" - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - digest = "1:c7354463195544b1ab3c1f1fadb41430947f5d28dfbf2cdbd38268c5717a5a03" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - digest = "1:cae1afe858922bd10e9573b87130f730a6e4183a00eba79920d6656629468bfa" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - pruneopts = "UT" - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - digest = "1:9ec6cf1df5ad1d55cf41a43b6b1e7e118a91bade4f68ff4303379343e40c0e25" - name = "github.com/oklog/run" - packages = ["."] - pruneopts = "UT" - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - digest = "1:0e792eea6c96ec55ff302ef33886acbaa5006e900fefe82689e88d96439dcd84" - name = "github.com/ryanuber/go-glob" - packages = ["."] - pruneopts = "UT" - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - digest = "1:1d18232beafad93272158a9e9810f417b418c2f967e0506f3e2609c10310fe31" - name = "golang.org/x/crypto" - packages = [ - "pkcs12", - "pkcs12/internal/rc2", - ] - pruneopts = "UT" - revision = "de0752318171da717af4ce24d0a2e8626afaeb11" - -[[projects]] - branch = "master" - digest = "1:b5c3834d33445efdc5a8dcb154bed9e4c211edadbf02f6f5cc20c5e9be26a499" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - digest = "1:05662433b3a13c921587a6e622b5722072edff83211efd1cd79eeaeedfd83f07" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "UT" - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - digest = "1:047efbc3c9a51f3002b0002f92543857d372654a676fb6b01931982cd80467dd" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/Azure/azure-sdk-for-go/profiles/latest/compute/mgmt/compute", - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac", - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization", - "github.com/Azure/go-autorest/autorest", - "github.com/Azure/go-autorest/autorest/azure", - "github.com/Azure/go-autorest/autorest/azure/auth", - "github.com/Azure/go-autorest/autorest/date", - "github.com/Azure/go-autorest/autorest/to", - "github.com/go-test/deep", - "github.com/hashicorp/errwrap", - "github.com/hashicorp/go-hclog", - "github.com/hashicorp/go-multierror", - "github.com/hashicorp/go-uuid", - "github.com/hashicorp/vault/helper/jsonutil", - "github.com/hashicorp/vault/helper/logging", - "github.com/hashicorp/vault/helper/pluginutil", - "github.com/hashicorp/vault/helper/useragent", - "github.com/hashicorp/vault/logical", - "github.com/hashicorp/vault/logical/framework", - "github.com/hashicorp/vault/logical/plugin", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.toml deleted file mode 100644 index 22b68a87b..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Gopkg.toml +++ /dev/null @@ -1,62 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - name = "github.com/Azure/azure-sdk-for-go" - version = "19.1.0" - -[[constraint]] - name = "github.com/Azure/go-autorest" - version = "10.15.2" - -[[constraint]] - name = "github.com/go-test/deep" - version = "1.0.1" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/errwrap" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-multierror" - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-uuid" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/LICENSE b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/LICENSE deleted file mode 100644 index a612ad981..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Makefile b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Makefile deleted file mode 100644 index ffb9cc260..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -TOOL?=vault-plugin-secrets-azure -TEST?=$$(go list ./... | grep -v /vendor/) -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox \ - github.com/kardianos/govendor -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin, except for quickdev which -# is only put into /bin/ -quickdev: generate - @CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/vault-plugin-secrets-azure -dev: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" -dev-dynamic: generate - @CGO_ENABLED=1 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -testcompile: fmtcheck generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# test runs all tests -test: fmtcheck generate - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 45m - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - gofmt -w $(GOFMT_FILES) - -.PHONY: bin default generate test vet bootstrap fmt fmtcheck diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/README.md b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/README.md deleted file mode 100644 index 8edfe9fb5..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/README.md +++ /dev/null @@ -1,124 +0,0 @@ -# Vault Plugin: Azure Secrets Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-secrets-azure.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-secrets-azure) - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin generates revocable, time-limited Service Principals for Microsoft Azure. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links -- [Vault Website](https://www.vaultproject.io) -- [Azure Secrets Docs](https://www.vaultproject.io/docs/secrets/azure/index.html) -- [Vault Github Project](https://www.github.com/hashicorp/vault) - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/secrets/azure/index.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `azure`. To enable this in a running Vault server: - -```sh -$ vault secrets enable azure -Success! Enabled the azure secrets engine at: azure/ -``` - - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine -(version 1.10+ is *required*). - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-secrets-azure`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/azure \ - sha_256= \ - command="vault-plugin-secrets-azure" -... -Success! Data written to: sys/plugins/catalog/azure -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-secrets-azure -... -SHA256(.../go/bin/vault-plugin-secrets-azure)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the secrets enable plugin command: - -```sh -$ vault secrets enable -plugin-name='azure' plugin -... - -Successfully enabled 'plugin' at 'azure'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` - diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/backend.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/backend.go deleted file mode 100644 index 563432618..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/backend.go +++ /dev/null @@ -1,83 +0,0 @@ -package azuresecrets - -import ( - "context" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -type azureSecretBackend struct { - *framework.Backend - - getProvider func(*clientSettings) (AzureProvider, error) - settings *clientSettings - lock sync.RWMutex -} - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func backend() *azureSecretBackend { - var b = azureSecretBackend{} - - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config", - }, - }, - Paths: framework.PathAppend( - pathsRole(&b), - []*framework.Path{ - pathConfig(&b), - pathServicePrincipal(&b), - }, - ), - Secrets: []*framework.Secret{ - secretServicePrincipal(&b), - }, - BackendType: logical.TypeLogical, - Invalidate: b.invalidate, - } - - b.getProvider = newAzureProvider - - return &b -} - -// reset clears the backend's Provider -// This is useful when the configuration changes and a new Provider should be -// created with the updated settings. -func (b *azureSecretBackend) reset() { - b.lock.Lock() - defer b.lock.Unlock() - - b.settings = nil -} - -func (b *azureSecretBackend) invalidate(ctx context.Context, key string) { - switch key { - case "config": - b.reset() - } -} - -const backendHelp = ` -The Azure secrets backend dynamically generates Azure service -principals. The SP credentials have a configurable lease and -are automatically revoked at the end of the lease. - -After mounting this backend, credentials to manage Azure resources -must be configured with the "config/" endpoints and policies must be -written using the "roles/" endpoints before any credentials can be -generated. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/client.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/client.go deleted file mode 100644 index 7e067a7c1..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/client.go +++ /dev/null @@ -1,298 +0,0 @@ -package azuresecrets - -import ( - "context" - "errors" - "fmt" - "math/rand" - "os" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" -) - -const ( - appNamePrefix = "vault-" - retryTimeout = 80 * time.Second -) - -// client offers higher level Azure operations that provide a simpler interface -// for handlers. It in turn relies on a Provider interface to access the lower level -// Azure Client SDK methods. -type client struct { - provider AzureProvider - settings *clientSettings -} - -func (b *azureSecretBackend) getClient(ctx context.Context, s logical.Storage) (*client, error) { - b.lock.RLock() - unlockFunc := b.lock.RUnlock - defer func() { unlockFunc() }() - - if b.settings == nil { - // Upgrade lock - b.lock.RUnlock() - b.lock.Lock() - unlockFunc = b.lock.Unlock - - if b.settings == nil { - // Create a new client from the stored or empty config - config, err := b.getConfig(ctx, s) - if err != nil { - return nil, err - } - if config == nil { - config = new(azureConfig) - } - - settings, err := b.getClientSettings(ctx, config) - if err != nil { - return nil, err - } - b.settings = settings - } - } - - p, err := b.getProvider(b.settings) - if err != nil { - return nil, err - } - - c := &client{ - provider: p, - settings: b.settings, - } - - return c, nil -} - -// createApp creates a new Azure application. -// An Application is a needed to create service principals used by -// the caller for authentication. -func (c *client) createApp(ctx context.Context) (app *graphrbac.Application, err error) { - name, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - name = appNamePrefix + name - - appURL := fmt.Sprintf("https://%s", name) - - result, err := c.provider.CreateApplication(ctx, graphrbac.ApplicationCreateParameters{ - AvailableToOtherTenants: to.BoolPtr(false), - DisplayName: to.StringPtr(name), - Homepage: to.StringPtr(appURL), - IdentifierUris: to.StringSlicePtr([]string{appURL}), - }) - - return &result, err -} - -// createSP creates a new service principal. -func (c *client) createSP( - ctx context.Context, - app *graphrbac.Application, - duration time.Duration) (*graphrbac.ServicePrincipal, string, error) { - - // Generate a random key (which must be a UUID) and password - keyID, err := uuid.GenerateUUID() - if err != nil { - return nil, "", err - } - - password, err := uuid.GenerateUUID() - if err != nil { - return nil, "", err - } - - resultRaw, err := retry(ctx, func() (interface{}, bool, error) { - now := time.Now() - result, err := c.provider.CreateServicePrincipal(ctx, graphrbac.ServicePrincipalCreateParameters{ - AppID: app.AppID, - AccountEnabled: to.BoolPtr(true), - PasswordCredentials: &[]graphrbac.PasswordCredential{ - graphrbac.PasswordCredential{ - StartDate: &date.Time{Time: now}, - EndDate: &date.Time{Time: now.Add(duration)}, - KeyID: to.StringPtr(keyID), - Value: to.StringPtr(password), - }, - }, - }) - - // Propagation delays within Azure can cause this error occasionally, so don't quit on it. - if err != nil && strings.Contains(err.Error(), "does not reference a valid application object") { - return nil, false, nil - } - - return result, true, err - }) - - result := resultRaw.(graphrbac.ServicePrincipal) - - return &result, password, err -} - -// deleteApp deletes an Azure application. -func (c *client) deleteApp(ctx context.Context, appObjectID string) error { - resp, err := c.provider.DeleteApplication(ctx, appObjectID) - - // Don't consider it an error if the object wasn't present - if err != nil && resp.Response != nil && resp.StatusCode == 404 { - return nil - } - - return err -} - -// assignRoles assigns Azure roles to a service principal. -func (c *client) assignRoles(ctx context.Context, sp *graphrbac.ServicePrincipal, roles []*azureRole) ([]string, error) { - var ids []string - - for _, role := range roles { - assignmentID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - resultRaw, err := retry(ctx, func() (interface{}, bool, error) { - ra, err := c.provider.CreateRoleAssignment(ctx, role.Scope, assignmentID, - authorization.RoleAssignmentCreateParameters{ - RoleAssignmentProperties: &authorization.RoleAssignmentProperties{ - RoleDefinitionID: to.StringPtr(role.RoleID), - PrincipalID: sp.ObjectID, - }, - }) - - // Propagation delays within Azure can cause this error occasionally, so don't quit on it. - if err != nil && strings.Contains(err.Error(), "PrincipalNotFound") { - return nil, false, nil - } - - return to.String(ra.ID), true, err - }) - - if err != nil { - return nil, errwrap.Wrapf("error while assigning roles: {{err}}", err) - } - - ids = append(ids, resultRaw.(string)) - } - - return ids, nil -} - -// unassignRoles deletes role assignments, if they existed. -// This is a clean-up operation that isn't essential to revocation. As such, an -// attempt is made to remove all assignments, and not return immediately if there -// is an error. -func (c *client) unassignRoles(ctx context.Context, roleIDs []string) error { - var merr *multierror.Error - - for _, id := range roleIDs { - if _, err := c.provider.DeleteRoleAssignmentByID(ctx, id); err != nil { - merr = multierror.Append(merr, errwrap.Wrapf("error unassigning role: {{err}}", err)) - } - } - - return merr.ErrorOrNil() -} - -// search for roles by name -func (c *client) findRoles(ctx context.Context, roleName string) ([]authorization.RoleDefinition, error) { - return c.provider.ListRoles(ctx, fmt.Sprintf("subscriptions/%s", c.settings.SubscriptionID), fmt.Sprintf("roleName eq '%s'", roleName)) -} - -// clientSettings is used by a client to configure the connections to Azure. -// It is created from a combination of Vault config settings and environment variables. -type clientSettings struct { - SubscriptionID string - TenantID string - ClientID string - ClientSecret string - Environment azure.Environment - PluginEnv *logical.PluginEnvironment -} - -// getClientSettings creates a new clientSettings object. -// Environment variables have higher precedence than stored configuration. -func (b *azureSecretBackend) getClientSettings(ctx context.Context, config *azureConfig) (*clientSettings, error) { - firstAvailable := func(opts ...string) string { - for _, s := range opts { - if s != "" { - return s - } - } - return "" - } - - settings := new(clientSettings) - - settings.ClientID = firstAvailable(os.Getenv("AZURE_CLIENT_ID"), config.ClientID) - settings.ClientSecret = firstAvailable(os.Getenv("AZURE_CLIENT_SECRET"), config.ClientSecret) - settings.SubscriptionID = firstAvailable(os.Getenv("AZURE_SUBSCRIPTION_ID")) - - settings.SubscriptionID = firstAvailable(os.Getenv("AZURE_SUBSCRIPTION_ID"), config.SubscriptionID) - if settings.SubscriptionID == "" { - return nil, errors.New("subscription_id is required") - } - - settings.TenantID = firstAvailable(os.Getenv("AZURE_TENANT_ID"), config.TenantID) - if settings.TenantID == "" { - return nil, errors.New("tenant_id is required") - } - - envName := firstAvailable(os.Getenv("AZURE_ENVIRONMENT"), config.Environment, "AZUREPUBLICCLOUD") - env, err := azure.EnvironmentFromName(envName) - if err != nil { - return nil, err - } - settings.Environment = env - - pluginEnv, err := b.System().PluginEnv(ctx) - if err != nil { - return nil, errwrap.Wrapf("error loading plugin environment: {{err}}", err) - } - settings.PluginEnv = pluginEnv - - return settings, nil -} - -// retry will repeatedly call f until one of: -// -// * f returns true -// * the context is cancelled -// * 80 seconds elapses. Vault's default request timeout is 90s; we want to expire before then. -// -// Delays are random but will average 5 seconds. -func retry(ctx context.Context, f func() (interface{}, bool, error)) (interface{}, error) { - delayTimer := time.NewTimer(0) - endCh := time.NewTimer(retryTimeout).C - - for { - if result, done, err := f(); done { - return result, err - } - - delay := time.Duration(2000+rand.Intn(6000)) * time.Millisecond - delayTimer.Reset(delay) - - select { - case <-delayTimer.C: - case <-endCh: - return nil, errors.New("retry: timeout") - case <-ctx.Done(): - return nil, errors.New("retry: cancelled") - } - } -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_config.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_config.go deleted file mode 100644 index 1454ff11e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_config.go +++ /dev/null @@ -1,202 +0,0 @@ -package azuresecrets - -import ( - "context" - "errors" - - "github.com/Azure/go-autorest/autorest/azure" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - configStoragePath = "config" -) - -// azureConfig contains values to configure Azure clients and -// defaults for roles. The zero value is useful and results in -// environments variable and system defaults being used. -type azureConfig struct { - SubscriptionID string `json:"subscription_id"` - TenantID string `json:"tenant_id"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - Environment string `json:"environment"` -} - -func pathConfig(b *azureSecretBackend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "subscription_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The subscription id for the Azure Active Directory. - This value can also be provided with the AZURE_SUBSCRIPTION_ID environment variable.`, - }, - "tenant_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The tenant id for the Azure Active Directory. This value can also - be provided with the AZURE_TENANT_ID environment variable.`, - }, - "environment": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The Azure environment name. If not provided, AzurePublicCloud is used. - This value can also be provided with the AZURE_ENVIRONMENT environment variable.`, - }, - "client_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The OAuth2 client id to connect to Azure. - This value can also be provided with the AZURE_CLIENT_ID environment variable.`, - }, - "client_secret": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The OAuth2 client secret to connect to Azure. - This value can also be provided with the AZURE_CLIENT_SECRET environment variable.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.CreateOperation: b.pathConfigWrite, - logical.UpdateOperation: b.pathConfigWrite, - logical.DeleteOperation: b.pathConfigDelete, - }, - ExistenceCheck: b.pathConfigExistenceCheck, - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -func (b *azureSecretBackend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var merr *multierror.Error - - config, err := b.getConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - - if config == nil { - if req.Operation == logical.UpdateOperation { - return nil, errors.New("config not found during update operation") - } - config = new(azureConfig) - } - - if subscriptionID, ok := data.GetOk("subscription_id"); ok { - config.SubscriptionID = subscriptionID.(string) - } - - if tenantID, ok := data.GetOk("tenant_id"); ok { - config.TenantID = tenantID.(string) - } - - if environment, ok := data.GetOk("environment"); ok { - e := environment.(string) - if _, err := azure.EnvironmentFromName(e); err != nil { - merr = multierror.Append(merr, err) - } else { - config.Environment = e - } - } - - if clientID, ok := data.GetOk("client_id"); ok { - config.ClientID = clientID.(string) - } - - if clientSecret, ok := data.GetOk("client_secret"); ok { - config.ClientSecret = clientSecret.(string) - } - - if merr.ErrorOrNil() != nil { - return logical.ErrorResponse(merr.Error()), nil - } - - err = b.saveConfig(ctx, config, req.Storage) - - return nil, err -} - -func (b *azureSecretBackend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.getConfig(ctx, req.Storage) - - if err != nil { - return nil, err - } - - if config == nil { - config = new(azureConfig) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "subscription_id": config.SubscriptionID, - "tenant_id": config.TenantID, - "environment": config.Environment, - "client_id": config.ClientID, - }, - } - return resp, nil -} - -func (b *azureSecretBackend) pathConfigDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, configStoragePath) - - if err == nil { - b.reset() - } - - return nil, err -} - -func (b *azureSecretBackend) pathConfigExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - config, err := b.getConfig(ctx, req.Storage) - if err != nil { - return false, err - } - - return config != nil, err -} - -func (b *azureSecretBackend) getConfig(ctx context.Context, s logical.Storage) (*azureConfig, error) { - entry, err := s.Get(ctx, configStoragePath) - if err != nil { - return nil, err - } - - if entry == nil { - return nil, nil - } - - config := new(azureConfig) - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - - return config, nil -} - -func (b *azureSecretBackend) saveConfig(ctx context.Context, config *azureConfig, s logical.Storage) error { - entry, err := logical.StorageEntryJSON(configStoragePath, config) - - if err != nil { - return err - } - - err = s.Put(ctx, entry) - if err != nil { - return err - } - - // reset the backend since the client and provider will have been - // built using old versions of this data - b.reset() - - return nil -} - -const confHelpSyn = `Configure the Azure Secret backend.` -const confHelpDesc = ` -The Azure secret backend requires credentials for managing applications and -service principals. This endpoint is used to configure those credentials as -well as default values for the backend in general. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_roles.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_roles.go deleted file mode 100644 index bd95f359d..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_roles.go +++ /dev/null @@ -1,288 +0,0 @@ -package azuresecrets - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization" - "github.com/Azure/go-autorest/autorest/to" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - rolesStoragePath = "roles" - - credentialTypeSP = 0 -) - -// Role is a Vault role construct that maps to Azure roles -type Role struct { - CredentialType int `json:"credential_type"` // Reserved. Always SP at this time. - AzureRoles []*azureRole `json:"azure_roles"` - TTL time.Duration `json:"ttl"` - MaxTTL time.Duration `json:"max_ttl"` -} - -// azureRole is an Azure Role (https://docs.microsoft.com/en-us/azure/role-based-access-control/overview) applied -// to a scope. RoleName and RoleID are both traits of the role. RoleID is the unique identifier, but RoleName is -// more useful to a human (thought it is not unique). -type azureRole struct { - RoleName string `json:"role_name"` // e.g. Owner - RoleID string `json:"role_id"` // e.g. /subscriptions/e0a207b2-.../providers/Microsoft.Authorization/roleDefinitions/de139f84-... - Scope string `json:"scope"` // e.g. /subscriptions/e0a207b2-... -} - -func pathsRole(b *azureSecretBackend) []*framework.Path { - return []*framework.Path{ - { - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeLowerCaseString, - Description: "Name of the role", - }, - "azure_roles": { - Type: framework.TypeString, - Description: "JSON list of Azure roles to assign", - }, - "ttl": { - Type: framework.TypeDurationSecond, - Description: "Default lease for generated credentials. If not set or set to 0, will use system default.", - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: "Maximum time a service principal. If not set or set to 0, will use system default.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.CreateOperation: b.pathRoleUpdate, - logical.UpdateOperation: b.pathRoleUpdate, - logical.DeleteOperation: b.pathRoleDelete, - }, - HelpSynopsis: roleHelpSyn, - HelpDescription: roleHelpDesc, - ExistenceCheck: b.pathRoleExistenceCheck, - }, - { - Pattern: "roles/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - HelpSynopsis: roleListHelpSyn, - HelpDescription: roleListHelpDesc, - }, - } - -} - -// pathRoleUpdate creates or updates Vault roles. -// -// Basic validity check are made to verify that the provided fields meet requirements -// and the Azure roles exist. The Azure role lookup step will all the operator to provide -// a role name or ID. ID is unambigious and will be used if provided. Given just role name, -// a search will be performed and if exactly one match is found, that role will be used. -func (b *azureSecretBackend) pathRoleUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var resp *logical.Response - - // load or create role - name := d.Get("name").(string) - role, err := getRole(ctx, name, req.Storage) - if err != nil { - return nil, errwrap.Wrapf("error reading role: {{err}}", err) - } - - if role == nil { - if req.Operation == logical.UpdateOperation { - return nil, errors.New("role entry not found during update operation") - } - role = &Role{ - CredentialType: credentialTypeSP, - } - } - - // update role with any provided parameters - if ttlRaw, ok := d.GetOk("ttl"); ok { - role.TTL = time.Duration(ttlRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.TTL = time.Duration(d.Get("ttl").(int)) * time.Second - } - - if maxTTLRaw, ok := d.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.MaxTTL = time.Duration(d.Get("max_ttl").(int)) * time.Second - } - - if roles, ok := d.GetOk("azure_roles"); ok { - parsedRoles := make([]*azureRole, 0) // non-nil to avoid a "missing roles" error later - - err := jsonutil.DecodeJSON([]byte(roles.(string)), &parsedRoles) - if err != nil { - return logical.ErrorResponse("invalid Azure role definitions"), nil - } - role.AzureRoles = parsedRoles - } - - // verify Azure roles, including looking up each role - // by ID or name. - c, err := b.getClient(ctx, req.Storage) - if err != nil { - return nil, err - } - - roleIDs := make(map[string]bool) - for _, r := range role.AzureRoles { - var roleDef authorization.RoleDefinition - if r.RoleID != "" { - roleDef, err = c.provider.GetRoleByID(ctx, r.RoleID) - if err != nil { - if strings.Contains(err.Error(), "RoleDefinitionDoesNotExist") { - return logical.ErrorResponse(fmt.Sprintf("no role found for role_id: '%s'", r.RoleID)), nil - } - return nil, errwrap.Wrapf("unable to lookup Azure role: {{err}}", err) - } - } else { - defs, err := c.findRoles(ctx, r.RoleName) - if err != nil { - return nil, errwrap.Wrapf("unable to lookup Azure role: {{err}}", err) - } - if l := len(defs); l == 0 { - return logical.ErrorResponse(fmt.Sprintf("no role found for role_name: '%s'", r.RoleName)), nil - } else if l > 1 { - return logical.ErrorResponse(fmt.Sprintf("multiple matches found for role_name: '%s'. Specify role by ID instead.", r.RoleName)), nil - } - roleDef = defs[0] - } - - roleDefID := to.String(roleDef.ID) - roleDefName := to.String(roleDef.RoleName) - if roleIDs[roleDefID] { - return logical.ErrorResponse(fmt.Sprintf("duplicate role_id: '%s'", *roleDef.ID)), nil - } - roleIDs[roleDefID] = true - - r.RoleName, r.RoleID = roleDefName, roleDefID - } - - // validate role definition constraints - if role.MaxTTL != 0 && role.TTL > role.MaxTTL { - return logical.ErrorResponse("ttl cannot be greater than max_ttl"), nil - } - - if len(role.AzureRoles) == 0 { - return logical.ErrorResponse("missing Azure role definitions"), nil - } - - // save role - err = saveRole(ctx, req.Storage, role, name) - if err != nil { - return nil, errwrap.Wrapf("error storing role: {{err}}", err) - } - - return resp, nil -} - -func (b *azureSecretBackend) pathRoleRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var data = make(map[string]interface{}) - - name := d.Get("name").(string) - - r, err := getRole(ctx, name, req.Storage) - if err != nil { - return nil, errwrap.Wrapf("error reading role: {{err}}", err) - } - - if r == nil { - return nil, nil - } - - data["ttl"] = r.TTL / time.Second - data["max_ttl"] = r.MaxTTL / time.Second - data["azure_roles"] = r.AzureRoles - - return &logical.Response{ - Data: data, - }, nil -} - -func (b *azureSecretBackend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roles, err := req.Storage.List(ctx, rolesStoragePath+"/") - if err != nil { - return nil, errwrap.Wrapf("error listing roles: {{err}}", err) - } - - return logical.ListResponse(roles), nil -} - -func (b *azureSecretBackend) pathRoleDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - err := req.Storage.Delete(ctx, fmt.Sprintf("%s/%s", rolesStoragePath, name)) - if err != nil { - return nil, errwrap.Wrapf("error deleting role: {{err}}", err) - } - - return nil, nil -} - -func (b *azureSecretBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) { - name := d.Get("name").(string) - - role, err := getRole(ctx, name, req.Storage) - if err != nil { - return false, errwrap.Wrapf("error reading role: {{err}}", err) - } - - return role != nil, nil -} - -func saveRole(ctx context.Context, s logical.Storage, c *Role, name string) error { - entry, err := logical.StorageEntryJSON(fmt.Sprintf("%s/%s", rolesStoragePath, name), c) - if err != nil { - return err - } - - return s.Put(ctx, entry) -} - -func getRole(ctx context.Context, name string, s logical.Storage) (*Role, error) { - entry, err := s.Get(ctx, fmt.Sprintf("%s/%s", rolesStoragePath, name)) - if err != nil { - return nil, err - } - - if entry == nil { - return nil, nil - } - - role := new(Role) - if err := entry.DecodeJSON(role); err != nil { - return nil, err - } - return role, nil -} - -const roleHelpSyn = "Manage the Vault roles used to generate Azure credentials." -const roleHelpDesc = ` -This path allows you to read and write roles that are used to generate Azure login -credentials. These roles are associated with Azure roles, which are in turn used to -control permissions to Azure resources. - -If the backend is mounted at "azure", you would create a Vault role at "azure/roles/my_role", -and request credentials from "azure/creds/my_role". - -Each Vault role is configured with the standard ttl parameters and a list of Azure -roles and scopes. These Azure roles will be fetched during the Vault role creation -and must exist for the request to succeed. Multiple Azure roles may be specified. When -a used requests credentials against the Vault role, and new service principal is created -and the configured set of Azure roles are assigned to it. -` -const roleListHelpSyn = `List existing roles.` -const roleListHelpDesc = `List existing roles by name.` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_service_principal.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_service_principal.go deleted file mode 100644 index 525ce9e6e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/path_service_principal.go +++ /dev/null @@ -1,166 +0,0 @@ -package azuresecrets - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/Azure/go-autorest/autorest/to" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - SecretTypeSP = "service_principal" -) - -func secretServicePrincipal(b *azureSecretBackend) *framework.Secret { - return &framework.Secret{ - Type: SecretTypeSP, - Renew: b.spRenew, - Revoke: b.spRevoke, - } -} - -func pathServicePrincipal(b *azureSecretBackend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("creds/%s", framework.GenericNameRegex("role")), - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeLowerCaseString, - Description: "Name of the Vault role", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathSPRead, - }, - HelpSynopsis: pathServicePrincipalHelpSyn, - HelpDescription: pathServicePrincipalHelpDesc, - } -} - -// pathSPRead generates Azure an service principal and credentials. -// -// This is a multistep process of: -// 1. Create an Azure application -// 2. Create a service principal associated with the new App -// 3. Assign roles -func (b *azureSecretBackend) pathSPRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - c, err := b.getClient(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - roleName := d.Get("role").(string) - role, err := getRole(ctx, roleName, req.Storage) - if err != nil { - return nil, err - } - - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("role '%s' does not exists", roleName)), nil - } - - // Create the App, which is the top level object to be tracked in the secret - // and deleted upon revocation. If any subsequent step fails, the App is deleted. - app, err := c.createApp(ctx) - if err != nil { - return nil, err - } - appID := to.String(app.AppID) - appObjID := to.String(app.ObjectID) - - // Create the SP. A far future credential expiration is set on the Azure side. - sp, password, err := c.createSP(ctx, app, 10*365*24*time.Hour) - if err != nil { - c.deleteApp(ctx, appObjID) - return nil, err - } - - raIDs, err := c.assignRoles(ctx, sp, role.AzureRoles) - if err != nil { - c.deleteApp(ctx, appObjID) - return nil, err - } - - resp := b.Secret(SecretTypeSP).Response(map[string]interface{}{ - "client_id": appID, - "client_secret": password, - }, map[string]interface{}{ - "app_object_id": appObjID, - "role_assignment_ids": raIDs, - "role": roleName, - }) - - resp.Secret.TTL = role.TTL - resp.Secret.MaxTTL = role.MaxTTL - - return resp, nil -} - -func (b *azureSecretBackend) spRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleRaw, ok := req.Secret.InternalData["role"] - if !ok { - return nil, errors.New("internal data not found") - } - - role, err := getRole(ctx, roleRaw.(string), req.Storage) - if err != nil { - return nil, err - } - - if role == nil { - return nil, nil - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = role.TTL - resp.Secret.MaxTTL = role.MaxTTL - - return resp, nil -} - -func (b *azureSecretBackend) spRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - resp := new(logical.Response) - - appObjectIDRaw, ok := req.Secret.InternalData["app_object_id"] - if !ok { - return nil, errors.New("internal data not found") - } - - appObjectID := appObjectIDRaw.(string) - - var raIDs []string - if req.Secret.InternalData["role_assignment_ids"] != nil { - for _, v := range req.Secret.InternalData["role_assignment_ids"].([]interface{}) { - raIDs = append(raIDs, v.(string)) - } - } - - c, err := b.getClient(ctx, req.Storage) - if err != nil { - return nil, errwrap.Wrapf("error during revoke: {{err}}", err) - } - - // unassigning roles is effectively a garbage collection operation. Errors will be noted but won't fail the - // revocation process. Deleting the app, however, *is* required to consider the secret revoked. - if err := c.unassignRoles(ctx, raIDs); err != nil { - resp.AddWarning(err.Error()) - } - - err = c.deleteApp(ctx, appObjectID) - - return resp, err -} - -const pathServicePrincipalHelpSyn = ` -Request Service Principal credentials for a given Vault role. -` - -const pathServicePrincipalHelpDesc = ` -This path creates a Service Principal and assigns Azure roles for a -given Vault role, returning the associated login credentials. The -Service Principal will be automatically deleted when the lease has expired. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/provider.go b/vendor/github.com/hashicorp/vault-plugin-secrets-azure/provider.go deleted file mode 100644 index a84eaf60f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-azure/provider.go +++ /dev/null @@ -1,190 +0,0 @@ -package azuresecrets - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure/auth" - "github.com/hashicorp/vault/helper/useragent" -) - -// AzureProvider is an interface to access underlying Azure client objects and supporting services. -// Where practical the original function signature is preserved. client provides higher -// level operations atop AzureProvider. -type AzureProvider interface { - ApplicationsClient - ServicePrincipalsClient - RoleAssignmentsClient - RoleDefinitionsClient -} - -type ApplicationsClient interface { - CreateApplication(ctx context.Context, parameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) - DeleteApplication(ctx context.Context, applicationObjectID string) (autorest.Response, error) -} - -type ServicePrincipalsClient interface { - CreateServicePrincipal(ctx context.Context, parameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) -} - -type RoleAssignmentsClient interface { - CreateRoleAssignment( - ctx context.Context, - scope string, - roleAssignmentName string, - parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) - DeleteRoleAssignmentByID(ctx context.Context, roleID string) (authorization.RoleAssignment, error) -} - -type RoleDefinitionsClient interface { - ListRoles(ctx context.Context, scope string, filter string) ([]authorization.RoleDefinition, error) - GetRoleByID(ctx context.Context, roleID string) (result authorization.RoleDefinition, err error) -} - -// provider is a concrete implementation of AzureProvider. In most cases it is a simple passthrough -// to the appropriate client object. But if the response requires processing that is more practical -// at this layer, the response signature may different from the Azure signature. -type provider struct { - settings *clientSettings - - appClient *graphrbac.ApplicationsClient - spClient *graphrbac.ServicePrincipalsClient - raClient *authorization.RoleAssignmentsClient - rdClient *authorization.RoleDefinitionsClient -} - -// newAzureProvider creates an azureProvider, backed by Azure client objects for underlying services. -func newAzureProvider(settings *clientSettings) (AzureProvider, error) { - // build clients that use the GraphRBAC endpoint - authorizer, err := getAuthorizer(settings, settings.Environment.GraphEndpoint) - if err != nil { - return nil, err - } - - var userAgent string - if settings.PluginEnv != nil { - userAgent = useragent.PluginString(settings.PluginEnv, "azure-secrets") - } else { - userAgent = useragent.String() - } - - appClient := graphrbac.NewApplicationsClient(settings.TenantID) - appClient.Authorizer = authorizer - appClient.AddToUserAgent(userAgent) - - spClient := graphrbac.NewServicePrincipalsClient(settings.TenantID) - spClient.Authorizer = authorizer - spClient.AddToUserAgent(userAgent) - - // build clients that use the Resource Manager endpoint - authorizer, err = getAuthorizer(settings, settings.Environment.ResourceManagerEndpoint) - if err != nil { - return nil, err - } - - raClient := authorization.NewRoleAssignmentsClient(settings.SubscriptionID) - raClient.Authorizer = authorizer - raClient.AddToUserAgent(userAgent) - - rdClient := authorization.NewRoleDefinitionsClient(settings.SubscriptionID) - rdClient.Authorizer = authorizer - rdClient.AddToUserAgent(userAgent) - - p := &provider{ - settings: settings, - - appClient: &appClient, - spClient: &spClient, - raClient: &raClient, - rdClient: &rdClient, - } - - return p, nil -} - -// getAuthorizer attempts to create an authorizer, preferring ClientID/Secret if present, -// and falling back to MSI if not. -func getAuthorizer(settings *clientSettings, resource string) (authorizer autorest.Authorizer, err error) { - - if settings.ClientID != "" && settings.ClientSecret != "" && settings.TenantID != "" { - config := auth.NewClientCredentialsConfig(settings.ClientID, settings.ClientSecret, settings.TenantID) - config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint - config.Resource = resource - authorizer, err = config.Authorizer() - if err != nil { - return nil, err - } - } else { - config := auth.NewMSIConfig() - config.Resource = resource - authorizer, err = config.Authorizer() - if err != nil { - return nil, err - } - } - - return authorizer, nil -} - -// CreateApplication create a new Azure application object. -func (p *provider) CreateApplication(ctx context.Context, parameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) { - return p.appClient.Create(ctx, parameters) -} - -// DeleteApplication deletes an Azure application object. -// This will in turn remove the service principal (but not the role assignments). -func (p *provider) DeleteApplication(ctx context.Context, applicationObjectID string) (autorest.Response, error) { - return p.appClient.Delete(ctx, applicationObjectID) -} - -// CreateServicePrincipal creates a new Azure service principal. -// An Application must be created prior to calling this and pass in parameters. -func (p *provider) CreateServicePrincipal(ctx context.Context, parameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) { - return p.spClient.Create(ctx, parameters) -} - -// ListRoles like all Azure roles with a scope (often subscription). -func (p *provider) ListRoles(ctx context.Context, scope string, filter string) (result []authorization.RoleDefinition, err error) { - page, err := p.rdClient.List(ctx, scope, filter) - - if err != nil { - return nil, err - } - - return page.Values(), nil -} - -// GetRoleByID fetches the full role definition given a roleID. -func (p *provider) GetRoleByID(ctx context.Context, roleID string) (result authorization.RoleDefinition, err error) { - return p.rdClient.GetByID(ctx, roleID) -} - -// CreateRoleAssignment assigns a role to a service principal. -func (p *provider) CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) { - return p.raClient.Create(ctx, scope, roleAssignmentName, parameters) -} - -// GetRoleAssignmentByID fetches the full role assignment info given a roleAssignmentID. -func (p *provider) GetRoleAssignmentByID(ctx context.Context, roleAssignmentID string) (result authorization.RoleAssignment, err error) { - return p.raClient.GetByID(ctx, roleAssignmentID) -} - -// DeleteRoleAssignmentByID deletes a role assignment. -func (p *provider) DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentID string) (result authorization.RoleAssignment, err error) { - return p.raClient.DeleteByID(ctx, roleAssignmentID) -} - -// ListRoleAssignments lists all role assignments. -// There is no need for paging; the caller only cares about the the first match and whether -// there are 0, 1 or >1 items. Unpacking here is a simpler interface. -func (p *provider) ListRoleAssignments(ctx context.Context, filter string) ([]authorization.RoleAssignment, error) { - page, err := p.raClient.List(ctx, filter) - - if err != nil { - return nil, err - } - - return page.Values(), nil -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/LICENSE b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/backend.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/backend.go deleted file mode 100644 index cef2eb803..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/backend.go +++ /dev/null @@ -1,115 +0,0 @@ -package gcpsecrets - -import ( - "context" - "net/http" - "strings" - "sync" - "time" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/iamutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/oauth2" - "google.golang.org/api/iam/v1" -) - -type backend struct { - *framework.Backend - - iamResources iamutil.IamResourceParser - - rolesetLock sync.Mutex -} - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b = backend{ - iamResources: iamutil.GetEnabledIamResources(), - } - - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - PathsSpecial: &logical.Paths{ - LocalStorage: []string{ - framework.WALPrefix, - }, - SealWrapStorage: []string{ - "config", - }, - }, - - Paths: framework.PathAppend( - pathsRoleSet(&b), - []*framework.Path{ - pathConfig(&b), - pathSecretAccessToken(&b), - pathSecretServiceAccountKey(&b), - }, - ), - Secrets: []*framework.Secret{ - secretAccessToken(&b), - secretServiceAccountKey(&b), - }, - - BackendType: logical.TypeLogical, - WALRollback: b.walRollback, - WALRollbackMinAge: 5 * time.Minute, - } - - return &b -} - -func newHttpClient(ctx context.Context, s logical.Storage, scopes ...string) (*http.Client, error) { - if len(scopes) == 0 { - scopes = []string{"https://www.googleapis.com/auth/cloud-platform"} - } - - cfg, err := getConfig(ctx, s) - if err != nil { - return nil, err - } - credsJSON := "" - if cfg != nil { - credsJSON = cfg.CredentialsRaw - } - - _, tokenSource, err := gcputil.FindCredentials(credsJSON, ctx, scopes...) - if err != nil { - return nil, err - } - - tc := cleanhttp.DefaultClient() - return oauth2.NewClient( - context.WithValue(ctx, oauth2.HTTPClient, tc), - tokenSource), nil -} - -func newIamAdmin(ctx context.Context, s logical.Storage) (*iam.Service, error) { - c, err := newHttpClient(ctx, s, iam.CloudPlatformScope) - if err != nil { - return nil, err - } - - return iam.New(c) -} - -const backendHelp = ` -The GCP secrets backend dynamically generates GCP IAM service -account keys with a given set of IAM policies. The service -account keys have a configurable lease set and are automatically -revoked at the end of the lease. - -After mounting this backend, credentials to generate IAM keys must -be configured with the "config/" endpoints and policies must be -written using the "roles/" endpoints before any keys can be generated. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_config.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_config.go deleted file mode 100644 index 8a5913c4d..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_config.go +++ /dev/null @@ -1,132 +0,0 @@ -package gcpsecrets - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "credentials": { - Type: framework.TypeString, - Description: `GCP IAM service account credentials JSON with permissions to create new service accounts and set IAM policies`, - }, - "ttl": { - Type: framework.TypeDurationSecond, - Description: "Default lease for generated keys. If <= 0, will use system default.", - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: "Maximum time a service account key is valid for. If <= 0, will use system default.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.UpdateOperation: b.pathConfigWrite, - }, - - HelpSynopsis: pathConfigHelpSyn, - HelpDescription: pathConfigHelpDesc, - } -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - cfg, err := getConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if cfg == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "ttl": int64(cfg.TTL / time.Second), - "max_ttl": int64(cfg.MaxTTL / time.Second), - }, - }, nil -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - cfg, err := getConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if cfg == nil { - cfg = &config{} - } - - credentialsRaw, ok := data.GetOk("credentials") - if ok { - _, err := gcputil.Credentials(credentialsRaw.(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid credentials JSON file: %v", err)), nil - } - cfg.CredentialsRaw = credentialsRaw.(string) - } - - // Update token TTL. - ttlRaw, ok := data.GetOk("ttl") - if ok { - cfg.TTL = time.Duration(ttlRaw.(int)) * time.Second - } - - // Update token Max TTL. - maxTTLRaw, ok := data.GetOk("max_ttl") - if ok { - cfg.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second - } - - entry, err := logical.StorageEntryJSON("config", cfg) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type config struct { - CredentialsRaw string - - TTL time.Duration - MaxTTL time.Duration -} - -func getConfig(ctx context.Context, s logical.Storage) (*config, error) { - var cfg config - cfgRaw, err := s.Get(ctx, "config") - if err != nil { - return nil, err - } - if cfgRaw == nil { - return nil, nil - } - - if err := cfgRaw.DecodeJSON(&cfg); err != nil { - return nil, err - } - - return &cfg, err -} - -const pathConfigHelpSyn = ` -Configure the GCP backend. -` - -const pathConfigHelpDesc = ` -The GCP backend requires credentials for managing IAM service accounts and keys -and IAM policies on various GCP resources. This endpoint is used to configure -those credentials as well as default values for the backend in general. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_role_set.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_role_set.go deleted file mode 100644 index 781cb0994..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/path_role_set.go +++ /dev/null @@ -1,521 +0,0 @@ -package gcpsecrets - -import ( - "context" - "errors" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/iamutil" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/util" - "github.com/hashicorp/vault/helper/useragent" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "google.golang.org/api/iam/v1" -) - -const ( - rolesetStoragePrefix = "roleset" -) - -func pathsRoleSet(b *backend) []*framework.Path { - return []*framework.Path{ - { - Pattern: fmt.Sprintf("roleset/%s", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Required. Name of the role.", - }, - "secret_type": { - Type: framework.TypeString, - Description: fmt.Sprintf("Type of secret generated for this role set. Defaults to '%s'", SecretTypeAccessToken), - Default: SecretTypeAccessToken, - }, - "project": { - Type: framework.TypeString, - Description: "Name of the GCP project that this roleset's service account will belong to.", - }, - "bindings": { - Type: framework.TypeString, - Description: "Bindings configuration string.", - }, - "token_scopes": { - Type: framework.TypeCommaStringSlice, - Description: `List of OAuth scopes to assign to credentials generated under this role set`, - }, - }, - ExistenceCheck: b.pathRoleSetExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathRoleSetDelete, - logical.ReadOperation: b.pathRoleSetRead, - logical.CreateOperation: b.pathRoleSetCreateUpdate, - logical.UpdateOperation: b.pathRoleSetCreateUpdate, - }, - HelpSynopsis: pathRoleSetHelpSyn, - HelpDescription: pathRoleSetHelpDesc, - }, - // Path to rotate role set service accounts - { - Pattern: fmt.Sprintf("roleset/%s/rotate", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - ExistenceCheck: b.pathRoleSetExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSetRotateAccount, - }, - HelpSynopsis: pathRoleSetRotateHelpSyn, - HelpDescription: pathRoleSetRotateHelpDesc, - }, - // Path to rotating role set service account key used to generate access tokens - { - Pattern: fmt.Sprintf("roleset/%s/rotate-key", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - ExistenceCheck: b.pathRoleSetExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSetRotateKey, - }, - HelpSynopsis: pathRoleSetRotateKeyHelpSyn, - HelpDescription: pathRoleSetRotateKeyHelpDesc, - }, - // Paths for listing role sets - { - Pattern: "rolesets/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleSetList, - }, - - HelpSynopsis: pathListRoleSetHelpSyn, - HelpDescription: pathListRoleSetHelpDesc, - }, - { - Pattern: "roleset/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleSetList, - }, - - HelpSynopsis: pathListRoleSetHelpSyn, - HelpDescription: pathListRoleSetHelpDesc, - }, - } -} - -func (b *backend) pathRoleSetExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) { - nameRaw, ok := d.GetOk("name") - if !ok { - return false, errors.New("roleset name is required") - } - - rs, err := getRoleSet(nameRaw.(string), ctx, req.Storage) - if err != nil { - return false, err - } - - return rs != nil, nil -} - -func (b *backend) pathRoleSetRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - nameRaw, ok := d.GetOk("name") - if !ok { - return logical.ErrorResponse("name is required"), nil - } - - rs, err := getRoleSet(nameRaw.(string), ctx, req.Storage) - if err != nil { - return nil, err - } - if rs == nil { - return nil, nil - } - - data := map[string]interface{}{ - "secret_type": rs.SecretType, - "bindings": rs.Bindings.asOutput(), - } - - if rs.AccountId != nil { - data["service_account_email"] = rs.AccountId.EmailOrId - data["service_account_project"] = rs.AccountId.Project - } - - if rs.TokenGen != nil && rs.SecretType == SecretTypeAccessToken { - data["token_scopes"] = rs.TokenGen.Scopes - } - - return &logical.Response{ - Data: data, - }, nil -} - -func (b *backend) pathRoleSetDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - nameRaw, ok := d.GetOk("name") - if !ok { - return logical.ErrorResponse("name is required"), nil - } - rsName := nameRaw.(string) - - rs, err := getRoleSet(rsName, ctx, req.Storage) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("unable to get role set %s: {{err}}", rsName), err) - } - if rs == nil { - return nil, nil - } - - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - if rs.AccountId != nil { - _, err := framework.PutWAL(ctx, req.Storage, walTypeAccount, &walAccount{ - RoleSet: rsName, - Id: *rs.AccountId, - }) - if err != nil { - return nil, errwrap.Wrapf("unable to create WAL entry to clean up service account: {{err}}", err) - } - - for resName, roleSet := range rs.Bindings { - _, err := framework.PutWAL(ctx, req.Storage, walTypeIamPolicy, &walIamPolicy{ - RoleSet: rsName, - AccountId: *rs.AccountId, - Resource: resName, - Roles: roleSet.ToSlice(), - }) - if err != nil { - return nil, errwrap.Wrapf("unable to create WAL entry to clean up service account bindings: {{err}}", err) - } - } - - if rs.TokenGen != nil { - _, err := framework.PutWAL(ctx, req.Storage, walTypeAccount, &walAccountKey{ - RoleSet: rsName, - ServiceAccountName: rs.AccountId.ResourceName(), - KeyName: rs.TokenGen.KeyName, - }) - if err != nil { - return nil, errwrap.Wrapf("unable to create WAL entry to clean up service account key: {{err}}", err) - } - } - } - - if err := req.Storage.Delete(ctx, fmt.Sprintf("roleset/%s", nameRaw)); err != nil { - return nil, err - } - - // Clean up resources: - httpC, err := newHttpClient(ctx, req.Storage) - if err != nil { - return nil, err - } - - iamAdmin, err := iam.New(httpC) - if err != nil { - return nil, err - } - - iamHandle := iamutil.GetIamHandle(httpC, useragent.String()) - - warnings := make([]string, 0) - if rs.AccountId != nil { - if err := b.deleteServiceAccount(ctx, iamAdmin, rs.AccountId); err != nil { - w := fmt.Sprintf("unable to delete service account '%s' (WAL entry to clean-up later has been added): %v", rs.AccountId.ResourceName(), err) - warnings = append(warnings, w) - } - if err := b.deleteTokenGenKey(ctx, iamAdmin, rs.TokenGen); err != nil { - w := fmt.Sprintf("unable to delete key for service account '%s' (WAL entry to clean-up later has been added): %v", rs.AccountId.ResourceName(), err) - warnings = append(warnings, w) - } - if merr := b.removeBindings(ctx, iamHandle, rs.AccountId.EmailOrId, rs.Bindings); merr != nil { - for _, err := range merr.Errors { - w := fmt.Sprintf("unable to delete IAM policy bindings for service account '%s' (WAL entry to clean-up later has been added): %v", rs.AccountId.EmailOrId, err) - warnings = append(warnings, w) - } - } - } - - if len(warnings) > 0 { - return &logical.Response{Warnings: warnings}, nil - } - - return nil, nil -} - -func (b *backend) pathRoleSetCreateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var warnings []string - nameRaw, ok := d.GetOk("name") - if !ok { - return logical.ErrorResponse("name is required"), nil - } - name := nameRaw.(string) - - rs, err := getRoleSet(name, ctx, req.Storage) - if err != nil { - return nil, err - } - - if rs == nil { - rs = &RoleSet{ - Name: name, - } - } - - isCreate := req.Operation == logical.CreateOperation - - // Secret type - if isCreate { - secretType := d.Get("secret_type").(string) - switch secretType { - case SecretTypeKey, SecretTypeAccessToken: - rs.SecretType = secretType - default: - return logical.ErrorResponse(fmt.Sprintf(`invalid "secret_type" value: "%s"`, secretType)), nil - } - } else { - secretTypeRaw, ok := d.GetOk("secret_type") - if ok && rs.SecretType != secretTypeRaw.(string) { - return logical.ErrorResponse("cannot change secret_type after roleset creation"), nil - } - } - - // Project - var project string - projectRaw, ok := d.GetOk("project") - if ok { - project = projectRaw.(string) - if !isCreate && rs.AccountId.Project != project { - return logical.ErrorResponse(fmt.Sprintf("cannot change project for existing role set (old: %s, new: %s)", rs.AccountId.Project, project)), nil - } - if len(project) == 0 { - return logical.ErrorResponse("given empty project"), nil - } - } else { - if isCreate { - return logical.ErrorResponse("project argument is required for new role set"), nil - } - project = rs.AccountId.Project - } - - // Default scopes - var scopes []string - scopesRaw, ok := d.GetOk("token_scopes") - if ok { - if rs.SecretType != SecretTypeAccessToken { - warnings = []string{ - fmt.Sprintf("ignoring token_scopes, only valid for '%s' secret type role set", SecretTypeAccessToken), - } - } - scopes = scopesRaw.([]string) - if len(scopes) == 0 { - return logical.ErrorResponse("cannot provide empty token_scopes"), nil - } - } else if rs.SecretType == SecretTypeAccessToken { - if isCreate { - return logical.ErrorResponse("token_scopes must be provided for creating access token role set"), nil - } - if rs.TokenGen != nil { - scopes = rs.TokenGen.Scopes - } - } - - // Bindings - bRaw, newBindings := d.GetOk("bindings") - if len(bRaw.(string)) == 0 { - return logical.ErrorResponse("given empty bindings string"), nil - } - - if isCreate && newBindings == false { - return logical.ErrorResponse("bindings are required for new role set"), nil - } - - if !newBindings { - // Just save role with updated metadata: - if err := rs.save(ctx, req.Storage); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - return nil, nil - } - - // If new bindings, update service account. - var bindings ResourceBindings - bindings, err = util.ParseBindings(bRaw.(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to parse bindings: %v", err)), nil - } - if len(bindings) == 0 { - return logical.ErrorResponse("unable to parse any bindings from given bindings HCL"), nil - } - rs.RawBindings = bRaw.(string) - updateWarns, err := b.saveRoleSetWithNewAccount(ctx, req.Storage, rs, project, bindings, scopes) - if updateWarns != nil { - warnings = append(warnings, updateWarns...) - } - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } else if warnings != nil && len(warnings) > 0 { - return &logical.Response{Warnings: warnings}, nil - } - return nil, nil -} - -func (b *backend) pathRoleSetList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - rolesets, err := req.Storage.List(ctx, "roleset/") - if err != nil { - return nil, err - } - return logical.ListResponse(rolesets), nil -} - -func (b *backend) pathRoleSetRotateAccount(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - nameRaw, ok := d.GetOk("name") - if !ok { - return logical.ErrorResponse("name is required"), nil - } - name := nameRaw.(string) - - rs, err := getRoleSet(name, ctx, req.Storage) - if err != nil { - return nil, err - } - if rs == nil { - return logical.ErrorResponse(fmt.Sprintf("roleset '%s' not found", name)), nil - } - - var scopes []string - if rs.TokenGen != nil { - scopes = rs.TokenGen.Scopes - } - - warnings, err := b.saveRoleSetWithNewAccount(ctx, req.Storage, rs, rs.AccountId.Project, nil, scopes) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } else if warnings != nil && len(warnings) > 0 { - return &logical.Response{Warnings: warnings}, nil - } - return nil, nil -} - -func (b *backend) pathRoleSetRotateKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - nameRaw, ok := d.GetOk("name") - if !ok { - return logical.ErrorResponse("name is required"), nil - } - name := nameRaw.(string) - - rs, err := getRoleSet(name, ctx, req.Storage) - if err != nil { - return nil, err - } - if rs == nil { - return logical.ErrorResponse(fmt.Sprintf("roleset '%s' not found", name)), nil - } - - if rs.SecretType != SecretTypeAccessToken { - return logical.ErrorResponse("cannot rotate key for non-access-token role set"), nil - } - var scopes []string - if rs.TokenGen != nil { - scopes = rs.TokenGen.Scopes - } - warn, err := b.saveRoleSetWithNewTokenKey(ctx, req.Storage, rs, scopes) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - if warn != "" { - return &logical.Response{Warnings: []string{warn}}, nil - } - return nil, nil -} - -func getRoleSet(name string, ctx context.Context, s logical.Storage) (*RoleSet, error) { - entry, err := s.Get(ctx, fmt.Sprintf("%s/%s", rolesetStoragePrefix, name)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - rs := &RoleSet{} - if err := entry.DecodeJSON(rs); err != nil { - return nil, err - } - return rs, nil -} - -const pathRoleSetHelpSyn = `Read/write sets of IAM roles to be given to generated credentials for specified GCP resources.` -const pathListRoleSetHelpSyn = `List existing rolesets.` -const pathRoleSetRotateHelpSyn = `Rotate the service account (and key for access token roleset) created and used to generate secrets` -const pathRoleSetRotateKeyHelpSyn = `Rotate only the service account key used by an access token roleset to generate tokens` - -const pathRoleSetRotateHelpDesc = ` -This path allows you to rotate (i.e. recreate) the service account used to -generate secrets for a given role set.` -const pathRoleSetRotateKeyHelpDesc = ` -This path allows you to rotate (i.e. recreate) the service account -key used to generate access tokens under a given role set. This -path only applies to role sets that generate access tokens ` - -const pathRoleSetHelpDesc = ` -This path allows you create role sets, which bind sets of IAM roles -to specific GCP resources. Secrets (either service account keys or -access tokens) are generated under a role set and will have the -given set of roles on resources. - -The specified binding file accepts an HCL (or JSON) string -with the following format: - -resource "some/gcp/resource/uri" { - roles = [ - "roles/role1", - "roles/role2", - "roles/role3", - ... - ] -} - -The given resource can have the following - -* Project-level self link - Self-link for a resource under a given project - (i.e. resource name starts with 'projects/...') - Use if you need to provide a versioned object or - are directly using resource.self_link. - - Example (Compute instance): - http://www.googleapis.com/compute/v1/projects/$PROJECT/zones/$ZONE/instances/$INSTANCE_NAME - -* Full Resource Name - A scheme-less URI consisting of a DNS-compatible - API service name and a resource path (i.e. the - relative resource name). Useful if you need to - specify what service this resource is under - but just want the preferred supported API version. - Note that if the resource you are using is for - a non-preferred API with multiple service versions, - you MUST specify the version. - - Example (IAM service account): - //$SERVICE.googleapis.com/projects/my-project/serviceAccounts/myserviceaccount@... - -* Relative Resource Name: - A URI path (path-noscheme) without the leading "/". - It identifies a resource within the API service. - Use if there is only one service that your - resource could belong to. If there are multiple - API versions that support the resource, we will - attempt to use the preferred version and ask - for more specific format otherwise. - - Example (Pubsub subscription): - projects/myproject/subscriptions/mysub -` -const pathListRoleSetHelpDesc = `List role sets by role set name` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/role_set.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/role_set.go deleted file mode 100644 index 5f895d30f..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/role_set.go +++ /dev/null @@ -1,417 +0,0 @@ -package gcpsecrets - -import ( - "context" - "crypto/sha256" - "encoding/base64" - "errors" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/iamutil" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/util" - "github.com/hashicorp/vault/helper/useragent" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "google.golang.org/api/iam/v1" - "regexp" -) - -const ( - serviceAccountMaxLen = 30 - serviceAccountDisplayNameTmpl = "Service account for Vault secrets backend role set %s" - defaultCloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" -) - -type RoleSet struct { - Name string - SecretType string - - RawBindings string - Bindings ResourceBindings - - AccountId *gcputil.ServiceAccountId - TokenGen *TokenGenerator -} - -func (rs *RoleSet) validate() error { - var err *multierror.Error - if rs.Name == "" { - err = multierror.Append(err, errors.New("role set name is empty")) - } - - if rs.SecretType == "" { - err = multierror.Append(err, errors.New("role set secret type is empty")) - } - - if rs.AccountId == nil { - err = multierror.Append(err, fmt.Errorf("role set should have account associated")) - } - - if len(rs.Bindings) == 0 { - err = multierror.Append(err, fmt.Errorf("role set bindings cannot be empty")) - } - - if len(rs.RawBindings) == 0 { - err = multierror.Append(err, fmt.Errorf("role set raw bindings cannot be empty string")) - } - - switch rs.SecretType { - case SecretTypeAccessToken: - if rs.TokenGen == nil { - err = multierror.Append(err, fmt.Errorf("access token role set should have initialized token generator")) - } else if len(rs.TokenGen.Scopes) == 0 { - err = multierror.Append(err, fmt.Errorf("access token role set should have defined scopes")) - } - case SecretTypeKey: - break - default: - err = multierror.Append(err, fmt.Errorf("unknown secret type: %s", rs.SecretType)) - } - return err.ErrorOrNil() -} - -func (rs *RoleSet) save(ctx context.Context, s logical.Storage) error { - if err := rs.validate(); err != nil { - return err - } - - entry, err := logical.StorageEntryJSON(fmt.Sprintf("%s/%s", rolesetStoragePrefix, rs.Name), rs) - if err != nil { - return err - } - - return s.Put(ctx, entry) -} - -func (rs *RoleSet) bindingHash() string { - ssum := sha256.Sum256([]byte(rs.RawBindings)[:]) - return base64.StdEncoding.EncodeToString(ssum[:]) -} - -func (rs *RoleSet) getServiceAccount(iamAdmin *iam.Service) (*iam.ServiceAccount, error) { - if rs.AccountId == nil { - return nil, fmt.Errorf("role set '%s' is invalid, has no associated service account", rs.Name) - } - - account, err := iamAdmin.Projects.ServiceAccounts.Get(rs.AccountId.ResourceName()).Do() - if err != nil { - return nil, fmt.Errorf("could not find service account: %v. If account was deleted, role set must be updated (write to roleset/%s/rotate) before generating new secrets", err, rs.Name) - } else if account == nil { - return nil, fmt.Errorf("roleset service account was removed - role set must be updated (path roleset/%s/rotate) before generating new secrets", rs.Name) - } - - return account, nil -} - -type ResourceBindings map[string]util.StringSet - -func (rb ResourceBindings) asOutput() map[string][]string { - out := make(map[string][]string) - for k, v := range rb { - out[k] = v.ToSlice() - } - return out -} - -type TokenGenerator struct { - KeyName string - B64KeyJSON string - - Scopes []string -} - -func (b *backend) saveRoleSetWithNewAccount(ctx context.Context, s logical.Storage, rs *RoleSet, project string, newBinds ResourceBindings, scopes []string) (warning []string, err error) { - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - httpC, err := newHttpClient(ctx, s, defaultCloudPlatformScope) - if err != nil { - return nil, err - } - - iamAdmin, err := newIamAdmin(ctx, s) - if err != nil { - return nil, err - } - - iamHandle := iamutil.GetIamHandle(httpC, useragent.String()) - - oldAccount := rs.AccountId - oldBindings := rs.Bindings - oldTokenKey := rs.TokenGen - - oldWals, err := rs.addWALsForCurrentAccount(ctx, s) - if err != nil { - tryDeleteWALs(ctx, s, oldWals...) - return nil, errwrap.Wrapf("failed to create WAL for cleaning up old account: {{err}}", err) - } - - newWals := make([]string, 0, len(newBinds)+2) - walId, err := rs.newServiceAccount(ctx, s, iamAdmin, project) - if err != nil { - tryDeleteWALs(ctx, s, oldWals...) - return nil, err - } - newWals = append(newWals, walId) - - binds := rs.Bindings - if newBinds != nil { - binds = newBinds - rs.Bindings = newBinds - } - walIds, err := rs.updateIamPolicies(ctx, s, b.iamResources, iamHandle, binds) - if err != nil { - tryDeleteWALs(ctx, s, oldWals...) - return nil, err - } - newWals = append(newWals, walIds...) - - if rs.SecretType == SecretTypeAccessToken { - walId, err := rs.newKeyForTokenGen(ctx, s, iamAdmin, scopes) - if err != nil { - tryDeleteWALs(ctx, s, oldWals...) - return nil, err - } - newWals = append(newWals, walId) - } - - if err := rs.save(ctx, s); err != nil { - tryDeleteWALs(ctx, s, oldWals...) - return nil, err - } - - // Delete WALs for cleaning up new resources now that they have been saved. - tryDeleteWALs(ctx, s, newWals...) - - // Try deleting old resources (WALs exist so we can ignore failures) - if oldAccount == nil || oldAccount.EmailOrId == "" { - // nothing to clean up - return nil, nil - } - - // Return any errors as warnings so user knows immediate cleanup failed - warnings := make([]string, 0) - if errs := b.removeBindings(ctx, iamHandle, oldAccount.EmailOrId, oldBindings); errs != nil { - warnings = make([]string, len(errs.Errors), len(errs.Errors)+2) - for idx, err := range errs.Errors { - warnings[idx] = fmt.Sprintf("unable to immediately delete old binding (WAL cleanup entry has been added): %v", err) - } - } - if err := b.deleteServiceAccount(ctx, iamAdmin, oldAccount); err != nil { - warnings = append(warnings, fmt.Sprintf("unable to immediately delete old account (WAL cleanup entry has been added): %v", err)) - } - if err := b.deleteTokenGenKey(ctx, iamAdmin, oldTokenKey); err != nil { - warnings = append(warnings, fmt.Sprintf("unable to immediately delete old key (WAL cleanup entry has been added): %v", err)) - } - return warnings, nil -} - -func (b *backend) saveRoleSetWithNewTokenKey(ctx context.Context, s logical.Storage, rs *RoleSet, scopes []string) (warning string, err error) { - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - if rs.SecretType != SecretTypeAccessToken { - return "", fmt.Errorf("a key is not saved or used for non-access-token role set '%s'", rs.Name) - } - - iamAdmin, err := newIamAdmin(ctx, s) - if err != nil { - return "", err - } - - oldKeyWalId := "" - if rs.TokenGen != nil { - if oldKeyWalId, err = framework.PutWAL(ctx, s, walTypeAccountKey, &walAccountKey{ - RoleSet: rs.Name, - KeyName: rs.TokenGen.KeyName, - ServiceAccountName: rs.AccountId.ResourceName(), - }); err != nil { - return "", errwrap.Wrapf("unable to create WAL for deleting old key: {{err}}", err) - } - } - oldKeyGen := rs.TokenGen - - newKeyWalId, err := rs.newKeyForTokenGen(ctx, s, iamAdmin, scopes) - if err != nil { - tryDeleteWALs(ctx, s, oldKeyWalId) - return "", err - } - - if err := rs.save(ctx, s); err != nil { - tryDeleteWALs(ctx, s, oldKeyWalId) - return "", err - } - - // Delete WALs for cleaning up new key now that it's been saved. - tryDeleteWALs(ctx, s, newKeyWalId) - if err := b.deleteTokenGenKey(ctx, iamAdmin, oldKeyGen); err != nil { - return errwrap.Wrapf("unable to delete old key (delayed cleaned up WAL entry added): {{err}}", err).Error(), nil - } - - return "", nil -} - -func (rs *RoleSet) addWALsForCurrentAccount(ctx context.Context, s logical.Storage) ([]string, error) { - if rs.AccountId == nil { - return nil, nil - } - wals := make([]string, 0, len(rs.Bindings)+2) - walId, err := framework.PutWAL(ctx, s, walTypeAccount, &walAccount{ - RoleSet: rs.Name, - Id: gcputil.ServiceAccountId{ - Project: rs.AccountId.Project, - EmailOrId: rs.AccountId.EmailOrId, - }, - }) - if err != nil { - return nil, err - } - wals = append(wals, walId) - for resource, roles := range rs.Bindings { - var walId string - walId, err = framework.PutWAL(ctx, s, walTypeIamPolicy, &walIamPolicy{ - RoleSet: rs.Name, - AccountId: gcputil.ServiceAccountId{ - Project: rs.AccountId.Project, - EmailOrId: rs.AccountId.EmailOrId, - }, - Resource: resource, - Roles: roles.ToSlice(), - }) - if err != nil { - return nil, err - } - wals = append(wals, walId) - } - - if rs.SecretType == SecretTypeAccessToken && rs.TokenGen != nil { - walId, err := framework.PutWAL(ctx, s, walTypeAccountKey, &walAccountKey{ - RoleSet: rs.Name, - KeyName: rs.TokenGen.KeyName, - ServiceAccountName: rs.AccountId.ResourceName(), - }) - if err != nil { - return nil, err - } - wals = append(wals, walId) - } - return wals, nil -} - -func (rs *RoleSet) newServiceAccount(ctx context.Context, s logical.Storage, iamAdmin *iam.Service, project string) (string, error) { - saEmailPrefix := roleSetServiceAccountName(rs.Name) - projectName := fmt.Sprintf("projects/%s", project) - displayName := fmt.Sprintf(serviceAccountDisplayNameTmpl, rs.Name) - - walId, err := framework.PutWAL(ctx, s, walTypeAccount, &walAccount{ - RoleSet: rs.Name, - Id: gcputil.ServiceAccountId{ - Project: project, - EmailOrId: fmt.Sprintf("%s@%s.iam.gserviceaccount.com", saEmailPrefix, project), - }, - }) - if err != nil { - return "", errwrap.Wrapf("unable to create WAL entry for generating new service account: {{err}}", err) - } - - sa, err := iamAdmin.Projects.ServiceAccounts.Create( - projectName, &iam.CreateServiceAccountRequest{ - AccountId: saEmailPrefix, - ServiceAccount: &iam.ServiceAccount{DisplayName: displayName}, - }).Do() - if err != nil { - return walId, errwrap.Wrapf(fmt.Sprintf("unable to create new service account under project '%s': {{err}}", projectName), err) - } - rs.AccountId = &gcputil.ServiceAccountId{ - Project: project, - EmailOrId: sa.Email, - } - return walId, nil -} - -func (rs *RoleSet) newKeyForTokenGen(ctx context.Context, s logical.Storage, iamAdmin *iam.Service, scopes []string) (string, error) { - walId, err := framework.PutWAL(ctx, s, walTypeAccountKey, &walAccountKey{ - RoleSet: rs.Name, - KeyName: "", - ServiceAccountName: rs.AccountId.ResourceName(), - }) - if err != nil { - return "", err - } - - key, err := iamAdmin.Projects.ServiceAccounts.Keys.Create(rs.AccountId.ResourceName(), - &iam.CreateServiceAccountKeyRequest{ - PrivateKeyType: privateKeyTypeJson, - }).Do() - if err != nil { - framework.DeleteWAL(ctx, s, walId) - return "", err - } - rs.TokenGen = &TokenGenerator{ - KeyName: key.Name, - B64KeyJSON: key.PrivateKeyData, - Scopes: scopes, - } - return walId, nil -} - -func (rs *RoleSet) updateIamPolicies(ctx context.Context, s logical.Storage, enabledIamResources iamutil.IamResourceParser, iamHandle *iamutil.IamHandle, rb ResourceBindings) ([]string, error) { - wals := make([]string, 0, len(rb)) - for rName, roles := range rb { - walId, err := framework.PutWAL(ctx, s, walTypeIamPolicy, &walIamPolicy{ - RoleSet: rs.Name, - AccountId: gcputil.ServiceAccountId{ - Project: rs.AccountId.Project, - EmailOrId: rs.AccountId.EmailOrId, - }, - Resource: rName, - Roles: roles.ToSlice(), - }) - if err != nil { - return wals, err - } - - resource, err := enabledIamResources.Parse(rName) - if err != nil { - return wals, err - } - - p, err := iamHandle.GetIamPolicy(ctx, resource) - if err != nil { - return wals, err - } - - changed, newP := p.AddBindings(&iamutil.PolicyDelta{ - Roles: roles, - Email: rs.AccountId.EmailOrId, - }) - if !changed || newP == nil { - continue - } - - if _, err := iamHandle.SetIamPolicy(ctx, resource, newP); err != nil { - return wals, err - } - wals = append(wals, walId) - } - return wals, nil -} - -func roleSetServiceAccountName(rsName string) (name string) { - // Sanitize role name - reg := regexp.MustCompile("[^a-zA-Z0-9-]+") - rsName = reg.ReplaceAllString(rsName, "-") - - intSuffix := fmt.Sprintf("%d", time.Now().Unix()) - fullName := fmt.Sprintf("vault%s-%s", rsName, intSuffix) - name = fullName - if len(fullName) > serviceAccountMaxLen { - toTrunc := len(fullName) - serviceAccountMaxLen - name = fmt.Sprintf("vault%s-%s", rsName[:len(rsName)-toTrunc], intSuffix) - } - return name -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/rollback.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/rollback.go deleted file mode 100644 index b061e71bc..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/rollback.go +++ /dev/null @@ -1,277 +0,0 @@ -package gcpsecrets - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/iamutil" - "github.com/hashicorp/vault-plugin-secrets-gcp/plugin/util" - "github.com/hashicorp/vault/helper/useragent" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" - "google.golang.org/api/googleapi" - "google.golang.org/api/iam/v1" -) - -const ( - walTypeAccount = "account" - walTypeAccountKey = "account_key" - walTypeIamPolicy = "iam_policy" -) - -func (b *backend) walRollback(ctx context.Context, req *logical.Request, kind string, data interface{}) error { - switch kind { - case walTypeAccount: - return b.serviceAccountRollback(ctx, req, data) - case walTypeAccountKey: - return b.serviceAccountKeyRollback(ctx, req, data) - case walTypeIamPolicy: - return b.serviceAccountPolicyRollback(ctx, req, data) - default: - return fmt.Errorf("unknown type to rollback") - } -} - -type walAccount struct { - RoleSet string - Id gcputil.ServiceAccountId -} - -type walAccountKey struct { - RoleSet string - ServiceAccountName string - KeyName string -} - -type walIamPolicy struct { - RoleSet string - AccountId gcputil.ServiceAccountId - Resource string - Roles []string -} - -func (b *backend) serviceAccountRollback(ctx context.Context, req *logical.Request, data interface{}) error { - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - var entry walAccount - if err := mapstructure.Decode(data, &entry); err != nil { - return err - } - - // If account is still being used, WAL entry was not - // deleted properly after a successful operation. - // Remove WAL entry. - rs, err := getRoleSet(entry.RoleSet, ctx, req.Storage) - if err != nil { - return err - } - if rs != nil && entry.Id.ResourceName() == rs.AccountId.ResourceName() { - // Still being used - don't delete this service account. - return nil - } - - // Delete service account. - iamC, err := newIamAdmin(ctx, req.Storage) - if err != nil { - return err - } - - return b.deleteServiceAccount(ctx, iamC, &entry.Id) -} - -func (b *backend) serviceAccountKeyRollback(ctx context.Context, req *logical.Request, data interface{}) error { - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - var entry walAccountKey - if err := mapstructure.Decode(data, &entry); err != nil { - return err - } - - // If key is still being used, WAL entry was not - // deleted properly after a successful operation. - // Remove WAL entry. - rs, err := getRoleSet(entry.RoleSet, ctx, req.Storage) - if err != nil { - return err - } - if rs != nil && rs.TokenGen != nil && entry.KeyName == rs.TokenGen.KeyName { - return nil - } - - iamC, err := newIamAdmin(ctx, req.Storage) - if err != nil { - return err - } - - if entry.KeyName == "" { - if rs.SecretType != SecretTypeAccessToken { - // Do not clean up non-access-token role set keys. - return nil - } - - // delete all keys not in use by role set - keys, err := iamC.Projects.ServiceAccounts.Keys.List(rs.AccountId.ResourceName()).KeyTypes("USER_MANAGED").Do() - if err != nil && !isGoogleApi404Error(err) { - return err - } else if err != nil || keys == nil { - return nil - } - - for _, k := range keys.Keys { - if rs.TokenGen != nil && rs.TokenGen.KeyName == k.Name { - continue - } - // Delete all keys not being used by role set - _, err = iamC.Projects.ServiceAccounts.Keys.Delete(entry.KeyName).Do() - if err != nil && !isGoogleApi404Error(err) { - return err - } - } - } else { - _, err = iamC.Projects.ServiceAccounts.Keys.Delete(entry.KeyName).Do() - if err != nil && !isGoogleApi404Error(err) { - return err - } - } - return nil -} - -func (b *backend) serviceAccountPolicyRollback(ctx context.Context, req *logical.Request, data interface{}) error { - b.rolesetLock.Lock() - defer b.rolesetLock.Unlock() - - var entry walIamPolicy - if err := mapstructure.Decode(data, &entry); err != nil { - return err - } - - // Try to verify service account not being used by roleset - rs, err := getRoleSet(entry.RoleSet, ctx, req.Storage) - if err != nil { - return err - } - - // Take out any bindings still being used by this role set from roles being removed. - rolesToRemove := util.ToSet(entry.Roles) - if rs != nil && rs.AccountId.ResourceName() == entry.AccountId.ResourceName() { - currRoles, ok := rs.Bindings[entry.Resource] - if ok { - rolesToRemove = rolesToRemove.Sub(currRoles) - } - } - - r, err := b.iamResources.Parse(entry.Resource) - if err != nil { - return err - } - - httpC, err := newHttpClient(ctx, req.Storage) - if err != nil { - return err - } - - iamHandle := iamutil.GetIamHandle(httpC, useragent.String()) - if err != nil { - return err - } - - p, err := iamHandle.GetIamPolicy(ctx, r) - if err != nil { - return err - } - - changed, newP := p.RemoveBindings( - &iamutil.PolicyDelta{ - Email: entry.AccountId.EmailOrId, - Roles: rolesToRemove, - }) - - if !changed { - return nil - } - - _, err = iamHandle.SetIamPolicy(ctx, r, newP) - return err -} - -func (b *backend) deleteServiceAccount(ctx context.Context, iamAdmin *iam.Service, account *gcputil.ServiceAccountId) error { - if account == nil || account.EmailOrId == "" { - return nil - } - - _, err := iamAdmin.Projects.ServiceAccounts.Delete(account.ResourceName()).Do() - if err != nil && !isGoogleApi404Error(err) { - return errwrap.Wrapf("unable to delete service account: {{err}}", err) - } - return nil -} - -func (b *backend) deleteTokenGenKey(ctx context.Context, iamAdmin *iam.Service, tgen *TokenGenerator) error { - if tgen == nil || tgen.KeyName == "" { - return nil - } - - _, err := iamAdmin.Projects.ServiceAccounts.Keys.Delete(tgen.KeyName).Do() - if err != nil && !isGoogleApi404Error(err) { - return errwrap.Wrapf("unable to delete service account key: {{err}}", err) - } - return nil -} - -func (b *backend) removeBindings(ctx context.Context, iamHandle *iamutil.IamHandle, email string, bindings ResourceBindings) (allErr *multierror.Error) { - for resName, roles := range bindings { - resource, err := b.iamResources.Parse(resName) - if err != nil { - allErr = multierror.Append(allErr, errwrap.Wrapf(fmt.Sprintf("unable to delete role binding for resource '%s': {{err}}", resName), err)) - continue - } - - p, err := iamHandle.GetIamPolicy(ctx, resource) - if err != nil { - allErr = multierror.Append(allErr, errwrap.Wrapf(fmt.Sprintf("unable to delete role binding for resource '%s': {{err}}", resName), err)) - continue - } - - changed, newP := p.RemoveBindings(&iamutil.PolicyDelta{ - Email: email, - Roles: roles, - }) - if !changed { - continue - } - if _, err = iamHandle.SetIamPolicy(ctx, resource, newP); err != nil { - allErr = multierror.Append(allErr, errwrap.Wrapf(fmt.Sprintf("unable to delete role binding for resource '%s': {{err}}", resName), err)) - continue - } - } - return -} - -// This tries to clean up WALs that are no longer needed. -// We can ignore errors if deletion fails as WAL rollback -// will not be done if the object is still in use in the roleset -// or was not actually created. -func tryDeleteWALs(ctx context.Context, s logical.Storage, walIds ...string) { - for _, walId := range walIds { - // ignore errors - if not deleted and still used by - // roleset, will be ignored - framework.DeleteWAL(ctx, s, walId) - } -} - -func isGoogleApi404Error(err error) bool { - if err == nil { - return false - } - gErr, ok := err.(*googleapi.Error) - if ok && gErr.Code == 404 { - return true - } - return false -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_access_token.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_access_token.go deleted file mode 100644 index e603e0297..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_access_token.go +++ /dev/null @@ -1,184 +0,0 @@ -package gcpsecrets - -import ( - "context" - "encoding/base64" - "errors" - "fmt" - "net/http" - "net/url" - "time" - - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "google.golang.org/api/googleapi" - "google.golang.org/api/iam/v1" -) - -const ( - SecretTypeAccessToken = "access_token" - revokeAccessTokenEndpoint = "https://accounts.google.com/o/oauth2/revoke" - revokeTokenWarning = `revocation request was successful; however, due to how OAuth access propagation works, the OAuth token might still be valid until it expires` -) - -func secretAccessToken(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretTypeAccessToken, - Fields: map[string]*framework.FieldSchema{ - "token": { - Type: framework.TypeString, - Description: "OAuth2 token", - }, - }, - Renew: b.secretAccessTokenRenew, - Revoke: b.secretAccessTokenRevoke, - } -} - -func pathSecretAccessToken(b *backend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("token/%s", framework.GenericNameRegex("roleset")), - Fields: map[string]*framework.FieldSchema{ - "roleset": { - Type: framework.TypeString, - Description: "Required. Name of the role set.", - }, - }, - ExistenceCheck: b.pathRoleSetExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathAccessToken, - logical.UpdateOperation: b.pathAccessToken, - }, - HelpSynopsis: pathTokenHelpSyn, - HelpDescription: pathTokenHelpDesc, - } -} - -func (b *backend) pathAccessToken(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - rsName := d.Get("roleset").(string) - - rs, err := getRoleSet(rsName, ctx, req.Storage) - if err != nil { - return nil, err - } - if rs == nil { - return logical.ErrorResponse(fmt.Sprintf("role set '%s' does not exists", rsName)), nil - } - - if rs.SecretType != SecretTypeAccessToken { - return logical.ErrorResponse(fmt.Sprintf("role set '%s' cannot generate access tokens (has secret type %s)", rsName, rs.SecretType)), nil - } - - return b.getSecretAccessToken(ctx, req.Storage, rs) -} - -func (b *backend) secretAccessTokenRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Renewal not allowed - return logical.ErrorResponse("short-term access tokens cannot be renewed - request new access token instead"), nil -} - -func isInvalidTokenErr(err error) bool { - if gerr, ok := err.(*googleapi.Error); ok { - return gerr.Code == 400 && strings.Contains(gerr.Body, "invalid_token") - } - return false -} - -func (b *backend) secretAccessTokenRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - tokenRaw, ok := req.Secret.InternalData["access_token"] - if !ok { - return nil, fmt.Errorf("secret is missing token internal data") - } - - resp, err := http.Get(revokeAccessTokenEndpoint + fmt.Sprintf("?token=%s", url.QueryEscape(tokenRaw.(string)))) - defer googleapi.CloseBody(resp) - if err == nil { - err = googleapi.CheckResponse(resp) - } - - if err != nil { - // Token may have already expired on server; ignore if OAuth server returns error. - if req.Secret.ExpirationTime().Before(time.Now()) && isInvalidTokenErr(err) { - invalidTokenWarn := fmt.Sprintf("manual token revocation failed because token has already been invalidated. ignoring error: '%v'", err) - b.Logger().Warn(invalidTokenWarn) - - return &logical.Response{ - Warnings: []string{invalidTokenWarn}, - }, nil - } - - return logical.ErrorResponse(err.Error()), nil - } - - return &logical.Response{ - Warnings: []string{revokeTokenWarning}, - }, nil -} - -func (b *backend) getSecretAccessToken(ctx context.Context, s logical.Storage, rs *RoleSet) (*logical.Response, error) { - iamC, err := newIamAdmin(ctx, s) - if err != nil { - return nil, errwrap.Wrapf("could not create IAM Admin client: {{err}}", err) - } - - // Verify account still exists - _, err = rs.getServiceAccount(iamC) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not get role set service account: %v", err)), nil - } - - if rs.TokenGen == nil || rs.TokenGen.KeyName == "" { - return logical.ErrorResponse(fmt.Sprintf("invalid role set has no service account key, must be updated (path roleset/%s/rotate-key) before generating new secrets", rs.Name)), nil - } - - token, err := rs.TokenGen.getAccessToken(ctx, iamC) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not generate token: %v", err)), nil - } - - secretD := map[string]interface{}{ - "token": token.AccessToken, - } - internalD := map[string]interface{}{ - "access_token": token.AccessToken, - "key_name": rs.TokenGen.KeyName, - "role_set": rs.Name, - "role_set_bindings": rs.bindingHash(), - } - resp := b.Secret(SecretTypeAccessToken).Response(secretD, internalD) - resp.Secret.TTL = token.Expiry.Sub(time.Now()) - resp.Secret.Renewable = false - - return resp, err -} - -func (tg *TokenGenerator) getAccessToken(ctx context.Context, iamAdmin *iam.Service) (*oauth2.Token, error) { - key, err := iamAdmin.Projects.ServiceAccounts.Keys.Get(tg.KeyName).Do() - if err != nil { - return nil, errwrap.Wrapf("could not verify key used to generate tokens: {{err}}", err) - } - if key == nil { - return nil, errors.New("could not find key used to generate tokens, must update role set") - } - - jsonBytes, err := base64.StdEncoding.DecodeString(tg.B64KeyJSON) - if err != nil { - return nil, errwrap.Wrapf("could not b64-decode key data: {{err}}", err) - } - - cfg, err := google.JWTConfigFromJSON(jsonBytes, tg.Scopes...) - if err != nil { - return nil, errwrap.Wrapf("could not generate token JWT config: {{err}}", err) - } - - tkn, err := cfg.TokenSource(ctx).Token() - if err != nil { - return nil, errwrap.Wrapf("could not generate token: {{err}}", err) - } - return tkn, err -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_service_account_key.go b/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_service_account_key.go deleted file mode 100644 index 1b15b1772..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-gcp/plugin/secrets_service_account_key.go +++ /dev/null @@ -1,237 +0,0 @@ -package gcpsecrets - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "google.golang.org/api/iam/v1" -) - -const ( - SecretTypeKey = "service_account_key" - keyAlgorithmRSA2k = "KEY_ALG_RSA_2048" - privateKeyTypeJson = "TYPE_GOOGLE_CREDENTIALS_FILE" -) - -func secretServiceAccountKey(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretTypeKey, - Fields: map[string]*framework.FieldSchema{ - "private_key_data": { - Type: framework.TypeString, - Description: "Base-64 encoded string. Private key data for a service account key", - }, - "key_algorithm": { - Type: framework.TypeString, - Description: "Which type of key and algorithm to use for the key (defaults to 2K RSA). Valid values are GCP enum(ServiceAccountKeyAlgorithm)", - }, - "key_type": { - Type: framework.TypeString, - Description: "Type of the private key (i.e. whether it is JSON or P12). Valid values are GCP enum(ServiceAccountPrivateKeyType)", - }, - }, - - Renew: b.secretKeyRenew, - Revoke: secretKeyRevoke, - } -} - -func pathSecretServiceAccountKey(b *backend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("key/%s", framework.GenericNameRegex("roleset")), - Fields: map[string]*framework.FieldSchema{ - "roleset": { - Type: framework.TypeString, - Description: "Required. Name of the role set.", - }, - "key_algorithm": { - Type: framework.TypeString, - Description: fmt.Sprintf(`Private key algorithm for service account key - defaults to %s"`, keyAlgorithmRSA2k), - Default: keyAlgorithmRSA2k, - }, - "key_type": { - Type: framework.TypeString, - Description: fmt.Sprintf(`Private key type for service account key - defaults to %s"`, privateKeyTypeJson), - Default: privateKeyTypeJson, - }, - }, - ExistenceCheck: b.pathRoleSetExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathServiceAccountKey, - logical.UpdateOperation: b.pathServiceAccountKey, - }, - HelpSynopsis: pathServiceAccountKeySyn, - HelpDescription: pathServiceAccountKeyDesc, - } -} - -func (b *backend) pathServiceAccountKey(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - rsName := d.Get("roleset").(string) - keyType := d.Get("key_type").(string) - keyAlg := d.Get("key_algorithm").(string) - - rs, err := getRoleSet(rsName, ctx, req.Storage) - if err != nil { - return nil, err - } - if rs == nil { - return logical.ErrorResponse(fmt.Sprintf("role set '%s' does not exists", rsName)), nil - } - - if rs.SecretType != SecretTypeKey { - return logical.ErrorResponse(fmt.Sprintf("role set '%s' cannot generate service account keys (has secret type %s)", rsName, rs.SecretType)), nil - } - - return b.getSecretKey(ctx, req.Storage, rs, keyType, keyAlg) -} - -func (b *backend) secretKeyRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - resp, err := b.verifySecretServiceKeyExists(ctx, req) - if err != nil { - return resp, err - } - if resp == nil { - resp = &logical.Response{} - } - cfg, err := getConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if cfg == nil { - cfg = &config{} - } - - resp.Secret = req.Secret - resp.Secret.TTL = cfg.TTL - resp.Secret.MaxTTL = cfg.MaxTTL - return resp, nil -} - -func (b *backend) verifySecretServiceKeyExists(ctx context.Context, req *logical.Request) (*logical.Response, error) { - keyName, ok := req.Secret.InternalData["key_name"] - if !ok { - return nil, fmt.Errorf("invalid secret, internal data is missing key name") - } - - rsName, ok := req.Secret.InternalData["role_set"] - if !ok { - return nil, fmt.Errorf("invalid secret, internal data is missing role set name") - } - - bindingSum, ok := req.Secret.InternalData["role_set_bindings"] - if !ok { - return nil, fmt.Errorf("invalid secret, internal data is missing role set checksum") - } - - // Verify role set was not deleted. - rs, err := getRoleSet(rsName.(string), ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not find role set '%v' for secret", rsName)), nil - } - - // Verify role set bindings have not changed since secret was generated. - if rs.bindingHash() != bindingSum.(string) { - return logical.ErrorResponse(fmt.Sprintf("role set '%v' bindings were updated since secret was generated, cannot renew", rsName)), nil - } - - // Verify service account key still exists. - iamAdmin, err := newIamAdmin(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse("could not confirm key still exists in GCP"), nil - } - if k, err := iamAdmin.Projects.ServiceAccounts.Keys.Get(keyName.(string)).Do(); err != nil || k == nil { - return logical.ErrorResponse(fmt.Sprintf("could not confirm key still exists in GCP: %v", err)), nil - } - return nil, nil -} - -func secretKeyRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - keyNameRaw, ok := req.Secret.InternalData["key_name"] - if !ok { - return nil, fmt.Errorf("secret is missing key_name internal data") - } - - iamAdmin, err := newIamAdmin(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - _, err = iamAdmin.Projects.ServiceAccounts.Keys.Delete(keyNameRaw.(string)).Do() - if err != nil && !isGoogleApi404Error(err) { - return logical.ErrorResponse(fmt.Sprintf("unable to delete service account key: %v", err)), nil - } - - return nil, nil -} - -func (b *backend) getSecretKey(ctx context.Context, s logical.Storage, rs *RoleSet, keyType, keyAlgorithm string) (*logical.Response, error) { - cfg, err := getConfig(ctx, s) - if err != nil { - return nil, errwrap.Wrapf("could not read backend config: {{err}}", err) - } - if cfg == nil { - cfg = &config{} - } - - iamC, err := newIamAdmin(ctx, s) - if err != nil { - return nil, errwrap.Wrapf("could not create IAM Admin client: {{err}}", err) - } - - account, err := rs.getServiceAccount(iamC) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("roleset service account was removed - role set must be updated (write to roleset/%s/rotate) before generating new secrets", rs.Name)), nil - } - - key, err := iamC.Projects.ServiceAccounts.Keys.Create( - account.Name, &iam.CreateServiceAccountKeyRequest{ - KeyAlgorithm: keyAlgorithm, - PrivateKeyType: keyType, - }).Do() - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - secretD := map[string]interface{}{ - "private_key_data": key.PrivateKeyData, - "key_algorithm": key.KeyAlgorithm, - "key_type": key.PrivateKeyType, - } - internalD := map[string]interface{}{ - "key_name": key.Name, - "role_set": rs.Name, - "role_set_bindings": rs.bindingHash(), - } - - resp := b.Secret(SecretTypeKey).Response(secretD, internalD) - resp.Secret.TTL = cfg.TTL - resp.Secret.MaxTTL = cfg.MaxTTL - resp.Secret.Renewable = true - return resp, nil -} - -const pathTokenHelpSyn = `Generate an OAuth2 access token under a specific role set.` -const pathTokenHelpDesc = ` -This path will generate a new OAuth2 access token for accessing GCP APIs. -A role set, binding IAM roles to specific GCP resources, will be specified -by name - for example, if this backend is mounted at "gcp", -then "gcp/token/deploy" would generate tokens for the "deploy" role set. - -On the backend, each roleset is associated with a service account. -The token will be associated with this service account. Tokens have a -short-term lease (1-hour) associated with them but cannot be renewed. -` - -const pathServiceAccountKeySyn = `Generate an service account private key under a specific role set.` -const pathServiceAccountKeyDesc = ` -This path will generate a new service account private key for accessing GCP APIs. -A role set, binding IAM roles to specific GCP resources, will be specified -by name - for example, if this backend is mounted at "gcp", then "gcp/key/deploy" -would generate service account keys for the "deploy" role set. - -On the backend, each roleset is associated with a service account under -which secrets/keys are created. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.lock b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.lock deleted file mode 100644 index 5fa45aac5..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.lock +++ /dev/null @@ -1,309 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/SermoDigital/jose" - packages = [ - ".", - "crypto", - "jws", - "jwt" - ] - revision = "f6df55f235c24f236d11dbcf665249a59ac2021f" - version = "1.1" - -[[projects]] - branch = "master" - name = "github.com/armon/go-radix" - packages = ["."] - revision = "7fddfc383310abc091d79a27f116d30cf0424032" - -[[projects]] - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp" - ] - revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" - version = "v1.1.0" - -[[projects]] - branch = "master" - name = "github.com/golang/snappy" - packages = ["."] - revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/errwrap" - packages = ["."] - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-cleanhttp" - packages = ["."] - revision = "d5fe4b57a186c716b0e00b8c301cbd9b4182694d" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - packages = ["."] - revision = "ff2cf002a8dd750586d91dddd4470c341f981fe1" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-immutable-radix" - packages = ["."] - revision = "7f3cd4390caab3250a57f30efdb2a65dd7649ecf" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-multierror" - packages = ["."] - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-plugin" - packages = ["."] - revision = "a4620f9913d19f03a6bf19b2f304daaaf83ea130" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-retryablehttp" - packages = ["."] - revision = "e651d75abec6fbd4f2c09508f72ae7af8a8b7171" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-rootcerts" - packages = ["."] - revision = "6bb64b370b90e7ef1fa532be9e591a81c3493e00" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-sockaddr" - packages = ["."] - revision = "6d291a969b86c4b633730bfc6b8b9d64c3aafed9" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-uuid" - packages = ["."] - revision = "27454136f0364f2d44b1276c552d69105cf8c498" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/go-version" - packages = ["."] - revision = "270f2f71b1ee587f3b609f00f422b76a6b28f348" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru" - ] - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token" - ] - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/vault" - packages = [ - "api", - "helper/base62", - "helper/certutil", - "helper/compressutil", - "helper/consts", - "helper/errutil", - "helper/hclutil", - "helper/jsonutil", - "helper/kdf", - "helper/keysutil", - "helper/locksutil", - "helper/logging", - "helper/mlock", - "helper/parseutil", - "helper/pathmanager", - "helper/pluginutil", - "helper/salt", - "helper/strutil", - "helper/wrapping", - "logical", - "logical/framework", - "logical/plugin", - "logical/plugin/pb", - "physical", - "physical/inmem", - "version" - ] - revision = "27ba04d734b87a22d50d10571c1b4da574cb9056" - -[[projects]] - branch = "master" - name = "github.com/hashicorp/yamux" - packages = ["."] - revision = "3520598351bb3500a49ae9563f5539666ae0a27c" - -[[projects]] - branch = "master" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - revision = "58046073cbffe2f25d425fe1331102f55cf719de" - -[[projects]] - branch = "master" - name = "github.com/mitchellh/go-testing-interface" - packages = ["."] - revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28" - -[[projects]] - branch = "master" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" - -[[projects]] - name = "github.com/oklog/run" - packages = ["."] - revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39" - version = "v1.0.0" - -[[projects]] - name = "github.com/ryanuber/go-glob" - packages = ["."] - revision = "572520ed46dbddaed19ea3d9541bdd0494163693" - version = "v0.1" - -[[projects]] - branch = "master" - name = "golang.org/x/crypto" - packages = [ - "chacha20poly1305", - "ed25519", - "ed25519/internal/edwards25519", - "hkdf", - "internal/chacha20", - "internal/subtle", - "poly1305" - ] - revision = "de0752318171da717af4ce24d0a2e8626afaeb11" - -[[projects]] - branch = "master" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace" - ] - revision = "aaf60122140d3fcf75376d319f0554393160eb50" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = [ - "cpu", - "unix" - ] - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable" - ] - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - name = "golang.org/x/time" - packages = ["rate"] - revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" - -[[projects]] - branch = "master" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - revision = "d0a8f471bba2dbb160885b0000d814ee5d559bad" - -[[projects]] - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "health", - "health/grpc_health_v1", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap" - ] - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "740d4e4fd63b71fd35439d84478f05f41a67e634c1d5548418f68fc5c99050e0" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.toml b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.toml deleted file mode 100644 index c454f7740..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Gopkg.toml +++ /dev/null @@ -1,42 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - branch = "master" - name = "github.com/hashicorp/go-hclog" - -[[constraint]] - name = "github.com/hashicorp/vault" - branch = "master" - -[[constraint]] - branch = "master" - name = "github.com/mitchellh/mapstructure" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/LICENSE b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/LICENSE deleted file mode 100644 index a612ad981..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/LICENSE +++ /dev/null @@ -1,373 +0,0 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Makefile b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Makefile deleted file mode 100644 index 38e7d5dc3..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -TOOL?=vault-plugin-secrets-kv -TEST?=$$(go list ./... | grep -v /vendor/) -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/mitchellh/gox \ - github.com/golang/dep/cmd/dep -BUILD_TAGS?=${TOOL} -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -# bin generates the releaseable binaries for this plugin -bin: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'" - -default: dev - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin. -dev: fmtcheck generate - @CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -# test runs the unit tests and vets the code -test: fmtcheck generate - CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -count=1 -timeout=20m -parallel=4 - -testcompile: fmtcheck generate - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# generate runs `go generate` to build the dynamically generated -# source files. -generate: - go generate $(go list ./... | grep -v /vendor/) - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - gofmt -w $(GOFMT_FILES) - -proto: - protoc *.proto --go_out=plugins=grpc:. - -.PHONY: bin default generate test vet bootstrap fmt fmtcheck diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/README.md b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/README.md deleted file mode 100644 index f92747837..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/README.md +++ /dev/null @@ -1,125 +0,0 @@ -# Vault Plugin: Key-Value Secrets Backend [![Build Status](https://travis-ci.org/hashicorp/vault-plugin-secrets-kv.svg?branch=master)](https://travis-ci.org/hashicorp/vault-plugin-secrets-kv) - -This is a standalone backend plugin for use with [Hashicorp Vault](https://www.github.com/hashicorp/vault). -This plugin provides Key-Value functionality to Vault. - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - -## Quick Links - - Vault Website: https://www.vaultproject.io - - KV Docs: https://www.vaultproject.io/docs/secrets/kv/index.html - - Main Project Github: https://www.github.com/hashicorp/vault - -## Getting Started - -This is a [Vault plugin](https://www.vaultproject.io/docs/internals/plugins.html) -and is meant to work with Vault. This guide assumes you have already installed Vault -and have a basic understanding of how Vault works. - -Otherwise, first read this guide on how to [get started with Vault](https://www.vaultproject.io/intro/getting-started/install.html). - -To learn specifically about how plugins work, see documentation on [Vault plugins](https://www.vaultproject.io/docs/internals/plugins.html). - -## Usage - -Please see [documentation for the plugin](https://www.vaultproject.io/docs/secrets/kv/index.html) -on the Vault website. - -This plugin is currently built into Vault and by default is accessed -at `kv`. To enable this in a running Vault server: - -```sh -$ vault secrets enable kv -Success! Enabled the kv secrets engine at: kv/ -``` - -Additionally starting with Vault 0.10 this backend is by default mounted -at `secret/`. - -## Developing - -If you wish to work on this plugin, you'll first need -[Go](https://www.golang.org) installed on your machine -(version 1.10+ is *required*). - -For local dev first make sure Go is properly installed, including -setting up a [GOPATH](https://golang.org/doc/code.html#GOPATH). -Next, clone this repository into -`$GOPATH/src/github.com/hashicorp/vault-plugin-secrets-kv`. -You can then download any required build tools by bootstrapping your -environment: - -```sh -$ make bootstrap -``` - -To compile a development version of this plugin, run `make` or `make dev`. -This will put the plugin binary in the `bin` and `$GOPATH/bin` folders. `dev` -mode will only generate the binary for your platform and is faster: - -```sh -$ make -$ make dev -``` - -Put the plugin binary into a location of your choice. This directory -will be specified as the [`plugin_directory`](https://www.vaultproject.io/docs/configuration/index.html#plugin_directory) -in the Vault config used to start the server. - -```json -... -plugin_directory = "path/to/plugin/directory" -... -``` - -Start a Vault server with this config file: -```sh -$ vault server -config=path/to/config.json ... -... -``` - -Once the server is started, register the plugin in the Vault server's [plugin catalog](https://www.vaultproject.io/docs/internals/plugins.html#plugin-catalog): - -```sh -$ vault write sys/plugins/catalog/kv \ - sha_256= \ - command="vault-plugin-secrets-kv" -... -Success! Data written to: sys/plugins/catalog/kv -``` - -Note you should generate a new sha256 checksum if you have made changes -to the plugin. Example using openssl: - -```sh -openssl dgst -sha256 $GOPATH/vault-plugin-secrets-kv -... -SHA256(.../go/bin/vault-plugin-secrets-kv)= 896c13c0f5305daed381952a128322e02bc28a57d0c862a78cbc2ea66e8c6fa1 -``` - -Enable the auth plugin backend using the secrets enable plugin command: - -```sh -$ vault secrets enable -plugin-name='kv' plugin -... - -Successfully enabled 'plugin' at 'kv'! -``` - -#### Tests - -If you are developing this plugin and want to verify it is still -functioning (and you haven't broken anything else), we recommend -running the tests. - -To run the tests, invoke `make test`: - -```sh -$ make test -``` - -You can also specify a `TESTARGS` variable to filter tests like so: - -```sh -$ make test TESTARGS='--run=TestConfig' -``` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/backend.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/backend.go deleted file mode 100644 index e251add70..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/backend.go +++ /dev/null @@ -1,467 +0,0 @@ -package kv - -import ( - "context" - "errors" - "fmt" - "net/http" - "path" - "sync" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // configPath is the location where the config is stored - configPath string = "config" - - // metadataPrefix is the prefix where the key metadata is stored. - metadataPrefix string = "metadata/" - - // versionPrefix is the prefix where the version data is stored. - versionPrefix string = "versions/" - - // defaultMaxVersions is the number of versions to keep around unless set by - // the config or key configuration. - defaultMaxVersions uint32 = 10 -) - -// versionedKVBackend implements logical.Backend -type versionedKVBackend struct { - *framework.Backend - - // keyEncryptedWrapper is a cached version of the EncryptedKeyStorageWrapper - keyEncryptedWrapper *keysutil.EncryptedKeyStorageWrapper - - // salt is the cached version of the salt used to create paths for version - // data storage paths. - salt *salt.Salt - - // l locks the keyPolicy and salt caches. - l sync.RWMutex - - // locks is a slice of 256 locks that are used to protect key and version - // updates. - locks []*locksutil.LockEntry - - // storagePrefix is the prefix given to all the data for a versioned KV - // store. We prefix this data so that upgrading from a passthrough backend - // to a versioned backend is easier. This value is passed from Vault core - // through the backend config. - storagePrefix string - - // upgrading is an atomic value denoting if the backend is in the process of - // upgrading its data. - upgrading *uint32 - - // globalConfig is a cached value for fast lookup - globalConfig *Configuration - globalConfigLock *sync.RWMutex -} - -// Factory will return a logical backend of type versionedKVBackend or -// PassthroughBackend based on the config passed in. -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - version := conf.Config["version"] - - var b logical.Backend - var err error - switch version { - case "1", "": - return LeaseSwitchedPassthroughBackend(ctx, conf, conf.Config["leased_passthrough"] == "true") - case "2": - b, err = VersionedKVFactory(ctx, conf) - } - if err != nil { - return nil, err - } - - return b, nil -} - -// Factory returns a new backend as logical.Backend. -func VersionedKVFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := &versionedKVBackend{ - upgrading: new(uint32), - globalConfigLock: new(sync.RWMutex), - } - if conf.BackendUUID == "" { - return nil, errors.New("could not initialize versioned K/V Store, no UUID was provided") - } - b.storagePrefix = conf.BackendUUID - - b.Backend = &framework.Backend{ - BackendType: logical.TypeLogical, - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - // Seal wrap the versioned data - path.Join(b.storagePrefix, versionPrefix) + "/", - - // Seal wrap the key policy - path.Join(b.storagePrefix, "policy") + "/", - - // Seal wrap the archived key policy - path.Join(b.storagePrefix, "archive") + "/", - }, - }, - - Paths: framework.PathAppend( - []*framework.Path{ - pathConfig(b), - pathData(b), - pathMetadata(b), - pathDestroy(b), - }, - pathsDelete(b), - - // Make sure this stays at the end so that the valid paths are - // processed first. - pathInvalid(b), - ), - } - - b.locks = locksutil.CreateLocks() - - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - - upgradeDone, err := b.upgradeDone(ctx, conf.StorageView) - if err != nil { - return nil, err - } - if !upgradeDone { - err := b.Upgrade(ctx, conf.StorageView) - if err != nil { - return nil, err - } - } - - return b, nil -} - -func (b *versionedKVBackend) upgradeDone(ctx context.Context, s logical.Storage) (bool, error) { - upgradeEntry, err := s.Get(ctx, path.Join(b.storagePrefix, "upgrading")) - if err != nil { - return false, err - } - - var upgradeInfo UpgradeInfo - if upgradeEntry != nil { - err := proto.Unmarshal(upgradeEntry.Value, &upgradeInfo) - if err != nil { - return false, err - } - } - - return upgradeInfo.Done, nil -} - -func pathInvalid(b *versionedKVBackend) []*framework.Path { - handler := func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - switch req.Path { - case "metadata", "data", "delete", "undelete", "destroy": - resp := &logical.Response{} - resp.AddWarning("Non-listing operations on the root of a K/V v2 mount are not supported.") - return logical.RespondWithStatusCode(resp, req, http.StatusNotFound) - } - - var subCommand string - switch req.Operation { - case logical.CreateOperation, logical.UpdateOperation: - subCommand = "put" - case logical.ReadOperation: - subCommand = "get" - case logical.ListOperation: - subCommand = "list" - case logical.DeleteOperation: - subCommand = "delete" - } - resp := &logical.Response{} - resp.AddWarning(fmt.Sprintf("Invalid path for a versioned K/V secrets engine. See the API docs for the appropriate API endpoints to use. If using the Vault CLI, use 'vault kv %s' for this operation.", subCommand)) - return logical.RespondWithStatusCode(resp, req, http.StatusNotFound) - } - - return []*framework.Path{ - &framework.Path{ - Pattern: ".*", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: handler, - logical.CreateOperation: handler, - logical.ReadOperation: handler, - logical.DeleteOperation: handler, - logical.ListOperation: handler, - }, - - HelpDescription: pathInvalidHelp, - }, - } -} - -// Invalidate invalidates the salt and the policy so replication secondaries can -// cache these values. -func (b *versionedKVBackend) Invalidate(ctx context.Context, key string) { - switch key { - case path.Join(b.storagePrefix, salt.DefaultLocation): - b.l.Lock() - b.salt = nil - b.l.Unlock() - case path.Join(b.storagePrefix, "policy/metadata"): - b.l.Lock() - b.keyEncryptedWrapper = nil - b.l.Unlock() - case path.Join(b.storagePrefix, configPath): - b.globalConfigLock.Lock() - b.globalConfig = nil - b.globalConfigLock.Unlock() - } -} - -// Salt will load a the salt, or if one has not been created yet it will -// generate and store a new salt. -func (b *versionedKVBackend) Salt(ctx context.Context, s logical.Storage) (*salt.Salt, error) { - b.l.RLock() - if b.salt != nil { - defer b.l.RUnlock() - return b.salt, nil - } - b.l.RUnlock() - b.l.Lock() - defer b.l.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, s, &salt.Config{ - HashFunc: salt.SHA256Hash, - Location: path.Join(b.storagePrefix, salt.DefaultLocation), - }) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -// policy loads the key policy for this backend, if one has not been created yet -// it will generate and store a new policy. The caller must have the backend lock. -func (b *versionedKVBackend) policy(ctx context.Context, s logical.Storage) (*keysutil.Policy, error) { - // Try loading policy - policy, err := keysutil.LoadPolicy(ctx, s, path.Join(b.storagePrefix, "policy/metadata")) - if err != nil { - return nil, err - } - if policy != nil { - return policy, nil - } - - // Policy didn't exist, create it. - policy = keysutil.NewPolicy(keysutil.PolicyConfig{ - Name: "metadata", - Type: keysutil.KeyType_AES256_GCM96, - Derived: true, - KDF: keysutil.Kdf_hkdf_sha256, - ConvergentEncryption: true, - StoragePrefix: b.storagePrefix, - VersionTemplate: keysutil.EncryptedKeyPolicyVersionTpl, - }) - - err = policy.Rotate(ctx, s) - if err != nil { - return nil, err - } - - return policy, nil -} - -func (b *versionedKVBackend) getKeyEncryptor(ctx context.Context, s logical.Storage) (*keysutil.EncryptedKeyStorageWrapper, error) { - b.l.RLock() - if b.keyEncryptedWrapper != nil { - defer b.l.RUnlock() - return b.keyEncryptedWrapper, nil - } - b.l.RUnlock() - b.l.Lock() - defer b.l.Unlock() - - if b.keyEncryptedWrapper != nil { - return b.keyEncryptedWrapper, nil - } - - policy, err := b.policy(ctx, s) - if err != nil { - return nil, err - } - - e, err := keysutil.NewEncryptedKeyStorageWrapper(keysutil.EncryptedKeyStorageConfig{ - Policy: policy, - Prefix: path.Join(b.storagePrefix, metadataPrefix), - }) - if err != nil { - return nil, err - } - - // Cache the value - b.keyEncryptedWrapper = e - - return b.keyEncryptedWrapper, nil -} - -// config takes a storage object and returns a configuration object -func (b *versionedKVBackend) config(ctx context.Context, s logical.Storage) (*Configuration, error) { - b.globalConfigLock.RLock() - if b.globalConfig != nil { - defer b.globalConfigLock.RUnlock() - return &Configuration{ - CasRequired: b.globalConfig.CasRequired, - MaxVersions: b.globalConfig.MaxVersions, - }, nil - } - - b.globalConfigLock.RUnlock() - b.globalConfigLock.Lock() - defer b.globalConfigLock.Unlock() - - // Verify this hasn't already changed - if b.globalConfig != nil { - return &Configuration{ - CasRequired: b.globalConfig.CasRequired, - MaxVersions: b.globalConfig.MaxVersions, - }, nil - } - - raw, err := s.Get(ctx, path.Join(b.storagePrefix, configPath)) - if err != nil { - return nil, err - } - - conf := &Configuration{} - if raw != nil { - if err := proto.Unmarshal(raw.Value, conf); err != nil { - return nil, err - } - } - - b.globalConfig = conf - - return conf, nil -} - -// getVersionKey uses the salt to generate the version key for a specific -// version of a key. -func (b *versionedKVBackend) getVersionKey(ctx context.Context, key string, version uint64, s logical.Storage) (string, error) { - salt, err := b.Salt(ctx, s) - if err != nil { - return "", err - } - - salted := salt.SaltID(fmt.Sprintf("%s|%d", key, version)) - - return path.Join(b.storagePrefix, versionPrefix, salted[0:3], salted[3:]), nil -} - -// getKeyMetadata returns the metadata object for the provided key, if no object -// exits it will return nil. -func (b *versionedKVBackend) getKeyMetadata(ctx context.Context, s logical.Storage, key string) (*KeyMetadata, error) { - - wrapper, err := b.getKeyEncryptor(ctx, s) - if err != nil { - return nil, err - } - - es := wrapper.Wrap(s) - - item, err := es.Get(ctx, key) - if err != nil { - return nil, err - } - if item == nil { - return nil, nil - } - - meta := &KeyMetadata{} - err = proto.Unmarshal(item.Value, meta) - if err != nil { - return nil, fmt.Errorf("failed to decode key metadata from storage: %v", err) - } - - return meta, nil -} - -// writeKeyMetadata writes a metadata object to storage. -func (b *versionedKVBackend) writeKeyMetadata(ctx context.Context, s logical.Storage, meta *KeyMetadata) error { - wrapper, err := b.getKeyEncryptor(ctx, s) - if err != nil { - return err - } - - es := wrapper.Wrap(s) - - bytes, err := proto.Marshal(meta) - if err != nil { - return err - } - - err = es.Put(ctx, &logical.StorageEntry{ - Key: meta.Key, - Value: bytes, - }) - if err != nil { - return err - } - - return nil -} - -func ptypesTimestampToString(t *timestamp.Timestamp) string { - if t == nil { - return "" - } - - return ptypes.TimestampString(t) -} - -var backendHelp string = ` -This backend provides a versioned key-value store. The kv backend reads and -writes arbitrary secrets to the storage backend. The secrets are -encrypted/decrypted by Vault: they are never stored unencrypted in the backend -and the backend never has an opportunity to see the unencrypted value. Each key -can have a configured number of versions, and versions can be retrieved based on -their version numbers. -` - -var pathInvalidHelp string = backendHelp + ` - -## PATHS - -The following paths are supported by this backend. To view help for -any of the paths below, use the help command with any route matching -the path pattern. Note that depending on the policy of your auth token, -you may or may not be able to access certain paths. - - ^config$ - Configures settings for the KV store - - ^data/.*$ - Write, Read, and Delete data in the Key-Value Store. - - ^delete/.*$ - Marks one or more versions as deleted in the KV store. - - ^destroy/.*$ - Permanently removes one or more versions in the KV store - - ^metadata/.*$ - Configures settings for the KV store - - ^undelete/.*$ - Undeletes one or more versions from the KV store. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/passthrough.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/passthrough.go deleted file mode 100644 index 036e351e7..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/passthrough.go +++ /dev/null @@ -1,265 +0,0 @@ -package kv - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -type Passthrough interface { - handleRead() framework.OperationFunc - handleWrite() framework.OperationFunc - handleDelete() framework.OperationFunc - handleList() framework.OperationFunc - handleExistenceCheck() framework.ExistenceFunc -} - -// PassthroughBackendFactory returns a PassthroughBackend -// with leases switched off -func PassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, false) -} - -// LeasedPassthroughBackendFactory returns a PassthroughBackend -// with leases switched on -func LeasedPassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, true) -} - -// LeaseSwitchedPassthroughBackend returns a PassthroughBackend -// with leases switched on or off -func LeaseSwitchedPassthroughBackend(ctx context.Context, conf *logical.BackendConfig, leases bool) (logical.Backend, error) { - b := &PassthroughBackend{ - generateLeases: leases, - } - - backend := &framework.Backend{ - BackendType: logical.TypeLogical, - Help: strings.TrimSpace(passthroughHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "*", - }, - }, - - Paths: []*framework.Path{ - &framework.Path{ - Pattern: ".*", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRead(), - logical.CreateOperation: b.handleWrite(), - logical.UpdateOperation: b.handleWrite(), - logical.DeleteOperation: b.handleDelete(), - logical.ListOperation: b.handleList(), - }, - - ExistenceCheck: b.handleExistenceCheck(), - - HelpSynopsis: strings.TrimSpace(passthroughHelpSynopsis), - HelpDescription: strings.TrimSpace(passthroughHelpDescription), - }, - }, - Secrets: []*framework.Secret{ - &framework.Secret{ - Type: "kv", - - Renew: b.handleRead(), - Revoke: func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // This is a no-op - return nil, nil - }, - }, - }, - } - - if conf == nil { - return nil, fmt.Errorf("Configuation passed into backend is nil") - } - backend.Setup(ctx, conf) - b.Backend = backend - - return b, nil -} - -// PassthroughBackend is used storing secrets directly into the physical -// backend. The secrets are encrypted in the durable storage and custom TTL -// information can be specified, but otherwise this backend doesn't do anything -// fancy. -type PassthroughBackend struct { - *framework.Backend - generateLeases bool -} - -func (b *PassthroughBackend) handleExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return false, fmt.Errorf("existence check failed: %v", err) - } - - return out != nil, nil - } -} - -func (b *PassthroughBackend) handleRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Read the path - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return nil, fmt.Errorf("read failed: %v", err) - } - - // Fast-path the no data case - if out == nil { - return nil, nil - } - - // Decode the data - var rawData map[string]interface{} - - if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, fmt.Errorf("json decoding failed: %v", err) - } - - var resp *logical.Response - if b.generateLeases { - // Generate the response - resp = b.Secret("kv").Response(rawData, nil) - resp.Secret.Renewable = false - } else { - resp = &logical.Response{ - Secret: &logical.Secret{}, - Data: rawData, - } - } - - // Ensure seal wrapping is carried through if the response is - // response-wrapped - if out.SealWrap { - if resp.WrapInfo == nil { - resp.WrapInfo = &wrapping.ResponseWrapInfo{} - } - resp.WrapInfo.SealWrap = out.SealWrap - } - - // Check if there is a ttl key - ttlDuration := b.System().DefaultLeaseTTL() - ttlRaw, ok := rawData["ttl"] - if !ok { - ttlRaw, ok = rawData["lease"] - } - if ok { - dur, err := parseutil.ParseDurationSecond(ttlRaw) - if err == nil { - ttlDuration = dur - } - - if b.generateLeases { - resp.Secret.Renewable = true - } - } - - resp.Secret.TTL = ttlDuration - - return resp, nil - } -} - -func (b *PassthroughBackend) GeneratesLeases() bool { - return b.generateLeases -} - -func (b *PassthroughBackend) handleWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Check that some fields are given - if len(req.Data) == 0 { - return logical.ErrorResponse("missing data fields"), nil - } - - // JSON encode the data - buf, err := json.Marshal(req.Data) - if err != nil { - return nil, fmt.Errorf("json encoding failed: %v", err) - } - - // Write out a new key - entry := &logical.StorageEntry{ - Key: req.Path, - Value: buf, - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, fmt.Errorf("failed to write: %v", err) - } - - return nil, nil - } -} - -func (b *PassthroughBackend) handleDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Delete the key at the request path - if err := req.Storage.Delete(ctx, req.Path); err != nil { - return nil, err - } - - return nil, nil - } -} - -func (b *PassthroughBackend) handleList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Right now we only handle directories, so ensure it ends with /; however, - // some physical backends may not handle the "/" case properly, so only add - // it if we're not listing the root - path := req.Path - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // List the keys at the prefix given by the request - keys, err := req.Storage.List(ctx, path) - if err != nil { - return nil, err - } - - // Generate the response - return logical.ListResponse(keys), nil - } -} - -const passthroughHelp = ` -The kv backend reads and writes arbitrary secrets to the backend. -The secrets are encrypted/decrypted by Vault: they are never stored -unencrypted in the backend and the backend never has an opportunity to -see the unencrypted value. - -TTLs can be set on a per-secret basis. These TTLs will be sent down -when that secret is read, and it is assumed that some outside process will -revoke and/or replace the secret at that path. -` - -const passthroughHelpSynopsis = ` -Pass-through secret storage to the storage backend, allowing you to -read/write arbitrary data into secret storage. -` - -const passthroughHelpDescription = ` -The pass-through backend reads and writes arbitrary data into secret storage, -encrypting it along the way. - -A TTL can be specified when writing with the "ttl" field. If given, the -duration of leases returned by this backend will be set to this value. This -can be used as a hint from the writer of a secret to the consumer of a secret -that the consumer should re-read the value before the TTL has expired. -However, any revocation must be handled by the user of this backend; the lease -duration does not affect the provided data in any way. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_config.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_config.go deleted file mode 100644 index 6c9aa9741..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_config.go +++ /dev/null @@ -1,110 +0,0 @@ -package kv - -import ( - "context" - "path" - - "github.com/golang/protobuf/proto" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathConfig returns the path configuration for CRUD operations on the backend -// configuration. -func pathConfig(b *versionedKVBackend) *framework.Path { - return &framework.Path{ - Pattern: "config$", - Fields: map[string]*framework.FieldSchema{ - "max_versions": { - Type: framework.TypeInt, - Description: "The number of versions to keep for each key. Defaults to 10", - }, - "cas_required": { - Type: framework.TypeBool, - Description: "If true, the backend will require the cas parameter to be set for each write", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathConfigWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathConfigWrite()), - logical.ReadOperation: b.upgradeCheck(b.pathConfigRead()), - }, - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -// pathConfigWrite handles create and update commands to the config -func (b *versionedKVBackend) pathConfigRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "max_versions": config.MaxVersions, - "cas_required": config.CasRequired, - }, - }, nil - } -} - -// pathConfigWrite handles create and update commands to the config -func (b *versionedKVBackend) pathConfigWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - maxRaw, mOk := data.GetOk("max_versions") - casRaw, cOk := data.GetOk("cas_required") - - // Fast path validation - if !mOk && !cOk { - return nil, nil - } - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if mOk { - config.MaxVersions = uint32(maxRaw.(int)) - } - if cOk { - config.CasRequired = casRaw.(bool) - } - - bytes, err := proto.Marshal(config) - if err != nil { - return nil, err - } - - err = req.Storage.Put(ctx, &logical.StorageEntry{ - Key: path.Join(b.storagePrefix, configPath), - Value: bytes, - }) - if err != nil { - return nil, err - } - - b.globalConfigLock.Lock() - defer b.globalConfigLock.Unlock() - - b.globalConfig = config - - return nil, nil - } -} - -const confHelpSyn = `Configures settings for the KV store` -const confHelpDesc = ` -This path configures backend level settings that are applied to every key in the -key-value store. This parameter accetps: - - * max_versions (int) - The number of versions to keep for each key. Defaults - to 10 - - * cas_required (bool) - If true, the backend will require the cas parameter - to be set for each write -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_data.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_data.go deleted file mode 100644 index 9a777e8c4..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_data.go +++ /dev/null @@ -1,428 +0,0 @@ -package kv - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -// pathConfig returns the path configuration for CRUD operations on the backend -// configuration. -func pathData(b *versionedKVBackend) *framework.Path { - return &framework.Path{ - Pattern: "data/.*", - Fields: map[string]*framework.FieldSchema{ - "version": { - Type: framework.TypeInt, - Description: "If provided during a read, the value at the version number will be returned", - }, - "options": { - Type: framework.TypeMap, - Description: `Options for writing a KV entry. - -Set the "cas" value to use a Check-And-Set operation. If not set the write will -be allowed. If set to 0 a write will only be allowed if the key doesn’t exist. -If the index is non-zero the write will only be allowed if the key’s current -version matches the version specified in the cas parameter.`, - }, - "data": { - Type: framework.TypeMap, - Description: "The contents of the data map will be stored and returned on read.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathDataWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathDataWrite()), - logical.ReadOperation: b.upgradeCheck(b.pathDataRead()), - logical.DeleteOperation: b.upgradeCheck(b.pathDataDelete()), - }, - - ExistenceCheck: b.dataExistenceCheck(), - - HelpSynopsis: dataHelpSyn, - HelpDescription: dataHelpDesc, - } -} - -func (b *versionedKVBackend) dataExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - key := strings.TrimPrefix(req.Path, "data/") - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return false, err - } - - return meta != nil, nil - } -} - -// pathDataRead handles read commands to a kv entry -func (b *versionedKVBackend) pathDataRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "data/") - - lock := locksutil.LockForKey(b.locks, key) - lock.RLock() - defer lock.RUnlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - verNum := meta.CurrentVersion - verParam := data.Get("version").(int) - if verParam > 0 { - verNum = uint64(verParam) - } - - // If there is no version with that number, return - vm := meta.Versions[verNum] - if vm == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "data": nil, - "metadata": map[string]interface{}{ - "version": verNum, - "created_time": ptypesTimestampToString(vm.CreatedTime), - "deletion_time": ptypesTimestampToString(vm.DeletionTime), - "destroyed": vm.Destroyed, - }, - }, - } - - // If the version has been deleted return metadata with a 404 - if vm.DeletionTime != nil { - deletionTime, err := ptypes.Timestamp(vm.DeletionTime) - if err != nil { - return nil, err - } - - if deletionTime.Before(time.Now()) { - return logical.RespondWithStatusCode(resp, req, http.StatusNotFound) - - } - } - - // If the version has been destroyed return metadata with a 404 - if vm.Destroyed { - return logical.RespondWithStatusCode(resp, req, http.StatusNotFound) - - } - - versionKey, err := b.getVersionKey(ctx, key, verNum, req.Storage) - if err != nil { - return nil, err - } - - raw, err := req.Storage.Get(ctx, versionKey) - if err != nil { - return nil, err - } - if raw == nil { - return nil, errors.New("could not find version data") - } - - version := &Version{} - if err := proto.Unmarshal(raw.Value, version); err != nil { - return nil, err - } - - vData := map[string]interface{}{} - if err := json.Unmarshal(version.Data, &vData); err != nil { - return nil, err - } - - resp.Data["data"] = vData - - return resp, nil - } -} - -// pathDataWrite handles create and update commands to a kv entry -func (b *versionedKVBackend) pathDataWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "data/") - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Parse data, this can happen before the lock so we can fail early if - // not set. - var marshaledData []byte - { - dataRaw, ok := data.GetOk("data") - if !ok { - return logical.ErrorResponse("no data provided"), logical.ErrInvalidRequest - } - marshaledData, err = json.Marshal(dataRaw.(map[string]interface{})) - if err != nil { - return nil, err - } - } - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - meta = &KeyMetadata{ - Key: key, - Versions: map[uint64]*VersionMetadata{}, - } - } - - // Parse options - { - var casRaw interface{} - var casOk bool - optionsRaw, ok := data.GetOk("options") - if ok { - options := optionsRaw.(map[string]interface{}) - - // Verify the CAS parameter is valid. - casRaw, casOk = options["cas"] - } - - switch { - case casOk: - var cas int - if err := mapstructure.WeakDecode(casRaw, &cas); err != nil { - return logical.ErrorResponse("error parsing check-and-set parameter"), logical.ErrInvalidRequest - } - if uint64(cas) != meta.CurrentVersion { - return logical.ErrorResponse("check-and-set parameter did not match the current version"), logical.ErrInvalidRequest - } - case config.CasRequired, meta.CasRequired: - return logical.ErrorResponse("check-and-set parameter required for this call"), logical.ErrInvalidRequest - } - } - - // Create a version key for the new version - versionKey, err := b.getVersionKey(ctx, key, meta.CurrentVersion+1, req.Storage) - if err != nil { - return nil, err - } - version := &Version{ - Data: marshaledData, - CreatedTime: ptypes.TimestampNow(), - } - - buf, err := proto.Marshal(version) - if err != nil { - return nil, err - } - - // Write the new version - if err := req.Storage.Put(ctx, &logical.StorageEntry{ - Key: versionKey, - Value: buf, - }); err != nil { - return nil, err - } - - vm, versionToDelete := meta.AddVersion(version.CreatedTime, nil, config.MaxVersions) - err = b.writeKeyMetadata(ctx, req.Storage, meta) - if err != nil { - return nil, err - } - - // We create the response here so we can add warnings to it below. - resp := &logical.Response{ - Data: map[string]interface{}{ - "version": meta.CurrentVersion, - "created_time": ptypesTimestampToString(vm.CreatedTime), - "deletion_time": ptypesTimestampToString(vm.DeletionTime), - "destroyed": vm.Destroyed, - }, - } - - // Cleanup the version data that is past max version. - if versionToDelete > 0 { - - // Create a list of version keys to delete. We will delete from the - // back of the array so we can delete the oldest versions - // first. If there is an error deleting one of the keys we can - // ensure the rest will be deleted on the next go around. - var versionKeysToDelete []string - - for i := versionToDelete; i > 0; i-- { - versionKey, err := b.getVersionKey(ctx, key, i, req.Storage) - if err != nil { - resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err)) - return resp, nil - } - - // We intentionally do not return these errors here. If the get - // or delete fail they will be cleaned up on the next write. - v, err := req.Storage.Get(ctx, versionKey) - if err != nil { - resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err)) - return resp, nil - } - - if v == nil { - break - } - - // append to the end of the list - versionKeysToDelete = append(versionKeysToDelete, versionKey) - } - - // Walk the list backwards deleting the oldest versions first. This - // allows us to continue the cleanup on next write if an error - // occurs during one of the deletes. - for i := len(versionKeysToDelete) - 1; i >= 0; i-- { - err := req.Storage.Delete(ctx, versionKeysToDelete[i]) - if err != nil { - resp.AddWarning(fmt.Sprintf("Error occured when cleaning up old versions, these will be cleaned up on next write: %s", err)) - break - } - } - - } - - return resp, nil - } -} - -func (b *versionedKVBackend) pathDataDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "data/") - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - // If there is no latest version, or the latest version is already - // deleted or destroyed return - lv := meta.Versions[meta.CurrentVersion] - if lv == nil || lv.Destroyed { - return nil, nil - } - - if lv.DeletionTime != nil { - deletionTime, err := ptypes.Timestamp(lv.DeletionTime) - if err != nil { - return nil, err - } - - if deletionTime.Before(time.Now()) { - return nil, nil - } - } - - lv.DeletionTime = ptypes.TimestampNow() - - err = b.writeKeyMetadata(ctx, req.Storage, meta) - if err != nil { - return nil, err - } - - return nil, nil - } -} - -// AddVersion adds a version to the key metadata and moves the sliding window of -// max versions. It returns the newly added version and the version to delete -// from storage. -func (k *KeyMetadata) AddVersion(createdTime, deletionTime *timestamp.Timestamp, configMaxVersions uint32) (*VersionMetadata, uint64) { - if k.Versions == nil { - k.Versions = map[uint64]*VersionMetadata{} - } - - vm := &VersionMetadata{ - CreatedTime: createdTime, - DeletionTime: deletionTime, - } - - k.CurrentVersion++ - k.Versions[k.CurrentVersion] = vm - k.UpdatedTime = createdTime - if k.CreatedTime == nil { - k.CreatedTime = createdTime - } - - var maxVersions uint32 - switch { - case max(k.MaxVersions, configMaxVersions) > 0: - maxVersions = max(k.MaxVersions, configMaxVersions) - default: - maxVersions = defaultMaxVersions - } - - if uint32(k.CurrentVersion-k.OldestVersion) >= maxVersions { - versionToDelete := k.CurrentVersion - uint64(maxVersions) - // We need to do a loop here in the event that max versions has - // changed and we need to delete more than one entry. - for i := k.OldestVersion; i < versionToDelete+1; i++ { - delete(k.Versions, i) - } - - k.OldestVersion = versionToDelete + 1 - - return vm, versionToDelete - } - - return vm, 0 -} - -func max(a, b uint32) uint32 { - if b > a { - return b - } - - return a -} - -const dataHelpSyn = `Write, Read, and Delete data in the Key-Value Store.` -const dataHelpDesc = ` -This path takes a key name and based on the opperation stores, retreives or -deletes versions of data. - -If a write operation is used the endpoint takes an options object and a data -object. The options object is used to pass some options to the write command and -the data object is encrypted and stored in the storage backend. Each write -operation for a key creates a new version and does not overwrite the previous -data. - -A read operation will return the latest version for a key unless the "version" -parameter is set, then it returns the version at that number. - -Delete operations are a soft delete. They will mark the latest version as -deleted, but the underlying data will not be fully removed. Delete operations -can be undone. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_delete.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_delete.go deleted file mode 100644 index 6de3261f2..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_delete.go +++ /dev/null @@ -1,156 +0,0 @@ -package kv - -import ( - "context" - "strings" - "time" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathsDelete returns the path configuration for the delete and undelete paths -func pathsDelete(b *versionedKVBackend) []*framework.Path { - return []*framework.Path{ - &framework.Path{ - Pattern: "delete/.*", - Fields: map[string]*framework.FieldSchema{ - "versions": { - Type: framework.TypeCommaIntSlice, - Description: "The versions to be archived. The versioned data will not be deleted, but it will no longer be returned in normal get requests.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathDeleteWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathDeleteWrite()), - }, - - HelpSynopsis: deleteHelpSyn, - HelpDescription: deleteHelpDesc, - }, - &framework.Path{ - Pattern: "undelete/.*", - Fields: map[string]*framework.FieldSchema{ - "versions": { - Type: framework.TypeCommaIntSlice, - Description: "The versions to unarchive. The versions will be restored and their data will be returned on normal get requests.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathUndeleteWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathUndeleteWrite()), - }, - - HelpSynopsis: undeleteHelpSyn, - HelpDescription: undeleteHelpDesc, - }, - } -} - -// pathUndeleteWrite is used to undelete a set of versions -func (b *versionedKVBackend) pathUndeleteWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "undelete/") - - versions := data.Get("versions").([]int) - if len(versions) == 0 { - return logical.ErrorResponse("No version number provided"), logical.ErrInvalidRequest - } - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - for _, verNum := range versions { - // If there is no version or the version is destroyed continue - lv := meta.Versions[uint64(verNum)] - if lv == nil || lv.Destroyed { - continue - } - - lv.DeletionTime = nil - } - err = b.writeKeyMetadata(ctx, req.Storage, meta) - if err != nil { - return nil, err - } - - return nil, nil - } -} - -// pathDeleteWrite is used to delete a set of versions. -func (b *versionedKVBackend) pathDeleteWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "delete/") - - versions := data.Get("versions").([]int) - if len(versions) == 0 { - return logical.ErrorResponse("No version number provided"), logical.ErrInvalidRequest - } - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - for _, verNum := range versions { - // If there is no latest version, or the latest version is already - // deleted or destroyed continue - lv := meta.Versions[uint64(verNum)] - if lv == nil || lv.Destroyed { - continue - } - - if lv.DeletionTime != nil { - deletionTime, err := ptypes.Timestamp(lv.DeletionTime) - if err != nil { - return nil, err - } - - if deletionTime.Before(time.Now()) { - continue - } - } - - lv.DeletionTime = ptypes.TimestampNow() - } - - err = b.writeKeyMetadata(ctx, req.Storage, meta) - if err != nil { - return nil, err - } - - return nil, nil - } -} - -const deleteHelpSyn = `Marks one or more versions as deleted in the KV store.` -const deleteHelpDesc = ` -Deletes the data for the provided version and path in the key-value store. The -versioned data will not be fully removed, but marked as deleted and will no -longer be returned in normal get requests. This operation can be undone. -` - -const undeleteHelpSyn = `Undeletes one or more versions from the KV store.` -const undeleteHelpDesc = ` -Undeletes the data for the provided version and path in the key-value store. -This restores the data, allowing it to be returned on get requests. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_destroy.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_destroy.go deleted file mode 100644 index 7994b6357..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_destroy.go +++ /dev/null @@ -1,91 +0,0 @@ -package kv - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathDestroy returns the path configuration for the destroy endpoint -func pathDestroy(b *versionedKVBackend) *framework.Path { - return &framework.Path{ - Pattern: "destroy/.*", - Fields: map[string]*framework.FieldSchema{ - "versions": { - Type: framework.TypeCommaIntSlice, - Description: "The versions to destroy. Their data will be permanently deleted.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathDestroyWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathDestroyWrite()), - }, - - HelpSynopsis: destroyHelpSyn, - HelpDescription: destroyHelpDesc, - } -} - -func (b *versionedKVBackend) pathDestroyWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "destroy/") - - versions := data.Get("versions").([]int) - if len(versions) == 0 { - return logical.ErrorResponse("no version number provided"), logical.ErrInvalidRequest - } - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - for _, verNum := range versions { - // If there is no version, or the version is already destroyed, - // continue - lv := meta.Versions[uint64(verNum)] - if lv == nil || lv.Destroyed { - continue - } - - lv.Destroyed = true - } - - // Write the metadata key before deleting the versions - err = b.writeKeyMetadata(ctx, req.Storage, meta) - if err != nil { - return nil, err - } - - for _, verNum := range versions { - // Delete versioned data - versionKey, err := b.getVersionKey(ctx, key, uint64(verNum), req.Storage) - if err != nil { - return nil, err - } - - err = req.Storage.Delete(ctx, versionKey) - if err != nil { - return nil, err - } - } - - return nil, nil - } -} - -const destroyHelpSyn = `Permanently removes one or more versions in the KV store` -const destroyHelpDesc = ` -Permanently removes the specified version data for the provided key and version -numbers from the key-value store. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_metadata.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_metadata.go deleted file mode 100644 index 6e2a88c97..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/path_metadata.go +++ /dev/null @@ -1,214 +0,0 @@ -package kv - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// pathMetadata returns the path configuration for CRUD operations on the -// metadata endpoint -func pathMetadata(b *versionedKVBackend) *framework.Path { - return &framework.Path{ - Pattern: "metadata/.*", - Fields: map[string]*framework.FieldSchema{ - "cas_required": { - Type: framework.TypeBool, - Description: ` -If true the key will require the cas parameter to be set on all write requests. -If false, the backend’s configuration will be used.`, - }, - "max_versions": { - Type: framework.TypeInt, - Description: ` -The number of versions to keep. If not set, the backend’s configured max -version is used.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.upgradeCheck(b.pathMetadataWrite()), - logical.CreateOperation: b.upgradeCheck(b.pathMetadataWrite()), - logical.ReadOperation: b.upgradeCheck(b.pathMetadataRead()), - logical.DeleteOperation: b.upgradeCheck(b.pathMetadataDelete()), - logical.ListOperation: b.upgradeCheck(b.pathMetadataList()), - }, - - ExistenceCheck: b.metadataExistenceCheck(), - - HelpSynopsis: confHelpSyn, - HelpDescription: confHelpDesc, - } -} - -func (b *versionedKVBackend) metadataExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - key := strings.TrimPrefix(req.Path, "metadata/") - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return false, err - } - - return meta != nil, nil - } -} - -func (b *versionedKVBackend) pathMetadataList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "metadata/") - - // Get an encrypted key storage object - wrapper, err := b.getKeyEncryptor(ctx, req.Storage) - if err != nil { - return nil, err - } - - es := wrapper.Wrap(req.Storage) - - // Use encrypted key storage to list the keys - keys, err := es.List(ctx, key) - return logical.ListResponse(keys), err - } -} - -func (b *versionedKVBackend) pathMetadataRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "metadata/") - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - versions := make(map[string]interface{}, len(meta.Versions)) - for i, v := range meta.Versions { - versions[fmt.Sprintf("%d", i)] = map[string]interface{}{ - "created_time": ptypesTimestampToString(v.CreatedTime), - "deletion_time": ptypesTimestampToString(v.DeletionTime), - "destroyed": v.Destroyed, - } - } - - return &logical.Response{ - Data: map[string]interface{}{ - "versions": versions, - "current_version": meta.CurrentVersion, - "oldest_version": meta.OldestVersion, - "created_time": ptypesTimestampToString(meta.CreatedTime), - "updated_time": ptypesTimestampToString(meta.UpdatedTime), - "max_versions": meta.MaxVersions, - "cas_required": meta.CasRequired, - }, - }, nil - } -} - -func (b *versionedKVBackend) pathMetadataWrite() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "metadata/") - - maxRaw, mOk := data.GetOk("max_versions") - casRaw, cOk := data.GetOk("cas_required") - - // Fast path validation - if !mOk && !cOk { - return nil, nil - } - - config, err := b.config(ctx, req.Storage) - if err != nil { - return nil, err - } - - var resp *logical.Response - if cOk && config.CasRequired && !casRaw.(bool) { - resp = &logical.Response{} - resp.AddWarning("\"cas_required\" set to false, but is mandated by backend config. This value will be ignored.") - } - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - now := ptypes.TimestampNow() - meta = &KeyMetadata{ - Key: key, - Versions: map[uint64]*VersionMetadata{}, - CreatedTime: now, - UpdatedTime: now, - } - } - - if mOk { - meta.MaxVersions = uint32(maxRaw.(int)) - } - if cOk { - meta.CasRequired = casRaw.(bool) - } - - err = b.writeKeyMetadata(ctx, req.Storage, meta) - return resp, err - } -} - -func (b *versionedKVBackend) pathMetadataDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key := strings.TrimPrefix(req.Path, "metadata/") - - lock := locksutil.LockForKey(b.locks, key) - lock.Lock() - defer lock.Unlock() - - meta, err := b.getKeyMetadata(ctx, req.Storage, key) - if err != nil { - return nil, err - } - if meta == nil { - return nil, nil - } - - // Delete each version. - for id, _ := range meta.Versions { - versionKey, err := b.getVersionKey(ctx, key, id, req.Storage) - if err != nil { - return nil, err - } - - err = req.Storage.Delete(ctx, versionKey) - if err != nil { - return nil, err - } - } - - // Get an encrypted key storage object - wrapper, err := b.getKeyEncryptor(ctx, req.Storage) - if err != nil { - return nil, err - } - - es := wrapper.Wrap(req.Storage) - - // Use encrypted key storage to delete the key - err = es.Delete(ctx, key) - return nil, err - } -} - -const metadataHelpSyn = `Allows interaction with key metadata and settings in the KV store.` -const metadataHelpDesc = ` -This endpoint allows for reading, information about a key in the key-value -store, writing key settings, and permanently deleting a key and all versions. -` diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.pb.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.pb.go deleted file mode 100644 index 6acfb22ff..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.pb.go +++ /dev/null @@ -1,287 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: types.proto - -/* -Package kv is a generated protocol buffer package. - -It is generated from these files: - types.proto - -It has these top-level messages: - Configuration - VersionMetadata - KeyMetadata - Version - UpgradeInfo -*/ -package kv - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/timestamp" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Configuration struct { - MaxVersions uint32 `protobuf:"varint,1,opt,name=max_versions,json=maxVersions" json:"max_versions,omitempty"` - CasRequired bool `protobuf:"varint,2,opt,name=cas_required,json=casRequired" json:"cas_required,omitempty"` -} - -func (m *Configuration) Reset() { *m = Configuration{} } -func (m *Configuration) String() string { return proto.CompactTextString(m) } -func (*Configuration) ProtoMessage() {} -func (*Configuration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *Configuration) GetMaxVersions() uint32 { - if m != nil { - return m.MaxVersions - } - return 0 -} - -func (m *Configuration) GetCasRequired() bool { - if m != nil { - return m.CasRequired - } - return false -} - -type VersionMetadata struct { - // CreatedTime is when the version was created. - CreatedTime *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=created_time,json=createdTime" json:"created_time,omitempty"` - // DeletionTime is the time this version becomes invalid. - // Set to Now() to delete the version before the configured - // delete time. - DeletionTime *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=deletion_time,json=deletionTime" json:"deletion_time,omitempty"` - // Destroyed is used to specify this version is - // a has been removed and the underlying data deleted. - Destroyed bool `protobuf:"varint,3,opt,name=destroyed" json:"destroyed,omitempty"` -} - -func (m *VersionMetadata) Reset() { *m = VersionMetadata{} } -func (m *VersionMetadata) String() string { return proto.CompactTextString(m) } -func (*VersionMetadata) ProtoMessage() {} -func (*VersionMetadata) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *VersionMetadata) GetCreatedTime() *google_protobuf.Timestamp { - if m != nil { - return m.CreatedTime - } - return nil -} - -func (m *VersionMetadata) GetDeletionTime() *google_protobuf.Timestamp { - if m != nil { - return m.DeletionTime - } - return nil -} - -func (m *VersionMetadata) GetDestroyed() bool { - if m != nil { - return m.Destroyed - } - return false -} - -type KeyMetadata struct { - // Key is the key for this entry - Key string `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` - // Versions is the map of versionID -> VersionMetadata. - // Useful when listing all versions. - Versions map[uint64]*VersionMetadata `protobuf:"bytes,2,rep,name=versions" json:"versions,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // CurrentVersion is the latest version of the value - CurrentVersion uint64 `protobuf:"varint,3,opt,name=current_version,json=currentVersion" json:"current_version,omitempty"` - // OldestVersion is the oldest version of the value. - OldestVersion uint64 `protobuf:"varint,4,opt,name=oldest_version,json=oldestVersion" json:"oldest_version,omitempty"` - // Created time is when the metadata was created. - CreatedTime *google_protobuf.Timestamp `protobuf:"bytes,5,opt,name=created_time,json=createdTime" json:"created_time,omitempty"` - // Updated time was the last time the metadata version - // was updated. - UpdatedTime *google_protobuf.Timestamp `protobuf:"bytes,6,opt,name=updated_time,json=updatedTime" json:"updated_time,omitempty"` - // MaxVersions specifies how many versions to keep around. - // If empty value, defaults to the configured Max - // for the mount. - MaxVersions uint32 `protobuf:"varint,7,opt,name=max_versions,json=maxVersions" json:"max_versions,omitempty"` - // CasRequired specifies if the cas parameter is - // required for this key - CasRequired bool `protobuf:"varint,8,opt,name=cas_required,json=casRequired" json:"cas_required,omitempty"` -} - -func (m *KeyMetadata) Reset() { *m = KeyMetadata{} } -func (m *KeyMetadata) String() string { return proto.CompactTextString(m) } -func (*KeyMetadata) ProtoMessage() {} -func (*KeyMetadata) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *KeyMetadata) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *KeyMetadata) GetVersions() map[uint64]*VersionMetadata { - if m != nil { - return m.Versions - } - return nil -} - -func (m *KeyMetadata) GetCurrentVersion() uint64 { - if m != nil { - return m.CurrentVersion - } - return 0 -} - -func (m *KeyMetadata) GetOldestVersion() uint64 { - if m != nil { - return m.OldestVersion - } - return 0 -} - -func (m *KeyMetadata) GetCreatedTime() *google_protobuf.Timestamp { - if m != nil { - return m.CreatedTime - } - return nil -} - -func (m *KeyMetadata) GetUpdatedTime() *google_protobuf.Timestamp { - if m != nil { - return m.UpdatedTime - } - return nil -} - -func (m *KeyMetadata) GetMaxVersions() uint32 { - if m != nil { - return m.MaxVersions - } - return 0 -} - -func (m *KeyMetadata) GetCasRequired() bool { - if m != nil { - return m.CasRequired - } - return false -} - -type Version struct { - // Data is a JSON object with string keys that - // represents the user supplied data. - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` - // CreatedTime is when the version was created. - CreatedTime *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=created_time,json=createdTime" json:"created_time,omitempty"` - // DeletionTime is the time this version becomes invalid. - // Set to Now() to delete the version before the configured - // deletion time. - DeletionTime *google_protobuf.Timestamp `protobuf:"bytes,3,opt,name=deletion_time,json=deletionTime" json:"deletion_time,omitempty"` -} - -func (m *Version) Reset() { *m = Version{} } -func (m *Version) String() string { return proto.CompactTextString(m) } -func (*Version) ProtoMessage() {} -func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *Version) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *Version) GetCreatedTime() *google_protobuf.Timestamp { - if m != nil { - return m.CreatedTime - } - return nil -} - -func (m *Version) GetDeletionTime() *google_protobuf.Timestamp { - if m != nil { - return m.DeletionTime - } - return nil -} - -type UpgradeInfo struct { - // Started time is when the upgrade was started. - StartedTime *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=started_time,json=startedTime" json:"started_time,omitempty"` - // done is set to true once the backend has been successfully - // upgraded. - Done bool `protobuf:"varint,2,opt,name=done" json:"done,omitempty"` -} - -func (m *UpgradeInfo) Reset() { *m = UpgradeInfo{} } -func (m *UpgradeInfo) String() string { return proto.CompactTextString(m) } -func (*UpgradeInfo) ProtoMessage() {} -func (*UpgradeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *UpgradeInfo) GetStartedTime() *google_protobuf.Timestamp { - if m != nil { - return m.StartedTime - } - return nil -} - -func (m *UpgradeInfo) GetDone() bool { - if m != nil { - return m.Done - } - return false -} - -func init() { - proto.RegisterType((*Configuration)(nil), "kv.Configuration") - proto.RegisterType((*VersionMetadata)(nil), "kv.VersionMetadata") - proto.RegisterType((*KeyMetadata)(nil), "kv.KeyMetadata") - proto.RegisterType((*Version)(nil), "kv.Version") - proto.RegisterType((*UpgradeInfo)(nil), "kv.UpgradeInfo") -} - -func init() { proto.RegisterFile("types.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 436 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xdf, 0x8a, 0x13, 0x31, - 0x18, 0xc5, 0x99, 0x3f, 0xbb, 0xdb, 0xfd, 0x32, 0xb3, 0x2b, 0xf1, 0xa6, 0x14, 0xc5, 0x3a, 0x20, - 0xd6, 0x9b, 0x59, 0x58, 0x6f, 0x54, 0x58, 0xbc, 0x10, 0x2f, 0x44, 0x04, 0x09, 0xae, 0xb7, 0x35, - 0xdb, 0x7c, 0x2d, 0x43, 0xdb, 0xc9, 0x98, 0x64, 0xca, 0xce, 0xc3, 0xf8, 0x0c, 0xbe, 0x82, 0x8f, - 0x26, 0xc9, 0x24, 0xdd, 0xb5, 0x0a, 0xa5, 0x78, 0x17, 0x4e, 0xcf, 0x09, 0xbf, 0x9e, 0x39, 0x01, - 0x62, 0xba, 0x06, 0x75, 0xd9, 0x28, 0x69, 0x24, 0x8d, 0x97, 0x9b, 0xd1, 0x93, 0x85, 0x94, 0x8b, - 0x15, 0x5e, 0x38, 0xe5, 0xa6, 0x9d, 0x5f, 0x98, 0x6a, 0x8d, 0xda, 0xf0, 0x75, 0xd3, 0x9b, 0x8a, - 0x6b, 0xc8, 0xdf, 0xc9, 0x7a, 0x5e, 0x2d, 0x5a, 0xc5, 0x4d, 0x25, 0x6b, 0xfa, 0x14, 0xb2, 0x35, - 0xbf, 0x9d, 0x6e, 0x50, 0xe9, 0x4a, 0xd6, 0x7a, 0x18, 0x8d, 0xa3, 0x49, 0xce, 0xc8, 0x9a, 0xdf, - 0x7e, 0xf5, 0x92, 0xb5, 0xcc, 0xb8, 0x9e, 0x2a, 0xfc, 0xde, 0x56, 0x0a, 0xc5, 0x30, 0x1e, 0x47, - 0x93, 0x01, 0x23, 0x33, 0xae, 0x99, 0x97, 0x8a, 0x9f, 0x11, 0x9c, 0x7b, 0xff, 0x27, 0x34, 0x5c, - 0x70, 0xc3, 0xe9, 0x15, 0x64, 0x33, 0x85, 0xdc, 0xa0, 0x98, 0x5a, 0x0a, 0x77, 0x33, 0xb9, 0x1c, - 0x95, 0x3d, 0x62, 0x19, 0x10, 0xcb, 0x2f, 0x01, 0x91, 0x11, 0xef, 0xb7, 0x0a, 0x7d, 0x0b, 0xb9, - 0xc0, 0x15, 0x5a, 0xc8, 0x3e, 0x1f, 0xef, 0xcd, 0x67, 0x21, 0xe0, 0x2e, 0x78, 0x04, 0xa7, 0x02, - 0xb5, 0x51, 0xb2, 0x43, 0x31, 0x4c, 0x1c, 0xf3, 0x9d, 0x50, 0xfc, 0x4a, 0x80, 0x7c, 0xc4, 0x6e, - 0x4b, 0xfb, 0x00, 0x92, 0x25, 0x76, 0x0e, 0xf2, 0x94, 0xd9, 0x23, 0x7d, 0x0d, 0x83, 0x6d, 0x2b, - 0xf1, 0x38, 0x99, 0x90, 0xcb, 0xc7, 0xe5, 0x72, 0x53, 0xde, 0x0b, 0x95, 0xa1, 0xa2, 0xf7, 0xb5, - 0x51, 0x1d, 0xdb, 0xda, 0xe9, 0x73, 0x38, 0x9f, 0xb5, 0x4a, 0x61, 0x6d, 0x42, 0xb1, 0x0e, 0x20, - 0x65, 0x67, 0x5e, 0xf6, 0x41, 0xfa, 0x0c, 0xce, 0xe4, 0xca, 0x42, 0x6d, 0x7d, 0xa9, 0xf3, 0xe5, - 0xbd, 0x1a, 0x6c, 0xbb, 0x55, 0x1e, 0x1d, 0x56, 0xe5, 0x15, 0x64, 0x6d, 0x23, 0xee, 0xe2, 0xc7, - 0xfb, 0xe3, 0xde, 0xef, 0xe2, 0xbb, 0x13, 0x39, 0xd9, 0x3f, 0x91, 0xc1, 0x5f, 0x13, 0x19, 0x7d, - 0x86, 0xfc, 0x8f, 0xba, 0xee, 0x37, 0x9e, 0xf6, 0x8d, 0xbf, 0x80, 0xa3, 0x0d, 0x5f, 0xb5, 0xe1, - 0x53, 0x3f, 0xb4, 0x75, 0xef, 0xac, 0x8a, 0xf5, 0x8e, 0x37, 0xf1, 0xab, 0xa8, 0xf8, 0x11, 0xc1, - 0x49, 0x68, 0x88, 0x42, 0x6a, 0x7f, 0x76, 0xb7, 0x65, 0x2c, 0xfd, 0xe7, 0x00, 0xe3, 0xff, 0x1c, - 0x60, 0x72, 0xd8, 0x00, 0x8b, 0x6f, 0x40, 0xae, 0x9b, 0x85, 0xe2, 0x02, 0x3f, 0xd4, 0x73, 0x69, - 0x71, 0xb4, 0xe1, 0xea, 0x90, 0xf7, 0xe0, 0xfd, 0x0e, 0xc7, 0xfe, 0x43, 0x59, 0xa3, 0x7f, 0x7d, - 0xee, 0x7c, 0x73, 0xec, 0x42, 0x2f, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0xa2, 0xd2, 0xb5, 0x3c, - 0x08, 0x04, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.proto b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.proto deleted file mode 100644 index aaa3a821e..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/types.proto +++ /dev/null @@ -1,81 +0,0 @@ -syntax = "proto3"; -package kv; - -import "google/protobuf/timestamp.proto"; - -// If values are added to this, be sure to update the config() function -message Configuration { - uint32 max_versions = 1; - bool cas_required = 2; -} - -message VersionMetadata { - // CreatedTime is when the version was created. - google.protobuf.Timestamp created_time = 1; - - // DeletionTime is the time this version becomes invalid. - // Set to Now() to delete the version before the configured - // delete time. - google.protobuf.Timestamp deletion_time = 2; - - // Destroyed is used to specify this version is - // a has been removed and the underlying data deleted. - bool destroyed = 3; -} - -message KeyMetadata { - // Key is the key for this entry - string key = 1; - - // Versions is the map of versionID -> VersionMetadata. - // Useful when listing all versions. - map versions = 2; - - // CurrentVersion is the latest version of the value - uint64 current_version = 3; - - // OldestVersion is the oldest version of the value. - uint64 oldest_version = 4; - - // Created time is when the metadata was created. - google.protobuf.Timestamp created_time = 5; - - // Updated time was the last time the metadata version - // was updated. - google.protobuf.Timestamp updated_time = 6; - - // MaxVersions specifies how many versions to keep around. - // If empty value, defaults to the configured Max - // for the mount. - uint32 max_versions = 7; - - // CasRequired specifies if the cas parameter is - // required for this key - bool cas_required = 8; -} - - -message Version { - // Data is a JSON object with string keys that - // represents the user supplied data. - bytes data = 1; - - // CreatedTime is when the version was created. - google.protobuf.Timestamp created_time = 2; - - // DeletionTime is the time this version becomes invalid. - // Set to Now() to delete the version before the configured - // deletion time. - google.protobuf.Timestamp deletion_time = 3; -} - -message UpgradeInfo { - // Started time is when the upgrade was started. - google.protobuf.Timestamp started_time = 1; - - // done is set to true once the backend has been successfully - // upgraded. - bool done = 2; -} - - diff --git a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/upgrade.go b/vendor/github.com/hashicorp/vault-plugin-secrets-kv/upgrade.go deleted file mode 100644 index 309d9ea84..000000000 --- a/vendor/github.com/hashicorp/vault-plugin-secrets-kv/upgrade.go +++ /dev/null @@ -1,216 +0,0 @@ -package kv - -import ( - "context" - "errors" - "fmt" - "path" - "strings" - "sync/atomic" - "time" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *versionedKVBackend) upgradeCheck(next framework.OperationFunc) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if atomic.LoadUint32(b.upgrading) == 1 { - // Sleep for a very short time before returning. This helps clients - // that are trying to access a mount immediately upon enabling be - // more likely to behave correctly since the operation should take - // almost no time. - time.Sleep(15 * time.Millisecond) - - if atomic.LoadUint32(b.upgrading) == 1 { - return logical.ErrorResponse("Uprading from non-versioned to versioned data. This backend will be unavailable for a brief period and will resume service shortly."), logical.ErrInvalidRequest - } - } - - return next(ctx, req, data) - } -} - -func (b *versionedKVBackend) Upgrade(ctx context.Context, s logical.Storage) error { - // Don't run if the plugin is in metadata mode. - if pluginutil.InMetadataMode() { - b.Logger().Info("upgrade not running while plugin is in metadata mode") - return nil - } - - // Don't run while on a DR secondary. - if b.System().ReplicationState().HasState(consts.ReplicationDRSecondary) { - b.Logger().Info("upgrade not running on disaster recovery replication secondary") - return nil - } - - if !atomic.CompareAndSwapUint32(b.upgrading, 0, 1) { - return errors.New("upgrade already in process") - } - - // If we are a replication secondary, wait until the primary has finished - // upgrading. - if !b.System().LocalMount() && b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary|consts.ReplicationPerformanceStandby) { - b.Logger().Info("upgrade not running on performace replication secondary") - - go func() { - for { - time.Sleep(time.Second) - - done, err := b.upgradeDone(ctx, s) - if err != nil { - b.Logger().Error("upgrading resulted in error", "error", err) - return - } - - if done { - break - } - } - - atomic.StoreUint32(b.upgrading, 0) - }() - - return nil - } - - upgradeInfo := &UpgradeInfo{ - StartedTime: ptypes.TimestampNow(), - } - - // Encode the canary - info, err := proto.Marshal(upgradeInfo) - if err != nil { - return err - } - - // Because this is a long running process we need a new context. - ctx = context.Background() - - upgradeKey := func(key string) error { - if strings.HasPrefix(key, b.storagePrefix) { - return nil - } - - // Read the old data - data, err := s.Get(ctx, key) - if err != nil { - return err - } - - locksutil.LockForKey(b.locks, key).Lock() - defer locksutil.LockForKey(b.locks, key).Unlock() - - meta := &KeyMetadata{ - Key: key, - Versions: map[uint64]*VersionMetadata{}, - } - - versionKey, err := b.getVersionKey(ctx, key, 1, s) - if err != nil { - return err - } - - version := &Version{ - Data: data.Value, - CreatedTime: ptypes.TimestampNow(), - } - - buf, err := proto.Marshal(version) - if err != nil { - return err - } - - // Store the version data - if err := s.Put(ctx, &logical.StorageEntry{ - Key: versionKey, - Value: buf, - }); err != nil { - return err - } - - // Store the metadata - meta.AddVersion(version.CreatedTime, nil, 1) - err = b.writeKeyMetadata(ctx, s, meta) - if err != nil { - return err - } - - // delete the old key - err = s.Delete(ctx, key) - if err != nil { - return err - } - - return nil - } - - // Run the actual upgrade in a go routine so we don't block the client on a - // potentially long process. - go func() { - - // Write the canary value and if we are read only wait until the setup - // process has finished. - READONLY_LOOP: - for { - err := s.Put(ctx, &logical.StorageEntry{ - Key: path.Join(b.storagePrefix, "upgrading"), - Value: info, - }) - switch { - case err == nil: - break READONLY_LOOP - case err.Error() == logical.ErrSetupReadOnly.Error(): - time.Sleep(10 * time.Millisecond) - default: - b.Logger().Error("writing upgrade info resulted in an error", "error", err) - return - } - } - - b.Logger().Info("collecting keys to upgrade") - keys, err := logical.CollectKeys(ctx, s) - if err != nil { - b.Logger().Error("upgrading resulted in error", "error", err) - return - } - - b.Logger().Info("done collecting keys", "num_keys", len(keys)) - for i, key := range keys { - if b.Logger().IsDebug() && i%500 == 0 { - b.Logger().Debug("upgrading keys", "progress", fmt.Sprintf("%d/%d", i, len(keys))) - } - err := upgradeKey(key) - if err != nil { - b.Logger().Error("upgrading resulted in error", "error", err, "progress", fmt.Sprintf("%d/%d", i+1, len(keys))) - return - } - } - - b.Logger().Info("upgrading keys finished") - - // Write upgrade done value - upgradeInfo.Done = true - info, err := proto.Marshal(upgradeInfo) - if err != nil { - b.Logger().Error("encoding upgrade info resulted in an error", "error", err) - } - - err = s.Put(ctx, &logical.StorageEntry{ - Key: path.Join(b.storagePrefix, "upgrading"), - Value: info, - }) - if err != nil { - b.Logger().Error("writing upgrade done resulted in an error", "error", err) - } - - atomic.StoreUint32(b.upgrading, 0) - }() - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/CHANGELOG.md b/vendor/github.com/hashicorp/vault/CHANGELOG.md deleted file mode 100644 index de6bdcc18..000000000 --- a/vendor/github.com/hashicorp/vault/CHANGELOG.md +++ /dev/null @@ -1,3312 +0,0 @@ -## 0.11.1 (September 6th, 2018) - -SECURITY: - - * Random Byte Reading in Barrier: Prior to this release, Vault was not - properly checking the error code when reading random bytes for the IV for - AES operations in its cryptographic barrier. Specifically, this means that - such an IV could potentially be zero multiple times, causing nonce re-use - and weakening the security of the key. On most platforms this should never - happen because reading from kernel random sources is non-blocking and always - successful, but there may be platform-specific behavior that has not been - accounted for. (Vault has tests to check exactly this, and the tests have - never seen nonce re-use.) - -FEATURES: - - * AliCloud Agent Support: Vault Agent can now authenticate against the - AliCloud auth method. - * UI: Enable AliCloud auth method and Azure secrets engine via the UI. - -IMPROVEMENTS: - - * core: Logging level for most logs (not including secrets/auth plugins) can - now be changed on-the-fly via `SIGHUP`, reading the desired value from - Vault's config file [GH-5280] - -BUG FIXES: - - * core: Ensure we use a background context when stepping down [GH-5290] - * core: Properly check error return from random byte reading [GH-5277] - * core: Re-add `sys/` top-route injection for now [GH-5241] - * core: Properly store the replication checkpoint file if it's larger than the - storage engine's per-item limit - * identity: Update MemDB with identity group alias while loading groups [GH-5289] - * secrets/database: Fix nil pointer when revoking some leases [GH-5262] - * secrets/pki: Fix sign-verbatim losing extra Subject attributes [GH-5245] - * secrets/pki: Remove certificates from store when tidying revoked - certificates and simplify API [GH-5231] - * ui: JSON editor will not coerce input to an object, and will now show an - error about Vault expecting an object [GH-5271] - * ui: authentication form will now default to any methods that have been tuned - to show up for unauthenticated users [GH-5281] - - -## 0.11.0 (August 28th, 2018) - -DEPRECATIONS/CHANGES: - - * Request Timeouts: A default request timeout of 90s is now enforced. This - setting can be overwritten in the config file. If you anticipate requests - taking longer than 90s this setting should be updated before upgrading. - * (NOTE: will be re-added into 0.11.1 as it broke more than anticipated. There - will be some further guidelines around when this will be removed again.) - * `sys/` Top Level Injection: For the last two years for backwards - compatibility data for various `sys/` routes has been injected into both the - Secret's Data map and into the top level of the JSON response object. - However, this has some subtle issues that pop up from time to time and is - becoming increasingly complicated to maintain, so it's finally being - removed. - * Path Fallback for List Operations: For a very long time Vault has - automatically adjusted `list` operations to always end in a `/`, as list - operations operates on prefixes, so all list operations by definition end - with `/`. This was done server-side so affects all clients. However, this - has also led to a lot of confusion for users writing policies that assume - that the path that they use in the CLI is the path used internally. Starting - in 0.11, ACL policies gain a new fallback rule for listing: they will use a - matching path ending in `/` if available, but if not found, they will look - for the same path without a trailing `/`. This allows putting `list` - capabilities in the same path block as most other capabilities for that - path, while not providing any extra access if `list` wasn't actually - provided there. - * Performance Standbys On By Default: If you flavor/license of Vault - Enterprise supports Performance Standbys, they are on by default. You can - disable this behavior per-node with the `disable_performance_standby` - configuration flag. - * AWS Secret Engine Roles: The AWS Secret Engine roles are now explicit about - the type of AWS credential they are generating; this reduces reduce - ambiguity that existed previously as well as enables new features for - specific credential types. Writing role data and generating credentials - remain backwards compatible; however, the data returned when reading a - role's configuration has changed in backwards-incompatible ways. Anything - that depended on reading role data from the AWS secret engine will break - until it is updated to work with the new format. - -FEATURES: - - * **Namespaces (Enterprise)**: A set of features within Vault Enterprise - that allows Vault environments to support *Secure Multi-tenancy* within a - single Vault Enterprise infrastructure. Through namespaces, Vault - administrators can support tenant isolation for teams and individuals as - well as empower those individuals to self-manage their own tenant - environment. - * **Performance Standbys (Enterprise)**: Standby nodes can now service - requests that do not modify storage. This provides near-horizontal scaling - of a cluster in some workloads, and is the intra-cluster analogue of - the existing Performance Replication feature, which replicates to distinct - clusters in other datacenters, geos, etc. - * **AliCloud OSS Storage**: AliCloud OSS can now be used for Vault storage. - * **AliCloud Auth Plugin**: AliCloud's identity services can now be used to - grant access to Vault. See the [plugin - repository](https://github.com/hashicorp/vault-plugin-auth-alicloud) for - more information. - * **Azure Secrets Plugin**: There is now a plugin (pulled in to Vault) that - allows generating credentials to allow access to Azure. See the [plugin - repository](https://github.com/hashicorp/vault-plugin-secrets-azure) for - more information. - * **HA Support for MySQL Storage**: MySQL storage now supports HA. - * **ACL Templating**: ACL policies can now be templated using identity Entity, - Groups, and Metadata. - * **UI Onboarding wizards**: The Vault UI can provide contextual help and - guidance, linking out to relevant links or guides on vaultproject.io for - various workflows in Vault. - -IMPROVEMENTS: - - * agent: Add `exit_after_auth` to be able to use the Agent for a single - authentication [GH-5013] - * auth/approle: Add ability to set token bound CIDRs on individual Secret IDs - [GH-5034] - * cli: Add support for passing parameters to `vault read` operations [GH-5093] - * secrets/aws: Make credential types more explicit [GH-4360] - * secrets/nomad: Support for longer token names [GH-5117] - * secrets/pki: Allow disabling CRL generation [GH-5134] - * storage/azure: Add support for different Azure environments [GH-4997] - * storage/file: Sort keys in list responses [GH-5141] - * storage/mysql: Support special characters in database and table names. - -BUG FIXES: - - * auth/jwt: Always validate `aud` claim even if `bound_audiences` isn't set - (IOW, error in this case) - * core: Prevent Go's HTTP library from interspersing logs in a different - format and/or interleaved [GH-5135] - * identity: Properly populate `mount_path` and `mount_type` on group lookup - [GH-5074] - * identity: Fix persisting alias metadata [GH-5188] - * identity: Fix carryover issue from previously fixed race condition that - could cause Vault not to start up due to two entities referencing the same - alias. These entities are now merged. [GH-5000] - * replication: Fix issue causing some pages not to flush to storage - * secrets/database: Fix inability to update custom SQL statements on - database roles. [GH-5080] - * secrets/pki: Disallow putting the CA's serial on its CRL. While technically - legal, doing so inherently means the CRL can't be trusted anyways, so it's - not useful and easy to footgun. [GH-5134] - * storage/gcp,spanner: Fix data races [GH-5081] - -## 0.10.4 (July 25th, 2018) - -SECURITY: - - * Control Groups: The associated Identity entity with a request was not being - properly persisted. As a result, the same authorizer could provide more than - one authorization. - -DEPRECATIONS/CHANGES: - - * Revocations of dynamic secrets leases are now queued/asynchronous rather - than synchronous. This allows Vault to take responsibility for revocation - even if the initial attempt fails. The previous synchronous behavior can be - attained via the `-sync` CLI flag or `sync` API parameter. When in - synchronous mode, if the operation results in failure it is up to the user - to retry. - * CLI Retries: The CLI will no longer retry commands on 5xx errors. This was a - source of confusion to users as to why Vault would "hang" before returning a - 5xx error. The Go API client still defaults to two retries. - * Identity Entity Alias metadata: You can no longer manually set metadata on - entity aliases. All alias data (except the canonical entity ID it refers to) - is intended to be managed by the plugin providing the alias information, so - allowing it to be set manually didn't make sense. - -FEATURES: - - * **JWT/OIDC Auth Method**: The new `jwt` auth method accepts JWTs and either - validates signatures locally or uses OIDC Discovery to fetch the current set - of keys for signature validation. Various claims can be specified for - validation (in addition to the cryptographic signature) and a user and - optional groups claim can be used to provide Identity information. - * **FoundationDB Storage**: You can now use FoundationDB for storing Vault - data. - * **UI Control Group Workflow (enterprise)**: The UI will now detect control - group responses and provides a workflow to view the status of the request - and to authorize requests. - * **Vault Agent (Beta)**: Vault Agent is a daemon that can automatically - authenticate for you across a variety of authentication methods, provide - tokens to clients, and keep the tokens renewed, reauthenticating as - necessary. - -IMPROVEMENTS: - - * auth/azure: Add support for virtual machine scale sets - * auth/gcp: Support multiple bindings for region, zone, and instance group - * cli: Add subcommands for interacting with the plugin catalog [GH-4911] - * cli: Add a `-description` flag to secrets and auth tune subcommands to allow - updating an existing secret engine's or auth method's description. This - change also allows the description to be unset by providing an empty string. - * core: Add config flag to disable non-printable character check [GH-4917] - * core: A `max_request_size` parameter can now be set per-listener to adjust - the maximum allowed size per request [GH-4824] - * core: Add control group request endpoint to default policy [GH-4904] - * identity: Identity metadata is now passed through to plugins [GH-4967] - * replication: Add additional saftey checks and logging when replication is - in a bad state - * secrets/kv: Add support for using `-field=data` to KVv2 when using `vault - kv` [GH-4895] - * secrets/pki: Add the ability to tidy revoked but unexpired certificates - [GH-4916] - * secrets/ssh: Allow Vault to work with single-argument SSH flags [GH-4825] - * secrets/ssh: SSH executable path can now be configured in the CLI [GH-4937] - * storage/swift: Add additional configuration options [GH-4901] - * ui: Choose which auth methods to show to unauthenticated users via - `listing_visibility` in the auth method edit forms [GH-4854] - * ui: Authenticate users automatically by passing a wrapped token to the UI via - the new `wrapped_token` query parameter [GH-4854] - -BUG FIXES: - - * api: Fix response body being cleared too early [GH-4987] - * auth/approle: Fix issue with tidy endpoint that would unnecessarily remove - secret accessors [GH-4981] - * auth/aws: Fix updating `max_retries` [GH-4980] - * auth/kubernetes: Trim trailing whitespace when sending JWT - * cli: Fix parsing of environment variables for integer flags [GH-4925] - * core: Fix returning 500 instead of 503 if a rekey is attempted when Vault is - sealed [GH-4874] - * core: Fix issue releasing the leader lock in some circumstances [GH-4915] - * core: Fix a panic that could happen if the server was shut down while still - starting up - * core: Fix deadlock that would occur if a leadership loss occurs at the same - time as a seal operation [GH-4932] - * core: Fix issue with auth mounts failing to renew tokens due to policies - changing [GH-4960] - * auth/radius: Fix issue where some radius logins were being canceled too early - [GH-4941] - * core: Fix accidental seal of vault of we lose leadership during startup - [GH-4924] - * core: Fix standby not being able to forward requests larger than 4MB - [GH-4844] - * core: Avoid panic while processing group memberships [GH-4841] - * identity: Fix a race condition creating aliases [GH-4965] - * plugins: Fix being unable to send very large payloads to or from plugins - [GH-4958] - * physical/azure: Long list responses would sometimes be truncated [GH-4983] - * replication: Allow replication status requests to be processed while in - merkle sync - * replication: Ensure merkle reindex flushes all changes to storage immediately - * replication: Fix a case where a network interruption could cause a secondary - to be unable to reconnect to a primary - * secrets/pki: Fix permitted DNS domains performing improper validation - [GH-4863] - * secrets/database: Fix panic during DB creds revocation [GH-4846] - * ui: Fix usage of cubbyhole backend in the UI [GH-4851] - * ui: Fix toggle state when a secret is JSON-formatted [GH-4913] - * ui: Fix coercion of falsey values to empty string when editing secrets as - JSON [GH-4977] - -## 0.10.3 (June 20th, 2018) - -DEPRECATIONS/CHANGES: - - * In the audit log and in client responses, policies are now split into three - parameters: policies that came only from tokens, policies that came only - from Identity, and the combined set. Any previous location of policies via - the API now contains the full, combined set. - * When a token is tied to an Identity entity and the entity is deleted, the - token will no longer be usable, regardless of the validity of the token - itself. - * When authentication succeeds but no policies were defined for that specific - user, most auth methods would allow a token to be generated but a few would - reject the authentication, namely `ldap`, `okta`, and `radius`. Since the - `default` policy is added by Vault's core, this would incorrectly reject - valid authentications before they would in fact be granted policies. This - inconsistency has been addressed; valid authentications for these methods - now succeed even if no policy was specifically defined in that method for - that user. - -FEATURES: - - * Root Rotation for Active Directory: You can now command Vault to rotate the - configured root credentials used in the AD secrets engine, to ensure that - only Vault knows the credentials it's using. - * URI SANs in PKI: You can now configure URI Subject Alternate Names in the - `pki` backend. Roles can limit which SANs are allowed via globbing. - * `kv rollback` Command: You can now use `vault kv rollback` to roll a KVv2 - path back to a previous non-deleted/non-destroyed version. The previous - version becomes the next/newest version for the path. - * Token Bound CIDRs in AppRole: You can now add CIDRs to which a token - generated from AppRole will be bound. - -IMPROVEMENTS: - - * approle: Return 404 instead of 202 on invalid role names during POST - operations [GH-4778] - * core: Add idle and initial header read/TLS handshake timeouts to connections - to ensure server resources are cleaned up [GH-4760] - * core: Report policies in token, identity, and full sets [GH-4747] - * secrets/databases: Add `create`/`update` distinction for connection - configurations [GH-3544] - * secrets/databases: Add `create`/`update` distinction for role configurations - [GH-3544] - * secrets/databases: Add best-effort revocation logic for use when a role has - been deleted [GH-4782] - * secrets/kv: Add `kv rollback` [GH-4774] - * secrets/pki: Add URI SANs support [GH-4675] - * secrets/ssh: Allow standard SSH command arguments to be used, without - requiring username@hostname syntax [GH-4710] - * storage/consul: Add context support so that requests are cancelable - [GH-4739] - * sys: Added `hidden` option to `listing_visibility` field on `sys/mounts` - API [GH-4827] - * ui: Secret values are obfuscated by default and visibility is toggleable [GH-4422] - -BUG FIXES: - - * auth/approle: Fix panic due to metadata being nil [GH-4719] - * auth/aws: Fix delete path for tidy operations [GH-4799] - * core: Optimizations to remove some speed regressions due to the - security-related changes in 0.10.2 - * storage/dynamodb: Fix errors seen when reading existing DynamoDB data [GH-4721] - * secrets/database: Fix default MySQL root rotation statement [GH-4748] - * secrets/gcp: Fix renewal for GCP account keys - * secrets/kv: Fix writing to the root of a KVv2 mount from `vault kv` commands - incorrectly operating on a root+mount path instead of being an error - [GH-4726] - * seal/pkcs11: Add `CKK_SHA256_HMAC` to the search list when finding HMAC - keys, fixing lookup on some Thales devices - * replication: Fix issue enabling replication when a non-auth mount and auth - mount have the same name - * auth/kubernetes: Fix issue verifying ECDSA signed JWTs - * ui: add missing edit mode for auth method configs [GH-4770] - -## 0.10.2 (June 6th, 2018) - -SECURITY: - - * Tokens: A race condition was identified that could occur if a token's - lease expired while Vault was not running. In this case, when Vault came - back online, sometimes it would properly revoke the lease but other times it - would not, leading to a Vault token that no longer had an expiration and had - essentially unlimited lifetime. This race was per-token, not all-or-nothing - for all tokens that may have expired during Vault's downtime. We have fixed - the behavior and put extra checks in place to help prevent any similar - future issues. In addition, the logic we have put in place ensures that such - lease-less tokens can no longer be used (unless they are root tokens that - never had an expiration to begin with). - * Convergent Encryption: The version 2 algorithm used in `transit`'s - convergent encryption feature is susceptible to offline - plaintext-confirmation attacks. As a result, we are introducing a version 3 - algorithm that mitigates this. If you are currently using convergent - encryption, we recommend upgrading, rotating your encryption key (the new - key version will use the new algorithm), and rewrapping your data (the - `rewrap` endpoint can be used to allow a relatively non-privileged user to - perform the rewrapping while never divulging the plaintext). - * AppRole case-sensitive role name secret-id leaking: When using a mixed-case - role name via AppRole, deleting a secret-id via accessor or other operations - could end up leaving the secret-id behind and valid but without an accessor. - This has now been fixed, and we have put checks in place to prevent these - secret-ids from being used. - -DEPRECATIONS/CHANGES: - - * PKI duration return types: The PKI backend now returns durations (e.g. when - reading a role) as an integer number of seconds instead of a Go-style - string, in line with how the rest of Vault's API returns durations. - -FEATURES: - - * Active Directory Secrets Engine: A new `ad` secrets engine has been created - which allows Vault to rotate and provide credentials for configured AD - accounts. - * Rekey Verification: Rekey operations can now require verification. This - turns on a two-phase process where the existing key shares authorize - generating a new master key, and a threshold of the new, returned key shares - must be provided to verify that they have been successfully received in - order for the actual master key to be rotated. - * CIDR restrictions for `cert`, `userpass`, and `kubernetes` auth methods: - You can now limit authentication to specific CIDRs; these will also be - encoded in resultant tokens to limit their use. - * Vault UI Browser CLI: The UI now supports usage of read/write/list/delete - commands in a CLI that can be accessed from the nav bar. Complex inputs such - as JSON files are not currently supported. This surfaces features otherwise - unsupported in Vault's UI. - * Azure Key Vault Auto Unseal/Seal Wrap Support (Enterprise): Azure Key Vault - can now be used a support seal for Auto Unseal and Seal Wrapping. - -IMPROVEMENTS: - - * api: Close renewer's doneCh when the renewer is stopped, so that programs - expecting a final value through doneCh behave correctly [GH-4472] - * auth/cert: Break out `allowed_names` into component parts and add - `allowed_uri_sans` [GH-4231] - * auth/ldap: Obfuscate error messages pre-bind for greater security [GH-4700] - * cli: `vault login` now supports a `-no-print` flag to suppress printing - token information but still allow storing into the token helper [GH-4454] - * core/pkcs11 (enterprise): Add support for CKM_AES_CBC_PAD, CKM_RSA_PKCS, and - CKM_RSA_PKCS_OAEP mechanisms - * core/pkcs11 (enterprise): HSM slots can now be selected by token label - instead of just slot number - * core/token: Optimize token revocation by removing unnecessary list call - against the storage backend when calling revoke-orphan on tokens [GH-4465] - * core/token: Refactor token revocation logic to not block on the call when - underlying leases are pending revocation by moving the expiration logic to - the expiration manager [GH-4512] - * expiration: Allow revoke-prefix and revoke-force to work on single leases as - well as prefixes [GH-4450] - * identity: Return parent group info when reading a group [GH-4648] - * identity: Provide more contextual key information when listing entities, - groups, and aliases - * identity: Passthrough EntityID to backends [GH-4663] - * identity: Adds ability to request entity information through system view - [GH_4681] - * secret/pki: Add custom extended key usages [GH-4667] - * secret/pki: Add custom PKIX serial numbers [GH-4694] - * secret/ssh: Use hostname instead of IP in OTP mode, similar to CA mode - [GH-4673] - * storage/file: Attempt in some error conditions to do more cleanup [GH-4684] - * ui: wrapping lookup now distplays the path [GH-4644] - * ui: Identity interface now has more inline actions to make editing and adding - aliases to an entity or group easier [GH-4502] - * ui: Identity interface now lists groups by name [GH-4655] - * ui: Permission denied errors still render the sidebar in the Access section - [GH-4658] - * replication: Improve performance of index page flushes and WAL garbage - collecting - -BUG FIXES: - - * auth/approle: Make invalid role_id a 400 error instead of 500 [GH-4470] - * auth/cert: Fix Identity alias using serial number instead of common name - [GH-4475] - * cli: Fix panic running `vault token capabilities` with multiple paths - [GH-4552] - * core: When using the `use_always` option with PROXY protocol support, do not - require `authorized_addrs` to be set [GH-4065] - * core: Fix panic when certain combinations of policy paths and allowed/denied - parameters were used [GH-4582] - * secret/gcp: Make `bound_region` able to use short names - * secret/kv: Fix response wrapping for KV v2 [GH-4511] - * secret/kv: Fix address flag not being honored correctly [GH-4617] - * secret/pki: Fix `safety_buffer` for tidy being allowed to be negative, - clearing all certs [GH-4641] - * secret/pki: Fix `key_type` not being allowed to be set to `any` [GH-4595] - * secret/pki: Fix path length parameter being ignored when using - `use_csr_values` and signing an intermediate CA cert [GH-4459] - * secret/ssh: Only append UserKnownHostsFile to args when configured with a - value [GH-4674] - * storage/dynamodb: Fix listing when one child is left within a nested path - [GH-4570] - * storage/gcs: Fix swallowing an error on connection close [GH-4691] - * ui: Fix HMAC algorithm in transit [GH-4604] - * ui: Fix unwrap of auth responses via the UI's unwrap tool [GH-4611] - * ui (enterprise): Fix parsing of version string that blocked some users from seeing - enterprise-specific pages in the UI [GH-4547] - * ui: Fix incorrect capabilities path check when viewing policies [GH-4566] - * replication: Fix error while running plugins on a newly created replication - secondary - * replication: Fix issue with token store lookups after a secondary's mount table - is invalidated. - * replication: Improve startup time when a large merkle index is in use. - * replication: Fix panic when storage becomes unreachable during unseal. - -## 0.10.1/0.9.7 (April 25th, 2018) - -The following two items are in both 0.9.7 and 0.10.1. They only affect -Enterprise, and as such 0.9.7 is an Enterprise-only release: - -SECURITY: - - * EGPs: A regression affecting 0.9.6 and 0.10.0 causes EGPs to not be applied - correctly if an EGP is updated in a running Vault after initial write or - after it is loaded on unseal. This has been fixed. - -BUG FIXES: - - * Fixed an upgrade issue affecting performance secondaries when migrating from - a version that did not include Identity to one that did. - -All other content in this release is for 0.10.1 only. - -DEPRECATIONS/CHANGES: - - * `vault kv` and Vault versions: In 0.10.1 some issues with `vault kv` against - v1 K/V engine mounts are fixed. However, using 0.10.1 for both the server - and CLI versions is required. - * Mount information visibility: Users that have access to any path within a - mount can now see information about that mount, such as its type and - options, via some API calls. - * Identity and Local Mounts: Local mounts would allow creating Identity - entities but these would not be able to be used successfully (even locally) - in replicated scenarios. We have now disallowed entities and groups from - being created for local mounts in the first place. - -FEATURES: - - * X-Forwarded-For support: `X-Forwarded-For` headers can now be used to set the - client IP seen by Vault. See the [TCP listener configuration - page](https://www.vaultproject.io/docs/configuration/listener/tcp.html) for - details. - * CIDR IP Binding for Tokens: Tokens now support being bound to specific - CIDR(s) for usage. Currently this is implemented in Token Roles; usage can be - expanded to other authentication backends over time. - * `vault kv patch` command: A new `kv patch` helper command that allows - modifying only some values in existing data at a K/V path, but uses - check-and-set to ensure that this modification happens safely. - * AppRole Local Secret IDs: Roles can now be configured to generate secret IDs - local to the cluster. This enables performance secondaries to generate and - consume secret IDs without contacting the primary. - * AES-GCM Support for PKCS#11 [BETA] (Enterprise): For supporting HSMs, - AES-GCM can now be used in lieu of AES-CBC/HMAC-SHA256. This has currently - only been fully tested on AWS CloudHSM. - * Auto Unseal/Seal Wrap Key Rotation Support (Enterprise): Auto Unseal - mechanisms, including PKCS#11 HSMs, now support rotation of encryption keys, - and migration between key and encryption types, such as from AES-CBC to - AES-GCM, can be performed at the same time (where supported). - -IMPROVEMENTS: - - * auth/approle: Support for cluster local secret IDs. This enables secondaries - to generate secret IDs without contacting the primary [GH-4427] - * auth/token: Add to the token lookup response, the policies inherited due to - identity associations [GH-4366] - * auth/token: Add CIDR binding to token roles [GH-815] - * cli: Add `vault kv patch` [GH-4432] - * core: Add X-Forwarded-For support [GH-4380] - * core: Add token CIDR-binding support [GH-815] - * identity: Add the ability to disable an entity. Disabling an entity does not - revoke associated tokens, but while the entity is disabled they cannot be - used. [GH-4353] - * physical/consul: Allow tuning of session TTL and lock wait time [GH-4352] - * replication: Dynamically adjust WAL cleanup over a period of time based on - the rate of writes committed - * secret/ssh: Update dynamic key install script to use shell locking to avoid - concurrent modifications [GH-4358] - * ui: Access to `sys/mounts` is no longer needed to use the UI - the list of - engines will show you the ones you implicitly have access to (because you have - access to to secrets in those engines) [GH-4439] - -BUG FIXES: - - * cli: Fix `vault kv` backwards compatibility with KV v1 engine mounts - [GH-4430] - * identity: Persist entity memberships in external identity groups across - mounts [GH-4365] - * identity: Fix error preventing authentication using local mounts on - performance secondary replication clusters [GH-4407] - * replication: Fix issue causing secondaries to not connect properly to a - pre-0.10 primary until the primary was upgraded - * secret/gcp: Fix panic on rollback when a roleset wasn't created properly - [GH-4344] - * secret/gcp: Fix panic on renewal - * ui: Fix IE11 form submissions in a few parts of the application [GH-4378] - * ui: Fix IE file saving on policy pages and init screens [GH-4376] - * ui: Fixed an issue where the AWS secret backend would show the wrong menu - [GH-4371] - * ui: Fixed an issue where policies with commas would not render in the - interface properly [GH-4398] - * ui: Corrected the saving of mount tune ttls for auth methods [GH-4431] - * ui: Credentials generation no longer checks capabilities before making - api calls. This should fix needing "update" capabilites to read IAM - credentials in the AWS secrets engine [GH-4446] - -## 0.10.0 (April 10th, 2018) - -SECURITY: - - * Log sanitization for Combined Database Secret Engine: In certain failure - scenarios with incorrectly formatted connection urls, the raw connection - errors were being returned to the user with the configured database - credentials. Errors are now sanitized before being returned to the user. - -DEPRECATIONS/CHANGES: - - * Database plugin compatibility: The database plugin interface was enhanced to - support some additional functionality related to root credential rotation - and supporting templated URL strings. The changes were made in a - backwards-compatible way and all builtin plugins were updated with the new - features. Custom plugins not built into Vault will need to be upgraded to - support templated URL strings and root rotation. Additionally, the - Initialize method was deprecated in favor of a new Init method that supports - configuration modifications that occur in the plugin back to the primary - data store. - * Removal of returned secret information: For a long time Vault has returned - configuration given to various secret engines and auth methods with secret - values (such as secret API keys or passwords) still intact, and with a - warning to the user on write that anyone with read access could see the - secret. This was mostly done to make it easy for tools like Terraform to - judge whether state had drifted. However, it also feels quite un-Vault-y to - do this and we've never felt very comfortable doing so. In 0.10 we have gone - through and removed this behavior from the various backends; fields which - contained secret values are simply no longer returned on read. We are - working with the Terraform team to make changes to their provider to - accommodate this as best as possible, and users of other tools may have to - make adjustments, but in the end we felt that the ends did not justify the - means and we needed to prioritize security over operational convenience. - * LDAP auth method case sensitivity: We now treat usernames and groups - configured locally for policy assignment in a case insensitive fashion by - default. Existing configurations will continue to work as they do now; - however, the next time a configuration is written `case_sensitive_names` - will need to be explicitly set to `true`. - * TTL handling within core: All lease TTL handling has been centralized within - the core of Vault to ensure consistency across all backends. Since this was - previously delegated to individual backends, there may be some slight - differences in TTLs generated from some backends. - * Removal of default `secret/` mount: In 0.12 we will stop mounting `secret/` - by default at initialization time (it will still be available in `dev` - mode). - -FEATURES: - - * OSS UI: The Vault UI is now fully open-source. Similarly to the CLI, some - features are only available with a supporting version of Vault, but the code - base is entirely open. - * Versioned K/V: The `kv` backend has been completely revamped, featuring - flexible versioning of values, check-and-set protections, and more. A new - `vault kv` subcommand allows friendly interactions with it. Existing mounts - of the `kv` backend can be upgraded to the new versioned mode (downgrades - are not currently supported). The old "passthrough" mode is still the - default for new mounts; versioning can be turned on by setting the - `-version=2` flag for the `vault secrets enable` command. - * Database Root Credential Rotation: Database configurations can now rotate - their own configured admin/root credentials, allowing configured credentials - for a database connection to be rotated immediately after sending them into - Vault, invalidating the old credentials and ensuring only Vault knows the - actual valid values. - * Azure Authentication Plugin: There is now a plugin (pulled in to Vault) that - allows authenticating Azure machines to Vault using Azure's Managed Service - Identity credentials. See the [plugin - repository](https://github.com/hashicorp/vault-plugin-auth-azure) for more - information. - * GCP Secrets Plugin: There is now a plugin (pulled in to Vault) that allows - generating secrets to allow access to GCP. See the [plugin - repository](https://github.com/hashicorp/vault-plugin-secrets-gcp) for more - information. - * Selective Audit HMACing of Request and Response Data Keys: HMACing in audit - logs can be turned off for specific keys in the request input map and - response `data` map on a per-mount basis. - * Passthrough Request Headers: Request headers can now be selectively passed - through to backends on a per-mount basis. This is useful in various cases - when plugins are interacting with external services. - * HA for Google Cloud Storage: The GCS storage type now supports HA. - * UI support for identity: Add and edit entities, groups, and their associated - aliases. - * UI auth method support: Enable, disable, and configure all of the built-in - authentication methods. - * UI (Enterprise): View and edit Sentinel policies. - -IMPROVEMENTS: - - * core: Centralize TTL generation for leases in core [GH-4230] - * identity: API to update group-alias by ID [GH-4237] - * secret/cassandra: Update Cassandra storage delete function to not use batch - operations [GH-4054] - * storage/mysql: Allow setting max idle connections and connection lifetime - [GH-4211] - * storage/gcs: Add HA support [GH-4226] - * ui: Add Nomad to the list of available secret engines - * ui: Adds ability to set static headers to be returned by the UI - -BUG FIXES: - - * api: Fix retries not working [GH-4322] - * auth/gcp: Invalidate clients on config change - * auth/token: Revoke-orphan and tidy operations now correctly cleans up the - parent prefix entry in the underlying storage backend. These operations also - mark corresponding child tokens as orphans by removing the parent/secondary - index from the entries. [GH-4193] - * command: Re-add `-mfa` flag and migrate to OSS binary [GH-4223] - * core: Fix issue occurring from mounting two auth backends with the same path - with one mount having `auth/` in front [GH-4206] - * mfa: Invalidation of MFA configurations (Enterprise) - * replication: Fix a panic on some non-64-bit platforms - * replication: Fix invalidation of policies on performance secondaries - * secret/pki: When tidying if a value is unexpectedly nil, delete it and move - on [GH-4214] - * storage/s3: Fix panic if S3 returns no Content-Length header [GH-4222] - * ui: Fixed an issue where the UI was checking incorrect paths when operating - on transit keys. Capabilities are now checked when attempting to encrypt / - decrypt, etc. - * ui: Fixed IE 11 layout issues and JS errors that would stop the application - from running. - * ui: Fixed the link that gets rendered when a user doesn't have permissions - to view the root of a secret engine. The link now sends them back to the list - of secret engines. - * replication: Fix issue with DR secondaries when using mount specified local - paths. - * cli: Fix an issue where generating a dr operation token would not output the - token [GH-4328] - -## 0.9.6 (March 20th, 2018) - -DEPRECATIONS/CHANGES: - - * The AWS authentication backend now allows binds for inputs as either a - comma-delimited string or a string array. However, to keep consistency with - input and output, when reading a role the binds will now be returned as - string arrays rather than strings. - * In order to prefix-match IAM role and instance profile ARNs in AWS auth - backend, you now must explicitly opt-in by adding a `*` to the end of the - ARN. Existing configurations will be upgraded automatically, but when - writing a new role configuration the updated behavior will be used. - -FEATURES: - - * Replication Activation Enhancements: When activating a replication - secondary, a public key can now be fetched first from the target cluster. - This public key can be provided to the primary when requesting the - activation token. If provided, the public key will be used to perform a - Diffie-Hellman key exchange resulting in a shared key that encrypts the - contents of the activation token. The purpose is to protect against - accidental disclosure of the contents of the token if unwrapped by the wrong - party, given that the contents of the token are highly sensitive. If - accidentally unwrapped, the contents of the token are not usable by the - unwrapping party. It is important to note that just as a malicious operator - could unwrap the contents of the token, a malicious operator can pretend to - be a secondary and complete the Diffie-Hellman exchange on their own; this - feature provides defense in depth but still requires due diligence around - replication activation, including multiple eyes on the commands/tokens and - proper auditing. - -IMPROVEMENTS: - - * api: Update renewer grace period logic. It no longer is static, but rather - dynamically calculates one based on the current lease duration after each - renew. [GH-4090] - * auth/approle: Allow array input for bound_cidr_list [4078] - * auth/aws: Allow using lists in role bind parameters [GH-3907] - * auth/aws: Allow binding by EC2 instance IDs [GH-3816] - * auth/aws: Allow non-prefix-matched IAM role and instance profile ARNs - [GH-4071] - * auth/ldap: Set a very large size limit on queries [GH-4169] - * core: Log info notifications of revoked leases for all leases/reasons, not - just expirations [GH-4164] - * physical/couchdb: Removed limit on the listing of items [GH-4149] - * secret/pki: Support certificate policies [GH-4125] - * secret/pki: Add ability to have CA:true encoded into intermediate CSRs, to - improve compatibility with some ADFS scenarios [GH-3883] - * secret/transit: Allow selecting signature algorithm as well as hash - algorithm when signing/verifying [GH-4018] - * server: Make sure `tls_disable_client_cert` is actually a true value rather - than just set [GH-4049] - * storage/dynamodb: Allow specifying max retries for dynamo client [GH-4115] - * storage/gcs: Allow specifying chunk size for transfers, which can reduce - memory utilization [GH-4060] - * sys/capabilities: Add the ability to use multiple paths for capability - checking [GH-3663] - -BUG FIXES: - - * auth/aws: Fix honoring `max_ttl` when a corresponding role `ttl` is not also - set [GH-4107] - * auth/okta: Fix honoring configured `max_ttl` value [GH-4110] - * auth/token: If a periodic token being issued has a period greater than the - max_lease_ttl configured on the token store mount, truncate it. This matches - renewal behavior; before it was inconsistent between issuance and renewal. - [GH-4112] - * cli: Improve error messages around `vault auth help` when there is no CLI - helper for a particular method [GH-4056] - * cli: Fix autocomplete installation when using Fish as the shell [GH-4094] - * secret/database: Properly honor mount-tuned max TTL [GH-4051] - * secret/ssh: Return `key_bits` value when reading a role [GH-4098] - * sys: When writing policies on a performance replication secondary, properly - forward requests to the primary [GH-4129] - -## 0.9.5 (February 26th, 2018) - -IMPROVEMENTS: - - * auth: Allow sending default_lease_ttl and max_lease_ttl values when enabling - auth methods. [GH-4019] - * secret/database: Add list functionality to `database/config` endpoint - [GH-4026] - * physical/consul: Allow setting a specific service address [GH-3971] - * replication: When bootstrapping a new secondary, if the initial cluster - connection fails, Vault will attempt to roll back state so that - bootstrapping can be tried again, rather than having to recreate the - downstream cluster. This will still require fetching a new secondary - activation token. - -BUG FIXES: - - * auth/aws: Update libraries to fix regression verifying PKCS#7 identity - documents [GH-4014] - * listener: Revert to Go 1.9 for now to allow certificates with non-DNS names - in their DNS SANs to be used for Vault's TLS connections [GH-4028] - * replication: Fix issue with a performance secondary/DR primary node losing - its DR primary status when performing an update-primary operation - * replication: Fix issue where performance secondaries could be unable to - automatically connect to a performance primary after that performance - primary has been promoted to a DR primary from a DR secondary - * ui: Fix behavior when a value contains a `.` - -## 0.9.4 (February 20th, 2018) - -SECURITY: - - * Role Tags used with the EC2 style of AWS auth were being improperly parsed; - as a result they were not being used to properly restrict values. - Implementations following our suggestion of using these as defense-in-depth - rather than the only source of restriction should not have significant - impact. - -FEATURES: - - * **ChaCha20-Poly1305 support in `transit`**: You can now encrypt and decrypt - with ChaCha20-Poly1305 in `transit`. Key derivation and convergent - encryption is also supported. - * **Okta Push support in Okta Auth Backend**: If a user account has MFA - required within Okta, an Okta Push MFA flow can be used to successfully - finish authentication. - * **PKI Improvements**: Custom OID subject alternate names can now be set, - subject to allow restrictions that support globbing. Additionally, Country, - Locality, Province, Street Address, and Postal Code can now be set in - certificate subjects. - * **Manta Storage**: Joyent Triton Manta can now be used for Vault storage - * **Google Cloud Spanner Storage**: Google Cloud Spanner can now be used for - Vault storage - -IMPROVEMENTS: - - * auth/centrify: Add CLI helper - * audit: Always log failure metrics, even if zero, to ensure the values appear - on dashboards [GH-3937] - * cli: Disable color when output is not a TTY [GH-3897] - * cli: Add `-format` flag to all subcommands [GH-3897] - * cli: Do not display deprecation warnings when the format is not table - [GH-3897] - * core: If over a predefined lease count (256k), log a warning not more than - once a minute. Too many leases can be problematic for many of the storage - backends and often this number of leases is indicative of a need for - workflow improvements. [GH-3957] - * secret/nomad: Have generated ACL tokens cap out at 64 characters [GH-4009] - * secret/pki: Country, Locality, Province, Street Address, and Postal Code can - now be set on certificates [GH-3992] - * secret/pki: UTF-8 Other Names can now be set in Subject Alternate Names in - issued certs; allowed values can be set per role and support globbing - [GH-3889] - * secret/pki: Add a flag to make the common name optional on certs [GH-3940] - * secret/pki: Ensure only DNS-compatible names go into DNS SANs; additionally, - properly handle IDNA transformations for these DNS names [GH-3953] - * secret/ssh: Add `valid-principles` flag to CLI for CA mode [GH-3922] - * storage/manta: Add Manta storage [GH-3270] - * ui (Enterprise): Support for ChaCha20-Poly1305 keys in the transit engine. - -BUG FIXES: - * api/renewer: Honor increment value in renew auth calls [GH-3904] - * auth/approle: Fix inability to use limited-use-count secret IDs on - replication performance secondaries - * auth/approle: Cleanup of secret ID accessors during tidy and removal of - dangling accessor entries [GH-3924] - * auth/aws-ec2: Avoid masking of role tag response [GH-3941] - * auth/cert: Verify DNS SANs in the authenticating certificate [GH-3982] - * auth/okta: Return configured durations as seconds, not nanoseconds [GH-3871] - * auth/okta: Get all okta groups for a user vs. default 200 limit [GH-4034] - * auth/token: Token creation via the CLI no longer forces periodic token - creation. Passing an explicit zero value for the period no longer create - periodic tokens. [GH-3880] - * command: Fix interpreted formatting directives when printing raw fields - [GH-4005] - * command: Correctly format output when using -field and -format flags at the - same time [GH-3987] - * command/rekey: Re-add lost `stored-shares` parameter [GH-3974] - * command/ssh: Create and reuse the api client [GH-3909] - * command/status: Fix panic when status returns 500 from leadership lookup - [GH-3998] - * identity: Fix race when creating entities [GH-3932] - * plugin/gRPC: Fixed an issue with list requests and raw responses coming from - plugins using gRPC transport [GH-3881] - * plugin/gRPC: Fix panic when special paths are not set [GH-3946] - * secret/pki: Verify a name is a valid hostname before adding to DNS SANs - [GH-3918] - * secret/transit: Fix auditing when reading a key after it has been backed up - or restored [GH-3919] - * secret/transit: Fix storage/memory consistency when persistence fails - [GH-3959] - * storage/consul: Validate that service names are RFC 1123 compliant [GH-3960] - * storage/etcd3: Fix memory ballooning with standby instances [GH-3798] - * storage/etcd3: Fix large lists (like token loading at startup) not being - handled [GH-3772] - * storage/postgresql: Fix compatibility with versions using custom string - version tags [GH-3949] - * storage/zookeeper: Update vendoring to fix freezing issues [GH-3896] - * ui (Enterprise): Decoding the replication token should no longer error and - prevent enabling of a secondary replication cluster via the ui. - * plugin/gRPC: Add connection info to the request object [GH-3997] - -## 0.9.3 (January 28th, 2018) - -A regression from a feature merge disabled the Nomad secrets backend in 0.9.2. -This release re-enables the Nomad secrets backend; it is otherwise identical to -0.9.2. - -## 0.9.2 (January 26th, 2018) - -SECURITY: - - * Okta Auth Backend: While the Okta auth backend was successfully verifying - usernames and passwords, it was not checking the returned state of the - account, so accounts that had been marked locked out could still be used to - log in. Only accounts in SUCCESS or PASSWORD_WARN states are now allowed. - * Periodic Tokens: A regression in 0.9.1 meant that periodic tokens created by - the AppRole, AWS, and Cert auth backends would expire when the max TTL for - the backend/mount/system was hit instead of their stated behavior of living - as long as they are renewed. This is now fixed; existing tokens do not have - to be reissued as this was purely a regression in the renewal logic. - * Seal Wrapping: During certain replication states values written marked for - seal wrapping may not be wrapped on the secondaries. This has been fixed, - and existing values will be wrapped on next read or write. This does not - affect the barrier keys. - -DEPRECATIONS/CHANGES: - - * `sys/health` DR Secondary Reporting: The `replication_dr_secondary` bool - returned by `sys/health` could be misleading since it would be `false` both - when a cluster was not a DR secondary but also when the node is a standby in - the cluster and has not yet fully received state from the active node. This - could cause health checks on LBs to decide that the node was acceptable for - traffic even though DR secondaries cannot handle normal Vault traffic. (In - other words, the bool could only convey "yes" or "no" but not "not sure - yet".) This has been replaced by `replication_dr_mode` and - `replication_perf_mode` which are string values that convey the current - state of the node; a value of `disabled` indicates that replication is - disabled or the state is still being discovered. As a result, an LB check - can positively verify that the node is both not `disabled` and is not a DR - secondary, and avoid sending traffic to it if either is true. - * PKI Secret Backend Roles parameter types: For `ou` and `organization` - in role definitions in the PKI secret backend, input can now be a - comma-separated string or an array of strings. Reading a role will - now return arrays for these parameters. - * Plugin API Changes: The plugin API has been updated to utilize golang's - context.Context package. Many function signatures now accept a context - object as the first parameter. Existing plugins will need to pull in the - latest Vault code and update their function signatures to begin using - context and the new gRPC transport. - -FEATURES: - - * **gRPC Backend Plugins**: Backend plugins now use gRPC for transport, - allowing them to be written in other languages. - * **Brand New CLI**: Vault has a brand new CLI interface that is significantly - streamlined, supports autocomplete, and is almost entirely backwards - compatible. - * **UI: PKI Secret Backend (Enterprise)**: Configure PKI secret backends, - create and browse roles and certificates, and issue and sign certificates via - the listed roles. - -IMPROVEMENTS: - - * auth/aws: Handle IAM headers produced by clients that formulate numbers as - ints rather than strings [GH-3763] - * auth/okta: Support JSON lists when specifying groups and policies [GH-3801] - * autoseal/hsm: Attempt reconnecting to the HSM on certain kinds of issues, - including HA scenarios for some Gemalto HSMs. - (Enterprise) - * cli: Output password prompts to stderr to make it easier to pipe an output - token to another command [GH-3782] - * core: Report replication status in `sys/health` [GH-3810] - * physical/s3: Allow using paths with S3 for non-AWS deployments [GH-3730] - * physical/s3: Add ability to disable SSL for non-AWS deployments [GH-3730] - * plugins: Args for plugins can now be specified separately from the command, - allowing the same output format and input format for plugin information - [GH-3778] - * secret/pki: `ou` and `organization` can now be specified as a - comma-separated string or an array of strings [GH-3804] - * plugins: Plugins will fall back to using netrpc as the communication protocol - on older versions of Vault [GH-3833] - -BUG FIXES: - - * auth/(approle,aws,cert): Fix behavior where periodic tokens generated by - these backends could not have their TTL renewed beyond the system/mount max - TTL value [GH-3803] - * auth/aws: Fix error returned if `bound_iam_principal_arn` was given to an - existing role update [GH-3843] - * core/sealwrap: Speed improvements and bug fixes (Enterprise) - * identity: Delete group alias when an external group is deleted [GH-3773] - * legacymfa/duo: Fix intermittent panic when Duo could not be reached - [GH-2030] - * secret/database: Fix a location where a lock could potentially not be - released, leading to deadlock [GH-3774] - * secret/(all databases) Fix behavior where if a max TTL was specified but no - default TTL was specified the system/mount default TTL would be used but not - be capped by the local max TTL [GH-3814] - * secret/database: Fix an issue where plugins were not closed properly if they - failed to initialize [GH-3768] - * ui: mounting a secret backend will now properly set `max_lease_ttl` and - `default_lease_ttl` when specified - previously both fields set - `default_lease_ttl`. - -## 0.9.1 (December 21st, 2017) - -DEPRECATIONS/CHANGES: - - * AppRole Case Sensitivity: In prior versions of Vault, `list` operations - against AppRole roles would require preserving case in the role name, even - though most other operations within AppRole are case-insensitive with - respect to the role name. This has been fixed; existing roles will behave as - they have in the past, but new roles will act case-insensitively in these - cases. - * Token Auth Backend Roles parameter types: For `allowed_policies` and - `disallowed_policies` in role definitions in the token auth backend, input - can now be a comma-separated string or an array of strings. Reading a role - will now return arrays for these parameters. - * Transit key exporting: You can now mark a key in the `transit` backend as - `exportable` at any time, rather than just at creation time; however, once - this value is set, it still cannot be unset. - * PKI Secret Backend Roles parameter types: For `allowed_domains` and - `key_usage` in role definitions in the PKI secret backend, input - can now be a comma-separated string or an array of strings. Reading a role - will now return arrays for these parameters. - * SSH Dynamic Keys Method Defaults to 2048-bit Keys: When using the dynamic - key method in the SSH backend, the default is now to use 2048-bit keys if no - specific key bit size is specified. - * Consul Secret Backend lease handling: The `consul` secret backend can now - accept both strings and integer numbers of seconds for its lease value. The - value returned on a role read will be an integer number of seconds instead - of a human-friendly string. - * Unprintable characters not allowed in API paths: Unprintable characters are - no longer allowed in names in the API (paths and path parameters), with an - extra restriction on whitespace characters. Allowed characters are those - that are considered printable by Unicode plus spaces. - -FEATURES: - - * **Transit Backup/Restore**: The `transit` backend now supports a backup - operation that can export a given key, including all key versions and - configuration, as well as a restore operation allowing import into another - Vault. - * **gRPC Database Plugins**: Database plugins now use gRPC for transport, - allowing them to be written in other languages. - * **Nomad Secret Backend**: Nomad ACL tokens can now be generated and revoked - using Vault. - * **TLS Cert Auth Backend Improvements**: The `cert` auth backend can now - match against custom certificate extensions via exact or glob matching, and - additionally supports max_ttl and periodic token toggles. - -IMPROVEMENTS: - - * auth/cert: Support custom certificate constraints [GH-3634] - * auth/cert: Support setting `max_ttl` and `period` [GH-3642] - * audit/file: Setting a file mode of `0000` will now disable Vault from - automatically `chmod`ing the log file [GH-3649] - * auth/github: The legacy MFA system can now be used with the GitHub auth - backend [GH-3696] - * auth/okta: The legacy MFA system can now be used with the Okta auth backend - [GH-3653] - * auth/token: `allowed_policies` and `disallowed_policies` can now be specified - as a comma-separated string or an array of strings [GH-3641] - * command/server: The log level can now be specified with `VAULT_LOG_LEVEL` - [GH-3721] - * core: Period values from auth backends will now be checked and applied to the - TTL value directly by core on login and renewal requests [GH-3677] - * database/mongodb: Add optional `write_concern` parameter, which can be set - during database configuration. This establishes a session-wide [write - concern](https://docs.mongodb.com/manual/reference/write-concern/) for the - lifecycle of the mount [GH-3646] - * http: Request path containing non-printable characters will return 400 - Bad - Request [GH-3697] - * mfa/okta: Filter a given email address as a login filter, allowing operation - when login email and account email are different - * plugins: Make Vault more resilient when unsealing when plugins are - unavailable [GH-3686] - * secret/pki: `allowed_domains` and `key_usage` can now be specified - as a comma-separated string or an array of strings [GH-3642] - * secret/ssh: Allow 4096-bit keys to be used in dynamic key method [GH-3593] - * secret/consul: The Consul secret backend now uses the value of `lease` set - on the role, if set, when renewing a secret. [GH-3796] - * storage/mysql: Don't attempt database creation if it exists, which can help - under certain permissions constraints [GH-3716] - -BUG FIXES: - - * api/status (enterprise): Fix status reporting when using an auto seal - * auth/approle: Fix case-sensitive/insensitive comparison issue [GH-3665] - * auth/cert: Return `allowed_names` on role read [GH-3654] - * auth/ldap: Fix incorrect control information being sent [GH-3402] [GH-3496] - [GH-3625] [GH-3656] - * core: Fix seal status reporting when using an autoseal - * core: Add creation path to wrap info for a control group token - * core: Fix potential panic that could occur using plugins when a node - transitioned from active to standby [GH-3638] - * core: Fix memory ballooning when a connection would connect to the cluster - port and then go away -- redux! [GH-3680] - * core: Replace recursive token revocation logic with depth-first logic, which - can avoid hitting stack depth limits in extreme cases [GH-2348] - * core: When doing a read on configured audited-headers, properly handle case - insensitivity [GH-3701] - * core/pkcs11 (enterprise): Fix panic when PKCS#11 library is not readable - * database/mysql: Allow the creation statement to use commands that are not yet - supported by the prepare statement protocol [GH-3619] - * plugin/auth-gcp: Fix IAM roles when using `allow_gce_inference` [VPAG-19] - -## 0.9.0.1 (November 21st, 2017) (Enterprise Only) - -IMPROVEMENTS: - - * auth/gcp: Support seal wrapping of configuration parameters - * auth/kubernetes: Support seal wrapping of configuration parameters - -BUG FIXES: - - * Fix an upgrade issue with some physical backends when migrating from legacy - HSM stored key support to the new Seal Wrap mechanism (Enterprise) - * mfa: Add the 'mfa' flag that was removed by mistake [GH-4223] - -## 0.9.0 (November 14th, 2017) - -DEPRECATIONS/CHANGES: - - * HSM config parameter requirements: When using Vault with an HSM, a new - parameter is required: `hmac_key_label`. This performs a similar function to - `key_label` but for the HMAC key Vault will use. Vault will generate a - suitable key if this value is specified and `generate_key` is set true. - * API HTTP client behavior: When calling `NewClient` the API no longer - modifies the provided client/transport. In particular this means it will no - longer enable redirection limiting and HTTP/2 support on custom clients. It - is suggested that if you want to make changes to an HTTP client that you use - one created by `DefaultConfig` as a starting point. - * AWS EC2 client nonce behavior: The client nonce generated by the backend - that gets returned along with the authentication response will be audited in - plaintext. If this is undesired, the clients can choose to supply a custom - nonce to the login endpoint. The custom nonce set by the client will from - now on, not be returned back with the authentication response, and hence not - audit logged. - * AWS Auth role options: The API will now error when trying to create or - update a role with the mutually-exclusive options - `disallow_reauthentication` and `allow_instance_migration`. - * SSH CA role read changes: When reading back a role from the `ssh` backend, - the TTL/max TTL values will now be an integer number of seconds rather than - a string. This better matches the API elsewhere in Vault. - * SSH role list changes: When listing roles from the `ssh` backend via the API, - the response data will additionally return a `key_info` map that will contain - a map of each key with a corresponding object containing the `key_type`. - * More granularity in audit logs: Audit request and response entries are still - in RFC3339 format but now have a granularity of nanoseconds. - * High availability related values have been moved out of the `storage` and - `ha_storage` stanzas, and into the top-level configuration. `redirect_addr` - has been renamed to `api_addr`. The stanzas still support accepting - HA-related values to maintain backward compatibility, but top-level values - will take precedence. - * A new `seal` stanza has been added to the configuration file, which is - optional and enables configuration of the seal type to use for additional - data protection, such as using HSM or Cloud KMS solutions to encrypt and - decrypt data. - -FEATURES: - - * **RSA Support for Transit Backend**: Transit backend can now generate RSA - keys which can be used for encryption and signing. [GH-3489] - * **Identity System**: Now in open source and with significant enhancements, - Identity is an integrated system for understanding users across tokens and - enabling easier management of users directly and via groups. - * **External Groups in Identity**: Vault can now automatically assign users - and systems to groups in Identity based on their membership in external - groups. - * **Seal Wrap / FIPS 140-2 Compatibility (Enterprise)**: Vault can now take - advantage of FIPS 140-2-certified HSMs to ensure that Critical Security - Parameters are protected in a compliant fashion. Vault's implementation has - received a statement of compliance from Leidos. - * **Control Groups (Enterprise)**: Require multiple members of an Identity - group to authorize a requested action before it is allowed to run. - * **Cloud Auto-Unseal (Enterprise)**: Automatically unseal Vault using AWS KMS - and GCP CKMS. - * **Sentinel Integration (Enterprise)**: Take advantage of HashiCorp Sentinel - to create extremely flexible access control policies -- even on - unauthenticated endpoints. - * **Barrier Rekey Support for Auto-Unseal (Enterprise)**: When using auto-unsealing - functionality, the `rekey` operation is now supported; it uses recovery keys - to authorize the master key rekey. - * **Operation Token for Disaster Recovery Actions (Enterprise)**: When using - Disaster Recovery replication, a token can be created that can be used to - authorize actions such as promotion and updating primary information, rather - than using recovery keys. - * **Trigger Auto-Unseal with Recovery Keys (Enterprise)**: When using - auto-unsealing, a request to unseal Vault can be triggered by a threshold of - recovery keys, rather than requiring the Vault process to be restarted. - * **UI Redesign (Enterprise)**: All new experience for the Vault Enterprise - UI. The look and feel has been completely redesigned to give users a better - experience and make managing secrets fast and easy. - * **UI: SSH Secret Backend (Enterprise)**: Configure an SSH secret backend, - create and browse roles. And use them to sign keys or generate one time - passwords. - * **UI: AWS Secret Backend (Enterprise)**: You can now configure the AWS - backend via the Vault Enterprise UI. In addition you can create roles, - browse the roles and Generate IAM Credentials from them in the UI. - -IMPROVEMENTS: - - * api: Add ability to set custom headers on each call [GH-3394] - * command/server: Add config option to disable requesting client certificates - [GH-3373] - * auth/aws: Max retries can now be customized for the AWS client [GH-3965] - * core: Disallow mounting underneath an existing path, not just over [GH-2919] - * physical/file: Use `700` as permissions when creating directories. The files - themselves were `600` and are all encrypted, but this doesn't hurt. - * secret/aws: Add ability to use custom IAM/STS endpoints [GH-3416] - * secret/aws: Max retries can now be customized for the AWS client [GH-3965] - * secret/cassandra: Work around Cassandra ignoring consistency levels for a - user listing query [GH-3469] - * secret/pki: Private keys can now be marshalled as PKCS#8 [GH-3518] - * secret/pki: Allow entering URLs for `pki` as both comma-separated strings and JSON - arrays [GH-3409] - * secret/ssh: Role TTL/max TTL can now be specified as either a string or an - integer [GH-3507] - * secret/transit: Sign and verify operations now support a `none` hash - algorithm to allow signing/verifying pre-hashed data [GH-3448] - * secret/database: Add the ability to glob allowed roles in the Database Backend [GH-3387] - * ui (enterprise): Support for RSA keys in the transit backend - * ui (enterprise): Support for DR Operation Token generation, promoting, and - updating primary on DR Secondary clusters - -BUG FIXES: - - * api: Fix panic when setting a custom HTTP client but with a nil transport - [GH-3435] [GH-3437] - * api: Fix authing to the `cert` backend when the CA for the client cert is - not known to the server's listener [GH-2946] - * auth/approle: Create role ID index during read if a role is missing one [GH-3561] - * auth/aws: Don't allow mutually exclusive options [GH-3291] - * auth/radius: Fix logging in in some situations [GH-3461] - * core: Fix memleak when a connection would connect to the cluster port and - then go away [GH-3513] - * core: Fix panic if a single-use token is used to step-down or seal [GH-3497] - * core: Set rather than add headers to prevent some duplicated headers in - responses when requests were forwarded to the active node [GH-3485] - * physical/etcd3: Fix some listing issues due to how etcd3 does prefix - matching [GH-3406] - * physical/etcd3: Fix case where standbys can lose their etcd client lease - [GH-3031] - * physical/file: Fix listing when underscores are the first component of a - path [GH-3476] - * plugins: Allow response errors to be returned from backend plugins [GH-3412] - * secret/transit: Fix panic if the length of the input ciphertext was less - than the expected nonce length [GH-3521] - * ui (enterprise): Reinstate support for generic secret backends - this was - erroneously removed in a previous release - -## 0.8.3 (September 19th, 2017) - -CHANGES: - - * Policy input/output standardization: For all built-in authentication - backends, policies can now be specified as a comma-delimited string or an - array if using JSON as API input; on read, policies will be returned as an - array; and the `default` policy will not be forcefully added to policies - saved in configurations. Please note that the `default` policy will continue - to be added to generated tokens, however, rather than backends adding - `default` to the given set of input policies (in some cases, and not in - others), the stored set will reflect the user-specified set. - * `sign-self-issued` modifies Issuer in generated certificates: In 0.8.2 the - endpoint would not modify the Issuer in the generated certificate, leaving - the output self-issued. Although theoretically valid, in practice crypto - stacks were unhappy validating paths containing such certs. As a result, - `sign-self-issued` now encodes the signing CA's Subject DN into the Issuer - DN of the generated certificate. - * `sys/raw` requires enabling: While the `sys/raw` endpoint can be extremely - useful in break-glass or support scenarios, it is also extremely dangerous. - As of now, a configuration file option `raw_storage_endpoint` must be set in - order to enable this API endpoint. Once set, the available functionality has - been enhanced slightly; it now supports listing and decrypting most of - Vault's core data structures, except for the encryption keyring itself. - * `generic` is now `kv`: To better reflect its actual use, the `generic` - backend is now `kv`. Using `generic` will still work for backwards - compatibility. - -FEATURES: - - * **GCE Support for GCP Auth**: GCE instances can now authenticate to Vault - using machine credentials. - * **Support for Kubernetes Service Account Auth**: Kubernetes Service Accounts - can now authenticate to vault using JWT tokens. - -IMPROVEMENTS: - - * configuration: Provide a config option to store Vault server's process ID - (PID) in a file [GH-3321] - * mfa (Enterprise): Add the ability to use identity metadata in username format - * mfa/okta (Enterprise): Add support for configuring base_url for API calls - * secret/pki: `sign-intermediate` will now allow specifying a `ttl` value - longer than the signing CA certificate's NotAfter value. [GH-3325] - * sys/raw: Raw storage access is now disabled by default [GH-3329] - -BUG FIXES: - - * auth/okta: Fix regression that removed the ability to set base_url [GH-3313] - * core: Fix panic while loading leases at startup on ARM processors - [GH-3314] - * secret/pki: Fix `sign-self-issued` encoding the wrong subject public key - [GH-3325] - -## 0.8.2.1 (September 11th, 2017) (Enterprise Only) - -BUG FIXES: - - * Fix an issue upgrading to 0.8.2 for Enterprise customers. - -## 0.8.2 (September 5th, 2017) - -SECURITY: - -* In prior versions of Vault, if authenticating via AWS IAM and requesting a - periodic token, the period was not properly respected. This could lead to - tokens expiring unexpectedly, or a token lifetime being longer than expected. - Upon token renewal with Vault 0.8.2 the period will be properly enforced. - -DEPRECATIONS/CHANGES: - -* `vault ssh` users should supply `-mode` and `-role` to reduce the number of - API calls. A future version of Vault will mark these optional values are - required. Failure to supply `-mode` or `-role` will result in a warning. -* Vault plugins will first briefly run a restricted version of the plugin to - fetch metadata, and then lazy-load the plugin on first request to prevent - crash/deadlock of Vault during the unseal process. Plugins will need to be - built with the latest changes in order for them to run properly. - -FEATURES: - -* **Lazy Lease Loading**: On startup, Vault will now load leases from storage - in a lazy fashion (token checks and revocation/renewal requests still force - an immediate load). For larger installations this can significantly reduce - downtime when switching active nodes or bringing Vault up from cold start. -* **SSH CA Login with `vault ssh`**: `vault ssh` now supports the SSH CA - backend for authenticating to machines. It also supports remote host key - verification through the SSH CA backend, if enabled. -* **Signing of Self-Issued Certs in PKI**: The `pki` backend now supports - signing self-issued CA certs. This is useful when switching root CAs. - -IMPROVEMENTS: - - * audit/file: Allow specifying `stdout` as the `file_path` to log to standard - output [GH-3235] - * auth/aws: Allow wildcards in `bound_iam_principal_arn` [GH-3213] - * auth/okta: Compare groups case-insensitively since Okta is only - case-preserving [GH-3240] - * auth/okta: Standardize Okta configuration APIs across backends [GH-3245] - * cli: Add subcommand autocompletion that can be enabled with - `vault -autocomplete-install` [GH-3223] - * cli: Add ability to handle wrapped responses when using `vault auth`. What - is output depends on the other given flags; see the help output for that - command for more information. [GH-3263] - * core: TLS cipher suites used for cluster behavior can now be set via - `cluster_cipher_suites` in configuration [GH-3228] - * core: The `plugin_name` can now either be specified directly as part of the - parameter or within the `config` object when mounting a secret or auth backend - via `sys/mounts/:path` or `sys/auth/:path` respectively [GH-3202] - * core: It is now possible to update the `description` of a mount when - mount-tuning, although this must be done through the HTTP layer [GH-3285] - * secret/databases/mongo: If an EOF is encountered, attempt reconnecting and - retrying the operation [GH-3269] - * secret/pki: TTLs can now be specified as a string or an integer number of - seconds [GH-3270] - * secret/pki: Self-issued certs can now be signed via - `pki/root/sign-self-issued` [GH-3274] - * storage/gcp: Use application default credentials if they exist [GH-3248] - -BUG FIXES: - - * auth/aws: Properly use role-set period values for IAM-derived token renewals - [GH-3220] - * auth/okta: Fix updating organization/ttl/max_ttl after initial setting - [GH-3236] - * core: Fix PROXY when underlying connection is TLS [GH-3195] - * core: Policy-related commands would sometimes fail to act case-insensitively - [GH-3210] - * storage/consul: Fix parsing TLS configuration when using a bare IPv6 address - [GH-3268] - * plugins: Lazy-load plugins to prevent crash/deadlock during unseal process. - [GH-3255] - * plugins: Skip mounting plugin-based secret and credential mounts when setting - up mounts if the plugin is no longer present in the catalog. [GH-3255] - -## 0.8.1 (August 16th, 2017) - -DEPRECATIONS/CHANGES: - - * PKI Root Generation: Calling `pki/root/generate` when a CA cert/key already - exists will now return a `204` instead of overwriting an existing root. If - you want to recreate the root, first run a delete operation on `pki/root` - (requires `sudo` capability), then generate it again. - -FEATURES: - - * **Oracle Secret Backend**: There is now an external plugin to support leased - credentials for Oracle databases (distributed separately). - * **GCP IAM Auth Backend**: There is now an authentication backend that allows - using GCP IAM credentials to retrieve Vault tokens. This is available as - both a plugin and built-in to Vault. - * **PingID Push Support for Path-Based MFA (Enterprise)**: PingID Push can - now be used for MFA with the new path-based MFA introduced in Vault - Enterprise 0.8. - * **Permitted DNS Domains Support in PKI**: The `pki` backend now supports - specifying permitted DNS domains for CA certificates, allowing you to - narrowly scope the set of domains for which a CA can issue or sign child - certificates. - * **Plugin Backend Reload Endpoint**: Plugin backends can now be triggered to - reload using the `sys/plugins/reload/backend` endpoint and providing either - the plugin name or the mounts to reload. - * **Self-Reloading Plugins**: The plugin system will now attempt to reload a - crashed or stopped plugin, once per request. - -IMPROVEMENTS: - - * auth/approle: Allow array input for policies in addition to comma-delimited - strings [GH-3163] - * plugins: Send logs through Vault's logger rather than stdout [GH-3142] - * secret/pki: Add `pki/root` delete operation [GH-3165] - * secret/pki: Don't overwrite an existing root cert/key when calling generate - [GH-3165] - -BUG FIXES: - - * aws: Don't prefer a nil HTTP client over an existing one [GH-3159] - * core: If there is an error when checking for create/update existence, return - 500 instead of 400 [GH-3162] - * secret/database: Avoid creating usernames that are too long for legacy MySQL - [GH-3138] - -## 0.8.0 (August 9th, 2017) - -SECURITY: - - * We've added a note to the docs about the way the GitHub auth backend works - as it may not be readily apparent that GitHub personal access tokens, which - are used by the backend, can be used for unauthorized access if they are - stolen from third party services and access to Vault is public. - -DEPRECATIONS/CHANGES: - - * Database Plugin Backends: Passwords generated for these backends now - enforce stricter password requirements, as opposed to the previous behavior - of returning a randomized UUID. Passwords are of length 20, and have a `A1a-` - characters prepended to ensure stricter requirements. No regressions are - expected from this change. (For database backends that were previously - substituting underscores for hyphens in passwords, this will remain the - case.) - * Lease Endpoints: The endpoints `sys/renew`, `sys/revoke`, `sys/revoke-prefix`, - `sys/revoke-force` have been deprecated and relocated under `sys/leases`. - Additionally, the deprecated path `sys/revoke-force` now requires the `sudo` - capability. - * Response Wrapping Lookup Unauthenticated: The `sys/wrapping/lookup` endpoint - is now unauthenticated. This allows introspection of the wrapping info by - clients that only have the wrapping token without then invalidating the - token. Validation functions/checks are still performed on the token. - -FEATURES: - - * **Cassandra Storage**: Cassandra can now be used for Vault storage - * **CockroachDB Storage**: CockroachDB can now be used for Vault storage - * **CouchDB Storage**: CouchDB can now be used for Vault storage - * **SAP HANA Database Plugin**: The `databases` backend can now manage users - for SAP HANA databases - * **Plugin Backends**: Vault now supports running secret and auth backends as - plugins. Plugins can be mounted like normal backends and can be developed - independently from Vault. - * **PROXY Protocol Support** Vault listeners can now be configured to honor - PROXY protocol v1 information to allow passing real client IPs into Vault. A - list of authorized addresses (IPs or subnets) can be defined and - accept/reject behavior controlled. - * **Lease Lookup and Browsing in the Vault Enterprise UI**: Vault Enterprise UI - now supports lookup and listing of leases and the associated actions from the - `sys/leases` endpoints in the API. These are located in the new top level - navigation item "Leases". - * **Filtered Mounts for Performance Mode Replication**: Whitelists or - blacklists of mounts can be defined per-secondary to control which mounts - are actually replicated to that secondary. This can allow targeted - replication of specific sets of data to specific geolocations/datacenters. - * **Disaster Recovery Mode Replication (Enterprise Only)**: There is a new - replication mode, Disaster Recovery (DR), that performs full real-time - replication (including tokens and leases) to DR secondaries. DR secondaries - cannot handle client requests, but can be promoted to primary as needed for - failover. - * **Manage New Replication Features in the Vault Enterprise UI**: Support for - Replication features in Vault Enterprise UI has expanded to include new DR - Replication mode and management of Filtered Mounts in Performance Replication - mode. - * **Vault Identity (Enterprise Only)**: Vault's new Identity system allows - correlation of users across tokens. At present this is only used for MFA, - but will be the foundation of many other features going forward. - * **Duo Push, Okta Push, and TOTP MFA For All Authenticated Paths (Enterprise - Only)**: A brand new MFA system built on top of Identity allows MFA - (currently Duo Push, Okta Push, and TOTP) for any authenticated path within - Vault. MFA methods can be configured centrally, and TOTP keys live within - the user's Identity information to allow using the same key across tokens. - Specific MFA method(s) required for any given path within Vault can be - specified in normal ACL path statements. - -IMPROVEMENTS: - - * api: Add client method for a secret renewer background process [GH-2886] - * api: Add `RenewTokenAsSelf` [GH-2886] - * api: Client timeout can now be adjusted with the `VAULT_CLIENT_TIMEOUT` env - var or with a new API function [GH-2956] - * api/cli: Client will now attempt to look up SRV records for the given Vault - hostname [GH-3035] - * audit/socket: Enhance reconnection logic and don't require the connection to - be established at unseal time [GH-2934] - * audit/file: Opportunistically try re-opening the file on error [GH-2999] - * auth/approle: Add role name to token metadata [GH-2985] - * auth/okta: Allow specifying `ttl`/`max_ttl` inside the mount [GH-2915] - * cli: Client timeout can now be adjusted with the `VAULT_CLIENT_TIMEOUT` env - var [GH-2956] - * command/auth: Add `-token-only` flag to `vault auth` that returns only the - token on stdout and does not store it via the token helper [GH-2855] - * core: CORS allowed origins can now be configured [GH-2021] - * core: Add metrics counters for audit log failures [GH-2863] - * cors: Allow setting allowed headers via the API instead of always using - wildcard [GH-3023] - * secret/ssh: Allow specifying the key ID format using template values for CA - type [GH-2888] - * server: Add `tls_client_ca_file` option for specifying a CA file to use for - client certificate verification when `tls_require_and_verify_client_cert` is - enabled [GH-3034] - * storage/cockroachdb: Add CockroachDB storage backend [GH-2713] - * storage/couchdb: Add CouchDB storage backend [GH-2880] - * storage/mssql: Add `max_parallel` [GH-3026] - * storage/postgresql: Add `max_parallel` [GH-3026] - * storage/postgresql: Improve listing speed [GH-2945] - * storage/s3: More efficient paging when an object has a lot of subobjects - [GH-2780] - * sys/wrapping: Make `sys/wrapping/lookup` unauthenticated [GH-3084] - * sys/wrapping: Wrapped tokens now store the original request path of the data - [GH-3100] - * telemetry: Add support for DogStatsD [GH-2490] - -BUG FIXES: - - * api/health: Don't treat standby `429` codes as an error [GH-2850] - * api/leases: Fix lease lookup returning lease properties at the top level - * audit: Fix panic when audit logging a read operation on an asymmetric - `transit` key [GH-2958] - * auth/approle: Fix panic when secret and cidr list not provided in role - [GH-3075] - * auth/aws: Look up proper account ID on token renew [GH-3012] - * auth/aws: Store IAM header in all cases when it changes [GH-3004] - * auth/ldap: Verify given certificate is PEM encoded instead of failing - silently [GH-3016] - * auth/token: Don't allow using the same token ID twice when manually - specifying [GH-2916] - * cli: Fix issue with parsing keys that start with special characters [GH-2998] - * core: Relocated `sys/leases/renew` returns same payload as original - `sys/leases` endpoint [GH-2891] - * secret/ssh: Fix panic when signing with incorrect key type [GH-3072] - * secret/totp: Ensure codes can only be used once. This makes some automated - workflows harder but complies with the RFC. [GH-2908] - * secret/transit: Fix locking when creating a key with unsupported options - [GH-2974] - -## 0.7.3 (June 7th, 2017) - -SECURITY: - - * Cert auth backend now checks validity of individual certificates: In - previous versions of Vault, validity (e.g. expiration) of individual leaf - certificates added for authentication was not checked. This was done to make - it easier for administrators to control lifecycles of individual - certificates added to the backend, e.g. the authentication material being - checked was access to that specific certificate's private key rather than - all private keys signed by a CA. However, this behavior is often unexpected - and as a result can lead to insecure deployments, so we are now validating - these certificates as well. - * App-ID path salting was skipped in 0.7.1/0.7.2: A regression in 0.7.1/0.7.2 - caused the HMACing of any App-ID information stored in paths (including - actual app-IDs and user-IDs) to be unsalted and written as-is from the API. - In 0.7.3 any such paths will be automatically changed to salted versions on - access (e.g. login or read); however, if you created new app-IDs or user-IDs - in 0.7.1/0.7.2, you may want to consider whether any users with access to - Vault's underlying data store may have intercepted these values, and - revoke/roll them. - -DEPRECATIONS/CHANGES: - - * Step-Down is Forwarded: When a step-down is issued against a non-active node - in an HA cluster, it will now forward the request to the active node. - -FEATURES: - - * **ed25519 Signing/Verification in Transit with Key Derivation**: The - `transit` backend now supports generating - [ed25519](https://ed25519.cr.yp.to/) keys for signing and verification - functionality. These keys support derivation, allowing you to modify the - actual encryption key used by supplying a `context` value. - * **Key Version Specification for Encryption in Transit**: You can now specify - the version of a key you use to wish to generate a signature, ciphertext, or - HMAC. This can be controlled by the `min_encryption_version` key - configuration property. - * **Replication Primary Discovery (Enterprise)**: Replication primaries will - now advertise the addresses of their local HA cluster members to replication - secondaries. This helps recovery if the primary active node goes down and - neither service discovery nor load balancers are in use to steer clients. - -IMPROVEMENTS: - - * api/health: Add Sys().Health() [GH-2805] - * audit: Add auth information to requests that error out [GH-2754] - * command/auth: Add `-no-store` option that prevents the auth command from - storing the returned token into the configured token helper [GH-2809] - * core/forwarding: Request forwarding now heartbeats to prevent unused - connections from being terminated by firewalls or proxies - * plugins/databases: Add MongoDB as an internal database plugin [GH-2698] - * storage/dynamodb: Add a method for checking the existence of children, - speeding up deletion operations in the DynamoDB storage backend [GH-2722] - * storage/mysql: Add max_parallel parameter to MySQL backend [GH-2760] - * secret/databases: Support listing connections [GH-2823] - * secret/databases: Support custom renewal statements in Postgres database - plugin [GH-2788] - * secret/databases: Use the role name as part of generated credentials - [GH-2812] - * ui (Enterprise): Transit key and secret browsing UI handle large lists better - * ui (Enterprise): root tokens are no longer persisted - * ui (Enterprise): support for mounting Database and TOTP secret backends - -BUG FIXES: - - * auth/app-id: Fix regression causing loading of salts to be skipped - * auth/aws: Improve EC2 describe instances performance [GH-2766] - * auth/aws: Fix lookup of some instance profile ARNs [GH-2802] - * auth/aws: Resolve ARNs to internal AWS IDs which makes lookup at various - points (e.g. renewal time) more robust [GH-2814] - * auth/aws: Properly honor configured period when using IAM authentication - [GH-2825] - * auth/aws: Check that a bound IAM principal is not empty (in the current - state of the role) before requiring it match the previously authenticated - client [GH-2781] - * auth/cert: Fix panic on renewal [GH-2749] - * auth/cert: Certificate verification for non-CA certs [GH-2761] - * core/acl: Prevent race condition when compiling ACLs in some scenarios - [GH-2826] - * secret/database: Increase wrapping token TTL; in a loaded scenario it could - be too short - * secret/generic: Allow integers to be set as the value of `ttl` field as the - documentation claims is supported [GH-2699] - * secret/ssh: Added host key callback to ssh client config [GH-2752] - * storage/s3: Avoid a panic when some bad data is returned [GH-2785] - * storage/dynamodb: Fix list functions working improperly on Windows [GH-2789] - * storage/file: Don't leak file descriptors in some error cases - * storage/swift: Fix pre-v3 project/tenant name reading [GH-2803] - -## 0.7.2 (May 8th, 2017) - -BUG FIXES: - - * audit: Fix auditing entries containing certain kinds of time values - [GH-2689] - -## 0.7.1 (May 5th, 2017) - -DEPRECATIONS/CHANGES: - - * LDAP Auth Backend: Group membership queries will now run as the `binddn` - user when `binddn`/`bindpass` are configured, rather than as the - authenticating user as was the case previously. - -FEATURES: - - * **AWS IAM Authentication**: IAM principals can get Vault tokens - automatically, opening AWS-based authentication to users, ECS containers, - Lambda instances, and more. Signed client identity information retrieved - using the AWS API `sts:GetCallerIdentity` is validated against the AWS STS - service before issuing a Vault token. This backend is unified with the - `aws-ec2` authentication backend under the name `aws`, and allows additional - EC2-related restrictions to be applied during the IAM authentication; the - previous EC2 behavior is also still available. [GH-2441] - * **MSSQL Physical Backend**: You can now use Microsoft SQL Server as your - Vault physical data store [GH-2546] - * **Lease Listing and Lookup**: You can now introspect a lease to get its - creation and expiration properties via `sys/leases/lookup`; with `sudo` - capability you can also list leases for lookup, renewal, or revocation via - that endpoint. Various lease functions (renew, revoke, revoke-prefix, - revoke-force) have also been relocated to `sys/leases/`, but they also work - at the old paths for compatibility. Reading (but not listing) leases via - `sys/leases/lookup` is now a part of the current `default` policy. [GH-2650] - * **TOTP Secret Backend**: You can now store multi-factor authentication keys - in Vault and use the API to retrieve time-based one-time use passwords on - demand. The backend can also be used to generate a new key and validate - passwords generated by that key. [GH-2492] - * **Database Secret Backend & Secure Plugins (Beta)**: This new secret backend - combines the functionality of the MySQL, PostgreSQL, MSSQL, and Cassandra - backends. It also provides a plugin interface for extendability through - custom databases. [GH-2200] - -IMPROVEMENTS: - - * auth/cert: Support for constraints on subject Common Name and DNS/email - Subject Alternate Names in certificates [GH-2595] - * auth/ldap: Use the binding credentials to search group membership rather - than the user credentials [GH-2534] - * cli/revoke: Add `-self` option to allow revoking the currently active token - [GH-2596] - * core: Randomize x coordinate in Shamir shares [GH-2621] - * replication: Fix a bug when enabling `approle` on a primary before - secondaries were connected - * replication: Add heartbeating to ensure firewalls don't kill connections to - primaries - * secret/pki: Add `no_store` option that allows certificates to be issued - without being stored. This removes the ability to look up and/or add to a - CRL but helps with scaling to very large numbers of certificates. [GH-2565] - * secret/pki: If used with a role parameter, the `sign-verbatim/` - endpoint honors the values of `generate_lease`, `no_store`, `ttl` and - `max_ttl` from the given role [GH-2593] - * secret/pki: Add role parameter `allow_glob_domains` that enables defining - names in `allowed_domains` containing `*` glob patterns [GH-2517] - * secret/pki: Update certificate storage to not use characters that are not - supported on some filesystems [GH-2575] - * storage/etcd3: Add `discovery_srv` option to query for SRV records to find - servers [GH-2521] - * storage/s3: Support `max_parallel` option to limit concurrent outstanding - requests [GH-2466] - * storage/s3: Use pooled transport for http client [GH-2481] - * storage/swift: Allow domain values for V3 authentication [GH-2554] - * tidy: Improvements to `auth/token/tidy` and `sys/leases/tidy` to handle more - cleanup cases [GH-2452] - -BUG FIXES: - - * api: Respect a configured path in Vault's address [GH-2588] - * auth/aws-ec2: New bounds added as criteria to allow role creation [GH-2600] - * auth/ldap: Don't lowercase groups attached to users [GH-2613] - * cli: Don't panic if `vault write` is used with the `force` flag but no path - [GH-2674] - * core: Help operations should request forward since standbys may not have - appropriate info [GH-2677] - * replication: Fix enabling secondaries when certain mounts already existed on - the primary - * secret/mssql: Update mssql driver to support queries with colons [GH-2610] - * secret/pki: Don't lowercase O/OU values in certs [GH-2555] - * secret/pki: Don't attempt to validate IP SANs if none are provided [GH-2574] - * secret/ssh: Don't automatically lowercase principles in issued SSH certs - [GH-2591] - * storage/consul: Properly handle state events rather than timing out - [GH-2548] - * storage/etcd3: Ensure locks are released if client is improperly shut down - [GH-2526] - -## 0.7.0 (March 21th, 2017) - -SECURITY: - - * Common name not being validated when `exclude_cn_from_sans` option used in - `pki` backend: When using a role in the `pki` backend that specified the - `exclude_cn_from_sans` option, the common name would not then be properly - validated against the role's constraints. This has been fixed. We recommend - any users of this feature to upgrade to 0.7 as soon as feasible. - -DEPRECATIONS/CHANGES: - - * List Operations Always Use Trailing Slash: Any list operation, whether via - the `GET` or `LIST` HTTP verb, will now internally canonicalize the path to - have a trailing slash. This makes policy writing more predictable, as it - means clients will no longer work or fail based on which client they're - using or which HTTP verb they're using. However, it also means that policies - allowing `list` capability must be carefully checked to ensure that they - contain a trailing slash; some policies may need to be split into multiple - stanzas to accommodate. - * PKI Defaults to Unleased Certificates: When issuing certificates from the - PKI backend, by default, no leases will be issued. If you want to manually - revoke a certificate, its serial number can be used with the `pki/revoke` - endpoint. Issuing leases is still possible by enabling the `generate_lease` - toggle in PKI role entries (this will default to `true` for upgrades, to - keep existing behavior), which will allow using lease IDs to revoke - certificates. For installations issuing large numbers of certificates (tens - to hundreds of thousands, or millions), this will significantly improve - Vault startup time since leases associated with these certificates will not - have to be loaded; however note that it also means that revocation of a - token used to issue certificates will no longer add these certificates to a - CRL. If this behavior is desired or needed, consider keeping leases enabled - and ensuring lifetimes are reasonable, and issue long-lived certificates via - a different role with leases disabled. - -FEATURES: - - * **Replication (Enterprise)**: Vault Enterprise now has support for creating - a multi-datacenter replication set between clusters. The current replication - offering is based on an asynchronous primary/secondary (1:N) model that - replicates static data while keeping dynamic data (leases, tokens) - cluster-local, focusing on horizontal scaling for high-throughput and - high-fanout deployments. - * **Response Wrapping & Replication in the Vault Enterprise UI**: Vault - Enterprise UI now supports looking up and rotating response wrapping tokens, - as well as creating tokens with arbitrary values inside. It also now - supports replication functionality, enabling the configuration of a - replication set in the UI. - * **Expanded Access Control Policies**: Access control policies can now - specify allowed and denied parameters -- and, optionally, their values -- to - control what a client can and cannot submit during an API call. Policies can - also specify minimum/maximum response wrapping TTLs to both enforce the use - of response wrapping and control the duration of resultant wrapping tokens. - See the [policies concepts - page](https://www.vaultproject.io/docs/concepts/policies.html) for more - information. - * **SSH Backend As Certificate Authority**: The SSH backend can now be - configured to sign host and user certificates. Each mount of the backend - acts as an independent signing authority. The CA key pair can be configured - for each mount and the public key is accessible via an unauthenticated API - call; additionally, the backend can generate a public/private key pair for - you. We recommend using separate mounts for signing host and user - certificates. - -IMPROVEMENTS: - - * api/request: Passing username and password information in API request - [GH-2469] - * audit: Logging the token's use count with authentication response and - logging the remaining uses of the client token with request [GH-2437] - * auth/approle: Support for restricting the number of uses on the tokens - issued [GH-2435] - * auth/aws-ec2: AWS EC2 auth backend now supports constraints for VPC ID, - Subnet ID and Region [GH-2407] - * auth/ldap: Use the value of the `LOGNAME` or `USER` env vars for the - username if not explicitly set on the command line when authenticating - [GH-2154] - * audit: Support adding a configurable prefix (such as `@cee`) before each - line [GH-2359] - * core: Canonicalize list operations to use a trailing slash [GH-2390] - * core: Add option to disable caching on a per-mount level [GH-2455] - * core: Add ability to require valid client certs in listener config [GH-2457] - * physical/dynamodb: Implement a session timeout to avoid having to use - recovery mode in the case of an unclean shutdown, which makes HA much safer - [GH-2141] - * secret/pki: O (Organization) values can now be set to role-defined values - for issued/signed certificates [GH-2369] - * secret/pki: Certificates issued/signed from PKI backend do not generate - leases by default [GH-2403] - * secret/pki: When using DER format, still return the private key type - [GH-2405] - * secret/pki: Add an intermediate to the CA chain even if it lacks an - authority key ID [GH-2465] - * secret/pki: Add role option to use CSR SANs [GH-2489] - * secret/ssh: SSH backend as CA to sign user and host certificates [GH-2208] - * secret/ssh: Support reading of SSH CA public key from `config/ca` endpoint - and also return it when CA key pair is generated [GH-2483] - -BUG FIXES: - - * audit: When auditing headers use case-insensitive comparisons [GH-2362] - * auth/aws-ec2: Return role period in seconds and not nanoseconds [GH-2374] - * auth/okta: Fix panic if user had no local groups and/or policies set - [GH-2367] - * command/server: Fix parsing of redirect address when port is not mentioned - [GH-2354] - * physical/postgresql: Fix listing returning incorrect results if there were - multiple levels of children [GH-2393] - -## 0.6.5 (February 7th, 2017) - -FEATURES: - - * **Okta Authentication**: A new Okta authentication backend allows you to use - Okta usernames and passwords to authenticate to Vault. If provided with an - appropriate Okta API token, group membership can be queried to assign - policies; users and groups can be defined locally as well. - * **RADIUS Authentication**: A new RADIUS authentication backend allows using - a RADIUS server to authenticate to Vault. Policies can be configured for - specific users or for any authenticated user. - * **Exportable Transit Keys**: Keys in `transit` can now be marked as - `exportable` at creation time. This allows a properly ACL'd user to retrieve - the associated signing key, encryption key, or HMAC key. The `exportable` - value is returned on a key policy read and cannot be changed, so if a key is - marked `exportable` it will always be exportable, and if it is not it will - never be exportable. - * **Batch Transit Operations**: `encrypt`, `decrypt` and `rewrap` operations - in the transit backend now support processing multiple input items in one - call, returning the output of each item in the response. - * **Configurable Audited HTTP Headers**: You can now specify headers that you - want to have included in each audit entry, along with whether each header - should be HMAC'd or kept plaintext. This can be useful for adding additional - client or network metadata to the audit logs. - * **Transit Backend UI (Enterprise)**: Vault Enterprise UI now supports the transit - backend, allowing creation, viewing and editing of named keys as well as using - those keys to perform supported transit operations directly in the UI. - * **Socket Audit Backend** A new socket audit backend allows audit logs to be sent - through TCP, UDP, or UNIX Sockets. - -IMPROVEMENTS: - - * auth/aws-ec2: Add support for cross-account auth using STS [GH-2148] - * auth/aws-ec2: Support issuing periodic tokens [GH-2324] - * auth/github: Support listing teams and users [GH-2261] - * auth/ldap: Support adding policies to local users directly, in addition to - local groups [GH-2152] - * command/server: Add ability to select and prefer server cipher suites - [GH-2293] - * core: Add a nonce to unseal operations as a check (useful mostly for - support, not as a security principle) [GH-2276] - * duo: Added ability to supply extra context to Duo pushes [GH-2118] - * physical/consul: Add option for setting consistency mode on Consul gets - [GH-2282] - * physical/etcd: Full v3 API support; code will autodetect which API version - to use. The v3 code path is significantly less complicated and may be much - more stable. [GH-2168] - * secret/pki: Allow specifying OU entries in generated certificate subjects - [GH-2251] - * secret mount ui (Enterprise): the secret mount list now shows all mounted - backends even if the UI cannot browse them. Additional backends can now be - mounted from the UI as well. - -BUG FIXES: - - * auth/token: Fix regression in 0.6.4 where using token store roles as a - blacklist (with only `disallowed_policies` set) would not work in most - circumstances [GH-2286] - * physical/s3: Page responses in client so list doesn't truncate [GH-2224] - * secret/cassandra: Stop a connection leak that could occur on active node - failover [GH-2313] - * secret/pki: When using `sign-verbatim`, don't require a role and use the - CSR's common name [GH-2243] - -## 0.6.4 (December 16, 2016) - -SECURITY: - -Further details about these security issues can be found in the 0.6.4 upgrade -guide. - - * `default` Policy Privilege Escalation: If a parent token did not have the - `default` policy attached to its token, it could still create children with - the `default` policy. This is no longer allowed (unless the parent has - `sudo` capability for the creation path). In most cases this is low severity - since the access grants in the `default` policy are meant to be access - grants that are acceptable for all tokens to have. - * Leases Not Expired When Limited Use Token Runs Out of Uses: When using - limited-use tokens to create leased secrets, if the limited-use token was - revoked due to running out of uses (rather than due to TTL expiration or - explicit revocation) it would fail to revoke the leased secrets. These - secrets would still be revoked when their TTL expired, limiting the severity - of this issue. An endpoint has been added (`auth/token/tidy`) that can - perform housekeeping tasks on the token store; one of its tasks can detect - this situation and revoke the associated leases. - -FEATURES: - - * **Policy UI (Enterprise)**: Vault Enterprise UI now supports viewing, - creating, and editing policies. - -IMPROVEMENTS: - - * http: Vault now sets a `no-store` cache control header to make it more - secure in setups that are not end-to-end encrypted [GH-2183] - -BUG FIXES: - - * auth/ldap: Don't panic if dialing returns an error and starttls is enabled; - instead, return the error [GH-2188] - * ui (Enterprise): Submitting an unseal key now properly resets the - form so a browser refresh isn't required to continue. - -## 0.6.3 (December 6, 2016) - -DEPRECATIONS/CHANGES: - - * Request size limitation: A maximum request size of 32MB is imposed to - prevent a denial of service attack with arbitrarily large requests [GH-2108] - * LDAP denies passwordless binds by default: In new LDAP mounts, or when - existing LDAP mounts are rewritten, passwordless binds will be denied by - default. The new `deny_null_bind` parameter can be set to `false` to allow - these. [GH-2103] - * Any audit backend activated satisfies conditions: Previously, when a new - Vault node was taking over service in an HA cluster, all audit backends were - required to be loaded successfully to take over active duty. This behavior - now matches the behavior of the audit logging system itself: at least one - audit backend must successfully be loaded. The server log contains an error - when this occurs. This helps keep a Vault HA cluster working when there is a - misconfiguration on a standby node. [GH-2083] - -FEATURES: - - * **Web UI (Enterprise)**: Vault Enterprise now contains a built-in web UI - that offers access to a number of features, including init/unsealing/sealing, - authentication via userpass or LDAP, and K/V reading/writing. The capability - set of the UI will be expanding rapidly in further releases. To enable it, - set `ui = true` in the top level of Vault's configuration file and point a - web browser at your Vault address. - * **Google Cloud Storage Physical Backend**: You can now use GCS for storing - Vault data [GH-2099] - -IMPROVEMENTS: - - * auth/github: Policies can now be assigned to users as well as to teams - [GH-2079] - * cli: Set the number of retries on 500 down to 0 by default (no retrying). It - can be very confusing to users when there is a pause while the retries - happen if they haven't explicitly set it. With request forwarding the need - for this is lessened anyways. [GH-2093] - * core: Response wrapping is now allowed to be specified by backend responses - (requires backends gaining support) [GH-2088] - * physical/consul: When announcing service, use the scheme of the Vault server - rather than the Consul client [GH-2146] - * secret/consul: Added listing functionality to roles [GH-2065] - * secret/postgresql: Added `revocation_sql` parameter on the role endpoint to - enable customization of user revocation SQL statements [GH-2033] - * secret/transit: Add listing of keys [GH-1987] - -BUG FIXES: - - * api/unwrap, command/unwrap: Increase compatibility of `unwrap` command with - Vault 0.6.1 and older [GH-2014] - * api/unwrap, command/unwrap: Fix error when no client token exists [GH-2077] - * auth/approle: Creating the index for the role_id properly [GH-2004] - * auth/aws-ec2: Handle the case of multiple upgrade attempts when setting the - instance-profile ARN [GH-2035] - * auth/ldap: Avoid leaking connections on login [GH-2130] - * command/path-help: Use the actual error generated by Vault rather than - always using 500 when there is a path help error [GH-2153] - * command/ssh: Use temporary file for identity and ensure its deletion before - the command returns [GH-2016] - * cli: Fix error printing values with `-field` if the values contained - formatting directives [GH-2109] - * command/server: Don't say mlock is supported on OSX when it isn't. [GH-2120] - * core: Fix bug where a failure to come up as active node (e.g. if an audit - backend failed) could lead to deadlock [GH-2083] - * physical/mysql: Fix potential crash during setup due to a query failure - [GH-2105] - * secret/consul: Fix panic on user error [GH-2145] - -## 0.6.2 (October 5, 2016) - -DEPRECATIONS/CHANGES: - - * Convergent Encryption v2: New keys in `transit` using convergent mode will - use a new nonce derivation mechanism rather than require the user to supply - a nonce. While not explicitly increasing security, it minimizes the - likelihood that a user will use the mode improperly and impact the security - of their keys. Keys in convergent mode that were created in v0.6.1 will - continue to work with the same mechanism (user-supplied nonce). - * `etcd` HA off by default: Following in the footsteps of `dynamodb`, the - `etcd` storage backend now requires that `ha_enabled` be explicitly - specified in the configuration file. The backend currently has known broken - HA behavior, so this flag discourages use by default without explicitly - enabling it. If you are using this functionality, when upgrading, you should - set `ha_enabled` to `"true"` *before* starting the new versions of Vault. - * Default/Max lease/token TTLs are now 32 days: In previous versions of Vault - the default was 30 days, but moving it to 32 days allows some operations - (e.g. reauthenticating, renewing, etc.) to be performed via a monthly cron - job. - * AppRole Secret ID endpoints changed: Secret ID and Secret ID accessors are - no longer part of request URLs. The GET and DELETE operations are now moved - to new endpoints (`/lookup` and `/destroy`) which consumes the input from - the body and not the URL. - * AppRole requires at least one constraint: previously it was sufficient to - turn off all AppRole authentication constraints (secret ID, CIDR block) and - use the role ID only. It is now required that at least one additional - constraint is enabled. Existing roles are unaffected, but any new roles or - updated roles will require this. - * Reading wrapped responses from `cubbyhole/response` is deprecated. The - `sys/wrapping/unwrap` endpoint should be used instead as it provides - additional security, auditing, and other benefits. The ability to read - directly will be removed in a future release. - * Request Forwarding is now on by default: in 0.6.1 this required toggling on, - but is now enabled by default. This can be disabled via the - `"disable_clustering"` parameter in Vault's - [config](https://www.vaultproject.io/docs/config/index.html), or per-request - with the `X-Vault-No-Request-Forwarding` header. - * In prior versions a bug caused the `bound_iam_role_arn` value in the - `aws-ec2` authentication backend to actually use the instance profile ARN. - This has been corrected, but as a result there is a behavior change. To - match using the instance profile ARN, a new parameter - `bound_iam_instance_profile_arn` has been added. Existing roles will - automatically transfer the value over to the correct parameter, but the next - time the role is updated, the new meanings will take effect. - -FEATURES: - - * **Secret ID CIDR Restrictions in `AppRole`**: Secret IDs generated under an - approle can now specify a list of CIDR blocks from where the requests to - generate secret IDs should originate from. If an approle already has CIDR - restrictions specified, the CIDR restrictions on the secret ID should be a - subset of those specified on the role [GH-1910] - * **Initial Root Token PGP Encryption**: Similar to `generate-root`, the root - token created at initialization time can now be PGP encrypted [GH-1883] - * **Support Chained Intermediate CAs in `pki`**: The `pki` backend now allows, - when a CA cert is being supplied as a signed root or intermediate, a trust - chain of arbitrary length. The chain is returned as a parameter at - certificate issue/sign time and is retrievable independently as well. - [GH-1694] - * **Response Wrapping Enhancements**: There are new endpoints to look up - response wrapped token parameters; wrap arbitrary values; rotate wrapping - tokens; and unwrap with enhanced validation. In addition, list operations - can now be response-wrapped. [GH-1927] - * **Transit Features**: The `transit` backend now supports generating random - bytes and SHA sums; HMACs; and signing and verification functionality using - EC keys (P-256 curve) - -IMPROVEMENTS: - - * api: Return error when an invalid (as opposed to incorrect) unseal key is - submitted, rather than ignoring it [GH-1782] - * api: Add method to call `auth/token/create-orphan` endpoint [GH-1834] - * api: Rekey operation now redirects from standbys to master [GH-1862] - * audit/file: Sending a `SIGHUP` to Vault now causes Vault to close and - re-open the log file, making it easier to rotate audit logs [GH-1953] - * auth/aws-ec2: EC2 instances can get authenticated by presenting the identity - document and its SHA256 RSA digest [GH-1961] - * auth/aws-ec2: IAM bound parameters on the aws-ec2 backend will perform a - prefix match instead of exact match [GH-1943] - * auth/aws-ec2: Added a new constraint `bound_iam_instance_profile_arn` to - refer to IAM instance profile ARN and fixed the earlier `bound_iam_role_arn` - to refer to IAM role ARN instead of the instance profile ARN [GH-1913] - * auth/aws-ec2: Backend generates the nonce by default and clients can - explicitly disable reauthentication by setting empty nonce [GH-1889] - * auth/token: Added warnings if tokens and accessors are used in URLs [GH-1806] - * command/format: The `format` flag on select CLI commands takes `yml` as an - alias for `yaml` [GH-1899] - * core: Allow the size of the read cache to be set via the config file, and - change the default value to 1MB (from 32KB) [GH-1784] - * core: Allow single and two-character path parameters for most places - [GH-1811] - * core: Allow list operations to be response-wrapped [GH-1814] - * core: Provide better protection against timing attacks in Shamir code - [GH-1877] - * core: Unmounting/disabling backends no longer returns an error if the mount - didn't exist. This is line with elsewhere in Vault's API where `DELETE` is - an idempotent operation. [GH-1903] - * credential/approle: At least one constraint is required to be enabled while - creating and updating a role [GH-1882] - * secret/cassandra: Added consistency level for use with roles [GH-1931] - * secret/mysql: SQL for revoking user can be configured on the role [GH-1914] - * secret/transit: Use HKDF (RFC 5869) as the key derivation function for new - keys [GH-1812] - * secret/transit: Empty plaintext values are now allowed [GH-1874] - -BUG FIXES: - - * audit: Fix panic being caused by some values logging as underlying Go types - instead of formatted strings [GH-1912] - * auth/approle: Fixed panic on deleting approle that doesn't exist [GH-1920] - * auth/approle: Not letting secret IDs and secret ID accessors to get logged - in plaintext in audit logs [GH-1947] - * auth/aws-ec2: Allow authentication if the underlying host is in a bad state - but the instance is running [GH-1884] - * auth/token: Fixed metadata getting missed out from token lookup response by - gracefully handling token entry upgrade [GH-1924] - * cli: Don't error on newline in token file [GH-1774] - * core: Pass back content-type header for forwarded requests [GH-1791] - * core: Fix panic if the same key was given twice to `generate-root` [GH-1827] - * core: Fix potential deadlock on unmount/remount [GH-1793] - * physical/file: Remove empty directories from the `file` storage backend [GH-1821] - * physical/zookeeper: Remove empty directories from the `zookeeper` storage - backend and add a fix to the `file` storage backend's logic [GH-1964] - * secret/aws: Added update operation to `aws/sts` path to consider `ttl` - parameter [39b75c6] - * secret/aws: Mark STS secrets as non-renewable [GH-1804] - * secret/cassandra: Properly store session for re-use [GH-1802] - * secret/ssh: Fix panic when revoking SSH dynamic keys [GH-1781] - -## 0.6.1 (August 22, 2016) - -DEPRECATIONS/CHANGES: - - * Once the active node is 0.6.1, standby nodes must also be 0.6.1 in order to - connect to the HA cluster. We recommend following our [general upgrade - instructions](https://www.vaultproject.io/docs/install/upgrade.html) in - addition to 0.6.1-specific upgrade instructions to ensure that this is not - an issue. - * Status codes for sealed/uninitialized Vaults have changed to `503`/`501` - respectively. See the [version-specific upgrade - guide](https://www.vaultproject.io/docs/install/upgrade-to-0.6.1.html) for - more details. - * Root tokens (tokens with the `root` policy) can no longer be created except - by another root token or the `generate-root` endpoint. - * Issued certificates from the `pki` backend against new roles created or - modified after upgrading will contain a set of default key usages. - * The `dynamodb` physical data store no longer supports HA by default. It has - some non-ideal behavior around failover that was causing confusion. See the - [documentation](https://www.vaultproject.io/docs/config/index.html#ha_enabled) - for information on enabling HA mode. It is very important that this - configuration is added _before upgrading_. - * The `ldap` backend no longer searches for `memberOf` groups as part of its - normal flow. Instead, the desired group filter must be specified. This fixes - some errors and increases speed for directories with different structures, - but if this behavior has been relied upon, ensure that you see the upgrade - notes _before upgrading_. - * `app-id` is now deprecated with the addition of the new AppRole backend. - There are no plans to remove it, but we encourage using AppRole whenever - possible, as it offers enhanced functionality and can accommodate many more - types of authentication paradigms. - -FEATURES: - - * **AppRole Authentication Backend**: The `approle` backend is a - machine-oriented authentication backend that provides a similar concept to - App-ID while adding many missing features, including a pull model that - allows for the backend to generate authentication credentials rather than - requiring operators or other systems to push credentials in. It should be - useful in many more situations than App-ID. The inclusion of this backend - deprecates App-ID. [GH-1426] - * **Request Forwarding**: Vault servers can now forward requests to each other - rather than redirecting clients. This feature is off by default in 0.6.1 but - will be on by default in the next release. See the [HA concepts - page](https://www.vaultproject.io/docs/concepts/ha.html) for information on - enabling and configuring it. [GH-443] - * **Convergent Encryption in `Transit`**: The `transit` backend now supports a - convergent encryption mode where the same plaintext will produce the same - ciphertext. Although very useful in some situations, this has potential - security implications, which are mostly mitigated by requiring the use of - key derivation when convergent encryption is enabled. See [the `transit` - backend - documentation](https://www.vaultproject.io/docs/secrets/transit/index.html) - for more details. [GH-1537] - * **Improved LDAP Group Filters**: The `ldap` auth backend now uses templates - to define group filters, providing the capability to support some - directories that could not easily be supported before (especially specific - Active Directory setups with nested groups). [GH-1388] - * **Key Usage Control in `PKI`**: Issued certificates from roles created or - modified after upgrading contain a set of default key usages for increased - compatibility with OpenVPN and some other software. This set can be changed - when writing a role definition. Existing roles are unaffected. [GH-1552] - * **Request Retrying in the CLI and Go API**: Requests that fail with a `5xx` - error code will now retry after a backoff. The maximum total number of - retries (including disabling this functionality) can be set with an - environment variable. See the [environment variable - documentation](https://www.vaultproject.io/docs/commands/environment.html) - for more details. [GH-1594] - * **Service Discovery in `vault init`**: The new `-auto` option on `vault init` - will perform service discovery using Consul. When only one node is discovered, - it will be initialized and when more than one node is discovered, they will - be output for easy selection. See `vault init --help` for more details. [GH-1642] - * **MongoDB Secret Backend**: Generate dynamic unique MongoDB database - credentials based on configured roles. Sponsored by - [CommerceHub](http://www.commercehub.com/). [GH-1414] - * **Circonus Metrics Integration**: Vault can now send metrics to - [Circonus](http://www.circonus.com/). See the [configuration - documentation](https://www.vaultproject.io/docs/config/index.html) for - details. [GH-1646] - -IMPROVEMENTS: - - * audit: Added a unique identifier to each request which will also be found in - the request portion of the response. [GH-1650] - * auth/aws-ec2: Added a new constraint `bound_account_id` to the role - [GH-1523] - * auth/aws-ec2: Added a new constraint `bound_iam_role_arn` to the role - [GH-1522] - * auth/aws-ec2: Added `ttl` field for the role [GH-1703] - * auth/ldap, secret/cassandra, physical/consul: Clients with `tls.Config` - have the minimum TLS version set to 1.2 by default. This is configurable. - * auth/token: Added endpoint to list accessors [GH-1676] - * auth/token: Added `disallowed_policies` option to token store roles [GH-1681] - * auth/token: `root` or `sudo` tokens can now create periodic tokens via - `auth/token/create`; additionally, the same token can now be periodic and - have an explicit max TTL [GH-1725] - * build: Add support for building on Solaris/Illumos [GH-1726] - * cli: Output formatting in the presence of warnings in the response object - [GH-1533] - * cli: `vault auth` command supports a `-path` option to take in the path at - which the auth backend is enabled, thereby allowing authenticating against - different paths using the command options [GH-1532] - * cli: `vault auth -methods` will now display the config settings of the mount - [GH-1531] - * cli: `vault read/write/unwrap -field` now allows selecting token response - fields [GH-1567] - * cli: `vault write -field` now allows selecting wrapped response fields - [GH-1567] - * command/status: Version information and cluster details added to the output - of `vault status` command [GH-1671] - * core: Response wrapping is now enabled for login endpoints [GH-1588] - * core: The duration of leadership is now exported via events through - telemetry [GH-1625] - * core: `sys/capabilities-self` is now accessible as part of the `default` - policy [GH-1695] - * core: `sys/renew` is now accessible as part of the `default` policy [GH-1701] - * core: Unseal keys will now be returned in both hex and base64 forms, and - either can be used [GH-1734] - * core: Responses from most `/sys` endpoints now return normal `api.Secret` - structs in addition to the values they carried before. This means that - response wrapping can now be used with most authenticated `/sys` operations - [GH-1699] - * physical/etcd: Support `ETCD_ADDR` env var for specifying addresses [GH-1576] - * physical/consul: Allowing additional tags to be added to Consul service - registration via `service_tags` option [GH-1643] - * secret/aws: Listing of roles is supported now [GH-1546] - * secret/cassandra: Add `connect_timeout` value for Cassandra connection - configuration [GH-1581] - * secret/mssql,mysql,postgresql: Reading of connection settings is supported - in all the sql backends [GH-1515] - * secret/mysql: Added optional maximum idle connections value to MySQL - connection configuration [GH-1635] - * secret/mysql: Use a combination of the role name and token display name in - generated user names and allow the length to be controlled [GH-1604] - * secret/{cassandra,mssql,mysql,postgresql}: SQL statements can now be passed - in via one of four ways: a semicolon-delimited string, a base64-delimited - string, a serialized JSON string array, or a base64-encoded serialized JSON - string array [GH-1686] - * secret/ssh: Added `allowed_roles` to vault-ssh-helper's config and returning - role name as part of response of `verify` API - * secret/ssh: Added passthrough of command line arguments to `ssh` [GH-1680] - * sys/health: Added version information to the response of health status - endpoint [GH-1647] - * sys/health: Cluster information isbe returned as part of health status when - Vault is unsealed [GH-1671] - * sys/mounts: MountTable data is compressed before serializing to accommodate - thousands of mounts [GH-1693] - * website: The [token - concepts](https://www.vaultproject.io/docs/concepts/tokens.html) page has - been completely rewritten [GH-1725] - -BUG FIXES: - - * auth/aws-ec2: Added a nil check for stored whitelist identity object - during renewal [GH-1542] - * auth/cert: Fix panic if no client certificate is supplied [GH-1637] - * auth/token: Don't report that a non-expiring root token is renewable, as - attempting to renew it results in an error [GH-1692] - * cli: Don't retry a command when a redirection is received [GH-1724] - * core: Fix regression causing status codes to be `400` in most non-5xx error - cases [GH-1553] - * core: Fix panic that could occur during a leadership transition [GH-1627] - * physical/postgres: Remove use of prepared statements as this causes - connection multiplexing software to break [GH-1548] - * physical/consul: Multiple Vault nodes on the same machine leading to check ID - collisions were resulting in incorrect health check responses [GH-1628] - * physical/consul: Fix deregistration of health checks on exit [GH-1678] - * secret/postgresql: Check for existence of role before attempting deletion - [GH-1575] - * secret/postgresql: Handle revoking roles that have privileges on sequences - [GH-1573] - * secret/postgresql(,mysql,mssql): Fix incorrect use of database over - transaction object which could lead to connection exhaustion [GH-1572] - * secret/pki: Fix parsing CA bundle containing trailing whitespace [GH-1634] - * secret/pki: Fix adding email addresses as SANs [GH-1688] - * secret/pki: Ensure that CRL values are always UTC, per RFC [GH-1727] - * sys/seal-status: Fixed nil Cluster object while checking seal status [GH-1715] - -## 0.6.0 (June 14th, 2016) - -SECURITY: - - * Although `sys/revoke-prefix` was intended to revoke prefixes of secrets (via - lease IDs, which incorporate path information) and - `auth/token/revoke-prefix` was intended to revoke prefixes of tokens (using - the tokens' paths and, since 0.5.2, role information), in implementation - they both behaved exactly the same way since a single component in Vault is - responsible for managing lifetimes of both, and the type of the tracked - lifetime was not being checked. The end result was that either endpoint - could revoke both secret leases and tokens. We consider this a very minor - security issue as there are a number of mitigating factors: both endpoints - require `sudo` capability in addition to write capability, preventing - blanket ACL path globs from providing access; both work by using the prefix - to revoke as a part of the endpoint path, allowing them to be properly - ACL'd; and both are intended for emergency scenarios and users should - already not generally have access to either one. In order to prevent - confusion, we have simply removed `auth/token/revoke-prefix` in 0.6, and - `sys/revoke-prefix` will be meant for both leases and tokens instead. - -DEPRECATIONS/CHANGES: - - * `auth/token/revoke-prefix` has been removed. See the security notice for - details. [GH-1280] - * Vault will now automatically register itself as the `vault` service when - using the `consul` backend and will perform its own health checks. See - the Consul backend documentation for information on how to disable - auto-registration and service checks. - * List operations that do not find any keys now return a `404` status code - rather than an empty response object [GH-1365] - * CA certificates issued from the `pki` backend no longer have associated - leases, and any CA certs already issued will ignore revocation requests from - the lease manager. This is to prevent CA certificates from being revoked - when the token used to issue the certificate expires; it was not be obvious - to users that they need to ensure that the token lifetime needed to be at - least as long as a potentially very long-lived CA cert. - -FEATURES: - - * **AWS EC2 Auth Backend**: Provides a secure introduction mechanism for AWS - EC2 instances allowing automated retrieval of Vault tokens. Unlike most - Vault authentication backends, this backend does not require first deploying - or provisioning security-sensitive credentials (tokens, username/password, - client certificates, etc). Instead, it treats AWS as a Trusted Third Party - and uses the cryptographically signed dynamic metadata information that - uniquely represents each EC2 instance. [Vault - Enterprise](https://www.hashicorp.com/vault.html) customers have access to a - turnkey client that speaks the backend API and makes access to a Vault token - easy. - * **Response Wrapping**: Nearly any response within Vault can now be wrapped - inside a single-use, time-limited token's cubbyhole, taking the [Cubbyhole - Authentication - Principles](https://www.hashicorp.com/blog/vault-cubbyhole-principles.html) - mechanism to its logical conclusion. Retrieving the original response is as - simple as a single API command or the new `vault unwrap` command. This makes - secret distribution easier and more secure, including secure introduction. - * **Azure Physical Backend**: You can now use Azure blob object storage as - your Vault physical data store [GH-1266] - * **Swift Physical Backend**: You can now use Swift blob object storage as - your Vault physical data store [GH-1425] - * **Consul Backend Health Checks**: The Consul backend will automatically - register a `vault` service and perform its own health checking. By default - the active node can be found at `active.vault.service.consul` and all with - standby nodes are `standby.vault.service.consul`. Sealed vaults are marked - critical and are not listed by default in Consul's service discovery. See - the documentation for details. [GH-1349] - * **Explicit Maximum Token TTLs**: You can now set explicit maximum TTLs on - tokens that do not honor changes in the system- or mount-set values. This is - useful, for instance, when the max TTL of the system or the `auth/token` - mount must be set high to accommodate certain needs but you want more - granular restrictions on tokens being issued directly from the Token - authentication backend at `auth/token`. [GH-1399] - * **Non-Renewable Tokens**: When creating tokens directly through the token - authentication backend, you can now specify in both token store roles and - the API whether or not a token should be renewable, defaulting to `true`. - * **RabbitMQ Secret Backend**: Vault can now generate credentials for - RabbitMQ. Vhosts and tags can be defined within roles. [GH-788] - -IMPROVEMENTS: - - * audit: Add the DisplayName value to the copy of the Request object embedded - in the associated Response, to match the original Request object [GH-1387] - * audit: Enable auditing of the `seal` and `step-down` commands [GH-1435] - * backends: Remove most `root`/`sudo` paths in favor of normal ACL mechanisms. - A particular exception are any current MFA paths. A few paths in `token` and - `sys` also require `root` or `sudo`. [GH-1478] - * command/auth: Restore the previous authenticated token if the `auth` command - fails to authenticate the provided token [GH-1233] - * command/write: `-format` and `-field` can now be used with the `write` - command [GH-1228] - * core: Add `mlock` support for FreeBSD, OpenBSD, and Darwin [GH-1297] - * core: Don't keep lease timers around when tokens are revoked [GH-1277] - * core: If using the `disable_cache` option, caches for the policy store and - the `transit` backend are now disabled as well [GH-1346] - * credential/cert: Renewal requests are rejected if the set of policies has - changed since the token was issued [GH-477] - * credential/cert: Check CRLs for specific non-CA certs configured in the - backend [GH-1404] - * credential/ldap: If `groupdn` is not configured, skip searching LDAP and - only return policies for local groups, plus a warning [GH-1283] - * credential/ldap: `vault list` support for users and groups [GH-1270] - * credential/ldap: Support for the `memberOf` attribute for group membership - searching [GH-1245] - * credential/userpass: Add list support for users [GH-911] - * credential/userpass: Remove user configuration paths from requiring sudo, in - favor of normal ACL mechanisms [GH-1312] - * credential/token: Sanitize policies and add `default` policies in appropriate - places [GH-1235] - * credential/token: Setting the renewable status of a token is now possible - via `vault token-create` and the API. The default is true, but tokens can be - specified as non-renewable. [GH-1499] - * secret/aws: Use chain credentials to allow environment/EC2 instance/shared - providers [GH-307] - * secret/aws: Support for STS AssumeRole functionality [GH-1318] - * secret/consul: Reading consul access configuration supported. The response - will contain non-sensitive information only [GH-1445] - * secret/pki: Added `exclude_cn_from_sans` field to prevent adding the CN to - DNS or Email Subject Alternate Names [GH-1220] - * secret/pki: Added list support for certificates [GH-1466] - * sys/capabilities: Enforce ACL checks for requests that query the capabilities - of a token on a given path [GH-1221] - * sys/health: Status information can now be retrieved with `HEAD` [GH-1509] - -BUG FIXES: - - * command/read: Fix panic when using `-field` with a non-string value [GH-1308] - * command/token-lookup: Fix TTL showing as 0 depending on how a token was - created. This only affected the value shown at lookup, not the token - behavior itself. [GH-1306] - * command/various: Tell the JSON decoder to not convert all numbers to floats; - fixes some various places where numbers were showing up in scientific - notation - * command/server: Prioritized `devRootTokenID` and `devListenAddress` flags - over their respective env vars [GH-1480] - * command/ssh: Provided option to disable host key checking. The automated - variant of `vault ssh` command uses `sshpass` which was failing to handle - host key checking presented by the `ssh` binary. [GH-1473] - * core: Properly persist mount-tuned TTLs for auth backends [GH-1371] - * core: Don't accidentally crosswire SIGINT to the reload handler [GH-1372] - * credential/github: Make organization comparison case-insensitive during - login [GH-1359] - * credential/github: Fix panic when renewing a token created with some earlier - versions of Vault [GH-1510] - * credential/github: The token used to log in via `vault auth` can now be - specified in the `VAULT_AUTH_GITHUB_TOKEN` environment variable [GH-1511] - * credential/ldap: Fix problem where certain error conditions when configuring - or opening LDAP connections would cause a panic instead of return a useful - error message [GH-1262] - * credential/token: Fall back to normal parent-token semantics if - `allowed_policies` is empty for a role. Using `allowed_policies` of - `default` resulted in the same behavior anyways. [GH-1276] - * credential/token: Fix issues renewing tokens when using the "suffix" - capability of token roles [GH-1331] - * credential/token: Fix lookup via POST showing the request token instead of - the desired token [GH-1354] - * credential/various: Fix renewal conditions when `default` policy is not - contained in the backend config [GH-1256] - * physical/s3: Don't panic in certain error cases from bad S3 responses [GH-1353] - * secret/consul: Use non-pooled Consul API client to avoid leaving files open - [GH-1428] - * secret/pki: Don't check whether a certificate is destined to be a CA - certificate if sign-verbatim endpoint is used [GH-1250] - -## 0.5.3 (May 27th, 2016) - -SECURITY: - - * Consul ACL Token Revocation: An issue was reported to us indicating that - generated Consul ACL tokens were not being properly revoked. Upon - investigation, we found that this behavior was reproducible in a specific - scenario: when a generated lease for a Consul ACL token had been renewed - prior to revocation. In this case, the generated token was not being - properly persisted internally through the renewal function, leading to an - error during revocation due to the missing token. Unfortunately, this was - coded as a user error rather than an internal error, and the revocation - logic was expecting internal errors if revocation failed. As a result, the - revocation logic believed the revocation to have succeeded when it in fact - failed, causing the lease to be dropped while the token was still valid - within Consul. In this release, the Consul backend properly persists the - token through renewals, and the revocation logic has been changed to - consider any error type to have been a failure to revoke, causing the lease - to persist and attempt to be revoked later. - -We have written an example shell script that searches through Consul's ACL -tokens and looks for those generated by Vault, which can be used as a template -for a revocation script as deemed necessary for any particular security -response. The script is available at -https://gist.github.com/jefferai/6233c2963f9407a858d84f9c27d725c0 - -Please note that any outstanding leases for Consul tokens produced prior to -0.5.3 that have been renewed will continue to exhibit this behavior. As a -result, we recommend either revoking all tokens produced by the backend and -issuing new ones, or if needed, a more advanced variant of the provided example -could use the timestamp embedded in each generated token's name to decide which -tokens are too old and should be deleted. This could then be run periodically -up until the maximum lease time for any outstanding pre-0.5.3 tokens has -expired. - -This is a security-only release. There are no other code changes since 0.5.2. -The binaries have one additional change: they are built against Go 1.6.1 rather -than Go 1.6, as Go 1.6.1 contains two security fixes to the Go programming -language itself. - -## 0.5.2 (March 16th, 2016) - -FEATURES: - - * **MSSQL Backend**: Generate dynamic unique MSSQL database credentials based - on configured roles [GH-998] - * **Token Accessors**: Vault now provides an accessor with each issued token. - This accessor is an identifier that can be used for a limited set of - actions, notably for token revocation. This value can be logged in - plaintext to audit logs, and in combination with the plaintext metadata - logged to audit logs, provides a searchable and straightforward way to - revoke particular users' or services' tokens in many cases. To enable - plaintext audit logging of these accessors, set `hmac_accessor=false` when - enabling an audit backend. - * **Token Credential Backend Roles**: Roles can now be created in the `token` - credential backend that allow modifying token behavior in ways that are not - otherwise exposed or easily delegated. This allows creating tokens with a - fixed set (or subset) of policies (rather than a subset of the calling - token's), periodic tokens with a fixed TTL but no expiration, specified - prefixes, and orphans. - * **Listener Certificate Reloading**: Vault's configured listeners now reload - their TLS certificate and private key when the Vault process receives a - SIGHUP. - -IMPROVEMENTS: - - * auth/token: Endpoints optionally accept tokens from the HTTP body rather - than just from the URLs [GH-1211] - * auth/token,sys/capabilities: Added new endpoints - `auth/token/lookup-accessor`, `auth/token/revoke-accessor` and - `sys/capabilities-accessor`, which enables performing the respective actions - with just the accessor of the tokens, without having access to the actual - token [GH-1188] - * core: Ignore leading `/` in policy paths [GH-1170] - * core: Ignore leading `/` in mount paths [GH-1172] - * command/policy-write: Provided HCL is now validated for format violations - and provides helpful information around where the violation occurred - [GH-1200] - * command/server: The initial root token ID when running in `-dev` mode can - now be specified via `-dev-root-token-id` or the environment variable - `VAULT_DEV_ROOT_TOKEN_ID` [GH-1162] - * command/server: The listen address when running in `-dev` mode can now be - specified via `-dev-listen-address` or the environment variable - `VAULT_DEV_LISTEN_ADDRESS` [GH-1169] - * command/server: The configured listeners now reload their TLS - certificates/keys when Vault is SIGHUP'd [GH-1196] - * command/step-down: New `vault step-down` command and API endpoint to force - the targeted node to give up active status, but without sealing. The node - will wait ten seconds before attempting to grab the lock again. [GH-1146] - * command/token-renew: Allow no token to be passed in; use `renew-self` in - this case. Change the behavior for any token being passed in to use `renew`. - [GH-1150] - * credential/app-id: Allow `app-id` parameter to be given in the login path; - this causes the `app-id` to be part of the token path, making it easier to - use with `revoke-prefix` [GH-424] - * credential/cert: Non-CA certificates can be used for authentication. They - must be matched exactly (issuer and serial number) for authentication, and - the certificate must carry the client authentication or 'any' extended usage - attributes. [GH-1153] - * credential/cert: Subject and Authority key IDs are output in metadata; this - allows more flexible searching/revocation in the audit logs [GH-1183] - * credential/cert: Support listing configured certs [GH-1212] - * credential/userpass: Add support for `create`/`update` capability - distinction in user path, and add user-specific endpoints to allow changing - the password and policies [GH-1216] - * credential/token: Add roles [GH-1155] - * secret/mssql: Add MSSQL backend [GH-998] - * secret/pki: Add revocation time (zero or Unix epoch) to `pki/cert/SERIAL` - endpoint [GH-1180] - * secret/pki: Sanitize serial number in `pki/revoke` endpoint to allow some - other formats [GH-1187] - * secret/ssh: Added documentation for `ssh/config/zeroaddress` endpoint. - [GH-1154] - * sys: Added new endpoints `sys/capabilities` and `sys/capabilities-self` to - fetch the capabilities of a token on a given path [GH-1171] - * sys: Added `sys/revoke-force`, which enables a user to ignore backend errors - when revoking a lease, necessary in some emergency/failure scenarios - [GH-1168] - * sys: The return codes from `sys/health` can now be user-specified via query - parameters [GH-1199] - -BUG FIXES: - - * logical/cassandra: Apply hyphen/underscore replacement to the entire - generated username, not just the UUID, in order to handle token display name - hyphens [GH-1140] - * physical/etcd: Output actual error when cluster sync fails [GH-1141] - * vault/expiration: Not letting the error responses from the backends to skip - during renewals [GH-1176] - -## 0.5.1 (February 25th, 2016) - -DEPRECATIONS/CHANGES: - - * RSA keys less than 2048 bits are no longer supported in the PKI backend. - 1024-bit keys are considered unsafe and are disallowed in the Internet PKI. - The `pki` backend has enforced SHA256 hashes in signatures from the - beginning, and software that can handle these hashes should be able to - handle larger key sizes. [GH-1095] - * The PKI backend now does not automatically delete expired certificates, - including from the CRL. Doing so could lead to a situation where a time - mismatch between the Vault server and clients could result in a certificate - that would not be considered expired by a client being removed from the CRL. - The new `pki/tidy` endpoint can be used to trigger expirations. [GH-1129] - * The `cert` backend now performs a variant of channel binding at renewal time - for increased security. In order to not overly burden clients, a notion of - identity is used. This functionality can be disabled. See the 0.5.1 upgrade - guide for more specific information [GH-1127] - -FEATURES: - - * **Codebase Audit**: Vault's 0.5 codebase was audited by iSEC. (The terms of - the audit contract do not allow us to make the results public.) [GH-220] - -IMPROVEMENTS: - - * api: The `VAULT_TLS_SERVER_NAME` environment variable can be used to control - the SNI header during TLS connections [GH-1131] - * api/health: Add the server's time in UTC to health responses [GH-1117] - * command/rekey and command/generate-root: These now return the status at - attempt initialization time, rather than requiring a separate fetch for the - nonce [GH-1054] - * credential/cert: Don't require root/sudo tokens for the `certs/` and `crls/` - paths; use normal ACL behavior instead [GH-468] - * credential/github: The validity of the token used for login will be checked - at renewal time [GH-1047] - * credential/github: The `config` endpoint no longer requires a root token; - normal ACL path matching applies - * deps: Use the standardized Go 1.6 vendoring system - * secret/aws: Inform users of AWS-imposed policy restrictions around STS - tokens if they attempt to use an invalid policy [GH-1113] - * secret/mysql: The MySQL backend now allows disabling verification of the - `connection_url` [GH-1096] - * secret/pki: Submitted CSRs are now verified to have the correct key type and - minimum number of bits according to the role. The exception is intermediate - CA signing and the `sign-verbatim` path [GH-1104] - * secret/pki: New `tidy` endpoint to allow expunging expired certificates. - [GH-1129] - * secret/postgresql: The PostgreSQL backend now allows disabling verification - of the `connection_url` [GH-1096] - * secret/ssh: When verifying an OTP, return 400 if it is not valid instead of - 204 [GH-1086] - * credential/app-id: App ID backend will check the validity of app-id and user-id - during renewal time [GH-1039] - * credential/cert: TLS Certificates backend, during renewal, will now match the - client identity with the client identity used during login [GH-1127] - -BUG FIXES: - - * credential/ldap: Properly escape values being provided to search filters - [GH-1100] - * secret/aws: Capping on length of usernames for both IAM and STS types - [GH-1102] - * secret/pki: If a cert is not found during lookup of a serial number, - respond with a 400 rather than a 500 [GH-1085] - * secret/postgresql: Add extra revocation statements to better handle more - permission scenarios [GH-1053] - * secret/postgresql: Make connection_url work properly [GH-1112] - -## 0.5.0 (February 10, 2016) - -SECURITY: - - * Previous versions of Vault could allow a malicious user to hijack the rekey - operation by canceling an operation in progress and starting a new one. The - practical application of this is very small. If the user was an unseal key - owner, they could attempt to do this in order to either receive unencrypted - reseal keys or to replace the PGP keys used for encryption with ones under - their control. However, since this would invalidate any rekey progress, they - would need other unseal key holders to resubmit, which would be rather - suspicious during this manual operation if they were not also the original - initiator of the rekey attempt. If the user was not an unseal key holder, - there is no benefit to be gained; the only outcome that could be attempted - would be a denial of service against a legitimate rekey operation by sending - cancel requests over and over. Thanks to Josh Snyder for the report! - -DEPRECATIONS/CHANGES: - - * `s3` physical backend: Environment variables are now preferred over - configuration values. This makes it behave similar to the rest of Vault, - which, in increasing order of preference, uses values from the configuration - file, environment variables, and CLI flags. [GH-871] - * `etcd` physical backend: `sync` functionality is now supported and turned on - by default. This can be disabled. [GH-921] - * `transit`: If a client attempts to encrypt a value with a key that does not - yet exist, what happens now depends on the capabilities set in the client's - ACL policies. If the client has `create` (or `create` and `update`) - capability, the key will upsert as in the past. If the client has `update` - capability, they will receive an error. [GH-1012] - * `token-renew` CLI command: If the token given for renewal is the same as the - client token, the `renew-self` endpoint will be used in the API. Given that - the `default` policy (by default) allows all clients access to the - `renew-self` endpoint, this makes it much more likely that the intended - operation will be successful. [GH-894] - * Token `lookup`: the `ttl` value in the response now reflects the actual - remaining TTL rather than the original TTL specified when the token was - created; this value is now located in `creation_ttl` [GH-986] - * Vault no longer uses grace periods on leases or token TTLs. Uncertainty - about the length grace period for any given backend could cause confusion - and uncertainty. [GH-1002] - * `rekey`: Rekey now requires a nonce to be supplied with key shares. This - nonce is generated at the start of a rekey attempt and is unique for that - attempt. - * `status`: The exit code for the `status` CLI command is now `2` for an - uninitialized Vault instead of `1`. `1` is returned for errors. This better - matches the rest of the CLI. - -FEATURES: - - * **Split Data/High Availability Physical Backends**: You can now configure - two separate physical backends: one to be used for High Availability - coordination and another to be used for encrypted data storage. See the - [configuration - documentation](https://vaultproject.io/docs/config/index.html) for details. - [GH-395] - * **Fine-Grained Access Control**: Policies can now use the `capabilities` set - to specify fine-grained control over operations allowed on a path, including - separation of `sudo` privileges from other privileges. These can be mixed - and matched in any way desired. The `policy` value is kept for backwards - compatibility. See the [updated policy - documentation](https://vaultproject.io/docs/concepts/policies.html) for - details. [GH-914] - * **List Support**: Listing is now supported via the API and the new `vault - list` command. This currently supports listing keys in the `generic` and - `cubbyhole` backends and a few other places (noted in the IMPROVEMENTS - section below). Different parts of the API and backends will need to - implement list capabilities in ways that make sense to particular endpoints, - so further support will appear over time. [GH-617] - * **Root Token Generation via Unseal Keys**: You can now use the - `generate-root` CLI command to generate new orphaned, non-expiring root - tokens in case the original is lost or revoked (accidentally or - purposefully). This requires a quorum of unseal key holders. The output - value is protected via any PGP key of the initiator's choosing or a one-time - pad known only to the initiator (a suitable pad can be generated via the - `-genotp` flag to the command. [GH-915] - * **Unseal Key Archiving**: You can now optionally have Vault store your - unseal keys in your chosen physical store for disaster recovery purposes. - This option is only available when the keys are encrypted with PGP. [GH-907] - * **Keybase Support for PGP Encryption Keys**: You can now specify Keybase - users when passing in PGP keys to the `init`, `rekey`, and `generate-root` - CLI commands. Public keys for these users will be fetched automatically. - [GH-901] - * **DynamoDB HA Physical Backend**: There is now a new, community-supported - HA-enabled physical backend using Amazon DynamoDB. See the [configuration - documentation](https://vaultproject.io/docs/config/index.html) for details. - [GH-878] - * **PostgreSQL Physical Backend**: There is now a new, community-supported - physical backend using PostgreSQL. See the [configuration - documentation](https://vaultproject.io/docs/config/index.html) for details. - [GH-945] - * **STS Support in AWS Secret Backend**: You can now use the AWS secret - backend to fetch STS tokens rather than IAM users. [GH-927] - * **Speedups in the transit backend**: The `transit` backend has gained a - cache, and now loads only the working set of keys (e.g. from the - `min_decryption_version` to the current key version) into its working set. - This provides large speedups and potential memory savings when the `rotate` - feature of the backend is used heavily. - -IMPROVEMENTS: - - * cli: Output secrets sorted by key name [GH-830] - * cli: Support YAML as an output format [GH-832] - * cli: Show an error if the output format is incorrect, rather than falling - back to an empty table [GH-849] - * cli: Allow setting the `advertise_addr` for HA via the - `VAULT_ADVERTISE_ADDR` environment variable [GH-581] - * cli/generate-root: Add generate-root and associated functionality [GH-915] - * cli/init: Add `-check` flag that returns whether Vault is initialized - [GH-949] - * cli/server: Use internal functions for the token-helper rather than shelling - out, which fixes some problems with using a static binary in Docker or paths - with multiple spaces when launching in `-dev` mode [GH-850] - * cli/token-lookup: Add token-lookup command [GH-892] - * command/{init,rekey}: Allow ASCII-armored keychain files to be arguments for - `-pgp-keys` [GH-940] - * conf: Use normal bool values rather than empty/non-empty for the - `tls_disable` option [GH-802] - * credential/ldap: Add support for binding, both anonymously (to discover a - user DN) and via a username and password [GH-975] - * credential/token: Add `last_renewal_time` to token lookup calls [GH-896] - * credential/token: Change `ttl` to reflect the current remaining TTL; the - original value is in `creation_ttl` [GH-1007] - * helper/certutil: Add ability to parse PKCS#8 bundles [GH-829] - * logical/aws: You can now get STS tokens instead of IAM users [GH-927] - * logical/cassandra: Add `protocol_version` parameter to set the CQL proto - version [GH-1005] - * logical/cubbyhole: Add cubbyhole access to default policy [GH-936] - * logical/mysql: Add list support for roles path [GH-984] - * logical/pki: Fix up key usages being specified for CAs [GH-989] - * logical/pki: Add list support for roles path [GH-985] - * logical/pki: Allow `pem_bundle` to be specified as the format, which - provides a concatenated PEM bundle of returned values [GH-1008] - * logical/pki: Add 30 seconds of slack to the validity start period to - accommodate some clock skew in machines [GH-1036] - * logical/postgres: Add `max_idle_connections` parameter [GH-950] - * logical/postgres: Add list support for roles path - * logical/ssh: Add list support for roles path [GH-983] - * logical/transit: Keys are archived and only keys between the latest version - and `min_decryption_version` are loaded into the working set. This can - provide a very large speed increase when rotating keys very often. [GH-977] - * logical/transit: Keys are now cached, which should provide a large speedup - in most cases [GH-979] - * physical/cache: Use 2Q cache instead of straight LRU [GH-908] - * physical/etcd: Support basic auth [GH-859] - * physical/etcd: Support sync functionality and enable by default [GH-921] - -BUG FIXES: - - * api: Correct the HTTP verb used in the LookupSelf method [GH-887] - * api: Fix the output of `Sys().MountConfig(...)` to return proper values - [GH-1017] - * command/read: Fix panic when an empty argument was given [GH-923] - * command/ssh: Fix panic when username lookup fails [GH-886] - * core: When running in standalone mode, don't advertise that we are active - until post-unseal setup completes [GH-872] - * core: Update go-cleanhttp dependency to ensure idle connections aren't - leaked [GH-867] - * core: Don't allow tokens to have duplicate policies [GH-897] - * core: Fix regression in `sys/renew` that caused information stored in the - Secret part of the response to be lost [GH-912] - * physical: Use square brackets when setting an IPv6-based advertise address - as the auto-detected advertise address [GH-883] - * physical/s3: Use an initialized client when using IAM roles to fix a - regression introduced against newer versions of the AWS Go SDK [GH-836] - * secret/pki: Fix a condition where unmounting could fail if the CA - certificate was not properly loaded [GH-946] - * secret/ssh: Fix a problem where SSH connections were not always closed - properly [GH-942] - -MISC: - - * Clarified our stance on support for community-derived physical backends. - See the [configuration - documentation](https://vaultproject.io/docs/config/index.html) for details. - * Add `vault-java` to libraries [GH-851] - * Various minor documentation fixes and improvements [GH-839] [GH-854] - [GH-861] [GH-876] [GH-899] [GH-900] [GH-904] [GH-923] [GH-924] [GH-958] - [GH-959] [GH-981] [GH-990] [GH-1024] [GH-1025] - -BUILD NOTE: - - * The HashiCorp-provided binary release of Vault 0.5.0 is built against a - patched version of Go 1.5.3 containing two specific bug fixes affecting TLS - certificate handling. These fixes are in the Go 1.6 tree and were - cherry-picked on top of stock Go 1.5.3. If you want to examine the way in - which the releases were built, please look at our [cross-compilation - Dockerfile](https://github.com/hashicorp/vault/blob/v0.5.0/scripts/cross/Dockerfile-patched-1.5.3). - -## 0.4.1 (January 13, 2016) - -SECURITY: - - * Build against Go 1.5.3 to mitigate a security vulnerability introduced in - Go 1.5. For more information, please see - https://groups.google.com/forum/#!topic/golang-dev/MEATuOi_ei4 - -This is a security-only release; other than the version number and building -against Go 1.5.3, there are no changes from 0.4.0. - -## 0.4.0 (December 10, 2015) - -DEPRECATIONS/CHANGES: - - * Policy Name Casing: Policy names are now normalized to lower-case on write, - helping prevent accidental case mismatches. For backwards compatibility, - policy names are not currently normalized when reading or deleting. [GH-676] - * Default etcd port number: the default connection string for the `etcd` - physical store uses port 2379 instead of port 4001, which is the port used - by the supported version 2.x of etcd. [GH-753] - * As noted below in the FEATURES section, if your Vault installation contains - a policy called `default`, new tokens created will inherit this policy - automatically. - * In the PKI backend there have been a few minor breaking changes: - * The token display name is no longer a valid option for providing a base - domain for issuance. Since this name is prepended with the name of the - authentication backend that issued it, it provided a faulty use-case at best - and a confusing experience at worst. We hope to figure out a better - per-token value in a future release. - * The `allowed_base_domain` parameter has been changed to `allowed_domains`, - which accepts a comma-separated list of domains. This allows issuing - certificates with DNS subjects across multiple domains. If you had a - configured `allowed_base_domain` parameter, it will be migrated - automatically when the role is read (either via a normal read, or via - issuing a certificate). - -FEATURES: - - * **Significantly Enhanced PKI Backend**: The `pki` backend can now generate - and sign root CA certificates and intermediate CA CSRs. It can also now sign - submitted client CSRs, as well as a significant number of other - enhancements. See the updated documentation for the full API. [GH-666] - * **CRL Checking for Certificate Authentication**: The `cert` backend now - supports pushing CRLs into the mount and using the contained serial numbers - for revocation checking. See the documentation for the `cert` backend for - more info. [GH-330] - * **Default Policy**: Vault now ensures that a policy named `default` is added - to every token. This policy cannot be deleted, but it can be modified - (including to an empty policy). There are three endpoints allowed in the - default `default` policy, related to token self-management: `lookup-self`, - which allows a token to retrieve its own information, and `revoke-self` and - `renew-self`, which are self-explanatory. If your existing Vault - installation contains a policy called `default`, it will not be overridden, - but it will be added to each new token created. You can override this - behavior when using manual token creation (i.e. not via an authentication - backend) by setting the "no_default_policy" flag to true. [GH-732] - -IMPROVEMENTS: - - * api: API client now uses a 60 second timeout instead of indefinite [GH-681] - * api: Implement LookupSelf, RenewSelf, and RevokeSelf functions for auth - tokens [GH-739] - * api: Standardize environment variable reading logic inside the API; the CLI - now uses this but can still override via command-line parameters [GH-618] - * audit: HMAC-SHA256'd client tokens are now stored with each request entry. - Previously they were only displayed at creation time; this allows much - better traceability of client actions. [GH-713] - * audit: There is now a `sys/audit-hash` endpoint that can be used to generate - an HMAC-SHA256'd value from provided data using the given audit backend's - salt [GH-784] - * core: The physical storage read cache can now be disabled via - "disable_cache" [GH-674] - * core: The unsealing process can now be reset midway through (this feature - was documented before, but not enabled) [GH-695] - * core: Tokens can now renew themselves [GH-455] - * core: Base64-encoded PGP keys can be used with the CLI for `init` and - `rekey` operations [GH-653] - * core: Print version on startup [GH-765] - * core: Access to `sys/policy` and `sys/mounts` now uses the normal ACL system - instead of requiring a root token [GH-769] - * credential/token: Display whether or not a token is an orphan in the output - of a lookup call [GH-766] - * logical: Allow `.` in path-based variables in many more locations [GH-244] - * logical: Responses now contain a "warnings" key containing a list of - warnings returned from the server. These are conditions that did not require - failing an operation, but of which the client should be aware. [GH-676] - * physical/(consul,etcd): Consul and etcd now use a connection pool to limit - the number of outstanding operations, improving behavior when a lot of - operations must happen at once [GH-677] [GH-780] - * physical/consul: The `datacenter` parameter was removed; It could not be - effective unless the Vault node (or the Consul node it was connecting to) - was in the datacenter specified, in which case it wasn't needed [GH-816] - * physical/etcd: Support TLS-encrypted connections and use a connection pool - to limit the number of outstanding operations [GH-780] - * physical/s3: The S3 endpoint can now be configured, allowing using - S3-API-compatible storage solutions [GH-750] - * physical/s3: The S3 bucket can now be configured with the `AWS_S3_BUCKET` - environment variable [GH-758] - * secret/consul: Management tokens can now be created [GH-714] - -BUG FIXES: - - * api: API client now checks for a 301 response for redirects. Vault doesn't - generate these, but in certain conditions Go's internal HTTP handler can - generate them, leading to client errors. - * cli: `token-create` now supports the `ttl` parameter in addition to the - deprecated `lease` parameter. [GH-688] - * core: Return data from `generic` backends on the last use of a limited-use - token [GH-615] - * core: Fix upgrade path for leases created in `generic` prior to 0.3 [GH-673] - * core: Stale leader entries will now be reaped [GH-679] - * core: Using `mount-tune` on the auth/token path did not take effect. - [GH-688] - * core: Fix a potential race condition when (un)sealing the vault with metrics - enabled [GH-694] - * core: Fix an error that could happen in some failure scenarios where Vault - could fail to revert to a clean state [GH-733] - * core: Ensure secondary indexes are removed when a lease is expired [GH-749] - * core: Ensure rollback manager uses an up-to-date mounts table [GH-771] - * everywhere: Don't use http.DefaultClient, as it shares state implicitly and - is a source of hard-to-track-down bugs [GH-700] - * credential/token: Allow creating orphan tokens via an API path [GH-748] - * secret/generic: Validate given duration at write time, not just read time; - if stored durations are not parseable, return a warning and the default - duration rather than an error [GH-718] - * secret/generic: Return 400 instead of 500 when `generic` backend is written - to with no data fields [GH-825] - * secret/postgresql: Revoke permissions before dropping a user or revocation - may fail [GH-699] - -MISC: - - * Various documentation fixes and improvements [GH-685] [GH-688] [GH-697] - [GH-710] [GH-715] [GH-831] - -## 0.3.1 (October 6, 2015) - -SECURITY: - - * core: In certain failure scenarios, the full values of requests and - responses would be logged [GH-665] - -FEATURES: - - * **Settable Maximum Open Connections**: The `mysql` and `postgresql` backends - now allow setting the number of maximum open connections to the database, - which was previously capped to 2. [GH-661] - * **Renewable Tokens for GitHub**: The `github` backend now supports - specifying a TTL, enabling renewable tokens. [GH-664] - -BUG FIXES: - - * dist: linux-amd64 distribution was dynamically linked [GH-656] - * credential/github: Fix acceptance tests [GH-651] - -MISC: - - * Various minor documentation fixes and improvements [GH-649] [GH-650] - [GH-654] [GH-663] - -## 0.3.0 (September 28, 2015) - -DEPRECATIONS/CHANGES: - -Note: deprecations and breaking changes in upcoming releases are announced -ahead of time on the "vault-tool" mailing list. - - * **Cookie Authentication Removed**: As of 0.3 the only way to authenticate is - via the X-Vault-Token header. Cookie authentication was hard to properly - test, could result in browsers/tools/applications saving tokens in plaintext - on disk, and other issues. [GH-564] - * **Terminology/Field Names**: Vault is transitioning from overloading the - term "lease" to mean both "a set of metadata" and "the amount of time the - metadata is valid". The latter is now being referred to as TTL (or - "lease_duration" for backwards-compatibility); some parts of Vault have - already switched to using "ttl" and others will follow in upcoming releases. - In particular, the "token", "generic", and "pki" backends accept both "ttl" - and "lease" but in 0.4 only "ttl" will be accepted. [GH-528] - * **Downgrade Not Supported**: Due to enhancements in the storage subsystem, - values written by Vault 0.3+ will not be able to be read by prior versions - of Vault. There are no expected upgrade issues, however, as with all - critical infrastructure it is recommended to back up Vault's physical - storage before upgrading. - -FEATURES: - - * **SSH Backend**: Vault can now be used to delegate SSH access to machines, - via a (recommended) One-Time Password approach or by issuing dynamic keys. - [GH-385] - * **Cubbyhole Backend**: This backend works similarly to the "generic" backend - but provides a per-token workspace. This enables some additional - authentication workflows (especially for containers) and can be useful to - applications to e.g. store local credentials while being restarted or - upgraded, rather than persisting to disk. [GH-612] - * **Transit Backend Improvements**: The transit backend now allows key - rotation and datakey generation. For rotation, data encrypted with previous - versions of the keys can still be decrypted, down to a (configurable) - minimum previous version; there is a rewrap function for manual upgrades of - ciphertext to newer versions. Additionally, the backend now allows - generating and returning high-entropy keys of a configurable bitsize - suitable for AES and other functions; this is returned wrapped by a named - key, or optionally both wrapped and plaintext for immediate use. [GH-626] - * **Global and Per-Mount Default/Max TTL Support**: You can now set the - default and maximum Time To Live for leases both globally and per-mount. - Per-mount settings override global settings. Not all backends honor these - settings yet, but the maximum is a hard limit enforced outside the backend. - See the documentation for "/sys/mounts/" for details on configuring - per-mount TTLs. [GH-469] - * **PGP Encryption for Unseal Keys**: When initializing or rotating Vault's - master key, PGP/GPG public keys can now be provided. The output keys will be - encrypted with the given keys, in order. [GH-570] - * **Duo Multifactor Authentication Support**: Backends that support MFA can - now use Duo as the mechanism. [GH-464] - * **Performance Improvements**: Users of the "generic" backend will see a - significant performance improvement as the backend no longer creates leases, - although it does return TTLs (global/mount default, or set per-item) as - before. [GH-631] - * **Codebase Audit**: Vault's codebase was audited by iSEC. (The terms of the - audit contract do not allow us to make the results public.) [GH-220] - -IMPROVEMENTS: - - * audit: Log entries now contain a time field [GH-495] - * audit: Obfuscated audit entries now use hmac-sha256 instead of sha1 [GH-627] - * backends: Add ability for a cleanup function to be called on backend unmount - [GH-608] - * config: Allow specifying minimum acceptable TLS version [GH-447] - * core: If trying to mount in a location that is already mounted, be more - helpful about the error [GH-510] - * core: Be more explicit on failure if the issue is invalid JSON [GH-553] - * core: Tokens can now revoke themselves [GH-620] - * credential/app-id: Give a more specific error when sending a duplicate POST - to sys/auth/app-id [GH-392] - * credential/github: Support custom API endpoints (e.g. for Github Enterprise) - [GH-572] - * credential/ldap: Add per-user policies and option to login with - userPrincipalName [GH-420] - * credential/token: Allow root tokens to specify the ID of a token being - created from CLI [GH-502] - * credential/userpass: Enable renewals for login tokens [GH-623] - * scripts: Use /usr/bin/env to find Bash instead of hardcoding [GH-446] - * scripts: Use godep for build scripts to use same environment as tests - [GH-404] - * secret/mysql: Allow reading configuration data [GH-529] - * secret/pki: Split "allow_any_name" logic to that and "enforce_hostnames", to - allow for non-hostname values (e.g. for client certificates) [GH-555] - * storage/consul: Allow specifying certificates used to talk to Consul - [GH-384] - * storage/mysql: Allow SSL encrypted connections [GH-439] - * storage/s3: Allow using temporary security credentials [GH-433] - * telemetry: Put telemetry object in configuration to allow more flexibility - [GH-419] - * testing: Disable mlock for testing of logical backends so as not to require - root [GH-479] - -BUG FIXES: - - * audit/file: Do not enable auditing if file permissions are invalid [GH-550] - * backends: Allow hyphens in endpoint patterns (fixes AWS and others) [GH-559] - * cli: Fixed missing setup of client TLS certificates if no custom CA was - provided - * cli/read: Do not include a carriage return when using raw field output - [GH-624] - * core: Bad input data could lead to a panic for that session, rather than - returning an error [GH-503] - * core: Allow SHA2-384/SHA2-512 hashed certificates [GH-448] - * core: Do not return a Secret if there are no uses left on a token (since it - will be unable to be used) [GH-615] - * core: Code paths that called lookup-self would decrement num_uses and - potentially immediately revoke a token [GH-552] - * core: Some /sys/ paths would not properly redirect from a standby to the - leader [GH-499] [GH-551] - * credential/aws: Translate spaces in a token's display name to avoid making - IAM unhappy [GH-567] - * credential/github: Integration failed if more than ten organizations or - teams [GH-489] - * credential/token: Tokens with sudo access to "auth/token/create" can now use - root-only options [GH-629] - * secret/cassandra: Work around backwards-incompatible change made in - Cassandra 2.2 preventing Vault from properly setting/revoking leases - [GH-549] - * secret/mysql: Use varbinary instead of varchar to avoid InnoDB/UTF-8 issues - [GH-522] - * secret/postgres: Explicitly set timezone in connections [GH-597] - * storage/etcd: Renew semaphore periodically to prevent leadership flapping - [GH-606] - * storage/zk: Fix collisions in storage that could lead to data unavailability - [GH-411] - -MISC: - - * Various documentation fixes and improvements [GH-412] [GH-474] [GH-476] - [GH-482] [GH-483] [GH-486] [GH-508] [GH-568] [GH-574] [GH-586] [GH-590] - [GH-591] [GH-592] [GH-595] [GH-613] [GH-637] - * Less "armon" in stack traces [GH-453] - * Sourcegraph integration [GH-456] - -## 0.2.0 (July 13, 2015) - -FEATURES: - - * **Key Rotation Support**: The `rotate` command can be used to rotate the - master encryption key used to write data to the storage (physical) backend. - [GH-277] - * **Rekey Support**: Rekey can be used to rotate the master key and change the - configuration of the unseal keys (number of shares, threshold required). - [GH-277] - * **New secret backend: `pki`**: Enable Vault to be a certificate authority - and generate signed TLS certificates. [GH-310] - * **New secret backend: `cassandra`**: Generate dynamic credentials for - Cassandra [GH-363] - * **New storage backend: `etcd`**: store physical data in etcd [GH-259] - [GH-297] - * **New storage backend: `s3`**: store physical data in S3. Does not support - HA. [GH-242] - * **New storage backend: `MySQL`**: store physical data in MySQL. Does not - support HA. [GH-324] - * `transit` secret backend supports derived keys for per-transaction unique - keys [GH-399] - -IMPROVEMENTS: - - * cli/auth: Enable `cert` method [GH-380] - * cli/auth: read input from stdin [GH-250] - * cli/read: Ability to read a single field from a secret [GH-257] - * cli/write: Adding a force flag when no input required - * core: allow time duration format in place of seconds for some inputs - * core: audit log provides more useful information [GH-360] - * core: graceful shutdown for faster HA failover - * core: **change policy format** to use explicit globbing [GH-400] Any - existing policy in Vault is automatically upgraded to avoid issues. All - policy files must be updated for future writes. Adding the explicit glob - character `*` to the path specification is all that is required. - * core: policy merging to give deny highest precedence [GH-400] - * credential/app-id: Protect against timing attack on app-id - * credential/cert: Record the common name in the metadata [GH-342] - * credential/ldap: Allow TLS verification to be disabled [GH-372] - * credential/ldap: More flexible names allowed [GH-245] [GH-379] [GH-367] - * credential/userpass: Protect against timing attack on password - * credential/userpass: Use bcrypt for password matching - * http: response codes improved to reflect error [GH-366] - * http: the `sys/health` endpoint supports `?standbyok` to return 200 on - standby [GH-389] - * secret/app-id: Support deleting AppID and UserIDs [GH-200] - * secret/consul: Fine grained lease control [GH-261] - * secret/transit: Decouple raw key from key management endpoint [GH-355] - * secret/transit: Upsert named key when encrypt is used [GH-355] - * storage/zk: Support for HA configuration [GH-252] - * storage/zk: Changing node representation. **Backwards incompatible**. - [GH-416] - -BUG FIXES: - - * audit/file: file removing TLS connection state - * audit/syslog: fix removing TLS connection state - * command/*: commands accepting `k=v` allow blank values - * core: Allow building on FreeBSD [GH-365] - * core: Fixed various panics when audit logging enabled - * core: Lease renewal does not create redundant lease - * core: fixed leases with negative duration [GH-354] - * core: token renewal does not create child token - * core: fixing panic when lease increment is null [GH-408] - * credential/app-id: Salt the paths in storage backend to avoid information - leak - * credential/cert: Fixing client certificate not being requested - * credential/cert: Fixing panic when no certificate match found [GH-361] - * http: Accept PUT as POST for sys/auth - * http: Accept PUT as POST for sys/mounts [GH-349] - * http: Return 503 when sealed [GH-225] - * secret/postgres: Username length is capped to exceeding limit - * server: Do not panic if backend not configured [GH-222] - * server: Explicitly check value of tls_diable [GH-201] - * storage/zk: Fixed issues with version conflicts [GH-190] - -MISC: - - * cli/path-help: renamed from `help` to avoid confusion - -## 0.1.2 (May 11, 2015) - -FEATURES: - - * **New physical backend: `zookeeper`**: store physical data in Zookeeper. - HA not supported yet. - * **New credential backend: `ldap`**: authenticate using LDAP credentials. - -IMPROVEMENTS: - - * core: Auth backends can store internal data about auth creds - * audit: display name for auth is shown in logs [GH-176] - * command/*: `-insecure` has been renamed to `-tls-skip-verify` [GH-130] - * command/*: `VAULT_TOKEN` overrides local stored auth [GH-162] - * command/server: environment variables are copy-pastable - * credential/app-id: hash of app and user ID are in metadata [GH-176] - * http: HTTP API accepts `X-Vault-Token` as auth header [GH-124] - * logical/*: Generate help output even if no synopsis specified - -BUG FIXES: - - * core: login endpoints should never return secrets - * core: Internal data should never be returned from core endpoints - * core: defer barrier initialization to as late as possible to avoid error - cases during init that corrupt data (no data loss) - * core: guard against invalid init config earlier - * audit/file: create file if it doesn't exist [GH-148] - * command/*: ignore directories when traversing CA paths [GH-181] - * credential/*: all policy mapping keys are case insensitive [GH-163] - * physical/consul: Fixing path for locking so HA works in every case - -## 0.1.1 (May 2, 2015) - -SECURITY CHANGES: - - * physical/file: create the storge with 0600 permissions [GH-102] - * token/disk: write the token to disk with 0600 perms - -IMPROVEMENTS: - - * core: Very verbose error if mlock fails [GH-59] - * command/*: On error with TLS oversized record, show more human-friendly - error message. [GH-123] - * command/read: `lease_renewable` is now outputted along with the secret to - show whether it is renewable or not - * command/server: Add configuration option to disable mlock - * command/server: Disable mlock for dev mode so it works on more systems - -BUG FIXES: - - * core: if token helper isn't absolute, prepend with path to Vault - executable, not "vault" (which requires PATH) [GH-60] - * core: Any "mapping" routes allow hyphens in keys [GH-119] - * core: Validate `advertise_addr` is a valid URL with scheme [GH-106] - * command/auth: Using an invalid token won't crash [GH-75] - * credential/app-id: app and user IDs can have hyphens in keys [GH-119] - * helper/password: import proper DLL for Windows to ask password [GH-83] - -## 0.1.0 (April 28, 2015) - - * Initial release diff --git a/vendor/github.com/hashicorp/vault/CONTRIBUTING.md b/vendor/github.com/hashicorp/vault/CONTRIBUTING.md deleted file mode 100644 index 6fc1888bf..000000000 --- a/vendor/github.com/hashicorp/vault/CONTRIBUTING.md +++ /dev/null @@ -1,72 +0,0 @@ -# Contributing to Vault - -**Please note:** We take Vault's security and our users' trust very seriously. -If you believe you have found a security issue in Vault, please responsibly -disclose by contacting us at security@hashicorp.com. - -**First:** if you're unsure or afraid of _anything_, just ask or submit the -issue or pull request anyways. You won't be yelled at for giving it your best -effort. The worst that can happen is that you'll be politely asked to change -something. We appreciate any sort of contributions, and don't want a wall of -rules to get in the way of that. - -That said, if you want to ensure that a pull request is likely to be merged, -talk to us! You can find out our thoughts and ensure that your contribution -won't clash or be obviated by Vault's normal direction. A great way to do this -is via the [Vault Google Group][2]. Sometimes Vault devs are in `#vault-tool` -on Freenode, too. - -This document will cover what we're looking for in terms of reporting issues. -By addressing all the points we're looking for, it raises the chances we can -quickly merge or address your contributions. - -## Issues - -### Reporting an Issue - -* Make sure you test against the latest released version. It is possible - we already fixed the bug you're experiencing. Even better is if you can test - against `master`, as bugs are fixed regularly but new versions are only - released every few months. - -* Provide steps to reproduce the issue, and if possible include the expected - results as well as the actual results. Please provide text, not screen shots! - -* If you are seeing an internal Vault error (a status code of 5xx), please be - sure to post relevant parts of (or the entire) Vault log, as often these - errors are logged on the server but not reported to the user - -* If you experienced a panic, please create a [gist](https://gist.github.com) - of the *entire* generated crash log for us to look at. Double check - no sensitive items were in the log. - -* Respond as promptly as possible to any questions made by the Vault - team to your issue. Stale issues will be closed periodically. - -### Issue Lifecycle - -1. The issue is reported. - -2. The issue is verified and categorized by a Vault collaborator. - Categorization is done via tags. For example, bugs are marked as "bugs". - -3. Unless it is critical, the issue may be left for a period of time (sometimes - many weeks), giving outside contributors -- maybe you!? -- a chance to - address the issue. - -4. The issue is addressed in a pull request or commit. The issue will be - referenced in the commit message so that the code that fixes it is clearly - linked. - -5. The issue is closed. Sometimes, valid issues will be closed to keep - the issue tracker clean. The issue is still indexed and available for - future viewers, or can be re-opened if necessary. - -## Setting up Go to work on Vault - -If you have never worked with Go before, you will have to complete the -following steps listed in the README, under the section [Developing Vault][1]. - - -[1]: https://github.com/hashicorp/vault#developing-vault -[2]: https://groups.google.com/group/vault-tool diff --git a/vendor/github.com/hashicorp/vault/Makefile b/vendor/github.com/hashicorp/vault/Makefile deleted file mode 100644 index b755301af..000000000 --- a/vendor/github.com/hashicorp/vault/Makefile +++ /dev/null @@ -1,184 +0,0 @@ -# Determine this makefile's path. -# Be sure to place this BEFORE `include` directives, if any. -THIS_FILE := $(lastword $(MAKEFILE_LIST)) - -TEST?=$$(go list ./... | grep -v /vendor/ | grep -v /integ) -TEST_TIMEOUT?=20m -EXTENDED_TEST_TIMEOUT=45m -VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr -EXTERNAL_TOOLS=\ - github.com/elazarl/go-bindata-assetfs/... \ - github.com/hashicorp/go-bindata/... \ - github.com/mitchellh/gox \ - github.com/kardianos/govendor \ - github.com/client9/misspell/cmd/misspell -GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor) - -GO_VERSION_MIN=1.10 - -CGO_ENABLED=0 -ifneq ($(FDB_ENABLED), ) - CGO_ENABLED=1 - BUILD_TAGS+=foundationdb -endif - -default: dev - -# bin generates the releasable binaries for Vault -bin: prep - @CGO_ENABLED=$(CGO_ENABLED) BUILD_TAGS='$(BUILD_TAGS) ui' sh -c "'$(CURDIR)/scripts/build.sh'" - -# dev creates binaries for testing Vault locally. These are put -# into ./bin/ as well as $GOPATH/bin -dev: prep - @CGO_ENABLED=$(CGO_ENABLED) BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" -dev-ui: prep - @CGO_ENABLED=$(CGO_ENABLED) BUILD_TAGS='$(BUILD_TAGS) ui' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" -dev-dynamic: prep - @CGO_ENABLED=1 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'" - -testtravis: BUILD_TAGS+=travis -testtravis: test - -testracetravis: BUILD_TAGS+=travis -testracetravis: testrace - -# test runs the unit tests and vets the code -test: prep - @CGO_ENABLED=$(CGO_ENABLED) \ - VAULT_ADDR= \ - VAULT_TOKEN= \ - VAULT_DEV_ROOT_TOKEN_ID= \ - VAULT_ACC= \ - go test -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -timeout=$(TEST_TIMEOUT) -parallel=20 - -testcompile: prep - @for pkg in $(TEST) ; do \ - go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \ - done - -# testacc runs acceptance tests -testacc: prep - @if [ "$(TEST)" = "./..." ]; then \ - echo "ERROR: Set TEST to a specific package"; \ - exit 1; \ - fi - VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout=$(EXTENDED_TEST_TIMEOUT) - -# testrace runs the race checker -testrace: prep - @CGO_ENABLED=1 \ - VAULT_ADDR= \ - VAULT_TOKEN= \ - VAULT_DEV_ROOT_TOKEN_ID= \ - VAULT_ACC= \ - go test -tags='$(BUILD_TAGS)' -race $(TEST) $(TESTARGS) -timeout=$(EXTENDED_TEST_TIMEOUT) -parallel=20 - -cover: - ./scripts/coverage.sh --html - -# vet runs the Go source code static analysis tool `vet` to find -# any common errors. -vet: - @go list -f '{{.Dir}}' ./... | grep -v /vendor/ \ - | grep -v '.*github.com/hashicorp/vault$$' \ - | xargs go tool vet ; if [ $$? -eq 1 ]; then \ - echo ""; \ - echo "Vet found suspicious constructs. Please check the reported constructs"; \ - echo "and fix them if necessary before submitting the code for reviewal."; \ - fi - -# prep runs `go generate` to build the dynamically generated -# source files. -prep: fmtcheck - @sh -c "'$(CURDIR)/scripts/goversioncheck.sh' '$(GO_VERSION_MIN)'" - go generate $(go list ./... | grep -v /vendor/) - @if [ -d .git/hooks ]; then cp .hooks/* .git/hooks/; fi - -# bootstrap the build by downloading additional tools -bootstrap: - @for tool in $(EXTERNAL_TOOLS) ; do \ - echo "Installing/Updating $$tool" ; \ - go get -u $$tool; \ - done - -# Note: if you have plugins in GOPATH you can update all of them via something like: -# for i in $(ls | grep vault-plugin-); do cd $i; git remote update; git reset --hard origin/master; dep ensure -update; git add .; git commit; git push; cd ..; done -update-plugins: - grep vault-plugin- vendor/vendor.json | cut -d '"' -f 4 | xargs govendor fetch - -static-assets: - @echo "--> Generating static assets" - @go-bindata-assetfs -o bindata_assetfs.go -pkg http -prefix pkg -modtime 1480000000 -tags ui ./pkg/web_ui/... - @mv bindata_assetfs.go http - @$(MAKE) -f $(THIS_FILE) fmt - -test-ember: - @echo "--> Installing JavaScript assets" - @cd ui && yarn - @echo "--> Running ember tests" - @cd ui && yarn run test-oss - -ember-dist: - @echo "--> Installing JavaScript assets" - @cd ui && yarn - @cd ui && npm rebuild node-sass - @echo "--> Building Ember application" - @cd ui && yarn run build - @rm -rf ui/if-you-need-to-delete-this-open-an-issue-async-disk-cache - -ember-dist-dev: - @echo "--> Installing JavaScript assets" - @cd ui && yarn - @cd ui && npm rebuild node-sass - @echo "--> Building Ember application" - @cd ui && yarn run build-dev - -static-dist: ember-dist static-assets -static-dist-dev: ember-dist-dev static-assets - -proto: - protoc vault/*.proto --go_out=plugins=grpc:../../.. - protoc helper/storagepacker/types.proto --go_out=plugins=grpc:../../.. - protoc helper/forwarding/types.proto --go_out=plugins=grpc:../../.. - protoc logical/*.proto --go_out=plugins=grpc:../../.. - protoc physical/types.proto --go_out=plugins=grpc:../../.. - protoc helper/identity/types.proto --go_out=plugins=grpc:../../.. - protoc builtin/logical/database/dbplugin/*.proto --go_out=plugins=grpc:../../.. - protoc logical/plugin/pb/*.proto --go_out=plugins=grpc:../../.. - sed -i -e 's/Idp/IDP/' -e 's/Url/URL/' -e 's/Id/ID/' -e 's/EntityId/EntityID/' -e 's/Api/API/' -e 's/Qr/QR/' -e 's/protobuf:"/sentinel:"" protobuf:"/' helper/identity/types.pb.go helper/storagepacker/types.pb.go logical/plugin/pb/backend.pb.go - -fmtcheck: - @true -#@sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - -fmt: - @true -#gofmt -w $(GOFMT_FILES) - -spellcheck: - @echo "==> Spell checking website..." - @misspell -error -source=text website/source - -mysql-database-plugin: - @CGO_ENABLED=0 go build -o bin/mysql-database-plugin ./plugins/database/mysql/mysql-database-plugin - -mysql-legacy-database-plugin: - @CGO_ENABLED=0 go build -o bin/mysql-legacy-database-plugin ./plugins/database/mysql/mysql-legacy-database-plugin - -cassandra-database-plugin: - @CGO_ENABLED=0 go build -o bin/cassandra-database-plugin ./plugins/database/cassandra/cassandra-database-plugin - -postgresql-database-plugin: - @CGO_ENABLED=0 go build -o bin/postgresql-database-plugin ./plugins/database/postgresql/postgresql-database-plugin - -mssql-database-plugin: - @CGO_ENABLED=0 go build -o bin/mssql-database-plugin ./plugins/database/mssql/mssql-database-plugin - -hana-database-plugin: - @CGO_ENABLED=0 go build -o bin/hana-database-plugin ./plugins/database/hana/hana-database-plugin - -mongodb-database-plugin: - @CGO_ENABLED=0 go build -o bin/mongodb-database-plugin ./plugins/database/mongodb/mongodb-database-plugin - -.PHONY: bin default prep test vet bootstrap fmt fmtcheck mysql-database-plugin mysql-legacy-database-plugin cassandra-database-plugin postgresql-database-plugin mssql-database-plugin hana-database-plugin mongodb-database-plugin static-assets ember-dist ember-dist-dev static-dist static-dist-dev diff --git a/vendor/github.com/hashicorp/vault/README.md b/vendor/github.com/hashicorp/vault/README.md deleted file mode 100644 index c31624d59..000000000 --- a/vendor/github.com/hashicorp/vault/README.md +++ /dev/null @@ -1,134 +0,0 @@ -# Vault [![Build Status](https://travis-ci.org/hashicorp/vault.svg)](https://travis-ci.org/hashicorp/vault) [![Join the chat at https://gitter.im/hashicorp-vault/Lobby](https://badges.gitter.im/hashicorp-vault/Lobby.svg)](https://gitter.im/hashicorp-vault/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![vault enterprise](https://img.shields.io/badge/vault-enterprise-yellow.svg?colorB=7c8797&colorA=000000)](https://www.hashicorp.com/products/vault/?utm_source=github&utm_medium=banner&utm_campaign=github-vault-enterprise) - ----- - -**Please note**: We take Vault's security and our users' trust very seriously. If you believe you have found a security issue in Vault, _please responsibly disclose_ by contacting us at [security@hashicorp.com](mailto:security@hashicorp.com). - ----- - -- Website: https://www.vaultproject.io -- IRC: `#vault-tool` on Freenode -- Announcement list: [Google Groups](https://groups.google.com/group/hashicorp-announce) -- Discussion list: [Google Groups](https://groups.google.com/group/vault-tool) - -Vault Logo - -Vault is a tool for securely accessing secrets. A secret is anything that you want to tightly control access to, such as API keys, passwords, certificates, and more. Vault provides a unified interface to any secret, while providing tight access control and recording a detailed audit log. - -A modern system requires access to a multitude of secrets: database credentials, API keys for external services, credentials for service-oriented architecture communication, etc. Understanding who is accessing what secrets is already very difficult and platform-specific. Adding on key rolling, secure storage, and detailed audit logs is almost impossible without a custom solution. This is where Vault steps in. - -The key features of Vault are: - -* **Secure Secret Storage**: Arbitrary key/value secrets can be stored - in Vault. Vault encrypts these secrets prior to writing them to persistent - storage, so gaining access to the raw storage isn't enough to access - your secrets. Vault can write to disk, [Consul](https://www.consul.io), - and more. - -* **Dynamic Secrets**: Vault can generate secrets on-demand for some - systems, such as AWS or SQL databases. For example, when an application - needs to access an S3 bucket, it asks Vault for credentials, and Vault - will generate an AWS keypair with valid permissions on demand. After - creating these dynamic secrets, Vault will also automatically revoke them - after the lease is up. - -* **Data Encryption**: Vault can encrypt and decrypt data without storing - it. This allows security teams to define encryption parameters and - developers to store encrypted data in a location such as SQL without - having to design their own encryption methods. - -* **Leasing and Renewal**: All secrets in Vault have a _lease_ associated - with it. At the end of the lease, Vault will automatically revoke that - secret. Clients are able to renew leases via built-in renew APIs. - -* **Revocation**: Vault has built-in support for secret revocation. Vault - can revoke not only single secrets, but a tree of secrets, for example - all secrets read by a specific user, or all secrets of a particular type. - Revocation assists in key rolling as well as locking down systems in the - case of an intrusion. - -For more information, see the [introduction section](https://www.vaultproject.io/intro) -of the Vault website. - -Getting Started & Documentation -------------------------------- - -All documentation is available on the [Vault website](https://www.vaultproject.io). - -Developing Vault --------------------- - -If you wish to work on Vault itself or any of its built-in systems, you'll -first need [Go](https://www.golang.org) installed on your machine (version -1.10.1+ is *required*). - -For local dev first make sure Go is properly installed, including setting up a -[GOPATH](https://golang.org/doc/code.html#GOPATH). Next, clone this repository -into `$GOPATH/src/github.com/hashicorp/vault`. You can then download any -required build tools by bootstrapping your environment: - -```sh -$ make bootstrap -... -``` - -To compile a development version of Vault, run `make` or `make dev`. This will -put the Vault binary in the `bin` and `$GOPATH/bin` folders: - -```sh -$ make dev -... -$ bin/vault -... -``` - -To run tests, type `make test`. Note: this requires Docker to be installed. If -this exits with exit status 0, then everything is working! - -```sh -$ make test -... -``` - -If you're developing a specific package, you can run tests for just that -package by specifying the `TEST` variable. For example below, only -`vault` package tests will be run. - -```sh -$ make test TEST=./vault -... -``` - -### Acceptance Tests - -Vault has comprehensive [acceptance tests](https://en.wikipedia.org/wiki/Acceptance_testing) -covering most of the features of the secret and auth methods. - -If you're working on a feature of a secret or auth method and want to -verify it is functioning (and also hasn't broken anything else), we recommend -running the acceptance tests. - -**Warning:** The acceptance tests create/destroy/modify *real resources*, which -may incur real costs in some cases. In the presence of a bug, it is technically -possible that broken backends could leave dangling data behind. Therefore, -please run the acceptance tests at your own risk. At the very least, -we recommend running them in their own private account for whatever backend -you're testing. - -To run the acceptance tests, invoke `make testacc`: - -```sh -$ make testacc TEST=./builtin/logical/consul -... -``` - -The `TEST` variable is required, and you should specify the folder where the -backend is. The `TESTARGS` variable is recommended to filter down to a specific -resource to test, since testing all of them at once can sometimes take a very -long time. - -Acceptance tests typically require other environment variables to be set for -things such as access keys. The test itself should error early and tell -you what to set, so it is not documented here. - -For more information on Vault Enterprise features, visit the [Vault Enterprise site](https://www.hashicorp.com/products/vault/?utm_source=github&utm_medium=referral&utm_campaign=github-vault-enterprise). diff --git a/vendor/github.com/hashicorp/vault/audit/audit.go b/vendor/github.com/hashicorp/vault/audit/audit.go deleted file mode 100644 index fed703350..000000000 --- a/vendor/github.com/hashicorp/vault/audit/audit.go +++ /dev/null @@ -1,63 +0,0 @@ -package audit - -import ( - "context" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -// Backend interface must be implemented for an audit -// mechanism to be made available. Audit backends can be enabled to -// sink information to different backends such as logs, file, databases, -// or other external services. -type Backend interface { - // LogRequest is used to synchronously log a request. This is done after the - // request is authorized but before the request is executed. The arguments - // MUST not be modified in anyway. They should be deep copied if this is - // a possibility. - LogRequest(context.Context, *LogInput) error - - // LogResponse is used to synchronously log a response. This is done after - // the request is processed but before the response is sent. The arguments - // MUST not be modified in anyway. They should be deep copied if this is - // a possibility. - LogResponse(context.Context, *LogInput) error - - // GetHash is used to return the given data with the backend's hash, - // so that a caller can determine if a value in the audit log matches - // an expected plaintext value - GetHash(context.Context, string) (string, error) - - // Reload is called on SIGHUP for supporting backends. - Reload(context.Context) error - - // Invalidate is called for path invalidation - Invalidate(context.Context) -} - -// LogInput contains the input parameters passed into LogRequest and LogResponse -type LogInput struct { - Auth *logical.Auth - Request *logical.Request - Response *logical.Response - OuterErr error - NonHMACReqDataKeys []string - NonHMACRespDataKeys []string -} - -// BackendConfig contains configuration parameters used in the factory func to -// instantiate audit backends -type BackendConfig struct { - // The view to store the salt - SaltView logical.Storage - - // The salt config that should be used for any secret obfuscation - SaltConfig *salt.Config - - // Config is the opaque user configuration provided when mounting - Config map[string]string -} - -// Factory is the factory function to create an audit backend. -type Factory func(context.Context, *BackendConfig) (Backend, error) diff --git a/vendor/github.com/hashicorp/vault/audit/format.go b/vendor/github.com/hashicorp/vault/audit/format.go deleted file mode 100644 index 55970ec36..000000000 --- a/vendor/github.com/hashicorp/vault/audit/format.go +++ /dev/null @@ -1,454 +0,0 @@ -package audit - -import ( - "context" - "fmt" - "io" - "strings" - "time" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -type AuditFormatWriter interface { - WriteRequest(io.Writer, *AuditRequestEntry) error - WriteResponse(io.Writer, *AuditResponseEntry) error - Salt(context.Context) (*salt.Salt, error) -} - -// AuditFormatter implements the Formatter interface, and allows the underlying -// marshaller to be swapped out -type AuditFormatter struct { - AuditFormatWriter -} - -var _ Formatter = (*AuditFormatter)(nil) - -func (f *AuditFormatter) FormatRequest(ctx context.Context, w io.Writer, config FormatterConfig, in *LogInput) error { - if in == nil || in.Request == nil { - return fmt.Errorf("request to request-audit a nil request") - } - - if w == nil { - return fmt.Errorf("writer for audit request is nil") - } - - if f.AuditFormatWriter == nil { - return fmt.Errorf("no format writer specified") - } - - salt, err := f.Salt(ctx) - if err != nil { - return errwrap.Wrapf("error fetching salt: {{err}}", err) - } - - // Set these to the input values at first - auth := in.Auth - req := in.Request - - if !config.Raw { - // Before we copy the structure we must nil out some data - // otherwise we will cause reflection to panic and die - if in.Request.Connection != nil && in.Request.Connection.ConnState != nil { - origState := in.Request.Connection.ConnState - in.Request.Connection.ConnState = nil - defer func() { - in.Request.Connection.ConnState = origState - }() - } - - // Copy the auth structure - if in.Auth != nil { - cp, err := copystructure.Copy(in.Auth) - if err != nil { - return err - } - auth = cp.(*logical.Auth) - } - - cp, err := copystructure.Copy(in.Request) - if err != nil { - return err - } - req = cp.(*logical.Request) - - // Hash any sensitive information - if auth != nil { - // Cache and restore accessor in the auth - var authAccessor string - if !config.HMACAccessor && auth.Accessor != "" { - authAccessor = auth.Accessor - } - if err := Hash(salt, auth, nil); err != nil { - return err - } - if authAccessor != "" { - auth.Accessor = authAccessor - } - } - - // Cache and restore accessor in the request - var clientTokenAccessor string - if !config.HMACAccessor && req != nil && req.ClientTokenAccessor != "" { - clientTokenAccessor = req.ClientTokenAccessor - } - if err := Hash(salt, req, in.NonHMACReqDataKeys); err != nil { - return err - } - if clientTokenAccessor != "" { - req.ClientTokenAccessor = clientTokenAccessor - } - } - - // If auth is nil, make an empty one - if auth == nil { - auth = new(logical.Auth) - } - var errString string - if in.OuterErr != nil { - errString = in.OuterErr.Error() - } - - reqEntry := &AuditRequestEntry{ - Type: "request", - Error: errString, - - Auth: AuditAuth{ - ClientToken: auth.ClientToken, - Accessor: auth.Accessor, - DisplayName: auth.DisplayName, - Policies: auth.Policies, - TokenPolicies: auth.TokenPolicies, - IdentityPolicies: auth.IdentityPolicies, - Metadata: auth.Metadata, - EntityID: auth.EntityID, - RemainingUses: req.ClientTokenRemainingUses, - }, - - Request: AuditRequest{ - ID: req.ID, - ClientToken: req.ClientToken, - ClientTokenAccessor: req.ClientTokenAccessor, - Operation: req.Operation, - Path: req.Path, - Data: req.Data, - PolicyOverride: req.PolicyOverride, - RemoteAddr: getRemoteAddr(req), - ReplicationCluster: req.ReplicationCluster, - Headers: req.Headers, - }, - } - - if req.WrapInfo != nil { - reqEntry.Request.WrapTTL = int(req.WrapInfo.TTL / time.Second) - } - - if !config.OmitTime { - reqEntry.Time = time.Now().UTC().Format(time.RFC3339Nano) - } - - return f.AuditFormatWriter.WriteRequest(w, reqEntry) -} - -func (f *AuditFormatter) FormatResponse(ctx context.Context, w io.Writer, config FormatterConfig, in *LogInput) error { - if in == nil || in.Request == nil { - return fmt.Errorf("request to response-audit a nil request") - } - - if w == nil { - return fmt.Errorf("writer for audit request is nil") - } - - if f.AuditFormatWriter == nil { - return fmt.Errorf("no format writer specified") - } - - salt, err := f.Salt(ctx) - if err != nil { - return errwrap.Wrapf("error fetching salt: {{err}}", err) - } - - // Set these to the input values at first - auth := in.Auth - req := in.Request - resp := in.Response - - if !config.Raw { - // Before we copy the structure we must nil out some data - // otherwise we will cause reflection to panic and die - if in.Request.Connection != nil && in.Request.Connection.ConnState != nil { - origState := in.Request.Connection.ConnState - in.Request.Connection.ConnState = nil - defer func() { - in.Request.Connection.ConnState = origState - }() - } - - // Copy the auth structure - if in.Auth != nil { - cp, err := copystructure.Copy(in.Auth) - if err != nil { - return err - } - auth = cp.(*logical.Auth) - } - - cp, err := copystructure.Copy(in.Request) - if err != nil { - return err - } - req = cp.(*logical.Request) - - if in.Response != nil { - cp, err := copystructure.Copy(in.Response) - if err != nil { - return err - } - resp = cp.(*logical.Response) - } - - // Hash any sensitive information - - // Cache and restore accessor in the auth - if auth != nil { - var accessor string - if !config.HMACAccessor && auth.Accessor != "" { - accessor = auth.Accessor - } - if err := Hash(salt, auth, nil); err != nil { - return err - } - if accessor != "" { - auth.Accessor = accessor - } - } - - // Cache and restore accessor in the request - var clientTokenAccessor string - if !config.HMACAccessor && req != nil && req.ClientTokenAccessor != "" { - clientTokenAccessor = req.ClientTokenAccessor - } - if err := Hash(salt, req, in.NonHMACReqDataKeys); err != nil { - return err - } - if clientTokenAccessor != "" { - req.ClientTokenAccessor = clientTokenAccessor - } - - // Cache and restore accessor in the response - if resp != nil { - var accessor, wrappedAccessor, wrappingAccessor string - if !config.HMACAccessor && resp != nil && resp.Auth != nil && resp.Auth.Accessor != "" { - accessor = resp.Auth.Accessor - } - if !config.HMACAccessor && resp != nil && resp.WrapInfo != nil && resp.WrapInfo.WrappedAccessor != "" { - wrappedAccessor = resp.WrapInfo.WrappedAccessor - wrappingAccessor = resp.WrapInfo.Accessor - } - if err := Hash(salt, resp, in.NonHMACRespDataKeys); err != nil { - return err - } - if accessor != "" { - resp.Auth.Accessor = accessor - } - if wrappedAccessor != "" { - resp.WrapInfo.WrappedAccessor = wrappedAccessor - } - if wrappingAccessor != "" { - resp.WrapInfo.Accessor = wrappingAccessor - } - } - } - - // If things are nil, make empty to avoid panics - if auth == nil { - auth = new(logical.Auth) - } - if resp == nil { - resp = new(logical.Response) - } - var errString string - if in.OuterErr != nil { - errString = in.OuterErr.Error() - } - - var respAuth *AuditAuth - if resp.Auth != nil { - respAuth = &AuditAuth{ - ClientToken: resp.Auth.ClientToken, - Accessor: resp.Auth.Accessor, - DisplayName: resp.Auth.DisplayName, - Policies: resp.Auth.Policies, - TokenPolicies: resp.Auth.TokenPolicies, - IdentityPolicies: resp.Auth.IdentityPolicies, - Metadata: resp.Auth.Metadata, - NumUses: resp.Auth.NumUses, - } - } - - var respSecret *AuditSecret - if resp.Secret != nil { - respSecret = &AuditSecret{ - LeaseID: resp.Secret.LeaseID, - } - } - - var respWrapInfo *AuditResponseWrapInfo - if resp.WrapInfo != nil { - token := resp.WrapInfo.Token - if jwtToken := parseVaultTokenFromJWT(token); jwtToken != nil { - token = *jwtToken - } - respWrapInfo = &AuditResponseWrapInfo{ - TTL: int(resp.WrapInfo.TTL / time.Second), - Token: token, - Accessor: resp.WrapInfo.Accessor, - CreationTime: resp.WrapInfo.CreationTime.UTC().Format(time.RFC3339Nano), - CreationPath: resp.WrapInfo.CreationPath, - WrappedAccessor: resp.WrapInfo.WrappedAccessor, - } - } - - respEntry := &AuditResponseEntry{ - Type: "response", - Error: errString, - Auth: AuditAuth{ - DisplayName: auth.DisplayName, - Policies: auth.Policies, - TokenPolicies: auth.TokenPolicies, - IdentityPolicies: auth.IdentityPolicies, - Metadata: auth.Metadata, - ClientToken: auth.ClientToken, - Accessor: auth.Accessor, - RemainingUses: req.ClientTokenRemainingUses, - EntityID: auth.EntityID, - }, - - Request: AuditRequest{ - ID: req.ID, - ClientToken: req.ClientToken, - ClientTokenAccessor: req.ClientTokenAccessor, - Operation: req.Operation, - Path: req.Path, - Data: req.Data, - PolicyOverride: req.PolicyOverride, - RemoteAddr: getRemoteAddr(req), - ReplicationCluster: req.ReplicationCluster, - Headers: req.Headers, - }, - - Response: AuditResponse{ - Auth: respAuth, - Secret: respSecret, - Data: resp.Data, - Redirect: resp.Redirect, - WrapInfo: respWrapInfo, - }, - } - - if req.WrapInfo != nil { - respEntry.Request.WrapTTL = int(req.WrapInfo.TTL / time.Second) - } - - if !config.OmitTime { - respEntry.Time = time.Now().UTC().Format(time.RFC3339Nano) - } - - return f.AuditFormatWriter.WriteResponse(w, respEntry) -} - -// AuditRequestEntry is the structure of a request audit log entry in Audit. -type AuditRequestEntry struct { - Time string `json:"time,omitempty"` - Type string `json:"type"` - Auth AuditAuth `json:"auth"` - Request AuditRequest `json:"request"` - Error string `json:"error"` -} - -// AuditResponseEntry is the structure of a response audit log entry in Audit. -type AuditResponseEntry struct { - Time string `json:"time,omitempty"` - Type string `json:"type"` - Auth AuditAuth `json:"auth"` - Request AuditRequest `json:"request"` - Response AuditResponse `json:"response"` - Error string `json:"error"` -} - -type AuditRequest struct { - ID string `json:"id"` - ReplicationCluster string `json:"replication_cluster,omitempty"` - Operation logical.Operation `json:"operation"` - ClientToken string `json:"client_token"` - ClientTokenAccessor string `json:"client_token_accessor"` - Path string `json:"path"` - Data map[string]interface{} `json:"data"` - PolicyOverride bool `json:"policy_override"` - RemoteAddr string `json:"remote_address"` - WrapTTL int `json:"wrap_ttl"` - Headers map[string][]string `json:"headers"` -} - -type AuditResponse struct { - Auth *AuditAuth `json:"auth,omitempty"` - Secret *AuditSecret `json:"secret,omitempty"` - Data map[string]interface{} `json:"data,omitempty"` - Redirect string `json:"redirect,omitempty"` - WrapInfo *AuditResponseWrapInfo `json:"wrap_info,omitempty"` -} - -type AuditAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - DisplayName string `json:"display_name"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies,omitempty"` - IdentityPolicies []string `json:"identity_policies,omitempty"` - Metadata map[string]string `json:"metadata"` - NumUses int `json:"num_uses,omitempty"` - RemainingUses int `json:"remaining_uses,omitempty"` - EntityID string `json:"entity_id"` -} - -type AuditSecret struct { - LeaseID string `json:"lease_id"` -} - -type AuditResponseWrapInfo struct { - TTL int `json:"ttl"` - Token string `json:"token"` - Accessor string `json:"accessor"` - CreationTime string `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor,omitempty"` -} - -// getRemoteAddr safely gets the remote address avoiding a nil pointer -func getRemoteAddr(req *logical.Request) string { - if req != nil && req.Connection != nil { - return req.Connection.RemoteAddr - } - return "" -} - -// parseVaultTokenFromJWT returns a string iff the token was a JWT and we could -// extract the original token ID from inside -func parseVaultTokenFromJWT(token string) *string { - if strings.Count(token, ".") != 2 { - return nil - } - - wt, err := jws.ParseJWT([]byte(token)) - if err != nil || wt == nil { - return nil - } - - result, _ := wt.Claims().JWTID() - - return &result -} diff --git a/vendor/github.com/hashicorp/vault/audit/format_json.go b/vendor/github.com/hashicorp/vault/audit/format_json.go deleted file mode 100644 index f42ab20d3..000000000 --- a/vendor/github.com/hashicorp/vault/audit/format_json.go +++ /dev/null @@ -1,53 +0,0 @@ -package audit - -import ( - "context" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/vault/helper/salt" -) - -// JSONFormatWriter is an AuditFormatWriter implementation that structures data into -// a JSON format. -type JSONFormatWriter struct { - Prefix string - SaltFunc func(context.Context) (*salt.Salt, error) -} - -func (f *JSONFormatWriter) WriteRequest(w io.Writer, req *AuditRequestEntry) error { - if req == nil { - return fmt.Errorf("request entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - enc := json.NewEncoder(w) - return enc.Encode(req) -} - -func (f *JSONFormatWriter) WriteResponse(w io.Writer, resp *AuditResponseEntry) error { - if resp == nil { - return fmt.Errorf("response entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - enc := json.NewEncoder(w) - return enc.Encode(resp) -} - -func (f *JSONFormatWriter) Salt(ctx context.Context) (*salt.Salt, error) { - return f.SaltFunc(ctx) -} diff --git a/vendor/github.com/hashicorp/vault/audit/format_jsonx.go b/vendor/github.com/hashicorp/vault/audit/format_jsonx.go deleted file mode 100644 index 30937464d..000000000 --- a/vendor/github.com/hashicorp/vault/audit/format_jsonx.go +++ /dev/null @@ -1,74 +0,0 @@ -package audit - -import ( - "context" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/vault/helper/salt" - "github.com/jefferai/jsonx" -) - -// JSONxFormatWriter is an AuditFormatWriter implementation that structures data into -// a XML format. -type JSONxFormatWriter struct { - Prefix string - SaltFunc func(context.Context) (*salt.Salt, error) -} - -func (f *JSONxFormatWriter) WriteRequest(w io.Writer, req *AuditRequestEntry) error { - if req == nil { - return fmt.Errorf("request entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - jsonBytes, err := json.Marshal(req) - if err != nil { - return err - } - - xmlBytes, err := jsonx.EncodeJSONBytes(jsonBytes) - if err != nil { - return err - } - - _, err = w.Write(xmlBytes) - return err -} - -func (f *JSONxFormatWriter) WriteResponse(w io.Writer, resp *AuditResponseEntry) error { - if resp == nil { - return fmt.Errorf("response entry was nil, cannot encode") - } - - if len(f.Prefix) > 0 { - _, err := w.Write([]byte(f.Prefix)) - if err != nil { - return err - } - } - - jsonBytes, err := json.Marshal(resp) - if err != nil { - return err - } - - xmlBytes, err := jsonx.EncodeJSONBytes(jsonBytes) - if err != nil { - return err - } - - _, err = w.Write(xmlBytes) - return err -} - -func (f *JSONxFormatWriter) Salt(ctx context.Context) (*salt.Salt, error) { - return f.SaltFunc(ctx) -} diff --git a/vendor/github.com/hashicorp/vault/audit/formatter.go b/vendor/github.com/hashicorp/vault/audit/formatter.go deleted file mode 100644 index 7702a1ee5..000000000 --- a/vendor/github.com/hashicorp/vault/audit/formatter.go +++ /dev/null @@ -1,24 +0,0 @@ -package audit - -import ( - "context" - "io" -) - -// Formatter is an interface that is responsible for formating a -// request/response into some format. Formatters write their output -// to an io.Writer. -// -// It is recommended that you pass data through Hash prior to formatting it. -type Formatter interface { - FormatRequest(context.Context, io.Writer, FormatterConfig, *LogInput) error - FormatResponse(context.Context, io.Writer, FormatterConfig, *LogInput) error -} - -type FormatterConfig struct { - Raw bool - HMACAccessor bool - - // This should only ever be used in a testing context - OmitTime bool -} diff --git a/vendor/github.com/hashicorp/vault/audit/hashstructure.go b/vendor/github.com/hashicorp/vault/audit/hashstructure.go deleted file mode 100644 index be1aad97e..000000000 --- a/vendor/github.com/hashicorp/vault/audit/hashstructure.go +++ /dev/null @@ -1,319 +0,0 @@ -package audit - -import ( - "errors" - "reflect" - "strings" - "time" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" - "github.com/mitchellh/reflectwalk" -) - -// HashString hashes the given opaque string and returns it -func HashString(salter *salt.Salt, data string) string { - return salter.GetIdentifiedHMAC(data) -} - -// Hash will hash the given type. This has built-in support for auth, -// requests, and responses. If it is a type that isn't recognized, then -// it will be passed through. -// -// The structure is modified in-place. -func Hash(salter *salt.Salt, raw interface{}, nonHMACDataKeys []string) error { - fn := salter.GetIdentifiedHMAC - - switch s := raw.(type) { - case *logical.Auth: - if s == nil { - return nil - } - if s.ClientToken != "" { - s.ClientToken = fn(s.ClientToken) - } - if s.Accessor != "" { - s.Accessor = fn(s.Accessor) - } - - case *logical.Request: - if s == nil { - return nil - } - if s.Auth != nil { - if err := Hash(salter, s.Auth, nil); err != nil { - return err - } - } - - if s.ClientToken != "" { - s.ClientToken = fn(s.ClientToken) - } - - if s.ClientTokenAccessor != "" { - s.ClientTokenAccessor = fn(s.ClientTokenAccessor) - } - - data, err := HashStructure(s.Data, fn, nonHMACDataKeys) - if err != nil { - return err - } - - s.Data = data.(map[string]interface{}) - - case *logical.Response: - if s == nil { - return nil - } - - if s.Auth != nil { - if err := Hash(salter, s.Auth, nil); err != nil { - return err - } - } - - if s.WrapInfo != nil { - if err := Hash(salter, s.WrapInfo, nil); err != nil { - return err - } - } - - data, err := HashStructure(s.Data, fn, nonHMACDataKeys) - if err != nil { - return err - } - - s.Data = data.(map[string]interface{}) - - case *wrapping.ResponseWrapInfo: - if s == nil { - return nil - } - - s.Token = fn(s.Token) - s.Accessor = fn(s.Accessor) - - if s.WrappedAccessor != "" { - s.WrappedAccessor = fn(s.WrappedAccessor) - } - } - - return nil -} - -// HashStructure takes an interface and hashes all the values within -// the structure. Only _values_ are hashed: keys of objects are not. -// -// For the HashCallback, see the built-in HashCallbacks below. -func HashStructure(s interface{}, cb HashCallback, ignoredKeys []string) (interface{}, error) { - s, err := copystructure.Copy(s) - if err != nil { - return nil, err - } - - walker := &hashWalker{Callback: cb, IgnoredKeys: ignoredKeys} - if err := reflectwalk.Walk(s, walker); err != nil { - return nil, err - } - - return s, nil -} - -// HashCallback is the callback called for HashStructure to hash -// a value. -type HashCallback func(string) string - -// hashWalker implements interfaces for the reflectwalk package -// (github.com/mitchellh/reflectwalk) that can be used to automatically -// replace primitives with a hashed value. -type hashWalker struct { - // Callback is the function to call with the primitive that is - // to be hashed. If there is an error, walking will be halted - // immediately and the error returned. - Callback HashCallback - - // IgnoreKeys are the keys that wont have the HashCallback applied - IgnoredKeys []string - - key []string - lastValue reflect.Value - loc reflectwalk.Location - cs []reflect.Value - csKey []reflect.Value - csData interface{} - sliceIndex int - unknownKeys []string -} - -// hashTimeType stores a pre-computed reflect.Type for a time.Time so -// we can quickly compare in hashWalker.Struct. We create an empty/invalid -// time.Time{} so we don't need to incur any additional startup cost vs. -// Now() or Unix(). -var hashTimeType = reflect.TypeOf(time.Time{}) - -func (w *hashWalker) Enter(loc reflectwalk.Location) error { - w.loc = loc - return nil -} - -func (w *hashWalker) Exit(loc reflectwalk.Location) error { - w.loc = reflectwalk.None - - switch loc { - case reflectwalk.Map: - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.MapValue: - w.key = w.key[:len(w.key)-1] - w.csKey = w.csKey[:len(w.csKey)-1] - case reflectwalk.Slice: - w.cs = w.cs[:len(w.cs)-1] - case reflectwalk.SliceElem: - w.csKey = w.csKey[:len(w.csKey)-1] - } - - return nil -} - -func (w *hashWalker) Map(m reflect.Value) error { - w.cs = append(w.cs, m) - return nil -} - -func (w *hashWalker) MapElem(m, k, v reflect.Value) error { - w.csData = k - w.csKey = append(w.csKey, k) - w.key = append(w.key, k.String()) - w.lastValue = v - return nil -} - -func (w *hashWalker) Slice(s reflect.Value) error { - w.cs = append(w.cs, s) - return nil -} - -func (w *hashWalker) SliceElem(i int, elem reflect.Value) error { - w.csKey = append(w.csKey, reflect.ValueOf(i)) - w.sliceIndex = i - return nil -} - -func (w *hashWalker) Struct(v reflect.Value) error { - // We are looking for time values. If it isn't one, ignore it. - if v.Type() != hashTimeType { - return nil - } - - // If we aren't in a map value, return an error to prevent a panic - if v.Interface() != w.lastValue.Interface() { - return errors.New("time.Time value in a non map key cannot be hashed for audits") - } - - // Create a string value of the time. IMPORTANT: this must never change - // across Vault versions or the hash value of equivalent time.Time will - // change. - strVal := v.Interface().(time.Time).Format(time.RFC3339Nano) - - // Set the map value to the string instead of the time.Time object - m := w.cs[len(w.cs)-1] - mk := w.csData.(reflect.Value) - m.SetMapIndex(mk, reflect.ValueOf(strVal)) - - // Skip this entry so that we don't walk the struct. - return reflectwalk.SkipEntry -} - -func (w *hashWalker) StructField(reflect.StructField, reflect.Value) error { - return nil -} - -func (w *hashWalker) Primitive(v reflect.Value) error { - if w.Callback == nil { - return nil - } - - // We don't touch map keys - if w.loc == reflectwalk.MapKey { - return nil - } - - setV := v - - // We only care about strings - if v.Kind() == reflect.Interface { - setV = v - v = v.Elem() - } - if v.Kind() != reflect.String { - return nil - } - - // See if the current key is part of the ignored keys - currentKey := w.key[len(w.key)-1] - if strutil.StrListContains(w.IgnoredKeys, currentKey) { - return nil - } - - replaceVal := w.Callback(v.String()) - - resultVal := reflect.ValueOf(replaceVal) - switch w.loc { - case reflectwalk.MapKey: - m := w.cs[len(w.cs)-1] - - // Delete the old value - var zero reflect.Value - m.SetMapIndex(w.csData.(reflect.Value), zero) - - // Set the new key with the existing value - m.SetMapIndex(resultVal, w.lastValue) - - // Set the key to be the new key - w.csData = resultVal - case reflectwalk.MapValue: - // If we're in a map, then the only way to set a map value is - // to set it directly. - m := w.cs[len(w.cs)-1] - mk := w.csData.(reflect.Value) - m.SetMapIndex(mk, resultVal) - default: - // Otherwise, we should be addressable - setV.Set(resultVal) - } - - return nil -} - -func (w *hashWalker) removeCurrent() { - // Append the key to the unknown keys - w.unknownKeys = append(w.unknownKeys, strings.Join(w.key, ".")) - - for i := 1; i <= len(w.cs); i++ { - c := w.cs[len(w.cs)-i] - switch c.Kind() { - case reflect.Map: - // Zero value so that we delete the map key - var val reflect.Value - - // Get the key and delete it - k := w.csData.(reflect.Value) - c.SetMapIndex(k, val) - return - } - } - - panic("No container found for removeCurrent") -} - -func (w *hashWalker) replaceCurrent(v reflect.Value) { - c := w.cs[len(w.cs)-2] - switch c.Kind() { - case reflect.Map: - // Get the key and delete it - k := w.csKey[len(w.csKey)-1] - c.SetMapIndex(k, v) - } -} diff --git a/vendor/github.com/hashicorp/vault/builtin/audit/file/backend.go b/vendor/github.com/hashicorp/vault/builtin/audit/file/backend.go deleted file mode 100644 index 281c1de07..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/audit/file/backend.go +++ /dev/null @@ -1,295 +0,0 @@ -package file - -import ( - "context" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, error) { - if conf.SaltConfig == nil { - return nil, fmt.Errorf("nil salt config") - } - if conf.SaltView == nil { - return nil, fmt.Errorf("nil salt view") - } - - path, ok := conf.Config["file_path"] - if !ok { - path, ok = conf.Config["path"] - if !ok { - return nil, fmt.Errorf("file_path is required") - } - } - - // normalize path if configured for stdout - if strings.ToLower(path) == "stdout" { - path = "stdout" - } - if strings.ToLower(path) == "discard" { - path = "discard" - } - - format, ok := conf.Config["format"] - if !ok { - format = "json" - } - switch format { - case "json", "jsonx": - default: - return nil, fmt.Errorf("unknown format type %q", format) - } - - // Check if hashing of accessor is disabled - hmacAccessor := true - if hmacAccessorRaw, ok := conf.Config["hmac_accessor"]; ok { - value, err := strconv.ParseBool(hmacAccessorRaw) - if err != nil { - return nil, err - } - hmacAccessor = value - } - - // Check if raw logging is enabled - logRaw := false - if raw, ok := conf.Config["log_raw"]; ok { - b, err := strconv.ParseBool(raw) - if err != nil { - return nil, err - } - logRaw = b - } - - // Check if mode is provided - mode := os.FileMode(0600) - if modeRaw, ok := conf.Config["mode"]; ok { - m, err := strconv.ParseUint(modeRaw, 8, 32) - if err != nil { - return nil, err - } - if m != 0 { - mode = os.FileMode(m) - } - } - - b := &Backend{ - path: path, - mode: mode, - saltConfig: conf.SaltConfig, - saltView: conf.SaltView, - formatConfig: audit.FormatterConfig{ - Raw: logRaw, - HMACAccessor: hmacAccessor, - }, - } - - switch format { - case "json": - b.formatter.AuditFormatWriter = &audit.JSONFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - case "jsonx": - b.formatter.AuditFormatWriter = &audit.JSONxFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - } - - switch path { - case "stdout", "discard": - // no need to test opening file if outputting to stdout or discarding - default: - // Ensure that the file can be successfully opened for writing; - // otherwise it will be too late to catch later without problems - // (ref: https://github.com/hashicorp/vault/issues/550) - if err := b.open(); err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("sanity check failed; unable to open %q for writing: {{err}}", path), err) - } - } - - return b, nil -} - -// Backend is the audit backend for the file-based audit store. -// -// NOTE: This audit backend is currently very simple: it appends to a file. -// It doesn't do anything more at the moment to assist with rotation -// or reset the write cursor, this should be done in the future. -type Backend struct { - path string - - formatter audit.AuditFormatter - formatConfig audit.FormatterConfig - - fileLock sync.RWMutex - f *os.File - mode os.FileMode - - saltMutex sync.RWMutex - salt *salt.Salt - saltConfig *salt.Config - saltView logical.Storage -} - -var _ audit.Backend = (*Backend)(nil) - -func (b *Backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.saltMutex.RLock() - if b.salt != nil { - defer b.saltMutex.RUnlock() - return b.salt, nil - } - b.saltMutex.RUnlock() - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.saltView, b.saltConfig) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *Backend) GetHash(ctx context.Context, data string) (string, error) { - salt, err := b.Salt(ctx) - if err != nil { - return "", err - } - return audit.HashString(salt, data), nil -} - -func (b *Backend) LogRequest(ctx context.Context, in *audit.LogInput) error { - b.fileLock.Lock() - defer b.fileLock.Unlock() - - switch b.path { - case "stdout": - return b.formatter.FormatRequest(ctx, os.Stdout, b.formatConfig, in) - case "discard": - return b.formatter.FormatRequest(ctx, ioutil.Discard, b.formatConfig, in) - } - - if err := b.open(); err != nil { - return err - } - - if err := b.formatter.FormatRequest(ctx, b.f, b.formatConfig, in); err == nil { - return nil - } - - // Opportunistically try to re-open the FD, once per call - b.f.Close() - b.f = nil - - if err := b.open(); err != nil { - return err - } - - return b.formatter.FormatRequest(ctx, b.f, b.formatConfig, in) -} - -func (b *Backend) LogResponse(ctx context.Context, in *audit.LogInput) error { - - b.fileLock.Lock() - defer b.fileLock.Unlock() - - switch b.path { - case "stdout": - return b.formatter.FormatResponse(ctx, os.Stdout, b.formatConfig, in) - case "discard": - return b.formatter.FormatResponse(ctx, ioutil.Discard, b.formatConfig, in) - } - - if err := b.open(); err != nil { - return err - } - - if err := b.formatter.FormatResponse(ctx, b.f, b.formatConfig, in); err == nil { - return nil - } - - // Opportunistically try to re-open the FD, once per call - b.f.Close() - b.f = nil - - if err := b.open(); err != nil { - return err - } - - return b.formatter.FormatResponse(ctx, b.f, b.formatConfig, in) -} - -// The file lock must be held before calling this -func (b *Backend) open() error { - if b.f != nil { - return nil - } - if err := os.MkdirAll(filepath.Dir(b.path), b.mode); err != nil { - return err - } - - var err error - b.f, err = os.OpenFile(b.path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, b.mode) - if err != nil { - return err - } - - // Change the file mode in case the log file already existed. We special - // case /dev/null since we can't chmod it and bypass if the mode is zero - switch b.path { - case "/dev/null": - default: - if b.mode != 0 { - err = os.Chmod(b.path, b.mode) - if err != nil { - return err - } - } - } - - return nil -} - -func (b *Backend) Reload(_ context.Context) error { - switch b.path { - case "stdout", "discard": - return nil - } - - b.fileLock.Lock() - defer b.fileLock.Unlock() - - if b.f == nil { - return b.open() - } - - err := b.f.Close() - // Set to nil here so that even if we error out, on the next access open() - // will be tried - b.f = nil - if err != nil { - return err - } - - return b.open() -} - -func (b *Backend) Invalidate(_ context.Context) { - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - b.salt = nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/audit/socket/backend.go b/vendor/github.com/hashicorp/vault/builtin/audit/socket/backend.go deleted file mode 100644 index 64e499b46..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/audit/socket/backend.go +++ /dev/null @@ -1,250 +0,0 @@ -package socket - -import ( - "bytes" - "context" - "fmt" - "net" - "strconv" - "sync" - "time" - - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, error) { - if conf.SaltConfig == nil { - return nil, fmt.Errorf("nil salt config") - } - if conf.SaltView == nil { - return nil, fmt.Errorf("nil salt view") - } - - address, ok := conf.Config["address"] - if !ok { - return nil, fmt.Errorf("address is required") - } - - socketType, ok := conf.Config["socket_type"] - if !ok { - socketType = "tcp" - } - - writeDeadline, ok := conf.Config["write_timeout"] - if !ok { - writeDeadline = "2s" - } - writeDuration, err := parseutil.ParseDurationSecond(writeDeadline) - if err != nil { - return nil, err - } - - format, ok := conf.Config["format"] - if !ok { - format = "json" - } - switch format { - case "json", "jsonx": - default: - return nil, fmt.Errorf("unknown format type %q", format) - } - - // Check if hashing of accessor is disabled - hmacAccessor := true - if hmacAccessorRaw, ok := conf.Config["hmac_accessor"]; ok { - value, err := strconv.ParseBool(hmacAccessorRaw) - if err != nil { - return nil, err - } - hmacAccessor = value - } - - // Check if raw logging is enabled - logRaw := false - if raw, ok := conf.Config["log_raw"]; ok { - b, err := strconv.ParseBool(raw) - if err != nil { - return nil, err - } - logRaw = b - } - - b := &Backend{ - saltConfig: conf.SaltConfig, - saltView: conf.SaltView, - formatConfig: audit.FormatterConfig{ - Raw: logRaw, - HMACAccessor: hmacAccessor, - }, - - writeDuration: writeDuration, - address: address, - socketType: socketType, - } - - switch format { - case "json": - b.formatter.AuditFormatWriter = &audit.JSONFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - case "jsonx": - b.formatter.AuditFormatWriter = &audit.JSONxFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - } - - return b, nil -} - -// Backend is the audit backend for the socket audit transport. -type Backend struct { - connection net.Conn - - formatter audit.AuditFormatter - formatConfig audit.FormatterConfig - - writeDuration time.Duration - address string - socketType string - - sync.Mutex - - saltMutex sync.RWMutex - salt *salt.Salt - saltConfig *salt.Config - saltView logical.Storage -} - -var _ audit.Backend = (*Backend)(nil) - -func (b *Backend) GetHash(ctx context.Context, data string) (string, error) { - salt, err := b.Salt(ctx) - if err != nil { - return "", err - } - return audit.HashString(salt, data), nil -} - -func (b *Backend) LogRequest(ctx context.Context, in *audit.LogInput) error { - var buf bytes.Buffer - if err := b.formatter.FormatRequest(ctx, &buf, b.formatConfig, in); err != nil { - return err - } - - b.Lock() - defer b.Unlock() - - err := b.write(ctx, buf.Bytes()) - if err != nil { - rErr := b.reconnect(ctx) - if rErr != nil { - err = multierror.Append(err, rErr) - } else { - // Try once more after reconnecting - err = b.write(ctx, buf.Bytes()) - } - } - - return err -} - -func (b *Backend) LogResponse(ctx context.Context, in *audit.LogInput) error { - var buf bytes.Buffer - if err := b.formatter.FormatResponse(ctx, &buf, b.formatConfig, in); err != nil { - return err - } - - b.Lock() - defer b.Unlock() - - err := b.write(ctx, buf.Bytes()) - if err != nil { - rErr := b.reconnect(ctx) - if rErr != nil { - err = multierror.Append(err, rErr) - } else { - // Try once more after reconnecting - err = b.write(ctx, buf.Bytes()) - } - } - - return err -} - -func (b *Backend) write(ctx context.Context, buf []byte) error { - if b.connection == nil { - if err := b.reconnect(ctx); err != nil { - return err - } - } - - err := b.connection.SetWriteDeadline(time.Now().Add(b.writeDuration)) - if err != nil { - return err - } - - _, err = b.connection.Write(buf) - if err != nil { - return err - } - - return err -} - -func (b *Backend) reconnect(ctx context.Context) error { - if b.connection != nil { - b.connection.Close() - b.connection = nil - } - - dialer := net.Dialer{} - conn, err := dialer.DialContext(ctx, b.socketType, b.address) - if err != nil { - return err - } - - b.connection = conn - - return nil -} - -func (b *Backend) Reload(ctx context.Context) error { - b.Lock() - defer b.Unlock() - - err := b.reconnect(ctx) - - return err -} - -func (b *Backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.saltMutex.RLock() - if b.salt != nil { - defer b.saltMutex.RUnlock() - return b.salt, nil - } - b.saltMutex.RUnlock() - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.saltView, b.saltConfig) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *Backend) Invalidate(_ context.Context) { - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - b.salt = nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/audit/syslog/backend.go b/vendor/github.com/hashicorp/vault/builtin/audit/syslog/backend.go deleted file mode 100644 index ed707217a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/audit/syslog/backend.go +++ /dev/null @@ -1,171 +0,0 @@ -package syslog - -import ( - "bytes" - "context" - "fmt" - "strconv" - "sync" - - "github.com/hashicorp/go-syslog" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -func Factory(ctx context.Context, conf *audit.BackendConfig) (audit.Backend, error) { - if conf.SaltConfig == nil { - return nil, fmt.Errorf("nil salt config") - } - if conf.SaltView == nil { - return nil, fmt.Errorf("nil salt view") - } - - // Get facility or default to AUTH - facility, ok := conf.Config["facility"] - if !ok { - facility = "AUTH" - } - - // Get tag or default to 'vault' - tag, ok := conf.Config["tag"] - if !ok { - tag = "vault" - } - - format, ok := conf.Config["format"] - if !ok { - format = "json" - } - switch format { - case "json", "jsonx": - default: - return nil, fmt.Errorf("unknown format type %q", format) - } - - // Check if hashing of accessor is disabled - hmacAccessor := true - if hmacAccessorRaw, ok := conf.Config["hmac_accessor"]; ok { - value, err := strconv.ParseBool(hmacAccessorRaw) - if err != nil { - return nil, err - } - hmacAccessor = value - } - - // Check if raw logging is enabled - logRaw := false - if raw, ok := conf.Config["log_raw"]; ok { - b, err := strconv.ParseBool(raw) - if err != nil { - return nil, err - } - logRaw = b - } - - // Get the logger - logger, err := gsyslog.NewLogger(gsyslog.LOG_INFO, facility, tag) - if err != nil { - return nil, err - } - - b := &Backend{ - logger: logger, - saltConfig: conf.SaltConfig, - saltView: conf.SaltView, - formatConfig: audit.FormatterConfig{ - Raw: logRaw, - HMACAccessor: hmacAccessor, - }, - } - - switch format { - case "json": - b.formatter.AuditFormatWriter = &audit.JSONFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - case "jsonx": - b.formatter.AuditFormatWriter = &audit.JSONxFormatWriter{ - Prefix: conf.Config["prefix"], - SaltFunc: b.Salt, - } - } - - return b, nil -} - -// Backend is the audit backend for the syslog-based audit store. -type Backend struct { - logger gsyslog.Syslogger - - formatter audit.AuditFormatter - formatConfig audit.FormatterConfig - - saltMutex sync.RWMutex - salt *salt.Salt - saltConfig *salt.Config - saltView logical.Storage -} - -var _ audit.Backend = (*Backend)(nil) - -func (b *Backend) GetHash(ctx context.Context, data string) (string, error) { - salt, err := b.Salt(ctx) - if err != nil { - return "", err - } - return audit.HashString(salt, data), nil -} - -func (b *Backend) LogRequest(ctx context.Context, in *audit.LogInput) error { - var buf bytes.Buffer - if err := b.formatter.FormatRequest(ctx, &buf, b.formatConfig, in); err != nil { - return err - } - - // Write out to syslog - _, err := b.logger.Write(buf.Bytes()) - return err -} - -func (b *Backend) LogResponse(ctx context.Context, in *audit.LogInput) error { - var buf bytes.Buffer - if err := b.formatter.FormatResponse(ctx, &buf, b.formatConfig, in); err != nil { - return err - } - - // Write out to syslog - _, err := b.logger.Write(buf.Bytes()) - return err -} - -func (b *Backend) Reload(_ context.Context) error { - return nil -} - -func (b *Backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.saltMutex.RLock() - if b.salt != nil { - defer b.saltMutex.RUnlock() - return b.salt, nil - } - b.saltMutex.RUnlock() - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.saltView, b.saltConfig) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *Backend) Invalidate(_ context.Context) { - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - b.salt = nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/app-id/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/app-id/backend.go deleted file mode 100644 index 32ec15875..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/app-id/backend.go +++ /dev/null @@ -1,184 +0,0 @@ -package appId - -import ( - "context" - "sync" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b, err := Backend(conf) - if err != nil { - return nil, err - } - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) (*backend, error) { - var b backend - b.MapAppId = &framework.PolicyMap{ - PathMap: framework.PathMap{ - Name: "app-id", - Schema: map[string]*framework.FieldSchema{ - "display_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "A name to map to this app ID for logs.", - }, - - "value": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Policies for the app ID.", - }, - }, - }, - DefaultKey: "default", - } - - b.MapUserId = &framework.PathMap{ - Name: "user-id", - Schema: map[string]*framework.FieldSchema{ - "cidr_block": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "If not blank, restricts auth by this CIDR block", - }, - - "value": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "App IDs that this user associates with.", - }, - }, - } - - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - "login/*", - }, - }, - Paths: framework.PathAppend([]*framework.Path{ - pathLogin(&b), - pathLoginWithAppIDPath(&b), - }, - b.MapAppId.Paths(), - b.MapUserId.Paths(), - ), - AuthRenew: b.pathLoginRenew, - Invalidate: b.invalidate, - BackendType: logical.TypeCredential, - } - - b.view = conf.StorageView - b.MapAppId.SaltFunc = b.Salt - b.MapUserId.SaltFunc = b.Salt - - return &b, nil -} - -type backend struct { - *framework.Backend - - salt *salt.Salt - SaltMutex sync.RWMutex - view logical.Storage - MapAppId *framework.PolicyMap - MapUserId *framework.PathMap -} - -func (b *backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.SaltMutex.RLock() - if b.salt != nil { - defer b.SaltMutex.RUnlock() - return b.salt, nil - } - b.SaltMutex.RUnlock() - b.SaltMutex.Lock() - defer b.SaltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.view, &salt.Config{ - HashFunc: salt.SHA1Hash, - Location: salt.DefaultLocation, - }) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *backend) invalidate(_ context.Context, key string) { - switch key { - case salt.DefaultLocation: - b.SaltMutex.Lock() - defer b.SaltMutex.Unlock() - b.salt = nil - } -} - -const backendHelp = ` -The App ID credential provider is used to perform authentication from -within applications or machine by pairing together two hard-to-guess -unique pieces of information: a unique app ID, and a unique user ID. - -The goal of this credential provider is to allow elastic users -(dynamic machines, containers, etc.) to authenticate with Vault without -having to store passwords outside of Vault. It is a single method of -solving the chicken-and-egg problem of setting up Vault access on a machine. -With this provider, nobody except the machine itself has access to both -pieces of information necessary to authenticate. For example: -configuration management will have the app IDs, but the machine itself -will detect its user ID based on some unique machine property such as a -MAC address (or a hash of it with some salt). - -An example, real world process for using this provider: - - 1. Create unique app IDs (UUIDs work well) and map them to policies. - (Path: map/app-id/) - - 2. Store the app IDs within configuration management systems. - - 3. An out-of-band process run by security operators map unique user IDs - to these app IDs. Example: when an instance is launched, a cloud-init - system tells security operators a unique ID for this machine. This - process can be scripted, but the key is that it is out-of-band and - out of reach of configuration management. - (Path: map/user-id/) - - 4. A new server is provisioned. Configuration management configures the - app ID, the server itself detects its user ID. With both of these - pieces of information, Vault can be accessed according to the policy - set by the app ID. - -More details on this process follow: - -The app ID is a unique ID that maps to a set of policies. This ID is -generated by an operator and configured into the backend. The ID itself -is usually a UUID, but any hard-to-guess unique value can be used. - -After creating app IDs, an operator authorizes a fixed set of user IDs -with each app ID. When a valid {app ID, user ID} tuple is given to the -"login" path, then the user is authenticated with the configured app -ID policies. - -The user ID can be any value (just like the app ID), however it is -generally a value unique to a machine, such as a MAC address or instance ID, -or a value hashed from these unique values. - -It is possible to authorize multiple app IDs with each -user ID by writing them as comma-separated values to the map/user-id/ -path. - -It is also possible to renew the auth tokens with 'vault token-renew ' command. -Before the token is renewed, the validity of app ID, user ID and the associated -policies are checked again. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/app-id/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/app-id/path_login.go deleted file mode 100644 index ec744b283..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/app-id/path_login.go +++ /dev/null @@ -1,230 +0,0 @@ -package appId - -import ( - "context" - "crypto/sha1" - "crypto/subtle" - "encoding/hex" - "fmt" - "net" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLoginWithAppIDPath(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login/(?P.+)", - Fields: map[string]*framework.FieldSchema{ - "app_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The unique app ID", - }, - - "user_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The unique user ID", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "app_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The unique app ID", - }, - - "user_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The unique user ID", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - appId := data.Get("app_id").(string) - - if appId == "" { - return nil, fmt.Errorf("missing app_id") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: appId, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - appId := data.Get("app_id").(string) - userId := data.Get("user_id").(string) - - var displayName string - if dispName, resp, err := b.verifyCredentials(ctx, req, appId, userId); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - displayName = dispName - } - - // Get the policies associated with the app - policies, err := b.MapAppId.Policies(ctx, req.Storage, appId) - if err != nil { - return nil, err - } - - // Store hashes of the app ID and user ID for the metadata - appIdHash := sha1.Sum([]byte(appId)) - userIdHash := sha1.Sum([]byte(userId)) - metadata := map[string]string{ - "app-id": "sha1:" + hex.EncodeToString(appIdHash[:]), - "user-id": "sha1:" + hex.EncodeToString(userIdHash[:]), - } - - return &logical.Response{ - Auth: &logical.Auth{ - InternalData: map[string]interface{}{ - "app-id": appId, - "user-id": userId, - }, - DisplayName: displayName, - Policies: policies, - Metadata: metadata, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - }, - Alias: &logical.Alias{ - Name: appId, - }, - }, - }, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - appId := req.Auth.InternalData["app-id"].(string) - userId := req.Auth.InternalData["user-id"].(string) - - // Skipping CIDR verification to enable renewal from machines other than - // the ones encompassed by CIDR block. - if _, resp, err := b.verifyCredentials(ctx, req, appId, userId); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } - - // Get the policies associated with the app - mapPolicies, err := b.MapAppId.Policies(ctx, req.Storage, appId) - if err != nil { - return nil, err - } - if !policyutil.EquivalentPolicies(mapPolicies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies do not match") - } - - return &logical.Response{Auth: req.Auth}, nil -} - -func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, appId, userId string) (string, *logical.Response, error) { - // Ensure both appId and userId are provided - if appId == "" || userId == "" { - return "", logical.ErrorResponse("missing 'app_id' or 'user_id'"), nil - } - - // Look up the apps that this user is allowed to access - appsMap, err := b.MapUserId.Get(ctx, req.Storage, userId) - if err != nil { - return "", nil, err - } - if appsMap == nil { - return "", logical.ErrorResponse("invalid user ID or app ID"), nil - } - - // If there is a CIDR block restriction, check that - if raw, ok := appsMap["cidr_block"]; ok { - _, cidr, err := net.ParseCIDR(raw.(string)) - if err != nil { - return "", nil, errwrap.Wrapf("invalid restriction cidr: {{err}}", err) - } - - var addr string - if req.Connection != nil { - addr = req.Connection.RemoteAddr - } - if addr == "" || !cidr.Contains(net.ParseIP(addr)) { - return "", logical.ErrorResponse("unauthorized source address"), nil - } - } - - appsRaw, ok := appsMap["value"] - if !ok { - appsRaw = "" - } - - apps, ok := appsRaw.(string) - if !ok { - return "", nil, fmt.Errorf("mapping is not a string") - } - - // Verify that the app is in the list - found := false - appIdBytes := []byte(appId) - for _, app := range strings.Split(apps, ",") { - match := []byte(strings.TrimSpace(app)) - // Protect against a timing attack with the app_id comparison - if subtle.ConstantTimeCompare(match, appIdBytes) == 1 { - found = true - } - } - if !found { - return "", logical.ErrorResponse("invalid user ID or app ID"), nil - } - - // Get the raw data associated with the app - appRaw, err := b.MapAppId.Get(ctx, req.Storage, appId) - if err != nil { - return "", nil, err - } - if appRaw == nil { - return "", logical.ErrorResponse("invalid user ID or app ID"), nil - } - var displayName string - if raw, ok := appRaw["display_name"]; ok { - displayName = raw.(string) - } - - return displayName, nil, nil -} - -const pathLoginSyn = ` -Log in with an App ID and User ID. -` - -const pathLoginDesc = ` -This endpoint authenticates using an application ID, user ID and potential the IP address of the connecting client. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/approle/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/approle/backend.go deleted file mode 100644 index 3705dbb1e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/approle/backend.go +++ /dev/null @@ -1,176 +0,0 @@ -package approle - -import ( - "context" - "sync" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - secretIDPrefix = "secret_id/" - secretIDLocalPrefix = "secret_id_local/" - secretIDAccessorPrefix = "accessor/" - secretIDAccessorLocalPrefix = "accessor_local/" -) - -type backend struct { - *framework.Backend - - // The salt value to be used by the information to be accessed only - // by this backend. - salt *salt.Salt - saltMutex sync.RWMutex - - // The view to use when creating the salt - view logical.Storage - - // Guard to clean-up the expired SecretID entries - tidySecretIDCASGuard *uint32 - - // Locks to make changes to role entries. These will be initialized to a - // predefined number of locks when the backend is created, and will be - // indexed based on salted role names. - roleLocks []*locksutil.LockEntry - - // Locks to make changes to the storage entries of RoleIDs generated. These - // will be initialized to a predefined number of locks when the backend is - // created, and will be indexed based on the salted RoleIDs. - roleIDLocks []*locksutil.LockEntry - - // Locks to make changes to the storage entries of SecretIDs generated. - // These will be initialized to a predefined number of locks when the - // backend is created, and will be indexed based on the HMAC-ed SecretIDs. - secretIDLocks []*locksutil.LockEntry - - // Locks to make changes to the storage entries of SecretIDAccessors - // generated. These will be initialized to a predefined number of locks - // when the backend is created, and will be indexed based on the - // SecretIDAccessors itself. - secretIDAccessorLocks []*locksutil.LockEntry - - // secretIDListingLock is a dedicated lock for listing SecretIDAccessors - // for all the SecretIDs issued against an approle - secretIDListingLock sync.RWMutex - - testTidyDelay time.Duration -} - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b, err := Backend(conf) - if err != nil { - return nil, err - } - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) (*backend, error) { - // Create a backend object - b := &backend{ - view: conf.StorageView, - - // Create locks to modify the registered roles - roleLocks: locksutil.CreateLocks(), - - // Create locks to modify the generated RoleIDs - roleIDLocks: locksutil.CreateLocks(), - - // Create locks to modify the generated SecretIDs - secretIDLocks: locksutil.CreateLocks(), - - // Create locks to modify the generated SecretIDAccessors - secretIDAccessorLocks: locksutil.CreateLocks(), - - tidySecretIDCASGuard: new(uint32), - } - - // Attach the paths and secrets that are to be handled by the backend - b.Backend = &framework.Backend{ - // Register a periodic function that deletes the expired SecretID entries - PeriodicFunc: b.periodicFunc, - Help: backendHelp, - AuthRenew: b.pathLoginRenew, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - LocalStorage: []string{ - secretIDLocalPrefix, - secretIDAccessorLocalPrefix, - }, - }, - Paths: framework.PathAppend( - rolePaths(b), - []*framework.Path{ - pathLogin(b), - pathTidySecretID(b), - }, - ), - Invalidate: b.invalidate, - BackendType: logical.TypeCredential, - } - return b, nil -} - -func (b *backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.saltMutex.RLock() - if b.salt != nil { - defer b.saltMutex.RUnlock() - return b.salt, nil - } - b.saltMutex.RUnlock() - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.view, &salt.Config{ - HashFunc: salt.SHA256Hash, - Location: salt.DefaultLocation, - }) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *backend) invalidate(_ context.Context, key string) { - switch key { - case salt.DefaultLocation: - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - b.salt = nil - } -} - -// periodicFunc of the backend will be invoked once a minute by the RollbackManager. -// RoleRole backend utilizes this function to delete expired SecretID entries. -// This could mean that the SecretID may live in the backend upto 1 min after its -// expiration. The deletion of SecretIDs are not security sensitive and it is okay -// to delay the removal of SecretIDs by a minute. -func (b *backend) periodicFunc(ctx context.Context, req *logical.Request) error { - // Initiate clean-up of expired SecretID entries - if b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - b.tidySecretID(ctx, req) - } - return nil -} - -const backendHelp = ` -Any registered Role can authenticate itself with Vault. The credentials -depends on the constraints that are set on the Role. One common required -credential is the 'role_id' which is a unique identifier of the Role. -It can be retrieved from the 'role//role-id' endpoint. - -The default constraint configuration is 'bind_secret_id', which requires -the credential 'secret_id' to be presented during login. Refer to the -documentation for other types of constraints.` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_login.go deleted file mode 100644 index 24a2a9fc1..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_login.go +++ /dev/null @@ -1,350 +0,0 @@ -package approle - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Unique identifier of the Role. Required to be supplied when the 'bind_secret_id' constraint is set.", - }, - "secret_id": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "SecretID belong to the App role", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLoginUpdate, - logical.AliasLookaheadOperation: b.pathLoginUpdateAliasLookahead, - }, - HelpSynopsis: pathLoginHelpSys, - HelpDescription: pathLoginHelpDesc, - } -} - -func (b *backend) pathLoginUpdateAliasLookahead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleID := strings.TrimSpace(data.Get("role_id").(string)) - if roleID == "" { - return nil, fmt.Errorf("missing role_id") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: roleID, - }, - }, - }, nil -} - -// Returns the Auth object indicating the authentication and authorization information -// if the credentials provided are validated by the backend. -func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - - // RoleID must be supplied during every login - roleID := strings.TrimSpace(data.Get("role_id").(string)) - if roleID == "" { - return logical.ErrorResponse("missing role_id"), nil - } - - // Look for the storage entry that maps the roleID to role - roleIDIndex, err := b.roleIDEntry(ctx, req.Storage, roleID) - if err != nil { - return nil, err - } - if roleIDIndex == nil { - return logical.ErrorResponse("invalid role ID"), nil - } - - roleName := roleIDIndex.Name - - roleLock := b.roleLock(roleName) - roleLock.RLock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - roleLock.RUnlock() - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse("invalid role ID"), nil - } - - metadata := make(map[string]string) - var entry *secretIDStorageEntry - if role.BindSecretID { - secretID := strings.TrimSpace(data.Get("secret_id").(string)) - if secretID == "" { - return logical.ErrorResponse("missing secret_id"), nil - } - - secretIDHMAC, err := createHMAC(role.HMACKey, secretID) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) - } - - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - - secretIDLock := b.secretIDLock(secretIDHMAC) - secretIDLock.RLock() - - unlockFunc := secretIDLock.RUnlock - defer func() { - unlockFunc() - }() - - entry, err = b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if entry == nil { - return logical.ErrorResponse("invalid secret id"), nil - } - - // If a secret ID entry does not have a corresponding accessor - // entry, revoke the secret ID immediately - accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, entry.SecretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to read secret ID accessor entry: {{err}}", err) - } - if accessorEntry == nil { - // Switch the locks and recheck the conditions - secretIDLock.RUnlock() - secretIDLock.Lock() - unlockFunc = secretIDLock.Unlock - - entry, err = b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if entry == nil { - return logical.ErrorResponse("invalid secret id"), nil - } - - accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, entry.SecretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to read secret ID accessor entry: {{err}}", err) - } - - if accessorEntry == nil { - if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error deleting secret ID %q from storage: {{err}}", secretIDHMAC), err) - } - } - return logical.ErrorResponse("invalid secret id"), nil - } - - switch { - case entry.SecretIDNumUses == 0: - // - // SecretIDNumUses will be zero only if the usage limit was not set at all, - // in which case, the SecretID will remain to be valid as long as it is not - // expired. - // - - // Ensure that the CIDRs on the secret ID are still a subset of that of - // role's - err = verifyCIDRRoleSecretIDSubset(entry.CIDRList, role.SecretIDBoundCIDRs) - if err != nil { - return nil, err - } - - // If CIDR restrictions are present on the secret ID, check if the - // source IP complies to it - if len(entry.CIDRList) != 0 { - if req.Connection == nil || req.Connection.RemoteAddr == "" { - return nil, fmt.Errorf("failed to get connection information") - } - - belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, entry.CIDRList) - if !belongs || err != nil { - return logical.ErrorResponse(errwrap.Wrapf(fmt.Sprintf("source address %q unauthorized through CIDR restrictions on the secret ID: {{err}}", req.Connection.RemoteAddr), err).Error()), nil - } - } - default: - // - // If the SecretIDNumUses is non-zero, it means that its use-count should be updated - // in the storage. Switch the lock from a `read` to a `write` and update - // the storage entry. - // - - secretIDLock.RUnlock() - secretIDLock.Lock() - unlockFunc = secretIDLock.Unlock - - // Lock switching may change the data. Refresh the contents. - entry, err = b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if entry == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid secret_id %q", secretID)), nil - } - - // If there exists a single use left, delete the SecretID entry from - // the storage but do not fail the validation request. Subsequent - // requests to use the same SecretID will fail. - if entry.SecretIDNumUses == 1 { - // Delete the secret IDs accessor first - err = b.deleteSecretIDAccessorEntry(ctx, req.Storage, entry.SecretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, err - } - err = req.Storage.Delete(ctx, entryIndex) - if err != nil { - return nil, errwrap.Wrapf("failed to delete secret ID: {{err}}", err) - } - } else { - // If the use count is greater than one, decrement it and update the last updated time. - entry.SecretIDNumUses -= 1 - entry.LastUpdatedTime = time.Now() - - sEntry, err := logical.StorageEntryJSON(entryIndex, &entry) - if err != nil { - return nil, err - } - - err = req.Storage.Put(ctx, sEntry) - if err != nil { - return nil, err - } - } - - // Ensure that the CIDRs on the secret ID are still a subset of that of - // role's - err = verifyCIDRRoleSecretIDSubset(entry.CIDRList, role.SecretIDBoundCIDRs) - if err != nil { - return nil, err - } - - // If CIDR restrictions are present on the secret ID, check if the - // source IP complies to it - if len(entry.CIDRList) != 0 { - if req.Connection == nil || req.Connection.RemoteAddr == "" { - return nil, fmt.Errorf("failed to get connection information") - } - - belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, entry.CIDRList) - if err != nil || !belongs { - return logical.ErrorResponse(errwrap.Wrapf(fmt.Sprintf("source address %q unauthorized by CIDR restrictions on the secret ID: {{err}}", req.Connection.RemoteAddr), err).Error()), nil - } - } - } - - metadata = entry.Metadata - } - - if len(role.SecretIDBoundCIDRs) != 0 { - if req.Connection == nil || req.Connection.RemoteAddr == "" { - return nil, fmt.Errorf("failed to get connection information") - } - belongs, err := cidrutil.IPBelongsToCIDRBlocksSlice(req.Connection.RemoteAddr, role.SecretIDBoundCIDRs) - if err != nil || !belongs { - return logical.ErrorResponse(errwrap.Wrapf(fmt.Sprintf("source address %q unauthorized by CIDR restrictions on the role: {{err}}", req.Connection.RemoteAddr), err).Error()), nil - } - } - - // Parse the CIDRs we should be binding the token to. - var tokenBoundCIDRStrings []string - if entry != nil { - tokenBoundCIDRStrings = entry.TokenBoundCIDRs - } - if len(tokenBoundCIDRStrings) == 0 { - tokenBoundCIDRStrings = role.TokenBoundCIDRs - } - tokenBoundCIDRs, err := parseutil.ParseAddrs(tokenBoundCIDRStrings) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - // For some reason, if metadata was set to nil while processing secret ID - // binding, ensure that it is initialized again to avoid a panic. - if metadata == nil { - metadata = make(map[string]string) - } - - // Always include the role name, for later filtering - metadata["role_name"] = role.name - - auth := &logical.Auth{ - NumUses: role.TokenNumUses, - Period: role.Period, - InternalData: map[string]interface{}{ - "role_name": role.name, - }, - Metadata: metadata, - Policies: role.Policies, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: role.TokenTTL, - MaxTTL: role.TokenMaxTTL, - }, - Alias: &logical.Alias{ - Name: role.RoleID, - }, - BoundCIDRs: tokenBoundCIDRs, - } - - return &logical.Response{ - Auth: auth, - }, nil -} - -// Invoked when the token issued by this backend is attempting a renewal. -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := req.Auth.InternalData["role_name"].(string) - if roleName == "" { - return nil, fmt.Errorf("failed to fetch role_name during renewal") - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - // Ensure that the Role still exists. - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to validate role %q during renewal: {{err}}", roleName), err) - } - if role == nil { - return nil, fmt.Errorf("role %q does not exist during renewal", roleName) - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = role.TokenTTL - resp.Auth.MaxTTL = role.TokenMaxTTL - resp.Auth.Period = role.Period - return resp, nil -} - -const pathLoginHelpSys = "Issue a token based on the credentials supplied" - -const pathLoginHelpDesc = ` -While the credential 'role_id' is required at all times, -other credentials required depends on the properties App role -to which the 'role_id' belongs to. The 'bind_secret_id' -constraint (enabled by default) on the App role requires the -'secret_id' credential to be presented. - -'role_id' is fetched using the 'role//role_id' -endpoint and 'secret_id' is fetched using the 'role//secret_id' -endpoint.` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_role.go b/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_role.go deleted file mode 100644 index a21261ceb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_role.go +++ /dev/null @@ -1,2562 +0,0 @@ -package approle - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// roleStorageEntry stores all the options that are set on an role -type roleStorageEntry struct { - // Name of the role. This field is not persisted on disk. After the role is - // read out of disk, the sanitized version of name is set in this field for - // subsequent use of role name elsewhere. - name string - - // UUID that uniquely represents this role. This serves as a credential - // to perform login using this role. - RoleID string `json:"role_id" mapstructure:"role_id"` - - // UUID that serves as the HMAC key for the hashing the 'secret_id's - // of the role - HMACKey string `json:"hmac_key" mapstructure:"hmac_key"` - - // Policies that are to be required by the token to access this role - Policies []string `json:"policies" mapstructure:"policies"` - - // Number of times the SecretID generated against this role can be - // used to perform login operation - SecretIDNumUses int `json:"secret_id_num_uses" mapstructure:"secret_id_num_uses"` - - // Duration (less than the backend mount's max TTL) after which a - // SecretID generated against the role will expire - SecretIDTTL time.Duration `json:"secret_id_ttl" mapstructure:"secret_id_ttl"` - - // TokenNumUses defines the number of allowed uses of the token issued - TokenNumUses int `json:"token_num_uses" mapstructure:"token_num_uses"` - - // Duration before which an issued token must be renewed - TokenTTL time.Duration `json:"token_ttl" mapstructure:"token_ttl"` - - // Duration after which an issued token should not be allowed to be renewed - TokenMaxTTL time.Duration `json:"token_max_ttl" mapstructure:"token_max_ttl"` - - // A constraint, if set, requires 'secret_id' credential to be presented during login - BindSecretID bool `json:"bind_secret_id" mapstructure:"bind_secret_id"` - - // Deprecated: A constraint, if set, specifies the CIDR blocks from which logins should be allowed, - // please use SecretIDBoundCIDRs instead. - BoundCIDRListOld string `json:"bound_cidr_list,omitempty"` - - // Deprecated: A constraint, if set, specifies the CIDR blocks from which logins should be allowed, - // please use SecretIDBoundCIDRs instead. - BoundCIDRList []string `json:"bound_cidr_list_list" mapstructure:"bound_cidr_list"` - - // A constraint, if set, specifies the CIDR blocks from which logins should be allowed - SecretIDBoundCIDRs []string `json:"secret_id_bound_cidrs" mapstructure:"secret_id_bound_cidrs"` - - // A constraint, if set, specifies the CIDR blocks from which token use should be allowed - TokenBoundCIDRs []string `json:"token_bound_cidrs" mapstructure:"token_bound_cidrs"` - - // Period, if set, indicates that the token generated using this role - // should never expire. The token should be renewed within the duration - // specified by this value. The renewal duration will be fixed if the - // value is not modified on the role. If the `Period` in the role is modified, - // a token will pick up the new value during its next renewal. - Period time.Duration `json:"period" mapstructure:"period"` - - // LowerCaseRoleName enforces the lower casing of role names for all the - // roles that get created since this field was introduced. - LowerCaseRoleName bool `json:"lower_case_role_name" mapstructure:"lower_case_role_name"` - - // SecretIDPrefix is the storage prefix for persisting secret IDs. This - // differs based on whether the secret IDs are cluster local or not. - SecretIDPrefix string `json:"secret_id_prefix" mapstructure:"secret_id_prefix"` -} - -// roleIDStorageEntry represents the reverse mapping from RoleID to Role -type roleIDStorageEntry struct { - Name string `json:"name" mapstructure:"name"` -} - -// rolePaths creates all the paths that are used to register and manage an role. -// -// Paths returned: -// role/ - For listing all the registered roles -// role/ - For registering an role -// role//policies - For updating the param -// role//secret-id-num-uses - For updating the param -// role//secret-id-ttl - For updating the param -// role//token-ttl - For updating the param -// role//token-max-ttl - For updating the param -// role//token-num-uses - For updating the param -// role//bind-secret-id - For updating the param -// role//bound-cidr-list - For updating the param -// role//period - For updating the param -// role//role-id - For fetching the role_id of an role -// role//secret-id - For issuing a secret_id against an role, also to list the secret_id_accessors -// role//custom-secret-id - For assigning a custom SecretID against an role -// role//secret-id/lookup - For reading the properties of a secret_id -// role//secret-id/destroy - For deleting a secret_id -// role//secret-id-accessor/lookup - For reading secret_id using accessor -// role//secret-id-accessor/destroy - For deleting secret_id using accessor -func rolePaths(b *backend) []*framework.Path { - return []*framework.Path{ - &framework.Path{ - Pattern: "role/?", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-list"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-list"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name"), - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "bind_secret_id": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: "Impose secret_id to be presented when logging in using this role. Defaults to 'true'.", - }, - // Deprecated - "bound_cidr_list": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Deprecated: Please use "secret_id_bound_cidrs" instead. Comma separated string or list -of CIDR blocks. If set, specifies the blocks of IP addresses which can perform the login operation.`, - }, - "secret_id_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - "token_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can use the returned token.`, - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: "default", - Description: "Comma separated list of policies on the role.", - }, - "secret_id_num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of times a SecretID can access the role, after which the SecretID -will expire. Defaults to 0 meaning that the the secret_id is of unlimited use.`, - }, - "secret_id_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued SecretID should expire. Defaults -to 0, meaning no expiration.`, - }, - "token_num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of times issued tokens can be used`, - }, - "token_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "token_max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should not be allowed to -be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`, - }, - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - "role_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Identifier of the role. Defaults to a UUID.", - }, - "local_secret_ids": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, the secret IDs generated using this role will be cluster local. This -can only be set during role creation and once set, it can't be reset later.`, - }, - }, - ExistenceCheck: b.pathRoleExistenceCheck, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathRoleCreateUpdate, - logical.UpdateOperation: b.pathRoleCreateUpdate, - logical.ReadOperation: b.pathRoleRead, - logical.DeleteOperation: b.pathRoleDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/local-secret-ids$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleLocalSecretIDsRead, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-local-secret-ids"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-local-secret-ids"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/policies$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: "default", - Description: "Comma separated list of policies on the role.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRolePoliciesUpdate, - logical.ReadOperation: b.pathRolePoliciesRead, - logical.DeleteOperation: b.pathRolePoliciesDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-policies"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-policies"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/bound-cidr-list$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "bound_cidr_list": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Deprecated: Please use "secret_id_bound_cidrs" instead. Comma separated string or list -of CIDR blocks. If set, specifies the blocks of IP addresses which can perform the login operation.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleBoundCIDRUpdate, - logical.ReadOperation: b.pathRoleBoundCIDRListRead, - logical.DeleteOperation: b.pathRoleBoundCIDRListDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-bound-cidr-list"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-bound-cidr-list"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-bound-cidrs$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleBoundCIDRUpdate, - logical.ReadOperation: b.pathRoleSecretIDBoundCIDRRead, - logical.DeleteOperation: b.pathRoleSecretIDBoundCIDRDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["secret-id-bound-cidrs"][0]), - HelpDescription: strings.TrimSpace(roleHelp["secret-id-bound-cidrs"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-bound-cidrs$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "token_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can use the returned token.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleBoundCIDRUpdate, - logical.ReadOperation: b.pathRoleTokenBoundCIDRRead, - logical.DeleteOperation: b.pathRoleTokenBoundCIDRDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["token-bound-cidrs"][0]), - HelpDescription: strings.TrimSpace(roleHelp["token-bound-cidrs"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/bind-secret-id$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "bind_secret_id": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: "Impose secret_id to be presented when logging in using this role.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleBindSecretIDUpdate, - logical.ReadOperation: b.pathRoleBindSecretIDRead, - logical.DeleteOperation: b.pathRoleBindSecretIDDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-bind-secret-id"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-bind-secret-id"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-num-uses$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id_num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Number of times a SecretID can access the role, after which the SecretID will expire.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDNumUsesUpdate, - logical.ReadOperation: b.pathRoleSecretIDNumUsesRead, - logical.DeleteOperation: b.pathRoleSecretIDNumUsesDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-num-uses"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-num-uses"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-ttl$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued SecretID should expire. Defaults -to 0, meaning no expiration.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDTTLUpdate, - logical.ReadOperation: b.pathRoleSecretIDTTLRead, - logical.DeleteOperation: b.pathRoleSecretIDTTLDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-ttl"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-ttl"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/period$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRolePeriodUpdate, - logical.ReadOperation: b.pathRolePeriodRead, - logical.DeleteOperation: b.pathRolePeriodDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-period"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-period"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-num-uses$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "token_num_uses": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of times issued tokens can be used`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleTokenNumUsesUpdate, - logical.ReadOperation: b.pathRoleTokenNumUsesRead, - logical.DeleteOperation: b.pathRoleTokenNumUsesDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-token-num-uses"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-token-num-uses"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-ttl$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "token_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fall back to the system/mount defaults.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleTokenTTLUpdate, - logical.ReadOperation: b.pathRoleTokenTTLRead, - logical.DeleteOperation: b.pathRoleTokenTTLDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-token-ttl"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-token-ttl"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/token-max-ttl$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "token_max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in seconds after which the issued token should not be allowed to -be renewed. Defaults to 0, in which case the value will fall back to the system/mount defaults.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleTokenMaxTTLUpdate, - logical.ReadOperation: b.pathRoleTokenMaxTTLRead, - logical.DeleteOperation: b.pathRoleTokenMaxTTLDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-token-max-ttl"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-token-max-ttl"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/role-id$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "role_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Identifier of the role. Defaults to a UUID.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRoleIDRead, - logical.UpdateOperation: b.pathRoleRoleIDUpdate, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-id"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-id"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/?$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "metadata": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Metadata to be tied to the SecretID. This should be a JSON -formatted string containing the metadata in key value pairs.`, - }, - "cidr_list": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks enforcing secret IDs to be used from -specific set of IP addresses. If 'bound_cidr_list' is set on the role, then the -list of CIDR blocks listed here should be a subset of the CIDR blocks listed on -the role.`, - }, - "token_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can use the returned token. Should be a subset of the token CIDR blocks listed on the role, if any.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDUpdate, - logical.ListOperation: b.pathRoleSecretIDList, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/lookup/?$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "SecretID attached to the role.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDLookupUpdate, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-lookup"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-lookup"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id/destroy/?$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "SecretID attached to the role.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDDestroyUpdateDelete, - logical.DeleteOperation: b.pathRoleSecretIDDestroyUpdateDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-destroy"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-destroy"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-accessor/lookup/?$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id_accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the SecretID", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDAccessorLookupUpdate, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-accessor"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-accessor"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/secret-id-accessor/destroy/?$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id_accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the SecretID", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleSecretIDAccessorDestroyUpdateDelete, - logical.DeleteOperation: b.pathRoleSecretIDAccessorDestroyUpdateDelete, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-secret-id-accessor"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-secret-id-accessor"][1]), - }, - &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role_name") + "/custom-secret-id$", - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "secret_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "SecretID to be attached to the role.", - }, - "metadata": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Metadata to be tied to the SecretID. This should be a JSON -formatted string containing metadata in key value pairs.`, - }, - "cidr_list": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks enforcing secret IDs to be used from -specific set of IP addresses. If 'bound_cidr_list' is set on the role, then the -list of CIDR blocks listed here should be a subset of the CIDR blocks listed on -the role.`, - }, - "token_bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can use the returned token. Should be a subset of the token CIDR blocks listed on the role, if any.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleCustomSecretIDUpdate, - }, - HelpSynopsis: strings.TrimSpace(roleHelp["role-custom-secret-id"][0]), - HelpDescription: strings.TrimSpace(roleHelp["role-custom-secret-id"][1]), - }, - } -} - -// pathRoleExistenceCheck returns whether the role with the given name exists or not. -func (b *backend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return false, fmt.Errorf("missing role_name") - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return false, err - } - - return role != nil, nil -} - -// pathRoleList is used to list all the Roles registered with the backend. -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lock := b.roleLock("") - - lock.RLock() - defer lock.RUnlock() - - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil -} - -// pathRoleSecretIDList is used to list all the 'secret_id_accessor's issued against the role. -func (b *backend) pathRoleSecretIDList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - // Get the role entry - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("role %q does not exist", roleName)), nil - } - - // Guard the list operation with an outer lock - b.secretIDListingLock.RLock() - defer b.secretIDListingLock.RUnlock() - - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - // Listing works one level at a time. Get the first level of data - // which could then be used to get the actual SecretID storage entries. - secretIDHMACs, err := req.Storage.List(ctx, fmt.Sprintf("%s%s/", role.SecretIDPrefix, roleNameHMAC)) - if err != nil { - return nil, err - } - - var listItems []string - for _, secretIDHMAC := range secretIDHMACs { - // For sanity - if secretIDHMAC == "" { - continue - } - - // Prepare the full index of the SecretIDs. - entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - - // SecretID locks are not indexed by SecretIDs itself. - // This is because SecretIDs are not stored in plaintext - // form anywhere in the backend, and hence accessing its - // corresponding lock many times using SecretIDs is not - // possible. Also, indexing it everywhere using secretIDHMACs - // makes listing operation easier. - secretIDLock := b.secretIDLock(secretIDHMAC) - - secretIDLock.RLock() - - result := secretIDStorageEntry{} - if entry, err := req.Storage.Get(ctx, entryIndex); err != nil { - secretIDLock.RUnlock() - return nil, err - } else if entry == nil { - secretIDLock.RUnlock() - return nil, fmt.Errorf("storage entry for SecretID is present but no content found at the index") - } else if err := entry.DecodeJSON(&result); err != nil { - secretIDLock.RUnlock() - return nil, err - } - listItems = append(listItems, result.SecretIDAccessor) - secretIDLock.RUnlock() - } - - return logical.ListResponse(listItems), nil -} - -// validateRoleConstraints checks if the role has at least one constraint -// enabled. -func validateRoleConstraints(role *roleStorageEntry) error { - if role == nil { - return fmt.Errorf("nil role") - } - - // At least one constraint should be enabled on the role - switch { - case role.BindSecretID: - case len(role.BoundCIDRList) != 0: - case len(role.SecretIDBoundCIDRs) != 0: - case len(role.TokenBoundCIDRs) != 0: - default: - return fmt.Errorf("at least one constraint should be enabled on the role") - } - - return nil -} - -// setRoleEntry persists the role and creates an index from roleID to role -// name. -func (b *backend) setRoleEntry(ctx context.Context, s logical.Storage, roleName string, role *roleStorageEntry, previousRoleID string) error { - if roleName == "" { - return fmt.Errorf("missing role name") - } - - if role == nil { - return fmt.Errorf("nil role") - } - - // Check if role constraints are properly set - if err := validateRoleConstraints(role); err != nil { - return err - } - - // Create a storage entry for the role - entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), role) - if err != nil { - return err - } - if entry == nil { - return fmt.Errorf("failed to create storage entry for role %q", roleName) - } - - // Check if the index from the role_id to role already exists - roleIDIndex, err := b.roleIDEntry(ctx, s, role.RoleID) - if err != nil { - return errwrap.Wrapf("failed to read role_id index: {{err}}", err) - } - - // If the entry exists, make sure that it belongs to the current role - if roleIDIndex != nil && roleIDIndex.Name != roleName { - return fmt.Errorf("role_id already in use") - } - - // When role_id is getting updated, delete the old index before - // a new one is created - if previousRoleID != "" && previousRoleID != role.RoleID { - if err = b.roleIDEntryDelete(ctx, s, previousRoleID); err != nil { - return fmt.Errorf("failed to delete previous role ID index") - } - } - - // Save the role entry only after all the validations - if err = s.Put(ctx, entry); err != nil { - return err - } - - // If previousRoleID is still intact, don't create another one - if previousRoleID != "" && previousRoleID == role.RoleID { - return nil - } - - // Create a storage entry for reverse mapping of RoleID to role. - // Note that secondary index is created when the roleLock is held. - return b.setRoleIDEntry(ctx, s, role.RoleID, &roleIDStorageEntry{ - Name: roleName, - }) -} - -// roleEntry reads the role from storage -func (b *backend) roleEntry(ctx context.Context, s logical.Storage, roleName string) (*roleStorageEntry, error) { - if roleName == "" { - return nil, fmt.Errorf("missing role_name") - } - - var role roleStorageEntry - - if entry, err := s.Get(ctx, "role/"+strings.ToLower(roleName)); err != nil { - return nil, err - } else if entry == nil { - return nil, nil - } else if err := entry.DecodeJSON(&role); err != nil { - return nil, err - } - - needsUpgrade := false - - if role.BoundCIDRListOld != "" { - role.SecretIDBoundCIDRs = strutil.ParseDedupAndSortStrings(role.BoundCIDRListOld, ",") - role.BoundCIDRListOld = "" - needsUpgrade = true - } - - if len(role.BoundCIDRList) != 0 { - role.SecretIDBoundCIDRs = role.BoundCIDRList - role.BoundCIDRList = nil - needsUpgrade = true - } - - if role.SecretIDPrefix == "" { - role.SecretIDPrefix = secretIDPrefix - needsUpgrade = true - } - - if needsUpgrade && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) { - entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), &role) - if err != nil { - return nil, err - } - if err := s.Put(ctx, entry); err != nil { - // Only perform upgrades on replication primary - if !strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return nil, err - } - } - } - - role.name = roleName - if role.LowerCaseRoleName { - role.name = strings.ToLower(roleName) - } - - return &role, nil -} - -// pathRoleCreateUpdate registers a new role with the backend or updates the options -// of an existing role -func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - // Check if the role already exists - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - // Create a new entry object if this is a CreateOperation - switch { - case role == nil && req.Operation == logical.CreateOperation: - hmacKey, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to create role_id: {{err}}", err) - } - role = &roleStorageEntry{ - name: strings.ToLower(roleName), - HMACKey: hmacKey, - LowerCaseRoleName: true, - } - case role == nil: - return logical.ErrorResponse(fmt.Sprintf("role name %q doesn't exist", roleName)), logical.ErrUnsupportedPath - } - - localSecretIDsRaw, ok := data.GetOk("local_secret_ids") - if ok { - switch { - case req.Operation == logical.CreateOperation: - localSecretIDs := localSecretIDsRaw.(bool) - if localSecretIDs { - role.SecretIDPrefix = secretIDLocalPrefix - } - default: - return logical.ErrorResponse("local_secret_ids can only be modified during role creation"), nil - } - } - - previousRoleID := role.RoleID - if roleIDRaw, ok := data.GetOk("role_id"); ok { - role.RoleID = roleIDRaw.(string) - } else if req.Operation == logical.CreateOperation { - roleID, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to generate role_id: {{err}}", err) - } - role.RoleID = roleID - } - if role.RoleID == "" { - return logical.ErrorResponse("invalid role_id supplied, or failed to generate a role_id"), nil - } - - if bindSecretIDRaw, ok := data.GetOk("bind_secret_id"); ok { - role.BindSecretID = bindSecretIDRaw.(bool) - } else if req.Operation == logical.CreateOperation { - role.BindSecretID = data.Get("bind_secret_id").(bool) - } - - if boundCIDRListRaw, ok := data.GetFirst("secret_id_bound_cidrs", "bound_cidr_list"); ok { - role.SecretIDBoundCIDRs = boundCIDRListRaw.([]string) - } - - if len(role.SecretIDBoundCIDRs) != 0 { - valid, err := cidrutil.ValidateCIDRListSlice(role.SecretIDBoundCIDRs) - if err != nil { - return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("invalid CIDR blocks"), nil - } - } - - if boundCIDRListRaw, ok := data.GetOk("token_bound_cidrs"); ok { - role.TokenBoundCIDRs = boundCIDRListRaw.([]string) - } - - if len(role.TokenBoundCIDRs) != 0 { - valid, err := cidrutil.ValidateCIDRListSlice(role.TokenBoundCIDRs) - if err != nil { - return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("invalid CIDR blocks"), nil - } - } - - if policiesRaw, ok := data.GetOk("policies"); ok { - role.Policies = policyutil.ParsePolicies(policiesRaw) - } else if req.Operation == logical.CreateOperation { - role.Policies = policyutil.ParsePolicies(data.Get("policies")) - } - - periodRaw, ok := data.GetOk("period") - if ok { - role.Period = time.Second * time.Duration(periodRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.Period = time.Second * time.Duration(data.Get("period").(int)) - } - if role.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("period of %q is greater than the backend's maximum lease TTL of %q", role.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - - if secretIDNumUsesRaw, ok := data.GetOk("secret_id_num_uses"); ok { - role.SecretIDNumUses = secretIDNumUsesRaw.(int) - } else if req.Operation == logical.CreateOperation { - role.SecretIDNumUses = data.Get("secret_id_num_uses").(int) - } - if role.SecretIDNumUses < 0 { - return logical.ErrorResponse("secret_id_num_uses cannot be negative"), nil - } - - if secretIDTTLRaw, ok := data.GetOk("secret_id_ttl"); ok { - role.SecretIDTTL = time.Second * time.Duration(secretIDTTLRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.SecretIDTTL = time.Second * time.Duration(data.Get("secret_id_ttl").(int)) - } - - if tokenNumUsesRaw, ok := data.GetOk("token_num_uses"); ok { - role.TokenNumUses = tokenNumUsesRaw.(int) - } else if req.Operation == logical.CreateOperation { - role.TokenNumUses = data.Get("token_num_uses").(int) - } - if role.TokenNumUses < 0 { - return logical.ErrorResponse("token_num_uses cannot be negative"), nil - } - - if tokenTTLRaw, ok := data.GetOk("token_ttl"); ok { - role.TokenTTL = time.Second * time.Duration(tokenTTLRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.TokenTTL = time.Second * time.Duration(data.Get("token_ttl").(int)) - } - - if tokenMaxTTLRaw, ok := data.GetOk("token_max_ttl"); ok { - role.TokenMaxTTL = time.Second * time.Duration(tokenMaxTTLRaw.(int)) - } else if req.Operation == logical.CreateOperation { - role.TokenMaxTTL = time.Second * time.Duration(data.Get("token_max_ttl").(int)) - } - - // Check that the TokenTTL value provided is less than the TokenMaxTTL. - // Sanitizing the TTL and MaxTTL is not required now and can be performed - // at credential issue time. - if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL { - return logical.ErrorResponse("token_ttl should not be greater than token_max_ttl"), nil - } - - var resp *logical.Response - if role.TokenMaxTTL > b.System().MaxLeaseTTL() { - resp = &logical.Response{} - resp.AddWarning("token_max_ttl is greater than the backend mount's maximum TTL value; issued tokens' max TTL value will be truncated") - } - - // Store the entry. - return resp, b.setRoleEntry(ctx, req.Storage, role.name, role, previousRoleID) -} - -// pathRoleRead grabs a read lock and reads the options set on the role from the storage -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - lockRelease := lock.RUnlock - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - lockRelease() - return nil, err - } - - if role == nil { - lockRelease() - return nil, nil - } - - respData := map[string]interface{}{ - "bind_secret_id": role.BindSecretID, - // TODO - remove this deprecated field in future versions, - // and its associated warning below. - "bound_cidr_list": role.SecretIDBoundCIDRs, - "secret_id_bound_cidrs": role.SecretIDBoundCIDRs, - "token_bound_cidrs": role.TokenBoundCIDRs, - "period": role.Period / time.Second, - "policies": role.Policies, - "secret_id_num_uses": role.SecretIDNumUses, - "secret_id_ttl": role.SecretIDTTL / time.Second, - "token_max_ttl": role.TokenMaxTTL / time.Second, - "token_num_uses": role.TokenNumUses, - "token_ttl": role.TokenTTL / time.Second, - "local_secret_ids": false, - } - - if role.SecretIDPrefix == secretIDLocalPrefix { - respData["local_secret_ids"] = true - } - - resp := &logical.Response{ - Data: respData, - } - - if err := validateRoleConstraints(role); err != nil { - resp.AddWarning("Role does not have any constraints set on it. Updates to this role will require a constraint to be set") - } - resp.AddWarning(`The "bound_cidr_list" parameter is deprecated and will be removed in favor of "secret_id_bound_cidrs".`) - - // For sanity, verify that the index still exists. If the index is missing, - // add one and return a warning so it can be reported. - roleIDIndex, err := b.roleIDEntry(ctx, req.Storage, role.RoleID) - if err != nil { - lockRelease() - return nil, err - } - - if roleIDIndex == nil { - // Switch to a write lock - lock.RUnlock() - lock.Lock() - lockRelease = lock.Unlock - - // Check again if the index is missing - roleIDIndex, err = b.roleIDEntry(ctx, req.Storage, role.RoleID) - if err != nil { - lockRelease() - return nil, err - } - - if roleIDIndex == nil { - // Create a new index - err = b.setRoleIDEntry(ctx, req.Storage, role.RoleID, &roleIDStorageEntry{ - Name: role.name, - }) - if err != nil { - lockRelease() - return nil, errwrap.Wrapf(fmt.Sprintf("failed to create secondary index for role_id %q: {{err}}", role.RoleID), err) - } - resp.AddWarning("Role identifier was missing an index back to role name. A new index has been added. Please report this observation.") - } - } - - lockRelease() - - return resp, nil -} - -// pathRoleDelete removes the role from the storage -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Just before the role is deleted, remove all the SecretIDs issued as part of the role. - if err = b.flushRoleSecrets(ctx, req.Storage, role.name, role.HMACKey, role.SecretIDPrefix); err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to invalidate the secrets belonging to role %q: {{err}}", role.name), err) - } - - // Delete the reverse mapping from RoleID to the role - if err = b.roleIDEntryDelete(ctx, req.Storage, role.RoleID); err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to delete the mapping from RoleID to role %q: {{err}}", role.name), err) - } - - // After deleting the SecretIDs and the RoleID, delete the role itself - if err = req.Storage.Delete(ctx, "role/"+strings.ToLower(role.name)); err != nil { - return nil, err - } - - return nil, nil -} - -// Returns the properties of the SecretID -func (b *backend) pathRoleSecretIDLookupUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - secretID := data.Get("secret_id").(string) - if secretID == "" { - return logical.ErrorResponse("missing secret_id"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - // Fetch the role - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("role %q does not exist", roleName) - } - - // Create the HMAC of the secret ID using the per-role HMAC key - secretIDHMAC, err := createHMAC(role.HMACKey, secretID) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) - } - - // Create the HMAC of the roleName using the per-role HMAC key - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - // Create the index at which the secret_id would've been stored - entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - - secretLock := b.secretIDLock(secretIDHMAC) - secretLock.Lock() - defer secretLock.Unlock() - - secretIDEntry, err := b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if secretIDEntry == nil { - return nil, nil - } - - // If a secret ID entry does not have a corresponding accessor - // entry, revoke the secret ID immediately - accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, secretIDEntry.SecretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to read secret ID accessor entry: {{err}}", err) - } - if accessorEntry == nil { - if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error deleting secret ID %q from storage: {{err}}", secretIDHMAC), err) - } - return logical.ErrorResponse("invalid secret id"), nil - } - - return &logical.Response{ - Data: secretIDEntry.ToResponseData(), - }, nil -} - -func (entry *secretIDStorageEntry) ToResponseData() map[string]interface{} { - return map[string]interface{}{ - "secret_id_accessor": entry.SecretIDAccessor, - "secret_id_num_uses": entry.SecretIDNumUses, - "secret_id_ttl": entry.SecretIDTTL / time.Second, - "creation_time": entry.CreationTime, - "expiration_time": entry.ExpirationTime, - "last_updated_time": entry.LastUpdatedTime, - "metadata": entry.Metadata, - "cidr_list": entry.CIDRList, - "token_bound_cidrs": entry.TokenBoundCIDRs, - } -} - -func (b *backend) pathRoleSecretIDDestroyUpdateDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - secretID := data.Get("secret_id").(string) - if secretID == "" { - return logical.ErrorResponse("missing secret_id"), nil - } - - roleLock := b.roleLock(roleName) - roleLock.RLock() - defer roleLock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("role %q does not exist", roleName) - } - - secretIDHMAC, err := createHMAC(role.HMACKey, secretID) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err) - } - - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - - lock := b.secretIDLock(secretIDHMAC) - lock.Lock() - defer lock.Unlock() - - entry, err := b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - // Delete the accessor of the SecretID first - if err := b.deleteSecretIDAccessorEntry(ctx, req.Storage, entry.SecretIDAccessor, role.SecretIDPrefix); err != nil { - return nil, err - } - - // Delete the storage entry that corresponds to the SecretID - if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, errwrap.Wrapf("failed to delete secret_id: {{err}}", err) - } - - return nil, nil -} - -// pathRoleSecretIDAccessorLookupUpdate returns the properties of the SecretID -// given its accessor -func (b *backend) pathRoleSecretIDAccessorLookupUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - secretIDAccessor := data.Get("secret_id_accessor").(string) - if secretIDAccessor == "" { - return logical.ErrorResponse("missing secret_id_accessor"), nil - } - - // SecretID is indexed based on HMACed roleName and HMACed SecretID. - // Get the role details to fetch the RoleID and accessor to get - // the HMACed SecretID. - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("role %q does not exist", roleName) - } - - accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, secretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, err - } - if accessorEntry == nil { - return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q", secretIDAccessor) - } - - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - secretLock := b.secretIDLock(accessorEntry.SecretIDHMAC) - secretLock.RLock() - defer secretLock.RUnlock() - - secretIDEntry, err := b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, accessorEntry.SecretIDHMAC) - if err != nil { - return nil, err - } - if secretIDEntry == nil { - return nil, nil - } - - return &logical.Response{ - Data: secretIDEntry.ToResponseData(), - }, nil -} - -func (b *backend) pathRoleSecretIDAccessorDestroyUpdateDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - secretIDAccessor := data.Get("secret_id_accessor").(string) - if secretIDAccessor == "" { - return logical.ErrorResponse("missing secret_id_accessor"), nil - } - - // SecretID is indexed based on HMACed roleName and HMACed SecretID. - // Get the role details to fetch the RoleID and accessor to get - // the HMACed SecretID. - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("role %q does not exist", roleName) - } - - accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, secretIDAccessor, role.SecretIDPrefix) - if err != nil { - return nil, err - } - if accessorEntry == nil { - return nil, fmt.Errorf("failed to find accessor entry for secret_id_accessor: %q", secretIDAccessor) - } - - roleNameHMAC, err := createHMAC(role.HMACKey, role.name) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, accessorEntry.SecretIDHMAC) - - lock := b.secretIDLock(accessorEntry.SecretIDHMAC) - lock.Lock() - defer lock.Unlock() - - // Delete the accessor of the SecretID first - if err := b.deleteSecretIDAccessorEntry(ctx, req.Storage, secretIDAccessor, role.SecretIDPrefix); err != nil { - return nil, err - } - - // Delete the storage entry that corresponds to the SecretID - if err := req.Storage.Delete(ctx, entryIndex); err != nil { - return nil, errwrap.Wrapf("failed to delete secret_id: {{err}}", err) - } - - return nil, nil -} - -func (b *backend) pathRoleBoundCIDRUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - // Re-read the role after grabbing the lock - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - var cidrs []string - if cidrsIfc, ok := data.GetFirst("secret_id_bound_cidrs", "bound_cidr_list"); ok { - cidrs = cidrsIfc.([]string) - role.SecretIDBoundCIDRs = cidrs - } else if cidrsIfc, ok := data.GetOk("token_bound_cidrs"); ok { - cidrs = cidrsIfc.([]string) - role.TokenBoundCIDRs = cidrs - } - if len(cidrs) == 0 { - return logical.ErrorResponse("missing bound_cidr_list"), nil - } - valid, err := cidrutil.ValidateCIDRListSlice(cidrs) - if err != nil { - return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("failed to validate CIDR blocks"), nil - } - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleSecretIDBoundCIDRRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleFieldRead(ctx, req, data, "secret_id_bound_cidrs") -} - -func (b *backend) pathRoleTokenBoundCIDRRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleFieldRead(ctx, req, data, "token_bound_cidrs") -} - -func (b *backend) pathRoleBoundCIDRListRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleFieldRead(ctx, req, data, "bound_cidr_list") -} - -func (b *backend) pathRoleFieldRead(ctx context.Context, req *logical.Request, data *framework.FieldData, fieldName string) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } else { - switch fieldName { - case "secret_id_bound_cidrs": - return &logical.Response{ - Data: map[string]interface{}{ - "secret_id_bound_cidrs": role.SecretIDBoundCIDRs, - }, - }, nil - case "token_bound_cidrs": - return &logical.Response{ - Data: map[string]interface{}{ - "token_bound_cidrs": role.TokenBoundCIDRs, - }, - }, nil - case "bound_cidr_list": - resp := &logical.Response{ - Data: map[string]interface{}{ - "bound_cidr_list": role.BoundCIDRList, - }, - } - resp.AddWarning(`The "bound_cidr_list" parameter is deprecated and will be removed. Please use "secret_id_bound_cidrs" instead.`) - return resp, nil - default: - // shouldn't occur IRL - return nil, errors.New("unrecognized field provided: " + fieldName) - } - } -} - -func (b *backend) pathRoleBoundCIDRDelete(ctx context.Context, req *logical.Request, data *framework.FieldData, fieldName string) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Deleting a field implies setting the value to it's default value. - switch fieldName { - case "bound_cidr_list": - role.BoundCIDRList = data.GetDefaultOrZero("bound_cidr_list").([]string) - case "secret_id_bound_cidrs": - role.SecretIDBoundCIDRs = data.GetDefaultOrZero("secret_id_bound_cidrs").([]string) - case "token_bound_cidrs": - role.TokenBoundCIDRs = data.GetDefaultOrZero("token_bound_cidrs").([]string) - } - return nil, b.setRoleEntry(ctx, req.Storage, roleName, role, "") -} - -func (b *backend) pathRoleBoundCIDRListDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleBoundCIDRDelete(ctx, req, data, "bound_cidr_list") -} - -func (b *backend) pathRoleSecretIDBoundCIDRDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleBoundCIDRDelete(ctx, req, data, "secret_id_bound_cidrs") -} - -func (b *backend) pathRoleTokenBoundCIDRDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.pathRoleBoundCIDRDelete(ctx, req, data, "token_bound_cidrs") -} - -func (b *backend) pathRoleBindSecretIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if bindSecretIDRaw, ok := data.GetOk("bind_secret_id"); ok { - role.BindSecretID = bindSecretIDRaw.(bool) - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing bind_secret_id"), nil - } -} - -func (b *backend) pathRoleBindSecretIDRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "bind_secret_id": role.BindSecretID, - }, - }, nil -} - -func (b *backend) pathRoleBindSecretIDDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Deleting a field implies setting the value to it's default value. - role.BindSecretID = data.GetDefaultOrZero("bind_secret_id").(bool) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleLocalSecretIDsRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - localSecretIDs := false - if role.SecretIDPrefix == secretIDLocalPrefix { - localSecretIDs = true - } - - return &logical.Response{ - Data: map[string]interface{}{ - "local_secret_ids": localSecretIDs, - }, - }, nil -} - -func (b *backend) pathRolePoliciesUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - policiesRaw, ok := data.GetOk("policies") - if !ok { - return logical.ErrorResponse("missing policies"), nil - } - - role.Policies = policyutil.ParsePolicies(policiesRaw) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRolePoliciesRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "policies": role.Policies, - }, - }, nil -} - -func (b *backend) pathRolePoliciesDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.Policies = []string{} - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleSecretIDNumUsesUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if numUsesRaw, ok := data.GetOk("secret_id_num_uses"); ok { - role.SecretIDNumUses = numUsesRaw.(int) - if role.SecretIDNumUses < 0 { - return logical.ErrorResponse("secret_id_num_uses cannot be negative"), nil - } - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing secret_id_num_uses"), nil - } -} - -func (b *backend) pathRoleRoleIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - previousRoleID := role.RoleID - role.RoleID = data.Get("role_id").(string) - if role.RoleID == "" { - return logical.ErrorResponse("missing role_id"), nil - } - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, previousRoleID) -} - -func (b *backend) pathRoleRoleIDRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "role_id": role.RoleID, - }, - }, nil -} - -func (b *backend) pathRoleSecretIDNumUsesRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "secret_id_num_uses": role.SecretIDNumUses, - }, - }, nil -} - -func (b *backend) pathRoleSecretIDNumUsesDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.SecretIDNumUses = data.GetDefaultOrZero("secret_id_num_uses").(int) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleSecretIDTTLUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if secretIDTTLRaw, ok := data.GetOk("secret_id_ttl"); ok { - role.SecretIDTTL = time.Second * time.Duration(secretIDTTLRaw.(int)) - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing secret_id_ttl"), nil - } -} - -func (b *backend) pathRoleSecretIDTTLRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "secret_id_ttl": role.SecretIDTTL / time.Second, - }, - }, nil -} - -func (b *backend) pathRoleSecretIDTTLDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.SecretIDTTL = time.Second * time.Duration(data.GetDefaultOrZero("secret_id_ttl").(int)) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRolePeriodUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if periodRaw, ok := data.GetOk("period"); ok { - role.Period = time.Second * time.Duration(periodRaw.(int)) - if role.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("period of %q is greater than the backend's maximum lease TTL of %q", role.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing period"), nil - } -} - -func (b *backend) pathRolePeriodRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "period": role.Period / time.Second, - }, - }, nil -} - -func (b *backend) pathRolePeriodDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.Period = time.Second * time.Duration(data.GetDefaultOrZero("period").(int)) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleTokenNumUsesUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if tokenNumUsesRaw, ok := data.GetOk("token_num_uses"); ok { - role.TokenNumUses = tokenNumUsesRaw.(int) - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing token_num_uses"), nil - } -} - -func (b *backend) pathRoleTokenNumUsesRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "token_num_uses": role.TokenNumUses, - }, - }, nil -} - -func (b *backend) pathRoleTokenNumUsesDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.TokenNumUses = data.GetDefaultOrZero("token_num_uses").(int) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleTokenTTLUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if tokenTTLRaw, ok := data.GetOk("token_ttl"); ok { - role.TokenTTL = time.Second * time.Duration(tokenTTLRaw.(int)) - if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL { - return logical.ErrorResponse("token_ttl should not be greater than token_max_ttl"), nil - } - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing token_ttl"), nil - } -} - -func (b *backend) pathRoleTokenTTLRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "token_ttl": role.TokenTTL / time.Second, - }, - }, nil -} - -func (b *backend) pathRoleTokenTTLDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.TokenTTL = time.Second * time.Duration(data.GetDefaultOrZero("token_ttl").(int)) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleTokenMaxTTLUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, logical.ErrUnsupportedPath - } - - if tokenMaxTTLRaw, ok := data.GetOk("token_max_ttl"); ok { - role.TokenMaxTTL = time.Second * time.Duration(tokenMaxTTLRaw.(int)) - if role.TokenMaxTTL > time.Duration(0) && role.TokenTTL > role.TokenMaxTTL { - return logical.ErrorResponse("token_max_ttl should be greater than or equal to token_ttl"), nil - } - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") - } else { - return logical.ErrorResponse("missing token_max_ttl"), nil - } -} - -func (b *backend) pathRoleTokenMaxTTLRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "token_max_ttl": role.TokenMaxTTL / time.Second, - }, - }, nil -} - -func (b *backend) pathRoleTokenMaxTTLDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - lock := b.roleLock(roleName) - lock.Lock() - defer lock.Unlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - role.TokenMaxTTL = time.Second * time.Duration(data.GetDefaultOrZero("token_max_ttl").(int)) - - return nil, b.setRoleEntry(ctx, req.Storage, role.name, role, "") -} - -func (b *backend) pathRoleSecretIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - secretID, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to generate secret_id: {{err}}", err) - } - return b.handleRoleSecretIDCommon(ctx, req, data, secretID) -} - -func (b *backend) pathRoleCustomSecretIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRoleSecretIDCommon(ctx, req, data, data.Get("secret_id").(string)) -} - -func (b *backend) handleRoleSecretIDCommon(ctx context.Context, req *logical.Request, data *framework.FieldData, secretID string) (*logical.Response, error) { - roleName := data.Get("role_name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role_name"), nil - } - - if secretID == "" { - return logical.ErrorResponse("missing secret_id"), nil - } - - lock := b.roleLock(roleName) - lock.RLock() - defer lock.RUnlock() - - role, err := b.roleEntry(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("role %q does not exist", roleName)), logical.ErrUnsupportedPath - } - - if !role.BindSecretID { - return logical.ErrorResponse("bind_secret_id is not set on the role"), nil - } - - secretIDCIDRs := data.Get("cidr_list").([]string) - - // Validate the list of CIDR blocks - if len(secretIDCIDRs) != 0 { - valid, err := cidrutil.ValidateCIDRListSlice(secretIDCIDRs) - if err != nil { - return nil, errwrap.Wrapf("failed to validate CIDR blocks: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("failed to validate CIDR blocks"), nil - } - } - // Ensure that the CIDRs on the secret ID are a subset of that of role's - if err := verifyCIDRRoleSecretIDSubset(secretIDCIDRs, role.SecretIDBoundCIDRs); err != nil { - return nil, err - } - - secretIDTokenCIDRs := data.Get("token_bound_cidrs").([]string) - if len(secretIDTokenCIDRs) != 0 { - valid, err := cidrutil.ValidateCIDRListSlice(secretIDTokenCIDRs) - if err != nil { - return nil, errwrap.Wrapf("failed to validate token CIDR blocks: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("failed to validate token CIDR blocks"), nil - } - } - // Ensure that the token CIDRs on the secret ID are a subset of that of role's - if err := verifyCIDRRoleSecretIDSubset(secretIDTokenCIDRs, role.TokenBoundCIDRs); err != nil { - return nil, err - } - - secretIDStorage := &secretIDStorageEntry{ - SecretIDNumUses: role.SecretIDNumUses, - SecretIDTTL: role.SecretIDTTL, - Metadata: make(map[string]string), - CIDRList: secretIDCIDRs, - TokenBoundCIDRs: secretIDTokenCIDRs, - } - - if err = strutil.ParseArbitraryKeyValues(data.Get("metadata").(string), secretIDStorage.Metadata, ","); err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil - } - - if secretIDStorage, err = b.registerSecretIDEntry(ctx, req.Storage, role.name, secretID, role.HMACKey, role.SecretIDPrefix, secretIDStorage); err != nil { - return nil, errwrap.Wrapf("failed to store secret_id: {{err}}", err) - } - - return &logical.Response{ - Data: map[string]interface{}{ - "secret_id": secretID, - "secret_id_accessor": secretIDStorage.SecretIDAccessor, - }, - }, nil -} - -func (b *backend) roleIDLock(roleID string) *locksutil.LockEntry { - return locksutil.LockForKey(b.roleIDLocks, roleID) -} - -func (b *backend) roleLock(roleName string) *locksutil.LockEntry { - return locksutil.LockForKey(b.roleLocks, strings.ToLower(roleName)) -} - -// setRoleIDEntry creates a storage entry that maps RoleID to Role -func (b *backend) setRoleIDEntry(ctx context.Context, s logical.Storage, roleID string, roleIDEntry *roleIDStorageEntry) error { - lock := b.roleIDLock(roleID) - lock.Lock() - defer lock.Unlock() - - salt, err := b.Salt(ctx) - if err != nil { - return err - } - entryIndex := "role_id/" + salt.SaltID(roleID) - - entry, err := logical.StorageEntryJSON(entryIndex, roleIDEntry) - if err != nil { - return err - } - if err = s.Put(ctx, entry); err != nil { - return err - } - return nil -} - -// roleIDEntry is used to read the storage entry that maps RoleID to Role -func (b *backend) roleIDEntry(ctx context.Context, s logical.Storage, roleID string) (*roleIDStorageEntry, error) { - if roleID == "" { - return nil, fmt.Errorf("missing role id") - } - - lock := b.roleIDLock(roleID) - lock.RLock() - defer lock.RUnlock() - - var result roleIDStorageEntry - - salt, err := b.Salt(ctx) - if err != nil { - return nil, err - } - entryIndex := "role_id/" + salt.SaltID(roleID) - - if entry, err := s.Get(ctx, entryIndex); err != nil { - return nil, err - } else if entry == nil { - return nil, nil - } else if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// roleIDEntryDelete is used to remove the secondary index that maps the -// RoleID to the Role itself. -func (b *backend) roleIDEntryDelete(ctx context.Context, s logical.Storage, roleID string) error { - if roleID == "" { - return fmt.Errorf("missing role id") - } - - lock := b.roleIDLock(roleID) - lock.Lock() - defer lock.Unlock() - - salt, err := b.Salt(ctx) - if err != nil { - return err - } - entryIndex := "role_id/" + salt.SaltID(roleID) - - return s.Delete(ctx, entryIndex) -} - -var roleHelp = map[string][2]string{ - "role-list": { - "Lists all the roles registered with the backend.", - "The list will contain the names of the roles.", - }, - "role": { - "Register an role with the backend.", - `A role can represent a service, a machine or anything that can be IDed. -The set of policies on the role defines access to the role, meaning, any -Vault token with a policy set that is a superset of the policies on the -role registered here will have access to the role. If a SecretID is desired -to be generated against only this specific role, it can be done via -'role//secret-id' and 'role//custom-secret-id' endpoints. -The properties of the SecretID created against the role and the properties -of the token issued with the SecretID generated against the role, can be -configured using the parameters of this endpoint.`, - }, - "role-bind-secret-id": { - "Impose secret_id to be presented during login using this role.", - `By setting this to 'true', during login the parameter 'secret_id' becomes a mandatory argument. -The value of 'secret_id' can be retrieved using 'role//secret-id' endpoint.`, - }, - "role-bound-cidr-list": { - `Deprecated: Comma separated list of CIDR blocks, if set, specifies blocks of IP -addresses which can perform the login operation`, - `During login, the IP address of the client will be checked to see if it -belongs to the CIDR blocks specified. If CIDR blocks were set and if the -IP is not encompassed by it, login fails`, - }, - "secret-id-bound-cidrs": { - `Comma separated list of CIDR blocks, if set, specifies blocks of IP -addresses which can perform the login operation`, - `During login, the IP address of the client will be checked to see if it -belongs to the CIDR blocks specified. If CIDR blocks were set and if the -IP is not encompassed by it, login fails`, - }, - "token-bound-cidrs": { - `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can use the returned token.`, - `During use of the returned token, the IP address of the client will be checked to see if it -belongs to the CIDR blocks specified. If CIDR blocks were set and if the -IP is not encompassed by it, token use fails`, - }, - "role-policies": { - "Policies of the role.", - `A comma-delimited set of Vault policies that defines access to the role. -All the Vault tokens with policies that encompass the policy set -defined on the role, can access the role.`, - }, - "role-secret-id-num-uses": { - "Use limit of the SecretID generated against the role.", - `If the SecretIDs are generated/assigned against the role using the -'role//secret-id' or 'role//custom-secret-id' endpoints, -then the number of times that SecretID can access the role is defined by -this option.`, - }, - "role-secret-id-ttl": { - `Duration in seconds, representing the lifetime of the SecretIDs -that are generated against the role using 'role//secret-id' or -'role//custom-secret-id' endpoints.`, - ``, - }, - "role-secret-id-lookup": { - "Read the properties of an issued secret_id", - `This endpoint is used to read the properties of a secret_id associated to a -role.`}, - "role-secret-id-destroy": { - "Invalidate an issued secret_id", - `This endpoint is used to delete the properties of a secret_id associated to a -role.`}, - "role-secret-id-accessor-lookup": { - "Read an issued secret_id, using its accessor", - `This is particularly useful to lookup the non-expiring 'secret_id's. -The list operation on the 'role//secret-id' endpoint will return -the 'secret_id_accessor's. This endpoint can be used to read the properties -of the secret. If the 'secret_id_num_uses' field in the response is 0, it -represents a non-expiring 'secret_id'.`, - }, - "role-secret-id-accessor-destroy": { - "Delete an issued secret_id, using its accessor", - `This is particularly useful to clean-up the non-expiring 'secret_id's. -The list operation on the 'role//secret-id' endpoint will return -the 'secret_id_accessor's. This endpoint can be used to read the properties -of the secret. If the 'secret_id_num_uses' field in the response is 0, it -represents a non-expiring 'secret_id'.`, - }, - "role-token-num-uses": { - "Number of times issued tokens can be used", - `By default, this will be set to zero, indicating that the issued -tokens can be used any number of times.`, - }, - "role-token-ttl": { - `Duration in seconds, the lifetime of the token issued by using the SecretID that -is generated against this role, before which the token needs to be renewed.`, - `If SecretIDs are generated against the role, using 'role//secret-id' or the -'role//custom-secret-id' endpoints, and if those SecretIDs are used -to perform the login operation, then the value of 'token-ttl' defines the -lifetime of the token issued, before which the token needs to be renewed.`, - }, - "role-token-max-ttl": { - `Duration in seconds, the maximum lifetime of the tokens issued by using -the SecretIDs that were generated against this role, after which the -tokens are not allowed to be renewed.`, - `If SecretIDs are generated against the role using 'role//secret-id' -or the 'role//custom-secret-id' endpoints, and if those SecretIDs -are used to perform the login operation, then the value of 'token-max-ttl' -defines the maximum lifetime of the tokens issued, after which the tokens -cannot be renewed. A reauthentication is required after this duration. -This value will be capped by the backend mount's maximum TTL value.`, - }, - "role-id": { - "Returns the 'role_id' of the role.", - `If login is performed from an role, then its 'role_id' should be presented -as a credential during the login. This 'role_id' can be retrieved using -this endpoint.`, - }, - "role-secret-id": { - "Generate a SecretID against this role.", - `The SecretID generated using this endpoint will be scoped to access -just this role and none else. The properties of this SecretID will be -based on the options set on the role. It will expire after a period -defined by the 'secret_id_ttl' option on the role and/or the backend -mount's maximum TTL value.`, - }, - "role-custom-secret-id": { - "Assign a SecretID of choice against the role.", - `This option is not recommended unless there is a specific need -to do so. This will assign a client supplied SecretID to be used to access -the role. This SecretID will behave similarly to the SecretIDs generated by -the backend. The properties of this SecretID will be based on the options -set on the role. It will expire after a period defined by the 'secret_id_ttl' -option on the role and/or the backend mount's maximum TTL value.`, - }, - "role-period": { - "Updates the value of 'period' on the role", - `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. The renewal duration will -be fixed. If the Period in the role is modified, the token -will pick up the new value during its next renewal.`, - }, - "role-local-secret-ids": { - "Enables cluster local secret IDs", - `If set, the secret IDs generated using this role will be cluster local. -This can only be set during role creation and once set, it can't be -reset later.`, - }, -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_tidy_user_id.go b/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_tidy_user_id.go deleted file mode 100644 index 5bdd12640..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/approle/path_tidy_user_id.go +++ /dev/null @@ -1,246 +0,0 @@ -package approle - -import ( - "context" - "fmt" - "net/http" - "sync/atomic" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathTidySecretID(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "tidy/secret-id$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathTidySecretIDUpdate, - }, - - HelpSynopsis: pathTidySecretIDSyn, - HelpDescription: pathTidySecretIDDesc, - } -} - -// tidySecretID is used to delete entries in the whitelist that are expired. -func (b *backend) tidySecretID(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if !atomic.CompareAndSwapUint32(b.tidySecretIDCASGuard, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - s := req.Storage - - go func() { - defer atomic.StoreUint32(b.tidySecretIDCASGuard, 0) - - logger := b.Logger().Named("tidy") - - checkCount := 0 - - defer func() { - if b.testTidyDelay > 0 { - logger.Trace("done checking entries", "num_entries", checkCount) - } - }() - - // Don't cancel when the original client request goes away - ctx = context.Background() - - tidyFunc := func(secretIDPrefixToUse, accessorIDPrefixToUse string) error { - logger.Trace("listing role HMACs", "prefix", secretIDPrefixToUse) - - roleNameHMACs, err := s.List(ctx, secretIDPrefixToUse) - if err != nil { - return err - } - - logger.Trace("listing accessors", "prefix", accessorIDPrefixToUse) - - // List all the accessors and add them all to a map - accessorHashes, err := s.List(ctx, accessorIDPrefixToUse) - if err != nil { - return err - } - accessorMap := make(map[string]bool, len(accessorHashes)) - for _, accessorHash := range accessorHashes { - accessorMap[accessorHash] = true - } - - time.Sleep(b.testTidyDelay) - - secretIDCleanupFunc := func(secretIDHMAC, roleNameHMAC, secretIDPrefixToUse string) error { - checkCount++ - lock := b.secretIDLock(secretIDHMAC) - lock.Lock() - defer lock.Unlock() - - entryIndex := fmt.Sprintf("%s%s%s", secretIDPrefixToUse, roleNameHMAC, secretIDHMAC) - secretIDEntry, err := s.Get(ctx, entryIndex) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching SecretID %q: {{err}}", secretIDHMAC), err) - } - - if secretIDEntry == nil { - logger.Error("entry for secret id was nil", "secret_id_hmac", secretIDHMAC) - return nil - } - - if secretIDEntry.Value == nil || len(secretIDEntry.Value) == 0 { - return fmt.Errorf("found entry for SecretID %q but actual SecretID is empty", secretIDHMAC) - } - - var result secretIDStorageEntry - if err := secretIDEntry.DecodeJSON(&result); err != nil { - return err - } - - // If a secret ID entry does not have a corresponding accessor - // entry, revoke the secret ID immediately - accessorEntry, err := b.secretIDAccessorEntry(ctx, s, result.SecretIDAccessor, secretIDPrefixToUse) - if err != nil { - return errwrap.Wrapf("failed to read secret ID accessor entry: {{err}}", err) - } - if accessorEntry == nil { - logger.Trace("found nil accessor") - if err := s.Delete(ctx, entryIndex); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting secret ID %q from storage: {{err}}", secretIDHMAC), err) - } - return nil - } - - // ExpirationTime not being set indicates non-expiring SecretIDs - if !result.ExpirationTime.IsZero() && time.Now().After(result.ExpirationTime) { - logger.Trace("found expired secret ID") - // Clean up the accessor of the secret ID first - err = b.deleteSecretIDAccessorEntry(ctx, s, result.SecretIDAccessor, secretIDPrefixToUse) - if err != nil { - return errwrap.Wrapf("failed to delete secret ID accessor entry: {{err}}", err) - } - - if err := s.Delete(ctx, entryIndex); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting SecretID %q from storage: {{err}}", secretIDHMAC), err) - } - - return nil - } - - // At this point, the secret ID is not expired and is valid. Delete - // the corresponding accessor from the accessorMap. This will leave - // only the dangling accessors in the map which can then be cleaned - // up later. - salt, err := b.Salt(ctx) - if err != nil { - return err - } - delete(accessorMap, salt.SaltID(result.SecretIDAccessor)) - - return nil - } - - for _, roleNameHMAC := range roleNameHMACs { - logger.Trace("listing secret ID HMACs", "role_hmac", roleNameHMAC) - secretIDHMACs, err := s.List(ctx, fmt.Sprintf("%s%s", secretIDPrefixToUse, roleNameHMAC)) - if err != nil { - return err - } - for _, secretIDHMAC := range secretIDHMACs { - err = secretIDCleanupFunc(secretIDHMAC, roleNameHMAC, secretIDPrefixToUse) - if err != nil { - return err - } - } - } - - // Accessor indexes were not getting cleaned up until 0.9.3. This is a fix - // to clean up the dangling accessor entries. - if len(accessorMap) > 0 { - for _, lock := range b.secretIDLocks { - lock.Lock() - defer lock.Unlock() - } - for accessorHash, _ := range accessorMap { - logger.Trace("found dangling accessor, verifying") - // Ideally, locking on accessors should be performed here too - // but for that, accessors are required in plaintext, which are - // not available. The code above helps but it may still be - // racy. - // ... - // Look up the secret again now that we have all the locks. The - // lock is held when writing accessor/secret so if we have the - // lock we know we're not in a - // wrote-accessor-but-not-yet-secret case, which can be racy. - var entry secretIDAccessorStorageEntry - entryIndex := accessorIDPrefixToUse + accessorHash - se, err := s.Get(ctx, entryIndex) - if err != nil { - return err - } - if se != nil { - err = se.DecodeJSON(&entry) - if err != nil { - return err - } - - // The storage entry doesn't store the role ID, so we have - // to go about this the long way; fortunately we shouldn't - // actually hit this very often - var found bool - searchloop: - for _, roleNameHMAC := range roleNameHMACs { - secretIDHMACs, err := s.List(ctx, fmt.Sprintf("%s%s", secretIDPrefixToUse, roleNameHMAC)) - if err != nil { - return err - } - for _, v := range secretIDHMACs { - if v == entry.SecretIDHMAC { - found = true - logger.Trace("accessor verified, not removing") - break searchloop - } - } - } - if !found { - logger.Trace("could not verify dangling accessor, removing") - err = s.Delete(ctx, entryIndex) - if err != nil { - return err - } - } - } - } - } - - return nil - } - - err := tidyFunc(secretIDPrefix, secretIDAccessorPrefix) - if err != nil { - logger.Error("error tidying global secret IDs", "error", err) - return - } - err = tidyFunc(secretIDLocalPrefix, secretIDAccessorLocalPrefix) - if err != nil { - logger.Error("error tidying local secret IDs", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -// pathTidySecretIDUpdate is used to delete the expired SecretID entries -func (b *backend) pathTidySecretIDUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.tidySecretID(ctx, req) -} - -const pathTidySecretIDSyn = "Trigger the clean-up of expired SecretID entries." -const pathTidySecretIDDesc = `SecretIDs will have expiration time attached to them. The periodic function -of the backend will look for expired entries and delete them. This happens once in a minute. Invoking -this endpoint will trigger the clean-up action, without waiting for the backend's periodic function.` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/approle/validation.go b/vendor/github.com/hashicorp/vault/builtin/credential/approle/validation.go deleted file mode 100644 index 99e9bddc3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/approle/validation.go +++ /dev/null @@ -1,390 +0,0 @@ -package approle - -import ( - "context" - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" -) - -// secretIDStorageEntry represents the information stored in storage -// when a SecretID is created. The structure of the SecretID storage -// entry is the same for all the types of SecretIDs generated. -type secretIDStorageEntry struct { - // Accessor for the SecretID. It is a random UUID serving as - // a secondary index for the SecretID. This uniquely identifies - // the SecretID it belongs to, and hence can be used for listing - // and deleting SecretIDs. Accessors cannot be used as valid - // SecretIDs during login. - SecretIDAccessor string `json:"secret_id_accessor" mapstructure:"secret_id_accessor"` - - // Number of times this SecretID can be used to perform the login - // operation - SecretIDNumUses int `json:"secret_id_num_uses" mapstructure:"secret_id_num_uses"` - - // Duration after which this SecretID should expire. This is capped by - // the backend mount's max TTL value. - SecretIDTTL time.Duration `json:"secret_id_ttl" mapstructure:"secret_id_ttl"` - - // The time when the SecretID was created - CreationTime time.Time `json:"creation_time" mapstructure:"creation_time"` - - // The time when the SecretID becomes eligible for tidy operation. - // Tidying is performed by the PeriodicFunc of the backend which is 1 - // minute apart. - ExpirationTime time.Time `json:"expiration_time" mapstructure:"expiration_time"` - - // The time representing the last time this storage entry was modified - LastUpdatedTime time.Time `json:"last_updated_time" mapstructure:"last_updated_time"` - - // Metadata that belongs to the SecretID - Metadata map[string]string `json:"metadata" mapstructure:"metadata"` - - // CIDRList is a set of CIDR blocks that impose source address - // restrictions on the usage of SecretID - CIDRList []string `json:"cidr_list" mapstructure:"cidr_list"` - - // TokenBoundCIDRs is a set of CIDR blocks that impose source address - // restrictions on the usage of the token generated by this SecretID - TokenBoundCIDRs []string `json:"token_cidr_list" mapstructure:"token_bound_cidrs"` - - // This is a deprecated field - SecretIDNumUsesDeprecated int `json:"SecretIDNumUses" mapstructure:"SecretIDNumUses"` -} - -// Represents the payload of the storage entry of the accessor that maps to a -// unique SecretID. Note that SecretIDs should never be stored in plaintext -// anywhere in the backend. SecretIDHMAC will be used as an index to fetch the -// properties of the SecretID and to delete the SecretID. -type secretIDAccessorStorageEntry struct { - // Hash of the SecretID which can be used to find the storage index at which - // properties of SecretID is stored. - SecretIDHMAC string `json:"secret_id_hmac" mapstructure:"secret_id_hmac"` -} - -// verifyCIDRRoleSecretIDSubset checks if the CIDR blocks set on the secret ID -// are a subset of CIDR blocks set on the role -func verifyCIDRRoleSecretIDSubset(secretIDCIDRs []string, roleBoundCIDRList []string) error { - if len(secretIDCIDRs) != 0 { - // If there are no CIDR blocks on the role, then the subset - // requirement would be satisfied - if len(roleBoundCIDRList) != 0 { - subset, err := cidrutil.SubsetBlocks(roleBoundCIDRList, secretIDCIDRs) - if !subset || err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to verify subset relationship between CIDR blocks on the role %q and CIDR blocks on the secret ID %q: {{err}}", roleBoundCIDRList, secretIDCIDRs), err) - } - } - } - - return nil -} - -// Creates a SHA256 HMAC of the given 'value' using the given 'key' and returns -// a hex encoded string. -func createHMAC(key, value string) (string, error) { - if key == "" { - return "", fmt.Errorf("invalid HMAC key") - } - hm := hmac.New(sha256.New, []byte(key)) - hm.Write([]byte(value)) - return hex.EncodeToString(hm.Sum(nil)), nil -} - -func (b *backend) secretIDLock(secretIDHMAC string) *locksutil.LockEntry { - return locksutil.LockForKey(b.secretIDLocks, secretIDHMAC) -} - -func (b *backend) secretIDAccessorLock(secretIDAccessor string) *locksutil.LockEntry { - return locksutil.LockForKey(b.secretIDAccessorLocks, secretIDAccessor) -} - -// nonLockedSecretIDStorageEntry fetches the secret ID properties from physical -// storage. The entry will be indexed based on the given HMACs of both role -// name and the secret ID. This method will not acquire secret ID lock to fetch -// the storage entry. Locks need to be acquired before calling this method. -func (b *backend) nonLockedSecretIDStorageEntry(ctx context.Context, s logical.Storage, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC string) (*secretIDStorageEntry, error) { - if secretIDHMAC == "" { - return nil, fmt.Errorf("missing secret ID HMAC") - } - - if roleNameHMAC == "" { - return nil, fmt.Errorf("missing role name HMAC") - } - - // Prepare the storage index at which the secret ID will be stored - entryIndex := fmt.Sprintf("%s%s/%s", roleSecretIDPrefix, roleNameHMAC, secretIDHMAC) - - entry, err := s.Get(ctx, entryIndex) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - result := secretIDStorageEntry{} - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - // TODO: Remove this upgrade bit in future releases - persistNeeded := false - if result.SecretIDNumUsesDeprecated != 0 { - if result.SecretIDNumUses == 0 || - result.SecretIDNumUsesDeprecated < result.SecretIDNumUses { - result.SecretIDNumUses = result.SecretIDNumUsesDeprecated - persistNeeded = true - } - if result.SecretIDNumUses < result.SecretIDNumUsesDeprecated { - result.SecretIDNumUsesDeprecated = result.SecretIDNumUses - persistNeeded = true - } - } - - if persistNeeded { - if err := b.nonLockedSetSecretIDStorageEntry(ctx, s, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC, &result); err != nil { - return nil, errwrap.Wrapf("failed to upgrade role storage entry {{err}}", err) - } - } - - return &result, nil -} - -// nonLockedSetSecretIDStorageEntry creates or updates a secret ID entry at the -// physical storage. The entry will be indexed based on the given HMACs of both -// role name and the secret ID. This method will not acquire secret ID lock to -// create/update the storage entry. Locks need to be acquired before calling -// this method. -func (b *backend) nonLockedSetSecretIDStorageEntry(ctx context.Context, s logical.Storage, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC string, secretEntry *secretIDStorageEntry) error { - if roleSecretIDPrefix == "" { - return fmt.Errorf("missing secret ID prefix") - } - if secretIDHMAC == "" { - return fmt.Errorf("missing secret ID HMAC") - } - - if roleNameHMAC == "" { - return fmt.Errorf("missing role name HMAC") - } - - if secretEntry == nil { - return fmt.Errorf("nil secret entry") - } - - entryIndex := fmt.Sprintf("%s%s/%s", roleSecretIDPrefix, roleNameHMAC, secretIDHMAC) - - if entry, err := logical.StorageEntryJSON(entryIndex, secretEntry); err != nil { - return err - } else if err = s.Put(ctx, entry); err != nil { - return err - } - - return nil -} - -// registerSecretIDEntry creates a new storage entry for the given SecretID. -func (b *backend) registerSecretIDEntry(ctx context.Context, s logical.Storage, roleName, secretID, hmacKey, roleSecretIDPrefix string, secretEntry *secretIDStorageEntry) (*secretIDStorageEntry, error) { - secretIDHMAC, err := createHMAC(hmacKey, secretID) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of secret ID: {{err}}", err) - } - roleNameHMAC, err := createHMAC(hmacKey, roleName) - if err != nil { - return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - lock := b.secretIDLock(secretIDHMAC) - lock.RLock() - - entry, err := b.nonLockedSecretIDStorageEntry(ctx, s, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - lock.RUnlock() - return nil, err - } - if entry != nil { - lock.RUnlock() - return nil, fmt.Errorf("SecretID is already registered") - } - - // If there isn't an entry for the secretID already, switch the read lock - // with a write lock and create an entry. - lock.RUnlock() - lock.Lock() - defer lock.Unlock() - - // But before saving a new entry, check if the secretID entry was created during the lock switch. - entry, err = b.nonLockedSecretIDStorageEntry(ctx, s, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err != nil { - return nil, err - } - if entry != nil { - return nil, fmt.Errorf("SecretID is already registered") - } - - // - // Create a new entry for the SecretID - // - - // Set the creation time for the SecretID - currentTime := time.Now() - secretEntry.CreationTime = currentTime - secretEntry.LastUpdatedTime = currentTime - - // If SecretIDTTL is not specified or if it crosses the backend mount's limit, - // cap the expiration to backend's max. Otherwise, use it to determine the - // expiration time. - if secretEntry.SecretIDTTL < time.Duration(0) || secretEntry.SecretIDTTL > b.System().MaxLeaseTTL() { - secretEntry.ExpirationTime = currentTime.Add(b.System().MaxLeaseTTL()) - } else if secretEntry.SecretIDTTL != time.Duration(0) { - // Set the ExpirationTime only if SecretIDTTL was set. SecretIDs should not - // expire by default. - secretEntry.ExpirationTime = currentTime.Add(secretEntry.SecretIDTTL) - } - - // Before storing the SecretID, store its accessor. - if err := b.createSecretIDAccessorEntry(ctx, s, secretEntry, secretIDHMAC, roleSecretIDPrefix); err != nil { - return nil, err - } - - if err := b.nonLockedSetSecretIDStorageEntry(ctx, s, roleSecretIDPrefix, roleNameHMAC, secretIDHMAC, secretEntry); err != nil { - return nil, err - } - - return secretEntry, nil -} - -// secretIDAccessorEntry is used to read the storage entry that maps an -// accessor to a secret_id. -func (b *backend) secretIDAccessorEntry(ctx context.Context, s logical.Storage, secretIDAccessor, roleSecretIDPrefix string) (*secretIDAccessorStorageEntry, error) { - if secretIDAccessor == "" { - return nil, fmt.Errorf("missing secretIDAccessor") - } - - var result secretIDAccessorStorageEntry - - // Create index entry, mapping the accessor to the token ID - salt, err := b.Salt(ctx) - if err != nil { - return nil, err - } - accessorPrefix := secretIDAccessorPrefix - if roleSecretIDPrefix == secretIDLocalPrefix { - accessorPrefix = secretIDAccessorLocalPrefix - } - entryIndex := accessorPrefix + salt.SaltID(secretIDAccessor) - - accessorLock := b.secretIDAccessorLock(secretIDAccessor) - accessorLock.RLock() - defer accessorLock.RUnlock() - - if entry, err := s.Get(ctx, entryIndex); err != nil { - return nil, err - } else if entry == nil { - return nil, nil - } else if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// createSecretIDAccessorEntry creates an identifier for the SecretID. A storage index, -// mapping the accessor to the SecretID is also created. This method should -// be called when the lock for the corresponding SecretID is held. -func (b *backend) createSecretIDAccessorEntry(ctx context.Context, s logical.Storage, entry *secretIDStorageEntry, secretIDHMAC, roleSecretIDPrefix string) error { - // Create a random accessor - accessorUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.SecretIDAccessor = accessorUUID - - // Create index entry, mapping the accessor to the token ID - salt, err := b.Salt(ctx) - if err != nil { - return err - } - - accessorPrefix := secretIDAccessorPrefix - if roleSecretIDPrefix == secretIDLocalPrefix { - accessorPrefix = secretIDAccessorLocalPrefix - } - entryIndex := accessorPrefix + salt.SaltID(entry.SecretIDAccessor) - - accessorLock := b.secretIDAccessorLock(accessorUUID) - accessorLock.Lock() - defer accessorLock.Unlock() - - if entry, err := logical.StorageEntryJSON(entryIndex, &secretIDAccessorStorageEntry{ - SecretIDHMAC: secretIDHMAC, - }); err != nil { - return err - } else if err = s.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) - } - - return nil -} - -// deleteSecretIDAccessorEntry deletes the storage index mapping the accessor to a SecretID. -func (b *backend) deleteSecretIDAccessorEntry(ctx context.Context, s logical.Storage, secretIDAccessor, roleSecretIDPrefix string) error { - salt, err := b.Salt(ctx) - if err != nil { - return err - } - - accessorPrefix := secretIDAccessorPrefix - if roleSecretIDPrefix == secretIDLocalPrefix { - accessorPrefix = secretIDAccessorLocalPrefix - } - entryIndex := accessorPrefix + salt.SaltID(secretIDAccessor) - - accessorLock := b.secretIDAccessorLock(secretIDAccessor) - accessorLock.Lock() - defer accessorLock.Unlock() - - // Delete the accessor of the SecretID first - if err := s.Delete(ctx, entryIndex); err != nil { - return errwrap.Wrapf("failed to delete accessor storage entry: {{err}}", err) - } - - return nil -} - -// flushRoleSecrets deletes all the SecretIDs that belong to the given -// RoleID. -func (b *backend) flushRoleSecrets(ctx context.Context, s logical.Storage, roleName, hmacKey, roleSecretIDPrefix string) error { - roleNameHMAC, err := createHMAC(hmacKey, roleName) - if err != nil { - return errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err) - } - - // Acquire the custom lock to perform listing of SecretIDs - b.secretIDListingLock.RLock() - defer b.secretIDListingLock.RUnlock() - - secretIDHMACs, err := s.List(ctx, fmt.Sprintf("%s%s/", roleSecretIDPrefix, roleNameHMAC)) - if err != nil { - return err - } - for _, secretIDHMAC := range secretIDHMACs { - // Acquire the lock belonging to the SecretID - lock := b.secretIDLock(secretIDHMAC) - lock.Lock() - entryIndex := fmt.Sprintf("%s%s/%s", roleSecretIDPrefix, roleNameHMAC, secretIDHMAC) - if err := s.Delete(ctx, entryIndex); err != nil { - lock.Unlock() - return errwrap.Wrapf(fmt.Sprintf("error deleting SecretID %q from storage: {{err}}", secretIDHMAC), err) - } - lock.Unlock() - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/backend.go deleted file mode 100644 index 1d4926819..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/backend.go +++ /dev/null @@ -1,311 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - "sync" - "time" - - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/patrickmn/go-cache" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b, err := Backend(conf) - if err != nil { - return nil, err - } - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -type backend struct { - *framework.Backend - - // Lock to make changes to any of the backend's configuration endpoints. - configMutex sync.RWMutex - - // Lock to make changes to role entries - roleMutex sync.RWMutex - - // Lock to make changes to the blacklist entries - blacklistMutex sync.RWMutex - - // Guards the blacklist/whitelist tidy functions - tidyBlacklistCASGuard *uint32 - tidyWhitelistCASGuard *uint32 - - // Duration after which the periodic function of the backend needs to - // tidy the blacklist and whitelist entries. - tidyCooldownPeriod time.Duration - - // nextTidyTime holds the time at which the periodic func should initiate - // the tidy operations. This is set by the periodicFunc based on the value - // of tidyCooldownPeriod. - nextTidyTime time.Time - - // Map to hold the EC2 client objects indexed by region and STS role. - // This avoids the overhead of creating a client object for every login request. - // When the credentials are modified or deleted, all the cached client objects - // will be flushed. The empty STS role signifies the master account - EC2ClientsMap map[string]map[string]*ec2.EC2 - - // Map to hold the IAM client objects indexed by region and STS role. - // This avoids the overhead of creating a client object for every login request. - // When the credentials are modified or deleted, all the cached client objects - // will be flushed. The empty STS role signifies the master account - IAMClientsMap map[string]map[string]*iam.IAM - - // Map of AWS unique IDs to the full ARN corresponding to that unique ID - // This avoids the overhead of an AWS API hit for every login request - // using the IAM auth method when bound_iam_principal_arn contains a wildcard - iamUserIdToArnCache *cache.Cache - - // AWS Account ID of the "default" AWS credentials - // This cache avoids the need to call GetCallerIdentity repeatedly to learn it - // We can't store this because, in certain pathological cases, it could change - // out from under us, such as a standby and active Vault server in different AWS - // accounts using their IAM instance profile to get their credentials. - defaultAWSAccountID string - - resolveArnToUniqueIDFunc func(context.Context, logical.Storage, string) (string, error) -} - -func Backend(conf *logical.BackendConfig) (*backend, error) { - b := &backend{ - // Setting the periodic func to be run once in an hour. - // If there is a real need, this can be made configurable. - tidyCooldownPeriod: time.Hour, - EC2ClientsMap: make(map[string]map[string]*ec2.EC2), - IAMClientsMap: make(map[string]map[string]*iam.IAM), - iamUserIdToArnCache: cache.New(7*24*time.Hour, 24*time.Hour), - tidyBlacklistCASGuard: new(uint32), - tidyWhitelistCASGuard: new(uint32), - } - - b.resolveArnToUniqueIDFunc = b.resolveArnToRealUniqueId - - b.Backend = &framework.Backend{ - PeriodicFunc: b.periodicFunc, - AuthRenew: b.pathLoginRenew, - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - LocalStorage: []string{ - "whitelist/identity/", - }, - SealWrapStorage: []string{ - "config/client", - }, - }, - Paths: []*framework.Path{ - pathLogin(b), - pathListRole(b), - pathListRoles(b), - pathRole(b), - pathRoleTag(b), - pathConfigClient(b), - pathConfigCertificate(b), - pathConfigSts(b), - pathListSts(b), - pathConfigTidyRoletagBlacklist(b), - pathConfigTidyIdentityWhitelist(b), - pathListCertificates(b), - pathListRoletagBlacklist(b), - pathRoletagBlacklist(b), - pathTidyRoletagBlacklist(b), - pathListIdentityWhitelist(b), - pathIdentityWhitelist(b), - pathTidyIdentityWhitelist(b), - }, - Invalidate: b.invalidate, - BackendType: logical.TypeCredential, - } - - return b, nil -} - -// periodicFunc performs the tasks that the backend wishes to do periodically. -// Currently this will be triggered once in a minute by the RollbackManager. -// -// The tasks being done currently by this function are to cleanup the expired -// entries of both blacklist role tags and whitelist identities. Tidying is done -// not once in a minute, but once in an hour, controlled by 'tidyCooldownPeriod'. -// Tidying of blacklist and whitelist are by default enabled. This can be -// changed using `config/tidy/roletags` and `config/tidy/identities` endpoints. -func (b *backend) periodicFunc(ctx context.Context, req *logical.Request) error { - // Run the tidy operations for the first time. Then run it when current - // time matches the nextTidyTime. - if b.nextTidyTime.IsZero() || !time.Now().Before(b.nextTidyTime) { - if b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - // safety_buffer defaults to 180 days for roletag blacklist - safety_buffer := 15552000 - tidyBlacklistConfigEntry, err := b.lockedConfigTidyRoleTags(ctx, req.Storage) - if err != nil { - return err - } - skipBlacklistTidy := false - // check if tidying of role tags was configured - if tidyBlacklistConfigEntry != nil { - // check if periodic tidying of role tags was disabled - if tidyBlacklistConfigEntry.DisablePeriodicTidy { - skipBlacklistTidy = true - } - // overwrite the default safety_buffer with the configured value - safety_buffer = tidyBlacklistConfigEntry.SafetyBuffer - } - // tidy role tags if explicitly not disabled - if !skipBlacklistTidy { - b.tidyBlacklistRoleTag(ctx, req, safety_buffer) - } - } - - // We don't check for replication state for whitelist identities as - // these are locally stored - - safety_buffer := 259200 - tidyWhitelistConfigEntry, err := b.lockedConfigTidyIdentities(ctx, req.Storage) - if err != nil { - return err - } - skipWhitelistTidy := false - // check if tidying of identities was configured - if tidyWhitelistConfigEntry != nil { - // check if periodic tidying of identities was disabled - if tidyWhitelistConfigEntry.DisablePeriodicTidy { - skipWhitelistTidy = true - } - // overwrite the default safety_buffer with the configured value - safety_buffer = tidyWhitelistConfigEntry.SafetyBuffer - } - // tidy identities if explicitly not disabled - if !skipWhitelistTidy { - b.tidyWhitelistIdentity(ctx, req, safety_buffer) - } - - // Update the time at which to run the tidy functions again. - b.nextTidyTime = time.Now().Add(b.tidyCooldownPeriod) - } - return nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/client": - b.configMutex.Lock() - defer b.configMutex.Unlock() - b.flushCachedEC2Clients() - b.flushCachedIAMClients() - b.defaultAWSAccountID = "" - } -} - -// Putting this here so we can inject a fake resolver into the backend for unit testing -// purposes -func (b *backend) resolveArnToRealUniqueId(ctx context.Context, s logical.Storage, arn string) (string, error) { - entity, err := parseIamArn(arn) - if err != nil { - return "", err - } - // This odd-looking code is here because IAM is an inherently global service. IAM and STS ARNs - // don't have regions in them, and there is only a single global endpoint for IAM; see - // http://docs.aws.amazon.com/general/latest/gr/rande.html#iam_region - // However, the ARNs do have a partition in them, because the GovCloud and China partitions DO - // have their own separate endpoints, and the partition is encoded in the ARN. If Amazon's Go SDK - // would allow us to pass a partition back to the IAM client, it would be much simpler. But it - // doesn't appear that's possible, so in order to properly support GovCloud and China, we do a - // circular dance of extracting the partition from the ARN, finding any arbitrary region in the - // partition, and passing that region back back to the SDK, so that the SDK can figure out the - // proper partition from the arbitrary region we passed in to look up the endpoint. - // Sigh - region := getAnyRegionForAwsPartition(entity.Partition) - if region == nil { - return "", fmt.Errorf("unable to resolve partition %q to a region", entity.Partition) - } - iamClient, err := b.clientIAM(ctx, s, region.ID(), entity.AccountNumber) - if err != nil { - return "", err - } - - switch entity.Type { - case "user": - userInfo, err := iamClient.GetUser(&iam.GetUserInput{UserName: &entity.FriendlyName}) - if err != nil { - return "", err - } - if userInfo == nil { - return "", fmt.Errorf("got nil result from GetUser") - } - return *userInfo.User.UserId, nil - case "role": - roleInfo, err := iamClient.GetRole(&iam.GetRoleInput{RoleName: &entity.FriendlyName}) - if err != nil { - return "", err - } - if roleInfo == nil { - return "", fmt.Errorf("got nil result from GetRole") - } - return *roleInfo.Role.RoleId, nil - case "instance-profile": - profileInfo, err := iamClient.GetInstanceProfile(&iam.GetInstanceProfileInput{InstanceProfileName: &entity.FriendlyName}) - if err != nil { - return "", err - } - if profileInfo == nil { - return "", fmt.Errorf("got nil result from GetInstanceProfile") - } - return *profileInfo.InstanceProfile.InstanceProfileId, nil - default: - return "", fmt.Errorf("unrecognized error type %#v", entity.Type) - } -} - -// Adapted from https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ -// the "Enumerating Regions and Endpoint Metadata" section -func getAnyRegionForAwsPartition(partitionId string) *endpoints.Region { - resolver := endpoints.DefaultResolver() - partitions := resolver.(endpoints.EnumPartitions).Partitions() - - for _, p := range partitions { - if p.ID() == partitionId { - for _, r := range p.Regions() { - return &r - } - } - } - return nil -} - -const backendHelp = ` -The aws auth method uses either AWS IAM credentials or AWS-signed EC2 metadata -to authenticate clients, which are IAM principals or EC2 instances. - -Authentication is backed by a preconfigured role in the backend. The role -represents the authorization of resources by containing Vault's policies. -Role can be created using 'role/' endpoint. - -Authentication of IAM principals, either IAM users or roles, is done using a -specifically signed AWS API request using clients' AWS IAM credentials. IAM -principals can then be assigned to roles within Vault. This is known as the -"iam" auth method. - -Authentication of EC2 instances is done using either a signed PKCS#7 document -or a detached RSA signature of an AWS EC2 instance's identity document along -with a client-created nonce. This is known as the "ec2" auth method. - -If there is need to further restrict the capabilities of the role on the instance -that is using the role, 'role_tag' option can be enabled on the role, and a tag -can be generated using 'role//tag' endpoint. This tag represents the -subset of capabilities set on the role. When the 'role_tag' option is enabled on -the role, the login operation requires that a respective role tag is attached to -the EC2 instance which performs the login. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/cli.go deleted file mode 100644 index 0024513e7..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/cli.go +++ /dev/null @@ -1,164 +0,0 @@ -package awsauth - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/awsutil" -) - -type CLIHandler struct{} - -// Generates the necessary data to send to the Vault server for generating a token -// This is useful for other API clients to use -func GenerateLoginData(accessKey, secretKey, sessionToken, headerValue string) (map[string]interface{}, error) { - loginData := make(map[string]interface{}) - - credConfig := &awsutil.CredentialsConfig{ - AccessKey: accessKey, - SecretKey: secretKey, - SessionToken: sessionToken, - } - creds, err := credConfig.GenerateCredentialChain() - if err != nil { - return nil, err - } - if creds == nil { - return nil, fmt.Errorf("could not compile valid credential providers from static config, environment, shared, or instance metadata") - } - - _, err = creds.Get() - if err != nil { - return nil, errwrap.Wrapf("failed to retrieve credentials from credential chain: {{err}}", err) - } - - // Use the credentials we've found to construct an STS session - stsSession, err := session.NewSessionWithOptions(session.Options{ - Config: aws.Config{Credentials: creds}, - }) - if err != nil { - return nil, err - } - - var params *sts.GetCallerIdentityInput - svc := sts.New(stsSession) - stsRequest, _ := svc.GetCallerIdentityRequest(params) - - // Inject the required auth header value, if supplied, and then sign the request including that header - if headerValue != "" { - stsRequest.HTTPRequest.Header.Add(iamServerIdHeader, headerValue) - } - stsRequest.Sign() - - // Now extract out the relevant parts of the request - headersJson, err := json.Marshal(stsRequest.HTTPRequest.Header) - if err != nil { - return nil, err - } - requestBody, err := ioutil.ReadAll(stsRequest.HTTPRequest.Body) - if err != nil { - return nil, err - } - loginData["iam_http_request_method"] = stsRequest.HTTPRequest.Method - loginData["iam_request_url"] = base64.StdEncoding.EncodeToString([]byte(stsRequest.HTTPRequest.URL.String())) - loginData["iam_request_headers"] = base64.StdEncoding.EncodeToString(headersJson) - loginData["iam_request_body"] = base64.StdEncoding.EncodeToString(requestBody) - - return loginData, nil -} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "aws" - } - - role, ok := m["role"] - if !ok { - role = "" - } - - headerValue, ok := m["header_value"] - if !ok { - headerValue = "" - } - - loginData, err := GenerateLoginData(m["aws_access_key_id"], m["aws_secret_access_key"], m["aws_security_token"], headerValue) - if err != nil { - return nil, err - } - if loginData == nil { - return nil, fmt.Errorf("got nil response from GenerateLoginData") - } - loginData["role"] = role - path := fmt.Sprintf("auth/%s/login", mount) - secret, err := c.Logical().Write(path, loginData) - - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=aws [CONFIG K=V...] - - The AWS auth method allows users to authenticate with AWS IAM - credentials. The AWS IAM credentials may be specified in a number of ways, - listed in order of precedence below: - - 1. Explicitly via the command line (not recommended) - - 2. Via the standard AWS environment variables (AWS_ACCESS_KEY, etc.) - - 3. Via the ~/.aws/credentials file - - 4. Via EC2 instance profile - - Authenticate using locally stored credentials: - - $ vault login -method=aws - - Authenticate by passing keys: - - $ vault login -method=aws aws_access_key_id=... aws_secret_access_key=... - -Configuration: - - aws_access_key_id= - Explicit AWS access key ID - - aws_secret_access_key= - Explicit AWS secret access key - - aws_security_token= - Explicit AWS security token for temporary credentials - - header_value= - Value for the x-vault-aws-iam-server-id header in requests - - mount= - Path where the AWS credential method is mounted. This is usually provided - via the -path flag in the "vault login" command, but it can be specified - here as well. If specified here, it takes precedence over the value for - -path. The default value is "aws". - - role= - Name of the role to request a token against -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/client.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/client.go deleted file mode 100644 index 2d09bab30..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/client.go +++ /dev/null @@ -1,276 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/awsutil" - "github.com/hashicorp/vault/logical" -) - -// getRawClientConfig creates a aws-sdk-go config, which is used to create client -// that can interact with AWS API. This builds credentials in the following -// order of preference: -// -// * Static credentials from 'config/client' -// * Environment variables -// * Instance metadata role -func (b *backend) getRawClientConfig(ctx context.Context, s logical.Storage, region, clientType string) (*aws.Config, error) { - credsConfig := &awsutil.CredentialsConfig{ - Region: region, - } - - // Read the configured secret key and access key - config, err := b.nonLockedClientConfigEntry(ctx, s) - if err != nil { - return nil, err - } - - endpoint := aws.String("") - var maxRetries int = aws.UseServiceDefaultRetries - if config != nil { - // Override the default endpoint with the configured endpoint. - switch { - case clientType == "ec2" && config.Endpoint != "": - endpoint = aws.String(config.Endpoint) - case clientType == "iam" && config.IAMEndpoint != "": - endpoint = aws.String(config.IAMEndpoint) - case clientType == "sts" && config.STSEndpoint != "": - endpoint = aws.String(config.STSEndpoint) - } - - credsConfig.AccessKey = config.AccessKey - credsConfig.SecretKey = config.SecretKey - maxRetries = config.MaxRetries - } - - credsConfig.HTTPClient = cleanhttp.DefaultClient() - - creds, err := credsConfig.GenerateCredentialChain() - if err != nil { - return nil, err - } - if creds == nil { - return nil, fmt.Errorf("could not compile valid credential providers from static config, environment, shared, or instance metadata") - } - - // Create a config that can be used to make the API calls. - return &aws.Config{ - Credentials: creds, - Region: aws.String(region), - HTTPClient: cleanhttp.DefaultClient(), - Endpoint: endpoint, - MaxRetries: aws.Int(maxRetries), - }, nil -} - -// getClientConfig returns an aws-sdk-go config, with optionally assumed credentials -// It uses getRawClientConfig to obtain config for the runtime environment, and if -// stsRole is a non-empty string, it will use AssumeRole to obtain a set of assumed -// credentials. The credentials will expire after 15 minutes but will auto-refresh. -func (b *backend) getClientConfig(ctx context.Context, s logical.Storage, region, stsRole, accountID, clientType string) (*aws.Config, error) { - - config, err := b.getRawClientConfig(ctx, s, region, clientType) - if err != nil { - return nil, err - } - if config == nil { - return nil, fmt.Errorf("could not compile valid credentials through the default provider chain") - } - - stsConfig, err := b.getRawClientConfig(ctx, s, region, "sts") - if stsConfig == nil { - return nil, fmt.Errorf("could not configure STS client") - } - if err != nil { - return nil, err - } - if stsRole != "" { - assumedCredentials := stscreds.NewCredentials(session.New(stsConfig), stsRole) - // Test that we actually have permissions to assume the role - if _, err = assumedCredentials.Get(); err != nil { - return nil, err - } - config.Credentials = assumedCredentials - } else { - if b.defaultAWSAccountID == "" { - client := sts.New(session.New(stsConfig)) - if client == nil { - return nil, errwrap.Wrapf("could not obtain sts client: {{err}}", err) - } - inputParams := &sts.GetCallerIdentityInput{} - identity, err := client.GetCallerIdentity(inputParams) - if err != nil { - return nil, errwrap.Wrapf("unable to fetch current caller: {{err}}", err) - } - if identity == nil { - return nil, fmt.Errorf("got nil result from GetCallerIdentity") - } - b.defaultAWSAccountID = *identity.Account - } - if b.defaultAWSAccountID != accountID { - return nil, fmt.Errorf("unable to fetch client for account ID %q -- default client is for account %q", accountID, b.defaultAWSAccountID) - } - } - - return config, nil -} - -// flushCachedEC2Clients deletes all the cached ec2 client objects from the backend. -// If the client credentials configuration is deleted or updated in the backend, all -// the cached EC2 client objects will be flushed. Config mutex lock should be -// acquired for write operation before calling this method. -func (b *backend) flushCachedEC2Clients() { - // deleting items in map during iteration is safe - for region, _ := range b.EC2ClientsMap { - delete(b.EC2ClientsMap, region) - } -} - -// flushCachedIAMClients deletes all the cached iam client objects from the -// backend. If the client credentials configuration is deleted or updated in -// the backend, all the cached IAM client objects will be flushed. Config mutex -// lock should be acquired for write operation before calling this method. -func (b *backend) flushCachedIAMClients() { - // deleting items in map during iteration is safe - for region, _ := range b.IAMClientsMap { - delete(b.IAMClientsMap, region) - } -} - -// Gets an entry out of the user ID cache -func (b *backend) getCachedUserId(userId string) string { - if userId == "" { - return "" - } - if entry, ok := b.iamUserIdToArnCache.Get(userId); ok { - b.iamUserIdToArnCache.SetDefault(userId, entry) - return entry.(string) - } - return "" -} - -// Sets an entry in the user ID cache -func (b *backend) setCachedUserId(userId, arn string) { - if userId != "" { - b.iamUserIdToArnCache.SetDefault(userId, arn) - } -} - -func (b *backend) stsRoleForAccount(ctx context.Context, s logical.Storage, accountID string) (string, error) { - // Check if an STS configuration exists for the AWS account - sts, err := b.lockedAwsStsEntry(ctx, s, accountID) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error fetching STS config for account ID %q: {{err}}", accountID), err) - } - // An empty STS role signifies the master account - if sts != nil { - return sts.StsRole, nil - } - return "", nil -} - -// clientEC2 creates a client to interact with AWS EC2 API -func (b *backend) clientEC2(ctx context.Context, s logical.Storage, region, accountID string) (*ec2.EC2, error) { - stsRole, err := b.stsRoleForAccount(ctx, s, accountID) - if err != nil { - return nil, err - } - b.configMutex.RLock() - if b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil { - defer b.configMutex.RUnlock() - // If the client object was already created, return it - return b.EC2ClientsMap[region][stsRole], nil - } - - // Release the read lock and acquire the write lock - b.configMutex.RUnlock() - b.configMutex.Lock() - defer b.configMutex.Unlock() - - // If the client gets created while switching the locks, return it - if b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil { - return b.EC2ClientsMap[region][stsRole], nil - } - - // Create an AWS config object using a chain of providers - var awsConfig *aws.Config - awsConfig, err = b.getClientConfig(ctx, s, region, stsRole, accountID, "ec2") - - if err != nil { - return nil, err - } - - if awsConfig == nil { - return nil, fmt.Errorf("could not retrieve valid assumed credentials") - } - - // Create a new EC2 client object, cache it and return the same - client := ec2.New(session.New(awsConfig)) - if client == nil { - return nil, fmt.Errorf("could not obtain ec2 client") - } - if _, ok := b.EC2ClientsMap[region]; !ok { - b.EC2ClientsMap[region] = map[string]*ec2.EC2{stsRole: client} - } else { - b.EC2ClientsMap[region][stsRole] = client - } - - return b.EC2ClientsMap[region][stsRole], nil -} - -// clientIAM creates a client to interact with AWS IAM API -func (b *backend) clientIAM(ctx context.Context, s logical.Storage, region, accountID string) (*iam.IAM, error) { - stsRole, err := b.stsRoleForAccount(ctx, s, accountID) - if err != nil { - return nil, err - } - b.configMutex.RLock() - if b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil { - defer b.configMutex.RUnlock() - // If the client object was already created, return it - return b.IAMClientsMap[region][stsRole], nil - } - - // Release the read lock and acquire the write lock - b.configMutex.RUnlock() - b.configMutex.Lock() - defer b.configMutex.Unlock() - - // If the client gets created while switching the locks, return it - if b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil { - return b.IAMClientsMap[region][stsRole], nil - } - - // Create an AWS config object using a chain of providers - var awsConfig *aws.Config - awsConfig, err = b.getClientConfig(ctx, s, region, stsRole, accountID, "iam") - - if err != nil { - return nil, err - } - - if awsConfig == nil { - return nil, fmt.Errorf("could not retrieve valid assumed credentials") - } - - // Create a new IAM client object, cache it and return the same - client := iam.New(session.New(awsConfig)) - if client == nil { - return nil, fmt.Errorf("could not obtain iam client") - } - if _, ok := b.IAMClientsMap[region]; !ok { - b.IAMClientsMap[region] = map[string]*iam.IAM{stsRole: client} - } else { - b.IAMClientsMap[region][stsRole] = client - } - return b.IAMClientsMap[region][stsRole], nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_certificate.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_certificate.go deleted file mode 100644 index 1f5a842b2..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_certificate.go +++ /dev/null @@ -1,447 +0,0 @@ -package awsauth - -import ( - "context" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "fmt" - "math/big" - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// dsaSignature represents the contents of the signature of a signed -// content using digital signature algorithm. -type dsaSignature struct { - R, S *big.Int -} - -// This certificate is used to verify the PKCS#7 signature of the instance -// identity document. As per AWS documentation, this public key is valid for -// US East (N. Virginia), US West (Oregon), US West (N. California), EU -// (Ireland), EU (Frankfurt), Asia Pacific (Tokyo), Asia Pacific (Seoul), Asia -// Pacific (Singapore), Asia Pacific (Sydney), and South America (Sao Paulo). -// -// It's also the same certificate, but for some reason listed separately, for -// GovCloud (US) -const genericAWSPublicCertificatePkcs7 = `-----BEGIN CERTIFICATE----- -MIIC7TCCAq0CCQCWukjZ5V4aZzAJBgcqhkjOOAQDMFwxCzAJBgNVBAYTAlVTMRkw -FwYDVQQIExBXYXNoaW5ndG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYD -VQQKExdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzAeFw0xMjAxMDUxMjU2MTJaFw0z -ODAxMDUxMjU2MTJaMFwxCzAJBgNVBAYTAlVTMRkwFwYDVQQIExBXYXNoaW5ndG9u -IFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYDVQQKExdBbWF6b24gV2ViIFNl -cnZpY2VzIExMQzCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQCjkvcS2bb1VQ4yt/5e -ih5OO6kK/n1Lzllr7D8ZwtQP8fOEpp5E2ng+D6Ud1Z1gYipr58Kj3nssSNpI6bX3 -VyIQzK7wLclnd/YozqNNmgIyZecN7EglK9ITHJLP+x8FtUpt3QbyYXJdmVMegN6P -hviYt5JH/nYl4hh3Pa1HJdskgQIVALVJ3ER11+Ko4tP6nwvHwh6+ERYRAoGBAI1j -k+tkqMVHuAFcvAGKocTgsjJem6/5qomzJuKDmbJNu9Qxw3rAotXau8Qe+MBcJl/U -hhy1KHVpCGl9fueQ2s6IL0CaO/buycU1CiYQk40KNHCcHfNiZbdlx1E9rpUp7bnF -lRa2v1ntMX3caRVDdbtPEWmdxSCYsYFDk4mZrOLBA4GEAAKBgEbmeve5f8LIE/Gf -MNmP9CM5eovQOGx5ho8WqD+aTebs+k2tn92BBPqeZqpWRa5P/+jrdKml1qx4llHW -MXrs3IgIb6+hUIB+S8dz8/mmO0bpr76RoZVCXYab2CZedFut7qc3WUH9+EUAH5mw -vSeDCOUMYQR7R9LINYwouHIziqQYMAkGByqGSM44BAMDLwAwLAIUWXBlk40xTwSw -7HX32MxXYruse9ACFBNGmdX2ZBrVNGrN9N2f6ROk0k9K ------END CERTIFICATE----- -` - -// This certificate is used to verify the instance identity document using the -// RSA digest of the same -const genericAWSPublicCertificateIdentity = `-----BEGIN CERTIFICATE----- -MIIDIjCCAougAwIBAgIJAKnL4UEDMN/FMA0GCSqGSIb3DQEBBQUAMGoxCzAJBgNV -BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRgw -FgYDVQQKEw9BbWF6b24uY29tIEluYy4xGjAYBgNVBAMTEWVjMi5hbWF6b25hd3Mu -Y29tMB4XDTE0MDYwNTE0MjgwMloXDTI0MDYwNTE0MjgwMlowajELMAkGA1UEBhMC -VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxGDAWBgNV -BAoTD0FtYXpvbi5jb20gSW5jLjEaMBgGA1UEAxMRZWMyLmFtYXpvbmF3cy5jb20w -gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIe9GN//SRK2knbjySG0ho3yqQM3 -e2TDhWO8D2e8+XZqck754gFSo99AbT2RmXClambI7xsYHZFapbELC4H91ycihvrD -jbST1ZjkLQgga0NE1q43eS68ZeTDccScXQSNivSlzJZS8HJZjgqzBlXjZftjtdJL -XeE4hwvo0sD4f3j9AgMBAAGjgc8wgcwwHQYDVR0OBBYEFCXWzAgVyrbwnFncFFIs -77VBdlE4MIGcBgNVHSMEgZQwgZGAFCXWzAgVyrbwnFncFFIs77VBdlE4oW6kbDBq -MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh -dHRsZTEYMBYGA1UEChMPQW1hem9uLmNvbSBJbmMuMRowGAYDVQQDExFlYzIuYW1h -em9uYXdzLmNvbYIJAKnL4UEDMN/FMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEF -BQADgYEAFYcz1OgEhQBXIwIdsgCOS8vEtiJYF+j9uO6jz7VOmJqO+pRlAbRlvY8T -C1haGgSI/A1uZUKs/Zfnph0oEI0/hu1IIJ/SKBDtN5lvmZ/IzbOPIJWirlsllQIQ -7zvWbGd9c9+Rm3p04oTvhup99la7kZqevJK0QRdD/6NpCKsqP/0= ------END CERTIFICATE-----` - -// pathListCertificates creates a path that enables listing of all -// the AWS public certificates registered with Vault. -func pathListCertificates(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/certificates/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathCertificatesList, - }, - - HelpSynopsis: pathListCertificatesHelpSyn, - HelpDescription: pathListCertificatesHelpDesc, - } -} - -func pathConfigCertificate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/certificate/" + framework.GenericNameRegex("cert_name"), - Fields: map[string]*framework.FieldSchema{ - "cert_name": { - Type: framework.TypeString, - Description: "Name of the certificate.", - }, - "aws_public_cert": { - Type: framework.TypeString, - Description: "Base64 encoded AWS Public cert required to verify PKCS7 signature of the EC2 instance metadata.", - }, - "type": { - Type: framework.TypeString, - Default: "pkcs7", - Description: ` -Takes the value of either "pkcs7" or "identity", indicating the type of -document which can be verified using the given certificate. The reason is that -the PKCS#7 document will have a DSA digest and the identity signature will have -an RSA signature, and accordingly the public certificates to verify those also -vary. Defaults to "pkcs7".`, - }, - }, - - ExistenceCheck: b.pathConfigCertificateExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathConfigCertificateCreateUpdate, - logical.UpdateOperation: b.pathConfigCertificateCreateUpdate, - logical.ReadOperation: b.pathConfigCertificateRead, - logical.DeleteOperation: b.pathConfigCertificateDelete, - }, - - HelpSynopsis: pathConfigCertificateSyn, - HelpDescription: pathConfigCertificateDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) pathConfigCertificateExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - certName := data.Get("cert_name").(string) - if certName == "" { - return false, fmt.Errorf("missing cert_name") - } - - entry, err := b.lockedAWSPublicCertificateEntry(ctx, req.Storage, certName) - if err != nil { - return false, err - } - return entry != nil, nil -} - -// pathCertificatesList is used to list all the AWS public certificates registered with Vault -func (b *backend) pathCertificatesList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - certs, err := req.Storage.List(ctx, "config/certificate/") - if err != nil { - return nil, err - } - return logical.ListResponse(certs), nil -} - -// Decodes the PEM encoded certiticate and parses it into a x509 cert -func decodePEMAndParseCertificate(certificate string) (*x509.Certificate, error) { - // Decode the PEM block and error out if a block is not detected in the first attempt - decodedPublicCert, rest := pem.Decode([]byte(certificate)) - if len(rest) != 0 { - return nil, fmt.Errorf("invalid certificate; should be one PEM block only") - } - - // Check if the certificate can be parsed - publicCert, err := x509.ParseCertificate(decodedPublicCert.Bytes) - if err != nil { - return nil, err - } - if publicCert == nil { - return nil, fmt.Errorf("invalid certificate; failed to parse certificate") - } - return publicCert, nil -} - -// awsPublicCertificates returns a slice of all the parsed AWS public -// certificates, which are used to verify either the SHA256 RSA signature, or -// the PKCS7 signatures of the instance identity documents. This method will -// append the certificates registered using `config/certificate/` -// endpoint, along with the default certificate in the backend. -func (b *backend) awsPublicCertificates(ctx context.Context, s logical.Storage, isPkcs bool) ([]*x509.Certificate, error) { - // Lock at beginning and use internal method so that we are consistent as - // we iterate through - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - var certs []*x509.Certificate - - defaultCert := genericAWSPublicCertificateIdentity - if isPkcs { - defaultCert = genericAWSPublicCertificatePkcs7 - } - - // Append the generic certificate provided in the AWS EC2 instance metadata documentation - decodedCert, err := decodePEMAndParseCertificate(defaultCert) - if err != nil { - return nil, err - } - certs = append(certs, decodedCert) - - // Get the list of all the registered certificates - registeredCerts, err := s.List(ctx, "config/certificate/") - if err != nil { - return nil, err - } - - // Iterate through each certificate, parse and append it to a slice - for _, cert := range registeredCerts { - certEntry, err := b.nonLockedAWSPublicCertificateEntry(ctx, s, cert) - if err != nil { - return nil, err - } - if certEntry == nil { - return nil, fmt.Errorf("certificate storage has a nil entry under the name: %q", cert) - } - // Append relevant certificates only - if (isPkcs && certEntry.Type == "pkcs7") || - (!isPkcs && certEntry.Type == "identity") { - decodedCert, err := decodePEMAndParseCertificate(certEntry.AWSPublicCert) - if err != nil { - return nil, err - } - certs = append(certs, decodedCert) - } - } - - return certs, nil -} - -// lockedSetAWSPublicCertificateEntry is used to store the AWS public key in -// the storage. This method acquires lock before creating or updating a storage -// entry. -func (b *backend) lockedSetAWSPublicCertificateEntry(ctx context.Context, s logical.Storage, certName string, certEntry *awsPublicCert) error { - if certName == "" { - return fmt.Errorf("missing certificate name") - } - - if certEntry == nil { - return fmt.Errorf("nil AWS public key certificate") - } - - b.configMutex.Lock() - defer b.configMutex.Unlock() - - return b.nonLockedSetAWSPublicCertificateEntry(ctx, s, certName, certEntry) -} - -// nonLockedSetAWSPublicCertificateEntry is used to store the AWS public key in -// the storage. This method does not acquire lock before reading the storage. -// If locking is desired, use lockedSetAWSPublicCertificateEntry instead. -func (b *backend) nonLockedSetAWSPublicCertificateEntry(ctx context.Context, s logical.Storage, certName string, certEntry *awsPublicCert) error { - if certName == "" { - return fmt.Errorf("missing certificate name") - } - - if certEntry == nil { - return fmt.Errorf("nil AWS public key certificate") - } - - entry, err := logical.StorageEntryJSON("config/certificate/"+certName, certEntry) - if err != nil { - return err - } - if entry == nil { - return fmt.Errorf("failed to create storage entry for AWS public key certificate") - } - - return s.Put(ctx, entry) -} - -// lockedAWSPublicCertificateEntry is used to get the configured AWS Public Key -// that is used to verify the PKCS#7 signature of the instance identity -// document. -func (b *backend) lockedAWSPublicCertificateEntry(ctx context.Context, s logical.Storage, certName string) (*awsPublicCert, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - return b.nonLockedAWSPublicCertificateEntry(ctx, s, certName) -} - -// nonLockedAWSPublicCertificateEntry reads the certificate information from -// the storage. This method does not acquire lock before reading the storage. -// If locking is desired, use lockedAWSPublicCertificateEntry instead. -func (b *backend) nonLockedAWSPublicCertificateEntry(ctx context.Context, s logical.Storage, certName string) (*awsPublicCert, error) { - entry, err := s.Get(ctx, "config/certificate/"+certName) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - var certEntry awsPublicCert - if err := entry.DecodeJSON(&certEntry); err != nil { - return nil, err - } - - // Handle upgrade for certificate type - persistNeeded := false - if certEntry.Type == "" { - certEntry.Type = "pkcs7" - persistNeeded = true - } - - if persistNeeded { - if err := b.nonLockedSetAWSPublicCertificateEntry(ctx, s, certName, &certEntry); err != nil { - return nil, err - } - } - - return &certEntry, nil -} - -// pathConfigCertificateDelete is used to delete the previously configured AWS -// Public Key that is used to verify the PKCS#7 signature of the instance -// identity document. -func (b *backend) pathConfigCertificateDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - certName := data.Get("cert_name").(string) - if certName == "" { - return logical.ErrorResponse("missing cert_name"), nil - } - - return nil, req.Storage.Delete(ctx, "config/certificate/"+certName) -} - -// pathConfigCertificateRead is used to view the configured AWS Public Key that -// is used to verify the PKCS#7 signature of the instance identity document. -func (b *backend) pathConfigCertificateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - certName := data.Get("cert_name").(string) - if certName == "" { - return logical.ErrorResponse("missing cert_name"), nil - } - - certificateEntry, err := b.lockedAWSPublicCertificateEntry(ctx, req.Storage, certName) - if err != nil { - return nil, err - } - if certificateEntry == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "aws_public_cert": certificateEntry.AWSPublicCert, - "type": certificateEntry.Type, - }, - }, nil -} - -// pathConfigCertificateCreateUpdate is used to register an AWS Public Key that -// is used to verify the PKCS#7 signature of the instance identity document. -func (b *backend) pathConfigCertificateCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - certName := data.Get("cert_name").(string) - if certName == "" { - return logical.ErrorResponse("missing certificate name"), nil - } - - b.configMutex.Lock() - defer b.configMutex.Unlock() - - // Check if there is already a certificate entry registered - certEntry, err := b.nonLockedAWSPublicCertificateEntry(ctx, req.Storage, certName) - if err != nil { - return nil, err - } - if certEntry == nil { - certEntry = &awsPublicCert{} - } - - // Check if type information is provided - certTypeRaw, ok := data.GetOk("type") - if ok { - certEntry.Type = strings.ToLower(certTypeRaw.(string)) - } else if req.Operation == logical.CreateOperation { - certEntry.Type = data.Get("type").(string) - } - - switch certEntry.Type { - case "pkcs7": - case "identity": - default: - return logical.ErrorResponse(fmt.Sprintf("invalid certificate type %q", certEntry.Type)), nil - } - - // Check if the value is provided by the client - certStrData, ok := data.GetOk("aws_public_cert") - if ok { - if certBytes, err := base64.StdEncoding.DecodeString(certStrData.(string)); err == nil { - certEntry.AWSPublicCert = string(certBytes) - } else { - certEntry.AWSPublicCert = certStrData.(string) - } - } else { - // aws_public_cert should be supplied for both create and update operations. - // If it is not provided, throw an error. - return logical.ErrorResponse("missing aws_public_cert"), nil - } - - // If explicitly set to empty string, error out - if certEntry.AWSPublicCert == "" { - return logical.ErrorResponse("invalid aws_public_cert"), nil - } - - // Verify the certificate by decoding it and parsing it - publicCert, err := decodePEMAndParseCertificate(certEntry.AWSPublicCert) - if err != nil { - return nil, err - } - if publicCert == nil { - return logical.ErrorResponse("invalid certificate; failed to decode and parse certificate"), nil - } - - // If none of the checks fail, save the provided certificate - if err := b.nonLockedSetAWSPublicCertificateEntry(ctx, req.Storage, certName, certEntry); err != nil { - return nil, err - } - - return nil, nil -} - -// Struct awsPublicCert holds the AWS Public Key that is used to verify the PKCS#7 signature -// of the instance identity document. -type awsPublicCert struct { - AWSPublicCert string `json:"aws_public_cert"` - Type string `json:"type"` -} - -const pathConfigCertificateSyn = ` -Adds the AWS Public Key that is used to verify the PKCS#7 signature of the identity document. -` - -const pathConfigCertificateDesc = ` -AWS Public Key which is used to verify the PKCS#7 signature of the identity document, -varies by region. The public key(s) can be found in AWS EC2 instance metadata documentation. -The default key that is used to verify the signature is the one that is applicable for -following regions: US East (N. Virginia), US West (Oregon), US West (N. California), -EU (Ireland), EU (Frankfurt), Asia Pacific (Tokyo), Asia Pacific (Seoul), Asia Pacific (Singapore), -Asia Pacific (Sydney), and South America (Sao Paulo). - -If the instances belongs to region other than the above, the public key(s) for the -corresponding regions should be registered using this endpoint. PKCS#7 is verified -using a collection of certificates containing the default certificate and all the -certificates that are registered using this endpoint. -` -const pathListCertificatesHelpSyn = ` -Lists all the AWS public certificates that are registered with the backend. -` -const pathListCertificatesHelpDesc = ` -Certificates will be listed by their respective names that were used during registration. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_client.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_client.go deleted file mode 100644 index 05315ee67..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_client.go +++ /dev/null @@ -1,292 +0,0 @@ -package awsauth - -import ( - "context" - - "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigClient(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/client$", - Fields: map[string]*framework.FieldSchema{ - "access_key": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "AWS Access Key ID for the account used to make AWS API requests.", - }, - - "secret_key": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "AWS Secret Access Key for the account used to make AWS API requests.", - }, - - "endpoint": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "URL to override the default generated endpoint for making AWS EC2 API calls.", - }, - - "iam_endpoint": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "URL to override the default generated endpoint for making AWS IAM API calls.", - }, - - "sts_endpoint": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "URL to override the default generated endpoint for making AWS STS API calls.", - }, - - "iam_server_id_header_value": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "Value to require in the X-Vault-AWS-IAM-Server-ID request header", - }, - "max_retries": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: aws.UseServiceDefaultRetries, - Description: "Maximum number of retries for recoverable exceptions of AWS APIs", - }, - }, - - ExistenceCheck: b.pathConfigClientExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathConfigClientCreateUpdate, - logical.UpdateOperation: b.pathConfigClientCreateUpdate, - logical.DeleteOperation: b.pathConfigClientDelete, - logical.ReadOperation: b.pathConfigClientRead, - }, - - HelpSynopsis: pathConfigClientHelpSyn, - HelpDescription: pathConfigClientHelpDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) pathConfigClientExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.lockedClientConfigEntry(ctx, req.Storage) - if err != nil { - return false, err - } - return entry != nil, nil -} - -// Fetch the client configuration required to access the AWS API, after acquiring an exclusive lock. -func (b *backend) lockedClientConfigEntry(ctx context.Context, s logical.Storage) (*clientConfig, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - return b.nonLockedClientConfigEntry(ctx, s) -} - -// Fetch the client configuration required to access the AWS API. -func (b *backend) nonLockedClientConfigEntry(ctx context.Context, s logical.Storage) (*clientConfig, error) { - entry, err := s.Get(ctx, "config/client") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result clientConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathConfigClientRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - clientConfig, err := b.lockedClientConfigEntry(ctx, req.Storage) - if err != nil { - return nil, err - } - - if clientConfig == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "access_key": clientConfig.AccessKey, - "endpoint": clientConfig.Endpoint, - "iam_endpoint": clientConfig.IAMEndpoint, - "sts_endpoint": clientConfig.STSEndpoint, - "iam_server_id_header_value": clientConfig.IAMServerIdHeaderValue, - "max_retries": clientConfig.MaxRetries, - }, - }, nil -} - -func (b *backend) pathConfigClientDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - if err := req.Storage.Delete(ctx, "config/client"); err != nil { - return nil, err - } - - // Remove all the cached EC2 client objects in the backend. - b.flushCachedEC2Clients() - - // Remove all the cached EC2 client objects in the backend. - b.flushCachedIAMClients() - - // unset the cached default AWS account ID - b.defaultAWSAccountID = "" - - return nil, nil -} - -// pathConfigClientCreateUpdate is used to register the 'aws_secret_key' and 'aws_access_key' -// that can be used to interact with AWS EC2 API. -func (b *backend) pathConfigClientCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - configEntry, err := b.nonLockedClientConfigEntry(ctx, req.Storage) - if err != nil { - return nil, err - } - if configEntry == nil { - configEntry = &clientConfig{} - } - - // changedCreds is whether we need to flush the cached AWS clients and store in the backend - changedCreds := false - // changedOtherConfig is whether other config has changed that requires storing in the backend - // but does not require flushing the cached clients - changedOtherConfig := false - - accessKeyStr, ok := data.GetOk("access_key") - if ok { - if configEntry.AccessKey != accessKeyStr.(string) { - changedCreds = true - configEntry.AccessKey = accessKeyStr.(string) - } - } else if req.Operation == logical.CreateOperation { - // Use the default - configEntry.AccessKey = data.Get("access_key").(string) - } - - secretKeyStr, ok := data.GetOk("secret_key") - if ok { - if configEntry.SecretKey != secretKeyStr.(string) { - changedCreds = true - configEntry.SecretKey = secretKeyStr.(string) - } - } else if req.Operation == logical.CreateOperation { - configEntry.SecretKey = data.Get("secret_key").(string) - } - - endpointStr, ok := data.GetOk("endpoint") - if ok { - if configEntry.Endpoint != endpointStr.(string) { - changedCreds = true - configEntry.Endpoint = endpointStr.(string) - } - } else if req.Operation == logical.CreateOperation { - configEntry.Endpoint = data.Get("endpoint").(string) - } - - iamEndpointStr, ok := data.GetOk("iam_endpoint") - if ok { - if configEntry.IAMEndpoint != iamEndpointStr.(string) { - changedCreds = true - configEntry.IAMEndpoint = iamEndpointStr.(string) - } - } else if req.Operation == logical.CreateOperation { - configEntry.IAMEndpoint = data.Get("iam_endpoint").(string) - } - - stsEndpointStr, ok := data.GetOk("sts_endpoint") - if ok { - if configEntry.STSEndpoint != stsEndpointStr.(string) { - // We don't directly cache STS clients as they are ever directly used. - // However, they are potentially indirectly used as credential providers - // for the EC2 and IAM clients, and thus we would be indirectly caching - // them there. So, if we change the STS endpoint, we should flush those - // cached clients. - changedCreds = true - configEntry.STSEndpoint = stsEndpointStr.(string) - } - } else if req.Operation == logical.CreateOperation { - configEntry.STSEndpoint = data.Get("sts_endpoint").(string) - } - - headerValStr, ok := data.GetOk("iam_server_id_header_value") - if ok { - if configEntry.IAMServerIdHeaderValue != headerValStr.(string) { - // NOT setting changedCreds here, since this isn't really cached - configEntry.IAMServerIdHeaderValue = headerValStr.(string) - changedOtherConfig = true - } - } else if req.Operation == logical.CreateOperation { - configEntry.IAMServerIdHeaderValue = data.Get("iam_server_id_header_value").(string) - } - - maxRetriesInt, ok := data.GetOk("max_retries") - if ok { - configEntry.MaxRetries = maxRetriesInt.(int) - changedOtherConfig = true - } else if req.Operation == logical.CreateOperation { - configEntry.MaxRetries = data.Get("max_retries").(int) - } - - // Since this endpoint supports both create operation and update operation, - // the error checks for access_key and secret_key not being set are not present. - // This allows calling this endpoint multiple times to provide the values. - // Hence, the readers of this endpoint should do the validation on - // the validation of keys before using them. - entry, err := logical.StorageEntryJSON("config/client", configEntry) - if err != nil { - return nil, err - } - - if changedCreds || changedOtherConfig || req.Operation == logical.CreateOperation { - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - } - - if changedCreds { - b.flushCachedEC2Clients() - b.flushCachedIAMClients() - b.defaultAWSAccountID = "" - } - - return nil, nil -} - -// Struct to hold 'aws_access_key' and 'aws_secret_key' that are required to -// interact with the AWS EC2 API. -type clientConfig struct { - AccessKey string `json:"access_key"` - SecretKey string `json:"secret_key"` - Endpoint string `json:"endpoint"` - IAMEndpoint string `json:"iam_endpoint"` - STSEndpoint string `json:"sts_endpoint"` - IAMServerIdHeaderValue string `json:"iam_server_id_header_value"` - MaxRetries int `json:"max_retries"` -} - -const pathConfigClientHelpSyn = ` -Configure AWS IAM credentials that are used to query instance and role details from the AWS API. -` - -const pathConfigClientHelpDesc = ` -The aws-ec2 auth method makes AWS API queries to retrieve information -regarding EC2 instances that perform login operations. The 'aws_secret_key' and -'aws_access_key' parameters configured here should map to an AWS IAM user that -has permission to make the following API queries: - -* ec2:DescribeInstances -* iam:GetInstanceProfile (if IAM Role binding is used) -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_sts.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_sts.go deleted file mode 100644 index 23816846c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_sts.go +++ /dev/null @@ -1,249 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// awsStsEntry is used to store details of an STS role for assumption -type awsStsEntry struct { - StsRole string `json:"sts_role"` -} - -func pathListSts(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/sts/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathStsList, - }, - - HelpSynopsis: pathListStsHelpSyn, - HelpDescription: pathListStsHelpDesc, - } -} - -func pathConfigSts(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/sts/" + framework.GenericNameRegex("account_id"), - Fields: map[string]*framework.FieldSchema{ - "account_id": { - Type: framework.TypeString, - Description: `AWS account ID to be associated with STS role. If set, -Vault will use assumed credentials to verify any login attempts from EC2 -instances in this account.`, - }, - "sts_role": { - Type: framework.TypeString, - Description: `AWS ARN for STS role to be assumed when interacting with the account specified. -The Vault server must have permissions to assume this role.`, - }, - }, - - ExistenceCheck: b.pathConfigStsExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathConfigStsCreateUpdate, - logical.UpdateOperation: b.pathConfigStsCreateUpdate, - logical.ReadOperation: b.pathConfigStsRead, - logical.DeleteOperation: b.pathConfigStsDelete, - }, - - HelpSynopsis: pathConfigStsSyn, - HelpDescription: pathConfigStsDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) pathConfigStsExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - accountID := data.Get("account_id").(string) - if accountID == "" { - return false, fmt.Errorf("missing account_id") - } - - entry, err := b.lockedAwsStsEntry(ctx, req.Storage, accountID) - if err != nil { - return false, err - } - - return entry != nil, nil -} - -// pathStsList is used to list all the AWS STS role configurations -func (b *backend) pathStsList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - sts, err := req.Storage.List(ctx, "config/sts/") - if err != nil { - return nil, err - } - return logical.ListResponse(sts), nil -} - -// nonLockedSetAwsStsEntry creates or updates an STS role association with the given accountID -// This method does not acquire the write lock before creating or updating. If locking is -// desired, use lockedSetAwsStsEntry instead -func (b *backend) nonLockedSetAwsStsEntry(ctx context.Context, s logical.Storage, accountID string, stsEntry *awsStsEntry) error { - if accountID == "" { - return fmt.Errorf("missing AWS account ID") - } - - if stsEntry == nil { - return fmt.Errorf("missing AWS STS Role ARN") - } - - entry, err := logical.StorageEntryJSON("config/sts/"+accountID, stsEntry) - if err != nil { - return err - } - - if entry == nil { - return fmt.Errorf("failed to create storage entry for AWS STS configuration") - } - - return s.Put(ctx, entry) -} - -// lockedSetAwsStsEntry creates or updates an STS role association with the given accountID -// This method acquires the write lock before creating or updating the STS entry. -func (b *backend) lockedSetAwsStsEntry(ctx context.Context, s logical.Storage, accountID string, stsEntry *awsStsEntry) error { - if accountID == "" { - return fmt.Errorf("missing AWS account ID") - } - - if stsEntry == nil { - return fmt.Errorf("missing sts entry") - } - - b.configMutex.Lock() - defer b.configMutex.Unlock() - - return b.nonLockedSetAwsStsEntry(ctx, s, accountID, stsEntry) -} - -// nonLockedAwsStsEntry returns the STS role associated with the given accountID. -// This method does not acquire the read lock before returning information. If locking is -// desired, use lockedAwsStsEntry instead -func (b *backend) nonLockedAwsStsEntry(ctx context.Context, s logical.Storage, accountID string) (*awsStsEntry, error) { - entry, err := s.Get(ctx, "config/sts/"+accountID) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - var stsEntry awsStsEntry - if err := entry.DecodeJSON(&stsEntry); err != nil { - return nil, err - } - - return &stsEntry, nil -} - -// lockedAwsStsEntry returns the STS role associated with the given accountID. -// This method acquires the read lock before returning the association. -func (b *backend) lockedAwsStsEntry(ctx context.Context, s logical.Storage, accountID string) (*awsStsEntry, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - return b.nonLockedAwsStsEntry(ctx, s, accountID) -} - -// pathConfigStsRead is used to return information about an STS role/AWS accountID association -func (b *backend) pathConfigStsRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - accountID := data.Get("account_id").(string) - if accountID == "" { - return logical.ErrorResponse("missing account id"), nil - } - - stsEntry, err := b.lockedAwsStsEntry(ctx, req.Storage, accountID) - if err != nil { - return nil, err - } - if stsEntry == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "sts_role": stsEntry.StsRole, - }, - }, nil -} - -// pathConfigStsCreateUpdate is used to associate an STS role with a given AWS accountID -func (b *backend) pathConfigStsCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - accountID := data.Get("account_id").(string) - if accountID == "" { - return logical.ErrorResponse("missing AWS account ID"), nil - } - - b.configMutex.Lock() - defer b.configMutex.Unlock() - - // Check if an STS role is already registered - stsEntry, err := b.nonLockedAwsStsEntry(ctx, req.Storage, accountID) - if err != nil { - return nil, err - } - if stsEntry == nil { - stsEntry = &awsStsEntry{} - } - - // Check that an STS role has actually been provided - stsRole, ok := data.GetOk("sts_role") - if ok { - stsEntry.StsRole = stsRole.(string) - } else if req.Operation == logical.CreateOperation { - return logical.ErrorResponse("missing sts role"), nil - } - - if stsEntry.StsRole == "" { - return logical.ErrorResponse("sts role cannot be empty"), nil - } - - // save the provided STS role - if err := b.nonLockedSetAwsStsEntry(ctx, req.Storage, accountID, stsEntry); err != nil { - return nil, err - } - - return nil, nil -} - -// pathConfigStsDelete is used to delete a previously configured STS configuration -func (b *backend) pathConfigStsDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - accountID := data.Get("account_id").(string) - if accountID == "" { - return logical.ErrorResponse("missing account id"), nil - } - - return nil, req.Storage.Delete(ctx, "config/sts/"+accountID) -} - -const pathConfigStsSyn = ` -Specify STS roles to be assumed for certain AWS accounts. -` - -const pathConfigStsDesc = ` -Allows the explicit association of STS roles to satellite AWS accounts (i.e. those -which are not the account in which the Vault server is running.) Login attempts from -EC2 instances running in these accounts will be verified using credentials obtained -by assumption of these STS roles. - -The environment in which the Vault server resides must have access to assume the -given STS roles. -` -const pathListStsHelpSyn = ` -List all the AWS account/STS role relationships registered with Vault. -` - -const pathListStsHelpDesc = ` -AWS accounts will be listed by account ID, along with their respective role names. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_identity_whitelist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_identity_whitelist.go deleted file mode 100644 index aeedfea22..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_identity_whitelist.go +++ /dev/null @@ -1,152 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - identityWhitelistConfigPath = "config/tidy/identity-whitelist" -) - -func pathConfigTidyIdentityWhitelist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("%s$", identityWhitelistConfigPath), - Fields: map[string]*framework.FieldSchema{ - "safety_buffer": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 259200, //72h - Description: `The amount of extra time that must have passed beyond the identity's -expiration, before it is removed from the backend storage.`, - }, - "disable_periodic_tidy": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: "If set to 'true', disables the periodic tidying of the 'identity-whitelist/' entries.", - }, - }, - - ExistenceCheck: b.pathConfigTidyIdentityWhitelistExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathConfigTidyIdentityWhitelistCreateUpdate, - logical.UpdateOperation: b.pathConfigTidyIdentityWhitelistCreateUpdate, - logical.ReadOperation: b.pathConfigTidyIdentityWhitelistRead, - logical.DeleteOperation: b.pathConfigTidyIdentityWhitelistDelete, - }, - - HelpSynopsis: pathConfigTidyIdentityWhitelistHelpSyn, - HelpDescription: pathConfigTidyIdentityWhitelistHelpDesc, - } -} - -func (b *backend) pathConfigTidyIdentityWhitelistExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.lockedConfigTidyIdentities(ctx, req.Storage) - if err != nil { - return false, err - } - return entry != nil, nil -} - -func (b *backend) lockedConfigTidyIdentities(ctx context.Context, s logical.Storage) (*tidyWhitelistIdentityConfig, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - return b.nonLockedConfigTidyIdentities(ctx, s) -} - -func (b *backend) nonLockedConfigTidyIdentities(ctx context.Context, s logical.Storage) (*tidyWhitelistIdentityConfig, error) { - entry, err := s.Get(ctx, identityWhitelistConfigPath) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result tidyWhitelistIdentityConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathConfigTidyIdentityWhitelistCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - configEntry, err := b.nonLockedConfigTidyIdentities(ctx, req.Storage) - if err != nil { - return nil, err - } - if configEntry == nil { - configEntry = &tidyWhitelistIdentityConfig{} - } - - safetyBufferInt, ok := data.GetOk("safety_buffer") - if ok { - configEntry.SafetyBuffer = safetyBufferInt.(int) - } else if req.Operation == logical.CreateOperation { - configEntry.SafetyBuffer = data.Get("safety_buffer").(int) - } - - disablePeriodicTidyBool, ok := data.GetOk("disable_periodic_tidy") - if ok { - configEntry.DisablePeriodicTidy = disablePeriodicTidyBool.(bool) - } else if req.Operation == logical.CreateOperation { - configEntry.DisablePeriodicTidy = data.Get("disable_periodic_tidy").(bool) - } - - entry, err := logical.StorageEntryJSON(identityWhitelistConfigPath, configEntry) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigTidyIdentityWhitelistRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - clientConfig, err := b.lockedConfigTidyIdentities(ctx, req.Storage) - if err != nil { - return nil, err - } - if clientConfig == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "safety_buffer": clientConfig.SafetyBuffer, - "disable_periodic_tidy": clientConfig.DisablePeriodicTidy, - }, - }, nil -} - -func (b *backend) pathConfigTidyIdentityWhitelistDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - return nil, req.Storage.Delete(ctx, identityWhitelistConfigPath) -} - -type tidyWhitelistIdentityConfig struct { - SafetyBuffer int `json:"safety_buffer"` - DisablePeriodicTidy bool `json:"disable_periodic_tidy"` -} - -const pathConfigTidyIdentityWhitelistHelpSyn = ` -Configures the periodic tidying operation of the whitelisted identity entries. -` -const pathConfigTidyIdentityWhitelistHelpDesc = ` -By default, the expired entries in the whitelist will be attempted to be removed -periodically. This operation will look for expired items in the list and purges them. -However, there is a safety buffer duration (defaults to 72h), purges the entries -only if they have been persisting this duration, past its expiration time. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_roletag_blacklist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_roletag_blacklist.go deleted file mode 100644 index 0c52c53dd..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_config_tidy_roletag_blacklist.go +++ /dev/null @@ -1,153 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - roletagBlacklistConfigPath = "config/tidy/roletag-blacklist" -) - -func pathConfigTidyRoletagBlacklist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("%s$", roletagBlacklistConfigPath), - Fields: map[string]*framework.FieldSchema{ - "safety_buffer": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 15552000, //180d - Description: `The amount of extra time that must have passed beyond the roletag -expiration, before it is removed from the backend storage. -Defaults to 4320h (180 days).`, - }, - - "disable_periodic_tidy": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: "If set to 'true', disables the periodic tidying of blacklisted entries.", - }, - }, - - ExistenceCheck: b.pathConfigTidyRoletagBlacklistExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathConfigTidyRoletagBlacklistCreateUpdate, - logical.UpdateOperation: b.pathConfigTidyRoletagBlacklistCreateUpdate, - logical.ReadOperation: b.pathConfigTidyRoletagBlacklistRead, - logical.DeleteOperation: b.pathConfigTidyRoletagBlacklistDelete, - }, - - HelpSynopsis: pathConfigTidyRoletagBlacklistHelpSyn, - HelpDescription: pathConfigTidyRoletagBlacklistHelpDesc, - } -} - -func (b *backend) pathConfigTidyRoletagBlacklistExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.lockedConfigTidyRoleTags(ctx, req.Storage) - if err != nil { - return false, err - } - return entry != nil, nil -} - -func (b *backend) lockedConfigTidyRoleTags(ctx context.Context, s logical.Storage) (*tidyBlacklistRoleTagConfig, error) { - b.configMutex.RLock() - defer b.configMutex.RUnlock() - - return b.nonLockedConfigTidyRoleTags(ctx, s) -} - -func (b *backend) nonLockedConfigTidyRoleTags(ctx context.Context, s logical.Storage) (*tidyBlacklistRoleTagConfig, error) { - entry, err := s.Get(ctx, roletagBlacklistConfigPath) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result tidyBlacklistRoleTagConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathConfigTidyRoletagBlacklistCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - configEntry, err := b.nonLockedConfigTidyRoleTags(ctx, req.Storage) - if err != nil { - return nil, err - } - if configEntry == nil { - configEntry = &tidyBlacklistRoleTagConfig{} - } - safetyBufferInt, ok := data.GetOk("safety_buffer") - if ok { - configEntry.SafetyBuffer = safetyBufferInt.(int) - } else if req.Operation == logical.CreateOperation { - configEntry.SafetyBuffer = data.Get("safety_buffer").(int) - } - disablePeriodicTidyBool, ok := data.GetOk("disable_periodic_tidy") - if ok { - configEntry.DisablePeriodicTidy = disablePeriodicTidyBool.(bool) - } else if req.Operation == logical.CreateOperation { - configEntry.DisablePeriodicTidy = data.Get("disable_periodic_tidy").(bool) - } - - entry, err := logical.StorageEntryJSON(roletagBlacklistConfigPath, configEntry) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigTidyRoletagBlacklistRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - clientConfig, err := b.lockedConfigTidyRoleTags(ctx, req.Storage) - if err != nil { - return nil, err - } - if clientConfig == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "safety_buffer": clientConfig.SafetyBuffer, - "disable_periodic_tidy": clientConfig.DisablePeriodicTidy, - }, - }, nil -} - -func (b *backend) pathConfigTidyRoletagBlacklistDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.configMutex.Lock() - defer b.configMutex.Unlock() - - return nil, req.Storage.Delete(ctx, roletagBlacklistConfigPath) -} - -type tidyBlacklistRoleTagConfig struct { - SafetyBuffer int `json:"safety_buffer"` - DisablePeriodicTidy bool `json:"disable_periodic_tidy"` -} - -const pathConfigTidyRoletagBlacklistHelpSyn = ` -Configures the periodic tidying operation of the blacklisted role tag entries. -` -const pathConfigTidyRoletagBlacklistHelpDesc = ` -By default, the expired entries in the blacklist will be attempted to be removed -periodically. This operation will look for expired items in the list and purges them. -However, there is a safety buffer duration (defaults to 72h), purges the entries -only if they have been persisting this duration, past its expiration time. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_identity_whitelist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_identity_whitelist.go deleted file mode 100644 index 54587e70e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_identity_whitelist.go +++ /dev/null @@ -1,159 +0,0 @@ -package awsauth - -import ( - "context" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathIdentityWhitelist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "identity-whitelist/" + framework.GenericNameRegex("instance_id"), - Fields: map[string]*framework.FieldSchema{ - "instance_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `EC2 instance ID. A successful login operation from an EC2 instance -gets cached in this whitelist, keyed off of instance ID.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathIdentityWhitelistRead, - logical.DeleteOperation: b.pathIdentityWhitelistDelete, - }, - - HelpSynopsis: pathIdentityWhitelistSyn, - HelpDescription: pathIdentityWhitelistDesc, - } -} - -func pathListIdentityWhitelist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "identity-whitelist/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathWhitelistIdentitiesList, - }, - - HelpSynopsis: pathListIdentityWhitelistHelpSyn, - HelpDescription: pathListIdentityWhitelistHelpDesc, - } -} - -// pathWhitelistIdentitiesList is used to list all the instance IDs that are present -// in the identity whitelist. This will list both valid and expired entries. -func (b *backend) pathWhitelistIdentitiesList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - identities, err := req.Storage.List(ctx, "whitelist/identity/") - if err != nil { - return nil, err - } - return logical.ListResponse(identities), nil -} - -// Fetch an item from the whitelist given an instance ID. -func whitelistIdentityEntry(ctx context.Context, s logical.Storage, instanceID string) (*whitelistIdentity, error) { - entry, err := s.Get(ctx, "whitelist/identity/"+instanceID) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result whitelistIdentity - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -// Stores an instance ID and the information required to validate further login/renewal attempts from -// the same instance ID. -func setWhitelistIdentityEntry(ctx context.Context, s logical.Storage, instanceID string, identity *whitelistIdentity) error { - entry, err := logical.StorageEntryJSON("whitelist/identity/"+instanceID, identity) - if err != nil { - return err - } - - if err := s.Put(ctx, entry); err != nil { - return err - } - return nil -} - -// pathIdentityWhitelistDelete is used to delete an entry from the identity whitelist given an instance ID. -func (b *backend) pathIdentityWhitelistDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - instanceID := data.Get("instance_id").(string) - if instanceID == "" { - return logical.ErrorResponse("missing instance_id"), nil - } - - return nil, req.Storage.Delete(ctx, "whitelist/identity/"+instanceID) -} - -// pathIdentityWhitelistRead is used to view an entry in the identity whitelist given an instance ID. -func (b *backend) pathIdentityWhitelistRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - instanceID := data.Get("instance_id").(string) - if instanceID == "" { - return logical.ErrorResponse("missing instance_id"), nil - } - - entry, err := whitelistIdentityEntry(ctx, req.Storage, instanceID) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "role": entry.Role, - "client_nonce": entry.ClientNonce, - "creation_time": entry.CreationTime.Format(time.RFC3339Nano), - "disallow_reauthentication": entry.DisallowReauthentication, - "pending_time": entry.PendingTime, - "expiration_time": entry.ExpirationTime.Format(time.RFC3339Nano), - "last_updated_time": entry.LastUpdatedTime.Format(time.RFC3339Nano), - }, - }, nil -} - -// Struct to represent each item in the identity whitelist. -type whitelistIdentity struct { - Role string `json:"role"` - ClientNonce string `json:"client_nonce"` - CreationTime time.Time `json:"creation_time"` - DisallowReauthentication bool `json:"disallow_reauthentication"` - PendingTime string `json:"pending_time"` - ExpirationTime time.Time `json:"expiration_time"` - LastUpdatedTime time.Time `json:"last_updated_time"` -} - -const pathIdentityWhitelistSyn = ` -Read or delete entries in the identity whitelist. -` - -const pathIdentityWhitelistDesc = ` -Each login from an EC2 instance creates/updates an entry in the identity whitelist. - -Entries in this list can be viewed or deleted using this endpoint. - -By default, a cron task will periodically look for expired entries in the whitelist -and deletes them. The duration to periodically run this, is one hour by default. -However, this can be configured using the 'config/tidy/identities' endpoint. This tidy -action can be triggered via the API as well, using the 'tidy/identities' endpoint. -` - -const pathListIdentityWhitelistHelpSyn = ` -Lists the items present in the identity whitelist. -` - -const pathListIdentityWhitelistHelpDesc = ` -The entries in the identity whitelist is keyed off of the EC2 instance IDs. -This endpoint lists all the entries present in the identity whitelist, both -expired and un-expired entries. Use 'tidy/identities' endpoint to clean-up -the whitelist of identities. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_login.go deleted file mode 100644 index 950ff5159..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_login.go +++ /dev/null @@ -1,1688 +0,0 @@ -package awsauth - -import ( - "context" - "crypto/subtle" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "regexp" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/fullsailor/pkcs7" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - reauthenticationDisabledNonce = "reauthentication-disabled-nonce" - iamAuthType = "iam" - ec2AuthType = "ec2" - ec2EntityType = "ec2_instance" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login$", - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeString, - Description: `Name of the role against which the login is being attempted. -If 'role' is not specified, then the login endpoint looks for a role -bearing the name of the AMI ID of the EC2 instance that is trying to login. -If a matching role is not found, login fails.`, - }, - - "pkcs7": { - Type: framework.TypeString, - Description: `PKCS7 signature of the identity document when using an auth_type -of ec2.`, - }, - - "nonce": { - Type: framework.TypeString, - Description: `The nonce to be used for subsequent login requests when -auth_type is ec2. If this parameter is not specified at -all and if reauthentication is allowed, then the backend will generate a random -nonce, attaches it to the instance's identity-whitelist entry and returns the -nonce back as part of auth metadata. This value should be used with further -login requests, to establish client authenticity. Clients can choose to set a -custom nonce if preferred, in which case, it is recommended that clients provide -a strong nonce. If a nonce is provided but with an empty value, it indicates -intent to disable reauthentication. Note that, when 'disallow_reauthentication' -option is enabled on either the role or the role tag, the 'nonce' holds no -significance.`, - }, - - "iam_http_request_method": { - Type: framework.TypeString, - Description: `HTTP method to use for the AWS request when auth_type is -iam. This must match what has been signed in the -presigned request. Currently, POST is the only supported value`, - }, - - "iam_request_url": { - Type: framework.TypeString, - Description: `Base64-encoded full URL against which to make the AWS request -when using iam auth_type.`, - }, - - "iam_request_body": { - Type: framework.TypeString, - Description: `Base64-encoded request body when auth_type is iam. -This must match the request body included in the signature.`, - }, - "iam_request_headers": { - Type: framework.TypeString, - Description: `Base64-encoded JSON representation of the request headers when auth_type is -iam. This must at a minimum include the headers over -which AWS has included a signature.`, - }, - "identity": { - Type: framework.TypeString, - Description: `Base64 encoded EC2 instance identity document. This needs to be supplied along -with the 'signature' parameter. If using 'curl' for fetching the identity -document, consider using the option '-w 0' while piping the output to 'base64' -binary.`, - }, - "signature": { - Type: framework.TypeString, - Description: `Base64 encoded SHA256 RSA signature of the instance identity document. This -needs to be supplied along with 'identity' parameter.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLoginUpdate, - logical.AliasLookaheadOperation: b.pathLoginUpdate, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -// instanceIamRoleARN fetches the IAM role ARN associated with the given -// instance profile name -func (b *backend) instanceIamRoleARN(iamClient *iam.IAM, instanceProfileName string) (string, error) { - if iamClient == nil { - return "", fmt.Errorf("nil iamClient") - } - if instanceProfileName == "" { - return "", fmt.Errorf("missing instance profile name") - } - - profile, err := iamClient.GetInstanceProfile(&iam.GetInstanceProfileInput{ - InstanceProfileName: aws.String(instanceProfileName), - }) - if err != nil { - return "", err - } - if profile == nil { - return "", fmt.Errorf("nil output while getting instance profile details") - } - - if profile.InstanceProfile == nil { - return "", fmt.Errorf("nil instance profile in the output of instance profile details") - } - - if profile.InstanceProfile.Roles == nil || len(profile.InstanceProfile.Roles) != 1 { - return "", fmt.Errorf("invalid roles in the output of instance profile details") - } - - if profile.InstanceProfile.Roles[0].Arn == nil { - return "", fmt.Errorf("nil role ARN in the output of instance profile details") - } - - return *profile.InstanceProfile.Roles[0].Arn, nil -} - -// validateInstance queries the status of the EC2 instance using AWS EC2 API -// and checks if the instance is running and is healthy -func (b *backend) validateInstance(ctx context.Context, s logical.Storage, instanceID, region, accountID string) (*ec2.Instance, error) { - // Create an EC2 client to pull the instance information - ec2Client, err := b.clientEC2(ctx, s, region, accountID) - if err != nil { - return nil, err - } - - status, err := ec2Client.DescribeInstances(&ec2.DescribeInstancesInput{ - InstanceIds: []*string{ - aws.String(instanceID), - }, - }) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error fetching description for instance ID %q: {{err}}", instanceID), err) - } - if status == nil { - return nil, fmt.Errorf("nil output from describe instances") - } - if len(status.Reservations) == 0 { - return nil, fmt.Errorf("no reservations found in instance description") - - } - if len(status.Reservations[0].Instances) == 0 { - return nil, fmt.Errorf("no instance details found in reservations") - } - if *status.Reservations[0].Instances[0].InstanceId != instanceID { - return nil, fmt.Errorf("expected instance ID not matching the instance ID in the instance description") - } - if status.Reservations[0].Instances[0].State == nil { - return nil, fmt.Errorf("instance state in instance description is nil") - } - if *status.Reservations[0].Instances[0].State.Name != "running" { - return nil, fmt.Errorf("instance is not in 'running' state") - } - return status.Reservations[0].Instances[0], nil -} - -// validateMetadata matches the given client nonce and pending time with the -// one cached in the identity whitelist during the previous login. But, if -// reauthentication is disabled, login attempt is failed immediately. -func validateMetadata(clientNonce, pendingTime string, storedIdentity *whitelistIdentity, roleEntry *awsRoleEntry) error { - // For sanity - if !storedIdentity.DisallowReauthentication && storedIdentity.ClientNonce == "" { - return fmt.Errorf("client nonce missing in stored identity") - } - - // If reauthentication is disabled or if the nonce supplied matches a - // predefied nonce which indicates reauthentication to be disabled, - // authentication will not succeed. - if storedIdentity.DisallowReauthentication || - subtle.ConstantTimeCompare([]byte(reauthenticationDisabledNonce), []byte(clientNonce)) == 1 { - return fmt.Errorf("reauthentication is disabled") - } - - givenPendingTime, err := time.Parse(time.RFC3339, pendingTime) - if err != nil { - return err - } - - storedPendingTime, err := time.Parse(time.RFC3339, storedIdentity.PendingTime) - if err != nil { - return err - } - - // When the presented client nonce does not match the cached entry, it - // is either that a rogue client is trying to login or that a valid - // client suffered a migration. The migration is detected via - // pendingTime in the instance metadata, which sadly is only updated - // when an instance is stopped and started but *not* when the instance - // is rebooted. If reboot survivability is needed, either - // instrumentation to delete the instance ID from the whitelist is - // necessary, or the client must durably store the nonce. - // - // If the `allow_instance_migration` property of the registered role is - // enabled, then the client nonce mismatch is ignored, as long as the - // pending time in the presented instance identity document is newer - // than the cached pending time. The new pendingTime is stored and used - // for future checks. - // - // This is a weak criterion and hence the `allow_instance_migration` - // option should be used with caution. - if subtle.ConstantTimeCompare([]byte(clientNonce), []byte(storedIdentity.ClientNonce)) != 1 { - if !roleEntry.AllowInstanceMigration { - return fmt.Errorf("client nonce mismatch") - } - if roleEntry.AllowInstanceMigration && !givenPendingTime.After(storedPendingTime) { - return fmt.Errorf("client nonce mismatch and instance meta-data incorrect") - } - } - - // Ensure that the 'pendingTime' on the given identity document is not - // before the 'pendingTime' that was used for previous login. This - // disallows old metadata documents from being used to perform login. - if givenPendingTime.Before(storedPendingTime) { - return fmt.Errorf("instance meta-data is older than the one used for previous login") - } - return nil -} - -// Verifies the integrity of the instance identity document using its SHA256 -// RSA signature. After verification, returns the unmarshaled instance identity -// document. -func (b *backend) verifyInstanceIdentitySignature(ctx context.Context, s logical.Storage, identityBytes, signatureBytes []byte) (*identityDocument, error) { - if len(identityBytes) == 0 { - return nil, fmt.Errorf("missing instance identity document") - } - - if len(signatureBytes) == 0 { - return nil, fmt.Errorf("missing SHA256 RSA signature of the instance identity document") - } - - // Get the public certificates that are used to verify the signature. - // This returns a slice of certificates containing the default - // certificate and all the registered certificates via - // 'config/certificate/' endpoint, for verifying the RSA - // digest. - publicCerts, err := b.awsPublicCertificates(ctx, s, false) - if err != nil { - return nil, err - } - if publicCerts == nil || len(publicCerts) == 0 { - return nil, fmt.Errorf("certificates to verify the signature are not found") - } - - // Check if any of the certs registered at the backend can verify the - // signature - for _, cert := range publicCerts { - err := cert.CheckSignature(x509.SHA256WithRSA, identityBytes, signatureBytes) - if err == nil { - var identityDoc identityDocument - if decErr := jsonutil.DecodeJSON(identityBytes, &identityDoc); decErr != nil { - return nil, decErr - } - return &identityDoc, nil - } - } - - return nil, fmt.Errorf("instance identity verification using SHA256 RSA signature is unsuccessful") -} - -// Verifies the correctness of the authenticated attributes present in the PKCS#7 -// signature. After verification, extracts the instance identity document from the -// signature, parses it and returns it. -func (b *backend) parseIdentityDocument(ctx context.Context, s logical.Storage, pkcs7B64 string) (*identityDocument, error) { - // Insert the header and footer for the signature to be able to pem decode it - pkcs7B64 = fmt.Sprintf("-----BEGIN PKCS7-----\n%s\n-----END PKCS7-----", pkcs7B64) - - // Decode the PEM encoded signature - pkcs7BER, pkcs7Rest := pem.Decode([]byte(pkcs7B64)) - if len(pkcs7Rest) != 0 { - return nil, fmt.Errorf("failed to decode the PEM encoded PKCS#7 signature") - } - - // Parse the signature from asn1 format into a struct - pkcs7Data, err := pkcs7.Parse(pkcs7BER.Bytes) - if err != nil { - return nil, errwrap.Wrapf("failed to parse the BER encoded PKCS#7 signature: {{err}}", err) - } - - // Get the public certificates that are used to verify the signature. - // This returns a slice of certificates containing the default certificate - // and all the registered certificates via 'config/certificate/' endpoint - publicCerts, err := b.awsPublicCertificates(ctx, s, true) - if err != nil { - return nil, err - } - if publicCerts == nil || len(publicCerts) == 0 { - return nil, fmt.Errorf("certificates to verify the signature are not found") - } - - // Before calling Verify() on the PKCS#7 struct, set the certificates to be used - // to verify the contents in the signer information. - pkcs7Data.Certificates = publicCerts - - // Verify extracts the authenticated attributes in the PKCS#7 signature, and verifies - // the authenticity of the content using 'dsa.PublicKey' embedded in the public certificate. - if pkcs7Data.Verify() != nil { - return nil, fmt.Errorf("failed to verify the signature") - } - - // Check if the signature has content inside of it - if len(pkcs7Data.Content) == 0 { - return nil, fmt.Errorf("instance identity document could not be found in the signature") - } - - var identityDoc identityDocument - if err := jsonutil.DecodeJSON(pkcs7Data.Content, &identityDoc); err != nil { - return nil, err - } - - return &identityDoc, nil -} - -func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - anyEc2, allEc2 := hasValuesForEc2Auth(data) - anyIam, allIam := hasValuesForIamAuth(data) - switch { - case anyEc2 && anyIam: - return logical.ErrorResponse("supplied auth values for both ec2 and iam auth types"), nil - case anyEc2 && !allEc2: - return logical.ErrorResponse("supplied some of the auth values for the ec2 auth type but not all"), nil - case anyEc2: - return b.pathLoginUpdateEc2(ctx, req, data) - case anyIam && !allIam: - return logical.ErrorResponse("supplied some of the auth values for the iam auth type but not all"), nil - case anyIam: - return b.pathLoginUpdateIam(ctx, req, data) - default: - return logical.ErrorResponse("didn't supply required authentication values"), nil - } -} - -// Returns whether the EC2 instance meets the requirements of the particular -// AWS role entry. -// The first error return value is whether there's some sort of validation -// error that means the instance doesn't meet the role requirements -// The second error return value indicates whether there's an error in even -// trying to validate those requirements -func (b *backend) verifyInstanceMeetsRoleRequirements(ctx context.Context, - s logical.Storage, instance *ec2.Instance, roleEntry *awsRoleEntry, roleName string, identityDoc *identityDocument) (error, error) { - - switch { - case instance == nil: - return nil, fmt.Errorf("nil instance") - case roleEntry == nil: - return nil, fmt.Errorf("nil roleEntry") - case identityDoc == nil: - return nil, fmt.Errorf("nil identityDoc") - } - - // Verify that the instance ID matches one of the ones set by the role - if len(roleEntry.BoundEc2InstanceIDs) > 0 && !strutil.StrListContains(roleEntry.BoundEc2InstanceIDs, *instance.InstanceId) { - return fmt.Errorf("instance ID %q does not belong to the role %q", *instance.InstanceId, roleName), nil - } - - // Verify that the AccountID of the instance trying to login matches the - // AccountID specified as a constraint on role - if len(roleEntry.BoundAccountIDs) > 0 && !strutil.StrListContains(roleEntry.BoundAccountIDs, identityDoc.AccountID) { - return fmt.Errorf("account ID %q does not belong to role %q", identityDoc.AccountID, roleName), nil - } - - // Verify that the AMI ID of the instance trying to login matches the - // AMI ID specified as a constraint on the role. - // - // Here, we're making a tradeoff and pulling the AMI ID out of the EC2 - // API rather than the signed instance identity doc. They *should* match. - // This means we require an EC2 API call to retrieve the AMI ID, but we're - // already calling the API to validate the Instance ID anyway, so it shouldn't - // matter. The benefit is that we have the exact same code whether auth_type - // is ec2 or iam. - if len(roleEntry.BoundAmiIDs) > 0 { - if instance.ImageId == nil { - return nil, fmt.Errorf("AMI ID in the instance description is nil") - } - if !strutil.StrListContains(roleEntry.BoundAmiIDs, *instance.ImageId) { - return fmt.Errorf("AMI ID %q does not belong to role %q", *instance.ImageId, roleName), nil - } - } - - // Validate the SubnetID if corresponding bound was set on the role - if len(roleEntry.BoundSubnetIDs) > 0 { - if instance.SubnetId == nil { - return nil, fmt.Errorf("subnet ID in the instance description is nil") - } - if !strutil.StrListContains(roleEntry.BoundSubnetIDs, *instance.SubnetId) { - return fmt.Errorf("subnet ID %q does not satisfy the constraint on role %q", *instance.SubnetId, roleName), nil - } - } - - // Validate the VpcID if corresponding bound was set on the role - if len(roleEntry.BoundVpcIDs) > 0 { - if instance.VpcId == nil { - return nil, fmt.Errorf("VPC ID in the instance description is nil") - } - if !strutil.StrListContains(roleEntry.BoundVpcIDs, *instance.VpcId) { - return fmt.Errorf("VPC ID %q does not satisfy the constraint on role %q", *instance.VpcId, roleName), nil - } - } - - // Check if the IAM instance profile ARN of the instance trying to - // login, matches the IAM instance profile ARN specified as a constraint - // on the role - if len(roleEntry.BoundIamInstanceProfileARNs) > 0 { - if instance.IamInstanceProfile == nil { - return nil, fmt.Errorf("IAM instance profile in the instance description is nil") - } - if instance.IamInstanceProfile.Arn == nil { - return nil, fmt.Errorf("IAM instance profile ARN in the instance description is nil") - } - iamInstanceProfileARN := *instance.IamInstanceProfile.Arn - matchesInstanceProfile := false - // NOTE: Can't use strutil.StrListContainsGlob. A * is a perfectly valid character in the "path" component - // of an ARN. See, e.g., https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html : - // The path allows strings "containing any ASCII character from the ! (\u0021) thru the DEL character - // (\u007F), including most punctuation characters, digits, and upper and lowercased letters." - // So, e.g., arn:aws:iam::123456789012:instance-profile/Some*Path/MyProfileName is a perfectly valid instance - // profile ARN, and it wouldn't be correct to expand the * in the middle as a wildcard. - // If a user wants to match an IAM instance profile arn beginning with arn:aws:iam::123456789012:instance-profile/foo* - // then bound_iam_instance_profile_arn would need to be arn:aws:iam::123456789012:instance-profile/foo** - // Wanting to exactly match an ARN that has a * at the end is not a valid use case. The * is only valid in the - // path; it's not valid in the name. That means no valid ARN can ever end with a *. For example, - // arn:aws:iam::123456789012:instance-profile/Foo* is NOT valid as an instance profile ARN, so no valid instance - // profile ARN could ever equal that value. - for _, boundInstanceProfileARN := range roleEntry.BoundIamInstanceProfileARNs { - switch { - case strings.HasSuffix(boundInstanceProfileARN, "*") && strings.HasPrefix(iamInstanceProfileARN, boundInstanceProfileARN[:len(boundInstanceProfileARN)-1]): - matchesInstanceProfile = true - break - case iamInstanceProfileARN == boundInstanceProfileARN: - matchesInstanceProfile = true - break - } - } - if !matchesInstanceProfile { - return fmt.Errorf("IAM instance profile ARN %q does not satisfy the constraint role %q", iamInstanceProfileARN, roleName), nil - } - } - - // Check if the IAM role ARN of the instance trying to login, matches - // the IAM role ARN specified as a constraint on the role. - if len(roleEntry.BoundIamRoleARNs) > 0 { - if instance.IamInstanceProfile == nil { - return nil, fmt.Errorf("IAM instance profile in the instance description is nil") - } - if instance.IamInstanceProfile.Arn == nil { - return nil, fmt.Errorf("IAM instance profile ARN in the instance description is nil") - } - - // Fetch the instance profile ARN from the instance description - iamInstanceProfileARN := *instance.IamInstanceProfile.Arn - - if iamInstanceProfileARN == "" { - return nil, fmt.Errorf("IAM instance profile ARN in the instance description is empty") - } - - // Extract out the instance profile name from the instance - // profile ARN - iamInstanceProfileEntity, err := parseIamArn(iamInstanceProfileARN) - - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to parse IAM instance profile ARN %q: {{err}}", iamInstanceProfileARN), err) - } - - // Use instance profile ARN to fetch the associated role ARN - iamClient, err := b.clientIAM(ctx, s, identityDoc.Region, identityDoc.AccountID) - if err != nil { - return nil, errwrap.Wrapf("could not fetch IAM client: {{err}}", err) - } else if iamClient == nil { - return nil, fmt.Errorf("received a nil iamClient") - } - iamRoleARN, err := b.instanceIamRoleARN(iamClient, iamInstanceProfileEntity.FriendlyName) - if err != nil { - return nil, errwrap.Wrapf("IAM role ARN could not be fetched: {{err}}", err) - } - if iamRoleARN == "" { - return nil, fmt.Errorf("IAM role ARN could not be fetched") - } - - matchesInstanceRoleARN := false - for _, boundIamRoleARN := range roleEntry.BoundIamRoleARNs { - switch { - // as with boundInstanceProfileARN, can't use strutil.StrListContainsGlob because * can validly exist in the middle of an ARN - case strings.HasSuffix(boundIamRoleARN, "*") && strings.HasPrefix(iamRoleARN, boundIamRoleARN[:len(boundIamRoleARN)-1]): - matchesInstanceRoleARN = true - break - case iamRoleARN == boundIamRoleARN: - matchesInstanceRoleARN = true - break - } - } - if !matchesInstanceRoleARN { - return fmt.Errorf("IAM role ARN %q does not satisfy the constraint role %q", iamRoleARN, roleName), nil - } - } - - return nil, nil -} - -// pathLoginUpdateEc2 is used to create a Vault token by the EC2 instances -// by providing the pkcs7 signature of the instance identity document -// and a client created nonce. Client nonce is optional if 'disallow_reauthentication' -// option is enabled on the registered role. -func (b *backend) pathLoginUpdateEc2(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - identityDocB64 := data.Get("identity").(string) - var identityDocBytes []byte - var err error - if identityDocB64 != "" { - identityDocBytes, err = base64.StdEncoding.DecodeString(identityDocB64) - if err != nil || len(identityDocBytes) == 0 { - return logical.ErrorResponse("failed to base64 decode the instance identity document"), nil - } - } - - signatureB64 := data.Get("signature").(string) - var signatureBytes []byte - if signatureB64 != "" { - signatureBytes, err = base64.StdEncoding.DecodeString(signatureB64) - if err != nil { - return logical.ErrorResponse("failed to base64 decode the SHA256 RSA signature of the instance identity document"), nil - } - } - - pkcs7B64 := data.Get("pkcs7").(string) - - // Either the pkcs7 signature of the instance identity document, or - // the identity document itself along with its SHA256 RSA signature - // needs to be provided. - if pkcs7B64 == "" && (len(identityDocBytes) == 0 && len(signatureBytes) == 0) { - return logical.ErrorResponse("either pkcs7 or a tuple containing the instance identity document and its SHA256 RSA signature needs to be provided"), nil - } else if pkcs7B64 != "" && (len(identityDocBytes) != 0 && len(signatureBytes) != 0) { - return logical.ErrorResponse("both pkcs7 and a tuple containing the instance identity document and its SHA256 RSA signature is supplied; provide only one"), nil - } - - // Verify the signature of the identity document and unmarshal it - var identityDocParsed *identityDocument - if pkcs7B64 != "" { - identityDocParsed, err = b.parseIdentityDocument(ctx, req.Storage, pkcs7B64) - if err != nil { - return nil, err - } - if identityDocParsed == nil { - return logical.ErrorResponse("failed to verify the instance identity document using pkcs7"), nil - } - } else { - identityDocParsed, err = b.verifyInstanceIdentitySignature(ctx, req.Storage, identityDocBytes, signatureBytes) - if err != nil { - return nil, err - } - if identityDocParsed == nil { - return logical.ErrorResponse("failed to verify the instance identity document using the SHA256 RSA digest"), nil - } - } - - // If we're just looking up for MFA, return the Alias info - if req.Operation == logical.AliasLookaheadOperation { - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: identityDocParsed.InstanceID, - }, - }, - }, nil - } - - roleName := data.Get("role").(string) - - // If roleName is not supplied, a role in the name of the instance's AMI ID will be looked for - if roleName == "" { - roleName = identityDocParsed.AmiID - } - - // Get the entry for the role used by the instance - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("entry for role %q not found", roleName)), nil - } - - if roleEntry.AuthType != ec2AuthType { - return logical.ErrorResponse(fmt.Sprintf("auth method ec2 not allowed for role %s", roleName)), nil - } - - // Validate the instance ID by making a call to AWS EC2 DescribeInstances API - // and fetching the instance description. Validation succeeds only if the - // instance is in 'running' state. - instance, err := b.validateInstance(ctx, req.Storage, identityDocParsed.InstanceID, identityDocParsed.Region, identityDocParsed.AccountID) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to verify instance ID: %v", err)), nil - } - - // Verify that the `Region` of the instance trying to login matches the - // `Region` specified as a constraint on role - if len(roleEntry.BoundRegions) > 0 && !strutil.StrListContains(roleEntry.BoundRegions, identityDocParsed.Region) { - return logical.ErrorResponse(fmt.Sprintf("Region %q does not satisfy the constraint on role %q", identityDocParsed.Region, roleName)), nil - } - - validationError, err := b.verifyInstanceMeetsRoleRequirements(ctx, req.Storage, instance, roleEntry, roleName, identityDocParsed) - if err != nil { - return nil, err - } - if validationError != nil { - return logical.ErrorResponse(fmt.Sprintf("Error validating instance: %v", validationError)), nil - } - - // Get the entry from the identity whitelist, if there is one - storedIdentity, err := whitelistIdentityEntry(ctx, req.Storage, identityDocParsed.InstanceID) - if err != nil { - return nil, err - } - - // disallowReauthentication value that gets cached at the stored - // identity-whitelist entry is determined not just by the role entry. - // If client explicitly sets nonce to be empty, it implies intent to - // disable reauthentication. Also, role tag can override the 'false' - // value with 'true' (the other way around is not allowed). - - // Read the value from the role entry - disallowReauthentication := roleEntry.DisallowReauthentication - - clientNonce := "" - - // Check if the nonce is supplied by the client - clientNonceRaw, clientNonceSupplied := data.GetOk("nonce") - if clientNonceSupplied { - clientNonce = clientNonceRaw.(string) - - // Nonce explicitly set to empty implies intent to disable - // reauthentication by the client. Set a predefined nonce which - // indicates reauthentication being disabled. - if clientNonce == "" { - clientNonce = reauthenticationDisabledNonce - - // Ensure that the intent lands in the whitelist - disallowReauthentication = true - } - } - - // This is NOT a first login attempt from the client - if storedIdentity != nil { - // Check if the client nonce match the cached nonce and if the pending time - // of the identity document is not before the pending time of the document - // with which previous login was made. If 'allow_instance_migration' is - // enabled on the registered role, client nonce requirement is relaxed. - if err = validateMetadata(clientNonce, identityDocParsed.PendingTime, storedIdentity, roleEntry); err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - // Don't let subsequent login attempts to bypass the initial - // intent of disabling reauthentication, despite the properties - // of role getting updated. For example: Role has the value set - // to 'false', a role-tag login sets the value to 'true', then - // role gets updated to not use a role-tag, and a login attempt - // is made with role's value set to 'false'. Removing the entry - // from the identity-whitelist should be the only way to be - // able to login from the instance again. - disallowReauthentication = disallowReauthentication || storedIdentity.DisallowReauthentication - } - - // If we reach this point without erroring and if the client nonce was - // not supplied, a first time login is implied and that the client - // intends that the nonce be generated by the backend. Create a random - // nonce to be associated for the instance ID. - if !clientNonceSupplied { - if clientNonce, err = uuid.GenerateUUID(); err != nil { - return nil, fmt.Errorf("failed to generate random nonce") - } - } - - // Load the current values for max TTL and policies from the role entry, - // before checking for overriding max TTL in the role tag. The shortest - // max TTL is used to cap the token TTL; the longest max TTL is used to - // make the whitelist entry as long as possible as it controls for replay - // attacks. - shortestMaxTTL := b.System().MaxLeaseTTL() - longestMaxTTL := b.System().MaxLeaseTTL() - if roleEntry.MaxTTL > time.Duration(0) && roleEntry.MaxTTL < shortestMaxTTL { - shortestMaxTTL = roleEntry.MaxTTL - } - if roleEntry.MaxTTL > longestMaxTTL { - longestMaxTTL = roleEntry.MaxTTL - } - - policies := roleEntry.Policies - rTagMaxTTL := time.Duration(0) - var roleTagResp *roleTagLoginResponse - if roleEntry.RoleTag != "" { - roleTagResp, err = b.handleRoleTagLogin(ctx, req.Storage, roleName, roleEntry, instance) - if err != nil { - return nil, err - } - if roleTagResp == nil { - return logical.ErrorResponse("failed to fetch and verify the role tag"), nil - } - } - - if roleTagResp != nil { - // Role tag is enabled on the role. - - // Overwrite the policies with the ones returned from processing the role tag - // If there are no policies on the role tag, policies on the role are inherited. - // If policies on role tag are set, by this point, it is verified that it is a subset of the - // policies on the role. So, apply only those. - if len(roleTagResp.Policies) != 0 { - policies = roleTagResp.Policies - } - - // If roleEntry had disallowReauthentication set to 'true', do not reset it - // to 'false' based on role tag having it not set. But, if role tag had it set, - // be sure to override the value. - if !disallowReauthentication { - disallowReauthentication = roleTagResp.DisallowReauthentication - } - - // Cache the value of role tag's max_ttl value - rTagMaxTTL = roleTagResp.MaxTTL - - // Scope the shortestMaxTTL to the value set on the role tag - if roleTagResp.MaxTTL > time.Duration(0) && roleTagResp.MaxTTL < shortestMaxTTL { - shortestMaxTTL = roleTagResp.MaxTTL - } - if roleTagResp.MaxTTL > longestMaxTTL { - longestMaxTTL = roleTagResp.MaxTTL - } - } - - // Save the login attempt in the identity whitelist - currentTime := time.Now() - if storedIdentity == nil { - // Role, ClientNonce and CreationTime of the identity entry, - // once set, should never change. - storedIdentity = &whitelistIdentity{ - Role: roleName, - ClientNonce: clientNonce, - CreationTime: currentTime, - } - } - - // DisallowReauthentication, PendingTime, LastUpdatedTime and - // ExpirationTime may change. - storedIdentity.LastUpdatedTime = currentTime - storedIdentity.ExpirationTime = currentTime.Add(longestMaxTTL) - storedIdentity.PendingTime = identityDocParsed.PendingTime - storedIdentity.DisallowReauthentication = disallowReauthentication - - // Don't cache the nonce if DisallowReauthentication is set - if storedIdentity.DisallowReauthentication { - storedIdentity.ClientNonce = "" - } - - // Sanitize the nonce to a reasonable length - if len(clientNonce) > 128 && !storedIdentity.DisallowReauthentication { - return logical.ErrorResponse("client nonce exceeding the limit of 128 characters"), nil - } - - if err = setWhitelistIdentityEntry(ctx, req.Storage, identityDocParsed.InstanceID, storedIdentity); err != nil { - return nil, err - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - Period: roleEntry.Period, - Policies: policies, - Metadata: map[string]string{ - "instance_id": identityDocParsed.InstanceID, - "region": identityDocParsed.Region, - "account_id": identityDocParsed.AccountID, - "role_tag_max_ttl": rTagMaxTTL.String(), - "role": roleName, - "ami_id": identityDocParsed.AmiID, - }, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: roleEntry.TTL, - MaxTTL: shortestMaxTTL, - }, - Alias: &logical.Alias{ - Name: identityDocParsed.InstanceID, - }, - }, - } - - // Return the nonce only if reauthentication is allowed and if the nonce - // was not supplied by the user. - if !disallowReauthentication && !clientNonceSupplied { - // Echo the client nonce back. If nonce param was not supplied - // to the endpoint at all (setting it to empty string does not - // qualify here), callers should extract out the nonce from - // this field for reauthentication requests. - resp.Auth.Metadata["nonce"] = clientNonce - } - - return resp, nil -} - -// handleRoleTagLogin is used to fetch the role tag of the instance and -// verifies it to be correct. Then the policies for the login request will be -// set off of the role tag, if certain criteria satisfies. -func (b *backend) handleRoleTagLogin(ctx context.Context, s logical.Storage, roleName string, roleEntry *awsRoleEntry, instance *ec2.Instance) (*roleTagLoginResponse, error) { - if roleEntry == nil { - return nil, fmt.Errorf("nil role entry") - } - if instance == nil { - return nil, fmt.Errorf("nil instance") - } - - // Input validation on instance is not performed here considering - // that it would have been done in validateInstance method. - tags := instance.Tags - if tags == nil || len(tags) == 0 { - return nil, fmt.Errorf("missing tag with key %q on the instance", roleEntry.RoleTag) - } - - // Iterate through the tags attached on the instance and look for - // a tag with its 'key' matching the expected role tag value. - rTagValue := "" - for _, tagItem := range tags { - if tagItem.Key != nil && *tagItem.Key == roleEntry.RoleTag { - rTagValue = *tagItem.Value - break - } - } - - // If 'role_tag' is enabled on the role, and if a corresponding tag is not found - // to be attached to the instance, fail. - if rTagValue == "" { - return nil, fmt.Errorf("missing tag with key %q on the instance", roleEntry.RoleTag) - } - - // Parse the role tag into a struct, extract the plaintext part of it and verify its HMAC - rTag, err := b.parseAndVerifyRoleTagValue(ctx, s, rTagValue) - if err != nil { - return nil, err - } - - // Check if the role name with which this login is being made is same - // as the role name embedded in the tag. - if rTag.Role != roleName { - return nil, fmt.Errorf("role on the tag is not matching the role supplied") - } - - // If instance_id was set on the role tag, check if the same instance is attempting to login - if rTag.InstanceID != "" && rTag.InstanceID != *instance.InstanceId { - return nil, fmt.Errorf("role tag is being used by an unauthorized instance") - } - - // Check if the role tag is blacklisted - blacklistEntry, err := b.lockedBlacklistRoleTagEntry(ctx, s, rTagValue) - if err != nil { - return nil, err - } - if blacklistEntry != nil { - return nil, fmt.Errorf("role tag is blacklisted") - } - - // Ensure that the policies on the RoleTag is a subset of policies on the role - if !strutil.StrListSubset(roleEntry.Policies, rTag.Policies) { - return nil, fmt.Errorf("policies on the role tag must be subset of policies on the role") - } - - return &roleTagLoginResponse{ - Policies: rTag.Policies, - MaxTTL: rTag.MaxTTL, - DisallowReauthentication: rTag.DisallowReauthentication, - }, nil -} - -// pathLoginRenew is used to renew an authenticated token -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - authType, ok := req.Auth.Metadata["auth_type"] - if !ok { - // backwards compatibility for clients that have leases from before we added auth_type - authType = ec2AuthType - } - - if authType == ec2AuthType { - return b.pathLoginRenewEc2(ctx, req, data) - } else if authType == iamAuthType { - return b.pathLoginRenewIam(ctx, req, data) - } else { - return nil, fmt.Errorf("unrecognized auth_type: %q", authType) - } -} - -func (b *backend) pathLoginRenewIam(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - canonicalArn := req.Auth.Metadata["canonical_arn"] - if canonicalArn == "" { - return nil, fmt.Errorf("unable to retrieve canonical ARN from metadata during renewal") - } - - roleName := "" - roleNameIfc, ok := req.Auth.InternalData["role_name"] - if ok { - roleName = roleNameIfc.(string) - } - if roleName == "" { - return nil, fmt.Errorf("error retrieving role_name during renewal") - } - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if roleEntry == nil { - return nil, fmt.Errorf("role entry not found") - } - - // we don't really care what the inferred entity type was when the role was initially created. We - // care about what the role currently requires. However, the metadata's inferred_entity_id is only - // set when inferencing is turned on at initial login time. So, if inferencing is turned on, any - // existing roles will NOT be able to renew tokens. - // This might change later, but authenticating the actual inferred entity ID is NOT done if there - // is no inferencing requested in the role. The reason is that authenticating the inferred entity - // ID requires additional AWS IAM permissions that might not be present (e.g., - // ec2:DescribeInstances) as well as additional inferencing configuration (the inferred region). - // So, for now, if you want to turn on inferencing, all clients must re-authenticate and cannot - // renew existing tokens. - if roleEntry.InferredEntityType != "" { - if roleEntry.InferredEntityType == ec2EntityType { - instanceID, ok := req.Auth.Metadata["inferred_entity_id"] - if !ok { - return nil, fmt.Errorf("no inferred entity ID in auth metadata") - } - instanceRegion, ok := req.Auth.Metadata["inferred_aws_region"] - if !ok { - return nil, fmt.Errorf("no inferred AWS region in auth metadata") - } - _, err := b.validateInstance(ctx, req.Storage, instanceID, instanceRegion, req.Auth.Metadata["account_id"]) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to verify instance ID %q: {{err}}", instanceID), err) - } - } else { - return nil, fmt.Errorf("unrecognized entity_type in metadata: %q", roleEntry.InferredEntityType) - } - } - - // Note that the error messages below can leak a little bit of information about the role information - // For example, if on renew, the client gets the "error parsing ARN..." error message, the client - // will know that it's a wildcard bind (but not the actual bind), even if the client can't actually - // read the role directly to know what the bind is. It's a relatively small amount of leakage, in - // some fairly corner cases, and in the most likely error case (role has been changed to a new ARN), - // the error message is identical. - if len(roleEntry.BoundIamPrincipalARNs) > 0 { - // We might not get here if all bindings were on the inferred entity, which we've already validated - // above - // As with logins, there are three ways to pass this check: - // 1: clientUserId is in roleEntry.BoundIamPrincipalIDs (entries in roleEntry.BoundIamPrincipalIDs - // implies that roleEntry.ResolveAWSUniqueIDs is true) - // 2: roleEntry.ResolveAWSUniqueIDs is false and canonical_arn is in roleEntry.BoundIamPrincipalARNs - // 3: Full ARN matches one of the wildcard globs in roleEntry.BoundIamPrincipalARNs - clientUserId, ok := req.Auth.Metadata["client_user_id"] - switch { - case ok && strutil.StrListContains(roleEntry.BoundIamPrincipalIDs, clientUserId): // check 1 passed - case !roleEntry.ResolveAWSUniqueIDs && strutil.StrListContains(roleEntry.BoundIamPrincipalARNs, canonicalArn): // check 2 passed - default: - // check 3 is a bit more complex, so we do it last - fullArn := b.getCachedUserId(clientUserId) - if fullArn == "" { - entity, err := parseIamArn(canonicalArn) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing ARN %q: {{err}}", canonicalArn), err) - } - fullArn, err = b.fullArn(ctx, entity, req.Storage) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error looking up full ARN of entity %v: {{err}}", entity), err) - } - if fullArn == "" { - return nil, fmt.Errorf("got empty string back when looking up full ARN of entity %v", entity) - } - if clientUserId != "" { - b.setCachedUserId(clientUserId, fullArn) - } - } - matchedWildcardBind := false - for _, principalARN := range roleEntry.BoundIamPrincipalARNs { - if strings.HasSuffix(principalARN, "*") && strutil.GlobbedStringsMatch(principalARN, fullArn) { - matchedWildcardBind = true - break - } - } - if !matchedWildcardBind { - return nil, fmt.Errorf("role no longer bound to ARN %q", canonicalArn) - } - } - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = roleEntry.TTL - resp.Auth.MaxTTL = roleEntry.MaxTTL - resp.Auth.Period = roleEntry.Period - return resp, nil -} - -func (b *backend) pathLoginRenewEc2(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - instanceID := req.Auth.Metadata["instance_id"] - if instanceID == "" { - return nil, fmt.Errorf("unable to fetch instance ID from metadata during renewal") - } - - region := req.Auth.Metadata["region"] - if region == "" { - return nil, fmt.Errorf("unable to fetch region from metadata during renewal") - } - - // Ensure backwards compatibility for older clients without account_id saved in metadata - accountID, ok := req.Auth.Metadata["account_id"] - if ok { - if accountID == "" { - return nil, fmt.Errorf("unable to fetch account_id from metadata during renewal") - } - } - - // Cross check that the instance is still in 'running' state - _, err := b.validateInstance(ctx, req.Storage, instanceID, region, accountID) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to verify instance ID %q: {{err}}", instanceID), err) - } - - storedIdentity, err := whitelistIdentityEntry(ctx, req.Storage, instanceID) - if err != nil { - return nil, err - } - if storedIdentity == nil { - return nil, fmt.Errorf("failed to verify the whitelist identity entry for instance ID: %q", instanceID) - } - - // Ensure that role entry is not deleted - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, storedIdentity.Role) - if err != nil { - return nil, err - } - if roleEntry == nil { - return nil, fmt.Errorf("role entry not found") - } - - // If the login was made using the role tag, then max_ttl from tag - // is cached in internal data during login and used here to cap the - // max_ttl of renewal. - rTagMaxTTL, err := time.ParseDuration(req.Auth.Metadata["role_tag_max_ttl"]) - if err != nil { - return nil, err - } - - // Re-evaluate the maxTTL bounds - shortestMaxTTL := b.System().MaxLeaseTTL() - longestMaxTTL := b.System().MaxLeaseTTL() - if roleEntry.MaxTTL > time.Duration(0) && roleEntry.MaxTTL < shortestMaxTTL { - shortestMaxTTL = roleEntry.MaxTTL - } - if roleEntry.MaxTTL > longestMaxTTL { - longestMaxTTL = roleEntry.MaxTTL - } - if rTagMaxTTL > time.Duration(0) && rTagMaxTTL < shortestMaxTTL { - shortestMaxTTL = rTagMaxTTL - } - if rTagMaxTTL > longestMaxTTL { - longestMaxTTL = rTagMaxTTL - } - - // Only LastUpdatedTime and ExpirationTime change and all other fields remain the same - currentTime := time.Now() - storedIdentity.LastUpdatedTime = currentTime - storedIdentity.ExpirationTime = currentTime.Add(longestMaxTTL) - - // Updating the expiration time is required for the tidy operation on the - // whitelist identity storage items - if err = setWhitelistIdentityEntry(ctx, req.Storage, instanceID, storedIdentity); err != nil { - return nil, err - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = roleEntry.TTL - resp.Auth.MaxTTL = shortestMaxTTL - resp.Auth.Period = roleEntry.Period - return resp, nil -} - -func (b *backend) pathLoginUpdateIam(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - method := data.Get("iam_http_request_method").(string) - if method == "" { - return logical.ErrorResponse("missing iam_http_request_method"), nil - } - - // In the future, might consider supporting GET - if method != "POST" { - return logical.ErrorResponse("invalid iam_http_request_method; currently only 'POST' is supported"), nil - } - - rawUrlB64 := data.Get("iam_request_url").(string) - if rawUrlB64 == "" { - return logical.ErrorResponse("missing iam_request_url"), nil - } - rawUrl, err := base64.StdEncoding.DecodeString(rawUrlB64) - if err != nil { - return logical.ErrorResponse("failed to base64 decode iam_request_url"), nil - } - parsedUrl, err := url.Parse(string(rawUrl)) - if err != nil { - return logical.ErrorResponse("error parsing iam_request_url"), nil - } - - // TODO: There are two potentially valid cases we're not yet supporting that would - // necessitate this check being changed. First, if we support GET requests. - // Second if we support presigned POST requests - bodyB64 := data.Get("iam_request_body").(string) - if bodyB64 == "" { - return logical.ErrorResponse("missing iam_request_body"), nil - } - bodyRaw, err := base64.StdEncoding.DecodeString(bodyB64) - if err != nil { - return logical.ErrorResponse("failed to base64 decode iam_request_body"), nil - } - body := string(bodyRaw) - - headersB64 := data.Get("iam_request_headers").(string) - if headersB64 == "" { - return logical.ErrorResponse("missing iam_request_headers"), nil - } - headers, err := parseIamRequestHeaders(headersB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error parsing iam_request_headers: %v", err)), nil - } - if headers == nil { - return logical.ErrorResponse("nil response when parsing iam_request_headers"), nil - } - - config, err := b.lockedClientConfigEntry(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse("error getting configuration"), nil - } - - endpoint := "https://sts.amazonaws.com" - - if config != nil { - if config.IAMServerIdHeaderValue != "" { - err = validateVaultHeaderValue(headers, parsedUrl, config.IAMServerIdHeaderValue) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error validating %s header: %v", iamServerIdHeader, err)), nil - } - } - if config.STSEndpoint != "" { - endpoint = config.STSEndpoint - } - } - - callerID, err := submitCallerIdentityRequest(method, endpoint, parsedUrl, body, headers) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error making upstream request: %v", err)), nil - } - // This could either be a "userID:SessionID" (in the case of an assumed role) or just a "userID" - // (in the case of an IAM user). - callerUniqueId := strings.Split(callerID.UserId, ":")[0] - - // If we're just looking up for MFA, return the Alias info - if req.Operation == logical.AliasLookaheadOperation { - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: callerUniqueId, - }, - }, - }, nil - } - - entity, err := parseIamArn(callerID.Arn) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error parsing arn %q: %v", callerID.Arn, err)), nil - } - - roleName := data.Get("role").(string) - if roleName == "" { - roleName = entity.FriendlyName - } - - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("entry for role %s not found", roleName)), nil - } - - if roleEntry.AuthType != iamAuthType { - return logical.ErrorResponse(fmt.Sprintf("auth method iam not allowed for role %s", roleName)), nil - } - - // The role creation should ensure that either we're inferring this is an EC2 instance - // or that we're binding an ARN - if len(roleEntry.BoundIamPrincipalARNs) > 0 { - // As with renews, there are three ways to pass this check: - // 1: callerUniqueId is in roleEntry.BoundIamPrincipalIDs (entries in roleEntry.BoundIamPrincipalIDs - // implies that roleEntry.ResolveAWSUniqueIDs is true) - // 2: roleEntry.ResolveAWSUniqueIDs is false and entity.canonicalArn() is in roleEntry.BoundIamPrincipalARNs - // 3: Full ARN matches one of the wildcard globs in roleEntry.BoundIamPrincipalARNs - // Need to be able to handle pathological configurations such as roleEntry.BoundIamPrincipalARNs looking something like: - // arn:aw:iam::123456789012:{user/UserName,user/path/*,role/RoleName,role/path/*} - switch { - case strutil.StrListContains(roleEntry.BoundIamPrincipalIDs, callerUniqueId): // check 1 passed - case !roleEntry.ResolveAWSUniqueIDs && strutil.StrListContains(roleEntry.BoundIamPrincipalARNs, entity.canonicalArn()): // check 2 passed - default: - // evaluate check 3 - fullArn := b.getCachedUserId(callerUniqueId) - if fullArn == "" { - fullArn, err = b.fullArn(ctx, entity, req.Storage) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error looking up full ARN of entity %v: %v", entity, err)), nil - } - if fullArn == "" { - return logical.ErrorResponse(fmt.Sprintf("got empty string back when looking up full ARN of entity %v", entity)), nil - } - b.setCachedUserId(callerUniqueId, fullArn) - } - matchedWildcardBind := false - for _, principalARN := range roleEntry.BoundIamPrincipalARNs { - if strings.HasSuffix(principalARN, "*") && strutil.GlobbedStringsMatch(principalARN, fullArn) { - matchedWildcardBind = true - break - } - } - if !matchedWildcardBind { - return logical.ErrorResponse(fmt.Sprintf("IAM Principal %q does not belong to the role %q", callerID.Arn, roleName)), nil - } - } - } - - policies := roleEntry.Policies - - inferredEntityType := "" - inferredEntityID := "" - if roleEntry.InferredEntityType == ec2EntityType { - instance, err := b.validateInstance(ctx, req.Storage, entity.SessionInfo, roleEntry.InferredAWSRegion, callerID.Account) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to verify %s as a valid EC2 instance in region %s", entity.SessionInfo, roleEntry.InferredAWSRegion)), nil - } - - // build a fake identity doc to pass on metadata about the instance to verifyInstanceMeetsRoleRequirements - identityDoc := &identityDocument{ - Tags: nil, // Don't really need the tags, so not doing the work of converting them from Instance.Tags to identityDocument.Tags - InstanceID: *instance.InstanceId, - AmiID: *instance.ImageId, - AccountID: callerID.Account, - Region: roleEntry.InferredAWSRegion, - PendingTime: instance.LaunchTime.Format(time.RFC3339), - } - - validationError, err := b.verifyInstanceMeetsRoleRequirements(ctx, req.Storage, instance, roleEntry, roleName, identityDoc) - if err != nil { - return nil, err - } - if validationError != nil { - return logical.ErrorResponse(fmt.Sprintf("error validating instance: %s", validationError)), nil - } - - inferredEntityType = ec2EntityType - inferredEntityID = entity.SessionInfo - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - Period: roleEntry.Period, - Policies: policies, - Metadata: map[string]string{ - "client_arn": callerID.Arn, - "canonical_arn": entity.canonicalArn(), - "client_user_id": callerUniqueId, - "auth_type": iamAuthType, - "inferred_entity_type": inferredEntityType, - "inferred_entity_id": inferredEntityID, - "inferred_aws_region": roleEntry.InferredAWSRegion, - "account_id": entity.AccountNumber, - }, - InternalData: map[string]interface{}{ - "role_name": roleName, - }, - DisplayName: entity.FriendlyName, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: roleEntry.TTL, - MaxTTL: roleEntry.MaxTTL, - }, - Alias: &logical.Alias{ - Name: callerUniqueId, - }, - }, - } - - return resp, nil -} - -// These two methods (hasValuesFor*) return two bools -// The first is a hasAll, that is, does the request have all the values -// necessary for this auth method -// The second is a hasAny, that is, does the request have any of the fields -// exclusive to this auth method -func hasValuesForEc2Auth(data *framework.FieldData) (bool, bool) { - _, hasPkcs7 := data.GetOk("pkcs7") - _, hasIdentity := data.GetOk("identity") - _, hasSignature := data.GetOk("signature") - return (hasPkcs7 || (hasIdentity && hasSignature)), (hasPkcs7 || hasIdentity || hasSignature) -} - -func hasValuesForIamAuth(data *framework.FieldData) (bool, bool) { - _, hasRequestMethod := data.GetOk("iam_http_request_method") - _, hasRequestURL := data.GetOk("iam_request_url") - _, hasRequestBody := data.GetOk("iam_request_body") - _, hasRequestHeaders := data.GetOk("iam_request_headers") - return (hasRequestMethod && hasRequestURL && hasRequestBody && hasRequestHeaders), - (hasRequestMethod || hasRequestURL || hasRequestBody || hasRequestHeaders) -} - -func parseIamArn(iamArn string) (*iamEntity, error) { - // iamArn should look like one of the following: - // 1. arn:aws:iam:::/ - // 2. arn:aws:sts:::assumed-role// - // if we get something like 2, then we want to transform that back to what - // most people would expect, which is arn:aws:iam:::role/ - var entity iamEntity - fullParts := strings.Split(iamArn, ":") - if len(fullParts) != 6 { - return nil, fmt.Errorf("unrecognized arn: contains %d colon-separated parts, expected 6", len(fullParts)) - } - if fullParts[0] != "arn" { - return nil, fmt.Errorf("unrecognized arn: does not begin with \"arn:\"") - } - // normally aws, but could be aws-cn or aws-us-gov - entity.Partition = fullParts[1] - if fullParts[2] != "iam" && fullParts[2] != "sts" { - return nil, fmt.Errorf("unrecognized service: %v, not one of iam or sts", fullParts[2]) - } - // fullParts[3] is the region, which doesn't matter for AWS IAM entities - entity.AccountNumber = fullParts[4] - // fullParts[5] would now be something like user/ or assumed-role// - parts := strings.Split(fullParts[5], "/") - if len(parts) < 2 { - return nil, fmt.Errorf("unrecognized arn: %q contains fewer than 2 slash-separated parts", fullParts[5]) - } - entity.Type = parts[0] - entity.Path = strings.Join(parts[1:len(parts)-1], "/") - entity.FriendlyName = parts[len(parts)-1] - // now, entity.FriendlyName should either be or - switch entity.Type { - case "assumed-role": - // Assumed roles don't have paths and have a slightly different format - // parts[2] is - entity.Path = "" - entity.FriendlyName = parts[1] - entity.SessionInfo = parts[2] - case "user": - case "role": - case "instance-profile": - default: - return &iamEntity{}, fmt.Errorf("unrecognized principal type: %q", entity.Type) - } - return &entity, nil -} - -func validateVaultHeaderValue(headers http.Header, requestUrl *url.URL, requiredHeaderValue string) error { - providedValue := "" - for k, v := range headers { - if strings.ToLower(iamServerIdHeader) == strings.ToLower(k) { - providedValue = strings.Join(v, ",") - break - } - } - if providedValue == "" { - return fmt.Errorf("missing header %q", iamServerIdHeader) - } - - // NOT doing a constant time compare here since the value is NOT intended to be secret - if providedValue != requiredHeaderValue { - return fmt.Errorf("expected %q but got %q", requiredHeaderValue, providedValue) - } - - if authzHeaders, ok := headers["Authorization"]; ok { - // authzHeader looks like AWS4-HMAC-SHA256 Credential=AKI..., SignedHeaders=host;x-amz-date;x-vault-awsiam-id, Signature=... - // We need to extract out the SignedHeaders - re := regexp.MustCompile(".*SignedHeaders=([^,]+)") - authzHeader := strings.Join(authzHeaders, ",") - matches := re.FindSubmatch([]byte(authzHeader)) - if len(matches) < 1 { - return fmt.Errorf("vault header wasn't signed") - } - if len(matches) > 2 { - return fmt.Errorf("found multiple SignedHeaders components") - } - signedHeaders := string(matches[1]) - return ensureHeaderIsSigned(signedHeaders, iamServerIdHeader) - } - // TODO: If we support GET requests, then we need to parse the X-Amz-SignedHeaders - // argument out of the query string and search in there for the header value - return fmt.Errorf("missing Authorization header") -} - -func buildHttpRequest(method, endpoint string, parsedUrl *url.URL, body string, headers http.Header) *http.Request { - // This is all a bit complicated because the AWS signature algorithm requires that - // the Host header be included in the signed headers. See - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - // The use cases we want to support, in order of increasing complexity, are: - // 1. All defaults (client assumes sts.amazonaws.com and server has no override) - // 2. Alternate STS regions: client wants to go to a specific region, in which case - // Vault must be configured with that endpoint as well. The client's signed request - // will include a signature over what the client expects the Host header to be, - // so we cannot change that and must match. - // 3. Alternate STS regions with a proxy that is transparent to Vault's clients. - // In this case, Vault is aware of the proxy, as the proxy is configured as the - // endpoint, but the clients should NOT be aware of the proxy (because STS will - // not be aware of the proxy) - // It's also annoying because: - // 1. The AWS Sigv4 algorithm requires the Host header to be defined - // 2. Some of the official SDKs (at least botocore and aws-sdk-go) don't actually - // include an explicit Host header in the HTTP requests they generate, relying on - // the underlying HTTP library to do that for them. - // 3. To get a validly signed request, the SDKs check if a Host header has been set - // and, if not, add an inferred host header (based on the URI) to the internal - // data structure used for calculating the signature, but never actually expose - // that to clients. So then they just "hope" that the underlying library actually - // adds the right Host header which was included in the signature calculation. - // We could either explicitly require all Vault clients to explicitly add the Host header - // in the encoded request, or we could also implicitly infer it from the URI. - // We choose to support both -- allow you to explicitly set a Host header, but if not, - // infer one from the URI. - // HOWEVER, we have to preserve the request URI portion of the client's - // URL because the GetCallerIdentity Action can be encoded in either the body - // or the URL. So, we need to rebuild the URL sent to the http library to have the - // custom, Vault-specified endpoint with the client-side request parameters. - targetUrl := fmt.Sprintf("%s/%s", endpoint, parsedUrl.RequestURI()) - request, err := http.NewRequest(method, targetUrl, strings.NewReader(body)) - if err != nil { - return nil - } - request.Host = parsedUrl.Host - for k, vals := range headers { - for _, val := range vals { - request.Header.Add(k, val) - } - } - return request -} - -func ensureHeaderIsSigned(signedHeaders, headerToSign string) error { - // Not doing a constant time compare here, the values aren't secret - for _, header := range strings.Split(signedHeaders, ";") { - if header == strings.ToLower(headerToSign) { - return nil - } - } - return fmt.Errorf("vault header wasn't signed") -} - -func parseGetCallerIdentityResponse(response string) (GetCallerIdentityResponse, error) { - decoder := xml.NewDecoder(strings.NewReader(response)) - result := GetCallerIdentityResponse{} - err := decoder.Decode(&result) - return result, err -} - -func parseIamRequestHeaders(headersB64 string) (http.Header, error) { - headersJson, err := base64.StdEncoding.DecodeString(headersB64) - if err != nil { - return nil, fmt.Errorf("failed to base64 decode iam_request_headers") - } - var headersDecoded map[string]interface{} - err = jsonutil.DecodeJSON(headersJson, &headersDecoded) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to JSON decode iam_request_headers %q: {{err}}", headersJson), err) - } - headers := make(http.Header) - for k, v := range headersDecoded { - switch typedValue := v.(type) { - case string: - headers.Add(k, typedValue) - case json.Number: - headers.Add(k, typedValue.String()) - case []interface{}: - for _, individualVal := range typedValue { - switch possibleStrVal := individualVal.(type) { - case string: - headers.Add(k, possibleStrVal) - case json.Number: - headers.Add(k, possibleStrVal.String()) - default: - return nil, fmt.Errorf("header %q contains value %q that has type %s, not string", k, individualVal, reflect.TypeOf(individualVal)) - } - } - default: - return nil, fmt.Errorf("header %q value %q has type %s, not string or []interface", k, typedValue, reflect.TypeOf(v)) - } - } - return headers, nil -} - -func submitCallerIdentityRequest(method, endpoint string, parsedUrl *url.URL, body string, headers http.Header) (*GetCallerIdentityResult, error) { - // NOTE: We need to ensure we're calling STS, instead of acting as an unintended network proxy - // The protection against this is that this method will only call the endpoint specified in the - // client config (defaulting to sts.amazonaws.com), so it would require a Vault admin to override - // the endpoint to talk to alternate web addresses - request := buildHttpRequest(method, endpoint, parsedUrl, body, headers) - client := cleanhttp.DefaultClient() - client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - } - response, err := client.Do(request) - if err != nil { - return nil, errwrap.Wrapf("error making request: {{err}}", err) - } - if response != nil { - defer response.Body.Close() - } - // we check for status code afterwards to also print out response body - responseBody, err := ioutil.ReadAll(response.Body) - if err != nil { - return nil, err - } - if response.StatusCode != 200 { - return nil, fmt.Errorf("received error code %d from STS: %s", response.StatusCode, string(responseBody)) - } - callerIdentityResponse, err := parseGetCallerIdentityResponse(string(responseBody)) - if err != nil { - return nil, fmt.Errorf("error parsing STS response") - } - return &callerIdentityResponse.GetCallerIdentityResult[0], nil -} - -type GetCallerIdentityResponse struct { - XMLName xml.Name `xml:"GetCallerIdentityResponse"` - GetCallerIdentityResult []GetCallerIdentityResult `xml:"GetCallerIdentityResult"` - ResponseMetadata []ResponseMetadata `xml:"ResponseMetadata"` -} - -type GetCallerIdentityResult struct { - Arn string `xml:"Arn"` - UserId string `xml:"UserId"` - Account string `xml:"Account"` -} - -type ResponseMetadata struct { - RequestId string `xml:"RequestId"` -} - -// identityDocument represents the items of interest from the EC2 instance -// identity document -type identityDocument struct { - Tags map[string]interface{} `json:"tags,omitempty"` - InstanceID string `json:"instanceId,omitempty"` - AmiID string `json:"imageId,omitempty"` - AccountID string `json:"accountId,omitempty"` - Region string `json:"region,omitempty"` - PendingTime string `json:"pendingTime,omitempty"` -} - -// roleTagLoginResponse represents the return values required after the process -// of verifying a role tag login -type roleTagLoginResponse struct { - Policies []string `json:"policies"` - MaxTTL time.Duration `json:"max_ttl"` - DisallowReauthentication bool `json:"disallow_reauthentication"` -} - -type iamEntity struct { - Partition string - AccountNumber string - Type string - Path string - FriendlyName string - SessionInfo string -} - -// Returns a Vault-internal canonical ARN for referring to an IAM entity -func (e *iamEntity) canonicalArn() string { - entityType := e.Type - // canonicalize "assumed-role" into "role" - if entityType == "assumed-role" { - entityType = "role" - } - // Annoyingly, the assumed-role entity type doesn't have the Path of the role which was assumed - // So, we "canonicalize" it by just completely dropping the path. The other option would be to - // make an AWS API call to look up the role by FriendlyName, which introduces more complexity to - // code and test, and it also breaks backwards compatibility in an area where we would really want - // it - return fmt.Sprintf("arn:%s:iam::%s:%s/%s", e.Partition, e.AccountNumber, entityType, e.FriendlyName) -} - -// This returns the "full" ARN of an iamEntity, how it would be referred to in AWS proper -func (b *backend) fullArn(ctx context.Context, e *iamEntity, s logical.Storage) (string, error) { - // Not assuming path is reliable for any entity types - client, err := b.clientIAM(ctx, s, getAnyRegionForAwsPartition(e.Partition).ID(), e.AccountNumber) - if err != nil { - return "", errwrap.Wrapf("error creating IAM client: {{err}}", err) - } - - switch e.Type { - case "user": - input := iam.GetUserInput{ - UserName: aws.String(e.FriendlyName), - } - resp, err := client.GetUser(&input) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error fetching user %q: {{err}}", e.FriendlyName), err) - } - if resp == nil { - return "", fmt.Errorf("nil response from GetUser") - } - return *(resp.User.Arn), nil - case "assumed-role": - fallthrough - case "role": - input := iam.GetRoleInput{ - RoleName: aws.String(e.FriendlyName), - } - resp, err := client.GetRole(&input) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error fetching role %q: {{err}}", e.FriendlyName), err) - } - if resp == nil { - return "", fmt.Errorf("nil response form GetRole") - } - return *(resp.Role.Arn), nil - default: - return "", fmt.Errorf("unrecognized entity type: %s", e.Type) - } -} - -const iamServerIdHeader = "X-Vault-AWS-IAM-Server-ID" - -const pathLoginSyn = ` -Authenticates an EC2 instance with Vault. -` - -const pathLoginDesc = ` -Authenticate AWS entities, either an arbitrary IAM principal or EC2 instances. - -IAM principals are authenticated by processing a signed sts:GetCallerIdentity -request and then parsing the response to see who signed the request. Optionally, -the caller can be inferred to be another AWS entity type, with EC2 instances -the only currently supported entity type, and additional filtering can be -implemented based on that inferred type. - -An EC2 instance is authenticated using the PKCS#7 signature of the instance identity -document and a client created nonce. This nonce should be unique and should be used by -the instance for all future logins, unless 'disallow_reauthentication' option on the -registered role is enabled, in which case client nonce is optional. - -First login attempt, creates a whitelist entry in Vault associating the instance to the nonce -provided. All future logins will succeed only if the client nonce matches the nonce in the -whitelisted entry. - -By default, a cron task will periodically look for expired entries in the whitelist -and deletes them. The duration to periodically run this, is one hour by default. -However, this can be configured using the 'config/tidy/identities' endpoint. This tidy -action can be triggered via the API as well, using the 'tidy/identities' endpoint. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role.go deleted file mode 100644 index fe7d76c2e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role.go +++ /dev/null @@ -1,918 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -var ( - currentRoleStorageVersion = 2 -) - -func pathRole(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role"), - Fields: map[string]*framework.FieldSchema{ - "role": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - "auth_type": { - Type: framework.TypeString, - Description: `The auth_type permitted to authenticate to this role. Must be one of -iam or ec2 and cannot be changed after role creation.`, - }, - "bound_ami_id": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the EC2 instances that they should be -using one of the AMI IDs specified by this parameter. This is only applicable -when auth_type is ec2 or inferred_entity_type is ec2_instance.`, - }, - "bound_account_id": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the EC2 instances that the account ID -in its identity document to match one of the IDs specified by this parameter. -This is only applicable when auth_type is ec2 or inferred_entity_type is -ec2_instance.`, - }, - "bound_iam_principal_arn": { - Type: framework.TypeCommaStringSlice, - Description: `ARN of the IAM principals to bind to this role. Only applicable when -auth_type is iam.`, - }, - "bound_region": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the EC2 instances that the region in -its identity document match one of the regions specified by this parameter. This is only -applicable when auth_type is ec2.`, - }, - "bound_iam_role_arn": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the authenticating EC2 instance -that it must match one of the IAM role ARNs specified by this parameter. -The value is prefix-matched (as though it were a glob ending in -'*'). The configured IAM user or EC2 instance role must be allowed -to execute the 'iam:GetInstanceProfile' action if this is specified. This is -only applicable when auth_type is ec2 or inferred_entity_type is -ec2_instance.`, - }, - "bound_iam_instance_profile_arn": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the EC2 instances to be associated -with an IAM instance profile ARN which has a prefix that matches -one of the values specified by this parameter. The value is prefix-matched -(as though it were a glob ending in '*'). This is only applicable when -auth_type is ec2 or inferred_entity_type is ec2_instance.`, - }, - "bound_ec2_instance_id": { - Type: framework.TypeCommaStringSlice, - Description: `If set, defines a constraint on the EC2 instances to have one of the -given instance IDs. Can be a list or comma-separated string of EC2 instance -IDs. This is only applicable when auth_type is ec2 or inferred_entity_type is -ec2_instance.`, - }, - "resolve_aws_unique_ids": { - Type: framework.TypeBool, - Default: true, - Description: `If set, resolve all AWS IAM ARNs into AWS's internal unique IDs. -When an IAM entity (e.g., user, role, or instance profile) is deleted, then all references -to it within the role will be invalidated, which prevents a new IAM entity from being created -with the same name and matching the role's IAM binds. Once set, this cannot be unset.`, - }, - "inferred_entity_type": { - Type: framework.TypeString, - Description: `When auth_type is iam, the -AWS entity type to infer from the authenticated principal. The only supported -value is ec2_instance, which will extract the EC2 instance ID from the -authenticated role and apply the following restrictions specific to EC2 -instances: bound_ami_id, bound_account_id, bound_iam_role_arn, -bound_iam_instance_profile_arn, bound_vpc_id, bound_subnet_id. The configured -EC2 client must be able to find the inferred instance ID in the results, and the -instance must be running. If unable to determine the EC2 instance ID or unable -to find the EC2 instance ID among running instances, then authentication will -fail.`, - }, - "inferred_aws_region": { - Type: framework.TypeString, - Description: `When auth_type is iam and -inferred_entity_type is set, the region to assume the inferred entity exists in.`, - }, - "bound_vpc_id": { - Type: framework.TypeCommaStringSlice, - Description: ` -If set, defines a constraint on the EC2 instance to be associated with a VPC -ID that matches one of the value specified by this parameter. This is only -applicable when auth_type is ec2 or inferred_entity_type is ec2_instance.`, - }, - "bound_subnet_id": { - Type: framework.TypeCommaStringSlice, - Description: ` -If set, defines a constraint on the EC2 instance to be associated with the -subnet ID that matches one of the values specified by this parameter. This is -only applicable when auth_type is ec2 or inferred_entity_type is -ec2_instance.`, - }, - "role_tag": { - Type: framework.TypeString, - Default: "", - Description: `If set, enables the role tags for this role. The value set for this -field should be the 'key' of the tag on the EC2 instance. The 'value' -of the tag should be generated using 'role//tag' endpoint. -Defaults to an empty string, meaning that role tags are disabled. This -is only allowed if auth_type is ec2.`, - }, - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: ` -If set, indicates that the token generated using this role should never expire. -The token should be renewed within the duration specified by this value. At -each renewal, the token's TTL will be set to the value of this parameter.`, - }, - "ttl": { - Type: framework.TypeDurationSecond, - Default: 0, - Description: `Duration in seconds after which the issued token should expire. Defaults -to 0, in which case the value will fallback to the system/mount defaults.`, - }, - "max_ttl": { - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The maximum allowed lifetime of tokens issued using this role.", - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Default: "default", - Description: "Policies to be set on tokens issued using this role.", - }, - "allow_instance_migration": { - Type: framework.TypeBool, - Default: false, - Description: `If set, allows migration of the underlying instance where the client -resides. This keys off of pendingTime in the metadata document, so -essentially, this disables the client nonce check whenever the -instance is migrated to a new host and pendingTime is newer than the -previously-remembered time. Use with caution. This is only checked when -auth_type is ec2.`, - }, - "disallow_reauthentication": { - Type: framework.TypeBool, - Default: false, - Description: `If set, only allows a single token to be granted per - instance ID. In order to perform a fresh login, the entry in whitelist - for the instance ID needs to be cleared using - 'auth/aws-ec2/identity-whitelist/' endpoint. This is only - applicable when auth_type is ec2.`, - }, - }, - - ExistenceCheck: b.pathRoleExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathRoleCreateUpdate, - logical.UpdateOperation: b.pathRoleCreateUpdate, - logical.ReadOperation: b.pathRoleRead, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleSyn, - HelpDescription: pathRoleDesc, - } -} - -func pathListRole(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.lockedAWSRole(ctx, req.Storage, strings.ToLower(data.Get("role").(string))) - if err != nil { - return false, err - } - return entry != nil, nil -} - -// lockedAWSRole returns the properties set on the given role. This method -// acquires the read lock before reading the role from the storage. -func (b *backend) lockedAWSRole(ctx context.Context, s logical.Storage, roleName string) (*awsRoleEntry, error) { - if roleName == "" { - return nil, fmt.Errorf("missing role name") - } - - b.roleMutex.RLock() - roleEntry, err := b.nonLockedAWSRole(ctx, s, roleName) - // we manually unlock rather than defer the unlock because we might need to grab - // a read/write lock in the upgrade path - b.roleMutex.RUnlock() - if err != nil { - return nil, err - } - if roleEntry == nil { - return nil, nil - } - needUpgrade, err := b.upgradeRoleEntry(ctx, s, roleEntry) - if err != nil { - return nil, errwrap.Wrapf("error upgrading roleEntry: {{err}}", err) - } - if needUpgrade && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) { - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - // Now that we have a R/W lock, we need to re-read the role entry in case it was - // written to between releasing the read lock and acquiring the write lock - roleEntry, err = b.nonLockedAWSRole(ctx, s, roleName) - if err != nil { - return nil, err - } - // somebody deleted the role, so no use in putting it back - if roleEntry == nil { - return nil, nil - } - // now re-check to see if we need to upgrade - if needUpgrade, err = b.upgradeRoleEntry(ctx, s, roleEntry); err != nil { - return nil, errwrap.Wrapf("error upgrading roleEntry: {{err}}", err) - } - if needUpgrade { - if err = b.nonLockedSetAWSRole(ctx, s, roleName, roleEntry); err != nil { - return nil, errwrap.Wrapf("error saving upgraded roleEntry: {{err}}", err) - } - } - } - return roleEntry, nil -} - -// lockedSetAWSRole creates or updates a role in the storage. This method -// acquires the write lock before creating or updating the role at the storage. -func (b *backend) lockedSetAWSRole(ctx context.Context, s logical.Storage, roleName string, roleEntry *awsRoleEntry) error { - if roleName == "" { - return fmt.Errorf("missing role name") - } - - if roleEntry == nil { - return fmt.Errorf("nil role entry") - } - - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - - return b.nonLockedSetAWSRole(ctx, s, roleName, roleEntry) -} - -// nonLockedSetAWSRole creates or updates a role in the storage. This method -// does not acquire the write lock before reading the role from the storage. If -// locking is desired, use lockedSetAWSRole instead. -func (b *backend) nonLockedSetAWSRole(ctx context.Context, s logical.Storage, roleName string, - roleEntry *awsRoleEntry) error { - if roleName == "" { - return fmt.Errorf("missing role name") - } - - if roleEntry == nil { - return fmt.Errorf("nil role entry") - } - - entry, err := logical.StorageEntryJSON("role/"+strings.ToLower(roleName), roleEntry) - if err != nil { - return err - } - - if err := s.Put(ctx, entry); err != nil { - return err - } - - return nil -} - -// If needed, updates the role entry and returns a bool indicating if it was updated -// (and thus needs to be persisted) -func (b *backend) upgradeRoleEntry(ctx context.Context, s logical.Storage, roleEntry *awsRoleEntry) (bool, error) { - if roleEntry == nil { - return false, fmt.Errorf("received nil roleEntry") - } - upgraded := roleEntry.Version < currentRoleStorageVersion - switch roleEntry.Version { - case 0: - // Check if the value held by role ARN field is actually an instance profile ARN - if roleEntry.BoundIamRoleARN != "" && strings.Contains(roleEntry.BoundIamRoleARN, ":instance-profile/") { - // If yes, move it to the correct field - roleEntry.BoundIamInstanceProfileARN = roleEntry.BoundIamRoleARN - - // Reset the old field - roleEntry.BoundIamRoleARN = "" - } - - // Check if there was no pre-existing AuthType set (from older versions) - if roleEntry.AuthType == "" { - // then default to the original behavior of ec2 - roleEntry.AuthType = ec2AuthType - } - - // Check if we need to resolve the unique ID on the role - if roleEntry.AuthType == iamAuthType && - roleEntry.ResolveAWSUniqueIDs && - roleEntry.BoundIamPrincipalARN != "" && - roleEntry.BoundIamPrincipalID == "" && - !strings.HasSuffix(roleEntry.BoundIamPrincipalARN, "*") { - principalId, err := b.resolveArnToUniqueIDFunc(ctx, s, roleEntry.BoundIamPrincipalARN) - if err != nil { - return false, err - } - roleEntry.BoundIamPrincipalID = principalId - // Not setting roleEntry.BoundIamPrincipalARN to "" here so that clients can see the original - // ARN that the role was bound to - } - - // Check if we need to convert individual string values to lists - if roleEntry.BoundAmiID != "" { - roleEntry.BoundAmiIDs = []string{roleEntry.BoundAmiID} - roleEntry.BoundAmiID = "" - } - if roleEntry.BoundAccountID != "" { - roleEntry.BoundAccountIDs = []string{roleEntry.BoundAccountID} - roleEntry.BoundAccountID = "" - } - if roleEntry.BoundIamPrincipalARN != "" { - roleEntry.BoundIamPrincipalARNs = []string{roleEntry.BoundIamPrincipalARN} - roleEntry.BoundIamPrincipalARN = "" - } - if roleEntry.BoundIamPrincipalID != "" { - roleEntry.BoundIamPrincipalIDs = []string{roleEntry.BoundIamPrincipalID} - roleEntry.BoundIamPrincipalID = "" - } - if roleEntry.BoundIamRoleARN != "" { - roleEntry.BoundIamRoleARNs = []string{roleEntry.BoundIamRoleARN} - roleEntry.BoundIamRoleARN = "" - } - if roleEntry.BoundIamInstanceProfileARN != "" { - roleEntry.BoundIamInstanceProfileARNs = []string{roleEntry.BoundIamInstanceProfileARN} - roleEntry.BoundIamInstanceProfileARN = "" - } - if roleEntry.BoundRegion != "" { - roleEntry.BoundRegions = []string{roleEntry.BoundRegion} - roleEntry.BoundRegion = "" - } - if roleEntry.BoundSubnetID != "" { - roleEntry.BoundSubnetIDs = []string{roleEntry.BoundSubnetID} - roleEntry.BoundSubnetID = "" - } - if roleEntry.BoundVpcID != "" { - roleEntry.BoundVpcIDs = []string{roleEntry.BoundVpcID} - roleEntry.BoundVpcID = "" - } - roleEntry.Version = 1 - fallthrough - case 1: - // Make BoundIamRoleARNs and BoundIamInstanceProfileARNs explicitly prefix-matched - for i, arn := range roleEntry.BoundIamRoleARNs { - roleEntry.BoundIamRoleARNs[i] = fmt.Sprintf("%s*", arn) - } - for i, arn := range roleEntry.BoundIamInstanceProfileARNs { - roleEntry.BoundIamInstanceProfileARNs[i] = fmt.Sprintf("%s*", arn) - } - roleEntry.Version = 2 - fallthrough - case currentRoleStorageVersion: - default: - return false, fmt.Errorf("unrecognized role version: %q", roleEntry.Version) - } - - return upgraded, nil - -} - -// nonLockedAWSRole returns the properties set on the given role. This method -// does not acquire the read lock before reading the role from the storage. If -// locking is desired, use lockedAWSRole instead. -// This method also does NOT check to see if a role upgrade is required. It is -// the responsibility of the caller to check if a role upgrade is required and, -// if so, to upgrade the role -func (b *backend) nonLockedAWSRole(ctx context.Context, s logical.Storage, roleName string) (*awsRoleEntry, error) { - if roleName == "" { - return nil, fmt.Errorf("missing role name") - } - - entry, err := s.Get(ctx, "role/"+strings.ToLower(roleName)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result awsRoleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// pathRoleDelete is used to delete the information registered for a given AMI ID. -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role").(string) - if roleName == "" { - return logical.ErrorResponse("missing role"), nil - } - - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - - return nil, req.Storage.Delete(ctx, "role/"+strings.ToLower(roleName)) -} - -// pathRoleList is used to list all the AMI IDs registered with Vault. -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.roleMutex.RLock() - defer b.roleMutex.RUnlock() - - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - return logical.ListResponse(roles), nil -} - -// pathRoleRead is used to view the information registered for a given AMI ID. -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, strings.ToLower(data.Get("role").(string))) - if err != nil { - return nil, err - } - if roleEntry == nil { - return nil, nil - } - - return &logical.Response{ - Data: roleEntry.ToResponseData(), - }, nil -} - -// pathRoleCreateUpdate is used to associate Vault policies to a given AMI ID. -func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := strings.ToLower(data.Get("role").(string)) - if roleName == "" { - return logical.ErrorResponse("missing role"), nil - } - - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - - roleEntry, err := b.nonLockedAWSRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if roleEntry == nil { - roleEntry = &awsRoleEntry{ - Version: currentRoleStorageVersion, - } - } else { - needUpdate, err := b.upgradeRoleEntry(ctx, req.Storage, roleEntry) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to update roleEntry: %v", err)), nil - } - if needUpdate { - err = b.nonLockedSetAWSRole(ctx, req.Storage, roleName, roleEntry) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to save upgraded roleEntry: %v", err)), nil - } - } - } - - // Fetch and set the bound parameters. There can't be default values - // for these. - if boundAmiIDRaw, ok := data.GetOk("bound_ami_id"); ok { - roleEntry.BoundAmiIDs = boundAmiIDRaw.([]string) - } - - if boundAccountIDRaw, ok := data.GetOk("bound_account_id"); ok { - roleEntry.BoundAccountIDs = boundAccountIDRaw.([]string) - } - - if boundRegionRaw, ok := data.GetOk("bound_region"); ok { - roleEntry.BoundRegions = boundRegionRaw.([]string) - } - - if boundVpcIDRaw, ok := data.GetOk("bound_vpc_id"); ok { - roleEntry.BoundVpcIDs = boundVpcIDRaw.([]string) - } - - if boundSubnetIDRaw, ok := data.GetOk("bound_subnet_id"); ok { - roleEntry.BoundSubnetIDs = boundSubnetIDRaw.([]string) - } - - if resolveAWSUniqueIDsRaw, ok := data.GetOk("resolve_aws_unique_ids"); ok { - switch { - case req.Operation == logical.CreateOperation: - roleEntry.ResolveAWSUniqueIDs = resolveAWSUniqueIDsRaw.(bool) - case roleEntry.ResolveAWSUniqueIDs && !resolveAWSUniqueIDsRaw.(bool): - return logical.ErrorResponse("changing resolve_aws_unique_ids from true to false is not allowed"), nil - default: - roleEntry.ResolveAWSUniqueIDs = resolveAWSUniqueIDsRaw.(bool) - } - } else if req.Operation == logical.CreateOperation { - roleEntry.ResolveAWSUniqueIDs = data.Get("resolve_aws_unique_ids").(bool) - } - - if boundIamRoleARNRaw, ok := data.GetOk("bound_iam_role_arn"); ok { - roleEntry.BoundIamRoleARNs = boundIamRoleARNRaw.([]string) - } - - if boundIamInstanceProfileARNRaw, ok := data.GetOk("bound_iam_instance_profile_arn"); ok { - roleEntry.BoundIamInstanceProfileARNs = boundIamInstanceProfileARNRaw.([]string) - } - - if boundEc2InstanceIDRaw, ok := data.GetOk("bound_ec2_instance_id"); ok { - roleEntry.BoundEc2InstanceIDs = boundEc2InstanceIDRaw.([]string) - } - - if boundIamPrincipalARNRaw, ok := data.GetOk("bound_iam_principal_arn"); ok { - principalARNs := boundIamPrincipalARNRaw.([]string) - roleEntry.BoundIamPrincipalARNs = principalARNs - roleEntry.BoundIamPrincipalIDs = []string{} - } - if roleEntry.ResolveAWSUniqueIDs && len(roleEntry.BoundIamPrincipalIDs) == 0 { - // we might be turning on resolution on this role, so ensure we update the IDs - for _, principalARN := range roleEntry.BoundIamPrincipalARNs { - if !strings.HasSuffix(principalARN, "*") { - principalID, err := b.resolveArnToUniqueIDFunc(ctx, req.Storage, principalARN) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to resolve ARN %#v to internal ID: %s", principalARN, err.Error())), nil - } - roleEntry.BoundIamPrincipalIDs = append(roleEntry.BoundIamPrincipalIDs, principalID) - } - } - } - - if inferRoleTypeRaw, ok := data.GetOk("inferred_entity_type"); ok { - roleEntry.InferredEntityType = inferRoleTypeRaw.(string) - } - - if inferredAWSRegionRaw, ok := data.GetOk("inferred_aws_region"); ok { - roleEntry.InferredAWSRegion = inferredAWSRegionRaw.(string) - } - - // auth_type is a special case as it's immutable and can't be changed once a role is created - if authTypeRaw, ok := data.GetOk("auth_type"); ok { - // roleEntry.AuthType should only be "" when it's a new role; existing roles without an - // auth_type should have already been upgraded to have one before we get here - if roleEntry.AuthType == "" { - switch authTypeRaw.(string) { - case ec2AuthType, iamAuthType: - roleEntry.AuthType = authTypeRaw.(string) - default: - return logical.ErrorResponse(fmt.Sprintf("unrecognized auth_type: %v", authTypeRaw.(string))), nil - } - } else if authTypeRaw.(string) != roleEntry.AuthType { - return logical.ErrorResponse("changing auth_type on a role is not allowed"), nil - } - } else if req.Operation == logical.CreateOperation { - switch req.MountType { - // maintain backwards compatibility for old aws-ec2 auth types - case "aws-ec2": - roleEntry.AuthType = ec2AuthType - // but default to iamAuth for new mounts going forward - case "aws": - roleEntry.AuthType = iamAuthType - default: - roleEntry.AuthType = iamAuthType - } - } - - allowEc2Binds := roleEntry.AuthType == ec2AuthType - - if roleEntry.InferredEntityType != "" { - switch { - case roleEntry.AuthType != iamAuthType: - return logical.ErrorResponse("specified inferred_entity_type but didn't allow iam auth_type"), nil - case roleEntry.InferredEntityType != ec2EntityType: - return logical.ErrorResponse(fmt.Sprintf("specified invalid inferred_entity_type: %s", roleEntry.InferredEntityType)), nil - case roleEntry.InferredAWSRegion == "": - return logical.ErrorResponse("specified inferred_entity_type but not inferred_aws_region"), nil - } - allowEc2Binds = true - } else if roleEntry.InferredAWSRegion != "" { - return logical.ErrorResponse("specified inferred_aws_region but not inferred_entity_type"), nil - } - - numBinds := 0 - - if len(roleEntry.BoundAccountIDs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_account_id but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundRegions) > 0 { - if roleEntry.AuthType != ec2AuthType { - return logical.ErrorResponse("specified bound_region but not specifying ec2 auth_type"), nil - } - numBinds++ - } - - if len(roleEntry.BoundAmiIDs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_ami_id but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundIamInstanceProfileARNs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_iam_instance_profile_arn but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundEc2InstanceIDs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_ec2_instance_id but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundIamRoleARNs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_iam_role_arn but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundIamPrincipalARNs) > 0 { - if roleEntry.AuthType != iamAuthType { - return logical.ErrorResponse("specified bound_iam_principal_arn but not specifying iam auth_type"), nil - } - numBinds++ - } - - if len(roleEntry.BoundVpcIDs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_vpc_id but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if len(roleEntry.BoundSubnetIDs) > 0 { - if !allowEc2Binds { - return logical.ErrorResponse(fmt.Sprintf("specified bound_subnet_id but not specifying ec2 auth_type or inferring %s", ec2EntityType)), nil - } - numBinds++ - } - - if numBinds == 0 { - return logical.ErrorResponse("at least be one bound parameter should be specified on the role"), nil - } - - policiesRaw, ok := data.GetOk("policies") - if ok { - roleEntry.Policies = policyutil.ParsePolicies(policiesRaw) - } else if req.Operation == logical.CreateOperation { - roleEntry.Policies = []string{} - } - - disallowReauthenticationBool, ok := data.GetOk("disallow_reauthentication") - if ok { - if roleEntry.AuthType != ec2AuthType { - return logical.ErrorResponse("specified disallow_reauthentication when not using ec2 auth type"), nil - } - roleEntry.DisallowReauthentication = disallowReauthenticationBool.(bool) - } else if req.Operation == logical.CreateOperation && roleEntry.AuthType == ec2AuthType { - roleEntry.DisallowReauthentication = data.Get("disallow_reauthentication").(bool) - } - - allowInstanceMigrationBool, ok := data.GetOk("allow_instance_migration") - if ok { - if roleEntry.AuthType != ec2AuthType { - return logical.ErrorResponse("specified allow_instance_migration when not using ec2 auth type"), nil - } - roleEntry.AllowInstanceMigration = allowInstanceMigrationBool.(bool) - } else if req.Operation == logical.CreateOperation && roleEntry.AuthType == ec2AuthType { - roleEntry.AllowInstanceMigration = data.Get("allow_instance_migration").(bool) - } - - if roleEntry.AllowInstanceMigration && roleEntry.DisallowReauthentication { - return logical.ErrorResponse("cannot specify both disallow_reauthentication=true and allow_instance_migration=true"), nil - } - - var resp logical.Response - - ttlRaw, ok := data.GetOk("ttl") - if ok { - ttl := time.Duration(ttlRaw.(int)) * time.Second - defaultLeaseTTL := b.System().DefaultLeaseTTL() - if ttl > defaultLeaseTTL { - resp.AddWarning(fmt.Sprintf("Given ttl of %d seconds greater than current mount/system default of %d seconds; ttl will be capped at login time", ttl/time.Second, defaultLeaseTTL/time.Second)) - } - roleEntry.TTL = ttl - } else if req.Operation == logical.CreateOperation { - roleEntry.TTL = time.Duration(data.Get("ttl").(int)) * time.Second - } - - maxTTLInt, ok := data.GetOk("max_ttl") - if ok { - maxTTL := time.Duration(maxTTLInt.(int)) * time.Second - systemMaxTTL := b.System().MaxLeaseTTL() - if maxTTL > systemMaxTTL { - resp.AddWarning(fmt.Sprintf("Given max_ttl of %d seconds greater than current mount/system default of %d seconds; max_ttl will be capped at login time", maxTTL/time.Second, systemMaxTTL/time.Second)) - } - - if maxTTL < time.Duration(0) { - return logical.ErrorResponse("max_ttl cannot be negative"), nil - } - - roleEntry.MaxTTL = maxTTL - } else if req.Operation == logical.CreateOperation { - roleEntry.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second - } - - if roleEntry.MaxTTL != 0 && roleEntry.MaxTTL < roleEntry.TTL { - return logical.ErrorResponse("ttl should be shorter than max_ttl"), nil - } - - periodRaw, ok := data.GetOk("period") - if ok { - roleEntry.Period = time.Second * time.Duration(periodRaw.(int)) - } else if req.Operation == logical.CreateOperation { - roleEntry.Period = time.Second * time.Duration(data.Get("period").(int)) - } - - if roleEntry.Period > b.System().MaxLeaseTTL() { - return logical.ErrorResponse(fmt.Sprintf("'period' of '%s' is greater than the backend's maximum lease TTL of '%s'", roleEntry.Period.String(), b.System().MaxLeaseTTL().String())), nil - } - - roleTagStr, ok := data.GetOk("role_tag") - if ok { - if roleEntry.AuthType != ec2AuthType { - return logical.ErrorResponse("tried to enable role_tag when not using ec2 auth method"), nil - } - roleEntry.RoleTag = roleTagStr.(string) - // There is a limit of 127 characters on the tag key for AWS EC2 instances. - // Complying to that requirement, do not allow the value of 'key' to be more than that. - if len(roleEntry.RoleTag) > 127 { - return logical.ErrorResponse("length of role tag exceeds the EC2 key limit of 127 characters"), nil - } - } else if req.Operation == logical.CreateOperation && roleEntry.AuthType == ec2AuthType { - roleEntry.RoleTag = data.Get("role_tag").(string) - } - - if roleEntry.HMACKey == "" { - roleEntry.HMACKey, err = uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to generate role HMAC key: {{err}}", err) - } - } - - if err := b.nonLockedSetAWSRole(ctx, req.Storage, roleName, roleEntry); err != nil { - return nil, err - } - - if len(resp.Warnings) == 0 { - return nil, nil - } - - return &resp, nil -} - -// Struct to hold the information associated with a Vault role -type awsRoleEntry struct { - AuthType string `json:"auth_type" ` - BoundAmiIDs []string `json:"bound_ami_id_list"` - BoundAccountIDs []string `json:"bound_account_id_list"` - BoundEc2InstanceIDs []string `json:"bound_ec2_instance_id_list"` - BoundIamPrincipalARNs []string `json:"bound_iam_principal_arn_list"` - BoundIamPrincipalIDs []string `json:"bound_iam_principal_id_list"` - BoundIamRoleARNs []string `json:"bound_iam_role_arn_list"` - BoundIamInstanceProfileARNs []string `json:"bound_iam_instance_profile_arn_list"` - BoundRegions []string `json:"bound_region_list"` - BoundSubnetIDs []string `json:"bound_subnet_id_list"` - BoundVpcIDs []string `json:"bound_vpc_id_list"` - InferredEntityType string `json:"inferred_entity_type"` - InferredAWSRegion string `json:"inferred_aws_region"` - ResolveAWSUniqueIDs bool `json:"resolve_aws_unique_ids"` - RoleTag string `json:"role_tag"` - AllowInstanceMigration bool `json:"allow_instance_migration"` - TTL time.Duration `json:"ttl"` - MaxTTL time.Duration `json:"max_ttl"` - Policies []string `json:"policies"` - DisallowReauthentication bool `json:"disallow_reauthentication"` - HMACKey string `json:"hmac_key"` - Period time.Duration `json:"period"` - Version int `json:"version"` - // DEPRECATED -- these are the old fields before we supported lists and exist for backwards compatibility - BoundAmiID string `json:"bound_ami_id,omitempty" ` - BoundAccountID string `json:"bound_account_id,omitempty"` - BoundIamPrincipalARN string `json:"bound_iam_principal_arn,omitempty"` - BoundIamPrincipalID string `json:"bound_iam_principal_id,omitempty"` - BoundIamRoleARN string `json:"bound_iam_role_arn,omitempty"` - BoundIamInstanceProfileARN string `json:"bound_iam_instance_profile_arn,omitempty"` - BoundRegion string `json:"bound_region,omitempty"` - BoundSubnetID string `json:"bound_subnet_id,omitempty"` - BoundVpcID string `json:"bound_vpc_id,omitempty"` -} - -func (r *awsRoleEntry) ToResponseData() map[string]interface{} { - responseData := map[string]interface{}{ - "auth_type": r.AuthType, - "bound_ami_id": r.BoundAmiIDs, - "bound_account_id": r.BoundAccountIDs, - "bound_ec2_instance_id": r.BoundEc2InstanceIDs, - "bound_iam_principal_arn": r.BoundIamPrincipalARNs, - "bound_iam_principal_id": r.BoundIamPrincipalIDs, - "bound_iam_role_arn": r.BoundIamRoleARNs, - "bound_iam_instance_profile_arn": r.BoundIamInstanceProfileARNs, - "bound_region": r.BoundRegions, - "bound_subnet_id": r.BoundSubnetIDs, - "bound_vpc_id": r.BoundVpcIDs, - "inferred_entity_type": r.InferredEntityType, - "inferred_aws_region": r.InferredAWSRegion, - "resolve_aws_unique_ids": r.ResolveAWSUniqueIDs, - "role_tag": r.RoleTag, - "allow_instance_migration": r.AllowInstanceMigration, - "ttl": r.TTL / time.Second, - "max_ttl": r.MaxTTL / time.Second, - "policies": r.Policies, - "disallow_reauthentication": r.DisallowReauthentication, - "period": r.Period / time.Second, - } - - convertNilToEmptySlice := func(data map[string]interface{}, field string) { - if data[field] == nil || len(data[field].([]string)) == 0 { - data[field] = []string{} - } - } - convertNilToEmptySlice(responseData, "bound_ami_id") - convertNilToEmptySlice(responseData, "bound_account_id") - convertNilToEmptySlice(responseData, "bound_iam_principal_arn") - convertNilToEmptySlice(responseData, "bound_iam_principal_id") - convertNilToEmptySlice(responseData, "bound_iam_role_arn") - convertNilToEmptySlice(responseData, "bound_iam_instance_profile_arn") - convertNilToEmptySlice(responseData, "bound_region") - convertNilToEmptySlice(responseData, "bound_subnet_id") - convertNilToEmptySlice(responseData, "bound_vpc_id") - - return responseData -} - -const pathRoleSyn = ` -Create a role and associate policies to it. -` - -const pathRoleDesc = ` -A precondition for login is that a role should be created in the backend. -The login endpoint takes in the role name against which the client -should be validated. After authenticating the client, the authorization -to access Vault's resources is determined by the policies that are -associated to the role though this endpoint. - -When an EC2 instance requires only a subset of policies on the role, then -'role_tag' option on the role can be enabled to create a role tag via the -endpoint 'role//tag'. This tag then needs to be applied on the -instance before it attempts a login. The policies on the tag should be a -subset of policies that are associated to the role. In order to enable -login using tags, 'role_tag' option should be set while creating a role. -This only applies when authenticating EC2 instances. - -Also, a 'max_ttl' can be configured in this endpoint that determines the maximum -duration for which a login can be renewed. Note that the 'max_ttl' has an upper -limit of the 'max_ttl' value on the backend's mount. -` - -const pathListRolesHelpSyn = ` -Lists all the roles that are registered with Vault. -` - -const pathListRolesHelpDesc = ` -Roles will be listed by their respective role names. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role_tag.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role_tag.go deleted file mode 100644 index 48f44caf6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_role_tag.go +++ /dev/null @@ -1,435 +0,0 @@ -package awsauth - -import ( - "context" - "crypto/hmac" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const roleTagVersion = "v1" - -func pathRoleTag(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("role") + "/tag$", - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - - "instance_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Instance ID for which this tag is intended for. -If set, the created tag can only be used by the instance with the given ID.`, - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Policies to be associated with the tag. If set, must be a subset of the role's policies. If set, but set to an empty value, only the 'default' policy will be given to issued tokens.", - }, - - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "If set, specifies the maximum allowed token lifetime.", - }, - - "allow_instance_migration": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: "If set, allows migration of the underlying instance where the client resides. This keys off of pendingTime in the metadata document, so essentially, this disables the client nonce check whenever the instance is migrated to a new host and pendingTime is newer than the previously-remembered time. Use with caution.", - }, - - "disallow_reauthentication": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: "If set, only allows a single token to be granted per instance ID. In order to perform a fresh login, the entry in whitelist for the instance ID needs to be cleared using the 'auth/aws-ec2/identity-whitelist/' endpoint.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoleTagUpdate, - }, - - HelpSynopsis: pathRoleTagSyn, - HelpDescription: pathRoleTagDesc, - } -} - -// pathRoleTagUpdate is used to create an EC2 instance tag which will -// identify the Vault resources that the instance will be authorized for. -func (b *backend) pathRoleTagUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := strings.ToLower(data.Get("role").(string)) - if roleName == "" { - return logical.ErrorResponse("missing role"), nil - } - - // Fetch the role entry - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("entry not found for role %s", roleName)), nil - } - - // If RoleTag is empty, disallow creation of tag. - if roleEntry.RoleTag == "" { - return logical.ErrorResponse("tag creation is not enabled for this role"), nil - } - - // There should be a HMAC key present in the role entry - if roleEntry.HMACKey == "" { - // Not being able to find the HMACKey is an internal error - return nil, fmt.Errorf("failed to find the HMAC key") - } - - resp := &logical.Response{} - - // Instance ID is an optional field. - instanceID := strings.ToLower(data.Get("instance_id").(string)) - - // If no policies field was not supplied, then the tag should inherit all the policies - // on the role. But, it was provided, but set to empty explicitly, only "default" policy - // should be inherited. So, by leaving the policies var unset to anything when it is not - // supplied, we ensure that it inherits all the policies on the role. - var policies []string - policiesRaw, ok := data.GetOk("policies") - if ok { - policies = policyutil.ParsePolicies(policiesRaw) - } - if !strutil.StrListSubset(roleEntry.Policies, policies) { - resp.AddWarning("Policies on the tag are not a subset of the policies set on the role. Login will not be allowed with this tag unless the role policies are updated.") - } - - // This is an optional field. - disallowReauthentication := data.Get("disallow_reauthentication").(bool) - - // This is an optional field. - allowInstanceMigration := data.Get("allow_instance_migration").(bool) - if allowInstanceMigration && !roleEntry.AllowInstanceMigration { - resp.AddWarning("Role does not allow instance migration. Login will not be allowed with this tag unless the role value is updated.") - } - - if disallowReauthentication && allowInstanceMigration { - return logical.ErrorResponse("cannot set both disallow_reauthentication and allow_instance_migration"), nil - } - - // max_ttl for the role tag should be less than the max_ttl set on the role. - maxTTL := time.Duration(data.Get("max_ttl").(int)) * time.Second - - // max_ttl on the tag should not be greater than the system view's max_ttl value. - if maxTTL > b.System().MaxLeaseTTL() { - resp.AddWarning(fmt.Sprintf("Given max TTL of %d is greater than the mount maximum of %d seconds, and will be capped at login time.", maxTTL/time.Second, b.System().MaxLeaseTTL()/time.Second)) - } - // If max_ttl is set for the role, check the bounds for tag's max_ttl value using that. - if roleEntry.MaxTTL != time.Duration(0) && maxTTL > roleEntry.MaxTTL { - resp.AddWarning(fmt.Sprintf("Given max TTL of %d is greater than the role maximum of %d seconds, and will be capped at login time.", maxTTL/time.Second, roleEntry.MaxTTL/time.Second)) - } - - if maxTTL < time.Duration(0) { - return logical.ErrorResponse("max_ttl cannot be negative"), nil - } - - // Create a random nonce. - nonce, err := createRoleTagNonce() - if err != nil { - return nil, err - } - - // Create a role tag out of all the information provided. - rTagValue, err := createRoleTagValue(&roleTag{ - Version: roleTagVersion, - Role: roleName, - Nonce: nonce, - Policies: policies, - MaxTTL: maxTTL, - InstanceID: instanceID, - DisallowReauthentication: disallowReauthentication, - AllowInstanceMigration: allowInstanceMigration, - }, roleEntry) - if err != nil { - return nil, err - } - - // Return the key to be used for the tag and the value to be used for that tag key. - // This key value pair should be set on the EC2 instance. - resp.Data = map[string]interface{}{ - "tag_key": roleEntry.RoleTag, - "tag_value": rTagValue, - } - - return resp, nil -} - -// createRoleTagValue prepares the plaintext version of the role tag, -// and appends a HMAC of the plaintext value to it, before returning. -func createRoleTagValue(rTag *roleTag, roleEntry *awsRoleEntry) (string, error) { - if rTag == nil { - return "", fmt.Errorf("nil role tag") - } - - if roleEntry == nil { - return "", fmt.Errorf("nil role entry") - } - - // Attach version, nonce, policies and maxTTL to the role tag value. - rTagPlaintext, err := prepareRoleTagPlaintextValue(rTag) - if err != nil { - return "", err - } - - // Attach HMAC to tag's plaintext and return. - return appendHMAC(rTagPlaintext, roleEntry) -} - -// Takes in the plaintext part of the role tag, creates a HMAC of it and returns -// a role tag value containing both the plaintext part and the HMAC part. -func appendHMAC(rTagPlaintext string, roleEntry *awsRoleEntry) (string, error) { - if rTagPlaintext == "" { - return "", fmt.Errorf("empty role tag plaintext string") - } - - if roleEntry == nil { - return "", fmt.Errorf("nil role entry") - } - - // Create the HMAC of the value - hmacB64, err := createRoleTagHMACBase64(roleEntry.HMACKey, rTagPlaintext) - if err != nil { - return "", err - } - - // attach the HMAC to the value - rTagValue := fmt.Sprintf("%s:%s", rTagPlaintext, hmacB64) - - // This limit of 255 is enforced on the EC2 instance. Hence complying to that here. - if len(rTagValue) > 255 { - return "", fmt.Errorf("role tag 'value' exceeding the limit of 255 characters") - } - - return rTagValue, nil -} - -// verifyRoleTagValue rebuilds the role tag's plaintext part, computes the HMAC -// from it using the role specific HMAC key and compares it with the received HMAC. -func verifyRoleTagValue(rTag *roleTag, roleEntry *awsRoleEntry) (bool, error) { - if rTag == nil { - return false, fmt.Errorf("nil role tag") - } - - if roleEntry == nil { - return false, fmt.Errorf("nil role entry") - } - - // Fetch the plaintext part of role tag - rTagPlaintext, err := prepareRoleTagPlaintextValue(rTag) - if err != nil { - return false, err - } - - // Compute the HMAC of the plaintext - hmacB64, err := createRoleTagHMACBase64(roleEntry.HMACKey, rTagPlaintext) - if err != nil { - return false, err - } - - return subtle.ConstantTimeCompare([]byte(rTag.HMAC), []byte(hmacB64)) == 1, nil -} - -// prepareRoleTagPlaintextValue builds the role tag value without the HMAC in it. -func prepareRoleTagPlaintextValue(rTag *roleTag) (string, error) { - if rTag == nil { - return "", fmt.Errorf("nil role tag") - } - if rTag.Version == "" { - return "", fmt.Errorf("missing version") - } - if rTag.Nonce == "" { - return "", fmt.Errorf("missing nonce") - } - if rTag.Role == "" { - return "", fmt.Errorf("missing role") - } - - // Attach Version, Nonce, Role, DisallowReauthentication and AllowInstanceMigration - // fields to the role tag. - value := fmt.Sprintf("%s:%s:r=%s:d=%s:m=%s", rTag.Version, rTag.Nonce, rTag.Role, strconv.FormatBool(rTag.DisallowReauthentication), strconv.FormatBool(rTag.AllowInstanceMigration)) - - // Attach the policies only if they are specified. - if len(rTag.Policies) != 0 { - value = fmt.Sprintf("%s:p=%s", value, strings.Join(rTag.Policies, ",")) - } - - // Attach instance_id if set. - if rTag.InstanceID != "" { - value = fmt.Sprintf("%s:i=%s", value, rTag.InstanceID) - } - - // Attach max_ttl if it is provided. - if int(rTag.MaxTTL.Seconds()) > 0 { - value = fmt.Sprintf("%s:t=%d", value, int(rTag.MaxTTL.Seconds())) - } - - return value, nil -} - -// Parses the tag from string form into a struct form. This method -// also verifies the correctness of the parsed role tag. -func (b *backend) parseAndVerifyRoleTagValue(ctx context.Context, s logical.Storage, tag string) (*roleTag, error) { - tagItems := strings.Split(tag, ":") - - // Tag must contain version, nonce, policies and HMAC - if len(tagItems) < 4 { - return nil, fmt.Errorf("invalid tag") - } - - rTag := &roleTag{} - - // Cache the HMAC value. The last item in the collection. - rTag.HMAC = tagItems[len(tagItems)-1] - - // Remove the HMAC from the list. - tagItems = tagItems[:len(tagItems)-1] - - // Version will be the first element. - rTag.Version = tagItems[0] - if rTag.Version != roleTagVersion { - return nil, fmt.Errorf("invalid role tag version") - } - - // Nonce will be the second element. - rTag.Nonce = tagItems[1] - - // Delete the version and nonce from the list. - tagItems = tagItems[2:] - - for _, tagItem := range tagItems { - var err error - switch { - case strings.HasPrefix(tagItem, "i="): - rTag.InstanceID = strings.TrimPrefix(tagItem, "i=") - case strings.HasPrefix(tagItem, "r="): - rTag.Role = strings.TrimPrefix(tagItem, "r=") - case strings.HasPrefix(tagItem, "p="): - rTag.Policies = strings.Split(strings.TrimPrefix(tagItem, "p="), ",") - case strings.HasPrefix(tagItem, "d="): - rTag.DisallowReauthentication, err = strconv.ParseBool(strings.TrimPrefix(tagItem, "d=")) - if err != nil { - return nil, err - } - case strings.HasPrefix(tagItem, "m="): - rTag.AllowInstanceMigration, err = strconv.ParseBool(strings.TrimPrefix(tagItem, "m=")) - if err != nil { - return nil, err - } - case strings.HasPrefix(tagItem, "t="): - rTag.MaxTTL, err = time.ParseDuration(fmt.Sprintf("%ss", strings.TrimPrefix(tagItem, "t="))) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("unrecognized item %q in tag", tagItem) - } - } - - if rTag.Role == "" { - return nil, fmt.Errorf("missing role name") - } - - roleEntry, err := b.lockedAWSRole(ctx, s, rTag.Role) - if err != nil { - return nil, err - } - if roleEntry == nil { - return nil, fmt.Errorf("entry not found for %q", rTag.Role) - } - - // Create a HMAC of the plaintext value of role tag and compare it with the given value. - verified, err := verifyRoleTagValue(rTag, roleEntry) - if err != nil { - return nil, err - } - if !verified { - return nil, fmt.Errorf("role tag signature verification failed") - } - - return rTag, nil -} - -// Creates base64 encoded HMAC using a per-role key. -func createRoleTagHMACBase64(key, value string) (string, error) { - if key == "" { - return "", fmt.Errorf("invalid HMAC key") - } - hm := hmac.New(sha256.New, []byte(key)) - hm.Write([]byte(value)) - - // base64 encode the hmac bytes. - return base64.StdEncoding.EncodeToString(hm.Sum(nil)), nil -} - -// Creates a base64 encoded random nonce. -func createRoleTagNonce() (string, error) { - if uuidBytes, err := uuid.GenerateRandomBytes(8); err != nil { - return "", err - } else { - return base64.StdEncoding.EncodeToString(uuidBytes), nil - } -} - -// Struct roleTag represents a role tag in a struct form. -type roleTag struct { - Version string `json:"version"` - InstanceID string `json:"instance_id"` - Nonce string `json:"nonce"` - Policies []string `json:"policies"` - MaxTTL time.Duration `json:"max_ttl"` - Role string `json:"role"` - HMAC string `json:"hmac"` - DisallowReauthentication bool `json:"disallow_reauthentication"` - AllowInstanceMigration bool `json:"allow_instance_migration"` -} - -func (rTag1 *roleTag) Equal(rTag2 *roleTag) bool { - return rTag1 != nil && - rTag2 != nil && - rTag1.Version == rTag2.Version && - rTag1.Nonce == rTag2.Nonce && - policyutil.EquivalentPolicies(rTag1.Policies, rTag2.Policies) && - rTag1.MaxTTL == rTag2.MaxTTL && - rTag1.Role == rTag2.Role && - rTag1.HMAC == rTag2.HMAC && - rTag1.InstanceID == rTag2.InstanceID && - rTag1.DisallowReauthentication == rTag2.DisallowReauthentication && - rTag1.AllowInstanceMigration == rTag2.AllowInstanceMigration -} - -const pathRoleTagSyn = ` -Create a tag on a role in order to be able to further restrict the capabilities of a role. -` - -const pathRoleTagDesc = ` -If there are needs to apply only a subset of role's capabilities to any specific -instance, create a role tag using this endpoint and attach the tag on the instance -before performing login. - -To be able to create a role tag, the 'role_tag' option on the role should be -enabled via the endpoint 'role/'. Also, the policies to be associated -with the tag should be a subset of the policies associated with the registered role. - -This endpoint will return both the 'key' and the 'value' of the tag to be set -on the EC2 instance. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_roletag_blacklist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_roletag_blacklist.go deleted file mode 100644 index 6a8b2471d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_roletag_blacklist.go +++ /dev/null @@ -1,252 +0,0 @@ -package awsauth - -import ( - "context" - "encoding/base64" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathRoletagBlacklist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roletag-blacklist/(?P.*)", - Fields: map[string]*framework.FieldSchema{ - "role_tag": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Role tag to be blacklisted. The tag can be supplied as-is. In order -to avoid any encoding problems, it can be base64 encoded.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRoletagBlacklistUpdate, - logical.ReadOperation: b.pathRoletagBlacklistRead, - logical.DeleteOperation: b.pathRoletagBlacklistDelete, - }, - - HelpSynopsis: pathRoletagBlacklistSyn, - HelpDescription: pathRoletagBlacklistDesc, - } -} - -// Path to list all the blacklisted tags. -func pathListRoletagBlacklist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roletag-blacklist/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoletagBlacklistsList, - }, - - HelpSynopsis: pathListRoletagBlacklistHelpSyn, - HelpDescription: pathListRoletagBlacklistHelpDesc, - } -} - -// Lists all the blacklisted role tags. -func (b *backend) pathRoletagBlacklistsList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.blacklistMutex.RLock() - defer b.blacklistMutex.RUnlock() - - tags, err := req.Storage.List(ctx, "blacklist/roletag/") - if err != nil { - return nil, err - } - - // Tags are base64 encoded before indexing to avoid problems - // with the path separators being present in the tag. - // Reverse it before returning the list response. - for i, keyB64 := range tags { - if key, err := base64.StdEncoding.DecodeString(keyB64); err != nil { - return nil, err - } else { - // Overwrite the result with the decoded string. - tags[i] = string(key) - } - } - return logical.ListResponse(tags), nil -} - -// Fetch an entry from the role tag blacklist for a given tag. -// This method takes a role tag in its original form and not a base64 encoded form. -func (b *backend) lockedBlacklistRoleTagEntry(ctx context.Context, s logical.Storage, tag string) (*roleTagBlacklistEntry, error) { - b.blacklistMutex.RLock() - defer b.blacklistMutex.RUnlock() - - return b.nonLockedBlacklistRoleTagEntry(ctx, s, tag) -} - -func (b *backend) nonLockedBlacklistRoleTagEntry(ctx context.Context, s logical.Storage, tag string) (*roleTagBlacklistEntry, error) { - entry, err := s.Get(ctx, "blacklist/roletag/"+base64.StdEncoding.EncodeToString([]byte(tag))) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleTagBlacklistEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -// Deletes an entry from the role tag blacklist for a given tag. -func (b *backend) pathRoletagBlacklistDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.blacklistMutex.Lock() - defer b.blacklistMutex.Unlock() - - tag := data.Get("role_tag").(string) - if tag == "" { - return logical.ErrorResponse("missing role_tag"), nil - } - - return nil, req.Storage.Delete(ctx, "blacklist/roletag/"+base64.StdEncoding.EncodeToString([]byte(tag))) -} - -// If the given role tag is blacklisted, returns the details of the blacklist entry. -// Returns 'nil' otherwise. -func (b *backend) pathRoletagBlacklistRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - tag := data.Get("role_tag").(string) - if tag == "" { - return logical.ErrorResponse("missing role_tag"), nil - } - - entry, err := b.lockedBlacklistRoleTagEntry(ctx, req.Storage, tag) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "creation_time": entry.CreationTime.Format(time.RFC3339Nano), - "expiration_time": entry.ExpirationTime.Format(time.RFC3339Nano), - }, - }, nil -} - -// pathRoletagBlacklistUpdate is used to blacklist a given role tag. -// Before a role tag is blacklisted, the correctness of the plaintext part -// in the role tag is verified using the associated HMAC. -func (b *backend) pathRoletagBlacklistUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // The role_tag value provided, optionally can be base64 encoded. - tagInput := data.Get("role_tag").(string) - if tagInput == "" { - return logical.ErrorResponse("missing role_tag"), nil - } - - tag := "" - - // Try to base64 decode the value. - tagBytes, err := base64.StdEncoding.DecodeString(tagInput) - if err != nil { - // If the decoding failed, use the value as-is. - tag = tagInput - } else { - // If the decoding succeeded, use the decoded value. - tag = string(tagBytes) - } - - // Parse and verify the role tag from string form to a struct form and verify it. - rTag, err := b.parseAndVerifyRoleTagValue(ctx, req.Storage, tag) - if err != nil { - return nil, err - } - if rTag == nil { - return logical.ErrorResponse("failed to verify the role tag and parse it"), nil - } - - // Get the entry for the role mentioned in the role tag. - roleEntry, err := b.lockedAWSRole(ctx, req.Storage, rTag.Role) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse("role entry not found"), nil - } - - b.blacklistMutex.Lock() - defer b.blacklistMutex.Unlock() - - // Check if the role tag is already blacklisted. If yes, update it. - blEntry, err := b.nonLockedBlacklistRoleTagEntry(ctx, req.Storage, tag) - if err != nil { - return nil, err - } - if blEntry == nil { - blEntry = &roleTagBlacklistEntry{} - } - - currentTime := time.Now() - - // Check if this is a creation of blacklist entry. - if blEntry.CreationTime.IsZero() { - // Set the creation time for the blacklist entry. - // This should not be updated after setting it once. - // If blacklist operation is invoked more than once, only update the expiration time. - blEntry.CreationTime = currentTime - } - - // Decide the expiration time based on the max_ttl values. Since this is - // restricting access, use the greatest duration, not the least. - maxDur := rTag.MaxTTL - if roleEntry.MaxTTL > maxDur { - maxDur = roleEntry.MaxTTL - } - if b.System().MaxLeaseTTL() > maxDur { - maxDur = b.System().MaxLeaseTTL() - } - - blEntry.ExpirationTime = currentTime.Add(maxDur) - - entry, err := logical.StorageEntryJSON("blacklist/roletag/"+base64.StdEncoding.EncodeToString([]byte(tag)), blEntry) - if err != nil { - return nil, err - } - - // Store the blacklist entry. - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type roleTagBlacklistEntry struct { - CreationTime time.Time `json:"creation_time"` - ExpirationTime time.Time `json:"expiration_time"` -} - -const pathRoletagBlacklistSyn = ` -Blacklist a previously created role tag. -` - -const pathRoletagBlacklistDesc = ` -Blacklist a role tag so that it cannot be used by any EC2 instance to perform further -logins. This can be used if the role tag is suspected or believed to be possessed by -an unintended party. - -By default, a cron task will periodically look for expired entries in the blacklist -and deletes them. The duration to periodically run this, is one hour by default. -However, this can be configured using the 'config/tidy/roletags' endpoint. This tidy -action can be triggered via the API as well, using the 'tidy/roletags' endpoint. - -Also note that delete operation is supported on this endpoint to remove specific -entries from the blacklist. -` - -const pathListRoletagBlacklistHelpSyn = ` -Lists the blacklisted role tags. -` - -const pathListRoletagBlacklistHelpDesc = ` -Lists all the entries present in the blacklist. This will show both the valid -entries and the expired entries in the blacklist. Use 'tidy/roletags' endpoint -to clean-up the blacklist of role tags based on expiration time. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_identity_whitelist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_identity_whitelist.go deleted file mode 100644 index c09c97de3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_identity_whitelist.go +++ /dev/null @@ -1,119 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - "net/http" - "sync/atomic" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathTidyIdentityWhitelist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "tidy/identity-whitelist$", - Fields: map[string]*framework.FieldSchema{ - "safety_buffer": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 259200, - Description: `The amount of extra time that must have passed beyond the identity's -expiration, before it is removed from the backend storage.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathTidyIdentityWhitelistUpdate, - }, - - HelpSynopsis: pathTidyIdentityWhitelistSyn, - HelpDescription: pathTidyIdentityWhitelistDesc, - } -} - -// tidyWhitelistIdentity is used to delete entries in the whitelist that are expired. -func (b *backend) tidyWhitelistIdentity(ctx context.Context, req *logical.Request, safetyBuffer int) (*logical.Response, error) { - if !atomic.CompareAndSwapUint32(b.tidyWhitelistCASGuard, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - s := req.Storage - - go func() { - defer atomic.StoreUint32(b.tidyWhitelistCASGuard, 0) - - // Don't cancel when the original client request goes away - ctx = context.Background() - - logger := b.Logger().Named("wltidy") - - bufferDuration := time.Duration(safetyBuffer) * time.Second - - doTidy := func() error { - identities, err := s.List(ctx, "whitelist/identity/") - if err != nil { - return err - } - - for _, instanceID := range identities { - identityEntry, err := s.Get(ctx, "whitelist/identity/"+instanceID) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching identity of instanceID %q: {{err}}", instanceID), err) - } - - if identityEntry == nil { - return fmt.Errorf("identity entry for instanceID %q is nil", instanceID) - } - - if identityEntry.Value == nil || len(identityEntry.Value) == 0 { - return fmt.Errorf("found identity entry for instanceID %q but actual identity is empty", instanceID) - } - - var result whitelistIdentity - if err := identityEntry.DecodeJSON(&result); err != nil { - return err - } - - if time.Now().After(result.ExpirationTime.Add(bufferDuration)) { - if err := s.Delete(ctx, "whitelist/identity/"+instanceID); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting identity of instanceID %q from storage: {{err}}", instanceID), err) - } - } - } - - return nil - } - - if err := doTidy(); err != nil { - logger.Error("error running whitelist tidy", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -// pathTidyIdentityWhitelistUpdate is used to delete entries in the whitelist that are expired. -func (b *backend) pathTidyIdentityWhitelistUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.tidyWhitelistIdentity(ctx, req, data.Get("safety_buffer").(int)) -} - -const pathTidyIdentityWhitelistSyn = ` -Clean-up the whitelist instance identity entries. -` - -const pathTidyIdentityWhitelistDesc = ` -When an instance identity is whitelisted, the expiration time of the whitelist -entry is set based on the maximum 'max_ttl' value set on: the role, the role tag -and the backend's mount. - -When this endpoint is invoked, all the entries that are expired will be deleted. -A 'safety_buffer' (duration in seconds) can be provided, to ensure deletion of -only those entries that are expired before 'safety_buffer' seconds. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_roletag_blacklist.go b/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_roletag_blacklist.go deleted file mode 100644 index 7f9a65230..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/aws/path_tidy_roletag_blacklist.go +++ /dev/null @@ -1,119 +0,0 @@ -package awsauth - -import ( - "context" - "fmt" - "net/http" - "sync/atomic" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathTidyRoletagBlacklist(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "tidy/roletag-blacklist$", - Fields: map[string]*framework.FieldSchema{ - "safety_buffer": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 259200, // 72h - Description: `The amount of extra time that must have passed beyond the roletag -expiration, before it is removed from the backend storage.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathTidyRoletagBlacklistUpdate, - }, - - HelpSynopsis: pathTidyRoletagBlacklistSyn, - HelpDescription: pathTidyRoletagBlacklistDesc, - } -} - -// tidyBlacklistRoleTag is used to clean-up the entries in the role tag blacklist. -func (b *backend) tidyBlacklistRoleTag(ctx context.Context, req *logical.Request, safetyBuffer int) (*logical.Response, error) { - if !atomic.CompareAndSwapUint32(b.tidyBlacklistCASGuard, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - s := req.Storage - - go func() { - defer atomic.StoreUint32(b.tidyBlacklistCASGuard, 0) - - // Don't cancel when the original client request goes away - ctx = context.Background() - - logger := b.Logger().Named("bltidy") - - bufferDuration := time.Duration(safetyBuffer) * time.Second - - doTidy := func() error { - tags, err := s.List(ctx, "blacklist/roletag/") - if err != nil { - return err - } - - for _, tag := range tags { - tagEntry, err := s.Get(ctx, "blacklist/roletag/"+tag) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching tag %q: {{err}}", tag), err) - } - - if tagEntry == nil { - return fmt.Errorf("tag entry for tag %q is nil", tag) - } - - if tagEntry.Value == nil || len(tagEntry.Value) == 0 { - return fmt.Errorf("found entry for tag %q but actual tag is empty", tag) - } - - var result roleTagBlacklistEntry - if err := tagEntry.DecodeJSON(&result); err != nil { - return err - } - - if time.Now().After(result.ExpirationTime.Add(bufferDuration)) { - if err := s.Delete(ctx, "blacklist/roletag/"+tag); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting tag %q from storage: {{err}}", tag), err) - } - } - } - - return nil - } - - if err := doTidy(); err != nil { - logger.Error("error running blacklist tidy", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -// pathTidyRoletagBlacklistUpdate is used to clean-up the entries in the role tag blacklist. -func (b *backend) pathTidyRoletagBlacklistUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.tidyBlacklistRoleTag(ctx, req, data.Get("safety_buffer").(int)) -} - -const pathTidyRoletagBlacklistSyn = ` -Clean-up the blacklist role tag entries. -` - -const pathTidyRoletagBlacklistDesc = ` -When a role tag is blacklisted, the expiration time of the blacklist entry is -set based on the maximum 'max_ttl' value set on: the role, the role tag and the -backend's mount. - -When this endpoint is invoked, all the entries that are expired will be deleted. -A 'safety_buffer' (duration in seconds) can be provided, to ensure deletion of -only those entries that are expired before 'safety_buffer' seconds. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/backend.go deleted file mode 100644 index ab4b2a30d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/backend.go +++ /dev/null @@ -1,72 +0,0 @@ -package cert - -import ( - "context" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: backendHelp, - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "login", - }, - }, - Paths: append([]*framework.Path{ - pathConfig(&b), - pathLogin(&b), - pathListCerts(&b), - pathCerts(&b), - pathCRLs(&b), - }), - AuthRenew: b.pathLoginRenew, - Invalidate: b.invalidate, - BackendType: logical.TypeCredential, - } - - b.crlUpdateMutex = &sync.RWMutex{} - - return &b -} - -type backend struct { - *framework.Backend - MapCertId *framework.PathMap - - crls map[string]CRLInfo - crlUpdateMutex *sync.RWMutex -} - -func (b *backend) invalidate(_ context.Context, key string) { - switch { - case strings.HasPrefix(key, "crls/"): - b.crlUpdateMutex.Lock() - defer b.crlUpdateMutex.Unlock() - b.crls = nil - } -} - -const backendHelp = ` -The "cert" credential provider allows authentication using -TLS client certificates. A client connects to Vault and uses -the "login" endpoint to generate a client token. - -Trusted certificates are configured using the "certs/" endpoint -by a user with root access. A certificate authority can be trusted, -which permits all keys signed by it. Alternatively, self-signed -certificates can be trusted avoiding the need for a CA. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/cli.go deleted file mode 100644 index 4a470c896..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/cli.go +++ /dev/null @@ -1,61 +0,0 @@ -package cert - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/mapstructure" -) - -type CLIHandler struct{} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - var data struct { - Mount string `mapstructure:"mount"` - Name string `mapstructure:"name"` - } - if err := mapstructure.WeakDecode(m, &data); err != nil { - return nil, err - } - - if data.Mount == "" { - data.Mount = "cert" - } - - options := map[string]interface{}{ - "name": data.Name, - } - path := fmt.Sprintf("auth/%s/login", data.Mount) - secret, err := c.Logical().Write(path, options) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=cert [CONFIG K=V...] - - The certificate auth method allows users to authenticate with a - client certificate passed with the request. The -client-cert and -client-key - flags are included with the "vault login" command, NOT as configuration to the - auth method. - - Authenticate using a local client certificate: - - $ vault login -method=cert -client-cert=cert.pem -client-key=key.pem - -Configuration: - - name= - Certificate role to authenticate against. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_certs.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_certs.go deleted file mode 100644 index 384cd47fd..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_certs.go +++ /dev/null @@ -1,341 +0,0 @@ -package cert - -import ( - "context" - "crypto/x509" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListCerts(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "certs/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathCertList, - }, - - HelpSynopsis: pathCertHelpSyn, - HelpDescription: pathCertHelpDesc, - } -} - -func pathCerts(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "certs/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The name of the certificate", - }, - - "certificate": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The public certificate that should be trusted. -Must be x509 PEM encoded.`, - }, - - "allowed_names": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated list of names. -At least one must exist in either the Common Name or SANs. Supports globbing. -This parameter is deprecated, please use allowed_common_names, allowed_dns_sans, -allowed_email_sans, allowed_uri_sans.`, - }, - - "allowed_common_names": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated list of names. -At least one must exist in the Common Name. Supports globbing.`, - }, - - "allowed_dns_sans": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated list of DNS names. -At least one must exist in the SANs. Supports globbing.`, - }, - - "allowed_email_sans": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated list of Email Addresses. -At least one must exist in the SANs. Supports globbing.`, - }, - - "allowed_uri_sans": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated list of URIs. -At least one must exist in the SANs. Supports globbing.`, - }, - - "required_extensions": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated string or array of extensions -formatted as "oid:value". Expects the extension value to be some type of ASN1 encoded string. -All values much match. Supports globbing on "value".`, - }, - - "display_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The display name to use for clients using this -certificate.`, - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies.", - }, - - "lease": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Deprecated: use "ttl" instead. TTL time in -seconds. Defaults to system/backend default TTL.`, - }, - - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `TTL for tokens issued by this backend. -Defaults to system/backend default TTL time.`, - }, - - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration in either an integer number of seconds (3600) or -an integer time unit (60m) after which the -issued token can no longer be renewed.`, - }, - - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `If set, indicates that the token generated using this role -should never expire. The token should be renewed within the -duration specified by this value. At each renewal, the token's -TTL will be set to the value of this parameter.`, - }, - "bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathCertDelete, - logical.ReadOperation: b.pathCertRead, - logical.UpdateOperation: b.pathCertWrite, - }, - - HelpSynopsis: pathCertHelpSyn, - HelpDescription: pathCertHelpDesc, - } -} - -func (b *backend) Cert(ctx context.Context, s logical.Storage, n string) (*CertEntry, error) { - entry, err := s.Get(ctx, "cert/"+strings.ToLower(n)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result CertEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathCertDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "cert/"+strings.ToLower(d.Get("name").(string))) - if err != nil { - return nil, err - } - return nil, nil -} - -func (b *backend) pathCertList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - certs, err := req.Storage.List(ctx, "cert/") - if err != nil { - return nil, err - } - return logical.ListResponse(certs), nil -} - -func (b *backend) pathCertRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - cert, err := b.Cert(ctx, req.Storage, strings.ToLower(d.Get("name").(string))) - if err != nil { - return nil, err - } - if cert == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "certificate": cert.Certificate, - "display_name": cert.DisplayName, - "policies": cert.Policies, - "ttl": cert.TTL / time.Second, - "max_ttl": cert.MaxTTL / time.Second, - "period": cert.Period / time.Second, - "allowed_names": cert.AllowedNames, - "allowed_common_names": cert.AllowedCommonNames, - "allowed_dns_sans": cert.AllowedDNSSANs, - "allowed_email_sans": cert.AllowedEmailSANs, - "allowed_uri_sans": cert.AllowedURISANs, - "required_extensions": cert.RequiredExtensions, - }, - }, nil -} - -func (b *backend) pathCertWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := strings.ToLower(d.Get("name").(string)) - certificate := d.Get("certificate").(string) - displayName := d.Get("display_name").(string) - policies := policyutil.ParsePolicies(d.Get("policies")) - allowedNames := d.Get("allowed_names").([]string) - allowedCommonNames := d.Get("allowed_common_names").([]string) - allowedDNSSANs := d.Get("allowed_dns_sans").([]string) - allowedEmailSANs := d.Get("allowed_email_sans").([]string) - allowedURISANs := d.Get("allowed_uri_sans").([]string) - requiredExtensions := d.Get("required_extensions").([]string) - - var resp logical.Response - - // Parse the ttl (or lease duration) - systemDefaultTTL := b.System().DefaultLeaseTTL() - ttl := time.Duration(d.Get("ttl").(int)) * time.Second - if ttl == 0 { - ttl = time.Duration(d.Get("lease").(int)) * time.Second - } - if ttl > systemDefaultTTL { - resp.AddWarning(fmt.Sprintf("Given ttl of %d seconds is greater than current mount/system default of %d seconds", ttl/time.Second, systemDefaultTTL/time.Second)) - } - - if ttl < time.Duration(0) { - return logical.ErrorResponse("ttl cannot be negative"), nil - } - - // Parse max_ttl - systemMaxTTL := b.System().MaxLeaseTTL() - maxTTL := time.Duration(d.Get("max_ttl").(int)) * time.Second - if maxTTL > systemMaxTTL { - resp.AddWarning(fmt.Sprintf("Given max_ttl of %d seconds is greater than current mount/system default of %d seconds", maxTTL/time.Second, systemMaxTTL/time.Second)) - } - - if maxTTL < time.Duration(0) { - return logical.ErrorResponse("max_ttl cannot be negative"), nil - } - - if maxTTL != 0 && ttl > maxTTL { - return logical.ErrorResponse("ttl should be shorter than max_ttl"), nil - } - - // Parse period - period := time.Duration(d.Get("period").(int)) * time.Second - if period > systemMaxTTL { - resp.AddWarning(fmt.Sprintf("Given period of %d seconds is greater than the backend's maximum TTL of %d seconds", period/time.Second, systemMaxTTL/time.Second)) - } - - if period < time.Duration(0) { - return logical.ErrorResponse("period cannot be negative"), nil - } - - // Default the display name to the certificate name if not given - if displayName == "" { - displayName = name - } - - parsed := parsePEM([]byte(certificate)) - if len(parsed) == 0 { - return logical.ErrorResponse("failed to parse certificate"), nil - } - - // If the certificate is not a CA cert, then ensure that x509.ExtKeyUsageClientAuth is set - if !parsed[0].IsCA && parsed[0].ExtKeyUsage != nil { - var clientAuth bool - for _, usage := range parsed[0].ExtKeyUsage { - if usage == x509.ExtKeyUsageClientAuth || usage == x509.ExtKeyUsageAny { - clientAuth = true - break - } - } - if !clientAuth { - return logical.ErrorResponse("non-CA certificates should have TLS client authentication set as an extended key usage"), nil - } - } - - parsedCIDRs, err := parseutil.ParseAddrs(d.Get("bound_cidrs")) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - certEntry := &CertEntry{ - Name: name, - Certificate: certificate, - DisplayName: displayName, - Policies: policies, - AllowedNames: allowedNames, - AllowedCommonNames: allowedCommonNames, - AllowedDNSSANs: allowedDNSSANs, - AllowedEmailSANs: allowedEmailSANs, - AllowedURISANs: allowedURISANs, - RequiredExtensions: requiredExtensions, - TTL: ttl, - MaxTTL: maxTTL, - Period: period, - BoundCIDRs: parsedCIDRs, - } - - // Store it - entry, err := logical.StorageEntryJSON("cert/"+name, certEntry) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - if len(resp.Warnings) == 0 { - return nil, nil - } - - return &resp, nil -} - -type CertEntry struct { - Name string - Certificate string - DisplayName string - Policies []string - TTL time.Duration - MaxTTL time.Duration - Period time.Duration - AllowedNames []string - AllowedCommonNames []string - AllowedDNSSANs []string - AllowedEmailSANs []string - AllowedURISANs []string - RequiredExtensions []string - BoundCIDRs []*sockaddr.SockAddrMarshaler -} - -const pathCertHelpSyn = ` -Manage trusted certificates used for authentication. -` - -const pathCertHelpDesc = ` -This endpoint allows you to create, read, update, and delete trusted certificates -that are allowed to authenticate. - -Deleting a certificate will not revoke auth for prior authenticated connections. -To do this, do a revoke on "login". If you don't need to revoke login immediately, -then the next renew will cause the lease to expire. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_config.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_config.go deleted file mode 100644 index 514a65b49..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_config.go +++ /dev/null @@ -1,63 +0,0 @@ -package cert - -import ( - "context" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "disable_binding": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: `If set, during renewal, skips the matching of presented client identity with the client identity used during login. Defaults to false.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigWrite, - }, - } -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - disableBinding := data.Get("disable_binding").(bool) - - entry, err := logical.StorageEntryJSON("config", config{ - DisableBinding: disableBinding, - }) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil -} - -// Config returns the configuration for this backend. -func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error) { - entry, err := s.Get(ctx, "config") - if err != nil { - return nil, err - } - - // Returning a default configuration if an entry is not found - var result config - if entry != nil { - if err := entry.DecodeJSON(&result); err != nil { - return nil, errwrap.Wrapf("error reading configuration: {{err}}", err) - } - } - return &result, nil -} - -type config struct { - DisableBinding bool `json:"disable_binding"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_crls.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_crls.go deleted file mode 100644 index 06ced5705..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_crls.go +++ /dev/null @@ -1,252 +0,0 @@ -package cert - -import ( - "context" - "crypto/x509" - "fmt" - "math/big" - "strings" - - "github.com/fatih/structs" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathCRLs(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "crls/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The name of the certificate", - }, - - "crl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The public certificate that should be trusted. -May be DER or PEM encoded. Note: the expiration time -is ignored; if the CRL is no longer valid, delete it -using the same name as specified here.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathCRLDelete, - logical.ReadOperation: b.pathCRLRead, - logical.UpdateOperation: b.pathCRLWrite, - }, - - HelpSynopsis: pathCRLsHelpSyn, - HelpDescription: pathCRLsHelpDesc, - } -} - -func (b *backend) populateCRLs(ctx context.Context, storage logical.Storage) error { - b.crlUpdateMutex.Lock() - defer b.crlUpdateMutex.Unlock() - - if b.crls != nil { - return nil - } - - b.crls = map[string]CRLInfo{} - - keys, err := storage.List(ctx, "crls/") - if err != nil { - return errwrap.Wrapf("error listing CRLs: {{err}}", err) - } - if keys == nil || len(keys) == 0 { - return nil - } - - for _, key := range keys { - entry, err := storage.Get(ctx, "crls/"+key) - if err != nil { - b.crls = nil - return errwrap.Wrapf(fmt.Sprintf("error loading CRL %q: {{err}}", key), err) - } - if entry == nil { - continue - } - var crlInfo CRLInfo - err = entry.DecodeJSON(&crlInfo) - if err != nil { - b.crls = nil - return errwrap.Wrapf(fmt.Sprintf("error decoding CRL %q: {{err}}", key), err) - } - b.crls[key] = crlInfo - } - - return nil -} - -func (b *backend) findSerialInCRLs(serial *big.Int) map[string]RevokedSerialInfo { - b.crlUpdateMutex.RLock() - defer b.crlUpdateMutex.RUnlock() - ret := map[string]RevokedSerialInfo{} - for key, crl := range b.crls { - if crl.Serials == nil { - continue - } - if info, ok := crl.Serials[serial.String()]; ok { - ret[key] = info - } - } - return ret -} - -func parseSerialString(input string) (*big.Int, error) { - ret := &big.Int{} - - switch { - case strings.Count(input, ":") > 0: - serialBytes := certutil.ParseHexFormatted(input, ":") - if serialBytes == nil { - return nil, fmt.Errorf("error parsing serial %q", input) - } - ret.SetBytes(serialBytes) - case strings.Count(input, "-") > 0: - serialBytes := certutil.ParseHexFormatted(input, "-") - if serialBytes == nil { - return nil, fmt.Errorf("error parsing serial %q", input) - } - ret.SetBytes(serialBytes) - default: - var success bool - ret, success = ret.SetString(input, 0) - if !success { - return nil, fmt.Errorf("error parsing serial %q", input) - } - } - - return ret, nil -} - -func (b *backend) pathCRLDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := strings.ToLower(d.Get("name").(string)) - if name == "" { - return logical.ErrorResponse(`"name" parameter cannot be empty`), nil - } - - if err := b.populateCRLs(ctx, req.Storage); err != nil { - return nil, err - } - - b.crlUpdateMutex.Lock() - defer b.crlUpdateMutex.Unlock() - - _, ok := b.crls[name] - if !ok { - return logical.ErrorResponse(fmt.Sprintf( - "no such CRL %s", name, - )), nil - } - - if err := req.Storage.Delete(ctx, "crls/"+name); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "error deleting crl %s: %v", name, err), - ), nil - } - - delete(b.crls, name) - - return nil, nil -} - -func (b *backend) pathCRLRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := strings.ToLower(d.Get("name").(string)) - if name == "" { - return logical.ErrorResponse(`"name" parameter must be set`), nil - } - - if err := b.populateCRLs(ctx, req.Storage); err != nil { - return nil, err - } - - b.crlUpdateMutex.RLock() - defer b.crlUpdateMutex.RUnlock() - - var retData map[string]interface{} - - crl, ok := b.crls[name] - if !ok { - return logical.ErrorResponse(fmt.Sprintf( - "no such CRL %s", name, - )), nil - } - - retData = structs.New(&crl).Map() - - return &logical.Response{ - Data: retData, - }, nil -} - -func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := strings.ToLower(d.Get("name").(string)) - if name == "" { - return logical.ErrorResponse(`"name" parameter cannot be empty`), nil - } - crl := d.Get("crl").(string) - - certList, err := x509.ParseCRL([]byte(crl)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse CRL: %v", err)), nil - } - if certList == nil { - return logical.ErrorResponse("parsed CRL is nil"), nil - } - - if err := b.populateCRLs(ctx, req.Storage); err != nil { - return nil, err - } - - b.crlUpdateMutex.Lock() - defer b.crlUpdateMutex.Unlock() - - crlInfo := CRLInfo{ - Serials: map[string]RevokedSerialInfo{}, - } - for _, revokedCert := range certList.TBSCertList.RevokedCertificates { - crlInfo.Serials[revokedCert.SerialNumber.String()] = RevokedSerialInfo{} - } - - entry, err := logical.StorageEntryJSON("crls/"+name, crlInfo) - if err != nil { - return nil, err - } - if err = req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - b.crls[name] = crlInfo - - return nil, nil -} - -type CRLInfo struct { - Serials map[string]RevokedSerialInfo `json:"serials" structs:"serials" mapstructure:"serials"` -} - -type RevokedSerialInfo struct { -} - -const pathCRLsHelpSyn = ` -Manage Certificate Revocation Lists checked during authentication. -` - -const pathCRLsHelpDesc = ` -This endpoint allows you to create, read, update, and delete the Certificate -Revocation Lists checked during authentication. - -When any CRLs are in effect, any login will check the trust chains sent by a -client against the submitted CRLs. Any chain containing a serial number revoked -by one or more of the CRLs causes that chain to be marked as invalid for the -authentication attempt. Conversely, *any* valid chain -- that is, a chain -in which none of the serials are revoked by any CRL -- allows authentication. -This allows authentication to succeed when interim parts of one chain have been -revoked; for instance, if a certificate is signed by two intermediate CAs due to -one of them expiring. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_login.go deleted file mode 100644 index 90dbacb44..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/cert/path_login.go +++ /dev/null @@ -1,519 +0,0 @@ -package cert - -import ( - "bytes" - "context" - "crypto/tls" - "crypto/x509" - "encoding/asn1" - "encoding/base64" - "encoding/pem" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/ryanuber/go-glob" -) - -// ParsedCert is a certificate that has been configured as trusted -type ParsedCert struct { - Entry *CertEntry - Certificates []*x509.Certificate -} - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login", - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The name of the certificate role to authenticate against.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - clientCerts := req.Connection.ConnState.PeerCertificates - if len(clientCerts) == 0 { - return nil, fmt.Errorf("no client certificate found") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: clientCerts[0].Subject.CommonName, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var matched *ParsedCert - if verifyResp, resp, err := b.verifyCredentials(ctx, req, data); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - matched = verifyResp - } - - if matched == nil { - return nil, nil - } - - if err := b.checkCIDR(matched.Entry, req); err != nil { - return nil, err - } - - clientCerts := req.Connection.ConnState.PeerCertificates - if len(clientCerts) == 0 { - return logical.ErrorResponse("no client certificate found"), nil - } - skid := base64.StdEncoding.EncodeToString(clientCerts[0].SubjectKeyId) - akid := base64.StdEncoding.EncodeToString(clientCerts[0].AuthorityKeyId) - - resp := &logical.Response{ - Auth: &logical.Auth{ - Period: matched.Entry.Period, - InternalData: map[string]interface{}{ - "subject_key_id": skid, - "authority_key_id": akid, - }, - Policies: matched.Entry.Policies, - DisplayName: matched.Entry.DisplayName, - Metadata: map[string]string{ - "cert_name": matched.Entry.Name, - "common_name": clientCerts[0].Subject.CommonName, - "serial_number": clientCerts[0].SerialNumber.String(), - "subject_key_id": certutil.GetHexFormatted(clientCerts[0].SubjectKeyId, ":"), - "authority_key_id": certutil.GetHexFormatted(clientCerts[0].AuthorityKeyId, ":"), - }, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - TTL: matched.Entry.TTL, - MaxTTL: matched.Entry.MaxTTL, - }, - Alias: &logical.Alias{ - Name: clientCerts[0].Subject.CommonName, - }, - BoundCIDRs: matched.Entry.BoundCIDRs, - }, - } - - // Generate a response - return resp, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if !config.DisableBinding { - var matched *ParsedCert - if verifyResp, resp, err := b.verifyCredentials(ctx, req, d); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - matched = verifyResp - } - - if matched == nil { - return nil, nil - } - - clientCerts := req.Connection.ConnState.PeerCertificates - if len(clientCerts) == 0 { - return logical.ErrorResponse("no client certificate found"), nil - } - skid := base64.StdEncoding.EncodeToString(clientCerts[0].SubjectKeyId) - akid := base64.StdEncoding.EncodeToString(clientCerts[0].AuthorityKeyId) - - // Certificate should not only match a registered certificate policy. - // Also, the identity of the certificate presented should match the identity of the certificate used during login - if req.Auth.InternalData["subject_key_id"] != skid && req.Auth.InternalData["authority_key_id"] != akid { - return nil, fmt.Errorf("client identity during renewal not matching client identity used during login") - } - - } - // Get the cert and use its TTL - cert, err := b.Cert(ctx, req.Storage, req.Auth.Metadata["cert_name"]) - if err != nil { - return nil, err - } - if cert == nil { - // User no longer exists, do not renew - return nil, nil - } - - if !policyutil.EquivalentPolicies(cert.Policies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies have changed, not renewing") - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = cert.TTL - resp.Auth.MaxTTL = cert.MaxTTL - resp.Auth.Period = cert.Period - return resp, nil -} - -func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, d *framework.FieldData) (*ParsedCert, *logical.Response, error) { - // Get the connection state - if req.Connection == nil || req.Connection.ConnState == nil { - return nil, logical.ErrorResponse("tls connection required"), nil - } - connState := req.Connection.ConnState - - if connState.PeerCertificates == nil || len(connState.PeerCertificates) == 0 { - return nil, logical.ErrorResponse("client certificate must be supplied"), nil - } - clientCert := connState.PeerCertificates[0] - - // Allow constraining the login request to a single CertEntry - var certName string - if req.Auth != nil { // It's a renewal, use the saved certName - certName = req.Auth.Metadata["cert_name"] - } else { - certName = d.Get("name").(string) - } - - // Load the trusted certificates - roots, trusted, trustedNonCAs := b.loadTrustedCerts(ctx, req.Storage, certName) - - // Get the list of full chains matching the connection and validates the - // certificate itself - trustedChains, err := validateConnState(roots, connState) - if err != nil { - return nil, nil, err - } - - // If trustedNonCAs is not empty it means that client had registered a non-CA cert - // with the backend. - if len(trustedNonCAs) != 0 { - for _, trustedNonCA := range trustedNonCAs { - tCert := trustedNonCA.Certificates[0] - // Check for client cert being explicitly listed in the config (and matching other constraints) - if tCert.SerialNumber.Cmp(clientCert.SerialNumber) == 0 && - bytes.Equal(tCert.AuthorityKeyId, clientCert.AuthorityKeyId) && - b.matchesConstraints(clientCert, trustedNonCA.Certificates, trustedNonCA) { - return trustedNonCA, nil, nil - } - } - } - - // If no trusted chain was found, client is not authenticated - // This check happens after checking for a matching configured non-CA certs - if len(trustedChains) == 0 { - return nil, logical.ErrorResponse("invalid certificate or no client certificate supplied"), nil - } - - // Search for a ParsedCert that intersects with the validated chains and any additional constraints - matches := make([]*ParsedCert, 0) - for _, trust := range trusted { // For each ParsedCert in the config - for _, tCert := range trust.Certificates { // For each certificate in the entry - for _, chain := range trustedChains { // For each root chain that we matched - for _, cCert := range chain { // For each cert in the matched chain - if tCert.Equal(cCert) && // ParsedCert intersects with matched chain - b.matchesConstraints(clientCert, chain, trust) { // validate client cert + matched chain against the config - // Add the match to the list - matches = append(matches, trust) - } - } - } - } - } - - // Fail on no matches - if len(matches) == 0 { - return nil, logical.ErrorResponse("no chain matching all constraints could be found for this login certificate"), nil - } - - // Return the first matching entry (for backwards compatibility, we continue to just pick one if multiple match) - return matches[0], nil, nil -} - -func (b *backend) matchesConstraints(clientCert *x509.Certificate, trustedChain []*x509.Certificate, config *ParsedCert) bool { - return !b.checkForChainInCRLs(trustedChain) && - b.matchesNames(clientCert, config) && - b.matchesCommonName(clientCert, config) && - b.matchesDNSSANs(clientCert, config) && - b.matchesEmailSANs(clientCert, config) && - b.matchesURISANs(clientCert, config) && - b.matchesCertificateExtensions(clientCert, config) -} - -// matchesNames verifies that the certificate matches at least one configured -// allowed name -func (b *backend) matchesNames(clientCert *x509.Certificate, config *ParsedCert) bool { - // Default behavior (no names) is to allow all names - if len(config.Entry.AllowedNames) == 0 { - return true - } - // At least one pattern must match at least one name if any patterns are specified - for _, allowedName := range config.Entry.AllowedNames { - if glob.Glob(allowedName, clientCert.Subject.CommonName) { - return true - } - - for _, name := range clientCert.DNSNames { - if glob.Glob(allowedName, name) { - return true - } - } - - for _, name := range clientCert.EmailAddresses { - if glob.Glob(allowedName, name) { - return true - } - } - - } - return false -} - -// matchesCommonName verifies that the certificate matches at least one configured -// allowed common name -func (b *backend) matchesCommonName(clientCert *x509.Certificate, config *ParsedCert) bool { - // Default behavior (no names) is to allow all names - if len(config.Entry.AllowedCommonNames) == 0 { - return true - } - // At least one pattern must match at least one name if any patterns are specified - for _, allowedCommonName := range config.Entry.AllowedCommonNames { - if glob.Glob(allowedCommonName, clientCert.Subject.CommonName) { - return true - } - } - - return false -} - -// matchesDNSSANs verifies that the certificate matches at least one configured -// allowed dns entry in the subject alternate name extension -func (b *backend) matchesDNSSANs(clientCert *x509.Certificate, config *ParsedCert) bool { - // Default behavior (no names) is to allow all names - if len(config.Entry.AllowedDNSSANs) == 0 { - return true - } - // At least one pattern must match at least one name if any patterns are specified - for _, allowedDNS := range config.Entry.AllowedDNSSANs { - for _, name := range clientCert.DNSNames { - if glob.Glob(allowedDNS, name) { - return true - } - } - } - - return false -} - -// matchesEmailSANs verifies that the certificate matches at least one configured -// allowed email in the subject alternate name extension -func (b *backend) matchesEmailSANs(clientCert *x509.Certificate, config *ParsedCert) bool { - // Default behavior (no names) is to allow all names - if len(config.Entry.AllowedEmailSANs) == 0 { - return true - } - // At least one pattern must match at least one name if any patterns are specified - for _, allowedEmail := range config.Entry.AllowedEmailSANs { - for _, email := range clientCert.EmailAddresses { - if glob.Glob(allowedEmail, email) { - return true - } - } - } - - return false -} - -// matchesURISANs verifies that the certificate matches at least one configured -// allowed uri in the subject alternate name extension -func (b *backend) matchesURISANs(clientCert *x509.Certificate, config *ParsedCert) bool { - // Default behavior (no names) is to allow all names - if len(config.Entry.AllowedURISANs) == 0 { - return true - } - // At least one pattern must match at least one name if any patterns are specified - for _, allowedURI := range config.Entry.AllowedURISANs { - for _, name := range clientCert.URIs { - if glob.Glob(allowedURI, name.String()) { - return true - } - } - } - - return false -} - -// matchesCertificateExtensions verifies that the certificate matches configured -// required extensions -func (b *backend) matchesCertificateExtensions(clientCert *x509.Certificate, config *ParsedCert) bool { - // If no required extensions, nothing to check here - if len(config.Entry.RequiredExtensions) == 0 { - return true - } - // Fail fast if we have required extensions but no extensions on the cert - if len(clientCert.Extensions) == 0 { - return false - } - - // Build Client Extensions Map for Constraint Matching - // x509 Writes Extensions in ASN1 with a bitstring tag, which results in the field - // including its ASN.1 type tag bytes. For the sake of simplicity, assume string type - // and drop the tag bytes. And get the number of bytes from the tag. - clientExtMap := make(map[string]string, len(clientCert.Extensions)) - for _, ext := range clientCert.Extensions { - var parsedValue string - asn1.Unmarshal(ext.Value, &parsedValue) - clientExtMap[ext.Id.String()] = parsedValue - } - // If any of the required extensions don't match the constraint fails - for _, requiredExt := range config.Entry.RequiredExtensions { - reqExt := strings.SplitN(requiredExt, ":", 2) - clientExtValue, clientExtValueOk := clientExtMap[reqExt[0]] - if !clientExtValueOk || !glob.Glob(reqExt[1], clientExtValue) { - return false - } - } - return true -} - -// loadTrustedCerts is used to load all the trusted certificates from the backend -func (b *backend) loadTrustedCerts(ctx context.Context, storage logical.Storage, certName string) (pool *x509.CertPool, trusted []*ParsedCert, trustedNonCAs []*ParsedCert) { - pool = x509.NewCertPool() - trusted = make([]*ParsedCert, 0) - trustedNonCAs = make([]*ParsedCert, 0) - names, err := storage.List(ctx, "cert/") - if err != nil { - b.Logger().Error("failed to list trusted certs", "error", err) - return - } - for _, name := range names { - // If we are trying to select a single CertEntry and this isn't it - if certName != "" && name != certName { - continue - } - entry, err := b.Cert(ctx, storage, strings.TrimPrefix(name, "cert/")) - if err != nil { - b.Logger().Error("failed to load trusted cert", "name", name, "error", err) - continue - } - parsed := parsePEM([]byte(entry.Certificate)) - if len(parsed) == 0 { - b.Logger().Error("failed to parse certificate", "name", name) - continue - } - if !parsed[0].IsCA { - trustedNonCAs = append(trustedNonCAs, &ParsedCert{ - Entry: entry, - Certificates: parsed, - }) - } else { - for _, p := range parsed { - pool.AddCert(p) - } - - // Create a ParsedCert entry - trusted = append(trusted, &ParsedCert{ - Entry: entry, - Certificates: parsed, - }) - } - } - return -} - -func (b *backend) checkForChainInCRLs(chain []*x509.Certificate) bool { - badChain := false - for _, cert := range chain { - badCRLs := b.findSerialInCRLs(cert.SerialNumber) - if len(badCRLs) != 0 { - badChain = true - break - } - } - return badChain -} - -func (b *backend) checkForValidChain(chains [][]*x509.Certificate) bool { - for _, chain := range chains { - if !b.checkForChainInCRLs(chain) { - return true - } - } - return false -} - -func (b *backend) checkCIDR(cert *CertEntry, req *logical.Request) error { - if cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, cert.BoundCIDRs) { - return nil - } - return logical.ErrPermissionDenied -} - -// parsePEM parses a PEM encoded x509 certificate -func parsePEM(raw []byte) (certs []*x509.Certificate) { - for len(raw) > 0 { - var block *pem.Block - block, raw = pem.Decode(raw) - if block == nil { - break - } - if (block.Type != "CERTIFICATE" && block.Type != "TRUSTED CERTIFICATE") || len(block.Headers) != 0 { - continue - } - - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - continue - } - certs = append(certs, cert) - } - return -} - -// validateConnState is used to validate that the TLS client is authorized -// by at trusted certificate. Most of this logic is lifted from the client -// verification logic here: http://golang.org/src/crypto/tls/handshake_server.go -// The trusted chains are returned. -func validateConnState(roots *x509.CertPool, cs *tls.ConnectionState) ([][]*x509.Certificate, error) { - certs := cs.PeerCertificates - if len(certs) == 0 { - return nil, nil - } - - opts := x509.VerifyOptions{ - Roots: roots, - Intermediates: x509.NewCertPool(), - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, - } - - if len(certs) > 1 { - for _, cert := range certs[1:] { - opts.Intermediates.AddCert(cert) - } - } - - chains, err := certs[0].Verify(opts) - if err != nil { - if _, ok := err.(x509.UnknownAuthorityError); ok { - return nil, nil - } - return nil, errors.New("failed to verify client's certificate: " + err.Error()) - } - - return chains, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/github/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/github/backend.go deleted file mode 100644 index 5f2c13171..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/github/backend.go +++ /dev/null @@ -1,98 +0,0 @@ -package github - -import ( - "context" - - "github.com/google/go-github/github" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/mfa" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/oauth2" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.TeamMap = &framework.PolicyMap{ - PathMap: framework.PathMap{ - Name: "teams", - }, - DefaultKey: "default", - } - - b.UserMap = &framework.PolicyMap{ - PathMap: framework.PathMap{ - Name: "users", - }, - DefaultKey: "default", - } - - allPaths := append(b.TeamMap.Paths(), b.UserMap.Paths()...) - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Root: mfa.MFARootPaths(), - Unauthenticated: []string{ - "login", - }, - }, - - Paths: append([]*framework.Path{ - pathConfig(&b), - }, append(allPaths, mfa.MFAPaths(b.Backend, pathLogin(&b))...)...), - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend - - TeamMap *framework.PolicyMap - - UserMap *framework.PolicyMap -} - -// Client returns the GitHub client to communicate to GitHub via the -// configured settings. -func (b *backend) Client(token string) (*github.Client, error) { - tc := cleanhttp.DefaultClient() - if token != "" { - ctx := context.WithValue(context.Background(), oauth2.HTTPClient, tc) - tc = oauth2.NewClient(ctx, &tokenSource{Value: token}) - } - - return github.NewClient(tc), nil -} - -// tokenSource is an oauth2.TokenSource implementation. -type tokenSource struct { - Value string -} - -func (t *tokenSource) Token() (*oauth2.Token, error) { - return &oauth2.Token{AccessToken: t.Value}, nil -} - -const backendHelp = ` -The GitHub credential provider allows authentication via GitHub. - -Users provide a personal access token to log in, and the credential -provider verifies they're part of the correct organization and then -maps the user to a set of Vault policies according to the teams they're -part of. - -After enabling the credential provider, use the "config" route to -configure it. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/github/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/github/cli.go deleted file mode 100644 index b3a4577ed..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/github/cli.go +++ /dev/null @@ -1,95 +0,0 @@ -package github - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/password" -) - -type CLIHandler struct { - // for tests - testStdout io.Writer -} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "github" - } - - // Extract or prompt for token - token := m["token"] - if token == "" { - token = os.Getenv("VAULT_AUTH_GITHUB_TOKEN") - } - if token == "" { - // Override the output - stdout := h.testStdout - if stdout == nil { - stdout = os.Stderr - } - - var err error - fmt.Fprintf(stdout, "GitHub Personal Access Token (will be hidden): ") - token, err = password.Read(os.Stdin) - fmt.Fprintf(stdout, "\n") - if err != nil { - if err == password.ErrInterrupted { - return nil, fmt.Errorf("user interrupted") - } - - return nil, errwrap.Wrapf("An error occurred attempting to "+ - "ask for a token. The raw error message is shown below, but usually "+ - "this is because you attempted to pipe a value into the command or "+ - "you are executing outside of a terminal (tty). If you want to pipe "+ - "the value, pass \"-\" as the argument to read from stdin. The raw "+ - "error was: {{err}}", err) - } - } - - path := fmt.Sprintf("auth/%s/login", mount) - secret, err := c.Logical().Write(path, map[string]interface{}{ - "token": strings.TrimSpace(token), - }) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=github [CONFIG K=V...] - - The GitHub auth method allows users to authenticate using a GitHub - personal access token. Users can generate a personal access token from the - settings page on their GitHub account. - - Authenticate using a GitHub token: - - $ vault login -method=github token=abcd1234 - -Configuration: - - mount= - Path where the GitHub credential method is mounted. This is usually - provided via the -path flag in the "vault login" command, but it can be - specified here as well. If specified here, it takes precedence over the - value for -path. The default value is "github". - - token= - GitHub personal access token to use for authentication. If not provided, - Vault will prompt for the value. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/github/path_config.go b/vendor/github.com/hashicorp/vault/builtin/credential/github/path_config.go deleted file mode 100644 index f42b156db..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/github/path_config.go +++ /dev/null @@ -1,143 +0,0 @@ -package github - -import ( - "context" - "fmt" - "net/url" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "organization": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The organization users must be part of", - }, - - "base_url": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The API endpoint to use. Useful if you -are running GitHub Enterprise or an -API-compatible authentication server.`, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Duration after which authentication will be expired`, - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Maximum duration after which authentication will be expired`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigWrite, - logical.ReadOperation: b.pathConfigRead, - }, - } -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - organization := data.Get("organization").(string) - baseURL := data.Get("base_url").(string) - if len(baseURL) != 0 { - _, err := url.Parse(baseURL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error parsing given base_url: %s", err)), nil - } - } - - var ttl time.Duration - var err error - ttlRaw, ok := data.GetOk("ttl") - if !ok || len(ttlRaw.(string)) == 0 { - ttl = 0 - } else { - ttl, err = time.ParseDuration(ttlRaw.(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Invalid 'ttl':%s", err)), nil - } - } - - var maxTTL time.Duration - maxTTLRaw, ok := data.GetOk("max_ttl") - if !ok || len(maxTTLRaw.(string)) == 0 { - maxTTL = 0 - } else { - maxTTL, err = time.ParseDuration(maxTTLRaw.(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Invalid 'max_ttl':%s", err)), nil - } - } - - entry, err := logical.StorageEntryJSON("config", config{ - Organization: organization, - BaseURL: baseURL, - TTL: ttl, - MaxTTL: maxTTL, - }) - - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - if config == nil { - return nil, fmt.Errorf("configuration object not found") - } - - config.TTL /= time.Second - config.MaxTTL /= time.Second - - resp := &logical.Response{ - Data: map[string]interface{}{ - "organization": config.Organization, - "base_url": config.BaseURL, - "ttl": config.TTL, - "max_ttl": config.MaxTTL, - }, - } - return resp, nil -} - -// Config returns the configuration for this backend. -func (b *backend) Config(ctx context.Context, s logical.Storage) (*config, error) { - entry, err := s.Get(ctx, "config") - if err != nil { - return nil, err - } - - var result config - if entry != nil { - if err := entry.DecodeJSON(&result); err != nil { - return nil, errwrap.Wrapf("error reading configuration: {{err}}", err) - } - } - - return &result, nil -} - -type config struct { - Organization string `json:"organization" structs:"organization" mapstructure:"organization"` - BaseURL string `json:"base_url" structs:"base_url" mapstructure:"base_url"` - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl"` - MaxTTL time.Duration `json:"max_ttl" structs:"max_ttl" mapstructure:"max_ttl"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/github/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/github/path_login.go deleted file mode 100644 index 216a159b1..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/github/path_login.go +++ /dev/null @@ -1,266 +0,0 @@ -package github - -import ( - "context" - "fmt" - "net/url" - "strings" - - "github.com/google/go-github/github" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login", - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "GitHub personal API token", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - token := data.Get("token").(string) - - var verifyResp *verifyCredentialsResp - if verifyResponse, resp, err := b.verifyCredentials(ctx, req, token); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - verifyResp = verifyResponse - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: *verifyResp.User.Login, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - token := data.Get("token").(string) - - var verifyResp *verifyCredentialsResp - if verifyResponse, resp, err := b.verifyCredentials(ctx, req, token); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - verifyResp = verifyResponse - } - - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - resp := &logical.Response{ - Auth: &logical.Auth{ - InternalData: map[string]interface{}{ - "token": token, - }, - Policies: verifyResp.Policies, - Metadata: map[string]string{ - "username": *verifyResp.User.Login, - "org": *verifyResp.Org.Login, - }, - DisplayName: *verifyResp.User.Login, - LeaseOptions: logical.LeaseOptions{ - TTL: config.TTL, - MaxTTL: config.MaxTTL, - Renewable: true, - }, - Alias: &logical.Alias{ - Name: *verifyResp.User.Login, - }, - }, - } - - for _, teamName := range verifyResp.TeamNames { - if teamName == "" { - continue - } - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: teamName, - }) - } - - return resp, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.Auth == nil { - return nil, fmt.Errorf("request auth was nil") - } - - tokenRaw, ok := req.Auth.InternalData["token"] - if !ok { - return nil, fmt.Errorf("token created in previous version of Vault cannot be validated properly at renewal time") - } - token := tokenRaw.(string) - - var verifyResp *verifyCredentialsResp - if verifyResponse, resp, err := b.verifyCredentials(ctx, req, token); err != nil { - return nil, err - } else if resp != nil { - return resp, nil - } else { - verifyResp = verifyResponse - } - if !policyutil.EquivalentPolicies(verifyResp.Policies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies do not match") - } - - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = config.TTL - resp.Auth.MaxTTL = config.MaxTTL - - // Remove old aliases - resp.Auth.GroupAliases = nil - - for _, teamName := range verifyResp.TeamNames { - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: teamName, - }) - } - - return resp, nil -} - -func (b *backend) verifyCredentials(ctx context.Context, req *logical.Request, token string) (*verifyCredentialsResp, *logical.Response, error) { - config, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, nil, err - } - if config.Organization == "" { - return nil, logical.ErrorResponse( - "configure the github credential backend first"), nil - } - - client, err := b.Client(token) - if err != nil { - return nil, nil, err - } - - if config.BaseURL != "" { - parsedURL, err := url.Parse(config.BaseURL) - if err != nil { - return nil, nil, errwrap.Wrapf("successfully parsed base_url when set but failing to parse now: {{err}}", err) - } - client.BaseURL = parsedURL - } - - // Get the user - user, _, err := client.Users.Get(ctx, "") - if err != nil { - return nil, nil, err - } - - // Verify that the user is part of the organization - var org *github.Organization - - orgOpt := &github.ListOptions{ - PerPage: 100, - } - - var allOrgs []*github.Organization - for { - orgs, resp, err := client.Organizations.List(ctx, "", orgOpt) - if err != nil { - return nil, nil, err - } - allOrgs = append(allOrgs, orgs...) - if resp.NextPage == 0 { - break - } - orgOpt.Page = resp.NextPage - } - - for _, o := range allOrgs { - if strings.ToLower(*o.Login) == strings.ToLower(config.Organization) { - org = o - break - } - } - if org == nil { - return nil, logical.ErrorResponse("user is not part of required org"), nil - } - - // Get the teams that this user is part of to determine the policies - var teamNames []string - - teamOpt := &github.ListOptions{ - PerPage: 100, - } - - var allTeams []*github.Team - for { - teams, resp, err := client.Organizations.ListUserTeams(ctx, teamOpt) - if err != nil { - return nil, nil, err - } - allTeams = append(allTeams, teams...) - if resp.NextPage == 0 { - break - } - teamOpt.Page = resp.NextPage - } - - for _, t := range allTeams { - // We only care about teams that are part of the organization we use - if *t.Organization.ID != *org.ID { - continue - } - - // Append the names so we can get the policies - teamNames = append(teamNames, *t.Name) - if *t.Name != *t.Slug { - teamNames = append(teamNames, *t.Slug) - } - } - - groupPoliciesList, err := b.TeamMap.Policies(ctx, req.Storage, teamNames...) - - if err != nil { - return nil, nil, err - } - - userPoliciesList, err := b.UserMap.Policies(ctx, req.Storage, []string{*user.Login}...) - - if err != nil { - return nil, nil, err - } - - return &verifyCredentialsResp{ - User: user, - Org: org, - Policies: append(groupPoliciesList, userPoliciesList...), - TeamNames: teamNames, - }, nil, nil -} - -type verifyCredentialsResp struct { - User *github.User - Org *github.Organization - Policies []string - TeamNames []string -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/backend.go deleted file mode 100644 index 817e0c97c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/backend.go +++ /dev/null @@ -1,204 +0,0 @@ -package ldap - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/ldaputil" - "github.com/hashicorp/vault/helper/mfa" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Root: mfa.MFARootPaths(), - - Unauthenticated: []string{ - "login/*", - }, - - SealWrapStorage: []string{ - "config", - }, - }, - - Paths: append([]*framework.Path{ - pathConfig(&b), - pathGroups(&b), - pathGroupsList(&b), - pathUsers(&b), - pathUsersList(&b), - }, - mfa.MFAPaths(b.Backend, pathLogin(&b))..., - ), - - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -func (b *backend) Login(ctx context.Context, req *logical.Request, username string, password string) ([]string, *logical.Response, []string, error) { - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, nil, nil, err - } - if cfg == nil { - return nil, logical.ErrorResponse("ldap backend not configured"), nil, nil - } - - if cfg.DenyNullBind && len(password) == 0 { - return nil, logical.ErrorResponse("password cannot be of zero length when passwordless binds are being denied"), nil, nil - } - - ldapClient := ldaputil.Client{ - Logger: b.Logger(), - LDAP: ldaputil.NewLDAP(), - } - - c, err := ldapClient.DialLDAP(cfg) - if err != nil { - return nil, logical.ErrorResponse(err.Error()), nil, nil - } - if c == nil { - return nil, logical.ErrorResponse("invalid connection returned from LDAP dial"), nil, nil - } - - // Clean connection - defer c.Close() - - userBindDN, err := ldapClient.GetUserBindDN(cfg, c, username) - if err != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("error getting user bind DN", "error", err) - } - return nil, logical.ErrorResponse("ldap operation failed"), nil, nil - } - - if b.Logger().IsDebug() { - b.Logger().Debug("user binddn fetched", "username", username, "binddn", userBindDN) - } - - // Try to bind as the login user. This is where the actual authentication takes place. - if len(password) > 0 { - err = c.Bind(userBindDN, password) - } else { - err = c.UnauthenticatedBind(userBindDN) - } - if err != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("ldap bind failed", "error", err) - } - return nil, logical.ErrorResponse("ldap operation failed"), nil, nil - } - - // We re-bind to the BindDN if it's defined because we assume - // the BindDN should be the one to search, not the user logging in. - if cfg.BindDN != "" && cfg.BindPassword != "" { - if err := c.Bind(cfg.BindDN, cfg.BindPassword); err != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("error while attempting to re-bind with the BindDN User", "error", err) - } - return nil, logical.ErrorResponse("ldap operation failed"), nil, nil - } - if b.Logger().IsDebug() { - b.Logger().Debug("re-bound to original binddn") - } - } - - userDN, err := ldapClient.GetUserDN(cfg, c, userBindDN) - if err != nil { - return nil, logical.ErrorResponse(err.Error()), nil, nil - } - - ldapGroups, err := ldapClient.GetLdapGroups(cfg, c, userDN, username) - if err != nil { - return nil, logical.ErrorResponse(err.Error()), nil, nil - } - if b.Logger().IsDebug() { - b.Logger().Debug("groups fetched from server", "num_server_groups", len(ldapGroups), "server_groups", ldapGroups) - } - - ldapResponse := &logical.Response{ - Data: map[string]interface{}{}, - } - if len(ldapGroups) == 0 { - errString := fmt.Sprintf( - "no LDAP groups found in groupDN '%s'; only policies from locally-defined groups available", - cfg.GroupDN) - ldapResponse.AddWarning(errString) - } - - var allGroups []string - canonicalUsername := username - cs := *cfg.CaseSensitiveNames - if !cs { - canonicalUsername = strings.ToLower(username) - } - // Import the custom added groups from ldap backend - user, err := b.User(ctx, req.Storage, canonicalUsername) - if err == nil && user != nil && user.Groups != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("adding local groups", "num_local_groups", len(user.Groups), "local_groups", user.Groups) - } - allGroups = append(allGroups, user.Groups...) - } - // Merge local and LDAP groups - allGroups = append(allGroups, ldapGroups...) - - canonicalGroups := allGroups - // If not case sensitive, lowercase all - if !cs { - canonicalGroups = make([]string, len(allGroups)) - for i, v := range allGroups { - canonicalGroups[i] = strings.ToLower(v) - } - } - - // Retrieve policies - var policies []string - for _, groupName := range canonicalGroups { - group, err := b.Group(ctx, req.Storage, groupName) - if err == nil && group != nil { - policies = append(policies, group.Policies...) - } - } - if user != nil && user.Policies != nil { - policies = append(policies, user.Policies...) - } - // Policies from each group may overlap - policies = strutil.RemoveDuplicates(policies, true) - - return policies, ldapResponse, allGroups, nil -} - -const backendHelp = ` -The "ldap" credential provider allows authentication querying -a LDAP server, checking username and password, and associating groups -to set of policies. - -Configuration of the server is done through the "config" and "groups" -endpoints by a user with root access. Authentication is then done -by supplying the two fields for "login". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/cli.go deleted file mode 100644 index 73648eb74..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/cli.go +++ /dev/null @@ -1,111 +0,0 @@ -package ldap - -import ( - "fmt" - "os" - "strings" - - "github.com/hashicorp/vault/api" - pwd "github.com/hashicorp/vault/helper/password" -) - -type CLIHandler struct{} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "ldap" - } - - username, ok := m["username"] - if !ok { - username = usernameFromEnv() - if username == "" { - return nil, fmt.Errorf("'username' not supplied and neither 'LOGNAME' nor 'USER' env vars set") - } - } - password, ok := m["password"] - if !ok { - fmt.Fprintf(os.Stderr, "Password (will be hidden): ") - var err error - password, err = pwd.Read(os.Stdin) - fmt.Fprintf(os.Stderr, "\n") - if err != nil { - return nil, err - } - } - - data := map[string]interface{}{ - "password": password, - } - - mfa_method, ok := m["method"] - if ok { - data["method"] = mfa_method - } - mfa_passcode, ok := m["passcode"] - if ok { - data["passcode"] = mfa_passcode - } - - path := fmt.Sprintf("auth/%s/login/%s", mount, username) - secret, err := c.Logical().Write(path, data) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=ldap [CONFIG K=V...] - - The LDAP auth method allows users to authenticate using LDAP or - Active Directory. - - If MFA is enabled, a "method" and/or "passcode" may be required depending on - the MFA method. To check which MFA is in use, run: - - $ vault read auth//mfa_config - - Authenticate as "sally": - - $ vault login -method=ldap username=sally - Password (will be hidden): - - Authenticate as "bob": - - $ vault login -method=ldap username=bob password=password - -Configuration: - - method= - MFA method. - - passcode= - MFA OTP/passcode. - - password= - LDAP password to use for authentication. If not provided, the CLI will - prompt for this on stdin. - - username= - LDAP username to use for authentication. -` - - return strings.TrimSpace(help) -} - -func usernameFromEnv() string { - if logname := os.Getenv("LOGNAME"); logname != "" { - return logname - } - if user := os.Getenv("USER"); user != "" { - return user - } - return "" -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_config.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_config.go deleted file mode 100644 index 81237930b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_config.go +++ /dev/null @@ -1,175 +0,0 @@ -package ldap - -import ( - "context" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/ldaputil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `config`, - Fields: ldaputil.ConfigFields(), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.UpdateOperation: b.pathConfigWrite, - }, - - HelpSynopsis: pathConfigHelpSyn, - HelpDescription: pathConfigHelpDesc, - } -} - -/* - * Construct ConfigEntry struct using stored configuration. - */ -func (b *backend) Config(ctx context.Context, req *logical.Request) (*ldaputil.ConfigEntry, error) { - // Schema for ConfigEntry - fd, err := b.getConfigFieldData() - if err != nil { - return nil, err - } - - // Create a new ConfigEntry, filling in defaults where appropriate - result, err := ldaputil.NewConfigEntry(fd) - if err != nil { - return nil, err - } - - storedConfig, err := req.Storage.Get(ctx, "config") - if err != nil { - return nil, err - } - - if storedConfig == nil { - // No user overrides, return default configuration - result.CaseSensitiveNames = new(bool) - *result.CaseSensitiveNames = false - - return result, nil - } - - // Deserialize stored configuration. - // Fields not specified in storedConfig will retain their defaults. - if err := storedConfig.DecodeJSON(&result); err != nil { - return nil, err - } - - var persistNeeded bool - if result.CaseSensitiveNames == nil { - // Upgrade from before switching to case-insensitive - result.CaseSensitiveNames = new(bool) - *result.CaseSensitiveNames = true - persistNeeded = true - } - - if persistNeeded && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) { - entry, err := logical.StorageEntryJSON("config", result) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - } - - return result, nil -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: cfg.PasswordlessMap(), - } - return resp, nil -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Build a ConfigEntry struct out of the supplied FieldData - cfg, err := ldaputil.NewConfigEntry(d) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - // On write, if not specified, use false. We do this here so upgrade logic - // works since it calls the same newConfigEntry function - if cfg.CaseSensitiveNames == nil { - cfg.CaseSensitiveNames = new(bool) - *cfg.CaseSensitiveNames = false - } - - entry, err := logical.StorageEntryJSON("config", cfg) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -/* - * Returns FieldData describing our ConfigEntry struct schema - */ -func (b *backend) getConfigFieldData() (*framework.FieldData, error) { - configPath := b.Route("config") - - if configPath == nil { - return nil, logical.ErrUnsupportedPath - } - - raw := make(map[string]interface{}, len(configPath.Fields)) - - fd := framework.FieldData{ - Raw: raw, - Schema: configPath.Fields, - } - - return &fd, nil -} - -const pathConfigHelpSyn = ` -Configure the LDAP server to connect to, along with its options. -` - -const pathConfigHelpDesc = ` -This endpoint allows you to configure the LDAP server to connect to and its -configuration options. - -The LDAP URL can use either the "ldap://" or "ldaps://" schema. In the former -case, an unencrypted connection will be made with a default port of 389, unless -the "starttls" parameter is set to true, in which case TLS will be used. In the -latter case, a SSL connection will be established with a default port of 636. - -## A NOTE ON ESCAPING - -It is up to the administrator to provide properly escaped DNs. This includes -the user DN, bind DN for search, and so on. - -The only DN escaping performed by this backend is on usernames given at login -time when they are inserted into the final bind DN, and uses escaping rules -defined in RFC 4514. - -Additionally, Active Directory has escaping rules that differ slightly from the -RFC; in particular it requires escaping of '#' regardless of position in the DN -(the RFC only requires it to be escaped when it is the first character), and -'=', which the RFC indicates can be escaped with a backslash, but does not -contain in its set of required escapes. If you are using Active Directory and -these appear in your usernames, please ensure that they are escaped, in -addition to being properly escaped in your configured DNs. - -For reference, see https://www.ietf.org/rfc/rfc4514.txt and -http://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_groups.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_groups.go deleted file mode 100644 index 9d402faa9..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_groups.go +++ /dev/null @@ -1,158 +0,0 @@ -package ldap - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathGroupsList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "groups/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathGroupList, - }, - - HelpSynopsis: pathGroupHelpSyn, - HelpDescription: pathGroupHelpDesc, - } -} - -func pathGroups(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `groups/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the LDAP group.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies associated to the group.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathGroupDelete, - logical.ReadOperation: b.pathGroupRead, - logical.UpdateOperation: b.pathGroupWrite, - }, - - HelpSynopsis: pathGroupHelpSyn, - HelpDescription: pathGroupHelpDesc, - } -} - -func (b *backend) Group(ctx context.Context, s logical.Storage, n string) (*GroupEntry, error) { - entry, err := s.Get(ctx, "group/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result GroupEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathGroupDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "group/"+d.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathGroupRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupname := d.Get("name").(string) - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return logical.ErrorResponse("ldap backend not configured"), nil - } - if !*cfg.CaseSensitiveNames { - groupname = strings.ToLower(groupname) - } - - group, err := b.Group(ctx, req.Storage, groupname) - if err != nil { - return nil, err - } - if group == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "policies": group.Policies, - }, - }, nil -} - -func (b *backend) pathGroupWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupname := d.Get("name").(string) - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return logical.ErrorResponse("ldap backend not configured"), nil - } - if !*cfg.CaseSensitiveNames { - groupname = strings.ToLower(groupname) - } - - // Store it - entry, err := logical.StorageEntryJSON("group/"+groupname, &GroupEntry{ - Policies: policyutil.ParsePolicies(d.Get("policies")), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathGroupList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groups, err := req.Storage.List(ctx, "group/") - if err != nil { - return nil, err - } - return logical.ListResponse(groups), nil -} - -type GroupEntry struct { - Policies []string -} - -const pathGroupHelpSyn = ` -Manage users allowed to authenticate. -` - -const pathGroupHelpDesc = ` -This endpoint allows you to create, read, update, and delete configuration -for LDAP groups that are allowed to authenticate, and associate policies to -them. - -Deleting a group will not revoke auth for prior authenticated users in that -group. To do this, do a revoke on "login/" for -the usernames you want revoked. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_login.go deleted file mode 100644 index 114f20a90..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_login.go +++ /dev/null @@ -1,135 +0,0 @@ -package ldap - -import ( - "context" - "fmt" - "sort" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `login/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DN (distinguished name) to be used for login.", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - if username == "" { - return nil, fmt.Errorf("missing username") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: username, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - password := d.Get("password").(string) - - policies, resp, groupNames, err := b.Login(ctx, req, username, password) - // Handle an internal error - if err != nil { - return nil, err - } - if resp != nil { - // Handle a logical error - if resp.IsError() { - return resp, nil - } - } else { - resp = &logical.Response{} - } - - sort.Strings(policies) - - resp.Auth = &logical.Auth{ - Policies: policies, - Metadata: map[string]string{ - "username": username, - }, - InternalData: map[string]interface{}{ - "password": password, - }, - DisplayName: username, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - }, - Alias: &logical.Alias{ - Name: username, - }, - } - - for _, groupName := range groupNames { - if groupName == "" { - continue - } - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: groupName, - }) - } - return resp, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := req.Auth.Metadata["username"] - password := req.Auth.InternalData["password"].(string) - - loginPolicies, resp, groupNames, err := b.Login(ctx, req, username, password) - if len(loginPolicies) == 0 { - return resp, err - } - - if !policyutil.EquivalentPolicies(loginPolicies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies have changed, not renewing") - } - - resp.Auth = req.Auth - - // Remove old aliases - resp.Auth.GroupAliases = nil - - for _, groupName := range groupNames { - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: groupName, - }) - } - - return resp, nil -} - -const pathLoginSyn = ` -Log in with a username and password. -` - -const pathLoginDesc = ` -This endpoint authenticates using a username and password. Please be sure to -read the note on escaping from the path-help for the 'config' endpoint. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_users.go b/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_users.go deleted file mode 100644 index b19004597..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/ldap/path_users.go +++ /dev/null @@ -1,174 +0,0 @@ -package ldap - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUsersList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathUserList, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func pathUsers(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `users/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the LDAP user.", - }, - - "groups": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Comma-separated list of additional groups associated with the user.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies associated with the user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathUserDelete, - logical.ReadOperation: b.pathUserRead, - logical.UpdateOperation: b.pathUserWrite, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func (b *backend) User(ctx context.Context, s logical.Storage, n string) (*UserEntry, error) { - entry, err := s.Get(ctx, "user/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result UserEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathUserDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "user/"+d.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("name").(string) - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return logical.ErrorResponse("ldap backend not configured"), nil - } - if !*cfg.CaseSensitiveNames { - username = strings.ToLower(username) - } - - user, err := b.User(ctx, req.Storage, username) - if err != nil { - return nil, err - } - if user == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "groups": strings.Join(user.Groups, ","), - "policies": user.Policies, - }, - }, nil -} - -func (b *backend) pathUserWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - lowercaseGroups := false - username := d.Get("name").(string) - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return logical.ErrorResponse("ldap backend not configured"), nil - } - if !*cfg.CaseSensitiveNames { - username = strings.ToLower(username) - lowercaseGroups = true - } - - groups := strutil.RemoveDuplicates(strutil.ParseStringSlice(d.Get("groups").(string), ","), lowercaseGroups) - policies := policyutil.ParsePolicies(d.Get("policies")) - for i, g := range groups { - groups[i] = strings.TrimSpace(g) - } - - // Store it - entry, err := logical.StorageEntryJSON("user/"+username, &UserEntry{ - Groups: groups, - Policies: policies, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - users, err := req.Storage.List(ctx, "user/") - if err != nil { - return nil, err - } - return logical.ListResponse(users), nil -} - -type UserEntry struct { - Groups []string - Policies []string -} - -const pathUserHelpSyn = ` -Manage additional groups for users allowed to authenticate. -` - -const pathUserHelpDesc = ` -This endpoint allows you to create, read, update, and delete configuration -for LDAP users that are allowed to authenticate, in particular associating -additional groups to them. - -Deleting a user will not revoke their auth. To do this, do a revoke on "login/" for -the usernames you want revoked. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/backend.go deleted file mode 100644 index 1080f520f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/backend.go +++ /dev/null @@ -1,315 +0,0 @@ -package okta - -import ( - "context" - "fmt" - "time" - - "github.com/chrismalek/oktasdk-go/okta" - "github.com/hashicorp/vault/helper/mfa" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Root: mfa.MFARootPaths(), - - Unauthenticated: []string{ - "login/*", - }, - SealWrapStorage: []string{ - "config", - }, - }, - - Paths: append([]*framework.Path{ - pathConfig(&b), - pathUsers(&b), - pathGroups(&b), - pathUsersList(&b), - pathGroupsList(&b), - }, - mfa.MFAPaths(b.Backend, pathLogin(&b))..., - ), - - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -func (b *backend) Login(ctx context.Context, req *logical.Request, username string, password string) ([]string, *logical.Response, []string, error) { - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, nil, nil, err - } - if cfg == nil { - return nil, logical.ErrorResponse("Okta auth method not configured"), nil, nil - } - - client := cfg.OktaClient() - - type mfaFactor struct { - Id string `json:"id"` - Type string `json:"factorType"` - Provider string `json:"provider"` - } - - type embeddedResult struct { - User okta.User `json:"user"` - Factors []mfaFactor `json:"factors"` - } - - type authResult struct { - Embedded embeddedResult `json:"_embedded"` - Status string `json:"status"` - FactorResult string `json:"factorResult"` - StateToken string `json:"stateToken"` - } - - authReq, err := client.NewRequest("POST", "authn", map[string]interface{}{ - "username": username, - "password": password, - }) - if err != nil { - return nil, nil, nil, err - } - - var result authResult - rsp, err := client.Do(authReq, &result) - if err != nil { - return nil, logical.ErrorResponse(fmt.Sprintf("Okta auth failed: %v", err)), nil, nil - } - if rsp == nil { - return nil, logical.ErrorResponse("okta auth method unexpected failure"), nil, nil - } - - oktaResponse := &logical.Response{ - Data: map[string]interface{}{}, - } - - // More about Okta's Auth transaction state here: - // https://developer.okta.com/docs/api/resources/authn#transaction-state - - // If lockout failures are not configured to be hidden, the status needs to - // be inspected for LOCKED_OUT status. Otherwise, it is handled above by an - // error returned during the authentication request. - switch result.Status { - case "LOCKED_OUT": - if b.Logger().IsDebug() { - b.Logger().Debug("user is locked out", "user", username) - } - return nil, logical.ErrorResponse("okta authentication failed"), nil, nil - - case "PASSWORD_EXPIRED": - if b.Logger().IsDebug() { - b.Logger().Debug("password is expired", "user", username) - } - return nil, logical.ErrorResponse("okta authentication failed"), nil, nil - - case "PASSWORD_WARN": - oktaResponse.AddWarning("Your Okta password is in warning state and needs to be changed soon.") - - case "MFA_ENROLL", "MFA_ENROLL_ACTIVATE": - if !cfg.BypassOktaMFA { - if b.Logger().IsDebug() { - b.Logger().Debug("user must enroll or complete mfa enrollment", "user", username) - } - return nil, logical.ErrorResponse("okta authentication failed: you must complete MFA enrollment to continue"), nil, nil - } - - case "MFA_REQUIRED": - // Per Okta documentation: Users are challenged for MFA (MFA_REQUIRED) - // before the Status of PASSWORD_EXPIRED is exposed (if they have an - // active factor enrollment). This bypass removes visibility - // into the authenticating user's password expiry, but still ensures the - // credentials are valid and the user is not locked out. - if cfg.BypassOktaMFA { - result.Status = "SUCCESS" - break - } - - factorAvailable := false - - var selectedFactor mfaFactor - // only okta push is currently supported - for _, v := range result.Embedded.Factors { - if v.Type == "push" && v.Provider == "OKTA" { - factorAvailable = true - selectedFactor = v - } - } - - if !factorAvailable { - return nil, logical.ErrorResponse("Okta Verify Push factor is required in order to perform MFA"), nil, nil - } - - requestPath := fmt.Sprintf("authn/factors/%s/verify", selectedFactor.Id) - payload := map[string]interface{}{ - "stateToken": result.StateToken, - } - verifyReq, err := client.NewRequest("POST", requestPath, payload) - if err != nil { - return nil, nil, nil, err - } - - rsp, err := client.Do(verifyReq, &result) - if err != nil { - return nil, logical.ErrorResponse(fmt.Sprintf("Okta auth failed: %v", err)), nil, nil - } - if rsp == nil { - return nil, logical.ErrorResponse("okta auth backend unexpected failure"), nil, nil - } - for result.Status == "MFA_CHALLENGE" { - switch result.FactorResult { - case "WAITING": - verifyReq, err := client.NewRequest("POST", requestPath, payload) - rsp, err := client.Do(verifyReq, &result) - if err != nil { - return nil, logical.ErrorResponse(fmt.Sprintf("Okta auth failed checking loop: %v", err)), nil, nil - } - if rsp == nil { - return nil, logical.ErrorResponse("okta auth backend unexpected failure"), nil, nil - } - - select { - case <-time.After(500 * time.Millisecond): - // Continue - case <-ctx.Done(): - return nil, logical.ErrorResponse("exiting pending mfa challenge"), nil, nil - } - case "REJECTED": - return nil, logical.ErrorResponse("multi-factor authentication denied"), nil, nil - case "TIMEOUT": - return nil, logical.ErrorResponse("failed to complete multi-factor authentication"), nil, nil - case "SUCCESS": - // Allowed - default: - if b.Logger().IsDebug() { - b.Logger().Debug("unhandled result status", "status", result.Status, "factorstatus", result.FactorResult) - } - return nil, logical.ErrorResponse("okta authentication failed"), nil, nil - } - } - - case "SUCCESS": - // Do nothing here - - default: - if b.Logger().IsDebug() { - b.Logger().Debug("unhandled result status", "status", result.Status) - } - return nil, logical.ErrorResponse("okta authentication failed"), nil, nil - } - - // Verify result status again in case a switch case above modifies result - switch { - case result.Status == "SUCCESS", - result.Status == "PASSWORD_WARN", - result.Status == "MFA_REQUIRED" && cfg.BypassOktaMFA, - result.Status == "MFA_ENROLL" && cfg.BypassOktaMFA, - result.Status == "MFA_ENROLL_ACTIVATE" && cfg.BypassOktaMFA: - // Allowed - default: - if b.Logger().IsDebug() { - b.Logger().Debug("authentication returned a non-success status", "status", result.Status) - } - return nil, logical.ErrorResponse("okta authentication failed"), nil, nil - } - - var allGroups []string - // Only query the Okta API for group membership if we have a token - if cfg.Token != "" { - oktaGroups, err := b.getOktaGroups(client, &result.Embedded.User) - if err != nil { - return nil, logical.ErrorResponse(fmt.Sprintf("okta failure retrieving groups: %v", err)), nil, nil - } - if len(oktaGroups) == 0 { - errString := fmt.Sprintf( - "no Okta groups found; only policies from locally-defined groups available") - oktaResponse.AddWarning(errString) - } - allGroups = append(allGroups, oktaGroups...) - } - - // Import the custom added groups from okta backend - user, err := b.User(ctx, req.Storage, username) - if err != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("error looking up user", "error", err) - } - } - if err == nil && user != nil && user.Groups != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("adding local groups", "num_local_groups", len(user.Groups), "local_groups", user.Groups) - } - allGroups = append(allGroups, user.Groups...) - } - - // Retrieve policies - var policies []string - for _, groupName := range allGroups { - entry, _, err := b.Group(ctx, req.Storage, groupName) - if err != nil { - if b.Logger().IsDebug() { - b.Logger().Debug("error looking up group policies", "error", err) - } - } - if err == nil && entry != nil && entry.Policies != nil { - policies = append(policies, entry.Policies...) - } - } - - // Merge local Policies into Okta Policies - if user != nil && user.Policies != nil { - policies = append(policies, user.Policies...) - } - - return policies, oktaResponse, allGroups, nil -} - -func (b *backend) getOktaGroups(client *okta.Client, user *okta.User) ([]string, error) { - rsp, err := client.Users.PopulateGroups(user) - if err != nil { - return nil, err - } - if rsp == nil { - return nil, fmt.Errorf("okta auth method unexpected failure") - } - oktaGroups := make([]string, 0, len(user.Groups)) - for _, group := range user.Groups { - oktaGroups = append(oktaGroups, group.Profile.Name) - } - if b.Logger().IsDebug() { - b.Logger().Debug("Groups fetched from Okta", "num_groups", len(oktaGroups), "groups", fmt.Sprintf("%#v", oktaGroups)) - } - return oktaGroups, nil -} - -const backendHelp = ` -The Okta credential provider allows authentication querying, -checking username and password, and associating policies. If an api token is -configured groups are pulled down from Okta. - -Configuration of the connection is done through the "config" and "policies" -endpoints by a user with root access. Authentication is then done -by supplying the two fields for "login". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/cli.go deleted file mode 100644 index 951398fdb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/cli.go +++ /dev/null @@ -1,89 +0,0 @@ -package okta - -import ( - "fmt" - "os" - "strings" - - "github.com/hashicorp/vault/api" - pwd "github.com/hashicorp/vault/helper/password" -) - -// CLIHandler struct -type CLIHandler struct{} - -// Auth cli method -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - mount, ok := m["mount"] - if !ok { - mount = "okta" - } - - username, ok := m["username"] - if !ok { - return nil, fmt.Errorf("'username' var must be set") - } - password, ok := m["password"] - if !ok { - fmt.Fprintf(os.Stderr, "Password (will be hidden): ") - var err error - password, err = pwd.Read(os.Stdin) - fmt.Fprintf(os.Stderr, "\n") - if err != nil { - return nil, err - } - } - - data := map[string]interface{}{ - "password": password, - } - - mfa_method, ok := m["method"] - if ok { - data["method"] = mfa_method - } - mfa_passcode, ok := m["passcode"] - if ok { - data["passcode"] = mfa_passcode - } - - path := fmt.Sprintf("auth/%s/login/%s", mount, username) - secret, err := c.Logical().Write(path, data) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -// Help method for okta cli -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=okta [CONFIG K=V...] - - The Okta auth method allows users to authenticate using Okta. - - Authenticate as "sally": - - $ vault login -method=okta username=sally - Password (will be hidden): - - Authenticate as "bob": - - $ vault login -method=okta username=bob password=password - -Configuration: - - password= - Okta password to use for authentication. If not provided, the CLI will - prompt for this on stdin. - - username= - Okta username to use for authentication. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_config.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_config.go deleted file mode 100644 index 58f92571a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_config.go +++ /dev/null @@ -1,266 +0,0 @@ -package okta - -import ( - "context" - "fmt" - "net/url" - - "time" - - "github.com/chrismalek/oktasdk-go/okta" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - defaultBaseURL = "okta.com" - previewBaseURL = "oktapreview.com" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `config`, - Fields: map[string]*framework.FieldSchema{ - "organization": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "(DEPRECATED) Okta organization to authenticate against. Use org_name instead.", - }, - "org_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the organization to be used in the Okta API.", - }, - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "(DEPRECATED) Okta admin API token. Use api_token instead.", - }, - "api_token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Okta API key.", - }, - "base_url": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The base domain to use for the Okta API. When not specified in the configuration, "okta.com" is used.`, - }, - "production": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `(DEPRECATED) Use base_url.`, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration after which authentication will be expired`, - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Maximum duration after which authentication will be expired`, - }, - "bypass_okta_mfa": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `When set true, requests by Okta for a MFA check will be bypassed. This also disallows certain status checks on the account, such as whether the password is expired.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.CreateOperation: b.pathConfigWrite, - logical.UpdateOperation: b.pathConfigWrite, - }, - - ExistenceCheck: b.pathConfigExistenceCheck, - - HelpSynopsis: pathConfigHelp, - } -} - -// Config returns the configuration for this backend. -func (b *backend) Config(ctx context.Context, s logical.Storage) (*ConfigEntry, error) { - entry, err := s.Get(ctx, "config") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result ConfigEntry - if entry != nil { - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - } - - return &result, nil -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - if cfg == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "organization": cfg.Org, - "org_name": cfg.Org, - "ttl": cfg.TTL.Seconds(), - "max_ttl": cfg.MaxTTL.Seconds(), - "bypass_okta_mfa": cfg.BypassOktaMFA, - }, - } - if cfg.BaseURL != "" { - resp.Data["base_url"] = cfg.BaseURL - } - if cfg.Production != nil { - resp.Data["production"] = *cfg.Production - } - - if cfg.BypassOktaMFA { - resp.AddWarning("Okta MFA bypass is configured. In addition to ignoring Okta MFA requests, certain other account statuses will not be seen, such as PASSWORD_EXPIRED. Authentication will succeed in these cases.") - } - - return resp, nil -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Due to the existence check, entry will only be nil if it's a create - // operation, so just create a new one - if cfg == nil { - cfg = &ConfigEntry{} - } - - org, ok := d.GetOk("org_name") - if ok { - cfg.Org = org.(string) - } - if cfg.Org == "" { - org, ok = d.GetOk("organization") - if ok { - cfg.Org = org.(string) - } - } - if cfg.Org == "" && req.Operation == logical.CreateOperation { - return logical.ErrorResponse("org_name is missing"), nil - } - - token, ok := d.GetOk("api_token") - if ok { - cfg.Token = token.(string) - } - if cfg.Token == "" { - token, ok = d.GetOk("token") - if ok { - cfg.Token = token.(string) - } - } - - baseURLRaw, ok := d.GetOk("base_url") - if ok { - baseURL := baseURLRaw.(string) - _, err = url.Parse(fmt.Sprintf("https://%s,%s", cfg.Org, baseURL)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error parsing given base_url: %s", err)), nil - } - cfg.BaseURL = baseURL - } - - // We only care about the production flag when base_url is not set. It is - // for compatibility reasons. - if cfg.BaseURL == "" { - productionRaw, ok := d.GetOk("production") - if ok { - production := productionRaw.(bool) - cfg.Production = &production - } - } else { - // clear out old production flag if base_url is set - cfg.Production = nil - } - - bypass, ok := d.GetOk("bypass_okta_mfa") - if ok { - cfg.BypassOktaMFA = bypass.(bool) - } - - ttl, ok := d.GetOk("ttl") - if ok { - cfg.TTL = time.Duration(ttl.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - cfg.TTL = time.Duration(d.Get("ttl").(int)) * time.Second - } - - maxTTL, ok := d.GetOk("max_ttl") - if ok { - cfg.MaxTTL = time.Duration(maxTTL.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - cfg.MaxTTL = time.Duration(d.Get("max_ttl").(int)) * time.Second - } - - jsonCfg, err := logical.StorageEntryJSON("config", cfg) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, jsonCfg); err != nil { - return nil, err - } - - var resp *logical.Response - if cfg.BypassOktaMFA { - resp = new(logical.Response) - resp.AddWarning("Okta MFA bypass is configured. In addition to ignoring Okta MFA requests, certain other account statuses will not be seen, such as PASSWORD_EXPIRED. Authentication will succeed in these cases.") - } - - return resp, nil -} - -func (b *backend) pathConfigExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) { - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return false, err - } - - return cfg != nil, nil -} - -// OktaClient creates a basic okta client connection -func (c *ConfigEntry) OktaClient() *okta.Client { - baseURL := defaultBaseURL - if c.Production != nil { - if !*c.Production { - baseURL = previewBaseURL - } - } - if c.BaseURL != "" { - baseURL = c.BaseURL - } - - // We validate config on input and errors are only returned when parsing URLs - client, _ := okta.NewClientWithDomain(cleanhttp.DefaultClient(), c.Org, baseURL, c.Token) - return client -} - -// ConfigEntry for Okta -type ConfigEntry struct { - Org string `json:"organization"` - Token string `json:"token"` - BaseURL string `json:"base_url"` - Production *bool `json:"is_production,omitempty"` - TTL time.Duration `json:"ttl"` - MaxTTL time.Duration `json:"max_ttl"` - BypassOktaMFA bool `json:"bypass_okta_mfa"` -} - -const pathConfigHelp = ` -This endpoint allows you to configure the Okta and its -configuration options. - -The Okta organization are the characters at the front of the URL for Okta. -Example https://ORG.okta.com -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_groups.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_groups.go deleted file mode 100644 index 2c9bf6ba2..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_groups.go +++ /dev/null @@ -1,183 +0,0 @@ -package okta - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathGroupsList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "groups/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathGroupList, - }, - - HelpSynopsis: pathGroupHelpSyn, - HelpDescription: pathGroupHelpDesc, - } -} - -func pathGroups(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `groups/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the Okta group.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies associated to the group.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathGroupDelete, - logical.ReadOperation: b.pathGroupRead, - logical.UpdateOperation: b.pathGroupWrite, - }, - - HelpSynopsis: pathGroupHelpSyn, - HelpDescription: pathGroupHelpDesc, - } -} - -// We look up groups in a case-insensitive manner since Okta is case-preserving -// but case-insensitive for comparisons -func (b *backend) Group(ctx context.Context, s logical.Storage, n string) (*GroupEntry, string, error) { - canonicalName := n - entry, err := s.Get(ctx, "group/"+n) - if err != nil { - return nil, "", err - } - if entry == nil { - entries, err := s.List(ctx, "group/") - if err != nil { - return nil, "", err - } - for _, groupName := range entries { - if strings.ToLower(groupName) == strings.ToLower(n) { - entry, err = s.Get(ctx, "group/"+groupName) - if err != nil { - return nil, "", err - } - canonicalName = groupName - break - } - } - } - if entry == nil { - return nil, "", nil - } - - var result GroupEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, "", err - } - - return &result, canonicalName, nil -} - -func (b *backend) pathGroupDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("'name' must be supplied"), nil - } - - entry, canonicalName, err := b.Group(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if entry != nil { - err := req.Storage.Delete(ctx, "group/"+canonicalName) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -func (b *backend) pathGroupRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("'name' must be supplied"), nil - } - - group, _, err := b.Group(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if group == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "policies": group.Policies, - }, - }, nil -} - -func (b *backend) pathGroupWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("'name' must be supplied"), nil - } - - // Check for an existing group, possibly lowercased so that we keep using - // existing user set values - _, canonicalName, err := b.Group(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if canonicalName != "" { - name = canonicalName - } else { - name = strings.ToLower(name) - } - - entry, err := logical.StorageEntryJSON("group/"+name, &GroupEntry{ - Policies: policyutil.ParsePolicies(d.Get("policies")), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathGroupList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groups, err := req.Storage.List(ctx, "group/") - if err != nil { - return nil, err - } - return logical.ListResponse(groups), nil -} - -type GroupEntry struct { - Policies []string -} - -const pathGroupHelpSyn = ` -Manage users allowed to authenticate. -` - -const pathGroupHelpDesc = ` -This endpoint allows you to create, read, update, and delete configuration -for Okta groups that are allowed to authenticate, and associate policies to -them. - -Deleting a group will not revoke auth for prior authenticated users in that -group. To do this, do a revoke on "login/" for -the usernames you want revoked. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_login.go deleted file mode 100644 index af784e015..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_login.go +++ /dev/null @@ -1,166 +0,0 @@ -package okta - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/go-errors/errors" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `login/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username to be used for login.", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - if username == "" { - return nil, fmt.Errorf("missing username") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: username, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - password := d.Get("password").(string) - - policies, resp, groupNames, err := b.Login(ctx, req, username, password) - // Handle an internal error - if err != nil { - return nil, err - } - if resp != nil { - // Handle a logical error - if resp.IsError() { - return resp, nil - } - } else { - resp = &logical.Response{} - } - - sort.Strings(policies) - - cfg, err := b.getConfig(ctx, req) - if err != nil { - return nil, err - } - - resp.Auth = &logical.Auth{ - Policies: policies, - Metadata: map[string]string{ - "username": username, - "policies": strings.Join(policies, ","), - }, - InternalData: map[string]interface{}{ - "password": password, - }, - DisplayName: username, - LeaseOptions: logical.LeaseOptions{ - TTL: cfg.TTL, - MaxTTL: cfg.MaxTTL, - Renewable: true, - }, - Alias: &logical.Alias{ - Name: username, - }, - } - - for _, groupName := range groupNames { - if groupName == "" { - continue - } - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: groupName, - }) - } - - return resp, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := req.Auth.Metadata["username"] - password := req.Auth.InternalData["password"].(string) - - loginPolicies, resp, groupNames, err := b.Login(ctx, req, username, password) - if len(loginPolicies) == 0 { - return resp, err - } - - if !policyutil.EquivalentPolicies(loginPolicies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies have changed, not renewing") - } - - cfg, err := b.getConfig(ctx, req) - if err != nil { - return nil, err - } - - resp.Auth = req.Auth - resp.Auth.TTL = cfg.TTL - resp.Auth.MaxTTL = cfg.MaxTTL - - // Remove old aliases - resp.Auth.GroupAliases = nil - - for _, groupName := range groupNames { - resp.Auth.GroupAliases = append(resp.Auth.GroupAliases, &logical.Alias{ - Name: groupName, - }) - } - - return resp, nil - -} - -func (b *backend) getConfig(ctx context.Context, req *logical.Request) (*ConfigEntry, error) { - - cfg, err := b.Config(ctx, req.Storage) - if err != nil { - return nil, err - } - if cfg == nil { - return nil, errors.New("Okta backend not configured") - } - - return cfg, nil -} - -const pathLoginSyn = ` -Log in with a username and password. -` - -const pathLoginDesc = ` -This endpoint authenticates using a username and password. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_users.go b/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_users.go deleted file mode 100644 index b815825ce..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/okta/path_users.go +++ /dev/null @@ -1,155 +0,0 @@ -package okta - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUsersList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathUserList, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func pathUsers(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `users/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the user.", - }, - - "groups": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "List of groups associated with the user.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "List of policies associated with the user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathUserDelete, - logical.ReadOperation: b.pathUserRead, - logical.UpdateOperation: b.pathUserWrite, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func (b *backend) User(ctx context.Context, s logical.Storage, n string) (*UserEntry, error) { - entry, err := s.Get(ctx, "user/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result UserEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathUserDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("Error empty name"), nil - } - - err := req.Storage.Delete(ctx, "user/"+name) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("Error empty name"), nil - } - - user, err := b.User(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if user == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "groups": user.Groups, - "policies": user.Policies, - }, - }, nil -} - -func (b *backend) pathUserWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if len(name) == 0 { - return logical.ErrorResponse("Error empty name"), nil - } - - groups := d.Get("groups").([]string) - policies := d.Get("policies").([]string) - - // Store it - entry, err := logical.StorageEntryJSON("user/"+name, &UserEntry{ - Groups: groups, - Policies: policies, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - users, err := req.Storage.List(ctx, "user/") - if err != nil { - return nil, err - } - return logical.ListResponse(users), nil -} - -type UserEntry struct { - Groups []string - Policies []string -} - -const pathUserHelpSyn = ` -Manage additional groups for users allowed to authenticate. -` - -const pathUserHelpDesc = ` -This endpoint allows you to create, read, update, and delete configuration -for Okta users that are allowed to authenticate, in particular associating -additional groups to them. - -Deleting a user will not revoke their auth. To do this, do a revoke on "login/" for -the usernames you want revoked. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/radius/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/radius/backend.go deleted file mode 100644 index 2681f3d5f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/radius/backend.go +++ /dev/null @@ -1,68 +0,0 @@ -package radius - -import ( - "context" - - "github.com/hashicorp/vault/helper/mfa" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Root: mfa.MFARootPaths(), - - Unauthenticated: []string{ - "login", - "login/*", - }, - - SealWrapStorage: []string{ - "config", - }, - }, - - Paths: append([]*framework.Path{ - pathConfig(&b), - pathUsers(&b), - pathUsersList(&b), - }, - mfa.MFAPaths(b.Backend, pathLogin(&b))..., - ), - - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -const backendHelp = ` -The "radius" credential provider allows authentication against -a RADIUS server, checking username and associating users -to set of policies. - -Configuration of the server is done through the "config" and "users" -endpoints by a user with appropriate access mandated by policy. -Authentication is then done by supplying the two fields for "login". - -The backend optionally allows to grant a set of policies to any -user that successfully authenticates against the RADIUS server, -without them being explicitly mapped in vault. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_config.go b/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_config.go deleted file mode 100644 index 4a3f72e33..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_config.go +++ /dev/null @@ -1,221 +0,0 @@ -package radius - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config", - Fields: map[string]*framework.FieldSchema{ - "host": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "RADIUS server host", - }, - - "port": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 1812, - Description: "RADIUS server port (default: 1812)", - }, - "secret": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Secret shared with the RADIUS server", - }, - "unregistered_user_policies": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: "Comma-separated list of policies to grant upon successful RADIUS authentication of an unregisted user (default: emtpy)", - }, - "dial_timeout": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 10, - Description: "Number of seconds before connect times out (default: 10)", - }, - "read_timeout": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 10, - Description: "Number of seconds before response times out (default: 10)", - }, - "nas_port": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 10, - Description: "RADIUS NAS port field (default: 10)", - }, - }, - - ExistenceCheck: b.configExistenceCheck, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigRead, - logical.CreateOperation: b.pathConfigCreateUpdate, - logical.UpdateOperation: b.pathConfigCreateUpdate, - }, - - HelpSynopsis: pathConfigHelpSyn, - HelpDescription: pathConfigHelpDesc, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) configExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.Config(ctx, req) - if err != nil { - return false, err - } - return entry != nil, nil -} - -/* - * Construct ConfigEntry struct using stored configuration. - */ -func (b *backend) Config(ctx context.Context, req *logical.Request) (*ConfigEntry, error) { - storedConfig, err := req.Storage.Get(ctx, "config") - if err != nil { - return nil, err - } - - if storedConfig == nil { - return nil, nil - } - - var result ConfigEntry - - if err := storedConfig.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "host": cfg.Host, - "port": cfg.Port, - "unregistered_user_policies": cfg.UnregisteredUserPolicies, - "dial_timeout": cfg.DialTimeout, - "read_timeout": cfg.ReadTimeout, - "nas_port": cfg.NasPort, - }, - } - return resp, nil -} - -func (b *backend) pathConfigCreateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Build a ConfigEntry struct out of the supplied FieldData - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, err - } - if cfg == nil { - cfg = &ConfigEntry{} - } - - host, ok := d.GetOk("host") - if ok { - cfg.Host = strings.ToLower(host.(string)) - } else if req.Operation == logical.CreateOperation { - cfg.Host = strings.ToLower(d.Get("host").(string)) - } - if cfg.Host == "" { - return logical.ErrorResponse("config parameter `host` cannot be empty"), nil - } - - port, ok := d.GetOk("port") - if ok { - cfg.Port = port.(int) - } else if req.Operation == logical.CreateOperation { - cfg.Port = d.Get("port").(int) - } - - secret, ok := d.GetOk("secret") - if ok { - cfg.Secret = secret.(string) - } else if req.Operation == logical.CreateOperation { - cfg.Secret = d.Get("secret").(string) - } - if cfg.Secret == "" { - return logical.ErrorResponse("config parameter `secret` cannot be empty"), nil - } - - policies := make([]string, 0) - unregisteredUserPoliciesRaw, ok := d.GetOk("unregistered_user_policies") - if ok { - unregisteredUserPoliciesStr := unregisteredUserPoliciesRaw.(string) - if strings.TrimSpace(unregisteredUserPoliciesStr) != "" { - policies = strings.Split(unregisteredUserPoliciesStr, ",") - for _, policy := range policies { - if policy == "root" { - return logical.ErrorResponse("root policy cannot be granted by an auth method"), nil - } - } - } - cfg.UnregisteredUserPolicies = policies - } else if req.Operation == logical.CreateOperation { - cfg.UnregisteredUserPolicies = policies - } - - dialTimeout, ok := d.GetOk("dial_timeout") - if ok { - cfg.DialTimeout = dialTimeout.(int) - } else if req.Operation == logical.CreateOperation { - cfg.DialTimeout = d.Get("dial_timeout").(int) - } - - readTimeout, ok := d.GetOk("read_timeout") - if ok { - cfg.ReadTimeout = readTimeout.(int) - } else if req.Operation == logical.CreateOperation { - cfg.ReadTimeout = d.Get("read_timeout").(int) - } - - nasPort, ok := d.GetOk("nas_port") - if ok { - cfg.NasPort = nasPort.(int) - } else if req.Operation == logical.CreateOperation { - cfg.NasPort = d.Get("nas_port").(int) - } - - entry, err := logical.StorageEntryJSON("config", cfg) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type ConfigEntry struct { - Host string `json:"host" structs:"host" mapstructure:"host"` - Port int `json:"port" structs:"port" mapstructure:"port"` - Secret string `json:"secret" structs:"secret" mapstructure:"secret"` - UnregisteredUserPolicies []string `json:"unregistered_user_policies" structs:"unregistered_user_policies" mapstructure:"unregistered_user_policies"` - DialTimeout int `json:"dial_timeout" structs:"dial_timeout" mapstructure:"dial_timeout"` - ReadTimeout int `json:"read_timeout" structs:"read_timeout" mapstructure:"read_timeout"` - NasPort int `json:"nas_port" structs:"nas_port" mapstructure:"nas_port"` -} - -const pathConfigHelpSyn = ` -Configure the RADIUS server to connect to, along with its options. -` - -const pathConfigHelpDesc = ` -This endpoint allows you to configure the RADIUS server to connect to and its -configuration options. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_login.go deleted file mode 100644 index ef0c185d8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_login.go +++ /dev/null @@ -1,185 +0,0 @@ -package radius - -import ( - "context" - "fmt" - "net" - "strconv" - "strings" - "time" - - "layeh.com/radius" - . "layeh.com/radius/rfc2865" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login" + framework.OptionalParamRegex("urlusername"), - Fields: map[string]*framework.FieldSchema{ - "urlusername": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username to be used for login. (URL parameter)", - }, - - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username to be used for login. (POST request body)", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - if username == "" { - return nil, fmt.Errorf("missing username") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: username, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - password := d.Get("password").(string) - - if username == "" { - username = d.Get("urlusername").(string) - if username == "" { - return logical.ErrorResponse("username cannot be empty"), nil - } - } - - if password == "" { - return logical.ErrorResponse("password cannot be empty"), nil - } - - policies, resp, err := b.RadiusLogin(ctx, req, username, password) - // Handle an internal error - if err != nil { - return nil, err - } - if resp != nil { - // Handle a logical error - if resp.IsError() { - return resp, nil - } - } - - resp.Auth = &logical.Auth{ - Policies: policies, - Metadata: map[string]string{ - "username": username, - "policies": strings.Join(policies, ","), - }, - InternalData: map[string]interface{}{ - "password": password, - }, - DisplayName: username, - LeaseOptions: logical.LeaseOptions{ - Renewable: true, - }, - Alias: &logical.Alias{ - Name: username, - }, - } - return resp, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var err error - - username := req.Auth.Metadata["username"] - password := req.Auth.InternalData["password"].(string) - - var resp *logical.Response - var loginPolicies []string - - loginPolicies, resp, err = b.RadiusLogin(ctx, req, username, password) - if err != nil || (resp != nil && resp.IsError()) { - return resp, err - } - - if !policyutil.EquivalentPolicies(loginPolicies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies have changed, not renewing") - } - - return &logical.Response{Auth: req.Auth}, nil -} - -func (b *backend) RadiusLogin(ctx context.Context, req *logical.Request, username string, password string) ([]string, *logical.Response, error) { - - cfg, err := b.Config(ctx, req) - if err != nil { - return nil, nil, err - } - if cfg == nil || cfg.Host == "" || cfg.Secret == "" { - return nil, logical.ErrorResponse("radius backend not configured"), nil - } - - hostport := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)) - - packet := radius.New(radius.CodeAccessRequest, []byte(cfg.Secret)) - UserName_SetString(packet, username) - UserPassword_SetString(packet, password) - packet.Add(5, radius.NewInteger(uint32(cfg.NasPort))) - - client := radius.Client{ - Dialer: net.Dialer{ - Timeout: time.Duration(cfg.DialTimeout) * time.Second, - }, - } - clientCtx, cancelFunc := context.WithTimeout(ctx, time.Duration(cfg.ReadTimeout)*time.Second) - received, err := client.Exchange(clientCtx, packet, hostport) - cancelFunc() - if err != nil { - return nil, logical.ErrorResponse(err.Error()), nil - } - if received.Code != radius.CodeAccessAccept { - return nil, logical.ErrorResponse("access denied by the authentication server"), nil - } - - policies := cfg.UnregisteredUserPolicies - - // Retrieve user entry from storage - user, err := b.user(ctx, req.Storage, username) - if err != nil { - return nil, logical.ErrorResponse("could not retrieve user entry from storage"), err - } - if user != nil { - policies = user.Policies - } - - return policies, &logical.Response{}, nil -} - -const pathLoginSyn = ` -Log in with a username and password. -` - -const pathLoginDesc = ` -This endpoint authenticates using a username and password. Please be sure to -read the note on escaping from the path-help for the 'config' endpoint. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_users.go b/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_users.go deleted file mode 100644 index 00e36a5bf..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/radius/path_users.go +++ /dev/null @@ -1,157 +0,0 @@ -package radius - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUsersList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathUserList, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func pathUsers(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `users/(?P.+)`, - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the RADIUS user.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies associated to the user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathUserDelete, - logical.ReadOperation: b.pathUserRead, - logical.UpdateOperation: b.pathUserWrite, - logical.CreateOperation: b.pathUserWrite, - }, - - ExistenceCheck: b.userExistenceCheck, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func (b *backend) userExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - userEntry, err := b.user(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - - return userEntry != nil, nil -} - -func (b *backend) user(ctx context.Context, s logical.Storage, username string) (*UserEntry, error) { - if username == "" { - return nil, fmt.Errorf("missing username") - } - - entry, err := s.Get(ctx, "user/"+strings.ToLower(username)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result UserEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathUserDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "user/"+d.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - user, err := b.user(ctx, req.Storage, d.Get("name").(string)) - if err != nil { - return nil, err - } - if user == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "policies": user.Policies, - }, - }, nil -} - -func (b *backend) pathUserWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - - var policies = policyutil.ParsePolicies(d.Get("policies")) - for _, policy := range policies { - if policy == "root" { - return logical.ErrorResponse("root policy cannot be granted by an auth method"), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("user/"+d.Get("name").(string), &UserEntry{ - Policies: policies, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - users, err := req.Storage.List(ctx, "user/") - if err != nil { - return nil, err - } - return logical.ListResponse(users), nil -} - -type UserEntry struct { - Policies []string -} - -const pathUserHelpSyn = ` -Manage users allowed to authenticate. -` - -const pathUserHelpDesc = ` -This endpoint allows you to create, read, update, and delete configuration -for RADIUS users that are allowed to authenticate, and associate policies to -them. - -Deleting a user will not revoke auth for prior authenticated users. -To do this, do a revoke token by path on "auth/radius/login/" -for the usernames you want revoked. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/token/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/token/cli.go deleted file mode 100644 index af087eb6e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/token/cli.go +++ /dev/null @@ -1,170 +0,0 @@ -package token - -import ( - "fmt" - "io" - "os" - "strconv" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/password" -) - -type CLIHandler struct { - // for tests - testStdin io.Reader - testStdout io.Writer -} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - // Parse "lookup" first - we want to return an early error if the user - // supplied an invalid value here before we prompt them for a token. It would - // be annoying to type your token and then be told you supplied an invalid - // value that we could have known in advance. - lookup := true - if x, ok := m["lookup"]; ok { - parsed, err := strconv.ParseBool(x) - if err != nil { - return nil, errwrap.Wrapf("Failed to parse \"lookup\" as boolean: {{err}}", err) - } - lookup = parsed - } - - // Parse the token. - token, ok := m["token"] - if !ok { - // Override the output - stdout := h.testStdout - if stdout == nil { - stdout = os.Stderr - } - - // No arguments given, read the token from user input - fmt.Fprintf(stdout, "Token (will be hidden): ") - var err error - token, err = password.Read(os.Stdin) - fmt.Fprintf(stdout, "\n") - - if err != nil { - if err == password.ErrInterrupted { - return nil, fmt.Errorf("user interrupted") - } - - return nil, errwrap.Wrapf("An error occurred attempting to "+ - "ask for a token. The raw error message is shown below, but usually "+ - "this is because you attempted to pipe a value into the command or "+ - "you are executing outside of a terminal (tty). If you want to pipe "+ - "the value, pass \"-\" as the argument to read from stdin. The raw "+ - "error was: {{err}}", err) - } - } - - // Remove any whitespace, etc. - token = strings.TrimSpace(token) - - if token == "" { - return nil, fmt.Errorf( - "a token must be passed to auth, please view the help for more " + - "information") - } - - // If the user declined verification, return now. Note that we will not have - // a lot of information about the token. - if !lookup { - return &api.Secret{ - Auth: &api.SecretAuth{ - ClientToken: token, - }, - }, nil - } - - // If we got this far, we want to lookup and lookup the token and pull it's - // list of policies an metadata. - c.SetToken(token) - c.SetWrappingLookupFunc(func(string, string) string { return "" }) - - secret, err := c.Auth().Token().LookupSelf() - if err != nil { - return nil, errwrap.Wrapf("error looking up token: {{err}}", err) - } - if secret == nil { - return nil, fmt.Errorf("empty response from lookup-self") - } - - // Return an auth struct that "looks" like the response from an auth method. - // lookup and lookup-self return their data in data, not auth. We try to - // mirror that data here. - id, err := secret.TokenID() - if err != nil { - return nil, errwrap.Wrapf("error accessing token ID: {{err}}", err) - } - accessor, err := secret.TokenAccessor() - if err != nil { - return nil, errwrap.Wrapf("error accessing token accessor: {{err}}", err) - } - // This populates secret.Auth - _, err = secret.TokenPolicies() - if err != nil { - return nil, errwrap.Wrapf("error accessing token policies: {{err}}", err) - } - metadata, err := secret.TokenMetadata() - if err != nil { - return nil, errwrap.Wrapf("error accessing token metadata: {{err}}", err) - } - dur, err := secret.TokenTTL() - if err != nil { - return nil, errwrap.Wrapf("error converting token TTL: {{err}}", err) - } - renewable, err := secret.TokenIsRenewable() - if err != nil { - return nil, errwrap.Wrapf("error checking if token is renewable: {{err}}", err) - } - return &api.Secret{ - Auth: &api.SecretAuth{ - ClientToken: id, - Accessor: accessor, - Policies: secret.Auth.Policies, - TokenPolicies: secret.Auth.TokenPolicies, - IdentityPolicies: secret.Auth.IdentityPolicies, - Metadata: metadata, - - LeaseDuration: int(dur.Seconds()), - Renewable: renewable, - }, - }, nil - -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login TOKEN [CONFIG K=V...] - - The token auth method allows logging in directly with a token. This - can be a token from the "token-create" command or API. There are no - configuration options for this auth method. - - Authenticate using a token: - - $ vault login 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Authenticate but do not lookup information about the token: - - $ vault login token=96ddf4bc-d217-f3ba-f9bd-017055595017 lookup=false - - This token usually comes from a different source such as the API or via the - built-in "vault token create" command. - -Configuration: - - token= - The token to use for authentication. This is usually provided directly - via the "vault login" command. - - lookup= - Perform a lookup of the token's metadata and policies. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/backend.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/backend.go deleted file mode 100644 index 19e62cf7a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/backend.go +++ /dev/null @@ -1,60 +0,0 @@ -package userpass - -import ( - "context" - - "github.com/hashicorp/vault/helper/mfa" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: backendHelp, - - PathsSpecial: &logical.Paths{ - Root: mfa.MFARootPaths(), - - Unauthenticated: []string{ - "login/*", - }, - }, - - Paths: append([]*framework.Path{ - pathUsers(&b), - pathUsersList(&b), - pathUserPolicies(&b), - pathUserPassword(&b), - }, - mfa.MFAPaths(b.Backend, pathLogin(&b))..., - ), - - AuthRenew: b.pathLoginRenew, - BackendType: logical.TypeCredential, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -const backendHelp = ` -The "userpass" credential provider allows authentication using -a combination of a username and password. No additional factors -are supported. - -The username/password combination is configured using the "users/" -endpoints by a user with root access. Authentication is then done -by supplying the two fields for "login". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/cli.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/cli.go deleted file mode 100644 index 8531af3ce..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/cli.go +++ /dev/null @@ -1,105 +0,0 @@ -package userpass - -import ( - "fmt" - "os" - "strings" - - "github.com/hashicorp/vault/api" - pwd "github.com/hashicorp/vault/helper/password" - "github.com/mitchellh/mapstructure" -) - -type CLIHandler struct { - DefaultMount string -} - -func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) { - var data struct { - Username string `mapstructure:"username"` - Password string `mapstructure:"password"` - Mount string `mapstructure:"mount"` - Method string `mapstructure:"method"` - Passcode string `mapstructure:"passcode"` - } - if err := mapstructure.WeakDecode(m, &data); err != nil { - return nil, err - } - - if data.Username == "" { - return nil, fmt.Errorf("'username' must be specified") - } - if data.Password == "" { - fmt.Fprintf(os.Stderr, "Password (will be hidden): ") - password, err := pwd.Read(os.Stdin) - fmt.Fprintf(os.Stderr, "\n") - if err != nil { - return nil, err - } - data.Password = password - } - if data.Mount == "" { - data.Mount = h.DefaultMount - } - - options := map[string]interface{}{ - "password": data.Password, - } - if data.Method != "" { - options["method"] = data.Method - } - if data.Passcode != "" { - options["passcode"] = data.Passcode - } - - path := fmt.Sprintf("auth/%s/login/%s", data.Mount, data.Username) - secret, err := c.Logical().Write(path, options) - if err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("empty response from credential provider") - } - - return secret, nil -} - -func (h *CLIHandler) Help() string { - help := ` -Usage: vault login -method=userpass [CONFIG K=V...] - - The userpass auth method allows users to authenticate using Vault's - internal user database. - - If MFA is enabled, a "method" and/or "passcode" may be required depending on - the MFA method. To check which MFA is in use, run: - - $ vault read auth//mfa_config - - Authenticate as "sally": - - $ vault login -method=userpass username=sally - Password (will be hidden): - - Authenticate as "bob": - - $ vault login -method=userpass username=bob password=password - -Configuration: - - method= - MFA method. - - passcode= - MFA OTP/passcode. - - password= - Password to use for authentication. If not provided, the CLI will prompt - for this on stdin. - - username= - Username to use for authentication. -` - - return strings.TrimSpace(help) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_login.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_login.go deleted file mode 100644 index 91fcdd1e1..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_login.go +++ /dev/null @@ -1,138 +0,0 @@ -package userpass - -import ( - "context" - "crypto/subtle" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/crypto/bcrypt" -) - -func pathLogin(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "login/" + framework.GenericNameRegex("username"), - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username of the user.", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLogin, - logical.AliasLookaheadOperation: b.pathLoginAliasLookahead, - }, - - HelpSynopsis: pathLoginSyn, - HelpDescription: pathLoginDesc, - } -} - -func (b *backend) pathLoginAliasLookahead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := strings.ToLower(d.Get("username").(string)) - if username == "" { - return nil, fmt.Errorf("missing username") - } - - return &logical.Response{ - Auth: &logical.Auth{ - Alias: &logical.Alias{ - Name: username, - }, - }, - }, nil -} - -func (b *backend) pathLogin(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := strings.ToLower(d.Get("username").(string)) - - password := d.Get("password").(string) - if password == "" { - return nil, fmt.Errorf("missing password") - } - - // Get the user and validate auth - user, err := b.user(ctx, req.Storage, username) - if err != nil { - return nil, err - } - if user == nil { - return logical.ErrorResponse("invalid username or password"), nil - } - - // Check for a CIDR match. - if !cidrutil.RemoteAddrIsOk(req.Connection.RemoteAddr, user.BoundCIDRs) { - return logical.ErrorResponse("login request originated from invalid CIDR"), nil - } - - // Check for a password match. Check for a hash collision for Vault 0.2+, - // but handle the older legacy passwords with a constant time comparison. - passwordBytes := []byte(password) - if user.PasswordHash != nil { - if err := bcrypt.CompareHashAndPassword(user.PasswordHash, passwordBytes); err != nil { - return logical.ErrorResponse("invalid username or password"), nil - } - } else { - if subtle.ConstantTimeCompare([]byte(user.Password), passwordBytes) != 1 { - return logical.ErrorResponse("invalid username or password"), nil - } - } - - return &logical.Response{ - Auth: &logical.Auth{ - Policies: user.Policies, - Metadata: map[string]string{ - "username": username, - }, - DisplayName: username, - LeaseOptions: logical.LeaseOptions{ - TTL: user.TTL, - MaxTTL: user.MaxTTL, - Renewable: true, - }, - Alias: &logical.Alias{ - Name: username, - }, - BoundCIDRs: user.BoundCIDRs, - }, - }, nil -} - -func (b *backend) pathLoginRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the user - user, err := b.user(ctx, req.Storage, req.Auth.Metadata["username"]) - if err != nil { - return nil, err - } - if user == nil { - // User no longer exists, do not renew - return nil, nil - } - - if !policyutil.EquivalentPolicies(user.Policies, req.Auth.TokenPolicies) { - return nil, fmt.Errorf("policies have changed, not renewing") - } - - resp := &logical.Response{Auth: req.Auth} - resp.Auth.TTL = user.TTL - resp.Auth.MaxTTL = user.MaxTTL - return resp, nil -} - -const pathLoginSyn = ` -Log in with a username and password. -` - -const pathLoginDesc = ` -This endpoint authenticates using a username and password. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_password.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_password.go deleted file mode 100644 index 0d47db3cb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_password.go +++ /dev/null @@ -1,79 +0,0 @@ -package userpass - -import ( - "context" - "fmt" - - "golang.org/x/crypto/bcrypt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUserPassword(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/" + framework.GenericNameRegex("username") + "/password$", - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username for this user.", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathUserPasswordUpdate, - }, - - HelpSynopsis: pathUserPasswordHelpSyn, - HelpDescription: pathUserPasswordHelpDesc, - } -} - -func (b *backend) pathUserPasswordUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - - userEntry, err := b.user(ctx, req.Storage, username) - if err != nil { - return nil, err - } - if userEntry == nil { - return nil, fmt.Errorf("username does not exist") - } - - userErr, intErr := b.updateUserPassword(req, d, userEntry) - if intErr != nil { - return nil, err - } - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), logical.ErrInvalidRequest - } - - return nil, b.setUser(ctx, req.Storage, username, userEntry) -} - -func (b *backend) updateUserPassword(req *logical.Request, d *framework.FieldData, userEntry *UserEntry) (error, error) { - password := d.Get("password").(string) - if password == "" { - return fmt.Errorf("missing password"), nil - } - // Generate a hash of the password - hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) - if err != nil { - return nil, err - } - userEntry.PasswordHash = hash - return nil, nil -} - -const pathUserPasswordHelpSyn = ` -Reset user's password. -` - -const pathUserPasswordHelpDesc = ` -This endpoint allows resetting the user's password. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_policies.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_policies.go deleted file mode 100644 index f23e35df3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_user_policies.go +++ /dev/null @@ -1,57 +0,0 @@ -package userpass - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUserPolicies(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/" + framework.GenericNameRegex("username") + "/policies$", - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username for this user.", - }, - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathUserPoliciesUpdate, - }, - - HelpSynopsis: pathUserPoliciesHelpSyn, - HelpDescription: pathUserPoliciesHelpDesc, - } -} - -func (b *backend) pathUserPoliciesUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := d.Get("username").(string) - - userEntry, err := b.user(ctx, req.Storage, username) - if err != nil { - return nil, err - } - if userEntry == nil { - return nil, fmt.Errorf("username does not exist") - } - - userEntry.Policies = policyutil.ParsePolicies(d.Get("policies")) - - return nil, b.setUser(ctx, req.Storage, username, userEntry) -} - -const pathUserPoliciesHelpSyn = ` -Update the policies associated with the username. -` - -const pathUserPoliciesHelpDesc = ` -This endpoint allows updating the policies associated with the username. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_users.go b/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_users.go deleted file mode 100644 index 0e8eee886..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/credential/userpass/path_users.go +++ /dev/null @@ -1,238 +0,0 @@ -package userpass - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathUsersList(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/?", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathUserList, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func pathUsers(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "users/" + framework.GenericNameRegex("username"), - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username for this user.", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for this user.", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated list of policies", - }, - - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "Duration after which authentication will be expired", - }, - - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "Maximum duration after which authentication will be expired", - }, - - "bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or list of CIDR blocks. If set, specifies the blocks of -IP addresses which can perform the login operation.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathUserDelete, - logical.ReadOperation: b.pathUserRead, - logical.UpdateOperation: b.pathUserWrite, - logical.CreateOperation: b.pathUserWrite, - }, - - ExistenceCheck: b.userExistenceCheck, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func (b *backend) userExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - userEntry, err := b.user(ctx, req.Storage, data.Get("username").(string)) - if err != nil { - return false, err - } - - return userEntry != nil, nil -} - -func (b *backend) user(ctx context.Context, s logical.Storage, username string) (*UserEntry, error) { - if username == "" { - return nil, fmt.Errorf("missing username") - } - - entry, err := s.Get(ctx, "user/"+strings.ToLower(username)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result UserEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) setUser(ctx context.Context, s logical.Storage, username string, userEntry *UserEntry) error { - entry, err := logical.StorageEntryJSON("user/"+username, userEntry) - if err != nil { - return err - } - - return s.Put(ctx, entry) -} - -func (b *backend) pathUserList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - users, err := req.Storage.List(ctx, "user/") - if err != nil { - return nil, err - } - return logical.ListResponse(users), nil -} - -func (b *backend) pathUserDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "user/"+strings.ToLower(d.Get("username").(string))) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathUserRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - user, err := b.user(ctx, req.Storage, strings.ToLower(d.Get("username").(string))) - if err != nil { - return nil, err - } - if user == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "policies": user.Policies, - "ttl": user.TTL.Seconds(), - "max_ttl": user.MaxTTL.Seconds(), - "bound_cidrs": user.BoundCIDRs, - }, - }, nil -} - -func (b *backend) userCreateUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - username := strings.ToLower(d.Get("username").(string)) - userEntry, err := b.user(ctx, req.Storage, username) - if err != nil { - return nil, err - } - // Due to existence check, user will only be nil if it's a create operation - if userEntry == nil { - userEntry = &UserEntry{} - } - - if _, ok := d.GetOk("password"); ok { - userErr, intErr := b.updateUserPassword(req, d, userEntry) - if intErr != nil { - return nil, err - } - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), logical.ErrInvalidRequest - } - } - - if policiesRaw, ok := d.GetOk("policies"); ok { - userEntry.Policies = policyutil.ParsePolicies(policiesRaw) - } - - ttl, ok := d.GetOk("ttl") - if ok { - userEntry.TTL = time.Duration(ttl.(int)) * time.Second - } - - maxTTL, ok := d.GetOk("max_ttl") - if ok { - userEntry.MaxTTL = time.Duration(maxTTL.(int)) * time.Second - } - - boundCIDRs, err := parseutil.ParseAddrs(d.Get("bound_cidrs")) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - userEntry.BoundCIDRs = boundCIDRs - - return nil, b.setUser(ctx, req.Storage, username, userEntry) -} - -func (b *backend) pathUserWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - password := d.Get("password").(string) - if req.Operation == logical.CreateOperation && password == "" { - return logical.ErrorResponse("missing password"), logical.ErrInvalidRequest - } - return b.userCreateUpdate(ctx, req, d) -} - -type UserEntry struct { - // Password is deprecated in Vault 0.2 in favor of - // PasswordHash, but is retained for backwards compatibility. - Password string - - // PasswordHash is a bcrypt hash of the password. This is - // used instead of the actual password in Vault 0.2+. - PasswordHash []byte - - Policies []string - - // Duration after which the user will be revoked unless renewed - TTL time.Duration - - // Maximum duration for which user can be valid - MaxTTL time.Duration - - BoundCIDRs []*sockaddr.SockAddrMarshaler -} - -const pathUserHelpSyn = ` -Manage users allowed to authenticate. -` - -const pathUserHelpDesc = ` -This endpoint allows you to create, read, update, and delete users -that are allowed to authenticate. - -Deleting a user will not revoke auth for prior authenticated users -with that name. To do this, do a revoke on "login/" for -the username you want revoked. If you don't need to revoke login immediately, -then the next renew will cause the lease to expire. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/backend.go deleted file mode 100644 index 1c1f04b68..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/backend.go +++ /dev/null @@ -1,70 +0,0 @@ -package aws - -import ( - "context" - "strings" - "sync" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - LocalStorage: []string{ - framework.WALPrefix, - }, - SealWrapStorage: []string{ - "config/root", - }, - }, - - Paths: []*framework.Path{ - pathConfigRoot(), - pathConfigLease(&b), - pathRoles(&b), - pathListRoles(&b), - pathUser(&b), - }, - - Secrets: []*framework.Secret{ - secretAccessKeys(&b), - }, - - WALRollback: b.walRollback, - WALRollbackMinAge: 5 * time.Minute, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend - - // Mutex to protect access to reading and writing policies - roleMutex sync.RWMutex -} - -const backendHelp = ` -The AWS backend dynamically generates AWS access keys for a set of -IAM policies. The AWS access keys have a configurable lease set and -are automatically revoked at the end of the lease. - -After mounting this backend, credentials to generate IAM keys must -be configured with the "root" path and policies must be written using -the "roles/" endpoints before any access keys can be generated. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/client.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/client.go deleted file mode 100644 index 6a8ffa26f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/client.go +++ /dev/null @@ -1,96 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/awsutil" - "github.com/hashicorp/vault/logical" -) - -func getRootConfig(ctx context.Context, s logical.Storage, clientType string) (*aws.Config, error) { - credsConfig := &awsutil.CredentialsConfig{} - var endpoint string - var maxRetries int = aws.UseServiceDefaultRetries - - entry, err := s.Get(ctx, "config/root") - if err != nil { - return nil, err - } - if entry != nil { - var config rootConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, errwrap.Wrapf("error reading root configuration: {{err}}", err) - } - - credsConfig.AccessKey = config.AccessKey - credsConfig.SecretKey = config.SecretKey - credsConfig.Region = config.Region - maxRetries = config.MaxRetries - switch { - case clientType == "iam" && config.IAMEndpoint != "": - endpoint = *aws.String(config.IAMEndpoint) - case clientType == "sts" && config.STSEndpoint != "": - endpoint = *aws.String(config.STSEndpoint) - } - } - - if credsConfig.Region == "" { - credsConfig.Region = os.Getenv("AWS_REGION") - if credsConfig.Region == "" { - credsConfig.Region = os.Getenv("AWS_DEFAULT_REGION") - if credsConfig.Region == "" { - credsConfig.Region = "us-east-1" - } - } - } - - credsConfig.HTTPClient = cleanhttp.DefaultClient() - - creds, err := credsConfig.GenerateCredentialChain() - if err != nil { - return nil, err - } - - return &aws.Config{ - Credentials: creds, - Region: aws.String(credsConfig.Region), - Endpoint: &endpoint, - HTTPClient: cleanhttp.DefaultClient(), - MaxRetries: aws.Int(maxRetries), - }, nil -} - -func clientIAM(ctx context.Context, s logical.Storage) (*iam.IAM, error) { - awsConfig, err := getRootConfig(ctx, s, "iam") - if err != nil { - return nil, err - } - - client := iam.New(session.New(awsConfig)) - - if client == nil { - return nil, fmt.Errorf("could not obtain iam client") - } - return client, nil -} - -func clientSTS(ctx context.Context, s logical.Storage) (*sts.STS, error) { - awsConfig, err := getRootConfig(ctx, s, "sts") - if err != nil { - return nil, err - } - client := sts.New(session.New(awsConfig)) - - if client == nil { - return nil, fmt.Errorf("could not obtain sts client") - } - return client, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_lease.go deleted file mode 100644 index 86fa47f38..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_lease.go +++ /dev/null @@ -1,127 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "lease": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Default lease for roles.", - }, - - "lease_max": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Maximum time a credential is valid for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathLeaseRead, - logical.UpdateOperation: b.pathLeaseWrite, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -// Lease returns the lease information -func (b *backend) Lease(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathLeaseWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - leaseRaw := d.Get("lease").(string) - leaseMaxRaw := d.Get("lease_max").(string) - - if len(leaseRaw) == 0 { - return logical.ErrorResponse("'lease' is a required parameter"), nil - } - if len(leaseMaxRaw) == 0 { - return logical.ErrorResponse("'lease_max' is a required parameter"), nil - } - - lease, err := time.ParseDuration(leaseRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease: %s", err)), nil - } - leaseMax, err := time.ParseDuration(leaseMaxRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease_max: %s", err)), nil - } - - // Store it - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - Lease: lease, - LeaseMax: leaseMax, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lease, err := b.Lease(ctx, req.Storage) - - if err != nil { - return nil, err - } - if lease == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "lease": lease.Lease.String(), - "lease_max": lease.LeaseMax.String(), - }, - }, nil -} - -type configLease struct { - Lease time.Duration - LeaseMax time.Duration -} - -const pathConfigLeaseHelpSyn = ` -Configure the default lease information for generated credentials. -` - -const pathConfigLeaseHelpDesc = ` -This configures the default lease information used for credentials -generated by this backend. The lease specifies the duration that a -credential will be valid for, as well as the maximum session for -a set of credentials. - -The format for the lease is "1h" or integer and then unit. The longest -unit is hour. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_root.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_root.go deleted file mode 100644 index d3503410a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_config_root.go +++ /dev/null @@ -1,96 +0,0 @@ -package aws - -import ( - "context" - - "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigRoot() *framework.Path { - return &framework.Path{ - Pattern: "config/root", - Fields: map[string]*framework.FieldSchema{ - "access_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Access key with permission to create new keys.", - }, - - "secret_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Secret key with permission to create new keys.", - }, - - "region": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Region for API calls.", - }, - "iam_endpoint": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Endpoint to custom IAM server URL", - }, - "sts_endpoint": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Endpoint to custom STS server URL", - }, - "max_retries": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: aws.UseServiceDefaultRetries, - Description: "Maximum number of retries for recoverable exceptions of AWS APIs", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: pathConfigRootWrite, - }, - - HelpSynopsis: pathConfigRootHelpSyn, - HelpDescription: pathConfigRootHelpDesc, - } -} - -func pathConfigRootWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - region := data.Get("region").(string) - iamendpoint := data.Get("iam_endpoint").(string) - stsendpoint := data.Get("sts_endpoint").(string) - maxretries := data.Get("max_retries").(int) - - entry, err := logical.StorageEntryJSON("config/root", rootConfig{ - AccessKey: data.Get("access_key").(string), - SecretKey: data.Get("secret_key").(string), - IAMEndpoint: iamendpoint, - STSEndpoint: stsendpoint, - Region: region, - MaxRetries: maxretries, - }) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type rootConfig struct { - AccessKey string `json:"access_key"` - SecretKey string `json:"secret_key"` - IAMEndpoint string `json:"iam_endpoint"` - STSEndpoint string `json:"sts_endpoint"` - Region string `json:"region"` - MaxRetries int `json:"max_retries"` -} - -const pathConfigRootHelpSyn = ` -Configure the root credentials that are used to manage IAM. -` - -const pathConfigRootHelpDesc = ` -Before doing anything, the AWS backend needs credentials that are able -to manage IAM policies, users, access keys, etc. This endpoint is used -to configure those credentials. They don't necessarily need to be root -keys as long as they have permission to manage IAM. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_roles.go deleted file mode 100644 index 531e746cc..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_roles.go +++ /dev/null @@ -1,433 +0,0 @@ -package aws - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws/arn" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the policy", - }, - - "credential_type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: fmt.Sprintf("Type of credential to retrieve. Must be one of %s, %s, or %s", assumedRoleCred, iamUserCred, federationTokenCred), - }, - - "role_arns": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "ARNs of AWS roles allowed to be assumed. Only valid when credential_type is " + assumedRoleCred, - }, - - "policy_arns": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "ARNs of AWS policies to attach to IAM users. Only valid when credential_type is " + iamUserCred, - }, - - "policy_document": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `JSON-encoded IAM policy document. Behavior varies by credential_type. When credential_type is -iam_user, then it will attach the contents of the policy_document to the IAM -user generated. When credential_type is assumed_role or federation_token, this -will be passed in as the Policy parameter to the AssumeRole or -GetFederationToken API call, acting as a filter on permissions available.`, - }, - - "arn": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Deprecated; use role_arns or policy_arns instead. ARN Reference to a managed policy -or IAM role to assume`, - }, - - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Deprecated; use policy_document instead. IAM policy document", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathRolesDelete, - logical.ReadOperation: b.pathRolesRead, - logical.UpdateOperation: b.pathRolesWrite, - }, - - HelpSynopsis: pathRolesHelpSyn, - HelpDescription: pathRolesHelpDesc, - } -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - b.roleMutex.RLock() - defer b.roleMutex.RUnlock() - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - legacyEntries, err := req.Storage.List(ctx, "policy/") - if err != nil { - return nil, err - } - - return logical.ListResponse(append(entries, legacyEntries...)), nil -} - -func (b *backend) pathRolesDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - for _, prefix := range []string{"policy/", "role/"} { - err := req.Storage.Delete(ctx, prefix+d.Get("name").(string)) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -func (b *backend) pathRolesRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := b.roleRead(ctx, req.Storage, d.Get("name").(string), true) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - return &logical.Response{ - Data: entry.toResponseData(), - }, nil -} - -func legacyRoleData(d *framework.FieldData) (string, error) { - policy := d.Get("policy").(string) - arn := d.Get("arn").(string) - - switch { - case policy == "" && arn == "": - return "", nil - case policy != "" && arn != "": - return "", errors.New("only one of policy or arn should be provided") - case policy != "": - return policy, nil - default: - return arn, nil - } -} - -func (b *backend) pathRolesWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var resp logical.Response - - roleName := d.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - roleEntry, err := b.roleRead(ctx, req.Storage, roleName, false) - if err != nil { - return nil, err - } - if roleEntry == nil { - roleEntry = &awsRoleEntry{} - } else if roleEntry.InvalidData != "" { - resp.AddWarning(fmt.Sprintf("Invalid data of %q cleared out of role", roleEntry.InvalidData)) - roleEntry.InvalidData = "" - } - - legacyRole, err := legacyRoleData(d) - if err != nil { - return nil, err - } - - if credentialTypeRaw, ok := d.GetOk("credential_type"); ok { - if legacyRole != "" { - return logical.ErrorResponse("cannot supply deprecated role or policy parameters with an explicit credential_type"), nil - } - credentialType := credentialTypeRaw.(string) - allowedCredentialTypes := []string{iamUserCred, assumedRoleCred, federationTokenCred} - if !strutil.StrListContains(allowedCredentialTypes, credentialType) { - return logical.ErrorResponse(fmt.Sprintf("unrecognized credential_type: %q, not one of %#v", credentialType, allowedCredentialTypes)), nil - } - roleEntry.CredentialTypes = []string{credentialType} - } - - if roleArnsRaw, ok := d.GetOk("role_arns"); ok { - if legacyRole != "" { - return logical.ErrorResponse("cannot supply deprecated role or policy parameters with role_arns"), nil - } - roleEntry.RoleArns = roleArnsRaw.([]string) - } - - if policyArnsRaw, ok := d.GetOk("policy_arns"); ok { - if legacyRole != "" { - return logical.ErrorResponse("cannot supply deprecated role or policy parameters with policy_arns"), nil - } - roleEntry.PolicyArns = policyArnsRaw.([]string) - } - - if policyDocumentRaw, ok := d.GetOk("policy_document"); ok { - if legacyRole != "" { - return logical.ErrorResponse("cannot supply deprecated role or policy parameters with policy_document"), nil - } - compacted := policyDocumentRaw.(string) - if len(compacted) > 0 { - compacted, err = compactJSON(policyDocumentRaw.(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("cannot parse policy document: %q", policyDocumentRaw.(string))), nil - } - } - roleEntry.PolicyDocument = compacted - } - - if legacyRole != "" { - roleEntry = upgradeLegacyPolicyEntry(legacyRole) - if roleEntry.InvalidData != "" { - return logical.ErrorResponse(fmt.Sprintf("unable to parse supplied data: %q", roleEntry.InvalidData)), nil - } - resp.AddWarning("Detected use of legacy role or policy parameter. Please upgrade to use the new parameters.") - } else { - roleEntry.ProhibitFlexibleCredPath = false - } - - if len(roleEntry.CredentialTypes) == 0 { - return logical.ErrorResponse("did not supply credential_type"), nil - } - - if len(roleEntry.RoleArns) > 0 && !strutil.StrListContains(roleEntry.CredentialTypes, assumedRoleCred) { - return logical.ErrorResponse(fmt.Sprintf("cannot supply role_arns when credential_type isn't %s", assumedRoleCred)), nil - } - if len(roleEntry.PolicyArns) > 0 && !strutil.StrListContains(roleEntry.CredentialTypes, iamUserCred) { - return logical.ErrorResponse(fmt.Sprintf("cannot supply policy_arns when credential_type isn't %s", iamUserCred)), nil - } - - err = setAwsRole(ctx, req.Storage, roleName, roleEntry) - if err != nil { - return nil, err - } - - return &resp, nil -} - -func (b *backend) roleRead(ctx context.Context, s logical.Storage, roleName string, shouldLock bool) (*awsRoleEntry, error) { - if roleName == "" { - return nil, fmt.Errorf("missing role name") - } - if shouldLock { - b.roleMutex.RLock() - } - entry, err := s.Get(ctx, "role/"+roleName) - if shouldLock { - b.roleMutex.RUnlock() - } - if err != nil { - return nil, err - } - var roleEntry awsRoleEntry - if entry != nil { - if err := entry.DecodeJSON(&roleEntry); err != nil { - return nil, err - } - return &roleEntry, nil - } - - if shouldLock { - b.roleMutex.Lock() - defer b.roleMutex.Unlock() - } - entry, err = s.Get(ctx, "role/"+roleName) - if err != nil { - return nil, err - } - - if entry != nil { - if err := entry.DecodeJSON(&roleEntry); err != nil { - return nil, err - } - return &roleEntry, nil - } - - legacyEntry, err := s.Get(ctx, "policy/"+roleName) - if err != nil { - return nil, err - } - if legacyEntry == nil { - return nil, nil - } - - newRoleEntry := upgradeLegacyPolicyEntry(string(legacyEntry.Value)) - if b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - err = setAwsRole(ctx, s, roleName, newRoleEntry) - if err != nil { - return nil, err - } - // This can leave legacy data around in the policy/ path if it fails for some reason, - // but should be pretty rare for this to fail but prior writes to succeed, so not worrying - // about cleaning it up in case of error - err = s.Delete(ctx, "policy/"+roleName) - if err != nil { - return nil, err - } - } - return newRoleEntry, nil -} - -func upgradeLegacyPolicyEntry(entry string) *awsRoleEntry { - var newRoleEntry *awsRoleEntry - if strings.HasPrefix(entry, "arn:") { - parsedArn, err := arn.Parse(entry) - if err != nil { - newRoleEntry = &awsRoleEntry{ - InvalidData: entry, - Version: 1, - } - return newRoleEntry - } - resourceParts := strings.Split(parsedArn.Resource, "/") - resourceType := resourceParts[0] - switch resourceType { - case "role": - newRoleEntry = &awsRoleEntry{ - CredentialTypes: []string{assumedRoleCred}, - RoleArns: []string{entry}, - ProhibitFlexibleCredPath: true, - Version: 1, - } - case "policy": - newRoleEntry = &awsRoleEntry{ - CredentialTypes: []string{iamUserCred}, - PolicyArns: []string{entry}, - ProhibitFlexibleCredPath: true, - Version: 1, - } - default: - newRoleEntry = &awsRoleEntry{ - InvalidData: entry, - Version: 1, - } - } - } else { - compacted, err := compactJSON(entry) - if err != nil { - newRoleEntry = &awsRoleEntry{ - InvalidData: entry, - Version: 1, - } - } else { - // unfortunately, this is ambiguous between the cred types, so allow both - newRoleEntry = &awsRoleEntry{ - CredentialTypes: []string{iamUserCred, federationTokenCred}, - PolicyDocument: compacted, - ProhibitFlexibleCredPath: true, - Version: 1, - } - } - } - - return newRoleEntry -} - -func setAwsRole(ctx context.Context, s logical.Storage, roleName string, roleEntry *awsRoleEntry) error { - if roleName == "" { - return fmt.Errorf("empty role name") - } - if roleEntry == nil { - return fmt.Errorf("nil roleEntry") - } - entry, err := logical.StorageEntryJSON("role/"+roleName, roleEntry) - if err != nil { - return err - } - if entry == nil { - return fmt.Errorf("nil result when writing to storage") - } - if err := s.Put(ctx, entry); err != nil { - return err - } - return nil -} - -type awsRoleEntry struct { - CredentialTypes []string `json:"credential_types"` // Entries must all be in the set of ("iam_user", "assumed_role", "federation_token") - PolicyArns []string `json:"policy_arns"` // ARNs of managed policies to attach to an IAM user - RoleArns []string `json:"role_arns"` // ARNs of roles to assume for AssumedRole credentials - PolicyDocument string `json:"policy_document"` // JSON-serialized inline policy to attach to IAM users and/or to specify as the Policy parameter in AssumeRole calls - InvalidData string `json:"invalid_data,omitempty"` // Invalid role data. Exists to support converting the legacy role data into the new format - ProhibitFlexibleCredPath bool `json:"prohibit_flexible_cred_path,omitempty"` // Disallow accessing STS credentials via the creds path and vice verse - Version int `json:"version"` // Version number of the role format -} - -func (r *awsRoleEntry) toResponseData() map[string]interface{} { - respData := map[string]interface{}{ - "credential_types": r.CredentialTypes, - "policy_arns": r.PolicyArns, - "role_arns": r.RoleArns, - "policy_document": r.PolicyDocument, - } - if r.InvalidData != "" { - respData["invalid_data"] = r.InvalidData - } - return respData -} - -func compactJSON(input string) (string, error) { - var compacted bytes.Buffer - err := json.Compact(&compacted, []byte(input)) - return compacted.String(), err -} - -const ( - assumedRoleCred = "assumed_role" - iamUserCred = "iam_user" - federationTokenCred = "federation_token" -) - -const pathListRolesHelpSyn = `List the existing roles in this backend` - -const pathListRolesHelpDesc = `Roles will be listed by the role name.` - -const pathRolesHelpSyn = ` -Read, write and reference IAM policies that access keys can be made for. -` - -const pathRolesHelpDesc = ` -This path allows you to read and write roles that are used to -create access keys. These roles are associated with IAM policies that -map directly to the route to read the access keys. For example, if the -backend is mounted at "aws" and you create a role at "aws/roles/deploy" -then a user could request access credentials at "aws/creds/deploy". - -You can either supply a user inline policy (via the policy argument), or -provide a reference to an existing AWS policy by supplying the full arn -reference (via the arn argument). Inline user policies written are normal -IAM policies. Vault will not attempt to parse these except to validate -that they're basic JSON. No validation is performed on arn references. - -To validate the keys, attempt to read an access key after writing the policy. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_user.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_user.go deleted file mode 100644 index 0d541546f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/path_user.go +++ /dev/null @@ -1,239 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -func pathUser(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "(creds|sts)/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - "role_arn": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "ARN of role to assume when credential_type is " + assumedRoleCred, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "Lifetime of the returned credentials in seconds", - Default: 3600, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsRead, - logical.UpdateOperation: b.pathCredsRead, - }, - - HelpSynopsis: pathUserHelpSyn, - HelpDescription: pathUserHelpDesc, - } -} - -func (b *backend) pathCredsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleName := d.Get("name").(string) - - // Read the policy - role, err := b.roleRead(ctx, req.Storage, roleName, true) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf( - "Role '%s' not found", roleName)), nil - } - - ttl := int64(d.Get("ttl").(int)) - roleArn := d.Get("role_arn").(string) - - var credentialType string - switch { - case len(role.CredentialTypes) == 1: - credentialType = role.CredentialTypes[0] - // There is only one way for the CredentialTypes to contain more than one entry, and that's an upgrade path - // where it contains iamUserCred and federationTokenCred - // This ambiguity can be resolved based on req.Path, so resolve it assuming CredentialTypes only has those values - case len(role.CredentialTypes) > 1: - if strings.HasPrefix(req.Path, "creds") { - credentialType = iamUserCred - } else { - credentialType = federationTokenCred - } - // sanity check on the assumption above - if !strutil.StrListContains(role.CredentialTypes, credentialType) { - return logical.ErrorResponse(fmt.Sprintf("requested credential type %q not in allowed credential types %#v", credentialType, role.CredentialTypes)), nil - } - } - - // creds requested through the sts path shouldn't be allowed to get iamUserCred type creds - // when the role is created from legacy data because they might have more privileges in AWS. - // See https://github.com/hashicorp/vault/issues/4229#issuecomment-380316788 for details. - if role.ProhibitFlexibleCredPath { - if credentialType == iamUserCred && strings.HasPrefix(req.Path, "sts") { - return logical.ErrorResponse(fmt.Sprintf("attempted to retrieve %s credentials through the sts path; this is not allowed for legacy roles", iamUserCred)), nil - } - if credentialType != iamUserCred && strings.HasPrefix(req.Path, "creds") { - return logical.ErrorResponse(fmt.Sprintf("attempted to retrieve %s credentials through the creds path; this is not allowed for legacy roles", credentialType)), nil - } - } - - switch credentialType { - case iamUserCred: - return b.secretAccessKeysCreate(ctx, req.Storage, req.DisplayName, roleName, role) - case assumedRoleCred: - switch { - case roleArn == "": - if len(role.RoleArns) != 1 { - return logical.ErrorResponse("did not supply a role_arn parameter and unable to determine one"), nil - } - roleArn = role.RoleArns[0] - case !strutil.StrListContains(role.RoleArns, roleArn): - return logical.ErrorResponse(fmt.Sprintf("role_arn %q not in allowed role arns for Vault role %q", roleArn, roleName)), nil - } - return b.assumeRole(ctx, req.Storage, req.DisplayName, roleName, roleArn, role.PolicyDocument, ttl) - case federationTokenCred: - return b.secretTokenCreate(ctx, req.Storage, req.DisplayName, roleName, role.PolicyDocument, ttl) - default: - return logical.ErrorResponse(fmt.Sprintf("unknown credential_type: %q", credentialType)), nil - } -} - -func pathUserRollback(ctx context.Context, req *logical.Request, _kind string, data interface{}) error { - var entry walUser - if err := mapstructure.Decode(data, &entry); err != nil { - return err - } - username := entry.UserName - - // Get the client - client, err := clientIAM(ctx, req.Storage) - if err != nil { - return err - } - - // Get information about this user - groupsResp, err := client.ListGroupsForUser(&iam.ListGroupsForUserInput{ - UserName: aws.String(username), - MaxItems: aws.Int64(1000), - }) - if err != nil { - return err - } - groups := groupsResp.Groups - - // Inline (user) policies - policiesResp, err := client.ListUserPolicies(&iam.ListUserPoliciesInput{ - UserName: aws.String(username), - MaxItems: aws.Int64(1000), - }) - if err != nil { - return err - } - policies := policiesResp.PolicyNames - - // Attached managed policies - manPoliciesResp, err := client.ListAttachedUserPolicies(&iam.ListAttachedUserPoliciesInput{ - UserName: aws.String(username), - MaxItems: aws.Int64(1000), - }) - if err != nil { - return err - } - manPolicies := manPoliciesResp.AttachedPolicies - - keysResp, err := client.ListAccessKeys(&iam.ListAccessKeysInput{ - UserName: aws.String(username), - MaxItems: aws.Int64(1000), - }) - if err != nil { - return err - } - keys := keysResp.AccessKeyMetadata - - // Revoke all keys - for _, k := range keys { - _, err = client.DeleteAccessKey(&iam.DeleteAccessKeyInput{ - AccessKeyId: k.AccessKeyId, - UserName: aws.String(username), - }) - if err != nil { - return err - } - } - - // Detach managed policies - for _, p := range manPolicies { - _, err = client.DetachUserPolicy(&iam.DetachUserPolicyInput{ - UserName: aws.String(username), - PolicyArn: p.PolicyArn, - }) - if err != nil { - return err - } - } - - // Delete any inline (user) policies - for _, p := range policies { - _, err = client.DeleteUserPolicy(&iam.DeleteUserPolicyInput{ - UserName: aws.String(username), - PolicyName: p, - }) - if err != nil { - return err - } - } - - // Remove the user from all their groups - for _, g := range groups { - _, err = client.RemoveUserFromGroup(&iam.RemoveUserFromGroupInput{ - GroupName: g.GroupName, - UserName: aws.String(username), - }) - if err != nil { - return err - } - } - - // Delete the user - _, err = client.DeleteUser(&iam.DeleteUserInput{ - UserName: aws.String(username), - }) - if err != nil { - return err - } - - return nil -} - -type walUser struct { - UserName string -} - -const pathUserHelpSyn = ` -Generate AWS credentials from a specific Vault role. -` - -const pathUserHelpDesc = ` -This path will generate new, never before used AWS credentials for -accessing AWS. The IAM policy used to back this key pair will be -the "name" parameter. For example, if this backend is mounted at "aws", -then "aws/creds/deploy" would generate access keys for the "deploy" role. - -The access keys will have a lease associated with them. The access keys -can be revoked by using the lease ID when using the iam_user credential type. -When using AWS STS credential types (assumed_role or federation_token), -revoking the lease does not revoke the access keys. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/rollback.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/rollback.go deleted file mode 100644 index 92130bceb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/rollback.go +++ /dev/null @@ -1,27 +0,0 @@ -package aws - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -var walRollbackMap = map[string]framework.WALRollbackFunc{ - "user": pathUserRollback, -} - -func (b *backend) walRollback(ctx context.Context, req *logical.Request, kind string, data interface{}) error { - if !b.System().LocalMount() && b.System().ReplicationState().HasState(consts.ReplicationPerformancePrimary) { - return nil - } - - f, ok := walRollbackMap[kind] - if !ok { - return fmt.Errorf("unknown type to rollback") - } - - return f(ctx, req, kind, data) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/aws/secret_access_keys.go b/vendor/github.com/hashicorp/vault/builtin/logical/aws/secret_access_keys.go deleted file mode 100644 index 57e1105da..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/aws/secret_access_keys.go +++ /dev/null @@ -1,325 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "math/rand" - "regexp" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const SecretAccessKeyType = "access_keys" - -func secretAccessKeys(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretAccessKeyType, - Fields: map[string]*framework.FieldSchema{ - "access_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Access Key", - }, - - "secret_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Secret Key", - }, - "security_token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Security Token", - }, - }, - - Renew: b.secretAccessKeysRenew, - Revoke: secretAccessKeysRevoke, - } -} - -func genUsername(displayName, policyName, userType string) (ret string, warning string) { - var midString string - - switch userType { - case "iam_user": - // IAM users are capped at 64 chars; this leaves, after the beginning and - // end added below, 42 chars to play with. - midString = fmt.Sprintf("%s-%s-", - normalizeDisplayName(displayName), - normalizeDisplayName(policyName)) - if len(midString) > 42 { - midString = midString[0:42] - warning = "the calling token display name/IAM policy name were truncated to fit into IAM username length limits" - } - case "sts": - // Capped at 32 chars, which leaves only a couple of characters to play - // with, so don't insert display name or policy name at all - } - - ret = fmt.Sprintf("vault-%s%d-%d", midString, time.Now().Unix(), rand.Int31n(10000)) - return -} - -func (b *backend) secretTokenCreate(ctx context.Context, s logical.Storage, - displayName, policyName, policy string, - lifeTimeInSeconds int64) (*logical.Response, error) { - STSClient, err := clientSTS(ctx, s) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - username, usernameWarning := genUsername(displayName, policyName, "sts") - - tokenResp, err := STSClient.GetFederationToken( - &sts.GetFederationTokenInput{ - Name: aws.String(username), - Policy: aws.String(policy), - DurationSeconds: &lifeTimeInSeconds, - }) - - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error generating STS keys: %s", err)), nil - } - - resp := b.Secret(SecretAccessKeyType).Response(map[string]interface{}{ - "access_key": *tokenResp.Credentials.AccessKeyId, - "secret_key": *tokenResp.Credentials.SecretAccessKey, - "security_token": *tokenResp.Credentials.SessionToken, - }, map[string]interface{}{ - "username": username, - "policy": policy, - "is_sts": true, - }) - - // Set the secret TTL to appropriately match the expiration of the token - resp.Secret.TTL = tokenResp.Credentials.Expiration.Sub(time.Now()) - - // STS are purposefully short-lived and aren't renewable - resp.Secret.Renewable = false - - if usernameWarning != "" { - resp.AddWarning(usernameWarning) - } - - return resp, nil -} - -func (b *backend) assumeRole(ctx context.Context, s logical.Storage, - displayName, roleName, roleArn, policy string, - lifeTimeInSeconds int64) (*logical.Response, error) { - STSClient, err := clientSTS(ctx, s) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - username, usernameWarning := genUsername(displayName, roleName, "iam_user") - - assumeRoleInput := &sts.AssumeRoleInput{ - RoleSessionName: aws.String(username), - RoleArn: aws.String(roleArn), - DurationSeconds: &lifeTimeInSeconds, - } - if policy != "" { - assumeRoleInput.SetPolicy(policy) - } - tokenResp, err := STSClient.AssumeRole(assumeRoleInput) - - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error assuming role: %s", err)), nil - } - - resp := b.Secret(SecretAccessKeyType).Response(map[string]interface{}{ - "access_key": *tokenResp.Credentials.AccessKeyId, - "secret_key": *tokenResp.Credentials.SecretAccessKey, - "security_token": *tokenResp.Credentials.SessionToken, - }, map[string]interface{}{ - "username": username, - "policy": roleArn, - "is_sts": true, - }) - - // Set the secret TTL to appropriately match the expiration of the token - resp.Secret.TTL = tokenResp.Credentials.Expiration.Sub(time.Now()) - - // STS are purposefully short-lived and aren't renewable - resp.Secret.Renewable = false - - if usernameWarning != "" { - resp.AddWarning(usernameWarning) - } - - return resp, nil -} - -func (b *backend) secretAccessKeysCreate( - ctx context.Context, - s logical.Storage, - displayName, policyName string, role *awsRoleEntry) (*logical.Response, error) { - client, err := clientIAM(ctx, s) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - username, usernameWarning := genUsername(displayName, policyName, "iam_user") - - // Write to the WAL that this user will be created. We do this before - // the user is created because if switch the order then the WAL put - // can fail, which would put us in an awkward position: we have a user - // we need to rollback but can't put the WAL entry to do the rollback. - walId, err := framework.PutWAL(ctx, s, "user", &walUser{ - UserName: username, - }) - if err != nil { - return nil, errwrap.Wrapf("error writing WAL entry: {{err}}", err) - } - - // Create the user - _, err = client.CreateUser(&iam.CreateUserInput{ - UserName: aws.String(username), - }) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error creating IAM user: %s", err)), nil - } - - for _, arn := range role.PolicyArns { - // Attach existing policy against user - _, err = client.AttachUserPolicy(&iam.AttachUserPolicyInput{ - UserName: aws.String(username), - PolicyArn: aws.String(arn), - }) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error attaching user policy: %s", err)), nil - } - - } - if role.PolicyDocument != "" { - // Add new inline user policy against user - _, err = client.PutUserPolicy(&iam.PutUserPolicyInput{ - UserName: aws.String(username), - PolicyName: aws.String(policyName), - PolicyDocument: aws.String(role.PolicyDocument), - }) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error putting user policy: %s", err)), nil - } - } - - // Create the keys - keyResp, err := client.CreateAccessKey(&iam.CreateAccessKeyInput{ - UserName: aws.String(username), - }) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error creating access keys: %s", err)), nil - } - - // Remove the WAL entry, we succeeded! If we fail, we don't return - // the secret because it'll get rolled back anyways, so we have to return - // an error here. - if err := framework.DeleteWAL(ctx, s, walId); err != nil { - return nil, errwrap.Wrapf("failed to commit WAL entry: {{err}}", err) - } - - // Return the info! - resp := b.Secret(SecretAccessKeyType).Response(map[string]interface{}{ - "access_key": *keyResp.AccessKey.AccessKeyId, - "secret_key": *keyResp.AccessKey.SecretAccessKey, - "security_token": nil, - }, map[string]interface{}{ - "username": username, - "policy": role, - "is_sts": false, - }) - - lease, err := b.Lease(ctx, s) - if err != nil || lease == nil { - lease = &configLease{} - } - - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - - if usernameWarning != "" { - resp.AddWarning(usernameWarning) - } - - return resp, nil -} - -func (b *backend) secretAccessKeysRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // STS already has a lifetime, and we don't support renewing it - isSTSRaw, ok := req.Secret.InternalData["is_sts"] - if ok { - isSTS, ok := isSTSRaw.(bool) - if ok { - if isSTS { - return nil, nil - } - } - } - - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - return resp, nil -} - -func secretAccessKeysRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - - // STS cleans up after itself so we can skip this if is_sts internal data - // element set to true. If is_sts is not set, assumes old version - // and defaults to the IAM approach. - isSTSRaw, ok := req.Secret.InternalData["is_sts"] - if ok { - isSTS, ok := isSTSRaw.(bool) - if ok { - if isSTS { - return nil, nil - } - } else { - return nil, fmt.Errorf("secret has is_sts but value could not be understood") - } - } - - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - - // Use the user rollback mechanism to delete this user - err := pathUserRollback(ctx, req, "user", map[string]interface{}{ - "username": username, - }) - if err != nil { - return nil, err - } - - return nil, nil -} - -func normalizeDisplayName(displayName string) string { - re := regexp.MustCompile("[^a-zA-Z0-9+=,.@_-]") - return re.ReplaceAllString(displayName, "_") -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/backend.go deleted file mode 100644 index fba89781f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/backend.go +++ /dev/null @@ -1,135 +0,0 @@ -package cassandra - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/gocql/gocql" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Factory creates a new backend -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Backend contains the base information for the backend's functionality -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathRoles(&b), - pathCredsCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Invalidate: b.invalidate, - - Clean: func(_ context.Context) { - b.ResetDB(nil) - }, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend - - // Session is goroutine safe, however, since we reinitialize - // it when connection info changes, we want to make sure we - // can close it and use a new connection; hence the lock - session *gocql.Session - lock sync.Mutex -} - -type sessionConfig struct { - Hosts string `json:"hosts" structs:"hosts" mapstructure:"hosts"` - Username string `json:"username" structs:"username" mapstructure:"username"` - Password string `json:"password" structs:"password" mapstructure:"password"` - TLS bool `json:"tls" structs:"tls" mapstructure:"tls"` - InsecureTLS bool `json:"insecure_tls" structs:"insecure_tls" mapstructure:"insecure_tls"` - Certificate string `json:"certificate" structs:"certificate" mapstructure:"certificate"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` - IssuingCA string `json:"issuing_ca" structs:"issuing_ca" mapstructure:"issuing_ca"` - ProtocolVersion int `json:"protocol_version" structs:"protocol_version" mapstructure:"protocol_version"` - ConnectTimeout int `json:"connect_timeout" structs:"connect_timeout" mapstructure:"connect_timeout"` - TLSMinVersion string `json:"tls_min_version" structs:"tls_min_version" mapstructure:"tls_min_version"` -} - -// DB returns the database connection. -func (b *backend) DB(ctx context.Context, s logical.Storage) (*gocql.Session, error) { - b.lock.Lock() - defer b.lock.Unlock() - - // If we already have a DB, we got it! - if b.session != nil { - return b.session, nil - } - - entry, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return nil, fmt.Errorf("configure the DB connection with config/connection first") - } - - config := &sessionConfig{} - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - - session, err := createSession(config, s) - // Store the session in backend for reuse - b.session = session - - return session, err - -} - -// ResetDB forces a connection next time DB() is called. -func (b *backend) ResetDB(newSession *gocql.Session) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.session != nil { - b.session.Close() - } - - b.session = newSession -} - -func (b *backend) invalidate(_ context.Context, key string) { - switch key { - case "config/connection": - b.ResetDB(nil) - } -} - -const backendHelp = ` -The Cassandra backend dynamically generates database users. - -After mounting this backend, configure it using the endpoints within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_config_connection.go deleted file mode 100644 index 3b616f7c7..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_config_connection.go +++ /dev/null @@ -1,244 +0,0 @@ -package cassandra - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "hosts": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Comma-separated list of hosts", - }, - - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The username to use for connecting to the cluster", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The password to use for connecting to the cluster", - }, - - "tls": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Whether to use TLS. If pem_bundle or pem_json are -set, this is automatically set to true`, - }, - - "insecure_tls": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Whether to use TLS but skip verification; has no -effect if a CA certificate is provided`, - }, - - "tls_min_version": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "tls12", - Description: "Minimum TLS version to use. Accepted values are 'tls10', 'tls11' or 'tls12'. Defaults to 'tls12'", - }, - - "pem_bundle": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `PEM-format, concatenated unencrypted secret key -and certificate, with optional CA certificate`, - }, - - "pem_json": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `JSON containing a PEM-format, unencrypted secret -key and certificate, with optional CA certificate. -The JSON output of a certificate issued with the PKI -backend can be directly passed into this parameter. -If both this and "pem_bundle" are specified, this will -take precedence.`, - }, - - "protocol_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The protocol version to use. Defaults to 2.`, - }, - - "connect_timeout": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 5, - Description: `The connection timeout to use. Defaults to 5.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConnectionRead, - logical.UpdateOperation: b.pathConnectionWrite, - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := req.Storage.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return logical.ErrorResponse(fmt.Sprintf("Configure the DB connection with config/connection first")), nil - } - - config := &sessionConfig{} - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "hosts": config.Hosts, - "username": config.Username, - "tls": config.TLS, - "insecure_tls": config.InsecureTLS, - "certificate": config.Certificate, - "issuing_ca": config.IssuingCA, - "protocol_version": config.ProtocolVersion, - "connect_timeout": config.ConnectTimeout, - "tls_min_version": config.TLSMinVersion, - }, - } - return resp, nil -} - -func (b *backend) pathConnectionWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - hosts := data.Get("hosts").(string) - username := data.Get("username").(string) - password := data.Get("password").(string) - - switch { - case len(hosts) == 0: - return logical.ErrorResponse("Hosts cannot be empty"), nil - case len(username) == 0: - return logical.ErrorResponse("Username cannot be empty"), nil - case len(password) == 0: - return logical.ErrorResponse("Password cannot be empty"), nil - } - - config := &sessionConfig{ - Hosts: hosts, - Username: username, - Password: password, - TLS: data.Get("tls").(bool), - InsecureTLS: data.Get("insecure_tls").(bool), - ProtocolVersion: data.Get("protocol_version").(int), - ConnectTimeout: data.Get("connect_timeout").(int), - } - - config.TLSMinVersion = data.Get("tls_min_version").(string) - if config.TLSMinVersion == "" { - return logical.ErrorResponse("failed to get 'tls_min_version' value"), nil - } - - var ok bool - _, ok = tlsutil.TLSLookup[config.TLSMinVersion] - if !ok { - return logical.ErrorResponse("invalid 'tls_min_version'"), nil - } - - if config.InsecureTLS { - config.TLS = true - } - - pemBundle := data.Get("pem_bundle").(string) - pemJSON := data.Get("pem_json").(string) - - var certBundle *certutil.CertBundle - var parsedCertBundle *certutil.ParsedCertBundle - var err error - - switch { - case len(pemJSON) != 0: - parsedCertBundle, err = certutil.ParsePKIJSON([]byte(pemJSON)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Could not parse given JSON; it must be in the format of the output of the PKI backend certificate issuing command: %s", err)), nil - } - certBundle, err = parsedCertBundle.ToCertBundle() - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error marshaling PEM information: %s", err)), nil - } - config.Certificate = certBundle.Certificate - config.PrivateKey = certBundle.PrivateKey - config.IssuingCA = certBundle.IssuingCA - config.TLS = true - - case len(pemBundle) != 0: - parsedCertBundle, err = certutil.ParsePEMBundle(pemBundle) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error parsing the given PEM information: %s", err)), nil - } - certBundle, err = parsedCertBundle.ToCertBundle() - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error marshaling PEM information: %s", err)), nil - } - config.Certificate = certBundle.Certificate - config.PrivateKey = certBundle.PrivateKey - config.IssuingCA = certBundle.IssuingCA - config.TLS = true - } - - session, err := createSession(config, req.Storage) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the DB connection - b.ResetDB(session) - - return nil, nil -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection information to talk to Cassandra. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection information used to connect to Cassandra. - -"hosts" is a comma-delimited list of hostnames in the Cassandra cluster. - -"username" and "password" are self-explanatory, although the given user -must have superuser access within Cassandra. Note that since this backend -issues username/password credentials, Cassandra must be configured to use -PasswordAuthenticator or a similar backend for its authentication. If you wish -to have no authorization in Cassandra and want to use TLS client certificates, -see the PKI backend. - -TLS works as follows: - -* If "tls" is set to true, the connection will use TLS; this happens automatically if "pem_bundle", "pem_json", or "insecure_tls" is set - -* If "insecure_tls" is set to true, the connection will not perform verification of the server certificate; this also sets "tls" to true - -* If only "issuing_ca" is set in "pem_json", or the only certificate in "pem_bundle" is a CA certificate, the given CA certificate will be used for server certificate verification; otherwise the system CA certificates will be used - -* If "certificate" and "private_key" are set in "pem_bundle" or "pem_json", client auth will be turned on for the connection - -"pem_bundle" should be a PEM-concatenated bundle of a private key + client certificate, an issuing CA certificate, or both. "pem_json" should contain the same information; for convenience, the JSON format is the same as that output by the issue command from the PKI backend. - -When configuring the connection information, the backend will verify its -validity. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_creds_create.go deleted file mode 100644 index 896176fb7..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_creds_create.go +++ /dev/null @@ -1,123 +0,0 @@ -package cassandra - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/gocql/gocql" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathCredsCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsCreateRead, - }, - - HelpSynopsis: pathCredsCreateReadHelpSyn, - HelpDescription: pathCredsCreateReadHelpDesc, - } -} - -func (b *backend) pathCredsCreateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := getRole(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("Unknown role: %s", name)), nil - } - - displayName := req.DisplayName - userUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - username := fmt.Sprintf("vault_%s_%s_%s_%d", name, displayName, userUUID, time.Now().Unix()) - username = strings.Replace(username, "-", "_", -1) - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - // Get our connection - session, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Set consistency - if role.Consistency != "" { - consistencyValue, err := gocql.ParseConsistencyWrapper(role.Consistency) - if err != nil { - return nil, err - } - - session.SetConsistency(consistencyValue) - } - - // Execute each query - for _, query := range strutil.ParseArbitraryStringSlice(role.CreationCQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - err = session.Query(substQuery(query, map[string]string{ - "username": username, - "password": password, - })).Exec() - if err != nil { - for _, query := range strutil.ParseArbitraryStringSlice(role.RollbackCQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - session.Query(substQuery(query, map[string]string{ - "username": username, - "password": password, - })).Exec() - } - return nil, err - } - } - - // Return the secret - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - "role": name, - }) - resp.Secret.TTL = role.Lease - - return resp, nil -} - -const pathCredsCreateReadHelpSyn = ` -Request database credentials for a certain role. -` - -const pathCredsCreateReadHelpDesc = ` -This path creates database credentials for a certain role. The -database credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_roles.go deleted file mode 100644 index 9e7c8c1b1..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/path_roles.go +++ /dev/null @@ -1,196 +0,0 @@ -package cassandra - -import ( - "context" - "fmt" - "time" - - "github.com/fatih/structs" - "github.com/gocql/gocql" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - defaultCreationCQL = `CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;` - defaultRollbackCQL = `DROP USER '{{username}}';` -) - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "creation_cql": &framework.FieldSchema{ - Type: framework.TypeString, - Default: defaultCreationCQL, - Description: `CQL to create a user and optionally grant -authorization. If not supplied, a default that -creates non-superuser accounts with the built-in -password authenticator will be used; no -authorization grants will be configured. Separate -statements by semicolons; use @file to load from a -file. Valid template values are '{{username}}' and -'{{password}}' -- the single quotes are important!`, - }, - - "rollback_cql": &framework.FieldSchema{ - Type: framework.TypeString, - Default: defaultRollbackCQL, - Description: `CQL to roll back an account operation. This will -be used if there is an error during execution of a -statement passed in via the "creation_cql" parameter -parameter. The default simply drops the user, which -should generally be sufficient. Separate statements -by semicolons; use @file to load from a file. Valid -template values are '{{username}}' and -'{{password}}' -- the single quotes are important!`, - }, - - "lease": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "4h", - Description: "The lease length; defaults to 4 hours", - }, - - "consistency": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "Quorum", - Description: "The consistency level for the operations; defaults to Quorum.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func getRole(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := getRole(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: structs.New(role).Map(), - }, nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - creationCQL := data.Get("creation_cql").(string) - - rollbackCQL := data.Get("rollback_cql").(string) - - leaseRaw := data.Get("lease").(string) - lease, err := time.ParseDuration(leaseRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error parsing lease value of %s: %s", leaseRaw, err)), nil - } - - consistencyStr := data.Get("consistency").(string) - _, err = gocql.ParseConsistencyWrapper(consistencyStr) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error parsing consistency value of %q: %v", consistencyStr, err)), nil - } - - entry := &roleEntry{ - Lease: lease, - CreationCQL: creationCQL, - RollbackCQL: rollbackCQL, - Consistency: consistencyStr, - } - - // Store it - entryJSON, err := logical.StorageEntryJSON("role/"+name, entry) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entryJSON); err != nil { - return nil, err - } - - return nil, nil -} - -type roleEntry struct { - CreationCQL string `json:"creation_cql" structs:"creation_cql"` - Lease time.Duration `json:"lease" structs:"lease"` - RollbackCQL string `json:"rollback_cql" structs:"rollback_cql"` - Consistency string `json:"consistency" structs:"consistency"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "creation_cql" parameter customizes the CQL string used to create users -and assign them grants. This can be a sequence of CQL queries separated by -semicolons. Some substitution will be done to the CQL string for certain keys. -The names of the variables must be surrounded by '{{' and '}}' to be replaced. -Note that it is important that single quotes are used, not double quotes. - - * "username" - The random username generated for the DB user. - - * "password" - The random password generated for the DB user. - -If no "creation_cql" parameter is given, a default will be used: - -` + defaultCreationCQL + ` - -This default should be suitable for Cassandra installations using the password -authenticator but not configured to use authorization. - -Similarly, the "rollback_cql" is used if user creation fails, in the absence of -Cassandra transactions. The default should be suitable for almost any -instance of Cassandra: - -` + defaultRollbackCQL + ` - -"lease" the lease time; if not set the mount/system defaults are used. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/secret_creds.go deleted file mode 100644 index 4aa54956a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/secret_creds.go +++ /dev/null @@ -1,78 +0,0 @@ -package cassandra - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// SecretCredsType is the type of creds issued from this backend -const SecretCredsType = "cassandra" - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password", - }, - }, - - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the lease information - roleRaw, ok := req.Secret.InternalData["role"] - if !ok { - return nil, fmt.Errorf("secret is missing role internal data") - } - roleName, ok := roleRaw.(string) - if !ok { - return nil, fmt.Errorf("error converting role internal data to string") - } - - role, err := getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, errwrap.Wrapf("unable to load role: {{err}}", err) - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = role.Lease - return resp, nil -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("error converting username internal data to string") - } - - session, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, fmt.Errorf("error getting session") - } - - err = session.Query(fmt.Sprintf("DROP USER '%s'", username)).Exec() - if err != nil { - return nil, fmt.Errorf("error removing user %q", username) - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/util.go deleted file mode 100644 index 2be6d9671..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/cassandra/util.go +++ /dev/null @@ -1,96 +0,0 @@ -package cassandra - -import ( - "crypto/tls" - "fmt" - "strings" - "time" - - "github.com/gocql/gocql" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/logical" -) - -// Query templates a query for us. -func substQuery(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} - -func createSession(cfg *sessionConfig, s logical.Storage) (*gocql.Session, error) { - clusterConfig := gocql.NewCluster(strings.Split(cfg.Hosts, ",")...) - clusterConfig.Authenticator = gocql.PasswordAuthenticator{ - Username: cfg.Username, - Password: cfg.Password, - } - - clusterConfig.ProtoVersion = cfg.ProtocolVersion - if clusterConfig.ProtoVersion == 0 { - clusterConfig.ProtoVersion = 2 - } - - clusterConfig.Timeout = time.Duration(cfg.ConnectTimeout) * time.Second - - if cfg.TLS { - var tlsConfig *tls.Config - if len(cfg.Certificate) > 0 || len(cfg.IssuingCA) > 0 { - if len(cfg.Certificate) > 0 && len(cfg.PrivateKey) == 0 { - return nil, fmt.Errorf("found certificate for TLS authentication but no private key") - } - - certBundle := &certutil.CertBundle{} - if len(cfg.Certificate) > 0 { - certBundle.Certificate = cfg.Certificate - certBundle.PrivateKey = cfg.PrivateKey - } - if len(cfg.IssuingCA) > 0 { - certBundle.IssuingCA = cfg.IssuingCA - } - - parsedCertBundle, err := certBundle.ToParsedCertBundle() - if err != nil { - return nil, errwrap.Wrapf("failed to parse certificate bundle: {{err}}", err) - } - - tlsConfig, err = parsedCertBundle.GetTLSConfig(certutil.TLSClient) - if err != nil || tlsConfig == nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to get TLS configuration: tlsConfig: %#v; {{err}}", tlsConfig), err) - } - tlsConfig.InsecureSkipVerify = cfg.InsecureTLS - - if cfg.TLSMinVersion != "" { - var ok bool - tlsConfig.MinVersion, ok = tlsutil.TLSLookup[cfg.TLSMinVersion] - if !ok { - return nil, fmt.Errorf("invalid 'tls_min_version' in config") - } - } else { - // MinVersion was not being set earlier. Reset it to - // zero to gracefully handle upgrades. - tlsConfig.MinVersion = 0 - } - } - - clusterConfig.SslOpts = &gocql.SslOptions{ - Config: tlsConfig, - } - } - - session, err := clusterConfig.CreateSession() - if err != nil { - return nil, errwrap.Wrapf("error creating session: {{err}}", err) - } - - // Verify the info - err = session.Query(`LIST USERS`).Exec() - if err != nil { - return nil, errwrap.Wrapf("error validating connection info: {{err}}", err) - } - - return session, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/backend.go deleted file mode 100644 index 55b77bbd0..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/backend.go +++ /dev/null @@ -1,45 +0,0 @@ -package consul - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/access", - }, - }, - - Paths: []*framework.Path{ - pathConfigAccess(), - pathListRoles(&b), - pathRoles(), - pathToken(&b), - }, - - Secrets: []*framework.Secret{ - secretToken(&b), - }, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/client.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/client.go deleted file mode 100644 index 228529deb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/client.go +++ /dev/null @@ -1,30 +0,0 @@ -package consul - -import ( - "context" - "fmt" - - "github.com/hashicorp/consul/api" - "github.com/hashicorp/vault/logical" -) - -func client(ctx context.Context, s logical.Storage) (*api.Client, error, error) { - conf, userErr, intErr := readConfigAccess(ctx, s) - if intErr != nil { - return nil, nil, intErr - } - if userErr != nil { - return nil, userErr, nil - } - if conf == nil { - return nil, nil, fmt.Errorf("no error received but no configuration found") - } - - consulConf := api.DefaultNonPooledConfig() - consulConf.Address = conf.Address - consulConf.Scheme = conf.Scheme - consulConf.Token = conf.Token - - client, err := api.NewClient(consulConf) - return client, nil, err -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_config.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_config.go deleted file mode 100644 index 61087ff5b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_config.go +++ /dev/null @@ -1,102 +0,0 @@ -package consul - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigAccess() *framework.Path { - return &framework.Path{ - Pattern: "config/access", - Fields: map[string]*framework.FieldSchema{ - "address": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Consul server address", - }, - - "scheme": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "URI scheme for the Consul address", - - // https would be a better default but Consul on its own - // defaults to HTTP access, and when HTTPS is enabled it - // disables HTTP, so there isn't really any harm done here. - Default: "http", - }, - - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for API calls", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: pathConfigAccessRead, - logical.UpdateOperation: pathConfigAccessWrite, - }, - } -} - -func readConfigAccess(ctx context.Context, storage logical.Storage) (*accessConfig, error, error) { - entry, err := storage.Get(ctx, "config/access") - if err != nil { - return nil, nil, err - } - if entry == nil { - return nil, fmt.Errorf("access credentials for the backend itself haven't been configured; please configure them at the '/config/access' endpoint"), nil - } - - conf := &accessConfig{} - if err := entry.DecodeJSON(conf); err != nil { - return nil, nil, errwrap.Wrapf("error reading consul access configuration: {{err}}", err) - } - - return conf, nil, nil -} - -func pathConfigAccessRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - conf, userErr, intErr := readConfigAccess(ctx, req.Storage) - if intErr != nil { - return nil, intErr - } - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), nil - } - if conf == nil { - return nil, fmt.Errorf("no user error reported but consul access configuration not found") - } - - return &logical.Response{ - Data: map[string]interface{}{ - "address": conf.Address, - "scheme": conf.Scheme, - }, - }, nil -} - -func pathConfigAccessWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := logical.StorageEntryJSON("config/access", accessConfig{ - Address: data.Get("address").(string), - Scheme: data.Get("scheme").(string), - Token: data.Get("token").(string), - }) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type accessConfig struct { - Address string `json:"address"` - Scheme string `json:"scheme"` - Token string `json:"token"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_roles.go deleted file mode 100644 index db9c2fe9d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_roles.go +++ /dev/null @@ -1,164 +0,0 @@ -package consul - -import ( - "context" - "encoding/base64" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - } -} - -func pathRoles() *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Policy document, base64 encoded. Required -for 'client' tokens.`, - }, - - "token_type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "client", - Description: `Which type of token to create: 'client' -or 'management'. If a 'management' token, -the "policy" parameter is not required. -Defaults to 'client'.`, - }, - - "lease": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "Lease time of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: pathRolesRead, - logical.UpdateOperation: pathRolesWrite, - logical.DeleteOperation: pathRolesDelete, - }, - } -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "policy/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func pathRolesRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - entry, err := req.Storage.Get(ctx, "policy/"+name) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - if result.TokenType == "" { - result.TokenType = "client" - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "lease": int64(result.Lease.Seconds()), - "token_type": result.TokenType, - }, - } - if result.Policy != "" { - resp.Data["policy"] = base64.StdEncoding.EncodeToString([]byte(result.Policy)) - } - return resp, nil -} - -func pathRolesWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - tokenType := d.Get("token_type").(string) - - switch tokenType { - case "client": - case "management": - default: - return logical.ErrorResponse( - "token_type must be \"client\" or \"management\""), nil - } - - name := d.Get("name").(string) - policy := d.Get("policy").(string) - var policyRaw []byte - var err error - if tokenType != "management" { - if policy == "" { - return logical.ErrorResponse( - "policy cannot be empty when not using management tokens"), nil - } - policyRaw, err = base64.StdEncoding.DecodeString(d.Get("policy").(string)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error decoding policy base64: %s", err)), nil - } - } - - var lease time.Duration - leaseParamRaw, ok := d.GetOk("lease") - if ok { - lease = time.Second * time.Duration(leaseParamRaw.(int)) - } - - entry, err := logical.StorageEntryJSON("policy/"+name, roleConfig{ - Policy: string(policyRaw), - Lease: lease, - TokenType: tokenType, - }) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func pathRolesDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if err := req.Storage.Delete(ctx, "policy/"+name); err != nil { - return nil, err - } - return nil, nil -} - -type roleConfig struct { - Policy string `json:"policy"` - Lease time.Duration `json:"lease"` - TokenType string `json:"token_type"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_token.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_token.go deleted file mode 100644 index d79651e80..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/path_token.go +++ /dev/null @@ -1,85 +0,0 @@ -package consul - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/consul/api" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathToken(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("role"), - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathTokenRead, - }, - } -} - -func (b *backend) pathTokenRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - role := d.Get("role").(string) - - entry, err := req.Storage.Get(ctx, "policy/"+role) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if entry == nil { - return logical.ErrorResponse(fmt.Sprintf("role %q not found", role)), nil - } - - var result roleConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - if result.TokenType == "" { - result.TokenType = "client" - } - - // Get the consul client - c, userErr, intErr := client(ctx, req.Storage) - if intErr != nil { - return nil, intErr - } - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), nil - } - - // Generate a name for the token - tokenName := fmt.Sprintf("Vault %s %s %d", role, req.DisplayName, time.Now().UnixNano()) - - writeOpts := &api.WriteOptions{} - writeOpts = writeOpts.WithContext(ctx) - - // Create it - token, _, err := c.ACL().Create(&api.ACLEntry{ - Name: tokenName, - Type: result.TokenType, - Rules: result.Policy, - }, writeOpts) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - // Use the helper to create the secret - s := b.Secret(SecretTokenType).Response(map[string]interface{}{ - "token": token, - }, map[string]interface{}{ - "token": token, - "role": role, - }) - s.Secret.TTL = result.Lease - - return s, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/consul/secret_token.go b/vendor/github.com/hashicorp/vault/builtin/logical/consul/secret_token.go deleted file mode 100644 index 45bf7ff4d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/consul/secret_token.go +++ /dev/null @@ -1,84 +0,0 @@ -package consul - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - SecretTokenType = "token" -) - -func secretToken(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretTokenType, - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Request token", - }, - }, - - Renew: b.secretTokenRenew, - Revoke: secretTokenRevoke, - } -} - -func (b *backend) secretTokenRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - resp := &logical.Response{Secret: req.Secret} - roleRaw, ok := req.Secret.InternalData["role"] - if !ok || roleRaw == nil { - return resp, nil - } - - role, ok := roleRaw.(string) - if !ok { - return resp, nil - } - - entry, err := req.Storage.Get(ctx, "policy/"+role) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if entry == nil { - return logical.ErrorResponse(fmt.Sprintf("issuing role %q not found", role)), nil - } - - var result roleConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - resp.Secret.TTL = result.Lease - return resp, nil -} - -func secretTokenRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - c, userErr, intErr := client(ctx, req.Storage) - if intErr != nil { - return nil, intErr - } - if userErr != nil { - // Returning logical.ErrorResponse from revocation function is risky - return nil, userErr - } - - tokenRaw, ok := req.Secret.InternalData["token"] - if !ok { - // We return nil here because this is a pre-0.5.3 problem and there is - // nothing we can do about it. We already can't revoke the lease - // properly if it has been renewed and this is documented pre-0.5.3 - // behavior with a security bulletin about it. - return nil, nil - } - - _, err := c.ACL().Destroy(tokenRaw.(string), nil) - if err != nil { - return nil, err - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/backend.go deleted file mode 100644 index 9c4ef39e9..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/backend.go +++ /dev/null @@ -1,285 +0,0 @@ -package database - -import ( - "context" - "fmt" - "net/rpc" - "strings" - "sync" - - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/hashicorp/vault/plugins/helper/database/dbutil" -) - -const databaseConfigPath = "database/config/" - -type dbPluginInstance struct { - sync.RWMutex - dbplugin.Database - - id string - name string - closed bool -} - -func (dbi *dbPluginInstance) Close() error { - dbi.Lock() - defer dbi.Unlock() - - if dbi.closed { - return nil - } - dbi.closed = true - - return dbi.Database.Close() -} - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend(conf) - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) *databaseBackend { - var b databaseBackend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/*", - }, - }, - - Paths: []*framework.Path{ - pathListPluginConnection(&b), - pathConfigurePluginConnection(&b), - pathListRoles(&b), - pathRoles(&b), - pathCredsCreate(&b), - pathResetConnection(&b), - pathRotateCredentials(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - Clean: b.closeAllDBs, - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - - b.logger = conf.Logger - b.connections = make(map[string]*dbPluginInstance) - return &b -} - -type databaseBackend struct { - connections map[string]*dbPluginInstance - logger log.Logger - - *framework.Backend - sync.RWMutex -} - -func (b *databaseBackend) DatabaseConfig(ctx context.Context, s logical.Storage, name string) (*DatabaseConfig, error) { - entry, err := s.Get(ctx, fmt.Sprintf("config/%s", name)) - if err != nil { - return nil, errwrap.Wrapf("failed to read connection configuration: {{err}}", err) - } - if entry == nil { - return nil, fmt.Errorf("failed to find entry for connection with name: %q", name) - } - - var config DatabaseConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, err - } - - return &config, nil -} - -type upgradeStatements struct { - // This json tag has a typo in it, the new version does not. This - // necessitates this upgrade logic. - CreationStatements string `json:"creation_statments"` - RevocationStatements string `json:"revocation_statements"` - RollbackStatements string `json:"rollback_statements"` - RenewStatements string `json:"renew_statements"` -} - -type upgradeCheck struct { - // This json tag has a typo in it, the new version does not. This - // necessitates this upgrade logic. - Statements *upgradeStatements `json:"statments,omitempty"` -} - -func (b *databaseBackend) Role(ctx context.Context, s logical.Storage, roleName string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+roleName) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var upgradeCh upgradeCheck - if err := entry.DecodeJSON(&upgradeCh); err != nil { - return nil, err - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - switch { - case upgradeCh.Statements != nil: - var stmts dbplugin.Statements - if upgradeCh.Statements.CreationStatements != "" { - stmts.Creation = []string{upgradeCh.Statements.CreationStatements} - } - if upgradeCh.Statements.RevocationStatements != "" { - stmts.Revocation = []string{upgradeCh.Statements.RevocationStatements} - } - if upgradeCh.Statements.RollbackStatements != "" { - stmts.Rollback = []string{upgradeCh.Statements.RollbackStatements} - } - if upgradeCh.Statements.RenewStatements != "" { - stmts.Renewal = []string{upgradeCh.Statements.RenewStatements} - } - result.Statements = stmts - } - - // For backwards compatibility, copy the values back into the string form - // of the fields - result.Statements = dbutil.StatementCompatibilityHelper(result.Statements) - - return &result, nil -} - -func (b *databaseBackend) invalidate(ctx context.Context, key string) { - switch { - case strings.HasPrefix(key, databaseConfigPath): - name := strings.TrimPrefix(key, databaseConfigPath) - b.ClearConnection(name) - } -} - -func (b *databaseBackend) GetConnection(ctx context.Context, s logical.Storage, name string) (*dbPluginInstance, error) { - b.RLock() - unlockFunc := b.RUnlock - defer func() { unlockFunc() }() - - db, ok := b.connections[name] - if ok { - return db, nil - } - - // Upgrade lock - b.RUnlock() - b.Lock() - unlockFunc = b.Unlock - - db, ok = b.connections[name] - if ok { - return db, nil - } - - config, err := b.DatabaseConfig(ctx, s, name) - if err != nil { - return nil, err - } - - dbp, err := dbplugin.PluginFactory(ctx, config.PluginName, b.System(), b.logger) - if err != nil { - return nil, err - } - - _, err = dbp.Init(ctx, config.ConnectionDetails, true) - if err != nil { - dbp.Close() - return nil, err - } - - id, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - db = &dbPluginInstance{ - Database: dbp, - name: name, - id: id, - } - - b.connections[name] = db - return db, nil -} - -// ClearConnection closes the database connection and -// removes it from the b.connections map. -func (b *databaseBackend) ClearConnection(name string) error { - b.Lock() - defer b.Unlock() - return b.clearConnection(name) -} - -func (b *databaseBackend) clearConnection(name string) error { - db, ok := b.connections[name] - if ok { - // Ignore error here since the database client is always killed - db.Close() - delete(b.connections, name) - } - return nil -} - -func (b *databaseBackend) CloseIfShutdown(db *dbPluginInstance, err error) { - // Plugin has shutdown, close it so next call can reconnect. - switch err { - case rpc.ErrShutdown, dbplugin.ErrPluginShutdown: - // Put this in a goroutine so that requests can run with the read or write lock - // and simply defer the unlock. Since we are attaching the instance and matching - // the id in the connection map, we can safely do this. - go func() { - b.Lock() - defer b.Unlock() - db.Close() - - // Ensure we are deleting the correct connection - mapDB, ok := b.connections[db.name] - if ok && db.id == mapDB.id { - delete(b.connections, db.name) - } - }() - } -} - -// closeAllDBs closes all connections from all database types -func (b *databaseBackend) closeAllDBs(ctx context.Context) { - b.Lock() - defer b.Unlock() - - for _, db := range b.connections { - db.Close() - } - b.connections = make(map[string]*dbPluginInstance) -} - -const backendHelp = ` -The database backend supports using many different databases -as secret backends, including but not limited to: -cassandra, mssql, mysql, postgres - -After mounting this backend, configure it using the endpoints within -the "database/config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/path_config_connection.go deleted file mode 100644 index bf3b378a5..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_config_connection.go +++ /dev/null @@ -1,381 +0,0 @@ -package database - -import ( - "context" - "errors" - "fmt" - "net/url" - "strings" - - "github.com/fatih/structs" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -var ( - respErrEmptyPluginName = "empty plugin name" - respErrEmptyName = "empty name attribute given" -) - -// DatabaseConfig is used by the Factory function to configure a Database -// object. -type DatabaseConfig struct { - PluginName string `json:"plugin_name" structs:"plugin_name" mapstructure:"plugin_name"` - // ConnectionDetails stores the database specific connection settings needed - // by each database type. - ConnectionDetails map[string]interface{} `json:"connection_details" structs:"connection_details" mapstructure:"connection_details"` - AllowedRoles []string `json:"allowed_roles" structs:"allowed_roles" mapstructure:"allowed_roles"` - - RootCredentialsRotateStatements []string `json:"root_credentials_rotate_statements" structs:"root_credentials_rotate_statements" mapstructure:"root_credentials_rotate_statements"` -} - -// pathResetConnection configures a path to reset a plugin. -func pathResetConnection(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("reset/%s", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of this database connection", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConnectionReset(), - }, - - HelpSynopsis: pathResetConnectionHelpSyn, - HelpDescription: pathResetConnectionHelpDesc, - } -} - -// pathConnectionReset resets a plugin by closing the existing instance and -// creating a new one. -func (b *databaseBackend) pathConnectionReset() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(respErrEmptyName), nil - } - - // Close plugin and delete the entry in the connections cache. - if err := b.ClearConnection(name); err != nil { - return nil, err - } - - // Execute plugin again, we don't need the object so throw away. - if _, err := b.GetConnection(ctx, req.Storage, name); err != nil { - return nil, err - } - - return nil, nil - } -} - -// pathConfigurePluginConnection returns a configured framework.Path setup to -// operate on plugins. -func pathConfigurePluginConnection(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("config/%s", framework.GenericNameRegex("name")), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of this database connection", - }, - - "plugin_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The name of a builtin or previously registered - plugin known to vault. This endpoint will create an instance of - that plugin type.`, - }, - - "verify_connection": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If true, the connection details are verified by - actually connecting to the database. Defaults to true.`, - }, - - "allowed_roles": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or array of the role names - allowed to get creds from this database connection. If empty no - roles are allowed. If "*" all roles are allowed.`, - }, - - "root_rotation_statements": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: `Specifies the database statements to be executed - to rotate the root user's credentials. See the plugin's API - page for more information on support and formatting for this - parameter.`, - }, - }, - - ExistenceCheck: b.connectionExistenceCheck(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.connectionWriteHandler(), - logical.UpdateOperation: b.connectionWriteHandler(), - logical.ReadOperation: b.connectionReadHandler(), - logical.DeleteOperation: b.connectionDeleteHandler(), - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -func (b *databaseBackend) connectionExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - name := data.Get("name").(string) - if name == "" { - return false, errors.New(`missing "name" parameter`) - } - - entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", name)) - if err != nil { - return false, errors.New("failed to read connection configuration") - } - - return entry != nil, nil - } -} - -func pathListPluginConnection(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: fmt.Sprintf("config/?$"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.connectionListHandler(), - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -func (b *databaseBackend) connectionListHandler() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "config/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil - } -} - -// connectionReadHandler reads out the connection configuration -func (b *databaseBackend) connectionReadHandler() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(respErrEmptyName), nil - } - - entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", name)) - if err != nil { - return nil, errors.New("failed to read connection configuration") - } - if entry == nil { - return nil, nil - } - - var config DatabaseConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, err - } - - // Mask the password if it is in the url - if connURLRaw, ok := config.ConnectionDetails["connection_url"]; ok { - connURL := connURLRaw.(string) - if conn, err := url.Parse(connURL); err == nil { - if password, ok := conn.User.Password(); ok { - config.ConnectionDetails["connection_url"] = strings.Replace(connURL, password, "*****", -1) - } - } - } - - delete(config.ConnectionDetails, "password") - - return &logical.Response{ - Data: structs.New(config).Map(), - }, nil - } -} - -// connectionDeleteHandler deletes the connection configuration -func (b *databaseBackend) connectionDeleteHandler() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(respErrEmptyName), nil - } - - err := req.Storage.Delete(ctx, fmt.Sprintf("config/%s", name)) - if err != nil { - return nil, errors.New("failed to delete connection configuration") - } - - if err := b.ClearConnection(name); err != nil { - return nil, err - } - - return nil, nil - } -} - -// connectionWriteHandler returns a handler function for creating and updating -// both builtin and plugin database types. -func (b *databaseBackend) connectionWriteHandler() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - verifyConnection := data.Get("verify_connection").(bool) - - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(respErrEmptyName), nil - } - - // Baseline - config := &DatabaseConfig{} - - entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", name)) - if err != nil { - return nil, errors.New("failed to read connection configuration") - } - if entry != nil { - if err := entry.DecodeJSON(config); err != nil { - return nil, err - } - } - - if pluginNameRaw, ok := data.GetOk("plugin_name"); ok { - config.PluginName = pluginNameRaw.(string) - } else if req.Operation == logical.CreateOperation { - config.PluginName = data.Get("plugin_name").(string) - } - if config.PluginName == "" { - return logical.ErrorResponse(respErrEmptyPluginName), nil - } - - if allowedRolesRaw, ok := data.GetOk("allowed_roles"); ok { - config.AllowedRoles = allowedRolesRaw.([]string) - } else if req.Operation == logical.CreateOperation { - config.AllowedRoles = data.Get("allowed_roles").([]string) - } - - if rootRotationStatementsRaw, ok := data.GetOk("root_rotation_statements"); ok { - config.RootCredentialsRotateStatements = rootRotationStatementsRaw.([]string) - } else if req.Operation == logical.CreateOperation { - config.RootCredentialsRotateStatements = data.Get("root_rotation_statements").([]string) - } - - // Remove these entries from the data before we store it keyed under - // ConnectionDetails. - delete(data.Raw, "name") - delete(data.Raw, "plugin_name") - delete(data.Raw, "allowed_roles") - delete(data.Raw, "verify_connection") - delete(data.Raw, "root_rotation_statements") - - // Create a database plugin and initialize it. - db, err := dbplugin.PluginFactory(ctx, config.PluginName, b.System(), b.logger) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error creating database object: %s", err)), nil - } - - // If this is an update, take any new values, overwrite what was there - // before, and pass that in as the "new" set of values to the plugin, - // then save what results - if req.Operation == logical.CreateOperation { - config.ConnectionDetails = data.Raw - } else { - if config.ConnectionDetails == nil { - config.ConnectionDetails = make(map[string]interface{}) - } - for k, v := range data.Raw { - config.ConnectionDetails[k] = v - } - } - - config.ConnectionDetails, err = db.Init(ctx, config.ConnectionDetails, verifyConnection) - if err != nil { - db.Close() - return logical.ErrorResponse(fmt.Sprintf("error creating database object: %s", err)), nil - } - - b.Lock() - defer b.Unlock() - - // Close and remove the old connection - b.clearConnection(name) - - id, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - b.connections[name] = &dbPluginInstance{ - Database: db, - name: name, - id: id, - } - - // Store it - entry, err = logical.StorageEntryJSON(fmt.Sprintf("config/%s", name), config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - resp := &logical.Response{} - - // This is a simple test to to check for passwords in the connection_url paramater. If one exists, - // warn the user to use templated url string - if connURLRaw, ok := config.ConnectionDetails["connection_url"]; ok { - if connURL, err := url.Parse(connURLRaw.(string)); err == nil { - if _, ok := connURL.User.Password(); ok { - resp.AddWarning("Password found in connection_url, use a templated url to enable root rotation and prevent read access to password information.") - } - } - } - - return resp, nil - } -} - -const pathConfigConnectionHelpSyn = ` -Configure connection details to a database plugin. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection details used to connect to a particular -database. This path runs the provided plugin name and passes the configured -connection details to the plugin. See the documentation for the plugin specified -for a full list of accepted connection details. - -In addition to the database specific connection details, this endpoint also -accepts: - - * "plugin_name" (required) - The name of a builtin or previously registered - plugin known to vault. This endpoint will create an instance of that - plugin type. - - * "verify_connection" (default: true) - A boolean value denoting if the plugin should verify - it is able to connect to the database using the provided connection - details. -` - -const pathResetConnectionHelpSyn = ` -Resets a database plugin. -` - -const pathResetConnectionHelpDesc = ` -This path resets the database connection by closing the existing database plugin -instance and running a new one. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/path_creds_create.go deleted file mode 100644 index e002c6b7f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_creds_create.go +++ /dev/null @@ -1,110 +0,0 @@ -package database - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathCredsCreate(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsCreateRead(), - }, - - HelpSynopsis: pathCredsCreateReadHelpSyn, - HelpDescription: pathCredsCreateReadHelpDesc, - } -} - -func (b *databaseBackend) pathCredsCreateRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - dbConfig, err := b.DatabaseConfig(ctx, req.Storage, role.DBName) - if err != nil { - return nil, err - } - - // If role name isn't in the database's allowed roles, send back a - // permission denied. - if !strutil.StrListContains(dbConfig.AllowedRoles, "*") && !strutil.StrListContainsGlob(dbConfig.AllowedRoles, name) { - return nil, logical.ErrPermissionDenied - } - - // Get the Database object - db, err := b.GetConnection(ctx, req.Storage, role.DBName) - if err != nil { - return nil, err - } - - db.RLock() - defer db.RUnlock() - - ttl, _, err := framework.CalculateTTL(b.System(), 0, role.DefaultTTL, 0, role.MaxTTL, 0, time.Time{}) - if err != nil { - return nil, err - } - expiration := time.Now().Add(ttl) - // Adding a small buffer since the TTL will be calculated again after this call - // to ensure the database credential does not expire before the lease - expiration = expiration.Add(5 * time.Second) - - usernameConfig := dbplugin.UsernameConfig{ - DisplayName: req.DisplayName, - RoleName: name, - } - - // Create the user - username, password, err := db.CreateUser(ctx, role.Statements, usernameConfig, expiration) - if err != nil { - b.CloseIfShutdown(db, err) - return nil, err - } - - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - "role": name, - "db_name": role.DBName, - "revocation_statements": role.Statements.Revocation, - }) - resp.Secret.TTL = role.DefaultTTL - resp.Secret.MaxTTL = role.MaxTTL - return resp, nil - } -} - -const pathCredsCreateReadHelpSyn = ` -Request database credentials for a certain role. -` - -const pathCredsCreateReadHelpDesc = ` -This path reads database credentials for a certain role. The -database credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/path_roles.go deleted file mode 100644 index ef1475ceb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_roles.go +++ /dev/null @@ -1,284 +0,0 @@ -package database - -import ( - "context" - "time" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList(), - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - - "db_name": { - Type: framework.TypeString, - Description: "Name of the database this role acts on.", - }, - "creation_statements": { - Type: framework.TypeStringSlice, - Description: `Specifies the database statements executed to - create and configure a user. See the plugin's API page for more - information on support and formatting for this parameter.`, - }, - "revocation_statements": { - Type: framework.TypeStringSlice, - Description: `Specifies the database statements to be executed - to revoke a user. See the plugin's API page for more information - on support and formatting for this parameter.`, - }, - "renew_statements": { - Type: framework.TypeStringSlice, - Description: `Specifies the database statements to be executed - to renew a user. Not every plugin type will support this - functionality. See the plugin's API page for more information on - support and formatting for this parameter. `, - }, - "rollback_statements": { - Type: framework.TypeStringSlice, - Description: `Specifies the database statements to be executed - rollback a create operation in the event of an error. Not every - plugin type will support this functionality. See the plugin's - API page for more information on support and formatting for this - parameter.`, - }, - - "default_ttl": { - Type: framework.TypeDurationSecond, - Description: "Default ttl for role.", - }, - - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: "Maximum time a credential is valid for", - }, - }, - - ExistenceCheck: b.pathRoleExistenceCheck(), - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead(), - logical.CreateOperation: b.pathRoleCreateUpdate(), - logical.UpdateOperation: b.pathRoleCreateUpdate(), - logical.DeleteOperation: b.pathRoleDelete(), - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *databaseBackend) pathRoleExistenceCheck() framework.ExistenceFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return false, err - } - - return role != nil, nil - } -} - -func (b *databaseBackend) pathRoleDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil - } -} - -func (b *databaseBackend) pathRoleRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "db_name": role.DBName, - "creation_statements": role.Statements.Creation, - "revocation_statements": role.Statements.Revocation, - "rollback_statements": role.Statements.Rollback, - "renew_statements": role.Statements.Renewal, - "default_ttl": role.DefaultTTL.Seconds(), - "max_ttl": role.MaxTTL.Seconds(), - }, - }, nil - } -} - -func (b *databaseBackend) pathRoleList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil - } -} - -func (b *databaseBackend) pathRoleCreateUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse("empty role name attribute given"), nil - } - - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - role = &roleEntry{} - } - - // DB Attributes - { - if dbNameRaw, ok := data.GetOk("db_name"); ok { - role.DBName = dbNameRaw.(string) - } else if req.Operation == logical.CreateOperation { - role.DBName = data.Get("db_name").(string) - } - if role.DBName == "" { - return logical.ErrorResponse("empty database name attribute"), nil - } - } - - // TTLs - { - if defaultTTLRaw, ok := data.GetOk("default_ttl"); ok { - role.DefaultTTL = time.Duration(defaultTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.DefaultTTL = time.Duration(data.Get("default_ttl").(int)) * time.Second - } - if maxTTLRaw, ok := data.GetOk("max_ttl"); ok { - role.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second - } else if req.Operation == logical.CreateOperation { - role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second - } - } - - // Statements - { - if creationStmtsRaw, ok := data.GetOk("creation_statements"); ok { - role.Statements.Creation = creationStmtsRaw.([]string) - } else if req.Operation == logical.CreateOperation { - role.Statements.Creation = data.Get("creation_statements").([]string) - } - - if revocationStmtsRaw, ok := data.GetOk("revocation_statements"); ok { - role.Statements.Revocation = revocationStmtsRaw.([]string) - } else if req.Operation == logical.CreateOperation { - role.Statements.Revocation = data.Get("revocation_statements").([]string) - } - - if rollbackStmtsRaw, ok := data.GetOk("rollback_statements"); ok { - role.Statements.Rollback = rollbackStmtsRaw.([]string) - } else if req.Operation == logical.CreateOperation { - role.Statements.Rollback = data.Get("rollback_statements").([]string) - } - - if renewStmtsRaw, ok := data.GetOk("renew_statements"); ok { - role.Statements.Renewal = renewStmtsRaw.([]string) - } else if req.Operation == logical.CreateOperation { - role.Statements.Renewal = data.Get("renew_statements").([]string) - } - - // Do not persist deprecated statements that are populated on role read - role.Statements.CreationStatements = "" - role.Statements.RevocationStatements = "" - role.Statements.RenewStatements = "" - role.Statements.RollbackStatements = "" - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, role) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil - } -} - -type roleEntry struct { - DBName string `json:"db_name"` - Statements dbplugin.Statements `json:"statements"` - DefaultTTL time.Duration `json:"default_ttl"` - MaxTTL time.Duration `json:"max_ttl"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "db_name" parameter is required and configures the name of the database -connection to use. - -The "creation_statements" parameter customizes the string used to create the -credentials. This can be a sequence of SQL queries, or other statement formats -for a particular database type. Some substitution will be done to the statement -strings for certain keys. The names of the variables must be surrounded by "{{" -and "}}" to be replaced. - - * "name" - The random username generated for the DB user. - - * "password" - The random password generated for the DB user. - - * "expiration" - The timestamp when this user will expire. - -Example of a decent creation_statements for a postgresql database plugin: - - CREATE ROLE "{{name}}" WITH - LOGIN - PASSWORD '{{password}}' - VALID UNTIL '{{expiration}}'; - GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}"; - -The "revocation_statements" parameter customizes the statement string used to -revoke a user. Example of a decent revocation_statements for a postgresql -database plugin: - - REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM {{name}}; - REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM {{name}}; - REVOKE USAGE ON SCHEMA public FROM {{name}}; - DROP ROLE IF EXISTS {{name}}; - -The "renew_statements" parameter customizes the statement string used to renew a -user. -The "rollback_statements' parameter customizes the statement string used to -rollback a change if needed. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_rotate_credentials.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/path_rotate_credentials.go deleted file mode 100644 index 1028bc397..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/path_rotate_credentials.go +++ /dev/null @@ -1,87 +0,0 @@ -package database - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathRotateCredentials(b *databaseBackend) *framework.Path { - return &framework.Path{ - Pattern: "rotate-root/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of this database connection", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRotateCredentialsUpdate(), - }, - - HelpSynopsis: pathCredsCreateReadHelpSyn, - HelpDescription: pathCredsCreateReadHelpDesc, - } -} - -func (b *databaseBackend) pathRotateCredentialsUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse(respErrEmptyName), nil - } - - config, err := b.DatabaseConfig(ctx, req.Storage, name) - if err != nil { - return nil, err - } - - db, err := b.GetConnection(ctx, req.Storage, name) - if err != nil { - return nil, err - } - - // Take out the backend lock since we are swapping out the connection - b.Lock() - defer b.Unlock() - - // Take the write lock on the instance - db.Lock() - defer db.Unlock() - - connectionDetails, err := db.RotateRootCredentials(ctx, config.RootCredentialsRotateStatements) - if err != nil { - return nil, err - } - - config.ConnectionDetails = connectionDetails - entry, err := logical.StorageEntryJSON(fmt.Sprintf("config/%s", name), config) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Close the plugin - db.closed = true - if err := db.Database.Close(); err != nil { - b.Logger().Error("error closing the database plugin connection", "err", err) - } - // Even on error, still remove the connection - delete(b.connections, name) - - return nil, nil - } -} - -const pathRotateCredentialsUpdateHelpSyn = ` -Request to rotate the root credentials for a certain database connection. -` - -const pathRotateCredentialsUpdateHelpDesc = ` -This path attempts to rotate the root credentials for the given database. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/database/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/database/secret_creds.go deleted file mode 100644 index 04df2663b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/database/secret_creds.go +++ /dev/null @@ -1,145 +0,0 @@ -package database - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/builtin/logical/database/dbplugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const SecretCredsType = "creds" - -func secretCreds(b *databaseBackend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{}, - - Renew: b.secretCredsRenew(), - Revoke: b.secretCredsRevoke(), - } -} - -func (b *databaseBackend) secretCredsRenew() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - - roleNameRaw, ok := req.Secret.InternalData["role"] - if !ok { - return nil, fmt.Errorf("could not find role with name: %q", req.Secret.InternalData["role"]) - } - - role, err := b.Role(ctx, req.Storage, roleNameRaw.(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, fmt.Errorf("error during renew: could not find role with name %q", req.Secret.InternalData["role"]) - } - - // Get the Database object - db, err := b.GetConnection(ctx, req.Storage, role.DBName) - if err != nil { - return nil, err - } - - db.RLock() - defer db.RUnlock() - - // Make sure we increase the VALID UNTIL endpoint for this user. - ttl, _, err := framework.CalculateTTL(b.System(), req.Secret.Increment, role.DefaultTTL, 0, role.MaxTTL, 0, req.Secret.IssueTime) - if err != nil { - return nil, err - } - if ttl > 0 { - expireTime := time.Now().Add(ttl) - // Adding a small buffer since the TTL will be calculated again after this call - // to ensure the database credential does not expire before the lease - expireTime = expireTime.Add(5 * time.Second) - err := db.RenewUser(ctx, role.Statements, username, expireTime) - if err != nil { - b.CloseIfShutdown(db, err) - return nil, err - } - } - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = role.DefaultTTL - resp.Secret.MaxTTL = role.MaxTTL - return resp, nil - } -} - -func (b *databaseBackend) secretCredsRevoke() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - - var resp *logical.Response - - roleNameRaw, ok := req.Secret.InternalData["role"] - if !ok { - return nil, fmt.Errorf("no role name was provided") - } - - var dbName string - var statements dbplugin.Statements - - role, err := b.Role(ctx, req.Storage, roleNameRaw.(string)) - if err != nil { - return nil, err - } - if role != nil { - dbName = role.DBName - statements = role.Statements - } else { - if dbNameRaw, ok := req.Secret.InternalData["db_name"]; !ok { - return nil, fmt.Errorf("error during revoke: could not find role with name %q or embedded revocation db name data", req.Secret.InternalData["role"]) - } else { - dbName = dbNameRaw.(string) - } - if statementsRaw, ok := req.Secret.InternalData["revocation_statements"]; !ok { - return nil, fmt.Errorf("error during revoke: could not find role with name %q or embedded revocation statement data", req.Secret.InternalData["role"]) - } else { - // If we don't actually have any statements, because none were - // set in the role, we'll end up with an empty one and the - // default for the db type will be attempted - if statementsRaw != nil { - statementsSlice, ok := statementsRaw.([]interface{}) - if !ok { - return nil, fmt.Errorf("error during revoke: could not find role with name %q and embedded reovcation data could not be read", req.Secret.InternalData["role"]) - } else { - for _, v := range statementsSlice { - statements.Revocation = append(statements.Revocation, v.(string)) - } - } - } - } - } - - // Get our connection - db, err := b.GetConnection(ctx, req.Storage, dbName) - if err != nil { - return nil, err - } - - db.RLock() - defer db.RUnlock() - - if err := db.RevokeUser(ctx, statements, username); err != nil { - b.CloseIfShutdown(db, err) - return nil, err - } - return resp, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/backend.go deleted file mode 100644 index db7405282..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/backend.go +++ /dev/null @@ -1,144 +0,0 @@ -package mongodb - -import ( - "context" - "fmt" - "strings" - "sync" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "gopkg.in/mgo.v2" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *framework.Backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathRoles(&b), - pathCredsCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Clean: b.ResetSession, - - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - - return b.Backend -} - -type backend struct { - *framework.Backend - - session *mgo.Session - lock sync.Mutex -} - -// Session returns the database connection. -func (b *backend) Session(ctx context.Context, s logical.Storage) (*mgo.Session, error) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.session != nil { - if err := b.session.Ping(); err == nil { - return b.session, nil - } - b.session.Close() - } - - connConfigJSON, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if connConfigJSON == nil { - return nil, fmt.Errorf("configure the MongoDB connection with config/connection first") - } - - var connConfig connectionConfig - if err := connConfigJSON.DecodeJSON(&connConfig); err != nil { - return nil, err - } - - dialInfo, err := parseMongoURI(connConfig.URI) - if err != nil { - return nil, err - } - - b.session, err = mgo.DialWithInfo(dialInfo) - if err != nil { - return nil, err - } - b.session.SetSyncTimeout(1 * time.Minute) - b.session.SetSocketTimeout(1 * time.Minute) - - return b.session, nil -} - -// ResetSession forces creation of a new connection next time Session() is called. -func (b *backend) ResetSession(_ context.Context) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.session != nil { - b.session.Close() - } - - b.session = nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/connection": - b.ResetSession(ctx) - } -} - -// LeaseConfig returns the lease configuration -func (b *backend) LeaseConfig(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -const backendHelp = ` -The mongodb backend dynamically generates MongoDB credentials. - -After mounting this backend, configure it using the endpoints within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_connection.go deleted file mode 100644 index ea33c432c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_connection.go +++ /dev/null @@ -1,112 +0,0 @@ -package mongodb - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "gopkg.in/mgo.v2" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "uri": { - Type: framework.TypeString, - Description: "MongoDB standard connection string (URI)", - }, - "verify_connection": { - Type: framework.TypeBool, - Default: true, - Description: `If set, uri is verified by actually connecting to the database`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConnectionRead, - logical.UpdateOperation: b.pathConnectionWrite, - }, - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -// pathConnectionRead reads out the connection configuration -func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := req.Storage.Get(ctx, "config/connection") - if err != nil { - return nil, fmt.Errorf("failed to read connection configuration") - } - if entry == nil { - return nil, nil - } - - return nil, nil -} - -func (b *backend) pathConnectionWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - uri := data.Get("uri").(string) - if uri == "" { - return logical.ErrorResponse("uri parameter is required"), nil - } - - dialInfo, err := parseMongoURI(uri) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid uri: %s", err)), nil - } - - // Don't check the config if verification is disabled - verifyConnection := data.Get("verify_connection").(bool) - if verifyConnection { - // Verify the config - session, err := mgo.DialWithInfo(dialInfo) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - defer session.Close() - if err := session.Ping(); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ - URI: uri, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the Session - b.ResetSession(ctx) - - resp := &logical.Response{} - resp.AddWarning("Read access to this endpoint should be controlled via ACLs as it will return the connection URI as it is, including passwords, if any.") - - return resp, nil -} - -type connectionConfig struct { - URI string `json:"uri" structs:"uri" mapstructure:"uri"` -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection string to talk to MongoDB. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the standard connection string (URI) used to connect to MongoDB. - -A MongoDB URI looks like: -"mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]" - -See https://docs.mongodb.org/manual/reference/connection-string/ for detailed documentation of the URI format. - -When configuring the connection string, the backend will verify its validity. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_lease.go deleted file mode 100644 index cb9ff7120..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_config_lease.go +++ /dev/null @@ -1,90 +0,0 @@ -package mongodb - -import ( - "context" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "ttl": { - Type: framework.TypeDurationSecond, - Description: "Default ttl for credentials.", - }, - - "max_ttl": { - Type: framework.TypeDurationSecond, - Description: "Maximum time a set of credentials can be valid for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigLeaseRead, - logical.UpdateOperation: b.pathConfigLeaseWrite, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -func (b *backend) pathConfigLeaseWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - TTL: time.Second * time.Duration(d.Get("ttl").(int)), - MaxTTL: time.Second * time.Duration(d.Get("max_ttl").(int)), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - - if err != nil { - return nil, err - } - if leaseConfig == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "ttl": leaseConfig.TTL.Seconds(), - "max_ttl": leaseConfig.MaxTTL.Seconds(), - }, - }, nil -} - -type configLease struct { - TTL time.Duration - MaxTTL time.Duration -} - -const pathConfigLeaseHelpSyn = ` -Configure the default lease TTL settings for credentials -generated by the mongodb backend. -` - -const pathConfigLeaseHelpDesc = ` -This configures the default lease TTL settings used for -credentials generated by this backend. The ttl specifies the -duration that a set of credentials will be valid for before -the lease must be renewed (if it is renewable), while the -max_ttl specifies the overall maximum duration that the -credentials will be valid regardless of lease renewals. - -The format for the TTL values is an integer and then unit. For -example, the value "1h" specifies a 1-hour TTL. The longest -supported unit is hours. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_creds_create.go deleted file mode 100644 index ea24f4505..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_creds_create.go +++ /dev/null @@ -1,119 +0,0 @@ -package mongodb - -import ( - "context" - "fmt" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathCredsCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role to generate credentials for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsCreateRead, - }, - - HelpSynopsis: pathCredsCreateReadHelpSyn, - HelpDescription: pathCredsCreateReadHelpDesc, - } -} - -func (b *backend) pathCredsCreateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - // Determine if we have a lease configuration - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if leaseConfig == nil { - leaseConfig = &configLease{} - } - - // Generate the username and password - displayName := req.DisplayName - if displayName != "" { - displayName += "-" - } - - userUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - username := fmt.Sprintf("vault-%s%s", displayName, userUUID) - - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - // Build the user creation command - createUserCmd := createUserCommand{ - Username: username, - Password: password, - Roles: role.MongoDBRoles.toStandardRolesArray(), - } - - // Get our connection - session, err := b.Session(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Create the user - err = session.DB(role.DB).Run(createUserCmd, nil) - if err != nil { - return nil, err - } - - // Return the secret - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "db": role.DB, - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - "db": role.DB, - }) - resp.Secret.TTL = leaseConfig.TTL - resp.Secret.MaxTTL = leaseConfig.MaxTTL - - return resp, nil -} - -type createUserCommand struct { - Username string `bson:"createUser"` - Password string `bson:"pwd"` - Roles []interface{} `bson:"roles"` -} - -const pathCredsCreateReadHelpSyn = ` -Request MongoDB database credentials for a particular role. -` - -const pathCredsCreateReadHelpDesc = ` -This path reads generates MongoDB database credentials for -a particular role. The database credentials will be -generated on demand and will be automatically revoked when -the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_roles.go deleted file mode 100644 index 6446e9db3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/path_roles.go +++ /dev/null @@ -1,224 +0,0 @@ -package mongodb - -import ( - "context" - "encoding/json" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - "db": { - Type: framework.TypeString, - Description: "Name of the authentication database for users generated for this role.", - }, - "roles": { - Type: framework.TypeString, - Description: "MongoDB roles to assign to the users generated for this role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) Role(ctx context.Context, s logical.Storage, n string) (*roleStorageEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleStorageEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - rolesJsonBytes, err := json.Marshal(role.MongoDBRoles.toStandardRolesArray()) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "db": role.DB, - "roles": string(rolesJsonBytes), - }, - }, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - if name == "" { - return logical.ErrorResponse("Missing name"), nil - } - - roleDB := data.Get("db").(string) - if roleDB == "" { - return logical.ErrorResponse("db parameter is required"), nil - } - - // Example roles JSON: - // - // [ "readWrite", { "role": "readWrite", "db": "test" } ] - // - // For storage, we convert such an array into a homogeneous array of role documents like: - // - // [ { "role": "readWrite" }, { "role": "readWrite", "db": "test" } ] - // - var roles []mongodbRole - rolesJson := []byte(data.Get("roles").(string)) - if len(rolesJson) > 0 { - var rolesArray []interface{} - err := json.Unmarshal(rolesJson, &rolesArray) - if err != nil { - return nil, err - } - for _, rawRole := range rolesArray { - switch role := rawRole.(type) { - case string: - roles = append(roles, mongodbRole{Role: role}) - case map[string]interface{}: - if db, ok := role["db"].(string); ok { - if roleName, ok := role["role"].(string); ok { - roles = append(roles, mongodbRole{Role: roleName, DB: db}) - } - } - } - } - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, &roleStorageEntry{ - DB: roleDB, - MongoDBRoles: roles, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (roles mongodbRoles) toStandardRolesArray() []interface{} { - // Convert array of role documents like: - // - // [ { "role": "readWrite" }, { "role": "readWrite", "db": "test" } ] - // - // into a "standard" MongoDB roles array containing both strings and role documents: - // - // [ "readWrite", { "role": "readWrite", "db": "test" } ] - // - // MongoDB's createUser command accepts the latter. - // - var standardRolesArray []interface{} - for _, role := range roles { - if role.DB == "" { - standardRolesArray = append(standardRolesArray, role.Role) - } else { - standardRolesArray = append(standardRolesArray, role) - } - } - return standardRolesArray -} - -type roleStorageEntry struct { - DB string `json:"db"` - MongoDBRoles mongodbRoles `json:"roles"` -} - -type mongodbRole struct { - Role string `json:"role" bson:"role"` - DB string `json:"db" bson:"db"` -} - -type mongodbRoles []mongodbRole - -const pathRoleHelpSyn = ` -Manage the roles used to generate MongoDB credentials. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles used to generate MongoDB credentials. - -The "db" parameter specifies the authentication database for users -generated for a given role. - -The "roles" parameter specifies the MongoDB roles that should be assigned -to users created for a given role. Just like when creating a user directly -using db.createUser, the roles JSON array can specify both built-in roles -and user-defined roles for both the database the user is created in and -for other databases. - -For example, the following roles JSON array grants the "readWrite" -permission on both the user's authentication database and the "test" -database: - -[ "readWrite", { "role": "readWrite", "db": "test" } ] - -Please consult the MongoDB documentation for more -details on Role-Based Access Control in MongoDB. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/secret_creds.go deleted file mode 100644 index bde31c681..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/secret_creds.go +++ /dev/null @@ -1,84 +0,0 @@ -package mongodb - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "gopkg.in/mgo.v2" -) - -const SecretCredsType = "creds" - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": { - Type: framework.TypeString, - Description: "Username", - }, - - "password": { - Type: framework.TypeString, - Description: "Password", - }, - }, - - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the lease information - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if leaseConfig == nil { - leaseConfig = &configLease{} - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = leaseConfig.TTL - resp.Secret.MaxTTL = leaseConfig.MaxTTL - return resp, nil -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("username internal data is not a string") - } - - // Get the db from the internal data - dbRaw, ok := req.Secret.InternalData["db"] - if !ok { - return nil, fmt.Errorf("secret is missing db internal data") - } - db, ok := dbRaw.(string) - if !ok { - return nil, fmt.Errorf("db internal data is not a string") - } - - // Get our connection - session, err := b.Session(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Drop the user - err = session.DB(db).RemoveUser(username) - if err != nil && err != mgo.ErrNotFound { - return nil, err - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/util.go deleted file mode 100644 index 209feb0f7..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mongodb/util.go +++ /dev/null @@ -1,81 +0,0 @@ -package mongodb - -import ( - "crypto/tls" - "errors" - "net" - "net/url" - "strconv" - "strings" - "time" - - "gopkg.in/mgo.v2" -) - -// Unfortunately, mgo doesn't support the ssl parameter in its MongoDB URI parsing logic, so we have to handle that -// ourselves. See https://github.com/go-mgo/mgo/issues/84 -func parseMongoURI(rawUri string) (*mgo.DialInfo, error) { - uri, err := url.Parse(rawUri) - if err != nil { - return nil, err - } - - info := mgo.DialInfo{ - Addrs: strings.Split(uri.Host, ","), - Database: strings.TrimPrefix(uri.Path, "/"), - Timeout: 10 * time.Second, - } - - if uri.User != nil { - info.Username = uri.User.Username() - info.Password, _ = uri.User.Password() - } - - query := uri.Query() - for key, values := range query { - var value string - if len(values) > 0 { - value = values[0] - } - - switch key { - case "authSource": - info.Source = value - case "authMechanism": - info.Mechanism = value - case "gssapiServiceName": - info.Service = value - case "replicaSet": - info.ReplicaSetName = value - case "maxPoolSize": - poolLimit, err := strconv.Atoi(value) - if err != nil { - return nil, errors.New("bad value for maxPoolSize: " + value) - } - info.PoolLimit = poolLimit - case "ssl": - ssl, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.New("bad value for ssl: " + value) - } - if ssl { - info.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { - return tls.Dial("tcp", addr.String(), &tls.Config{}) - } - } - case "connect": - if value == "direct" { - info.Direct = true - break - } - if value == "replicaSet" { - break - } - fallthrough - default: - return nil, errors.New("unsupported connection URL option: " + key + "=" + value) - } - } - - return &info, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/backend.go deleted file mode 100644 index e5d3766b8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/backend.go +++ /dev/null @@ -1,160 +0,0 @@ -package mssql - -import ( - "context" - "database/sql" - "fmt" - "strings" - "sync" - - _ "github.com/denisenkom/go-mssqldb" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathRoles(&b), - pathCredsCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Invalidate: b.invalidate, - Clean: b.ResetDB, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend - - db *sql.DB - defaultDb string - lock sync.Mutex -} - -// DB returns the default database connection. -func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) { - b.lock.Lock() - defer b.lock.Unlock() - - // If we already have a DB, we got it! - if b.db != nil { - if err := b.db.Ping(); err == nil { - return b.db, nil - } - // If the ping was unsuccessful, close it and ignore errors as we'll be - // reestablishing anyways - b.db.Close() - } - - // Otherwise, attempt to make connection - entry, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return nil, fmt.Errorf("configure the DB connection with config/connection first") - } - - var connConfig connectionConfig - if err := entry.DecodeJSON(&connConfig); err != nil { - return nil, err - } - connString := connConfig.ConnectionString - - db, err := sql.Open("sqlserver", connString) - if err != nil { - return nil, err - } - - // Set some connection pool settings. We don't need much of this, - // since the request rate shouldn't be high. - db.SetMaxOpenConns(connConfig.MaxOpenConnections) - - stmt, err := db.Prepare("SELECT db_name();") - if err != nil { - return nil, err - } - defer stmt.Close() - - err = stmt.QueryRow().Scan(&b.defaultDb) - if err != nil { - return nil, err - } - - b.db = db - return b.db, nil -} - -// ResetDB forces a connection next time DB() is called. -func (b *backend) ResetDB(_ context.Context) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.db != nil { - b.db.Close() - } - - b.db = nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/connection": - b.ResetDB(ctx) - } -} - -// LeaseConfig returns the lease configuration -func (b *backend) LeaseConfig(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -const backendHelp = ` -The MSSQL backend dynamically generates database users. - -After mounting this backend, configure it using the endpoints within -the "config/" path. - -This backend does not support Azure SQL Databases. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_connection.go deleted file mode 100644 index b4c9a1d17..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_connection.go +++ /dev/null @@ -1,127 +0,0 @@ -package mssql - -import ( - "context" - "database/sql" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "connection_string": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DB connection parameters", - }, - "max_open_connections": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Maximum number of open connections to database", - }, - "verify_connection": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: "If set, connection_string is verified by actually connecting to the database", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConnectionWrite, - logical.ReadOperation: b.pathConnectionRead, - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -// pathConnectionRead reads out the connection configuration -func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := req.Storage.Get(ctx, "config/connection") - if err != nil { - return nil, fmt.Errorf("failed to read connection configuration") - } - if entry == nil { - return nil, nil - } - - var config connectionConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "max_open_connections": config.MaxOpenConnections, - }, - }, nil -} - -// pathConnectionWrite stores the connection configuration -func (b *backend) pathConnectionWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - connString := data.Get("connection_string").(string) - - maxOpenConns := data.Get("max_open_connections").(int) - if maxOpenConns == 0 { - maxOpenConns = 2 - } - - // Don't check the connection_string if verification is disabled - verifyConnection := data.Get("verify_connection").(bool) - if verifyConnection { - // Verify the string - db, err := sql.Open("mssql", connString) - - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - defer db.Close() - if err := db.Ping(); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ - ConnectionString: connString, - MaxOpenConnections: maxOpenConns, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the DB connection - b.ResetDB(ctx) - - resp := &logical.Response{} - resp.AddWarning("Read access to this endpoint should be controlled via ACLs as it will return the connection string as it is, including passwords, if any.") - - return resp, nil -} - -type connectionConfig struct { - ConnectionString string `json:"connection_string" structs:"connection_string" mapstructure:"connection_string"` - MaxOpenConnections int `json:"max_open_connections" structs:"max_open_connections" mapstructure:"max_open_connections"` -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection string to talk to Microsoft Sql Server. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection string used to connect to Sql Server. -The value of the string is a Data Source Name (DSN). An example is -using "server=;port=;user id=;password=;database=;app name=vault;" - -When configuring the connection string, the backend will verify its validity. -If the database is not available when setting the connection string, set the -"verify_connection" option to false. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_lease.go deleted file mode 100644 index b4035b56d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_config_lease.go +++ /dev/null @@ -1,115 +0,0 @@ -package mssql - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Default ttl for roles.", - }, - - "ttl_max": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Deprecated: use "max_ttl" instead. Maximum -time a credential is valid for.`, - }, - - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Maximum time a credential is valid for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigLeaseRead, - logical.UpdateOperation: b.pathConfigLeaseWrite, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -func (b *backend) pathConfigLeaseWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ttlRaw := d.Get("ttl").(string) - ttlMaxRaw := d.Get("max_ttl").(string) - if len(ttlMaxRaw) == 0 { - ttlMaxRaw = d.Get("ttl_max").(string) - } - - ttl, err := time.ParseDuration(ttlRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid ttl: %s", err)), nil - } - ttlMax, err := time.ParseDuration(ttlMaxRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid max_ttl: %s", err)), nil - } - - // Store it - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - TTL: ttl, - TTLMax: ttlMax, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - - if err != nil { - return nil, err - } - if leaseConfig == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "ttl": leaseConfig.TTL.String(), - "ttl_max": leaseConfig.TTLMax.String(), - "max_ttl": leaseConfig.TTLMax.String(), - }, - } - resp.AddWarning("The field ttl_max is deprecated and will be removed in a future release. Use max_ttl instead.") - - return resp, nil -} - -type configLease struct { - TTL time.Duration - TTLMax time.Duration -} - -const pathConfigLeaseHelpSyn = ` -Configure the default lease ttl for generated credentials. -` - -const pathConfigLeaseHelpDesc = ` -This configures the default lease ttl used for credentials -generated by this backend. The ttl specifies the duration that a -credential will be valid for, as well as the maximum session for -a set of credentials. - -The format for the ttl is "1h" or integer and then unit. The longest -unit is hour. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_creds_create.go deleted file mode 100644 index 1a954c87b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_creds_create.go +++ /dev/null @@ -1,129 +0,0 @@ -package mssql - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathCredsCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsCreateRead, - }, - - HelpSynopsis: pathCredsCreateHelpSyn, - HelpDescription: pathCredsCreateHelpDesc, - } -} - -func (b *backend) pathCredsCreateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - // Determine if we have a lease configuration - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if leaseConfig == nil { - leaseConfig = &configLease{} - } - - // Generate our username and password - displayName := req.DisplayName - if len(displayName) > 10 { - displayName = displayName[:10] - } - userUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - username := fmt.Sprintf("%s-%s", displayName, userUUID) - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - // Get our handle - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Start a transaction - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer tx.Rollback() - - // Always reset database to default db of connection. Since it is in a - // transaction, all statements will be on the same connection in the pool. - roleSQL := fmt.Sprintf("USE [%s]; %s", b.defaultDb, role.SQL) - - // Execute each query - for _, query := range strutil.ParseArbitraryStringSlice(roleSQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - "password": password, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return nil, err - } - - // Return the secret - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - }) - resp.Secret.TTL = leaseConfig.TTL - resp.Secret.MaxTTL = leaseConfig.TTLMax - - return resp, nil -} - -const pathCredsCreateHelpSyn = ` -Request database credentials for a certain role. -` - -const pathCredsCreateHelpDesc = ` -This path reads database credentials for a certain role. The -database credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_roles.go deleted file mode 100644 index fd29f36d2..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/path_roles.go +++ /dev/null @@ -1,172 +0,0 @@ -package mssql - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - - "sql": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "SQL string to create a role. See help for more info.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) Role(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "sql": role.SQL, - }, - }, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - sql := data.Get("sql").(string) - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Test the query by trying to prepare it - for _, query := range strutil.ParseArbitraryStringSlice(sql, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - stmt, err := db.Prepare(Query(query, map[string]string{ - "name": "foo", - "password": "bar", - })) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error testing query: %s", err)), nil - } - stmt.Close() - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, &roleEntry{ - SQL: sql, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil -} - -type roleEntry struct { - SQL string `json:"sql"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "sql" parameter customizes the SQL string used to create the login to -the server. The parameter can be a sequence of SQL queries, each semi-colon -separated. Some substitution will be done to the SQL string for certain keys. -The names of the variables must be surrounded by "{{" and "}}" to be replaced. - - * "name" - The random username generated for the DB user. - - * "password" - The random password generated for the DB user. - -Example SQL query to use: - - CREATE LOGIN [{{name}}] WITH PASSWORD = '{{password}}'; - CREATE USER [{{name}}] FROM LOGIN [{{name}}]; - GRANT SELECT, UPDATE, DELETE, INSERT on SCHEMA::dbo TO [{{name}}]; - -Please see the Microsoft SQL Server manual on the GRANT command to learn how to -do more fine grained access. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/secret_creds.go deleted file mode 100644 index 5edac67be..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/secret_creds.go +++ /dev/null @@ -1,181 +0,0 @@ -package mssql - -import ( - "context" - "database/sql" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const SecretCredsType = "creds" - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password", - }, - }, - - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the lease information - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if leaseConfig == nil { - leaseConfig = &configLease{} - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = leaseConfig.TTL - resp.Secret.MaxTTL = leaseConfig.TTLMax - return resp, nil -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // First disable server login - disableStmt, err := db.Prepare(fmt.Sprintf("ALTER LOGIN [%s] DISABLE;", username)) - if err != nil { - return nil, err - } - defer disableStmt.Close() - if _, err := disableStmt.Exec(); err != nil { - return nil, err - } - - // Query for sessions for the login so that we can kill any outstanding - // sessions. There cannot be any active sessions before we drop the logins - // This isn't done in a transaction because even if we fail along the way, - // we want to remove as much access as possible - sessionStmt, err := db.Prepare(fmt.Sprintf( - "SELECT session_id FROM sys.dm_exec_sessions WHERE login_name = '%s';", username)) - if err != nil { - return nil, err - } - defer sessionStmt.Close() - - sessionRows, err := sessionStmt.Query() - if err != nil { - return nil, err - } - defer sessionRows.Close() - - var revokeStmts []string - for sessionRows.Next() { - var sessionID int - err = sessionRows.Scan(&sessionID) - if err != nil { - return nil, err - } - revokeStmts = append(revokeStmts, fmt.Sprintf("KILL %d;", sessionID)) - } - - // Query for database users using undocumented stored procedure for now since - // it is the easiest way to get this information; - // we need to drop the database users before we can drop the login and the role - // This isn't done in a transaction because even if we fail along the way, - // we want to remove as much access as possible - stmt, err := db.Prepare(fmt.Sprintf("EXEC master.dbo.sp_msloginmappings '%s';", username)) - if err != nil { - return nil, err - } - defer stmt.Close() - - rows, err := stmt.Query() - if err != nil { - return nil, err - } - defer rows.Close() - - for rows.Next() { - var loginName, dbName, qUsername string - var aliasName sql.NullString - err = rows.Scan(&loginName, &dbName, &qUsername, &aliasName) - if err != nil { - return nil, err - } - revokeStmts = append(revokeStmts, fmt.Sprintf(dropUserSQL, dbName, username, username)) - } - - // we do not stop on error, as we want to remove as - // many permissions as possible right now - var lastStmtError error - for _, query := range revokeStmts { - - if err := dbtxn.ExecuteDBQuery(ctx, db, nil, query); err != nil { - lastStmtError = err - continue - } - } - - // can't drop if not all database users are dropped - if rows.Err() != nil { - return nil, errwrap.Wrapf("could not generate sql statements for all rows: {{err}}", rows.Err()) - } - if lastStmtError != nil { - return nil, errwrap.Wrapf("could not perform all sql statements: {{err}}", lastStmtError) - } - - // Drop this login - stmt, err = db.Prepare(fmt.Sprintf(dropLoginSQL, username, username)) - if err != nil { - return nil, err - } - defer stmt.Close() - if _, err := stmt.Exec(); err != nil { - return nil, err - } - - return nil, nil -} - -const dropUserSQL = ` -USE [%s] -IF EXISTS - (SELECT name - FROM sys.database_principals - WHERE name = N'%s') -BEGIN - DROP USER [%s] -END -` - -const dropLoginSQL = ` -IF EXISTS - (SELECT name - FROM master.sys.server_principals - WHERE name = N'%s') -BEGIN - DROP LOGIN [%s] -END -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/mssql/util.go deleted file mode 100644 index 362cbd36a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mssql/util.go +++ /dev/null @@ -1,28 +0,0 @@ -package mssql - -import ( - "fmt" - "strings" -) - -// SplitSQL is used to split a series of SQL statements -func SplitSQL(sql string) []string { - parts := strings.Split(sql, ";") - out := make([]string, 0, len(parts)) - for _, p := range parts { - clean := strings.TrimSpace(p) - if len(clean) > 0 { - out = append(out, clean) - } - } - return out -} - -// Query templates a query for us. -func Query(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/backend.go deleted file mode 100644 index 871eca90c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/backend.go +++ /dev/null @@ -1,151 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - "fmt" - "strings" - "sync" - - _ "github.com/go-sql-driver/mysql" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathRoles(&b), - pathRoleCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Invalidate: b.invalidate, - Clean: b.ResetDB, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend - - db *sql.DB - lock sync.Mutex -} - -// DB returns the database connection. -func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) { - b.lock.Lock() - defer b.lock.Unlock() - - // If we already have a DB, we got it! - if b.db != nil { - if err := b.db.Ping(); err == nil { - return b.db, nil - } - // If the ping was unsuccessful, close it and ignore errors as we'll be - // reestablishing anyways - b.db.Close() - } - - // Otherwise, attempt to make connection - entry, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return nil, - fmt.Errorf("configure the DB connection with config/connection first") - } - - var connConfig connectionConfig - if err := entry.DecodeJSON(&connConfig); err != nil { - return nil, err - } - - conn := connConfig.ConnectionURL - if len(conn) == 0 { - conn = connConfig.ConnectionString - } - - b.db, err = sql.Open("mysql", conn) - if err != nil { - return nil, err - } - - // Set some connection pool settings. We don't need much of this, - // since the request rate shouldn't be high. - b.db.SetMaxOpenConns(connConfig.MaxOpenConnections) - b.db.SetMaxIdleConns(connConfig.MaxIdleConnections) - - return b.db, nil -} - -// ResetDB forces a connection next time DB() is called. -func (b *backend) ResetDB(_ context.Context) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.db != nil { - b.db.Close() - } - - b.db = nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/connection": - b.ResetDB(ctx) - } -} - -// Lease returns the lease information -func (b *backend) Lease(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -const backendHelp = ` -The MySQL backend dynamically generates database users. - -After mounting this backend, configure it using the endpoints within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_connection.go deleted file mode 100644 index 998775ce2..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_connection.go +++ /dev/null @@ -1,160 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - "fmt" - - _ "github.com/go-sql-driver/mysql" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "connection_url": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DB connection string", - }, - "value": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `DB connection string. Use 'connection_url' instead. -This name is deprecated.`, - }, - "max_open_connections": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Maximum number of open connections to database", - }, - "max_idle_connections": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Maximum number of idle connections to the database; a zero uses the value of max_open_connections and a negative value disables idle connections. If larger than max_open_connections it will be reduced to the same size.", - }, - "verify_connection": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: "If set, connection_url is verified by actually connecting to the database", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConnectionWrite, - logical.ReadOperation: b.pathConnectionRead, - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -// pathConnectionRead reads out the connection configuration -func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := req.Storage.Get(ctx, "config/connection") - if err != nil { - return nil, fmt.Errorf("failed to read connection configuration") - } - if entry == nil { - return nil, nil - } - - var config connectionConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "max_open_connections": config.MaxOpenConnections, - "max_idle_connections": config.MaxIdleConnections, - }, - }, nil -} - -func (b *backend) pathConnectionWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - connValue := data.Get("value").(string) - connURL := data.Get("connection_url").(string) - if connURL == "" { - if connValue == "" { - return logical.ErrorResponse("the connection_url parameter must be supplied"), nil - } else { - connURL = connValue - } - } - - maxOpenConns := data.Get("max_open_connections").(int) - if maxOpenConns == 0 { - maxOpenConns = 2 - } - - maxIdleConns := data.Get("max_idle_connections").(int) - if maxIdleConns == 0 { - maxIdleConns = maxOpenConns - } - if maxIdleConns > maxOpenConns { - maxIdleConns = maxOpenConns - } - - // Don't check the connection_url if verification is disabled - verifyConnection := data.Get("verify_connection").(bool) - if verifyConnection { - // Verify the string - db, err := sql.Open("mysql", connURL) - - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "error validating connection info: %s", err)), nil - } - defer db.Close() - if err := db.Ping(); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "error validating connection info: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ - ConnectionURL: connURL, - MaxOpenConnections: maxOpenConns, - MaxIdleConnections: maxIdleConns, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the DB connection - b.ResetDB(ctx) - - resp := &logical.Response{} - resp.AddWarning("Read access to this endpoint should be controlled via ACLs as it will return the connection URL as it is, including passwords, if any.") - - return resp, nil -} - -type connectionConfig struct { - ConnectionURL string `json:"connection_url" structs:"connection_url" mapstructure:"connection_url"` - // Deprecate "value" in coming releases - ConnectionString string `json:"value" structs:"value" mapstructure:"value"` - MaxOpenConnections int `json:"max_open_connections" structs:"max_open_connections" mapstructure:"max_open_connections"` - MaxIdleConnections int `json:"max_idle_connections" structs:"max_idle_connections" mapstructure:"max_idle_connections"` -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection string to talk to MySQL. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection string used to connect to MySQL. The value -of the string is a Data Source Name (DSN). An example is using -"username:password@protocol(address)/dbname?param=value" - -For example, RDS may look like: -"id:password@tcp(your-amazonaws-uri.com:3306)/dbname" - -When configuring the connection string, the backend will verify its validity. -If the database is not available when setting the connection URL, set the -"verify_connection" option to false. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_lease.go deleted file mode 100644 index 6f17e18d6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_config_lease.go +++ /dev/null @@ -1,102 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "lease": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Default lease for roles.", - }, - - "lease_max": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Maximum time a credential is valid for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathLeaseRead, - logical.UpdateOperation: b.pathLeaseWrite, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -func (b *backend) pathLeaseWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - leaseRaw := d.Get("lease").(string) - leaseMaxRaw := d.Get("lease_max").(string) - - lease, err := time.ParseDuration(leaseRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease: %s", err)), nil - } - leaseMax, err := time.ParseDuration(leaseMaxRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease: %s", err)), nil - } - - // Store it - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - Lease: lease, - LeaseMax: leaseMax, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lease, err := b.Lease(ctx, req.Storage) - - if err != nil { - return nil, err - } - if lease == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "lease": lease.Lease.String(), - "lease_max": lease.LeaseMax.String(), - }, - }, nil -} - -type configLease struct { - Lease time.Duration - LeaseMax time.Duration -} - -const pathConfigLeaseHelpSyn = ` -Configure the default lease information for generated credentials. -` - -const pathConfigLeaseHelpDesc = ` -This configures the default lease information used for credentials -generated by this backend. The lease specifies the duration that a -credential will be valid for, as well as the maximum session for -a set of credentials. - -The format for the lease is "1h" or integer and then unit. The longest -unit is hour. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_role_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_role_create.go deleted file mode 100644 index 135587575..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_role_create.go +++ /dev/null @@ -1,144 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - _ "github.com/lib/pq" -) - -func pathRoleCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleCreateRead, - }, - - HelpSynopsis: pathRoleCreateReadHelpSyn, - HelpDescription: pathRoleCreateReadHelpDesc, - } -} - -func (b *backend) pathRoleCreateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - // Determine if we have a lease - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - - // Generate our username and password. The username will be a - // concatenation of: - // - // - the role name, truncated to role.rolenameLength (default 4) - // - the token display name, truncated to role.displaynameLength (default 4) - // - a UUID - // - // the entire concatenated string is then truncated to role.usernameLength, - // which by default is 16 due to limitations in older but still-prevalent - // versions of MySQL. - roleName := name - if len(roleName) > role.RolenameLength { - roleName = roleName[:role.RolenameLength] - } - displayName := req.DisplayName - if len(displayName) > role.DisplaynameLength { - displayName = displayName[:role.DisplaynameLength] - } - userUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - username := fmt.Sprintf("%s-%s-%s", roleName, displayName, userUUID) - if len(username) > role.UsernameLength { - username = username[:role.UsernameLength] - } - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - // Get our handle - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Start a transaction - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer tx.Rollback() - - // Execute each query - for _, query := range strutil.ParseArbitraryStringSlice(role.SQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - "password": password, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return nil, err - } - - // Return the secret - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - "role": name, - }) - - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - - return resp, nil -} - -const pathRoleCreateReadHelpSyn = ` -Request database credentials for a certain role. -` - -const pathRoleCreateReadHelpDesc = ` -This path reads database credentials for a certain role. The -database credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_roles.go deleted file mode 100644 index 4c54f5f8b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/path_roles.go +++ /dev/null @@ -1,230 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - "strings" - - _ "github.com/go-sql-driver/mysql" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - - "sql": { - Type: framework.TypeString, - Description: "SQL string to create a user. See help for more info.", - }, - - "revocation_sql": { - Type: framework.TypeString, - Description: "SQL string to revoke a user. See help for more info.", - }, - - "username_length": { - Type: framework.TypeInt, - Description: "number of characters to truncate generated mysql usernames to (default 16)", - Default: 16, - }, - - "rolename_length": { - Type: framework.TypeInt, - Description: "number of characters to truncate the rolename portion of generated mysql usernames to (default 4)", - Default: 4, - }, - - "displayname_length": { - Type: framework.TypeInt, - Description: "number of characters to truncate the displayname portion of generated mysql usernames to (default 4)", - Default: 4, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) Role(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - // Set defaults to handle upgrade cases - result := roleEntry{ - UsernameLength: 16, - RolenameLength: 4, - DisplaynameLength: 4, - } - - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "sql": role.SQL, - "revocation_sql": role.RevocationSQL, - }, - }, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Test the query by trying to prepare it - sql := data.Get("sql").(string) - for _, query := range strutil.ParseArbitraryStringSlice(sql, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - stmt, err := db.Prepare(Query(query, map[string]string{ - "name": "foo", - "password": "bar", - })) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error testing query: %s", err)), nil - } - stmt.Close() - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, &roleEntry{ - SQL: sql, - RevocationSQL: data.Get("revocation_sql").(string), - UsernameLength: data.Get("username_length").(int), - DisplaynameLength: data.Get("displayname_length").(int), - RolenameLength: data.Get("rolename_length").(int), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil -} - -type roleEntry struct { - SQL string `json:"sql" mapstructure:"sql" structs:"sql"` - RevocationSQL string `json:"revocation_sql" mapstructure:"revocation_sql" structs:"revocation_sql"` - UsernameLength int `json:"username_length" mapstructure:"username_length" structs:"username_length"` - DisplaynameLength int `json:"displayname_length" mapstructure:"displayname_length" structs:"displayname_length"` - RolenameLength int `json:"rolename_length" mapstructure:"rolename_length" structs:"rolename_length"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "sql" parameter customizes the SQL string used to create the role. -This can be a sequence of SQL queries, each semi-colon separated. Some -substitution will be done to the SQL string for certain keys. -The names of the variables must be surrounded by "{{" and "}}" to be replaced. - - * "name" - The random username generated for the DB user. - - * "password" - The random password generated for the DB user. - -Example of a decent SQL query to use: - - CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}'; - GRANT ALL ON db1.* TO '{{name}}'@'%'; - -Note the above user would be able to access anything in db1. Please see the MySQL -manual on the GRANT command to learn how to do more fine grained access. - -The "rolename_length" parameter determines how many characters of the role name -will be used in creating the generated mysql username; the default is 4. - -The "displayname_length" parameter determines how many characters of the token -display name will be used in creating the generated mysql username; the default -is 4. - -The "username_length" parameter determines how many total characters the -generated username (including the role name, token display name and the uuid -portion) will be truncated to. Versions of MySQL prior to 5.7.8 are limited to -16 characters total (see -http://dev.mysql.com/doc/refman/5.7/en/user-names.html) so that is the default; -for versions >=5.7.8 it is safe to increase this to 32. - -For best readability in MySQL process lists, we recommend using MySQL 5.7.8 or -later, setting "username_length" to 32 and setting both "rolename_length" and -"displayname_length" to 8. However due the the prevalence of older versions of -MySQL in general deployment, the defaults are currently tuned for a -username_length of 16. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/secret_creds.go deleted file mode 100644 index 65d59dbc4..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/secret_creds.go +++ /dev/null @@ -1,136 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const SecretCredsType = "creds" - -// defaultRevocationSQL is a default SQL statement for revoking a user. Revoking -// permissions for the user is done before the drop, because MySQL explicitly -// documents that open user connections will not be closed. By revoking all -// grants, at least we ensure that the open connection is useless. Dropping the -// user will only affect the next connection. -const defaultRevocationSQL = ` -REVOKE ALL PRIVILEGES, GRANT OPTION FROM '{{name}}'@'%'; -DROP USER '{{name}}'@'%' -` - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password", - }, - }, - - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the lease information - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - return resp, nil -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var resp *logical.Response - - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("usernameRaw is not a string") - } - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - roleName := "" - roleNameRaw, ok := req.Secret.InternalData["role"] - if ok { - roleName = roleNameRaw.(string) - } - - var role *roleEntry - if roleName != "" { - role, err = b.Role(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - } - - // Use a default SQL statement for revocation if one cannot be fetched from the role - revocationSQL := defaultRevocationSQL - - if role != nil && role.RevocationSQL != "" { - revocationSQL = role.RevocationSQL - } else { - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning(fmt.Sprintf("Role %q cannot be found. Using default SQL for revoking user.", roleName)) - } - - // Start a transaction - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer tx.Rollback() - - for _, query := range strutil.ParseArbitraryStringSlice(revocationSQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - // This is not a prepared statement because not all commands are supported - // 1295: This command is not supported in the prepared statement protocol yet - // Reference https://mariadb.com/kb/en/mariadb/prepare-statement/ - query = strings.Replace(query, "{{name}}", username, -1) - _, err = tx.Exec(query) - if err != nil { - return nil, err - } - - } - - // Commit the transaction - if err := tx.Commit(); err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/mysql/util.go deleted file mode 100644 index 313264f90..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/mysql/util.go +++ /dev/null @@ -1,15 +0,0 @@ -package mysql - -import ( - "fmt" - "strings" -) - -// Query templates a query for us. -func Query(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/backend.go deleted file mode 100644 index a8b4b9928..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/backend.go +++ /dev/null @@ -1,73 +0,0 @@ -package nomad - -import ( - "context" - - "github.com/hashicorp/nomad/api" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Factory returns a Nomad backend that satisfies the logical.Backend interface -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Backend returns the configured Nomad backend -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/access", - }, - }, - - Paths: []*framework.Path{ - pathConfigAccess(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathRoles(&b), - pathCredsCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretToken(&b), - }, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend -} - -func (b *backend) client(ctx context.Context, s logical.Storage) (*api.Client, error) { - conf, err := b.readConfigAccess(ctx, s) - if err != nil { - return nil, err - } - - nomadConf := api.DefaultConfig() - if conf != nil { - if conf.Address != "" { - nomadConf.Address = conf.Address - } - if conf.Token != "" { - nomadConf.SecretID = conf.Token - } - } - - client, err := api.NewClient(nomadConf) - if err != nil { - return nil, err - } - - return client, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_access.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_access.go deleted file mode 100644 index c1edd6bad..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_access.go +++ /dev/null @@ -1,129 +0,0 @@ -package nomad - -import ( - "context" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const configAccessKey = "config/access" - -func pathConfigAccess(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/access", - Fields: map[string]*framework.FieldSchema{ - "address": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Nomad server address", - }, - - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for API calls", - }, - - "max_token_name_length": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: "Max length for name of generated Nomad tokens", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathConfigAccessRead, - logical.CreateOperation: b.pathConfigAccessWrite, - logical.UpdateOperation: b.pathConfigAccessWrite, - logical.DeleteOperation: b.pathConfigAccessDelete, - }, - - ExistenceCheck: b.configExistenceCheck, - } -} - -func (b *backend) configExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - entry, err := b.readConfigAccess(ctx, req.Storage) - if err != nil { - return false, err - } - - return entry != nil, nil -} - -func (b *backend) readConfigAccess(ctx context.Context, storage logical.Storage) (*accessConfig, error) { - entry, err := storage.Get(ctx, configAccessKey) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - conf := &accessConfig{} - if err := entry.DecodeJSON(conf); err != nil { - return nil, errwrap.Wrapf("error reading nomad access configuration: {{err}}", err) - } - - return conf, nil -} - -func (b *backend) pathConfigAccessRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - conf, err := b.readConfigAccess(ctx, req.Storage) - if err != nil { - return nil, err - } - if conf == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "address": conf.Address, - "max_token_name_length": conf.MaxTokenNameLength, - }, - }, nil -} - -func (b *backend) pathConfigAccessWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - conf, err := b.readConfigAccess(ctx, req.Storage) - if err != nil { - return nil, err - } - if conf == nil { - conf = &accessConfig{} - } - - address, ok := data.GetOk("address") - if ok { - conf.Address = address.(string) - } - token, ok := data.GetOk("token") - if ok { - conf.Token = token.(string) - } - - conf.MaxTokenNameLength = data.Get("max_token_name_length").(int) - - entry, err := logical.StorageEntryJSON("config/access", conf) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathConfigAccessDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if err := req.Storage.Delete(ctx, configAccessKey); err != nil { - return nil, err - } - return nil, nil -} - -type accessConfig struct { - Address string `json:"address"` - Token string `json:"token"` - MaxTokenNameLength int `json:"max_token_name_length"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_lease.go deleted file mode 100644 index 7816aae52..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_config_lease.go +++ /dev/null @@ -1,110 +0,0 @@ -package nomad - -import ( - "context" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const leaseConfigKey = "config/lease" - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "Duration before which the issued token needs renewal", - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `Duration after which the issued token should not be allowed to be renewed`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathLeaseRead, - logical.UpdateOperation: b.pathLeaseUpdate, - logical.DeleteOperation: b.pathLeaseDelete, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -// Sets the lease configuration parameters -func (b *backend) pathLeaseUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - TTL: time.Second * time.Duration(d.Get("ttl").(int)), - MaxTTL: time.Second * time.Duration(d.Get("max_ttl").(int)), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathLeaseDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if err := req.Storage.Delete(ctx, leaseConfigKey); err != nil { - return nil, err - } - - return nil, nil -} - -// Returns the lease configuration parameters -func (b *backend) pathLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lease, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "ttl": int64(lease.TTL.Seconds()), - "max_ttl": int64(lease.MaxTTL.Seconds()), - }, - }, nil -} - -// Lease returns the lease information -func (b *backend) LeaseConfig(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, leaseConfigKey) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// Lease configuration information for the secrets issued by this backend -type configLease struct { - TTL time.Duration `json:"ttl" mapstructure:"ttl"` - MaxTTL time.Duration `json:"max_ttl" mapstructure:"max_ttl"` -} - -var pathConfigLeaseHelpSyn = "Configure the lease parameters for generated tokens" - -var pathConfigLeaseHelpDesc = ` -Sets the ttl and max_ttl values for the secrets to be issued by this backend. -Both ttl and max_ttl takes in an integer number of seconds as input as well as -inputs like "1h". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_creds_create.go deleted file mode 100644 index deca9e490..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_creds_create.go +++ /dev/null @@ -1,98 +0,0 @@ -package nomad - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/nomad/api" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// maxTokenNameLength is the maximum length for the name of a Nomad access -// token -const maxTokenNameLength = 256 - -func pathCredsCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathTokenRead, - }, - } -} - -func (b *backend) pathTokenRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - conf, _ := b.readConfigAccess(ctx, req.Storage) - // establish a default - tokenNameLength := maxTokenNameLength - if conf != nil && conf.MaxTokenNameLength > 0 { - tokenNameLength = conf.MaxTokenNameLength - } - - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("role %q not found", name)), nil - } - - // Determine if we have a lease configuration - leaseConfig, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if leaseConfig == nil { - leaseConfig = &configLease{} - } - - // Get the nomad client - c, err := b.client(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Generate a name for the token - tokenName := fmt.Sprintf("vault-%s-%s-%d", name, req.DisplayName, time.Now().UnixNano()) - - // Note: if the given role name is sufficiently long, the UnixNano() portion - // of the pseudo randomized token name is the part that gets trimmed off, - // weakening it's randomness. - if len(tokenName) > tokenNameLength { - tokenName = tokenName[:tokenNameLength] - } - - // Create it - token, _, err := c.ACLTokens().Create(&api.ACLToken{ - Name: tokenName, - Type: role.TokenType, - Policies: role.Policies, - Global: role.Global, - }, nil) - if err != nil { - return nil, err - } - - // Use the helper to create the secret - resp := b.Secret(SecretTokenType).Response(map[string]interface{}{ - "secret_id": token.SecretID, - "accessor_id": token.AccessorID, - }, map[string]interface{}{ - "accessor_id": token.AccessorID, - }) - resp.Secret.TTL = leaseConfig.TTL - resp.Secret.MaxTTL = leaseConfig.MaxTTL - - return resp, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_roles.go deleted file mode 100644 index 563060281..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/path_roles.go +++ /dev/null @@ -1,186 +0,0 @@ -package nomad - -import ( - "context" - "errors" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "role/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Comma-separated string or list of policies as previously created in Nomad. Required for 'client' token.", - }, - - "global": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Boolean value describing if the token should be global or not. Defaults to false.", - }, - - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "client", - Description: `Which type of token to create: 'client' -or 'management'. If a 'management' token, -the "policies" parameter is not required. -Defaults to 'client'.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRolesRead, - logical.CreateOperation: b.pathRolesWrite, - logical.UpdateOperation: b.pathRolesWrite, - logical.DeleteOperation: b.pathRolesDelete, - }, - - ExistenceCheck: b.rolesExistenceCheck, - } -} - -// Establishes dichotomy of request operation between CreateOperation and UpdateOperation. -// Returning 'true' forces an UpdateOperation, CreateOperation otherwise. -func (b *backend) rolesExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) { - name := d.Get("name").(string) - entry, err := b.Role(ctx, req.Storage, name) - if err != nil { - return false, err - } - return entry != nil, nil -} - -func (b *backend) Role(ctx context.Context, storage logical.Storage, name string) (*roleConfig, error) { - if name == "" { - return nil, errors.New("invalid role name") - } - - entry, err := storage.Get(ctx, "role/"+name) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if entry == nil { - return nil, nil - } - - var result roleConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRolesRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "type": role.TokenType, - "global": role.Global, - "policies": role.Policies, - }, - } - return resp, nil -} - -func (b *backend) pathRolesWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - role = new(roleConfig) - } - - policies, ok := d.GetOk("policies") - if ok { - role.Policies = policies.([]string) - } - - role.TokenType = d.Get("type").(string) - switch role.TokenType { - case "client": - if len(role.Policies) == 0 { - return logical.ErrorResponse( - "policies cannot be empty when using client tokens"), nil - } - case "management": - if len(role.Policies) != 0 { - return logical.ErrorResponse( - "policies should be empty when using management tokens"), nil - } - default: - return logical.ErrorResponse( - `type must be "client" or "management"`), nil - } - - global, ok := d.GetOk("global") - if ok { - role.Global = global.(bool) - } - - entry, err := logical.StorageEntryJSON("role/"+name, role) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRolesDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if err := req.Storage.Delete(ctx, "role/"+name); err != nil { - return nil, err - } - return nil, nil -} - -type roleConfig struct { - Policies []string `json:"policies"` - TokenType string `json:"type"` - Global bool `json:"global"` -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/secret_token.go b/vendor/github.com/hashicorp/vault/builtin/logical/nomad/secret_token.go deleted file mode 100644 index 3509dcba4..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/nomad/secret_token.go +++ /dev/null @@ -1,69 +0,0 @@ -package nomad - -import ( - "context" - "errors" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - SecretTokenType = "token" -) - -func secretToken(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretTokenType, - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Request token", - }, - }, - - Renew: b.secretTokenRenew, - Revoke: b.secretTokenRevoke, - } -} - -func (b *backend) secretTokenRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - lease, err := b.LeaseConfig(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = lease.TTL - resp.Secret.MaxTTL = lease.MaxTTL - return resp, nil -} - -func (b *backend) secretTokenRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - c, err := b.client(ctx, req.Storage) - if err != nil { - return nil, err - } - - if c == nil { - return nil, fmt.Errorf("error getting Nomad client") - } - - accessorIDRaw, ok := req.Secret.InternalData["accessor_id"] - if !ok { - return nil, fmt.Errorf("accessor_id is missing on the lease") - } - accessorID, ok := accessorIDRaw.(string) - if !ok { - return nil, errors.New("unable to convert accessor_id") - } - _, err = c.ACLTokens().Delete(accessorID, nil) - if err != nil { - return nil, err - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/backend.go deleted file mode 100644 index 60e943acb..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/backend.go +++ /dev/null @@ -1,108 +0,0 @@ -package pki - -import ( - "context" - "strings" - "sync" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Factory creates a new backend implementing the logical.Backend interface -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend(conf) - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Backend returns a new Backend framework struct -func Backend(conf *logical.BackendConfig) *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "cert/*", - "ca/pem", - "ca_chain", - "ca", - "crl/pem", - "crl", - }, - - LocalStorage: []string{ - "revoked/", - "crl", - "certs/", - }, - - Root: []string{ - "root", - "root/sign-self-issued", - }, - - SealWrapStorage: []string{ - "config/ca_bundle", - }, - }, - - Paths: []*framework.Path{ - pathListRoles(&b), - pathRoles(&b), - pathGenerateRoot(&b), - pathSignIntermediate(&b), - pathSignSelfIssued(&b), - pathDeleteRoot(&b), - pathGenerateIntermediate(&b), - pathSetSignedIntermediate(&b), - pathConfigCA(&b), - pathConfigCRL(&b), - pathConfigURLs(&b), - pathSignVerbatim(&b), - pathSign(&b), - pathIssue(&b), - pathRotateCRL(&b), - pathFetchCA(&b), - pathFetchCAChain(&b), - pathFetchCRL(&b), - pathFetchCRLViaCertPath(&b), - pathFetchValid(&b), - pathFetchListCerts(&b), - pathRevoke(&b), - pathTidy(&b), - }, - - Secrets: []*framework.Secret{ - secretCerts(&b), - }, - - BackendType: logical.TypeLogical, - } - - b.crlLifetime = time.Hour * 72 - b.tidyCASGuard = new(uint32) - b.storage = conf.StorageView - - return &b -} - -type backend struct { - *framework.Backend - - storage logical.Storage - crlLifetime time.Duration - revokeStorageLock sync.RWMutex - tidyCASGuard *uint32 -} - -const backendHelp = ` -The PKI backend dynamically generates X509 server and client certificates. - -After mounting this backend, configure the CA using the "pem_bundle" endpoint within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/ca_util.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/ca_util.go deleted file mode 100644 index 143fd574e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/ca_util.go +++ /dev/null @@ -1,58 +0,0 @@ -package pki - -import ( - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) getGenerationParams( - data *framework.FieldData, -) (exported bool, format string, role *roleEntry, errorResp *logical.Response) { - exportedStr := data.Get("exported").(string) - switch exportedStr { - case "exported": - exported = true - case "internal": - default: - errorResp = logical.ErrorResponse( - `the "exported" path parameter must be "internal" or "exported"`) - return - } - - format = getFormat(data) - if format == "" { - errorResp = logical.ErrorResponse( - `the "format" path parameter must be "pem", "der", "der_pkcs", or "pem_bundle"`) - return - } - - role = &roleEntry{ - TTL: time.Duration(data.Get("ttl").(int)) * time.Second, - KeyType: data.Get("key_type").(string), - KeyBits: data.Get("key_bits").(int), - AllowLocalhost: true, - AllowAnyName: true, - AllowIPSANs: true, - EnforceHostnames: false, - AllowedURISANs: []string{"*"}, - AllowedSerialNumbers: []string{"*"}, - OU: data.Get("ou").([]string), - Organization: data.Get("organization").([]string), - Country: data.Get("country").([]string), - Locality: data.Get("locality").([]string), - Province: data.Get("province").([]string), - StreetAddress: data.Get("street_address").([]string), - PostalCode: data.Get("postal_code").([]string), - } - - if role.KeyType == "rsa" && role.KeyBits < 2048 { - errorResp = logical.ErrorResponse("RSA keys < 2048 bits are unsafe and not supported") - return - } - - errorResp = validateKeyTypeLength(role.KeyType, role.KeyBits) - - return -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/cert_util.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/cert_util.go deleted file mode 100644 index 28ca26eb8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/cert_util.go +++ /dev/null @@ -1,1646 +0,0 @@ -package pki - -import ( - "bytes" - "context" - "crypto" - "crypto/ecdsa" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/base64" - "encoding/pem" - "fmt" - "net" - "net/url" - "regexp" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/ryanuber/go-glob" - "golang.org/x/crypto/cryptobyte" - cbbasn1 "golang.org/x/crypto/cryptobyte/asn1" - "golang.org/x/net/idna" -) - -type certExtKeyUsage int - -const ( - anyExtKeyUsage certExtKeyUsage = 1 << iota - serverAuthExtKeyUsage - clientAuthExtKeyUsage - codeSigningExtKeyUsage - emailProtectionExtKeyUsage - ipsecEndSystemExtKeyUsage - ipsecTunnelExtKeyUsage - ipsecUserExtKeyUsage - timeStampingExtKeyUsage - ocspSigningExtKeyUsage - microsoftServerGatedCryptoExtKeyUsage - netscapeServerGatedCryptoExtKeyUsage - microsoftCommercialCodeSigningExtKeyUsage - microsoftKernelCodeSigningExtKeyUsage -) - -type dataBundle struct { - params *creationParameters - signingBundle *caInfoBundle - csr *x509.CertificateRequest - role *roleEntry - req *logical.Request - apiData *framework.FieldData -} - -type creationParameters struct { - Subject pkix.Name - DNSNames []string - EmailAddresses []string - IPAddresses []net.IP - URIs []*url.URL - OtherSANs map[string][]string - IsCA bool - KeyType string - KeyBits int - NotAfter time.Time - KeyUsage x509.KeyUsage - ExtKeyUsage certExtKeyUsage - ExtKeyUsageOIDs []string - PolicyIdentifiers []string - BasicConstraintsValidForNonCA bool - - // Only used when signing a CA cert - UseCSRValues bool - PermittedDNSDomains []string - - // URLs to encode into the certificate - URLs *urlEntries - - // The maximum path length to encode - MaxPathLength int -} - -type caInfoBundle struct { - certutil.ParsedCertBundle - URLs *urlEntries -} - -func (b *caInfoBundle) GetCAChain() []*certutil.CertBlock { - chain := []*certutil.CertBlock{} - - // Include issuing CA in Chain, not including Root Authority - if (len(b.Certificate.AuthorityKeyId) > 0 && - !bytes.Equal(b.Certificate.AuthorityKeyId, b.Certificate.SubjectKeyId)) || - (len(b.Certificate.AuthorityKeyId) == 0 && - !bytes.Equal(b.Certificate.RawIssuer, b.Certificate.RawSubject)) { - - chain = append(chain, &certutil.CertBlock{ - Certificate: b.Certificate, - Bytes: b.CertificateBytes, - }) - if b.CAChain != nil && len(b.CAChain) > 0 { - chain = append(chain, b.CAChain...) - } - } - - return chain -} - -var ( - // A note on hostnameRegex: although we set the StrictDomainName option - // when doing the idna conversion, this appears to only affect output, not - // input, so it will allow e.g. host^123.example.com straight through. So - // we still need to use this to check the output. - hostnameRegex = regexp.MustCompile(`^(\*\.)?(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`) - oidExtensionBasicConstraints = []int{2, 5, 29, 19} -) - -func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { - for _, e := range extensions { - if e.Id.Equal(oid) { - return true - } - } - return false -} - -func getFormat(data *framework.FieldData) string { - format := data.Get("format").(string) - switch format { - case "pem": - case "der": - case "pem_bundle": - default: - format = "" - } - return format -} - -func validateKeyTypeLength(keyType string, keyBits int) *logical.Response { - switch keyType { - case "rsa": - switch keyBits { - case 2048: - case 4096: - case 8192: - default: - return logical.ErrorResponse(fmt.Sprintf( - "unsupported bit length for RSA key: %d", keyBits)) - } - case "ec": - switch keyBits { - case 224: - case 256: - case 384: - case 521: - default: - return logical.ErrorResponse(fmt.Sprintf( - "unsupported bit length for EC key: %d", keyBits)) - } - case "any": - default: - return logical.ErrorResponse(fmt.Sprintf( - "unknown key type %s", keyType)) - } - - return nil -} - -// Fetches the CA info. Unlike other certificates, the CA info is stored -// in the backend as a CertBundle, because we are storing its private key -func fetchCAInfo(ctx context.Context, req *logical.Request) (*caInfoBundle, error) { - bundleEntry, err := req.Storage.Get(ctx, "config/ca_bundle") - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to fetch local CA certificate/key: %v", err)} - } - if bundleEntry == nil { - return nil, errutil.UserError{Err: "backend must be configured with a CA certificate/key"} - } - - var bundle certutil.CertBundle - if err := bundleEntry.DecodeJSON(&bundle); err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to decode local CA certificate/key: %v", err)} - } - - parsedBundle, err := bundle.ToParsedCertBundle() - if err != nil { - return nil, errutil.InternalError{Err: err.Error()} - } - - if parsedBundle.Certificate == nil { - return nil, errutil.InternalError{Err: "stored CA information not able to be parsed"} - } - - caInfo := &caInfoBundle{*parsedBundle, nil} - - entries, err := getURLs(ctx, req) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to fetch URL information: %v", err)} - } - if entries == nil { - entries = &urlEntries{ - IssuingCertificates: []string{}, - CRLDistributionPoints: []string{}, - OCSPServers: []string{}, - } - } - caInfo.URLs = entries - - return caInfo, nil -} - -// Allows fetching certificates from the backend; it handles the slightly -// separate pathing for CA, CRL, and revoked certificates. -func fetchCertBySerial(ctx context.Context, req *logical.Request, prefix, serial string) (*logical.StorageEntry, error) { - var path, legacyPath string - var err error - var certEntry *logical.StorageEntry - - hyphenSerial := normalizeSerial(serial) - colonSerial := strings.Replace(strings.ToLower(serial), "-", ":", -1) - - switch { - // Revoked goes first as otherwise ca/crl get hardcoded paths which fail if - // we actually want revocation info - case strings.HasPrefix(prefix, "revoked/"): - legacyPath = "revoked/" + colonSerial - path = "revoked/" + hyphenSerial - case serial == "ca": - path = "ca" - case serial == "crl": - path = "crl" - default: - legacyPath = "certs/" + colonSerial - path = "certs/" + hyphenSerial - } - - certEntry, err = req.Storage.Get(ctx, path) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error fetching certificate %s: %s", serial, err)} - } - if certEntry != nil { - if certEntry.Value == nil || len(certEntry.Value) == 0 { - return nil, errutil.InternalError{Err: fmt.Sprintf("returned certificate bytes for serial %s were empty", serial)} - } - return certEntry, nil - } - - // If legacyPath is unset, it's going to be a CA or CRL; return immediately - if legacyPath == "" { - return nil, nil - } - - // Retrieve the old-style path - certEntry, err = req.Storage.Get(ctx, legacyPath) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error fetching certificate %s: %s", serial, err)} - } - if certEntry == nil { - return nil, nil - } - if certEntry.Value == nil || len(certEntry.Value) == 0 { - return nil, errutil.InternalError{Err: fmt.Sprintf("returned certificate bytes for serial %s were empty", serial)} - } - - // Update old-style paths to new-style paths - certEntry.Key = path - if err = req.Storage.Put(ctx, certEntry); err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error saving certificate with serial %s to new location", serial)} - } - if err = req.Storage.Delete(ctx, legacyPath); err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error deleting certificate with serial %s from old location", serial)} - } - - return certEntry, nil -} - -// Given a set of requested names for a certificate, verifies that all of them -// match the various toggles set in the role for controlling issuance. -// If one does not pass, it is returned in the string argument. -func validateNames(data *dataBundle, names []string) string { - for _, name := range names { - sanitizedName := name - emailDomain := name - isEmail := false - isWildcard := false - - // If it has an @, assume it is an email address and separate out the - // user from the hostname portion so that we can act on the hostname. - // Note that this matches behavior from the alt_names parameter. If it - // ends up being problematic for users, I guess that could be separated - // into dns_names and email_names in the future to be explicit, but I - // don't think this is likely. - if strings.Contains(name, "@") { - splitEmail := strings.Split(name, "@") - if len(splitEmail) != 2 { - return name - } - sanitizedName = splitEmail[1] - emailDomain = splitEmail[1] - isEmail = true - } - - // If we have an asterisk as the first part of the domain name, mark it - // as wildcard and set the sanitized name to the remainder of the - // domain - if strings.HasPrefix(sanitizedName, "*.") { - sanitizedName = sanitizedName[2:] - isWildcard = true - } - - // Email addresses using wildcard domain names do not make sense - if isEmail && isWildcard { - return name - } - - // AllowAnyName is checked after this because EnforceHostnames still - // applies when allowing any name. Also, we check the sanitized name to - // ensure that we are not either checking a full email address or a - // wildcard prefix. - if data.role.EnforceHostnames { - p := idna.New( - idna.StrictDomainName(true), - idna.VerifyDNSLength(true), - ) - converted, err := p.ToASCII(sanitizedName) - if err != nil { - return name - } - if !hostnameRegex.MatchString(converted) { - return name - } - } - - // Self-explanatory - if data.role.AllowAnyName { - continue - } - - // The following blocks all work the same basic way: - // 1) If a role allows a certain class of base (localhost, token - // display name, role-configured domains), perform further tests - // - // 2) If there is a perfect match on either the name itself or it's an - // email address with a perfect match on the hostname portion, allow it - // - // 3) If subdomains are allowed, we check based on the sanitized name; - // note that if not a wildcard, will be equivalent to the email domain - // for email checks, and we already checked above for both a wildcard - // and email address being present in the same name - // 3a) First we check for a non-wildcard subdomain, as in . - // 3b) Then we check if it's a wildcard and the base domain is a match - // - // Variances are noted in-line - - if data.role.AllowLocalhost { - if name == "localhost" || - name == "localdomain" || - (isEmail && emailDomain == "localhost") || - (isEmail && emailDomain == "localdomain") { - continue - } - - if data.role.AllowSubdomains { - // It is possible, if unlikely, to have a subdomain of "localhost" - if strings.HasSuffix(sanitizedName, ".localhost") || - (isWildcard && sanitizedName == "localhost") { - continue - } - - // A subdomain of "localdomain" is also not entirely uncommon - if strings.HasSuffix(sanitizedName, ".localdomain") || - (isWildcard && sanitizedName == "localdomain") { - continue - } - } - } - - if data.role.AllowTokenDisplayName { - if name == data.req.DisplayName { - continue - } - - if data.role.AllowSubdomains { - if isEmail { - // If it's an email address, we need to parse the token - // display name in order to do a proper comparison of the - // subdomain - if strings.Contains(data.req.DisplayName, "@") { - splitDisplay := strings.Split(data.req.DisplayName, "@") - if len(splitDisplay) == 2 { - // Compare the sanitized name against the hostname - // portion of the email address in the broken - // display name - if strings.HasSuffix(sanitizedName, "."+splitDisplay[1]) { - continue - } - } - } - } - - if strings.HasSuffix(sanitizedName, "."+data.req.DisplayName) || - (isWildcard && sanitizedName == data.req.DisplayName) { - continue - } - } - } - - if len(data.role.AllowedDomains) > 0 { - valid := false - for _, currDomain := range data.role.AllowedDomains { - // If there is, say, a trailing comma, ignore it - if currDomain == "" { - continue - } - - // First, allow an exact match of the base domain if that role flag - // is enabled - if data.role.AllowBareDomains && - (name == currDomain || - (isEmail && emailDomain == currDomain)) { - valid = true - break - } - - if data.role.AllowSubdomains { - if strings.HasSuffix(sanitizedName, "."+currDomain) || - (isWildcard && sanitizedName == currDomain) { - valid = true - break - } - } - - if data.role.AllowGlobDomains && - strings.Contains(currDomain, "*") && - glob.Glob(currDomain, name) { - valid = true - break - } - } - if valid { - continue - } - } - - return name - } - - return "" -} - -// validateOtherSANs checks if the values requested are allowed. If an OID -// isn't allowed, it will be returned as the first string. If a value isn't -// allowed, it will be returned as the second string. Empty strings + error -// means everything is okay. -func validateOtherSANs(data *dataBundle, requested map[string][]string) (string, string, error) { - allowed, err := parseOtherSANs(data.role.AllowedOtherSANs) - if err != nil { - return "", "", errwrap.Wrapf("error parsing role's allowed SANs: {{err}}", err) - } - for oid, names := range requested { - for _, name := range names { - allowedNames, ok := allowed[oid] - if !ok { - return oid, "", nil - } - - valid := false - for _, allowedName := range allowedNames { - if glob.Glob(allowedName, name) { - valid = true - break - } - } - - if !valid { - return oid, name, nil - } - } - } - - return "", "", nil -} - -func parseOtherSANs(others []string) (map[string][]string, error) { - result := map[string][]string{} - for _, other := range others { - splitOther := strings.SplitN(other, ";", 2) - if len(splitOther) != 2 { - return nil, fmt.Errorf("expected a semicolon in other SAN %q", other) - } - splitType := strings.SplitN(splitOther[1], ":", 2) - if len(splitType) != 2 { - return nil, fmt.Errorf("expected a colon in other SAN %q", other) - } - if strings.ToLower(splitType[0]) != "utf8" { - return nil, fmt.Errorf("only utf8 other SANs are supported; found non-supported type in other SAN %q", other) - } - result[splitOther[0]] = append(result[splitOther[0]], splitType[1]) - } - - return result, nil -} - -func validateSerialNumber(data *dataBundle, serialNumber string) string { - valid := false - if len(data.role.AllowedSerialNumbers) > 0 { - for _, currSerialNumber := range data.role.AllowedSerialNumbers { - if currSerialNumber == "" { - continue - } - - if (strings.Contains(currSerialNumber, "*") && - glob.Glob(currSerialNumber, serialNumber)) || - currSerialNumber == serialNumber { - valid = true - break - } - } - } - if !valid { - return serialNumber - } else { - return "" - } -} - -func generateCert(ctx context.Context, - b *backend, - data *dataBundle, - isCA bool) (*certutil.ParsedCertBundle, error) { - - if data.role == nil { - return nil, errutil.InternalError{Err: "no role found in data bundle"} - } - - if data.role.KeyType == "rsa" && data.role.KeyBits < 2048 { - return nil, errutil.UserError{Err: "RSA keys < 2048 bits are unsafe and not supported"} - } - - err := generateCreationBundle(b, data) - if err != nil { - return nil, err - } - if data.params == nil { - return nil, errutil.InternalError{Err: "nil parameters received from parameter bundle generation"} - } - - if isCA { - data.params.IsCA = isCA - data.params.PermittedDNSDomains = data.apiData.Get("permitted_dns_domains").([]string) - - if data.signingBundle == nil { - // Generating a self-signed root certificate - entries, err := getURLs(ctx, data.req) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to fetch URL information: %v", err)} - } - if entries == nil { - entries = &urlEntries{ - IssuingCertificates: []string{}, - CRLDistributionPoints: []string{}, - OCSPServers: []string{}, - } - } - data.params.URLs = entries - - if data.role.MaxPathLength == nil { - data.params.MaxPathLength = -1 - } else { - data.params.MaxPathLength = *data.role.MaxPathLength - } - } - } - - parsedBundle, err := createCertificate(data) - if err != nil { - return nil, err - } - - return parsedBundle, nil -} - -// N.B.: This is only meant to be used for generating intermediate CAs. -// It skips some sanity checks. -func generateIntermediateCSR(b *backend, data *dataBundle) (*certutil.ParsedCSRBundle, error) { - err := generateCreationBundle(b, data) - if err != nil { - return nil, err - } - if data.params == nil { - return nil, errutil.InternalError{Err: "nil parameters received from parameter bundle generation"} - } - - parsedBundle, err := createCSR(data) - if err != nil { - return nil, err - } - - return parsedBundle, nil -} - -func signCert(b *backend, - data *dataBundle, - isCA bool, - useCSRValues bool) (*certutil.ParsedCertBundle, error) { - - if data.role == nil { - return nil, errutil.InternalError{Err: "no role found in data bundle"} - } - - csrString := data.apiData.Get("csr").(string) - if csrString == "" { - return nil, errutil.UserError{Err: fmt.Sprintf("\"csr\" is empty")} - } - - pemBytes := []byte(csrString) - pemBlock, pemBytes := pem.Decode(pemBytes) - if pemBlock == nil { - return nil, errutil.UserError{Err: "csr contains no data"} - } - csr, err := x509.ParseCertificateRequest(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("certificate request could not be parsed: %v", err)} - } - - switch data.role.KeyType { - case "rsa": - // Verify that the key matches the role type - if csr.PublicKeyAlgorithm != x509.RSA { - return nil, errutil.UserError{Err: fmt.Sprintf( - "role requires keys of type %s", - data.role.KeyType)} - } - pubKey, ok := csr.PublicKey.(*rsa.PublicKey) - if !ok { - return nil, errutil.UserError{Err: "could not parse CSR's public key"} - } - - // Verify that the key is at least 2048 bits - if pubKey.N.BitLen() < 2048 { - return nil, errutil.UserError{Err: "RSA keys < 2048 bits are unsafe and not supported"} - } - - // Verify that the bit size is at least the size specified in the role - if pubKey.N.BitLen() < data.role.KeyBits { - return nil, errutil.UserError{Err: fmt.Sprintf( - "role requires a minimum of a %d-bit key, but CSR's key is %d bits", - data.role.KeyBits, - pubKey.N.BitLen())} - } - - case "ec": - // Verify that the key matches the role type - if csr.PublicKeyAlgorithm != x509.ECDSA { - return nil, errutil.UserError{Err: fmt.Sprintf( - "role requires keys of type %s", - data.role.KeyType)} - } - pubKey, ok := csr.PublicKey.(*ecdsa.PublicKey) - if !ok { - return nil, errutil.UserError{Err: "could not parse CSR's public key"} - } - - // Verify that the bit size is at least the size specified in the role - if pubKey.Params().BitSize < data.role.KeyBits { - return nil, errutil.UserError{Err: fmt.Sprintf( - "role requires a minimum of a %d-bit key, but CSR's key is %d bits", - data.role.KeyBits, - pubKey.Params().BitSize)} - } - - case "any": - // We only care about running RSA < 2048 bit checks, so if not RSA - // break out - if csr.PublicKeyAlgorithm != x509.RSA { - break - } - - // Run RSA < 2048 bit checks - pubKey, ok := csr.PublicKey.(*rsa.PublicKey) - if !ok { - return nil, errutil.UserError{Err: "could not parse CSR's public key"} - } - if pubKey.N.BitLen() < 2048 { - return nil, errutil.UserError{Err: "RSA keys < 2048 bits are unsafe and not supported"} - } - - } - - data.csr = csr - - err = generateCreationBundle(b, data) - if err != nil { - return nil, err - } - if data.params == nil { - return nil, errutil.InternalError{Err: "nil parameters received from parameter bundle generation"} - } - - data.params.IsCA = isCA - data.params.UseCSRValues = useCSRValues - - if isCA { - data.params.PermittedDNSDomains = data.apiData.Get("permitted_dns_domains").([]string) - } - - parsedBundle, err := signCertificate(data) - if err != nil { - return nil, err - } - - return parsedBundle, nil -} - -// generateCreationBundle is a shared function that reads parameters supplied -// from the various endpoints and generates a creationParameters with the -// parameters that can be used to issue or sign -func generateCreationBundle(b *backend, data *dataBundle) error { - // Read in names -- CN, DNS and email addresses - var cn string - var ridSerialNumber string - dnsNames := []string{} - emailAddresses := []string{} - { - if data.csr != nil && data.role.UseCSRCommonName { - cn = data.csr.Subject.CommonName - } - if cn == "" { - cn = data.apiData.Get("common_name").(string) - if cn == "" && data.role.RequireCN { - return errutil.UserError{Err: `the common_name field is required, or must be provided in a CSR with "use_csr_common_name" set to true, unless "require_cn" is set to false`} - } - } - - ridSerialNumber = data.apiData.Get("serial_number").(string) - - // only take serial number from CSR if one was not supplied via API - if ridSerialNumber == "" && data.csr != nil { - ridSerialNumber = data.csr.Subject.SerialNumber - } - - if data.csr != nil && data.role.UseCSRSANs { - dnsNames = data.csr.DNSNames - emailAddresses = data.csr.EmailAddresses - } - - if cn != "" && !data.apiData.Get("exclude_cn_from_sans").(bool) { - if strings.Contains(cn, "@") { - // Note: emails are not disallowed if the role's email protection - // flag is false, because they may well be included for - // informational purposes; it is up to the verifying party to - // ensure that email addresses in a subject alternate name can be - // used for the purpose for which they are presented - emailAddresses = append(emailAddresses, cn) - } else { - // Only add to dnsNames if it's actually a DNS name but convert - // idn first - p := idna.New( - idna.StrictDomainName(true), - idna.VerifyDNSLength(true), - ) - converted, err := p.ToASCII(cn) - if err != nil { - return errutil.UserError{Err: err.Error()} - } - if hostnameRegex.MatchString(converted) { - dnsNames = append(dnsNames, converted) - } - } - } - - if data.csr == nil || !data.role.UseCSRSANs { - cnAltRaw, ok := data.apiData.GetOk("alt_names") - if ok { - cnAlt := strutil.ParseDedupLowercaseAndSortStrings(cnAltRaw.(string), ",") - for _, v := range cnAlt { - if strings.Contains(v, "@") { - emailAddresses = append(emailAddresses, v) - } else { - // Only add to dnsNames if it's actually a DNS name but - // convert idn first - p := idna.New( - idna.StrictDomainName(true), - idna.VerifyDNSLength(true), - ) - converted, err := p.ToASCII(v) - if err != nil { - return errutil.UserError{Err: err.Error()} - } - if hostnameRegex.MatchString(converted) { - dnsNames = append(dnsNames, converted) - } - } - } - } - } - - // Check the CN. This ensures that the CN is checked even if it's - // excluded from SANs. - if cn != "" { - badName := validateNames(data, []string{cn}) - if len(badName) != 0 { - return errutil.UserError{Err: fmt.Sprintf( - "common name %s not allowed by this role", badName)} - } - } - - if ridSerialNumber != "" { - badName := validateSerialNumber(data, ridSerialNumber) - if len(badName) != 0 { - return errutil.UserError{Err: fmt.Sprintf( - "serial_number %s not allowed by this role", badName)} - } - } - - // Check for bad email and/or DNS names - badName := validateNames(data, dnsNames) - if len(badName) != 0 { - return errutil.UserError{Err: fmt.Sprintf( - "subject alternate name %s not allowed by this role", badName)} - } - - badName = validateNames(data, emailAddresses) - if len(badName) != 0 { - return errutil.UserError{Err: fmt.Sprintf( - "email address %s not allowed by this role", badName)} - } - } - - var otherSANs map[string][]string - if sans := data.apiData.Get("other_sans").([]string); len(sans) > 0 { - requested, err := parseOtherSANs(sans) - if err != nil { - return errutil.UserError{Err: errwrap.Wrapf("could not parse requested other SAN: {{err}}", err).Error()} - } - badOID, badName, err := validateOtherSANs(data, requested) - switch { - case err != nil: - return errutil.UserError{Err: err.Error()} - case len(badName) > 0: - return errutil.UserError{Err: fmt.Sprintf( - "other SAN %s not allowed for OID %s by this role", badName, badOID)} - case len(badOID) > 0: - return errutil.UserError{Err: fmt.Sprintf( - "other SAN OID %s not allowed by this role", badOID)} - default: - otherSANs = requested - } - } - - // Get and verify any IP SANs - ipAddresses := []net.IP{} - { - if data.csr != nil && data.role.UseCSRSANs { - if len(data.csr.IPAddresses) > 0 { - if !data.role.AllowIPSANs { - return errutil.UserError{Err: fmt.Sprintf( - "IP Subject Alternative Names are not allowed in this role, but was provided some via CSR")} - } - ipAddresses = data.csr.IPAddresses - } - } else { - ipAlt := data.apiData.Get("ip_sans").([]string) - if len(ipAlt) > 0 { - if !data.role.AllowIPSANs { - return errutil.UserError{Err: fmt.Sprintf( - "IP Subject Alternative Names are not allowed in this role, but was provided %s", ipAlt)} - } - for _, v := range ipAlt { - parsedIP := net.ParseIP(v) - if parsedIP == nil { - return errutil.UserError{Err: fmt.Sprintf( - "the value '%s' is not a valid IP address", v)} - } - ipAddresses = append(ipAddresses, parsedIP) - } - } - } - } - - URIs := []*url.URL{} - { - if data.csr != nil && data.role.UseCSRSANs { - if len(data.csr.URIs) > 0 { - if len(data.role.AllowedURISANs) == 0 { - return errutil.UserError{Err: fmt.Sprintf( - "URI Subject Alternative Names are not allowed in this role, but were provided via CSR"), - } - } - - // validate uri sans - for _, uri := range data.csr.URIs { - valid := false - for _, allowed := range data.role.AllowedURISANs { - validURI := glob.Glob(allowed, uri.String()) - if validURI { - valid = true - break - } - } - - if !valid { - return errutil.UserError{Err: fmt.Sprintf( - "URI Subject Alternative Names were provided via CSR which are not valid for this role"), - } - } - - URIs = append(URIs, uri) - } - } - } else { - uriAlt := data.apiData.Get("uri_sans").([]string) - if len(uriAlt) > 0 { - if len(data.role.AllowedURISANs) == 0 { - return errutil.UserError{Err: fmt.Sprintf( - "URI Subject Alternative Names are not allowed in this role, but were provided via the API"), - } - } - - for _, uri := range uriAlt { - valid := false - for _, allowed := range data.role.AllowedURISANs { - validURI := glob.Glob(allowed, uri) - if validURI { - valid = true - break - } - } - - if !valid { - return errutil.UserError{Err: fmt.Sprintf( - "URI Subject Alternative Names were provided via CSR which are not valid for this role"), - } - } - - parsedURI, err := url.Parse(uri) - if parsedURI == nil || err != nil { - return errutil.UserError{Err: fmt.Sprintf( - "the provided URI Subject Alternative Name '%s' is not a valid URI", uri), - } - } - - URIs = append(URIs, parsedURI) - } - } - } - } - - subject := pkix.Name{ - CommonName: cn, - SerialNumber: ridSerialNumber, - Country: strutil.RemoveDuplicates(data.role.Country, false), - Organization: strutil.RemoveDuplicates(data.role.Organization, false), - OrganizationalUnit: strutil.RemoveDuplicates(data.role.OU, false), - Locality: strutil.RemoveDuplicates(data.role.Locality, false), - Province: strutil.RemoveDuplicates(data.role.Province, false), - StreetAddress: strutil.RemoveDuplicates(data.role.StreetAddress, false), - PostalCode: strutil.RemoveDuplicates(data.role.PostalCode, false), - } - - // Get the TTL and verify it against the max allowed - var ttl time.Duration - var maxTTL time.Duration - var notAfter time.Time - { - ttl = time.Duration(data.apiData.Get("ttl").(int)) * time.Second - - if ttl == 0 && data.role.TTL > 0 { - ttl = data.role.TTL - } - - if data.role.MaxTTL > 0 { - maxTTL = data.role.MaxTTL - } - - if ttl == 0 { - ttl = b.System().DefaultLeaseTTL() - } - if maxTTL == 0 { - maxTTL = b.System().MaxLeaseTTL() - } - if ttl > maxTTL { - ttl = maxTTL - } - - notAfter = time.Now().Add(ttl) - - // If it's not self-signed, verify that the issued certificate won't be - // valid past the lifetime of the CA certificate - if data.signingBundle != nil && - notAfter.After(data.signingBundle.Certificate.NotAfter) && !data.role.AllowExpirationPastCA { - - return errutil.UserError{Err: fmt.Sprintf( - "cannot satisfy request, as TTL would result in notAfter %s that is beyond the expiration of the CA certificate at %s", notAfter.Format(time.RFC3339Nano), data.signingBundle.Certificate.NotAfter.Format(time.RFC3339Nano))} - } - } - - data.params = &creationParameters{ - Subject: subject, - DNSNames: dnsNames, - EmailAddresses: emailAddresses, - IPAddresses: ipAddresses, - URIs: URIs, - OtherSANs: otherSANs, - KeyType: data.role.KeyType, - KeyBits: data.role.KeyBits, - NotAfter: notAfter, - KeyUsage: x509.KeyUsage(parseKeyUsages(data.role.KeyUsage)), - ExtKeyUsage: parseExtKeyUsages(data.role), - ExtKeyUsageOIDs: data.role.ExtKeyUsageOIDs, - PolicyIdentifiers: data.role.PolicyIdentifiers, - BasicConstraintsValidForNonCA: data.role.BasicConstraintsValidForNonCA, - } - - // Don't deal with URLs or max path length if it's self-signed, as these - // normally come from the signing bundle - if data.signingBundle == nil { - return nil - } - - // This will have been read in from the getURLs function - data.params.URLs = data.signingBundle.URLs - - // If the max path length in the role is not nil, it was specified at - // generation time with the max_path_length parameter; otherwise derive it - // from the signing certificate - if data.role.MaxPathLength != nil { - data.params.MaxPathLength = *data.role.MaxPathLength - } else { - switch { - case data.signingBundle.Certificate.MaxPathLen < 0: - data.params.MaxPathLength = -1 - case data.signingBundle.Certificate.MaxPathLen == 0 && - data.signingBundle.Certificate.MaxPathLenZero: - // The signing function will ensure that we do not issue a CA cert - data.params.MaxPathLength = 0 - default: - // If this takes it to zero, we handle this case later if - // necessary - data.params.MaxPathLength = data.signingBundle.Certificate.MaxPathLen - 1 - } - } - - return nil -} - -// addKeyUsages adds appropriate key usages to the template given the creation -// information -func addKeyUsages(data *dataBundle, certTemplate *x509.Certificate) { - if data.params.IsCA { - certTemplate.KeyUsage = x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign) - return - } - - certTemplate.KeyUsage = data.params.KeyUsage - - if data.params.ExtKeyUsage&anyExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageAny) - } - - if data.params.ExtKeyUsage&serverAuthExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageServerAuth) - } - - if data.params.ExtKeyUsage&clientAuthExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageClientAuth) - } - - if data.params.ExtKeyUsage&codeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageCodeSigning) - } - - if data.params.ExtKeyUsage&emailProtectionExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageEmailProtection) - } - - if data.params.ExtKeyUsage&ipsecEndSystemExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECEndSystem) - } - - if data.params.ExtKeyUsage&ipsecTunnelExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECTunnel) - } - - if data.params.ExtKeyUsage&ipsecUserExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECUser) - } - - if data.params.ExtKeyUsage&timeStampingExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageTimeStamping) - } - - if data.params.ExtKeyUsage&ocspSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageOCSPSigning) - } - - if data.params.ExtKeyUsageµsoftServerGatedCryptoExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftServerGatedCrypto) - } - - if data.params.ExtKeyUsage&netscapeServerGatedCryptoExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageNetscapeServerGatedCrypto) - } - - if data.params.ExtKeyUsageµsoftCommercialCodeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftCommercialCodeSigning) - } - - if data.params.ExtKeyUsageµsoftKernelCodeSigningExtKeyUsage != 0 { - certTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftKernelCodeSigning) - } -} - -// addPolicyIdentifiers adds certificate policies extension -// -func addPolicyIdentifiers(data *dataBundle, certTemplate *x509.Certificate) { - for _, oidstr := range data.params.PolicyIdentifiers { - oid, err := stringToOid(oidstr) - if err == nil { - certTemplate.PolicyIdentifiers = append(certTemplate.PolicyIdentifiers, oid) - } - } -} - -// addExtKeyUsageOids adds custom extended key usage OIDs to certificate -func addExtKeyUsageOids(data *dataBundle, certTemplate *x509.Certificate) { - for _, oidstr := range data.params.ExtKeyUsageOIDs { - oid, err := stringToOid(oidstr) - if err == nil { - certTemplate.UnknownExtKeyUsage = append(certTemplate.UnknownExtKeyUsage, oid) - } - } -} - -// Performs the heavy lifting of creating a certificate. Returns -// a fully-filled-in ParsedCertBundle. -func createCertificate(data *dataBundle) (*certutil.ParsedCertBundle, error) { - var err error - result := &certutil.ParsedCertBundle{} - - serialNumber, err := certutil.GenerateSerialNumber() - if err != nil { - return nil, err - } - - if err := certutil.GeneratePrivateKey(data.params.KeyType, - data.params.KeyBits, - result); err != nil { - return nil, err - } - - subjKeyID, err := certutil.GetSubjKeyID(result.PrivateKey) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error getting subject key ID: %s", err)} - } - - certTemplate := &x509.Certificate{ - SerialNumber: serialNumber, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: data.params.NotAfter, - IsCA: false, - SubjectKeyId: subjKeyID, - Subject: data.params.Subject, - DNSNames: data.params.DNSNames, - EmailAddresses: data.params.EmailAddresses, - IPAddresses: data.params.IPAddresses, - URIs: data.params.URIs, - } - - if err := handleOtherSANs(certTemplate, data.params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - // Add this before calling addKeyUsages - if data.signingBundle == nil { - certTemplate.IsCA = true - } else if data.params.BasicConstraintsValidForNonCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = false - } - - // This will only be filled in from the generation paths - if len(data.params.PermittedDNSDomains) > 0 { - certTemplate.PermittedDNSDomains = data.params.PermittedDNSDomains - certTemplate.PermittedDNSDomainsCritical = true - } - - addPolicyIdentifiers(data, certTemplate) - - addKeyUsages(data, certTemplate) - - addExtKeyUsageOids(data, certTemplate) - - certTemplate.IssuingCertificateURL = data.params.URLs.IssuingCertificates - certTemplate.CRLDistributionPoints = data.params.URLs.CRLDistributionPoints - certTemplate.OCSPServer = data.params.URLs.OCSPServers - - var certBytes []byte - if data.signingBundle != nil { - switch data.signingBundle.PrivateKeyType { - case certutil.RSAPrivateKey: - certTemplate.SignatureAlgorithm = x509.SHA256WithRSA - case certutil.ECPrivateKey: - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256 - } - - caCert := data.signingBundle.Certificate - certTemplate.AuthorityKeyId = caCert.SubjectKeyId - - certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, caCert, result.PrivateKey.Public(), data.signingBundle.PrivateKey) - } else { - // Creating a self-signed root - if data.params.MaxPathLength == 0 { - certTemplate.MaxPathLen = 0 - certTemplate.MaxPathLenZero = true - } else { - certTemplate.MaxPathLen = data.params.MaxPathLength - } - - switch data.params.KeyType { - case "rsa": - certTemplate.SignatureAlgorithm = x509.SHA256WithRSA - case "ec": - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256 - } - - certTemplate.AuthorityKeyId = subjKeyID - certTemplate.BasicConstraintsValid = true - certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, result.PrivateKey.Public(), result.PrivateKey) - } - - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CertificateBytes = certBytes - result.Certificate, err = x509.ParseCertificate(certBytes) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)} - } - - if data.signingBundle != nil { - if len(data.signingBundle.Certificate.AuthorityKeyId) > 0 && - !bytes.Equal(data.signingBundle.Certificate.AuthorityKeyId, data.signingBundle.Certificate.SubjectKeyId) { - - result.CAChain = []*certutil.CertBlock{ - &certutil.CertBlock{ - Certificate: data.signingBundle.Certificate, - Bytes: data.signingBundle.CertificateBytes, - }, - } - result.CAChain = append(result.CAChain, data.signingBundle.CAChain...) - } - } - - return result, nil -} - -// Creates a CSR. This is currently only meant for use when -// generating an intermediate certificate. -func createCSR(data *dataBundle) (*certutil.ParsedCSRBundle, error) { - var err error - result := &certutil.ParsedCSRBundle{} - - if err := certutil.GeneratePrivateKey(data.params.KeyType, - data.params.KeyBits, - result); err != nil { - return nil, err - } - - // Like many root CAs, other information is ignored - csrTemplate := &x509.CertificateRequest{ - Subject: data.params.Subject, - DNSNames: data.params.DNSNames, - EmailAddresses: data.params.EmailAddresses, - IPAddresses: data.params.IPAddresses, - URIs: data.params.URIs, - } - - if err := handleOtherCSRSANs(csrTemplate, data.params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - if data.apiData != nil && data.apiData.Get("add_basic_constraints").(bool) { - type basicConstraints struct { - IsCA bool `asn1:"optional"` - MaxPathLen int `asn1:"optional,default:-1"` - } - val, err := asn1.Marshal(basicConstraints{IsCA: true, MaxPathLen: -1}) - if err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling basic constraints: {{err}}", err).Error()} - } - ext := pkix.Extension{ - Id: oidExtensionBasicConstraints, - Value: val, - Critical: true, - } - csrTemplate.ExtraExtensions = append(csrTemplate.ExtraExtensions, ext) - } - - switch data.params.KeyType { - case "rsa": - csrTemplate.SignatureAlgorithm = x509.SHA256WithRSA - case "ec": - csrTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256 - } - - csr, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, result.PrivateKey) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CSRBytes = csr - result.CSR, err = x509.ParseCertificateRequest(csr) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %v", err)} - } - - return result, nil -} - -// Performs the heavy lifting of generating a certificate from a CSR. -// Returns a ParsedCertBundle sans private keys. -func signCertificate(data *dataBundle) (*certutil.ParsedCertBundle, error) { - switch { - case data == nil: - return nil, errutil.UserError{Err: "nil data bundle given to signCertificate"} - case data.params == nil: - return nil, errutil.UserError{Err: "nil parameters given to signCertificate"} - case data.signingBundle == nil: - return nil, errutil.UserError{Err: "nil signing bundle given to signCertificate"} - case data.csr == nil: - return nil, errutil.UserError{Err: "nil csr given to signCertificate"} - } - - err := data.csr.CheckSignature() - if err != nil { - return nil, errutil.UserError{Err: "request signature invalid"} - } - - result := &certutil.ParsedCertBundle{} - - serialNumber, err := certutil.GenerateSerialNumber() - if err != nil { - return nil, err - } - - marshaledKey, err := x509.MarshalPKIXPublicKey(data.csr.PublicKey) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error marshalling public key: %s", err)} - } - subjKeyID := sha1.Sum(marshaledKey) - - caCert := data.signingBundle.Certificate - - certTemplate := &x509.Certificate{ - SerialNumber: serialNumber, - Subject: data.params.Subject, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: data.params.NotAfter, - SubjectKeyId: subjKeyID[:], - AuthorityKeyId: caCert.SubjectKeyId, - } - - switch data.signingBundle.PrivateKeyType { - case certutil.RSAPrivateKey: - certTemplate.SignatureAlgorithm = x509.SHA256WithRSA - case certutil.ECPrivateKey: - certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256 - } - - if data.params.UseCSRValues { - certTemplate.Subject = data.csr.Subject - certTemplate.Subject.ExtraNames = certTemplate.Subject.Names - - certTemplate.DNSNames = data.csr.DNSNames - certTemplate.EmailAddresses = data.csr.EmailAddresses - certTemplate.IPAddresses = data.csr.IPAddresses - certTemplate.URIs = data.csr.URIs - - for _, name := range data.csr.Extensions { - if !name.Id.Equal(oidExtensionBasicConstraints) { - certTemplate.ExtraExtensions = append(certTemplate.ExtraExtensions, name) - } - } - - } else { - certTemplate.DNSNames = data.params.DNSNames - certTemplate.EmailAddresses = data.params.EmailAddresses - certTemplate.IPAddresses = data.params.IPAddresses - certTemplate.URIs = data.csr.URIs - } - - if err := handleOtherSANs(certTemplate, data.params.OtherSANs); err != nil { - return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()} - } - - addPolicyIdentifiers(data, certTemplate) - - addKeyUsages(data, certTemplate) - - addExtKeyUsageOids(data, certTemplate) - - var certBytes []byte - - certTemplate.IssuingCertificateURL = data.params.URLs.IssuingCertificates - certTemplate.CRLDistributionPoints = data.params.URLs.CRLDistributionPoints - certTemplate.OCSPServer = data.signingBundle.URLs.OCSPServers - - if data.params.IsCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = true - - if data.signingBundle.Certificate.MaxPathLen == 0 && - data.signingBundle.Certificate.MaxPathLenZero { - return nil, errutil.UserError{Err: "signing certificate has a max path length of zero, and cannot issue further CA certificates"} - } - - certTemplate.MaxPathLen = data.params.MaxPathLength - if certTemplate.MaxPathLen == 0 { - certTemplate.MaxPathLenZero = true - } - } else if data.params.BasicConstraintsValidForNonCA { - certTemplate.BasicConstraintsValid = true - certTemplate.IsCA = false - } - - if len(data.params.PermittedDNSDomains) > 0 { - certTemplate.PermittedDNSDomains = data.params.PermittedDNSDomains - certTemplate.PermittedDNSDomainsCritical = true - } - - certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, caCert, data.csr.PublicKey, data.signingBundle.PrivateKey) - - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)} - } - - result.CertificateBytes = certBytes - result.Certificate, err = x509.ParseCertificate(certBytes) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)} - } - - result.CAChain = data.signingBundle.GetCAChain() - - return result, nil -} - -func convertRespToPKCS8(resp *logical.Response) error { - privRaw, ok := resp.Data["private_key"] - if !ok { - return nil - } - priv, ok := privRaw.(string) - if !ok { - return fmt.Errorf("error converting response to pkcs8: could not parse original value as string") - } - - privKeyTypeRaw, ok := resp.Data["private_key_type"] - if !ok { - return fmt.Errorf("error converting response to pkcs8: %q not found in response", "private_key_type") - } - privKeyType, ok := privKeyTypeRaw.(certutil.PrivateKeyType) - if !ok { - return fmt.Errorf("error converting response to pkcs8: could not parse original type value as string") - } - - var keyData []byte - var pemUsed bool - var err error - var signer crypto.Signer - - block, _ := pem.Decode([]byte(priv)) - if block == nil { - keyData, err = base64.StdEncoding.DecodeString(priv) - if err != nil { - return errwrap.Wrapf("error converting response to pkcs8: error decoding original value: {{err}}", err) - } - } else { - keyData = block.Bytes - pemUsed = true - } - - switch privKeyType { - case certutil.RSAPrivateKey: - signer, err = x509.ParsePKCS1PrivateKey(keyData) - case certutil.ECPrivateKey: - signer, err = x509.ParseECPrivateKey(keyData) - default: - return fmt.Errorf("unknown private key type %q", privKeyType) - } - if err != nil { - return errwrap.Wrapf("error converting response to pkcs8: error parsing previous key: {{err}}", err) - } - - keyData, err = x509.MarshalPKCS8PrivateKey(signer) - if err != nil { - return errwrap.Wrapf("error converting response to pkcs8: error marshaling pkcs8 key: {{err}}", err) - } - - if pemUsed { - block.Type = "PRIVATE KEY" - block.Bytes = keyData - resp.Data["private_key"] = strings.TrimSpace(string(pem.EncodeToMemory(block))) - } else { - resp.Data["private_key"] = base64.StdEncoding.EncodeToString(keyData) - } - - return nil -} - -func handleOtherCSRSANs(in *x509.CertificateRequest, sans map[string][]string) error { - certTemplate := &x509.Certificate{ - DNSNames: in.DNSNames, - IPAddresses: in.IPAddresses, - EmailAddresses: in.EmailAddresses, - URIs: in.URIs, - } - if err := handleOtherSANs(certTemplate, sans); err != nil { - return err - } - if len(certTemplate.ExtraExtensions) > 0 { - for _, v := range certTemplate.ExtraExtensions { - in.ExtraExtensions = append(in.ExtraExtensions, v) - } - } - return nil -} - -func handleOtherSANs(in *x509.Certificate, sans map[string][]string) error { - // If other SANs is empty we return which causes normal Go stdlib parsing - // of the other SAN types - if len(sans) == 0 { - return nil - } - - var rawValues []asn1.RawValue - - // We need to generate an IMPLICIT sequence for compatibility with OpenSSL - // -- it's an open question what the default for RFC 5280 actually is, see - // https://github.com/openssl/openssl/issues/5091 -- so we have to use - // cryptobyte because using the asn1 package's marshaling always produces - // an EXPLICIT sequence. Note that asn1 is way too magical according to - // agl, and cryptobyte is modeled after the CBB/CBS bits that agl put into - // boringssl. - for oid, vals := range sans { - for _, val := range vals { - var b cryptobyte.Builder - oidStr, err := stringToOid(oid) - if err != nil { - return err - } - b.AddASN1ObjectIdentifier(oidStr) - b.AddASN1(cbbasn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) { - b.AddASN1(cbbasn1.UTF8String, func(b *cryptobyte.Builder) { - b.AddBytes([]byte(val)) - }) - }) - m, err := b.Bytes() - if err != nil { - return err - } - rawValues = append(rawValues, asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: m}) - } - } - - // If other SANs is empty we return which causes normal Go stdlib parsing - // of the other SAN types - if len(rawValues) == 0 { - return nil - } - - // Append any existing SANs, sans marshalling - rawValues = append(rawValues, marshalSANs(in.DNSNames, in.EmailAddresses, in.IPAddresses, in.URIs)...) - - // Marshal and add to ExtraExtensions - ext := pkix.Extension{ - // This is the defined OID for subjectAltName - Id: asn1.ObjectIdentifier{2, 5, 29, 17}, - } - var err error - ext.Value, err = asn1.Marshal(rawValues) - if err != nil { - return err - } - in.ExtraExtensions = append(in.ExtraExtensions, ext) - - return nil -} - -// Note: Taken from the Go source code since it's not public, and used in the -// modified function below (which also uses these consts upstream) -const ( - nameTypeEmail = 1 - nameTypeDNS = 2 - nameTypeURI = 6 - nameTypeIP = 7 -) - -// Note: Taken from the Go source code since it's not public, plus changed to not marshal -// marshalSANs marshals a list of addresses into a the contents of an X.509 -// SubjectAlternativeName extension. -func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) []asn1.RawValue { - var rawValues []asn1.RawValue - for _, name := range dnsNames { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)}) - } - for _, email := range emailAddresses { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)}) - } - for _, rawIP := range ipAddresses { - // If possible, we always want to encode IPv4 addresses in 4 bytes. - ip := rawIP.To4() - if ip == nil { - ip = rawIP - } - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip}) - } - for _, uri := range uris { - rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())}) - } - return rawValues -} - -func stringToOid(in string) (asn1.ObjectIdentifier, error) { - split := strings.Split(in, ".") - ret := make(asn1.ObjectIdentifier, 0, len(split)) - for _, v := range split { - i, err := strconv.Atoi(v) - if err != nil { - return nil, err - } - ret = append(ret, i) - } - return asn1.ObjectIdentifier(ret), nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/crl_util.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/crl_util.go deleted file mode 100644 index e5b873fb6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/crl_util.go +++ /dev/null @@ -1,238 +0,0 @@ -package pki - -import ( - "context" - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" -) - -type revocationInfo struct { - CertificateBytes []byte `json:"certificate_bytes"` - RevocationTime int64 `json:"revocation_time"` - RevocationTimeUTC time.Time `json:"revocation_time_utc"` -} - -// Revokes a cert, and tries to be smart about error recovery -func revokeCert(ctx context.Context, b *backend, req *logical.Request, serial string, fromLease bool) (*logical.Response, error) { - // As this backend is self-contained and this function does not hook into - // third parties to manage users or resources, if the mount is tainted, - // revocation doesn't matter anyways -- the CRL that would be written will - // be immediately blown away by the view being cleared. So we can simply - // fast path a successful exit. - if b.System().Tainted() { - return nil, nil - } - - signingBundle, caErr := fetchCAInfo(ctx, req) - switch caErr.(type) { - case errutil.UserError: - return logical.ErrorResponse(fmt.Sprintf("could not fetch the CA certificate: %s", caErr)), nil - case errutil.InternalError: - return nil, fmt.Errorf("error fetching CA certificate: %s", caErr) - } - if signingBundle == nil { - return nil, errors.New("CA info not found") - } - colonSerial := strings.Replace(strings.ToLower(serial), "-", ":", -1) - if colonSerial == certutil.GetHexFormatted(signingBundle.Certificate.SerialNumber.Bytes(), ":") { - return logical.ErrorResponse("adding CA to CRL is not allowed"), nil - } - - alreadyRevoked := false - var revInfo revocationInfo - - revEntry, err := fetchCertBySerial(ctx, req, "revoked/", serial) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - if revEntry != nil { - // Set the revocation info to the existing values - alreadyRevoked = true - err = revEntry.DecodeJSON(&revInfo) - if err != nil { - return nil, fmt.Errorf("error decoding existing revocation info") - } - } - - if !alreadyRevoked { - certEntry, err := fetchCertBySerial(ctx, req, "certs/", serial) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - if certEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("certificate with serial %s not found", serial)), nil - } - - cert, err := x509.ParseCertificate(certEntry.Value) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - if cert == nil { - return nil, fmt.Errorf("got a nil certificate") - } - - // Add a little wiggle room because leases are stored with a second - // granularity - if cert.NotAfter.Before(time.Now().Add(2 * time.Second)) { - return nil, nil - } - - // Compatibility: Don't revoke CAs if they had leases. New CAs going - // forward aren't issued leases. - if cert.IsCA && fromLease { - return nil, nil - } - - currTime := time.Now() - revInfo.CertificateBytes = certEntry.Value - revInfo.RevocationTime = currTime.Unix() - revInfo.RevocationTimeUTC = currTime.UTC() - - revEntry, err = logical.StorageEntryJSON("revoked/"+normalizeSerial(serial), revInfo) - if err != nil { - return nil, fmt.Errorf("error creating revocation entry") - } - - err = req.Storage.Put(ctx, revEntry) - if err != nil { - return nil, fmt.Errorf("error saving revoked certificate to new location") - } - - } - - crlErr := buildCRL(ctx, b, req, false) - switch crlErr.(type) { - case errutil.UserError: - return logical.ErrorResponse(fmt.Sprintf("Error during CRL building: %s", crlErr)), nil - case errutil.InternalError: - return nil, errwrap.Wrapf("error encountered during CRL building: {{err}}", crlErr) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "revocation_time": revInfo.RevocationTime, - }, - } - if !revInfo.RevocationTimeUTC.IsZero() { - resp.Data["revocation_time_rfc3339"] = revInfo.RevocationTimeUTC.Format(time.RFC3339Nano) - } - return resp, nil -} - -// Builds a CRL by going through the list of revoked certificates and building -// a new CRL with the stored revocation times and serial numbers. -func buildCRL(ctx context.Context, b *backend, req *logical.Request, forceNew bool) error { - crlInfo, err := b.CRL(ctx, req.Storage) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error fetching CRL config information: %s", err)} - } - - crlLifetime := b.crlLifetime - var revokedCerts []pkix.RevokedCertificate - var revInfo revocationInfo - var revokedSerials []string - - if crlInfo != nil { - if crlInfo.Expiry != "" { - crlDur, err := time.ParseDuration(crlInfo.Expiry) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error parsing CRL duration of %s", crlInfo.Expiry)} - } - crlLifetime = crlDur - } - - if crlInfo.Disable { - if !forceNew { - return nil - } - goto WRITE - } - } - - revokedSerials, err = req.Storage.List(ctx, "revoked/") - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error fetching list of revoked certs: %s", err)} - } - - for _, serial := range revokedSerials { - revokedEntry, err := req.Storage.Get(ctx, "revoked/"+serial) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("unable to fetch revoked cert with serial %s: %s", serial, err)} - } - if revokedEntry == nil { - return errutil.InternalError{Err: fmt.Sprintf("revoked certificate entry for serial %s is nil", serial)} - } - if revokedEntry.Value == nil || len(revokedEntry.Value) == 0 { - // TODO: In this case, remove it and continue? How likely is this to - // happen? Alternately, could skip it entirely, or could implement a - // delete function so that there is a way to remove these - return errutil.InternalError{Err: fmt.Sprintf("found revoked serial but actual certificate is empty")} - } - - err = revokedEntry.DecodeJSON(&revInfo) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error decoding revocation entry for serial %s: %s", serial, err)} - } - - revokedCert, err := x509.ParseCertificate(revInfo.CertificateBytes) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("unable to parse stored revoked certificate with serial %s: %s", serial, err)} - } - - // NOTE: We have to change this to UTC time because the CRL standard - // mandates it but Go will happily encode the CRL without this. - newRevCert := pkix.RevokedCertificate{ - SerialNumber: revokedCert.SerialNumber, - } - if !revInfo.RevocationTimeUTC.IsZero() { - newRevCert.RevocationTime = revInfo.RevocationTimeUTC - } else { - newRevCert.RevocationTime = time.Unix(revInfo.RevocationTime, 0).UTC() - } - revokedCerts = append(revokedCerts, newRevCert) - } - -WRITE: - signingBundle, caErr := fetchCAInfo(ctx, req) - switch caErr.(type) { - case errutil.UserError: - return errutil.UserError{Err: fmt.Sprintf("could not fetch the CA certificate: %s", caErr)} - case errutil.InternalError: - return errutil.InternalError{Err: fmt.Sprintf("error fetching CA certificate: %s", caErr)} - } - - crlBytes, err := signingBundle.Certificate.CreateCRL(rand.Reader, signingBundle.PrivateKey, revokedCerts, time.Now(), time.Now().Add(crlLifetime)) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error creating new CRL: %s", err)} - } - - err = req.Storage.Put(ctx, &logical.StorageEntry{ - Key: "crl", - Value: crlBytes, - }) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error storing CRL: %s", err)} - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/fields.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/fields.go deleted file mode 100644 index dee7779be..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/fields.go +++ /dev/null @@ -1,232 +0,0 @@ -package pki - -import "github.com/hashicorp/vault/logical/framework" - -// addIssueAndSignCommonFields adds fields common to both CA and non-CA issuing -// and signing -func addIssueAndSignCommonFields(fields map[string]*framework.FieldSchema) map[string]*framework.FieldSchema { - fields["exclude_cn_from_sans"] = &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: `If true, the Common Name will not be -included in DNS or Email Subject Alternate Names. -Defaults to false (CN is included).`, - } - - fields["format"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "pem", - Description: `Format for returned data. Can be "pem", "der", -or "pem_bundle". If "pem_bundle" any private -key and issuing cert will be appended to the -certificate pem. Defaults to "pem".`, - } - - fields["private_key_format"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "der", - Description: `Format for the returned private key. -Generally the default will be controlled by the "format" -parameter as either base64-encoded DER or PEM-encoded DER. -However, this can be set to "pkcs8" to have the returned -private key contain base64-encoded pkcs8 or PEM-encoded -pkcs8 instead. Defaults to "der".`, - } - - fields["ip_sans"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `The requested IP SANs, if any, in a -comma-delimited list`, - } - - fields["uri_sans"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `The requested URI SANs, if any, in a -comma-delimited list.`, - } - - fields["other_sans"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Requested other SANs, in an array with the format -;UTF8: for each entry.`, - } - - return fields -} - -// addNonCACommonFields adds fields with help text specific to non-CA -// certificate issuing and signing -func addNonCACommonFields(fields map[string]*framework.FieldSchema) map[string]*framework.FieldSchema { - fields = addIssueAndSignCommonFields(fields) - - fields["role"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The desired role with configuration for this -request`, - } - - fields["common_name"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested common name; if you want more than -one, specify the alternative names in the -alt_names map. If email protection is enabled -in the role, this may be an email address.`, - } - - fields["alt_names"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested Subject Alternative Names, if any, -in a comma-delimited list. If email protection -is enabled for the role, this may contain -email addresses.`, - } - - fields["serial_number"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested serial number, if any. If you want -more than one, specify alternative names in -the alt_names map using OID 2.5.4.5.`, - } - - fields["ttl"] = &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `The requested Time To Live for the certificate; -sets the expiration date. If not specified -the role default, backend default, or system -default TTL is used, in that order. Cannot -be larger than the role max TTL.`, - } - - return fields -} - -// addCACommonFields adds fields with help text specific to CA -// certificate issuing and signing -func addCACommonFields(fields map[string]*framework.FieldSchema) map[string]*framework.FieldSchema { - fields = addIssueAndSignCommonFields(fields) - - fields["alt_names"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested Subject Alternative Names, if any, -in a comma-delimited list. May contain both -DNS names and email addresses.`, - } - - fields["common_name"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested common name; if you want more than -one, specify the alternative names in the alt_names -map. If not specified when signing, the common -name will be taken from the CSR; other names -must still be specified in alt_names or ip_sans.`, - } - - fields["ttl"] = &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `The requested Time To Live for the certificate; -sets the expiration date. If not specified -the role default, backend default, or system -default TTL is used, in that order. Cannot -be larger than the mount max TTL. Note: -this only has an effect when generating -a CA cert or signing a CA cert, not when -generating a CSR for an intermediate CA.`, - } - - fields["ou"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, OU (OrganizationalUnit) will be set to -this value.`, - } - - fields["organization"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, O (Organization) will be set to -this value.`, - } - - fields["country"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Country will be set to -this value.`, - } - - fields["locality"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Locality will be set to -this value.`, - } - - fields["province"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Province will be set to -this value.`, - } - - fields["street_address"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Street Address will be set to -this value.`, - } - - fields["postal_code"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Postal Code will be set to -this value.`, - } - - fields["serial_number"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The requested serial number, if any. If you want -more than one, specify alternative names in -the alt_names map using OID 2.5.4.5.`, - } - - return fields -} - -// addCAKeyGenerationFields adds fields with help text specific to CA key -// generation and exporting -func addCAKeyGenerationFields(fields map[string]*framework.FieldSchema) map[string]*framework.FieldSchema { - fields["exported"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Must be "internal" or "exported". If set to -"exported", the generated private key will be -returned. This is your *only* chance to retrieve -the private key!`, - } - - fields["key_bits"] = &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 2048, - Description: `The number of bits to use. You will almost -certainly want to change this if you adjust -the key_type.`, - } - - fields["key_type"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "rsa", - Description: `The type of key to use; defaults to RSA. "rsa" -and "ec" are the only valid values.`, - } - - return fields -} - -// addCAIssueFields adds fields common to CA issuing, e.g. when returning -// an actual certificate -func addCAIssueFields(fields map[string]*framework.FieldSchema) map[string]*framework.FieldSchema { - fields["max_path_length"] = &framework.FieldSchema{ - Type: framework.TypeInt, - Default: -1, - Description: "The maximum allowable path length", - } - - fields["permitted_dns_domains"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Domains for which this certificate is allowed to sign or issue child certificates. If set, all DNS names (subject and alt) on child certs must be exact matches or subsets of the given domains (see https://tools.ietf.org/html/rfc5280#section-4.2.1.10).`, - } - - return fields -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_ca.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_ca.go deleted file mode 100644 index 3d2070f9e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_ca.go +++ /dev/null @@ -1,135 +0,0 @@ -package pki - -import ( - "context" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigCA(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/ca", - Fields: map[string]*framework.FieldSchema{ - "pem_bundle": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `PEM-format, concatenated unencrypted -secret key and certificate.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathCAWrite, - }, - - HelpSynopsis: pathConfigCAHelpSyn, - HelpDescription: pathConfigCAHelpDesc, - } -} - -func (b *backend) pathCAWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - pemBundle := data.Get("pem_bundle").(string) - - if pemBundle == "" { - return logical.ErrorResponse("'pem_bundle' was empty"), nil - } - - parsedBundle, err := certutil.ParsePEMBundle(pemBundle) - if err != nil { - switch err.(type) { - case errutil.InternalError: - return nil, err - default: - return logical.ErrorResponse(err.Error()), nil - } - } - - if parsedBundle.PrivateKey == nil || - parsedBundle.PrivateKeyType == certutil.UnknownPrivateKey { - return logical.ErrorResponse("private key not found in the PEM bundle"), nil - } - - if parsedBundle.Certificate == nil { - return logical.ErrorResponse("no certificate found in the PEM bundle"), nil - } - - if !parsedBundle.Certificate.IsCA { - return logical.ErrorResponse("the given certificate is not marked for CA use and cannot be used with this backend"), nil - } - - cb, err := parsedBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw values into cert bundle: {{err}}", err) - } - - entry, err := logical.StorageEntryJSON("config/ca_bundle", cb) - if err != nil { - return nil, err - } - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - // For ease of later use, also store just the certificate at a known - // location, plus a fresh CRL - entry.Key = "ca" - entry.Value = parsedBundle.CertificateBytes - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - err = buildCRL(ctx, b, req, true) - - return nil, err -} - -const pathConfigCAHelpSyn = ` -Set the CA certificate and private key used for generated credentials. -` - -const pathConfigCAHelpDesc = ` -This sets the CA information used for credentials generated by this -by this mount. This must be a PEM-format, concatenated unencrypted -secret key and certificate. - -For security reasons, the secret key cannot be retrieved later. -` - -const pathConfigCAGenerateHelpSyn = ` -Generate a new CA certificate and private key used for signing. -` - -const pathConfigCAGenerateHelpDesc = ` -This path generates a CA certificate and private key to be used for -credentials generated by this mount. The path can either -end in "internal" or "exported"; this controls whether the -unencrypted private key is exported after generation. This will -be your only chance to export the private key; for security reasons -it cannot be read or exported later. - -If the "type" option is set to "self-signed", the generated -certificate will be a self-signed root CA. Otherwise, this mount -will act as an intermediate CA; a CSR will be returned, to be signed -by your chosen CA (which could be another mount of this backend). -Note that the CRL path will be set to this mount's CRL path; if you -need further customization it is recommended that you create a CSR -separately and get it signed. Either way, use the "config/ca/set" -endpoint to load the signed certificate into Vault. -` - -const pathConfigCASignHelpSyn = ` -Generate a signed CA certificate from a CSR. -` - -const pathConfigCASignHelpDesc = ` -This path generates a CA certificate to be used for credentials -generated by the certificate's destination mount. - -Use the "config/ca/set" endpoint to load the signed certificate -into Vault another Vault mount. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_crl.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_crl.go deleted file mode 100644 index 8e6ccbbb4..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_crl.go +++ /dev/null @@ -1,133 +0,0 @@ -package pki - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// CRLConfig holds basic CRL configuration information -type crlConfig struct { - Expiry string `json:"expiry" mapstructure:"expiry"` - Disable bool `json:"disable"` -} - -func pathConfigCRL(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/crl", - Fields: map[string]*framework.FieldSchema{ - "expiry": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The amount of time the generated CRL should be -valid; defaults to 72 hours`, - Default: "72h", - }, - "disable": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set to true, disables generating the CRL entirely.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCRLRead, - logical.UpdateOperation: b.pathCRLWrite, - }, - - HelpSynopsis: pathConfigCRLHelpSyn, - HelpDescription: pathConfigCRLHelpDesc, - } -} - -func (b *backend) CRL(ctx context.Context, s logical.Storage) (*crlConfig, error) { - entry, err := s.Get(ctx, "config/crl") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result crlConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathCRLRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - config, err := b.CRL(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "expiry": config.Expiry, - "disable": config.Disable, - }, - }, nil -} - -func (b *backend) pathCRLWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - config, err := b.CRL(ctx, req.Storage) - if err != nil { - return nil, err - } - if config == nil { - config = &crlConfig{} - } - - if expiryRaw, ok := d.GetOk("expiry"); ok { - expiry := expiryRaw.(string) - _, err := time.ParseDuration(expiry) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("given expiry could not be decoded: %s", err)), nil - } - config.Expiry = expiry - } - - var oldDisable bool - if disableRaw, ok := d.GetOk("disable"); ok { - oldDisable = config.Disable - config.Disable = disableRaw.(bool) - } - - entry, err := logical.StorageEntryJSON("config/crl", config) - if err != nil { - return nil, err - } - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - if oldDisable != config.Disable { - // It wasn't disabled but now it is, rotate - crlErr := buildCRL(ctx, b, req, true) - switch crlErr.(type) { - case errutil.UserError: - return logical.ErrorResponse(fmt.Sprintf("Error during CRL building: %s", crlErr)), nil - case errutil.InternalError: - return nil, errwrap.Wrapf("error encountered during CRL building: {{err}}", crlErr) - } - } - - return nil, nil -} - -const pathConfigCRLHelpSyn = ` -Configure the CRL expiration. -` - -const pathConfigCRLHelpDesc = ` -This endpoint allows configuration of the CRL lifetime. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_urls.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_urls.go deleted file mode 100644 index e3a0d6f96..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_config_urls.go +++ /dev/null @@ -1,162 +0,0 @@ -package pki - -import ( - "context" - "fmt" - - "github.com/asaskevich/govalidator" - "github.com/fatih/structs" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigURLs(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/urls", - Fields: map[string]*framework.FieldSchema{ - "issuing_certificates": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of URLs to be used -for the issuing certificate attribute`, - }, - - "crl_distribution_points": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of URLs to be used -for the CRL distribution points attribute`, - }, - - "ocsp_servers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma-separated list of URLs to be used -for the OCSP servers attribute`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathWriteURL, - logical.ReadOperation: b.pathReadURL, - }, - - HelpSynopsis: pathConfigURLsHelpSyn, - HelpDescription: pathConfigURLsHelpDesc, - } -} - -func validateURLs(urls []string) string { - for _, curr := range urls { - if !govalidator.IsURL(curr) { - return curr - } - } - - return "" -} - -func getURLs(ctx context.Context, req *logical.Request) (*urlEntries, error) { - entry, err := req.Storage.Get(ctx, "urls") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var entries urlEntries - if err := entry.DecodeJSON(&entries); err != nil { - return nil, err - } - - return &entries, nil -} - -func writeURLs(ctx context.Context, req *logical.Request, entries *urlEntries) error { - entry, err := logical.StorageEntryJSON("urls", entries) - if err != nil { - return err - } - if entry == nil { - return fmt.Errorf("unable to marshal entry into JSON") - } - - err = req.Storage.Put(ctx, entry) - if err != nil { - return err - } - - return nil -} - -func (b *backend) pathReadURL(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entries, err := getURLs(ctx, req) - if err != nil { - return nil, err - } - if entries == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: structs.New(entries).Map(), - } - - return resp, nil -} - -func (b *backend) pathWriteURL(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entries, err := getURLs(ctx, req) - if err != nil { - return nil, err - } - if entries == nil { - entries = &urlEntries{ - IssuingCertificates: []string{}, - CRLDistributionPoints: []string{}, - OCSPServers: []string{}, - } - } - - if urlsInt, ok := data.GetOk("issuing_certificates"); ok { - entries.IssuingCertificates = urlsInt.([]string) - if badURL := validateURLs(entries.IssuingCertificates); badURL != "" { - return logical.ErrorResponse(fmt.Sprintf( - "invalid URL found in issuing certificates: %s", badURL)), nil - } - } - if urlsInt, ok := data.GetOk("crl_distribution_points"); ok { - entries.CRLDistributionPoints = urlsInt.([]string) - if badURL := validateURLs(entries.CRLDistributionPoints); badURL != "" { - return logical.ErrorResponse(fmt.Sprintf( - "invalid URL found in CRL distribution points: %s", badURL)), nil - } - } - if urlsInt, ok := data.GetOk("ocsp_servers"); ok { - entries.OCSPServers = urlsInt.([]string) - if badURL := validateURLs(entries.OCSPServers); badURL != "" { - return logical.ErrorResponse(fmt.Sprintf( - "invalid URL found in OCSP servers: %s", badURL)), nil - } - } - - return nil, writeURLs(ctx, req, entries) -} - -type urlEntries struct { - IssuingCertificates []string `json:"issuing_certificates" structs:"issuing_certificates" mapstructure:"issuing_certificates"` - CRLDistributionPoints []string `json:"crl_distribution_points" structs:"crl_distribution_points" mapstructure:"crl_distribution_points"` - OCSPServers []string `json:"ocsp_servers" structs:"ocsp_servers" mapstructure:"ocsp_servers"` -} - -const pathConfigURLsHelpSyn = ` -Set the URLs for the issuing CA, CRL distribution points, and OCSP servers. -` - -const pathConfigURLsHelpDesc = ` -This path allows you to set the issuing CA, CRL distribution points, and -OCSP server URLs that will be encoded into issued certificates. If these -values are not set, no such information will be encoded in the issued -certificates. To delete URLs, simply re-set the appropriate value with an -empty string. - -Multiple URLs can be specified for each type; use commas to separate them. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_fetch.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_fetch.go deleted file mode 100644 index a38367ac6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_fetch.go +++ /dev/null @@ -1,276 +0,0 @@ -package pki - -import ( - "context" - "encoding/pem" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Returns the CA in raw format -func pathFetchCA(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `ca(/pem)?`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchRead, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -// Returns the CA chain -func pathFetchCAChain(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `(cert/)?ca_chain`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchRead, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -// Returns the CRL in raw format -func pathFetchCRL(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `crl(/pem)?`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchRead, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -// Returns any valid (non-revoked) cert. Since "ca" fits the pattern, this path -// also handles returning the CA cert in a non-raw format. -func pathFetchValid(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `cert/(?P[0-9A-Fa-f-:]+)`, - Fields: map[string]*framework.FieldSchema{ - "serial": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Certificate serial number, in colon- or -hyphen-separated octal`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchRead, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -// This returns the CRL in a non-raw format -func pathFetchCRLViaCertPath(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `cert/crl`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchRead, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -// This returns the list of serial numbers for certs -func pathFetchListCerts(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "certs/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathFetchCertList, - }, - - HelpSynopsis: pathFetchHelpSyn, - HelpDescription: pathFetchHelpDesc, - } -} - -func (b *backend) pathFetchCertList(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) { - entries, err := req.Storage.List(ctx, "certs/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathFetchRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) { - var serial, pemType, contentType string - var certEntry, revokedEntry *logical.StorageEntry - var funcErr error - var certificate []byte - var revocationTime int64 - response = &logical.Response{ - Data: map[string]interface{}{}, - } - - // Some of these need to return raw and some non-raw; - // this is basically handled by setting contentType or not. - // Errors don't cause an immediate exit, because the raw - // paths still need to return raw output. - - switch { - case req.Path == "ca" || req.Path == "ca/pem": - serial = "ca" - contentType = "application/pkix-cert" - if req.Path == "ca/pem" { - pemType = "CERTIFICATE" - } - case req.Path == "ca_chain" || req.Path == "cert/ca_chain": - serial = "ca_chain" - if req.Path == "ca_chain" { - contentType = "application/pkix-cert" - } - case req.Path == "crl" || req.Path == "crl/pem": - serial = "crl" - contentType = "application/pkix-crl" - if req.Path == "crl/pem" { - pemType = "X509 CRL" - } - case req.Path == "cert/crl": - serial = "crl" - pemType = "X509 CRL" - default: - serial = data.Get("serial").(string) - pemType = "CERTIFICATE" - } - if len(serial) == 0 { - response = logical.ErrorResponse("The serial number must be provided") - goto reply - } - - if serial == "ca_chain" { - caInfo, err := fetchCAInfo(ctx, req) - switch err.(type) { - case errutil.UserError: - response = logical.ErrorResponse(err.Error()) - goto reply - case errutil.InternalError: - retErr = err - goto reply - } - - caChain := caInfo.GetCAChain() - var certStr string - for _, ca := range caChain { - block := pem.Block{ - Type: "CERTIFICATE", - Bytes: ca.Bytes, - } - certStr = strings.Join([]string{certStr, strings.TrimSpace(string(pem.EncodeToMemory(&block)))}, "\n") - } - certificate = []byte(certStr) - goto reply - } - - certEntry, funcErr = fetchCertBySerial(ctx, req, req.Path, serial) - if funcErr != nil { - switch funcErr.(type) { - case errutil.UserError: - response = logical.ErrorResponse(funcErr.Error()) - goto reply - case errutil.InternalError: - retErr = funcErr - goto reply - } - } - if certEntry == nil { - response = nil - goto reply - } - - certificate = certEntry.Value - - if len(pemType) != 0 { - block := pem.Block{ - Type: pemType, - Bytes: certEntry.Value, - } - // This is convoluted on purpose to ensure that we don't have trailing - // newlines via various paths - certificate = []byte(strings.TrimSpace(string(pem.EncodeToMemory(&block)))) - } - - revokedEntry, funcErr = fetchCertBySerial(ctx, req, "revoked/", serial) - if funcErr != nil { - switch funcErr.(type) { - case errutil.UserError: - response = logical.ErrorResponse(funcErr.Error()) - goto reply - case errutil.InternalError: - retErr = funcErr - goto reply - } - } - if revokedEntry != nil { - var revInfo revocationInfo - err := revokedEntry.DecodeJSON(&revInfo) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error decoding revocation entry for serial %s: %s", serial, err)), nil - } - revocationTime = revInfo.RevocationTime - } - -reply: - switch { - case len(contentType) != 0: - response = &logical.Response{ - Data: map[string]interface{}{ - logical.HTTPContentType: contentType, - logical.HTTPRawBody: certificate, - }} - if retErr != nil { - if b.Logger().IsWarn() { - b.Logger().Warn("Possible error, but cannot return in raw response. Note that an empty CA probably means none was configured, and an empty CRL is possibly correct", "error", retErr) - } - } - retErr = nil - if len(certificate) > 0 { - response.Data[logical.HTTPStatusCode] = 200 - } else { - response.Data[logical.HTTPStatusCode] = 204 - } - case retErr != nil: - response = nil - return - case response == nil: - return - case response.IsError(): - return response, nil - default: - response.Data["certificate"] = string(certificate) - response.Data["revocation_time"] = revocationTime - } - - return -} - -const pathFetchHelpSyn = ` -Fetch a CA, CRL, CA Chain, or non-revoked certificate. -` - -const pathFetchHelpDesc = ` -This allows certificates to be fetched. If using the fetch/ prefix any non-revoked certificate can be fetched. - -Using "ca" or "crl" as the value fetches the appropriate information in DER encoding. Add "/pem" to either to get PEM encoding. - -Using "ca_chain" as the value fetches the certificate authority trust chain in PEM encoding. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_intermediate.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_intermediate.go deleted file mode 100644 index 5a800e5c3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_intermediate.go +++ /dev/null @@ -1,254 +0,0 @@ -package pki - -import ( - "context" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathGenerateIntermediate(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "intermediate/generate/" + framework.GenericNameRegex("exported"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathGenerateIntermediate, - }, - - HelpSynopsis: pathGenerateIntermediateHelpSyn, - HelpDescription: pathGenerateIntermediateHelpDesc, - } - - ret.Fields = addCACommonFields(map[string]*framework.FieldSchema{}) - ret.Fields = addCAKeyGenerationFields(ret.Fields) - ret.Fields["add_basic_constraints"] = &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Whether to add a Basic Constraints -extension with CA: true. Only needed as a -workaround in some compatibility scenarios -with Active Directory Certificate Services.`, - } - - return ret -} - -func pathSetSignedIntermediate(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "intermediate/set-signed", - - Fields: map[string]*framework.FieldSchema{ - "certificate": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `PEM-format certificate. This must be a CA -certificate with a public key matching the -previously-generated key from the generation -endpoint.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathSetSignedIntermediate, - }, - - HelpSynopsis: pathSetSignedIntermediateHelpSyn, - HelpDescription: pathSetSignedIntermediateHelpDesc, - } - - return ret -} - -func (b *backend) pathGenerateIntermediate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - - exported, format, role, errorResp := b.getGenerationParams(data) - if errorResp != nil { - return errorResp, nil - } - - var resp *logical.Response - input := &dataBundle{ - role: role, - req: req, - apiData: data, - } - parsedBundle, err := generateIntermediateCSR(b, input) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - - csrb, err := parsedBundle.ToCSRBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw CSR bundle to CSR bundle: {{err}}", err) - } - - resp = &logical.Response{ - Data: map[string]interface{}{}, - } - - switch format { - case "pem": - resp.Data["csr"] = csrb.CSR - if exported { - resp.Data["private_key"] = csrb.PrivateKey - resp.Data["private_key_type"] = csrb.PrivateKeyType - } - - case "pem_bundle": - resp.Data["csr"] = csrb.CSR - if exported { - resp.Data["csr"] = fmt.Sprintf("%s\n%s", csrb.PrivateKey, csrb.CSR) - resp.Data["private_key"] = csrb.PrivateKey - resp.Data["private_key_type"] = csrb.PrivateKeyType - } - - case "der": - resp.Data["csr"] = base64.StdEncoding.EncodeToString(parsedBundle.CSRBytes) - if exported { - resp.Data["private_key"] = base64.StdEncoding.EncodeToString(parsedBundle.PrivateKeyBytes) - resp.Data["private_key_type"] = csrb.PrivateKeyType - } - } - - if data.Get("private_key_format").(string) == "pkcs8" { - err = convertRespToPKCS8(resp) - if err != nil { - return nil, err - } - } - - cb := &certutil.CertBundle{} - cb.PrivateKey = csrb.PrivateKey - cb.PrivateKeyType = csrb.PrivateKeyType - - entry, err := logical.StorageEntryJSON("config/ca_bundle", cb) - if err != nil { - return nil, err - } - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - return resp, nil -} - -func (b *backend) pathSetSignedIntermediate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - cert := data.Get("certificate").(string) - - if cert == "" { - return logical.ErrorResponse("no certificate provided in the \"certificate\" parameter"), nil - } - - inputBundle, err := certutil.ParsePEMBundle(cert) - if err != nil { - switch err.(type) { - case errutil.InternalError: - return nil, err - default: - return logical.ErrorResponse(err.Error()), nil - } - } - - if inputBundle.Certificate == nil { - return logical.ErrorResponse("supplied certificate could not be successfully parsed"), nil - } - - cb := &certutil.CertBundle{} - entry, err := req.Storage.Get(ctx, "config/ca_bundle") - if err != nil { - return nil, err - } - if entry == nil { - return logical.ErrorResponse("could not find any existing entry with a private key"), nil - } - - err = entry.DecodeJSON(cb) - if err != nil { - return nil, err - } - - if len(cb.PrivateKey) == 0 || cb.PrivateKeyType == "" { - return logical.ErrorResponse("could not find an existing private key"), nil - } - - parsedCB, err := cb.ToParsedCertBundle() - if err != nil { - return nil, err - } - if parsedCB.PrivateKey == nil { - return nil, fmt.Errorf("saved key could not be parsed successfully") - } - - inputBundle.PrivateKey = parsedCB.PrivateKey - inputBundle.PrivateKeyType = parsedCB.PrivateKeyType - inputBundle.PrivateKeyBytes = parsedCB.PrivateKeyBytes - - if !inputBundle.Certificate.IsCA { - return logical.ErrorResponse("the given certificate is not marked for CA use and cannot be used with this backend"), nil - } - - if err := inputBundle.Verify(); err != nil { - return nil, errwrap.Wrapf("verification of parsed bundle failed: {{err}}", err) - } - - cb, err = inputBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw values into cert bundle: {{err}}", err) - } - - entry, err = logical.StorageEntryJSON("config/ca_bundle", cb) - if err != nil { - return nil, err - } - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - entry.Key = "certs/" + normalizeSerial(cb.SerialNumber) - entry.Value = inputBundle.CertificateBytes - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - // For ease of later use, also store just the certificate at a known - // location - entry.Key = "ca" - entry.Value = inputBundle.CertificateBytes - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - // Build a fresh CRL - err = buildCRL(ctx, b, req, true) - - return nil, err -} - -const pathGenerateIntermediateHelpSyn = ` -Generate a new CSR and private key used for signing. -` - -const pathGenerateIntermediateHelpDesc = ` -See the API documentation for more information. -` - -const pathSetSignedIntermediateHelpSyn = ` -Provide the signed intermediate CA cert. -` - -const pathSetSignedIntermediateHelpDesc = ` -See the API documentation for more information. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_issue_sign.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_issue_sign.go deleted file mode 100644 index 2785009b3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_issue_sign.go +++ /dev/null @@ -1,364 +0,0 @@ -package pki - -import ( - "context" - "encoding/base64" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathIssue(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "issue/" + framework.GenericNameRegex("role"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathIssue, - }, - - HelpSynopsis: pathIssueHelpSyn, - HelpDescription: pathIssueHelpDesc, - } - - ret.Fields = addNonCACommonFields(map[string]*framework.FieldSchema{}) - return ret -} - -func pathSign(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "sign/" + framework.GenericNameRegex("role"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathSign, - }, - - HelpSynopsis: pathSignHelpSyn, - HelpDescription: pathSignHelpDesc, - } - - ret.Fields = addNonCACommonFields(map[string]*framework.FieldSchema{}) - - ret.Fields["csr"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: `PEM-format CSR to be signed.`, - } - - return ret -} - -func pathSignVerbatim(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "sign-verbatim" + framework.OptionalParamRegex("role"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathSignVerbatim, - }, - - HelpSynopsis: pathSignHelpSyn, - HelpDescription: pathSignHelpDesc, - } - - ret.Fields = addNonCACommonFields(map[string]*framework.FieldSchema{}) - - ret.Fields["csr"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: `PEM-format CSR to be signed. Values will be -taken verbatim from the CSR, except for -basic constraints.`, - } - - ret.Fields["key_usage"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: []string{"DigitalSignature", "KeyAgreement", "KeyEncipherment"}, - Description: `A comma-separated string or list of key usages (not extended -key usages). Valid values can be found at -https://golang.org/pkg/crypto/x509/#KeyUsage --- simply drop the "KeyUsage" part of the name. -To remove all key usages from being set, set -this value to an empty list.`, - } - - ret.Fields["ext_key_usage"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: []string{}, - Description: `A comma-separated string or list of extended key usages. Valid values can be found at -https://golang.org/pkg/crypto/x509/#ExtKeyUsage --- simply drop the "ExtKeyUsage" part of the name. -To remove all key usages from being set, set -this value to an empty list.`, - } - - ret.Fields["ext_key_usage_oids"] = &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated string or list of extended key usage oids.`, - } - - return ret -} - -// pathIssue issues a certificate and private key from given parameters, -// subject to role restrictions -func (b *backend) pathIssue(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role").(string) - - // Get the role - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", roleName)), nil - } - - if role.KeyType == "any" { - return logical.ErrorResponse("role key type \"any\" not allowed for issuing certificates, only signing"), nil - } - - return b.pathIssueSignCert(ctx, req, data, role, false, false) -} - -// pathSign issues a certificate from a submitted CSR, subject to role -// restrictions -func (b *backend) pathSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role").(string) - - // Get the role - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", roleName)), nil - } - - return b.pathIssueSignCert(ctx, req, data, role, true, false) -} - -// pathSignVerbatim issues a certificate from a submitted CSR, *not* subject to -// role restrictions -func (b *backend) pathSignVerbatim(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - - roleName := data.Get("role").(string) - - // Get the role if one was specified - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - entry := &roleEntry{ - TTL: b.System().DefaultLeaseTTL(), - MaxTTL: b.System().MaxLeaseTTL(), - AllowLocalhost: true, - AllowAnyName: true, - AllowIPSANs: true, - EnforceHostnames: false, - KeyType: "any", - UseCSRCommonName: true, - UseCSRSANs: true, - AllowedURISANs: []string{"*"}, - AllowedSerialNumbers: []string{"*"}, - GenerateLease: new(bool), - KeyUsage: data.Get("key_usage").([]string), - ExtKeyUsage: data.Get("ext_key_usage").([]string), - ExtKeyUsageOIDs: data.Get("ext_key_usage_oids").([]string), - } - - *entry.GenerateLease = false - - if role != nil { - if role.TTL > 0 { - entry.TTL = role.TTL - } - if role.MaxTTL > 0 { - entry.MaxTTL = role.MaxTTL - } - if role.GenerateLease != nil { - *entry.GenerateLease = *role.GenerateLease - } - entry.NoStore = role.NoStore - } - - if entry.MaxTTL > 0 && entry.TTL > entry.MaxTTL { - return logical.ErrorResponse(fmt.Sprintf("requested ttl of %s is greater than max ttl of %s", entry.TTL, entry.MaxTTL)), nil - } - - return b.pathIssueSignCert(ctx, req, data, entry, true, true) -} - -func (b *backend) pathIssueSignCert(ctx context.Context, req *logical.Request, data *framework.FieldData, role *roleEntry, useCSR, useCSRValues bool) (*logical.Response, error) { - format := getFormat(data) - if format == "" { - return logical.ErrorResponse( - `the "format" path parameter must be "pem", "der", or "pem_bundle"`), nil - } - - var caErr error - signingBundle, caErr := fetchCAInfo(ctx, req) - switch caErr.(type) { - case errutil.UserError: - return nil, errutil.UserError{Err: fmt.Sprintf( - "could not fetch the CA certificate (was one set?): %s", caErr)} - case errutil.InternalError: - return nil, errutil.InternalError{Err: fmt.Sprintf( - "error fetching CA certificate: %s", caErr)} - } - - input := &dataBundle{ - req: req, - apiData: data, - role: role, - signingBundle: signingBundle, - } - var parsedBundle *certutil.ParsedCertBundle - var err error - if useCSR { - parsedBundle, err = signCert(b, input, false, useCSRValues) - } else { - parsedBundle, err = generateCert(ctx, b, input, false) - } - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - - signingCB, err := signingBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw signing bundle to cert bundle: {{err}}", err) - } - - cb, err := parsedBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw cert bundle to cert bundle: {{err}}", err) - } - - respData := map[string]interface{}{ - "serial_number": cb.SerialNumber, - } - - switch format { - case "pem": - respData["issuing_ca"] = signingCB.Certificate - respData["certificate"] = cb.Certificate - if cb.CAChain != nil && len(cb.CAChain) > 0 { - respData["ca_chain"] = cb.CAChain - } - if !useCSR { - respData["private_key"] = cb.PrivateKey - respData["private_key_type"] = cb.PrivateKeyType - } - - case "pem_bundle": - respData["issuing_ca"] = signingCB.Certificate - respData["certificate"] = cb.ToPEMBundle() - if cb.CAChain != nil && len(cb.CAChain) > 0 { - respData["ca_chain"] = cb.CAChain - } - if !useCSR { - respData["private_key"] = cb.PrivateKey - respData["private_key_type"] = cb.PrivateKeyType - } - - case "der": - respData["certificate"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes) - respData["issuing_ca"] = base64.StdEncoding.EncodeToString(signingBundle.CertificateBytes) - - var caChain []string - for _, caCert := range parsedBundle.CAChain { - caChain = append(caChain, base64.StdEncoding.EncodeToString(caCert.Bytes)) - } - if caChain != nil && len(caChain) > 0 { - respData["ca_chain"] = caChain - } - - if !useCSR { - respData["private_key"] = base64.StdEncoding.EncodeToString(parsedBundle.PrivateKeyBytes) - respData["private_key_type"] = cb.PrivateKeyType - } - } - - var resp *logical.Response - switch { - case role.GenerateLease == nil: - return nil, fmt.Errorf("generate lease in role is nil") - case *role.GenerateLease == false: - // If lease generation is disabled do not populate `Secret` field in - // the response - resp = &logical.Response{ - Data: respData, - } - default: - resp = b.Secret(SecretCertsType).Response( - respData, - map[string]interface{}{ - "serial_number": cb.SerialNumber, - }) - resp.Secret.TTL = parsedBundle.Certificate.NotAfter.Sub(time.Now()) - } - - if data.Get("private_key_format").(string) == "pkcs8" { - err = convertRespToPKCS8(resp) - if err != nil { - return nil, err - } - } - - if !role.NoStore { - err = req.Storage.Put(ctx, &logical.StorageEntry{ - Key: "certs/" + normalizeSerial(cb.SerialNumber), - Value: parsedBundle.CertificateBytes, - }) - if err != nil { - return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err) - } - } - - if useCSR { - if role.UseCSRCommonName && data.Get("common_name").(string) != "" { - resp.AddWarning("the common_name field was provided but the role is set with \"use_csr_common_name\" set to true") - } - if role.UseCSRSANs && data.Get("alt_names").(string) != "" { - resp.AddWarning("the alt_names field was provided but the role is set with \"use_csr_sans\" set to true") - } - } - - return resp, nil -} - -const pathIssueHelpSyn = ` -Request a certificate using a certain role with the provided details. -` - -const pathIssueHelpDesc = ` -This path allows requesting a certificate to be issued according to the -policy of the given role. The certificate will only be issued if the -requested details are allowed by the role policy. - -This path returns a certificate and a private key. If you want a workflow -that does not expose a private key, generate a CSR locally and use the -sign path instead. -` - -const pathSignHelpSyn = ` -Request certificates using a certain role with the provided details. -` - -const pathSignHelpDesc = ` -This path allows requesting certificates to be issued according to the -policy of the given role. The certificate will only be issued if the -requested common name is allowed by the role policy. - -This path requires a CSR; if you want Vault to generate a private key -for you, use the issue path instead. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_revoke.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_revoke.go deleted file mode 100644 index ff4c462cf..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_revoke.go +++ /dev/null @@ -1,96 +0,0 @@ -package pki - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathRevoke(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `revoke`, - Fields: map[string]*framework.FieldSchema{ - "serial_number": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Certificate serial number, in colon- or -hyphen-separated octal`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRevokeWrite, - }, - - HelpSynopsis: pathRevokeHelpSyn, - HelpDescription: pathRevokeHelpDesc, - } -} - -func pathRotateCRL(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `crl/rotate`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRotateCRLRead, - }, - - HelpSynopsis: pathRotateCRLHelpSyn, - HelpDescription: pathRotateCRLHelpDesc, - } -} - -func (b *backend) pathRevokeWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - serial := data.Get("serial_number").(string) - if len(serial) == 0 { - return logical.ErrorResponse("The serial number must be provided"), nil - } - - // We store and identify by lowercase colon-separated hex, but other - // utilities use dashes and/or uppercase, so normalize - serial = strings.Replace(strings.ToLower(serial), "-", ":", -1) - - b.revokeStorageLock.Lock() - defer b.revokeStorageLock.Unlock() - - return revokeCert(ctx, b, req, serial, false) -} - -func (b *backend) pathRotateCRLRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.revokeStorageLock.RLock() - defer b.revokeStorageLock.RUnlock() - - crlErr := buildCRL(ctx, b, req, false) - switch crlErr.(type) { - case errutil.UserError: - return logical.ErrorResponse(fmt.Sprintf("Error during CRL building: %s", crlErr)), nil - case errutil.InternalError: - return nil, errwrap.Wrapf("error encountered during CRL building: {{err}}", crlErr) - default: - return &logical.Response{ - Data: map[string]interface{}{ - "success": true, - }, - }, nil - } -} - -const pathRevokeHelpSyn = ` -Revoke a certificate by serial number. -` - -const pathRevokeHelpDesc = ` -This allows certificates to be revoked using its serial number. A root token is required. -` - -const pathRotateCRLHelpSyn = ` -Force a rebuild of the CRL. -` - -const pathRotateCRLHelpDesc = ` -Force a rebuild of the CRL. This can be used to remove expired certificates from it if no certificates have been revoked. A root token is required. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_roles.go deleted file mode 100644 index 6f82474ea..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_roles.go +++ /dev/null @@ -1,745 +0,0 @@ -package pki - -import ( - "context" - "crypto/x509" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathListRolesHelpSyn, - HelpDescription: pathListRolesHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `The lease duration if no specific lease duration is -requested. The lease duration controls the expiration -of certificates issued by this backend. Defaults to -the value of max_ttl.`, - }, - - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: "The maximum allowed lease duration", - }, - - "allow_localhost": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `Whether to allow "localhost" as a valid common -name in a request`, - }, - - "allowed_domains": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, clients can request certificates for -subdomains directly beneath these domains, including -the wildcard subdomains. See the documentation for more -information. This parameter accepts a comma-separated -string or list of domains.`, - }, - - "allow_bare_domains": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, clients can request certificates -for the base domains themselves, e.g. "example.com". -This is a separate option as in some cases this can -be considered a security threat.`, - }, - - "allow_subdomains": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, clients can request certificates for -subdomains of the CNs allowed by the other role options, -including wildcard subdomains. See the documentation for -more information.`, - }, - - "allow_glob_domains": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, domains specified in "allowed_domains" -can include glob patterns, e.g. "ftp*.example.com". See -the documentation for more information.`, - }, - - "allow_any_name": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, clients can request certificates for -any CN they like. See the documentation for more -information.`, - }, - - "enforce_hostnames": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, only valid host names are allowed for -CN and SANs. Defaults to true.`, - }, - - "allow_ip_sans": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, IP Subject Alternative Names are allowed. -Any valid IP is accepted.`, - }, - - "allowed_uri_sans": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, an array of allowed URIs to put in the URI Subject Alternative Names. -Any valid URI is accepted, these values support globbing.`, - }, - - "allowed_other_sans": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, an array of allowed other names to put in SANs. These values support globbing.`, - }, - - "allowed_serial_numbers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, an array of allowed serial numbers to put in Subject. These values support globbing.`, - }, - - "server_flag": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, certificates are flagged for server auth use. -Defaults to true.`, - }, - - "client_flag": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, certificates are flagged for client auth use. -Defaults to true.`, - }, - - "code_signing_flag": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, certificates are flagged for code signing -use. Defaults to false.`, - }, - - "email_protection_flag": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `If set, certificates are flagged for email -protection use. Defaults to false.`, - }, - - "key_type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "rsa", - Description: `The type of key to use; defaults to RSA. "rsa" -and "ec" are the only valid values.`, - }, - - "key_bits": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 2048, - Description: `The number of bits to use. You will almost -certainly want to change this if you adjust -the key_type.`, - }, - - "key_usage": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: []string{"DigitalSignature", "KeyAgreement", "KeyEncipherment"}, - Description: `A comma-separated string or list of key usages (not extended -key usages). Valid values can be found at -https://golang.org/pkg/crypto/x509/#KeyUsage --- simply drop the "KeyUsage" part of the name. -To remove all key usages from being set, set -this value to an empty list.`, - }, - - "ext_key_usage": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Default: []string{}, - Description: `A comma-separated string or list of extended key usages. Valid values can be found at -https://golang.org/pkg/crypto/x509/#ExtKeyUsage --- simply drop the "ExtKeyUsage" part of the name. -To remove all key usages from being set, set -this value to an empty list.`, - }, - - "ext_key_usage_oids": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated string or list of extended key usage oids.`, - }, - - "use_csr_common_name": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, when used with a signing profile, -the common name in the CSR will be used. This -does *not* include any requested Subject Alternative -Names. Defaults to true.`, - }, - - "use_csr_sans": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, when used with a signing profile, -the SANs in the CSR will be used. This does *not* -include the Common Name (cn). Defaults to true.`, - }, - - "ou": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, OU (OrganizationalUnit) will be set to -this value in certificates issued by this role.`, - }, - - "organization": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, O (Organization) will be set to -this value in certificates issued by this role.`, - }, - - "country": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Country will be set to -this value in certificates issued by this role.`, - }, - - "locality": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Locality will be set to -this value in certificates issued by this role.`, - }, - - "province": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Province will be set to -this value in certificates issued by this role.`, - }, - - "street_address": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Street Address will be set to -this value in certificates issued by this role.`, - }, - - "postal_code": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `If set, Postal Code will be set to -this value in certificates issued by this role.`, - }, - - "generate_lease": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` -If set, certificates issued/signed against this role will have Vault leases -attached to them. Defaults to "false". Certificates can be added to the CRL by -"vault revoke " when certificates are associated with leases. It can -also be done using the "pki/revoke" endpoint. However, when lease generation is -disabled, invoking "pki/revoke" would be the only way to add the certificates -to the CRL. When large number of certificates are generated with long -lifetimes, it is recommended that lease generation be disabled, as large amount of -leases adversely affect the startup time of Vault.`, - }, - "no_store": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` -If set, certificates issued/signed against this role will not be stored in the -storage backend. This can improve performance when issuing large numbers of -certificates. However, certificates issued in this way cannot be enumerated -or revoked, so this option is recommended only for certificates that are -non-sensitive, or extremely short-lived. This option implies a value of "false" -for "generate_lease".`, - }, - "require_cn": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set to false, makes the 'common_name' field optional while generating a certificate.`, - }, - "policy_identifiers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `A comma-separated string or list of policy oids.`, - }, - "basic_constraints_valid_for_non_ca": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Mark Basic Constraints valid when issuing non-CA certificates.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) getRole(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - // Migrate existing saved entries and save back if changed - modified := false - if len(result.DeprecatedTTL) == 0 && len(result.Lease) != 0 { - result.DeprecatedTTL = result.Lease - result.Lease = "" - modified = true - } - if result.TTL == 0 && len(result.DeprecatedTTL) != 0 { - parsed, err := parseutil.ParseDurationSecond(result.DeprecatedTTL) - if err != nil { - return nil, err - } - result.TTL = parsed - result.DeprecatedTTL = "" - modified = true - } - if len(result.DeprecatedMaxTTL) == 0 && len(result.LeaseMax) != 0 { - result.DeprecatedMaxTTL = result.LeaseMax - result.LeaseMax = "" - modified = true - } - if result.MaxTTL == 0 && len(result.DeprecatedMaxTTL) != 0 { - parsed, err := parseutil.ParseDurationSecond(result.DeprecatedMaxTTL) - if err != nil { - return nil, err - } - result.MaxTTL = parsed - result.DeprecatedMaxTTL = "" - modified = true - } - if result.AllowBaseDomain { - result.AllowBaseDomain = false - result.AllowBareDomains = true - modified = true - } - if result.AllowedDomainsOld != "" { - result.AllowedDomains = strings.Split(result.AllowedDomainsOld, ",") - result.AllowedDomainsOld = "" - modified = true - } - if result.AllowedBaseDomain != "" { - found := false - for _, v := range result.AllowedDomains { - if v == result.AllowedBaseDomain { - found = true - break - } - } - if !found { - result.AllowedDomains = append(result.AllowedDomains, result.AllowedBaseDomain) - } - result.AllowedBaseDomain = "" - modified = true - } - - // Upgrade generate_lease in role - if result.GenerateLease == nil { - // All the new roles will have GenerateLease always set to a value. A - // nil value indicates that this role needs an upgrade. Set it to - // `true` to not alter its current behavior. - result.GenerateLease = new(bool) - *result.GenerateLease = true - modified = true - } - - // Upgrade key usages - if result.KeyUsageOld != "" { - result.KeyUsage = strings.Split(result.KeyUsageOld, ",") - result.KeyUsageOld = "" - modified = true - } - - // Upgrade OU - if result.OUOld != "" { - result.OU = strings.Split(result.OUOld, ",") - result.OUOld = "" - modified = true - } - - // Upgrade Organization - if result.OrganizationOld != "" { - result.Organization = strings.Split(result.OrganizationOld, ",") - result.OrganizationOld = "" - modified = true - } - - if modified && (b.System().LocalMount() || !b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) { - jsonEntry, err := logical.StorageEntryJSON("role/"+n, &result) - if err != nil { - return nil, err - } - if err := s.Put(ctx, jsonEntry); err != nil { - // Only perform upgrades on replication primary - if !strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return nil, err - } - } - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("name").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: role.ToResponseData(), - } - return resp, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - name := data.Get("name").(string) - - entry := &roleEntry{ - MaxTTL: time.Duration(data.Get("max_ttl").(int)) * time.Second, - TTL: time.Duration(data.Get("ttl").(int)) * time.Second, - AllowLocalhost: data.Get("allow_localhost").(bool), - AllowedDomains: data.Get("allowed_domains").([]string), - AllowBareDomains: data.Get("allow_bare_domains").(bool), - AllowSubdomains: data.Get("allow_subdomains").(bool), - AllowGlobDomains: data.Get("allow_glob_domains").(bool), - AllowAnyName: data.Get("allow_any_name").(bool), - EnforceHostnames: data.Get("enforce_hostnames").(bool), - AllowIPSANs: data.Get("allow_ip_sans").(bool), - AllowedURISANs: data.Get("allowed_uri_sans").([]string), - ServerFlag: data.Get("server_flag").(bool), - ClientFlag: data.Get("client_flag").(bool), - CodeSigningFlag: data.Get("code_signing_flag").(bool), - EmailProtectionFlag: data.Get("email_protection_flag").(bool), - KeyType: data.Get("key_type").(string), - KeyBits: data.Get("key_bits").(int), - UseCSRCommonName: data.Get("use_csr_common_name").(bool), - UseCSRSANs: data.Get("use_csr_sans").(bool), - KeyUsage: data.Get("key_usage").([]string), - ExtKeyUsage: data.Get("ext_key_usage").([]string), - ExtKeyUsageOIDs: data.Get("ext_key_usage_oids").([]string), - OU: data.Get("ou").([]string), - Organization: data.Get("organization").([]string), - Country: data.Get("country").([]string), - Locality: data.Get("locality").([]string), - Province: data.Get("province").([]string), - StreetAddress: data.Get("street_address").([]string), - PostalCode: data.Get("postal_code").([]string), - GenerateLease: new(bool), - NoStore: data.Get("no_store").(bool), - RequireCN: data.Get("require_cn").(bool), - AllowedSerialNumbers: data.Get("allowed_serial_numbers").([]string), - PolicyIdentifiers: data.Get("policy_identifiers").([]string), - BasicConstraintsValidForNonCA: data.Get("basic_constraints_valid_for_non_ca").(bool), - } - - otherSANs := data.Get("allowed_other_sans").([]string) - if len(otherSANs) > 0 { - _, err := parseOtherSANs(otherSANs) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf("error parsing allowed_other_sans: {{err}}", err).Error()), nil - } - entry.AllowedOtherSANs = otherSANs - } - - // no_store implies generate_lease := false - if entry.NoStore { - *entry.GenerateLease = false - } else { - *entry.GenerateLease = data.Get("generate_lease").(bool) - } - - if entry.KeyType == "rsa" && entry.KeyBits < 2048 { - return logical.ErrorResponse("RSA keys < 2048 bits are unsafe and not supported"), nil - } - - if entry.MaxTTL > 0 && entry.TTL > entry.MaxTTL { - return logical.ErrorResponse( - `"ttl" value must be less than "max_ttl" value`, - ), nil - } - - if errResp := validateKeyTypeLength(entry.KeyType, entry.KeyBits); errResp != nil { - return errResp, nil - } - - if len(entry.ExtKeyUsageOIDs) > 0 { - for _, oidstr := range entry.ExtKeyUsageOIDs { - _, err := stringToOid(oidstr) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("%q could not be parsed as a valid oid for an extended key usage", oidstr)), nil - } - } - } - - if len(entry.PolicyIdentifiers) > 0 { - for _, oidstr := range entry.PolicyIdentifiers { - _, err := stringToOid(oidstr) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("%q could not be parsed as a valid oid for a policy identifier", oidstr)), nil - } - } - } - - // Store it - jsonEntry, err := logical.StorageEntryJSON("role/"+name, entry) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, jsonEntry); err != nil { - return nil, err - } - - return nil, nil -} - -func parseKeyUsages(input []string) int { - var parsedKeyUsages x509.KeyUsage - for _, k := range input { - switch strings.ToLower(strings.TrimSpace(k)) { - case "digitalsignature": - parsedKeyUsages |= x509.KeyUsageDigitalSignature - case "contentcommitment": - parsedKeyUsages |= x509.KeyUsageContentCommitment - case "keyencipherment": - parsedKeyUsages |= x509.KeyUsageKeyEncipherment - case "dataencipherment": - parsedKeyUsages |= x509.KeyUsageDataEncipherment - case "keyagreement": - parsedKeyUsages |= x509.KeyUsageKeyAgreement - case "certsign": - parsedKeyUsages |= x509.KeyUsageCertSign - case "crlsign": - parsedKeyUsages |= x509.KeyUsageCRLSign - case "encipheronly": - parsedKeyUsages |= x509.KeyUsageEncipherOnly - case "decipheronly": - parsedKeyUsages |= x509.KeyUsageDecipherOnly - } - } - - return int(parsedKeyUsages) -} - -func parseExtKeyUsages(role *roleEntry) certExtKeyUsage { - var parsedKeyUsages certExtKeyUsage - - if role.ServerFlag { - parsedKeyUsages |= serverAuthExtKeyUsage - } - - if role.ClientFlag { - parsedKeyUsages |= clientAuthExtKeyUsage - } - - if role.CodeSigningFlag { - parsedKeyUsages |= codeSigningExtKeyUsage - } - - if role.EmailProtectionFlag { - parsedKeyUsages |= emailProtectionExtKeyUsage - } - - for _, k := range role.ExtKeyUsage { - switch strings.ToLower(strings.TrimSpace(k)) { - case "any": - parsedKeyUsages |= anyExtKeyUsage - case "serverauth": - parsedKeyUsages |= serverAuthExtKeyUsage - case "clientauth": - parsedKeyUsages |= clientAuthExtKeyUsage - case "codesigning": - parsedKeyUsages |= codeSigningExtKeyUsage - case "emailprotection": - parsedKeyUsages |= emailProtectionExtKeyUsage - case "ipsecendsystem": - parsedKeyUsages |= ipsecEndSystemExtKeyUsage - case "ipsectunnel": - parsedKeyUsages |= ipsecTunnelExtKeyUsage - case "ipsecuser": - parsedKeyUsages |= ipsecUserExtKeyUsage - case "timestamping": - parsedKeyUsages |= timeStampingExtKeyUsage - case "ocspsigning": - parsedKeyUsages |= ocspSigningExtKeyUsage - case "microsoftservergatedcrypto": - parsedKeyUsages |= microsoftServerGatedCryptoExtKeyUsage - case "netscapeservergatedcrypto": - parsedKeyUsages |= netscapeServerGatedCryptoExtKeyUsage - } - } - - return parsedKeyUsages -} - -type roleEntry struct { - LeaseMax string `json:"lease_max"` - Lease string `json:"lease"` - DeprecatedMaxTTL string `json:"max_ttl" mapstructure:"max_ttl"` - DeprecatedTTL string `json:"ttl" mapstructure:"ttl"` - TTL time.Duration `json:"ttl_duration" mapstructure:"ttl_duration"` - MaxTTL time.Duration `json:"max_ttl_duration" mapstructure:"max_ttl_duration"` - AllowLocalhost bool `json:"allow_localhost" mapstructure:"allow_localhost"` - AllowedBaseDomain string `json:"allowed_base_domain" mapstructure:"allowed_base_domain"` - AllowedDomainsOld string `json:"allowed_domains,omit_empty"` - AllowedDomains []string `json:"allowed_domains_list" mapstructure:"allowed_domains"` - AllowBaseDomain bool `json:"allow_base_domain"` - AllowBareDomains bool `json:"allow_bare_domains" mapstructure:"allow_bare_domains"` - AllowTokenDisplayName bool `json:"allow_token_displayname" mapstructure:"allow_token_displayname"` - AllowSubdomains bool `json:"allow_subdomains" mapstructure:"allow_subdomains"` - AllowGlobDomains bool `json:"allow_glob_domains" mapstructure:"allow_glob_domains"` - AllowAnyName bool `json:"allow_any_name" mapstructure:"allow_any_name"` - EnforceHostnames bool `json:"enforce_hostnames" mapstructure:"enforce_hostnames"` - AllowIPSANs bool `json:"allow_ip_sans" mapstructure:"allow_ip_sans"` - ServerFlag bool `json:"server_flag" mapstructure:"server_flag"` - ClientFlag bool `json:"client_flag" mapstructure:"client_flag"` - CodeSigningFlag bool `json:"code_signing_flag" mapstructure:"code_signing_flag"` - EmailProtectionFlag bool `json:"email_protection_flag" mapstructure:"email_protection_flag"` - UseCSRCommonName bool `json:"use_csr_common_name" mapstructure:"use_csr_common_name"` - UseCSRSANs bool `json:"use_csr_sans" mapstructure:"use_csr_sans"` - KeyType string `json:"key_type" mapstructure:"key_type"` - KeyBits int `json:"key_bits" mapstructure:"key_bits"` - MaxPathLength *int `json:",omitempty" mapstructure:"max_path_length"` - KeyUsageOld string `json:"key_usage,omitempty"` - KeyUsage []string `json:"key_usage_list" mapstructure:"key_usage"` - ExtKeyUsage []string `json:"extended_key_usage_list" mapstructure:"extended_key_usage"` - OUOld string `json:"ou,omitempty"` - OU []string `json:"ou_list" mapstructure:"ou"` - OrganizationOld string `json:"organization,omitempty"` - Organization []string `json:"organization_list" mapstructure:"organization"` - Country []string `json:"country" mapstructure:"country"` - Locality []string `json:"locality" mapstructure:"locality"` - Province []string `json:"province" mapstructure:"province"` - StreetAddress []string `json:"street_address" mapstructure:"street_address"` - PostalCode []string `json:"postal_code" mapstructure:"postal_code"` - GenerateLease *bool `json:"generate_lease,omitempty"` - NoStore bool `json:"no_store" mapstructure:"no_store"` - RequireCN bool `json:"require_cn" mapstructure:"require_cn"` - AllowedOtherSANs []string `json:"allowed_other_sans" mapstructure:"allowed_other_sans"` - AllowedSerialNumbers []string `json:"allowed_serial_numbers" mapstructure:"allowed_serial_numbers"` - AllowedURISANs []string `json:"allowed_uri_sans" mapstructure:"allowed_uri_sans"` - PolicyIdentifiers []string `json:"policy_identifiers" mapstructure:"policy_identifiers"` - ExtKeyUsageOIDs []string `json:"ext_key_usage_oids" mapstructure:"ext_key_usage_oids"` - BasicConstraintsValidForNonCA bool `json:"basic_constraints_valid_for_non_ca" mapstructure:"basic_constraints_valid_for_non_ca"` - - // Used internally for signing intermediates - AllowExpirationPastCA bool -} - -func (r *roleEntry) ToResponseData() map[string]interface{} { - responseData := map[string]interface{}{ - "ttl": int64(r.TTL.Seconds()), - "max_ttl": int64(r.MaxTTL.Seconds()), - "allow_localhost": r.AllowLocalhost, - "allowed_domains": r.AllowedDomains, - "allow_bare_domains": r.AllowBareDomains, - "allow_token_displayname": r.AllowTokenDisplayName, - "allow_subdomains": r.AllowSubdomains, - "allow_glob_domains": r.AllowGlobDomains, - "allow_any_name": r.AllowAnyName, - "enforce_hostnames": r.EnforceHostnames, - "allow_ip_sans": r.AllowIPSANs, - "server_flag": r.ServerFlag, - "client_flag": r.ClientFlag, - "code_signing_flag": r.CodeSigningFlag, - "email_protection_flag": r.EmailProtectionFlag, - "use_csr_common_name": r.UseCSRCommonName, - "use_csr_sans": r.UseCSRSANs, - "key_type": r.KeyType, - "key_bits": r.KeyBits, - "key_usage": r.KeyUsage, - "ext_key_usage": r.ExtKeyUsage, - "ext_key_usage_oids": r.ExtKeyUsageOIDs, - "ou": r.OU, - "organization": r.Organization, - "country": r.Country, - "locality": r.Locality, - "province": r.Province, - "street_address": r.StreetAddress, - "postal_code": r.PostalCode, - "no_store": r.NoStore, - "allowed_other_sans": r.AllowedOtherSANs, - "allowed_serial_numbers": r.AllowedSerialNumbers, - "allowed_uri_sans": r.AllowedURISANs, - "require_cn": r.RequireCN, - "policy_identifiers": r.PolicyIdentifiers, - "basic_constraints_valid_for_non_ca": r.BasicConstraintsValidForNonCA, - } - if r.MaxPathLength != nil { - responseData["max_path_length"] = r.MaxPathLength - } - if r.GenerateLease != nil { - responseData["generate_lease"] = r.GenerateLease - } - return responseData -} - -const pathListRolesHelpSyn = `List the existing roles in this backend` - -const pathListRolesHelpDesc = `Roles will be listed by the role name.` - -const pathRoleHelpSyn = `Manage the roles that can be created with this backend.` - -const pathRoleHelpDesc = `This path lets you manage the roles that can be created with this backend.` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_root.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_root.go deleted file mode 100644 index 1ea4309f8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_root.go +++ /dev/null @@ -1,485 +0,0 @@ -package pki - -import ( - "context" - "crypto/rand" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "fmt" - "reflect" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathGenerateRoot(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "root/generate/" + framework.GenericNameRegex("exported"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathCAGenerateRoot, - }, - - HelpSynopsis: pathGenerateRootHelpSyn, - HelpDescription: pathGenerateRootHelpDesc, - } - - ret.Fields = addCACommonFields(map[string]*framework.FieldSchema{}) - ret.Fields = addCAKeyGenerationFields(ret.Fields) - ret.Fields = addCAIssueFields(ret.Fields) - - return ret -} - -func pathDeleteRoot(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "root", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.DeleteOperation: b.pathCADeleteRoot, - }, - - HelpSynopsis: pathDeleteRootHelpSyn, - HelpDescription: pathDeleteRootHelpDesc, - } - - return ret -} - -func pathSignIntermediate(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "root/sign-intermediate", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathCASignIntermediate, - }, - - HelpSynopsis: pathSignIntermediateHelpSyn, - HelpDescription: pathSignIntermediateHelpDesc, - } - - ret.Fields = addCACommonFields(map[string]*framework.FieldSchema{}) - ret.Fields = addCAIssueFields(ret.Fields) - - ret.Fields["csr"] = &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: `PEM-format CSR to be signed.`, - } - - ret.Fields["use_csr_values"] = &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: `If true, then: -1) Subject information, including names and alternate -names, will be preserved from the CSR rather than -using values provided in the other parameters to -this path; -2) Any key usages requested in the CSR will be -added to the basic set of key usages used for CA -certs signed by this path; for instance, -the non-repudiation flag.`, - } - - return ret -} - -func pathSignSelfIssued(b *backend) *framework.Path { - ret := &framework.Path{ - Pattern: "root/sign-self-issued", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathCASignSelfIssued, - }, - - Fields: map[string]*framework.FieldSchema{ - "certificate": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `PEM-format self-issued certificate to be signed.`, - }, - }, - - HelpSynopsis: pathSignSelfIssuedHelpSyn, - HelpDescription: pathSignSelfIssuedHelpDesc, - } - - return ret -} - -func (b *backend) pathCADeleteRoot(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return nil, req.Storage.Delete(ctx, "config/ca_bundle") -} - -func (b *backend) pathCAGenerateRoot(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - - entry, err := req.Storage.Get(ctx, "config/ca_bundle") - if err != nil { - return nil, err - } - if entry != nil { - resp := &logical.Response{} - resp.AddWarning(fmt.Sprintf("Refusing to generate a root certificate over an existing root certificate. If you really want to destroy the original root certificate, please issue a delete against %sroot.", req.MountPoint)) - return resp, nil - } - - exported, format, role, errorResp := b.getGenerationParams(data) - if errorResp != nil { - return errorResp, nil - } - - maxPathLengthIface, ok := data.GetOk("max_path_length") - if ok { - maxPathLength := maxPathLengthIface.(int) - role.MaxPathLength = &maxPathLength - } - - input := &dataBundle{ - req: req, - apiData: data, - role: role, - } - parsedBundle, err := generateCert(ctx, b, input, true) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - - cb, err := parsedBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw cert bundle to cert bundle: {{err}}", err) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "expiration": int64(parsedBundle.Certificate.NotAfter.Unix()), - "serial_number": cb.SerialNumber, - }, - } - - switch format { - case "pem": - resp.Data["certificate"] = cb.Certificate - resp.Data["issuing_ca"] = cb.Certificate - if exported { - resp.Data["private_key"] = cb.PrivateKey - resp.Data["private_key_type"] = cb.PrivateKeyType - } - - case "pem_bundle": - resp.Data["issuing_ca"] = cb.Certificate - - if exported { - resp.Data["private_key"] = cb.PrivateKey - resp.Data["private_key_type"] = cb.PrivateKeyType - resp.Data["certificate"] = fmt.Sprintf("%s\n%s", cb.PrivateKey, cb.Certificate) - } else { - resp.Data["certificate"] = cb.Certificate - } - - case "der": - resp.Data["certificate"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes) - resp.Data["issuing_ca"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes) - if exported { - resp.Data["private_key"] = base64.StdEncoding.EncodeToString(parsedBundle.PrivateKeyBytes) - resp.Data["private_key_type"] = cb.PrivateKeyType - } - } - - if data.Get("private_key_format").(string) == "pkcs8" { - err = convertRespToPKCS8(resp) - if err != nil { - return nil, err - } - } - - // Store it as the CA bundle - entry, err = logical.StorageEntryJSON("config/ca_bundle", cb) - if err != nil { - return nil, err - } - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - // Also store it as just the certificate identified by serial number, so it - // can be revoked - err = req.Storage.Put(ctx, &logical.StorageEntry{ - Key: "certs/" + normalizeSerial(cb.SerialNumber), - Value: parsedBundle.CertificateBytes, - }) - if err != nil { - return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err) - } - - // For ease of later use, also store just the certificate at a known - // location - entry.Key = "ca" - entry.Value = parsedBundle.CertificateBytes - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - // Build a fresh CRL - err = buildCRL(ctx, b, req, true) - if err != nil { - return nil, err - } - - if parsedBundle.Certificate.MaxPathLen == 0 { - resp.AddWarning("Max path length of the generated certificate is zero. This certificate cannot be used to issue intermediate CA certificates.") - } - - return resp, nil -} - -func (b *backend) pathCASignIntermediate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - - format := getFormat(data) - if format == "" { - return logical.ErrorResponse( - `The "format" path parameter must be "pem" or "der"`, - ), nil - } - - role := &roleEntry{ - OU: data.Get("ou").([]string), - Organization: data.Get("organization").([]string), - Country: data.Get("country").([]string), - Locality: data.Get("locality").([]string), - Province: data.Get("province").([]string), - StreetAddress: data.Get("street_address").([]string), - PostalCode: data.Get("postal_code").([]string), - TTL: time.Duration(data.Get("ttl").(int)) * time.Second, - AllowLocalhost: true, - AllowAnyName: true, - AllowIPSANs: true, - EnforceHostnames: false, - KeyType: "any", - AllowedURISANs: []string{"*"}, - AllowedSerialNumbers: []string{"*"}, - AllowExpirationPastCA: true, - } - - if cn := data.Get("common_name").(string); len(cn) == 0 { - role.UseCSRCommonName = true - } - - var caErr error - signingBundle, caErr := fetchCAInfo(ctx, req) - switch caErr.(type) { - case errutil.UserError: - return nil, errutil.UserError{Err: fmt.Sprintf( - "could not fetch the CA certificate (was one set?): %s", caErr)} - case errutil.InternalError: - return nil, errutil.InternalError{Err: fmt.Sprintf( - "error fetching CA certificate: %s", caErr)} - } - - useCSRValues := data.Get("use_csr_values").(bool) - - maxPathLengthIface, ok := data.GetOk("max_path_length") - if ok { - maxPathLength := maxPathLengthIface.(int) - role.MaxPathLength = &maxPathLength - } - - input := &dataBundle{ - req: req, - apiData: data, - signingBundle: signingBundle, - role: role, - } - parsedBundle, err := signCert(b, input, true, useCSRValues) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), nil - case errutil.InternalError: - return nil, err - } - } - - if err := parsedBundle.Verify(); err != nil { - return nil, errwrap.Wrapf("verification of parsed bundle failed: {{err}}", err) - } - - signingCB, err := signingBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw signing bundle to cert bundle: {{err}}", err) - } - - cb, err := parsedBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw cert bundle to cert bundle: {{err}}", err) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "expiration": int64(parsedBundle.Certificate.NotAfter.Unix()), - "serial_number": cb.SerialNumber, - }, - } - - if signingBundle.Certificate.NotAfter.Before(parsedBundle.Certificate.NotAfter) { - resp.AddWarning("The expiration time for the signed certificate is after the CA's expiration time. If the new certificate is not treated as a root, validation paths with the certificate past the issuing CA's expiration time will fail.") - } - - switch format { - case "pem": - resp.Data["certificate"] = cb.Certificate - resp.Data["issuing_ca"] = signingCB.Certificate - if cb.CAChain != nil && len(cb.CAChain) > 0 { - resp.Data["ca_chain"] = cb.CAChain - } - - case "pem_bundle": - resp.Data["certificate"] = cb.ToPEMBundle() - resp.Data["issuing_ca"] = signingCB.Certificate - if cb.CAChain != nil && len(cb.CAChain) > 0 { - resp.Data["ca_chain"] = cb.CAChain - } - - case "der": - resp.Data["certificate"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes) - resp.Data["issuing_ca"] = base64.StdEncoding.EncodeToString(signingBundle.CertificateBytes) - - var caChain []string - for _, caCert := range parsedBundle.CAChain { - caChain = append(caChain, base64.StdEncoding.EncodeToString(caCert.Bytes)) - } - if caChain != nil && len(caChain) > 0 { - resp.Data["ca_chain"] = cb.CAChain - } - } - - err = req.Storage.Put(ctx, &logical.StorageEntry{ - Key: "certs/" + normalizeSerial(cb.SerialNumber), - Value: parsedBundle.CertificateBytes, - }) - if err != nil { - return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err) - } - - if parsedBundle.Certificate.MaxPathLen == 0 { - resp.AddWarning("Max path length of the signed certificate is zero. This certificate cannot be used to issue intermediate CA certificates.") - } - - return resp, nil -} - -func (b *backend) pathCASignSelfIssued(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - - certPem := data.Get("certificate").(string) - block, _ := pem.Decode([]byte(certPem)) - if block == nil || len(block.Bytes) == 0 { - return logical.ErrorResponse("certificate could not be PEM-decoded"), nil - } - certs, err := x509.ParseCertificates(block.Bytes) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error parsing certificate: %s", err)), nil - } - if len(certs) != 1 { - return logical.ErrorResponse(fmt.Sprintf("%d certificates found in PEM file, expected 1", len(certs))), nil - } - - cert := certs[0] - if !cert.IsCA { - return logical.ErrorResponse("given certificate is not a CA certificate"), nil - } - if !reflect.DeepEqual(cert.Issuer, cert.Subject) { - return logical.ErrorResponse("given certificate is not self-issued"), nil - } - - var caErr error - signingBundle, caErr := fetchCAInfo(ctx, req) - switch caErr.(type) { - case errutil.UserError: - return nil, errutil.UserError{Err: fmt.Sprintf( - "could not fetch the CA certificate (was one set?): %s", caErr)} - case errutil.InternalError: - return nil, errutil.InternalError{Err: fmt.Sprintf( - "error fetching CA certificate: %s", caErr)} - } - - signingCB, err := signingBundle.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting raw signing bundle to cert bundle: {{err}}", err) - } - - urls := &urlEntries{} - if signingBundle.URLs != nil { - urls = signingBundle.URLs - } - cert.IssuingCertificateURL = urls.IssuingCertificates - cert.CRLDistributionPoints = urls.CRLDistributionPoints - cert.OCSPServer = urls.OCSPServers - - newCert, err := x509.CreateCertificate(rand.Reader, cert, signingBundle.Certificate, cert.PublicKey, signingBundle.PrivateKey) - if err != nil { - return nil, errwrap.Wrapf("error signing self-issued certificate: {{err}}", err) - } - if len(newCert) == 0 { - return nil, fmt.Errorf("nil cert was created when signing self-issued certificate") - } - pemCert := pem.EncodeToMemory(&pem.Block{ - Type: "CERTIFICATE", - Bytes: newCert, - }) - - return &logical.Response{ - Data: map[string]interface{}{ - "certificate": strings.TrimSpace(string(pemCert)), - "issuing_ca": signingCB.Certificate, - }, - }, nil -} - -const pathGenerateRootHelpSyn = ` -Generate a new CA certificate and private key used for signing. -` - -const pathGenerateRootHelpDesc = ` -See the API documentation for more information. -` - -const pathDeleteRootHelpSyn = ` -Deletes the root CA key to allow a new one to be generated. -` - -const pathDeleteRootHelpDesc = ` -See the API documentation for more information. -` - -const pathSignIntermediateHelpSyn = ` -Issue an intermediate CA certificate based on the provided CSR. -` - -const pathSignIntermediateHelpDesc = ` -see the API documentation for more information. -` - -const pathSignSelfIssuedHelpSyn = ` -Signs another CA's self-issued certificate. -` - -const pathSignSelfIssuedHelpDesc = ` -Signs another CA's self-issued certificate. This is most often used for rolling roots; unless you know you need this you probably want to use sign-intermediate instead. - -Note that this is a very privileged operation and should be extremely restricted in terms of who is allowed to use it. All values will be taken directly from the incoming certificate and only verification that it is self-issued will be performed. - -Configured URLs for CRLs/OCSP/etc. will be copied over and the issuer will be this mount's CA cert. Other than that, all other values will be used verbatim. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_tidy.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_tidy.go deleted file mode 100644 index e70473576..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/path_tidy.go +++ /dev/null @@ -1,229 +0,0 @@ -package pki - -import ( - "context" - "crypto/x509" - "fmt" - "net/http" - "sync/atomic" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathTidy(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "tidy", - Fields: map[string]*framework.FieldSchema{ - "tidy_cert_store": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Set to true to enable tidying up -the certificate store`, - }, - - "tidy_revocation_list": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Deprecated; synonym for 'tidy_revoked_certs`, - }, - - "tidy_revoked_certs": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Set to true to expire all revoked -certificates, even if their duration has not yet passed, removing -them both from the CRL and from storage. The CRL will be rotated -if this causes any values to be removed.`, - }, - - "safety_buffer": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `The amount of extra time that must have passed -beyond certificate expiration before it is removed -from the backend storage and/or revocation list. -Defaults to 72 hours.`, - Default: 259200, //72h, but TypeDurationSecond currently requires defaults to be int - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathTidyWrite, - }, - - HelpSynopsis: pathTidyHelpSyn, - HelpDescription: pathTidyHelpDesc, - } -} - -func (b *backend) pathTidyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - safetyBuffer := d.Get("safety_buffer").(int) - tidyCertStore := d.Get("tidy_cert_store").(bool) - tidyRevokedCerts := d.Get("tidy_revoked_certs").(bool) - tidyRevocationList := d.Get("tidy_revocation_list").(bool) - - if safetyBuffer < 1 { - return logical.ErrorResponse("safety_buffer must be greater than zero"), nil - } - - bufferDuration := time.Duration(safetyBuffer) * time.Second - - if !atomic.CompareAndSwapUint32(b.tidyCASGuard, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - // Tests using framework will screw up the storage so make a locally - // scoped req to hold a reference - req = &logical.Request{ - Storage: req.Storage, - } - - go func() { - defer atomic.StoreUint32(b.tidyCASGuard, 0) - - // Don't cancel when the original client request goes away - ctx = context.Background() - - logger := b.Logger().Named("tidy") - - doTidy := func() error { - if tidyCertStore { - serials, err := req.Storage.List(ctx, "certs/") - if err != nil { - return errwrap.Wrapf("error fetching list of certs: {{err}}", err) - } - - for _, serial := range serials { - certEntry, err := req.Storage.Get(ctx, "certs/"+serial) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching certificate %q: {{err}}", serial), err) - } - - if certEntry == nil { - logger.Warn("certificate entry is nil; tidying up since it is no longer useful for any server operations", "serial", serial) - if err := req.Storage.Delete(ctx, "certs/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting nil entry with serial %s: {{err}}", serial), err) - } - } - - if certEntry.Value == nil || len(certEntry.Value) == 0 { - logger.Warn("certificate entry has no value; tidying up since it is no longer useful for any server operations", "serial", serial) - if err := req.Storage.Delete(ctx, "certs/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting entry with nil value with serial %s: {{err}}", serial), err) - } - } - - cert, err := x509.ParseCertificate(certEntry.Value) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("unable to parse stored certificate with serial %q: {{err}}", serial), err) - } - - if time.Now().After(cert.NotAfter.Add(bufferDuration)) { - if err := req.Storage.Delete(ctx, "certs/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting serial %q from storage: {{err}}", serial), err) - } - } - } - } - - if tidyRevokedCerts || tidyRevocationList { - b.revokeStorageLock.Lock() - defer b.revokeStorageLock.Unlock() - - tidiedRevoked := false - - revokedSerials, err := req.Storage.List(ctx, "revoked/") - if err != nil { - return errwrap.Wrapf("error fetching list of revoked certs: {{err}}", err) - } - - var revInfo revocationInfo - for _, serial := range revokedSerials { - revokedEntry, err := req.Storage.Get(ctx, "revoked/"+serial) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("unable to fetch revoked cert with serial %q: {{err}}", serial), err) - } - - if revokedEntry == nil { - logger.Warn("revoked entry is nil; tidying up since it is no longer useful for any server operations", "serial", serial) - if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting nil revoked entry with serial %s: {{err}}", serial), err) - } - } - - if revokedEntry.Value == nil || len(revokedEntry.Value) == 0 { - logger.Warn("revoked entry has nil value; tidying up since it is no longer useful for any server operations", "serial", serial) - if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting revoked entry with nil value with serial %s: {{err}}", serial), err) - } - } - - err = revokedEntry.DecodeJSON(&revInfo) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error decoding revocation entry for serial %q: {{err}}", serial), err) - } - - revokedCert, err := x509.ParseCertificate(revInfo.CertificateBytes) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("unable to parse stored revoked certificate with serial %q: {{err}}", serial), err) - } - - if time.Now().After(revokedCert.NotAfter.Add(bufferDuration)) { - if err := req.Storage.Delete(ctx, "revoked/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting serial %q from revoked list: {{err}}", serial), err) - } - if err := req.Storage.Delete(ctx, "certs/"+serial); err != nil { - return errwrap.Wrapf(fmt.Sprintf("error deleting serial %q from store when tidying revoked: {{err}}", serial), err) - } - tidiedRevoked = true - } - } - - if tidiedRevoked { - if err := buildCRL(ctx, b, req, false); err != nil { - return err - } - } - } - - return nil - } - - if err := doTidy(); err != nil { - logger.Error("error running tidy", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -const pathTidyHelpSyn = ` -Tidy up the backend by removing expired certificates, revocation information, -or both. -` - -const pathTidyHelpDesc = ` -This endpoint allows expired certificates and/or revocation information to be -removed from the backend, freeing up storage and shortening CRLs. - -For safety, this function is a noop if called without parameters; cleanup from -normal certificate storage must be enabled with 'tidy_cert_store' and cleanup -from revocation information must be enabled with 'tidy_revocation_list'. - -The 'safety_buffer' parameter is useful to ensure that clock skew amongst your -hosts cannot lead to a certificate being removed from the CRL while it is still -considered valid by other hosts (for instance, if their clocks are a few -minutes behind). The 'safety_buffer' parameter can be an integer number of -seconds or a string duration like "72h". - -All certificates and/or revocation information currently stored in the backend -will be checked when this endpoint is hit. The expiration of the -certificate/revocation information of each certificate being held in -certificate storage or in revocation information will then be checked. If the -current time, minus the value of 'safety_buffer', is greater than the -expiration, it will be removed. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/secret_certs.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/secret_certs.go deleted file mode 100644 index 9c1734e31..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/secret_certs.go +++ /dev/null @@ -1,52 +0,0 @@ -package pki - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// SecretCertsType is the name used to identify this type -const SecretCertsType = "pki" - -func secretCerts(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCertsType, - Fields: map[string]*framework.FieldSchema{ - "certificate": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The PEM-encoded concatenated certificate and -issuing certificate authority`, - }, - "private_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The PEM-encoded private key for the certificate", - }, - "serial": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The serial number of the certificate, for handy -reference`, - }, - }, - - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.Secret == nil { - return nil, fmt.Errorf("secret is nil in request") - } - - serialInt, ok := req.Secret.InternalData["serial_number"] - if !ok { - return nil, fmt.Errorf("could not find serial in internal secret data") - } - - b.revokeStorageLock.Lock() - defer b.revokeStorageLock.Unlock() - - return revokeCert(ctx, b, req, serialInt.(string), true) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/pki/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/pki/util.go deleted file mode 100644 index 3dffb536b..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/pki/util.go +++ /dev/null @@ -1,7 +0,0 @@ -package pki - -import "strings" - -func normalizeSerial(serial string) string { - return strings.Replace(strings.ToLower(serial), ":", "-", -1) -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/backend.go deleted file mode 100644 index ad7c33328..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/backend.go +++ /dev/null @@ -1,172 +0,0 @@ -package postgresql - -import ( - "context" - "database/sql" - "fmt" - "strings" - "sync" - - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend(conf) - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathRoles(&b), - pathRoleCreate(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Clean: b.ResetDB, - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - - b.logger = conf.Logger - return &b -} - -type backend struct { - *framework.Backend - - db *sql.DB - lock sync.Mutex - - logger log.Logger -} - -// DB returns the database connection. -func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) { - b.logger.Debug("postgres/db: enter") - defer b.logger.Debug("postgres/db: exit") - - b.lock.Lock() - defer b.lock.Unlock() - - // If we already have a DB, we got it! - if b.db != nil { - if err := b.db.Ping(); err == nil { - return b.db, nil - } - // If the ping was unsuccessful, close it and ignore errors as we'll be - // reestablishing anyways - b.db.Close() - } - - // Otherwise, attempt to make connection - entry, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return nil, - fmt.Errorf("configure the DB connection with config/connection first") - } - - var connConfig connectionConfig - if err := entry.DecodeJSON(&connConfig); err != nil { - return nil, err - } - - conn := connConfig.ConnectionURL - if len(conn) == 0 { - conn = connConfig.ConnectionString - } - - // Ensure timezone is set to UTC for all the connections - if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") { - if strings.Contains(conn, "?") { - conn += "&timezone=utc" - } else { - conn += "?timezone=utc" - } - } else { - conn += " timezone=utc" - } - - b.db, err = sql.Open("postgres", conn) - if err != nil { - return nil, err - } - - // Set some connection pool settings. We don't need much of this, - // since the request rate shouldn't be high. - b.db.SetMaxOpenConns(connConfig.MaxOpenConnections) - b.db.SetMaxIdleConns(connConfig.MaxIdleConnections) - - return b.db, nil -} - -// ResetDB forces a connection next time DB() is called. -func (b *backend) ResetDB(_ context.Context) { - b.logger.Debug("postgres/db: enter") - defer b.logger.Debug("postgres/db: exit") - - b.lock.Lock() - defer b.lock.Unlock() - - if b.db != nil { - b.db.Close() - } - - b.db = nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/connection": - b.ResetDB(ctx) - } -} - -// Lease returns the lease information -func (b *backend) Lease(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -const backendHelp = ` -The PostgreSQL backend dynamically generates database users. - -After mounting this backend, configure it using the endpoints within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_connection.go deleted file mode 100644 index ae43a30e5..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_connection.go +++ /dev/null @@ -1,168 +0,0 @@ -package postgresql - -import ( - "context" - "database/sql" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - _ "github.com/lib/pq" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "connection_url": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DB connection string", - }, - - "value": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `DB connection string. Use 'connection_url' instead. -This will be deprecated.`, - }, - - "verify_connection": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, connection_url is verified by actually connecting to the database`, - }, - - "max_open_connections": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Maximum number of open connections to the database; -a zero uses the default value of two and a -negative value means unlimited`, - }, - - "max_idle_connections": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Maximum number of idle connections to the database; -a zero uses the value of max_open_connections -and a negative value disables idle connections. -If larger than max_open_connections it will be -reduced to the same size.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConnectionWrite, - logical.ReadOperation: b.pathConnectionRead, - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -// pathConnectionRead reads out the connection configuration -func (b *backend) pathConnectionRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - entry, err := req.Storage.Get(ctx, "config/connection") - if err != nil { - return nil, fmt.Errorf("failed to read connection configuration") - } - if entry == nil { - return nil, nil - } - - var config connectionConfig - if err := entry.DecodeJSON(&config); err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "max_open_connections": config.MaxOpenConnections, - "max_idle_connections": config.MaxIdleConnections, - }, - }, nil -} - -func (b *backend) pathConnectionWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - connValue := data.Get("value").(string) - connURL := data.Get("connection_url").(string) - if connURL == "" { - if connValue == "" { - return logical.ErrorResponse("connection_url parameter must be supplied"), nil - } else { - connURL = connValue - } - } - - maxOpenConns := data.Get("max_open_connections").(int) - if maxOpenConns == 0 { - maxOpenConns = 2 - } - - maxIdleConns := data.Get("max_idle_connections").(int) - if maxIdleConns == 0 { - maxIdleConns = maxOpenConns - } - if maxIdleConns > maxOpenConns { - maxIdleConns = maxOpenConns - } - - // Don't check the connection_url if verification is disabled - verifyConnection := data.Get("verify_connection").(bool) - if verifyConnection { - // Verify the string - db, err := sql.Open("postgres", connURL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - defer db.Close() - if err := db.Ping(); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error validating connection info: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ - ConnectionString: connValue, - ConnectionURL: connURL, - MaxOpenConnections: maxOpenConns, - MaxIdleConnections: maxIdleConns, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the DB connection - b.ResetDB(ctx) - - resp := &logical.Response{} - resp.AddWarning("Read access to this endpoint should be controlled via ACLs as it will return the connection string or URL as it is, including passwords, if any.") - - return resp, nil -} - -type connectionConfig struct { - ConnectionURL string `json:"connection_url" structs:"connection_url" mapstructure:"connection_url"` - // Deprecate "value" in coming releases - ConnectionString string `json:"value" structs:"value" mapstructure:"value"` - MaxOpenConnections int `json:"max_open_connections" structs:"max_open_connections" mapstructure:"max_open_connections"` - MaxIdleConnections int `json:"max_idle_connections" structs:"max_idle_connections" mapstructure:"max_idle_connections"` -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection string to talk to PostgreSQL. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection string used to connect to PostgreSQL. -The value of the string can be a URL, or a PG style string in the -format of "user=foo host=bar" etc. - -The URL looks like: -"postgresql://user:pass@host:port/dbname" - -When configuring the connection string, the backend will verify its validity. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_lease.go deleted file mode 100644 index 54bc9b2ca..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_config_lease.go +++ /dev/null @@ -1,102 +0,0 @@ -package postgresql - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "lease": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Default lease for roles.", - }, - - "lease_max": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Maximum time a credential is valid for.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathLeaseRead, - logical.UpdateOperation: b.pathLeaseWrite, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -func (b *backend) pathLeaseWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - leaseRaw := d.Get("lease").(string) - leaseMaxRaw := d.Get("lease_max").(string) - - lease, err := time.ParseDuration(leaseRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease: %s", err)), nil - } - leaseMax, err := time.ParseDuration(leaseMaxRaw) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Invalid lease: %s", err)), nil - } - - // Store it - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - Lease: lease, - LeaseMax: leaseMax, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lease, err := b.Lease(ctx, req.Storage) - - if err != nil { - return nil, err - } - if lease == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "lease": lease.Lease.String(), - "lease_max": lease.LeaseMax.String(), - }, - }, nil -} - -type configLease struct { - Lease time.Duration - LeaseMax time.Duration -} - -const pathConfigLeaseHelpSyn = ` -Configure the default lease information for generated credentials. -` - -const pathConfigLeaseHelpDesc = ` -This configures the default lease information used for credentials -generated by this backend. The lease specifies the duration that a -credential will be valid for, as well as the maximum session for -a set of credentials. - -The format for the lease is "1h" or integer and then unit. The longest -unit is hour. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_role_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_role_create.go deleted file mode 100644 index 113e3ab89..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_role_create.go +++ /dev/null @@ -1,149 +0,0 @@ -package postgresql - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - _ "github.com/lib/pq" -) - -func pathRoleCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleCreateRead, - }, - - HelpSynopsis: pathRoleCreateReadHelpSyn, - HelpDescription: pathRoleCreateReadHelpDesc, - } -} - -func (b *backend) pathRoleCreateRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - // Determine if we have a lease - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - // Unlike some other backends we need a lease here (can't leave as 0 and - // let core fill it in) because Postgres also expires users as a safety - // measure, so cannot be zero - if lease == nil { - lease = &configLease{ - Lease: b.System().DefaultLeaseTTL(), - } - } - - // Generate the username, password and expiration. PG limits user to 63 characters - displayName := req.DisplayName - if len(displayName) > 26 { - displayName = displayName[:26] - } - userUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - username := fmt.Sprintf("%s-%s", displayName, userUUID) - if len(username) > 63 { - username = username[:63] - } - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - ttl, _, err := framework.CalculateTTL(b.System(), 0, lease.Lease, 0, lease.LeaseMax, 0, time.Time{}) - if err != nil { - return nil, err - } - expiration := time.Now(). - Add(ttl). - Format("2006-01-02 15:04:05-0700") - - // Get our handle - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Start a transaction - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer func() { - tx.Rollback() - }() - - // Execute each query - for _, query := range strutil.ParseArbitraryStringSlice(role.SQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - "password": password, - "expiration": expiration, - } - - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - - // Commit the transaction - - if err := tx.Commit(); err != nil { - return nil, err - } - - // Return the secret - - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - "role": name, - }) - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - return resp, nil -} - -const pathRoleCreateReadHelpSyn = ` -Request database credentials for a certain role. -` - -const pathRoleCreateReadHelpDesc = ` -This path reads database credentials for a certain role. The -database credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_roles.go deleted file mode 100644 index 83400e908..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/path_roles.go +++ /dev/null @@ -1,197 +0,0 @@ -package postgresql - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the role.", - }, - - "sql": { - Type: framework.TypeString, - Description: "SQL string to create a user. See help for more info.", - }, - - "revocation_sql": { - Type: framework.TypeString, - Description: `SQL statements to be executed to revoke a user. Must be a semicolon-separated -string, a base64-encoded semicolon-separated string, a serialized JSON string -array, or a base64-encoded serialized JSON string array. The '{{name}}' value -will be substituted.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleCreate, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) Role(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "role/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := b.Role(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "sql": role.SQL, - "revocation_sql": role.RevocationSQL, - }, - }, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathRoleCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - sql := data.Get("sql").(string) - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Test the query by trying to prepare it - for _, query := range strutil.ParseArbitraryStringSlice(sql, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - stmt, err := db.Prepare(Query(query, map[string]string{ - "name": "foo", - "password": "bar", - "expiration": "", - })) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error testing query: %s", err)), nil - } - stmt.Close() - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, &roleEntry{ - SQL: sql, - RevocationSQL: data.Get("revocation_sql").(string), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -type roleEntry struct { - SQL string `json:"sql" mapstructure:"sql" structs:"sql"` - RevocationSQL string `json:"revocation_sql" mapstructure:"revocation_sql" structs:"revocation_sql"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "sql" parameter customizes the SQL string used to create the role. -This can be a sequence of SQL queries. Some substitution will be done to the -SQL string for certain keys. The names of the variables must be surrounded -by "{{" and "}}" to be replaced. - - * "name" - The random username generated for the DB user. - - * "password" - The random password generated for the DB user. - - * "expiration" - The timestamp when this user will expire. - -Example of a decent SQL query to use: - - CREATE ROLE "{{name}}" WITH - LOGIN - PASSWORD '{{password}}' - VALID UNTIL '{{expiration}}'; - GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}"; - -Note the above user would be able to access everything in schema public. -For more complex GRANT clauses, see the PostgreSQL manual. - -The "revocation_sql" parameter customizes the SQL string used to revoke a user. -Example of a decent revocation SQL query to use: - - REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM {{name}}; - REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM {{name}}; - REVOKE USAGE ON SCHEMA public FROM {{name}}; - DROP ROLE IF EXISTS {{name}}; -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/query.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/query.go deleted file mode 100644 index e4f7f59dd..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/query.go +++ /dev/null @@ -1,15 +0,0 @@ -package postgresql - -import ( - "fmt" - "strings" -) - -// Query templates a query for us. -func Query(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/secret_creds.go deleted file mode 100644 index d00beacb6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/postgresql/secret_creds.go +++ /dev/null @@ -1,269 +0,0 @@ -package postgresql - -import ( - "context" - "database/sql" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/dbtxn" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/lib/pq" -) - -const SecretCredsType = "creds" - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username", - }, - - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password", - }, - }, - - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("usernameRaw is not a string") - } - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - // Get the lease information - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - - // Make sure we increase the VALID UNTIL endpoint for this user. - ttl, _, err := framework.CalculateTTL(b.System(), req.Secret.Increment, lease.Lease, 0, lease.LeaseMax, 0, req.Secret.IssueTime) - if err != nil { - return nil, err - } - if ttl > 0 { - expireTime := time.Now().Add(ttl) - // Adding a small buffer since the TTL will be calculated again afeter this call - // to ensure the database credential does not expire before the lease - expireTime = expireTime.Add(5 * time.Second) - expiration := expireTime.Format("2006-01-02 15:04:05-0700") - - query := fmt.Sprintf( - "ALTER ROLE %s VALID UNTIL '%s';", - pq.QuoteIdentifier(username), - expiration) - stmt, err := db.Prepare(query) - if err != nil { - return nil, err - } - defer stmt.Close() - if _, err := stmt.Exec(); err != nil { - return nil, err - } - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = lease.Lease - resp.Secret.MaxTTL = lease.LeaseMax - return resp, nil -} - -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username, ok := usernameRaw.(string) - if !ok { - return nil, fmt.Errorf("usernameRaw is not a string") - } - var revocationSQL string - var resp *logical.Response - - roleNameRaw, ok := req.Secret.InternalData["role"] - if ok { - role, err := b.Role(ctx, req.Storage, roleNameRaw.(string)) - if err != nil { - return nil, err - } - if role == nil { - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning(fmt.Sprintf("Role %q cannot be found. Using default revocation SQL.", roleNameRaw.(string))) - } else { - revocationSQL = role.RevocationSQL - } - } - - // Get our connection - db, err := b.DB(ctx, req.Storage) - if err != nil { - return nil, err - } - - switch revocationSQL { - - // This is the default revocation logic. If revocation SQL is provided it - // is simply executed as-is. - case "": - // Check if the role exists - var exists bool - err = db.QueryRow("SELECT exists (SELECT rolname FROM pg_roles WHERE rolname=$1);", username).Scan(&exists) - if err != nil && err != sql.ErrNoRows { - return nil, err - } - - if exists == false { - return resp, nil - } - - // Query for permissions; we need to revoke permissions before we can drop - // the role - // This isn't done in a transaction because even if we fail along the way, - // we want to remove as much access as possible - stmt, err := db.Prepare("SELECT DISTINCT table_schema FROM information_schema.role_column_grants WHERE grantee=$1;") - if err != nil { - return nil, err - } - defer stmt.Close() - - rows, err := stmt.Query(username) - if err != nil { - return nil, err - } - defer rows.Close() - - const initialNumRevocations = 16 - revocationStmts := make([]string, 0, initialNumRevocations) - for rows.Next() { - var schema string - err = rows.Scan(&schema) - if err != nil { - // keep going; remove as many permissions as possible right now - continue - } - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %s FROM %s;`, - pq.QuoteIdentifier(schema), - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE USAGE ON SCHEMA %s FROM %s;`, - pq.QuoteIdentifier(schema), - pq.QuoteIdentifier(username))) - } - - // for good measure, revoke all privileges and usage on schema public - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM %s;`, - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - "REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM %s;", - pq.QuoteIdentifier(username))) - - revocationStmts = append(revocationStmts, fmt.Sprintf( - "REVOKE USAGE ON SCHEMA public FROM %s;", - pq.QuoteIdentifier(username))) - - // get the current database name so we can issue a REVOKE CONNECT for - // this username - var dbname sql.NullString - if err := db.QueryRow("SELECT current_database();").Scan(&dbname); err != nil { - return nil, err - } - - if dbname.Valid { - revocationStmts = append(revocationStmts, fmt.Sprintf( - `REVOKE CONNECT ON DATABASE %s FROM %s;`, - pq.QuoteIdentifier(dbname.String), - pq.QuoteIdentifier(username))) - } - - // again, here, we do not stop on error, as we want to remove as - // many permissions as possible right now - var lastStmtError error - for _, query := range revocationStmts { - if err := dbtxn.ExecuteDBQuery(ctx, db, nil, query); err != nil { - lastStmtError = err - } - } - - // can't drop if not all privileges are revoked - if rows.Err() != nil { - return nil, errwrap.Wrapf("could not generate revocation statements for all rows: {{err}}", rows.Err()) - } - if lastStmtError != nil { - return nil, errwrap.Wrapf("could not perform all revocation statements: {{err}}", lastStmtError) - } - - // Drop this user - stmt, err = db.Prepare(fmt.Sprintf( - `DROP ROLE IF EXISTS %s;`, pq.QuoteIdentifier(username))) - if err != nil { - return nil, err - } - defer stmt.Close() - if _, err := stmt.Exec(); err != nil { - return nil, err - } - - // We have revocation SQL, execute directly, within a transaction - default: - tx, err := db.Begin() - if err != nil { - return nil, err - } - defer func() { - tx.Rollback() - }() - - for _, query := range strutil.ParseArbitraryStringSlice(revocationSQL, ";") { - query = strings.TrimSpace(query) - if len(query) == 0 { - continue - } - - m := map[string]string{ - "name": username, - } - if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil { - return nil, err - } - } - - if err := tx.Commit(); err != nil { - return nil, err - } - } - - return resp, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/backend.go deleted file mode 100644 index 854329776..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/backend.go +++ /dev/null @@ -1,145 +0,0 @@ -package rabbitmq - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/michaelklishin/rabbit-hole" -) - -// Factory creates and configures the backend -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Creates a new backend with all the paths and secrets belonging to it -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "config/connection", - }, - }, - - Paths: []*framework.Path{ - pathConfigConnection(&b), - pathConfigLease(&b), - pathListRoles(&b), - pathCreds(&b), - pathRoles(&b), - }, - - Secrets: []*framework.Secret{ - secretCreds(&b), - }, - - Clean: b.resetClient, - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - - return &b -} - -type backend struct { - *framework.Backend - - client *rabbithole.Client - lock sync.RWMutex -} - -// DB returns the database connection. -func (b *backend) Client(ctx context.Context, s logical.Storage) (*rabbithole.Client, error) { - b.lock.RLock() - - // If we already have a client, return it - if b.client != nil { - b.lock.RUnlock() - return b.client, nil - } - - b.lock.RUnlock() - - // Otherwise, attempt to make connection - entry, err := s.Get(ctx, "config/connection") - if err != nil { - return nil, err - } - if entry == nil { - return nil, fmt.Errorf("configure the client connection with config/connection first") - } - - var connConfig connectionConfig - if err := entry.DecodeJSON(&connConfig); err != nil { - return nil, err - } - - b.lock.Lock() - defer b.lock.Unlock() - - // If the client was created during the lock switch, return it - if b.client != nil { - return b.client, nil - } - - b.client, err = rabbithole.NewClient(connConfig.URI, connConfig.Username, connConfig.Password) - if err != nil { - return nil, err - } - // Use a default pooled transport so there would be no leaked file descriptors - b.client.SetTransport(cleanhttp.DefaultPooledTransport()) - - return b.client, nil -} - -// resetClient forces a connection next time Client() is called. -func (b *backend) resetClient(_ context.Context) { - b.lock.Lock() - defer b.lock.Unlock() - - b.client = nil -} - -func (b *backend) invalidate(ctx context.Context, key string) { - switch key { - case "config/connection": - b.resetClient(ctx) - } -} - -// Lease returns the lease information -func (b *backend) Lease(ctx context.Context, s logical.Storage) (*configLease, error) { - entry, err := s.Get(ctx, "config/lease") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result configLease - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -const backendHelp = ` -The RabbitMQ backend dynamically generates RabbitMQ users. - -After mounting this backend, configure it using the endpoints within -the "config/" path. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_connection.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_connection.go deleted file mode 100644 index db2fb3c78..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_connection.go +++ /dev/null @@ -1,119 +0,0 @@ -package rabbitmq - -import ( - "context" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/michaelklishin/rabbit-hole" -) - -func pathConfigConnection(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/connection", - Fields: map[string]*framework.FieldSchema{ - "connection_uri": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "RabbitMQ Management URI", - }, - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username of a RabbitMQ management administrator", - }, - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password of the provided RabbitMQ management user", - }, - "verify_connection": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: `If set, connection_uri is verified by actually connecting to the RabbitMQ management API`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConnectionUpdate, - }, - - HelpSynopsis: pathConfigConnectionHelpSyn, - HelpDescription: pathConfigConnectionHelpDesc, - } -} - -func (b *backend) pathConnectionUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - uri := data.Get("connection_uri").(string) - if uri == "" { - return logical.ErrorResponse("missing connection_uri"), nil - } - - username := data.Get("username").(string) - if username == "" { - return logical.ErrorResponse("missing username"), nil - } - - password := data.Get("password").(string) - if password == "" { - return logical.ErrorResponse("missing password"), nil - } - - // Don't check the connection_url if verification is disabled - verifyConnection := data.Get("verify_connection").(bool) - if verifyConnection { - // Create RabbitMQ management client - client, err := rabbithole.NewClient(uri, username, password) - if err != nil { - return nil, errwrap.Wrapf("failed to create client: {{err}}", err) - } - - // Verify that configured credentials is capable of listing - if _, err = client.ListUsers(); err != nil { - return nil, errwrap.Wrapf("failed to validate the connection: {{err}}", err) - } - } - - // Store it - entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{ - URI: uri, - Username: username, - Password: password, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - // Reset the client connection - b.resetClient(ctx) - - return nil, nil -} - -// connectionConfig contains the information required to make a connection to a RabbitMQ node -type connectionConfig struct { - // URI of the RabbitMQ server - URI string `json:"connection_uri"` - - // Username which has 'administrator' tag attached to it - Username string `json:"username"` - - // Password for the Username - Password string `json:"password"` -} - -const pathConfigConnectionHelpSyn = ` -Configure the connection URI, username, and password to talk to RabbitMQ management HTTP API. -` - -const pathConfigConnectionHelpDesc = ` -This path configures the connection properties used to connect to RabbitMQ management HTTP API. -The "connection_uri" parameter is a string that is used to connect to the API. The "username" -and "password" parameters are strings that are used as credentials to the API. The "verify_connection" -parameter is a boolean that is used to verify whether the provided connection URI, username, and password -are valid. - -The URI looks like: -"http://localhost:15672" -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_lease.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_lease.go deleted file mode 100644 index 55d95073f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_config_lease.go +++ /dev/null @@ -1,84 +0,0 @@ -package rabbitmq - -import ( - "context" - "time" - - "github.com/fatih/structs" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathConfigLease(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/lease", - Fields: map[string]*framework.FieldSchema{ - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "Duration before which the issued credentials needs renewal", - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: `Duration after which the issued credentials should not be allowed to be renewed`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathLeaseRead, - logical.UpdateOperation: b.pathLeaseUpdate, - }, - - HelpSynopsis: pathConfigLeaseHelpSyn, - HelpDescription: pathConfigLeaseHelpDesc, - } -} - -// Sets the lease configuration parameters -func (b *backend) pathLeaseUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := logical.StorageEntryJSON("config/lease", &configLease{ - TTL: time.Second * time.Duration(d.Get("ttl").(int)), - MaxTTL: time.Second * time.Duration(d.Get("max_ttl").(int)), - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -// Returns the lease configuration parameters -func (b *backend) pathLeaseRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - return nil, nil - } - - lease.TTL = lease.TTL / time.Second - lease.MaxTTL = lease.MaxTTL / time.Second - - return &logical.Response{ - Data: structs.New(lease).Map(), - }, nil -} - -// Lease configuration information for the secrets issued by this backend -type configLease struct { - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl"` - MaxTTL time.Duration `json:"max_ttl" structs:"max_ttl" mapstructure:"max_ttl"` -} - -var pathConfigLeaseHelpSyn = "Configure the lease parameters for generated credentials" - -var pathConfigLeaseHelpDesc = ` -Sets the ttl and max_ttl values for the secrets to be issued by this backend. -Both ttl and max_ttl takes in an integer number of seconds as input as well as -inputs like "1h". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_role_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_role_create.go deleted file mode 100644 index 6cbced5ac..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_role_create.go +++ /dev/null @@ -1,126 +0,0 @@ -package rabbitmq - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/michaelklishin/rabbit-hole" -) - -func pathCreds(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathCredsRead, - }, - - HelpSynopsis: pathRoleCreateReadHelpSyn, - HelpDescription: pathRoleCreateReadHelpDesc, - } -} - -// Issues the credential based on the role name -func (b *backend) pathCredsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if name == "" { - return logical.ErrorResponse("missing name"), nil - } - - // Get the role - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", name)), nil - } - - // Ensure username is unique - uuidVal, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - username := fmt.Sprintf("%s-%s", req.DisplayName, uuidVal) - - password, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - - // Get the client configuration - client, err := b.Client(ctx, req.Storage) - if err != nil { - return nil, err - } - if client == nil { - return logical.ErrorResponse("failed to get the client"), nil - } - - // Register the generated credentials in the backend, with the RabbitMQ server - if _, err = client.PutUser(username, rabbithole.UserSettings{ - Password: password, - Tags: role.Tags, - }); err != nil { - return nil, fmt.Errorf("failed to create a new user with the generated credentials") - } - - // If the role had vhost permissions specified, assign those permissions - // to the created username for respective vhosts. - for vhost, permission := range role.VHosts { - if _, err := client.UpdatePermissionsIn(vhost, username, rabbithole.Permissions{ - Configure: permission.Configure, - Write: permission.Write, - Read: permission.Read, - }); err != nil { - outerErr := errwrap.Wrapf(fmt.Sprintf("failed to update permissions to the %q user: {{err}}", username), err) - // Delete the user because it's in an unknown state - if _, rmErr := client.DeleteUser(username); rmErr != nil { - return nil, multierror.Append(errwrap.Wrapf("failed to delete user: {{err}}", rmErr), outerErr) - } - return nil, outerErr - } - } - - // Return the secret - resp := b.Secret(SecretCredsType).Response(map[string]interface{}{ - "username": username, - "password": password, - }, map[string]interface{}{ - "username": username, - }) - - // Determine if we have a lease - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - - if lease != nil { - resp.Secret.TTL = lease.TTL - resp.Secret.MaxTTL = lease.MaxTTL - } - - return resp, nil -} - -const pathRoleCreateReadHelpSyn = ` -Request RabbitMQ credentials for a certain role. -` - -const pathRoleCreateReadHelpDesc = ` -This path reads RabbitMQ credentials for a certain role. The -RabbitMQ credentials will be generated on demand and will be automatically -revoked when the lease is up. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_roles.go deleted file mode 100644 index a1e97299e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/path_roles.go +++ /dev/null @@ -1,181 +0,0 @@ -package rabbitmq - -import ( - "context" - "fmt" - - "github.com/fatih/structs" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role.", - }, - "tags": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Comma-separated list of tags for this role.", - }, - "vhosts": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "A map of virtual hosts to permissions.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleUpdate, - logical.DeleteOperation: b.pathRoleDelete, - }, - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -// Reads the role configuration from the storage -func (b *backend) Role(ctx context.Context, s logical.Storage, n string) (*roleEntry, error) { - entry, err := s.Get(ctx, "role/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result roleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// Deletes an existing role -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if name == "" { - return logical.ErrorResponse("missing name"), nil - } - - return nil, req.Storage.Delete(ctx, "role/"+name) -} - -// Reads an existing role -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if name == "" { - return logical.ErrorResponse("missing name"), nil - } - - role, err := b.Role(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - return &logical.Response{ - Data: structs.New(role).Map(), - }, nil -} - -// Lists all the roles registered with the backend -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roles, err := req.Storage.List(ctx, "role/") - if err != nil { - return nil, err - } - - return logical.ListResponse(roles), nil -} - -// Registers a new role with the backend -func (b *backend) pathRoleUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - if name == "" { - return logical.ErrorResponse("missing name"), nil - } - - tags := d.Get("tags").(string) - rawVHosts := d.Get("vhosts").(string) - - if tags == "" && rawVHosts == "" { - return logical.ErrorResponse("both tags and vhosts not specified"), nil - } - - var vhosts map[string]vhostPermission - if len(rawVHosts) > 0 { - if err := jsonutil.DecodeJSON([]byte(rawVHosts), &vhosts); err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to unmarshal vhosts: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("role/"+name, &roleEntry{ - Tags: tags, - VHosts: vhosts, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -// Role that defines the capabilities of the credentials issued against it -type roleEntry struct { - Tags string `json:"tags" structs:"tags" mapstructure:"tags"` - VHosts map[string]vhostPermission `json:"vhosts" structs:"vhosts" mapstructure:"vhosts"` -} - -// Structure representing the permissions of a vhost -type vhostPermission struct { - Configure string `json:"configure" structs:"configure" mapstructure:"configure"` - Write string `json:"write" structs:"write" mapstructure:"write"` - Read string `json:"read" structs:"read" mapstructure:"read"` -} - -const pathRoleHelpSyn = ` -Manage the roles that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path lets you manage the roles that can be created with this backend. - -The "tags" parameter customizes the tags used to create the role. -This is a comma separated list of strings. The "vhosts" parameter customizes -the virtual hosts that this user will be associated with. This is a JSON object -passed as a string in the form: -{ - "vhostOne": { - "configure": ".*", - "write": ".*", - "read": ".*" - }, - "vhostTwo": { - "configure": ".*", - "write": ".*", - "read": ".*" - } -} -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/secret_creds.go b/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/secret_creds.go deleted file mode 100644 index 3962c7bf8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/rabbitmq/secret_creds.go +++ /dev/null @@ -1,70 +0,0 @@ -package rabbitmq - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// SecretCredsType is the key for this backend's secrets. -const SecretCredsType = "creds" - -func secretCreds(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretCredsType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "RabbitMQ username", - }, - "password": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Password for the RabbitMQ username", - }, - }, - Renew: b.secretCredsRenew, - Revoke: b.secretCredsRevoke, - } -} - -// Renew the previously issued secret -func (b *backend) secretCredsRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the lease information - lease, err := b.Lease(ctx, req.Storage) - if err != nil { - return nil, err - } - if lease == nil { - lease = &configLease{} - } - - resp := &logical.Response{Secret: req.Secret} - resp.Secret.TTL = lease.TTL - resp.Secret.MaxTTL = lease.MaxTTL - return resp, nil -} - -// Revoke the previously issued secret -func (b *backend) secretCredsRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // Get the username from the internal data - usernameRaw, ok := req.Secret.InternalData["username"] - if !ok { - return nil, fmt.Errorf("secret is missing username internal data") - } - username := usernameRaw.(string) - - // Get our connection - client, err := b.Client(ctx, req.Storage) - if err != nil { - return nil, err - } - - if _, err = client.DeleteUser(username); err != nil { - return nil, errwrap.Wrapf("could not delete user: {{err}}", err) - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/backend.go deleted file mode 100644 index 0616b8f78..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/backend.go +++ /dev/null @@ -1,125 +0,0 @@ -package ssh - -import ( - "context" - "strings" - "sync" - - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -type backend struct { - *framework.Backend - view logical.Storage - salt *salt.Salt - saltMutex sync.RWMutex -} - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b, err := Backend(conf) - if err != nil { - return nil, err - } - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) (*backend, error) { - var b backend - b.view = conf.StorageView - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - Unauthenticated: []string{ - "verify", - "public_key", - }, - - LocalStorage: []string{ - "otp/", - }, - - SealWrapStorage: []string{ - caPrivateKey, - caPrivateKeyStoragePath, - "keys/", - }, - }, - - Paths: []*framework.Path{ - pathConfigZeroAddress(&b), - pathKeys(&b), - pathListRoles(&b), - pathRoles(&b), - pathCredsCreate(&b), - pathLookup(&b), - pathVerify(&b), - pathConfigCA(&b), - pathSign(&b), - pathFetchPublicKey(&b), - }, - - Secrets: []*framework.Secret{ - secretDynamicKey(&b), - secretOTP(&b), - }, - - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - return &b, nil -} - -func (b *backend) Salt(ctx context.Context) (*salt.Salt, error) { - b.saltMutex.RLock() - if b.salt != nil { - defer b.saltMutex.RUnlock() - return b.salt, nil - } - b.saltMutex.RUnlock() - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - if b.salt != nil { - return b.salt, nil - } - salt, err := salt.NewSalt(ctx, b.view, &salt.Config{ - HashFunc: salt.SHA256Hash, - Location: salt.DefaultLocation, - }) - if err != nil { - return nil, err - } - b.salt = salt - return salt, nil -} - -func (b *backend) invalidate(_ context.Context, key string) { - switch key { - case salt.DefaultLocation: - b.saltMutex.Lock() - defer b.saltMutex.Unlock() - b.salt = nil - } -} - -const backendHelp = ` -The SSH backend generates credentials allowing clients to establish SSH -connections to remote hosts. - -There are three variants of the backend, which generate different types of -credentials: dynamic keys, One-Time Passwords (OTPs) and certificate authority. The desired behavior -is role-specific and chosen at role creation time with the 'key_type' -parameter. - -Please see the backend documentation for a thorough description of both -types. The Vault team strongly recommends the OTP type. - -After mounting this backend, before generating credentials, configure the -backend's lease behavior using the 'config/lease' endpoint and create roles -using the 'roles/' endpoint. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/communicator.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/communicator.go deleted file mode 100644 index 8bcd3ec40..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/communicator.go +++ /dev/null @@ -1,351 +0,0 @@ -package ssh - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "path/filepath" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/agent" -) - -type comm struct { - client *ssh.Client - config *SSHCommConfig - conn net.Conn - address string -} - -// SSHCommConfig is the structure used to configure the SSH communicator. -type SSHCommConfig struct { - // The configuration of the Go SSH connection - SSHConfig *ssh.ClientConfig - - // Connection returns a new connection. The current connection - // in use will be closed as part of the Close method, or in the - // case an error occurs. - Connection func() (net.Conn, error) - - // Pty, if true, will request a pty from the remote end. - Pty bool - - // DisableAgent, if true, will not forward the SSH agent. - DisableAgent bool - - // Logger for output - Logger log.Logger -} - -// Creates a new communicator implementation over SSH. This takes -// an already existing TCP connection and SSH configuration. -func SSHCommNew(address string, config *SSHCommConfig) (result *comm, err error) { - // Establish an initial connection and connect - result = &comm{ - config: config, - address: address, - } - - if err = result.reconnect(); err != nil { - result = nil - return - } - - return -} - -func (c *comm) Close() error { - var err error - if c.conn != nil { - err = c.conn.Close() - } - c.conn = nil - c.client = nil - return err -} - -func (c *comm) Upload(path string, input io.Reader, fi *os.FileInfo) error { - // The target directory and file for talking the SCP protocol - target_dir := filepath.Dir(path) - target_file := filepath.Base(path) - - // On windows, filepath.Dir uses backslash separators (ie. "\tmp"). - // This does not work when the target host is unix. Switch to forward slash - // which works for unix and windows - target_dir = filepath.ToSlash(target_dir) - - scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error { - return scpUploadFile(target_file, input, w, stdoutR, fi) - } - - return c.scpSession("scp -vt "+target_dir, scpFunc) -} - -func (c *comm) NewSession() (session *ssh.Session, err error) { - if c.client == nil { - err = errors.New("client not available") - } else { - session, err = c.client.NewSession() - } - - if err != nil { - c.config.Logger.Error("ssh session open error, attempting reconnect", "error", err) - if err := c.reconnect(); err != nil { - c.config.Logger.Error("reconnect attempt failed", "error", err) - return nil, err - } - - return c.client.NewSession() - } - - return session, nil -} - -func (c *comm) reconnect() error { - // Close previous connection. - if c.conn != nil { - c.Close() - } - - var err error - c.conn, err = c.config.Connection() - if err != nil { - // Explicitly set this to the REAL nil. Connection() can return - // a nil implementation of net.Conn which will make the - // "if c.conn == nil" check fail above. Read here for more information - // on this psychotic language feature: - // - // http://golang.org/doc/faq#nil_error - c.conn = nil - c.config.Logger.Error("reconnection error", "error", err) - return err - } - - sshConn, sshChan, req, err := ssh.NewClientConn(c.conn, c.address, c.config.SSHConfig) - if err != nil { - c.config.Logger.Error("handshake error", "error", err) - c.Close() - return err - } - if sshConn != nil { - c.client = ssh.NewClient(sshConn, sshChan, req) - } - c.connectToAgent() - - return nil -} - -func (c *comm) connectToAgent() { - if c.client == nil { - return - } - - if c.config.DisableAgent { - return - } - - // open connection to the local agent - socketLocation := os.Getenv("SSH_AUTH_SOCK") - if socketLocation == "" { - return - } - agentConn, err := net.Dial("unix", socketLocation) - if err != nil { - c.config.Logger.Error("could not connect to local agent socket", "socket_path", socketLocation) - return - } - defer agentConn.Close() - - // create agent and add in auth - forwardingAgent := agent.NewClient(agentConn) - if forwardingAgent == nil { - c.config.Logger.Error("could not create agent client") - return - } - - // add callback for forwarding agent to SSH config - // XXX - might want to handle reconnects appending multiple callbacks - auth := ssh.PublicKeysCallback(forwardingAgent.Signers) - c.config.SSHConfig.Auth = append(c.config.SSHConfig.Auth, auth) - agent.ForwardToAgent(c.client, forwardingAgent) - - // Setup a session to request agent forwarding - session, err := c.NewSession() - if err != nil { - return - } - defer session.Close() - - err = agent.RequestAgentForwarding(session) - if err != nil { - c.config.Logger.Error("error requesting agent forwarding", "error", err) - return - } - return -} - -func (c *comm) scpSession(scpCommand string, f func(io.Writer, *bufio.Reader) error) error { - session, err := c.NewSession() - if err != nil { - return err - } - defer session.Close() - - // Get a pipe to stdin so that we can send data down - stdinW, err := session.StdinPipe() - if err != nil { - return err - } - - // We only want to close once, so we nil w after we close it, - // and only close in the defer if it hasn't been closed already. - defer func() { - if stdinW != nil { - stdinW.Close() - } - }() - - // Get a pipe to stdout so that we can get responses back - stdoutPipe, err := session.StdoutPipe() - if err != nil { - return err - } - stdoutR := bufio.NewReader(stdoutPipe) - - // Set stderr to a bytes buffer - stderr := new(bytes.Buffer) - session.Stderr = stderr - - // Start the sink mode on the other side - if err := session.Start(scpCommand); err != nil { - return err - } - - // Call our callback that executes in the context of SCP. We ignore - // EOF errors if they occur because it usually means that SCP prematurely - // ended on the other side. - if err := f(stdinW, stdoutR); err != nil && err != io.EOF { - return err - } - - // Close the stdin, which sends an EOF, and then set w to nil so that - // our defer func doesn't close it again since that is unsafe with - // the Go SSH package. - stdinW.Close() - stdinW = nil - - // Wait for the SCP connection to close, meaning it has consumed all - // our data and has completed. Or has errored. - err = session.Wait() - if err != nil { - if exitErr, ok := err.(*ssh.ExitError); ok { - // Otherwise, we have an ExitErorr, meaning we can just read - // the exit status - c.config.Logger.Error("got non-zero exit status", "exit_status", exitErr.ExitStatus()) - - // If we exited with status 127, it means SCP isn't available. - // Return a more descriptive error for that. - if exitErr.ExitStatus() == 127 { - return errors.New( - "SCP failed to start. This usually means that SCP is not\n" + - "properly installed on the remote system.") - } - } - - return err - } - return nil -} - -// checkSCPStatus checks that a prior command sent to SCP completed -// successfully. If it did not complete successfully, an error will -// be returned. -func checkSCPStatus(r *bufio.Reader) error { - code, err := r.ReadByte() - if err != nil { - return err - } - - if code != 0 { - // Treat any non-zero (really 1 and 2) as fatal errors - message, _, err := r.ReadLine() - if err != nil { - return errwrap.Wrapf("error reading error message: {{err}}", err) - } - - return errors.New(string(message)) - } - - return nil -} - -func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi *os.FileInfo) error { - var mode os.FileMode - var size int64 - - if fi != nil && (*fi).Mode().IsRegular() { - mode = (*fi).Mode().Perm() - size = (*fi).Size() - } else { - // Create a temporary file where we can copy the contents of the src - // so that we can determine the length, since SCP is length-prefixed. - tf, err := ioutil.TempFile("", "vault-ssh-upload") - if err != nil { - return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) - } - defer os.Remove(tf.Name()) - defer tf.Close() - - mode = 0644 - - if _, err := io.Copy(tf, src); err != nil { - return err - } - - // Sync the file so that the contents are definitely on disk, then - // read the length of it. - if err := tf.Sync(); err != nil { - return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) - } - - // Seek the file to the beginning so we can re-read all of it - if _, err := tf.Seek(0, 0); err != nil { - return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) - } - - tfi, err := tf.Stat() - if err != nil { - return errwrap.Wrapf("error creating temporary file for upload: {{err}}", err) - } - - size = tfi.Size() - src = tf - } - - // Start the protocol - perms := fmt.Sprintf("C%04o", mode) - - fmt.Fprintln(w, perms, size, dst) - if err := checkSCPStatus(r); err != nil { - return err - } - - if _, err := io.CopyN(w, src, size); err != nil { - return err - } - - fmt.Fprint(w, "\x00") - if err := checkSCPStatus(r); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/linux_install_script.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/linux_install_script.go deleted file mode 100644 index a2228b2fc..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/linux_install_script.go +++ /dev/null @@ -1,71 +0,0 @@ -package ssh - -const ( - // This is a constant representing a script to install and uninstall public - // key in remote hosts. - DefaultPublicKeyInstallScript = ` -#!/bin/bash -# -# This is a default script which installs or uninstalls an RSA public key to/from -# authorized_keys file in a typical linux machine. -# -# If the platform differs or if the binaries used in this script are not available -# in target machine, use the 'install_script' parameter with 'roles/' endpoint to -# register a custom script (applicable for Dynamic type only). -# -# Vault server runs this script on the target machine with the following params: -# -# $1:INSTALL_OPTION: "install" or "uninstall" -# -# $2:PUBLIC_KEY_FILE: File name containing public key to be installed. Vault server -# uses UUID as name to avoid collisions with public keys generated for other requests. -# -# $3:AUTH_KEYS_FILE: Absolute path of the authorized_keys file. -# Currently, vault uses /home//.ssh/authorized_keys as the path. -# -# [Note: This script will be run by Vault using the registered admin username. -# Notice that some commands below are run as 'sudo'. For graceful execution of -# this script there should not be any password prompts. So, disable password -# prompt for the admin username registered with Vault. - -set -e - -# Storing arguments into variables, to increase readability of the script. -INSTALL_OPTION=$1 -PUBLIC_KEY_FILE=$2 -AUTH_KEYS_FILE=$3 - -# Delete the public key file and the temporary file -function cleanup -{ - rm -f "$PUBLIC_KEY_FILE" temp_$PUBLIC_KEY_FILE -} - -# 'cleanup' will be called if the script ends or if any command fails. -trap cleanup EXIT - -# Return if the option is anything other than 'install' or 'uninstall'. -if [ "$INSTALL_OPTION" != "install" ] && [ "$INSTALL_OPTION" != "uninstall" ]; then - exit 1 -fi - -# use locking to avoid parallel script execution -( - flock --timeout 10 200 - # Create the .ssh directory and authorized_keys file if it does not exist - SSH_DIR=$(dirname $AUTH_KEYS_FILE) - sudo mkdir -p "$SSH_DIR" - sudo touch "$AUTH_KEYS_FILE" - # Remove the key from authorized_keys file if it is already present. - # This step is common for both install and uninstall. Note that grep's - # return code is ignored, thus if grep fails all keys will be removed - # rather than none and it fails secure - sudo grep -vFf "$PUBLIC_KEY_FILE" "$AUTH_KEYS_FILE" > temp_$PUBLIC_KEY_FILE || true - cat temp_$PUBLIC_KEY_FILE | sudo tee "$AUTH_KEYS_FILE" - # Append the new public key to authorized_keys file - if [ "$INSTALL_OPTION" == "install" ]; then - cat "$PUBLIC_KEY_FILE" | sudo tee --append "$AUTH_KEYS_FILE" - fi -) 200> ${AUTH_KEYS_FILE}.lock -` -) diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_ca.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_ca.go deleted file mode 100644 index de0f5515a..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_ca.go +++ /dev/null @@ -1,286 +0,0 @@ -package ssh - -import ( - "context" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "fmt" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/crypto/ssh" -) - -const ( - caPublicKey = "ca_public_key" - caPrivateKey = "ca_private_key" - caPublicKeyStoragePath = "config/ca_public_key" - caPublicKeyStoragePathDeprecated = "public_key" - caPrivateKeyStoragePath = "config/ca_private_key" - caPrivateKeyStoragePathDeprecated = "config/ca_bundle" -) - -type keyStorageEntry struct { - Key string `json:"key" structs:"key" mapstructure:"key"` -} - -func pathConfigCA(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/ca", - Fields: map[string]*framework.FieldSchema{ - "private_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Private half of the SSH key that will be used to sign certificates.`, - }, - "public_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Public half of the SSH key that will be used to sign certificates.`, - }, - "generate_signing_key": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Generate SSH key pair internally rather than use the private_key and public_key fields.`, - Default: true, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigCAUpdate, - logical.DeleteOperation: b.pathConfigCADelete, - logical.ReadOperation: b.pathConfigCARead, - }, - - HelpSynopsis: `Set the SSH private key used for signing certificates.`, - HelpDescription: `This sets the CA information used for certificates generated by this -by this mount. The fields must be in the standard private and public SSH format. - -For security reasons, the private key cannot be retrieved later. - -Read operations will return the public key, if already stored/generated.`, - } -} - -func (b *backend) pathConfigCARead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - publicKeyEntry, err := caKey(ctx, req.Storage, caPublicKey) - if err != nil { - return nil, errwrap.Wrapf("failed to read CA public key: {{err}}", err) - } - - if publicKeyEntry == nil { - return logical.ErrorResponse("keys haven't been configured yet"), nil - } - - response := &logical.Response{ - Data: map[string]interface{}{ - "public_key": publicKeyEntry.Key, - }, - } - - return response, nil -} - -func (b *backend) pathConfigCADelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if err := req.Storage.Delete(ctx, caPrivateKeyStoragePath); err != nil { - return nil, err - } - if err := req.Storage.Delete(ctx, caPublicKeyStoragePath); err != nil { - return nil, err - } - return nil, nil -} - -func caKey(ctx context.Context, storage logical.Storage, keyType string) (*keyStorageEntry, error) { - var path, deprecatedPath string - switch keyType { - case caPrivateKey: - path = caPrivateKeyStoragePath - deprecatedPath = caPrivateKeyStoragePathDeprecated - case caPublicKey: - path = caPublicKeyStoragePath - deprecatedPath = caPublicKeyStoragePathDeprecated - default: - return nil, fmt.Errorf("unrecognized key type %q", keyType) - } - - entry, err := storage.Get(ctx, path) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read CA key of type %q: {{err}}", keyType), err) - } - - if entry == nil { - // If the entry is not found, look at an older path. If found, upgrade - // it. - entry, err = storage.Get(ctx, deprecatedPath) - if err != nil { - return nil, err - } - if entry != nil { - entry, err = logical.StorageEntryJSON(path, keyStorageEntry{ - Key: string(entry.Value), - }) - if err != nil { - return nil, err - } - if err := storage.Put(ctx, entry); err != nil { - return nil, err - } - if err = storage.Delete(ctx, deprecatedPath); err != nil { - return nil, err - } - } - } - if entry == nil { - return nil, nil - } - - var keyEntry keyStorageEntry - if err := entry.DecodeJSON(&keyEntry); err != nil { - return nil, err - } - - return &keyEntry, nil -} - -func (b *backend) pathConfigCAUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var err error - publicKey := data.Get("public_key").(string) - privateKey := data.Get("private_key").(string) - - var generateSigningKey bool - - generateSigningKeyRaw, ok := data.GetOk("generate_signing_key") - switch { - // explicitly set true - case ok && generateSigningKeyRaw.(bool): - if publicKey != "" || privateKey != "" { - return logical.ErrorResponse("public_key and private_key must not be set when generate_signing_key is set to true"), nil - } - - generateSigningKey = true - - // explicitly set to false, or not set and we have both a public and private key - case ok, publicKey != "" && privateKey != "": - if publicKey == "" { - return logical.ErrorResponse("missing public_key"), nil - } - - if privateKey == "" { - return logical.ErrorResponse("missing private_key"), nil - } - - _, err := ssh.ParsePrivateKey([]byte(privateKey)) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Unable to parse private_key as an SSH private key: %v", err)), nil - } - - _, err = parsePublicSSHKey(publicKey) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Unable to parse public_key as an SSH public key: %v", err)), nil - } - - // not set and no public/private key provided so generate - case publicKey == "" && privateKey == "": - generateSigningKey = true - - // not set, but one or the other supplied - default: - return logical.ErrorResponse("only one of public_key and private_key set; both must be set to use, or both must be blank to auto-generate"), nil - } - - if generateSigningKey { - publicKey, privateKey, err = generateSSHKeyPair() - if err != nil { - return nil, err - } - } - - if publicKey == "" || privateKey == "" { - return nil, fmt.Errorf("failed to generate or parse the keys") - } - - publicKeyEntry, err := caKey(ctx, req.Storage, caPublicKey) - if err != nil { - return nil, errwrap.Wrapf("failed to read CA public key: {{err}}", err) - } - - privateKeyEntry, err := caKey(ctx, req.Storage, caPrivateKey) - if err != nil { - return nil, errwrap.Wrapf("failed to read CA private key: {{err}}", err) - } - - if (publicKeyEntry != nil && publicKeyEntry.Key != "") || (privateKeyEntry != nil && privateKeyEntry.Key != "") { - return nil, fmt.Errorf("keys are already configured; delete them before reconfiguring") - } - - entry, err := logical.StorageEntryJSON(caPublicKeyStoragePath, &keyStorageEntry{ - Key: publicKey, - }) - if err != nil { - return nil, err - } - - // Save the public key - err = req.Storage.Put(ctx, entry) - if err != nil { - return nil, err - } - - entry, err = logical.StorageEntryJSON(caPrivateKeyStoragePath, &keyStorageEntry{ - Key: privateKey, - }) - if err != nil { - return nil, err - } - - // Save the private key - err = req.Storage.Put(ctx, entry) - if err != nil { - var mErr *multierror.Error - - mErr = multierror.Append(mErr, errwrap.Wrapf("failed to store CA private key: {{err}}", err)) - - // If storing private key fails, the corresponding public key should be - // removed - if delErr := req.Storage.Delete(ctx, caPublicKeyStoragePath); delErr != nil { - mErr = multierror.Append(mErr, errwrap.Wrapf("failed to cleanup CA public key: {{err}}", delErr)) - return nil, mErr - } - - return nil, err - } - - if generateSigningKey { - response := &logical.Response{ - Data: map[string]interface{}{ - "public_key": publicKey, - }, - } - - return response, nil - } - - return nil, nil -} - -func generateSSHKeyPair() (string, string, error) { - privateSeed, err := rsa.GenerateKey(rand.Reader, 4096) - if err != nil { - return "", "", err - } - - privateBlock := &pem.Block{ - Type: "RSA PRIVATE KEY", - Headers: nil, - Bytes: x509.MarshalPKCS1PrivateKey(privateSeed), - } - - public, err := ssh.NewPublicKey(&privateSeed.PublicKey) - if err != nil { - return "", "", err - } - - return string(ssh.MarshalAuthorizedKey(public)), string(pem.EncodeToMemory(privateBlock)), nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_zeroaddress.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_zeroaddress.go deleted file mode 100644 index 02754baac..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_config_zeroaddress.go +++ /dev/null @@ -1,184 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// Structure to hold roles that are allowed to accept any IP address. -type zeroAddressRoles struct { - Roles []string `json:"roles" mapstructure:"roles"` -} - -func pathConfigZeroAddress(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "config/zeroaddress", - Fields: map[string]*framework.FieldSchema{ - "roles": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `[Required] Comma separated list of role names which - allows credentials to be requested for any IP address. CIDR blocks - previously registered under these roles will be ignored.`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigZeroAddressWrite, - logical.ReadOperation: b.pathConfigZeroAddressRead, - logical.DeleteOperation: b.pathConfigZeroAddressDelete, - }, - HelpSynopsis: pathConfigZeroAddressSyn, - HelpDescription: pathConfigZeroAddressDesc, - } -} - -func (b *backend) pathConfigZeroAddressDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "config/zeroaddress") - if err != nil { - return nil, err - } - return nil, nil -} - -func (b *backend) pathConfigZeroAddressRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := b.getZeroAddressRoles(ctx, req.Storage) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "roles": entry.Roles, - }, - }, nil -} - -func (b *backend) pathConfigZeroAddressWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleNames := d.Get("roles").(string) - if roleNames == "" { - return logical.ErrorResponse("Missing roles"), nil - } - - // Check if the roles listed actually exist in the backend - roles := strings.Split(roleNames, ",") - for _, item := range roles { - role, err := b.getRole(ctx, req.Storage, item) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("Role %q does not exist", item)), nil - } - } - - err := b.putZeroAddressRoles(ctx, req.Storage, roles) - if err != nil { - return nil, err - } - - return nil, nil -} - -// Stores the given list of roles at zeroaddress endpoint -func (b *backend) putZeroAddressRoles(ctx context.Context, s logical.Storage, roles []string) error { - entry, err := logical.StorageEntryJSON("config/zeroaddress", &zeroAddressRoles{ - Roles: roles, - }) - if err != nil { - return err - } - if err := s.Put(ctx, entry); err != nil { - return err - } - return nil -} - -// Retrieves the list of roles from the zeroaddress endpoint. -func (b *backend) getZeroAddressRoles(ctx context.Context, s logical.Storage) (*zeroAddressRoles, error) { - entry, err := s.Get(ctx, "config/zeroaddress") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result zeroAddressRoles - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// Removes a role from the list of roles present in config/zeroaddress path -func (b *backend) removeZeroAddressRole(ctx context.Context, s logical.Storage, roleName string) error { - zeroAddressEntry, err := b.getZeroAddressRoles(ctx, s) - if err != nil { - return err - } - if zeroAddressEntry == nil { - return nil - } - - err = zeroAddressEntry.remove(roleName) - if err != nil { - return err - } - - return b.putZeroAddressRoles(ctx, s, zeroAddressEntry.Roles) -} - -// Removes a given role from the comma separated string -func (r *zeroAddressRoles) remove(roleName string) error { - var index int - for i, role := range r.Roles { - if role == roleName { - index = i - break - } - } - length := len(r.Roles) - if index >= length || index < 0 { - return fmt.Errorf("invalid index %d", index) - } - // If slice has zero or one item, remove the item by setting slice to nil. - if length < 2 { - r.Roles = nil - return nil - } - - // Last item to be deleted - if length-1 == index { - r.Roles = r.Roles[:length-1] - return nil - } - - // Delete the item by appending all items except the one at index - r.Roles = append(r.Roles[:index], r.Roles[index+1:]...) - return nil -} - -const pathConfigZeroAddressSyn = ` -Assign zero address as default CIDR block for select roles. -` - -const pathConfigZeroAddressDesc = ` -Administrator can choose to make a select few registered roles to accept any IP -address, overriding the CIDR blocks registered during creation of roles. This -doesn't mean that the credentials are created for any IP address. Clients who -have access to these roles are trusted to make valid requests. Access to these -roles should be controlled using Vault policies. It is recommended that all the -roles that are allowed to accept any IP address should have an explicit policy -of deny for unintended clients. - -This is a root authenticated endpoint. If backend is mounted at 'ssh' then use -the endpoint 'ssh/config/zeroaddress' to provide the list of allowed roles. -After mounting the backend, use 'path-help' for additional information. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_creds_create.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_creds_create.go deleted file mode 100644 index 004fbe4e6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_creds_create.go +++ /dev/null @@ -1,332 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - "net" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -type sshOTP struct { - Username string `json:"username" structs:"username" mapstructure:"username"` - IP string `json:"ip" structs:"ip" mapstructure:"ip"` - RoleName string `json:"role_name" structs:"role_name" mapstructure:"role_name"` -} - -func pathCredsCreate(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "creds/" + framework.GenericNameRegex("role"), - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] Name of the role", - }, - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Optional] Username in remote host", - }, - "ip": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] IP of the remote host", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathCredsCreateWrite, - }, - HelpSynopsis: pathCredsCreateHelpSyn, - HelpDescription: pathCredsCreateHelpDesc, - } -} - -func (b *backend) pathCredsCreateWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleName := d.Get("role").(string) - if roleName == "" { - return logical.ErrorResponse("Missing role"), nil - } - - ipRaw := d.Get("ip").(string) - if ipRaw == "" { - return logical.ErrorResponse("Missing ip"), nil - } - - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, errwrap.Wrapf("error retrieving role: {{err}}", err) - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("Role %q not found", roleName)), nil - } - - // username is an optional parameter. - username := d.Get("username").(string) - - // Set the default username - if username == "" { - if role.DefaultUser == "" { - return logical.ErrorResponse("No default username registered. Use 'username' option"), nil - } - username = role.DefaultUser - } - - if role.AllowedUsers != "" { - // Check if the username is present in allowed users list. - err := validateUsername(username, role.AllowedUsers) - - // If username is not present in allowed users list, check if it - // is the default username in the role. If neither is true, then - // that username is not allowed to generate a credential. - if err != nil && username != role.DefaultUser { - return logical.ErrorResponse("Username is not present is allowed users list"), nil - } - } else if username != role.DefaultUser { - return logical.ErrorResponse("Username has to be either in allowed users list or has to be a default username"), nil - } - - // Validate the IP address - ipAddr := net.ParseIP(ipRaw) - if ipAddr == nil { - return logical.ErrorResponse(fmt.Sprintf("Invalid IP %q", ipRaw)), nil - } - - // Check if the IP belongs to the registered list of CIDR blocks under the role - ip := ipAddr.String() - - zeroAddressEntry, err := b.getZeroAddressRoles(ctx, req.Storage) - if err != nil { - return nil, errwrap.Wrapf("error retrieving zero-address roles: {{err}}", err) - } - var zeroAddressRoles []string - if zeroAddressEntry != nil { - zeroAddressRoles = zeroAddressEntry.Roles - } - - err = validateIP(ip, roleName, role.CIDRList, role.ExcludeCIDRList, zeroAddressRoles) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("Error validating IP: %v", err)), nil - } - - var result *logical.Response - if role.KeyType == KeyTypeOTP { - // Generate an OTP - otp, err := b.GenerateOTPCredential(ctx, req, &sshOTP{ - Username: username, - IP: ip, - RoleName: roleName, - }) - if err != nil { - return nil, err - } - - // Return the information relevant to user of OTP type and save - // the data required for later use in the internal section of secret. - // In this case, saving just the OTP is sufficient since there is - // no need to establish connection with the remote host. - result = b.Secret(SecretOTPType).Response(map[string]interface{}{ - "key_type": role.KeyType, - "key": otp, - "username": username, - "ip": ip, - "port": role.Port, - }, map[string]interface{}{ - "otp": otp, - }) - } else if role.KeyType == KeyTypeDynamic { - // Generate an RSA key pair. This also installs the newly generated - // public key in the remote host. - dynamicPublicKey, dynamicPrivateKey, err := b.GenerateDynamicCredential(ctx, req, role, username, ip) - if err != nil { - return nil, err - } - - // Return the information relevant to user of dynamic type and save - // information required for later use in internal section of secret. - result = b.Secret(SecretDynamicKeyType).Response(map[string]interface{}{ - "key": dynamicPrivateKey, - "key_type": role.KeyType, - "username": username, - "ip": ip, - "port": role.Port, - }, map[string]interface{}{ - "admin_user": role.AdminUser, - "username": username, - "ip": ip, - "host_key_name": role.KeyName, - "dynamic_public_key": dynamicPublicKey, - "port": role.Port, - "install_script": role.InstallScript, - }) - } else { - return nil, fmt.Errorf("key type unknown") - } - - return result, nil -} - -// Generates a RSA key pair and installs it in the remote target -func (b *backend) GenerateDynamicCredential(ctx context.Context, req *logical.Request, role *sshRole, username, ip string) (string, string, error) { - // Fetch the host key to be used for dynamic key installation - keyEntry, err := req.Storage.Get(ctx, fmt.Sprintf("keys/%s", role.KeyName)) - if err != nil { - return "", "", errwrap.Wrapf(fmt.Sprintf("key %q not found: {{err}}", role.KeyName), err) - } - - if keyEntry == nil { - return "", "", fmt.Errorf("key %q not found", role.KeyName) - } - - var hostKey sshHostKey - if err := keyEntry.DecodeJSON(&hostKey); err != nil { - return "", "", errwrap.Wrapf("error reading the host key: {{err}}", err) - } - - // Generate a new RSA key pair with the given key length. - dynamicPublicKey, dynamicPrivateKey, err := generateRSAKeys(role.KeyBits) - if err != nil { - return "", "", errwrap.Wrapf("error generating key: {{err}}", err) - } - - if len(role.KeyOptionSpecs) != 0 { - dynamicPublicKey = fmt.Sprintf("%s %s", role.KeyOptionSpecs, dynamicPublicKey) - } - - // Add the public key to authorized_keys file in target machine - err = b.installPublicKeyInTarget(ctx, role.AdminUser, username, ip, role.Port, hostKey.Key, dynamicPublicKey, role.InstallScript, true) - if err != nil { - return "", "", errwrap.Wrapf("failed to add public key to authorized_keys file in target: {{err}}", err) - } - return dynamicPublicKey, dynamicPrivateKey, nil -} - -// Generates a UUID OTP and its salted value based on the salt of the backend. -func (b *backend) GenerateSaltedOTP(ctx context.Context) (string, string, error) { - str, err := uuid.GenerateUUID() - if err != nil { - return "", "", err - } - salt, err := b.Salt(ctx) - if err != nil { - return "", "", err - } - - return str, salt.SaltID(str), nil -} - -// Generates an UUID OTP and creates an entry for the same in storage backend with its salted string. -func (b *backend) GenerateOTPCredential(ctx context.Context, req *logical.Request, sshOTPEntry *sshOTP) (string, error) { - otp, otpSalted, err := b.GenerateSaltedOTP(ctx) - if err != nil { - return "", err - } - - // Check if there is an entry already created for the newly generated OTP. - entry, err := b.getOTP(ctx, req.Storage, otpSalted) - - // If entry already exists for the OTP, make sure that new OTP is not - // replacing an existing one by recreating new ones until an unused - // OTP is generated. It is very unlikely that this is the case and this - // code is just for safety. - for err == nil && entry != nil { - otp, otpSalted, err = b.GenerateSaltedOTP(ctx) - if err != nil { - return "", err - } - entry, err = b.getOTP(ctx, req.Storage, otpSalted) - if err != nil { - return "", err - } - } - - // Store an entry for the salt of OTP. - newEntry, err := logical.StorageEntryJSON("otp/"+otpSalted, sshOTPEntry) - if err != nil { - return "", err - } - if err := req.Storage.Put(ctx, newEntry); err != nil { - return "", err - } - return otp, nil -} - -// ValidateIP first checks if the role belongs to the list of privileged -// roles that could allow any IP address and if there is a match, IP is -// accepted immediately. If not, IP is searched in the allowed CIDR blocks -// registered with the role. If there is a match, then it is searched in the -// excluded CIDR blocks and if IP is found there as well, an error is returned. -// IP is valid only if it is encompassed by allowed CIDR blocks and not by -// excluded CIDR blocks. -func validateIP(ip, roleName, cidrList, excludeCidrList string, zeroAddressRoles []string) error { - // Search IP in the zero-address list - for _, role := range zeroAddressRoles { - if roleName == role { - return nil - } - } - - // Search IP in allowed CIDR blocks - ipMatched, err := cidrListContainsIP(ip, cidrList) - if err != nil { - return err - } - if !ipMatched { - return fmt.Errorf("IP does not belong to role") - } - - if len(excludeCidrList) == 0 { - return nil - } - - // Search IP in exclude list - ipMatched, err = cidrListContainsIP(ip, excludeCidrList) - if err != nil { - return err - } - if ipMatched { - return fmt.Errorf("IP does not belong to role") - } - - return nil -} - -// Checks if the username supplied by the user is present in the list of -// allowed users registered which creation of role. -func validateUsername(username, allowedUsers string) error { - if allowedUsers == "" { - return fmt.Errorf("username not in allowed users list") - } - - // Role was explicitly configured to allow any username. - if allowedUsers == "*" { - return nil - } - - userList := strings.Split(allowedUsers, ",") - for _, user := range userList { - if strings.TrimSpace(user) == username { - return nil - } - } - - return fmt.Errorf("username not in allowed users list") -} - -const pathCredsCreateHelpSyn = ` -Creates a credential for establishing SSH connection with the remote host. -` - -const pathCredsCreateHelpDesc = ` -This path will generate a new key for establishing SSH session with -target host. The key can either be a long lived dynamic key or a One -Time Password (OTP), using 'key_type' parameter being 'dynamic' or -'otp' respectively. For dynamic keys, a named key should be supplied. -Create named key using the 'keys/' endpoint, and this represents the -shared SSH key of target host. If this backend is mounted at 'ssh', -then "ssh/creds/web" would generate a key for 'web' role. - -Keys will have a lease associated with them. The access keys can be -revoked by using the lease ID. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_fetch.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_fetch.go deleted file mode 100644 index f29ddcee0..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_fetch.go +++ /dev/null @@ -1,41 +0,0 @@ -package ssh - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathFetchPublicKey(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `public_key`, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathFetchPublicKey, - }, - - HelpSynopsis: `Retrieve the public key.`, - HelpDescription: `This allows the public key, that this backend has been configured with, to be fetched.`, - } -} - -func (b *backend) pathFetchPublicKey(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - publicKeyEntry, err := caKey(ctx, req.Storage, caPublicKey) - if err != nil { - return nil, err - } - if publicKeyEntry == nil || publicKeyEntry.Key == "" { - return nil, nil - } - - response := &logical.Response{ - Data: map[string]interface{}{ - logical.HTTPContentType: "text/plain", - logical.HTTPRawBody: []byte(publicKeyEntry.Key), - logical.HTTPStatusCode: 200, - }, - } - - return response, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_keys.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_keys.go deleted file mode 100644 index 593d80bc1..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_keys.go +++ /dev/null @@ -1,110 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - - "golang.org/x/crypto/ssh" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -type sshHostKey struct { - Key string `json:"key"` -} - -func pathKeys(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "keys/" + framework.GenericNameRegex("key_name"), - Fields: map[string]*framework.FieldSchema{ - "key_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] Name of the key", - }, - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] SSH private key with super user privileges in host", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathKeysWrite, - logical.DeleteOperation: b.pathKeysDelete, - }, - HelpSynopsis: pathKeysSyn, - HelpDescription: pathKeysDesc, - } -} - -func (b *backend) getKey(ctx context.Context, s logical.Storage, n string) (*sshHostKey, error) { - entry, err := s.Get(ctx, "keys/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result sshHostKey - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathKeysDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - keyName := d.Get("key_name").(string) - keyPath := fmt.Sprintf("keys/%s", keyName) - err := req.Storage.Delete(ctx, keyPath) - if err != nil { - return nil, err - } - return nil, nil -} - -func (b *backend) pathKeysWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - keyName := d.Get("key_name").(string) - if keyName == "" { - return logical.ErrorResponse("Missing key_name"), nil - } - - keyString := d.Get("key").(string) - - // Check if the key provided is infact a private key - signer, err := ssh.ParsePrivateKey([]byte(keyString)) - if err != nil || signer == nil { - return logical.ErrorResponse("Invalid key"), nil - } - - if keyString == "" { - return logical.ErrorResponse("Missing key"), nil - } - - keyPath := fmt.Sprintf("keys/%s", keyName) - - // Store the key - entry, err := logical.StorageEntryJSON(keyPath, map[string]interface{}{ - "key": keyString, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil -} - -const pathKeysSyn = ` -Register a shared private key with Vault. -` - -const pathKeysDesc = ` -Vault uses this key to install and uninstall dynamic keys in remote hosts. This -key should have sudoer privileges in remote hosts. This enables installing keys -for unprivileged usernames. - -If this backend is mounted as "ssh", then the endpoint for registering shared -key is "ssh/keys/". The name given here can be associated with any number -of roles via the endpoint "ssh/roles/". -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_lookup.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_lookup.go deleted file mode 100644 index 5f802d19e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_lookup.go +++ /dev/null @@ -1,91 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - "net" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathLookup(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "lookup", - Fields: map[string]*framework.FieldSchema{ - "ip": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] IP address of remote host", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathLookupWrite, - }, - HelpSynopsis: pathLookupSyn, - HelpDescription: pathLookupDesc, - } -} - -func (b *backend) pathLookupWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ipAddr := d.Get("ip").(string) - if ipAddr == "" { - return logical.ErrorResponse("Missing ip"), nil - } - ip := net.ParseIP(ipAddr) - if ip == nil { - return logical.ErrorResponse(fmt.Sprintf("Invalid IP %q", ip.String())), nil - } - - // Get all the roles created in the backend. - keys, err := req.Storage.List(ctx, "roles/") - if err != nil { - return nil, err - } - - // Look for roles which has CIDR blocks that encompasses the given IP - // and create a list out of it. - var matchingRoles []string - for _, role := range keys { - if contains, _ := roleContainsIP(ctx, req.Storage, role, ip.String()); contains { - matchingRoles = append(matchingRoles, role) - } - } - - // Add roles that are allowed to accept any IP address. - zeroAddressEntry, err := b.getZeroAddressRoles(ctx, req.Storage) - if err != nil { - return nil, err - } - if zeroAddressEntry != nil { - matchingRoles = append(matchingRoles, zeroAddressEntry.Roles...) - } - - // This list may potentially reveal more information than it is supposed to. - // The roles for which the client is not authorized to will also be displayed. - // However, if the client tries to use the role for which the client is not - // authenticated, it will fail. It is not a problem. In a way this can be - // viewed as a feature. The client can ask for permissions to be given for - // a specific role if things are not working! - // - // Ideally, the role names should be filtered and only the roles which - // the client is authorized to see, should be returned. - return &logical.Response{ - Data: map[string]interface{}{ - "roles": matchingRoles, - }, - }, nil -} - -const pathLookupSyn = ` -List all the roles associated with the given IP address. -` - -const pathLookupDesc = ` -The IP address for which the key is requested, is searched in the CIDR blocks -registered with vault using the 'roles' endpoint. Keys can be generated only by -specifying the 'role' name. The roles that can be used to generate the key for -a particular IP, are listed via this endpoint. For example, if this backend is -mounted at "ssh", then "ssh/lookup" lists the roles associated with keys can be -generated for a target IP, if the CIDR block encompassing the IP is registered -with vault. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_roles.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_roles.go deleted file mode 100644 index 76fda0e0e..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_roles.go +++ /dev/null @@ -1,657 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - "strings" - - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/cidrutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - KeyTypeOTP = "otp" - KeyTypeDynamic = "dynamic" - KeyTypeCA = "ca" -) - -// Structure that represents a role in SSH backend. This is a common role structure -// for both OTP and Dynamic roles. Not all the fields are mandatory for both type. -// Some are applicable for one and not for other. It doesn't matter. -type sshRole struct { - KeyType string `mapstructure:"key_type" json:"key_type"` - KeyName string `mapstructure:"key" json:"key"` - KeyBits int `mapstructure:"key_bits" json:"key_bits"` - AdminUser string `mapstructure:"admin_user" json:"admin_user"` - DefaultUser string `mapstructure:"default_user" json:"default_user"` - CIDRList string `mapstructure:"cidr_list" json:"cidr_list"` - ExcludeCIDRList string `mapstructure:"exclude_cidr_list" json:"exclude_cidr_list"` - Port int `mapstructure:"port" json:"port"` - InstallScript string `mapstructure:"install_script" json:"install_script"` - AllowedUsers string `mapstructure:"allowed_users" json:"allowed_users"` - AllowedDomains string `mapstructure:"allowed_domains" json:"allowed_domains"` - KeyOptionSpecs string `mapstructure:"key_option_specs" json:"key_option_specs"` - MaxTTL string `mapstructure:"max_ttl" json:"max_ttl"` - TTL string `mapstructure:"ttl" json:"ttl"` - DefaultCriticalOptions map[string]string `mapstructure:"default_critical_options" json:"default_critical_options"` - DefaultExtensions map[string]string `mapstructure:"default_extensions" json:"default_extensions"` - AllowedCriticalOptions string `mapstructure:"allowed_critical_options" json:"allowed_critical_options"` - AllowedExtensions string `mapstructure:"allowed_extensions" json:"allowed_extensions"` - AllowUserCertificates bool `mapstructure:"allow_user_certificates" json:"allow_user_certificates"` - AllowHostCertificates bool `mapstructure:"allow_host_certificates" json:"allow_host_certificates"` - AllowBareDomains bool `mapstructure:"allow_bare_domains" json:"allow_bare_domains"` - AllowSubdomains bool `mapstructure:"allow_subdomains" json:"allow_subdomains"` - AllowUserKeyIDs bool `mapstructure:"allow_user_key_ids" json:"allow_user_key_ids"` - KeyIDFormat string `mapstructure:"key_id_format" json:"key_id_format"` -} - -func pathListRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathRoleList, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func pathRoles(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("role"), - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Required for all types] - Name of the role being created.`, - }, - "key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Required for Dynamic type] [Not applicable for OTP type] [Not applicable for CA type] - Name of the registered key in Vault. Before creating the role, use the - 'keys/' endpoint to create a named key.`, - }, - "admin_user": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Required for Dynamic type] [Not applicable for OTP type] [Not applicable for CA type] - Admin user at remote host. The shared key being registered should be - for this user and should have root privileges. Everytime a dynamic - credential is being generated for other users, Vault uses this admin - username to login to remote host and install the generated credential - for the other user.`, - }, - "default_user": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Required for Dynamic type] [Required for OTP type] [Optional for CA type] - Default username for which a credential will be generated. - When the endpoint 'creds/' is used without a username, this - value will be used as default username.`, - }, - "cidr_list": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Optional for Dynamic type] [Optional for OTP type] [Not applicable for CA type] - Comma separated list of CIDR blocks for which the role is applicable for. - CIDR blocks can belong to more than one role.`, - }, - "exclude_cidr_list": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Optional for Dynamic type] [Optional for OTP type] [Not applicable for CA type] - Comma separated list of CIDR blocks. IP addresses belonging to these blocks are not - accepted by the role. This is particularly useful when big CIDR blocks are being used - by the role and certain parts of it needs to be kept out.`, - }, - "port": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: ` - [Optional for Dynamic type] [Optional for OTP type] [Not applicable for CA type] - Port number for SSH connection. Default is '22'. Port number does not - play any role in creation of OTP. For 'otp' type, this is just a way - to inform client about the port number to use. Port number will be - returned to client by Vault server along with OTP.`, - }, - "key_type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Required for all types] - Type of key used to login to hosts. It can be either 'otp', 'dynamic' or 'ca'. - 'otp' type requires agent to be installed in remote hosts.`, - }, - "key_bits": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: ` - [Optional for Dynamic type] [Not applicable for OTP type] [Not applicable for CA type] - Length of the RSA dynamic key in bits. It is 1024 by default or it can be 2048.`, - }, - "install_script": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Optional for Dynamic type] [Not-applicable for OTP type] [Not applicable for CA type] - Script used to install and uninstall public keys in the target machine. - The inbuilt default install script will be for Linux hosts. For sample - script, refer the project documentation website.`, - }, - "allowed_users": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Optional for all types] [Works differently for CA type] - If this option is not specified, or is '*', client can request a - credential for any valid user at the remote host, including the - admin user. If only certain usernames are to be allowed, then - this list enforces it. If this field is set, then credentials - can only be created for default_user and usernames present in - this list. Setting this option will enable all the users with - access to this role to fetch credentials for all other usernames - in this list. Use with caution. N.B.: with the CA type, an empty - list means that no users are allowed; explicitly specify '*' to - allow any user. - `, - }, - "allowed_domains": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If this option is not specified, client can request for a signed certificate for any - valid host. If only certain domains are allowed, then this list enforces it. - `, - }, - "key_option_specs": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Optional for Dynamic type] [Not applicable for OTP type] [Not applicable for CA type] - Comma separated option specifications which will be prefixed to RSA key in - authorized_keys file. Options should be valid and comply with authorized_keys - file format and should not contain spaces. - `, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - The lease duration if no specific lease duration is - requested. The lease duration controls the expiration - of certificates issued by this backend. Defaults to - the value of max_ttl.`, - }, - "max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - The maximum allowed lease duration - `, - }, - "allowed_critical_options": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - A comma-separated list of critical options that certificates can have when signed. - To allow any critical options, set this to an empty string. - `, - }, - "allowed_extensions": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - A comma-separated list of extensions that certificates can have when signed. - To allow any extensions, set this to an empty string. - `, - }, - "default_critical_options": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] - [Optional for CA type] Critical options certificates should - have if none are provided when signing. This field takes in key - value pairs in JSON format. Note that these are not restricted - by "allowed_critical_options". Defaults to none. - `, - }, - "default_extensions": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] - [Optional for CA type] Extensions certificates should have if - none are provided when signing. This field takes in key value - pairs in JSON format. Note that these are not restricted by - "allowed_extensions". Defaults to none. - `, - }, - "allow_user_certificates": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If set, certificates are allowed to be signed for use as a 'user'. - `, - Default: false, - }, - "allow_host_certificates": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If set, certificates are allowed to be signed for use as a 'host'. - `, - Default: false, - }, - "allow_bare_domains": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If set, host certificates that are requested are allowed to use the base domains listed in - "allowed_domains", e.g. "example.com". - This is a separate option as in some cases this can be considered a security threat. - `, - }, - "allow_subdomains": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If set, host certificates that are requested are allowed to use subdomains of those listed in "allowed_domains". - `, - }, - "allow_user_key_ids": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - If true, users can override the key ID for a signed certificate with the "key_id" field. - When false, the key ID will always be the token display name. - The key ID is logged by the SSH server and can be useful for auditing. - `, - }, - "key_id_format": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` - [Not applicable for Dynamic type] [Not applicable for OTP type] [Optional for CA type] - When supplied, this value specifies a custom format for the key id of a signed certificate. - The following variables are available for use: '{{token_display_name}}' - The display name of - the token used to make the request. '{{role_name}}' - The name of the role signing the request. - '{{public_key_hash}}' - A SHA256 checksum of the public key that is being signed. - `, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathRoleRead, - logical.UpdateOperation: b.pathRoleWrite, - logical.DeleteOperation: b.pathRoleDelete, - }, - - HelpSynopsis: pathRoleHelpSyn, - HelpDescription: pathRoleHelpDesc, - } -} - -func (b *backend) pathRoleWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleName := d.Get("role").(string) - if roleName == "" { - return logical.ErrorResponse("missing role name"), nil - } - - // Allowed users is an optional field, applicable for both OTP and Dynamic types. - allowedUsers := d.Get("allowed_users").(string) - - // Validate the CIDR blocks - cidrList := d.Get("cidr_list").(string) - if cidrList != "" { - valid, err := cidrutil.ValidateCIDRListString(cidrList, ",") - if err != nil { - return nil, errwrap.Wrapf("failed to validate cidr_list: {{err}}", err) - } - if !valid { - return logical.ErrorResponse("failed to validate cidr_list"), nil - } - } - - // Validate the excluded CIDR blocks - excludeCidrList := d.Get("exclude_cidr_list").(string) - if excludeCidrList != "" { - valid, err := cidrutil.ValidateCIDRListString(excludeCidrList, ",") - if err != nil { - return nil, errwrap.Wrapf("failed to validate exclude_cidr_list entry: {{err}}", err) - } - if !valid { - return logical.ErrorResponse(fmt.Sprintf("failed to validate exclude_cidr_list entry: %v", err)), nil - } - } - - port := d.Get("port").(int) - if port == 0 { - port = 22 - } - - keyType := d.Get("key_type").(string) - if keyType == "" { - return logical.ErrorResponse("missing key type"), nil - } - keyType = strings.ToLower(keyType) - - var roleEntry sshRole - if keyType == KeyTypeOTP { - defaultUser := d.Get("default_user").(string) - if defaultUser == "" { - return logical.ErrorResponse("missing default user"), nil - } - - // Admin user is not used if OTP key type is used because there is - // no need to login to remote machine. - adminUser := d.Get("admin_user").(string) - if adminUser != "" { - return logical.ErrorResponse("admin user not required for OTP type"), nil - } - - // Below are the only fields used from the role structure for OTP type. - roleEntry = sshRole{ - DefaultUser: defaultUser, - CIDRList: cidrList, - ExcludeCIDRList: excludeCidrList, - KeyType: KeyTypeOTP, - Port: port, - AllowedUsers: allowedUsers, - } - } else if keyType == KeyTypeDynamic { - defaultUser := d.Get("default_user").(string) - if defaultUser == "" { - return logical.ErrorResponse("missing default user"), nil - } - // Key name is required by dynamic type and not by OTP type. - keyName := d.Get("key").(string) - if keyName == "" { - return logical.ErrorResponse("missing key name"), nil - } - keyEntry, err := req.Storage.Get(ctx, fmt.Sprintf("keys/%s", keyName)) - if err != nil || keyEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid 'key': %q", keyName)), nil - } - - installScript := d.Get("install_script").(string) - keyOptionSpecs := d.Get("key_option_specs").(string) - - // Setting the default script here. The script will install the - // generated public key in the authorized_keys file of linux host. - if installScript == "" { - installScript = DefaultPublicKeyInstallScript - } - - adminUser := d.Get("admin_user").(string) - if adminUser == "" { - return logical.ErrorResponse("missing admin username"), nil - } - - // This defaults to 1024 and it can also be 2048 and 4096. - keyBits := d.Get("key_bits").(int) - if keyBits != 0 && keyBits != 1024 && keyBits != 2048 && keyBits != 4096 { - return logical.ErrorResponse("invalid key_bits field"), nil - } - - // If user has not set this field, default it to 2048 - if keyBits == 0 { - keyBits = 2048 - } - - // Store all the fields required by dynamic key type - roleEntry = sshRole{ - KeyName: keyName, - AdminUser: adminUser, - DefaultUser: defaultUser, - CIDRList: cidrList, - ExcludeCIDRList: excludeCidrList, - Port: port, - KeyType: KeyTypeDynamic, - KeyBits: keyBits, - InstallScript: installScript, - AllowedUsers: allowedUsers, - KeyOptionSpecs: keyOptionSpecs, - } - } else if keyType == KeyTypeCA { - role, errorResponse := b.createCARole(allowedUsers, d.Get("default_user").(string), d) - if errorResponse != nil { - return errorResponse, nil - } - roleEntry = *role - } else { - return logical.ErrorResponse("invalid key type"), nil - } - - entry, err := logical.StorageEntryJSON(fmt.Sprintf("roles/%s", roleName), roleEntry) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - return nil, nil -} - -func (b *backend) createCARole(allowedUsers, defaultUser string, data *framework.FieldData) (*sshRole, *logical.Response) { - ttl := time.Duration(data.Get("ttl").(int)) * time.Second - maxTTL := time.Duration(data.Get("max_ttl").(int)) * time.Second - role := &sshRole{ - AllowedCriticalOptions: data.Get("allowed_critical_options").(string), - AllowedExtensions: data.Get("allowed_extensions").(string), - AllowUserCertificates: data.Get("allow_user_certificates").(bool), - AllowHostCertificates: data.Get("allow_host_certificates").(bool), - AllowedUsers: allowedUsers, - AllowedDomains: data.Get("allowed_domains").(string), - DefaultUser: defaultUser, - AllowBareDomains: data.Get("allow_bare_domains").(bool), - AllowSubdomains: data.Get("allow_subdomains").(bool), - AllowUserKeyIDs: data.Get("allow_user_key_ids").(bool), - KeyIDFormat: data.Get("key_id_format").(string), - KeyType: KeyTypeCA, - } - - if !role.AllowUserCertificates && !role.AllowHostCertificates { - return nil, logical.ErrorResponse("Either 'allow_user_certificates' or 'allow_host_certificates' must be set to 'true'") - } - - defaultCriticalOptions := convertMapToStringValue(data.Get("default_critical_options").(map[string]interface{})) - defaultExtensions := convertMapToStringValue(data.Get("default_extensions").(map[string]interface{})) - - if ttl != 0 && maxTTL != 0 && ttl > maxTTL { - return nil, logical.ErrorResponse( - `"ttl" value must be less than "max_ttl" when both are specified`) - } - - // Persist TTLs - role.TTL = ttl.String() - role.MaxTTL = maxTTL.String() - role.DefaultCriticalOptions = defaultCriticalOptions - role.DefaultExtensions = defaultExtensions - - return role, nil -} - -func (b *backend) getRole(ctx context.Context, s logical.Storage, n string) (*sshRole, error) { - entry, err := s.Get(ctx, "roles/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result sshRole - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -// parseRole converts a sshRole object into its map[string]interface representation, -// with appropriate values for each KeyType. If the KeyType is invalid, it will return -// an error. -func (b *backend) parseRole(role *sshRole) (map[string]interface{}, error) { - var result map[string]interface{} - - switch role.KeyType { - case KeyTypeOTP: - result = map[string]interface{}{ - "default_user": role.DefaultUser, - "cidr_list": role.CIDRList, - "exclude_cidr_list": role.ExcludeCIDRList, - "key_type": role.KeyType, - "port": role.Port, - "allowed_users": role.AllowedUsers, - } - case KeyTypeCA: - ttl, err := parseutil.ParseDurationSecond(role.TTL) - if err != nil { - return nil, err - } - maxTTL, err := parseutil.ParseDurationSecond(role.MaxTTL) - if err != nil { - return nil, err - } - - result = map[string]interface{}{ - "allowed_users": role.AllowedUsers, - "allowed_domains": role.AllowedDomains, - "default_user": role.DefaultUser, - "ttl": int64(ttl.Seconds()), - "max_ttl": int64(maxTTL.Seconds()), - "allowed_critical_options": role.AllowedCriticalOptions, - "allowed_extensions": role.AllowedExtensions, - "allow_user_certificates": role.AllowUserCertificates, - "allow_host_certificates": role.AllowHostCertificates, - "allow_bare_domains": role.AllowBareDomains, - "allow_subdomains": role.AllowSubdomains, - "allow_user_key_ids": role.AllowUserKeyIDs, - "key_id_format": role.KeyIDFormat, - "key_type": role.KeyType, - "key_bits": role.KeyBits, - "default_critical_options": role.DefaultCriticalOptions, - "default_extensions": role.DefaultExtensions, - } - case KeyTypeDynamic: - result = map[string]interface{}{ - "key": role.KeyName, - "admin_user": role.AdminUser, - "default_user": role.DefaultUser, - "cidr_list": role.CIDRList, - "exclude_cidr_list": role.ExcludeCIDRList, - "port": role.Port, - "key_type": role.KeyType, - "key_bits": role.KeyBits, - "allowed_users": role.AllowedUsers, - "key_option_specs": role.KeyOptionSpecs, - // Returning install script will make the output look messy. - // But this is one way for clients to see the script that is - // being used to install the key. If there is some problem, - // the script can be modified and configured by clients. - "install_script": role.InstallScript, - } - default: - return nil, fmt.Errorf("invalid key type: %v", role.KeyType) - } - - return result, nil -} - -func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "roles/") - if err != nil { - return nil, err - } - - keyInfo := map[string]interface{}{} - for _, entry := range entries { - role, err := b.getRole(ctx, req.Storage, entry) - if err != nil { - // On error, log warning and continue - if b.Logger().IsWarn() { - b.Logger().Warn("error getting role info", "role", entry, "error", err) - } - continue - } - if role == nil { - // On empty role, log warning and continue - if b.Logger().IsWarn() { - b.Logger().Warn("no role info found", "role", entry) - } - continue - } - - roleInfo, err := b.parseRole(role) - if err != nil { - if b.Logger().IsWarn() { - b.Logger().Warn("error parsing role info", "role", entry, "error", err) - } - continue - } - - if keyType, ok := roleInfo["key_type"]; ok { - keyInfo[entry] = map[string]interface{}{ - "key_type": keyType, - } - } - } - - return logical.ListResponseWithInfo(entries, keyInfo), nil -} - -func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - role, err := b.getRole(ctx, req.Storage, d.Get("role").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - roleInfo, err := b.parseRole(role) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: roleInfo, - }, nil -} - -func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - roleName := d.Get("role").(string) - - // If the role was given privilege to accept any IP address, there will - // be an entry for this role in zero-address roles list. Before the role - // is removed, the entry in the list has to be removed. - err := b.removeZeroAddressRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - - err = req.Storage.Delete(ctx, fmt.Sprintf("roles/%s", roleName)) - if err != nil { - return nil, err - } - return nil, nil -} - -const pathRoleHelpSyn = ` -Manage the 'roles' that can be created with this backend. -` - -const pathRoleHelpDesc = ` -This path allows you to manage the roles that are used to generate credentials. - -Role takes a 'key_type' parameter that decides what type of credential this role -can generate. If remote hosts have Vault SSH Agent installed, an 'otp' type can -be used, otherwise 'dynamic' type can be used. - -If the backend is mounted at "ssh" and the role is created at "ssh/roles/web", -then a user could request for a credential at "ssh/creds/web" for an IP that -belongs to the role. The credential will be for the 'default_user' registered -with the role. There is also an optional parameter 'username' for 'creds/' endpoint. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_sign.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_sign.go deleted file mode 100644 index 68bd1efe6..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_sign.go +++ /dev/null @@ -1,425 +0,0 @@ -package ssh - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "golang.org/x/crypto/ssh" -) - -type creationBundle struct { - KeyId string - ValidPrincipals []string - PublicKey ssh.PublicKey - CertificateType uint32 - TTL time.Duration - Signer ssh.Signer - Role *sshRole - CriticalOptions map[string]string - Extensions map[string]string -} - -func pathSign(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "sign/" + framework.GenericNameRegex("role"), - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathSign, - }, - - Fields: map[string]*framework.FieldSchema{ - "role": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The desired role with configuration for this request.`, - }, - "ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: `The requested Time To Live for the SSH certificate; -sets the expiration date. If not specified -the role default, backend default, or system -default TTL is used, in that order. Cannot -be later than the role max TTL.`, - }, - "public_key": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `SSH public key that should be signed.`, - }, - "valid_principals": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Valid principals, either usernames or hostnames, that the certificate should be signed for.`, - }, - "cert_type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Type of certificate to be created; either "user" or "host".`, - Default: "user", - }, - "key_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Key id that the created certificate should have. If not specified, the display name of the token will be used.`, - }, - "critical_options": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: `Critical options that the certificate should be signed for.`, - }, - "extensions": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: `Extensions that the certificate should be signed for.`, - }, - }, - - HelpSynopsis: `Request signing an SSH key using a certain role with the provided details.`, - HelpDescription: `This path allows SSH keys to be signed according to the policy of the given role.`, - } -} - -func (b *backend) pathSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - roleName := data.Get("role").(string) - - // Get the role - role, err := b.getRole(ctx, req.Storage, roleName) - if err != nil { - return nil, err - } - if role == nil { - return logical.ErrorResponse(fmt.Sprintf("Unknown role: %s", roleName)), nil - } - - return b.pathSignCertificate(ctx, req, data, role) -} - -func (b *backend) pathSignCertificate(ctx context.Context, req *logical.Request, data *framework.FieldData, role *sshRole) (*logical.Response, error) { - publicKey := data.Get("public_key").(string) - if publicKey == "" { - return logical.ErrorResponse("missing public_key"), nil - } - - userPublicKey, err := parsePublicSSHKey(publicKey) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse public_key as SSH key: %s", err)), nil - } - - // Note that these various functions always return "user errors" so we pass - // them as 4xx values - keyId, err := b.calculateKeyId(data, req, role, userPublicKey) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - certificateType, err := b.calculateCertificateType(data, role) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - var parsedPrincipals []string - if certificateType == ssh.HostCert { - parsedPrincipals, err = b.calculateValidPrincipals(data, "", role.AllowedDomains, validateValidPrincipalForHosts(role)) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - } else { - parsedPrincipals, err = b.calculateValidPrincipals(data, role.DefaultUser, role.AllowedUsers, strutil.StrListContains) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - } - - ttl, err := b.calculateTTL(data, role) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - criticalOptions, err := b.calculateCriticalOptions(data, role) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - extensions, err := b.calculateExtensions(data, role) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - privateKeyEntry, err := caKey(ctx, req.Storage, caPrivateKey) - if err != nil { - return nil, errwrap.Wrapf("failed to read CA private key: {{err}}", err) - } - if privateKeyEntry == nil || privateKeyEntry.Key == "" { - return nil, fmt.Errorf("failed to read CA private key") - } - - signer, err := ssh.ParsePrivateKey([]byte(privateKeyEntry.Key)) - if err != nil { - return nil, errwrap.Wrapf("failed to parse stored CA private key: {{err}}", err) - } - - cBundle := creationBundle{ - KeyId: keyId, - PublicKey: userPublicKey, - Signer: signer, - ValidPrincipals: parsedPrincipals, - TTL: ttl, - CertificateType: certificateType, - Role: role, - CriticalOptions: criticalOptions, - Extensions: extensions, - } - - certificate, err := cBundle.sign() - if err != nil { - return nil, err - } - - signedSSHCertificate := ssh.MarshalAuthorizedKey(certificate) - if len(signedSSHCertificate) == 0 { - return nil, fmt.Errorf("error marshaling signed certificate") - } - - response := &logical.Response{ - Data: map[string]interface{}{ - "serial_number": strconv.FormatUint(certificate.Serial, 16), - "signed_key": string(signedSSHCertificate), - }, - } - - return response, nil -} - -func (b *backend) calculateValidPrincipals(data *framework.FieldData, defaultPrincipal, principalsAllowedByRole string, validatePrincipal func([]string, string) bool) ([]string, error) { - validPrincipals := "" - validPrincipalsRaw, ok := data.GetOk("valid_principals") - if ok { - validPrincipals = validPrincipalsRaw.(string) - } else { - validPrincipals = defaultPrincipal - } - - parsedPrincipals := strutil.RemoveDuplicates(strutil.ParseStringSlice(validPrincipals, ","), false) - allowedPrincipals := strutil.RemoveDuplicates(strutil.ParseStringSlice(principalsAllowedByRole, ","), false) - switch { - case len(parsedPrincipals) == 0: - // There is nothing to process - return nil, nil - case len(allowedPrincipals) == 0: - // User has requested principals to be set, but role is not configured - // with any principals - return nil, fmt.Errorf("role is not configured to allow any principles") - default: - // Role was explicitly configured to allow any principal. - if principalsAllowedByRole == "*" { - return parsedPrincipals, nil - } - - for _, principal := range parsedPrincipals { - if !validatePrincipal(allowedPrincipals, principal) { - return nil, fmt.Errorf("%v is not a valid value for valid_principals", principal) - } - } - return parsedPrincipals, nil - } -} - -func validateValidPrincipalForHosts(role *sshRole) func([]string, string) bool { - return func(allowedPrincipals []string, validPrincipal string) bool { - for _, allowedPrincipal := range allowedPrincipals { - if allowedPrincipal == validPrincipal && role.AllowBareDomains { - return true - } - if role.AllowSubdomains && strings.HasSuffix(validPrincipal, "."+allowedPrincipal) { - return true - } - } - - return false - } -} - -func (b *backend) calculateCertificateType(data *framework.FieldData, role *sshRole) (uint32, error) { - requestedCertificateType := data.Get("cert_type").(string) - - var certificateType uint32 - switch requestedCertificateType { - case "user": - if !role.AllowUserCertificates { - return 0, errors.New("cert_type 'user' is not allowed by role") - } - certificateType = ssh.UserCert - case "host": - if !role.AllowHostCertificates { - return 0, errors.New("cert_type 'host' is not allowed by role") - } - certificateType = ssh.HostCert - default: - return 0, errors.New("cert_type must be either 'user' or 'host'") - } - - return certificateType, nil -} - -func (b *backend) calculateKeyId(data *framework.FieldData, req *logical.Request, role *sshRole, pubKey ssh.PublicKey) (string, error) { - reqId := data.Get("key_id").(string) - - if reqId != "" { - if !role.AllowUserKeyIDs { - return "", fmt.Errorf("setting key_id is not allowed by role") - } - return reqId, nil - } - - keyIDFormat := "vault-{{token_display_name}}-{{public_key_hash}}" - if req.DisplayName == "" { - keyIDFormat = "vault-{{public_key_hash}}" - } - - if role.KeyIDFormat != "" { - keyIDFormat = role.KeyIDFormat - } - - keyID := substQuery(keyIDFormat, map[string]string{ - "token_display_name": req.DisplayName, - "role_name": data.Get("role").(string), - "public_key_hash": fmt.Sprintf("%x", sha256.Sum256(pubKey.Marshal())), - }) - - return keyID, nil -} - -func (b *backend) calculateCriticalOptions(data *framework.FieldData, role *sshRole) (map[string]string, error) { - unparsedCriticalOptions := data.Get("critical_options").(map[string]interface{}) - if len(unparsedCriticalOptions) == 0 { - return role.DefaultCriticalOptions, nil - } - - criticalOptions := convertMapToStringValue(unparsedCriticalOptions) - - if role.AllowedCriticalOptions != "" { - notAllowedOptions := []string{} - allowedCriticalOptions := strings.Split(role.AllowedCriticalOptions, ",") - - for option := range criticalOptions { - if !strutil.StrListContains(allowedCriticalOptions, option) { - notAllowedOptions = append(notAllowedOptions, option) - } - } - - if len(notAllowedOptions) != 0 { - return nil, fmt.Errorf("critical options not on allowed list: %v", notAllowedOptions) - } - } - - return criticalOptions, nil -} - -func (b *backend) calculateExtensions(data *framework.FieldData, role *sshRole) (map[string]string, error) { - unparsedExtensions := data.Get("extensions").(map[string]interface{}) - if len(unparsedExtensions) == 0 { - return role.DefaultExtensions, nil - } - - extensions := convertMapToStringValue(unparsedExtensions) - - if role.AllowedExtensions != "" { - notAllowed := []string{} - allowedExtensions := strings.Split(role.AllowedExtensions, ",") - - for extension := range extensions { - if !strutil.StrListContains(allowedExtensions, extension) { - notAllowed = append(notAllowed, extension) - } - } - - if len(notAllowed) != 0 { - return nil, fmt.Errorf("extensions %v are not on allowed list", notAllowed) - } - } - - return extensions, nil -} - -func (b *backend) calculateTTL(data *framework.FieldData, role *sshRole) (time.Duration, error) { - var ttl, maxTTL time.Duration - var err error - - ttlRaw, specifiedTTL := data.GetOk("ttl") - if specifiedTTL { - ttl = time.Duration(ttlRaw.(int)) * time.Second - } else { - ttl, err = parseutil.ParseDurationSecond(role.TTL) - if err != nil { - return 0, err - } - } - if ttl == 0 { - ttl = b.System().DefaultLeaseTTL() - } - - maxTTL, err = parseutil.ParseDurationSecond(role.MaxTTL) - if err != nil { - return 0, err - } - if maxTTL == 0 { - maxTTL = b.System().MaxLeaseTTL() - } - - if ttl > maxTTL { - // Don't error if they were using system defaults, only error if - // they specifically chose a bad TTL - if !specifiedTTL { - ttl = maxTTL - } else { - return 0, fmt.Errorf("ttl is larger than maximum allowed %d", maxTTL/time.Second) - } - } - - return ttl, nil -} - -func (b *creationBundle) sign() (retCert *ssh.Certificate, retErr error) { - defer func() { - if r := recover(); r != nil { - errMsg, ok := r.(string) - if ok { - retCert = nil - retErr = errors.New(errMsg) - } - } - }() - - serialNumber, err := certutil.GenerateSerialNumber() - if err != nil { - return nil, err - } - - now := time.Now() - - certificate := &ssh.Certificate{ - Serial: serialNumber.Uint64(), - Key: b.PublicKey, - KeyId: b.KeyId, - ValidPrincipals: b.ValidPrincipals, - ValidAfter: uint64(now.Add(-30 * time.Second).In(time.UTC).Unix()), - ValidBefore: uint64(now.Add(b.TTL).In(time.UTC).Unix()), - CertType: b.CertificateType, - Permissions: ssh.Permissions{ - CriticalOptions: b.CriticalOptions, - Extensions: b.Extensions, - }, - } - - err = certificate.SignCert(rand.Reader, b.Signer) - if err != nil { - return nil, fmt.Errorf("failed to generate signed SSH key") - } - - return certificate, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_verify.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_verify.go deleted file mode 100644 index da9bb4e6d..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/path_verify.go +++ /dev/null @@ -1,103 +0,0 @@ -package ssh - -import ( - "context" - - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathVerify(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "verify", - Fields: map[string]*framework.FieldSchema{ - "otp": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "[Required] One-Time-Key that needs to be validated", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathVerifyWrite, - }, - HelpSynopsis: pathVerifyHelpSyn, - HelpDescription: pathVerifyHelpDesc, - } -} - -func (b *backend) getOTP(ctx context.Context, s logical.Storage, n string) (*sshOTP, error) { - entry, err := s.Get(ctx, "otp/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result sshOTP - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathVerifyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - otp := d.Get("otp").(string) - - // If OTP is not a UUID and a string matching VerifyEchoRequest, then the - // response will be VerifyEchoResponse. This is used by agent to check if - // connection to Vault server is proper. - if otp == api.VerifyEchoRequest { - return &logical.Response{ - Data: map[string]interface{}{ - "message": api.VerifyEchoResponse, - }, - }, nil - } - - // Create the salt of OTP because entry would have been create with the - // salt and not directly of the OTP. Salt will yield the same value which - // because the seed is the same, the backend salt. - salt, err := b.Salt(ctx) - if err != nil { - return nil, err - } - otpSalted := salt.SaltID(otp) - - // Return nil if there is no entry found for the OTP - otpEntry, err := b.getOTP(ctx, req.Storage, otpSalted) - if err != nil { - return nil, err - } - if otpEntry == nil { - return logical.ErrorResponse("OTP not found"), nil - } - - // Delete the OTP if found. This is what makes the key an OTP. - err = req.Storage.Delete(ctx, "otp/"+otpSalted) - if err != nil { - return nil, err - } - - // Return username and IP only if there were no problems uptill this point. - return &logical.Response{ - Data: map[string]interface{}{ - "username": otpEntry.Username, - "ip": otpEntry.IP, - "role_name": otpEntry.RoleName, - }, - }, nil -} - -const pathVerifyHelpSyn = ` -Validate the OTP provided by Vault SSH Agent. -` - -const pathVerifyHelpDesc = ` -This path will be used by Vault SSH Agent running in the remote hosts. The OTP -provided by the client is sent to Vault for validation by the agent. If Vault -finds an entry for the OTP, it responds with the username and IP it is associated -with. Agent uses this information to authenticate the client. Vault deletes the -OTP after validating it once. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_dynamic_key.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_dynamic_key.go deleted file mode 100644 index 6078733f7..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_dynamic_key.go +++ /dev/null @@ -1,71 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -const SecretDynamicKeyType = "secret_dynamic_key_type" - -func secretDynamicKey(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretDynamicKeyType, - Fields: map[string]*framework.FieldSchema{ - "username": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Username in host", - }, - "ip": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "IP address of host", - }, - }, - - Renew: b.secretDynamicKeyRenew, - Revoke: b.secretDynamicKeyRevoke, - } -} - -func (b *backend) secretDynamicKeyRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return &logical.Response{Secret: req.Secret}, nil -} - -func (b *backend) secretDynamicKeyRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - type sec struct { - AdminUser string `mapstructure:"admin_user"` - Username string `mapstructure:"username"` - IP string `mapstructure:"ip"` - HostKeyName string `mapstructure:"host_key_name"` - DynamicPublicKey string `mapstructure:"dynamic_public_key"` - InstallScript string `mapstructure:"install_script"` - Port int `mapstructure:"port"` - } - - intSec := &sec{} - err := mapstructure.Decode(req.Secret.InternalData, intSec) - if err != nil { - return nil, errwrap.Wrapf("secret internal data could not be decoded: {{err}}", err) - } - - // Fetch the host key using the key name - hostKey, err := b.getKey(ctx, req.Storage, intSec.HostKeyName) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("key %q not found error: {{err}}", intSec.HostKeyName), err) - } - if hostKey == nil { - return nil, fmt.Errorf("key %q not found", intSec.HostKeyName) - } - - // Remove the public key from authorized_keys file in target machine - // The last param 'false' indicates that the key should be uninstalled. - err = b.installPublicKeyInTarget(ctx, intSec.AdminUser, intSec.Username, intSec.IP, intSec.Port, hostKey.Key, intSec.DynamicPublicKey, intSec.InstallScript, false) - if err != nil { - return nil, fmt.Errorf("error removing public key from authorized_keys file in target") - } - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_otp.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_otp.go deleted file mode 100644 index 40f75a308..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/secret_otp.go +++ /dev/null @@ -1,46 +0,0 @@ -package ssh - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const SecretOTPType = "secret_otp_type" - -func secretOTP(b *backend) *framework.Secret { - return &framework.Secret{ - Type: SecretOTPType, - Fields: map[string]*framework.FieldSchema{ - "otp": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "One time password", - }, - }, - - Revoke: b.secretOTPRevoke, - } -} - -func (b *backend) secretOTPRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - otpRaw, ok := req.Secret.InternalData["otp"] - if !ok { - return nil, fmt.Errorf("secret is missing internal data") - } - otp, ok := otpRaw.(string) - if !ok { - return nil, fmt.Errorf("secret is missing internal data") - } - - salt, err := b.Salt(ctx) - if err != nil { - return nil, err - } - err = req.Storage.Delete(ctx, "otp/"+salt.SaltID(otp)) - if err != nil { - return nil, err - } - return nil, nil -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/util.go b/vendor/github.com/hashicorp/vault/builtin/logical/ssh/util.go deleted file mode 100644 index 98a7036a4..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/ssh/util.go +++ /dev/null @@ -1,225 +0,0 @@ -package ssh - -import ( - "bytes" - "context" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "fmt" - "net" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - - log "github.com/hashicorp/go-hclog" - "golang.org/x/crypto/ssh" -) - -// Creates a new RSA key pair with the given key length. The private key will be -// of pem format and the public key will be of OpenSSH format. -func generateRSAKeys(keyBits int) (publicKeyRsa string, privateKeyRsa string, err error) { - privateKey, err := rsa.GenerateKey(rand.Reader, keyBits) - if err != nil { - return "", "", errwrap.Wrapf("error generating RSA key-pair: {{err}}", err) - } - - privateKeyRsa = string(pem.EncodeToMemory(&pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: x509.MarshalPKCS1PrivateKey(privateKey), - })) - - sshPublicKey, err := ssh.NewPublicKey(privateKey.Public()) - if err != nil { - return "", "", errwrap.Wrapf("error generating RSA key-pair: {{err}}", err) - } - publicKeyRsa = "ssh-rsa " + base64.StdEncoding.EncodeToString(sshPublicKey.Marshal()) - return -} - -// Public key and the script to install the key are uploaded to remote machine. -// Public key is either added or removed from authorized_keys file using the -// script. Default script is for a Linux machine and hence the path of the -// authorized_keys file is hard coded to resemble Linux. -// -// The last param 'install' if false, uninstalls the key. -func (b *backend) installPublicKeyInTarget(ctx context.Context, adminUser, username, ip string, port int, hostkey, dynamicPublicKey, installScript string, install bool) error { - // Transfer the newly generated public key to remote host under a random - // file name. This is to avoid name collisions from other requests. - _, publicKeyFileName, err := b.GenerateSaltedOTP(ctx) - if err != nil { - return err - } - - comm, err := createSSHComm(b.Logger(), adminUser, ip, port, hostkey) - if err != nil { - return err - } - defer comm.Close() - - err = comm.Upload(publicKeyFileName, bytes.NewBufferString(dynamicPublicKey), nil) - if err != nil { - return errwrap.Wrapf("error uploading public key: {{err}}", err) - } - - // Transfer the script required to install or uninstall the key to the remote - // host under a random file name as well. This is to avoid name collisions - // from other requests. - scriptFileName := fmt.Sprintf("%s.sh", publicKeyFileName) - err = comm.Upload(scriptFileName, bytes.NewBufferString(installScript), nil) - if err != nil { - return errwrap.Wrapf("error uploading install script: {{err}}", err) - } - - // Create a session to run remote command that triggers the script to install - // or uninstall the key. - session, err := comm.NewSession() - if err != nil { - return errwrap.Wrapf("unable to create SSH Session using public keys: {{err}}", err) - } - if session == nil { - return fmt.Errorf("invalid session object") - } - defer session.Close() - - authKeysFileName := fmt.Sprintf("/home/%s/.ssh/authorized_keys", username) - - var installOption string - if install { - installOption = "install" - } else { - installOption = "uninstall" - } - - // Give execute permissions to install script, run and delete it. - chmodCmd := fmt.Sprintf("chmod +x %s", scriptFileName) - scriptCmd := fmt.Sprintf("./%s %s %s %s", scriptFileName, installOption, publicKeyFileName, authKeysFileName) - rmCmd := fmt.Sprintf("rm -f %s", scriptFileName) - targetCmd := fmt.Sprintf("%s;%s;%s", chmodCmd, scriptCmd, rmCmd) - - session.Run(targetCmd) - return nil -} - -// Takes an IP address and role name and checks if the IP is part -// of CIDR blocks belonging to the role. -func roleContainsIP(ctx context.Context, s logical.Storage, roleName string, ip string) (bool, error) { - if roleName == "" { - return false, fmt.Errorf("missing role name") - } - - if ip == "" { - return false, fmt.Errorf("missing ip") - } - - roleEntry, err := s.Get(ctx, fmt.Sprintf("roles/%s", roleName)) - if err != nil { - return false, errwrap.Wrapf("error retrieving role {{err}}", err) - } - if roleEntry == nil { - return false, fmt.Errorf("role %q not found", roleName) - } - - var role sshRole - if err := roleEntry.DecodeJSON(&role); err != nil { - return false, fmt.Errorf("error decoding role %q", roleName) - } - - if matched, err := cidrListContainsIP(ip, role.CIDRList); err != nil { - return false, err - } else { - return matched, nil - } -} - -// Returns true if the IP supplied by the user is part of the comma -// separated CIDR blocks -func cidrListContainsIP(ip, cidrList string) (bool, error) { - if len(cidrList) == 0 { - return false, fmt.Errorf("IP does not belong to role") - } - for _, item := range strings.Split(cidrList, ",") { - _, cidrIPNet, err := net.ParseCIDR(item) - if err != nil { - return false, fmt.Errorf("invalid CIDR entry %q", item) - } - if cidrIPNet.Contains(net.ParseIP(ip)) { - return true, nil - } - } - return false, nil -} - -func createSSHComm(logger log.Logger, username, ip string, port int, hostkey string) (*comm, error) { - signer, err := ssh.ParsePrivateKey([]byte(hostkey)) - if err != nil { - return nil, err - } - - clientConfig := &ssh.ClientConfig{ - User: username, - Auth: []ssh.AuthMethod{ - ssh.PublicKeys(signer), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - } - - connfunc := func() (net.Conn, error) { - c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, port), 15*time.Second) - if err != nil { - return nil, err - } - - if tcpConn, ok := c.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(5 * time.Second) - } - - return c, nil - } - config := &SSHCommConfig{ - SSHConfig: clientConfig, - Connection: connfunc, - Pty: false, - DisableAgent: true, - Logger: logger, - } - - return SSHCommNew(fmt.Sprintf("%s:%d", ip, port), config) -} - -func parsePublicSSHKey(key string) (ssh.PublicKey, error) { - keyParts := strings.Split(key, " ") - if len(keyParts) > 1 { - // Someone has sent the 'full' public key rather than just the base64 encoded part that the ssh library wants - key = keyParts[1] - } - - decodedKey, err := base64.StdEncoding.DecodeString(key) - if err != nil { - return nil, err - } - - return ssh.ParsePublicKey([]byte(decodedKey)) -} - -func convertMapToStringValue(initial map[string]interface{}) map[string]string { - result := map[string]string{} - for key, value := range initial { - result[key] = fmt.Sprintf("%v", value) - } - return result -} - -// Serve a template processor for custom format inputs -func substQuery(tpl string, data map[string]string) string { - for k, v := range data { - tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1) - } - - return tpl -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/totp/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/totp/backend.go deleted file mode 100644 index d14246608..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/totp/backend.go +++ /dev/null @@ -1,55 +0,0 @@ -package totp - -import ( - "context" - "strings" - "time" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - cache "github.com/patrickmn/go-cache" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend() - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend() *backend { - var b backend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(backendHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "key/", - }, - }, - - Paths: []*framework.Path{ - pathListKeys(&b), - pathKeys(&b), - pathCode(&b), - }, - - Secrets: []*framework.Secret{}, - BackendType: logical.TypeLogical, - } - - b.usedCodes = cache.New(0, 30*time.Second) - - return &b -} - -type backend struct { - *framework.Backend - - usedCodes *cache.Cache -} - -const backendHelp = ` -The TOTP backend dynamically generates time-based one-time use passwords. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_code.go b/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_code.go deleted file mode 100644 index 41a66bbc3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_code.go +++ /dev/null @@ -1,127 +0,0 @@ -package totp - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - otplib "github.com/pquerna/otp" - totplib "github.com/pquerna/otp/totp" -) - -func pathCode(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "code/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key.", - }, - "code": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "TOTP code to be validated.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathReadCode, - logical.UpdateOperation: b.pathValidateCode, - }, - - HelpSynopsis: pathCodeHelpSyn, - HelpDescription: pathCodeHelpDesc, - } -} - -func (b *backend) pathReadCode(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - // Get the key - key, err := b.Key(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if key == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown key: %s", name)), nil - } - - // Generate password using totp library - totpToken, err := totplib.GenerateCodeCustom(key.Key, time.Now(), totplib.ValidateOpts{ - Period: key.Period, - Digits: key.Digits, - Algorithm: key.Algorithm, - }) - if err != nil { - return nil, err - } - - // Return the secret - return &logical.Response{ - Data: map[string]interface{}{ - "code": totpToken, - }, - }, nil -} - -func (b *backend) pathValidateCode(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - code := data.Get("code").(string) - - // Enforce input value requirements - if code == "" { - return logical.ErrorResponse("the code value is required"), nil - } - - // Get the key's stored values - key, err := b.Key(ctx, req.Storage, name) - if err != nil { - return nil, err - } - if key == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown key: %s", name)), nil - } - - usedName := fmt.Sprintf("%s_%s", name, code) - - _, ok := b.usedCodes.Get(usedName) - if ok { - return logical.ErrorResponse("code already used; wait until the next time period"), nil - } - - valid, err := totplib.ValidateCustom(code, key.Key, time.Now(), totplib.ValidateOpts{ - Period: key.Period, - Skew: key.Skew, - Digits: key.Digits, - Algorithm: key.Algorithm, - }) - if err != nil && err != otplib.ErrValidateInputInvalidLength { - return logical.ErrorResponse("an error occured while validating the code"), err - } - - // Take the key skew, add two for behind and in front, and multiple that by - // the period to cover the full possibility of the validity of the key - err = b.usedCodes.Add(usedName, nil, time.Duration( - int64(time.Second)* - int64(key.Period)* - int64((2+key.Skew)))) - if err != nil { - return nil, errwrap.Wrapf("error adding code to used cache: {{err}}", err) - } - - return &logical.Response{ - Data: map[string]interface{}{ - "valid": valid, - }, - }, nil -} - -const pathCodeHelpSyn = ` -Request time-based one-time use password or validate a password for a certain key . -` -const pathCodeHelpDesc = ` -This path generates and validates time-based one-time use passwords for a certain key. - -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_keys.go b/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_keys.go deleted file mode 100644 index 9f2b2a26c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/totp/path_keys.go +++ /dev/null @@ -1,422 +0,0 @@ -package totp - -import ( - "bytes" - "context" - "encoding/base32" - "encoding/base64" - "fmt" - "image/png" - "net/url" - "strconv" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - otplib "github.com/pquerna/otp" - totplib "github.com/pquerna/otp/totp" -) - -func pathListKeys(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "keys/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathKeyList, - }, - - HelpSynopsis: pathKeyHelpSyn, - HelpDescription: pathKeyHelpDesc, - } -} - -func pathKeys(b *backend) *framework.Path { - return &framework.Path{ - Pattern: "keys/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the key.", - }, - - "generate": { - Type: framework.TypeBool, - Default: false, - Description: "Determines if a key should be generated by Vault or if a key is being passed from another service.", - }, - - "exported": { - Type: framework.TypeBool, - Default: true, - Description: "Determines if a QR code and url are returned upon generating a key. Only used if generate is true.", - }, - - "key_size": { - Type: framework.TypeInt, - Default: 20, - Description: "Determines the size in bytes of the generated key. Only used if generate is true.", - }, - - "key": { - Type: framework.TypeString, - Description: "The shared master key used to generate a TOTP token. Only used if generate is false.", - }, - - "issuer": { - Type: framework.TypeString, - Description: `The name of the key's issuing organization. Required if generate is true.`, - }, - - "account_name": { - Type: framework.TypeString, - Description: `The name of the account associated with the key. Required if generate is true.`, - }, - - "period": { - Type: framework.TypeDurationSecond, - Default: 30, - Description: `The length of time used to generate a counter for the TOTP token calculation.`, - }, - - "algorithm": { - Type: framework.TypeString, - Default: "SHA1", - Description: `The hashing algorithm used to generate the TOTP token. Options include SHA1, SHA256 and SHA512.`, - }, - - "digits": { - Type: framework.TypeInt, - Default: 6, - Description: `The number of digits in the generated TOTP token. This value can either be 6 or 8.`, - }, - - "skew": { - Type: framework.TypeInt, - Default: 1, - Description: `The number of delay periods that are allowed when validating a TOTP token. This value can either be 0 or 1. Only used if generate is true.`, - }, - - "qr_size": { - Type: framework.TypeInt, - Default: 200, - Description: `The pixel size of the generated square QR code. Only used if generate is true and exported is true. If this value is 0, a QR code will not be returned.`, - }, - - "url": { - Type: framework.TypeString, - Description: `A TOTP url string containing all of the parameters for key setup. Only used if generate is false.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathKeyRead, - logical.UpdateOperation: b.pathKeyCreate, - logical.DeleteOperation: b.pathKeyDelete, - }, - - HelpSynopsis: pathKeyHelpSyn, - HelpDescription: pathKeyHelpDesc, - } -} - -func (b *backend) Key(ctx context.Context, s logical.Storage, n string) (*keyEntry, error) { - entry, err := s.Get(ctx, "key/"+n) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result keyEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (b *backend) pathKeyDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := req.Storage.Delete(ctx, "key/"+data.Get("name").(string)) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathKeyRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - key, err := b.Key(ctx, req.Storage, data.Get("name").(string)) - if err != nil { - return nil, err - } - if key == nil { - return nil, nil - } - - // Translate algorithm back to string - algorithm := key.Algorithm.String() - - // Return values of key - return &logical.Response{ - Data: map[string]interface{}{ - "issuer": key.Issuer, - "account_name": key.AccountName, - "period": key.Period, - "algorithm": algorithm, - "digits": key.Digits, - }, - }, nil -} - -func (b *backend) pathKeyList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "key/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathKeyCreate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - generate := data.Get("generate").(bool) - exported := data.Get("exported").(bool) - keyString := data.Get("key").(string) - issuer := data.Get("issuer").(string) - accountName := data.Get("account_name").(string) - period := data.Get("period").(int) - algorithm := data.Get("algorithm").(string) - digits := data.Get("digits").(int) - skew := data.Get("skew").(int) - qrSize := data.Get("qr_size").(int) - keySize := data.Get("key_size").(int) - inputURL := data.Get("url").(string) - - if generate { - if keyString != "" { - return logical.ErrorResponse("a key should not be passed if generate is true"), nil - } - if inputURL != "" { - return logical.ErrorResponse("a url should not be passed if generate is true"), nil - } - } - - // Read parameters from url if given - if inputURL != "" { - //Parse url - urlObject, err := url.Parse(inputURL) - if err != nil { - return logical.ErrorResponse("an error occured while parsing url string"), err - } - - //Set up query object - urlQuery := urlObject.Query() - path := strings.TrimPrefix(urlObject.Path, "/") - index := strings.Index(path, ":") - - //Read issuer - urlIssuer := urlQuery.Get("issuer") - if urlIssuer != "" { - issuer = urlIssuer - } else { - if index != -1 { - issuer = path[:index] - } - } - - //Read account name - if index == -1 { - accountName = path - } else { - accountName = path[index+1:] - } - - //Read key string - keyString = urlQuery.Get("secret") - - //Read period - periodQuery := urlQuery.Get("period") - if periodQuery != "" { - periodInt, err := strconv.Atoi(periodQuery) - if err != nil { - return logical.ErrorResponse("an error occured while parsing period value in url"), err - } - period = periodInt - } - - //Read digits - digitsQuery := urlQuery.Get("digits") - if digitsQuery != "" { - digitsInt, err := strconv.Atoi(digitsQuery) - if err != nil { - return logical.ErrorResponse("an error occured while parsing digits value in url"), err - } - digits = digitsInt - } - - //Read algorithm - algorithmQuery := urlQuery.Get("algorithm") - if algorithmQuery != "" { - algorithm = algorithmQuery - } - } - - // Translate digits and algorithm to a format the totp library understands - var keyDigits otplib.Digits - switch digits { - case 6: - keyDigits = otplib.DigitsSix - case 8: - keyDigits = otplib.DigitsEight - default: - return logical.ErrorResponse("the digits value can only be 6 or 8"), nil - } - - var keyAlgorithm otplib.Algorithm - switch algorithm { - case "SHA1": - keyAlgorithm = otplib.AlgorithmSHA1 - case "SHA256": - keyAlgorithm = otplib.AlgorithmSHA256 - case "SHA512": - keyAlgorithm = otplib.AlgorithmSHA512 - default: - return logical.ErrorResponse("the algorithm value is not valid"), nil - } - - // Enforce input value requirements - if period <= 0 { - return logical.ErrorResponse("the period value must be greater than zero"), nil - } - - switch skew { - case 0: - case 1: - default: - return logical.ErrorResponse("the skew value must be 0 or 1"), nil - } - - // QR size can be zero but it shouldn't be negative - if qrSize < 0 { - return logical.ErrorResponse("the qr_size value must be greater than or equal to zero"), nil - } - - if keySize <= 0 { - return logical.ErrorResponse("the key_size value must be greater than zero"), nil - } - - // Period, Skew and Key Size need to be unsigned ints - uintPeriod := uint(period) - uintSkew := uint(skew) - uintKeySize := uint(keySize) - - var response *logical.Response - - switch generate { - case true: - // If the key is generated, Account Name and Issuer are required. - if accountName == "" { - return logical.ErrorResponse("the account_name value is required for generated keys"), nil - } - - if issuer == "" { - return logical.ErrorResponse("the issuer value is required for generated keys"), nil - } - - // Generate a new key - keyObject, err := totplib.Generate(totplib.GenerateOpts{ - Issuer: issuer, - AccountName: accountName, - Period: uintPeriod, - Digits: keyDigits, - Algorithm: keyAlgorithm, - SecretSize: uintKeySize, - }) - if err != nil { - return logical.ErrorResponse("an error occured while generating a key"), err - } - - // Get key string value - keyString = keyObject.Secret() - - // Skip returning the QR code and url if exported is set to false - if exported { - // Prepare the url and barcode - urlString := keyObject.String() - - // Don't include QR code if size is set to zero - if qrSize == 0 { - response = &logical.Response{ - Data: map[string]interface{}{ - "url": urlString, - }, - } - } else { - barcode, err := keyObject.Image(qrSize, qrSize) - if err != nil { - return nil, errwrap.Wrapf("failed to generate QR code image: {{err}}", err) - } - - var buff bytes.Buffer - png.Encode(&buff, barcode) - b64Barcode := base64.StdEncoding.EncodeToString(buff.Bytes()) - response = &logical.Response{ - Data: map[string]interface{}{ - "url": urlString, - "barcode": b64Barcode, - }, - } - } - } - default: - if keyString == "" { - return logical.ErrorResponse("the key value is required"), nil - } - - _, err := base32.StdEncoding.DecodeString(keyString) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "invalid key value: %s", err)), nil - } - } - - // Store it - entry, err := logical.StorageEntryJSON("key/"+name, &keyEntry{ - Key: keyString, - Issuer: issuer, - AccountName: accountName, - Period: uintPeriod, - Algorithm: keyAlgorithm, - Digits: keyDigits, - Skew: uintSkew, - }) - if err != nil { - return nil, err - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return response, nil -} - -type keyEntry struct { - Key string `json:"key" mapstructure:"key" structs:"key"` - Issuer string `json:"issuer" mapstructure:"issuer" structs:"issuer"` - AccountName string `json:"account_name" mapstructure:"account_name" structs:"account_name"` - Period uint `json:"period" mapstructure:"period" structs:"period"` - Algorithm otplib.Algorithm `json:"algorithm" mapstructure:"algorithm" structs:"algorithm"` - Digits otplib.Digits `json:"digits" mapstructure:"digits" structs:"digits"` - Skew uint `json:"skew" mapstructure:"skew" structs:"skew"` -} - -const pathKeyHelpSyn = ` -Manage the keys that can be created with this backend. -` - -const pathKeyHelpDesc = ` -This path lets you manage the keys that can be created with this backend. - -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/backend.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/backend.go deleted file mode 100644 index 1bb7f4c92..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/backend.go +++ /dev/null @@ -1,75 +0,0 @@ -package transit - -import ( - "context" - "strings" - - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - b := Backend(conf) - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -func Backend(conf *logical.BackendConfig) *backend { - var b backend - b.Backend = &framework.Backend{ - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "archive/", - "policy/", - }, - }, - - Paths: []*framework.Path{ - // Rotate/Config needs to come before Keys - // as the handler is greedy - b.pathConfig(), - b.pathRotate(), - b.pathRewrap(), - b.pathKeys(), - b.pathListKeys(), - b.pathExportKeys(), - b.pathEncrypt(), - b.pathDecrypt(), - b.pathDatakey(), - b.pathRandom(), - b.pathHash(), - b.pathHMAC(), - b.pathSign(), - b.pathVerify(), - b.pathBackup(), - b.pathRestore(), - }, - - Secrets: []*framework.Secret{}, - Invalidate: b.invalidate, - BackendType: logical.TypeLogical, - } - - b.lm = keysutil.NewLockManager(conf.System.CachingDisabled()) - - return &b -} - -type backend struct { - *framework.Backend - lm *keysutil.LockManager -} - -func (b *backend) invalidate(_ context.Context, key string) { - if b.Logger().IsDebug() { - b.Logger().Debug("invalidating key", "key", key) - } - switch { - case strings.HasPrefix(key, "policy/"): - name := strings.TrimPrefix(key, "policy/") - b.lm.InvalidatePolicy(name) - } -} diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_backup.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_backup.go deleted file mode 100644 index 174959125..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_backup.go +++ /dev/null @@ -1,43 +0,0 @@ -package transit - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathBackup() *framework.Path { - return &framework.Path{ - Pattern: "backup/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathBackupRead, - }, - - HelpSynopsis: pathBackupHelpSyn, - HelpDescription: pathBackupHelpDesc, - } -} - -func (b *backend) pathBackupRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - backup, err := b.lm.BackupPolicy(ctx, req.Storage, d.Get("name").(string)) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: map[string]interface{}{ - "backup": backup, - }, - }, nil -} - -const pathBackupHelpSyn = `Backup the named key` -const pathBackupHelpDesc = `This path is used to backup the named key.` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_config.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_config.go deleted file mode 100644 index e97a0a698..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_config.go +++ /dev/null @@ -1,189 +0,0 @@ -package transit - -import ( - "context" - "fmt" - - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathConfig() *framework.Path { - return &framework.Path{ - Pattern: "keys/" + framework.GenericNameRegex("name") + "/config", - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - - "min_decryption_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `If set, the minimum version of the key allowed -to be decrypted. For signing keys, the minimum -version allowed to be used for verification.`, - }, - - "min_encryption_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `If set, the minimum version of the key allowed -to be used for encryption; or for signing keys, -to be used for signing. If set to zero, only -the latest version of the key is allowed.`, - }, - - "deletion_allowed": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Whether to allow deletion of the key", - }, - - "exportable": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Enables export of the key. Once set, this cannot be disabled.`, - }, - - "allow_plaintext_backup": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Enables taking a backup of the named key in plaintext format. Once set, this cannot be disabled.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathConfigWrite, - }, - - HelpSynopsis: pathConfigHelpSyn, - HelpDescription: pathConfigHelpDesc, - } -} - -func (b *backend) pathConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - // Check if the policy already exists before we lock everything - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse( - fmt.Sprintf("no existing key named %s could be found", name)), - logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(true) - } - defer p.Unlock() - - resp := &logical.Response{} - - persistNeeded := false - - minDecryptionVersionRaw, ok := d.GetOk("min_decryption_version") - if ok { - minDecryptionVersion := minDecryptionVersionRaw.(int) - - if minDecryptionVersion < 0 { - return logical.ErrorResponse("min decryption version cannot be negative"), nil - } - - if minDecryptionVersion == 0 { - minDecryptionVersion = 1 - resp.AddWarning("since Vault 0.3, transit key numbering starts at 1; forcing minimum to 1") - } - - if minDecryptionVersion != p.MinDecryptionVersion { - if minDecryptionVersion > p.LatestVersion { - return logical.ErrorResponse( - fmt.Sprintf("cannot set min decryption version of %d, latest key version is %d", minDecryptionVersion, p.LatestVersion)), nil - } - p.MinDecryptionVersion = minDecryptionVersion - persistNeeded = true - } - } - - minEncryptionVersionRaw, ok := d.GetOk("min_encryption_version") - if ok { - minEncryptionVersion := minEncryptionVersionRaw.(int) - - if minEncryptionVersion < 0 { - return logical.ErrorResponse("min encryption version cannot be negative"), nil - } - - if minEncryptionVersion != p.MinEncryptionVersion { - if minEncryptionVersion > p.LatestVersion { - return logical.ErrorResponse( - fmt.Sprintf("cannot set min encryption version of %d, latest key version is %d", minEncryptionVersion, p.LatestVersion)), nil - } - p.MinEncryptionVersion = minEncryptionVersion - persistNeeded = true - } - } - - // Check here to get the final picture after the logic on each - // individually. MinDecryptionVersion will always be 1 or above. - if p.MinEncryptionVersion > 0 && - p.MinEncryptionVersion < p.MinDecryptionVersion { - return logical.ErrorResponse( - fmt.Sprintf("cannot set min encryption/decryption values; min encryption version of %d must be greater than or equal to min decryption version of %d", p.MinEncryptionVersion, p.MinDecryptionVersion)), nil - } - - allowDeletionInt, ok := d.GetOk("deletion_allowed") - if ok { - allowDeletion := allowDeletionInt.(bool) - if allowDeletion != p.DeletionAllowed { - p.DeletionAllowed = allowDeletion - persistNeeded = true - } - } - - // Add this as a guard here before persisting since we now require the min - // decryption version to start at 1; even if it's not explicitly set here, - // force the upgrade - if p.MinDecryptionVersion == 0 { - p.MinDecryptionVersion = 1 - persistNeeded = true - } - - exportableRaw, ok := d.GetOk("exportable") - if ok { - exportable := exportableRaw.(bool) - // Don't unset the already set value - if exportable && !p.Exportable { - p.Exportable = exportable - persistNeeded = true - } - } - - allowPlaintextBackupRaw, ok := d.GetOk("allow_plaintext_backup") - if ok { - allowPlaintextBackup := allowPlaintextBackupRaw.(bool) - // Don't unset the already set value - if allowPlaintextBackup && !p.AllowPlaintextBackup { - p.AllowPlaintextBackup = allowPlaintextBackup - persistNeeded = true - } - } - - if !persistNeeded { - return nil, nil - } - - if len(resp.Warnings) == 0 { - return nil, p.Persist(ctx, req.Storage) - } - - return resp, p.Persist(ctx, req.Storage) -} - -const pathConfigHelpSyn = `Configure a named encryption key` - -const pathConfigHelpDesc = ` -This path is used to configure the named key. Currently, this -supports adjusting the minimum version of the key allowed to -be used for decryption via the min_decryption_version parameter. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_datakey.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_datakey.go deleted file mode 100644 index 0141e1736..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_datakey.go +++ /dev/null @@ -1,173 +0,0 @@ -package transit - -import ( - "context" - "crypto/rand" - "encoding/base64" - "fmt" - - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathDatakey() *framework.Path { - return &framework.Path{ - Pattern: "datakey/" + framework.GenericNameRegex("plaintext") + "/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The backend key used for encrypting the data key", - }, - - "plaintext": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `"plaintext" will return the key in both plaintext and -ciphertext; "wrapped" will return the ciphertext only.`, - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Context for key derivation. Required for derived keys.", - }, - - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Nonce for when convergent encryption v1 is used (only in Vault 0.6.1)", - }, - - "bits": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `Number of bits for the key; currently 128, 256, -and 512 bits are supported. Defaults to 256.`, - Default: 256, - }, - - "key_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The version of the Vault key to use for -encryption of the data key. Must be 0 (for latest) -or a value greater than or equal to the -min_encryption_version configured on the key.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathDatakeyWrite, - }, - - HelpSynopsis: pathDatakeyHelpSyn, - HelpDescription: pathDatakeyHelpDesc, - } -} - -func (b *backend) pathDatakeyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - ver := d.Get("key_version").(int) - - plaintext := d.Get("plaintext").(string) - plaintextAllowed := false - switch plaintext { - case "plaintext": - plaintextAllowed = true - case "wrapped": - default: - return logical.ErrorResponse("Invalid path, must be 'plaintext' or 'wrapped'"), logical.ErrInvalidRequest - } - - var err error - - // Decode the context if any - contextRaw := d.Get("context").(string) - var context []byte - if len(contextRaw) != 0 { - context, err = base64.StdEncoding.DecodeString(contextRaw) - if err != nil { - return logical.ErrorResponse("failed to base64-decode context"), logical.ErrInvalidRequest - } - } - - // Decode the nonce if any - nonceRaw := d.Get("nonce").(string) - var nonce []byte - if len(nonceRaw) != 0 { - nonce, err = base64.StdEncoding.DecodeString(nonceRaw) - if err != nil { - return logical.ErrorResponse("failed to base64-decode nonce"), logical.ErrInvalidRequest - } - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - defer p.Unlock() - - newKey := make([]byte, 32) - bits := d.Get("bits").(int) - switch bits { - case 512: - newKey = make([]byte, 64) - case 256: - case 128: - newKey = make([]byte, 16) - default: - return logical.ErrorResponse("invalid bit length"), logical.ErrInvalidRequest - } - _, err = rand.Read(newKey) - if err != nil { - return nil, err - } - - ciphertext, err := p.Encrypt(ver, context, nonce, base64.StdEncoding.EncodeToString(newKey)) - if err != nil { - switch err.(type) { - case errutil.UserError: - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - case errutil.InternalError: - return nil, err - default: - return nil, err - } - } - - if ciphertext == "" { - return nil, fmt.Errorf("empty ciphertext returned") - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "ciphertext": ciphertext, - }, - } - - if plaintextAllowed { - resp.Data["plaintext"] = base64.StdEncoding.EncodeToString(newKey) - } - - return resp, nil -} - -const pathDatakeyHelpSyn = `Generate a data key` - -const pathDatakeyHelpDesc = ` -This path can be used to generate a data key: a random -key of a certain length that can be used for encryption -and decryption, protected by the named backend key. 128, 256, -or 512 bits can be specified; if not specified, the default -is 256 bits. Call with the the "wrapped" path to prevent the -(base64-encoded) plaintext key from being returned along with -the encrypted key, the "plaintext" path returns both. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_decrypt.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_decrypt.go deleted file mode 100644 index 2e3185664..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_decrypt.go +++ /dev/null @@ -1,172 +0,0 @@ -package transit - -import ( - "context" - "encoding/base64" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -func (b *backend) pathDecrypt() *framework.Path { - return &framework.Path{ - Pattern: "decrypt/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the policy", - }, - - "ciphertext": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` -The ciphertext to decrypt, provided as returned by encrypt.`, - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` -Base64 encoded context for key derivation. Required if key derivation is -enabled.`, - }, - - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` -Base64 encoded nonce value used during encryption. Must be provided if -convergent encryption is enabled for this key and the key was generated with -Vault 0.6.1. Not required for keys created in 0.6.2+.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathDecryptWrite, - }, - - HelpSynopsis: pathDecryptHelpSyn, - HelpDescription: pathDecryptHelpDesc, - } -} - -func (b *backend) pathDecryptWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - batchInputRaw := d.Raw["batch_input"] - var batchInputItems []BatchRequestItem - var err error - if batchInputRaw != nil { - err = mapstructure.Decode(batchInputRaw, &batchInputItems) - if err != nil { - return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) - } - - if len(batchInputItems) == 0 { - return logical.ErrorResponse("missing batch input to process"), logical.ErrInvalidRequest - } - } else { - ciphertext := d.Get("ciphertext").(string) - if len(ciphertext) == 0 { - return logical.ErrorResponse("missing ciphertext to decrypt"), logical.ErrInvalidRequest - } - - batchInputItems = make([]BatchRequestItem, 1) - batchInputItems[0] = BatchRequestItem{ - Ciphertext: ciphertext, - Context: d.Get("context").(string), - Nonce: d.Get("nonce").(string), - } - } - - batchResponseItems := make([]BatchResponseItem, len(batchInputItems)) - contextSet := len(batchInputItems[0].Context) != 0 - - for i, item := range batchInputItems { - if (len(item.Context) == 0 && contextSet) || (len(item.Context) != 0 && !contextSet) { - return logical.ErrorResponse("context should be set either in all the request blocks or in none"), logical.ErrInvalidRequest - } - - if item.Ciphertext == "" { - batchResponseItems[i].Error = "missing ciphertext to decrypt" - continue - } - - // Decode the context - if len(item.Context) != 0 { - batchInputItems[i].DecodedContext, err = base64.StdEncoding.DecodeString(item.Context) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - - // Decode the nonce - if len(item.Nonce) != 0 { - batchInputItems[i].DecodedNonce, err = base64.StdEncoding.DecodeString(item.Nonce) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: d.Get("name").(string), - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - for i, item := range batchInputItems { - if batchResponseItems[i].Error != "" { - continue - } - - plaintext, err := p.Decrypt(item.DecodedContext, item.DecodedNonce, item.Ciphertext) - if err != nil { - switch err.(type) { - case errutil.UserError: - batchResponseItems[i].Error = err.Error() - continue - default: - p.Unlock() - return nil, err - } - } - batchResponseItems[i].Plaintext = plaintext - } - - resp := &logical.Response{} - if batchInputRaw != nil { - resp.Data = map[string]interface{}{ - "batch_results": batchResponseItems, - } - } else { - if batchResponseItems[0].Error != "" { - p.Unlock() - return logical.ErrorResponse(batchResponseItems[0].Error), logical.ErrInvalidRequest - } - resp.Data = map[string]interface{}{ - "plaintext": batchResponseItems[0].Plaintext, - } - } - - p.Unlock() - return resp, nil -} - -const pathDecryptHelpSyn = `Decrypt a ciphertext value using a named key` - -const pathDecryptHelpDesc = ` -This path uses the named key from the request path to decrypt a user -provided ciphertext. The plaintext is returned base64 encoded. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_encrypt.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_encrypt.go deleted file mode 100644 index 8c5e6c658..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_encrypt.go +++ /dev/null @@ -1,314 +0,0 @@ -package transit - -import ( - "context" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -// BatchRequestItem represents a request item for batch processing -type BatchRequestItem struct { - // Context for key derivation. This is required for derived keys. - Context string `json:"context" structs:"context" mapstructure:"context"` - - // DecodedContext is the base64 decoded version of Context - DecodedContext []byte - - // Plaintext for encryption - Plaintext string `json:"plaintext" structs:"plaintext" mapstructure:"plaintext"` - - // Ciphertext for decryption - Ciphertext string `json:"ciphertext" structs:"ciphertext" mapstructure:"ciphertext"` - - // Nonce to be used when v1 convergent encryption is used - Nonce string `json:"nonce" structs:"nonce" mapstructure:"nonce"` - - // The key version to be used for encryption - KeyVersion int `json:"key_version" structs:"key_version" mapstructure:"key_version"` - - // DecodedNonce is the base64 decoded version of Nonce - DecodedNonce []byte -} - -// BatchResponseItem represents a response item for batch processing -type BatchResponseItem struct { - // Ciphertext for the plaintext present in the corresponding batch - // request item - Ciphertext string `json:"ciphertext,omitempty" structs:"ciphertext" mapstructure:"ciphertext"` - - // Plaintext for the ciphertext present in the corresponding batch - // request item - Plaintext string `json:"plaintext,omitempty" structs:"plaintext" mapstructure:"plaintext"` - - // Error, if set represents a failure encountered while encrypting a - // corresponding batch request item - Error string `json:"error,omitempty" structs:"error" mapstructure:"error"` -} - -func (b *backend) pathEncrypt() *framework.Path { - return &framework.Path{ - Pattern: "encrypt/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the policy", - }, - - "plaintext": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Base64 encoded plaintext value to be encrypted", - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Base64 encoded context for key derivation. Required if key derivation is enabled", - }, - - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: ` -Base64 encoded nonce value. Must be provided if convergent encryption is -enabled for this key and the key was generated with Vault 0.6.1. Not required -for keys created in 0.6.2+. The value must be exactly 96 bits (12 bytes) long -and the user must ensure that for any given context (and thus, any given -encryption key) this nonce value is **never reused**. -`, - }, - - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "aes256-gcm96", - Description: ` -This parameter is required when encryption key is expected to be created. -When performing an upsert operation, the type of key to create. Currently, -"aes256-gcm96" (symmetric) is the only type supported. Defaults to -"aes256-gcm96".`, - }, - - "convergent_encryption": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: ` -This parameter will only be used when a key is expected to be created. Whether -to support convergent encryption. This is only supported when using a key with -key derivation enabled and will require all requests to carry both a context -and 96-bit (12-byte) nonce. The given nonce will be used in place of a randomly -generated nonce. As a result, when the same context and nonce are supplied, the -same ciphertext is generated. It is *very important* when using this mode that -you ensure that all nonces are unique for a given context. Failing to do so -will severely impact the ciphertext's security.`, - }, - - "key_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The version of the key to use for encryption. -Must be 0 (for latest) or a value greater than or equal -to the min_encryption_version configured on the key.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.CreateOperation: b.pathEncryptWrite, - logical.UpdateOperation: b.pathEncryptWrite, - }, - - ExistenceCheck: b.pathEncryptExistenceCheck, - - HelpSynopsis: pathEncryptHelpSyn, - HelpDescription: pathEncryptHelpDesc, - } -} - -func (b *backend) pathEncryptExistenceCheck(ctx context.Context, req *logical.Request, d *framework.FieldData) (bool, error) { - name := d.Get("name").(string) - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return false, err - } - if p != nil && b.System().CachingDisabled() { - p.Unlock() - } - - return p != nil, nil -} - -func (b *backend) pathEncryptWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - var err error - - batchInputRaw := d.Raw["batch_input"] - var batchInputItems []BatchRequestItem - if batchInputRaw != nil { - err = mapstructure.Decode(batchInputRaw, &batchInputItems) - if err != nil { - return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) - } - - if len(batchInputItems) == 0 { - return logical.ErrorResponse("missing batch input to process"), logical.ErrInvalidRequest - } - } else { - valueRaw, ok := d.GetOk("plaintext") - if !ok { - return logical.ErrorResponse("missing plaintext to encrypt"), logical.ErrInvalidRequest - } - - batchInputItems = make([]BatchRequestItem, 1) - batchInputItems[0] = BatchRequestItem{ - Plaintext: valueRaw.(string), - Context: d.Get("context").(string), - Nonce: d.Get("nonce").(string), - KeyVersion: d.Get("key_version").(int), - } - } - - batchResponseItems := make([]BatchResponseItem, len(batchInputItems)) - contextSet := len(batchInputItems[0].Context) != 0 - - // Before processing the batch request items, get the policy. If the - // policy is supposed to be upserted, then determine if 'derived' is to - // be set or not, based on the presence of 'context' field in all the - // input items. - for i, item := range batchInputItems { - if (len(item.Context) == 0 && contextSet) || (len(item.Context) != 0 && !contextSet) { - return logical.ErrorResponse("context should be set either in all the request blocks or in none"), logical.ErrInvalidRequest - } - - _, err := base64.StdEncoding.DecodeString(item.Plaintext) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - - // Decode the context - if len(item.Context) != 0 { - batchInputItems[i].DecodedContext, err = base64.StdEncoding.DecodeString(item.Context) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - - // Decode the nonce - if len(item.Nonce) != 0 { - batchInputItems[i].DecodedNonce, err = base64.StdEncoding.DecodeString(item.Nonce) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - } - - // Get the policy - var p *keysutil.Policy - var upserted bool - var polReq keysutil.PolicyRequest - if req.Operation == logical.CreateOperation { - convergent := d.Get("convergent_encryption").(bool) - if convergent && !contextSet { - return logical.ErrorResponse("convergent encryption requires derivation to be enabled, so context is required"), nil - } - - polReq = keysutil.PolicyRequest{ - Upsert: true, - Storage: req.Storage, - Name: name, - Derived: contextSet, - Convergent: convergent, - } - - keyType := d.Get("type").(string) - switch keyType { - case "aes256-gcm96": - polReq.KeyType = keysutil.KeyType_AES256_GCM96 - case "chacha20-poly1305": - polReq.KeyType = keysutil.KeyType_ChaCha20_Poly1305 - case "ecdsa-p256": - return logical.ErrorResponse(fmt.Sprintf("key type %v not supported for this operation", keyType)), logical.ErrInvalidRequest - default: - return logical.ErrorResponse(fmt.Sprintf("unknown key type %v", keyType)), logical.ErrInvalidRequest - } - } else { - polReq = keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - } - } - p, upserted, err = b.lm.GetPolicy(ctx, polReq) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - // Process batch request items. If encryption of any request - // item fails, respectively mark the error in the response - // collection and continue to process other items. - for i, item := range batchInputItems { - if batchResponseItems[i].Error != "" { - continue - } - - ciphertext, err := p.Encrypt(item.KeyVersion, item.DecodedContext, item.DecodedNonce, item.Plaintext) - if err != nil { - switch err.(type) { - case errutil.UserError: - batchResponseItems[i].Error = err.Error() - continue - default: - p.Unlock() - return nil, err - } - } - - if ciphertext == "" { - p.Unlock() - return nil, fmt.Errorf("empty ciphertext returned for input item %d", i) - } - - batchResponseItems[i].Ciphertext = ciphertext - } - - resp := &logical.Response{} - if batchInputRaw != nil { - resp.Data = map[string]interface{}{ - "batch_results": batchResponseItems, - } - } else { - if batchResponseItems[0].Error != "" { - p.Unlock() - return logical.ErrorResponse(batchResponseItems[0].Error), logical.ErrInvalidRequest - } - resp.Data = map[string]interface{}{ - "ciphertext": batchResponseItems[0].Ciphertext, - } - } - - if req.Operation == logical.CreateOperation && !upserted { - resp.AddWarning("Attempted creation of the key during the encrypt operation, but it was created beforehand") - } - - p.Unlock() - return resp, nil -} - -const pathEncryptHelpSyn = `Encrypt a plaintext value or a batch of plaintext -blocks using a named key` - -const pathEncryptHelpDesc = ` -This path uses the named key from the request path to encrypt a user provided -plaintext or a batch of plaintext blocks. The plaintext must be base64 encoded. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_export.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_export.go deleted file mode 100644 index 6b20fd3f0..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_export.go +++ /dev/null @@ -1,230 +0,0 @@ -package transit - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "errors" - "fmt" - "strconv" - "strings" - - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - exportTypeEncryptionKey = "encryption-key" - exportTypeSigningKey = "signing-key" - exportTypeHMACKey = "hmac-key" -) - -func (b *backend) pathExportKeys() *framework.Path { - return &framework.Path{ - Pattern: "export/" + framework.GenericNameRegex("type") + "/" + framework.GenericNameRegex("name") + framework.OptionalParamRegex("version"), - Fields: map[string]*framework.FieldSchema{ - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Type of key to export (encryption-key, signing-key, hmac-key)", - }, - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - "version": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Version of the key", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathPolicyExportRead, - }, - - HelpSynopsis: pathExportHelpSyn, - HelpDescription: pathExportHelpDesc, - } -} - -func (b *backend) pathPolicyExportRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - exportType := d.Get("type").(string) - name := d.Get("name").(string) - version := d.Get("version").(string) - - switch exportType { - case exportTypeEncryptionKey: - case exportTypeSigningKey: - case exportTypeHMACKey: - default: - return logical.ErrorResponse(fmt.Sprintf("invalid export type: %s", exportType)), logical.ErrInvalidRequest - } - - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return nil, nil - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - defer p.Unlock() - - if !p.Exportable { - return logical.ErrorResponse("key is not exportable"), nil - } - - switch exportType { - case exportTypeEncryptionKey: - if !p.Type.EncryptionSupported() { - return logical.ErrorResponse("encryption not supported for the key"), logical.ErrInvalidRequest - } - case exportTypeSigningKey: - if !p.Type.SigningSupported() { - return logical.ErrorResponse("signing not supported for the key"), logical.ErrInvalidRequest - } - } - - retKeys := map[string]string{} - switch version { - case "": - for k, v := range p.Keys { - exportKey, err := getExportKey(p, &v, exportType) - if err != nil { - return nil, err - } - retKeys[k] = exportKey - } - - default: - var versionValue int - if version == "latest" { - versionValue = p.LatestVersion - } else { - version = strings.TrimPrefix(version, "v") - versionValue, err = strconv.Atoi(version) - if err != nil { - return logical.ErrorResponse("invalid key version"), logical.ErrInvalidRequest - } - } - - if versionValue < p.MinDecryptionVersion { - return logical.ErrorResponse("version for export is below minimum decryption version"), logical.ErrInvalidRequest - } - key, ok := p.Keys[strconv.Itoa(versionValue)] - if !ok { - return logical.ErrorResponse("version does not exist or cannot be found"), logical.ErrInvalidRequest - } - - exportKey, err := getExportKey(p, &key, exportType) - if err != nil { - return nil, err - } - - retKeys[strconv.Itoa(versionValue)] = exportKey - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "name": p.Name, - "type": p.Type.String(), - "keys": retKeys, - }, - } - - return resp, nil -} - -func getExportKey(policy *keysutil.Policy, key *keysutil.KeyEntry, exportType string) (string, error) { - if policy == nil { - return "", errors.New("nil policy provided") - } - - switch exportType { - case exportTypeHMACKey: - return strings.TrimSpace(base64.StdEncoding.EncodeToString(key.HMACKey)), nil - - case exportTypeEncryptionKey: - switch policy.Type { - case keysutil.KeyType_AES256_GCM96, keysutil.KeyType_ChaCha20_Poly1305: - return strings.TrimSpace(base64.StdEncoding.EncodeToString(key.Key)), nil - - case keysutil.KeyType_RSA2048, keysutil.KeyType_RSA4096: - return encodeRSAPrivateKey(key.RSAKey), nil - } - - case exportTypeSigningKey: - switch policy.Type { - case keysutil.KeyType_ECDSA_P256: - ecKey, err := keyEntryToECPrivateKey(key, elliptic.P256()) - if err != nil { - return "", err - } - return ecKey, nil - - case keysutil.KeyType_ED25519: - return strings.TrimSpace(base64.StdEncoding.EncodeToString(key.Key)), nil - - case keysutil.KeyType_RSA2048, keysutil.KeyType_RSA4096: - return encodeRSAPrivateKey(key.RSAKey), nil - } - } - - return "", fmt.Errorf("unknown key type %v", policy.Type) -} - -func encodeRSAPrivateKey(key *rsa.PrivateKey) string { - // When encoding PKCS1, the PEM header should be `RSA PRIVATE KEY`. When Go - // has PKCS8 encoding support, we may want to change this. - derBytes := x509.MarshalPKCS1PrivateKey(key) - pemBlock := &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: derBytes, - } - pemBytes := pem.EncodeToMemory(pemBlock) - return string(pemBytes) -} - -func keyEntryToECPrivateKey(k *keysutil.KeyEntry, curve elliptic.Curve) (string, error) { - if k == nil { - return "", errors.New("nil KeyEntry provided") - } - - privKey := &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: curve, - X: k.EC_X, - Y: k.EC_Y, - }, - D: k.EC_D, - } - ecder, err := x509.MarshalECPrivateKey(privKey) - if err != nil { - return "", err - } - if ecder == nil { - return "", errors.New("no data returned when marshalling to private key") - } - - block := pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: ecder, - } - return strings.TrimSpace(string(pem.EncodeToMemory(&block))), nil -} - -const pathExportHelpSyn = `Export named encryption or signing key` - -const pathExportHelpDesc = ` -This path is used to export the named keys that are configured as -exportable. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hash.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hash.go deleted file mode 100644 index 78e9bdd59..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hash.go +++ /dev/null @@ -1,116 +0,0 @@ -package transit - -import ( - "context" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "encoding/hex" - "fmt" - "hash" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathHash() *framework.Path { - return &framework.Path{ - Pattern: "hash" + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data", - }, - - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Algorithm to use (POST body parameter). Valid values are: - -* sha2-224 -* sha2-256 -* sha2-384 -* sha2-512 - -Defaults to "sha2-256".`, - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Algorithm to use (POST URL parameter)`, - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "hex", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "hex".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathHashWrite, - }, - - HelpSynopsis: pathHashHelpSyn, - HelpDescription: pathHashHelpDesc, - } -} - -func (b *backend) pathHashWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - inputB64 := d.Get("input").(string) - format := d.Get("format").(string) - algorithm := d.Get("urlalgorithm").(string) - if algorithm == "" { - algorithm = d.Get("algorithm").(string) - } - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - var hf hash.Hash - switch algorithm { - case "sha2-224": - hf = sha256.New224() - case "sha2-256": - hf = sha256.New() - case "sha2-384": - hf = sha512.New384() - case "sha2-512": - hf = sha512.New() - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil - } - hf.Write(input) - retBytes := hf.Sum(nil) - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(retBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(retBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "sum": retStr, - }, - } - return resp, nil -} - -const pathHashHelpSyn = `Generate a hash sum for input data` - -const pathHashHelpDesc = ` -Generates a hash sum of the given algorithm against the given input data. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hmac.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hmac.go deleted file mode 100644 index 667c69660..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_hmac.go +++ /dev/null @@ -1,247 +0,0 @@ -package transit - -import ( - "context" - "crypto/hmac" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "fmt" - "hash" - "strconv" - "strings" - - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathHMAC() *framework.Path { - return &framework.Path{ - Pattern: "hmac/" + framework.GenericNameRegex("name") + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The key to use for the HMAC function", - }, - - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data", - }, - - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Algorithm to use (POST body parameter). Valid values are: - -* sha2-224 -* sha2-256 -* sha2-384 -* sha2-512 - -Defaults to "sha2-256".`, - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Algorithm to use (POST URL parameter)`, - }, - - "key_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The version of the key to use for generating the HMAC. -Must be 0 (for latest) or a value greater than or equal -to the min_encryption_version configured on the key.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathHMACWrite, - }, - - HelpSynopsis: pathHMACHelpSyn, - HelpDescription: pathHMACHelpDesc, - } -} - -func (b *backend) pathHMACWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - ver := d.Get("key_version").(int) - inputB64 := d.Get("input").(string) - algorithm := d.Get("urlalgorithm").(string) - if algorithm == "" { - algorithm = d.Get("algorithm").(string) - } - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - switch { - case ver == 0: - // Allowed, will use latest; set explicitly here to ensure the string - // is generated properly - ver = p.LatestVersion - case ver == p.LatestVersion: - // Allowed - case p.MinEncryptionVersion > 0 && ver < p.MinEncryptionVersion: - p.Unlock() - return logical.ErrorResponse("cannot generate HMAC: version is too old (disallowed by policy)"), logical.ErrInvalidRequest - } - - key, err := p.HMACKey(ver) - if err != nil { - p.Unlock() - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if key == nil { - p.Unlock() - return nil, fmt.Errorf("HMAC key value could not be computed") - } - - var hf hash.Hash - switch algorithm { - case "sha2-224": - hf = hmac.New(sha256.New224, key) - case "sha2-256": - hf = hmac.New(sha256.New, key) - case "sha2-384": - hf = hmac.New(sha512.New384, key) - case "sha2-512": - hf = hmac.New(sha512.New, key) - default: - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil - } - hf.Write(input) - retBytes := hf.Sum(nil) - - retStr := base64.StdEncoding.EncodeToString(retBytes) - retStr = fmt.Sprintf("vault:v%s:%s", strconv.Itoa(ver), retStr) - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "hmac": retStr, - }, - } - - p.Unlock() - return resp, nil -} - -func (b *backend) pathHMACVerify(ctx context.Context, req *logical.Request, d *framework.FieldData, verificationHMAC string) (*logical.Response, error) { - name := d.Get("name").(string) - inputB64 := d.Get("input").(string) - algorithm := d.Get("urlalgorithm").(string) - if algorithm == "" { - algorithm = d.Get("algorithm").(string) - } - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - // Verify the prefix - if !strings.HasPrefix(verificationHMAC, "vault:v") { - return logical.ErrorResponse("invalid HMAC to verify: no prefix"), logical.ErrInvalidRequest - } - - splitVerificationHMAC := strings.SplitN(strings.TrimPrefix(verificationHMAC, "vault:v"), ":", 2) - if len(splitVerificationHMAC) != 2 { - return logical.ErrorResponse("invalid HMAC: wrong number of fields"), logical.ErrInvalidRequest - } - - ver, err := strconv.Atoi(splitVerificationHMAC[0]) - if err != nil { - return logical.ErrorResponse("invalid HMAC: version number could not be decoded"), logical.ErrInvalidRequest - } - - verBytes, err := base64.StdEncoding.DecodeString(splitVerificationHMAC[1]) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode verification HMAC as base64: %s", err)), logical.ErrInvalidRequest - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - if ver > p.LatestVersion { - p.Unlock() - return logical.ErrorResponse("invalid HMAC: version is too new"), logical.ErrInvalidRequest - } - - if p.MinDecryptionVersion > 0 && ver < p.MinDecryptionVersion { - p.Unlock() - return logical.ErrorResponse("cannot verify HMAC: version is too old (disallowed by policy)"), logical.ErrInvalidRequest - } - - key, err := p.HMACKey(ver) - if err != nil { - p.Unlock() - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if key == nil { - p.Unlock() - return nil, fmt.Errorf("HMAC key value could not be computed") - } - - var hf hash.Hash - switch algorithm { - case "sha2-224": - hf = hmac.New(sha256.New224, key) - case "sha2-256": - hf = hmac.New(sha256.New, key) - case "sha2-384": - hf = hmac.New(sha512.New384, key) - case "sha2-512": - hf = hmac.New(sha512.New, key) - default: - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil - } - hf.Write(input) - retBytes := hf.Sum(nil) - - p.Unlock() - return &logical.Response{ - Data: map[string]interface{}{ - "valid": hmac.Equal(retBytes, verBytes), - }, - }, nil -} - -const pathHMACHelpSyn = `Generate an HMAC for input data using the named key` - -const pathHMACHelpDesc = ` -Generates an HMAC sum of the given algorithm and key against the given input data. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_keys.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_keys.go deleted file mode 100644 index 332d05bb8..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_keys.go +++ /dev/null @@ -1,346 +0,0 @@ -package transit - -import ( - "context" - "crypto/elliptic" - "crypto/x509" - "encoding/base64" - "encoding/pem" - "fmt" - "strconv" - "time" - - "golang.org/x/crypto/ed25519" - - "github.com/fatih/structs" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathListKeys() *framework.Path { - return &framework.Path{ - Pattern: "keys/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.pathKeysList, - }, - - HelpSynopsis: pathPolicyHelpSyn, - HelpDescription: pathPolicyHelpDesc, - } -} - -func (b *backend) pathKeys() *framework.Path { - return &framework.Path{ - Pattern: "keys/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "aes256-gcm96", - Description: ` -The type of key to create. Currently, "aes256-gcm96" (symmetric), "ecdsa-p256" -(asymmetric), 'ed25519' (asymmetric), 'rsa-2048' (asymmetric), 'rsa-4096' -(asymmetric) are supported. Defaults to "aes256-gcm96". -`, - }, - - "derived": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Enables key derivation mode. This -allows for per-transaction unique -keys for encryption operations.`, - }, - - "convergent_encryption": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Whether to support convergent encryption. -This is only supported when using a key with -key derivation enabled and will require all -requests to carry both a context and 96-bit -(12-byte) nonce. The given nonce will be used -in place of a randomly generated nonce. As a -result, when the same context and nonce are -supplied, the same ciphertext is generated. It -is *very important* when using this mode that -you ensure that all nonces are unique for a -given context. Failing to do so will severely -impact the ciphertext's security.`, - }, - - "exportable": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Enables keys to be exportable. -This allows for all the valid keys -in the key ring to be exported.`, - }, - - "allow_plaintext_backup": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Enables taking a backup of the named -key in plaintext format. Once set, -this cannot be disabled.`, - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Base64 encoded context for key derivation. -When reading a key with key derivation enabled, -if the key type supports public keys, this will -return the public key for the given context.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathPolicyWrite, - logical.DeleteOperation: b.pathPolicyDelete, - logical.ReadOperation: b.pathPolicyRead, - }, - - HelpSynopsis: pathPolicyHelpSyn, - HelpDescription: pathPolicyHelpDesc, - } -} - -func (b *backend) pathKeysList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := req.Storage.List(ctx, "policy/") - if err != nil { - return nil, err - } - - return logical.ListResponse(entries), nil -} - -func (b *backend) pathPolicyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - derived := d.Get("derived").(bool) - convergent := d.Get("convergent_encryption").(bool) - keyType := d.Get("type").(string) - exportable := d.Get("exportable").(bool) - allowPlaintextBackup := d.Get("allow_plaintext_backup").(bool) - - if !derived && convergent { - return logical.ErrorResponse("convergent encryption requires derivation to be enabled"), nil - } - - polReq := keysutil.PolicyRequest{ - Upsert: true, - Storage: req.Storage, - Name: name, - Derived: derived, - Convergent: convergent, - Exportable: exportable, - AllowPlaintextBackup: allowPlaintextBackup, - } - switch keyType { - case "aes256-gcm96": - polReq.KeyType = keysutil.KeyType_AES256_GCM96 - case "chacha20-poly1305": - polReq.KeyType = keysutil.KeyType_ChaCha20_Poly1305 - case "ecdsa-p256": - polReq.KeyType = keysutil.KeyType_ECDSA_P256 - case "ed25519": - polReq.KeyType = keysutil.KeyType_ED25519 - case "rsa-2048": - polReq.KeyType = keysutil.KeyType_RSA2048 - case "rsa-4096": - polReq.KeyType = keysutil.KeyType_RSA4096 - default: - return logical.ErrorResponse(fmt.Sprintf("unknown key type %v", keyType)), logical.ErrInvalidRequest - } - - p, upserted, err := b.lm.GetPolicy(ctx, polReq) - if err != nil { - return nil, err - } - if p == nil { - return nil, fmt.Errorf("error generating key: returned policy was nil") - } - if b.System().CachingDisabled() { - p.Unlock() - } - - resp := &logical.Response{} - if !upserted { - resp.AddWarning(fmt.Sprintf("key %s already existed", name)) - } - - return nil, nil -} - -// Built-in helper type for returning asymmetric keys -type asymKey struct { - Name string `json:"name" structs:"name" mapstructure:"name"` - PublicKey string `json:"public_key" structs:"public_key" mapstructure:"public_key"` - CreationTime time.Time `json:"creation_time" structs:"creation_time" mapstructure:"creation_time"` -} - -func (b *backend) pathPolicyRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return nil, nil - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - defer p.Unlock() - - // Return the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "name": p.Name, - "type": p.Type.String(), - "derived": p.Derived, - "deletion_allowed": p.DeletionAllowed, - "min_decryption_version": p.MinDecryptionVersion, - "min_encryption_version": p.MinEncryptionVersion, - "latest_version": p.LatestVersion, - "exportable": p.Exportable, - "allow_plaintext_backup": p.AllowPlaintextBackup, - "supports_encryption": p.Type.EncryptionSupported(), - "supports_decryption": p.Type.DecryptionSupported(), - "supports_signing": p.Type.SigningSupported(), - "supports_derivation": p.Type.DerivationSupported(), - }, - } - - if p.BackupInfo != nil { - resp.Data["backup_info"] = map[string]interface{}{ - "time": p.BackupInfo.Time, - "version": p.BackupInfo.Version, - } - } - if p.RestoreInfo != nil { - resp.Data["restore_info"] = map[string]interface{}{ - "time": p.RestoreInfo.Time, - "version": p.RestoreInfo.Version, - } - } - - if p.Derived { - switch p.KDF { - case keysutil.Kdf_hmac_sha256_counter: - resp.Data["kdf"] = "hmac-sha256-counter" - resp.Data["kdf_mode"] = "hmac-sha256-counter" - case keysutil.Kdf_hkdf_sha256: - resp.Data["kdf"] = "hkdf_sha256" - } - resp.Data["convergent_encryption"] = p.ConvergentEncryption - if p.ConvergentEncryption { - resp.Data["convergent_encryption_version"] = p.ConvergentVersion - } - } - - contextRaw := d.Get("context").(string) - var context []byte - if len(contextRaw) != 0 { - context, err = base64.StdEncoding.DecodeString(contextRaw) - if err != nil { - return logical.ErrorResponse("failed to base64-decode context"), logical.ErrInvalidRequest - } - } - - switch p.Type { - case keysutil.KeyType_AES256_GCM96, keysutil.KeyType_ChaCha20_Poly1305: - retKeys := map[string]int64{} - for k, v := range p.Keys { - retKeys[k] = v.DeprecatedCreationTime - } - resp.Data["keys"] = retKeys - - case keysutil.KeyType_ECDSA_P256, keysutil.KeyType_ED25519, keysutil.KeyType_RSA2048, keysutil.KeyType_RSA4096: - retKeys := map[string]map[string]interface{}{} - for k, v := range p.Keys { - key := asymKey{ - PublicKey: v.FormattedPublicKey, - CreationTime: v.CreationTime, - } - if key.CreationTime.IsZero() { - key.CreationTime = time.Unix(v.DeprecatedCreationTime, 0) - } - - switch p.Type { - case keysutil.KeyType_ECDSA_P256: - key.Name = elliptic.P256().Params().Name - case keysutil.KeyType_ED25519: - if p.Derived { - if len(context) == 0 { - key.PublicKey = "" - } else { - ver, err := strconv.Atoi(k) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("invalid version %q: {{err}}", k), err) - } - derived, err := p.DeriveKey(context, ver, 32) - if err != nil { - return nil, fmt.Errorf("failed to derive key to return public component") - } - pubKey := ed25519.PrivateKey(derived).Public().(ed25519.PublicKey) - key.PublicKey = base64.StdEncoding.EncodeToString(pubKey) - } - } - key.Name = "ed25519" - case keysutil.KeyType_RSA2048, keysutil.KeyType_RSA4096: - key.Name = "rsa-2048" - if p.Type == keysutil.KeyType_RSA4096 { - key.Name = "rsa-4096" - } - - // Encode the RSA public key in PEM format to return over the - // API - derBytes, err := x509.MarshalPKIXPublicKey(v.RSAKey.Public()) - if err != nil { - return nil, errwrap.Wrapf("error marshaling RSA public key: {{err}}", err) - } - pemBlock := &pem.Block{ - Type: "PUBLIC KEY", - Bytes: derBytes, - } - pemBytes := pem.EncodeToMemory(pemBlock) - if pemBytes == nil || len(pemBytes) == 0 { - return nil, fmt.Errorf("failed to PEM-encode RSA public key") - } - key.PublicKey = string(pemBytes) - } - - retKeys[k] = structs.New(key).Map() - } - resp.Data["keys"] = retKeys - } - - return resp, nil -} - -func (b *backend) pathPolicyDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - // Delete does its own locking - err := b.lm.DeletePolicy(ctx, req.Storage, name) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error deleting policy %s: %s", name, err)), err - } - - return nil, nil -} - -const pathPolicyHelpSyn = `Managed named encryption keys` - -const pathPolicyHelpDesc = ` -This path is used to manage the named keys that are available. -Doing a write with no value against a new named key will create -it using a randomly generated key. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_random.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_random.go deleted file mode 100644 index c5c82de50..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_random.go +++ /dev/null @@ -1,97 +0,0 @@ -package transit - -import ( - "context" - "encoding/base64" - "encoding/hex" - "fmt" - "strconv" - - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathRandom() *framework.Path { - return &framework.Path{ - Pattern: "random" + framework.OptionalParamRegex("urlbytes"), - Fields: map[string]*framework.FieldSchema{ - "urlbytes": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The number of bytes to generate (POST URL parameter)", - }, - - "bytes": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 32, - Description: "The number of bytes to generate (POST body parameter). Defaults to 32 (256 bits).", - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "base64", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "base64".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRandomWrite, - }, - - HelpSynopsis: pathRandomHelpSyn, - HelpDescription: pathRandomHelpDesc, - } -} - -func (b *backend) pathRandomWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - bytes := 0 - var err error - strBytes := d.Get("urlbytes").(string) - if strBytes != "" { - bytes, err = strconv.Atoi(strBytes) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error parsing url-set byte count: %s", err)), nil - } - } else { - bytes = d.Get("bytes").(int) - } - format := d.Get("format").(string) - - if bytes < 1 { - return logical.ErrorResponse(`"bytes" cannot be less than 1`), nil - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - randBytes, err := uuid.GenerateRandomBytes(bytes) - if err != nil { - return nil, err - } - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(randBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(randBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "random_bytes": retStr, - }, - } - return resp, nil -} - -const pathRandomHelpSyn = `Generate random bytes` - -const pathRandomHelpDesc = ` -This function can be used to generate high-entropy random bytes. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_restore.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_restore.go deleted file mode 100644 index e1a58d7da..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_restore.go +++ /dev/null @@ -1,43 +0,0 @@ -package transit - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathRestore() *framework.Path { - return &framework.Path{ - Pattern: "restore" + framework.OptionalParamRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "backup": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Backed up key data to be restored. This should be the output from the 'backup/' endpoint.", - }, - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "If set, this will be the name of the restored key.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRestoreUpdate, - }, - - HelpSynopsis: pathRestoreHelpSyn, - HelpDescription: pathRestoreHelpDesc, - } -} - -func (b *backend) pathRestoreUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - backupB64 := d.Get("backup").(string) - if backupB64 == "" { - return logical.ErrorResponse("'backup' must be supplied"), nil - } - - return nil, b.lm.RestorePolicy(ctx, req.Storage, d.Get("name").(string), backupB64) -} - -const pathRestoreHelpSyn = `Restore the named key` -const pathRestoreHelpDesc = `This path is used to restore the named key.` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rewrap.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rewrap.go deleted file mode 100644 index a752454c3..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rewrap.go +++ /dev/null @@ -1,198 +0,0 @@ -package transit - -import ( - "context" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -func (b *backend) pathRewrap() *framework.Path { - return &framework.Path{ - Pattern: "rewrap/" + framework.GenericNameRegex("name"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - - "ciphertext": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Ciphertext value to rewrap", - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Base64 encoded context for key derivation. Required for derived keys.", - }, - - "nonce": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Nonce for when convergent encryption is used", - }, - - "key_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The version of the key to use for encryption. -Must be 0 (for latest) or a value greater than or equal -to the min_encryption_version configured on the key.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRewrapWrite, - }, - - HelpSynopsis: pathRewrapHelpSyn, - HelpDescription: pathRewrapHelpDesc, - } -} - -func (b *backend) pathRewrapWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - batchInputRaw := d.Raw["batch_input"] - var batchInputItems []BatchRequestItem - var err error - if batchInputRaw != nil { - err = mapstructure.Decode(batchInputRaw, &batchInputItems) - if err != nil { - return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err) - } - - if len(batchInputItems) == 0 { - return logical.ErrorResponse("missing batch input to process"), logical.ErrInvalidRequest - } - } else { - ciphertext := d.Get("ciphertext").(string) - if len(ciphertext) == 0 { - return logical.ErrorResponse("missing ciphertext to decrypt"), logical.ErrInvalidRequest - } - - batchInputItems = make([]BatchRequestItem, 1) - batchInputItems[0] = BatchRequestItem{ - Ciphertext: ciphertext, - Context: d.Get("context").(string), - Nonce: d.Get("nonce").(string), - KeyVersion: d.Get("key_version").(int), - } - } - - batchResponseItems := make([]BatchResponseItem, len(batchInputItems)) - contextSet := len(batchInputItems[0].Context) != 0 - - for i, item := range batchInputItems { - if (len(item.Context) == 0 && contextSet) || (len(item.Context) != 0 && !contextSet) { - return logical.ErrorResponse("context should be set either in all the request blocks or in none"), logical.ErrInvalidRequest - } - - if item.Ciphertext == "" { - batchResponseItems[i].Error = "missing ciphertext to decrypt" - continue - } - - // Decode the context - if len(item.Context) != 0 { - batchInputItems[i].DecodedContext, err = base64.StdEncoding.DecodeString(item.Context) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - - // Decode the nonce - if len(item.Nonce) != 0 { - batchInputItems[i].DecodedNonce, err = base64.StdEncoding.DecodeString(item.Nonce) - if err != nil { - batchResponseItems[i].Error = err.Error() - continue - } - } - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: d.Get("name").(string), - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - for i, item := range batchInputItems { - if batchResponseItems[i].Error != "" { - continue - } - - plaintext, err := p.Decrypt(item.DecodedContext, item.DecodedNonce, item.Ciphertext) - if err != nil { - switch err.(type) { - case errutil.UserError: - batchResponseItems[i].Error = err.Error() - continue - default: - p.Unlock() - return nil, err - } - } - - ciphertext, err := p.Encrypt(item.KeyVersion, item.DecodedContext, item.DecodedNonce, plaintext) - if err != nil { - switch err.(type) { - case errutil.UserError: - batchResponseItems[i].Error = err.Error() - continue - case errutil.InternalError: - p.Unlock() - return nil, err - default: - p.Unlock() - return nil, err - } - } - - if ciphertext == "" { - p.Unlock() - return nil, fmt.Errorf("empty ciphertext returned for input item %d", i) - } - - batchResponseItems[i].Ciphertext = ciphertext - } - - resp := &logical.Response{} - if batchInputRaw != nil { - resp.Data = map[string]interface{}{ - "batch_results": batchResponseItems, - } - } else { - if batchResponseItems[0].Error != "" { - p.Unlock() - return logical.ErrorResponse(batchResponseItems[0].Error), logical.ErrInvalidRequest - } - resp.Data = map[string]interface{}{ - "ciphertext": batchResponseItems[0].Ciphertext, - } - } - - p.Unlock() - return resp, nil -} - -const pathRewrapHelpSyn = `Rewrap ciphertext` - -const pathRewrapHelpDesc = ` -After key rotation, this function can be used to rewrap the given ciphertext or -a batch of given ciphertext blocks with the latest version of the named key. -If the given ciphertext is already using the latest version of the key, this -function is a no-op. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rotate.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rotate.go deleted file mode 100644 index 90b8d9e47..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_rotate.go +++ /dev/null @@ -1,61 +0,0 @@ -package transit - -import ( - "context" - - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathRotate() *framework.Path { - return &framework.Path{ - Pattern: "keys/" + framework.GenericNameRegex("name") + "/rotate", - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the key", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRotateWrite, - }, - - HelpSynopsis: pathRotateHelpSyn, - HelpDescription: pathRotateHelpDesc, - } -} - -func (b *backend) pathRotateWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(true) - } - - // Rotate the policy - err = p.Rotate(ctx, req.Storage) - - p.Unlock() - return nil, err -} - -const pathRotateHelpSyn = `Rotate named encryption key` - -const pathRotateHelpDesc = ` -This path is used to rotate the named key. After rotation, -new encryption requests using this name will use the new key, -but decryption will still be supported for older versions. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_sign_verify.go b/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_sign_verify.go deleted file mode 100644 index 10c99474c..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/logical/transit/path_sign_verify.go +++ /dev/null @@ -1,371 +0,0 @@ -package transit - -import ( - "context" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "fmt" - "hash" - - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/keysutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func (b *backend) pathSign() *framework.Path { - return &framework.Path{ - Pattern: "sign/" + framework.GenericNameRegex("name") + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The key to use", - }, - - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data", - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Base64 encoded context for key derivation. Required if key -derivation is enabled; currently only available with ed25519 keys.`, - }, - - "hash_algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Hash algorithm to use (POST body parameter). Valid values are: - -* sha2-224 -* sha2-256 -* sha2-384 -* sha2-512 - -Defaults to "sha2-256". Not valid for all key types, -including ed25519.`, - }, - - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Deprecated: use "hash_algorithm" instead.`, - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Hash algorithm to use (POST URL parameter)`, - }, - - "key_version": &framework.FieldSchema{ - Type: framework.TypeInt, - Description: `The version of the key to use for signing. -Must be 0 (for latest) or a value greater than or equal -to the min_encryption_version configured on the key.`, - }, - - "prehashed": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Set to 'true' when the input is already hashed. If the key type is 'rsa-2048' or 'rsa-4096', then the algorithm used to hash the input should be indicated by the 'algorithm' parameter.`, - }, - "signature_algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The signature algorithm to use for signing. Currently only applies to RSA key types. -Options are 'pss' or 'pkcs1v15'. Defaults to 'pss'`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathSignWrite, - }, - - HelpSynopsis: pathSignHelpSyn, - HelpDescription: pathSignHelpDesc, - } -} - -func (b *backend) pathVerify() *framework.Path { - return &framework.Path{ - Pattern: "verify/" + framework.GenericNameRegex("name") + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The key to use", - }, - - "context": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Base64 encoded context for key derivation. Required if key -derivation is enabled; currently only available with ed25519 keys.`, - }, - - "signature": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The signature, including vault header/key version", - }, - - "hmac": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The HMAC, including vault header/key version", - }, - - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data to verify", - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Hash algorithm to use (POST URL parameter)`, - }, - - "hash_algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Hash algorithm to use (POST body parameter). Valid values are: - -* sha2-224 -* sha2-256 -* sha2-384 -* sha2-512 - -Defaults to "sha2-256". Not valid for all key types.`, - }, - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Deprecated: use "hash_algorithm" instead.`, - }, - - "prehashed": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: `Set to 'true' when the input is already hashed. If the key type is 'rsa-2048' or 'rsa-4096', then the algorithm used to hash the input should be indicated by the 'algorithm' parameter.`, - }, - "signature_algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `The signature algorithm to use for signature verification. Currently only applies to RSA key types. -Options are 'pss' or 'pkcs1v15'. Defaults to 'pss'`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathVerifyWrite, - }, - - HelpSynopsis: pathVerifyHelpSyn, - HelpDescription: pathVerifyHelpDesc, - } -} - -func (b *backend) pathSignWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("name").(string) - ver := d.Get("key_version").(int) - inputB64 := d.Get("input").(string) - hashAlgorithm := d.Get("urlalgorithm").(string) - if hashAlgorithm == "" { - hashAlgorithm = d.Get("hash_algorithm").(string) - if hashAlgorithm == "" { - hashAlgorithm = d.Get("algorithm").(string) - } - } - prehashed := d.Get("prehashed").(bool) - sigAlgorithm := d.Get("signature_algorithm").(string) - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - if !p.Type.SigningSupported() { - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("key type %v does not support signing", p.Type)), logical.ErrInvalidRequest - } - - contextRaw := d.Get("context").(string) - var context []byte - if len(contextRaw) != 0 { - context, err = base64.StdEncoding.DecodeString(contextRaw) - if err != nil { - p.Unlock() - return logical.ErrorResponse("failed to base64-decode context"), logical.ErrInvalidRequest - } - } - - if p.Type.HashSignatureInput() && !prehashed { - var hf hash.Hash - switch hashAlgorithm { - case "sha2-224": - hf = sha256.New224() - case "sha2-256": - hf = sha256.New() - case "sha2-384": - hf = sha512.New384() - case "sha2-512": - hf = sha512.New() - default: - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("unsupported hash algorithm %s", hashAlgorithm)), nil - } - hf.Write(input) - input = hf.Sum(nil) - } - - sig, err := p.Sign(ver, context, input, hashAlgorithm, sigAlgorithm) - if err != nil { - p.Unlock() - return nil, err - } - if sig == nil { - p.Unlock() - return nil, fmt.Errorf("signature could not be computed") - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "signature": sig.Signature, - }, - } - - if len(sig.PublicKey) > 0 { - resp.Data["public_key"] = sig.PublicKey - } - - p.Unlock() - return resp, nil -} - -func (b *backend) pathVerifyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - - sig := d.Get("signature").(string) - hmac := d.Get("hmac").(string) - switch { - case sig != "" && hmac != "": - return logical.ErrorResponse("provide one of 'signature' or 'hmac'"), logical.ErrInvalidRequest - - case sig == "" && hmac == "": - return logical.ErrorResponse("neither a 'signature' nor an 'hmac' were given to verify"), logical.ErrInvalidRequest - - case hmac != "": - return b.pathHMACVerify(ctx, req, d, hmac) - } - - name := d.Get("name").(string) - inputB64 := d.Get("input").(string) - hashAlgorithm := d.Get("urlalgorithm").(string) - if hashAlgorithm == "" { - hashAlgorithm = d.Get("hash_algorithm").(string) - if hashAlgorithm == "" { - hashAlgorithm = d.Get("algorithm").(string) - } - } - prehashed := d.Get("prehashed").(bool) - sigAlgorithm := d.Get("signature_algorithm").(string) - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - // Get the policy - p, _, err := b.lm.GetPolicy(ctx, keysutil.PolicyRequest{ - Storage: req.Storage, - Name: name, - }) - if err != nil { - return nil, err - } - if p == nil { - return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest - } - if !b.System().CachingDisabled() { - p.Lock(false) - } - - if !p.Type.SigningSupported() { - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("key type %v does not support verification", p.Type)), logical.ErrInvalidRequest - } - - contextRaw := d.Get("context").(string) - var context []byte - if len(contextRaw) != 0 { - context, err = base64.StdEncoding.DecodeString(contextRaw) - if err != nil { - p.Unlock() - return logical.ErrorResponse("failed to base64-decode context"), logical.ErrInvalidRequest - } - } - - if p.Type.HashSignatureInput() && !prehashed { - var hf hash.Hash - switch hashAlgorithm { - case "sha2-224": - hf = sha256.New224() - case "sha2-256": - hf = sha256.New() - case "sha2-384": - hf = sha512.New384() - case "sha2-512": - hf = sha512.New() - default: - p.Unlock() - return logical.ErrorResponse(fmt.Sprintf("unsupported hash algorithm %s", hashAlgorithm)), nil - } - hf.Write(input) - input = hf.Sum(nil) - } - - valid, err := p.VerifySignature(context, input, sig, hashAlgorithm, sigAlgorithm) - if err != nil { - switch err.(type) { - case errutil.UserError: - p.Unlock() - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - case errutil.InternalError: - p.Unlock() - return nil, err - default: - p.Unlock() - return nil, err - } - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "valid": valid, - }, - } - - p.Unlock() - return resp, nil -} - -const pathSignHelpSyn = `Generate a signature for input data using the named key` - -const pathSignHelpDesc = ` -Generates a signature of the input data using the named key and the given hash algorithm. -` -const pathVerifyHelpSyn = `Verify a signature or HMAC for input data created using the named key` - -const pathVerifyHelpDesc = ` -Verifies a signature or HMAC of the input data using the named key and the given hash algorithm. -` diff --git a/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go b/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go deleted file mode 100644 index c448bb89f..000000000 --- a/vendor/github.com/hashicorp/vault/builtin/plugin/backend.go +++ /dev/null @@ -1,229 +0,0 @@ -package plugin - -import ( - "context" - "fmt" - "net/rpc" - "reflect" - "sync" - - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - bplugin "github.com/hashicorp/vault/logical/plugin" -) - -var ( - ErrMismatchType = fmt.Errorf("mismatch on mounted backend and plugin backend type") - ErrMismatchPaths = fmt.Errorf("mismatch on mounted backend and plugin backend special paths") -) - -// Factory returns a configured plugin logical.Backend. -func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - _, ok := conf.Config["plugin_name"] - if !ok { - return nil, fmt.Errorf("plugin_name not provided") - } - b, err := Backend(ctx, conf) - if err != nil { - return nil, err - } - - if err := b.Setup(ctx, conf); err != nil { - return nil, err - } - return b, nil -} - -// Backend returns an instance of the backend, either as a plugin if external -// or as a concrete implementation if builtin, casted as logical.Backend. -func Backend(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - var b backend - - name := conf.Config["plugin_name"] - sys := conf.System - - // NewBackend with isMetadataMode set to true - raw, err := bplugin.NewBackend(ctx, name, sys, conf.Logger, true) - if err != nil { - return nil, err - } - err = raw.Setup(ctx, conf) - if err != nil { - return nil, err - } - // Get SpecialPaths and BackendType - paths := raw.SpecialPaths() - btype := raw.Type() - - // Cleanup meta plugin backend - raw.Cleanup(ctx) - - // Initialize b.Backend with dummy backend since plugin - // backends will need to be lazy loaded. - b.Backend = &framework.Backend{ - PathsSpecial: paths, - BackendType: btype, - } - - b.config = conf - - return &b, nil -} - -// backend is a thin wrapper around plugin.BackendPluginClient -type backend struct { - logical.Backend - sync.RWMutex - - config *logical.BackendConfig - - // Used to detect if we already reloaded - canary string - - // Used to detect if plugin is set - loaded bool -} - -func (b *backend) reloadBackend(ctx context.Context) error { - b.Logger().Debug("reloading plugin backend", "plugin", b.config.Config["plugin_name"]) - return b.startBackend(ctx) -} - -// startBackend starts a plugin backend -func (b *backend) startBackend(ctx context.Context) error { - pluginName := b.config.Config["plugin_name"] - - // Ensure proper cleanup of the backend (i.e. call client.Kill()) - b.Backend.Cleanup(ctx) - - nb, err := bplugin.NewBackend(ctx, pluginName, b.config.System, b.config.Logger, false) - if err != nil { - return err - } - err = nb.Setup(ctx, b.config) - if err != nil { - return err - } - - // If the backend has not been loaded (i.e. still in metadata mode), - // check if type and special paths still matches - if !b.loaded { - if b.Backend.Type() != nb.Type() { - nb.Cleanup(ctx) - b.Logger().Warn("failed to start plugin process", "plugin", b.config.Config["plugin_name"], "error", ErrMismatchType) - return ErrMismatchType - } - if !reflect.DeepEqual(b.Backend.SpecialPaths(), nb.SpecialPaths()) { - nb.Cleanup(ctx) - b.Logger().Warn("failed to start plugin process", "plugin", b.config.Config["plugin_name"], "error", ErrMismatchPaths) - return ErrMismatchPaths - } - } - - b.Backend = nb - b.loaded = true - - return nil -} - -// HandleRequest is a thin wrapper implementation of HandleRequest that includes automatic plugin reload. -func (b *backend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - b.RLock() - canary := b.canary - - // Lazy-load backend - if !b.loaded { - // Upgrade lock - b.RUnlock() - b.Lock() - // Check once more after lock swap - if !b.loaded { - err := b.startBackend(ctx) - if err != nil { - b.Unlock() - return nil, err - } - } - b.Unlock() - b.RLock() - } - resp, err := b.Backend.HandleRequest(ctx, req) - b.RUnlock() - // Need to compare string value for case were err comes from plugin RPC - // and is returned as plugin.BasicError type. - if err != nil && - (err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) { - // Reload plugin if it's an rpc.ErrShutdown - b.Lock() - if b.canary == canary { - err := b.reloadBackend(ctx) - if err != nil { - b.Unlock() - return nil, err - } - b.canary, err = uuid.GenerateUUID() - if err != nil { - b.Unlock() - return nil, err - } - } - b.Unlock() - - // Try request once more - b.RLock() - defer b.RUnlock() - return b.Backend.HandleRequest(ctx, req) - } - return resp, err -} - -// HandleExistenceCheck is a thin wrapper implementation of HandleRequest that includes automatic plugin reload. -func (b *backend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - b.RLock() - canary := b.canary - - // Lazy-load backend - if !b.loaded { - // Upgrade lock - b.RUnlock() - b.Lock() - // Check once more after lock swap - if !b.loaded { - err := b.startBackend(ctx) - if err != nil { - b.Unlock() - return false, false, err - } - } - b.Unlock() - b.RLock() - } - - checkFound, exists, err := b.Backend.HandleExistenceCheck(ctx, req) - b.RUnlock() - if err != nil && - (err.Error() == rpc.ErrShutdown.Error() || err == bplugin.ErrPluginShutdown) { - // Reload plugin if it's an rpc.ErrShutdown - b.Lock() - if b.canary == canary { - err := b.reloadBackend(ctx) - if err != nil { - b.Unlock() - return false, false, err - } - b.canary, err = uuid.GenerateUUID() - if err != nil { - b.Unlock() - return false, false, err - } - } - b.Unlock() - - // Try request once more - b.RLock() - defer b.RUnlock() - return b.Backend.HandleExistenceCheck(ctx, req) - } - return checkFound, exists, err -} diff --git a/vendor/github.com/hashicorp/vault/command/agent.go b/vendor/github.com/hashicorp/vault/command/agent.go deleted file mode 100644 index b9f49c79a..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent.go +++ /dev/null @@ -1,393 +0,0 @@ -package command - -import ( - "context" - "fmt" - "io" - "os" - "sort" - "strings" - "sync" - - "github.com/kr/pretty" - "github.com/mitchellh/cli" - "github.com/posener/complete" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/command/agent/auth" - "github.com/hashicorp/vault/command/agent/auth/alicloud" - "github.com/hashicorp/vault/command/agent/auth/aws" - "github.com/hashicorp/vault/command/agent/auth/azure" - "github.com/hashicorp/vault/command/agent/auth/gcp" - "github.com/hashicorp/vault/command/agent/auth/jwt" - "github.com/hashicorp/vault/command/agent/auth/kubernetes" - "github.com/hashicorp/vault/command/agent/config" - "github.com/hashicorp/vault/command/agent/sink" - "github.com/hashicorp/vault/command/agent/sink/file" - "github.com/hashicorp/vault/helper/gated-writer" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/version" -) - -var _ cli.Command = (*AgentCommand)(nil) -var _ cli.CommandAutocomplete = (*AgentCommand)(nil) - -type AgentCommand struct { - *BaseCommand - - ShutdownCh chan struct{} - SighupCh chan struct{} - - logWriter io.Writer - logGate *gatedwriter.Writer - logger log.Logger - - cleanupGuard sync.Once - - startedCh chan (struct{}) // for tests - - flagConfigs []string - flagLogLevel string - - flagTestVerifyOnly bool - flagCombineLogs bool -} - -func (c *AgentCommand) Synopsis() string { - return "Start a Vault agent" -} - -func (c *AgentCommand) Help() string { - helpText := ` -Usage: vault agent [options] - - This command starts a Vault agent that can perform automatic authentication - in certain environments. - - Start an agent with a configuration file: - - $ vault agent -config=/etc/vault/config.hcl - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *AgentCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "config", - Target: &c.flagConfigs, - Completion: complete.PredictOr( - complete.PredictFiles("*.hcl"), - complete.PredictFiles("*.json"), - ), - Usage: "Path to a configuration file. This configuration file should " + - "contain only agent directives.", - }) - - f.StringVar(&StringVar{ - Name: "log-level", - Target: &c.flagLogLevel, - Default: "info", - EnvVar: "VAULT_LOG_LEVEL", - Completion: complete.PredictSet("trace", "debug", "info", "warn", "err"), - Usage: "Log verbosity level. Supported values (in order of detail) are " + - "\"trace\", \"debug\", \"info\", \"warn\", and \"err\".", - }) - - // Internal-only flags to follow. - // - // Why hello there little source code reader! Welcome to the Vault source - // code. The remaining options are intentionally undocumented and come with - // no warranty or backwards-compatability promise. Do not use these flags - // in production. Do not build automation using these flags. Unless you are - // developing against Vault, you should not need any of these flags. - - // TODO: should the below flags be public? - f.BoolVar(&BoolVar{ - Name: "combine-logs", - Target: &c.flagCombineLogs, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "test-verify-only", - Target: &c.flagTestVerifyOnly, - Default: false, - Hidden: true, - }) - - // End internal-only flags. - - return set -} - -func (c *AgentCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictNothing -} - -func (c *AgentCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AgentCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Create a logger. We wrap it in a gated writer so that it doesn't - // start logging too early. - c.logGate = &gatedwriter.Writer{Writer: os.Stderr} - c.logWriter = c.logGate - if c.flagCombineLogs { - c.logWriter = os.Stdout - } - var level log.Level - c.flagLogLevel = strings.ToLower(strings.TrimSpace(c.flagLogLevel)) - switch c.flagLogLevel { - case "trace": - level = log.Trace - case "debug": - level = log.Debug - case "notice", "info", "": - level = log.Info - case "warn", "warning": - level = log.Warn - case "err", "error": - level = log.Error - default: - c.UI.Error(fmt.Sprintf("Unknown log level: %s", c.flagLogLevel)) - return 1 - } - - if c.logger == nil { - c.logger = logging.NewVaultLoggerWithWriter(c.logWriter, level) - } - - // Validation - if len(c.flagConfigs) != 1 { - c.UI.Error("Must specify exactly one config path using -config") - return 1 - } - - // Load the configuration - config, err := config.LoadConfig(c.flagConfigs[0], c.logger) - if err != nil { - c.UI.Error(fmt.Sprintf("Error loading configuration from %s: %s", c.flagConfigs[0], err)) - return 1 - } - - // Ensure at least one config was found. - if config == nil { - c.UI.Output(wrapAtLength( - "No configuration read. Please provide the configuration with the " + - "-config flag.")) - return 1 - } - if config.AutoAuth == nil { - c.UI.Error("No auto_auth block found in config file") - return 1 - } - - infoKeys := make([]string, 0, 10) - info := make(map[string]string) - info["log level"] = c.flagLogLevel - infoKeys = append(infoKeys, "log level") - - infoKeys = append(infoKeys, "version") - verInfo := version.GetVersion() - info["version"] = verInfo.FullVersionNumber(false) - if verInfo.Revision != "" { - info["version sha"] = strings.Trim(verInfo.Revision, "'") - infoKeys = append(infoKeys, "version sha") - } - infoKeys = append(infoKeys, "cgo") - info["cgo"] = "disabled" - if version.CgoEnabled { - info["cgo"] = "enabled" - } - - // Server configuration output - padding := 24 - sort.Strings(infoKeys) - c.UI.Output("==> Vault agent configuration:\n") - for _, k := range infoKeys { - c.UI.Output(fmt.Sprintf( - "%s%s: %s", - strings.Repeat(" ", padding-len(k)), - strings.Title(k), - info[k])) - } - c.UI.Output("") - - // Tests might not want to start a vault server and just want to verify - // the configuration. - if c.flagTestVerifyOnly { - if os.Getenv("VAULT_TEST_VERIFY_ONLY_DUMP_CONFIG") != "" { - c.UI.Output(fmt.Sprintf( - "\nConfiguration:\n%s\n", - pretty.Sprint(*config))) - } - return 0 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(fmt.Sprintf( - "Error fetching client: %v", - err)) - return 1 - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - - var sinks []*sink.SinkConfig - for _, sc := range config.AutoAuth.Sinks { - switch sc.Type { - case "file": - config := &sink.SinkConfig{ - Logger: c.logger.Named("sink.file"), - Config: sc.Config, - Client: client, - WrapTTL: sc.WrapTTL, - DHType: sc.DHType, - DHPath: sc.DHPath, - AAD: sc.AAD, - } - s, err := file.NewFileSink(config) - if err != nil { - c.UI.Error(errwrap.Wrapf("Error creating file sink: {{err}}", err).Error()) - return 1 - } - config.Sink = s - sinks = append(sinks, config) - default: - c.UI.Error(fmt.Sprintf("Unknown sink type %q", sc.Type)) - return 1 - } - } - - var method auth.AuthMethod - authConfig := &auth.AuthConfig{ - Logger: c.logger.Named(fmt.Sprintf("auth.%s", config.AutoAuth.Method.Type)), - MountPath: config.AutoAuth.Method.MountPath, - WrapTTL: config.AutoAuth.Method.WrapTTL, - Config: config.AutoAuth.Method.Config, - } - switch config.AutoAuth.Method.Type { - case "alicloud": - method, err = alicloud.NewAliCloudAuthMethod(authConfig) - case "aws": - method, err = aws.NewAWSAuthMethod(authConfig) - case "azure": - method, err = azure.NewAzureAuthMethod(authConfig) - case "gcp": - method, err = gcp.NewGCPAuthMethod(authConfig) - case "jwt": - method, err = jwt.NewJWTAuthMethod(authConfig) - case "kubernetes": - method, err = kubernetes.NewKubernetesAuthMethod(authConfig) - default: - c.UI.Error(fmt.Sprintf("Unknown auth method %q", config.AutoAuth.Method.Type)) - return 1 - } - if err != nil { - c.UI.Error(errwrap.Wrapf(fmt.Sprintf("Error creating %s auth method: {{err}}", config.AutoAuth.Method.Type), err).Error()) - return 1 - } - - // Output the header that the server has started - if !c.flagCombineLogs { - c.UI.Output("==> Vault server started! Log data will stream in below:\n") - } - - // Inform any tests that the server is ready - select { - case c.startedCh <- struct{}{}: - default: - } - - ss := sink.NewSinkServer(&sink.SinkServerConfig{ - Logger: c.logger.Named("sink.server"), - Client: client, - ExitAfterAuth: config.ExitAfterAuth, - }) - - ah := auth.NewAuthHandler(&auth.AuthHandlerConfig{ - Logger: c.logger.Named("auth.handler"), - Client: c.client, - }) - - // Start things running - go ah.Run(ctx, method) - go ss.Run(ctx, ah.OutputCh, sinks) - - // Release the log gate. - c.logGate.Flush() - - // Write out the PID to the file now that server has successfully started - if err := c.storePidFile(config.PidFile); err != nil { - c.UI.Error(fmt.Sprintf("Error storing PID: %s", err)) - return 1 - } - - defer func() { - if err := c.removePidFile(config.PidFile); err != nil { - c.UI.Error(fmt.Sprintf("Error deleting the PID file: %s", err)) - } - }() - - select { - case <-ss.DoneCh: - // This will happen if we exit-on-auth - c.logger.Info("sinks finished, exiting") - case <-c.ShutdownCh: - c.UI.Output("==> Vault agent shutdown triggered") - cancelFunc() - <-ah.DoneCh - <-ss.DoneCh - } - - return 0 -} - -// storePidFile is used to write out our PID to a file if necessary -func (c *AgentCommand) storePidFile(pidPath string) error { - // Quit fast if no pidfile - if pidPath == "" { - return nil - } - - // Open the PID file - pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) - if err != nil { - return errwrap.Wrapf("could not open pid file: {{err}}", err) - } - defer pidFile.Close() - - // Write out the PID - pid := os.Getpid() - _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) - if err != nil { - return errwrap.Wrapf("could not write to pid file: {{err}}", err) - } - return nil -} - -// removePidFile is used to cleanup the PID file if necessary -func (c *AgentCommand) removePidFile(pidPath string) error { - if pidPath == "" { - return nil - } - return os.Remove(pidPath) -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/alicloud/alicloud.go b/vendor/github.com/hashicorp/vault/command/agent/auth/alicloud/alicloud.go deleted file mode 100644 index a41e3ff2b..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/alicloud/alicloud.go +++ /dev/null @@ -1,233 +0,0 @@ -package alicloud - -import ( - "context" - "errors" - "fmt" - "reflect" - "sync" - "time" - - aliCloudAuth "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/providers" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault-plugin-auth-alicloud/tools" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/agent/auth" -) - -/* - - Creds can be inferred from instance metadata, and those creds - expire every 60 minutes, so we're going to need to poll for new - creds. Since we're polling anyways, let's poll once a minute so - all changes can be picked up rather quickly. This is configurable, - however. - -*/ -const defaultCredCheckFreqSeconds = 60 - -func NewAliCloudAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - a := &alicloudMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - credsFound: make(chan struct{}), - stopCh: make(chan struct{}), - } - - // Build the required information we'll need to create a client. - if roleRaw, ok := conf.Config["role"]; !ok { - return nil, errors.New("'role' is required but is not provided") - } else { - if a.role, ok = roleRaw.(string); !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - } - if regionRaw, ok := conf.Config["region"]; !ok { - return nil, errors.New("'region' is required but is not provided") - } else { - if a.region, ok = regionRaw.(string); !ok { - return nil, errors.New("could not convert 'region' config value to string") - } - } - - // Check for an optional custom frequency at which we should poll for creds. - credCheckFreqSec := defaultCredCheckFreqSeconds - if checkFreqRaw, ok := conf.Config["cred_check_freq_seconds"]; ok { - if credFreq, ok := checkFreqRaw.(int); ok { - credCheckFreqSec = credFreq - } - } - - // Build the optional, configuration-based piece of the credential chain. - credConfig := &providers.Configuration{} - - if accessKeyRaw, ok := conf.Config["access_key"]; ok { - if credConfig.AccessKeyID, ok = accessKeyRaw.(string); !ok { - return nil, errors.New("could not convert 'access_key' config value to string") - } - } - - if accessSecretRaw, ok := conf.Config["access_secret"]; ok { - if credConfig.AccessKeySecret, ok = accessSecretRaw.(string); !ok { - return nil, errors.New("could not convert 'access_secret' config value to string") - } - } - - if accessTokenRaw, ok := conf.Config["access_token"]; ok { - if credConfig.AccessKeyStsToken, ok = accessTokenRaw.(string); !ok { - return nil, errors.New("could not convert 'access_token' config value to string") - } - } - - if roleArnRaw, ok := conf.Config["role_arn"]; ok { - if credConfig.RoleArn, ok = roleArnRaw.(string); !ok { - return nil, errors.New("could not convert 'role_arn' config value to string") - } - } - - if roleSessionNameRaw, ok := conf.Config["role_session_name"]; ok { - if credConfig.RoleSessionName, ok = roleSessionNameRaw.(string); !ok { - return nil, errors.New("could not convert 'role_session_name' config value to string") - } - } - - if roleSessionExpirationRaw, ok := conf.Config["role_session_expiration"]; ok { - if roleSessionExpiration, ok := roleSessionExpirationRaw.(int); !ok { - return nil, errors.New("could not convert 'role_session_expiration' config value to int") - } else { - credConfig.RoleSessionExpiration = &roleSessionExpiration - } - } - - if privateKeyRaw, ok := conf.Config["private_key"]; ok { - if credConfig.PrivateKey, ok = privateKeyRaw.(string); !ok { - return nil, errors.New("could not convert 'private_key' config value to string") - } - } - - if publicKeyIdRaw, ok := conf.Config["public_key_id"]; ok { - if credConfig.PublicKeyID, ok = publicKeyIdRaw.(string); !ok { - return nil, errors.New("could not convert 'public_key_id' config value to string") - } - } - - if sessionExpirationRaw, ok := conf.Config["session_expiration"]; ok { - if sessionExpiration, ok := sessionExpirationRaw.(int); !ok { - return nil, errors.New("could not convert 'session_expiration' config value to int") - } else { - credConfig.SessionExpiration = &sessionExpiration - } - } - - if roleNameRaw, ok := conf.Config["role_name"]; ok { - if credConfig.RoleName, ok = roleNameRaw.(string); !ok { - return nil, errors.New("could not convert 'role_name' config value to string") - } - } - - credentialChain := []providers.Provider{ - providers.NewEnvCredentialProvider(), - providers.NewConfigurationCredentialProvider(credConfig), - providers.NewInstanceMetadataProvider(), - } - credProvider := providers.NewChainProvider(credentialChain) - - // Do an initial population of the creds because we want to err right away if we can't - // even get a first set. - lastCreds, err := credProvider.Retrieve() - if err != nil { - return nil, err - } - a.lastCreds = lastCreds - - go a.pollForCreds(credProvider, credCheckFreqSec) - - return a, nil -} - -type alicloudMethod struct { - logger hclog.Logger - mountPath string - - // These parameters are fed into building login data. - role string - region string - - // These are used to share the latest creds safely across goroutines. - credLock sync.Mutex - lastCreds aliCloudAuth.Credential - - // Notifies the outer environment that it should call Authenticate again. - credsFound chan struct{} - - // Detects that the outer environment is closing. - stopCh chan struct{} -} - -func (a *alicloudMethod) Authenticate(context.Context, *api.Client) (string, map[string]interface{}, error) { - a.credLock.Lock() - defer a.credLock.Unlock() - - a.logger.Trace("beginning authentication") - data, err := tools.GenerateLoginData(a.role, a.lastCreds, a.region) - if err != nil { - return "", nil, err - } - return fmt.Sprintf("%s/login", a.mountPath), data, nil -} - -func (a *alicloudMethod) NewCreds() chan struct{} { - return a.credsFound -} - -func (a *alicloudMethod) CredSuccess() {} - -func (a *alicloudMethod) Shutdown() { - close(a.credsFound) - close(a.stopCh) -} - -func (a *alicloudMethod) pollForCreds(credProvider providers.Provider, frequencySeconds int) { - ticker := time.NewTicker(time.Duration(frequencySeconds) * time.Second) - defer ticker.Stop() - for { - select { - case <-a.stopCh: - a.logger.Trace("shutdown triggered, stopping alicloud auth handler") - return - case <-ticker.C: - if err := a.checkCreds(credProvider); err != nil { - a.logger.Warn("unable to retrieve current creds, retaining last creds", err) - } - } - } -} - -func (a *alicloudMethod) checkCreds(credProvider providers.Provider) error { - a.credLock.Lock() - defer a.credLock.Unlock() - - a.logger.Trace("checking for new credentials") - currentCreds, err := credProvider.Retrieve() - if err != nil { - return err - } - // These will always have different pointers regardless of whether their - // values are identical, hence the use of DeepEqual. - if reflect.DeepEqual(currentCreds, a.lastCreds) { - a.logger.Trace("credentials are unchanged") - return nil - } - a.lastCreds = currentCreds - a.logger.Trace("new credentials detected, triggering Authenticate") - a.credsFound <- struct{}{} - return nil -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/auth.go b/vendor/github.com/hashicorp/vault/command/agent/auth/auth.go deleted file mode 100644 index 6a9127f9b..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/auth.go +++ /dev/null @@ -1,216 +0,0 @@ -package auth - -import ( - "context" - "math/rand" - "time" - - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/jsonutil" -) - -type AuthMethod interface { - Authenticate(context.Context, *api.Client) (string, map[string]interface{}, error) - NewCreds() chan struct{} - CredSuccess() - Shutdown() -} - -type AuthConfig struct { - Logger hclog.Logger - MountPath string - WrapTTL time.Duration - Config map[string]interface{} -} - -// AuthHandler is responsible for keeping a token alive and renewed and passing -// new tokens to the sink server -type AuthHandler struct { - DoneCh chan struct{} - OutputCh chan string - logger hclog.Logger - client *api.Client - random *rand.Rand - wrapTTL time.Duration -} - -type AuthHandlerConfig struct { - Logger hclog.Logger - Client *api.Client - WrapTTL time.Duration -} - -func NewAuthHandler(conf *AuthHandlerConfig) *AuthHandler { - ah := &AuthHandler{ - DoneCh: make(chan struct{}), - OutputCh: make(chan string), - logger: conf.Logger, - client: conf.Client, - random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))), - wrapTTL: conf.WrapTTL, - } - - return ah -} - -func backoffOrQuit(ctx context.Context, backoff time.Duration) { - select { - case <-time.After(backoff): - case <-ctx.Done(): - } -} - -func (ah *AuthHandler) Run(ctx context.Context, am AuthMethod) { - if am == nil { - panic("nil auth method") - } - - ah.logger.Info("starting auth handler") - defer func() { - am.Shutdown() - close(ah.OutputCh) - close(ah.DoneCh) - ah.logger.Info("auth handler stopped") - }() - - credCh := am.NewCreds() - if credCh == nil { - credCh = make(chan struct{}) - } - - var renewer *api.Renewer - - for { - select { - case <-ctx.Done(): - return - - default: - } - - // Create a fresh backoff value - backoff := 2*time.Second + time.Duration(ah.random.Int63()%int64(time.Second*2)-int64(time.Second)) - - ah.logger.Info("authenticating") - path, data, err := am.Authenticate(ctx, ah.client) - if err != nil { - ah.logger.Error("error getting path or data from method", "error", err, "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - - clientToUse := ah.client - if ah.wrapTTL > 0 { - wrapClient, err := ah.client.Clone() - if err != nil { - ah.logger.Error("error creating client for wrapped call", "error", err, "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - wrapClient.SetWrappingLookupFunc(func(string, string) string { - return ah.wrapTTL.String() - }) - clientToUse = wrapClient - } - - secret, err := clientToUse.Logical().Write(path, data) - // Check errors/sanity - if err != nil { - ah.logger.Error("error authenticating", "error", err, "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - - switch { - case ah.wrapTTL > 0: - if secret.WrapInfo == nil { - ah.logger.Error("authentication returned nil wrap info", "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - if secret.WrapInfo.Token == "" { - ah.logger.Error("authentication returned empty wrapped client token", "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - wrappedResp, err := jsonutil.EncodeJSON(secret.WrapInfo) - if err != nil { - ah.logger.Error("failed to encode wrapinfo", "error", err, "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - ah.logger.Info("authentication successful, sending wrapped token to sinks and pausing") - ah.OutputCh <- string(wrappedResp) - - am.CredSuccess() - - select { - case <-ctx.Done(): - ah.logger.Info("shutdown triggered") - continue - - case <-credCh: - ah.logger.Info("auth method found new credentials, re-authenticating") - continue - } - - default: - if secret.Auth == nil { - ah.logger.Error("authentication returned nil auth info", "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - if secret.Auth.ClientToken == "" { - ah.logger.Error("authentication returned empty client token", "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - ah.logger.Info("authentication successful, sending token to sinks") - ah.OutputCh <- secret.Auth.ClientToken - - am.CredSuccess() - } - - if renewer != nil { - renewer.Stop() - } - - renewer, err = ah.client.NewRenewer(&api.RenewerInput{ - Secret: secret, - }) - if err != nil { - ah.logger.Error("error creating renewer, backing off and retrying", "error", err, "backoff", backoff.Seconds()) - backoffOrQuit(ctx, backoff) - continue - } - - // Start the renewal process - ah.logger.Info("starting renewal process") - go renewer.Renew() - - RenewerLoop: - for { - select { - case <-ctx.Done(): - ah.logger.Info("shutdown triggered, stopping renewer") - renewer.Stop() - break RenewerLoop - - case err := <-renewer.DoneCh(): - ah.logger.Info("renewer done channel triggered") - if err != nil { - ah.logger.Error("error renewing token", "error", err) - } - break RenewerLoop - - case <-renewer.RenewCh(): - ah.logger.Info("renewed auth token") - - case <-credCh: - ah.logger.Info("auth method found new credentials, re-authenticating") - break RenewerLoop - } - } - } -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/aws/aws.go b/vendor/github.com/hashicorp/vault/command/agent/auth/aws/aws.go deleted file mode 100644 index 7ff9d2bdf..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/aws/aws.go +++ /dev/null @@ -1,207 +0,0 @@ -package aws - -import ( - "context" - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "net/http" - - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-hclog" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/api" - awsauth "github.com/hashicorp/vault/builtin/credential/aws" - "github.com/hashicorp/vault/command/agent/auth" -) - -const ( - typeEC2 = "ec2" - typeIAM = "iam" - identityEndpoint = "http://169.254.169.254/latest/dynamic/instance-identity" -) - -type awsMethod struct { - logger hclog.Logger - authType string - nonce string - mountPath string - role string - headerValue string - accessKey string - secretKey string - sessionToken string -} - -func NewAWSAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - a := &awsMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - } - - typeRaw, ok := conf.Config["type"] - if !ok { - return nil, errors.New("missing 'type' value") - } - a.authType, ok = typeRaw.(string) - if !ok { - return nil, errors.New("could not convert 'type' config value to string") - } - - roleRaw, ok := conf.Config["role"] - if !ok { - return nil, errors.New("missing 'role' value") - } - a.role, ok = roleRaw.(string) - if !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - - switch { - case a.role == "": - return nil, errors.New("'role' value is empty") - case a.authType == "": - return nil, errors.New("'type' value is empty") - case a.authType != typeEC2 && a.authType != typeIAM: - return nil, errors.New("'type' value is invalid") - } - - accessKeyRaw, ok := conf.Config["access_key"] - if ok { - a.accessKey, ok = accessKeyRaw.(string) - if !ok { - return nil, errors.New("could not convert 'access_key' value into string") - } - } - - secretKeyRaw, ok := conf.Config["secret_key"] - if ok { - a.secretKey, ok = secretKeyRaw.(string) - if !ok { - return nil, errors.New("could not convert 'secret_key' value into string") - } - } - - sessionTokenRaw, ok := conf.Config["session_token"] - if ok { - a.sessionToken, ok = sessionTokenRaw.(string) - if !ok { - return nil, errors.New("could not convert 'session_token' value into string") - } - } - - headerValueRaw, ok := conf.Config["header_value"] - if ok { - a.headerValue, ok = headerValueRaw.(string) - if !ok { - return nil, errors.New("could not convert 'header_value' value into string") - } - } - - return a, nil -} - -func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retToken string, retData map[string]interface{}, retErr error) { - a.logger.Trace("beginning authentication") - - data := make(map[string]interface{}) - - switch a.authType { - case typeEC2: - client := cleanhttp.DefaultClient() - - // Fetch document - { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/document", identityEndpoint), nil) - if err != nil { - retErr = errwrap.Wrapf("error creating request: {{err}}", err) - return - } - req = req.WithContext(ctx) - resp, err := client.Do(req) - if err != nil { - retErr = errwrap.Wrapf("error fetching instance document: {{err}}", err) - return - } - if resp == nil { - retErr = errors.New("empty response fetching instance document") - return - } - defer resp.Body.Close() - doc, err := ioutil.ReadAll(resp.Body) - if err != nil { - retErr = errwrap.Wrapf("error reading instance document response body: {{err}}", err) - return - } - data["identity"] = base64.StdEncoding.EncodeToString(doc) - } - - // Fetch signature - { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/signature", identityEndpoint), nil) - if err != nil { - retErr = errwrap.Wrapf("error creating request: {{err}}", err) - return - } - req = req.WithContext(ctx) - resp, err := client.Do(req) - if err != nil { - retErr = errwrap.Wrapf("error fetching instance document signature: {{err}}", err) - return - } - if resp == nil { - retErr = errors.New("empty response fetching instance document signature") - return - } - defer resp.Body.Close() - sig, err := ioutil.ReadAll(resp.Body) - if err != nil { - retErr = errwrap.Wrapf("error reading instance document signature response body: {{err}}", err) - return - } - data["signature"] = string(sig) - } - - // Add the reauthentication value, if we have one - if a.nonce == "" { - uuid, err := uuid.GenerateUUID() - if err != nil { - retErr = errwrap.Wrapf("error generating uuid for reauthentication value: {{err}}", err) - return - } - a.nonce = uuid - } - data["nonce"] = a.nonce - - default: - var err error - data, err = awsauth.GenerateLoginData(a.accessKey, a.secretKey, a.sessionToken, a.headerValue) - if err != nil { - retErr = errwrap.Wrapf("error creating login value: {{err}}", err) - return - } - } - - data["role"] = a.role - - return fmt.Sprintf("%s/login", a.mountPath), data, nil -} - -func (a *awsMethod) NewCreds() chan struct{} { - return nil -} - -func (a *awsMethod) CredSuccess() { -} - -func (a *awsMethod) Shutdown() { -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/azure/azure.go b/vendor/github.com/hashicorp/vault/command/agent/auth/azure/azure.go deleted file mode 100644 index 7d468d56d..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/azure/azure.go +++ /dev/null @@ -1,180 +0,0 @@ -package azure - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "net/http" - - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/agent/auth" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/useragent" -) - -const ( - instanceEndpoint = "http://169.254.169.254/metadata/instance" - identityEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" - - // minimum version 2018-02-01 needed for identity metadata - // regional availability: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service - apiVersion = "2018-02-01" -) - -type azureMethod struct { - logger hclog.Logger - mountPath string - - role string - resource string -} - -func NewAzureAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - a := &azureMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - } - - roleRaw, ok := conf.Config["role"] - if !ok { - return nil, errors.New("missing 'role' value") - } - a.role, ok = roleRaw.(string) - if !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - - resourceRaw, ok := conf.Config["resource"] - if !ok { - return nil, errors.New("missing 'resource' value") - } - a.resource, ok = resourceRaw.(string) - if !ok { - return nil, errors.New("could not convert 'resource' config value to string") - } - - switch { - case a.role == "": - return nil, errors.New("'role' value is empty") - case a.resource == "": - return nil, errors.New("'resource' value is empty") - } - - return a, nil -} - -func (a *azureMethod) Authenticate(ctx context.Context, client *api.Client) (retPath string, retData map[string]interface{}, retErr error) { - a.logger.Trace("beginning authentication") - - // Fetch instance data - var instance struct { - Compute struct { - Name string - ResourceGroupName string - SubscriptionID string - VMScaleSetName string - } - } - - body, err := getMetadataInfo(ctx, instanceEndpoint, "") - if err != nil { - retErr = err - return - } - - err = jsonutil.DecodeJSON(body, &instance) - if err != nil { - retErr = errwrap.Wrapf("error parsing instance metadata response: {{err}}", err) - return - } - - // Fetch JWT - var identity struct { - AccessToken string `json:"access_token"` - } - - body, err = getMetadataInfo(ctx, identityEndpoint, a.resource) - if err != nil { - retErr = err - return - } - - err = jsonutil.DecodeJSON(body, &identity) - if err != nil { - retErr = errwrap.Wrapf("error parsing identity metadata response: {{err}}", err) - return - } - - // Attempt login - data := map[string]interface{}{ - "role": a.role, - "vm_name": instance.Compute.Name, - "vmss_name": instance.Compute.VMScaleSetName, - "resource_group_name": instance.Compute.ResourceGroupName, - "subscription_id": instance.Compute.SubscriptionID, - "jwt": identity.AccessToken, - } - - return fmt.Sprintf("%s/login", a.mountPath), data, nil -} - -func (a *azureMethod) NewCreds() chan struct{} { - return nil -} - -func (a *azureMethod) CredSuccess() { -} - -func (a *azureMethod) Shutdown() { -} - -func getMetadataInfo(ctx context.Context, endpoint, resource string) ([]byte, error) { - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - return nil, err - } - - q := req.URL.Query() - q.Add("api-version", apiVersion) - if resource != "" { - q.Add("resource", resource) - } - req.URL.RawQuery = q.Encode() - req.Header.Set("Metadata", "true") - req.Header.Set("User-Agent", useragent.String()) - req = req.WithContext(ctx) - - client := cleanhttp.DefaultClient() - resp, err := client.Do(req) - - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error fetching metadata from %s: {{err}}", endpoint), err) - } - - if resp == nil { - return nil, fmt.Errorf("empty response fetching metadata from %s", endpoint) - } - - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error reading metadata from %s: {{err}}", endpoint), err) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("error response in metadata from %s: %s", endpoint, body) - } - - return body, nil -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/gcp/gcp.go b/vendor/github.com/hashicorp/vault/command/agent/auth/gcp/gcp.go deleted file mode 100644 index 75956633c..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/gcp/gcp.go +++ /dev/null @@ -1,241 +0,0 @@ -package gcp - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "time" - - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-gcp-common/gcputil" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/agent/auth" - "github.com/hashicorp/vault/helper/parseutil" - "golang.org/x/oauth2" - iam "google.golang.org/api/iam/v1" -) - -const ( - typeGCE = "gce" - typeIAM = "iam" - identityEndpoint = "http://metadata/computeMetadata/v1/instance/service-accounts/%s/identity" - defaultIamMaxJwtExpMinutes = 15 -) - -type gcpMethod struct { - logger hclog.Logger - authType string - mountPath string - role string - credentials string - serviceAccount string - project string - jwtExp int64 -} - -func NewGCPAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - var err error - - g := &gcpMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - serviceAccount: "default", - } - - typeRaw, ok := conf.Config["type"] - if !ok { - return nil, errors.New("missing 'type' value") - } - g.authType, ok = typeRaw.(string) - if !ok { - return nil, errors.New("could not convert 'type' config value to string") - } - - roleRaw, ok := conf.Config["role"] - if !ok { - return nil, errors.New("missing 'role' value") - } - g.role, ok = roleRaw.(string) - if !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - - switch { - case g.role == "": - return nil, errors.New("'role' value is empty") - case g.authType == "": - return nil, errors.New("'type' value is empty") - case g.authType != typeGCE && g.authType != typeIAM: - return nil, errors.New("'type' value is invalid") - } - - credentialsRaw, ok := conf.Config["credentials"] - if ok { - g.credentials, ok = credentialsRaw.(string) - if !ok { - return nil, errors.New("could not convert 'credentials' value into string") - } - } - - serviceAccountRaw, ok := conf.Config["service_account"] - if ok { - g.serviceAccount, ok = serviceAccountRaw.(string) - if !ok { - return nil, errors.New("could not convert 'service_account' value into string") - } - } - - projectRaw, ok := conf.Config["project"] - if ok { - g.project, ok = projectRaw.(string) - if !ok { - return nil, errors.New("could not convert 'project' value into string") - } - } - - jwtExpRaw, ok := conf.Config["jwt_exp"] - if ok { - g.jwtExp, err = parseutil.ParseInt(jwtExpRaw) - if err != nil { - return nil, errwrap.Wrapf("error parsing 'jwt_raw' into integer: {{err}}", err) - } - } - - return g, nil -} - -func (g *gcpMethod) Authenticate(ctx context.Context, client *api.Client) (retPath string, retData map[string]interface{}, retErr error) { - g.logger.Trace("beginning authentication") - - data := make(map[string]interface{}) - var jwt string - - switch g.authType { - case typeGCE: - httpClient := cleanhttp.DefaultClient() - - // Fetch token - { - req, err := http.NewRequest("GET", fmt.Sprintf(identityEndpoint, g.serviceAccount), nil) - if err != nil { - retErr = errwrap.Wrapf("error creating request: {{err}}", err) - return - } - req = req.WithContext(ctx) - req.Header.Add("Metadata-Flavor", "Google") - q := req.URL.Query() - q.Add("audience", fmt.Sprintf("%s/vault/%s", client.Address(), g.role)) - q.Add("format", "full") - req.URL.RawQuery = q.Encode() - resp, err := httpClient.Do(req) - if err != nil { - retErr = errwrap.Wrapf("error fetching instance token: {{err}}", err) - return - } - if resp == nil { - retErr = errors.New("empty response fetching instance toke") - return - } - defer resp.Body.Close() - jwtBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - retErr = errwrap.Wrapf("error reading instance token response body: {{err}}", err) - return - } - - jwt = string(jwtBytes) - } - - default: - ctx := context.WithValue(context.Background(), oauth2.HTTPClient, cleanhttp.DefaultClient()) - - credentials, tokenSource, err := gcputil.FindCredentials(g.credentials, ctx, iam.CloudPlatformScope) - if err != nil { - retErr = errwrap.Wrapf("could not obtain credentials: {{err}}", err) - return - } - - httpClient := oauth2.NewClient(ctx, tokenSource) - - var serviceAccount string - if g.serviceAccount == "" && credentials != nil { - serviceAccount = credentials.ClientEmail - } else { - serviceAccount = g.serviceAccount - } - if serviceAccount == "" { - retErr = errors.New("could not obtain service account from credentials (possibly Application Default Credentials are being used); a service account to authenticate as must be provided") - return - } - - project := "-" - if g.project != "" { - project = g.project - } else if credentials != nil { - project = credentials.ProjectId - } - - ttlMin := int64(defaultIamMaxJwtExpMinutes) - if g.jwtExp != 0 { - ttlMin = g.jwtExp - } - ttl := time.Minute * time.Duration(ttlMin) - - jwtPayload := map[string]interface{}{ - "aud": fmt.Sprintf("http://vault/%s", g.role), - "sub": serviceAccount, - "exp": time.Now().Add(ttl).Unix(), - } - payloadBytes, err := json.Marshal(jwtPayload) - if err != nil { - retErr = errwrap.Wrapf("could not convert JWT payload to JSON string: {{err}}", err) - return - } - - jwtReq := &iam.SignJwtRequest{ - Payload: string(payloadBytes), - } - - iamClient, err := iam.New(httpClient) - if err != nil { - retErr = errwrap.Wrapf("could not create IAM client: {{err}}", err) - return - } - - resourceName := fmt.Sprintf("projects/%s/serviceAccounts/%s", project, serviceAccount) - resp, err := iamClient.Projects.ServiceAccounts.SignJwt(resourceName, jwtReq).Do() - if err != nil { - retErr = errwrap.Wrapf(fmt.Sprintf("unable to sign JWT for %s using given Vault credentials: {{err}}", resourceName), err) - return - } - - jwt = resp.SignedJwt - } - - data["role"] = g.role - data["jwt"] = jwt - - return fmt.Sprintf("%s/login", g.mountPath), data, nil -} - -func (g *gcpMethod) NewCreds() chan struct{} { - return nil -} - -func (g *gcpMethod) CredSuccess() { -} - -func (g *gcpMethod) Shutdown() { -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/jwt/jwt.go b/vendor/github.com/hashicorp/vault/command/agent/auth/jwt/jwt.go deleted file mode 100644 index 06e640ebd..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/jwt/jwt.go +++ /dev/null @@ -1,184 +0,0 @@ -package jwt - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "os" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/agent/auth" -) - -type jwtMethod struct { - logger hclog.Logger - path string - mountPath string - role string - credsFound chan struct{} - watchCh chan string - stopCh chan struct{} - doneCh chan struct{} - credSuccessGate chan struct{} - ticker *time.Ticker - once *sync.Once - latestToken *atomic.Value -} - -func NewJWTAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - j := &jwtMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - credsFound: make(chan struct{}), - watchCh: make(chan string), - stopCh: make(chan struct{}), - doneCh: make(chan struct{}), - credSuccessGate: make(chan struct{}), - once: new(sync.Once), - latestToken: new(atomic.Value), - } - j.latestToken.Store("") - - pathRaw, ok := conf.Config["path"] - if !ok { - return nil, errors.New("missing 'path' value") - } - j.path, ok = pathRaw.(string) - if !ok { - return nil, errors.New("could not convert 'path' config value to string") - } - - roleRaw, ok := conf.Config["role"] - if !ok { - return nil, errors.New("missing 'role' value") - } - j.role, ok = roleRaw.(string) - if !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - - switch { - case j.path == "": - return nil, errors.New("'path' value is empty") - case j.role == "": - return nil, errors.New("'role' value is empty") - } - - j.ticker = time.NewTicker(500 * time.Millisecond) - - go j.runWatcher() - - j.logger.Info("jwt auth method created", "path", j.path) - - return j, nil -} - -func (j *jwtMethod) Authenticate(_ context.Context, client *api.Client) (string, map[string]interface{}, error) { - j.logger.Trace("beginning authentication") - - j.ingressToken() - - latestToken := j.latestToken.Load().(string) - if latestToken == "" { - return "", nil, errors.New("latest known jwt is empty, cannot authenticate") - } - - return fmt.Sprintf("%s/login", j.mountPath), map[string]interface{}{ - "role": j.role, - "jwt": latestToken, - }, nil -} - -func (j *jwtMethod) NewCreds() chan struct{} { - return j.credsFound -} - -func (j *jwtMethod) CredSuccess() { - j.once.Do(func() { - close(j.credSuccessGate) - }) -} - -func (j *jwtMethod) Shutdown() { - j.ticker.Stop() - close(j.stopCh) - <-j.doneCh -} - -func (j *jwtMethod) runWatcher() { - defer close(j.doneCh) - - select { - case <-j.stopCh: - return - - case <-j.credSuccessGate: - // We only start the next loop once we're initially successful, - // since at startup Authenticate will be called and we don't want - // to end up immediately reauthenticating by having found a new - // value - } - - for { - select { - case <-j.stopCh: - return - - case <-j.ticker.C: - latestToken := j.latestToken.Load().(string) - j.ingressToken() - newToken := j.latestToken.Load().(string) - if newToken != latestToken { - j.credsFound <- struct{}{} - } - } - } -} - -func (j *jwtMethod) ingressToken() { - fi, err := os.Lstat(j.path) - if err != nil { - if os.IsNotExist(err) { - return - } - j.logger.Error("error encountered stat'ing jwt file", "error", err) - return - } - - j.logger.Debug("new jwt file found") - - if !fi.Mode().IsRegular() { - j.logger.Error("jwt file is not a regular file") - return - } - - token, err := ioutil.ReadFile(j.path) - if err != nil { - j.logger.Error("failed to read jwt file", "error", err) - return - } - - switch len(token) { - case 0: - j.logger.Warn("empty jwt file read") - - default: - j.latestToken.Store(string(token)) - } - - if err := os.Remove(j.path); err != nil { - j.logger.Error("error removing jwt file", "error", err) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/auth/kubernetes/kubernetes.go b/vendor/github.com/hashicorp/vault/command/agent/auth/kubernetes/kubernetes.go deleted file mode 100644 index bed3a21a5..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/auth/kubernetes/kubernetes.go +++ /dev/null @@ -1,76 +0,0 @@ -package kubernetes - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "log" - "strings" - - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/agent/auth" -) - -const ( - serviceAccountFile = "/var/run/secrets/kubernetes.io/serviceaccount/token" -) - -type kubernetesMethod struct { - logger hclog.Logger - mountPath string - - role string -} - -func NewKubernetesAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) { - if conf == nil { - return nil, errors.New("empty config") - } - if conf.Config == nil { - return nil, errors.New("empty config data") - } - - k := &kubernetesMethod{ - logger: conf.Logger, - mountPath: conf.MountPath, - } - - roleRaw, ok := conf.Config["role"] - if !ok { - return nil, errors.New("missing 'role' value") - } - k.role, ok = roleRaw.(string) - if !ok { - return nil, errors.New("could not convert 'role' config value to string") - } - if k.role == "" { - return nil, errors.New("'role' value is empty") - } - - return k, nil -} - -func (k *kubernetesMethod) Authenticate(ctx context.Context, client *api.Client) (string, map[string]interface{}, error) { - k.logger.Trace("beginning authentication") - content, err := ioutil.ReadFile(serviceAccountFile) - if err != nil { - log.Fatal(err) - } - - return fmt.Sprintf("%s/login", k.mountPath), map[string]interface{}{ - "role": k.role, - "jwt": strings.TrimSpace(string(content)), - }, nil -} - -func (k *kubernetesMethod) NewCreds() chan struct{} { - return nil -} - -func (k *kubernetesMethod) CredSuccess() { -} - -func (k *kubernetesMethod) Shutdown() { -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/config/config.go b/vendor/github.com/hashicorp/vault/command/agent/config/config.go deleted file mode 100644 index f4e6c9f13..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/config/config.go +++ /dev/null @@ -1,239 +0,0 @@ -package config - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "strings" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/parseutil" - - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" -) - -// Config is the configuration for the vault server. -type Config struct { - AutoAuth *AutoAuth `hcl:"auto_auth"` - ExitAfterAuth bool `hcl:"exit_after_auth"` - PidFile string `hcl:"pid_file"` -} - -type AutoAuth struct { - Method *Method `hcl:"-"` - Sinks []*Sink `hcl:"sinks"` -} - -type Method struct { - Type string - MountPath string `hcl:"mount_path"` - WrapTTLRaw interface{} `hcl:"wrap_ttl"` - WrapTTL time.Duration `hcl:"-"` - Config map[string]interface{} -} - -type Sink struct { - Type string - WrapTTLRaw interface{} `hcl:"wrap_ttl"` - WrapTTL time.Duration `hcl:"-"` - DHType string `hcl:"dh_type"` - DHPath string `hcl:"dh_path"` - AAD string `hcl:"aad"` - AADEnvVar string `hcl:"aad_env_var"` - Config map[string]interface{} -} - -// LoadConfig loads the configuration at the given path, regardless if -// its a file or directory. -func LoadConfig(path string, logger log.Logger) (*Config, error) { - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - - if fi.IsDir() { - return nil, fmt.Errorf("location is a directory, not a file") - } - - // Read the file - d, err := ioutil.ReadFile(path) - if err != nil { - return nil, err - } - - // Parse! - obj, err := hcl.Parse(string(d)) - if err != nil { - return nil, err - } - - // Start building the result - var result Config - if err := hcl.DecodeObject(&result, obj); err != nil { - return nil, err - } - - list, ok := obj.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("error parsing: file doesn't contain a root object") - } - - if err := parseAutoAuth(&result, list); err != nil { - return nil, errwrap.Wrapf("error parsing 'auto_auth': {{err}}", err) - } - - return &result, nil -} - -func parseAutoAuth(result *Config, list *ast.ObjectList) error { - name := "auto_auth" - - autoAuthList := list.Filter(name) - if len(autoAuthList.Items) != 1 { - return fmt.Errorf("one and only one %q block is required", name) - } - - // Get our item - item := autoAuthList.Items[0] - - var a AutoAuth - if err := hcl.DecodeObject(&a, item.Val); err != nil { - return err - } - - result.AutoAuth = &a - - subs, ok := item.Val.(*ast.ObjectType) - if !ok { - return fmt.Errorf("could not parse %q as an object", name) - } - subList := subs.List - - if err := parseMethod(result, subList); err != nil { - return errwrap.Wrapf("error parsing 'method': {{err}}", err) - } - - if err := parseSinks(result, subList); err != nil { - return errwrap.Wrapf("error parsing 'sink' stanzas: {{err}}", err) - } - - switch { - case a.Method == nil: - return fmt.Errorf("no 'method' block found") - case len(a.Sinks) == 0: - return fmt.Errorf("at least one 'sink' block must be provided") - } - - return nil -} - -func parseMethod(result *Config, list *ast.ObjectList) error { - name := "method" - - methodList := list.Filter(name) - if len(methodList.Items) != 1 { - return fmt.Errorf("one and only one %q block is required", name) - } - - // Get our item - item := methodList.Items[0] - - var m Method - if err := hcl.DecodeObject(&m, item.Val); err != nil { - return err - } - - if m.Type == "" { - if len(item.Keys) == 1 { - m.Type = strings.ToLower(item.Keys[0].Token.Value().(string)) - } - if m.Type == "" { - return errors.New("method type must be specified") - } - } - - // Default to Vault's default - if m.MountPath == "" { - m.MountPath = fmt.Sprintf("auth/%s", m.Type) - } - // Standardize on no trailing slash - m.MountPath = strings.TrimSuffix(m.MountPath, "/") - - if m.WrapTTLRaw != nil { - var err error - if m.WrapTTL, err = parseutil.ParseDurationSecond(m.WrapTTLRaw); err != nil { - return err - } - m.WrapTTLRaw = nil - } - - result.AutoAuth.Method = &m - return nil -} - -func parseSinks(result *Config, list *ast.ObjectList) error { - name := "sink" - - sinkList := list.Filter(name) - if len(sinkList.Items) < 1 { - return fmt.Errorf("at least one %q block is required", name) - } - - var ts []*Sink - - for _, item := range sinkList.Items { - var s Sink - if err := hcl.DecodeObject(&s, item.Val); err != nil { - return err - } - - if s.Type == "" { - if len(item.Keys) == 1 { - s.Type = strings.ToLower(item.Keys[0].Token.Value().(string)) - } - if s.Type == "" { - return errors.New("sink type must be specified") - } - } - - if s.WrapTTLRaw != nil { - var err error - if s.WrapTTL, err = parseutil.ParseDurationSecond(s.WrapTTLRaw); err != nil { - return multierror.Prefix(err, fmt.Sprintf("sink.%s", s.Type)) - } - s.WrapTTLRaw = nil - } - - switch s.DHType { - case "": - case "curve25519": - default: - return multierror.Prefix(errors.New("invalid value for 'dh_type'"), fmt.Sprintf("sink.%s", s.Type)) - } - - if s.AADEnvVar != "" { - s.AAD = os.Getenv(s.AADEnvVar) - s.AADEnvVar = "" - } - - switch { - case s.DHPath == "" && s.DHType == "": - if s.AAD != "" { - return multierror.Prefix(errors.New("specifying AAD data without 'dh_type' does not make sense"), fmt.Sprintf("sink.%s", s.Type)) - } - case s.DHPath != "" && s.DHType != "": - default: - return multierror.Prefix(errors.New("'dh_type' and 'dh_path' must be specified together"), fmt.Sprintf("sink.%s", s.Type)) - } - - ts = append(ts, &s) - } - - result.AutoAuth.Sinks = ts - return nil -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/sink/file/file_sink.go b/vendor/github.com/hashicorp/vault/command/agent/sink/file/file_sink.go deleted file mode 100644 index 43ca805e8..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/sink/file/file_sink.go +++ /dev/null @@ -1,112 +0,0 @@ -package file - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/hashicorp/errwrap" - hclog "github.com/hashicorp/go-hclog" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/command/agent/sink" -) - -// fileSink is a Sink implementation that writes a token to a file -type fileSink struct { - path string - logger hclog.Logger -} - -// NewFileSink creates a new file sink with the given configuration -func NewFileSink(conf *sink.SinkConfig) (sink.Sink, error) { - if conf.Logger == nil { - return nil, errors.New("nil logger provided") - } - - conf.Logger.Info("creating file sink") - - f := &fileSink{ - logger: conf.Logger, - } - - pathRaw, ok := conf.Config["path"] - if !ok { - return nil, errors.New("'path' not specified for file sink") - } - path, ok := pathRaw.(string) - if !ok { - return nil, errors.New("could not parse 'path' as string") - } - - f.path = path - - if err := f.WriteToken(""); err != nil { - return nil, errwrap.Wrapf("error during write check: {{err}}", err) - } - - f.logger.Info("file sink configured", "path", f.path) - - return f, nil -} - -// WriteToken implements the Server interface and writes the token to a path on -// disk. It writes into the path's directory into a temp file and does an -// atomic rename to ensure consistency. If a blank token is passed in, it -// performs a write check but does not write a blank value to the final -// location. -func (f *fileSink) WriteToken(token string) error { - f.logger.Trace("enter write_token", "path", f.path) - defer f.logger.Trace("exit write_token", "path", f.path) - - u, err := uuid.GenerateUUID() - if err != nil { - return errwrap.Wrapf("error generating a uuid during write check: {{err}}", err) - } - - targetDir := filepath.Dir(f.path) - fileName := filepath.Base(f.path) - tmpSuffix := strings.Split(u, "-")[0] - - tmpFile, err := os.OpenFile(filepath.Join(targetDir, fmt.Sprintf("%s.tmp.%s", fileName, tmpSuffix)), os.O_WRONLY|os.O_CREATE, 0640) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error opening temp file in dir %s for writing: {{err}}", targetDir), err) - } - - valToWrite := token - if token == "" { - valToWrite = u - } - - _, err = tmpFile.WriteString(valToWrite) - if err != nil { - // Attempt closing and deleting but ignore any error - tmpFile.Close() - os.Remove(tmpFile.Name()) - return errwrap.Wrapf(fmt.Sprintf("error writing to %s: {{err}}", tmpFile.Name()), err) - } - - err = tmpFile.Close() - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error closing %s: {{err}}", tmpFile.Name()), err) - } - - // Now, if we were just doing a write check (blank token), remove the file - // and exit; otherwise, atomically rename it - if token == "" { - err = os.Remove(tmpFile.Name()) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error removing temp file %s during write check: {{err}}", tmpFile.Name()), err) - } - return nil - } - - err = os.Rename(tmpFile.Name(), f.path) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error renaming temp file %s to target file %s: {{err}}", tmpFile.Name(), f.path), err) - } - - f.logger.Info("token written", "path", f.path) - return nil -} diff --git a/vendor/github.com/hashicorp/vault/command/agent/sink/sink.go b/vendor/github.com/hashicorp/vault/command/agent/sink/sink.go deleted file mode 100644 index 9fe99ec4b..000000000 --- a/vendor/github.com/hashicorp/vault/command/agent/sink/sink.go +++ /dev/null @@ -1,242 +0,0 @@ -package sink - -import ( - "context" - "errors" - "io/ioutil" - "math/rand" - "os" - "sync/atomic" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/dhutil" - "github.com/hashicorp/vault/helper/jsonutil" -) - -type Sink interface { - WriteToken(string) error -} - -type SinkConfig struct { - Sink - Logger hclog.Logger - Config map[string]interface{} - Client *api.Client - WrapTTL time.Duration - DHType string - DHPath string - AAD string - cachedRemotePubKey []byte - cachedPubKey []byte - cachedPriKey []byte -} - -type SinkServerConfig struct { - Logger hclog.Logger - Client *api.Client - Context context.Context - ExitAfterAuth bool -} - -// SinkServer is responsible for pushing tokens to sinks -type SinkServer struct { - DoneCh chan struct{} - logger hclog.Logger - client *api.Client - random *rand.Rand - exitAfterAuth bool - remaining *int32 -} - -func NewSinkServer(conf *SinkServerConfig) *SinkServer { - ss := &SinkServer{ - DoneCh: make(chan struct{}), - logger: conf.Logger, - client: conf.Client, - random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))), - exitAfterAuth: conf.ExitAfterAuth, - remaining: new(int32), - } - - return ss -} - -// Run executes the server's run loop, which is responsible for reading -// in new tokens and pushing them out to the various sinks. -func (ss *SinkServer) Run(ctx context.Context, incoming chan string, sinks []*SinkConfig) { - if incoming == nil { - panic("incoming or shutdown channel are nil") - } - - ss.logger.Info("starting sink server") - defer func() { - ss.logger.Info("sink server stopped") - close(ss.DoneCh) - }() - - latestToken := new(string) - sinkCh := make(chan func() error, len(sinks)) - for { - select { - case <-ctx.Done(): - return - - case token := <-incoming: - if token != *latestToken { - - // Drain the existing funcs - drainLoop: - for { - select { - case <-sinkCh: - atomic.AddInt32(ss.remaining, -1) - default: - break drainLoop - } - } - - *latestToken = token - - for _, s := range sinks { - sinkFunc := func(currSink *SinkConfig, currToken string) func() error { - return func() error { - if currToken != *latestToken { - return nil - } - var err error - - if currSink.WrapTTL != 0 { - if currToken, err = s.wrapToken(ss.client, currSink.WrapTTL, currToken); err != nil { - return err - } - } - - if s.DHType != "" { - if currToken, err = s.encryptToken(currToken); err != nil { - return err - } - } - - return currSink.WriteToken(currToken) - } - } - atomic.AddInt32(ss.remaining, 1) - sinkCh <- sinkFunc(s, token) - } - } - - case sinkFunc := <-sinkCh: - atomic.AddInt32(ss.remaining, -1) - select { - case <-ctx.Done(): - return - default: - } - - if err := sinkFunc(); err != nil { - backoff := 2*time.Second + time.Duration(ss.random.Int63()%int64(time.Second*2)-int64(time.Second)) - ss.logger.Error("error returned by sink function, retrying", "error", err, "backoff", backoff.String()) - select { - case <-ctx.Done(): - return - case <-time.After(backoff): - atomic.AddInt32(ss.remaining, 1) - sinkCh <- sinkFunc - } - } else { - if atomic.LoadInt32(ss.remaining) == 0 && ss.exitAfterAuth { - return - } - } - } - } -} - -func (s *SinkConfig) encryptToken(token string) (string, error) { - var aesKey []byte - var err error - resp := new(dhutil.Envelope) - switch s.DHType { - case "curve25519": - if len(s.cachedRemotePubKey) == 0 { - _, err = os.Lstat(s.DHPath) - if err != nil { - if !os.IsNotExist(err) { - return "", errwrap.Wrapf("error stat-ing dh parameters file: {{err}}", err) - } - return "", errors.New("no dh parameters file found, and no cached pub key") - } - fileBytes, err := ioutil.ReadFile(s.DHPath) - if err != nil { - return "", errwrap.Wrapf("error reading file for dh parameters: {{err}}", err) - } - theirPubKey := new(dhutil.PublicKeyInfo) - if err := jsonutil.DecodeJSON(fileBytes, theirPubKey); err != nil { - return "", errwrap.Wrapf("error decoding public key: {{err}}", err) - } - if len(theirPubKey.Curve25519PublicKey) == 0 { - return "", errors.New("public key is nil") - } - s.cachedRemotePubKey = theirPubKey.Curve25519PublicKey - } - if len(s.cachedPubKey) == 0 { - s.cachedPubKey, s.cachedPriKey, err = dhutil.GeneratePublicPrivateKey() - if err != nil { - return "", errwrap.Wrapf("error generating pub/pri curve25519 keys: {{err}}", err) - } - } - resp.Curve25519PublicKey = s.cachedPubKey - } - - aesKey, err = dhutil.GenerateSharedKey(s.cachedPriKey, s.cachedRemotePubKey) - if err != nil { - return "", errwrap.Wrapf("error deriving shared key: {{err}}", err) - } - if len(aesKey) == 0 { - return "", errors.New("derived AES key is empty") - } - - resp.EncryptedPayload, resp.Nonce, err = dhutil.EncryptAES(aesKey, []byte(token), []byte(s.AAD)) - if err != nil { - return "", errwrap.Wrapf("error encrypting with shared key: {{err}}", err) - } - m, err := jsonutil.EncodeJSON(resp) - if err != nil { - return "", errwrap.Wrapf("error encoding encrypted payload: {{err}}", err) - } - - return string(m), nil -} - -func (s *SinkConfig) wrapToken(client *api.Client, wrapTTL time.Duration, token string) (string, error) { - wrapClient, err := client.Clone() - if err != nil { - return "", errwrap.Wrapf("error deriving client for wrapping, not writing out to sink: {{err}})", err) - } - wrapClient.SetToken(token) - wrapClient.SetWrappingLookupFunc(func(string, string) string { - return wrapTTL.String() - }) - secret, err := wrapClient.Logical().Write("sys/wrapping/wrap", map[string]interface{}{ - "token": token, - }) - if err != nil { - return "", errwrap.Wrapf("error wrapping token, not writing out to sink: {{err}})", err) - } - if secret == nil { - return "", errors.New("nil secret returned, not writing out to sink") - } - if secret.WrapInfo == nil { - return "", errors.New("nil wrap info returned, not writing out to sink") - } - - m, err := jsonutil.EncodeJSON(secret.WrapInfo) - if err != nil { - return "", errwrap.Wrapf("error marshaling token, not writing out to sink: {{err}})", err) - } - - return string(m), nil -} diff --git a/vendor/github.com/hashicorp/vault/command/audit.go b/vendor/github.com/hashicorp/vault/command/audit.go deleted file mode 100644 index 0e5935779..000000000 --- a/vendor/github.com/hashicorp/vault/command/audit.go +++ /dev/null @@ -1,42 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*AuditCommand)(nil) - -type AuditCommand struct { - *BaseCommand -} - -func (c *AuditCommand) Synopsis() string { - return "Interact with audit devices" -} - -func (c *AuditCommand) Help() string { - helpText := ` -Usage: vault audit [options] [args] - - This command groups subcommands for interacting with Vault's audit devices. - Users can list, enable, and disable audit devices. - - List all enabled audit devices: - - $ vault audit list - - Enable a new audit device "userpass"; - - $ vault audit enable file file_path=/var/log/audit.log - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *AuditCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/audit_disable.go b/vendor/github.com/hashicorp/vault/command/audit_disable.go deleted file mode 100644 index 1025a0ba2..000000000 --- a/vendor/github.com/hashicorp/vault/command/audit_disable.go +++ /dev/null @@ -1,87 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuditDisableCommand)(nil) -var _ cli.CommandAutocomplete = (*AuditDisableCommand)(nil) - -type AuditDisableCommand struct { - *BaseCommand -} - -func (c *AuditDisableCommand) Synopsis() string { - return "Disables an audit device" -} - -func (c *AuditDisableCommand) Help() string { - helpText := ` -Usage: vault audit disable [options] PATH - - Disables an audit device. Once an audit device is disabled, no future audit - logs are dispatched to it. The data associated with the audit device is not - affected. - - The argument corresponds to the PATH of audit device, not the TYPE! - - Disable the audit device enabled at "file/": - - $ vault audit disable file/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuditDisableCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *AuditDisableCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultAudits() -} - -func (c *AuditDisableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuditDisableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - path := ensureTrailingSlash(sanitizePath(args[0])) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().DisableAudit(path); err != nil { - c.UI.Error(fmt.Sprintf("Error disabling audit device: %s", err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Disabled audit device (if it was enabled) at: %s", path)) - - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/audit_enable.go b/vendor/github.com/hashicorp/vault/command/audit_enable.go deleted file mode 100644 index 85b3bac9a..000000000 --- a/vendor/github.com/hashicorp/vault/command/audit_enable.go +++ /dev/null @@ -1,154 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuditEnableCommand)(nil) -var _ cli.CommandAutocomplete = (*AuditEnableCommand)(nil) - -type AuditEnableCommand struct { - *BaseCommand - - flagDescription string - flagPath string - flagLocal bool - - testStdin io.Reader // For tests -} - -func (c *AuditEnableCommand) Synopsis() string { - return "Enables an audit device" -} - -func (c *AuditEnableCommand) Help() string { - helpText := ` -Usage: vault audit enable [options] TYPE [CONFIG K=V...] - - Enables an audit device at a given path. - - This command enables an audit device of TYPE. Additional options for - configuring the audit device can be specified after the type in the same - format as the "vault write" command in key/value pairs. - - For example, to configure the file audit device to write audit logs at the - path "/var/log/audit.log": - - $ vault audit enable file file_path=/var/log/audit.log - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuditEnableCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringVar(&StringVar{ - Name: "description", - Target: &c.flagDescription, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Human-friendly description for the purpose of this audit " + - "device.", - }) - - f.StringVar(&StringVar{ - Name: "path", - Target: &c.flagPath, - Default: "", // The default is complex, so we have to manually document - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Place where the audit device will be accessible. This must be " + - "unique across all audit devices. This defaults to the \"type\" of the " + - "audit device.", - }) - - f.BoolVar(&BoolVar{ - Name: "local", - Target: &c.flagLocal, - Default: false, - EnvVar: "", - Usage: "Mark the audit device as a local-only device. Local devices " + - "are not replicated or removed by replication.", - }) - - return set -} - -func (c *AuditEnableCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictSet( - "file", - "syslog", - "socket", - ) -} - -func (c *AuditEnableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuditEnableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) < 1 { - c.UI.Error("Missing TYPE!") - return 1 - } - - // Grab the type - auditType := strings.TrimSpace(args[0]) - - auditPath := c.flagPath - if auditPath == "" { - auditPath = auditType - } - auditPath = ensureTrailingSlash(auditPath) - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - options, err := parseArgsDataString(stdin, args[1:]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse K=V data: %s", err)) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().EnableAuditWithOptions(auditPath, &api.EnableAuditOptions{ - Type: auditType, - Description: c.flagDescription, - Options: options, - Local: c.flagLocal, - }); err != nil { - c.UI.Error(fmt.Sprintf("Error enabling audit device: %s", err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Enabled the %s audit device at: %s", auditType, auditPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/audit_list.go b/vendor/github.com/hashicorp/vault/command/audit_list.go deleted file mode 100644 index be3c87807..000000000 --- a/vendor/github.com/hashicorp/vault/command/audit_list.go +++ /dev/null @@ -1,166 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuditListCommand)(nil) -var _ cli.CommandAutocomplete = (*AuditListCommand)(nil) - -type AuditListCommand struct { - *BaseCommand - - flagDetailed bool -} - -func (c *AuditListCommand) Synopsis() string { - return "Lists enabled audit devices" -} - -func (c *AuditListCommand) Help() string { - helpText := ` -Usage: vault audit list [options] - - Lists the enabled audit devices in the Vault server. The output lists the - enabled audit devices and the options for those devices. - - List all audit devices: - - $ vault audit list - - List detailed output about the audit devices: - - $ vault audit list -detailed - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuditListCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "detailed", - Target: &c.flagDetailed, - Default: false, - EnvVar: "", - Usage: "Print detailed information such as options and replication " + - "status about each auth device.", - }) - - return set -} - -func (c *AuditListCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *AuditListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuditListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - audits, err := client.Sys().ListAudit() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing audits: %s", err)) - return 2 - } - - if len(audits) == 0 { - c.UI.Output(fmt.Sprintf("No audit devices are enabled.")) - return 0 - } - - switch Format(c.UI) { - case "table": - if c.flagDetailed { - c.UI.Output(tableOutput(c.detailedAudits(audits), nil)) - return 0 - } - c.UI.Output(tableOutput(c.simpleAudits(audits), nil)) - return 0 - default: - return OutputData(c.UI, audits) - } -} - -func (c *AuditListCommand) simpleAudits(audits map[string]*api.Audit) []string { - paths := make([]string, 0, len(audits)) - for path, _ := range audits { - paths = append(paths, path) - } - sort.Strings(paths) - - columns := []string{"Path | Type | Description"} - for _, path := range paths { - audit := audits[path] - columns = append(columns, fmt.Sprintf("%s | %s | %s", - audit.Path, - audit.Type, - audit.Description, - )) - } - - return columns -} - -func (c *AuditListCommand) detailedAudits(audits map[string]*api.Audit) []string { - paths := make([]string, 0, len(audits)) - for path, _ := range audits { - paths = append(paths, path) - } - sort.Strings(paths) - - columns := []string{"Path | Type | Description | Replication | Options"} - for _, path := range paths { - audit := audits[path] - - opts := make([]string, 0, len(audit.Options)) - for k, v := range audit.Options { - opts = append(opts, k+"="+v) - } - - replication := "replicated" - if audit.Local { - replication = "local" - } - - columns = append(columns, fmt.Sprintf("%s | %s | %s | %s | %s", - path, - audit.Type, - audit.Description, - replication, - strings.Join(opts, " "), - )) - } - - return columns -} diff --git a/vendor/github.com/hashicorp/vault/command/auth.go b/vendor/github.com/hashicorp/vault/command/auth.go deleted file mode 100644 index d51c067b1..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth.go +++ /dev/null @@ -1,124 +0,0 @@ -package command - -import ( - "flag" - "io" - "io/ioutil" - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*AuthCommand)(nil) - -type AuthCommand struct { - *BaseCommand - - Handlers map[string]LoginHandler - - testStdin io.Reader // for tests -} - -func (c *AuthCommand) Synopsis() string { - return "Interact with auth methods" -} - -func (c *AuthCommand) Help() string { - return strings.TrimSpace(` -Usage: vault auth [options] [args] - - This command groups subcommands for interacting with Vault's auth methods. - Users can list, enable, disable, and get help for different auth methods. - - To authenticate to Vault as a user or machine, use the "vault login" command - instead. This command is for interacting with the auth methods themselves, not - authenticating to Vault. - - List all enabled auth methods: - - $ vault auth list - - Enable a new auth method "userpass"; - - $ vault auth enable userpass - - Get detailed help information about how to authenticate to a particular auth - method: - - $ vault auth help github - - Please see the individual subcommand help for detailed usage information. -`) -} - -func (c *AuthCommand) Run(args []string) int { - // If we entered the run method, none of the subcommands picked up. This - // means the user is still trying to use auth as "vault auth TOKEN" or - // similar, so direct them to vault login instead. - // - // This run command is a bit messy to maintain BC for a bit. In the future, - // it will just be a tiny function, but for now we have to maintain bc. - // - // Deprecation - // TODO: remove in 0.9.0 - - // Parse the args for our deprecations and defer to the proper areas. - for _, arg := range args { - switch { - case strings.HasPrefix(arg, "-methods"): - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -methods flag is deprecated. Please use "+ - "\"vault auth list\" instead. This flag will be removed in "+ - "Vault 0.12.") + "\n") - } - return (&AuthListCommand{ - BaseCommand: &BaseCommand{ - UI: c.UI, - client: c.client, - }, - }).Run(nil) - case strings.HasPrefix(arg, "-method-help"): - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -method-help flag is deprecated. Please use "+ - "\"vault auth help\" instead. This flag will be removed in "+ - "Vault 0.12.") + "\n") - } - // Parse the args to pull out the method, suppressing any errors because - // there could be other flags that we don't care about. - f := flag.NewFlagSet("", flag.ContinueOnError) - f.Usage = func() {} - f.SetOutput(ioutil.Discard) - flagMethod := f.String("method", "", "") - f.Parse(args) - - return (&AuthHelpCommand{ - BaseCommand: &BaseCommand{ - UI: c.UI, - client: c.client, - }, - Handlers: c.Handlers, - }).Run([]string{*flagMethod}) - } - } - - // If we got this far, we have an arg or a series of args that should be - // passed directly to the new "vault login" command. - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The \"vault auth ARG\" command is deprecated and is now a "+ - "subcommand for interacting with auth methods. To authenticate "+ - "locally to Vault, use \"vault login\" instead. This backwards "+ - "compatibility will be removed in Vault 0.12.") + "\n") - } - return (&LoginCommand{ - BaseCommand: &BaseCommand{ - UI: c.UI, - client: c.client, - tokenHelper: c.tokenHelper, - flagAddress: c.flagAddress, - }, - Handlers: c.Handlers, - }).Run(args) -} diff --git a/vendor/github.com/hashicorp/vault/command/auth_disable.go b/vendor/github.com/hashicorp/vault/command/auth_disable.go deleted file mode 100644 index afcfe747d..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth_disable.go +++ /dev/null @@ -1,87 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuthDisableCommand)(nil) -var _ cli.CommandAutocomplete = (*AuthDisableCommand)(nil) - -type AuthDisableCommand struct { - *BaseCommand -} - -func (c *AuthDisableCommand) Synopsis() string { - return "Disables an auth method" -} - -func (c *AuthDisableCommand) Help() string { - helpText := ` -Usage: vault auth disable [options] PATH - - Disables an existing auth method at the given PATH. The argument corresponds - to the PATH of the mount, not the TYPE!. Once the auth method is disabled its - path can no longer be used to authenticate. - - All access tokens generated via the disabled auth method are immediately - revoked. This command will block until all tokens are revoked. - - Disable the auth method at userpass/: - - $ vault auth disable userpass/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuthDisableCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *AuthDisableCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultAuths() -} - -func (c *AuthDisableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuthDisableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - path := ensureTrailingSlash(sanitizePath(args[0])) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().DisableAuth(path); err != nil { - c.UI.Error(fmt.Sprintf("Error disabling auth method at %s: %s", path, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Disabled the auth method (if it existed) at: %s", path)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/auth_enable.go b/vendor/github.com/hashicorp/vault/command/auth_enable.go deleted file mode 100644 index f87126411..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth_enable.go +++ /dev/null @@ -1,274 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuthEnableCommand)(nil) -var _ cli.CommandAutocomplete = (*AuthEnableCommand)(nil) - -type AuthEnableCommand struct { - *BaseCommand - - flagDescription string - flagPath string - flagDefaultLeaseTTL time.Duration - flagMaxLeaseTTL time.Duration - flagAuditNonHMACRequestKeys []string - flagAuditNonHMACResponseKeys []string - flagListingVisibility string - flagPassthroughRequestHeaders []string - flagPluginName string - flagOptions map[string]string - flagLocal bool - flagSealWrap bool - flagVersion int -} - -func (c *AuthEnableCommand) Synopsis() string { - return "Enables a new auth method" -} - -func (c *AuthEnableCommand) Help() string { - helpText := ` -Usage: vault auth enable [options] TYPE - - Enables a new auth method. An auth method is responsible for authenticating - users or machines and assigning them policies with which they can access - Vault. - - Enable the userpass auth method at userpass/: - - $ vault auth enable userpass - - Enable the LDAP auth method at auth-prod/: - - $ vault auth enable -path=auth-prod ldap - - Enable a custom auth plugin (after it's registered in the plugin registry): - - $ vault auth enable -path=my-auth -plugin-name=my-auth-plugin plugin - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuthEnableCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringVar(&StringVar{ - Name: "description", - Target: &c.flagDescription, - Completion: complete.PredictAnything, - Usage: "Human-friendly description for the purpose of this " + - "auth method.", - }) - - f.StringVar(&StringVar{ - Name: "path", - Target: &c.flagPath, - Default: "", // The default is complex, so we have to manually document - Completion: complete.PredictAnything, - Usage: "Place where the auth method will be accessible. This must be " + - "unique across all auth methods. This defaults to the \"type\" of " + - "the auth method. The auth method will be accessible at " + - "\"/auth/\".", - }) - - f.DurationVar(&DurationVar{ - Name: "default-lease-ttl", - Target: &c.flagDefaultLeaseTTL, - Completion: complete.PredictAnything, - Usage: "The default lease TTL for this auth method. If unspecified, " + - "this defaults to the Vault server's globally configured default lease " + - "TTL.", - }) - - f.DurationVar(&DurationVar{ - Name: "max-lease-ttl", - Target: &c.flagMaxLeaseTTL, - Completion: complete.PredictAnything, - Usage: "The maximum lease TTL for this auth method. If unspecified, " + - "this defaults to the Vault server's globally configured maximum lease " + - "TTL.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACRequestKeys, - Target: &c.flagAuditNonHMACRequestKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the request data object.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACResponseKeys, - Target: &c.flagAuditNonHMACResponseKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the response data object.", - }) - - f.StringVar(&StringVar{ - Name: flagNameListingVisibility, - Target: &c.flagListingVisibility, - Usage: "Determines the visibility of the mount in the UI-specific listing endpoint.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNamePassthroughRequestHeaders, - Target: &c.flagPassthroughRequestHeaders, - Usage: "Comma-separated string or list of request header values that " + - "will be sent to the backend", - }) - - f.StringVar(&StringVar{ - Name: "plugin-name", - Target: &c.flagPluginName, - Completion: c.PredictVaultPlugins(), - Usage: "Name of the auth method plugin. This plugin name must already " + - "exist in the Vault server's plugin catalog.", - }) - - f.StringMapVar(&StringMapVar{ - Name: "options", - Target: &c.flagOptions, - Completion: complete.PredictAnything, - Usage: "Key-value pair provided as key=value for the mount options. " + - "This can be specified multiple times.", - }) - - f.BoolVar(&BoolVar{ - Name: "local", - Target: &c.flagLocal, - Default: false, - Usage: "Mark the auth method as local-only. Local auth methods are " + - "not replicated nor removed by replication.", - }) - - f.BoolVar(&BoolVar{ - Name: "seal-wrap", - Target: &c.flagSealWrap, - Default: false, - Usage: "Enable seal wrapping of critical values in the secrets engine.", - }) - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Default: 0, - Usage: "Select the version of the auth method to run. Not supported by all auth methods.", - }) - - return set -} - -func (c *AuthEnableCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultAvailableAuths() -} - -func (c *AuthEnableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuthEnableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - authType := strings.TrimSpace(args[0]) - - // If no path is specified, we default the path to the backend type - // or use the plugin name if it's a plugin backend - authPath := c.flagPath - if authPath == "" { - if authType == "plugin" { - authPath = c.flagPluginName - } else { - authPath = authType - } - } - - // Append a trailing slash to indicate it's a path in output - authPath = ensureTrailingSlash(authPath) - - if c.flagVersion > 0 { - if c.flagOptions == nil { - c.flagOptions = make(map[string]string) - } - c.flagOptions["version"] = strconv.Itoa(c.flagVersion) - } - - authOpts := &api.EnableAuthOptions{ - Type: authType, - Description: c.flagDescription, - Local: c.flagLocal, - SealWrap: c.flagSealWrap, - Config: api.AuthConfigInput{ - DefaultLeaseTTL: c.flagDefaultLeaseTTL.String(), - MaxLeaseTTL: c.flagMaxLeaseTTL.String(), - PluginName: c.flagPluginName, - }, - Options: c.flagOptions, - } - - // Set these values only if they are provided in the CLI - f.Visit(func(fl *flag.Flag) { - if fl.Name == flagNameAuditNonHMACRequestKeys { - authOpts.Config.AuditNonHMACRequestKeys = c.flagAuditNonHMACRequestKeys - } - - if fl.Name == flagNameAuditNonHMACResponseKeys { - authOpts.Config.AuditNonHMACResponseKeys = c.flagAuditNonHMACResponseKeys - } - - if fl.Name == flagNameListingVisibility { - authOpts.Config.ListingVisibility = c.flagListingVisibility - } - - if fl.Name == flagNamePassthroughRequestHeaders { - authOpts.Config.PassthroughRequestHeaders = c.flagPassthroughRequestHeaders - } - }) - - if err := client.Sys().EnableAuthWithOptions(authPath, authOpts); err != nil { - c.UI.Error(fmt.Sprintf("Error enabling %s auth: %s", authType, err)) - return 2 - } - - authThing := authType + " auth method" - if authType == "plugin" { - authThing = c.flagPluginName + " plugin" - } - - c.UI.Output(fmt.Sprintf("Success! Enabled %s at: %s", authThing, authPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/auth_help.go b/vendor/github.com/hashicorp/vault/command/auth_help.go deleted file mode 100644 index 6c665fbaf..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth_help.go +++ /dev/null @@ -1,123 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuthHelpCommand)(nil) -var _ cli.CommandAutocomplete = (*AuthHelpCommand)(nil) - -type AuthHelpCommand struct { - *BaseCommand - - Handlers map[string]LoginHandler -} - -func (c *AuthHelpCommand) Synopsis() string { - return "Prints usage for an auth method" -} - -func (c *AuthHelpCommand) Help() string { - helpText := ` -Usage: vault auth help [options] TYPE | PATH - - Prints usage and help for an auth method. - - - If given a TYPE, this command prints the default help for the - auth method of that type. - - - If given a PATH, this command prints the help output for the - auth method enabled at that path. This path must already - exist. - - Get usage instructions for the userpass auth method: - - $ vault auth help userpass - - Print usage for the auth method enabled at my-method/: - - $ vault auth help my-method/ - - Each auth method produces its own help output. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuthHelpCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *AuthHelpCommand) AutocompleteArgs() complete.Predictor { - handlers := make([]string, 0, len(c.Handlers)) - for k := range c.Handlers { - handlers = append(handlers, k) - } - return complete.PredictSet(handlers...) -} - -func (c *AuthHelpCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuthHelpCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Start with the assumption that we have an auth type, not a path. - authType := strings.TrimSpace(args[0]) - - authHandler, ok := c.Handlers[authType] - if !ok { - // There was no auth type by that name, see if it's a mount - auths, err := client.Sys().ListAuth() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing auth methods: %s", err)) - return 2 - } - - authPath := ensureTrailingSlash(sanitizePath(args[0])) - auth, ok := auths[authPath] - if !ok { - c.UI.Warn(fmt.Sprintf( - "No auth method available on the server at %q", authPath)) - return 1 - } - - authHandler, ok = c.Handlers[auth.Type] - if !ok { - c.UI.Warn(wrapAtLength(fmt.Sprintf( - "No method-specific CLI handler available for auth method %q", - authType))) - return 2 - } - } - - c.UI.Output(authHandler.Help()) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/auth_list.go b/vendor/github.com/hashicorp/vault/command/auth_list.go deleted file mode 100644 index 8a917ef91..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth_list.go +++ /dev/null @@ -1,173 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strconv" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuthListCommand)(nil) -var _ cli.CommandAutocomplete = (*AuthListCommand)(nil) - -type AuthListCommand struct { - *BaseCommand - - flagDetailed bool -} - -func (c *AuthListCommand) Synopsis() string { - return "Lists enabled auth methods" -} - -func (c *AuthListCommand) Help() string { - helpText := ` -Usage: vault auth list [options] - - Lists the enabled auth methods on the Vault server. This command also outputs - information about the method including configuration and human-friendly - descriptions. A TTL of "system" indicates that the system default is in use. - - List all enabled auth methods: - - $ vault auth list - - List all enabled auth methods with detailed output: - - $ vault auth list -detailed - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuthListCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "detailed", - Target: &c.flagDetailed, - Default: false, - Usage: "Print detailed information such as configuration and replication " + - "status about each auth method. This option is only applicable to " + - "table-formatted output.", - }) - - return set -} - -func (c *AuthListCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *AuthListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuthListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - auths, err := client.Sys().ListAuth() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing enabled authentications: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - if c.flagDetailed { - c.UI.Output(tableOutput(c.detailedMounts(auths), nil)) - return 0 - } - c.UI.Output(tableOutput(c.simpleMounts(auths), nil)) - return 0 - default: - return OutputData(c.UI, auths) - } -} - -func (c *AuthListCommand) simpleMounts(auths map[string]*api.AuthMount) []string { - paths := make([]string, 0, len(auths)) - for path := range auths { - paths = append(paths, path) - } - sort.Strings(paths) - - out := []string{"Path | Type | Accessor | Description"} - for _, path := range paths { - mount := auths[path] - out = append(out, fmt.Sprintf("%s | %s | %s | %s", path, mount.Type, mount.Accessor, mount.Description)) - } - - return out -} - -func (c *AuthListCommand) detailedMounts(auths map[string]*api.AuthMount) []string { - paths := make([]string, 0, len(auths)) - for path := range auths { - paths = append(paths, path) - } - sort.Strings(paths) - - calcTTL := func(typ string, ttl int) string { - switch { - case typ == "system", typ == "cubbyhole": - return "" - case ttl != 0: - return strconv.Itoa(ttl) - default: - return "system" - } - } - - out := []string{"Path | Type | Accessor | Plugin | Default TTL | Max TTL | Replication | Seal Wrap | Options | Description"} - for _, path := range paths { - mount := auths[path] - - defaultTTL := calcTTL(mount.Type, mount.Config.DefaultLeaseTTL) - maxTTL := calcTTL(mount.Type, mount.Config.MaxLeaseTTL) - - replication := "replicated" - if mount.Local { - replication = "local" - } - - out = append(out, fmt.Sprintf("%s | %s | %s | %s | %s | %s | %s | %t | %v | %s", - path, - mount.Type, - mount.Accessor, - mount.Config.PluginName, - defaultTTL, - maxTTL, - replication, - mount.SealWrap, - mount.Options, - mount.Description, - )) - } - - return out -} diff --git a/vendor/github.com/hashicorp/vault/command/auth_tune.go b/vendor/github.com/hashicorp/vault/command/auth_tune.go deleted file mode 100644 index 100cf6825..000000000 --- a/vendor/github.com/hashicorp/vault/command/auth_tune.go +++ /dev/null @@ -1,200 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*AuthTuneCommand)(nil) -var _ cli.CommandAutocomplete = (*AuthTuneCommand)(nil) - -type AuthTuneCommand struct { - *BaseCommand - - flagAuditNonHMACRequestKeys []string - flagAuditNonHMACResponseKeys []string - flagDefaultLeaseTTL time.Duration - flagDescription string - flagListingVisibility string - flagMaxLeaseTTL time.Duration - flagOptions map[string]string - flagVersion int -} - -func (c *AuthTuneCommand) Synopsis() string { - return "Tunes an auth method configuration" -} - -func (c *AuthTuneCommand) Help() string { - helpText := ` -Usage: vault auth tune [options] PATH - - Tunes the configuration options for the auth method at the given PATH. The - argument corresponds to the PATH where the auth method is enabled, not the - TYPE! - - Tune the default lease for the github auth method: - - $ vault auth tune -default-lease-ttl=72h github/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *AuthTuneCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACRequestKeys, - Target: &c.flagAuditNonHMACRequestKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the request data object.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACResponseKeys, - Target: &c.flagAuditNonHMACResponseKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the response data object.", - }) - - f.DurationVar(&DurationVar{ - Name: "default-lease-ttl", - Target: &c.flagDefaultLeaseTTL, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "The default lease TTL for this auth method. If unspecified, this " + - "defaults to the Vault server's globally configured default lease TTL, " + - "or a previously configured value for the auth method.", - }) - - f.StringVar(&StringVar{ - Name: flagNameDescription, - Target: &c.flagDescription, - Usage: "Human-friendly description of the this auth method. This overrides" + - "the current stored value, if any.", - }) - - f.StringVar(&StringVar{ - Name: flagNameListingVisibility, - Target: &c.flagListingVisibility, - Usage: "Determines the visibility of the mount in the UI-specific listing" + - "endpoint.", - }) - - f.DurationVar(&DurationVar{ - Name: "max-lease-ttl", - Target: &c.flagMaxLeaseTTL, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "The maximum lease TTL for this auth method. If unspecified, this " + - "defaults to the Vault server's globally configured maximum lease TTL, " + - "or a previously configured value for the auth method.", - }) - - f.StringMapVar(&StringMapVar{ - Name: "options", - Target: &c.flagOptions, - Completion: complete.PredictAnything, - Usage: "Key-value pair provided as key=value for the mount options. " + - "This can be specified multiple times.", - }) - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Default: 0, - Usage: "Select the version of the auth method to run. Not supported by all auth methods.", - }) - - return set -} - -func (c *AuthTuneCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultAuths() -} - -func (c *AuthTuneCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *AuthTuneCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if c.flagVersion > 0 { - if c.flagOptions == nil { - c.flagOptions = make(map[string]string) - } - c.flagOptions["version"] = strconv.Itoa(c.flagVersion) - } - - mountConfigInput := api.MountConfigInput{ - DefaultLeaseTTL: ttlToAPI(c.flagDefaultLeaseTTL), - MaxLeaseTTL: ttlToAPI(c.flagMaxLeaseTTL), - Options: c.flagOptions, - } - - // Set these values only if they are provided in the CLI - f.Visit(func(fl *flag.Flag) { - if fl.Name == flagNameAuditNonHMACRequestKeys { - mountConfigInput.AuditNonHMACRequestKeys = c.flagAuditNonHMACRequestKeys - } - - if fl.Name == flagNameAuditNonHMACResponseKeys { - mountConfigInput.AuditNonHMACResponseKeys = c.flagAuditNonHMACResponseKeys - } - - if fl.Name == flagNameDescription { - mountConfigInput.Description = &c.flagDescription - } - - if fl.Name == flagNameListingVisibility { - mountConfigInput.ListingVisibility = c.flagListingVisibility - } - }) - - // Append /auth (since that's where auths live) and a trailing slash to - // indicate it's a path in output - mountPath := ensureTrailingSlash(sanitizePath(args[0])) - - if err := client.Sys().TuneMount("/auth/"+mountPath, mountConfigInput); err != nil { - c.UI.Error(fmt.Sprintf("Error tuning auth method %s: %s", mountPath, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Tuned the auth method at: %s", mountPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/base.go b/vendor/github.com/hashicorp/vault/command/base.go deleted file mode 100644 index d71c4a798..000000000 --- a/vendor/github.com/hashicorp/vault/command/base.go +++ /dev/null @@ -1,487 +0,0 @@ -package command - -import ( - "bytes" - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "strings" - "sync" - "time" - - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/token" - "github.com/hashicorp/vault/helper/namespace" - "github.com/mitchellh/cli" - "github.com/pkg/errors" - "github.com/posener/complete" -) - -const ( - // maxLineLength is the maximum width of any line. - maxLineLength int = 78 - - // notSetValue is a flag value for a not-set value - notSetValue = "(not set)" -) - -// reRemoveWhitespace is a regular expression for stripping whitespace from -// a string. -var reRemoveWhitespace = regexp.MustCompile(`[\s]+`) - -type BaseCommand struct { - UI cli.Ui - - flags *FlagSets - flagsOnce sync.Once - - flagAddress string - flagCACert string - flagCAPath string - flagClientCert string - flagClientKey string - flagNamespace string - flagNS string - flagTLSServerName string - flagTLSSkipVerify bool - flagWrapTTL time.Duration - - flagFormat string - flagField string - - flagMFA []string - - tokenHelper token.TokenHelper - - client *api.Client -} - -// Client returns the HTTP API client. The client is cached on the command to -// save performance on future calls. -func (c *BaseCommand) Client() (*api.Client, error) { - // Read the test client if present - if c.client != nil { - return c.client, nil - } - - config := api.DefaultConfig() - - if err := config.ReadEnvironment(); err != nil { - return nil, errors.Wrap(err, "failed to read environment") - } - - if c.flagAddress != "" { - config.Address = c.flagAddress - } - - // If we need custom TLS configuration, then set it - if c.flagCACert != "" || c.flagCAPath != "" || c.flagClientCert != "" || - c.flagClientKey != "" || c.flagTLSServerName != "" || c.flagTLSSkipVerify { - t := &api.TLSConfig{ - CACert: c.flagCACert, - CAPath: c.flagCAPath, - ClientCert: c.flagClientCert, - ClientKey: c.flagClientKey, - TLSServerName: c.flagTLSServerName, - Insecure: c.flagTLSSkipVerify, - } - config.ConfigureTLS(t) - } - - // Build the client - client, err := api.NewClient(config) - if err != nil { - return nil, errors.Wrap(err, "failed to create client") - } - - // Turn off retries on the CLI - if os.Getenv(api.EnvVaultMaxRetries) == "" { - client.SetMaxRetries(0) - } - - // Set the wrapping function - client.SetWrappingLookupFunc(c.DefaultWrappingLookupFunc) - - // Get the token if it came in from the environment - token := client.Token() - - // If we don't have a token, check the token helper - if token == "" { - helper, err := c.TokenHelper() - if err != nil { - return nil, errors.Wrap(err, "failed to get token helper") - } - token, err = helper.Get() - if err != nil { - return nil, errors.Wrap(err, "failed to get token from token helper") - } - } - - // Set the token - if token != "" { - client.SetToken(token) - } - - client.SetMFACreds(c.flagMFA) - - // flagNS takes precedence over flagNamespace. After resolution, point both - // flags to the same value to be able to use them interchangeably anywhere. - if c.flagNS != notSetValue { - c.flagNamespace = c.flagNS - } - if c.flagNamespace != notSetValue { - client.SetNamespace(namespace.Canonicalize(c.flagNamespace)) - } - - c.client = client - - return client, nil -} - -// SetAddress sets the token helper on the command; useful for the demo server and other outside cases. -func (c *BaseCommand) SetAddress(addr string) { - c.flagAddress = addr -} - -// SetTokenHelper sets the token helper on the command. -func (c *BaseCommand) SetTokenHelper(th token.TokenHelper) { - c.tokenHelper = th -} - -// TokenHelper returns the token helper attached to the command. -func (c *BaseCommand) TokenHelper() (token.TokenHelper, error) { - if c.tokenHelper != nil { - return c.tokenHelper, nil - } - - helper, err := DefaultTokenHelper() - if err != nil { - return nil, err - } - return helper, nil -} - -// DefaultWrappingLookupFunc is the default wrapping function based on the -// CLI flag. -func (c *BaseCommand) DefaultWrappingLookupFunc(operation, path string) string { - if c.flagWrapTTL != 0 { - return c.flagWrapTTL.String() - } - - return api.DefaultWrappingLookupFunc(operation, path) -} - -type FlagSetBit uint - -const ( - FlagSetNone FlagSetBit = 1 << iota - FlagSetHTTP - FlagSetOutputField - FlagSetOutputFormat -) - -// flagSet creates the flags for this command. The result is cached on the -// command to save performance on future calls. -func (c *BaseCommand) flagSet(bit FlagSetBit) *FlagSets { - c.flagsOnce.Do(func() { - set := NewFlagSets(c.UI) - - // These flag sets will apply to all leaf subcommands. - // TODO: Optional, but FlagSetHTTP can be safely removed from the individual - // Flags() subcommands. - bit = bit | FlagSetHTTP - - if bit&FlagSetHTTP != 0 { - f := set.NewFlagSet("HTTP Options") - - addrStringVar := &StringVar{ - Name: "address", - Target: &c.flagAddress, - EnvVar: "VAULT_ADDR", - Completion: complete.PredictAnything, - Usage: "Address of the Vault server.", - } - if c.flagAddress != "" { - addrStringVar.Default = c.flagAddress - } else { - addrStringVar.Default = "https://127.0.0.1:8200" - } - f.StringVar(addrStringVar) - - f.StringVar(&StringVar{ - Name: "ca-cert", - Target: &c.flagCACert, - Default: "", - EnvVar: "VAULT_CACERT", - Completion: complete.PredictFiles("*"), - Usage: "Path on the local disk to a single PEM-encoded CA " + - "certificate to verify the Vault server's SSL certificate. This " + - "takes precedence over -ca-path.", - }) - - f.StringVar(&StringVar{ - Name: "ca-path", - Target: &c.flagCAPath, - Default: "", - EnvVar: "VAULT_CAPATH", - Completion: complete.PredictDirs("*"), - Usage: "Path on the local disk to a directory of PEM-encoded CA " + - "certificates to verify the Vault server's SSL certificate.", - }) - - f.StringVar(&StringVar{ - Name: "client-cert", - Target: &c.flagClientCert, - Default: "", - EnvVar: "VAULT_CLIENT_CERT", - Completion: complete.PredictFiles("*"), - Usage: "Path on the local disk to a single PEM-encoded CA " + - "certificate to use for TLS authentication to the Vault server. If " + - "this flag is specified, -client-key is also required.", - }) - - f.StringVar(&StringVar{ - Name: "client-key", - Target: &c.flagClientKey, - Default: "", - EnvVar: "VAULT_CLIENT_KEY", - Completion: complete.PredictFiles("*"), - Usage: "Path on the local disk to a single PEM-encoded private key " + - "matching the client certificate from -client-cert.", - }) - - f.StringVar(&StringVar{ - Name: "namespace", - Target: &c.flagNamespace, - Default: notSetValue, // this can never be a real value - EnvVar: "VAULT_NAMESPACE", - Completion: complete.PredictAnything, - Usage: "The namespace to use for the command. Setting this is not " + - "necessary but allows using relative paths. -ns can be used as " + - "shortcut.", - }) - - f.StringVar(&StringVar{ - Name: "ns", - Target: &c.flagNS, - Default: notSetValue, // this can never be a real value - Completion: complete.PredictAnything, - Hidden: true, - Usage: "Alias for -namespace. This takes precedence over -namespace.", - }) - - f.StringVar(&StringVar{ - Name: "tls-server-name", - Target: &c.flagTLSServerName, - Default: "", - EnvVar: "VAULT_TLS_SERVER_NAME", - Completion: complete.PredictAnything, - Usage: "Name to use as the SNI host when connecting to the Vault " + - "server via TLS.", - }) - - f.BoolVar(&BoolVar{ - Name: "tls-skip-verify", - Target: &c.flagTLSSkipVerify, - Default: false, - EnvVar: "VAULT_SKIP_VERIFY", - Usage: "Disable verification of TLS certificates. Using this option " + - "is highly discouraged and decreases the security of data " + - "transmissions to and from the Vault server.", - }) - - f.DurationVar(&DurationVar{ - Name: "wrap-ttl", - Target: &c.flagWrapTTL, - Default: 0, - EnvVar: "VAULT_WRAP_TTL", - Completion: complete.PredictAnything, - Usage: "Wraps the response in a cubbyhole token with the requested " + - "TTL. The response is available via the \"vault unwrap\" command. " + - "The TTL is specified as a numeric string with suffix like \"30s\" " + - "or \"5m\".", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: "mfa", - Target: &c.flagMFA, - Default: nil, - EnvVar: api.EnvVaultMFA, - Completion: complete.PredictAnything, - Usage: "Supply MFA credentials as part of X-Vault-MFA header.", - }) - } - - if bit&(FlagSetOutputField|FlagSetOutputFormat) != 0 { - f := set.NewFlagSet("Output Options") - - if bit&FlagSetOutputField != 0 { - f.StringVar(&StringVar{ - Name: "field", - Target: &c.flagField, - Default: "", - Completion: complete.PredictAnything, - Usage: "Print only the field with the given name. Specifying " + - "this option will take precedence over other formatting " + - "directives. The result will not have a trailing newline " + - "making it ideal for piping to other processes.", - }) - } - - if bit&FlagSetOutputFormat != 0 { - f.StringVar(&StringVar{ - Name: "format", - Target: &c.flagFormat, - Default: "table", - EnvVar: EnvVaultFormat, - Completion: complete.PredictSet("table", "json", "yaml"), - Usage: "Print the output in the given format. Valid formats " + - "are \"table\", \"json\", or \"yaml\".", - }) - } - } - - c.flags = set - }) - - return c.flags -} - -// FlagSets is a group of flag sets. -type FlagSets struct { - flagSets []*FlagSet - mainSet *flag.FlagSet - hiddens map[string]struct{} - completions complete.Flags -} - -// NewFlagSets creates a new flag sets. -func NewFlagSets(ui cli.Ui) *FlagSets { - mainSet := flag.NewFlagSet("", flag.ContinueOnError) - - // Errors and usage are controlled by the CLI. - mainSet.Usage = func() {} - mainSet.SetOutput(ioutil.Discard) - - return &FlagSets{ - flagSets: make([]*FlagSet, 0, 6), - mainSet: mainSet, - hiddens: make(map[string]struct{}), - completions: complete.Flags{}, - } -} - -// NewFlagSet creates a new flag set from the given flag sets. -func (f *FlagSets) NewFlagSet(name string) *FlagSet { - flagSet := NewFlagSet(name) - flagSet.mainSet = f.mainSet - flagSet.completions = f.completions - f.flagSets = append(f.flagSets, flagSet) - return flagSet -} - -// Completions returns the completions for this flag set. -func (f *FlagSets) Completions() complete.Flags { - return f.completions -} - -// Parse parses the given flags, returning any errors. -func (f *FlagSets) Parse(args []string) error { - return f.mainSet.Parse(args) -} - -// Parsed reports whether the command-line flags have been parsed. -func (f *FlagSets) Parsed() bool { - return f.mainSet.Parsed() -} - -// Args returns the remaining args after parsing. -func (f *FlagSets) Args() []string { - return f.mainSet.Args() -} - -// Visit visits the flags in lexicographical order, calling fn for each. It -// visits only those flags that have been set. -func (f *FlagSets) Visit(fn func(*flag.Flag)) { - f.mainSet.Visit(fn) -} - -// Help builds custom help for this command, grouping by flag set. -func (fs *FlagSets) Help() string { - var out bytes.Buffer - - for _, set := range fs.flagSets { - printFlagTitle(&out, set.name+":") - set.VisitAll(func(f *flag.Flag) { - // Skip any hidden flags - if v, ok := f.Value.(FlagVisibility); ok && v.Hidden() { - return - } - printFlagDetail(&out, f) - }) - } - - return strings.TrimRight(out.String(), "\n") -} - -// FlagSet is a grouped wrapper around a real flag set and a grouped flag set. -type FlagSet struct { - name string - flagSet *flag.FlagSet - mainSet *flag.FlagSet - completions complete.Flags -} - -// NewFlagSet creates a new flag set. -func NewFlagSet(name string) *FlagSet { - return &FlagSet{ - name: name, - flagSet: flag.NewFlagSet(name, flag.ContinueOnError), - } -} - -// Name returns the name of this flag set. -func (f *FlagSet) Name() string { - return f.name -} - -func (f *FlagSet) Visit(fn func(*flag.Flag)) { - f.flagSet.Visit(fn) -} - -func (f *FlagSet) VisitAll(fn func(*flag.Flag)) { - f.flagSet.VisitAll(fn) -} - -// printFlagTitle prints a consistently-formatted title to the given writer. -func printFlagTitle(w io.Writer, s string) { - fmt.Fprintf(w, "%s\n\n", s) -} - -// printFlagDetail prints a single flag to the given writer. -func printFlagDetail(w io.Writer, f *flag.Flag) { - // Check if the flag is hidden - do not print any flag detail or help output - // if it is hidden. - if h, ok := f.Value.(FlagVisibility); ok && h.Hidden() { - return - } - - // Check for a detailed example - example := "" - if t, ok := f.Value.(FlagExample); ok { - example = t.Example() - } - - if example != "" { - fmt.Fprintf(w, " -%s=<%s>\n", f.Name, example) - } else { - fmt.Fprintf(w, " -%s\n", f.Name) - } - - usage := reRemoveWhitespace.ReplaceAllString(f.Usage, " ") - indented := wrapAtLengthWithPadding(usage, 6) - fmt.Fprintf(w, "%s\n\n", indented) -} diff --git a/vendor/github.com/hashicorp/vault/command/base_flags.go b/vendor/github.com/hashicorp/vault/command/base_flags.go deleted file mode 100644 index 472317037..000000000 --- a/vendor/github.com/hashicorp/vault/command/base_flags.go +++ /dev/null @@ -1,780 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "os" - "sort" - "strconv" - "strings" - "time" - - "github.com/posener/complete" -) - -// FlagExample is an interface which declares an example value. -type FlagExample interface { - Example() string -} - -// FlagVisibility is an interface which declares whether a flag should be -// hidden from help and completions. This is usually used for deprecations -// on "internal-only" flags. -type FlagVisibility interface { - Hidden() bool -} - -// FlagBool is an interface which boolean flags implement. -type FlagBool interface { - IsBoolFlag() bool -} - -// -- BoolVar and boolValue -type BoolVar struct { - Name string - Aliases []string - Usage string - Default bool - Hidden bool - EnvVar string - Target *bool - Completion complete.Predictor -} - -func (f *FlagSet) BoolVar(i *BoolVar) { - def := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if b, err := strconv.ParseBool(v); err == nil { - def = b - } - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: strconv.FormatBool(i.Default), - EnvVar: i.EnvVar, - Value: newBoolValue(def, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type boolValue struct { - hidden bool - target *bool -} - -func newBoolValue(def bool, target *bool, hidden bool) *boolValue { - *target = def - - return &boolValue{ - hidden: hidden, - target: target, - } -} - -func (b *boolValue) Set(s string) error { - v, err := strconv.ParseBool(s) - if err != nil { - return err - } - - *b.target = v - return nil -} - -func (b *boolValue) Get() interface{} { return *b.target } -func (b *boolValue) String() string { return strconv.FormatBool(*b.target) } -func (b *boolValue) Example() string { return "" } -func (b *boolValue) Hidden() bool { return b.hidden } -func (b *boolValue) IsBoolFlag() bool { return true } - -// -- IntVar and intValue -type IntVar struct { - Name string - Aliases []string - Usage string - Default int - Hidden bool - EnvVar string - Target *int - Completion complete.Predictor -} - -func (f *FlagSet) IntVar(i *IntVar) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if i, err := strconv.ParseInt(v, 0, 64); err == nil { - initial = int(i) - } - } - - def := "" - if i.Default != 0 { - def = strconv.FormatInt(int64(i.Default), 10) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newIntValue(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type intValue struct { - hidden bool - target *int -} - -func newIntValue(def int, target *int, hidden bool) *intValue { - *target = def - return &intValue{ - hidden: hidden, - target: target, - } -} - -func (i *intValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - if err != nil { - return err - } - - *i.target = int(v) - return nil -} - -func (i *intValue) Get() interface{} { return int(*i.target) } -func (i *intValue) String() string { return strconv.Itoa(int(*i.target)) } -func (i *intValue) Example() string { return "int" } -func (i *intValue) Hidden() bool { return i.hidden } - -// -- Int64Var and int64Value -type Int64Var struct { - Name string - Aliases []string - Usage string - Default int64 - Hidden bool - EnvVar string - Target *int64 - Completion complete.Predictor -} - -func (f *FlagSet) Int64Var(i *Int64Var) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if i, err := strconv.ParseInt(v, 0, 64); err == nil { - initial = i - } - } - - def := "" - if i.Default != 0 { - def = strconv.FormatInt(int64(i.Default), 10) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newInt64Value(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type int64Value struct { - hidden bool - target *int64 -} - -func newInt64Value(def int64, target *int64, hidden bool) *int64Value { - *target = def - return &int64Value{ - hidden: hidden, - target: target, - } -} - -func (i *int64Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - if err != nil { - return err - } - - *i.target = v - return nil -} - -func (i *int64Value) Get() interface{} { return int64(*i.target) } -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i.target), 10) } -func (i *int64Value) Example() string { return "int" } -func (i *int64Value) Hidden() bool { return i.hidden } - -// -- UintVar && uintValue -type UintVar struct { - Name string - Aliases []string - Usage string - Default uint - Hidden bool - EnvVar string - Target *uint - Completion complete.Predictor -} - -func (f *FlagSet) UintVar(i *UintVar) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if i, err := strconv.ParseUint(v, 0, 64); err == nil { - initial = uint(i) - } - } - - def := "" - if i.Default != 0 { - def = strconv.FormatUint(uint64(i.Default), 10) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newUintValue(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type uintValue struct { - hidden bool - target *uint -} - -func newUintValue(def uint, target *uint, hidden bool) *uintValue { - *target = def - return &uintValue{ - hidden: hidden, - target: target, - } -} - -func (i *uintValue) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - if err != nil { - return err - } - - *i.target = uint(v) - return nil -} - -func (i *uintValue) Get() interface{} { return uint(*i.target) } -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i.target), 10) } -func (i *uintValue) Example() string { return "uint" } -func (i *uintValue) Hidden() bool { return i.hidden } - -// -- Uint64Var and uint64Value -type Uint64Var struct { - Name string - Aliases []string - Usage string - Default uint64 - Hidden bool - EnvVar string - Target *uint64 - Completion complete.Predictor -} - -func (f *FlagSet) Uint64Var(i *Uint64Var) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if i, err := strconv.ParseUint(v, 0, 64); err == nil { - initial = i - } - } - - def := "" - if i.Default != 0 { - strconv.FormatUint(i.Default, 10) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newUint64Value(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type uint64Value struct { - hidden bool - target *uint64 -} - -func newUint64Value(def uint64, target *uint64, hidden bool) *uint64Value { - *target = def - return &uint64Value{ - hidden: hidden, - target: target, - } -} - -func (i *uint64Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - if err != nil { - return err - } - - *i.target = v - return nil -} - -func (i *uint64Value) Get() interface{} { return uint64(*i.target) } -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i.target), 10) } -func (i *uint64Value) Example() string { return "uint" } -func (i *uint64Value) Hidden() bool { return i.hidden } - -// -- StringVar and stringValue -type StringVar struct { - Name string - Aliases []string - Usage string - Default string - Hidden bool - EnvVar string - Target *string - Completion complete.Predictor -} - -func (f *FlagSet) StringVar(i *StringVar) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - initial = v - } - - def := "" - if i.Default != "" { - def = i.Default - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newStringValue(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type stringValue struct { - hidden bool - target *string -} - -func newStringValue(def string, target *string, hidden bool) *stringValue { - *target = def - return &stringValue{ - hidden: hidden, - target: target, - } -} - -func (s *stringValue) Set(val string) error { - *s.target = val - return nil -} - -func (s *stringValue) Get() interface{} { return *s.target } -func (s *stringValue) String() string { return *s.target } -func (s *stringValue) Example() string { return "string" } -func (s *stringValue) Hidden() bool { return s.hidden } - -// -- Float64Var and float64Value -type Float64Var struct { - Name string - Aliases []string - Usage string - Default float64 - Hidden bool - EnvVar string - Target *float64 - Completion complete.Predictor -} - -func (f *FlagSet) Float64Var(i *Float64Var) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if i, err := strconv.ParseFloat(v, 64); err == nil { - initial = i - } - } - - def := "" - if i.Default != 0 { - def = strconv.FormatFloat(i.Default, 'e', -1, 64) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newFloat64Value(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type float64Value struct { - hidden bool - target *float64 -} - -func newFloat64Value(def float64, target *float64, hidden bool) *float64Value { - *target = def - return &float64Value{ - hidden: hidden, - target: target, - } -} - -func (f *float64Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return err - } - - *f.target = v - return nil -} - -func (f *float64Value) Get() interface{} { return float64(*f.target) } -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f.target), 'g', -1, 64) } -func (f *float64Value) Example() string { return "float" } -func (f *float64Value) Hidden() bool { return f.hidden } - -// -- DurationVar and durationValue -type DurationVar struct { - Name string - Aliases []string - Usage string - Default time.Duration - Hidden bool - EnvVar string - Target *time.Duration - Completion complete.Predictor -} - -func (f *FlagSet) DurationVar(i *DurationVar) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - if d, err := time.ParseDuration(appendDurationSuffix(v)); err == nil { - initial = d - } - } - - def := "" - if i.Default != 0 { - def = i.Default.String() - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newDurationValue(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type durationValue struct { - hidden bool - target *time.Duration -} - -func newDurationValue(def time.Duration, target *time.Duration, hidden bool) *durationValue { - *target = def - return &durationValue{ - hidden: hidden, - target: target, - } -} - -func (d *durationValue) Set(s string) error { - // Maintain bc for people specifying "system" as the value. - if s == "system" { - s = "-1" - } - - v, err := time.ParseDuration(appendDurationSuffix(s)) - if err != nil { - return err - } - *d.target = v - return nil -} - -func (d *durationValue) Get() interface{} { return time.Duration(*d.target) } -func (d *durationValue) String() string { return (*d.target).String() } -func (d *durationValue) Example() string { return "duration" } -func (d *durationValue) Hidden() bool { return d.hidden } - -// appendDurationSuffix is used as a backwards-compat tool for assuming users -// meant "seconds" when they do not provide a suffixed duration value. -func appendDurationSuffix(s string) string { - if strings.HasSuffix(s, "s") || strings.HasSuffix(s, "m") || strings.HasSuffix(s, "h") { - return s - } - return s + "s" -} - -// -- StringSliceVar and stringSliceValue -type StringSliceVar struct { - Name string - Aliases []string - Usage string - Default []string - Hidden bool - EnvVar string - Target *[]string - Completion complete.Predictor -} - -func (f *FlagSet) StringSliceVar(i *StringSliceVar) { - initial := i.Default - if v, exist := os.LookupEnv(i.EnvVar); exist { - parts := strings.Split(v, ",") - for i := range parts { - parts[i] = strings.TrimSpace(parts[i]) - } - initial = parts - } - - def := "" - if i.Default != nil { - def = strings.Join(i.Default, ",") - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - EnvVar: i.EnvVar, - Value: newStringSliceValue(initial, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type stringSliceValue struct { - hidden bool - target *[]string -} - -func newStringSliceValue(def []string, target *[]string, hidden bool) *stringSliceValue { - *target = def - return &stringSliceValue{ - hidden: hidden, - target: target, - } -} - -func (s *stringSliceValue) Set(val string) error { - *s.target = append(*s.target, strings.TrimSpace(val)) - return nil -} - -func (s *stringSliceValue) Get() interface{} { return *s.target } -func (s *stringSliceValue) String() string { return strings.Join(*s.target, ",") } -func (s *stringSliceValue) Example() string { return "string" } -func (s *stringSliceValue) Hidden() bool { return s.hidden } - -// -- StringMapVar and stringMapValue -type StringMapVar struct { - Name string - Aliases []string - Usage string - Default map[string]string - Hidden bool - Target *map[string]string - Completion complete.Predictor -} - -func (f *FlagSet) StringMapVar(i *StringMapVar) { - def := "" - if i.Default != nil { - def = mapToKV(i.Default) - } - - f.VarFlag(&VarFlag{ - Name: i.Name, - Aliases: i.Aliases, - Usage: i.Usage, - Default: def, - Value: newStringMapValue(i.Default, i.Target, i.Hidden), - Completion: i.Completion, - }) -} - -type stringMapValue struct { - hidden bool - target *map[string]string -} - -func newStringMapValue(def map[string]string, target *map[string]string, hidden bool) *stringMapValue { - *target = def - return &stringMapValue{ - hidden: hidden, - target: target, - } -} - -func (s *stringMapValue) Set(val string) error { - idx := strings.Index(val, "=") - if idx == -1 { - return fmt.Errorf("missing = in KV pair: %q", val) - } - - if *s.target == nil { - *s.target = make(map[string]string) - } - - k, v := val[0:idx], val[idx+1:] - (*s.target)[k] = v - return nil -} - -func (s *stringMapValue) Get() interface{} { return *s.target } -func (s *stringMapValue) String() string { return mapToKV(*s.target) } -func (s *stringMapValue) Example() string { return "key=value" } -func (s *stringMapValue) Hidden() bool { return s.hidden } - -func mapToKV(m map[string]string) string { - list := make([]string, 0, len(m)) - for k, _ := range m { - list = append(list, k) - } - sort.Strings(list) - - for i, k := range list { - list[i] = k + "=" + m[k] - } - - return strings.Join(list, ",") -} - -// -- VarFlag -type VarFlag struct { - Name string - Aliases []string - Usage string - Default string - EnvVar string - Value flag.Value - Completion complete.Predictor -} - -func (f *FlagSet) VarFlag(i *VarFlag) { - // If the flag is marked as hidden, just add it to the set and return to - // avoid unnecessary computations here. We do not want to add completions or - // generate help output for hidden flags. - if v, ok := i.Value.(FlagVisibility); ok && v.Hidden() { - f.Var(i.Value, i.Name, "") - return - } - - // Calculate the full usage - usage := i.Usage - - if len(i.Aliases) > 0 { - sentence := make([]string, len(i.Aliases)) - for i, a := range i.Aliases { - sentence[i] = fmt.Sprintf(`"-%s"`, a) - } - - aliases := "" - switch len(sentence) { - case 0: - // impossible... - case 1: - aliases = sentence[0] - case 2: - aliases = sentence[0] + " and " + sentence[1] - default: - sentence[len(sentence)-1] = "and " + sentence[len(sentence)-1] - aliases = strings.Join(sentence, ", ") - } - - usage += fmt.Sprintf(" This is aliased as %s.", aliases) - } - - if i.Default != "" { - usage += fmt.Sprintf(" The default is %s.", i.Default) - } - - if i.EnvVar != "" { - usage += fmt.Sprintf(" This can also be specified via the %s "+ - "environment variable.", i.EnvVar) - } - - // Add aliases to the main set - for _, a := range i.Aliases { - f.mainSet.Var(i.Value, a, "") - } - - f.Var(i.Value, i.Name, usage) - f.completions["-"+i.Name] = i.Completion -} - -// Var is a lower-level API for adding something to the flags. It should be used -// wtih caution, since it bypasses all validation. Consider VarFlag instead. -func (f *FlagSet) Var(value flag.Value, name, usage string) { - f.mainSet.Var(value, name, usage) - f.flagSet.Var(value, name, usage) -} - -// -- helpers -func envDefault(key, def string) string { - if v, exist := os.LookupEnv(key); exist { - return v - } - return def -} - -func envBoolDefault(key string, def bool) bool { - if v, exist := os.LookupEnv(key); exist { - b, err := strconv.ParseBool(v) - if err != nil { - panic(err) - } - return b - } - return def -} - -func envDurationDefault(key string, def time.Duration) time.Duration { - if v, exist := os.LookupEnv(key); exist { - d, err := time.ParseDuration(v) - if err != nil { - panic(err) - } - return d - } - return def -} diff --git a/vendor/github.com/hashicorp/vault/command/base_helpers.go b/vendor/github.com/hashicorp/vault/command/base_helpers.go deleted file mode 100644 index d4bf3b734..000000000 --- a/vendor/github.com/hashicorp/vault/command/base_helpers.go +++ /dev/null @@ -1,272 +0,0 @@ -package command - -import ( - "encoding/json" - "fmt" - "io" - "strings" - "time" - - "github.com/hashicorp/vault/api" - kvbuilder "github.com/hashicorp/vault/helper/kv-builder" - "github.com/kr/text" - homedir "github.com/mitchellh/go-homedir" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/ryanuber/columnize" -) - -// extractListData reads the secret and returns a typed list of data and a -// boolean indicating whether the extraction was successful. -func extractListData(secret *api.Secret) ([]interface{}, bool) { - if secret == nil || secret.Data == nil { - return nil, false - } - - k, ok := secret.Data["keys"] - if !ok || k == nil { - return nil, false - } - - i, ok := k.([]interface{}) - return i, ok -} - -// sanitizePath removes any leading or trailing things from a "path". -func sanitizePath(s string) string { - return ensureNoTrailingSlash(ensureNoLeadingSlash(strings.TrimSpace(s))) -} - -// ensureTrailingSlash ensures the given string has a trailing slash. -func ensureTrailingSlash(s string) string { - s = strings.TrimSpace(s) - if s == "" { - return "" - } - - for len(s) > 0 && s[len(s)-1] != '/' { - s = s + "/" - } - return s -} - -// ensureNoTrailingSlash ensures the given string has a trailing slash. -func ensureNoTrailingSlash(s string) string { - s = strings.TrimSpace(s) - if s == "" { - return "" - } - - for len(s) > 0 && s[len(s)-1] == '/' { - s = s[:len(s)-1] - } - return s -} - -// ensureNoLeadingSlash ensures the given string has a trailing slash. -func ensureNoLeadingSlash(s string) string { - s = strings.TrimSpace(s) - if s == "" { - return "" - } - - for len(s) > 0 && s[0] == '/' { - s = s[1:] - } - return s -} - -// columnOuput prints the list of items as a table with no headers. -func columnOutput(list []string, c *columnize.Config) string { - if len(list) == 0 { - return "" - } - - if c == nil { - c = &columnize.Config{} - } - if c.Glue == "" { - c.Glue = " " - } - if c.Empty == "" { - c.Empty = "n/a" - } - - return columnize.Format(list, c) -} - -// tableOutput prints the list of items as columns, where the first row is -// the list of headers. -func tableOutput(list []string, c *columnize.Config) string { - if len(list) == 0 { - return "" - } - - delim := "|" - if c != nil && c.Delim != "" { - delim = c.Delim - } - - underline := "" - headers := strings.Split(list[0], delim) - for i, h := range headers { - h = strings.TrimSpace(h) - u := strings.Repeat("-", len(h)) - - underline = underline + u - if i != len(headers)-1 { - underline = underline + delim - } - } - - list = append(list, "") - copy(list[2:], list[1:]) - list[1] = underline - - return columnOutput(list, c) -} - -// parseArgsData parses the given args in the format key=value into a map of -// the provided arguments. The given reader can also supply key=value pairs. -func parseArgsData(stdin io.Reader, args []string) (map[string]interface{}, error) { - builder := &kvbuilder.Builder{Stdin: stdin} - if err := builder.Add(args...); err != nil { - return nil, err - } - - return builder.Map(), nil -} - -// parseArgsDataString parses the args data and returns the values as strings. -// If the values cannot be represented as strings, an error is returned. -func parseArgsDataString(stdin io.Reader, args []string) (map[string]string, error) { - raw, err := parseArgsData(stdin, args) - if err != nil { - return nil, err - } - - var result map[string]string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, errors.Wrap(err, "failed to convert values to strings") - } - return result, nil -} - -// parseArgsDataStringLists parses the args data and returns the values as -// string lists. If the values cannot be represented as strings, an error is -// returned. -func parseArgsDataStringLists(stdin io.Reader, args []string) (map[string][]string, error) { - raw, err := parseArgsData(stdin, args) - if err != nil { - return nil, err - } - - var result map[string][]string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, errors.Wrap(err, "failed to convert values to strings") - } - return result, nil -} - -// truncateToSeconds truncates the given duration to the number of seconds. If -// the duration is less than 1s, it is returned as 0. The integer represents -// the whole number unit of seconds for the duration. -func truncateToSeconds(d time.Duration) int { - d = d.Truncate(1 * time.Second) - - // Handle the case where someone requested a ridiculously short increment - - // increments must be larger than a second. - if d < 1*time.Second { - return 0 - } - - return int(d.Seconds()) -} - -// printKeyStatus prints the KeyStatus response from the API. -func printKeyStatus(ks *api.KeyStatus) string { - return columnOutput([]string{ - fmt.Sprintf("Key Term | %d", ks.Term), - fmt.Sprintf("Install Time | %s", ks.InstallTime.UTC().Format(time.RFC822)), - }, nil) -} - -// expandPath takes a filepath and returns the full expanded path, accounting -// for user-relative things like ~/. -func expandPath(s string) string { - if s == "" { - return "" - } - - e, err := homedir.Expand(s) - if err != nil { - return s - } - return e -} - -// wrapAtLengthWithPadding wraps the given text at the maxLineLength, taking -// into account any provided left padding. -func wrapAtLengthWithPadding(s string, pad int) string { - wrapped := text.Wrap(s, maxLineLength-pad) - lines := strings.Split(wrapped, "\n") - for i, line := range lines { - lines[i] = strings.Repeat(" ", pad) + line - } - return strings.Join(lines, "\n") -} - -// wrapAtLength wraps the given text to maxLineLength. -func wrapAtLength(s string) string { - return wrapAtLengthWithPadding(s, 0) -} - -// ttlToAPI converts a user-supplied ttl into an API-compatible string. If -// the TTL is 0, this returns the empty string. If the TTL is negative, this -// returns "system" to indicate to use the system values. Otherwise, the -// time.Duration ttl is used. -func ttlToAPI(d time.Duration) string { - if d == 0 { - return "" - } - - if d < 0 { - return "system" - } - - return d.String() -} - -// humanDuration prints the time duration without those pesky zeros. -func humanDuration(d time.Duration) string { - if d == 0 { - return "0s" - } - - s := d.String() - if strings.HasSuffix(s, "m0s") { - s = s[:len(s)-2] - } - if idx := strings.Index(s, "h0m"); idx > 0 { - s = s[:idx+1] + s[idx+3:] - } - return s -} - -// humanDurationInt prints the given int as if it were a time.Duration number -// of seconds. -func humanDurationInt(i interface{}) interface{} { - switch i.(type) { - case int: - return humanDuration(time.Duration(i.(int)) * time.Second) - case int64: - return humanDuration(time.Duration(i.(int64)) * time.Second) - case json.Number: - if i, err := i.(json.Number).Int64(); err == nil { - return humanDuration(time.Duration(i) * time.Second) - } - } - - // If we don't know what type it is, just return the original value - return i -} diff --git a/vendor/github.com/hashicorp/vault/command/base_predict.go b/vendor/github.com/hashicorp/vault/command/base_predict.go deleted file mode 100644 index a280b86e0..000000000 --- a/vendor/github.com/hashicorp/vault/command/base_predict.go +++ /dev/null @@ -1,451 +0,0 @@ -package command - -import ( - "os" - "sort" - "strings" - "sync" - - "github.com/hashicorp/vault/api" - "github.com/posener/complete" -) - -type Predict struct { - client *api.Client - clientOnce sync.Once -} - -func NewPredict() *Predict { - return &Predict{} -} - -func (p *Predict) Client() *api.Client { - p.clientOnce.Do(func() { - if p.client == nil { // For tests - client, _ := api.NewClient(nil) - - if client.Token() == "" { - helper, err := DefaultTokenHelper() - if err != nil { - return - } - token, err := helper.Get() - if err != nil { - return - } - client.SetToken(token) - } - - // Turn off retries for prediction - if os.Getenv(api.EnvVaultMaxRetries) == "" { - client.SetMaxRetries(0) - } - - p.client = client - } - }) - return p.client -} - -// defaultPredictVaultMounts is the default list of mounts to return to the -// user. This is a best-guess, given we haven't communicated with the Vault -// server. If the user has no token or if the token does not have the default -// policy attached, it won't be able to read cubbyhole/, but it's a better UX -// that returning nothing. -var defaultPredictVaultMounts = []string{"cubbyhole/"} - -// predictClient is the API client to use for prediction. We create this at the -// beginning once, because completions are generated for each command (and this -// doesn't change), and the only way to configure the predict/autocomplete -// client is via environment variables. Even if the user specifies a flag, we -// can't parse that flag until after the command is submitted. -var predictClient *api.Client -var predictClientOnce sync.Once - -// PredictClient returns the cached API client for the predictor. -func PredictClient() *api.Client { - predictClientOnce.Do(func() { - if predictClient == nil { // For tests - predictClient, _ = api.NewClient(nil) - } - }) - return predictClient -} - -// PredictVaultAvailableMounts returns a predictor for the available mounts in -// Vault. For now, there is no way to programmatically get this list. If, in the -// future, such a list exists, we can adapt it here. Until then, it's -// hard-coded. -func (b *BaseCommand) PredictVaultAvailableMounts() complete.Predictor { - // This list does not contain deprecated backends. At present, there is no - // API that lists all available secret backends, so this is hard-coded :(. - return complete.PredictSet( - "aws", - "consul", - "database", - "generic", - "pki", - "plugin", - "rabbitmq", - "ssh", - "totp", - "transit", - ) -} - -// PredictVaultAvailableAuths returns a predictor for the available auths in -// Vault. For now, there is no way to programmatically get this list. If, in the -// future, such a list exists, we can adapt it here. Until then, it's -// hard-coded. -func (b *BaseCommand) PredictVaultAvailableAuths() complete.Predictor { - return complete.PredictSet( - "app-id", - "approle", - "aws", - "cert", - "gcp", - "github", - "ldap", - "okta", - "plugin", - "radius", - "userpass", - ) -} - -// PredictVaultFiles returns a predictor for Vault mounts and paths based on the -// configured client for the base command. Unfortunately this happens pre-flag -// parsing, so users must rely on environment variables for autocomplete if they -// are not using Vault at the default endpoints. -func (b *BaseCommand) PredictVaultFiles() complete.Predictor { - return NewPredict().VaultFiles() -} - -// PredictVaultFolders returns a predictor for "folders". See PredictVaultFiles -// for more information and restrictions. -func (b *BaseCommand) PredictVaultFolders() complete.Predictor { - return NewPredict().VaultFolders() -} - -// PredictVaultMounts returns a predictor for "folders". See PredictVaultFiles -// for more information and restrictions. -func (b *BaseCommand) PredictVaultMounts() complete.Predictor { - return NewPredict().VaultMounts() -} - -// PredictVaultAudits returns a predictor for "folders". See PredictVaultFiles -// for more information and restrictions. -func (b *BaseCommand) PredictVaultAudits() complete.Predictor { - return NewPredict().VaultAudits() -} - -// PredictVaultAuths returns a predictor for "folders". See PredictVaultFiles -// for more information and restrictions. -func (b *BaseCommand) PredictVaultAuths() complete.Predictor { - return NewPredict().VaultAuths() -} - -// PredictVaultPlugins returns a predictor for installed plugins. -func (b *BaseCommand) PredictVaultPlugins() complete.Predictor { - return NewPredict().VaultPlugins() -} - -// PredictVaultPolicies returns a predictor for "folders". See PredictVaultFiles -// for more information and restrictions. -func (b *BaseCommand) PredictVaultPolicies() complete.Predictor { - return NewPredict().VaultPolicies() -} - -// VaultFiles returns a predictor for Vault "files". This is a public API for -// consumers, but you probably want BaseCommand.PredictVaultFiles instead. -func (p *Predict) VaultFiles() complete.Predictor { - return p.vaultPaths(true) -} - -// VaultFolders returns a predictor for Vault "folders". This is a public -// API for consumers, but you probably want BaseCommand.PredictVaultFolders -// instead. -func (p *Predict) VaultFolders() complete.Predictor { - return p.vaultPaths(false) -} - -// VaultMounts returns a predictor for Vault "folders". This is a public -// API for consumers, but you probably want BaseCommand.PredictVaultMounts -// instead. -func (p *Predict) VaultMounts() complete.Predictor { - return p.filterFunc(p.mounts) -} - -// VaultAudits returns a predictor for Vault "folders". This is a public API for -// consumers, but you probably want BaseCommand.PredictVaultAudits instead. -func (p *Predict) VaultAudits() complete.Predictor { - return p.filterFunc(p.audits) -} - -// VaultAuths returns a predictor for Vault "folders". This is a public API for -// consumers, but you probably want BaseCommand.PredictVaultAuths instead. -func (p *Predict) VaultAuths() complete.Predictor { - return p.filterFunc(p.auths) -} - -// VaultPlugins returns a predictor for Vault's plugin catalog. This is a public -// API for consumers, but you probably want BaseCommand.PredictVaultPlugins -// instead. -func (p *Predict) VaultPlugins() complete.Predictor { - return p.filterFunc(p.plugins) -} - -// VaultPolicies returns a predictor for Vault "folders". This is a public API for -// consumers, but you probably want BaseCommand.PredictVaultPolicies instead. -func (p *Predict) VaultPolicies() complete.Predictor { - return p.filterFunc(p.policies) -} - -// vaultPaths parses the CLI options and returns the "best" list of possible -// paths. If there are any errors, this function returns an empty result. All -// errors are suppressed since this is a prediction function. -func (p *Predict) vaultPaths(includeFiles bool) complete.PredictFunc { - return func(args complete.Args) []string { - // Do not predict more than one paths - if p.hasPathArg(args.All) { - return nil - } - - client := p.Client() - if client == nil { - return nil - } - - path := args.Last - - var predictions []string - if strings.Contains(path, "/") { - predictions = p.paths(path, includeFiles) - } else { - predictions = p.filter(p.mounts(), path) - } - - // Either no results or many results, so return. - if len(predictions) != 1 { - return predictions - } - - // If this is not a "folder", do not try to recurse. - if !strings.HasSuffix(predictions[0], "/") { - return predictions - } - - // If the prediction is the same as the last guess, return it (we have no - // new information and we won't get anymore). - if predictions[0] == args.Last { - return predictions - } - - // Re-predict with the remaining path - args.Last = predictions[0] - return p.vaultPaths(includeFiles).Predict(args) - } -} - -// paths predicts all paths which start with the given path. -func (p *Predict) paths(path string, includeFiles bool) []string { - client := p.Client() - if client == nil { - return nil - } - - // Vault does not support listing based on a sub-key, so we have to back-pedal - // to the last "/" and return all paths on that "folder". Then we perform - // client-side filtering. - root := path - idx := strings.LastIndex(root, "/") - if idx > 0 && idx < len(root) { - root = root[:idx+1] - } - - paths := p.listPaths(root) - - var predictions []string - for _, p := range paths { - // Calculate the absolute "path" for matching. - p = root + p - - if strings.HasPrefix(p, path) { - // Ensure this is a directory or we've asked to include files. - if includeFiles || strings.HasSuffix(p, "/") { - predictions = append(predictions, p) - } - } - } - - // Add root to the path - if len(predictions) == 0 { - predictions = append(predictions, path) - } - - return predictions -} - -// audits returns a sorted list of the audit backends for Vault server for -// which the client is configured to communicate with. -func (p *Predict) audits() []string { - client := p.Client() - if client == nil { - return nil - } - - audits, err := client.Sys().ListAudit() - if err != nil { - return nil - } - - list := make([]string, 0, len(audits)) - for m := range audits { - list = append(list, m) - } - sort.Strings(list) - return list -} - -// auths returns a sorted list of the enabled auth provides for Vault server for -// which the client is configured to communicate with. -func (p *Predict) auths() []string { - client := p.Client() - if client == nil { - return nil - } - - auths, err := client.Sys().ListAuth() - if err != nil { - return nil - } - - list := make([]string, 0, len(auths)) - for m := range auths { - list = append(list, m) - } - sort.Strings(list) - return list -} - -// plugins returns a sorted list of the plugins in the catalog. -func (p *Predict) plugins() []string { - client := p.Client() - if client == nil { - return nil - } - - result, err := client.Sys().ListPlugins(nil) - if err != nil { - return nil - } - plugins := result.Names - sort.Strings(plugins) - return plugins -} - -// policies returns a sorted list of the policies stored in this Vault -// server. -func (p *Predict) policies() []string { - client := p.Client() - if client == nil { - return nil - } - - policies, err := client.Sys().ListPolicies() - if err != nil { - return nil - } - sort.Strings(policies) - return policies -} - -// mounts returns a sorted list of the mount paths for Vault server for -// which the client is configured to communicate with. This function returns the -// default list of mounts if an error occurs. -func (p *Predict) mounts() []string { - client := p.Client() - if client == nil { - return nil - } - - mounts, err := client.Sys().ListMounts() - if err != nil { - return defaultPredictVaultMounts - } - - list := make([]string, 0, len(mounts)) - for m := range mounts { - list = append(list, m) - } - sort.Strings(list) - return list -} - -// listPaths returns a list of paths (HTTP LIST) for the given path. This -// function returns an empty list of any errors occur. -func (p *Predict) listPaths(path string) []string { - client := p.Client() - if client == nil { - return nil - } - - secret, err := client.Logical().List(path) - if err != nil || secret == nil || secret.Data == nil { - return nil - } - - paths, ok := secret.Data["keys"].([]interface{}) - if !ok { - return nil - } - - list := make([]string, 0, len(paths)) - for _, p := range paths { - if str, ok := p.(string); ok { - list = append(list, str) - } - } - sort.Strings(list) - return list -} - -// hasPathArg determines if the args have already accepted a path. -func (p *Predict) hasPathArg(args []string) bool { - var nonFlags []string - for _, a := range args { - if !strings.HasPrefix(a, "-") { - nonFlags = append(nonFlags, a) - } - } - - return len(nonFlags) > 2 -} - -// filterFunc is used to compose a complete predictor that filters an array -// of strings as per the filter function. -func (p *Predict) filterFunc(f func() []string) complete.Predictor { - return complete.PredictFunc(func(args complete.Args) []string { - if p.hasPathArg(args.All) { - return nil - } - - client := p.Client() - if client == nil { - return nil - } - - return p.filter(f(), args.Last) - }) -} - -// filter filters the given list for items that start with the prefix. -func (p *Predict) filter(list []string, prefix string) []string { - var predictions []string - for _, item := range list { - if strings.HasPrefix(item, prefix) { - predictions = append(predictions, item) - } - } - return predictions -} diff --git a/vendor/github.com/hashicorp/vault/command/commands.go b/vendor/github.com/hashicorp/vault/command/commands.go deleted file mode 100644 index 2b31a7b72..000000000 --- a/vendor/github.com/hashicorp/vault/command/commands.go +++ /dev/null @@ -1,992 +0,0 @@ -package command - -import ( - "fmt" - "os" - "os/signal" - "syscall" - - ad "github.com/hashicorp/vault-plugin-secrets-ad/plugin" - azure "github.com/hashicorp/vault-plugin-secrets-azure" - gcp "github.com/hashicorp/vault-plugin-secrets-gcp/plugin" - kv "github.com/hashicorp/vault-plugin-secrets-kv" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/version" - "github.com/mitchellh/cli" - - "github.com/hashicorp/vault/builtin/logical/aws" - "github.com/hashicorp/vault/builtin/logical/cassandra" - "github.com/hashicorp/vault/builtin/logical/consul" - "github.com/hashicorp/vault/builtin/logical/database" - "github.com/hashicorp/vault/builtin/logical/mongodb" - "github.com/hashicorp/vault/builtin/logical/mssql" - "github.com/hashicorp/vault/builtin/logical/mysql" - "github.com/hashicorp/vault/builtin/logical/nomad" - "github.com/hashicorp/vault/builtin/logical/pki" - "github.com/hashicorp/vault/builtin/logical/postgresql" - "github.com/hashicorp/vault/builtin/logical/rabbitmq" - "github.com/hashicorp/vault/builtin/logical/ssh" - "github.com/hashicorp/vault/builtin/logical/totp" - "github.com/hashicorp/vault/builtin/logical/transit" - "github.com/hashicorp/vault/builtin/plugin" - - auditFile "github.com/hashicorp/vault/builtin/audit/file" - auditSocket "github.com/hashicorp/vault/builtin/audit/socket" - auditSyslog "github.com/hashicorp/vault/builtin/audit/syslog" - - credAliCloud "github.com/hashicorp/vault-plugin-auth-alicloud" - credAzure "github.com/hashicorp/vault-plugin-auth-azure" - credCentrify "github.com/hashicorp/vault-plugin-auth-centrify" - credGcp "github.com/hashicorp/vault-plugin-auth-gcp/plugin" - credJWT "github.com/hashicorp/vault-plugin-auth-jwt" - credKube "github.com/hashicorp/vault-plugin-auth-kubernetes" - credAppId "github.com/hashicorp/vault/builtin/credential/app-id" - credAppRole "github.com/hashicorp/vault/builtin/credential/approle" - credAws "github.com/hashicorp/vault/builtin/credential/aws" - credCert "github.com/hashicorp/vault/builtin/credential/cert" - credGitHub "github.com/hashicorp/vault/builtin/credential/github" - credLdap "github.com/hashicorp/vault/builtin/credential/ldap" - credOkta "github.com/hashicorp/vault/builtin/credential/okta" - credRadius "github.com/hashicorp/vault/builtin/credential/radius" - credToken "github.com/hashicorp/vault/builtin/credential/token" - credUserpass "github.com/hashicorp/vault/builtin/credential/userpass" - - physAliCloudOSS "github.com/hashicorp/vault/physical/alicloudoss" - physAzure "github.com/hashicorp/vault/physical/azure" - physCassandra "github.com/hashicorp/vault/physical/cassandra" - physCockroachDB "github.com/hashicorp/vault/physical/cockroachdb" - physConsul "github.com/hashicorp/vault/physical/consul" - physCouchDB "github.com/hashicorp/vault/physical/couchdb" - physDynamoDB "github.com/hashicorp/vault/physical/dynamodb" - physEtcd "github.com/hashicorp/vault/physical/etcd" - physFile "github.com/hashicorp/vault/physical/file" - physFoundationDB "github.com/hashicorp/vault/physical/foundationdb" - physGCS "github.com/hashicorp/vault/physical/gcs" - physInmem "github.com/hashicorp/vault/physical/inmem" - physManta "github.com/hashicorp/vault/physical/manta" - physMSSQL "github.com/hashicorp/vault/physical/mssql" - physMySQL "github.com/hashicorp/vault/physical/mysql" - physPostgreSQL "github.com/hashicorp/vault/physical/postgresql" - physS3 "github.com/hashicorp/vault/physical/s3" - physSpanner "github.com/hashicorp/vault/physical/spanner" - physSwift "github.com/hashicorp/vault/physical/swift" - physZooKeeper "github.com/hashicorp/vault/physical/zookeeper" -) - -const ( - // EnvVaultCLINoColor is an env var that toggles colored UI output. - EnvVaultCLINoColor = `VAULT_CLI_NO_COLOR` - // EnvVaultFormat is the output format - EnvVaultFormat = `VAULT_FORMAT` - - // flagNameAuditNonHMACRequestKeys is the flag name used for auth/secrets enable - flagNameAuditNonHMACRequestKeys = "audit-non-hmac-request-keys" - // flagNameAuditNonHMACResponseKeys is the flag name used for auth/secrets enable - flagNameAuditNonHMACResponseKeys = "audit-non-hmac-response-keys" - // flagNameDescription is the flag name used for tuning the secret and auth mount description parameter - flagNameDescription = "description" - // flagListingVisibility is the flag to toggle whether to show the mount in the UI-specific listing endpoint - flagNameListingVisibility = "listing-visibility" - // flagNamePassthroughRequestHeaders is the flag name used to set passthrough request headers to the backend - flagNamePassthroughRequestHeaders = "passthrough-request-headers" -) - -var ( - auditBackends = map[string]audit.Factory{ - "file": auditFile.Factory, - "socket": auditSocket.Factory, - "syslog": auditSyslog.Factory, - } - - credentialBackends = map[string]logical.Factory{ - "alicloud": credAliCloud.Factory, - "app-id": credAppId.Factory, - "approle": credAppRole.Factory, - "aws": credAws.Factory, - "azure": credAzure.Factory, - "centrify": credCentrify.Factory, - "cert": credCert.Factory, - "gcp": credGcp.Factory, - "github": credGitHub.Factory, - "jwt": credJWT.Factory, - "kubernetes": credKube.Factory, - "ldap": credLdap.Factory, - "okta": credOkta.Factory, - "plugin": plugin.Factory, - "radius": credRadius.Factory, - "userpass": credUserpass.Factory, - } - - logicalBackends = map[string]logical.Factory{ - "ad": ad.Factory, - "aws": aws.Factory, - "azure": azure.Factory, - "cassandra": cassandra.Factory, - "consul": consul.Factory, - "database": database.Factory, - "gcp": gcp.Factory, - "kv": kv.Factory, - "mongodb": mongodb.Factory, - "mssql": mssql.Factory, - "mysql": mysql.Factory, - "nomad": nomad.Factory, - "pki": pki.Factory, - "plugin": plugin.Factory, - "postgresql": postgresql.Factory, - "rabbitmq": rabbitmq.Factory, - "ssh": ssh.Factory, - "totp": totp.Factory, - "transit": transit.Factory, - } - - physicalBackends = map[string]physical.Factory{ - "alicloudoss": physAliCloudOSS.NewAliCloudOSSBackend, - "azure": physAzure.NewAzureBackend, - "cassandra": physCassandra.NewCassandraBackend, - "cockroachdb": physCockroachDB.NewCockroachDBBackend, - "consul": physConsul.NewConsulBackend, - "couchdb_transactional": physCouchDB.NewTransactionalCouchDBBackend, - "couchdb": physCouchDB.NewCouchDBBackend, - "dynamodb": physDynamoDB.NewDynamoDBBackend, - "etcd": physEtcd.NewEtcdBackend, - "file_transactional": physFile.NewTransactionalFileBackend, - "file": physFile.NewFileBackend, - "foundationdb": physFoundationDB.NewFDBBackend, - "gcs": physGCS.NewBackend, - "inmem_ha": physInmem.NewInmemHA, - "inmem_transactional_ha": physInmem.NewTransactionalInmemHA, - "inmem_transactional": physInmem.NewTransactionalInmem, - "inmem": physInmem.NewInmem, - "manta": physManta.NewMantaBackend, - "mssql": physMSSQL.NewMSSQLBackend, - "mysql": physMySQL.NewMySQLBackend, - "postgresql": physPostgreSQL.NewPostgreSQLBackend, - "s3": physS3.NewS3Backend, - "spanner": physSpanner.NewBackend, - "swift": physSwift.NewSwiftBackend, - "zookeeper": physZooKeeper.NewZooKeeperBackend, - } -) - -// DeprecatedCommand is a command that wraps an existing command and prints a -// deprecation notice and points the user to the new command. Deprecated -// commands are always hidden from help output. -type DeprecatedCommand struct { - cli.Command - UI cli.Ui - - // Old is the old command name, New is the new command name. - Old, New string -} - -// Help wraps the embedded Help command and prints a warning about deprecations. -func (c *DeprecatedCommand) Help() string { - c.warn() - return c.Command.Help() -} - -// Run wraps the embedded Run command and prints a warning about deprecation. -func (c *DeprecatedCommand) Run(args []string) int { - if Format(c.UI) == "table" { - c.warn() - } - return c.Command.Run(args) -} - -func (c *DeprecatedCommand) warn() { - c.UI.Warn(wrapAtLength(fmt.Sprintf( - "WARNING! The \"vault %s\" command is deprecated. Please use \"vault %s\" "+ - "instead. This command will be removed in Vault 0.12.", - c.Old, - c.New))) - c.UI.Warn("") -} - -// Commands is the mapping of all the available commands. -var Commands map[string]cli.CommandFactory -var DeprecatedCommands map[string]cli.CommandFactory - -func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) { - loginHandlers := map[string]LoginHandler{ - "alicloud": &credAliCloud.CLIHandler{}, - "aws": &credAws.CLIHandler{}, - "centrify": &credCentrify.CLIHandler{}, - "cert": &credCert.CLIHandler{}, - "gcp": &credGcp.CLIHandler{}, - "github": &credGitHub.CLIHandler{}, - "ldap": &credLdap.CLIHandler{}, - "okta": &credOkta.CLIHandler{}, - "radius": &credUserpass.CLIHandler{ - DefaultMount: "radius", - }, - "token": &credToken.CLIHandler{}, - "userpass": &credUserpass.CLIHandler{ - DefaultMount: "userpass", - }, - } - - getBaseCommand := func() *BaseCommand { - return &BaseCommand{ - UI: ui, - tokenHelper: runOpts.TokenHelper, - flagAddress: runOpts.Address, - client: runOpts.Client, - } - } - - Commands = map[string]cli.CommandFactory{ - "agent": func() (cli.Command, error) { - return &AgentCommand{ - BaseCommand: &BaseCommand{ - UI: serverCmdUi, - }, - ShutdownCh: MakeShutdownCh(), - }, nil - }, - "audit": func() (cli.Command, error) { - return &AuditCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "audit disable": func() (cli.Command, error) { - return &AuditDisableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "audit enable": func() (cli.Command, error) { - return &AuditEnableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "audit list": func() (cli.Command, error) { - return &AuditListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "auth tune": func() (cli.Command, error) { - return &AuthTuneCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "auth": func() (cli.Command, error) { - return &AuthCommand{ - BaseCommand: getBaseCommand(), - Handlers: loginHandlers, - }, nil - }, - "auth disable": func() (cli.Command, error) { - return &AuthDisableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "auth enable": func() (cli.Command, error) { - return &AuthEnableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "auth help": func() (cli.Command, error) { - return &AuthHelpCommand{ - BaseCommand: getBaseCommand(), - Handlers: loginHandlers, - }, nil - }, - "auth list": func() (cli.Command, error) { - return &AuthListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "delete": func() (cli.Command, error) { - return &DeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "lease": func() (cli.Command, error) { - return &LeaseCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "lease renew": func() (cli.Command, error) { - return &LeaseRenewCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "lease revoke": func() (cli.Command, error) { - return &LeaseRevokeCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "list": func() (cli.Command, error) { - return &ListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "login": func() (cli.Command, error) { - return &LoginCommand{ - BaseCommand: getBaseCommand(), - Handlers: loginHandlers, - }, nil - }, - "namespace": func() (cli.Command, error) { - return &NamespaceCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "namespace list": func() (cli.Command, error) { - return &NamespaceListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "namespace lookup": func() (cli.Command, error) { - return &NamespaceLookupCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "namespace create": func() (cli.Command, error) { - return &NamespaceCreateCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "namespace delete": func() (cli.Command, error) { - return &NamespaceDeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator": func() (cli.Command, error) { - return &OperatorCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator generate-root": func() (cli.Command, error) { - return &OperatorGenerateRootCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator init": func() (cli.Command, error) { - return &OperatorInitCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator key-status": func() (cli.Command, error) { - return &OperatorKeyStatusCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator rekey": func() (cli.Command, error) { - return &OperatorRekeyCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator rotate": func() (cli.Command, error) { - return &OperatorRotateCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator seal": func() (cli.Command, error) { - return &OperatorSealCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator step-down": func() (cli.Command, error) { - return &OperatorStepDownCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "operator unseal": func() (cli.Command, error) { - return &OperatorUnsealCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "path-help": func() (cli.Command, error) { - return &PathHelpCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "plugin": func() (cli.Command, error) { - return &PluginCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "plugin deregister": func() (cli.Command, error) { - return &PluginDeregisterCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "plugin info": func() (cli.Command, error) { - return &PluginInfoCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "plugin list": func() (cli.Command, error) { - return &PluginListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "plugin register": func() (cli.Command, error) { - return &PluginRegisterCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy": func() (cli.Command, error) { - return &PolicyCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy delete": func() (cli.Command, error) { - return &PolicyDeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy fmt": func() (cli.Command, error) { - return &PolicyFmtCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy list": func() (cli.Command, error) { - return &PolicyListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy read": func() (cli.Command, error) { - return &PolicyReadCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "policy write": func() (cli.Command, error) { - return &PolicyWriteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "read": func() (cli.Command, error) { - return &ReadCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets": func() (cli.Command, error) { - return &SecretsCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets disable": func() (cli.Command, error) { - return &SecretsDisableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets enable": func() (cli.Command, error) { - return &SecretsEnableCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets list": func() (cli.Command, error) { - return &SecretsListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets move": func() (cli.Command, error) { - return &SecretsMoveCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "secrets tune": func() (cli.Command, error) { - return &SecretsTuneCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "server": func() (cli.Command, error) { - return &ServerCommand{ - BaseCommand: &BaseCommand{ - UI: serverCmdUi, - tokenHelper: runOpts.TokenHelper, - flagAddress: runOpts.Address, - }, - AuditBackends: auditBackends, - CredentialBackends: credentialBackends, - LogicalBackends: logicalBackends, - PhysicalBackends: physicalBackends, - ShutdownCh: MakeShutdownCh(), - SighupCh: MakeSighupCh(), - }, nil - }, - "ssh": func() (cli.Command, error) { - return &SSHCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "status": func() (cli.Command, error) { - return &StatusCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token": func() (cli.Command, error) { - return &TokenCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token create": func() (cli.Command, error) { - return &TokenCreateCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token capabilities": func() (cli.Command, error) { - return &TokenCapabilitiesCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token lookup": func() (cli.Command, error) { - return &TokenLookupCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token renew": func() (cli.Command, error) { - return &TokenRenewCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "token revoke": func() (cli.Command, error) { - return &TokenRevokeCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "unwrap": func() (cli.Command, error) { - return &UnwrapCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "version": func() (cli.Command, error) { - return &VersionCommand{ - VersionInfo: version.GetVersion(), - BaseCommand: getBaseCommand(), - }, nil - }, - "write": func() (cli.Command, error) { - return &WriteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv": func() (cli.Command, error) { - return &KVCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv put": func() (cli.Command, error) { - return &KVPutCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv patch": func() (cli.Command, error) { - return &KVPatchCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv rollback": func() (cli.Command, error) { - return &KVRollbackCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv get": func() (cli.Command, error) { - return &KVGetCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv delete": func() (cli.Command, error) { - return &KVDeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv list": func() (cli.Command, error) { - return &KVListCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv destroy": func() (cli.Command, error) { - return &KVDestroyCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv undelete": func() (cli.Command, error) { - return &KVUndeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv enable-versioning": func() (cli.Command, error) { - return &KVEnableVersioningCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv metadata": func() (cli.Command, error) { - return &KVMetadataCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv metadata put": func() (cli.Command, error) { - return &KVMetadataPutCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv metadata get": func() (cli.Command, error) { - return &KVMetadataGetCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - "kv metadata delete": func() (cli.Command, error) { - return &KVMetadataDeleteCommand{ - BaseCommand: getBaseCommand(), - }, nil - }, - } - - // Deprecated commands - // - // TODO: Remove not before 0.11.0 - DeprecatedCommands = map[string]cli.CommandFactory{ - "audit-disable": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "audit-disable", - New: "audit disable", - UI: ui, - Command: &AuditDisableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "audit-enable": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "audit-enable", - New: "audit enable", - UI: ui, - Command: &AuditEnableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "audit-list": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "audit-list", - New: "audit list", - UI: ui, - Command: &AuditListCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "auth-disable": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "auth-disable", - New: "auth disable", - UI: ui, - Command: &AuthDisableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "auth-enable": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "auth-enable", - New: "auth enable", - UI: ui, - Command: &AuthEnableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "capabilities": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "capabilities", - New: "token capabilities", - UI: ui, - Command: &TokenCapabilitiesCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "generate-root": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "generate-root", - New: "operator generate-root", - UI: ui, - Command: &OperatorGenerateRootCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "init": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "init", - New: "operator init", - UI: ui, - Command: &OperatorInitCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "key-status": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "key-status", - New: "operator key-status", - UI: ui, - Command: &OperatorKeyStatusCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "renew": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "renew", - New: "lease renew", - UI: ui, - Command: &LeaseRenewCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "revoke": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "revoke", - New: "lease revoke", - UI: ui, - Command: &LeaseRevokeCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "mount": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "mount", - New: "secrets enable", - UI: ui, - Command: &SecretsEnableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "mount-tune": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "mount-tune", - New: "secrets tune", - UI: ui, - Command: &SecretsTuneCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "mounts": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "mounts", - New: "secrets list", - UI: ui, - Command: &SecretsListCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "policies": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "policies", - New: "policy read\" or \"vault policy list", // lol - UI: ui, - Command: &PoliciesDeprecatedCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "policy-delete": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "policy-delete", - New: "policy delete", - UI: ui, - Command: &PolicyDeleteCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "policy-write": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "policy-write", - New: "policy write", - UI: ui, - Command: &PolicyWriteCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "rekey": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "rekey", - New: "operator rekey", - UI: ui, - Command: &OperatorRekeyCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "remount": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "remount", - New: "secrets move", - UI: ui, - Command: &SecretsMoveCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "rotate": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "rotate", - New: "operator rotate", - UI: ui, - Command: &OperatorRotateCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "seal": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "seal", - New: "operator seal", - UI: ui, - Command: &OperatorSealCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "step-down": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "step-down", - New: "operator step-down", - UI: ui, - Command: &OperatorStepDownCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "token-create": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "token-create", - New: "token create", - UI: ui, - Command: &TokenCreateCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "token-lookup": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "token-lookup", - New: "token lookup", - UI: ui, - Command: &TokenLookupCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "token-renew": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "token-renew", - New: "token renew", - UI: ui, - Command: &TokenRenewCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "token-revoke": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "token-revoke", - New: "token revoke", - UI: ui, - Command: &TokenRevokeCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "unmount": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "unmount", - New: "secrets disable", - UI: ui, - Command: &SecretsDisableCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - - "unseal": func() (cli.Command, error) { - return &DeprecatedCommand{ - Old: "unseal", - New: "operator unseal", - UI: ui, - Command: &OperatorUnsealCommand{ - BaseCommand: getBaseCommand(), - }, - }, nil - }, - } - - // Add deprecated commands back to the main commands so they parse. - for k, v := range DeprecatedCommands { - if _, ok := Commands[k]; ok { - // Can't deprecate an existing command... - panic(fmt.Sprintf("command %q defined as deprecated and not at the same time!", k)) - } - Commands[k] = v - } -} - -// MakeShutdownCh returns a channel that can be used for shutdown -// notifications for commands. This channel will send a message for every -// SIGINT or SIGTERM received. -func MakeShutdownCh() chan struct{} { - resultCh := make(chan struct{}) - - shutdownCh := make(chan os.Signal, 4) - signal.Notify(shutdownCh, os.Interrupt, syscall.SIGTERM) - go func() { - <-shutdownCh - close(resultCh) - }() - return resultCh -} - -// MakeSighupCh returns a channel that can be used for SIGHUP -// reloading. This channel will send a message for every -// SIGHUP received. -func MakeSighupCh() chan struct{} { - resultCh := make(chan struct{}) - - signalCh := make(chan os.Signal, 4) - signal.Notify(signalCh, syscall.SIGHUP) - go func() { - for { - <-signalCh - resultCh <- struct{}{} - } - }() - return resultCh -} diff --git a/vendor/github.com/hashicorp/vault/command/config.go b/vendor/github.com/hashicorp/vault/command/config.go deleted file mode 100644 index b46581fc8..000000000 --- a/vendor/github.com/hashicorp/vault/command/config.go +++ /dev/null @@ -1,54 +0,0 @@ -package command - -import ( - "github.com/hashicorp/vault/command/config" -) - -const ( - // DefaultConfigPath is the default path to the configuration file - DefaultConfigPath = "~/.vault" - - // ConfigPathEnv is the environment variable that can be used to - // override where the Vault configuration is. - ConfigPathEnv = "VAULT_CONFIG_PATH" -) - -// Config is the CLI configuration for Vault that can be specified via -// a `$HOME/.vault` file which is HCL-formatted (therefore HCL or JSON). -type DefaultConfig struct { - // TokenHelper is the executable/command that is executed for storing - // and retrieving the authentication token for the Vault CLI. If this - // is not specified, then vault's internal token store will be used, which - // stores the token on disk unencrypted. - TokenHelper string `hcl:"token_helper"` -} - -// Config loads the configuration and returns it. If the configuration -// is already loaded, it is returned. -// -// Config just calls into config.Config for backwards compatibility purposes. -// Use config.Config instead. -func Config() (*DefaultConfig, error) { - conf, err := config.Config() - return (*DefaultConfig)(conf), err -} - -// LoadConfig reads the configuration from the given path. If path is -// empty, then the default path will be used, or the environment variable -// if set. -// -// LoadConfig just calls into config.LoadConfig for backwards compatibility -// purposes. Use config.LoadConfig instead. -func LoadConfig(path string) (*DefaultConfig, error) { - conf, err := config.LoadConfig(path) - return (*DefaultConfig)(conf), err -} - -// ParseConfig parses the given configuration as a string. -// -// ParseConfig just calls into config.ParseConfig for backwards compatibility -// purposes. Use config.ParseConfig instead. -func ParseConfig(contents string) (*DefaultConfig, error) { - conf, err := config.ParseConfig(contents) - return (*DefaultConfig)(conf), err -} diff --git a/vendor/github.com/hashicorp/vault/command/config/config.go b/vendor/github.com/hashicorp/vault/command/config/config.go index ebee11ecb..d9ed7b692 100644 --- a/vendor/github.com/hashicorp/vault/command/config/config.go +++ b/vendor/github.com/hashicorp/vault/command/config/config.go @@ -6,9 +6,9 @@ import ( "os" "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/hcl/hcl/ast" + "github.com/hashicorp/vault/helper/hclutil" "github.com/mitchellh/go-homedir" ) @@ -89,7 +89,7 @@ func ParseConfig(contents string) (*DefaultConfig, error) { valid := []string{ "token_helper", } - if err := checkHCLKeys(list, valid); err != nil { + if err := hclutil.CheckHCLKeys(list, valid); err != nil { return nil, err } @@ -99,30 +99,3 @@ func ParseConfig(contents string) (*DefaultConfig, error) { } return &c, nil } - -func checkHCLKeys(node ast.Node, valid []string) error { - var list *ast.ObjectList - switch n := node.(type) { - case *ast.ObjectList: - list = n - case *ast.ObjectType: - list = n.List - default: - return fmt.Errorf("cannot check HCL keys of type %T", n) - } - - validMap := make(map[string]struct{}, len(valid)) - for _, v := range valid { - validMap[v] = struct{}{} - } - - var result error - for _, item := range list.Items { - key := item.Keys[0].Token.Value().(string) - if _, ok := validMap[key]; !ok { - result = multierror.Append(result, fmt.Errorf("invalid key %q on line %d", key, item.Assign.Line)) - } - } - - return result -} diff --git a/vendor/github.com/hashicorp/vault/command/delete.go b/vendor/github.com/hashicorp/vault/command/delete.go deleted file mode 100644 index 221c5b72e..000000000 --- a/vendor/github.com/hashicorp/vault/command/delete.go +++ /dev/null @@ -1,98 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*DeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*DeleteCommand)(nil) - -type DeleteCommand struct { - *BaseCommand -} - -func (c *DeleteCommand) Synopsis() string { - return "Delete secrets and configuration" -} - -func (c *DeleteCommand) Help() string { - helpText := ` -Usage: vault delete [options] PATH - - Deletes secrets and configuration from Vault at the given path. The behavior - of "delete" is delegated to the backend corresponding to the given path. - - Remove data in the status secret backend: - - $ vault delete secret/my-secret - - Uninstall an encryption key in the transit backend: - - $ vault delete transit/keys/my-key - - Delete an IAM role: - - $ vault delete aws/roles/ops - - For a full list of examples and paths, please see the documentation that - corresponds to the secret backend in use. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *DeleteCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *DeleteCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *DeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *DeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - - secret, err := client.Logical().Delete(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error deleting %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - - c.UI.Info(fmt.Sprintf("Success! Data deleted (if it existed) at: %s", path)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/format.go b/vendor/github.com/hashicorp/vault/command/format.go deleted file mode 100644 index 2ef255663..000000000 --- a/vendor/github.com/hashicorp/vault/command/format.go +++ /dev/null @@ -1,380 +0,0 @@ -package command - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "sort" - "strings" - - "github.com/ghodss/yaml" - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/ryanuber/columnize" -) - -const ( - // hopeDelim is the delimiter to use when splitting columns. We call it a - // hopeDelim because we hope that it's never contained in a secret. - hopeDelim = "♨" -) - -type FormatOptions struct { - Format string -} - -func OutputSecret(ui cli.Ui, secret *api.Secret) int { - return outputWithFormat(ui, secret, secret) -} - -func OutputList(ui cli.Ui, data interface{}) int { - switch data.(type) { - case *api.Secret: - secret := data.(*api.Secret) - return outputWithFormat(ui, secret, secret.Data["keys"]) - default: - return outputWithFormat(ui, nil, data) - } -} - -func OutputData(ui cli.Ui, data interface{}) int { - return outputWithFormat(ui, nil, data) -} - -func outputWithFormat(ui cli.Ui, secret *api.Secret, data interface{}) int { - format := Format(ui) - formatter, ok := Formatters[format] - if !ok { - ui.Error(fmt.Sprintf("Invalid output format: %s", format)) - return 1 - } - - if err := formatter.Output(ui, secret, data); err != nil { - ui.Error(fmt.Sprintf("Could not parse output: %s", err.Error())) - return 1 - } - return 0 -} - -type Formatter interface { - Output(ui cli.Ui, secret *api.Secret, data interface{}) error - Format(data interface{}) ([]byte, error) -} - -var Formatters = map[string]Formatter{ - "json": JsonFormatter{}, - "table": TableFormatter{}, - "yaml": YamlFormatter{}, - "yml": YamlFormatter{}, -} - -func Format(ui cli.Ui) string { - switch ui.(type) { - case *VaultUI: - return ui.(*VaultUI).format - } - - format := os.Getenv(EnvVaultFormat) - if format == "" { - format = "table" - } - - return format -} - -// An output formatter for json output of an object -type JsonFormatter struct{} - -func (j JsonFormatter) Format(data interface{}) ([]byte, error) { - return json.MarshalIndent(data, "", " ") -} - -func (j JsonFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{}) error { - b, err := j.Format(data) - if err != nil { - return err - } - ui.Output(string(b)) - return nil -} - -// An output formatter for yaml output format of an object -type YamlFormatter struct{} - -func (y YamlFormatter) Format(data interface{}) ([]byte, error) { - return yaml.Marshal(data) -} - -func (y YamlFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{}) error { - b, err := y.Format(data) - if err == nil { - ui.Output(strings.TrimSpace(string(b))) - } - return err -} - -// An output formatter for table output of an object -type TableFormatter struct{} - -// We don't use this -func (t TableFormatter) Format(data interface{}) ([]byte, error) { - return nil, nil -} - -func (t TableFormatter) Output(ui cli.Ui, secret *api.Secret, data interface{}) error { - switch data.(type) { - case *api.Secret: - return t.OutputSecret(ui, secret) - case []interface{}: - return t.OutputList(ui, secret, data) - case []string: - return t.OutputList(ui, nil, data) - case map[string]interface{}: - t.OutputMap(ui, data.(map[string]interface{})) - return nil - default: - return errors.New("cannot use the table formatter for this type") - } -} - -func (t TableFormatter) OutputList(ui cli.Ui, secret *api.Secret, data interface{}) error { - t.printWarnings(ui, secret) - - switch data.(type) { - case []interface{}: - case []string: - ui.Output(tableOutput(data.([]string), nil)) - return nil - default: - return errors.New("error: table formatter cannot output list for this data type") - } - - list := data.([]interface{}) - - if len(list) > 0 { - keys := make([]string, len(list)) - for i, v := range list { - typed, ok := v.(string) - if !ok { - return fmt.Errorf("%v is not a string", v) - } - keys[i] = typed - } - sort.Strings(keys) - - // Prepend the header - keys = append([]string{"Keys"}, keys...) - - ui.Output(tableOutput(keys, &columnize.Config{ - Delim: hopeDelim, - })) - } - - return nil -} - -// printWarnings prints any warnings in the secret. -func (t TableFormatter) printWarnings(ui cli.Ui, secret *api.Secret) { - if secret != nil && len(secret.Warnings) > 0 { - ui.Warn("WARNING! The following warnings were returned from Vault:\n") - for _, warning := range secret.Warnings { - ui.Warn(wrapAtLengthWithPadding(fmt.Sprintf("* %s", warning), 2)) - ui.Warn("") - } - } -} - -func (t TableFormatter) OutputSecret(ui cli.Ui, secret *api.Secret) error { - if secret == nil { - return nil - } - - t.printWarnings(ui, secret) - - out := make([]string, 0, 8) - if secret.LeaseDuration > 0 { - if secret.LeaseID != "" { - out = append(out, fmt.Sprintf("lease_id %s %s", hopeDelim, secret.LeaseID)) - out = append(out, fmt.Sprintf("lease_duration %s %v", hopeDelim, humanDurationInt(secret.LeaseDuration))) - out = append(out, fmt.Sprintf("lease_renewable %s %t", hopeDelim, secret.Renewable)) - } else { - // This is probably the generic secret backend which has leases, but we - // print them as refresh_interval to reduce confusion. - out = append(out, fmt.Sprintf("refresh_interval %s %v", hopeDelim, humanDurationInt(secret.LeaseDuration))) - } - } - - if secret.Auth != nil { - out = append(out, fmt.Sprintf("token %s %s", hopeDelim, secret.Auth.ClientToken)) - out = append(out, fmt.Sprintf("token_accessor %s %s", hopeDelim, secret.Auth.Accessor)) - // If the lease duration is 0, it's likely a root token, so output the - // duration as "infinity" to clear things up. - if secret.Auth.LeaseDuration == 0 { - out = append(out, fmt.Sprintf("token_duration %s %s", hopeDelim, "∞")) - } else { - out = append(out, fmt.Sprintf("token_duration %s %v", hopeDelim, humanDurationInt(secret.Auth.LeaseDuration))) - } - out = append(out, fmt.Sprintf("token_renewable %s %t", hopeDelim, secret.Auth.Renewable)) - out = append(out, fmt.Sprintf("token_policies %s %q", hopeDelim, secret.Auth.TokenPolicies)) - out = append(out, fmt.Sprintf("identity_policies %s %q", hopeDelim, secret.Auth.IdentityPolicies)) - out = append(out, fmt.Sprintf("policies %s %q", hopeDelim, secret.Auth.Policies)) - for k, v := range secret.Auth.Metadata { - out = append(out, fmt.Sprintf("token_meta_%s %s %v", k, hopeDelim, v)) - } - } - - if secret.WrapInfo != nil { - out = append(out, fmt.Sprintf("wrapping_token: %s %s", hopeDelim, secret.WrapInfo.Token)) - out = append(out, fmt.Sprintf("wrapping_accessor: %s %s", hopeDelim, secret.WrapInfo.Accessor)) - out = append(out, fmt.Sprintf("wrapping_token_ttl: %s %v", hopeDelim, humanDurationInt(secret.WrapInfo.TTL))) - out = append(out, fmt.Sprintf("wrapping_token_creation_time: %s %s", hopeDelim, secret.WrapInfo.CreationTime.String())) - out = append(out, fmt.Sprintf("wrapping_token_creation_path: %s %s", hopeDelim, secret.WrapInfo.CreationPath)) - if secret.WrapInfo.WrappedAccessor != "" { - out = append(out, fmt.Sprintf("wrapped_accessor: %s %s", hopeDelim, secret.WrapInfo.WrappedAccessor)) - } - } - - if len(secret.Data) > 0 { - keys := make([]string, 0, len(secret.Data)) - for k := range secret.Data { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := secret.Data[k] - - // If the field "looks" like a TTL, print it as a time duration instead. - if k == "period" || strings.HasSuffix(k, "_period") || - k == "ttl" || strings.HasSuffix(k, "_ttl") || - k == "duration" || strings.HasSuffix(k, "_duration") || - k == "lease_max" || k == "ttl_max" { - - v = humanDurationInt(v) - } - - out = append(out, fmt.Sprintf("%s %s %v", k, hopeDelim, v)) - } - } - - // If we got this far and still don't have any data, there's nothing to print, - // sorry. - if len(out) == 0 { - return nil - } - - // Prepend the header - out = append([]string{"Key" + hopeDelim + "Value"}, out...) - - ui.Output(tableOutput(out, &columnize.Config{ - Delim: hopeDelim, - })) - return nil -} - -func (t TableFormatter) OutputMap(ui cli.Ui, data map[string]interface{}) { - out := make([]string, 0, len(data)+1) - if len(data) > 0 { - keys := make([]string, 0, len(data)) - for k := range data { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - out = append(out, fmt.Sprintf("%s %s %v", k, hopeDelim, data[k])) - } - } - - // If we got this far and still don't have any data, there's nothing to print, - // sorry. - if len(out) == 0 { - return - } - - // Prepend the header - out = append([]string{"Key" + hopeDelim + "Value"}, out...) - - ui.Output(tableOutput(out, &columnize.Config{ - Delim: hopeDelim, - })) -} - -// OutputSealStatus will print *api.SealStatusResponse in the CLI according to the format provided -func OutputSealStatus(ui cli.Ui, client *api.Client, status *api.SealStatusResponse) int { - switch Format(ui) { - case "table": - default: - return OutputData(ui, status) - } - - var sealPrefix string - if status.RecoverySeal { - sealPrefix = "Recovery " - } - - out := []string{} - out = append(out, "Key | Value") - out = append(out, fmt.Sprintf("%sSeal Type | %s", sealPrefix, status.Type)) - out = append(out, fmt.Sprintf("Sealed | %t", status.Sealed)) - out = append(out, fmt.Sprintf("Total %sShares | %d", sealPrefix, status.N)) - out = append(out, fmt.Sprintf("Threshold | %d", status.T)) - - if status.Sealed { - out = append(out, fmt.Sprintf("Unseal Progress | %d/%d", status.Progress, status.T)) - out = append(out, fmt.Sprintf("Unseal Nonce | %s", status.Nonce)) - } - - out = append(out, fmt.Sprintf("Version | %s", status.Version)) - - if status.ClusterName != "" && status.ClusterID != "" { - out = append(out, fmt.Sprintf("Cluster Name | %s", status.ClusterName)) - out = append(out, fmt.Sprintf("Cluster ID | %s", status.ClusterID)) - } - - // Mask the 'Vault is sealed' error, since this means HA is enabled, but that - // we cannot query for the leader since we are sealed. - leaderStatus, err := client.Sys().Leader() - if err != nil && strings.Contains(err.Error(), "Vault is sealed") { - leaderStatus = &api.LeaderResponse{HAEnabled: true} - err = nil - } - if err != nil { - ui.Error(fmt.Sprintf("Error checking leader status: %s", err)) - return 1 - } - - // Output if HA is enabled - out = append(out, fmt.Sprintf("HA Enabled | %t", leaderStatus.HAEnabled)) - if leaderStatus.HAEnabled { - mode := "sealed" - if !status.Sealed { - out = append(out, fmt.Sprintf("HA Cluster | %s", leaderStatus.LeaderClusterAddress)) - mode = "standby" - showLeaderAddr := false - if leaderStatus.IsSelf { - mode = "active" - } else { - if leaderStatus.LeaderAddress == "" { - leaderStatus.LeaderAddress = "" - } - showLeaderAddr = true - } - out = append(out, fmt.Sprintf("HA Mode | %s", mode)) - - // This is down here just to keep ordering consistent - if showLeaderAddr { - out = append(out, fmt.Sprintf("Active Node Address | %s", leaderStatus.LeaderAddress)) - } - - if leaderStatus.PerfStandby { - out = append(out, fmt.Sprintf("Performance Standby Node | %t", leaderStatus.PerfStandby)) - out = append(out, fmt.Sprintf("Performance Standby Last Remote WAL | %d", leaderStatus.PerfStandbyLastRemoteWAL)) - } - } - } - - ui.Output(tableOutput(out, nil)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/kv.go b/vendor/github.com/hashicorp/vault/command/kv.go deleted file mode 100644 index 3fa91c8c5..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv.go +++ /dev/null @@ -1,52 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*KVCommand)(nil) - -type KVCommand struct { - *BaseCommand -} - -func (c *KVCommand) Synopsis() string { - return "Interact with Vault's Key-Value storage" -} - -func (c *KVCommand) Help() string { - helpText := ` -Usage: vault kv [options] [args] - - This command has subcommands for interacting with Vault's key-value - store. Here are some simple examples, and more detailed examples are - available in the subcommands or the documentation. - - Create or update the key named "foo" in the "secret" mount with the value - "bar=baz": - - $ vault kv put secret/foo bar=baz - - Read this value back: - - $ vault kv get secret/foo - - Get metadata for the key: - - $ vault kv metadata get secret/foo - - Get a specific version of the key: - - $ vault kv get -version=1 secret/foo - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *KVCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_delete.go b/vendor/github.com/hashicorp/vault/command/kv_delete.go deleted file mode 100644 index 945b4c675..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_delete.go +++ /dev/null @@ -1,149 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVDeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*KVDeleteCommand)(nil) - -type KVDeleteCommand struct { - *BaseCommand - - flagVersions []string -} - -func (c *KVDeleteCommand) Synopsis() string { - return "Deletes versions in the KV store" -} - -func (c *KVDeleteCommand) Help() string { - helpText := ` -Usage: vault kv delete [options] PATH - - Deletes the data for the provided version and path in the key-value store. The - versioned data will not be fully removed, but marked as deleted and will no - longer be returned in normal get requests. - - To delete the latest version of the key "foo": - - $ vault kv delete secret/foo - - To delete version 3 of key foo: - - $ vault kv delete -versions=3 secret/foo - - To delete all versions and metadata, see the "vault kv metadata" subcommand. - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *KVDeleteCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - // Common Options - f := set.NewFlagSet("Common Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "versions", - Target: &c.flagVersions, - Default: nil, - Usage: `Specifies the version numbers to delete.`, - }) - - return set -} - -func (c *KVDeleteCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *KVDeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVDeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var secret *api.Secret - if v2 { - secret, err = c.deleteV2(path, mountPath, client) - } else { - secret, err = client.Logical().Delete(path) - } - - if err != nil { - c.UI.Error(fmt.Sprintf("Error deleting %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - - c.UI.Info(fmt.Sprintf("Success! Data deleted (if it existed) at: %s", path)) - return 0 -} - -func (c *KVDeleteCommand) deleteV2(path, mountPath string, client *api.Client) (*api.Secret, error) { - var err error - var secret *api.Secret - switch { - case len(c.flagVersions) > 0: - path = addPrefixToVKVPath(path, mountPath, "delete") - if err != nil { - return nil, err - } - - data := map[string]interface{}{ - "versions": kvParseVersionsFlags(c.flagVersions), - } - - secret, err = client.Logical().Write(path, data) - default: - - path = addPrefixToVKVPath(path, mountPath, "data") - if err != nil { - return nil, err - } - - secret, err = client.Logical().Delete(path) - } - - return secret, err -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_destroy.go b/vendor/github.com/hashicorp/vault/command/kv_destroy.go deleted file mode 100644 index 64ed284d1..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_destroy.go +++ /dev/null @@ -1,132 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVDestroyCommand)(nil) -var _ cli.CommandAutocomplete = (*KVDestroyCommand)(nil) - -type KVDestroyCommand struct { - *BaseCommand - - flagVersions []string -} - -func (c *KVDestroyCommand) Synopsis() string { - return "Permanently removes one or more versions in the KV store" -} - -func (c *KVDestroyCommand) Help() string { - helpText := ` -Usage: vault kv destroy [options] KEY - - Permanently removes the specified versions' data from the key-value store. If - no key exists at the path, no action is taken. - - To destroy version 3 of key foo: - - $ vault kv destroy -versions=3 secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVDestroyCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "versions", - Target: &c.flagVersions, - Default: nil, - Usage: `Specifies the version numbers to destroy.`, - }) - - return set -} - -func (c *KVDestroyCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVDestroyCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVDestroyCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - if len(c.flagVersions) == 0 { - c.UI.Error("No versions provided, use the \"-versions\" flag to specify the version to destroy.") - return 1 - } - var err error - path := sanitizePath(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - if !v2 { - c.UI.Error("Destroy not supported on KV Version 1") - return 1 - } - path = addPrefixToVKVPath(path, mountPath, "destroy") - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - data := map[string]interface{}{ - "versions": kvParseVersionsFlags(c.flagVersions), - } - - secret, err := client.Logical().Write(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_enable_versioning.go b/vendor/github.com/hashicorp/vault/command/kv_enable_versioning.go deleted file mode 100644 index 00fc74a72..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_enable_versioning.go +++ /dev/null @@ -1,89 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVEnableVersioningCommand)(nil) -var _ cli.CommandAutocomplete = (*KVEnableVersioningCommand)(nil) - -type KVEnableVersioningCommand struct { - *BaseCommand -} - -func (c *KVEnableVersioningCommand) Synopsis() string { - return "Turns on versioning for a KV store" -} - -func (c *KVEnableVersioningCommand) Help() string { - helpText := ` -Usage: vault kv enable-versions [options] KEY - - This command turns on versioning for the backend at the provided path. - - $ vault kv enable-versions secret - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVEnableVersioningCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - return set -} - -func (c *KVEnableVersioningCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVEnableVersioningCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVEnableVersioningCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Append a trailing slash to indicate it's a path in output - mountPath := ensureTrailingSlash(sanitizePath(args[0])) - - if err := client.Sys().TuneMount(mountPath, api.MountConfigInput{ - Options: map[string]string{ - "version": "2", - }, - }); err != nil { - c.UI.Error(fmt.Sprintf("Error tuning secrets engine %s: %s", mountPath, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Tuned the secrets engine at: %s", mountPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_get.go b/vendor/github.com/hashicorp/vault/command/kv_get.go deleted file mode 100644 index 2861ca82f..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_get.go +++ /dev/null @@ -1,184 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVGetCommand)(nil) -var _ cli.CommandAutocomplete = (*KVGetCommand)(nil) - -type KVGetCommand struct { - *BaseCommand - - flagVersion int -} - -func (c *KVGetCommand) Synopsis() string { - return "Retrieves data from the KV store" -} - -func (c *KVGetCommand) Help() string { - helpText := ` -Usage: vault kv get [options] KEY - - Retrieves the value from Vault's key-value store at the given key name. If no - key exists with that name, an error is returned. If a key exists with that - name but has no data, nothing is returned. - - $ vault kv get secret/foo - - To view the given key name at a specific version in time, specify the "-version" - flag: - - $ vault kv get -version=1 secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVGetCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Default: 0, - Usage: `If passed, the value at the version number will be returned.`, - }) - - return set -} - -func (c *KVGetCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVGetCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVGetCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var versionParam map[string]string - - if v2 { - path = addPrefixToVKVPath(path, mountPath, "data") - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if c.flagVersion > 0 { - versionParam = map[string]string{ - "version": fmt.Sprintf("%d", c.flagVersion), - } - } - } - - secret, err := kvReadRequest(client, path, versionParam) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - if c.flagField != "" { - if v2 { - // This is a v2, pass in the data field - if data, ok := secret.Data["data"]; ok && data != nil { - // If they requested a literal "data" see if they meant actual - // value or the data block itself - if c.flagField == "data" { - if dataMap, ok := data.(map[string]interface{}); ok { - if _, ok := dataMap["data"]; ok { - return PrintRawField(c.UI, dataMap, c.flagField) - } - } - return PrintRawField(c.UI, secret, c.flagField) - } - return PrintRawField(c.UI, data, c.flagField) - } else { - c.UI.Error(fmt.Sprintf("No data found at %s", path)) - return 2 - } - } else { - return PrintRawField(c.UI, secret, c.flagField) - } - } - - // If we have wrap info print the secret normally. - if secret.WrapInfo != nil || c.flagFormat != "table" { - return OutputSecret(c.UI, secret) - } - - if len(secret.Warnings) > 0 { - tf := TableFormatter{} - tf.printWarnings(c.UI, secret) - } - - if metadata, ok := secret.Data["metadata"]; ok && metadata != nil { - c.UI.Info(getHeaderForMap("Metadata", metadata.(map[string]interface{}))) - OutputData(c.UI, metadata) - c.UI.Info("") - } - - data := secret.Data - if v2 && data != nil { - data = nil - dataRaw := secret.Data["data"] - if dataRaw != nil { - data = dataRaw.(map[string]interface{}) - } - } - - if data != nil { - c.UI.Info(getHeaderForMap("Data", data)) - OutputData(c.UI, data) - } - - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_helpers.go b/vendor/github.com/hashicorp/vault/command/kv_helpers.go deleted file mode 100644 index 2ed1d9739..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_helpers.go +++ /dev/null @@ -1,145 +0,0 @@ -package command - -import ( - "fmt" - "io" - "path" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/strutil" -) - -func kvReadRequest(client *api.Client, path string, params map[string]string) (*api.Secret, error) { - r := client.NewRequest("GET", "/v1/"+path) - for k, v := range params { - r.Params.Set(k, v) - } - resp, err := client.RawRequest(r) - if resp != nil { - defer resp.Body.Close() - } - if resp != nil && resp.StatusCode == 404 { - secret, parseErr := api.ParseSecret(resp.Body) - switch parseErr { - case nil: - case io.EOF: - return nil, nil - default: - return nil, err - } - if secret != nil && (len(secret.Warnings) > 0 || len(secret.Data) > 0) { - return secret, nil - } - return nil, nil - } - if err != nil { - return nil, err - } - - return api.ParseSecret(resp.Body) -} - -func kvPreflightVersionRequest(client *api.Client, path string) (string, int, error) { - // We don't want to use a wrapping call here so save any custom value and - // restore after - currentWrappingLookupFunc := client.CurrentWrappingLookupFunc() - client.SetWrappingLookupFunc(nil) - defer client.SetWrappingLookupFunc(currentWrappingLookupFunc) - - r := client.NewRequest("GET", "/v1/sys/internal/ui/mounts/"+path) - resp, err := client.RawRequest(r) - if resp != nil { - defer resp.Body.Close() - } - if err != nil { - // If we get a 404 we are using an older version of vault, default to - // version 1 - if resp != nil && resp.StatusCode == 404 { - return "", 1, nil - } - - return "", 0, err - } - - secret, err := api.ParseSecret(resp.Body) - if err != nil { - return "", 0, err - } - var mountPath string - if mountPathRaw, ok := secret.Data["path"]; ok { - mountPath = mountPathRaw.(string) - } - options := secret.Data["options"] - if options == nil { - return mountPath, 1, nil - } - versionRaw := options.(map[string]interface{})["version"] - if versionRaw == nil { - return mountPath, 1, nil - } - version := versionRaw.(string) - switch version { - case "", "1": - return mountPath, 1, nil - case "2": - return mountPath, 2, nil - } - - return mountPath, 1, nil -} - -func isKVv2(path string, client *api.Client) (string, bool, error) { - mountPath, version, err := kvPreflightVersionRequest(client, path) - if err != nil { - return "", false, err - } - - return mountPath, version == 2, nil -} - -func addPrefixToVKVPath(p, mountPath, apiPrefix string) string { - switch { - case p == mountPath, p == strings.TrimSuffix(mountPath, "/"): - return path.Join(mountPath, apiPrefix) - default: - p = strings.TrimPrefix(p, mountPath) - return path.Join(mountPath, apiPrefix, p) - } -} - -func getHeaderForMap(header string, data map[string]interface{}) string { - maxKey := 0 - for k := range data { - if len(k) > maxKey { - maxKey = len(k) - } - } - - // 4 for the column spaces and 5 for the len("value") - totalLen := maxKey + 4 + 5 - - equalSigns := totalLen - (len(header) + 2) - - // If we have zero or fewer equal signs bump it back up to two on either - // side of the header. - if equalSigns <= 0 { - equalSigns = 4 - } - - // If the number of equal signs is not divisible by two add a sign. - if equalSigns%2 != 0 { - equalSigns = equalSigns + 1 - } - - return fmt.Sprintf("%s %s %s", strings.Repeat("=", equalSigns/2), header, strings.Repeat("=", equalSigns/2)) -} - -func kvParseVersionsFlags(versions []string) []string { - versionsOut := make([]string, 0, len(versions)) - for _, v := range versions { - versionsOut = append(versionsOut, strutil.ParseStringSlice(v, ",")...) - } - - return versionsOut -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_list.go b/vendor/github.com/hashicorp/vault/command/kv_list.go deleted file mode 100644 index faedd6f3f..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_list.go +++ /dev/null @@ -1,112 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVListCommand)(nil) -var _ cli.CommandAutocomplete = (*KVListCommand)(nil) - -type KVListCommand struct { - *BaseCommand -} - -func (c *KVListCommand) Synopsis() string { - return "List data or secrets" -} - -func (c *KVListCommand) Help() string { - helpText := ` - -Usage: vault kv list [options] PATH - - Lists data from Vault's key-value store at the given path. - - List values under the "my-app" folder of the key-value store: - - $ vault kv list secret/my-app/ - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *KVListCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *KVListCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *KVListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := ensureTrailingSlash(sanitizePath(args[0])) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if v2 { - path = addPrefixToVKVPath(path, mountPath, "metadata") - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - } - - secret, err := client.Logical().List(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing %s: %s", path, err)) - return 2 - } - if secret == nil || secret.Data == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - // If the secret is wrapped, return the wrapped response. - if secret.WrapInfo != nil && secret.WrapInfo.TTL != 0 { - return OutputSecret(c.UI, secret) - } - - if _, ok := extractListData(secret); !ok { - c.UI.Error(fmt.Sprintf("No entries found at %s", path)) - return 2 - } - - return OutputList(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_metadata.go b/vendor/github.com/hashicorp/vault/command/kv_metadata.go deleted file mode 100644 index ee4dca938..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_metadata.go +++ /dev/null @@ -1,48 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*KVMetadataCommand)(nil) - -type KVMetadataCommand struct { - *BaseCommand -} - -func (c *KVMetadataCommand) Synopsis() string { - return "Interact with Vault's Key-Value storage" -} - -func (c *KVMetadataCommand) Help() string { - helpText := ` -Usage: vault kv metadata [options] [args] - - This command has subcommands for interacting with the metadata endpoint in - Vault's key-value store. Here are some simple examples, and more detailed - examples are available in the subcommands or the documentation. - - Create or update a metadata entry for a key: - - $ vault kv metadata put -max-versions=5 secret/foo - - Get the metadata for a key, this provides information about each existing - version: - - $ vault kv metadata get secret/foo - - Delete a key and all existing versions: - - $ vault kv metadata delete secret/foo - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *KVMetadataCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_metadata_delete.go b/vendor/github.com/hashicorp/vault/command/kv_metadata_delete.go deleted file mode 100644 index 8ff3a5655..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_metadata_delete.go +++ /dev/null @@ -1,95 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVMetadataDeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*KVMetadataDeleteCommand)(nil) - -type KVMetadataDeleteCommand struct { - *BaseCommand -} - -func (c *KVMetadataDeleteCommand) Synopsis() string { - return "Deletes all versions and metadata for a key in the KV store" -} - -func (c *KVMetadataDeleteCommand) Help() string { - helpText := ` -Usage: vault kv metadata delete [options] PATH - - Deletes all versions and metadata for the provided key. - - $ vault kv metadata delete secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *KVMetadataDeleteCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *KVMetadataDeleteCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *KVMetadataDeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVMetadataDeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - if !v2 { - c.UI.Error("Metadata not supported on KV Version 1") - return 1 - } - - path = addPrefixToVKVPath(path, mountPath, "metadata") - if secret, err := client.Logical().Delete(path); err != nil { - c.UI.Error(fmt.Sprintf("Error deleting %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - - c.UI.Info(fmt.Sprintf("Success! Data deleted (if it existed) at: %s", path)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_metadata_get.go b/vendor/github.com/hashicorp/vault/command/kv_metadata_get.go deleted file mode 100644 index a9bfc77ea..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_metadata_get.go +++ /dev/null @@ -1,140 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strconv" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVMetadataGetCommand)(nil) -var _ cli.CommandAutocomplete = (*KVMetadataGetCommand)(nil) - -type KVMetadataGetCommand struct { - *BaseCommand -} - -func (c *KVMetadataGetCommand) Synopsis() string { - return "Retrieves key metadata from the KV store" -} - -func (c *KVMetadataGetCommand) Help() string { - helpText := ` -Usage: vault kv metadata get [options] KEY - - Retrieves the metadata from Vault's key-value store at the given key name. If no - key exists with that name, an error is returned. - - $ vault kv metadata get secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVMetadataGetCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - return set -} - -func (c *KVMetadataGetCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVMetadataGetCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVMetadataGetCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - if !v2 { - c.UI.Error("Metadata not supported on KV Version 1") - return 1 - } - - path = addPrefixToVKVPath(path, mountPath, "metadata") - secret, err := client.Logical().Read(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading %s: %s", path, err)) - return 2 - } - if secret == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - // If we have wrap info print the secret normally. - if secret.WrapInfo != nil || c.flagFormat != "table" { - return OutputSecret(c.UI, secret) - } - - versionsRaw, ok := secret.Data["versions"] - if !ok || versionsRaw == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - OutputSecret(c.UI, secret) - return 2 - } - versions := versionsRaw.(map[string]interface{}) - - delete(secret.Data, "versions") - - c.UI.Info(getHeaderForMap("Metadata", secret.Data)) - OutputSecret(c.UI, secret) - - versionKeys := []int{} - for k := range versions { - i, err := strconv.Atoi(k) - if err != nil { - c.UI.Error(fmt.Sprintf("Error parsing version %s", k)) - return 2 - } - - versionKeys = append(versionKeys, i) - } - - sort.Ints(versionKeys) - - for _, v := range versionKeys { - c.UI.Info("\n" + getHeaderForMap(fmt.Sprintf("Version %d", v), versions[strconv.Itoa(v)].(map[string]interface{}))) - OutputData(c.UI, versions[strconv.Itoa(v)]) - } - - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_metadata_put.go b/vendor/github.com/hashicorp/vault/command/kv_metadata_put.go deleted file mode 100644 index 77d82b0d4..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_metadata_put.go +++ /dev/null @@ -1,142 +0,0 @@ -package command - -import ( - "fmt" - "io" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVMetadataPutCommand)(nil) -var _ cli.CommandAutocomplete = (*KVMetadataPutCommand)(nil) - -type KVMetadataPutCommand struct { - *BaseCommand - - flagMaxVersions int - flagCASRequired bool - testStdin io.Reader // for tests -} - -func (c *KVMetadataPutCommand) Synopsis() string { - return "Sets or updates key settings in the KV store" -} - -func (c *KVMetadataPutCommand) Help() string { - helpText := ` -Usage: vault metadata kv put [options] KEY - - This command can be used to create a blank key in the key-value store or to - update key configuration for a specified key. - - Create a key in the key-value store with no data: - - $ vault kv metadata put secret/foo - - Set a max versions setting on the key: - - $ vault kv metadata put -max-versions=5 secret/foo - - Require Check-and-Set for this key: - - $ vault kv metadata put -require-cas secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVMetadataPutCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.IntVar(&IntVar{ - Name: "max-versions", - Target: &c.flagMaxVersions, - Default: 0, - Usage: `The number of versions to keep. If not set, the backend’s configured max version is used.`, - }) - - f.BoolVar(&BoolVar{ - Name: "cas-required", - Target: &c.flagCASRequired, - Default: false, - Usage: `If true the key will require the cas parameter to be set on all write requests. If false, the backend’s configuration will be used.`, - }) - - return set -} - -func (c *KVMetadataPutCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVMetadataPutCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVMetadataPutCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - if !v2 { - c.UI.Error("Metadata not supported on KV Version 1") - return 1 - } - - path = addPrefixToVKVPath(path, mountPath, "metadata") - data := map[string]interface{}{ - "max_versions": c.flagMaxVersions, - "cas_required": c.flagCASRequired, - } - - secret, err := client.Logical().Write(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_patch.go b/vendor/github.com/hashicorp/vault/command/kv_patch.go deleted file mode 100644 index f8009ae1b..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_patch.go +++ /dev/null @@ -1,195 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVPatchCommand)(nil) -var _ cli.CommandAutocomplete = (*KVPatchCommand)(nil) - -type KVPatchCommand struct { - *BaseCommand - - testStdin io.Reader // for tests -} - -func (c *KVPatchCommand) Synopsis() string { - return "Sets or updates data in the KV store without overwriting" -} - -func (c *KVPatchCommand) Help() string { - helpText := ` -Usage: vault kv patch [options] KEY [DATA] - - *NOTE*: This is only supported for KV v2 engine mounts. - - Writes the data to the given path in the key-value store. The data can be of - any type. - - $ vault kv patch secret/foo bar=baz - - The data can also be consumed from a file on disk by prefixing with the "@" - symbol. For example: - - $ vault kv patch secret/foo @data.json - - Or it can be read from stdin using the "-" symbol: - - $ echo "abcd1234" | vault kv patch secret/foo bar=- - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVPatchCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - return set -} - -func (c *KVPatchCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVPatchCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVPatchCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected >1, got %d)", len(args))) - return 1 - case len(args) == 1: - c.UI.Error("Must supply data") - return 1 - } - - var err error - path := sanitizePath(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - newData, err := parseArgsData(stdin, args[1:]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse K=V data: %s", err)) - return 1 - } - - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if !v2 { - c.UI.Error(fmt.Sprintf("K/V engine mount must be version 2 for patch support")) - return 2 - } - - path = addPrefixToVKVPath(path, mountPath, "data") - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // First, do a read - secret, err := kvReadRequest(client, path, nil) - if err != nil { - c.UI.Error(fmt.Sprintf("Error doing pre-read at %s: %s", path, err)) - return 2 - } - - // Make sure a value already exists - if secret == nil || secret.Data == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - // Verify metadata found - rawMeta, ok := secret.Data["metadata"] - if !ok || rawMeta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; patch only works on existing data", path)) - return 2 - } - meta, ok := rawMeta.(map[string]interface{}) - if !ok { - c.UI.Error(fmt.Sprintf("Metadata found at %s is not the expected type (JSON object)", path)) - return 2 - } - if meta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; patch only works on existing data", path)) - return 2 - } - - // Verify old data found - rawData, ok := secret.Data["data"] - if !ok || rawData == nil { - c.UI.Error(fmt.Sprintf("No data found at %s; patch only works on existing data", path)) - return 2 - } - data, ok := rawData.(map[string]interface{}) - if !ok { - c.UI.Error(fmt.Sprintf("Data found at %s is not the expected type (JSON object)", path)) - return 2 - } - if data == nil { - c.UI.Error(fmt.Sprintf("No data found at %s; patch only works on existing data", path)) - return 2 - } - - // Copy new data over - for k, v := range newData { - data[k] = v - } - - secret, err = client.Logical().Write(path, map[string]interface{}{ - "data": data, - "options": map[string]interface{}{ - "cas": meta["version"], - }, - }) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_put.go b/vendor/github.com/hashicorp/vault/command/kv_put.go deleted file mode 100644 index b4ba76aaf..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_put.go +++ /dev/null @@ -1,163 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVPutCommand)(nil) -var _ cli.CommandAutocomplete = (*KVPutCommand)(nil) - -type KVPutCommand struct { - *BaseCommand - - flagCAS int - testStdin io.Reader // for tests -} - -func (c *KVPutCommand) Synopsis() string { - return "Sets or updates data in the KV store" -} - -func (c *KVPutCommand) Help() string { - helpText := ` -Usage: vault kv put [options] KEY [DATA] - - Writes the data to the given path in the key-value store. The data can be of - any type. - - $ vault kv put secret/foo bar=baz - - The data can also be consumed from a file on disk by prefixing with the "@" - symbol. For example: - - $ vault kv put secret/foo @data.json - - Or it can be read from stdin using the "-" symbol: - - $ echo "abcd1234" | vault kv put secret/foo bar=- - - To perform a Check-And-Set operation, specify the -cas flag with the - appropriate version number corresponding to the key you want to perform - the CAS operation on: - - $ vault kv put -cas=1 secret/foo bar=baz - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVPutCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.IntVar(&IntVar{ - Name: "cas", - Target: &c.flagCAS, - Default: -1, - Usage: `Specifies to use a Check-And-Set operation. If not set the write - will be allowed. If set to 0 a write will only be allowed if the key - doesn’t exist. If the index is non-zero the write will only be allowed - if the key’s current version matches the version specified in the cas - parameter.`, - }) - - return set -} - -func (c *KVPutCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVPutCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVPutCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected >1, got %d)", len(args))) - return 1 - case len(args) == 1: - c.UI.Error("Must supply data") - return 1 - } - - var err error - path := sanitizePath(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - data, err := parseArgsData(stdin, args[1:]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse K=V data: %s", err)) - return 1 - } - - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if v2 { - path = addPrefixToVKVPath(path, mountPath, "data") - data = map[string]interface{}{ - "data": data, - "options": map[string]interface{}{}, - } - - if c.flagCAS > -1 { - data["options"].(map[string]interface{})["cas"] = c.flagCAS - } - } - - secret, err := client.Logical().Write(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_rollback.go b/vendor/github.com/hashicorp/vault/command/kv_rollback.go deleted file mode 100644 index e050aaeb3..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_rollback.go +++ /dev/null @@ -1,243 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVRollbackCommand)(nil) -var _ cli.CommandAutocomplete = (*KVRollbackCommand)(nil) - -type KVRollbackCommand struct { - *BaseCommand - - flagVersion int -} - -func (c *KVRollbackCommand) Synopsis() string { - return "Rolls back to a previous version of data" -} - -func (c *KVRollbackCommand) Help() string { - helpText := ` -Usage: vault kv rollback [options] KEY - - *NOTE*: This is only supported for KV v2 engine mounts. - - Restores a given previous version to the current version at the given path. - The value is written as a new version; for instance, if the current version - is 5 and the rollback version is 2, the data from version 2 will become - version 6. - - $ vault kv rollback -version=2 secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVRollbackCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Usage: `Specifies the version number that should be made current again.`, - }) - - return set -} - -func (c *KVRollbackCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVRollbackCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVRollbackCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - var version *int - f.Visit(func(fl *flag.Flag) { - if fl.Name == "version" { - version = &c.flagVersion - } - }) - - args = f.Args() - - switch { - case len(args) != 1: - c.UI.Error(fmt.Sprintf("Invalid number of arguments (expected 1, got %d)", len(args))) - return 1 - case version == nil: - c.UI.Error(fmt.Sprintf("Version flag must be specified")) - return 1 - case c.flagVersion <= 0: - c.UI.Error(fmt.Sprintf("Invalid value %d for the version flag", c.flagVersion)) - return 1 - } - - var err error - path := sanitizePath(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if !v2 { - c.UI.Error(fmt.Sprintf("K/V engine mount must be version 2 for rollback support")) - return 2 - } - - path = addPrefixToVKVPath(path, mountPath, "data") - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // First, do a read to get the current version for check-and-set - var meta map[string]interface{} - { - secret, err := kvReadRequest(client, path, nil) - if err != nil { - c.UI.Error(fmt.Sprintf("Error doing pre-read at %s: %s", path, err)) - return 2 - } - - // Make sure a value already exists - if secret == nil || secret.Data == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - // Verify metadata found - rawMeta, ok := secret.Data["metadata"] - if !ok || rawMeta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; rollback only works on existing data", path)) - return 2 - } - meta, ok = rawMeta.(map[string]interface{}) - if !ok { - c.UI.Error(fmt.Sprintf("Metadata found at %s is not the expected type (JSON object)", path)) - return 2 - } - if meta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; rollback only works on existing data", path)) - return 2 - } - } - - casVersion := meta["version"] - - // Set the version parameter - versionParam := map[string]string{ - "version": fmt.Sprintf("%d", c.flagVersion), - } - - // Now run it again and read the version we want to roll back to - var data map[string]interface{} - { - secret, err := kvReadRequest(client, path, versionParam) - if err != nil { - c.UI.Error(fmt.Sprintf("Error doing pre-read at %s: %s", path, err)) - return 2 - } - - // Make sure a value already exists - if secret == nil || secret.Data == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - // Verify metadata found - rawMeta, ok := secret.Data["metadata"] - if !ok || rawMeta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; rollback only works on existing data", path)) - return 2 - } - meta, ok := rawMeta.(map[string]interface{}) - if !ok { - c.UI.Error(fmt.Sprintf("Metadata found at %s is not the expected type (JSON object)", path)) - return 2 - } - if meta == nil { - c.UI.Error(fmt.Sprintf("No metadata found at %s; rollback only works on existing data", path)) - return 2 - } - - // Verify it hasn't been deleted - if meta["deletion_time"] != nil && meta["deletion_time"].(string) != "" { - c.UI.Error(fmt.Sprintf("Cannot roll back to a version that has been deleted")) - return 2 - } - - if meta["destroyed"] != nil && meta["destroyed"].(bool) { - c.UI.Error(fmt.Sprintf("Cannot roll back to a version that has been destroyed")) - return 2 - } - - // Verify old data found - rawData, ok := secret.Data["data"] - if !ok || rawData == nil { - c.UI.Error(fmt.Sprintf("No data found at %s; rollback only works on existing data", path)) - return 2 - } - data, ok = rawData.(map[string]interface{}) - if !ok { - c.UI.Error(fmt.Sprintf("Data found at %s is not the expected type (JSON object)", path)) - return 2 - } - if data == nil { - c.UI.Error(fmt.Sprintf("No data found at %s; rollback only works on existing data", path)) - return 2 - } - } - - secret, err := client.Logical().Write(path, map[string]interface{}{ - "data": data, - "options": map[string]interface{}{ - "cas": casVersion, - }, - }) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/kv_undelete.go b/vendor/github.com/hashicorp/vault/command/kv_undelete.go deleted file mode 100644 index 7c11e8ce5..000000000 --- a/vendor/github.com/hashicorp/vault/command/kv_undelete.go +++ /dev/null @@ -1,127 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*KVUndeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*KVUndeleteCommand)(nil) - -type KVUndeleteCommand struct { - *BaseCommand - - flagVersions []string -} - -func (c *KVUndeleteCommand) Synopsis() string { - return "Undeletes versions in the KV store" -} - -func (c *KVUndeleteCommand) Help() string { - helpText := ` -Usage: vault kv undelete [options] KEY - - Undeletes the data for the provided version and path in the key-value store. - This restores the data, allowing it to be returned on get requests. - - To undelete version 3 of key "foo": - - $ vault kv undelete -versions=3 secret/foo - - Additional flags and more advanced use cases are detailed below. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *KVUndeleteCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "versions", - Target: &c.flagVersions, - Default: nil, - Usage: `Specifies the version numbers to undelete.`, - }) - - return set -} - -func (c *KVUndeleteCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *KVUndeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *KVUndeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - if len(c.flagVersions) == 0 { - c.UI.Error("No versions provided, use the \"-versions\" flag to specify the version to undelete.") - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - mountPath, v2, err := isKVv2(path, client) - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - if !v2 { - c.UI.Error("Undelete not supported on KV Version 1") - return 1 - } - - path = addPrefixToVKVPath(path, mountPath, "undelete") - data := map[string]interface{}{ - "versions": kvParseVersionsFlags(c.flagVersions), - } - - secret, err := client.Logical().Write(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/lease.go b/vendor/github.com/hashicorp/vault/command/lease.go deleted file mode 100644 index 76f6cc174..000000000 --- a/vendor/github.com/hashicorp/vault/command/lease.go +++ /dev/null @@ -1,40 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*LeaseCommand)(nil) - -type LeaseCommand struct { - *BaseCommand -} - -func (c *LeaseCommand) Synopsis() string { - return "Interact with leases" -} - -func (c *LeaseCommand) Help() string { - helpText := ` -Usage: vault lease [options] [args] - - This command groups subcommands for interacting with leases. Users can revoke - or renew leases. - - Renew a lease: - - $ vault lease renew database/creds/readonly/2f6a614c... - - Revoke a lease: - - $ vault lease revoke database/creds/readonly/2f6a614c... -` - - return strings.TrimSpace(helpText) -} - -func (c *LeaseCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/lease_renew.go b/vendor/github.com/hashicorp/vault/command/lease_renew.go deleted file mode 100644 index a13d91322..000000000 --- a/vendor/github.com/hashicorp/vault/command/lease_renew.go +++ /dev/null @@ -1,112 +0,0 @@ -package command - -import ( - "fmt" - "strings" - "time" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*LeaseRenewCommand)(nil) -var _ cli.CommandAutocomplete = (*LeaseRenewCommand)(nil) - -type LeaseRenewCommand struct { - *BaseCommand - - flagIncrement time.Duration -} - -func (c *LeaseRenewCommand) Synopsis() string { - return "Renews the lease of a secret" -} - -func (c *LeaseRenewCommand) Help() string { - helpText := ` -Usage: vault lease renew [options] ID - - Renews the lease on a secret, extending the time that it can be used before - it is revoked by Vault. - - Every secret in Vault has a lease associated with it. If the owner of the - secret wants to use it longer than the lease, then it must be renewed. - Renewing the lease does not change the contents of the secret. The ID is the - full path lease ID. - - Renew a secret: - - $ vault lease renew database/creds/readonly/2f6a614c... - - Lease renewal will fail if the secret is not renewable, the secret has already - been revoked, or if the secret has already reached its maximum TTL. - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *LeaseRenewCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - f := set.NewFlagSet("Command Options") - - f.DurationVar(&DurationVar{ - Name: "increment", - Target: &c.flagIncrement, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Request a specific increment in seconds. Vault is not required " + - "to honor this request.", - }) - - return set -} - -func (c *LeaseRenewCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictAnything -} - -func (c *LeaseRenewCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *LeaseRenewCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - leaseID := "" - increment := c.flagIncrement - - args = f.Args() - switch len(args) { - case 0: - c.UI.Error("Missing ID!") - return 1 - case 1: - leaseID = strings.TrimSpace(args[0]) - default: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1-2, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Sys().Renew(leaseID, truncateToSeconds(increment)) - if err != nil { - c.UI.Error(fmt.Sprintf("Error renewing %s: %s", leaseID, err)) - return 2 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/lease_revoke.go b/vendor/github.com/hashicorp/vault/command/lease_revoke.go deleted file mode 100644 index 6077f053b..000000000 --- a/vendor/github.com/hashicorp/vault/command/lease_revoke.go +++ /dev/null @@ -1,176 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*LeaseRevokeCommand)(nil) -var _ cli.CommandAutocomplete = (*LeaseRevokeCommand)(nil) - -type LeaseRevokeCommand struct { - *BaseCommand - - flagForce bool - flagPrefix bool - flagSync bool -} - -func (c *LeaseRevokeCommand) Synopsis() string { - return "Revokes leases and secrets" -} - -func (c *LeaseRevokeCommand) Help() string { - helpText := ` -Usage: vault lease revoke [options] ID - - Revokes secrets by their lease ID. This command can revoke a single secret - or multiple secrets based on a path-matched prefix. - - The default behavior when not using -force is to revoke asynchronously; Vault - will queue the revocation and keep trying if it fails (including across - restarts). The -sync flag can be used to force a synchronous operation, but - it is then up to the caller to retry on failure. Force mode always operates - synchronously. - - Revoke a single lease: - - $ vault lease revoke database/creds/readonly/2f6a614c... - - Revoke all leases for a role: - - $ vault lease revoke -prefix aws/creds/deploy - - Force delete leases from Vault even if secret engine revocation fails: - - $ vault lease revoke -force -prefix consul/creds - - For a full list of examples and paths, please see the documentation that - corresponds to the secret engine in use. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *LeaseRevokeCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "force", - Aliases: []string{"f"}, - Target: &c.flagForce, - Default: false, - Usage: "Delete the lease from Vault even if the secret engine revocation " + - "fails. This is meant for recovery situations where the secret " + - "in the target secret engine was manually removed. If this flag is " + - "specified, -prefix is also required.", - }) - - f.BoolVar(&BoolVar{ - Name: "prefix", - Target: &c.flagPrefix, - Default: false, - Usage: "Treat the ID as a prefix instead of an exact lease ID. This can " + - "revoke multiple leases simultaneously.", - }) - - f.BoolVar(&BoolVar{ - Name: "sync", - Target: &c.flagSync, - Default: false, - Usage: "Force a synchronous operation; on failure it is up to the client " + - "to retry.", - }) - - return set -} - -func (c *LeaseRevokeCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *LeaseRevokeCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *LeaseRevokeCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - if c.flagForce && !c.flagPrefix { - c.UI.Error("Specifying -force requires also specifying -prefix") - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - leaseID := strings.TrimSpace(args[0]) - - revokeOpts := &api.RevokeOptions{ - LeaseID: leaseID, - Force: c.flagForce, - Prefix: c.flagPrefix, - Sync: c.flagSync, - } - - if c.flagForce { - c.UI.Warn(wrapAtLength("Warning! Force-removing leases can cause Vault " + - "to become out of sync with secret engines!")) - } - - err = client.Sys().RevokeWithOptions(revokeOpts) - if err != nil { - switch { - case c.flagForce: - c.UI.Error(fmt.Sprintf("Error force revoking leases with prefix %s: %s", leaseID, err)) - return 2 - case c.flagPrefix: - c.UI.Error(fmt.Sprintf("Error revoking leases with prefix %s: %s", leaseID, err)) - return 2 - default: - c.UI.Error(fmt.Sprintf("Error revoking lease %s: %s", leaseID, err)) - return 2 - } - } - - if c.flagForce { - c.UI.Output(fmt.Sprintf("Success! Force revoked any leases with prefix: %s", leaseID)) - return 0 - } - - if c.flagSync { - if c.flagPrefix { - c.UI.Output(fmt.Sprintf("Success! Revoked any leases with prefix: %s", leaseID)) - return 0 - } - c.UI.Output(fmt.Sprintf("Success! Revoked lease: %s", leaseID)) - return 0 - } - - c.UI.Output("All revocation operations queued successfully!") - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/list.go b/vendor/github.com/hashicorp/vault/command/list.go deleted file mode 100644 index 56762151a..000000000 --- a/vendor/github.com/hashicorp/vault/command/list.go +++ /dev/null @@ -1,106 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*ListCommand)(nil) -var _ cli.CommandAutocomplete = (*ListCommand)(nil) - -type ListCommand struct { - *BaseCommand -} - -func (c *ListCommand) Synopsis() string { - return "List data or secrets" -} - -func (c *ListCommand) Help() string { - helpText := ` - -Usage: vault list [options] PATH - - Lists data from Vault at the given path. This can be used to list keys in a, - given secret engine. - - List values under the "my-app" folder of the generic secret engine: - - $ vault list secret/my-app/ - - For a full list of examples and paths, please see the documentation that - corresponds to the secret engine in use. Not all engines support listing. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *ListCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *ListCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *ListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *ListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := ensureTrailingSlash(sanitizePath(args[0])) - - secret, err := client.Logical().List(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing %s: %s", path, err)) - return 2 - } - if secret == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - if secret.Data == nil { - // If secret wasn't nil, we have warnings, so output them anyways. We - // may also have non-keys info. - return OutputSecret(c.UI, secret) - } - - // If the secret is wrapped, return the wrapped response. - if secret.WrapInfo != nil && secret.WrapInfo.TTL != 0 { - return OutputSecret(c.UI, secret) - } - - if _, ok := extractListData(secret); !ok { - c.UI.Error(fmt.Sprintf("No entries found at %s", path)) - return 2 - } - - return OutputList(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/login.go b/vendor/github.com/hashicorp/vault/command/login.go deleted file mode 100644 index d9c2a3f52..000000000 --- a/vendor/github.com/hashicorp/vault/command/login.go +++ /dev/null @@ -1,401 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/posener/complete" -) - -// LoginHandler is the interface that any auth handlers must implement to enable -// auth via the CLI. -type LoginHandler interface { - Auth(*api.Client, map[string]string) (*api.Secret, error) - Help() string -} - -type LoginCommand struct { - *BaseCommand - - Handlers map[string]LoginHandler - - flagMethod string - flagPath string - flagNoStore bool - flagNoPrint bool - flagTokenOnly bool - - // Deprecations - // TODO: remove in 0.9.0 - flagNoVerify bool - - testStdin io.Reader // for tests -} - -func (c *LoginCommand) Synopsis() string { - return "Authenticate locally" -} - -func (c *LoginCommand) Help() string { - helpText := ` -Usage: vault login [options] [AUTH K=V...] - - Authenticates users or machines to Vault using the provided arguments. A - successful authentication results in a Vault token - conceptually similar to - a session token on a website. By default, this token is cached on the local - machine for future requests. - - The default auth method is "token". If not supplied via the CLI, - Vault will prompt for input. If the argument is "-", the values are read - from stdin. - - The -method flag allows using other auth methods, such as userpass, github, or - cert. For these, additional "K=V" pairs may be required. For example, to - authenticate to the userpass auth method: - - $ vault login -method=userpass username=my-username - - For more information about the list of configuration parameters available for - a given auth method, use the "vault auth help TYPE". You can also use "vault - auth list" to see the list of enabled auth methods. - - If an auth method is enabled at a non-standard path, the -method flag still - refers to the canonical type, but the -path flag refers to the enabled path. - If a github auth method was enabled at "github-ent", authenticate like this: - - $ vault login -method=github -path=github-prod - - If the authentication is requested with response wrapping (via -wrap-ttl), - the returned token is automatically unwrapped unless: - - - The -token-only flag is used, in which case this command will output - the wrapping token. - - - The -no-store flag is used, in which case this command will output the - details of the wrapping token. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *LoginCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.StringVar(&StringVar{ - Name: "method", - Target: &c.flagMethod, - Default: "token", - Completion: c.PredictVaultAvailableAuths(), - Usage: "Type of authentication to use such as \"userpass\" or " + - "\"ldap\". Note this corresponds to the TYPE, not the enabled path. " + - "Use -path to specify the path where the authentication is enabled.", - }) - - f.StringVar(&StringVar{ - Name: "path", - Target: &c.flagPath, - Default: "", - Completion: c.PredictVaultAuths(), - Usage: "Remote path in Vault where the auth method is enabled. " + - "This defaults to the TYPE of method (e.g. userpass -> userpass/).", - }) - - f.BoolVar(&BoolVar{ - Name: "no-store", - Target: &c.flagNoStore, - Default: false, - Usage: "Do not persist the token to the token helper (usually the " + - "local filesystem) after authentication for use in future requests. " + - "The token will only be displayed in the command output.", - }) - - f.BoolVar(&BoolVar{ - Name: "no-print", - Target: &c.flagNoPrint, - Default: false, - Usage: "Do not display the token. The token will be still be stored to the " + - "configured token helper.", - }) - - f.BoolVar(&BoolVar{ - Name: "token-only", - Target: &c.flagTokenOnly, - Default: false, - Usage: "Output only the token with no verification. This flag is a " + - "shortcut for \"-field=token -no-store\". Setting those flags to other " + - "values will have no affect.", - }) - - // Deprecations - // TODO: remove in 0.9.0 - f.BoolVar(&BoolVar{ - Name: "no-verify", - Target: &c.flagNoVerify, - Hidden: true, - Default: false, - Usage: "", - }) - - return set -} - -func (c *LoginCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *LoginCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *LoginCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - - // Deprecations - // TODO: remove in 0.10.0 - switch { - case c.flagNoVerify: - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -no-verify flag is deprecated. In the past, Vault " + - "performed a lookup on a token after authentication. This is no " + - "longer the case for all auth methods except \"token\". Vault will " + - "still attempt to perform a lookup when given a token directly " + - "because that is how it gets the list of policies, ttl, and other " + - "metadata. To disable this lookup, specify \"lookup=false\" as a " + - "configuration option to the token auth method, like this:")) - c.UI.Warn("") - c.UI.Warn(" $ vault auth token=ABCD lookup=false") - c.UI.Warn("") - c.UI.Warn("Or omit the token and Vault will prompt for it:") - c.UI.Warn("") - c.UI.Warn(" $ vault auth lookup=false") - c.UI.Warn(" Token (will be hidden): ...") - c.UI.Warn("") - c.UI.Warn(wrapAtLength( - "If you are not using token authentication, you can safely omit this " + - "flag. Vault will not perform a lookup after authentication.")) - c.UI.Warn("") - } - - // There's no point in passing this to other auth handlers... - if c.flagMethod == "token" { - args = append(args, "lookup=false") - } - } - - // Set the right flags if the user requested token-only - this overrides - // any previously configured values, as documented. - if c.flagTokenOnly { - c.flagNoStore = true - c.flagField = "token" - } - - if c.flagNoStore && c.flagNoPrint { - c.UI.Error(wrapAtLength( - "-no-store and -no-print cannot be used together")) - return 1 - } - - // Get the auth method - authMethod := sanitizePath(c.flagMethod) - if authMethod == "" { - authMethod = "token" - } - - // If no path is specified, we default the path to the method type - // or use the plugin name if it's a plugin - authPath := c.flagPath - if authPath == "" { - authPath = ensureTrailingSlash(authMethod) - } - - // Get the handler function - authHandler, ok := c.Handlers[authMethod] - if !ok { - c.UI.Error(wrapAtLength(fmt.Sprintf( - "Unknown auth method: %s. Use \"vault auth list\" to see the "+ - "complete list of auth methods. Additionally, some "+ - "auth methods are only available via the HTTP API.", - authMethod))) - return 1 - } - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - // If the user provided a token, pass it along to the auth provider. - if authMethod == "token" && len(args) > 0 && !strings.Contains(args[0], "=") { - args = append([]string{"token=" + args[0]}, args[1:]...) - } - - config, err := parseArgsDataString(stdin, args) - if err != nil { - c.UI.Error(fmt.Sprintf("Error parsing configuration: %s", err)) - return 1 - } - - // If the user did not specify a mount path, use the provided mount path. - if config["mount"] == "" && authPath != "" { - config["mount"] = authPath - } - - // Create the client - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Authenticate delegation to the auth handler - secret, err := authHandler.Auth(client, config) - if err != nil { - c.UI.Error(fmt.Sprintf("Error authenticating: %s", err)) - return 2 - } - - // Unset any previous token wrapping functionality. If the original request - // was for a wrapped token, we don't want future requests to be wrapped. - client.SetWrappingLookupFunc(func(string, string) string { return "" }) - - // Recursively extract the token, handling wrapping - unwrap := !c.flagTokenOnly && !c.flagNoStore - secret, isWrapped, err := c.extractToken(client, secret, unwrap) - if err != nil { - c.UI.Error(fmt.Sprintf("Error extracting token: %s", err)) - return 2 - } - if secret == nil { - c.UI.Error("Vault returned an empty secret") - return 2 - } - - // Handle special cases if the token was wrapped - if isWrapped { - if c.flagTokenOnly { - return PrintRawField(c.UI, secret, "wrapping_token") - } - if c.flagNoStore { - return OutputSecret(c.UI, secret) - } - } - - // If we got this far, verify we have authentication data before continuing - if secret.Auth == nil { - c.UI.Error(wrapAtLength( - "Vault returned a secret, but the secret has no authentication " + - "information attached. This should never happen and is likely a " + - "bug.")) - return 2 - } - - // Pull the token itself out, since we don't need the rest of the auth - // information anymore/. - token := secret.Auth.ClientToken - - if !c.flagNoStore { - // Grab the token helper so we can store - tokenHelper, err := c.TokenHelper() - if err != nil { - c.UI.Error(wrapAtLength(fmt.Sprintf( - "Error initializing token helper. Please verify that the token "+ - "helper is available and properly configured for your system. The "+ - "error was: %s", err))) - return 1 - } - - // Store the token in the local client - if err := tokenHelper.Store(token); err != nil { - c.UI.Error(fmt.Sprintf("Error storing token: %s", err)) - c.UI.Error(wrapAtLength( - "Authentication was successful, but the token was not persisted. The "+ - "resulting token is shown below for your records.") + "\n") - OutputSecret(c.UI, secret) - return 2 - } - - // Warn if the VAULT_TOKEN environment variable is set, as that will take - // precedence. We output as a warning, so piping should still work since it - // will be on a different stream. - if os.Getenv("VAULT_TOKEN") != "" { - c.UI.Warn(wrapAtLength("WARNING! The VAULT_TOKEN environment variable "+ - "is set! This takes precedence over the value set by this command. To "+ - "use the value set by this command, unset the VAULT_TOKEN environment "+ - "variable or set it to the token displayed below.") + "\n") - } - } else if !c.flagTokenOnly { - // If token-only the user knows it won't be stored, so don't warn - c.UI.Warn(wrapAtLength( - "The token was not stored in token helper. Set the VAULT_TOKEN "+ - "environment variable or pass the token below with each request to "+ - "Vault.") + "\n") - } - - if c.flagNoPrint { - return 0 - } - - // If the user requested a particular field, print that out now since we - // are likely piping to another process. - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - // Print some yay! text, but only in table mode. - if Format(c.UI) == "table" { - c.UI.Output(wrapAtLength( - "Success! You are now authenticated. The token information displayed "+ - "below is already stored in the token helper. You do NOT need to run "+ - "\"vault login\" again. Future Vault requests will automatically use "+ - "this token.") + "\n") - } - - return OutputSecret(c.UI, secret) -} - -// extractToken extracts the token from the given secret, automatically -// unwrapping responses and handling error conditions if unwrap is true. The -// result also returns whether it was a wrapped response that was not unwrapped. -func (c *LoginCommand) extractToken(client *api.Client, secret *api.Secret, unwrap bool) (*api.Secret, bool, error) { - switch { - case secret == nil: - return nil, false, fmt.Errorf("empty response from auth helper") - - case secret.Auth != nil: - return secret, false, nil - - case secret.WrapInfo != nil: - if secret.WrapInfo.WrappedAccessor == "" { - return nil, false, fmt.Errorf("wrapped response does not contain a token") - } - - if !unwrap { - return secret, true, nil - } - - client.SetToken(secret.WrapInfo.Token) - secret, err := client.Logical().Unwrap("") - if err != nil { - return nil, false, err - } - return c.extractToken(client, secret, unwrap) - - default: - return nil, false, fmt.Errorf("no auth or wrapping info in response") - } -} diff --git a/vendor/github.com/hashicorp/vault/command/main.go b/vendor/github.com/hashicorp/vault/command/main.go deleted file mode 100644 index cf9b0b777..000000000 --- a/vendor/github.com/hashicorp/vault/command/main.go +++ /dev/null @@ -1,236 +0,0 @@ -package command - -import ( - "bytes" - "fmt" - "io" - "os" - "sort" - "strings" - "text/tabwriter" - - "github.com/fatih/color" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/token" - colorable "github.com/mattn/go-colorable" - "github.com/mitchellh/cli" -) - -type VaultUI struct { - cli.Ui - format string -} - -// setupEnv parses args and may replace them and sets some env vars to known -// values based on format options -func setupEnv(args []string) (retArgs []string, format string) { - var nextArgFormat bool - - for _, arg := range args { - if nextArgFormat { - nextArgFormat = false - format = arg - continue - } - - if arg == "--" { - break - } - - if len(args) == 1 && (arg == "-v" || arg == "-version" || arg == "--version") { - args = []string{"version"} - break - } - - // Parse a given flag here, which overrides the env var - if strings.HasPrefix(arg, "--format=") { - format = strings.TrimPrefix(arg, "--format=") - } - if strings.HasPrefix(arg, "-format=") { - format = strings.TrimPrefix(arg, "-format=") - } - // For backwards compat, it could be specified without an equal sign - if arg == "-format" || arg == "--format" { - nextArgFormat = true - } - } - - envVaultFormat := os.Getenv(EnvVaultFormat) - // If we did not parse a value, fetch the env var - if format == "" && envVaultFormat != "" { - format = envVaultFormat - } - // Lowercase for consistency - format = strings.ToLower(format) - if format == "" { - format = "table" - } - - return args, format -} - -type RunOptions struct { - TokenHelper token.TokenHelper - Stdout io.Writer - Stderr io.Writer - Address string - Client *api.Client -} - -func Run(args []string) int { - return RunCustom(args, nil) -} - -// RunCustom allows passing in a base command template to pass to other -// commands. Currenty, this is only used for setting a custom token helper. -func RunCustom(args []string, runOpts *RunOptions) int { - if runOpts == nil { - runOpts = &RunOptions{} - } - - var format string - args, format = setupEnv(args) - - // Don't use color if disabled - useColor := true - if os.Getenv(EnvVaultCLINoColor) != "" || color.NoColor { - useColor = false - } - - if runOpts.Stdout == nil { - runOpts.Stdout = os.Stdout - } - if runOpts.Stderr == nil { - runOpts.Stderr = os.Stderr - } - - // Only use colored UI if stdout is a tty, and not disabled - if useColor && format == "table" { - if f, ok := runOpts.Stdout.(*os.File); ok { - runOpts.Stdout = colorable.NewColorable(f) - } - if f, ok := runOpts.Stderr.(*os.File); ok { - runOpts.Stderr = colorable.NewColorable(f) - } - } else { - runOpts.Stdout = colorable.NewNonColorable(runOpts.Stdout) - runOpts.Stderr = colorable.NewNonColorable(runOpts.Stderr) - } - - ui := &VaultUI{ - Ui: &cli.ColoredUi{ - ErrorColor: cli.UiColorRed, - WarnColor: cli.UiColorYellow, - Ui: &cli.BasicUi{ - Writer: runOpts.Stdout, - ErrorWriter: runOpts.Stderr, - }, - }, - format: format, - } - - serverCmdUi := &VaultUI{ - Ui: &cli.ColoredUi{ - ErrorColor: cli.UiColorRed, - WarnColor: cli.UiColorYellow, - Ui: &cli.BasicUi{ - Writer: runOpts.Stdout, - }, - }, - format: format, - } - - if _, ok := Formatters[format]; !ok { - ui.Error(fmt.Sprintf("Invalid output format: %s", format)) - return 1 - } - - initCommands(ui, serverCmdUi, runOpts) - - // Calculate hidden commands from the deprecated ones - hiddenCommands := make([]string, 0, len(DeprecatedCommands)+1) - for k := range DeprecatedCommands { - hiddenCommands = append(hiddenCommands, k) - } - hiddenCommands = append(hiddenCommands, "version") - - cli := &cli.CLI{ - Name: "vault", - Args: args, - Commands: Commands, - HelpFunc: groupedHelpFunc( - cli.BasicHelpFunc("vault"), - ), - HelpWriter: runOpts.Stderr, - HiddenCommands: hiddenCommands, - Autocomplete: true, - AutocompleteNoDefaultFlags: true, - } - - exitCode, err := cli.Run() - if err != nil { - fmt.Fprintf(runOpts.Stderr, "Error executing CLI: %s\n", err.Error()) - return 1 - } - - return exitCode -} - -var commonCommands = []string{ - "read", - "write", - "delete", - "list", - "login", - "agent", - "server", - "status", - "unwrap", -} - -func groupedHelpFunc(f cli.HelpFunc) cli.HelpFunc { - return func(commands map[string]cli.CommandFactory) string { - var b bytes.Buffer - tw := tabwriter.NewWriter(&b, 0, 2, 6, ' ', 0) - - fmt.Fprintf(tw, "Usage: vault [args]\n\n") - fmt.Fprintf(tw, "Common commands:\n") - for _, v := range commonCommands { - printCommand(tw, v, commands[v]) - } - - otherCommands := make([]string, 0, len(commands)) - for k := range commands { - found := false - for _, v := range commonCommands { - if k == v { - found = true - break - } - } - - if !found { - otherCommands = append(otherCommands, k) - } - } - sort.Strings(otherCommands) - - fmt.Fprintf(tw, "\n") - fmt.Fprintf(tw, "Other commands:\n") - for _, v := range otherCommands { - printCommand(tw, v, commands[v]) - } - - tw.Flush() - - return strings.TrimSpace(b.String()) - } -} - -func printCommand(w io.Writer, name string, cmdFn cli.CommandFactory) { - cmd, err := cmdFn() - if err != nil { - panic(fmt.Sprintf("failed to load %q command: %s", name, err)) - } - fmt.Fprintf(w, " %s\t%s\n", name, cmd.Synopsis()) -} diff --git a/vendor/github.com/hashicorp/vault/command/namespace.go b/vendor/github.com/hashicorp/vault/command/namespace.go deleted file mode 100644 index 8adfc66ef..000000000 --- a/vendor/github.com/hashicorp/vault/command/namespace.go +++ /dev/null @@ -1,51 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*NamespaceCommand)(nil) - -type NamespaceCommand struct { - *BaseCommand -} - -func (c *NamespaceCommand) Synopsis() string { - return "Interact with namespaces" -} - -func (c *NamespaceCommand) Help() string { - helpText := ` -Usage: vault namespace [options] [args] - - This command groups subcommands for interacting with Vault namespaces. - These subcommands operate in the context of the namespace that the - currently logged in token belongs to. - - List enabled child namespaces: - - $ vault namespace list - - Look up an existing namespace: - - $ vault namespace lookup - - Create a new namespace: - - $ vault namespace create - - Delete an existing namespace: - - $ vault namespace delete - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *NamespaceCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/namespace_create.go b/vendor/github.com/hashicorp/vault/command/namespace_create.go deleted file mode 100644 index 7fdff88d5..000000000 --- a/vendor/github.com/hashicorp/vault/command/namespace_create.go +++ /dev/null @@ -1,93 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*NamespaceCreateCommand)(nil) -var _ cli.CommandAutocomplete = (*NamespaceCreateCommand)(nil) - -type NamespaceCreateCommand struct { - *BaseCommand -} - -func (c *NamespaceCreateCommand) Synopsis() string { - return "Create a new namespace" -} - -func (c *NamespaceCreateCommand) Help() string { - helpText := ` -Usage: vault namespace create [options] PATH - - Create a child namespace. The namespace created will be relative to the - namespace provided in either the VAULT_NAMESPACE environment variable or - -namespace CLI flag. - - Create a child namespace (e.g. ns1/): - - $ vault namespace create ns1 - - Create a child namespace from a parent namespace (e.g. ns1/ns2/): - - $ vault namespace create -namespace=ns1 ns2 - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *NamespaceCreateCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) -} - -func (c *NamespaceCreateCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *NamespaceCreateCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *NamespaceCreateCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - namespacePath := strings.TrimSpace(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().Write("sys/namespaces/"+namespacePath, nil) - if err != nil { - c.UI.Error(fmt.Sprintf("Error creating namespace: %s", err)) - return 2 - } - - // Handle single field output - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/namespace_delete.go b/vendor/github.com/hashicorp/vault/command/namespace_delete.go deleted file mode 100644 index f0614adb8..000000000 --- a/vendor/github.com/hashicorp/vault/command/namespace_delete.go +++ /dev/null @@ -1,98 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*NamespaceDeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*NamespaceDeleteCommand)(nil) - -type NamespaceDeleteCommand struct { - *BaseCommand -} - -func (c *NamespaceDeleteCommand) Synopsis() string { - return "Delete an existing namespace" -} - -func (c *NamespaceDeleteCommand) Help() string { - helpText := ` -Usage: vault namespace delete [options] PATH - - Delete an existing namespace. The namespace deleted will be relative to the - namespace provided in either the VAULT_NAMESPACE environment variable or - -namespace CLI flag. - - Delete a namespace (e.g. ns1/): - - $ vault namespace delete ns1 - - Delete a namespace namespace from a parent namespace (e.g. ns1/ns2/): - - $ vault namespace create -namespace=ns1 ns2 - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *NamespaceDeleteCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *NamespaceDeleteCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *NamespaceDeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *NamespaceDeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - namespacePath := strings.TrimSpace(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().Delete("sys/namespaces/" + namespacePath) - if err != nil { - c.UI.Error(fmt.Sprintf("Error deleting namespace: %s", err)) - return 2 - } - - if secret != nil { - // Likely, we have warnings - return OutputSecret(c.UI, secret) - } - - if !strings.HasSuffix(namespacePath, "/") { - namespacePath = namespacePath + "/" - } - - c.UI.Output(fmt.Sprintf("Success! Namespace deleted at: %s", namespacePath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/namespace_list.go b/vendor/github.com/hashicorp/vault/command/namespace_list.go deleted file mode 100644 index 893e1a76e..000000000 --- a/vendor/github.com/hashicorp/vault/command/namespace_list.go +++ /dev/null @@ -1,94 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*NamespaceListCommand)(nil) -var _ cli.CommandAutocomplete = (*NamespaceListCommand)(nil) - -type NamespaceListCommand struct { - *BaseCommand -} - -func (c *NamespaceListCommand) Synopsis() string { - return "List child namespaces" -} - -func (c *NamespaceListCommand) Help() string { - helpText := ` -Usage: vault namespaces list [options] - - Lists the enabled child namespaces. - - List all enabled child namespaces: - - $ vault namespaces list - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *NamespaceListCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *NamespaceListCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *NamespaceListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *NamespaceListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().List("sys/namespaces") - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing namespaces: %s", err)) - return 2 - } - if secret == nil { - c.UI.Error(fmt.Sprintf("No namespaces found")) - return 2 - } - - // There could be e.g. warnings - if secret.Data == nil { - return OutputSecret(c.UI, secret) - } - - if secret.WrapInfo != nil && secret.WrapInfo.TTL != 0 { - return OutputSecret(c.UI, secret) - } - - if _, ok := extractListData(secret); !ok { - c.UI.Error(fmt.Sprintf("No entries found")) - return 2 - } - - return OutputList(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/namespace_lookup.go b/vendor/github.com/hashicorp/vault/command/namespace_lookup.go deleted file mode 100644 index 73f3ddc8d..000000000 --- a/vendor/github.com/hashicorp/vault/command/namespace_lookup.go +++ /dev/null @@ -1,92 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*NamespaceLookupCommand)(nil) -var _ cli.CommandAutocomplete = (*NamespaceLookupCommand)(nil) - -type NamespaceLookupCommand struct { - *BaseCommand -} - -func (c *NamespaceLookupCommand) Synopsis() string { - return "Look up an existing namespace" -} - -func (c *NamespaceLookupCommand) Help() string { - helpText := ` -Usage: vault namespace create [options] PATH - - Create a child namespace. The namespace created will be relative to the - namespace provided in either the VAULT_NAMESPACE environment variable or - -namespace CLI flag. - - Get information about the namespace of the locally authenticated token: - - $ vault namespace lookup - - Get information about the namespace of a particular child token (e.g. ns1/ns2/): - - $ vault namespace lookup -namespace=ns1 ns2 - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *NamespaceLookupCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *NamespaceLookupCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFolders() -} - -func (c *NamespaceLookupCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *NamespaceLookupCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - namespacePath := strings.TrimSpace(args[0]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().Read("sys/namespaces/" + namespacePath) - if err != nil { - c.UI.Error(fmt.Sprintf("Error looking up namespace: %s", err)) - return 2 - } - if secret == nil { - c.UI.Error("Namespace not found") - return 2 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/operator.go b/vendor/github.com/hashicorp/vault/command/operator.go deleted file mode 100644 index ad1bb439f..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator.go +++ /dev/null @@ -1,47 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*OperatorCommand)(nil) - -type OperatorCommand struct { - *BaseCommand -} - -func (c *OperatorCommand) Synopsis() string { - return "Perform operator-specific tasks" -} - -func (c *OperatorCommand) Help() string { - helpText := ` -Usage: vault operator [options] [args] - - This command groups subcommands for operators interacting with Vault. Most - users will not need to interact with these commands. Here are a few examples - of the operator commands: - - Initialize a new Vault cluster: - - $ vault operator init - - Force a Vault to resign leadership in a cluster: - - $ vault operator step-down - - Rotate Vault's underlying encryption key: - - $ vault operator rotate - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *OperatorCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_generate_root.go b/vendor/github.com/hashicorp/vault/command/operator_generate_root.go deleted file mode 100644 index a8f098c0a..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_generate_root.go +++ /dev/null @@ -1,541 +0,0 @@ -package command - -import ( - "bytes" - "crypto/rand" - "encoding/base64" - "fmt" - "io" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/base62" - "github.com/hashicorp/vault/helper/password" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/helper/xor" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorGenerateRootCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorGenerateRootCommand)(nil) - -type OperatorGenerateRootCommand struct { - *BaseCommand - - flagInit bool - flagCancel bool - flagStatus bool - flagDecode string - flagOTP string - flagPGPKey string - flagNonce string - flagGenerateOTP bool - flagDRToken bool - - // Deprecation - // TODO: remove in 0.9.0 - flagGenOTP bool - - testStdin io.Reader // for tests -} - -func (c *OperatorGenerateRootCommand) Synopsis() string { - return "Generates a new root token" -} - -func (c *OperatorGenerateRootCommand) Help() string { - helpText := ` -Usage: vault operator generate-root [options] [KEY] - - Generates a new root token by combining a quorum of share holders. One of - the following must be provided to start the root token generation: - - - A base64-encoded one-time-password (OTP) provided via the "-otp" flag. - Use the "-generate-otp" flag to generate a usable value. The resulting - token is XORed with this value when it is returned. Use the "-decode" - flag to output the final value. - - - A file containing a PGP key or a keybase username in the "-pgp-key" - flag. The resulting token is encrypted with this public key. - - An unseal key may be provided directly on the command line as an argument to - the command. If key is specified as "-", the command will read from stdin. If - a TTY is available, the command will prompt for text. - - Generate an OTP code for the final token: - - $ vault operator generate-root -generate-otp - - Start a root token generation: - - $ vault operator generate-root -init -otp="..." - $ vault operator generate-root -init -pgp-key="..." - - Enter an unseal key to progress root token generation: - - $ vault operator generate-root -otp="..." - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *OperatorGenerateRootCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "init", - Target: &c.flagInit, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Start a root token generation. This can only be done if " + - "there is not currently one in progress.", - }) - - f.BoolVar(&BoolVar{ - Name: "cancel", - Target: &c.flagCancel, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Reset the root token generation progress. This will discard any " + - "submitted unseal keys or configuration.", - }) - - f.BoolVar(&BoolVar{ - Name: "status", - Target: &c.flagStatus, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Print the status of the current attempt without providing an " + - "unseal key.", - }) - - f.StringVar(&StringVar{ - Name: "decode", - Target: &c.flagDecode, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "The value to decode; setting this triggers a decode operation.", - }) - - f.BoolVar(&BoolVar{ - Name: "generate-otp", - Target: &c.flagGenerateOTP, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Generate and print a high-entropy one-time-password (OTP) " + - "suitable for use with the \"-init\" flag.", - }) - - f.BoolVar(&BoolVar{ - Name: "dr-token", - Target: &c.flagDRToken, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Set this flag to do generate root operations on DR Operational " + - "tokens.", - }) - - f.StringVar(&StringVar{ - Name: "otp", - Target: &c.flagOTP, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "OTP code to use with \"-decode\" or \"-init\".", - }) - - f.VarFlag(&VarFlag{ - Name: "pgp-key", - Value: (*pgpkeys.PubKeyFileFlag)(&c.flagPGPKey), - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Path to a file on disk containing a binary or base64-encoded " + - "public GPG key. This can also be specified as a Keybase username " + - "using the format \"keybase:\". When supplied, the generated " + - "root token will be encrypted and base64-encoded with the given public " + - "key.", - }) - - f.StringVar(&StringVar{ - Name: "nonce", - Target: &c.flagNonce, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Nonce value provided at initialization. The same nonce value " + - "must be provided with each unseal key.", - }) - - // Deprecations: prefer longer-form, descriptive flags - // TODO: remove in 0.9.0 - f.BoolVar(&BoolVar{ - Name: "genotp", // -generate-otp - Target: &c.flagGenOTP, - Default: false, - Hidden: true, - }) - - return set -} - -func (c *OperatorGenerateRootCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorGenerateRootCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorGenerateRootCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 1 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0-1, got %d)", len(args))) - return 1 - } - - // Deprecations - // TODO: remove in 0.9.0 - switch { - case c.flagGenOTP: - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -gen-otp flag is deprecated. Please use the -generate-otp flag " + - "instead.")) - } - c.flagGenerateOTP = c.flagGenOTP - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - switch { - case c.flagGenerateOTP: - otp, code := c.generateOTP(client, c.flagDRToken) - if code == 0 { - return PrintRaw(c.UI, otp) - } - return code - case c.flagDecode != "": - return c.decode(client, c.flagDecode, c.flagOTP, c.flagDRToken) - case c.flagCancel: - return c.cancel(client, c.flagDRToken) - case c.flagInit: - return c.init(client, c.flagOTP, c.flagPGPKey, c.flagDRToken) - case c.flagStatus: - return c.status(client, c.flagDRToken) - default: - // If there are no other flags, prompt for an unseal key. - key := "" - if len(args) > 0 { - key = strings.TrimSpace(args[0]) - } - return c.provide(client, key, c.flagDRToken) - } -} - -// generateOTP generates a suitable OTP code for generating a root token. -func (c *OperatorGenerateRootCommand) generateOTP(client *api.Client, drToken bool) (string, int) { - f := client.Sys().GenerateRootStatus - if drToken { - f = client.Sys().GenerateDROperationTokenStatus - } - status, err := f() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting root generation status: %s", err)) - return "", 2 - } - - switch status.OTPLength { - case 0: - // This is the fallback case - buf := make([]byte, 16) - readLen, err := rand.Read(buf) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading random bytes: %s", err)) - return "", 2 - } - - if readLen != 16 { - c.UI.Error(fmt.Sprintf("Read %d bytes when we should have read 16", readLen)) - return "", 2 - } - - return base64.StdEncoding.EncodeToString(buf), 0 - - default: - otp, err := base62.Random(status.OTPLength, true) - if err != nil { - c.UI.Error(errwrap.Wrapf("Error reading random bytes: {{err}}", err).Error()) - return "", 2 - } - - return otp, 0 - } -} - -// decode decodes the given value using the otp. -func (c *OperatorGenerateRootCommand) decode(client *api.Client, encoded, otp string, drToken bool) int { - if encoded == "" { - c.UI.Error("Missing encoded value: use -decode= to supply it") - return 1 - } - if otp == "" { - c.UI.Error("Missing otp: use -otp to supply it") - return 1 - } - - f := client.Sys().GenerateRootStatus - if drToken { - f = client.Sys().GenerateDROperationTokenStatus - } - status, err := f() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting root generation status: %s", err)) - return 2 - } - - switch status.OTPLength { - case 0: - // Backwards compat - tokenBytes, err := xor.XORBase64(encoded, otp) - if err != nil { - c.UI.Error(fmt.Sprintf("Error xoring token: %s", err)) - return 1 - } - - token, err := uuid.FormatUUID(tokenBytes) - if err != nil { - c.UI.Error(fmt.Sprintf("Error formatting base64 token value: %s", err)) - return 1 - } - - return PrintRaw(c.UI, strings.TrimSpace(token)) - - default: - tokenBytes, err := base64.RawStdEncoding.DecodeString(encoded) - if err != nil { - c.UI.Error(errwrap.Wrapf("Error decoding base64'd token: {{err}}", err).Error()) - return 1 - } - - tokenBytes, err = xor.XORBytes(tokenBytes, []byte(otp)) - if err != nil { - c.UI.Error(errwrap.Wrapf("Error xoring token: {{err}}", err).Error()) - return 1 - } - - return PrintRaw(c.UI, string(tokenBytes)) - } -} - -// init is used to start the generation process -func (c *OperatorGenerateRootCommand) init(client *api.Client, otp, pgpKey string, drToken bool) int { - // Validate incoming fields. Either OTP OR PGP keys must be supplied. - if otp != "" && pgpKey != "" { - c.UI.Error("Error initializing: cannot specify both -otp and -pgp-key") - return 1 - } - - // Start the root generation - f := client.Sys().GenerateRootInit - if drToken { - f = client.Sys().GenerateDROperationTokenInit - } - status, err := f(otp, pgpKey) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing root generation: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - return c.printStatus(status) - default: - return OutputData(c.UI, status) - } -} - -// provide prompts the user for the seal key and posts it to the update root -// endpoint. If this is the last unseal, this function outputs it. -func (c *OperatorGenerateRootCommand) provide(client *api.Client, key string, drToken bool) int { - f := client.Sys().GenerateRootStatus - if drToken { - f = client.Sys().GenerateDROperationTokenStatus - } - status, err := f() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting root generation status: %s", err)) - return 2 - } - - // Verify a root token generation is in progress. If there is not one in - // progress, return an error instructing the user to start one. - if !status.Started { - c.UI.Error(wrapAtLength( - "No root generation is in progress. Start a root generation by " + - "running \"vault operator generate-root -init\".")) - c.UI.Warn(wrapAtLength(fmt.Sprintf( - "If starting root generation using the OTP method and generating "+ - "your own OTP, the length of the OTP string needs to be %d "+ - "characters in length.", status.OTPLength))) - return 1 - } - - var nonce string - - switch key { - case "-": // Read from stdin - nonce = c.flagNonce - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - var buf bytes.Buffer - if _, err := io.Copy(&buf, stdin); err != nil { - c.UI.Error(fmt.Sprintf("Failed to read from stdin: %s", err)) - return 1 - } - - key = buf.String() - case "": // Prompt using the tty - // Nonce value is not required if we are prompting via the terminal - nonce = status.Nonce - - w := getWriterFromUI(c.UI) - fmt.Fprintf(w, "Operation nonce: %s\n", nonce) - fmt.Fprintf(w, "Unseal Key (will be hidden): ") - key, err = password.Read(os.Stdin) - fmt.Fprintf(w, "\n") - if err != nil { - if err == password.ErrInterrupted { - c.UI.Error("user canceled") - return 1 - } - - c.UI.Error(wrapAtLength(fmt.Sprintf("An error occurred attempting to "+ - "ask for the unseal key. The raw error message is shown below, but "+ - "usually this is because you attempted to pipe a value into the "+ - "command or you are executing outside of a terminal (tty). If you "+ - "want to pipe the value, pass \"-\" as the argument to read from "+ - "stdin. The raw error was: %s", err))) - return 1 - } - default: // Supplied directly as an arg - nonce = c.flagNonce - } - - // Trim any whitespace from they key, especially since we might have prompted - // the user for it. - key = strings.TrimSpace(key) - - // Verify we have a nonce value - if nonce == "" { - c.UI.Error("Missing nonce value: specify it via the -nonce flag") - return 1 - } - - // Provide the key, this may potentially complete the update - fUpd := client.Sys().GenerateRootUpdate - if drToken { - fUpd = client.Sys().GenerateDROperationTokenUpdate - } - status, err = fUpd(key, nonce) - if err != nil { - c.UI.Error(fmt.Sprintf("Error posting unseal key: %s", err)) - return 2 - } - switch Format(c.UI) { - case "table": - return c.printStatus(status) - default: - return OutputData(c.UI, status) - } -} - -// cancel cancels the root token generation -func (c *OperatorGenerateRootCommand) cancel(client *api.Client, drToken bool) int { - f := client.Sys().GenerateRootCancel - if drToken { - f = client.Sys().GenerateDROperationTokenCancel - } - if err := f(); err != nil { - c.UI.Error(fmt.Sprintf("Error canceling root token generation: %s", err)) - return 2 - } - c.UI.Output("Success! Root token generation canceled (if it was started)") - return 0 -} - -// status is used just to fetch and dump the status -func (c *OperatorGenerateRootCommand) status(client *api.Client, drToken bool) int { - f := client.Sys().GenerateRootStatus - if drToken { - f = client.Sys().GenerateDROperationTokenStatus - } - status, err := f() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting root generation status: %s", err)) - return 2 - } - switch Format(c.UI) { - case "table": - return c.printStatus(status) - default: - return OutputData(c.UI, status) - } -} - -// printStatus dumps the status to output -func (c *OperatorGenerateRootCommand) printStatus(status *api.GenerateRootStatusResponse) int { - out := []string{} - out = append(out, fmt.Sprintf("Nonce | %s", status.Nonce)) - out = append(out, fmt.Sprintf("Started | %t", status.Started)) - out = append(out, fmt.Sprintf("Progress | %d/%d", status.Progress, status.Required)) - out = append(out, fmt.Sprintf("Complete | %t", status.Complete)) - if status.PGPFingerprint != "" { - out = append(out, fmt.Sprintf("PGP Fingerprint | %s", status.PGPFingerprint)) - } - switch { - case status.EncodedToken != "": - out = append(out, fmt.Sprintf("Encoded Token | %s", status.EncodedToken)) - case status.EncodedRootToken != "": - out = append(out, fmt.Sprintf("Encoded Root Token | %s", status.EncodedRootToken)) - } - if status.OTP != "" { - c.UI.Warn(wrapAtLength("A One-Time-Password has been generated for you and is shown in the OTP field. You will need this value to decode the resulting root token, so keep it safe.")) - out = append(out, fmt.Sprintf("OTP | %s", status.OTP)) - } - if status.OTPLength != 0 { - out = append(out, fmt.Sprintf("OTP Length | %d", status.OTPLength)) - } - - output := columnOutput(out, nil) - c.UI.Output(output) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_init.go b/vendor/github.com/hashicorp/vault/command/operator_init.go deleted file mode 100644 index 13ed30373..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_init.go +++ /dev/null @@ -1,571 +0,0 @@ -package command - -import ( - "fmt" - "net/url" - "runtime" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/mitchellh/cli" - "github.com/posener/complete" - - consulapi "github.com/hashicorp/consul/api" -) - -var _ cli.Command = (*OperatorInitCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorInitCommand)(nil) - -type OperatorInitCommand struct { - *BaseCommand - - flagStatus bool - flagKeyShares int - flagKeyThreshold int - flagPGPKeys []string - flagRootTokenPGPKey string - - // HSM - flagStoredShares int - flagRecoveryShares int - flagRecoveryThreshold int - flagRecoveryPGPKeys []string - - // Consul - flagConsulAuto bool - flagConsulService string - - // Deprecations - // TODO: remove in 0.9.0 - flagAuto bool - flagCheck bool -} - -func (c *OperatorInitCommand) Synopsis() string { - return "Initializes a server" -} - -func (c *OperatorInitCommand) Help() string { - helpText := ` -Usage: vault operator init [options] - - Initializes a Vault server. Initialization is the process by which Vault's - storage backend is prepared to receive data. Since Vault servers share the - same storage backend in HA mode, you only need to initialize one Vault to - initialize the storage backend. - - During initialization, Vault generates an in-memory master key and applies - Shamir's secret sharing algorithm to disassemble that master key into a - configuration number of key shares such that a configurable subset of those - key shares must come together to regenerate the master key. These keys are - often called "unseal keys" in Vault's documentation. - - This command cannot be run against already-initialized Vault cluster. - - Start initialization with the default options: - - $ vault operator init - - Initialize, but encrypt the unseal keys with pgp keys: - - $ vault operator init \ - -key-shares=3 \ - -key-threshold=2 \ - -pgp-keys="keybase:hashicorp,keybase:jefferai,keybase:sethvargo" - - Encrypt the initial root token using a pgp key: - - $ vault operator init -root-token-pgp-key="keybase:hashicorp" - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *OperatorInitCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - // Common Options - f := set.NewFlagSet("Common Options") - - f.BoolVar(&BoolVar{ - Name: "status", - Target: &c.flagStatus, - Default: false, - Usage: "Print the current initialization status. An exit code of 0 means " + - "the Vault is already initialized. An exit code of 1 means an error " + - "occurred. An exit code of 2 means the mean is not initialized.", - }) - - f.IntVar(&IntVar{ - Name: "key-shares", - Aliases: []string{"n"}, - Target: &c.flagKeyShares, - Default: 5, - Completion: complete.PredictAnything, - Usage: "Number of key shares to split the generated master key into. " + - "This is the number of \"unseal keys\" to generate.", - }) - - f.IntVar(&IntVar{ - Name: "key-threshold", - Aliases: []string{"t"}, - Target: &c.flagKeyThreshold, - Default: 3, - Completion: complete.PredictAnything, - Usage: "Number of key shares required to reconstruct the master key. " + - "This must be less than or equal to -key-shares.", - }) - - f.VarFlag(&VarFlag{ - Name: "pgp-keys", - Value: (*pgpkeys.PubKeyFilesFlag)(&c.flagPGPKeys), - Completion: complete.PredictAnything, - Usage: "Comma-separated list of paths to files on disk containing " + - "public GPG keys OR a comma-separated list of Keybase usernames using " + - "the format \"keybase:\". When supplied, the generated " + - "unseal keys will be encrypted and base64-encoded in the order " + - "specified in this list. The number of entries must match -key-shares, " + - "unless -store-shares are used.", - }) - - f.VarFlag(&VarFlag{ - Name: "root-token-pgp-key", - Value: (*pgpkeys.PubKeyFileFlag)(&c.flagRootTokenPGPKey), - Completion: complete.PredictAnything, - Usage: "Path to a file on disk containing a binary or base64-encoded " + - "public GPG key. This can also be specified as a Keybase username " + - "using the format \"keybase:\". When supplied, the generated " + - "root token will be encrypted and base64-encoded with the given public " + - "key.", - }) - - // Consul Options - f = set.NewFlagSet("Consul Options") - - f.BoolVar(&BoolVar{ - Name: "consul-auto", - Target: &c.flagConsulAuto, - Default: false, - Usage: "Perform automatic service discovery using Consul in HA mode. " + - "When all nodes in a Vault HA cluster are registered with Consul, " + - "enabling this option will trigger automatic service discovery based " + - "on the provided -consul-service value. When Consul is Vault's HA " + - "backend, this functionality is automatically enabled. Ensure the " + - "proper Consul environment variables are set (CONSUL_HTTP_ADDR, etc). " + - "When only one Vault server is discovered, it will be initialized " + - "automatically. When more than one Vault server is discovered, they " + - "will each be output for selection.", - }) - - f.StringVar(&StringVar{ - Name: "consul-service", - Target: &c.flagConsulService, - Default: "vault", - Completion: complete.PredictAnything, - Usage: "Name of the service in Consul under which the Vault servers are " + - "registered.", - }) - - // HSM Options - f = set.NewFlagSet("HSM Options") - - f.IntVar(&IntVar{ - Name: "recovery-shares", - Target: &c.flagRecoveryShares, - Default: 5, - Completion: complete.PredictAnything, - Usage: "Number of key shares to split the recovery key into. " + - "This is only used in HSM mode.", - }) - - f.IntVar(&IntVar{ - Name: "recovery-threshold", - Target: &c.flagRecoveryThreshold, - Default: 3, - Completion: complete.PredictAnything, - Usage: "Number of key shares required to reconstruct the recovery key. " + - "This is only used in HSM mode.", - }) - - f.VarFlag(&VarFlag{ - Name: "recovery-pgp-keys", - Value: (*pgpkeys.PubKeyFilesFlag)(&c.flagRecoveryPGPKeys), - Completion: complete.PredictAnything, - Usage: "Behaves like -pgp-keys, but for the recovery key shares. This " + - "is only used in HSM mode.", - }) - - // Deprecations - // TODO: remove in 0.9.0 - f.BoolVar(&BoolVar{ - Name: "check", // prefer -status - Target: &c.flagCheck, - Default: false, - Hidden: true, - Usage: "", - }) - f.BoolVar(&BoolVar{ - Name: "auto", // prefer -consul-auto - Target: &c.flagAuto, - Default: false, - Hidden: true, - Usage: "", - }) - - // Kept to keep scripts passing the flag working, but not used - f.IntVar(&IntVar{ - Name: "stored-shares", - Target: &c.flagStoredShares, - Default: 0, - Hidden: true, - Usage: "", - }) - - return set -} - -func (c *OperatorInitCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorInitCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorInitCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Deprecations - // TODO: remove in 0.9.0 - if c.flagAuto { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength("WARNING! -auto is deprecated. Please use " + - "-consul-auto instead. This will be removed in Vault 0.12.")) - } - c.flagConsulAuto = true - } - if c.flagCheck { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength("WARNING! -check is deprecated. Please use " + - "-status instead. This will be removed in Vault 0.12.")) - } - c.flagStatus = true - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - // Build the initial init request - initReq := &api.InitRequest{ - SecretShares: c.flagKeyShares, - SecretThreshold: c.flagKeyThreshold, - PGPKeys: c.flagPGPKeys, - RootTokenPGPKey: c.flagRootTokenPGPKey, - - StoredShares: c.flagStoredShares, - RecoveryShares: c.flagRecoveryShares, - RecoveryThreshold: c.flagRecoveryThreshold, - RecoveryPGPKeys: c.flagRecoveryPGPKeys, - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Check auto mode - switch { - case c.flagStatus: - return c.status(client) - case c.flagConsulAuto: - return c.consulAuto(client, initReq) - default: - return c.init(client, initReq) - } -} - -// consulAuto enables auto-joining via Consul. -func (c *OperatorInitCommand) consulAuto(client *api.Client, req *api.InitRequest) int { - // Capture the client original address and reset it - originalAddr := client.Address() - defer client.SetAddress(originalAddr) - - // Create a client to communicate with Consul - consulClient, err := consulapi.NewClient(consulapi.DefaultConfig()) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to create Consul client:%v", err)) - return 1 - } - - // Pull the scheme from the Vault client to determine if the Consul agent - // should talk via HTTP or HTTPS. - addr := client.Address() - clientURL, err := url.Parse(addr) - if err != nil || clientURL == nil { - c.UI.Error(fmt.Sprintf("Failed to parse Vault address %s: %s", addr, err)) - return 1 - } - - var uninitedVaults []string - var initedVault string - - // Query the nodes belonging to the cluster - services, _, err := consulClient.Catalog().Service(c.flagConsulService, "", &consulapi.QueryOptions{ - AllowStale: true, - }) - if err == nil { - for _, service := range services { - // Set the address on the client temporarily - vaultAddr := (&url.URL{ - Scheme: clientURL.Scheme, - Host: fmt.Sprintf("%s:%d", service.ServiceAddress, service.ServicePort), - }).String() - client.SetAddress(vaultAddr) - - // Check the initialization status of the discovered node - inited, err := client.Sys().InitStatus() - if err != nil { - c.UI.Error(fmt.Sprintf("Error checking init status of %q: %s", vaultAddr, err)) - } - if inited { - initedVault = vaultAddr - break - } - - // If we got this far, we communicated successfully with Vault, but it - // was not initialized. - uninitedVaults = append(uninitedVaults, vaultAddr) - } - } - - // Get the correct export keywords and quotes for *nix vs Windows - export := "export" - quote := "\"" - if runtime.GOOS == "windows" { - export = "set" - quote = "" - } - - if initedVault != "" { - vaultURL, err := url.Parse(initedVault) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse Vault address %q: %s", initedVault, err)) - return 2 - } - vaultAddr := vaultURL.String() - - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Discovered an initialized Vault node at %q with Consul service name "+ - "%q. Set the following environment variable to target the discovered "+ - "Vault server:", - vaultURL.String(), c.flagConsulService))) - c.UI.Output("") - c.UI.Output(fmt.Sprintf(" $ %s VAULT_ADDR=%s%s%s", export, quote, vaultAddr, quote)) - c.UI.Output("") - return 0 - } - - switch len(uninitedVaults) { - case 0: - c.UI.Error(fmt.Sprintf("No Vault nodes registered as %q in Consul", c.flagConsulService)) - return 2 - case 1: - // There was only one node found in the Vault cluster and it was - // uninitialized. - vaultURL, err := url.Parse(uninitedVaults[0]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse Vault address %q: %s", initedVault, err)) - return 2 - } - vaultAddr := vaultURL.String() - - // Update the client to connect to this Vault server - client.SetAddress(vaultAddr) - - // Let the client know that initialization is performed on the - // discovered node. - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Discovered an initialized Vault node at %q with Consul service name "+ - "%q. Set the following environment variable to target the discovered "+ - "Vault server:", - vaultURL.String(), c.flagConsulService))) - c.UI.Output("") - c.UI.Output(fmt.Sprintf(" $ %s VAULT_ADDR=%s%s%s", export, quote, vaultAddr, quote)) - c.UI.Output("") - c.UI.Output("Attempting to initialize it...") - c.UI.Output("") - - // Attempt to initialize it - return c.init(client, req) - default: - // If more than one Vault node were discovered, print out all of them, - // requiring the client to update VAULT_ADDR and to run init again. - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Discovered %d uninitialized Vault servers with Consul service name "+ - "%q. To initialize these Vaults, set any one of the following "+ - "environment variables and run \"vault operator init\":", - len(uninitedVaults), c.flagConsulService))) - c.UI.Output("") - - // Print valid commands to make setting the variables easier - for _, node := range uninitedVaults { - vaultURL, err := url.Parse(node) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse Vault address %q: %s", initedVault, err)) - return 2 - } - vaultAddr := vaultURL.String() - - c.UI.Output(fmt.Sprintf(" $ %s VAULT_ADDR=%s%s%s", export, quote, vaultAddr, quote)) - } - - c.UI.Output("") - return 0 - } -} - -func (c *OperatorInitCommand) init(client *api.Client, req *api.InitRequest) int { - resp, err := client.Sys().Init(req) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - default: - return OutputData(c.UI, newMachineInit(req, resp)) - } - - for i, key := range resp.Keys { - if resp.KeysB64 != nil && len(resp.KeysB64) == len(resp.Keys) { - c.UI.Output(fmt.Sprintf("Unseal Key %d: %s", i+1, resp.KeysB64[i])) - } else { - c.UI.Output(fmt.Sprintf("Unseal Key %d: %s", i+1, key)) - } - } - for i, key := range resp.RecoveryKeys { - if resp.RecoveryKeysB64 != nil && len(resp.RecoveryKeysB64) == len(resp.RecoveryKeys) { - c.UI.Output(fmt.Sprintf("Recovery Key %d: %s", i+1, resp.RecoveryKeysB64[i])) - } else { - c.UI.Output(fmt.Sprintf("Recovery Key %d: %s", i+1, key)) - } - } - - c.UI.Output("") - c.UI.Output(fmt.Sprintf("Initial Root Token: %s", resp.RootToken)) - - if len(resp.Keys) > 0 { - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Vault initialized with %d key shares and a key threshold of %d. Please "+ - "securely distribute the key shares printed above. When the Vault is "+ - "re-sealed, restarted, or stopped, you must supply at least %d of "+ - "these keys to unseal it before it can start servicing requests.", - req.SecretShares, - req.SecretThreshold, - req.SecretThreshold))) - - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Vault does not store the generated master key. Without at least %d "+ - "key to reconstruct the master key, Vault will remain permanently "+ - "sealed!", - req.SecretThreshold))) - - c.UI.Output("") - c.UI.Output(wrapAtLength( - "It is possible to generate new unseal keys, provided you have a quorum " + - "of existing unseal keys shares. See \"vault operator rekey\" for " + - "more information.")) - } else { - c.UI.Output("") - c.UI.Output("Success! Vault is initialized") - } - - if len(resp.RecoveryKeys) > 0 { - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Recovery key initialized with %d key shares and a key threshold of %d. "+ - "Please securely distribute the key shares printed above.", - req.RecoveryShares, - req.RecoveryThreshold))) - } - - return 0 -} - -// status inspects the init status of vault and returns an appropriate error -// code and message. -func (c *OperatorInitCommand) status(client *api.Client) int { - inited, err := client.Sys().InitStatus() - if err != nil { - c.UI.Error(fmt.Sprintf("Error checking init status: %s", err)) - return 1 // Normally we'd return 2, but 2 means something special here - } - - if inited { - c.UI.Output("Vault is initialized") - return 0 - } - - c.UI.Output("Vault is not initialized") - return 2 -} - -// machineInit is used to output information about the init command. -type machineInit struct { - UnsealKeysB64 []string `json:"unseal_keys_b64"` - UnsealKeysHex []string `json:"unseal_keys_hex"` - UnsealShares int `json:"unseal_shares"` - UnsealThreshold int `json:"unseal_threshold"` - RecoveryKeysB64 []string `json:"recovery_keys_b64"` - RecoveryKeysHex []string `json:"recovery_keys_hex"` - RecoveryShares int `json:"recovery_keys_shares"` - RecoveryThreshold int `json:"recovery_keys_threshold"` - RootToken string `json:"root_token"` -} - -func newMachineInit(req *api.InitRequest, resp *api.InitResponse) *machineInit { - init := &machineInit{} - - init.UnsealKeysHex = make([]string, len(resp.Keys)) - for i, v := range resp.Keys { - init.UnsealKeysHex[i] = v - } - - init.UnsealKeysB64 = make([]string, len(resp.KeysB64)) - for i, v := range resp.KeysB64 { - init.UnsealKeysB64[i] = v - } - - init.UnsealShares = req.SecretShares - init.UnsealThreshold = req.SecretThreshold - - init.RecoveryKeysHex = make([]string, len(resp.RecoveryKeys)) - for i, v := range resp.RecoveryKeys { - init.RecoveryKeysHex[i] = v - } - - init.RecoveryKeysB64 = make([]string, len(resp.RecoveryKeysB64)) - for i, v := range resp.RecoveryKeysB64 { - init.RecoveryKeysB64[i] = v - } - - init.RecoveryShares = req.RecoveryShares - init.RecoveryThreshold = req.RecoveryThreshold - - init.RootToken = resp.RootToken - - return init -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_key_status.go b/vendor/github.com/hashicorp/vault/command/operator_key_status.go deleted file mode 100644 index c5b61c8c0..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_key_status.go +++ /dev/null @@ -1,79 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorKeyStatusCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorKeyStatusCommand)(nil) - -type OperatorKeyStatusCommand struct { - *BaseCommand -} - -func (c *OperatorKeyStatusCommand) Synopsis() string { - return "Provides information about the active encryption key" -} - -func (c *OperatorKeyStatusCommand) Help() string { - helpText := ` -Usage: vault operator key-status [options] - - Provides information about the active encryption key. Specifically, - the current key term and the key installation time. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *OperatorKeyStatusCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *OperatorKeyStatusCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorKeyStatusCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorKeyStatusCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - status, err := client.Sys().KeyStatus() - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading key status: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - c.UI.Output(printKeyStatus(status)) - return 0 - default: - return OutputData(c.UI, status) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_rekey.go b/vendor/github.com/hashicorp/vault/command/operator_rekey.go deleted file mode 100644 index 2544a20bb..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_rekey.go +++ /dev/null @@ -1,807 +0,0 @@ -package command - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" - - "github.com/fatih/structs" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/password" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorRekeyCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorRekeyCommand)(nil) - -type OperatorRekeyCommand struct { - *BaseCommand - - flagCancel bool - flagInit bool - flagKeyShares int - flagKeyThreshold int - flagNonce string - flagPGPKeys []string - flagStatus bool - flagTarget string - flagVerify bool - - // Backup options - flagBackup bool - flagBackupDelete bool - flagBackupRetrieve bool - - // Deprecations - // TODO: remove in 0.9.0 - flagDelete bool - flagRecoveryKey bool - flagRetrieve bool - flagStoredShares int - - testStdin io.Reader // for tests -} - -func (c *OperatorRekeyCommand) Synopsis() string { - return "Generates new unseal keys" -} - -func (c *OperatorRekeyCommand) Help() string { - helpText := ` -Usage: vault operator rekey [options] [KEY] - - Generates a new set of unseal keys. This can optionally change the total - number of key shares or the required threshold of those key shares to - reconstruct the master key. This operation is zero downtime, but it requires - the Vault is unsealed and a quorum of existing unseal keys are provided. - - An unseal key may be provided directly on the command line as an argument to - the command. If key is specified as "-", the command will read from stdin. If - a TTY is available, the command will prompt for text. - - Initialize a rekey: - - $ vault operator rekey \ - -init \ - -key-shares=15 \ - -key-threshold=9 - - Rekey and encrypt the resulting unseal keys with PGP: - - $ vault operator rekey \ - -init \ - -key-shares=3 \ - -key-threshold=2 \ - -pgp-keys="keybase:hashicorp,keybase:jefferai,keybase:sethvargo" - - Store encrypted PGP keys in Vault's core: - - $ vault operator rekey \ - -init \ - -pgp-keys="..." \ - -backup - - Retrieve backed-up unseal keys: - - $ vault operator rekey -backup-retrieve - - Delete backed-up unseal keys: - - $ vault operator rekey -backup-delete - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *OperatorRekeyCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Common Options") - - f.BoolVar(&BoolVar{ - Name: "init", - Target: &c.flagInit, - Default: false, - Usage: "Initialize the rekeying operation. This can only be done if no " + - "rekeying operation is in progress. Customize the new number of key " + - "shares and key threshold using the -key-shares and -key-threshold " + - "flags.", - }) - - f.BoolVar(&BoolVar{ - Name: "cancel", - Target: &c.flagCancel, - Default: false, - Usage: "Reset the rekeying progress. This will discard any submitted " + - "unseal keys or configuration.", - }) - - f.BoolVar(&BoolVar{ - Name: "status", - Target: &c.flagStatus, - Default: false, - Usage: "Print the status of the current attempt without providing an " + - "unseal key.", - }) - - f.IntVar(&IntVar{ - Name: "key-shares", - Aliases: []string{"n"}, - Target: &c.flagKeyShares, - Default: 5, - Completion: complete.PredictAnything, - Usage: "Number of key shares to split the generated master key into. " + - "This is the number of \"unseal keys\" to generate.", - }) - - f.IntVar(&IntVar{ - Name: "key-threshold", - Aliases: []string{"t"}, - Target: &c.flagKeyThreshold, - Default: 3, - Completion: complete.PredictAnything, - Usage: "Number of key shares required to reconstruct the master key. " + - "This must be less than or equal to -key-shares.", - }) - - f.StringVar(&StringVar{ - Name: "nonce", - Target: &c.flagNonce, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Nonce value provided at initialization. The same nonce value " + - "must be provided with each unseal key.", - }) - - f.StringVar(&StringVar{ - Name: "target", - Target: &c.flagTarget, - Default: "barrier", - EnvVar: "", - Completion: complete.PredictSet("barrier", "recovery"), - Usage: "Target for rekeying. \"recovery\" only applies when HSM support " + - "is enabled.", - }) - - f.BoolVar(&BoolVar{ - Name: "verify", - Target: &c.flagVerify, - Default: false, - Usage: "Indicates that the action (-status, -cancel, or providing a key " + - "share) will be affecting verification for the current rekey " + - "attempt.", - }) - - f.VarFlag(&VarFlag{ - Name: "pgp-keys", - Value: (*pgpkeys.PubKeyFilesFlag)(&c.flagPGPKeys), - Completion: complete.PredictAnything, - Usage: "Comma-separated list of paths to files on disk containing " + - "public GPG keys OR a comma-separated list of Keybase usernames using " + - "the format \"keybase:\". When supplied, the generated " + - "unseal keys will be encrypted and base64-encoded in the order " + - "specified in this list.", - }) - - f = set.NewFlagSet("Backup Options") - - f.BoolVar(&BoolVar{ - Name: "backup", - Target: &c.flagBackup, - Default: false, - Usage: "Store a backup of the current PGP encrypted unseal keys in " + - "Vault's core. The encrypted values can be recovered in the event of " + - "failure or discarded after success. See the -backup-delete and " + - "-backup-retrieve options for more information. This option only " + - "applies when the existing unseal keys were PGP encrypted.", - }) - - f.BoolVar(&BoolVar{ - Name: "backup-delete", - Target: &c.flagBackupDelete, - Default: false, - Usage: "Delete any stored backup unseal keys.", - }) - - f.BoolVar(&BoolVar{ - Name: "backup-retrieve", - Target: &c.flagBackupRetrieve, - Default: false, - Usage: "Retrieve the backed-up unseal keys. This option is only available " + - "if the PGP keys were provided and the backup has not been deleted.", - }) - - // Deprecations - // TODO: remove in 0.9.0 - f.BoolVar(&BoolVar{ - Name: "delete", // prefer -backup-delete - Target: &c.flagDelete, - Default: false, - Hidden: true, - Usage: "", - }) - - f.BoolVar(&BoolVar{ - Name: "retrieve", // prefer -backup-retrieve - Target: &c.flagRetrieve, - Default: false, - Hidden: true, - Usage: "", - }) - - f.BoolVar(&BoolVar{ - Name: "recovery-key", // prefer -target=recovery - Target: &c.flagRecoveryKey, - Default: false, - Hidden: true, - Usage: "", - }) - - // Kept to keep scripts passing the flag working, but not used - f.IntVar(&IntVar{ - Name: "stored-shares", - Target: &c.flagStoredShares, - Default: 0, - Hidden: true, - Usage: "", - }) - - return set -} - -func (c *OperatorRekeyCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictAnything -} - -func (c *OperatorRekeyCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorRekeyCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 1 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0-1, got %d)", len(args))) - return 1 - } - - // Deprecations - // TODO: remove in 0.9.0 - if c.flagDelete { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -delete flag is deprecated. Please use -backup-delete " + - "instead. This flag will be removed in Vault 0.12.")) - } - c.flagBackupDelete = true - } - if c.flagRetrieve { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -retrieve flag is deprecated. Please use -backup-retrieve " + - "instead. This flag will be removed in Vault 0.12.")) - } - c.flagBackupRetrieve = true - } - if c.flagRecoveryKey { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! The -recovery-key flag is deprecated. Please use -target=recovery " + - "instead. This flag will be removed in Vault 0.12.")) - } - c.flagTarget = "recovery" - } - - // Create the client - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - switch { - case c.flagBackupDelete: - return c.backupDelete(client) - case c.flagBackupRetrieve: - return c.backupRetrieve(client) - case c.flagCancel: - return c.cancel(client) - case c.flagInit: - return c.init(client) - case c.flagStatus: - return c.status(client) - default: - // If there are no other flags, prompt for an unseal key. - key := "" - if len(args) > 0 { - key = strings.TrimSpace(args[0]) - } - return c.provide(client, key) - } -} - -// init starts the rekey process. -func (c *OperatorRekeyCommand) init(client *api.Client) int { - // Handle the different API requests - var fn func(*api.RekeyInitRequest) (*api.RekeyStatusResponse, error) - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - fn = client.Sys().RekeyInit - case "recovery", "hsm": - fn = client.Sys().RekeyRecoveryKeyInit - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - // Make the request - status, err := fn(&api.RekeyInitRequest{ - SecretShares: c.flagKeyShares, - SecretThreshold: c.flagKeyThreshold, - StoredShares: c.flagStoredShares, - PGPKeys: c.flagPGPKeys, - Backup: c.flagBackup, - RequireVerification: c.flagVerify, - }) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing rekey: %s", err)) - return 2 - } - - // Print warnings about recovery, etc. - if len(c.flagPGPKeys) == 0 { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! If you lose the keys after they are returned, there is no " + - "recovery. Consider canceling this operation and re-initializing " + - "with the -pgp-keys flag to protect the returned unseal keys along " + - "with -backup to allow recovery of the encrypted keys in case of " + - "emergency. You can delete the stored keys later using the -delete " + - "flag.")) - c.UI.Output("") - } - } - if len(c.flagPGPKeys) > 0 && !c.flagBackup { - if Format(c.UI) == "table" { - c.UI.Warn(wrapAtLength( - "WARNING! You are using PGP keys for encrypted the resulting unseal " + - "keys, but you did not enable the option to backup the keys to " + - "Vault's core. If you lose the encrypted keys after they are " + - "returned, you will not be able to recover them. Consider canceling " + - "this operation and re-running with -backup to allow recovery of the " + - "encrypted unseal keys in case of emergency. You can delete the " + - "stored keys later using the -delete flag.")) - c.UI.Output("") - } - } - - // Provide the current status - return c.printStatus(status) -} - -// cancel is used to abort the rekey process. -func (c *OperatorRekeyCommand) cancel(client *api.Client) int { - // Handle the different API requests - var fn func() error - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - fn = client.Sys().RekeyCancel - if c.flagVerify { - fn = client.Sys().RekeyVerificationCancel - } - case "recovery", "hsm": - fn = client.Sys().RekeyRecoveryKeyCancel - if c.flagVerify { - fn = client.Sys().RekeyRecoveryKeyVerificationCancel - } - - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - // Make the request - if err := fn(); err != nil { - c.UI.Error(fmt.Sprintf("Error canceling rekey: %s", err)) - return 2 - } - - c.UI.Output("Success! Canceled rekeying (if it was started)") - return 0 -} - -// provide prompts the user for the seal key and posts it to the update root -// endpoint. If this is the last unseal, this function outputs it. -func (c *OperatorRekeyCommand) provide(client *api.Client, key string) int { - var statusFn func() (interface{}, error) - var updateFn func(string, string) (interface{}, error) - - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - statusFn = func() (interface{}, error) { - return client.Sys().RekeyStatus() - } - updateFn = func(s1 string, s2 string) (interface{}, error) { - return client.Sys().RekeyUpdate(s1, s2) - } - if c.flagVerify { - statusFn = func() (interface{}, error) { - return client.Sys().RekeyVerificationStatus() - } - updateFn = func(s1 string, s2 string) (interface{}, error) { - return client.Sys().RekeyVerificationUpdate(s1, s2) - } - } - case "recovery", "hsm": - statusFn = func() (interface{}, error) { - return client.Sys().RekeyRecoveryKeyStatus() - } - updateFn = func(s1 string, s2 string) (interface{}, error) { - return client.Sys().RekeyRecoveryKeyUpdate(s1, s2) - } - if c.flagVerify { - statusFn = func() (interface{}, error) { - return client.Sys().RekeyRecoveryKeyVerificationStatus() - } - updateFn = func(s1 string, s2 string) (interface{}, error) { - return client.Sys().RekeyRecoveryKeyVerificationUpdate(s1, s2) - } - } - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - status, err := statusFn() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting rekey status: %s", err)) - return 2 - } - - var started bool - var nonce string - - switch status.(type) { - case *api.RekeyStatusResponse: - stat := status.(*api.RekeyStatusResponse) - started = stat.Started - nonce = stat.Nonce - case *api.RekeyVerificationStatusResponse: - stat := status.(*api.RekeyVerificationStatusResponse) - started = stat.Started - nonce = stat.Nonce - default: - c.UI.Error("Unknown status type") - return 1 - } - - // Verify a root token generation is in progress. If there is not one in - // progress, return an error instructing the user to start one. - if !started { - c.UI.Error(wrapAtLength( - "No rekey is in progress. Start a rekey process by running " + - "\"vault operator rekey -init\".")) - return 1 - } - - switch key { - case "-": // Read from stdin - nonce = c.flagNonce - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - var buf bytes.Buffer - if _, err := io.Copy(&buf, stdin); err != nil { - c.UI.Error(fmt.Sprintf("Failed to read from stdin: %s", err)) - return 1 - } - - key = buf.String() - case "": // Prompt using the tty - // Nonce value is not required if we are prompting via the terminal - w := getWriterFromUI(c.UI) - fmt.Fprintf(w, "Rekey operation nonce: %s\n", nonce) - fmt.Fprintf(w, "Unseal Key (will be hidden): ") - key, err = password.Read(os.Stdin) - fmt.Fprintf(w, "\n") - if err != nil { - if err == password.ErrInterrupted { - c.UI.Error("user canceled") - return 1 - } - - c.UI.Error(wrapAtLength(fmt.Sprintf("An error occurred attempting to "+ - "ask for the unseal key. The raw error message is shown below, but "+ - "usually this is because you attempted to pipe a value into the "+ - "command or you are executing outside of a terminal (tty). If you "+ - "want to pipe the value, pass \"-\" as the argument to read from "+ - "stdin. The raw error was: %s", err))) - return 1 - } - default: // Supplied directly as an arg - nonce = c.flagNonce - } - - // Trim any whitespace from they key, especially since we might have - // prompted the user for it. - key = strings.TrimSpace(key) - - // Verify we have a nonce value - if nonce == "" { - c.UI.Error("Missing nonce value: specify it via the -nonce flag") - return 1 - } - - // Provide the key, this may potentially complete the update - resp, err := updateFn(key, nonce) - if err != nil { - c.UI.Error(fmt.Sprintf("Error posting unseal key: %s", err)) - return 2 - } - - var complete bool - var mightContainUnsealKeys bool - - switch resp.(type) { - case *api.RekeyUpdateResponse: - complete = resp.(*api.RekeyUpdateResponse).Complete - mightContainUnsealKeys = true - case *api.RekeyVerificationUpdateResponse: - complete = resp.(*api.RekeyVerificationUpdateResponse).Complete - default: - c.UI.Error("Unknown update response type") - return 1 - } - - if !complete { - return c.status(client) - } - - if mightContainUnsealKeys { - return c.printUnsealKeys(client, status.(*api.RekeyStatusResponse), - resp.(*api.RekeyUpdateResponse)) - } - - c.UI.Output(wrapAtLength("Rekey verification successful. The rekey operation is complete and the new keys are now active.")) - return 0 -} - -// status is used just to fetch and dump the status. -func (c *OperatorRekeyCommand) status(client *api.Client) int { - // Handle the different API requests - var fn func() (interface{}, error) - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - fn = func() (interface{}, error) { - return client.Sys().RekeyStatus() - } - if c.flagVerify { - fn = func() (interface{}, error) { - return client.Sys().RekeyVerificationStatus() - } - } - case "recovery", "hsm": - fn = func() (interface{}, error) { - return client.Sys().RekeyRecoveryKeyStatus() - } - if c.flagVerify { - fn = func() (interface{}, error) { - return client.Sys().RekeyRecoveryKeyVerificationStatus() - } - } - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - // Make the request - status, err := fn() - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading rekey status: %s", err)) - return 2 - } - - return c.printStatus(status) -} - -// backupRetrieve retrieves the stored backup keys. -func (c *OperatorRekeyCommand) backupRetrieve(client *api.Client) int { - // Handle the different API requests - var fn func() (*api.RekeyRetrieveResponse, error) - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - fn = client.Sys().RekeyRetrieveBackup - case "recovery", "hsm": - fn = client.Sys().RekeyRetrieveRecoveryBackup - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - // Make the request - storedKeys, err := fn() - if err != nil { - c.UI.Error(fmt.Sprintf("Error retrieving rekey stored keys: %s", err)) - return 2 - } - - secret := &api.Secret{ - Data: structs.New(storedKeys).Map(), - } - - return OutputSecret(c.UI, secret) -} - -// backupDelete deletes the stored backup keys. -func (c *OperatorRekeyCommand) backupDelete(client *api.Client) int { - // Handle the different API requests - var fn func() error - switch strings.ToLower(strings.TrimSpace(c.flagTarget)) { - case "barrier": - fn = client.Sys().RekeyDeleteBackup - case "recovery", "hsm": - fn = client.Sys().RekeyDeleteRecoveryBackup - default: - c.UI.Error(fmt.Sprintf("Unknown target: %s", c.flagTarget)) - return 1 - } - - // Make the request - if err := fn(); err != nil { - c.UI.Error(fmt.Sprintf("Error deleting rekey stored keys: %s", err)) - return 2 - } - - c.UI.Output("Success! Delete stored keys (if they existed)") - return 0 -} - -// printStatus dumps the status to output -func (c *OperatorRekeyCommand) printStatus(in interface{}) int { - out := []string{} - out = append(out, "Key | Value") - - switch in.(type) { - case *api.RekeyStatusResponse: - status := in.(*api.RekeyStatusResponse) - out = append(out, fmt.Sprintf("Nonce | %s", status.Nonce)) - out = append(out, fmt.Sprintf("Started | %t", status.Started)) - if status.Started { - if status.Progress == status.Required { - out = append(out, fmt.Sprintf("Rekey Progress | %d/%d (verification in progress)", status.Progress, status.Required)) - } else { - out = append(out, fmt.Sprintf("Rekey Progress | %d/%d", status.Progress, status.Required)) - } - out = append(out, fmt.Sprintf("New Shares | %d", status.N)) - out = append(out, fmt.Sprintf("New Threshold | %d", status.T)) - out = append(out, fmt.Sprintf("Verification Required | %t", status.VerificationRequired)) - if status.VerificationNonce != "" { - out = append(out, fmt.Sprintf("Verification Nonce | %s", status.VerificationNonce)) - } - } - if len(status.PGPFingerprints) > 0 { - out = append(out, fmt.Sprintf("PGP Fingerprints | %s", status.PGPFingerprints)) - out = append(out, fmt.Sprintf("Backup | %t", status.Backup)) - } - case *api.RekeyVerificationStatusResponse: - status := in.(*api.RekeyVerificationStatusResponse) - out = append(out, fmt.Sprintf("Started | %t", status.Started)) - out = append(out, fmt.Sprintf("New Shares | %d", status.N)) - out = append(out, fmt.Sprintf("New Threshold | %d", status.T)) - out = append(out, fmt.Sprintf("Verification Nonce | %s", status.Nonce)) - out = append(out, fmt.Sprintf("Verification Progress | %d/%d", status.Progress, status.T)) - default: - c.UI.Error("Unknown status type") - return 1 - } - - switch Format(c.UI) { - case "table": - c.UI.Output(tableOutput(out, nil)) - return 0 - default: - return OutputData(c.UI, in) - } -} - -func (c *OperatorRekeyCommand) printUnsealKeys(client *api.Client, status *api.RekeyStatusResponse, resp *api.RekeyUpdateResponse) int { - switch Format(c.UI) { - case "table": - default: - return OutputData(c.UI, resp) - } - - // Space between the key prompt, if any, and the output - c.UI.Output("") - - // Provide the keys - var haveB64 bool - if resp.KeysB64 != nil && len(resp.KeysB64) == len(resp.Keys) { - haveB64 = true - } - for i, key := range resp.Keys { - if len(resp.PGPFingerprints) > 0 { - if haveB64 { - c.UI.Output(fmt.Sprintf("Key %d fingerprint: %s; value: %s", i+1, resp.PGPFingerprints[i], resp.KeysB64[i])) - } else { - c.UI.Output(fmt.Sprintf("Key %d fingerprint: %s; value: %s", i+1, resp.PGPFingerprints[i], key)) - } - } else { - if haveB64 { - c.UI.Output(fmt.Sprintf("Key %d: %s", i+1, resp.KeysB64[i])) - } else { - c.UI.Output(fmt.Sprintf("Key %d: %s", i+1, key)) - } - } - } - - c.UI.Output("") - c.UI.Output(fmt.Sprintf("Operation nonce: %s", resp.Nonce)) - - if len(resp.PGPFingerprints) > 0 && resp.Backup { - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "The encrypted unseal keys are backed up to \"core/unseal-keys-backup\"" + - "in the storage backend. Remove these keys at any time using " + - "\"vault operator rekey -delete-backup\". Vault does not automatically " + - "remove these keys.", - ))) - } - - switch status.VerificationRequired { - case false: - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Vault rekeyed with %d key shares and a key threshold of %d. Please "+ - "securely distributed the key shares printed above. When Vault is "+ - "re-sealed, restarted, or stopped, you must supply at least %d of "+ - "these keys to unseal it before it can start servicing requests.", - status.N, - status.T, - status.T))) - default: - c.UI.Output("") - c.UI.Output(wrapAtLength(fmt.Sprintf( - "Vault has created a new key, split into %d key shares and a key threshold "+ - "of %d. These will not be active until after verification is complete. "+ - "Please securely distributed the key shares printed above. When Vault "+ - "is re-sealed, restarted, or stopped, you must supply at least %d of "+ - "these keys to unseal it before it can start servicing requests.", - status.N, - status.T, - status.T))) - c.UI.Output("") - c.UI.Warn(wrapAtLength( - "Again, these key shares are _not_ valid until verification is performed. " + - "Do not lose or discard your current key shares until after verification " + - "is complete or you will be unable to unseal Vault. If you cancel the " + - "rekey process or seal Vault before verification is complete the new " + - "shares will be discarded and the current shares will remain valid.", - )) - c.UI.Output("") - c.UI.Warn(wrapAtLength( - "The current verification status, including initial nonce, is shown below.", - )) - c.UI.Output("") - - c.flagVerify = true - return c.status(client) - } - - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_seal.go b/vendor/github.com/hashicorp/vault/command/operator_seal.go deleted file mode 100644 index 90161e241..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_seal.go +++ /dev/null @@ -1,84 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorSealCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorSealCommand)(nil) - -type OperatorSealCommand struct { - *BaseCommand -} - -func (c *OperatorSealCommand) Synopsis() string { - return "Seals the Vault server" -} - -func (c *OperatorSealCommand) Help() string { - helpText := ` -Usage: vault operator seal [options] - - Seals the Vault server. Sealing tells the Vault server to stop responding - to any operations until it is unsealed. When sealed, the Vault server - discards its in-memory master key to unlock the data, so it is physically - blocked from responding to operations unsealed. - - If an unseal is in progress, sealing the Vault will reset the unsealing - process. Users will have to re-enter their portions of the master key again. - - This command does nothing if the Vault server is already sealed. - - Seal the Vault server: - - $ vault operator seal - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *OperatorSealCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *OperatorSealCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorSealCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorSealCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().Seal(); err != nil { - c.UI.Error(fmt.Sprintf("Error sealing: %s", err)) - return 2 - } - - c.UI.Output("Success! Vault is sealed.") - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_step_down.go b/vendor/github.com/hashicorp/vault/command/operator_step_down.go deleted file mode 100644 index 63208faf0..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_step_down.go +++ /dev/null @@ -1,80 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorStepDownCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorStepDownCommand)(nil) - -type OperatorStepDownCommand struct { - *BaseCommand -} - -func (c *OperatorStepDownCommand) Synopsis() string { - return "Forces Vault to resign active duty" -} - -func (c *OperatorStepDownCommand) Help() string { - helpText := ` -Usage: vault operator step-down [options] - - Forces the Vault server at the given address to step down from active duty. - While the affected node will have a delay before attempting to acquire the - leader lock again, if no other Vault nodes acquire the lock beforehand, it - is possible for the same node to re-acquire the lock and become active - again. - - Force Vault to step down as the leader: - - $ vault operator step-down - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *OperatorStepDownCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *OperatorStepDownCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorStepDownCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorStepDownCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().StepDown(); err != nil { - c.UI.Error(fmt.Sprintf("Error stepping down: %s", err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Stepped down: %s", client.Address())) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/operator_unseal.go b/vendor/github.com/hashicorp/vault/command/operator_unseal.go deleted file mode 100644 index c93a272ad..000000000 --- a/vendor/github.com/hashicorp/vault/command/operator_unseal.go +++ /dev/null @@ -1,145 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/hashicorp/vault/helper/password" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorUnsealCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorUnsealCommand)(nil) - -type OperatorUnsealCommand struct { - *BaseCommand - - flagReset bool - - testOutput io.Writer // for tests -} - -func (c *OperatorUnsealCommand) Synopsis() string { - return "Unseals the Vault server" -} - -func (c *OperatorUnsealCommand) Help() string { - helpText := ` -Usage: vault operator unseal [options] [KEY] - - Provide a portion of the master key to unseal a Vault server. Vault starts - in a sealed state. It cannot perform operations until it is unsealed. This - command accepts a portion of the master key (an "unseal key"). - - The unseal key can be supplied as an argument to the command, but this is - not recommended as the unseal key will be available in your history: - - $ vault operator unseal IXyR0OJnSFobekZMMCKCoVEpT7wI6l+USMzE3IcyDyo= - - Instead, run the command with no arguments and it will prompt for the key: - - $ vault operator unseal - Key (will be hidden): IXyR0OJnSFobekZMMCKCoVEpT7wI6l+USMzE3IcyDyo= - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *OperatorUnsealCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "reset", - Aliases: []string{}, - Target: &c.flagReset, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Discard any previously entered keys to the unseal process.", - }) - - return set -} - -func (c *OperatorUnsealCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictAnything -} - -func (c *OperatorUnsealCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorUnsealCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - unsealKey := "" - - args = f.Args() - switch len(args) { - case 0: - // We will prompt for the unsealKey later - case 1: - unsealKey = strings.TrimSpace(args[0]) - default: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if c.flagReset { - status, err := client.Sys().ResetUnsealProcess() - if err != nil { - c.UI.Error(fmt.Sprintf("Error resetting unseal process: %s", err)) - return 2 - } - return OutputSealStatus(c.UI, client, status) - } - - if unsealKey == "" { - // Override the output - writer := (io.Writer)(os.Stdout) - if c.testOutput != nil { - writer = c.testOutput - } - - fmt.Fprintf(writer, "Unseal Key (will be hidden): ") - value, err := password.Read(os.Stdin) - fmt.Fprintf(writer, "\n") - if err != nil { - c.UI.Error(wrapAtLength(fmt.Sprintf("An error occurred attempting to "+ - "ask for an unseal key. The raw error message is shown below, but "+ - "usually this is because you attempted to pipe a value into the "+ - "unseal command or you are executing outside of a terminal (tty). "+ - "You should run the unseal command from a terminal for maximum "+ - "security. If this is not an option, the unseal can be provided as "+ - "the first argument to the unseal command. The raw error "+ - "was:\n\n%s", err))) - return 1 - } - unsealKey = strings.TrimSpace(value) - } - - status, err := client.Sys().Unseal(unsealKey) - if err != nil { - c.UI.Error(fmt.Sprintf("Error unsealing: %s", err)) - return 2 - } - - return OutputSealStatus(c.UI, client, status) -} diff --git a/vendor/github.com/hashicorp/vault/command/path_help.go b/vendor/github.com/hashicorp/vault/command/path_help.go deleted file mode 100644 index 2ce4a38bf..000000000 --- a/vendor/github.com/hashicorp/vault/command/path_help.go +++ /dev/null @@ -1,102 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PathHelpCommand)(nil) -var _ cli.CommandAutocomplete = (*PathHelpCommand)(nil) - -var pathHelpVaultSealedMessage = strings.TrimSpace(` -Error: Vault is sealed. - -The "path-help" command requires the Vault to be unsealed so that the mount -points of the secret engines are known. -`) - -type PathHelpCommand struct { - *BaseCommand -} - -func (c *PathHelpCommand) Synopsis() string { - return "Retrieve API help for paths" -} - -func (c *PathHelpCommand) Help() string { - helpText := ` -Usage: vault path-help [options] PATH - - Retrieves API help for paths. All endpoints in Vault provide built-in help - in markdown format. This includes system paths, secret engines, and auth - methods. - - Get help for the thing mounted at database/: - - $ vault path-help database/ - - The response object will return additional paths to retrieve help: - - $ vault path-help database/roles/ - - Each secret engine produces different help output. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PathHelpCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *PathHelpCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictAnything // TODO: programatic way to invoke help -} - -func (c *PathHelpCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PathHelpCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := sanitizePath(args[0]) - - help, err := client.Help(path) - if err != nil { - if strings.Contains(err.Error(), "Vault is sealed") { - c.UI.Error(pathHelpVaultSealedMessage) - } else { - c.UI.Error(fmt.Sprintf("Error retrieving help: %s", err)) - } - return 2 - } - - c.UI.Output(help.Help) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/plugin.go b/vendor/github.com/hashicorp/vault/command/plugin.go deleted file mode 100644 index 4ed828503..000000000 --- a/vendor/github.com/hashicorp/vault/command/plugin.go +++ /dev/null @@ -1,46 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*PluginCommand)(nil) - -type PluginCommand struct { - *BaseCommand -} - -func (c *PluginCommand) Synopsis() string { - return "Interact with Vault plugins and catalog" -} - -func (c *PluginCommand) Help() string { - helpText := ` -Usage: vault plugin [options] [args] - - This command groups subcommands for interacting with Vault's plugins and the - plugin catalog. Here are a few examples of the plugin commands: - - List all available plugins in the catalog: - - $ vault plugin list - - Register a new plugin to the catalog: - - $ vault plugin register -sha256=d3f0a8b... my-custom-plugin - - Get information about a plugin in the catalog: - - $ vault plugin info my-custom-plugin - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *PluginCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/plugin_deregister.go b/vendor/github.com/hashicorp/vault/command/plugin_deregister.go deleted file mode 100644 index ad6fd66b0..000000000 --- a/vendor/github.com/hashicorp/vault/command/plugin_deregister.go +++ /dev/null @@ -1,86 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PluginDeregisterCommand)(nil) -var _ cli.CommandAutocomplete = (*PluginDeregisterCommand)(nil) - -type PluginDeregisterCommand struct { - *BaseCommand -} - -func (c *PluginDeregisterCommand) Synopsis() string { - return "Deregister an existing plugin in the catalog" -} - -func (c *PluginDeregisterCommand) Help() string { - helpText := ` -Usage: vault plugin deregister [options] NAME - - Deregister an existing plugin in the catalog. If the plugin does not exist, - no action is taken (the command is idempotent). - - Deregister the plugin named my-custom-plugin: - - $ vault plugin deregister my-custom-plugin - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PluginDeregisterCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *PluginDeregisterCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultPlugins() -} - -func (c *PluginDeregisterCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PluginDeregisterCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - pluginName := strings.TrimSpace(args[0]) - - if err := client.Sys().DeregisterPlugin(&api.DeregisterPluginInput{ - Name: pluginName, - }); err != nil { - c.UI.Error(fmt.Sprintf("Error deregistering plugin named %s: %s", pluginName, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Deregistered plugin (if it was registered): %s", pluginName)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/plugin_info.go b/vendor/github.com/hashicorp/vault/command/plugin_info.go deleted file mode 100644 index c4232e9f5..000000000 --- a/vendor/github.com/hashicorp/vault/command/plugin_info.go +++ /dev/null @@ -1,97 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PluginInfoCommand)(nil) -var _ cli.CommandAutocomplete = (*PluginInfoCommand)(nil) - -type PluginInfoCommand struct { - *BaseCommand -} - -func (c *PluginInfoCommand) Synopsis() string { - return "Read information about a plugin in the catalog" -} - -func (c *PluginInfoCommand) Help() string { - helpText := ` -Usage: vault plugin info [options] NAME - - Displays information about a plugin in the catalog with the given name. If - the plugin does not exist, an error is returned. - - Get info about a plugin: - - $ vault plugin info mysql-database-plugin - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PluginInfoCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) -} - -func (c *PluginInfoCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultPlugins() -} - -func (c *PluginInfoCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PluginInfoCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - pluginName := strings.TrimSpace(args[0]) - - resp, err := client.Sys().GetPlugin(&api.GetPluginInput{ - Name: pluginName, - }) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading plugin named %s: %s", pluginName, err)) - return 2 - } - - data := map[string]interface{}{ - "args": resp.Args, - "builtin": resp.Builtin, - "command": resp.Command, - "name": resp.Name, - "sha256": resp.SHA256, - } - - if c.flagField != "" { - return PrintRawField(c.UI, data, c.flagField) - } - return OutputData(c.UI, data) -} diff --git a/vendor/github.com/hashicorp/vault/command/plugin_list.go b/vendor/github.com/hashicorp/vault/command/plugin_list.go deleted file mode 100644 index 4e8375c66..000000000 --- a/vendor/github.com/hashicorp/vault/command/plugin_list.go +++ /dev/null @@ -1,89 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PluginListCommand)(nil) -var _ cli.CommandAutocomplete = (*PluginListCommand)(nil) - -type PluginListCommand struct { - *BaseCommand -} - -func (c *PluginListCommand) Synopsis() string { - return "Lists available plugins" -} - -func (c *PluginListCommand) Help() string { - helpText := ` -Usage: vault plugin list [options] - - Lists available plugins registered in the catalog. This does not list whether - plugins are in use, but rather just their availability. - - List all available plugins in the catalog: - - $ vault plugin list - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PluginListCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *PluginListCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictNothing -} - -func (c *PluginListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PluginListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - resp, err := client.Sys().ListPlugins(&api.ListPluginsInput{}) - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing available plugins: %s", err)) - return 2 - } - - pluginNames := resp.Names - sort.Strings(pluginNames) - - switch Format(c.UI) { - case "table": - list := append([]string{"Plugins"}, pluginNames...) - c.UI.Output(tableOutput(list, nil)) - return 0 - default: - return OutputData(c.UI, pluginNames) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/plugin_register.go b/vendor/github.com/hashicorp/vault/command/plugin_register.go deleted file mode 100644 index 9bd5e76b3..000000000 --- a/vendor/github.com/hashicorp/vault/command/plugin_register.go +++ /dev/null @@ -1,135 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PluginRegisterCommand)(nil) -var _ cli.CommandAutocomplete = (*PluginRegisterCommand)(nil) - -type PluginRegisterCommand struct { - *BaseCommand - - flagArgs []string - flagCommand string - flagSHA256 string -} - -func (c *PluginRegisterCommand) Synopsis() string { - return "Registers a new plugin in the catalog" -} - -func (c *PluginRegisterCommand) Help() string { - helpText := ` -Usage: vault plugin register [options] NAME - - Registers a new plugin in the catalog. The plugin binary must exist in Vault's - configured plugin directory. - - Register the plugin named my-custom-plugin: - - $ vault plugin register -sha256=d3f0a8b... my-custom-plugin - - Register a plugin with custom arguments: - - $ vault plugin register \ - -sha256=d3f0a8b... \ - -args=--with-glibc,--with-cgo \ - my-custom-plugin - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PluginRegisterCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "args", - Target: &c.flagArgs, - Completion: complete.PredictAnything, - Usage: "Arguments to pass to the plugin when starting. Separate " + - "multiple arguments with a comma.", - }) - - f.StringVar(&StringVar{ - Name: "command", - Target: &c.flagCommand, - Completion: complete.PredictAnything, - Usage: "Command to spawn the plugin. This defaults to the name of the " + - "plugin if unspecified.", - }) - - f.StringVar(&StringVar{ - Name: "sha256", - Target: &c.flagSHA256, - Completion: complete.PredictAnything, - Usage: "SHA256 of the plugin binary. This is required for all plugins.", - }) - - return set -} - -func (c *PluginRegisterCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultPlugins() -} - -func (c *PluginRegisterCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PluginRegisterCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - case c.flagSHA256 == "": - c.UI.Error("SHA256 is required for all plugins, please provide -sha256") - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - pluginName := strings.TrimSpace(args[0]) - - command := c.flagCommand - if command == "" { - command = pluginName - } - - if err := client.Sys().RegisterPlugin(&api.RegisterPluginInput{ - Name: pluginName, - Args: c.flagArgs, - Command: command, - SHA256: c.flagSHA256, - }); err != nil { - c.UI.Error(fmt.Sprintf("Error registering plugin %s: %s", pluginName, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Registered plugin: %s", pluginName)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/policies_deprecated.go b/vendor/github.com/hashicorp/vault/command/policies_deprecated.go deleted file mode 100644 index 79c872249..000000000 --- a/vendor/github.com/hashicorp/vault/command/policies_deprecated.go +++ /dev/null @@ -1,57 +0,0 @@ -package command - -import ( - "github.com/mitchellh/cli" -) - -// Deprecation -// TODO: remove in 0.9.0 - -var _ cli.Command = (*PoliciesDeprecatedCommand)(nil) - -type PoliciesDeprecatedCommand struct { - *BaseCommand -} - -func (c *PoliciesDeprecatedCommand) Synopsis() string { return "" } - -func (c *PoliciesDeprecatedCommand) Help() string { - return (&PolicyListCommand{ - BaseCommand: c.BaseCommand, - }).Help() -} - -func (c *PoliciesDeprecatedCommand) Run(args []string) int { - oargs := args - - f := c.flagSet(FlagSetHTTP) - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - - // Got an arg, this is trying to read a policy - if len(args) > 0 { - return (&PolicyReadCommand{ - BaseCommand: &BaseCommand{ - UI: c.UI, - client: c.client, - tokenHelper: c.tokenHelper, - flagAddress: c.flagAddress, - }, - }).Run(oargs) - } - - // No args, probably ran "vault policies" and we want to translate that to - // "vault policy list" - return (&PolicyListCommand{ - BaseCommand: &BaseCommand{ - UI: c.UI, - client: c.client, - tokenHelper: c.tokenHelper, - flagAddress: c.flagAddress, - }, - }).Run(oargs) -} diff --git a/vendor/github.com/hashicorp/vault/command/policy.go b/vendor/github.com/hashicorp/vault/command/policy.go deleted file mode 100644 index 59ffdf0bf..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy.go +++ /dev/null @@ -1,47 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*PolicyCommand)(nil) - -// PolicyCommand is a Command that holds the audit commands -type PolicyCommand struct { - *BaseCommand -} - -func (c *PolicyCommand) Synopsis() string { - return "Interact with policies" -} - -func (c *PolicyCommand) Help() string { - helpText := ` -Usage: vault policy [options] [args] - - This command groups subcommands for interacting with policies. - Users can write, read, and list policies in Vault. - - List all enabled policies: - - $ vault policy list - - Create a policy named "my-policy" from contents on local disk: - - $ vault policy write my-policy ./my-policy.hcl - - Delete the policy named my-policy: - - $ vault policy delete my-policy - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *PolicyCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/policy_delete.go b/vendor/github.com/hashicorp/vault/command/policy_delete.go deleted file mode 100644 index e74030640..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy_delete.go +++ /dev/null @@ -1,85 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PolicyDeleteCommand)(nil) -var _ cli.CommandAutocomplete = (*PolicyDeleteCommand)(nil) - -type PolicyDeleteCommand struct { - *BaseCommand -} - -func (c *PolicyDeleteCommand) Synopsis() string { - return "Deletes a policy by name" -} - -func (c *PolicyDeleteCommand) Help() string { - helpText := ` -Usage: vault policy delete [options] NAME - - Deletes the policy named NAME in the Vault server. Once the policy is deleted, - all tokens associated with the policy are affected immediately. - - Delete the policy named "my-policy": - - $ vault policy delete my-policy - - Note that it is not possible to delete the "default" or "root" policies. - These are built-in policies. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PolicyDeleteCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *PolicyDeleteCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultPolicies() -} - -func (c *PolicyDeleteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PolicyDeleteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - name := strings.TrimSpace(strings.ToLower(args[0])) - if err := client.Sys().DeletePolicy(name); err != nil { - c.UI.Error(fmt.Sprintf("Error deleting %s: %s", name, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Deleted policy: %s", name)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/policy_fmt.go b/vendor/github.com/hashicorp/vault/command/policy_fmt.go deleted file mode 100644 index 01bde16e6..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy_fmt.go +++ /dev/null @@ -1,109 +0,0 @@ -package command - -import ( - "fmt" - "io/ioutil" - "strings" - - "github.com/hashicorp/hcl/hcl/printer" - "github.com/hashicorp/vault/vault" - "github.com/mitchellh/cli" - homedir "github.com/mitchellh/go-homedir" - "github.com/posener/complete" -) - -var _ cli.Command = (*PolicyFmtCommand)(nil) -var _ cli.CommandAutocomplete = (*PolicyFmtCommand)(nil) - -type PolicyFmtCommand struct { - *BaseCommand -} - -func (c *PolicyFmtCommand) Synopsis() string { - return "Formats a policy on disk" -} - -func (c *PolicyFmtCommand) Help() string { - helpText := ` -Usage: vault policy fmt [options] PATH - - Formats a local policy file to the policy specification. This command will - overwrite the file at the given PATH with the properly-formatted policy - file contents. - - Format the local file "my-policy.hcl" as a policy file: - - $ vault policy fmt my-policy.hcl - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PolicyFmtCommand) Flags() *FlagSets { - return c.flagSet(FlagSetNone) -} - -func (c *PolicyFmtCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictFiles("*.hcl") -} - -func (c *PolicyFmtCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PolicyFmtCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - // Get the filepath, accounting for ~ and stuff - path, err := homedir.Expand(strings.TrimSpace(args[0])) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to expand path: %s", err)) - return 1 - } - - // Read the entire contents into memory - it would be nice if we could use - // a buffer, but hcl wants the full contents. - b, err := ioutil.ReadFile(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading source file: %s", err)) - return 1 - } - - // Actually parse the policy - if _, err := vault.ParseACLPolicy(string(b)); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Generate final contents - result, err := printer.Format(b) - if err != nil { - c.UI.Error(fmt.Sprintf("Error printing result: %s", err)) - return 1 - } - - // Write them back out - if err := ioutil.WriteFile(path, result, 0644); err != nil { - c.UI.Error(fmt.Sprintf("Error writing result: %s", err)) - return 1 - } - - c.UI.Output(fmt.Sprintf("Success! Formatted policy: %s", path)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/policy_list.go b/vendor/github.com/hashicorp/vault/command/policy_list.go deleted file mode 100644 index 43bd5287d..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy_list.go +++ /dev/null @@ -1,81 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PolicyListCommand)(nil) -var _ cli.CommandAutocomplete = (*PolicyListCommand)(nil) - -type PolicyListCommand struct { - *BaseCommand -} - -func (c *PolicyListCommand) Synopsis() string { - return "Lists the installed policies" -} - -func (c *PolicyListCommand) Help() string { - helpText := ` -Usage: vault policy list [options] - - Lists the names of the policies that are installed on the Vault server. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PolicyListCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *PolicyListCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *PolicyListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PolicyListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) > 0: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - policies, err := client.Sys().ListPolicies() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing policies: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - for _, p := range policies { - c.UI.Output(p) - } - return 0 - default: - return OutputData(c.UI, policies) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/policy_read.go b/vendor/github.com/hashicorp/vault/command/policy_read.go deleted file mode 100644 index d10a5d102..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy_read.go +++ /dev/null @@ -1,95 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PolicyReadCommand)(nil) -var _ cli.CommandAutocomplete = (*PolicyReadCommand)(nil) - -type PolicyReadCommand struct { - *BaseCommand -} - -func (c *PolicyReadCommand) Synopsis() string { - return "Prints the contents of a policy" -} - -func (c *PolicyReadCommand) Help() string { - helpText := ` -Usage: vault policy read [options] [NAME] - - Prints the contents and metadata of the Vault policy named NAME. If the policy - does not exist, an error is returned. - - Read the policy named "my-policy": - - $ vault policy read my-policy - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PolicyReadCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *PolicyReadCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultPolicies() -} - -func (c *PolicyReadCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PolicyReadCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - name := strings.ToLower(strings.TrimSpace(args[0])) - rules, err := client.Sys().GetPolicy(name) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading policy named %s: %s", name, err)) - return 2 - } - if rules == "" { - c.UI.Error(fmt.Sprintf("No policy named: %s", name)) - return 2 - } - - switch Format(c.UI) { - case "table": - c.UI.Output(strings.TrimSpace(rules)) - return 0 - default: - resp := map[string]string{ - "policy": rules, - } - return OutputData(c.UI, &resp) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/policy_write.go b/vendor/github.com/hashicorp/vault/command/policy_write.go deleted file mode 100644 index 9f6cb2222..000000000 --- a/vendor/github.com/hashicorp/vault/command/policy_write.go +++ /dev/null @@ -1,127 +0,0 @@ -package command - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*PolicyWriteCommand)(nil) -var _ cli.CommandAutocomplete = (*PolicyWriteCommand)(nil) - -type PolicyWriteCommand struct { - *BaseCommand - - testStdin io.Reader // for tests -} - -func (c *PolicyWriteCommand) Synopsis() string { - return "Uploads a named policy from a file" -} - -func (c *PolicyWriteCommand) Help() string { - helpText := ` -Usage: vault policy write [options] NAME PATH - - Uploads a policy with name NAME from the contents of a local file PATH or - stdin. If PATH is "-", the policy is read from stdin. Otherwise, it is - loaded from the file at the given path on the local disk. - - Upload a policy named "my-policy" from "/tmp/policy.hcl" on the local disk: - - $ vault policy write my-policy /tmp/policy.hcl - - Upload a policy from stdin: - - $ cat my-policy.hcl | vault policy write my-policy - - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *PolicyWriteCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *PolicyWriteCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictFunc(func(args complete.Args) []string { - // Predict the LAST argument hcl files - we don't want to predict the - // name argument as a filepath. - if len(args.All) == 3 { - return complete.PredictFiles("*.hcl").Predict(args) - } - return nil - }) -} - -func (c *PolicyWriteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *PolicyWriteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 2: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 2, got %d)", len(args))) - return 1 - case len(args) > 2: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 2, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Policies are normalized to lowercase - name := strings.TrimSpace(strings.ToLower(args[0])) - path := strings.TrimSpace(args[1]) - - // Get the policy contents, either from stdin of a file - var reader io.Reader - if path == "-" { - reader = os.Stdin - if c.testStdin != nil { - reader = c.testStdin - } - } else { - file, err := os.Open(path) - if err != nil { - c.UI.Error(fmt.Sprintf("Error opening policy file: %s", err)) - return 2 - } - defer file.Close() - reader = file - } - - // Read the policy - var buf bytes.Buffer - if _, err := io.Copy(&buf, reader); err != nil { - c.UI.Error(fmt.Sprintf("Error reading policy: %s", err)) - return 2 - } - rules := buf.String() - - if err := client.Sys().PutPolicy(name, rules); err != nil { - c.UI.Error(fmt.Sprintf("Error uploading policy: %s", err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Uploaded policy: %s", name)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/read.go b/vendor/github.com/hashicorp/vault/command/read.go deleted file mode 100644 index 0b3660838..000000000 --- a/vendor/github.com/hashicorp/vault/command/read.go +++ /dev/null @@ -1,107 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*ReadCommand)(nil) -var _ cli.CommandAutocomplete = (*ReadCommand)(nil) - -type ReadCommand struct { - *BaseCommand - - testStdin io.Reader // for tests -} - -func (c *ReadCommand) Synopsis() string { - return "Read data and retrieves secrets" -} - -func (c *ReadCommand) Help() string { - helpText := ` -Usage: vault read [options] PATH - - Reads data from Vault at the given path. This can be used to read secrets, - generate dynamic credentials, get configuration details, and more. - - Read a secret from the static secrets engine: - - $ vault read secret/my-secret - - For a full list of examples and paths, please see the documentation that - corresponds to the secrets engine in use. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *ReadCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) -} - -func (c *ReadCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *ReadCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *ReadCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - path := sanitizePath(args[0]) - - data, err := parseArgsDataStringLists(stdin, args[1:]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse K=V data: %s", err)) - return 1 - } - - secret, err := client.Logical().ReadWithData(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading %s: %s", path, err)) - return 2 - } - if secret == nil { - c.UI.Error(fmt.Sprintf("No value found at %s", path)) - return 2 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/rotate.go b/vendor/github.com/hashicorp/vault/command/rotate.go deleted file mode 100644 index d0f0a2db4..000000000 --- a/vendor/github.com/hashicorp/vault/command/rotate.go +++ /dev/null @@ -1,101 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*OperatorRotateCommand)(nil) -var _ cli.CommandAutocomplete = (*OperatorRotateCommand)(nil) - -type OperatorRotateCommand struct { - *BaseCommand -} - -func (c *OperatorRotateCommand) Synopsis() string { - return "Rotates the underlying encryption key" -} - -func (c *OperatorRotateCommand) Help() string { - helpText := ` -Usage: vault operator rotate [options] - - Rotates the underlying encryption key which is used to secure data written - to the storage backend. This installs a new key in the key ring. This new - key is used to encrypted new data, while older keys in the ring are used to - decrypt older data. - - This is an online operation and does not cause downtime. This command is run - per-cluster (not per-server), since Vault servers in HA mode share the same - storage backend. - - Rotate Vault's encryption key: - - $ vault operator rotate - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *OperatorRotateCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *OperatorRotateCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *OperatorRotateCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *OperatorRotateCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Rotate the key - err = client.Sys().Rotate() - if err != nil { - c.UI.Error(fmt.Sprintf("Error rotating key: %s", err)) - return 2 - } - - // Print the key status - status, err := client.Sys().KeyStatus() - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading key status: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - c.UI.Output("Success! Rotated key") - c.UI.Output("") - c.UI.Output(printKeyStatus(status)) - return 0 - default: - return OutputData(c.UI, status) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets.go b/vendor/github.com/hashicorp/vault/command/secrets.go deleted file mode 100644 index 06e63bec2..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets.go +++ /dev/null @@ -1,43 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*SecretsCommand)(nil) - -type SecretsCommand struct { - *BaseCommand -} - -func (c *SecretsCommand) Synopsis() string { - return "Interact with secrets engines" -} - -func (c *SecretsCommand) Help() string { - helpText := ` -Usage: vault secrets [options] [args] - - This command groups subcommands for interacting with Vault's secrets engines. - Each secret engine behaves differently. Please see the documentation for - more information. - - List all enabled secrets engines: - - $ vault secrets list - - Enable a new secrets engine: - - $ vault secrets enable database - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *SecretsCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets_disable.go b/vendor/github.com/hashicorp/vault/command/secrets_disable.go deleted file mode 100644 index 700287440..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets_disable.go +++ /dev/null @@ -1,84 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*SecretsDisableCommand)(nil) -var _ cli.CommandAutocomplete = (*SecretsDisableCommand)(nil) - -type SecretsDisableCommand struct { - *BaseCommand -} - -func (c *SecretsDisableCommand) Synopsis() string { - return "Disable a secret engine" -} - -func (c *SecretsDisableCommand) Help() string { - helpText := ` -Usage: vault secrets disable [options] PATH - - Disables a secrets engine at the given PATH. The argument corresponds to - the enabled PATH of the engine, not the TYPE! All secrets created by this - engine are revoked and its Vault data is removed. - - Disable the secrets engine enabled at aws/: - - $ vault secrets disable aws/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SecretsDisableCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *SecretsDisableCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultMounts() -} - -func (c *SecretsDisableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *SecretsDisableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - path := ensureTrailingSlash(sanitizePath(args[0])) - - if err := client.Sys().Unmount(path); err != nil { - c.UI.Error(fmt.Sprintf("Error disabling secrets engine at %s: %s", path, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Disabled the secrets engine (if it existed) at: %s", path)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets_enable.go b/vendor/github.com/hashicorp/vault/command/secrets_enable.go deleted file mode 100644 index 1756f40bd..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets_enable.go +++ /dev/null @@ -1,294 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*SecretsEnableCommand)(nil) -var _ cli.CommandAutocomplete = (*SecretsEnableCommand)(nil) - -type SecretsEnableCommand struct { - *BaseCommand - - flagDescription string - flagPath string - flagDefaultLeaseTTL time.Duration - flagMaxLeaseTTL time.Duration - flagAuditNonHMACRequestKeys []string - flagAuditNonHMACResponseKeys []string - flagListingVisibility string - flagPassthroughRequestHeaders []string - flagForceNoCache bool - flagPluginName string - flagOptions map[string]string - flagLocal bool - flagSealWrap bool - flagVersion int -} - -func (c *SecretsEnableCommand) Synopsis() string { - return "Enable a secrets engine" -} - -func (c *SecretsEnableCommand) Help() string { - helpText := ` -Usage: vault secrets enable [options] TYPE - - Enables a secrets engine. By default, secrets engines are enabled at the path - corresponding to their TYPE, but users can customize the path using the - -path option. - - Once enabled, Vault will route all requests which begin with the path to the - secrets engine. - - Enable the AWS secrets engine at aws/: - - $ vault secrets enable aws - - Enable the SSH secrets engine at ssh-prod/: - - $ vault secrets enable -path=ssh-prod ssh - - Enable the database secrets engine with an explicit maximum TTL of 30m: - - $ vault secrets enable -max-lease-ttl=30m database - - Enable a custom plugin (after it is registered in the plugin registry): - - $ vault secrets enable -path=my-secrets -plugin-name=my-plugin plugin - - For a full list of secrets engines and examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SecretsEnableCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringVar(&StringVar{ - Name: "description", - Target: &c.flagDescription, - Completion: complete.PredictAnything, - Usage: "Human-friendly description for the purpose of this engine.", - }) - - f.StringVar(&StringVar{ - Name: "path", - Target: &c.flagPath, - Default: "", // The default is complex, so we have to manually document - Completion: complete.PredictAnything, - Usage: "Place where the secrets engine will be accessible. This must be " + - "unique cross all secrets engines. This defaults to the \"type\" of the " + - "secrets engine.", - }) - - f.DurationVar(&DurationVar{ - Name: "default-lease-ttl", - Target: &c.flagDefaultLeaseTTL, - Completion: complete.PredictAnything, - Usage: "The default lease TTL for this secrets engine. If unspecified, " + - "this defaults to the Vault server's globally configured default lease " + - "TTL.", - }) - - f.DurationVar(&DurationVar{ - Name: "max-lease-ttl", - Target: &c.flagMaxLeaseTTL, - Completion: complete.PredictAnything, - Usage: "The maximum lease TTL for this secrets engine. If unspecified, " + - "this defaults to the Vault server's globally configured maximum lease " + - "TTL.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACRequestKeys, - Target: &c.flagAuditNonHMACRequestKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the request data object.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACResponseKeys, - Target: &c.flagAuditNonHMACResponseKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the response data object.", - }) - - f.StringVar(&StringVar{ - Name: flagNameListingVisibility, - Target: &c.flagListingVisibility, - Usage: "Determines the visibility of the mount in the UI-specific listing endpoint.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNamePassthroughRequestHeaders, - Target: &c.flagPassthroughRequestHeaders, - Usage: "Comma-separated string or list of request header values that " + - "will be sent to the backend", - }) - - f.BoolVar(&BoolVar{ - Name: "force-no-cache", - Target: &c.flagForceNoCache, - Default: false, - Usage: "Force the secrets engine to disable caching. If unspecified, this " + - "defaults to the Vault server's globally configured cache settings. " + - "This does not affect caching of the underlying encrypted data storage.", - }) - - f.StringVar(&StringVar{ - Name: "plugin-name", - Target: &c.flagPluginName, - Completion: c.PredictVaultPlugins(), - Usage: "Name of the secrets engine plugin. This plugin name must already " + - "exist in Vault's plugin catalog.", - }) - - f.StringMapVar(&StringMapVar{ - Name: "options", - Target: &c.flagOptions, - Completion: complete.PredictAnything, - Usage: "Key-value pair provided as key=value for the mount options. " + - "This can be specified multiple times.", - }) - - f.BoolVar(&BoolVar{ - Name: "local", - Target: &c.flagLocal, - Default: false, - Usage: "Mark the secrets engine as local-only. Local engines are not " + - "replicated or removed by replication.", - }) - - f.BoolVar(&BoolVar{ - Name: "seal-wrap", - Target: &c.flagSealWrap, - Default: false, - Usage: "Enable seal wrapping of critical values in the secrets engine.", - }) - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Default: 0, - Usage: "Select the version of the engine to run. Not supported by all engines.", - }) - - return set -} - -func (c *SecretsEnableCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultAvailableMounts() -} - -func (c *SecretsEnableCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *SecretsEnableCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - // Get the engine type type (first arg) - engineType := strings.TrimSpace(args[0]) - - // If no path is specified, we default the path to the backend type - // or use the plugin name if it's a plugin backend - mountPath := c.flagPath - if mountPath == "" { - if engineType == "plugin" { - mountPath = c.flagPluginName - } else { - mountPath = engineType - } - } - - if c.flagVersion > 0 { - if c.flagOptions == nil { - c.flagOptions = make(map[string]string) - } - c.flagOptions["version"] = strconv.Itoa(c.flagVersion) - } - - // Append a trailing slash to indicate it's a path in output - mountPath = ensureTrailingSlash(mountPath) - - // Build mount input - mountInput := &api.MountInput{ - Type: engineType, - Description: c.flagDescription, - Local: c.flagLocal, - SealWrap: c.flagSealWrap, - Config: api.MountConfigInput{ - DefaultLeaseTTL: c.flagDefaultLeaseTTL.String(), - MaxLeaseTTL: c.flagMaxLeaseTTL.String(), - ForceNoCache: c.flagForceNoCache, - PluginName: c.flagPluginName, - }, - Options: c.flagOptions, - } - - // Set these values only if they are provided in the CLI - f.Visit(func(fl *flag.Flag) { - if fl.Name == flagNameAuditNonHMACRequestKeys { - mountInput.Config.AuditNonHMACRequestKeys = c.flagAuditNonHMACRequestKeys - } - - if fl.Name == flagNameAuditNonHMACResponseKeys { - mountInput.Config.AuditNonHMACResponseKeys = c.flagAuditNonHMACResponseKeys - } - - if fl.Name == flagNameListingVisibility { - mountInput.Config.ListingVisibility = c.flagListingVisibility - } - - if fl.Name == flagNamePassthroughRequestHeaders { - mountInput.Config.PassthroughRequestHeaders = c.flagPassthroughRequestHeaders - } - }) - - if err := client.Sys().Mount(mountPath, mountInput); err != nil { - c.UI.Error(fmt.Sprintf("Error enabling: %s", err)) - return 2 - } - - thing := engineType + " secrets engine" - if engineType == "plugin" { - thing = c.flagPluginName + " plugin" - } - - c.UI.Output(fmt.Sprintf("Success! Enabled the %s at: %s", thing, mountPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets_list.go b/vendor/github.com/hashicorp/vault/command/secrets_list.go deleted file mode 100644 index 3d52a323b..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets_list.go +++ /dev/null @@ -1,174 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strconv" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*SecretsListCommand)(nil) -var _ cli.CommandAutocomplete = (*SecretsListCommand)(nil) - -type SecretsListCommand struct { - *BaseCommand - - flagDetailed bool -} - -func (c *SecretsListCommand) Synopsis() string { - return "List enabled secrets engines" -} - -func (c *SecretsListCommand) Help() string { - helpText := ` -Usage: vault secrets list [options] - - Lists the enabled secret engines on the Vault server. This command also - outputs information about the enabled path including configured TTLs and - human-friendly descriptions. A TTL of "system" indicates that the system - default is in use. - - List all enabled secrets engines: - - $ vault secrets list - - List all enabled secrets engines with detailed output: - - $ vault secrets list -detailed - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SecretsListCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "detailed", - Target: &c.flagDetailed, - Default: false, - Usage: "Print detailed information such as TTLs and replication status " + - "about each secrets engine.", - }) - - return set -} - -func (c *SecretsListCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *SecretsListCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *SecretsListCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - mounts, err := client.Sys().ListMounts() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing secrets engines: %s", err)) - return 2 - } - - switch Format(c.UI) { - case "table": - if c.flagDetailed { - c.UI.Output(tableOutput(c.detailedMounts(mounts), nil)) - return 0 - } - c.UI.Output(tableOutput(c.simpleMounts(mounts), nil)) - return 0 - default: - return OutputData(c.UI, mounts) - } -} - -func (c *SecretsListCommand) simpleMounts(mounts map[string]*api.MountOutput) []string { - paths := make([]string, 0, len(mounts)) - for path := range mounts { - paths = append(paths, path) - } - sort.Strings(paths) - - out := []string{"Path | Type | Accessor | Description"} - for _, path := range paths { - mount := mounts[path] - out = append(out, fmt.Sprintf("%s | %s | %s | %s", path, mount.Type, mount.Accessor, mount.Description)) - } - - return out -} - -func (c *SecretsListCommand) detailedMounts(mounts map[string]*api.MountOutput) []string { - paths := make([]string, 0, len(mounts)) - for path := range mounts { - paths = append(paths, path) - } - sort.Strings(paths) - - calcTTL := func(typ string, ttl int) string { - switch { - case typ == "system", typ == "cubbyhole": - return "" - case ttl != 0: - return strconv.Itoa(ttl) - default: - return "system" - } - } - - out := []string{"Path | Type | Accessor | Plugin | Default TTL | Max TTL | Force No Cache | Replication | Seal Wrap | Options | Description"} - for _, path := range paths { - mount := mounts[path] - - defaultTTL := calcTTL(mount.Type, mount.Config.DefaultLeaseTTL) - maxTTL := calcTTL(mount.Type, mount.Config.MaxLeaseTTL) - - replication := "replicated" - if mount.Local { - replication = "local" - } - - out = append(out, fmt.Sprintf("%s | %s | %s | %s | %s | %s | %t | %s | %t | %v | %s", - path, - mount.Type, - mount.Accessor, - mount.Config.PluginName, - defaultTTL, - maxTTL, - mount.Config.ForceNoCache, - replication, - mount.SealWrap, - mount.Options, - mount.Description, - )) - } - - return out -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets_move.go b/vendor/github.com/hashicorp/vault/command/secrets_move.go deleted file mode 100644 index 542b14d3d..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets_move.go +++ /dev/null @@ -1,89 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*SecretsMoveCommand)(nil) -var _ cli.CommandAutocomplete = (*SecretsMoveCommand)(nil) - -type SecretsMoveCommand struct { - *BaseCommand -} - -func (c *SecretsMoveCommand) Synopsis() string { - return "Move a secrets engine to a new path" -} - -func (c *SecretsMoveCommand) Help() string { - helpText := ` -Usage: vault secrets move [options] SOURCE DESTINATION - - Moves an existing secrets engine to a new path. Any leases from the old - secrets engine are revoked, but all configuration associated with the engine - is preserved. - - WARNING! Moving an existing secrets engine will revoke any leases from the - old engine. - - Move the existing secrets engine at secret/ to generic/: - - $ vault secrets move secret/ generic/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SecretsMoveCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP) -} - -func (c *SecretsMoveCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultMounts() -} - -func (c *SecretsMoveCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *SecretsMoveCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 2: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 2, got %d)", len(args))) - return 1 - case len(args) > 2: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 2, got %d)", len(args))) - return 1 - } - - // Grab the source and destination - source := ensureTrailingSlash(args[0]) - destination := ensureTrailingSlash(args[1]) - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if err := client.Sys().Remount(source, destination); err != nil { - c.UI.Error(fmt.Sprintf("Error moving secrets engine %s to %s: %s", source, destination, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Moved secrets engine %s to: %s", source, destination)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/secrets_tune.go b/vendor/github.com/hashicorp/vault/command/secrets_tune.go deleted file mode 100644 index 12f830510..000000000 --- a/vendor/github.com/hashicorp/vault/command/secrets_tune.go +++ /dev/null @@ -1,199 +0,0 @@ -package command - -import ( - "flag" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*SecretsTuneCommand)(nil) -var _ cli.CommandAutocomplete = (*SecretsTuneCommand)(nil) - -type SecretsTuneCommand struct { - *BaseCommand - - flagAuditNonHMACRequestKeys []string - flagAuditNonHMACResponseKeys []string - flagDefaultLeaseTTL time.Duration - flagDescription string - flagListingVisibility string - flagMaxLeaseTTL time.Duration - flagOptions map[string]string - flagVersion int -} - -func (c *SecretsTuneCommand) Synopsis() string { - return "Tune a secrets engine configuration" -} - -func (c *SecretsTuneCommand) Help() string { - helpText := ` -Usage: vault secrets tune [options] PATH - - Tunes the configuration options for the secrets engine at the given PATH. - The argument corresponds to the PATH where the secrets engine is enabled, - not the TYPE! - - Tune the default lease for the PKI secrets engine: - - $ vault secrets tune -default-lease-ttl=72h pki/ - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SecretsTuneCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACRequestKeys, - Target: &c.flagAuditNonHMACRequestKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the request data object.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: flagNameAuditNonHMACResponseKeys, - Target: &c.flagAuditNonHMACResponseKeys, - Usage: "Comma-separated string or list of keys that will not be HMAC'd by audit" + - "devices in the response data object.", - }) - - f.DurationVar(&DurationVar{ - Name: "default-lease-ttl", - Target: &c.flagDefaultLeaseTTL, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "The default lease TTL for this secrets engine. If unspecified, " + - "this defaults to the Vault server's globally configured default lease " + - "TTL, or a previously configured value for the secrets engine.", - }) - - f.StringVar(&StringVar{ - Name: flagNameDescription, - Target: &c.flagDescription, - Usage: "Human-friendly description of this secret engine. This overrides the" + - "current stored value, if any.", - }) - - f.StringVar(&StringVar{ - Name: flagNameListingVisibility, - Target: &c.flagListingVisibility, - Usage: "Determines the visibility of the mount in the UI-specific listing" + - "endpoint.", - }) - - f.DurationVar(&DurationVar{ - Name: "max-lease-ttl", - Target: &c.flagMaxLeaseTTL, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "The maximum lease TTL for this secrets engine. If unspecified, " + - "this defaults to the Vault server's globally configured maximum lease " + - "TTL, or a previously configured value for the secrets engine.", - }) - - f.StringMapVar(&StringMapVar{ - Name: "options", - Target: &c.flagOptions, - Completion: complete.PredictAnything, - Usage: "Key-value pair provided as key=value for the mount options. " + - "This can be specified multiple times.", - }) - - f.IntVar(&IntVar{ - Name: "version", - Target: &c.flagVersion, - Default: 0, - Usage: "Select the version of the engine to run. Not supported by all engines.", - }) - - return set -} - -func (c *SecretsTuneCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultMounts() -} - -func (c *SecretsTuneCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *SecretsTuneCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - if c.flagVersion > 0 { - if c.flagOptions == nil { - c.flagOptions = make(map[string]string) - } - c.flagOptions["version"] = strconv.Itoa(c.flagVersion) - } - - // Append a trailing slash to indicate it's a path in output - mountPath := ensureTrailingSlash(sanitizePath(args[0])) - - mountConfigInput := api.MountConfigInput{ - DefaultLeaseTTL: ttlToAPI(c.flagDefaultLeaseTTL), - MaxLeaseTTL: ttlToAPI(c.flagMaxLeaseTTL), - Options: c.flagOptions, - } - - // Set these values only if they are provided in the CLI - f.Visit(func(fl *flag.Flag) { - if fl.Name == flagNameAuditNonHMACRequestKeys { - mountConfigInput.AuditNonHMACRequestKeys = c.flagAuditNonHMACRequestKeys - } - - if fl.Name == flagNameAuditNonHMACResponseKeys { - mountConfigInput.AuditNonHMACResponseKeys = c.flagAuditNonHMACResponseKeys - } - - if fl.Name == flagNameDescription { - mountConfigInput.Description = &c.flagDescription - } - - if fl.Name == flagNameListingVisibility { - mountConfigInput.ListingVisibility = c.flagListingVisibility - } - }) - - if err := client.Sys().TuneMount(mountPath, mountConfigInput); err != nil { - c.UI.Error(fmt.Sprintf("Error tuning secrets engine %s: %s", mountPath, err)) - return 2 - } - - c.UI.Output(fmt.Sprintf("Success! Tuned the secrets engine at: %s", mountPath)) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/server.go b/vendor/github.com/hashicorp/vault/command/server.go deleted file mode 100644 index 84194d348..000000000 --- a/vendor/github.com/hashicorp/vault/command/server.go +++ /dev/null @@ -1,1771 +0,0 @@ -package command - -import ( - "context" - "crypto/sha256" - "encoding/base64" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "path/filepath" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/mitchellh/cli" - testing "github.com/mitchellh/go-testing-interface" - "github.com/posener/complete" - - "google.golang.org/grpc/grpclog" - - "github.com/armon/go-metrics" - "github.com/armon/go-metrics/circonus" - "github.com/armon/go-metrics/datadog" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-multierror" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/command/server" - "github.com/hashicorp/vault/helper/gated-writer" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/mlock" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/reload" - vaulthttp "github.com/hashicorp/vault/http" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/vault" - "github.com/hashicorp/vault/version" -) - -var _ cli.Command = (*ServerCommand)(nil) -var _ cli.CommandAutocomplete = (*ServerCommand)(nil) - -type ServerCommand struct { - *BaseCommand - - AuditBackends map[string]audit.Factory - CredentialBackends map[string]logical.Factory - LogicalBackends map[string]logical.Factory - PhysicalBackends map[string]physical.Factory - - ShutdownCh chan struct{} - SighupCh chan struct{} - - WaitGroup *sync.WaitGroup - - logWriter io.Writer - logGate *gatedwriter.Writer - logger log.Logger - - cleanupGuard sync.Once - - reloadFuncsLock *sync.RWMutex - reloadFuncs *map[string][]reload.ReloadFunc - startedCh chan (struct{}) // for tests - reloadedCh chan (struct{}) // for tests - - // new stuff - flagConfigs []string - flagLogLevel string - flagDev bool - flagDevRootTokenID string - flagDevListenAddr string - - flagDevPluginDir string - flagDevPluginInit bool - flagDevHA bool - flagDevLatency int - flagDevLatencyJitter int - flagDevLeasedKV bool - flagDevSkipInit bool - flagDevThreeNode bool - flagDevFourCluster bool - flagDevTransactional bool - flagTestVerifyOnly bool - flagCombineLogs bool -} - -type ServerListener struct { - net.Listener - config map[string]interface{} - maxRequestSize int64 - maxRequestDuration time.Duration -} - -func (c *ServerCommand) Synopsis() string { - return "Start a Vault server" -} - -func (c *ServerCommand) Help() string { - helpText := ` -Usage: vault server [options] - - This command starts a Vault server that responds to API requests. By default, - Vault will start in a "sealed" state. The Vault cluster must be initialized - before use, usually by the "vault operator init" command. Each Vault server must - also be unsealed using the "vault operator unseal" command or the API before the - server can respond to requests. - - Start a server with a configuration file: - - $ vault server -config=/etc/vault/config.hcl - - Run in "dev" mode: - - $ vault server -dev -dev-root-token-id="root" - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - return strings.TrimSpace(helpText) -} - -func (c *ServerCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.StringSliceVar(&StringSliceVar{ - Name: "config", - Target: &c.flagConfigs, - Completion: complete.PredictOr( - complete.PredictFiles("*.hcl"), - complete.PredictFiles("*.json"), - complete.PredictDirs("*"), - ), - Usage: "Path to a configuration file or directory of configuration " + - "files. This flag can be specified multiple times to load multiple " + - "configurations. If the path is a directory, all files which end in " + - ".hcl or .json are loaded.", - }) - - f.StringVar(&StringVar{ - Name: "log-level", - Target: &c.flagLogLevel, - Default: notSetValue, - EnvVar: "VAULT_LOG_LEVEL", - Completion: complete.PredictSet("trace", "debug", "info", "warn", "err"), - Usage: "Log verbosity level. Supported values (in order of detail) are " + - "\"trace\", \"debug\", \"info\", \"warn\", and \"err\".", - }) - - f = set.NewFlagSet("Dev Options") - - f.BoolVar(&BoolVar{ - Name: "dev", - Target: &c.flagDev, - Usage: "Enable development mode. In this mode, Vault runs in-memory and " + - "starts unsealed. As the name implies, do not run \"dev\" mode in " + - "production.", - }) - - f.StringVar(&StringVar{ - Name: "dev-root-token-id", - Target: &c.flagDevRootTokenID, - Default: "", - EnvVar: "VAULT_DEV_ROOT_TOKEN_ID", - Usage: "Initial root token. This only applies when running in \"dev\" " + - "mode.", - }) - - f.StringVar(&StringVar{ - Name: "dev-listen-address", - Target: &c.flagDevListenAddr, - Default: "127.0.0.1:8200", - EnvVar: "VAULT_DEV_LISTEN_ADDRESS", - Usage: "Address to bind to in \"dev\" mode.", - }) - - // Internal-only flags to follow. - // - // Why hello there little source code reader! Welcome to the Vault source - // code. The remaining options are intentionally undocumented and come with - // no warranty or backwards-compatability promise. Do not use these flags - // in production. Do not build automation using these flags. Unless you are - // developing against Vault, you should not need any of these flags. - - f.StringVar(&StringVar{ - Name: "dev-plugin-dir", - Target: &c.flagDevPluginDir, - Default: "", - Completion: complete.PredictDirs("*"), - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-plugin-init", - Target: &c.flagDevPluginInit, - Default: true, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-ha", - Target: &c.flagDevHA, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-transactional", - Target: &c.flagDevTransactional, - Default: false, - Hidden: true, - }) - - f.IntVar(&IntVar{ - Name: "dev-latency", - Target: &c.flagDevLatency, - Hidden: true, - }) - - f.IntVar(&IntVar{ - Name: "dev-latency-jitter", - Target: &c.flagDevLatencyJitter, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-leased-kv", - Target: &c.flagDevLeasedKV, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-skip-init", - Target: &c.flagDevSkipInit, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-three-node", - Target: &c.flagDevThreeNode, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "dev-four-cluster", - Target: &c.flagDevFourCluster, - Default: false, - Hidden: true, - }) - - // TODO: should the below flags be public? - f.BoolVar(&BoolVar{ - Name: "combine-logs", - Target: &c.flagCombineLogs, - Default: false, - Hidden: true, - }) - - f.BoolVar(&BoolVar{ - Name: "test-verify-only", - Target: &c.flagTestVerifyOnly, - Default: false, - Hidden: true, - }) - - // End internal-only flags. - - return set -} - -func (c *ServerCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictNothing -} - -func (c *ServerCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *ServerCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Create a logger. We wrap it in a gated writer so that it doesn't - // start logging too early. - c.logGate = &gatedwriter.Writer{Writer: os.Stderr} - c.logWriter = c.logGate - if c.flagCombineLogs { - c.logWriter = os.Stdout - } - var level log.Level - var logLevelWasNotSet bool - c.flagLogLevel = strings.ToLower(strings.TrimSpace(c.flagLogLevel)) - switch c.flagLogLevel { - case notSetValue: - logLevelWasNotSet = true - level = log.Info - case "trace": - level = log.Trace - case "debug": - level = log.Debug - case "notice", "info", "": - level = log.Info - case "warn", "warning": - level = log.Warn - case "err", "error": - level = log.Error - default: - c.UI.Error(fmt.Sprintf("Unknown log level: %s", c.flagLogLevel)) - return 1 - } - - if c.flagDevThreeNode || c.flagDevFourCluster { - c.logger = log.New(&log.LoggerOptions{ - Mutex: &sync.Mutex{}, - Output: c.logWriter, - Level: log.Trace, - }) - } else { - c.logger = logging.NewVaultLoggerWithWriter(c.logWriter, level) - } - - allLoggers := []log.Logger{c.logger} - - // Automatically enable dev mode if other dev flags are provided. - if c.flagDevHA || c.flagDevTransactional || c.flagDevLeasedKV || c.flagDevThreeNode || c.flagDevFourCluster { - c.flagDev = true - } - - // Validation - if !c.flagDev { - switch { - case len(c.flagConfigs) == 0: - c.UI.Error("Must specify at least one config path using -config") - return 1 - case c.flagDevRootTokenID != "": - c.UI.Warn(wrapAtLength( - "You cannot specify a custom root token ID outside of \"dev\" mode. " + - "Your request has been ignored.")) - c.flagDevRootTokenID = "" - } - } - - // Load the configuration - var config *server.Config - if c.flagDev { - config = server.DevConfig(c.flagDevHA, c.flagDevTransactional) - if c.flagDevListenAddr != "" { - config.Listeners[0].Config["address"] = c.flagDevListenAddr - } - } - for _, path := range c.flagConfigs { - current, err := server.LoadConfig(path, c.logger) - if err != nil { - c.UI.Error(fmt.Sprintf("Error loading configuration from %s: %s", path, err)) - return 1 - } - - if config == nil { - config = current - } else { - config = config.Merge(current) - } - } - - // Ensure at least one config was found. - if config == nil { - c.UI.Output(wrapAtLength( - "No configuration files found. Please provide configurations with the " + - "-config flag. If you are supply the path to a directory, please " + - "ensure the directory contains files with the .hcl or .json " + - "extension.")) - return 1 - } - - if config.LogLevel != "" && logLevelWasNotSet { - configLogLevel := strings.ToLower(strings.TrimSpace(config.LogLevel)) - switch configLogLevel { - case "trace": - c.logger.SetLevel(log.Trace) - case "debug": - c.logger.SetLevel(log.Debug) - case "notice", "info", "": - c.logger.SetLevel(log.Info) - case "warn", "warning": - c.logger.SetLevel(log.Warn) - case "err", "error": - c.logger.SetLevel(log.Error) - default: - c.UI.Error(fmt.Sprintf("Unknown log level: %s", config.LogLevel)) - return 1 - } - } - - namedGRPCLogFaker := c.logger.Named("grpclogfaker") - allLoggers = append(allLoggers, namedGRPCLogFaker) - grpclog.SetLogger(&grpclogFaker{ - logger: namedGRPCLogFaker, - log: os.Getenv("VAULT_GRPC_LOGGING") != "", - }) - - // Ensure that a backend is provided - if config.Storage == nil { - c.UI.Output("A storage backend must be specified") - return 1 - } - - if config.DefaultMaxRequestDuration != 0 { - vault.DefaultMaxRequestDuration = config.DefaultMaxRequestDuration - } - - // If mlockall(2) isn't supported, show a warning. We disable this in dev - // because it is quite scary to see when first using Vault. We also disable - // this if the user has explicitly disabled mlock in configuration. - if !c.flagDev && !config.DisableMlock && !mlock.Supported() { - c.UI.Warn(wrapAtLength( - "WARNING! mlock is not supported on this system! An mlockall(2)-like " + - "syscall to prevent memory from being swapped to disk is not " + - "supported on this system. For better security, only run Vault on " + - "systems where this call is supported. If you are running Vault " + - "in a Docker container, provide the IPC_LOCK cap to the container.")) - } - - if err := c.setupTelemetry(config); err != nil { - c.UI.Error(fmt.Sprintf("Error initializing telemetry: %s", err)) - return 1 - } - - // Initialize the backend - factory, exists := c.PhysicalBackends[config.Storage.Type] - if !exists { - c.UI.Error(fmt.Sprintf("Unknown storage type %s", config.Storage.Type)) - return 1 - } - namedStorageLogger := c.logger.Named("storage." + config.Storage.Type) - allLoggers = append(allLoggers, namedStorageLogger) - backend, err := factory(config.Storage.Config, namedStorageLogger) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing storage of type %s: %s", config.Storage.Type, err)) - return 1 - } - - infoKeys := make([]string, 0, 10) - info := make(map[string]string) - info["log level"] = c.flagLogLevel - infoKeys = append(infoKeys, "log level") - - var seal vault.Seal = vault.NewDefaultSeal() - - // Ensure that the seal finalizer is called, even if using verify-only - defer func() { - if seal != nil { - err = seal.Finalize(context.Background()) - if err != nil { - c.UI.Error(fmt.Sprintf("Error finalizing seals: %v", err)) - } - } - }() - - if seal == nil { - c.UI.Error(fmt.Sprintf("Could not create seal! Most likely proper Seal configuration information was not set, but no error was generated.")) - return 1 - } - - coreConfig := &vault.CoreConfig{ - Physical: backend, - RedirectAddr: config.Storage.RedirectAddr, - HAPhysical: nil, - Seal: seal, - AuditBackends: c.AuditBackends, - CredentialBackends: c.CredentialBackends, - LogicalBackends: c.LogicalBackends, - Logger: c.logger, - DisableCache: config.DisableCache, - DisableMlock: config.DisableMlock, - MaxLeaseTTL: config.MaxLeaseTTL, - DefaultLeaseTTL: config.DefaultLeaseTTL, - ClusterName: config.ClusterName, - CacheSize: config.CacheSize, - PluginDirectory: config.PluginDirectory, - EnableUI: config.EnableUI, - EnableRaw: config.EnableRawEndpoint, - AllLoggers: allLoggers, - } - if c.flagDev { - coreConfig.DevToken = c.flagDevRootTokenID - if c.flagDevLeasedKV { - coreConfig.LogicalBackends["kv"] = vault.LeasedPassthroughBackendFactory - } - if c.flagDevPluginDir != "" { - coreConfig.PluginDirectory = c.flagDevPluginDir - } - if c.flagDevLatency > 0 { - injectLatency := time.Duration(c.flagDevLatency) * time.Millisecond - if _, txnOK := backend.(physical.Transactional); txnOK { - coreConfig.Physical = physical.NewTransactionalLatencyInjector(backend, injectLatency, c.flagDevLatencyJitter, c.logger) - } else { - coreConfig.Physical = physical.NewLatencyInjector(backend, injectLatency, c.flagDevLatencyJitter, c.logger) - } - } - } - - if c.flagDevThreeNode { - return c.enableThreeNodeDevCluster(coreConfig, info, infoKeys, c.flagDevListenAddr, os.Getenv("VAULT_DEV_TEMP_DIR")) - } - - var disableClustering bool - - // Initialize the separate HA storage backend, if it exists - var ok bool - if config.HAStorage != nil { - factory, exists := c.PhysicalBackends[config.HAStorage.Type] - if !exists { - c.UI.Error(fmt.Sprintf("Unknown HA storage type %s", config.HAStorage.Type)) - return 1 - - } - habackend, err := factory(config.HAStorage.Config, c.logger) - if err != nil { - c.UI.Error(fmt.Sprintf( - "Error initializing HA storage of type %s: %s", config.HAStorage.Type, err)) - return 1 - - } - - if coreConfig.HAPhysical, ok = habackend.(physical.HABackend); !ok { - c.UI.Error("Specified HA storage does not support HA") - return 1 - } - - if !coreConfig.HAPhysical.HAEnabled() { - c.UI.Error("Specified HA storage has HA support disabled; please consult documentation") - return 1 - } - - coreConfig.RedirectAddr = config.HAStorage.RedirectAddr - disableClustering = config.HAStorage.DisableClustering - if !disableClustering { - coreConfig.ClusterAddr = config.HAStorage.ClusterAddr - } - } else { - if coreConfig.HAPhysical, ok = backend.(physical.HABackend); ok { - coreConfig.RedirectAddr = config.Storage.RedirectAddr - disableClustering = config.Storage.DisableClustering - if !disableClustering { - coreConfig.ClusterAddr = config.Storage.ClusterAddr - } - } - } - - if envRA := os.Getenv("VAULT_API_ADDR"); envRA != "" { - coreConfig.RedirectAddr = envRA - } else if envRA := os.Getenv("VAULT_REDIRECT_ADDR"); envRA != "" { - coreConfig.RedirectAddr = envRA - } else if envAA := os.Getenv("VAULT_ADVERTISE_ADDR"); envAA != "" { - coreConfig.RedirectAddr = envAA - } - - // Attempt to detect the redirect address, if possible - var detect physical.RedirectDetect - if coreConfig.HAPhysical != nil && coreConfig.HAPhysical.HAEnabled() { - detect, ok = coreConfig.HAPhysical.(physical.RedirectDetect) - } else { - detect, ok = coreConfig.Physical.(physical.RedirectDetect) - } - if ok && coreConfig.RedirectAddr == "" { - redirect, err := c.detectRedirect(detect, config) - if err != nil { - c.UI.Error(fmt.Sprintf("Error detecting api address: %s", err)) - } else if redirect == "" { - c.UI.Error("Failed to detect api address") - } else { - coreConfig.RedirectAddr = redirect - } - } - if coreConfig.RedirectAddr == "" && c.flagDev { - coreConfig.RedirectAddr = fmt.Sprintf("http://%s", config.Listeners[0].Config["address"]) - } - - // After the redirect bits are sorted out, if no cluster address was - // explicitly given, derive one from the redirect addr - if disableClustering { - coreConfig.ClusterAddr = "" - } else if envCA := os.Getenv("VAULT_CLUSTER_ADDR"); envCA != "" { - coreConfig.ClusterAddr = envCA - } else { - var addrToUse string - switch { - case coreConfig.ClusterAddr == "" && coreConfig.RedirectAddr != "": - addrToUse = coreConfig.RedirectAddr - case c.flagDev: - addrToUse = fmt.Sprintf("http://%s", config.Listeners[0].Config["address"]) - default: - goto CLUSTER_SYNTHESIS_COMPLETE - } - u, err := url.ParseRequestURI(addrToUse) - if err != nil { - c.UI.Error(fmt.Sprintf( - "Error parsing synthesized cluster address %s: %v", addrToUse, err)) - return 1 - } - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - // This sucks, as it's a const in the function but not exported in the package - if strings.Contains(err.Error(), "missing port in address") { - host = u.Host - port = "443" - } else { - c.UI.Error(fmt.Sprintf("Error parsing api address: %v", err)) - return 1 - } - } - nPort, err := strconv.Atoi(port) - if err != nil { - c.UI.Error(fmt.Sprintf( - "Error parsing synthesized address; failed to convert %q to a numeric: %v", port, err)) - return 1 - } - u.Host = net.JoinHostPort(host, strconv.Itoa(nPort+1)) - // Will always be TLS-secured - u.Scheme = "https" - coreConfig.ClusterAddr = u.String() - } - -CLUSTER_SYNTHESIS_COMPLETE: - - if coreConfig.RedirectAddr == coreConfig.ClusterAddr && len(coreConfig.RedirectAddr) != 0 { - c.UI.Error(fmt.Sprintf( - "Address %q used for both API and cluster addresses", coreConfig.RedirectAddr)) - return 1 - } - - if coreConfig.ClusterAddr != "" { - // Force https as we'll always be TLS-secured - u, err := url.ParseRequestURI(coreConfig.ClusterAddr) - if err != nil { - c.UI.Error(fmt.Sprintf("Error parsing cluster address %s: %v", coreConfig.ClusterAddr, err)) - return 11 - } - u.Scheme = "https" - coreConfig.ClusterAddr = u.String() - } - - // Override the UI enabling config by the environment variable - if enableUI := os.Getenv("VAULT_UI"); enableUI != "" { - var err error - coreConfig.EnableUI, err = strconv.ParseBool(enableUI) - if err != nil { - c.UI.Output("Error parsing the environment variable VAULT_UI") - return 1 - } - } - - // Initialize the core - core, newCoreError := vault.NewCore(coreConfig) - if newCoreError != nil { - if !errwrap.ContainsType(newCoreError, new(vault.NonFatalError)) { - c.UI.Error(fmt.Sprintf("Error initializing core: %s", newCoreError)) - return 1 - } - } - - // Copy the reload funcs pointers back - c.reloadFuncs = coreConfig.ReloadFuncs - c.reloadFuncsLock = coreConfig.ReloadFuncsLock - - // Compile server information for output later - info["storage"] = config.Storage.Type - info["log level"] = c.flagLogLevel - info["mlock"] = fmt.Sprintf( - "supported: %v, enabled: %v", - mlock.Supported(), !config.DisableMlock && mlock.Supported()) - infoKeys = append(infoKeys, "mlock", "storage") - - if coreConfig.ClusterAddr != "" { - info["cluster address"] = coreConfig.ClusterAddr - infoKeys = append(infoKeys, "cluster address") - } - if coreConfig.RedirectAddr != "" { - info["api address"] = coreConfig.RedirectAddr - infoKeys = append(infoKeys, "api address") - } - - if config.HAStorage != nil { - info["HA storage"] = config.HAStorage.Type - infoKeys = append(infoKeys, "HA storage") - } else { - // If the storage supports HA, then note it - if coreConfig.HAPhysical != nil { - if coreConfig.HAPhysical.HAEnabled() { - info["storage"] += " (HA available)" - } else { - info["storage"] += " (HA disabled)" - } - } - } - - clusterAddrs := []*net.TCPAddr{} - - // Initialize the listeners - lns := make([]ServerListener, 0, len(config.Listeners)) - c.reloadFuncsLock.Lock() - for i, lnConfig := range config.Listeners { - ln, props, reloadFunc, err := server.NewListener(lnConfig.Type, lnConfig.Config, c.logWriter, c.UI) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing listener of type %s: %s", lnConfig.Type, err)) - return 1 - } - - if reloadFunc != nil { - relSlice := (*c.reloadFuncs)["listener|"+lnConfig.Type] - relSlice = append(relSlice, reloadFunc) - (*c.reloadFuncs)["listener|"+lnConfig.Type] = relSlice - } - - if !disableClustering && lnConfig.Type == "tcp" { - var addrRaw interface{} - var addr string - var ok bool - if addrRaw, ok = lnConfig.Config["cluster_address"]; ok { - addr = addrRaw.(string) - tcpAddr, err := net.ResolveTCPAddr("tcp", addr) - if err != nil { - c.UI.Error(fmt.Sprintf("Error resolving cluster_address: %s", err)) - return 1 - } - clusterAddrs = append(clusterAddrs, tcpAddr) - } else { - tcpAddr, ok := ln.Addr().(*net.TCPAddr) - if !ok { - c.UI.Error("Failed to parse tcp listener") - return 1 - } - clusterAddr := &net.TCPAddr{ - IP: tcpAddr.IP, - Port: tcpAddr.Port + 1, - } - clusterAddrs = append(clusterAddrs, clusterAddr) - addr = clusterAddr.String() - } - props["cluster address"] = addr - } - - var maxRequestSize int64 = vaulthttp.DefaultMaxRequestSize - if valRaw, ok := lnConfig.Config["max_request_size"]; ok { - val, err := parseutil.ParseInt(valRaw) - if err != nil { - c.UI.Error(fmt.Sprintf("Could not parse max_request_size value %v", valRaw)) - return 1 - } - - if val >= 0 { - maxRequestSize = val - } - } - props["max_request_size"] = fmt.Sprintf("%d", maxRequestSize) - - var maxRequestDuration time.Duration = vault.DefaultMaxRequestDuration - if valRaw, ok := lnConfig.Config["max_request_duration"]; ok { - val, err := parseutil.ParseDurationSecond(valRaw) - if err != nil { - c.UI.Error(fmt.Sprintf("Could not parse max_request_duration value %v", valRaw)) - return 1 - } - - if val >= 0 { - maxRequestDuration = val - } - } - props["max_request_duration"] = fmt.Sprintf("%s", maxRequestDuration.String()) - - lns = append(lns, ServerListener{ - Listener: ln, - config: lnConfig.Config, - maxRequestSize: maxRequestSize, - maxRequestDuration: maxRequestDuration, - }) - - // Store the listener props for output later - key := fmt.Sprintf("listener %d", i+1) - propsList := make([]string, 0, len(props)) - for k, v := range props { - propsList = append(propsList, fmt.Sprintf( - "%s: %q", k, v)) - } - sort.Strings(propsList) - infoKeys = append(infoKeys, key) - info[key] = fmt.Sprintf( - "%s (%s)", lnConfig.Type, strings.Join(propsList, ", ")) - - } - c.reloadFuncsLock.Unlock() - if !disableClustering { - if c.logger.IsDebug() { - c.logger.Debug("cluster listener addresses synthesized", "cluster_addresses", clusterAddrs) - } - } - - // Make sure we close all listeners from this point on - listenerCloseFunc := func() { - for _, ln := range lns { - ln.Listener.Close() - } - } - - defer c.cleanupGuard.Do(listenerCloseFunc) - - infoKeys = append(infoKeys, "version") - verInfo := version.GetVersion() - info["version"] = verInfo.FullVersionNumber(false) - if verInfo.Revision != "" { - info["version sha"] = strings.Trim(verInfo.Revision, "'") - infoKeys = append(infoKeys, "version sha") - } - infoKeys = append(infoKeys, "cgo") - info["cgo"] = "disabled" - if version.CgoEnabled { - info["cgo"] = "enabled" - } - - // Server configuration output - padding := 24 - sort.Strings(infoKeys) - c.UI.Output("==> Vault server configuration:\n") - for _, k := range infoKeys { - c.UI.Output(fmt.Sprintf( - "%s%s: %s", - strings.Repeat(" ", padding-len(k)), - strings.Title(k), - info[k])) - } - c.UI.Output("") - - // Tests might not want to start a vault server and just want to verify - // the configuration. - if c.flagTestVerifyOnly { - return 0 - } - - // This needs to happen before we first unseal, so before we trigger dev - // mode if it's set - core.SetClusterListenerAddrs(clusterAddrs) - core.SetClusterHandler(vaulthttp.Handler(&vault.HandlerProperties{ - Core: core, - })) - - err = core.UnsealWithStoredKeys(context.Background()) - if err != nil { - if !errwrap.ContainsType(err, new(vault.NonFatalError)) { - c.UI.Error(fmt.Sprintf("Error initializing core: %s", err)) - return 1 - } - } - - // Perform service discovery registrations and initialization of - // HTTP server after the verifyOnly check. - - // Instantiate the wait group - c.WaitGroup = &sync.WaitGroup{} - - // If the backend supports service discovery, run service discovery - if coreConfig.HAPhysical != nil && coreConfig.HAPhysical.HAEnabled() { - sd, ok := coreConfig.HAPhysical.(physical.ServiceDiscovery) - if ok { - activeFunc := func() bool { - if isLeader, _, _, err := core.Leader(); err == nil { - return isLeader - } - return false - } - - if err := sd.RunServiceDiscovery(c.WaitGroup, c.ShutdownCh, coreConfig.RedirectAddr, activeFunc, core.Sealed); err != nil { - c.UI.Error(fmt.Sprintf("Error initializing service discovery: %v", err)) - return 1 - } - } - } - - // If we're in Dev mode, then initialize the core - if c.flagDev && !c.flagDevSkipInit { - init, err := c.enableDev(core, coreConfig) - if err != nil { - c.UI.Error(fmt.Sprintf("Error initializing Dev mode: %s", err)) - return 1 - } - - var plugins []string - if c.flagDevPluginDir != "" && c.flagDevPluginInit { - f, err := os.Open(c.flagDevPluginDir) - if err != nil { - c.UI.Error(fmt.Sprintf("Error reading plugin dir: %s", err)) - return 1 - } - - list, err := f.Readdirnames(0) - f.Close() - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing plugins: %s", err)) - return 1 - } - - for _, name := range list { - path := filepath.Join(f.Name(), name) - if err := c.addPlugin(path, init.RootToken, core); err != nil { - c.UI.Error(fmt.Sprintf("Error enabling plugin %s: %s", name, err)) - return 1 - } - plugins = append(plugins, name) - } - - sort.Strings(plugins) - } - - export := "export" - quote := "'" - if runtime.GOOS == "windows" { - export = "set" - quote = "" - } - - // Print the big dev mode warning! - c.UI.Warn(wrapAtLength( - "WARNING! dev mode is enabled! In this mode, Vault runs entirely " + - "in-memory and starts unsealed with a single unseal key. The root " + - "token is already authenticated to the CLI, so you can immediately " + - "begin using Vault.")) - c.UI.Warn("") - c.UI.Warn("You may need to set the following environment variable:") - c.UI.Warn("") - c.UI.Warn(fmt.Sprintf(" $ %s VAULT_ADDR=%s%s%s", - export, quote, "http://"+config.Listeners[0].Config["address"].(string), quote)) - - // Unseal key is not returned if stored shares is supported - if len(init.SecretShares) > 0 { - c.UI.Warn("") - c.UI.Warn(wrapAtLength( - "The unseal key and root token are displayed below in case you want " + - "to seal/unseal the Vault or re-authenticate.")) - c.UI.Warn("") - c.UI.Warn(fmt.Sprintf("Unseal Key: %s", base64.StdEncoding.EncodeToString(init.SecretShares[0]))) - } - - if len(init.RecoveryShares) > 0 { - c.UI.Warn("") - c.UI.Warn(wrapAtLength( - "The recovery key and root token are displayed below in case you want " + - "to seal/unseal the Vault or re-authenticate.")) - c.UI.Warn("") - c.UI.Warn(fmt.Sprintf("Unseal Key: %s", base64.StdEncoding.EncodeToString(init.RecoveryShares[0]))) - } - - c.UI.Warn(fmt.Sprintf("Root Token: %s", init.RootToken)) - - if len(plugins) > 0 { - c.UI.Warn("") - c.UI.Warn(wrapAtLength( - "The following dev plugins are registered in the catalog:")) - for _, p := range plugins { - c.UI.Warn(fmt.Sprintf(" - %s", p)) - } - } - - c.UI.Warn("") - c.UI.Warn(wrapAtLength( - "Development mode should NOT be used in production installations!")) - c.UI.Warn("") - } - - // Initialize the HTTP servers - for _, ln := range lns { - handler := vaulthttp.Handler(&vault.HandlerProperties{ - Core: core, - MaxRequestSize: ln.maxRequestSize, - MaxRequestDuration: ln.maxRequestDuration, - DisablePrintableCheck: config.DisablePrintableCheck, - }) - - // We perform validation on the config earlier, we can just cast here - if _, ok := ln.config["x_forwarded_for_authorized_addrs"]; ok { - hopSkips := ln.config["x_forwarded_for_hop_skips"].(int) - authzdAddrs := ln.config["x_forwarded_for_authorized_addrs"].([]*sockaddr.SockAddrMarshaler) - rejectNotPresent := ln.config["x_forwarded_for_reject_not_present"].(bool) - rejectNonAuthz := ln.config["x_forwarded_for_reject_not_authorized"].(bool) - if len(authzdAddrs) > 0 { - handler = vaulthttp.WrapForwardedForHandler(handler, authzdAddrs, rejectNotPresent, rejectNonAuthz, hopSkips) - } - } - - server := &http.Server{ - Handler: handler, - ReadHeaderTimeout: 10 * time.Second, - ReadTimeout: 30 * time.Second, - IdleTimeout: 5 * time.Minute, - ErrorLog: c.logger.StandardLogger(nil), - } - go server.Serve(ln.Listener) - } - - if newCoreError != nil { - c.UI.Warn(wrapAtLength( - "WARNING! A non-fatal error occurred during initialization. Please " + - "check the logs for more information.")) - c.UI.Warn("") - } - - // Output the header that the server has started - if !c.flagCombineLogs { - c.UI.Output("==> Vault server started! Log data will stream in below:\n") - } - - // Inform any tests that the server is ready - select { - case c.startedCh <- struct{}{}: - default: - } - - // Release the log gate. - c.logGate.Flush() - - // Write out the PID to the file now that server has successfully started - if err := c.storePidFile(config.PidFile); err != nil { - c.UI.Error(fmt.Sprintf("Error storing PID: %s", err)) - return 1 - } - - defer func() { - if err := c.removePidFile(config.PidFile); err != nil { - c.UI.Error(fmt.Sprintf("Error deleting the PID file: %s", err)) - } - }() - - // Wait for shutdown - shutdownTriggered := false - - for !shutdownTriggered { - select { - case <-c.ShutdownCh: - c.UI.Output("==> Vault shutdown triggered") - - // Stop the listeners so that we don't process further client requests. - c.cleanupGuard.Do(listenerCloseFunc) - - // Shutdown will wait until after Vault is sealed, which means the - // request forwarding listeners will also be closed (and also - // waited for). - if err := core.Shutdown(); err != nil { - c.UI.Error(fmt.Sprintf("Error with core shutdown: %s", err)) - } - - shutdownTriggered = true - - case <-c.SighupCh: - c.UI.Output("==> Vault reload triggered") - - // Check for new log level - var config *server.Config - var level log.Level - for _, path := range c.flagConfigs { - current, err := server.LoadConfig(path, c.logger) - if err != nil { - c.logger.Error("could not reload config", "path", path, "error", err) - goto RUNRELOADFUNCS - } - - if config == nil { - config = current - } else { - config = config.Merge(current) - } - } - - // Ensure at least one config was found. - if config == nil { - c.logger.Error("no config found at reload time") - goto RUNRELOADFUNCS - } - - if config.LogLevel != "" { - configLogLevel := strings.ToLower(strings.TrimSpace(config.LogLevel)) - switch configLogLevel { - case "trace": - level = log.Trace - case "debug": - level = log.Debug - case "notice", "info", "": - level = log.Info - case "warn", "warning": - level = log.Warn - case "err", "error": - level = log.Error - default: - c.logger.Error("unknown log level found on reload", "level", config.LogLevel) - goto RUNRELOADFUNCS - } - core.SetLogLevel(level) - } - - RUNRELOADFUNCS: - if err := c.Reload(c.reloadFuncsLock, c.reloadFuncs, c.flagConfigs); err != nil { - c.UI.Error(fmt.Sprintf("Error(s) were encountered during reload: %s", err)) - } - } - } - - // Wait for dependent goroutines to complete - c.WaitGroup.Wait() - return 0 -} - -func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig) (*vault.InitResult, error) { - var recoveryConfig *vault.SealConfig - barrierConfig := &vault.SealConfig{ - SecretShares: 1, - SecretThreshold: 1, - } - - if core.SealAccess().RecoveryKeySupported() { - recoveryConfig = &vault.SealConfig{ - SecretShares: 1, - SecretThreshold: 1, - } - } - - if core.SealAccess().StoredKeysSupported() { - barrierConfig.StoredShares = 1 - } - - ctx := context.Background() - - // Initialize it with a basic single key - init, err := core.Initialize(ctx, &vault.InitParams{ - BarrierConfig: barrierConfig, - RecoveryConfig: recoveryConfig, - }) - if err != nil { - return nil, err - } - - // Handle unseal with stored keys - if core.SealAccess().StoredKeysSupported() { - err := core.UnsealWithStoredKeys(ctx) - if err != nil { - return nil, err - } - } else { - // Copy the key so that it can be zeroed - key := make([]byte, len(init.SecretShares[0])) - copy(key, init.SecretShares[0]) - - // Unseal the core - unsealed, err := core.Unseal(key) - if err != nil { - return nil, err - } - if !unsealed { - return nil, fmt.Errorf("failed to unseal Vault for dev mode") - } - } - - isLeader, _, _, err := core.Leader() - if err != nil && err != vault.ErrHANotEnabled { - return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) - } - if err == nil { - leaderCount := 5 - for !isLeader { - if leaderCount == 0 { - buf := make([]byte, 1<<16) - runtime.Stack(buf, true) - return nil, fmt.Errorf("failed to get active status after five seconds; call stack is\n%s\n", buf) - } - time.Sleep(1 * time.Second) - isLeader, _, _, err = core.Leader() - if err != nil { - return nil, errwrap.Wrapf("failed to check active status: {{err}}", err) - } - leaderCount-- - } - } - - // Generate a dev root token if one is provided in the flag - if coreConfig.DevToken != "" { - req := &logical.Request{ - ID: "dev-gen-root", - Operation: logical.UpdateOperation, - ClientToken: init.RootToken, - Path: "auth/token/create", - Data: map[string]interface{}{ - "id": coreConfig.DevToken, - "policies": []string{"root"}, - "no_parent": true, - "no_default_policy": true, - }, - } - resp, err := core.HandleRequest(context.Background(), req) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to create root token with ID %q: {{err}}", coreConfig.DevToken), err) - } - if resp == nil { - return nil, fmt.Errorf("nil response when creating root token with ID %q", coreConfig.DevToken) - } - if resp.Auth == nil { - return nil, fmt.Errorf("nil auth when creating root token with ID %q", coreConfig.DevToken) - } - - init.RootToken = resp.Auth.ClientToken - - req.ID = "dev-revoke-init-root" - req.Path = "auth/token/revoke-self" - req.Data = nil - resp, err = core.HandleRequest(context.Background(), req) - if err != nil { - return nil, errwrap.Wrapf("failed to revoke initial root token: {{err}}", err) - } - } - - // Set the token - tokenHelper, err := c.TokenHelper() - if err != nil { - return nil, err - } - if err := tokenHelper.Store(init.RootToken); err != nil { - return nil, err - } - - // Upgrade the default K/V store - if !c.flagDevLeasedKV { - req := &logical.Request{ - Operation: logical.UpdateOperation, - ClientToken: init.RootToken, - Path: "sys/mounts/secret/tune", - Data: map[string]interface{}{ - "options": map[string]string{ - "version": "2", - }, - }, - } - resp, err := core.HandleRequest(context.Background(), req) - if err != nil { - return nil, errwrap.Wrapf("error upgrading default K/V store: {{err}}", err) - } - if resp.IsError() { - return nil, errwrap.Wrapf("failed to upgrade default K/V store: {{err}}", resp.Error()) - } - } - - return init, nil -} - -func (c *ServerCommand) enableThreeNodeDevCluster(base *vault.CoreConfig, info map[string]string, infoKeys []string, devListenAddress, tempDir string) int { - testCluster := vault.NewTestCluster(&testing.RuntimeT{}, base, &vault.TestClusterOptions{ - HandlerFunc: vaulthttp.Handler, - BaseListenAddress: c.flagDevListenAddr, - Logger: c.logger, - TempDir: tempDir, - }) - defer c.cleanupGuard.Do(testCluster.Cleanup) - - info["cluster parameters path"] = testCluster.TempDir - infoKeys = append(infoKeys, "cluster parameters path") - - for i, core := range testCluster.Cores { - info[fmt.Sprintf("node %d api address", i)] = fmt.Sprintf("https://%s", core.Listeners[0].Address.String()) - infoKeys = append(infoKeys, fmt.Sprintf("node %d api address", i)) - } - - infoKeys = append(infoKeys, "version") - verInfo := version.GetVersion() - info["version"] = verInfo.FullVersionNumber(false) - if verInfo.Revision != "" { - info["version sha"] = strings.Trim(verInfo.Revision, "'") - infoKeys = append(infoKeys, "version sha") - } - infoKeys = append(infoKeys, "cgo") - info["cgo"] = "disabled" - if version.CgoEnabled { - info["cgo"] = "enabled" - } - - // Server configuration output - padding := 24 - sort.Strings(infoKeys) - c.UI.Output("==> Vault server configuration:\n") - for _, k := range infoKeys { - c.UI.Output(fmt.Sprintf( - "%s%s: %s", - strings.Repeat(" ", padding-len(k)), - strings.Title(k), - info[k])) - } - c.UI.Output("") - - for _, core := range testCluster.Cores { - core.Server.Handler = vaulthttp.Handler(&vault.HandlerProperties{ - Core: core.Core, - }) - core.SetClusterHandler(core.Server.Handler) - } - - testCluster.Start() - - if base.DevToken != "" { - req := &logical.Request{ - ID: "dev-gen-root", - Operation: logical.UpdateOperation, - ClientToken: testCluster.RootToken, - Path: "auth/token/create", - Data: map[string]interface{}{ - "id": base.DevToken, - "policies": []string{"root"}, - "no_parent": true, - "no_default_policy": true, - }, - } - resp, err := testCluster.Cores[0].HandleRequest(context.Background(), req) - if err != nil { - c.UI.Error(fmt.Sprintf("failed to create root token with ID %s: %s", base.DevToken, err)) - return 1 - } - if resp == nil { - c.UI.Error(fmt.Sprintf("nil response when creating root token with ID %s", base.DevToken)) - return 1 - } - if resp.Auth == nil { - c.UI.Error(fmt.Sprintf("nil auth when creating root token with ID %s", base.DevToken)) - return 1 - } - - testCluster.RootToken = resp.Auth.ClientToken - - req.ID = "dev-revoke-init-root" - req.Path = "auth/token/revoke-self" - req.Data = nil - resp, err = testCluster.Cores[0].HandleRequest(context.Background(), req) - if err != nil { - c.UI.Output(fmt.Sprintf("failed to revoke initial root token: %s", err)) - return 1 - } - } - - // Set the token - tokenHelper, err := c.TokenHelper() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting token helper: %s", err)) - return 1 - } - if err := tokenHelper.Store(testCluster.RootToken); err != nil { - c.UI.Error(fmt.Sprintf("Error storing in token helper: %s", err)) - return 1 - } - - if err := ioutil.WriteFile(filepath.Join(testCluster.TempDir, "root_token"), []byte(testCluster.RootToken), 0755); err != nil { - c.UI.Error(fmt.Sprintf("Error writing token to tempfile: %s", err)) - return 1 - } - - c.UI.Output(fmt.Sprintf( - "==> Three node dev mode is enabled\n\n" + - "The unseal key and root token are reproduced below in case you\n" + - "want to seal/unseal the Vault or play with authentication.\n", - )) - - for i, key := range testCluster.BarrierKeys { - c.UI.Output(fmt.Sprintf( - "Unseal Key %d: %s", - i+1, base64.StdEncoding.EncodeToString(key), - )) - } - - c.UI.Output(fmt.Sprintf( - "\nRoot Token: %s\n", testCluster.RootToken, - )) - - c.UI.Output(fmt.Sprintf( - "\nUseful env vars:\n"+ - "VAULT_TOKEN=%s\n"+ - "VAULT_ADDR=%s\n"+ - "VAULT_CACERT=%s/ca_cert.pem\n", - testCluster.RootToken, - testCluster.Cores[0].Client.Address(), - testCluster.TempDir, - )) - - // Output the header that the server has started - c.UI.Output("==> Vault server started! Log data will stream in below:\n") - - // Inform any tests that the server is ready - select { - case c.startedCh <- struct{}{}: - default: - } - - // Release the log gate. - c.logGate.Flush() - - // Wait for shutdown - shutdownTriggered := false - - for !shutdownTriggered { - select { - case <-c.ShutdownCh: - c.UI.Output("==> Vault shutdown triggered") - - // Stop the listeners so that we don't process further client requests. - c.cleanupGuard.Do(testCluster.Cleanup) - - // Shutdown will wait until after Vault is sealed, which means the - // request forwarding listeners will also be closed (and also - // waited for). - for _, core := range testCluster.Cores { - if err := core.Shutdown(); err != nil { - c.UI.Error(fmt.Sprintf("Error with core shutdown: %s", err)) - } - } - - shutdownTriggered = true - - case <-c.SighupCh: - c.UI.Output("==> Vault reload triggered") - for _, core := range testCluster.Cores { - if err := c.Reload(core.ReloadFuncsLock, core.ReloadFuncs, nil); err != nil { - c.UI.Error(fmt.Sprintf("Error(s) were encountered during reload: %s", err)) - } - } - } - } - - return 0 -} - -// addPlugin adds any plugins to the catalog -func (c *ServerCommand) addPlugin(path, token string, core *vault.Core) error { - // Get the sha256 of the file at the given path. - pluginSum := func(p string) (string, error) { - hasher := sha256.New() - f, err := os.Open(p) - if err != nil { - return "", err - } - defer f.Close() - if _, err := io.Copy(hasher, f); err != nil { - return "", err - } - return hex.EncodeToString(hasher.Sum(nil)), nil - } - - // Mount any test plugins. We do this explicitly before we inform tests of - // a completely booted server intentionally. - sha256sum, err := pluginSum(path) - if err != nil { - return err - } - - // Default the name to the basename of the binary - name := filepath.Base(path) - - // File a request against core to enable the plugin - req := &logical.Request{ - Operation: logical.UpdateOperation, - ClientToken: token, - Path: "sys/plugins/catalog/" + name, - Data: map[string]interface{}{ - "sha256": sha256sum, - "command": name, - }, - } - if _, err := core.HandleRequest(context.Background(), req); err != nil { - return err - } - - return nil -} - -// detectRedirect is used to attempt redirect address detection -func (c *ServerCommand) detectRedirect(detect physical.RedirectDetect, - config *server.Config) (string, error) { - // Get the hostname - host, err := detect.DetectHostAddr() - if err != nil { - return "", err - } - - // set [] for ipv6 addresses - if strings.Contains(host, ":") && !strings.Contains(host, "]") { - host = "[" + host + "]" - } - - // Default the port and scheme - scheme := "https" - port := 8200 - - // Attempt to detect overrides - for _, list := range config.Listeners { - // Only attempt TCP - if list.Type != "tcp" { - continue - } - - // Check if TLS is disabled - if val, ok := list.Config["tls_disable"]; ok { - disable, err := parseutil.ParseBool(val) - if err != nil { - return "", errwrap.Wrapf("tls_disable: {{err}}", err) - } - - if disable { - scheme = "http" - } - } - - // Check for address override - var addr string - addrRaw, ok := list.Config["address"] - if !ok { - addr = "127.0.0.1:8200" - } else { - addr = addrRaw.(string) - } - - // Check for localhost - hostStr, portStr, err := net.SplitHostPort(addr) - if err != nil { - continue - } - if hostStr == "127.0.0.1" { - host = hostStr - } - - // Check for custom port - listPort, err := strconv.Atoi(portStr) - if err != nil { - continue - } - port = listPort - } - - // Build a URL - url := &url.URL{ - Scheme: scheme, - Host: fmt.Sprintf("%s:%d", host, port), - } - - // Return the URL string - return url.String(), nil -} - -// setupTelemetry is used to setup the telemetry sub-systems -func (c *ServerCommand) setupTelemetry(config *server.Config) error { - /* Setup telemetry - Aggregate on 10 second intervals for 1 minute. Expose the - metrics over stderr when there is a SIGUSR1 received. - */ - inm := metrics.NewInmemSink(10*time.Second, time.Minute) - metrics.DefaultInmemSignal(inm) - - var telConfig *server.Telemetry - if config.Telemetry == nil { - telConfig = &server.Telemetry{} - } else { - telConfig = config.Telemetry - } - - metricsConf := metrics.DefaultConfig("vault") - metricsConf.EnableHostname = !telConfig.DisableHostname - - // Configure the statsite sink - var fanout metrics.FanoutSink - if telConfig.StatsiteAddr != "" { - sink, err := metrics.NewStatsiteSink(telConfig.StatsiteAddr) - if err != nil { - return err - } - fanout = append(fanout, sink) - } - - // Configure the statsd sink - if telConfig.StatsdAddr != "" { - sink, err := metrics.NewStatsdSink(telConfig.StatsdAddr) - if err != nil { - return err - } - fanout = append(fanout, sink) - } - - // Configure the Circonus sink - if telConfig.CirconusAPIToken != "" || telConfig.CirconusCheckSubmissionURL != "" { - cfg := &circonus.Config{} - cfg.Interval = telConfig.CirconusSubmissionInterval - cfg.CheckManager.API.TokenKey = telConfig.CirconusAPIToken - cfg.CheckManager.API.TokenApp = telConfig.CirconusAPIApp - cfg.CheckManager.API.URL = telConfig.CirconusAPIURL - cfg.CheckManager.Check.SubmissionURL = telConfig.CirconusCheckSubmissionURL - cfg.CheckManager.Check.ID = telConfig.CirconusCheckID - cfg.CheckManager.Check.ForceMetricActivation = telConfig.CirconusCheckForceMetricActivation - cfg.CheckManager.Check.InstanceID = telConfig.CirconusCheckInstanceID - cfg.CheckManager.Check.SearchTag = telConfig.CirconusCheckSearchTag - cfg.CheckManager.Check.DisplayName = telConfig.CirconusCheckDisplayName - cfg.CheckManager.Check.Tags = telConfig.CirconusCheckTags - cfg.CheckManager.Broker.ID = telConfig.CirconusBrokerID - cfg.CheckManager.Broker.SelectTag = telConfig.CirconusBrokerSelectTag - - if cfg.CheckManager.API.TokenApp == "" { - cfg.CheckManager.API.TokenApp = "vault" - } - - if cfg.CheckManager.Check.DisplayName == "" { - cfg.CheckManager.Check.DisplayName = "Vault" - } - - if cfg.CheckManager.Check.SearchTag == "" { - cfg.CheckManager.Check.SearchTag = "service:vault" - } - - sink, err := circonus.NewCirconusSink(cfg) - if err != nil { - return err - } - sink.Start() - fanout = append(fanout, sink) - } - - if telConfig.DogStatsDAddr != "" { - var tags []string - - if telConfig.DogStatsDTags != nil { - tags = telConfig.DogStatsDTags - } - - sink, err := datadog.NewDogStatsdSink(telConfig.DogStatsDAddr, metricsConf.HostName) - if err != nil { - return errwrap.Wrapf("failed to start DogStatsD sink: {{err}}", err) - } - sink.SetTags(tags) - fanout = append(fanout, sink) - } - - // Initialize the global sink - if len(fanout) > 0 { - fanout = append(fanout, inm) - metrics.NewGlobal(metricsConf, fanout) - } else { - metricsConf.EnableHostname = false - metrics.NewGlobal(metricsConf, inm) - } - return nil -} - -func (c *ServerCommand) Reload(lock *sync.RWMutex, reloadFuncs *map[string][]reload.ReloadFunc, configPath []string) error { - lock.RLock() - defer lock.RUnlock() - - var reloadErrors *multierror.Error - - for k, relFuncs := range *reloadFuncs { - switch { - case strings.HasPrefix(k, "listener|"): - for _, relFunc := range relFuncs { - if relFunc != nil { - if err := relFunc(nil); err != nil { - reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf("error encountered reloading listener: {{err}}", err)) - } - } - } - - case strings.HasPrefix(k, "audit_file|"): - for _, relFunc := range relFuncs { - if relFunc != nil { - if err := relFunc(nil); err != nil { - reloadErrors = multierror.Append(reloadErrors, errwrap.Wrapf(fmt.Sprintf("error encountered reloading file audit device at path %q: {{err}}", strings.TrimPrefix(k, "audit_file|")), err)) - } - } - } - } - } - - // Send a message that we reloaded. This prevents "guessing" sleep times - // in tests. - select { - case c.reloadedCh <- struct{}{}: - default: - } - - return reloadErrors.ErrorOrNil() -} - -// storePidFile is used to write out our PID to a file if necessary -func (c *ServerCommand) storePidFile(pidPath string) error { - // Quit fast if no pidfile - if pidPath == "" { - return nil - } - - // Open the PID file - pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) - if err != nil { - return errwrap.Wrapf("could not open pid file: {{err}}", err) - } - defer pidFile.Close() - - // Write out the PID - pid := os.Getpid() - _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) - if err != nil { - return errwrap.Wrapf("could not write to pid file: {{err}}", err) - } - return nil -} - -// removePidFile is used to cleanup the PID file if necessary -func (c *ServerCommand) removePidFile(pidPath string) error { - if pidPath == "" { - return nil - } - return os.Remove(pidPath) -} - -type grpclogFaker struct { - logger log.Logger - log bool -} - -func (g *grpclogFaker) Fatal(args ...interface{}) { - g.logger.Error(fmt.Sprint(args...)) - os.Exit(1) -} - -func (g *grpclogFaker) Fatalf(format string, args ...interface{}) { - g.logger.Error(fmt.Sprintf(format, args...)) - os.Exit(1) -} - -func (g *grpclogFaker) Fatalln(args ...interface{}) { - g.logger.Error(fmt.Sprintln(args...)) - os.Exit(1) -} - -func (g *grpclogFaker) Print(args ...interface{}) { - if g.log && g.logger.IsDebug() { - g.logger.Debug(fmt.Sprint(args...)) - } -} - -func (g *grpclogFaker) Printf(format string, args ...interface{}) { - if g.log && g.logger.IsDebug() { - g.logger.Debug(fmt.Sprintf(format, args...)) - } -} - -func (g *grpclogFaker) Println(args ...interface{}) { - if g.log && g.logger.IsDebug() { - g.logger.Debug(fmt.Sprintln(args...)) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/server/config.go b/vendor/github.com/hashicorp/vault/command/server/config.go deleted file mode 100644 index 715120a98..000000000 --- a/vendor/github.com/hashicorp/vault/command/server/config.go +++ /dev/null @@ -1,804 +0,0 @@ -package server - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/helper/parseutil" -) - -// Config is the configuration for the vault server. -type Config struct { - Listeners []*Listener `hcl:"-"` - Storage *Storage `hcl:"-"` - HAStorage *Storage `hcl:"-"` - - Seal *Seal `hcl:"-"` - - CacheSize int `hcl:"cache_size"` - DisableCache bool `hcl:"-"` - DisableCacheRaw interface{} `hcl:"disable_cache"` - DisableMlock bool `hcl:"-"` - DisableMlockRaw interface{} `hcl:"disable_mlock"` - DisablePrintableCheck bool `hcl:"-"` - DisablePrintableCheckRaw interface{} `hcl:"disable_printable_check"` - - EnableUI bool `hcl:"-"` - EnableUIRaw interface{} `hcl:"ui"` - - Telemetry *Telemetry `hcl:"telemetry"` - - MaxLeaseTTL time.Duration `hcl:"-"` - MaxLeaseTTLRaw interface{} `hcl:"max_lease_ttl"` - DefaultLeaseTTL time.Duration `hcl:"-"` - DefaultLeaseTTLRaw interface{} `hcl:"default_lease_ttl"` - - DefaultMaxRequestDuration time.Duration `hcl:"-"` - DefaultMaxRequestDurationRaw interface{} `hcl:"default_max_request_time"` - - ClusterName string `hcl:"cluster_name"` - ClusterCipherSuites string `hcl:"cluster_cipher_suites"` - - PluginDirectory string `hcl:"plugin_directory"` - - LogLevel string `hcl:"log_level"` - - PidFile string `hcl:"pid_file"` - EnableRawEndpoint bool `hcl:"-"` - EnableRawEndpointRaw interface{} `hcl:"raw_storage_endpoint"` - - APIAddr string `hcl:"api_addr"` - ClusterAddr string `hcl:"cluster_addr"` - DisableClustering bool `hcl:"-"` - DisableClusteringRaw interface{} `hcl:"disable_clustering"` - - DisablePerformanceStandby bool `hcl:"-"` - DisablePerformanceStandbyRaw interface{} `hcl:"disable_performance_standby"` - - DisableSealWrap bool `hcl:"-"` - DisableSealWrapRaw interface{} `hcl:"disable_sealwrap"` -} - -// DevConfig is a Config that is used for dev mode of Vault. -func DevConfig(ha, transactional bool) *Config { - ret := &Config{ - DisableMlock: true, - EnableRawEndpoint: true, - - Storage: &Storage{ - Type: "inmem", - }, - - Listeners: []*Listener{ - &Listener{ - Type: "tcp", - Config: map[string]interface{}{ - "address": "127.0.0.1:8200", - "tls_disable": true, - "proxy_protocol_behavior": "allow_authorized", - "proxy_protocol_authorized_addrs": "127.0.0.1:8200", - }, - }, - }, - - EnableUI: true, - - Telemetry: &Telemetry{}, - } - - switch { - case ha && transactional: - ret.Storage.Type = "inmem_transactional_ha" - case !ha && transactional: - ret.Storage.Type = "inmem_transactional" - case ha && !transactional: - ret.Storage.Type = "inmem_ha" - } - - return ret -} - -// Listener is the listener configuration for the server. -type Listener struct { - Type string - Config map[string]interface{} -} - -func (l *Listener) GoString() string { - return fmt.Sprintf("*%#v", *l) -} - -// Storage is the underlying storage configuration for the server. -type Storage struct { - Type string - RedirectAddr string - ClusterAddr string - DisableClustering bool - Config map[string]string -} - -func (b *Storage) GoString() string { - return fmt.Sprintf("*%#v", *b) -} - -// Seal contains Seal configuration for the server -type Seal struct { - Type string - Config map[string]string -} - -func (h *Seal) GoString() string { - return fmt.Sprintf("*%#v", *h) -} - -// Telemetry is the telemetry configuration for the server -type Telemetry struct { - StatsiteAddr string `hcl:"statsite_address"` - StatsdAddr string `hcl:"statsd_address"` - - DisableHostname bool `hcl:"disable_hostname"` - - // Circonus: see https://github.com/circonus-labs/circonus-gometrics - // for more details on the various configuration options. - // Valid configuration combinations: - // - CirconusAPIToken - // metric management enabled (search for existing check or create a new one) - // - CirconusSubmissionUrl - // metric management disabled (use check with specified submission_url, - // broker must be using a public SSL certificate) - // - CirconusAPIToken + CirconusCheckSubmissionURL - // metric management enabled (use check with specified submission_url) - // - CirconusAPIToken + CirconusCheckID - // metric management enabled (use check with specified id) - - // CirconusAPIToken is a valid API Token used to create/manage check. If provided, - // metric management is enabled. - // Default: none - CirconusAPIToken string `hcl:"circonus_api_token"` - // CirconusAPIApp is an app name associated with API token. - // Default: "consul" - CirconusAPIApp string `hcl:"circonus_api_app"` - // CirconusAPIURL is the base URL to use for contacting the Circonus API. - // Default: "https://api.circonus.com/v2" - CirconusAPIURL string `hcl:"circonus_api_url"` - // CirconusSubmissionInterval is the interval at which metrics are submitted to Circonus. - // Default: 10s - CirconusSubmissionInterval string `hcl:"circonus_submission_interval"` - // CirconusCheckSubmissionURL is the check.config.submission_url field from a - // previously created HTTPTRAP check. - // Default: none - CirconusCheckSubmissionURL string `hcl:"circonus_submission_url"` - // CirconusCheckID is the check id (not check bundle id) from a previously created - // HTTPTRAP check. The numeric portion of the check._cid field. - // Default: none - CirconusCheckID string `hcl:"circonus_check_id"` - // CirconusCheckForceMetricActivation will force enabling metrics, as they are encountered, - // if the metric already exists and is NOT active. If check management is enabled, the default - // behavior is to add new metrics as they are encountered. If the metric already exists in the - // check, it will *NOT* be activated. This setting overrides that behavior. - // Default: "false" - CirconusCheckForceMetricActivation string `hcl:"circonus_check_force_metric_activation"` - // CirconusCheckInstanceID serves to uniquely identify the metrics coming from this "instance". - // It can be used to maintain metric continuity with transient or ephemeral instances as - // they move around within an infrastructure. - // Default: hostname:app - CirconusCheckInstanceID string `hcl:"circonus_check_instance_id"` - // CirconusCheckSearchTag is a special tag which, when coupled with the instance id, helps to - // narrow down the search results when neither a Submission URL or Check ID is provided. - // Default: service:app (e.g. service:consul) - CirconusCheckSearchTag string `hcl:"circonus_check_search_tag"` - // CirconusCheckTags is a comma separated list of tags to apply to the check. Note that - // the value of CirconusCheckSearchTag will always be added to the check. - // Default: none - CirconusCheckTags string `mapstructure:"circonus_check_tags"` - // CirconusCheckDisplayName is the name for the check which will be displayed in the Circonus UI. - // Default: value of CirconusCheckInstanceID - CirconusCheckDisplayName string `mapstructure:"circonus_check_display_name"` - // CirconusBrokerID is an explicit broker to use when creating a new check. The numeric portion - // of broker._cid. If metric management is enabled and neither a Submission URL nor Check ID - // is provided, an attempt will be made to search for an existing check using Instance ID and - // Search Tag. If one is not found, a new HTTPTRAP check will be created. - // Default: use Select Tag if provided, otherwise, a random Enterprise Broker associated - // with the specified API token or the default Circonus Broker. - // Default: none - CirconusBrokerID string `hcl:"circonus_broker_id"` - // CirconusBrokerSelectTag is a special tag which will be used to select a broker when - // a Broker ID is not provided. The best use of this is to as a hint for which broker - // should be used based on *where* this particular instance is running. - // (e.g. a specific geo location or datacenter, dc:sfo) - // Default: none - CirconusBrokerSelectTag string `hcl:"circonus_broker_select_tag"` - - // Dogstats: - // DogStatsdAddr is the address of a dogstatsd instance. If provided, - // metrics will be sent to that instance - DogStatsDAddr string `hcl:"dogstatsd_addr"` - - // DogStatsdTags are the global tags that should be sent with each packet to dogstatsd - // It is a list of strings, where each string looks like "my_tag_name:my_tag_value" - DogStatsDTags []string `hcl:"dogstatsd_tags"` -} - -func (s *Telemetry) GoString() string { - return fmt.Sprintf("*%#v", *s) -} - -// Merge merges two configurations. -func (c *Config) Merge(c2 *Config) *Config { - if c2 == nil { - return c - } - - result := new(Config) - for _, l := range c.Listeners { - result.Listeners = append(result.Listeners, l) - } - for _, l := range c2.Listeners { - result.Listeners = append(result.Listeners, l) - } - - result.Storage = c.Storage - if c2.Storage != nil { - result.Storage = c2.Storage - } - - result.HAStorage = c.HAStorage - if c2.HAStorage != nil { - result.HAStorage = c2.HAStorage - } - - result.Seal = c.Seal - if c2.Seal != nil { - result.Seal = c2.Seal - } - - result.Telemetry = c.Telemetry - if c2.Telemetry != nil { - result.Telemetry = c2.Telemetry - } - - result.CacheSize = c.CacheSize - if c2.CacheSize != 0 { - result.CacheSize = c2.CacheSize - } - - // merging these booleans via an OR operation - result.DisableCache = c.DisableCache - if c2.DisableCache { - result.DisableCache = c2.DisableCache - } - - result.DisableMlock = c.DisableMlock - if c2.DisableMlock { - result.DisableMlock = c2.DisableMlock - } - - // merge these integers via a MAX operation - result.MaxLeaseTTL = c.MaxLeaseTTL - if c2.MaxLeaseTTL > result.MaxLeaseTTL { - result.MaxLeaseTTL = c2.MaxLeaseTTL - } - - result.DefaultLeaseTTL = c.DefaultLeaseTTL - if c2.DefaultLeaseTTL > result.DefaultLeaseTTL { - result.DefaultLeaseTTL = c2.DefaultLeaseTTL - } - - result.DefaultMaxRequestDuration = c.DefaultMaxRequestDuration - if c2.DefaultMaxRequestDuration > result.DefaultMaxRequestDuration { - result.DefaultMaxRequestDuration = c2.DefaultMaxRequestDuration - } - - result.LogLevel = c.LogLevel - if c2.LogLevel != "" { - result.LogLevel = c2.LogLevel - } - - result.ClusterName = c.ClusterName - if c2.ClusterName != "" { - result.ClusterName = c2.ClusterName - } - - result.ClusterCipherSuites = c.ClusterCipherSuites - if c2.ClusterCipherSuites != "" { - result.ClusterCipherSuites = c2.ClusterCipherSuites - } - - result.EnableUI = c.EnableUI - if c2.EnableUI { - result.EnableUI = c2.EnableUI - } - - result.EnableRawEndpoint = c.EnableRawEndpoint - if c2.EnableRawEndpoint { - result.EnableRawEndpoint = c2.EnableRawEndpoint - } - - result.PluginDirectory = c.PluginDirectory - if c2.PluginDirectory != "" { - result.PluginDirectory = c2.PluginDirectory - } - - result.PidFile = c.PidFile - if c2.PidFile != "" { - result.PidFile = c2.PidFile - } - - result.DisablePerformanceStandby = c.DisablePerformanceStandby - if c2.DisablePerformanceStandby { - result.DisablePerformanceStandby = c2.DisablePerformanceStandby - } - - result.DisableSealWrap = c.DisableSealWrap - if c2.DisableSealWrap { - result.DisableSealWrap = c2.DisableSealWrap - } - - return result -} - -// LoadConfig loads the configuration at the given path, regardless if -// its a file or directory. -func LoadConfig(path string, logger log.Logger) (*Config, error) { - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - - if fi.IsDir() { - return LoadConfigDir(path, logger) - } - return LoadConfigFile(path, logger) -} - -// LoadConfigFile loads the configuration from the given file. -func LoadConfigFile(path string, logger log.Logger) (*Config, error) { - // Read the file - d, err := ioutil.ReadFile(path) - if err != nil { - return nil, err - } - return ParseConfig(string(d), logger) -} - -func ParseConfig(d string, logger log.Logger) (*Config, error) { - // Parse! - obj, err := hcl.Parse(d) - if err != nil { - return nil, err - } - - // Start building the result - var result Config - if err := hcl.DecodeObject(&result, obj); err != nil { - return nil, err - } - - if result.MaxLeaseTTLRaw != nil { - if result.MaxLeaseTTL, err = parseutil.ParseDurationSecond(result.MaxLeaseTTLRaw); err != nil { - return nil, err - } - } - if result.DefaultLeaseTTLRaw != nil { - if result.DefaultLeaseTTL, err = parseutil.ParseDurationSecond(result.DefaultLeaseTTLRaw); err != nil { - return nil, err - } - } - - if result.DefaultMaxRequestDurationRaw != nil { - if result.DefaultMaxRequestDuration, err = parseutil.ParseDurationSecond(result.DefaultMaxRequestDurationRaw); err != nil { - return nil, err - } - } - - if result.EnableUIRaw != nil { - if result.EnableUI, err = parseutil.ParseBool(result.EnableUIRaw); err != nil { - return nil, err - } - } - - if result.DisableCacheRaw != nil { - if result.DisableCache, err = parseutil.ParseBool(result.DisableCacheRaw); err != nil { - return nil, err - } - } - - if result.DisableMlockRaw != nil { - if result.DisableMlock, err = parseutil.ParseBool(result.DisableMlockRaw); err != nil { - return nil, err - } - } - - if result.DisablePrintableCheckRaw != nil { - if result.DisablePrintableCheck, err = parseutil.ParseBool(result.DisablePrintableCheckRaw); err != nil { - return nil, err - } - } - - if result.EnableRawEndpointRaw != nil { - if result.EnableRawEndpoint, err = parseutil.ParseBool(result.EnableRawEndpointRaw); err != nil { - return nil, err - } - } - - if result.DisableClusteringRaw != nil { - if result.DisableClustering, err = parseutil.ParseBool(result.DisableClusteringRaw); err != nil { - return nil, err - } - } - - if result.DisablePerformanceStandbyRaw != nil { - if result.DisablePerformanceStandby, err = parseutil.ParseBool(result.DisablePerformanceStandbyRaw); err != nil { - return nil, err - } - } - - if result.DisableSealWrapRaw != nil { - if result.DisableSealWrap, err = parseutil.ParseBool(result.DisableSealWrapRaw); err != nil { - return nil, err - } - } - - list, ok := obj.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("error parsing: file doesn't contain a root object") - } - - // Look for storage but still support old backend - if o := list.Filter("storage"); len(o.Items) > 0 { - if err := parseStorage(&result, o, "storage"); err != nil { - return nil, errwrap.Wrapf("error parsing 'storage': {{err}}", err) - } - } else { - if o := list.Filter("backend"); len(o.Items) > 0 { - if err := parseStorage(&result, o, "backend"); err != nil { - return nil, errwrap.Wrapf("error parsing 'backend': {{err}}", err) - } - } - } - - if o := list.Filter("ha_storage"); len(o.Items) > 0 { - if err := parseHAStorage(&result, o, "ha_storage"); err != nil { - return nil, errwrap.Wrapf("error parsing 'ha_storage': {{err}}", err) - } - } else { - if o := list.Filter("ha_backend"); len(o.Items) > 0 { - if err := parseHAStorage(&result, o, "ha_backend"); err != nil { - return nil, errwrap.Wrapf("error parsing 'ha_backend': {{err}}", err) - } - } - } - - if o := list.Filter("hsm"); len(o.Items) > 0 { - if err := parseSeal(&result, o, "hsm"); err != nil { - return nil, errwrap.Wrapf("error parsing 'hsm': {{err}}", err) - } - } - - if o := list.Filter("seal"); len(o.Items) > 0 { - if err := parseSeal(&result, o, "seal"); err != nil { - return nil, errwrap.Wrapf("error parsing 'seal': {{err}}", err) - } - } - - if o := list.Filter("listener"); len(o.Items) > 0 { - if err := parseListeners(&result, o); err != nil { - return nil, errwrap.Wrapf("error parsing 'listener': {{err}}", err) - } - } - - if o := list.Filter("telemetry"); len(o.Items) > 0 { - if err := parseTelemetry(&result, o); err != nil { - return nil, errwrap.Wrapf("error parsing 'telemetry': {{err}}", err) - } - } - - return &result, nil -} - -// LoadConfigDir loads all the configurations in the given directory -// in alphabetical order. -func LoadConfigDir(dir string, logger log.Logger) (*Config, error) { - f, err := os.Open(dir) - if err != nil { - return nil, err - } - defer f.Close() - - fi, err := f.Stat() - if err != nil { - return nil, err - } - if !fi.IsDir() { - return nil, fmt.Errorf("configuration path must be a directory: %q", dir) - } - - var files []string - err = nil - for err != io.EOF { - var fis []os.FileInfo - fis, err = f.Readdir(128) - if err != nil && err != io.EOF { - return nil, err - } - - for _, fi := range fis { - // Ignore directories - if fi.IsDir() { - continue - } - - // Only care about files that are valid to load. - name := fi.Name() - skip := true - if strings.HasSuffix(name, ".hcl") { - skip = false - } else if strings.HasSuffix(name, ".json") { - skip = false - } - if skip || isTemporaryFile(name) { - continue - } - - path := filepath.Join(dir, name) - files = append(files, path) - } - } - - var result *Config - for _, f := range files { - config, err := LoadConfigFile(f, logger) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error loading %q: {{err}}", f), err) - } - - if result == nil { - result = config - } else { - result = result.Merge(config) - } - } - - return result, nil -} - -// isTemporaryFile returns true or false depending on whether the -// provided file name is a temporary file for the following editors: -// emacs or vim. -func isTemporaryFile(name string) bool { - return strings.HasSuffix(name, "~") || // vim - strings.HasPrefix(name, ".#") || // emacs - (strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#")) // emacs -} - -func parseStorage(result *Config, list *ast.ObjectList, name string) error { - if len(list.Items) > 1 { - return fmt.Errorf("only one %q block is permitted", name) - } - - // Get our item - item := list.Items[0] - - key := name - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - var m map[string]string - if err := hcl.DecodeObject(&m, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("%s.%s:", name, key)) - } - - // Pull out the redirect address since it's common to all backends - var redirectAddr string - if v, ok := m["redirect_addr"]; ok { - redirectAddr = v - delete(m, "redirect_addr") - } else if v, ok := m["advertise_addr"]; ok { - redirectAddr = v - delete(m, "advertise_addr") - } - - // Pull out the cluster address since it's common to all backends - var clusterAddr string - if v, ok := m["cluster_addr"]; ok { - clusterAddr = v - delete(m, "cluster_addr") - } - - var disableClustering bool - var err error - if v, ok := m["disable_clustering"]; ok { - disableClustering, err = strconv.ParseBool(v) - if err != nil { - return multierror.Prefix(err, fmt.Sprintf("%s.%s:", name, key)) - } - delete(m, "disable_clustering") - } - - // Override with top-level values if they are set - if result.APIAddr != "" { - redirectAddr = result.APIAddr - } - - if result.ClusterAddr != "" { - clusterAddr = result.ClusterAddr - } - - if result.DisableClusteringRaw != nil { - disableClustering = result.DisableClustering - } - - result.Storage = &Storage{ - RedirectAddr: redirectAddr, - ClusterAddr: clusterAddr, - DisableClustering: disableClustering, - Type: strings.ToLower(key), - Config: m, - } - return nil -} - -func parseHAStorage(result *Config, list *ast.ObjectList, name string) error { - if len(list.Items) > 1 { - return fmt.Errorf("only one %q block is permitted", name) - } - - // Get our item - item := list.Items[0] - - key := name - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - var m map[string]string - if err := hcl.DecodeObject(&m, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("%s.%s:", name, key)) - } - - // Pull out the redirect address since it's common to all backends - var redirectAddr string - if v, ok := m["redirect_addr"]; ok { - redirectAddr = v - delete(m, "redirect_addr") - } else if v, ok := m["advertise_addr"]; ok { - redirectAddr = v - delete(m, "advertise_addr") - } - - // Pull out the cluster address since it's common to all backends - var clusterAddr string - if v, ok := m["cluster_addr"]; ok { - clusterAddr = v - delete(m, "cluster_addr") - } - - var disableClustering bool - var err error - if v, ok := m["disable_clustering"]; ok { - disableClustering, err = strconv.ParseBool(v) - if err != nil { - return multierror.Prefix(err, fmt.Sprintf("%s.%s:", name, key)) - } - delete(m, "disable_clustering") - } - - // Override with top-level values if they are set - if result.APIAddr != "" { - redirectAddr = result.APIAddr - } - - if result.ClusterAddr != "" { - clusterAddr = result.ClusterAddr - } - - if result.DisableClusteringRaw != nil { - disableClustering = result.DisableClustering - } - - result.HAStorage = &Storage{ - RedirectAddr: redirectAddr, - ClusterAddr: clusterAddr, - DisableClustering: disableClustering, - Type: strings.ToLower(key), - Config: m, - } - return nil -} - -func parseSeal(result *Config, list *ast.ObjectList, blockName string) error { - if len(list.Items) > 1 { - return fmt.Errorf("only one %q block is permitted", blockName) - } - - // Get our item - item := list.Items[0] - - key := blockName - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - // Valid parameter for the Seal types - switch key { - case "pkcs11": - case "awskms": - case "gcpckms": - case "azurekeyvault": - default: - return fmt.Errorf("invalid seal type %q", key) - } - - var m map[string]string - if err := hcl.DecodeObject(&m, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("%s.%s:", blockName, key)) - } - - result.Seal = &Seal{ - Type: strings.ToLower(key), - Config: m, - } - - return nil -} - -func parseListeners(result *Config, list *ast.ObjectList) error { - listeners := make([]*Listener, 0, len(list.Items)) - for _, item := range list.Items { - key := "listener" - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - var m map[string]interface{} - if err := hcl.DecodeObject(&m, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("listeners.%s:", key)) - } - - lnType := strings.ToLower(key) - - listeners = append(listeners, &Listener{ - Type: lnType, - Config: m, - }) - } - - result.Listeners = listeners - return nil -} - -func parseTelemetry(result *Config, list *ast.ObjectList) error { - if len(list.Items) > 1 { - return fmt.Errorf("only one 'telemetry' block is permitted") - } - - // Get our one item - item := list.Items[0] - - var t Telemetry - if err := hcl.DecodeObject(&t, item.Val); err != nil { - return multierror.Prefix(err, "telemetry:") - } - - if result.Telemetry == nil { - result.Telemetry = &Telemetry{} - } - - if err := hcl.DecodeObject(&result.Telemetry, item.Val); err != nil { - return multierror.Prefix(err, "telemetry:") - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/command/server/listener.go b/vendor/github.com/hashicorp/vault/command/server/listener.go deleted file mode 100644 index a1f2f3926..000000000 --- a/vendor/github.com/hashicorp/vault/command/server/listener.go +++ /dev/null @@ -1,191 +0,0 @@ -package server - -import ( - "github.com/hashicorp/errwrap" - // We must import sha512 so that it registers with the runtime so that - // certificates that use it can be parsed. - _ "crypto/sha512" - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net" - - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/proxyutil" - "github.com/hashicorp/vault/helper/reload" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/mitchellh/cli" -) - -// ListenerFactory is the factory function to create a listener. -type ListenerFactory func(map[string]interface{}, io.Writer, cli.Ui) (net.Listener, map[string]string, reload.ReloadFunc, error) - -// BuiltinListeners is the list of built-in listener types. -var BuiltinListeners = map[string]ListenerFactory{ - "tcp": tcpListenerFactory, -} - -// NewListener creates a new listener of the given type with the given -// configuration. The type is looked up in the BuiltinListeners map. -func NewListener(t string, config map[string]interface{}, logger io.Writer, ui cli.Ui) (net.Listener, map[string]string, reload.ReloadFunc, error) { - f, ok := BuiltinListeners[t] - if !ok { - return nil, nil, nil, fmt.Errorf("unknown listener type: %q", t) - } - - return f(config, logger, ui) -} - -func listenerWrapProxy(ln net.Listener, config map[string]interface{}) (net.Listener, error) { - behaviorRaw, ok := config["proxy_protocol_behavior"] - if !ok { - return ln, nil - } - - behavior, ok := behaviorRaw.(string) - if !ok { - return nil, fmt.Errorf("failed parsing proxy_protocol_behavior value: not a string") - } - - proxyProtoConfig := &proxyutil.ProxyProtoConfig{ - Behavior: behavior, - } - - if proxyProtoConfig.Behavior == "allow_authorized" || proxyProtoConfig.Behavior == "deny_unauthorized" { - authorizedAddrsRaw, ok := config["proxy_protocol_authorized_addrs"] - if !ok { - return nil, fmt.Errorf("proxy_protocol_behavior set but no proxy_protocol_authorized_addrs value") - } - - if err := proxyProtoConfig.SetAuthorizedAddrs(authorizedAddrsRaw); err != nil { - return nil, errwrap.Wrapf("failed parsing proxy_protocol_authorized_addrs: {{err}}", err) - } - } - - newLn, err := proxyutil.WrapInProxyProto(ln, proxyProtoConfig) - if err != nil { - return nil, errwrap.Wrapf("failed configuring PROXY protocol wrapper: {{err}}", err) - } - - return newLn, nil -} - -func listenerWrapTLS( - ln net.Listener, - props map[string]string, - config map[string]interface{}, - ui cli.Ui) (net.Listener, map[string]string, reload.ReloadFunc, error) { - props["tls"] = "disabled" - - if v, ok := config["tls_disable"]; ok { - disabled, err := parseutil.ParseBool(v) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_disable': {{err}}", err) - } - if disabled { - return ln, props, nil, nil - } - } - - certFileRaw, ok := config["tls_cert_file"] - if !ok { - return nil, nil, nil, fmt.Errorf("'tls_cert_file' must be set") - } - certFile := certFileRaw.(string) - keyFileRaw, ok := config["tls_key_file"] - if !ok { - return nil, nil, nil, fmt.Errorf("'tls_key_file' must be set") - } - keyFile := keyFileRaw.(string) - - cg := reload.NewCertificateGetter(certFile, keyFile, "") - if err := cg.Reload(config); err != nil { - // We try the key without a passphrase first and if we get an incorrect - // passphrase response, try again after prompting for a passphrase - if errwrap.Contains(err, x509.IncorrectPasswordError.Error()) { - var passphrase string - passphrase, err = ui.AskSecret(fmt.Sprintf("Enter passphrase for %s:", keyFile)) - if err == nil { - cg = reload.NewCertificateGetter(certFile, keyFile, passphrase) - if err = cg.Reload(config); err == nil { - goto PASSPHRASECORRECT - } - } - } - return nil, nil, nil, errwrap.Wrapf("error loading TLS cert: {{err}}", err) - } - -PASSPHRASECORRECT: - var tlsvers string - tlsversRaw, ok := config["tls_min_version"] - if !ok { - tlsvers = "tls12" - } else { - tlsvers = tlsversRaw.(string) - } - - tlsConf := &tls.Config{} - tlsConf.GetCertificate = cg.GetCertificate - tlsConf.NextProtos = []string{"h2", "http/1.1"} - tlsConf.MinVersion, ok = tlsutil.TLSLookup[tlsvers] - if !ok { - return nil, nil, nil, fmt.Errorf("'tls_min_version' value %q not supported, please specify one of [tls10,tls11,tls12]", tlsvers) - } - tlsConf.ClientAuth = tls.RequestClientCert - - if v, ok := config["tls_cipher_suites"]; ok { - ciphers, err := tlsutil.ParseCiphers(v.(string)) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_cipher_suites': {{err}}", err) - } - tlsConf.CipherSuites = ciphers - } - if v, ok := config["tls_prefer_server_cipher_suites"]; ok { - preferServer, err := parseutil.ParseBool(v) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_prefer_server_cipher_suites': {{err}}", err) - } - tlsConf.PreferServerCipherSuites = preferServer - } - var requireVerifyCerts bool - var err error - if v, ok := config["tls_require_and_verify_client_cert"]; ok { - requireVerifyCerts, err = parseutil.ParseBool(v) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_require_and_verify_client_cert': {{err}}", err) - } - if requireVerifyCerts { - tlsConf.ClientAuth = tls.RequireAndVerifyClientCert - } - if tlsClientCaFile, ok := config["tls_client_ca_file"]; ok { - caPool := x509.NewCertPool() - data, err := ioutil.ReadFile(tlsClientCaFile.(string)) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("failed to read tls_client_ca_file: {{err}}", err) - } - - if !caPool.AppendCertsFromPEM(data) { - return nil, nil, nil, fmt.Errorf("failed to parse CA certificate in tls_client_ca_file") - } - tlsConf.ClientCAs = caPool - } - } - if v, ok := config["tls_disable_client_certs"]; ok { - disableClientCerts, err := parseutil.ParseBool(v) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("invalid value for 'tls_disable_client_certs': {{err}}", err) - } - if disableClientCerts && requireVerifyCerts { - return nil, nil, nil, fmt.Errorf("'tls_disable_client_certs' and 'tls_require_and_verify_client_cert' are mutually exclusive") - } - if disableClientCerts { - tlsConf.ClientAuth = tls.NoClientCert - } - } - - ln = tls.NewListener(ln, tlsConf) - props["tls"] = "enabled" - return ln, props, cg.Reload, nil -} diff --git a/vendor/github.com/hashicorp/vault/command/server/listener_tcp.go b/vendor/github.com/hashicorp/vault/command/server/listener_tcp.go deleted file mode 100644 index 201e124f3..000000000 --- a/vendor/github.com/hashicorp/vault/command/server/listener_tcp.go +++ /dev/null @@ -1,118 +0,0 @@ -package server - -import ( - "fmt" - "io" - "net" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/reload" - "github.com/mitchellh/cli" -) - -func tcpListenerFactory(config map[string]interface{}, _ io.Writer, ui cli.Ui) (net.Listener, map[string]string, reload.ReloadFunc, error) { - bindProto := "tcp" - var addr string - addrRaw, ok := config["address"] - if !ok { - addr = "127.0.0.1:8200" - } else { - addr = addrRaw.(string) - } - - // If they've passed 0.0.0.0, we only want to bind on IPv4 - // rather than golang's dual stack default - if strings.HasPrefix(addr, "0.0.0.0:") { - bindProto = "tcp4" - } - - ln, err := net.Listen(bindProto, addr) - if err != nil { - return nil, nil, nil, err - } - - ln = tcpKeepAliveListener{ln.(*net.TCPListener)} - - ln, err = listenerWrapProxy(ln, config) - if err != nil { - return nil, nil, nil, err - } - - props := map[string]string{"addr": addr} - - ffAllowedRaw, ffAllowedOK := config["x_forwarded_for_authorized_addrs"] - if ffAllowedOK { - ffAllowed, err := parseutil.ParseAddrs(ffAllowedRaw) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("error parsing \"x_forwarded_for_authorized_addrs\": {{err}}", err) - } - props["x_forwarded_for_authorized_addrs"] = fmt.Sprintf("%v", ffAllowed) - config["x_forwarded_for_authorized_addrs"] = ffAllowed - } - - if ffHopsRaw, ok := config["x_forwarded_for_hop_skips"]; ok { - ffHops64, err := parseutil.ParseInt(ffHopsRaw) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("error parsing \"x_forwarded_for_hop_skips\": {{err}}", err) - } - if ffHops64 < 0 { - return nil, nil, nil, fmt.Errorf("\"x_forwarded_for_hop_skips\" cannot be negative") - } - ffHops := int(ffHops64) - props["x_forwarded_for_hop_skips"] = strconv.Itoa(ffHops) - config["x_forwarded_for_hop_skips"] = ffHops - } else if ffAllowedOK { - props["x_forwarded_for_hop_skips"] = "0" - config["x_forwarded_for_hop_skips"] = int(0) - } - - if ffRejectNotPresentRaw, ok := config["x_forwarded_for_reject_not_present"]; ok { - ffRejectNotPresent, err := parseutil.ParseBool(ffRejectNotPresentRaw) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("error parsing \"x_forwarded_for_reject_not_present\": {{err}}", err) - } - props["x_forwarded_for_reject_not_present"] = strconv.FormatBool(ffRejectNotPresent) - config["x_forwarded_for_reject_not_present"] = ffRejectNotPresent - } else if ffAllowedOK { - props["x_forwarded_for_reject_not_present"] = "true" - config["x_forwarded_for_reject_not_present"] = true - } - - if ffRejectNonAuthorizedRaw, ok := config["x_forwarded_for_reject_not_authorized"]; ok { - ffRejectNonAuthorized, err := parseutil.ParseBool(ffRejectNonAuthorizedRaw) - if err != nil { - return nil, nil, nil, errwrap.Wrapf("error parsing \"x_forwarded_for_reject_not_authorized\": {{err}}", err) - } - props["x_forwarded_for_reject_not_authorized"] = strconv.FormatBool(ffRejectNonAuthorized) - config["x_forwarded_for_reject_not_authorized"] = ffRejectNonAuthorized - } else if ffAllowedOK { - props["x_forwarded_for_reject_not_authorized"] = "true" - config["x_forwarded_for_reject_not_authorized"] = true - } - - return listenerWrapTLS(ln, props, config, ui) -} - -// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted -// connections. It's used by ListenAndServe and ListenAndServeTLS so -// dead TCP connections (e.g. closing laptop mid-download) eventually -// go away. -// -// This is copied directly from the Go source code. -type tcpKeepAliveListener struct { - *net.TCPListener -} - -func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { - tc, err := ln.AcceptTCP() - if err != nil { - return - } - tc.SetKeepAlive(true) - tc.SetKeepAlivePeriod(3 * time.Minute) - return tc, nil -} diff --git a/vendor/github.com/hashicorp/vault/command/ssh.go b/vendor/github.com/hashicorp/vault/command/ssh.go deleted file mode 100644 index 6b9999740..000000000 --- a/vendor/github.com/hashicorp/vault/command/ssh.go +++ /dev/null @@ -1,885 +0,0 @@ -package command - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "os/user" - "strings" - "syscall" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/builtin/logical/ssh" - "github.com/mitchellh/cli" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/posener/complete" -) - -var _ cli.Command = (*SSHCommand)(nil) -var _ cli.CommandAutocomplete = (*SSHCommand)(nil) - -type SSHCommand struct { - *BaseCommand - - // Common SSH options - flagMode string - flagRole string - flagNoExec bool - flagMountPoint string - flagStrictHostKeyChecking string - flagSSHExecutable string - flagUserKnownHostsFile string - - // SSH CA Mode options - flagPublicKeyPath string - flagPrivateKeyPath string - flagHostKeyMountPoint string - flagHostKeyHostnames string - flagValidPrincipals string -} - -func (c *SSHCommand) Synopsis() string { - return "Initiate an SSH session" -} - -func (c *SSHCommand) Help() string { - helpText := ` -Usage: vault ssh [options] username@ip [ssh options] - - Establishes an SSH connection with the target machine. - - This command uses one of the SSH secrets engines to authenticate and - automatically establish an SSH connection to a host. This operation requires - that the SSH secrets engine is mounted and configured. - - SSH using the OTP mode (requires sshpass for full automation): - - $ vault ssh -mode=otp -role=my-role user@1.2.3.4 - - SSH using the CA mode: - - $ vault ssh -mode=ca -role=my-role user@1.2.3.4 - - SSH using CA mode with host key verification: - - $ vault ssh \ - -mode=ca \ - -role=my-role \ - -host-key-mount-point=host-signer \ - -host-key-hostnames=example.com \ - user@example.com - - For the full list of options and arguments, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *SSHCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - f := set.NewFlagSet("SSH Options") - - // TODO: doc field? - - // General - f.StringVar(&StringVar{ - Name: "mode", - Target: &c.flagMode, - Default: "", - EnvVar: "", - Completion: complete.PredictSet("ca", "dynamic", "otp"), - Usage: "Name of the authentication mode (ca, dynamic, otp).", - }) - - f.StringVar(&StringVar{ - Name: "role", - Target: &c.flagRole, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Name of the role to use to generate the key.", - }) - - f.BoolVar(&BoolVar{ - Name: "no-exec", - Target: &c.flagNoExec, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Print the generated credentials, but do not establish a " + - "connection.", - }) - - f.StringVar(&StringVar{ - Name: "mount-point", - Target: &c.flagMountPoint, - Default: "ssh/", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Mount point to the SSH secrets engine.", - }) - - f.StringVar(&StringVar{ - Name: "strict-host-key-checking", - Target: &c.flagStrictHostKeyChecking, - Default: "ask", - EnvVar: "VAULT_SSH_STRICT_HOST_KEY_CHECKING", - Completion: complete.PredictSet("ask", "no", "yes"), - Usage: "Value to use for the SSH configuration option " + - "\"StrictHostKeyChecking\".", - }) - - f.StringVar(&StringVar{ - Name: "user-known-hosts-file", - Target: &c.flagUserKnownHostsFile, - Default: "", - EnvVar: "VAULT_SSH_USER_KNOWN_HOSTS_FILE", - Completion: complete.PredictFiles("*"), - Usage: "Value to use for the SSH configuration option " + - "\"UserKnownHostsFile\".", - }) - - // SSH CA - f = set.NewFlagSet("CA Mode Options") - - f.StringVar(&StringVar{ - Name: "public-key-path", - Target: &c.flagPublicKeyPath, - Default: "~/.ssh/id_rsa.pub", - EnvVar: "", - Completion: complete.PredictFiles("*"), - Usage: "Path to the SSH public key to send to Vault for signing.", - }) - - f.StringVar(&StringVar{ - Name: "private-key-path", - Target: &c.flagPrivateKeyPath, - Default: "~/.ssh/id_rsa", - EnvVar: "", - Completion: complete.PredictFiles("*"), - Usage: "Path to the SSH private key to use for authentication. This must " + - "be the corresponding private key to -public-key-path.", - }) - - f.StringVar(&StringVar{ - Name: "host-key-mount-point", - Target: &c.flagHostKeyMountPoint, - Default: "", - EnvVar: "VAULT_SSH_HOST_KEY_MOUNT_POINT", - Completion: complete.PredictAnything, - Usage: "Mount point to the SSH secrets engine where host keys are signed. " + - "When given a value, Vault will generate a custom \"known_hosts\" file " + - "with delegation to the CA at the provided mount point to verify the " + - "SSH connection's host keys against the provided CA. By default, host " + - "keys are validated against the user's local \"known_hosts\" file. " + - "This flag forces strict key host checking and ignores a custom user " + - "known hosts file.", - }) - - f.StringVar(&StringVar{ - Name: "host-key-hostnames", - Target: &c.flagHostKeyHostnames, - Default: "*", - EnvVar: "VAULT_SSH_HOST_KEY_HOSTNAMES", - Completion: complete.PredictAnything, - Usage: "List of hostnames to delegate for the CA. The default value " + - "allows all domains and IPs. This is specified as a comma-separated " + - "list of values.", - }) - - f.StringVar(&StringVar{ - Name: "valid-principals", - Target: &c.flagValidPrincipals, - Default: "", - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "List of valid principal names to include in the generated " + - "user certificate. This is specified as a comma-separated list of values.", - }) - - f.StringVar(&StringVar{ - Name: "ssh-executable", - Target: &c.flagSSHExecutable, - Default: "ssh", - EnvVar: "VAULT_SSH_EXECUTABLE", - Completion: complete.PredictAnything, - Usage: "Path to the SSH executable to use when connecting to the host", - }) - - return set -} - -func (c *SSHCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *SSHCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -// Structure to hold the fields returned when asked for a credential from SSH -// secrets engine. -type SSHCredentialResp struct { - KeyType string `mapstructure:"key_type"` - Key string `mapstructure:"key"` - Username string `mapstructure:"username"` - IP string `mapstructure:"ip"` - Port string `mapstructure:"port"` -} - -func (c *SSHCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Use homedir to expand any relative paths such as ~/.ssh - c.flagUserKnownHostsFile = expandPath(c.flagUserKnownHostsFile) - c.flagPublicKeyPath = expandPath(c.flagPublicKeyPath) - c.flagPrivateKeyPath = expandPath(c.flagPrivateKeyPath) - - args = f.Args() - if len(args) < 1 { - c.UI.Error(fmt.Sprintf("Not enough arguments, (expected 1-n, got %d)", len(args))) - return 1 - } - - // Extract the hostname, username and port from the ssh command - hostname, username, port, err := c.parseSSHCommand(args) - if err != nil { - c.UI.Error(fmt.Sprintf("Error parsing the ssh command: %q", err)) - return 1 - } - - // Use the current user if no user was specified in the ssh command - if username == "" { - u, err := user.Current() - if err != nil { - c.UI.Error(fmt.Sprintf("Error getting the current user: %q", err)) - return 1 - } - username = u.Username - } - - ip, err := c.resolveHostname(hostname) - if err != nil { - c.UI.Error(fmt.Sprintf("Error resolving the ssh hostname: %q", err)) - return 1 - } - - // Set the client in the command - _, err = c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 1 - } - - // Credentials are generated only against a registered role. If user - // does not specify a role with the SSH command, then lookup API is used - // to fetch all the roles with which this IP is associated. If there is - // only one role associated with it, use it to establish the connection. - // - // TODO: remove in 0.9.0, convert to validation error - if c.flagRole == "" { - c.UI.Warn(wrapAtLength( - "WARNING: No -role specified. Use -role to tell Vault which ssh role " + - "to use for authentication. In the future, you will need to tell " + - "Vault which role to use. For now, Vault will attempt to guess based " + - "on the API response. This will be removed in the Vault 0.12.")) - - role, err := c.defaultRole(c.flagMountPoint, ip) - if err != nil { - c.UI.Error(fmt.Sprintf("Error choosing role: %v", err)) - return 1 - } - // Print the default role chosen so that user knows the role name - // if something doesn't work. If the role chosen is not allowed to - // be used by the user (ACL enforcement), then user should see an - // error message accordingly. - c.UI.Output(fmt.Sprintf("Vault SSH: Role: %q", role)) - c.flagRole = role - } - - // If no mode was given, perform the old-school lookup. Keep this now for - // backwards-compatability, but print a warning. - // - // TODO: remove in 0.9.0, convert to validation error - if c.flagMode == "" { - c.UI.Warn(wrapAtLength( - "WARNING: No -mode specified. Use -mode to tell Vault which ssh " + - "authentication mode to use. In the future, you will need to tell " + - "Vault which mode to use. For now, Vault will attempt to guess based " + - "on the API response. This guess involves creating a temporary " + - "credential, reading its type, and then revoking it. To reduce the " + - "number of API calls and surface area, specify -mode directly. This " + - "will be removed in Vault 0.12.")) - secret, cred, err := c.generateCredential(username, ip) - if err != nil { - // This is _very_ hacky, but is the only sane backwards-compatible way - // to do this. If the error is "key type unknown", we just assume the - // type is "ca". In the future, mode will be required as an option. - if strings.Contains(err.Error(), "key type unknown") { - c.flagMode = ssh.KeyTypeCA - } else { - c.UI.Error(fmt.Sprintf("Error getting credential: %s", err)) - return 1 - } - } else { - c.flagMode = cred.KeyType - } - - // Revoke the secret, since the child functions will generate their own - // credential. Users wishing to avoid this should specify -mode. - if secret != nil { - if err := c.client.Sys().Revoke(secret.LeaseID); err != nil { - c.UI.Warn(fmt.Sprintf("Failed to revoke temporary key: %s", err)) - } - } - } - - switch strings.ToLower(c.flagMode) { - case ssh.KeyTypeCA: - return c.handleTypeCA(username, ip, port, args) - case ssh.KeyTypeOTP: - return c.handleTypeOTP(username, ip, port, args) - case ssh.KeyTypeDynamic: - return c.handleTypeDynamic(username, ip, port, args) - default: - c.UI.Error(fmt.Sprintf("Unknown SSH mode: %s", c.flagMode)) - return 1 - } -} - -// handleTypeCA is used to handle SSH logins using the "CA" key type. -func (c *SSHCommand) handleTypeCA(username, ip, port string, sshArgs []string) int { - // Read the key from disk - publicKey, err := ioutil.ReadFile(c.flagPublicKeyPath) - if err != nil { - c.UI.Error(fmt.Sprintf("failed to read public key %s: %s", - c.flagPublicKeyPath, err)) - return 1 - } - - sshClient := c.client.SSHWithMountPoint(c.flagMountPoint) - - var principals = username - if c.flagValidPrincipals != "" { - principals = c.flagValidPrincipals - } - - // Attempt to sign the public key - secret, err := sshClient.SignKey(c.flagRole, map[string]interface{}{ - // WARNING: publicKey is []byte, which is b64 encoded on JSON upload. We - // have to convert it to a string. SV lost many hours to this... - "public_key": string(publicKey), - "valid_principals": principals, - "cert_type": "user", - - // TODO: let the user configure these. In the interim, if users want to - // customize these values, they can produce the key themselves. - "extensions": map[string]string{ - "permit-X11-forwarding": "", - "permit-agent-forwarding": "", - "permit-port-forwarding": "", - "permit-pty": "", - "permit-user-rc": "", - }, - }) - if err != nil { - c.UI.Error(fmt.Sprintf("failed to sign public key %s: %s", - c.flagPublicKeyPath, err)) - return 2 - } - if secret == nil || secret.Data == nil { - c.UI.Error("missing signed key") - return 2 - } - - // Handle no-exec - if c.flagNoExec { - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - return OutputSecret(c.UI, secret) - } - - // Extract public key - key, ok := secret.Data["signed_key"].(string) - if !ok || key == "" { - c.UI.Error("signed key is empty") - return 2 - } - - // Capture the current value - this could be overwritten later if the user - // enabled host key signing verification. - userKnownHostsFile := c.flagUserKnownHostsFile - strictHostKeyChecking := c.flagStrictHostKeyChecking - - // Handle host key signing verification. If the user specified a mount point, - // download the public key, trust it with the given domains, and use that - // instead of the user's regular known_hosts file. - if c.flagHostKeyMountPoint != "" { - secret, err := c.client.Logical().Read(c.flagHostKeyMountPoint + "/config/ca") - if err != nil { - c.UI.Error(fmt.Sprintf("failed to get host signing key: %s", err)) - return 2 - } - if secret == nil || secret.Data == nil { - c.UI.Error("missing host signing key") - return 2 - } - publicKey, ok := secret.Data["public_key"].(string) - if !ok || publicKey == "" { - c.UI.Error("host signing key is empty") - return 2 - } - - // Write the known_hosts file - name := fmt.Sprintf("vault_ssh_ca_known_hosts_%s_%s", username, ip) - data := fmt.Sprintf("@cert-authority %s %s", c.flagHostKeyHostnames, publicKey) - knownHosts, err, closer := c.writeTemporaryFile(name, []byte(data), 0644) - defer closer() - if err != nil { - c.UI.Error(fmt.Sprintf("failed to write host public key: %s", err)) - return 1 - } - - // Update the variables - userKnownHostsFile = knownHosts - strictHostKeyChecking = "yes" - } - - // Write the signed public key to disk - name := fmt.Sprintf("vault_ssh_ca_%s_%s", username, ip) - signedPublicKeyPath, err, closer := c.writeTemporaryKey(name, []byte(key)) - defer closer() - if err != nil { - c.UI.Error(fmt.Sprintf("failed to write signed public key: %s", err)) - return 2 - } - - args := append([]string{ - "-i", c.flagPrivateKeyPath, - "-i", signedPublicKeyPath, - "-o StrictHostKeyChecking=" + strictHostKeyChecking, - }) - - if userKnownHostsFile != "" { - args = append(args, - "-o UserKnownHostsFile="+userKnownHostsFile, - ) - } - - // Add extra user defined ssh arguments - args = append(args, sshArgs...) - - cmd := exec.Command(c.flagSSHExecutable, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err = cmd.Run() - if err != nil { - exitCode := 2 - - if exitError, ok := err.(*exec.ExitError); ok { - if exitError.Success() { - return 0 - } - if ws, ok := exitError.Sys().(syscall.WaitStatus); ok { - exitCode = ws.ExitStatus() - } - } - - c.UI.Error(fmt.Sprintf("failed to run ssh command: %s", err)) - return exitCode - } - - // There is no secret to revoke, since it's a certificate signing - return 0 -} - -// handleTypeOTP is used to handle SSH logins using the "otp" key type. -func (c *SSHCommand) handleTypeOTP(username, ip, port string, sshArgs []string) int { - secret, cred, err := c.generateCredential(username, ip) - if err != nil { - c.UI.Error(fmt.Sprintf("failed to generate credential: %s", err)) - return 2 - } - - // Handle no-exec - if c.flagNoExec { - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - return OutputSecret(c.UI, secret) - } - - var cmd *exec.Cmd - - // Check if the application 'sshpass' is installed in the client machine. If - // it is then, use it to automate typing in OTP to the prompt. Unfortunately, - // it was not possible to automate it without a third-party application, with - // only the Go libraries. Feel free to try and remove this dependency. - args := make([]string, 0) - env := os.Environ() - sshCmd := c.flagSSHExecutable - - sshpassPath, err := exec.LookPath("sshpass") - if err != nil { - // No sshpass available so using normal ssh client - c.UI.Warn(wrapAtLength( - "Vault could not locate \"sshpass\". The OTP code for the session is " + - "displayed below. Enter this code in the SSH password prompt. If you " + - "install sshpass, Vault can automatically perform this step for you.")) - c.UI.Output("OTP for the session is: " + cred.Key) - } else { - // sshpass is available so lets use it instead - sshCmd = sshpassPath - args = append(args, - "-e", // Read password for SSHPASS environment variable - c.flagSSHExecutable, - ) - env = append(env, fmt.Sprintf("SSHPASS=%s", string(cred.Key))) - } - - // Only harcode the knownhostsfile path if it has been set - if c.flagUserKnownHostsFile != "" { - args = append(args, - "-o UserKnownHostsFile="+c.flagUserKnownHostsFile, - ) - } - - // If a port wasn't specified in the ssh arguments lets use the port we got back from vault - if port == "" { - args = append(args, "-p", cred.Port) - } - - args = append(args, - "-o StrictHostKeyChecking="+c.flagStrictHostKeyChecking, - ) - - // Add the rest of the ssh args appended by the user - args = append(args, sshArgs...) - - cmd = exec.Command(sshCmd, args...) - cmd.Env = env - - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err = cmd.Run() - if err != nil { - exitCode := 2 - - if exitError, ok := err.(*exec.ExitError); ok { - if exitError.Success() { - return 0 - } - if ws, ok := exitError.Sys().(syscall.WaitStatus); ok { - exitCode = ws.ExitStatus() - } - } - - c.UI.Error(fmt.Sprintf("failed to run ssh command: %s", err)) - return exitCode - } - - // Revoke the key if it's longer than expected - if err := c.client.Sys().Revoke(secret.LeaseID); err != nil { - c.UI.Error(fmt.Sprintf("failed to revoke key: %s", err)) - return 2 - } - - return 0 -} - -// handleTypeDynamic is used to handle SSH logins using the "dyanmic" key type. -func (c *SSHCommand) handleTypeDynamic(username, ip, port string, sshArgs []string) int { - // Generate the credential - secret, cred, err := c.generateCredential(username, ip) - if err != nil { - c.UI.Error(fmt.Sprintf("failed to generate credential: %s", err)) - return 2 - } - - // Handle no-exec - if c.flagNoExec { - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - return OutputSecret(c.UI, secret) - } - - // Write the dynamic key to disk - name := fmt.Sprintf("vault_ssh_dynamic_%s_%s", username, ip) - keyPath, err, closer := c.writeTemporaryKey(name, []byte(cred.Key)) - defer closer() - if err != nil { - c.UI.Error(fmt.Sprintf("failed to write dynamic key: %s", err)) - return 1 - } - - args := make([]string, 0) - // If a port wasn't specified in the ssh arguments lets use the port we got back from vault - if port == "" { - args = append(args, "-p", cred.Port) - } - - args = append(args, - "-i", keyPath, - "-o UserKnownHostsFile="+c.flagUserKnownHostsFile, - "-o StrictHostKeyChecking="+c.flagStrictHostKeyChecking, - ) - - // Add extra user defined ssh arguments - args = append(args, sshArgs...) - - cmd := exec.Command(c.flagSSHExecutable, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err = cmd.Run() - if err != nil { - exitCode := 2 - - if exitError, ok := err.(*exec.ExitError); ok { - if exitError.Success() { - return 0 - } - if ws, ok := exitError.Sys().(syscall.WaitStatus); ok { - exitCode = ws.ExitStatus() - } - } - - c.UI.Error(fmt.Sprintf("failed to run ssh command: %s", err)) - return exitCode - } - - // Revoke the key if it's longer than expected - if err := c.client.Sys().Revoke(secret.LeaseID); err != nil { - c.UI.Error(fmt.Sprintf("failed to revoke key: %s", err)) - return 2 - } - - return 0 -} - -// generateCredential generates a credential for the given role and returns the -// decoded secret data. -func (c *SSHCommand) generateCredential(username, ip string) (*api.Secret, *SSHCredentialResp, error) { - sshClient := c.client.SSHWithMountPoint(c.flagMountPoint) - - // Attempt to generate the credential. - secret, err := sshClient.Credential(c.flagRole, map[string]interface{}{ - "username": username, - "ip": ip, - }) - if err != nil { - return nil, nil, errors.Wrap(err, "failed to get credentials") - } - if secret == nil || secret.Data == nil { - return nil, nil, fmt.Errorf("vault returned empty credentials") - } - - // Port comes back as a json.Number which mapstructure doesn't like, so - // convert it - if d, ok := secret.Data["port"].(json.Number); ok { - secret.Data["port"] = d.String() - } - - // Use mapstructure to decode the response - var resp SSHCredentialResp - if err := mapstructure.Decode(secret.Data, &resp); err != nil { - return nil, nil, errors.Wrap(err, "failed to decode credential") - } - - // Check for an empty key response - if len(resp.Key) == 0 { - return nil, nil, fmt.Errorf("vault returned an invalid key") - } - - return secret, &resp, nil -} - -// writeTemporaryFile writes a file to a temp location with the given data and -// file permissions. -func (c *SSHCommand) writeTemporaryFile(name string, data []byte, perms os.FileMode) (string, error, func() error) { - // default closer to prevent panic - closer := func() error { return nil } - - f, err := ioutil.TempFile("", name) - if err != nil { - return "", errors.Wrap(err, "creating temporary file"), closer - } - - closer = func() error { return os.Remove(f.Name()) } - - if err := ioutil.WriteFile(f.Name(), data, perms); err != nil { - return "", errors.Wrap(err, "writing temporary key"), closer - } - - return f.Name(), nil, closer -} - -// writeTemporaryKey writes the key to a temporary file and returns the path. -// The caller should defer the closer to cleanup the key. -func (c *SSHCommand) writeTemporaryKey(name string, data []byte) (string, error, func() error) { - return c.writeTemporaryFile(name, data, 0600) -} - -// If user did not provide the role with which SSH connection has -// to be established and if there is only one role associated with -// the IP, it is used by default. -func (c *SSHCommand) defaultRole(mountPoint, ip string) (string, error) { - data := map[string]interface{}{ - "ip": ip, - } - secret, err := c.client.Logical().Write(mountPoint+"/lookup", data) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) - } - if secret == nil || secret.Data == nil { - return "", errwrap.Wrapf(fmt.Sprintf("error finding roles for IP %q: {{err}}", ip), err) - } - - if secret.Data["roles"] == nil { - return "", fmt.Errorf("no matching roles found for IP %q", ip) - } - - if len(secret.Data["roles"].([]interface{})) == 1 { - return secret.Data["roles"].([]interface{})[0].(string), nil - } else { - var roleNames string - for _, item := range secret.Data["roles"].([]interface{}) { - roleNames += item.(string) + ", " - } - roleNames = strings.TrimRight(roleNames, ", ") - return "", fmt.Errorf("Roles: %q. "+` - Multiple roles are registered for this IP. - Select a role using '-role' option. - Note that all roles may not be permitted, based on ACLs.`, roleNames) - } -} - -func (c *SSHCommand) isSingleSSHArg(arg string) bool { - // list of single SSH arguments is taken from - // https://github.com/openssh/openssh-portable/blob/28013759f09ed3ebf7e8335e83a62936bd7a7f47/ssh.c#L204 - singleArgs := []string{ - "4", "6", "A", "a", "C", "f", "G", "g", "K", "k", "M", "N", "n", "q", - "s", "T", "t", "V", "v", "X", "x", "Y", "y", - } - - // We want to get the first character after the dash. This is so args like -vvv are picked up as just being -v - flag := string(arg[1]) - - for _, a := range singleArgs { - if flag == a { - return true - } - } - return false -} - -// Finds the hostname, username (optional) and port (optional) from any valid ssh command -// Supports usrname@hostname but also specifying valid ssh flags like -o User=username, -// -o Port=2222 and -p 2222 anywhere in the command -func (c *SSHCommand) parseSSHCommand(args []string) (hostname string, username string, port string, err error) { - lastArg := "" - for _, i := range args { - arg := lastArg - lastArg = "" - - // If -p has been specified then this is our ssh port - if arg == "-p" { - port = i - continue - } - - // this is an ssh option, lets see if User or Port have been set and use it - if arg == "-o" { - split := strings.Split(i, "=") - key := split[0] - // Incase the value contains = signs we want to get all of them - value := strings.Join(split[1:], " ") - - if key == "User" { - // Don't overwrite the user if it is already set by username@hostname - // This matches the behaviour for how regular ssh reponds when both are specified - if username == "" { - username = value - } - } - - if key == "Port" { - // Don't overwrite the port if it is already set by -p - // This matches the behaviour for how regular ssh reponds when both are specified - if port == "" { - port = value - } - } - continue - } - - // This isn't an ssh argument that we care about. Lets keep on parsing the command - if arg != "" { - continue - } - - // If this is an ssh argument with a value we want to look at it in the next loop - if strings.HasPrefix(i, "-") { - // If this isn't a single SSH arg we want to store the flag to we can look at the value next loop - if !c.isSingleSSHArg(i) { - lastArg = i - } - continue - } - - // If we have gotten this far it means this is a bare argument - // The first bare argument is the hostname - // The second bare argument is the command to run on the remote host - - // If the hostname hasn't been set yet than it means we have found the first bare argument - if hostname == "" { - if strings.Contains(i, "@") { - split := strings.Split(i, "@") - username = split[0] - hostname = split[1] - } else { - hostname = i - } - continue - } else { - // The second bare argument is the command to run on the remote host. - // We need to break out and stop parsing arugments now - break - } - - } - if hostname == "" { - return "", "", "", errors.Wrap( - err, - fmt.Sprintf("failed to find a hostname in ssh command %q", strings.Join(args, " ")), - ) - } - return hostname, username, port, nil -} - -func (c *SSHCommand) resolveHostname(hostname string) (ip string, err error) { - // Resolving domain names to IP address on the client side. - // Vault only deals with IP addresses. - ipAddr, err := net.ResolveIPAddr("ip", hostname) - if err != nil { - return "", errors.Wrap(err, "failed to resolve IP address") - } - ip = ipAddr.String() - return ip, nil -} diff --git a/vendor/github.com/hashicorp/vault/command/status.go b/vendor/github.com/hashicorp/vault/command/status.go deleted file mode 100644 index 0e6be18f7..000000000 --- a/vendor/github.com/hashicorp/vault/command/status.go +++ /dev/null @@ -1,89 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*StatusCommand)(nil) -var _ cli.CommandAutocomplete = (*StatusCommand)(nil) - -type StatusCommand struct { - *BaseCommand -} - -func (c *StatusCommand) Synopsis() string { - return "Print seal and HA status" -} - -func (c *StatusCommand) Help() string { - helpText := ` -Usage: vault status [options] - - Prints the current state of Vault including whether it is sealed and if HA - mode is enabled. This command prints regardless of whether the Vault is - sealed. - - The exit code reflects the seal status: - - - 0 - unsealed - - 1 - error - - 2 - sealed - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *StatusCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *StatusCommand) AutocompleteArgs() complete.Predictor { - return complete.PredictNothing -} - -func (c *StatusCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *StatusCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - // We return 2 everywhere else, but 2 is reserved for "sealed" here - return 1 - } - - status, err := client.Sys().SealStatus() - if err != nil { - c.UI.Error(fmt.Sprintf("Error checking seal status: %s", err)) - return 1 - } - - // Do not return the int here yet, since we may want to return a custom error - // code depending on the seal status. - code := OutputSealStatus(c.UI, client, status) - - if status.Sealed { - return 2 - } - - return code -} diff --git a/vendor/github.com/hashicorp/vault/command/token.go b/vendor/github.com/hashicorp/vault/command/token.go deleted file mode 100644 index 20af230a5..000000000 --- a/vendor/github.com/hashicorp/vault/command/token.go +++ /dev/null @@ -1,46 +0,0 @@ -package command - -import ( - "strings" - - "github.com/mitchellh/cli" -) - -var _ cli.Command = (*TokenCommand)(nil) - -type TokenCommand struct { - *BaseCommand -} - -func (c *TokenCommand) Synopsis() string { - return "Interact with tokens" -} - -func (c *TokenCommand) Help() string { - helpText := ` -Usage: vault token [options] [args] - - This command groups subcommands for interacting with tokens. Users can - create, lookup, renew, and revoke tokens. - - Create a new token: - - $ vault token create - - Revoke a token: - - $ vault token revoke 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Renew a token: - - $ vault token renew 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Please see the individual subcommand help for detailed usage information. -` - - return strings.TrimSpace(helpText) -} - -func (c *TokenCommand) Run(args []string) int { - return cli.RunResultHelp -} diff --git a/vendor/github.com/hashicorp/vault/command/token_capabilities.go b/vendor/github.com/hashicorp/vault/command/token_capabilities.go deleted file mode 100644 index 2c877a713..000000000 --- a/vendor/github.com/hashicorp/vault/command/token_capabilities.go +++ /dev/null @@ -1,109 +0,0 @@ -package command - -import ( - "fmt" - "sort" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*TokenCapabilitiesCommand)(nil) -var _ cli.CommandAutocomplete = (*TokenCapabilitiesCommand)(nil) - -type TokenCapabilitiesCommand struct { - *BaseCommand -} - -func (c *TokenCapabilitiesCommand) Synopsis() string { - return "Print capabilities of a token on a path" -} - -func (c *TokenCapabilitiesCommand) Help() string { - helpText := ` -Usage: vault token capabilities [options] [TOKEN] PATH - - Fetches the capabilities of a token for a given path. If a TOKEN is provided - as an argument, the "/sys/capabilities" endpoint and permission is used. If - no TOKEN is provided, the "/sys/capabilities-self" endpoint and permission - is used with the locally authenticated token. - - List capabilities for the local token on the "secret/foo" path: - - $ vault token capabilities secret/foo - - List capabilities for a token on the "cubbyhole/foo" path: - - $ vault token capabilities 96ddf4bc-d217-f3ba-f9bd-017055595017 cubbyhole/foo - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *TokenCapabilitiesCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) -} - -func (c *TokenCapabilitiesCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *TokenCapabilitiesCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *TokenCapabilitiesCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - token := "" - path := "" - args = f.Args() - switch { - case len(args) == 1: - path = args[0] - case len(args) == 2: - token, path = args[0], args[1] - default: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1-2, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var capabilities []string - if token == "" { - capabilities, err = client.Sys().CapabilitiesSelf(path) - } else { - capabilities, err = client.Sys().Capabilities(token, path) - } - if err != nil { - c.UI.Error(fmt.Sprintf("Error listing capabilities: %s", err)) - return 2 - } - if capabilities == nil { - c.UI.Error(fmt.Sprintf("No capabilities found")) - return 1 - } - - switch Format(c.UI) { - case "table": - sort.Strings(capabilities) - c.UI.Output(strings.Join(capabilities, ", ")) - return 0 - default: - return OutputData(c.UI, capabilities) - } -} diff --git a/vendor/github.com/hashicorp/vault/command/token_create.go b/vendor/github.com/hashicorp/vault/command/token_create.go deleted file mode 100644 index fd269d947..000000000 --- a/vendor/github.com/hashicorp/vault/command/token_create.go +++ /dev/null @@ -1,252 +0,0 @@ -package command - -import ( - "fmt" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*TokenCreateCommand)(nil) -var _ cli.CommandAutocomplete = (*TokenCreateCommand)(nil) - -type TokenCreateCommand struct { - *BaseCommand - - flagID string - flagDisplayName string - flagTTL time.Duration - flagExplicitMaxTTL time.Duration - flagPeriod time.Duration - flagRenewable bool - flagOrphan bool - flagNoDefaultPolicy bool - flagUseLimit int - flagRole string - flagMetadata map[string]string - flagPolicies []string - - // Deprecated flags - flagLease time.Duration -} - -func (c *TokenCreateCommand) Synopsis() string { - return "Create a new token" -} - -func (c *TokenCreateCommand) Help() string { - helpText := ` -Usage: vault token create [options] - - Creates a new token that can be used for authentication. This token will be - created as a child of the currently authenticated token. The generated token - will inherit all policies and permissions of the currently authenticated - token unless you explicitly define a subset list policies to assign to the - token. - - A ttl can also be associated with the token. If a ttl is not associated - with the token, then it cannot be renewed. If a ttl is associated with - the token, it will expire after that amount of time unless it is renewed. - - Metadata associated with the token (specified with "-metadata") is written - to the audit log when the token is used. - - If a role is specified, the role may override parameters specified here. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *TokenCreateCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.StringVar(&StringVar{ - Name: "id", - Target: &c.flagID, - Completion: complete.PredictAnything, - Usage: "Value for the token. By default, this is an auto-generated 36 " + - "character UUID. Specifying this value requires sudo permissions.", - }) - - f.StringVar(&StringVar{ - Name: "display-name", - Target: &c.flagDisplayName, - Completion: complete.PredictAnything, - Usage: "Name to associate with this token. This is a non-sensitive value " + - "that can be used to help identify created secrets (e.g. prefixes).", - }) - - f.DurationVar(&DurationVar{ - Name: "ttl", - Target: &c.flagTTL, - Completion: complete.PredictAnything, - Usage: "Initial TTL to associate with the token. Token renewals may be " + - "able to extend beyond this value, depending on the configured maximum" + - "TTLs. This is specified as a numeric string with suffix like \"30s\" " + - "or \"5m\".", - }) - - f.DurationVar(&DurationVar{ - Name: "explicit-max-ttl", - Target: &c.flagExplicitMaxTTL, - Completion: complete.PredictAnything, - Usage: "Explicit maximum lifetime for the token. Unlike normal TTLs, the " + - "maximum TTL is a hard limit and cannot be exceeded. This is specified " + - "as a numeric string with suffix like \"30s\" or \"5m\".", - }) - - f.DurationVar(&DurationVar{ - Name: "period", - Target: &c.flagPeriod, - Completion: complete.PredictAnything, - Usage: "If specified, every renewal will use the given period. Periodic " + - "tokens do not expire (unless -explicit-max-ttl is also provided). " + - "Setting this value requires sudo permissions. This is specified as a " + - "numeric string with suffix like \"30s\" or \"5m\".", - }) - - f.BoolVar(&BoolVar{ - Name: "renewable", - Target: &c.flagRenewable, - Default: true, - Usage: "Allow the token to be renewed up to it's maximum TTL.", - }) - - f.BoolVar(&BoolVar{ - Name: "orphan", - Target: &c.flagOrphan, - Default: false, - Usage: "Create the token with no parent. This prevents the token from " + - "being revoked when the token which created it expires. Setting this " + - "value requires sudo permissions.", - }) - - f.BoolVar(&BoolVar{ - Name: "no-default-policy", - Target: &c.flagNoDefaultPolicy, - Default: false, - Usage: "Detach the \"default\" policy from the policy set for this " + - "token.", - }) - - f.IntVar(&IntVar{ - Name: "use-limit", - Target: &c.flagUseLimit, - Default: 0, - Usage: "Number of times this token can be used. After the last use, the " + - "token is automatically revoked. By default, tokens can be used an " + - "unlimited number of times until their expiration.", - }) - - f.StringVar(&StringVar{ - Name: "role", - Target: &c.flagRole, - Default: "", - Usage: "Name of the role to create the token against. Specifying -role " + - "may override other arguments. The locally authenticated Vault token " + - "must have permission for \"auth/token/create/\".", - }) - - f.StringMapVar(&StringMapVar{ - Name: "metadata", - Target: &c.flagMetadata, - Completion: complete.PredictAnything, - Usage: "Arbitrary key=value metadata to associate with the token. " + - "This metadata will show in the audit log when the token is used. " + - "This can be specified multiple times to add multiple pieces of " + - "metadata.", - }) - - f.StringSliceVar(&StringSliceVar{ - Name: "policy", - Target: &c.flagPolicies, - Completion: c.PredictVaultPolicies(), - Usage: "Name of a policy to associate with this token. This can be " + - "specified multiple times to attach multiple policies.", - }) - - // Deprecated flags - // TODO: remove in 0.9.0 - f.DurationVar(&DurationVar{ - Name: "lease", // prefer -ttl - Target: &c.flagLease, - Default: 0, - Hidden: true, - }) - - return set -} - -func (c *TokenCreateCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *TokenCreateCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *TokenCreateCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - if len(args) > 0 { - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", len(args))) - return 1 - } - - // TODO: remove in 0.9.0 - if c.flagLease != 0 { - if Format(c.UI) == "table" { - c.UI.Warn("The -lease flag is deprecated. Please use -ttl instead.") - c.flagTTL = c.flagLease - } - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - tcr := &api.TokenCreateRequest{ - ID: c.flagID, - Policies: c.flagPolicies, - Metadata: c.flagMetadata, - TTL: c.flagTTL.String(), - NoParent: c.flagOrphan, - NoDefaultPolicy: c.flagNoDefaultPolicy, - DisplayName: c.flagDisplayName, - NumUses: c.flagUseLimit, - Renewable: &c.flagRenewable, - ExplicitMaxTTL: c.flagExplicitMaxTTL.String(), - Period: c.flagPeriod.String(), - } - - var secret *api.Secret - if c.flagRole != "" { - secret, err = client.Auth().Token().CreateWithRole(tcr, c.flagRole) - } else { - secret, err = client.Auth().Token().Create(tcr) - } - if err != nil { - c.UI.Error(fmt.Sprintf("Error creating token: %s", err)) - return 2 - } - - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/token_lookup.go b/vendor/github.com/hashicorp/vault/command/token_lookup.go deleted file mode 100644 index 83b65f574..000000000 --- a/vendor/github.com/hashicorp/vault/command/token_lookup.go +++ /dev/null @@ -1,128 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*TokenLookupCommand)(nil) -var _ cli.CommandAutocomplete = (*TokenLookupCommand)(nil) - -type TokenLookupCommand struct { - *BaseCommand - - flagAccessor bool -} - -func (c *TokenLookupCommand) Synopsis() string { - return "Display information about a token" -} - -func (c *TokenLookupCommand) Help() string { - helpText := ` -Usage: vault token lookup [options] [TOKEN | ACCESSOR] - - Displays information about a token or accessor. If a TOKEN is not provided, - the locally authenticated token is used. - - Get information about the locally authenticated token (this uses the - /auth/token/lookup-self endpoint and permission): - - $ vault token lookup - - Get information about a particular token (this uses the /auth/token/lookup - endpoint and permission): - - $ vault token lookup 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Get information about a token via its accessor: - - $ vault token lookup -accessor 9793c9b3-e04a-46f3-e7b8-748d7da248da - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *TokenLookupCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "accessor", - Target: &c.flagAccessor, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Treat the argument as an accessor instead of a token. When " + - "this option is selected, the output will NOT include the token.", - }) - - return set -} - -func (c *TokenLookupCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *TokenLookupCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *TokenLookupCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - token := "" - - args = f.Args() - switch { - case c.flagAccessor && len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments with -accessor (expected 1, got %d)", len(args))) - return 1 - case c.flagAccessor && len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments with -accessor (expected 1, got %d)", len(args))) - return 1 - case len(args) == 0: - // Use the local token - case len(args) == 1: - token = strings.TrimSpace(args[0]) - case len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0-1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var secret *api.Secret - switch { - case token == "": - secret, err = client.Auth().Token().LookupSelf() - case c.flagAccessor: - secret, err = client.Auth().Token().LookupAccessor(token) - default: - secret, err = client.Auth().Token().Lookup(token) - } - - if err != nil { - c.UI.Error(fmt.Sprintf("Error looking up token: %s", err)) - return 2 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/token_renew.go b/vendor/github.com/hashicorp/vault/command/token_renew.go deleted file mode 100644 index ee6a62602..000000000 --- a/vendor/github.com/hashicorp/vault/command/token_renew.go +++ /dev/null @@ -1,137 +0,0 @@ -package command - -import ( - "fmt" - "strings" - "time" - - "github.com/hashicorp/vault/api" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*TokenRenewCommand)(nil) -var _ cli.CommandAutocomplete = (*TokenRenewCommand)(nil) - -type TokenRenewCommand struct { - *BaseCommand - - flagIncrement time.Duration -} - -func (c *TokenRenewCommand) Synopsis() string { - return "Renew a token lease" -} - -func (c *TokenRenewCommand) Help() string { - helpText := ` -Usage: vault token renew [options] [TOKEN] - - Renews a token's lease, extending the amount of time it can be used. If a - TOKEN is not provided, the locally authenticated token is used. Lease renewal - will fail if the token is not renewable, the token has already been revoked, - or if the token has already reached its maximum TTL. - - Renew a token (this uses the /auth/token/renew endpoint and permission): - - $ vault token renew 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Renew the currently authenticated token (this uses the /auth/token/renew-self - endpoint and permission): - - $ vault token renew - - Renew a token requesting a specific increment value: - - $ vault token renew -increment=30m 96ddf4bc-d217-f3ba-f9bd-017055595017 - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *TokenRenewCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputFormat) - f := set.NewFlagSet("Command Options") - - f.DurationVar(&DurationVar{ - Name: "increment", - Aliases: []string{"i"}, - Target: &c.flagIncrement, - Default: 0, - EnvVar: "", - Completion: complete.PredictAnything, - Usage: "Request a specific increment for renewal. Vault is not required " + - "to honor this request. If not supplied, Vault will use the default " + - "TTL. This is specified as a numeric string with suffix like \"30s\" " + - "or \"5m\".", - }) - - return set -} - -func (c *TokenRenewCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *TokenRenewCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *TokenRenewCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - token := "" - increment := c.flagIncrement - - args = f.Args() - switch len(args) { - case 0: - // Use the local token - case 1: - token = strings.TrimSpace(args[0]) - case 2: - // TODO: remove in 0.9.0 - backwards compat - if Format(c.UI) == "table" { - c.UI.Warn("Specifying increment as a second argument is deprecated. " + - "Please use -increment instead.") - } - token = strings.TrimSpace(args[0]) - parsed, err := time.ParseDuration(appendDurationSuffix(args[1])) - if err != nil { - c.UI.Error(fmt.Sprintf("Invalid increment: %s", err)) - return 1 - } - increment = parsed - default: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var secret *api.Secret - inc := truncateToSeconds(increment) - if token == "" { - secret, err = client.Auth().Token().RenewSelf(inc) - } else { - secret, err = client.Auth().Token().Renew(token, inc) - } - if err != nil { - c.UI.Error(fmt.Sprintf("Error renewing token: %s", err)) - return 2 - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/token_revoke.go b/vendor/github.com/hashicorp/vault/command/token_revoke.go deleted file mode 100644 index 351ce639c..000000000 --- a/vendor/github.com/hashicorp/vault/command/token_revoke.go +++ /dev/null @@ -1,174 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*TokenRevokeCommand)(nil) -var _ cli.CommandAutocomplete = (*TokenRevokeCommand)(nil) - -type TokenRevokeCommand struct { - *BaseCommand - - flagAccessor bool - flagSelf bool - flagMode string -} - -func (c *TokenRevokeCommand) Synopsis() string { - return "Revoke a token and its children" -} - -func (c *TokenRevokeCommand) Help() string { - helpText := ` -Usage: vault token revoke [options] [TOKEN | ACCESSOR] - - Revokes authentication tokens and their children. If a TOKEN is not provided, - the locally authenticated token is used. The "-mode" flag can be used to - control the behavior of the revocation. See the "-mode" flag documentation - for more information. - - Revoke a token and all the token's children: - - $ vault token revoke 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Revoke a token leaving the token's children: - - $ vault token revoke -mode=orphan 96ddf4bc-d217-f3ba-f9bd-017055595017 - - Revoke a token by accessor: - - $ vault token revoke -accessor 9793c9b3-e04a-46f3-e7b8-748d7da248da - - For a full list of examples, please see the documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *TokenRevokeCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP) - - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "accessor", - Target: &c.flagAccessor, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Treat the argument as an accessor instead of a token.", - }) - - f.BoolVar(&BoolVar{ - Name: "self", - Target: &c.flagSelf, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Perform the revocation on the currently authenticated token.", - }) - - f.StringVar(&StringVar{ - Name: "mode", - Target: &c.flagMode, - Default: "", - EnvVar: "", - Completion: complete.PredictSet("orphan", "path"), - Usage: "Type of revocation to perform. If unspecified, Vault will revoke " + - "the token and all of the token's children. If \"orphan\", Vault will " + - "revoke only the token, leaving the children as orphans. If \"path\", " + - "tokens created from the given authentication path prefix are deleted " + - "along with their children.", - }) - - return set -} - -func (c *TokenRevokeCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *TokenRevokeCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *TokenRevokeCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - token := "" - if len(args) > 0 { - token = strings.TrimSpace(args[0]) - } - - switch c.flagMode { - case "", "orphan", "path": - default: - c.UI.Error(fmt.Sprintf("Invalid mode: %s", c.flagMode)) - return 1 - } - - switch { - case c.flagSelf && len(args) > 0: - c.UI.Error(fmt.Sprintf("Too many arguments with -self (expected 0, got %d)", len(args))) - return 1 - case !c.flagSelf && len(args) > 1: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 1 or -self, got %d)", len(args))) - return 1 - case !c.flagSelf && len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1 or -self, got %d)", len(args))) - return 1 - case c.flagSelf && c.flagAccessor: - c.UI.Error("Cannot use -self with -accessor!") - return 1 - case c.flagSelf && c.flagMode != "": - c.UI.Error("Cannot use -self with -mode!") - return 1 - case c.flagAccessor && c.flagMode == "orphan": - c.UI.Error("Cannot use -accessor with -mode=orphan!") - return 1 - case c.flagAccessor && c.flagMode == "path": - c.UI.Error("Cannot use -accessor with -mode=path!") - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - var revokeFn func(string) error - // Handle all 6 possible combinations - switch { - case !c.flagAccessor && c.flagSelf && c.flagMode == "": - revokeFn = client.Auth().Token().RevokeSelf - case !c.flagAccessor && !c.flagSelf && c.flagMode == "": - revokeFn = client.Auth().Token().RevokeTree - case !c.flagAccessor && !c.flagSelf && c.flagMode == "orphan": - revokeFn = client.Auth().Token().RevokeOrphan - case !c.flagAccessor && !c.flagSelf && c.flagMode == "path": - revokeFn = client.Sys().RevokePrefix - case c.flagAccessor && !c.flagSelf && c.flagMode == "": - revokeFn = client.Auth().Token().RevokeAccessor - } - - if err := revokeFn(token); err != nil { - c.UI.Error(fmt.Sprintf("Error revoking token: %s", err)) - return 2 - } - - c.UI.Output("Success! Revoked token (if it existed)") - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/unwrap.go b/vendor/github.com/hashicorp/vault/command/unwrap.go deleted file mode 100644 index dbb8b46d1..000000000 --- a/vendor/github.com/hashicorp/vault/command/unwrap.go +++ /dev/null @@ -1,106 +0,0 @@ -package command - -import ( - "fmt" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*UnwrapCommand)(nil) -var _ cli.CommandAutocomplete = (*UnwrapCommand)(nil) - -// UnwrapCommand is a Command that behaves like ReadCommand but specifically for -// unwrapping cubbyhole-wrapped secrets -type UnwrapCommand struct { - *BaseCommand -} - -func (c *UnwrapCommand) Synopsis() string { - return "Unwrap a wrapped secret" -} - -func (c *UnwrapCommand) Help() string { - helpText := ` -Usage: vault unwrap [options] [TOKEN] - - Unwraps a wrapped secret from Vault by the given token. The result is the - same as the "vault read" operation on the non-wrapped secret. If no token - is given, the data in the currently authenticated token is unwrapped. - - Unwrap the data in the cubbyhole secrets engine for a token: - - $ vault unwrap 3de9ece1-b347-e143-29b0-dc2dc31caafd - - Unwrap the data in the active token: - - $ vault login 848f9ccf-7176-098c-5e2b-75a0689d41cd - $ vault unwrap # unwraps 848f9ccf... - - For a full list of examples and paths, please see the online documentation. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *UnwrapCommand) Flags() *FlagSets { - return c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) -} - -func (c *UnwrapCommand) AutocompleteArgs() complete.Predictor { - return c.PredictVaultFiles() -} - -func (c *UnwrapCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *UnwrapCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - token := "" - switch len(args) { - case 0: - // Leave token as "", that will use the local token - case 1: - token = strings.TrimSpace(args[0]) - default: - c.UI.Error(fmt.Sprintf("Too many arguments (expected 0-1, got %d)", len(args))) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().Unwrap(token) - if err != nil { - c.UI.Error(fmt.Sprintf("Error unwrapping: %s", err)) - return 2 - } - if secret == nil { - c.UI.Error("Could not find wrapped response") - return 2 - } - - // Handle single field output - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - // Check if the original was a list response and format as a list - if _, ok := extractListData(secret); ok { - return OutputList(c.UI, secret) - } - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/command/util.go b/vendor/github.com/hashicorp/vault/command/util.go deleted file mode 100644 index 7bec6ee05..000000000 --- a/vendor/github.com/hashicorp/vault/command/util.go +++ /dev/null @@ -1,159 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "time" - - "github.com/fatih/color" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/command/config" - "github.com/hashicorp/vault/command/token" - "github.com/mitchellh/cli" -) - -// DefaultTokenHelper returns the token helper that is configured for Vault. -func DefaultTokenHelper() (token.TokenHelper, error) { - return config.DefaultTokenHelper() -} - -// RawField extracts the raw field from the given data and returns it as a -// string for printing purposes. -func RawField(secret *api.Secret, field string) interface{} { - var val interface{} - switch { - case secret.Auth != nil: - switch field { - case "token": - val = secret.Auth.ClientToken - case "token_accessor": - val = secret.Auth.Accessor - case "token_duration": - val = secret.Auth.LeaseDuration - case "token_renewable": - val = secret.Auth.Renewable - case "token_policies": - val = secret.Auth.TokenPolicies - case "identity_policies": - val = secret.Auth.IdentityPolicies - case "policies": - val = secret.Auth.Policies - default: - val = secret.Data[field] - } - - case secret.WrapInfo != nil: - switch field { - case "wrapping_token": - val = secret.WrapInfo.Token - case "wrapping_accessor": - val = secret.WrapInfo.Accessor - case "wrapping_token_ttl": - val = secret.WrapInfo.TTL - case "wrapping_token_creation_time": - val = secret.WrapInfo.CreationTime.Format(time.RFC3339Nano) - case "wrapping_token_creation_path": - val = secret.WrapInfo.CreationPath - case "wrapped_accessor": - val = secret.WrapInfo.WrappedAccessor - default: - val = secret.Data[field] - } - - default: - switch field { - case "lease_duration": - val = secret.LeaseDuration - case "lease_id": - val = secret.LeaseID - case "request_id": - val = secret.RequestID - case "renewable": - val = secret.Renewable - case "refresh_interval": - val = secret.LeaseDuration - case "data": - var ok bool - val, ok = secret.Data["data"] - if !ok { - val = secret.Data - } - default: - val = secret.Data[field] - } - } - - return val -} - -// PrintRawField prints raw field from the secret. -func PrintRawField(ui cli.Ui, data interface{}, field string) int { - var val interface{} - switch data.(type) { - case *api.Secret: - val = RawField(data.(*api.Secret), field) - case map[string]interface{}: - val = data.(map[string]interface{})[field] - } - - if val == nil { - ui.Error(fmt.Sprintf("Field %q not present in secret", field)) - return 1 - } - - format := Format(ui) - if format == "" || format == "table" { - return PrintRaw(ui, fmt.Sprintf("%v", val)) - } - - // Handle specific format flags as best as possible - formatter, ok := Formatters[format] - if !ok { - ui.Error(fmt.Sprintf("Invalid output format: %s", format)) - return 1 - } - - b, err := formatter.Format(val) - if err != nil { - ui.Error(fmt.Sprintf("Error formatting output: %s", err)) - return 1 - } - - return PrintRaw(ui, string(b)) -} - -// PrintRaw prints a raw value to the terminal. If the process is being "piped" -// to something else, the "raw" value is printed without a newline character. -// Otherwise the value is printed as normal. -func PrintRaw(ui cli.Ui, str string) int { - if !color.NoColor { - ui.Output(str) - } else { - // The cli.Ui prints a CR, which is not wanted since the user probably wants - // just the raw value. - w := getWriterFromUI(ui) - fmt.Fprint(w, str) - } - return 0 -} - -// getWriterFromUI accepts a cli.Ui and returns the underlying io.Writer by -// unwrapping as many wrapped Uis as necessary. If there is an unknown UI -// type, this falls back to os.Stdout. -func getWriterFromUI(ui cli.Ui) io.Writer { - switch t := ui.(type) { - case *VaultUI: - return getWriterFromUI(t.Ui) - case *cli.BasicUi: - return t.Writer - case *cli.ColoredUi: - return getWriterFromUI(t.Ui) - case *cli.ConcurrentUi: - return getWriterFromUI(t.Ui) - case *cli.MockUi: - return t.OutputWriter - default: - return os.Stdout - } -} diff --git a/vendor/github.com/hashicorp/vault/command/version.go b/vendor/github.com/hashicorp/vault/command/version.go deleted file mode 100644 index 398036d3a..000000000 --- a/vendor/github.com/hashicorp/vault/command/version.go +++ /dev/null @@ -1,61 +0,0 @@ -package command - -import ( - "strings" - - "github.com/hashicorp/vault/version" - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*VersionCommand)(nil) -var _ cli.CommandAutocomplete = (*VersionCommand)(nil) - -// VersionCommand is a Command implementation prints the version. -type VersionCommand struct { - *BaseCommand - - VersionInfo *version.VersionInfo -} - -func (c *VersionCommand) Synopsis() string { - return "Prints the Vault CLI version" -} - -func (c *VersionCommand) Help() string { - helpText := ` -Usage: vault version - - Prints the version of this Vault CLI. This does not print the target Vault - server version. - - Print the version: - - $ vault version - - There are no arguments or flags to this command. Any additional arguments or - flags are ignored. -` - return strings.TrimSpace(helpText) -} - -func (c *VersionCommand) Flags() *FlagSets { - return nil -} - -func (c *VersionCommand) AutocompleteArgs() complete.Predictor { - return nil -} - -func (c *VersionCommand) AutocompleteFlags() complete.Flags { - return nil -} - -func (c *VersionCommand) Run(_ []string) int { - out := c.VersionInfo.FullVersionNumber(true) - if version.CgoEnabled { - out += " (cgo)" - } - c.UI.Output(out) - return 0 -} diff --git a/vendor/github.com/hashicorp/vault/command/write.go b/vendor/github.com/hashicorp/vault/command/write.go deleted file mode 100644 index 793c9ba53..000000000 --- a/vendor/github.com/hashicorp/vault/command/write.go +++ /dev/null @@ -1,153 +0,0 @@ -package command - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/mitchellh/cli" - "github.com/posener/complete" -) - -var _ cli.Command = (*WriteCommand)(nil) -var _ cli.CommandAutocomplete = (*WriteCommand)(nil) - -// WriteCommand is a Command that puts data into the Vault. -type WriteCommand struct { - *BaseCommand - - flagForce bool - - testStdin io.Reader // for tests -} - -func (c *WriteCommand) Synopsis() string { - return "Write data, configuration, and secrets" -} - -func (c *WriteCommand) Help() string { - helpText := ` -Usage: vault write [options] PATH [DATA K=V...] - - Writes data to Vault at the given path. The data can be credentials, secrets, - configuration, or arbitrary data. The specific behavior of this command is - determined at the thing mounted at the path. - - Data is specified as "key=value" pairs. If the value begins with an "@", then - it is loaded from a file. If the value is "-", Vault will read the value from - stdin. - - Persist data in the generic secrets engine: - - $ vault write secret/my-secret foo=bar - - Create a new encryption key in the transit secrets engine: - - $ vault write -f transit/keys/my-key - - Upload an AWS IAM policy from a file on disk: - - $ vault write aws/roles/ops policy=@policy.json - - Configure access to Consul by providing an access token: - - $ echo $MY_TOKEN | vault write consul/config/access token=- - - For a full list of examples and paths, please see the documentation that - corresponds to the secret engines in use. - -` + c.Flags().Help() - - return strings.TrimSpace(helpText) -} - -func (c *WriteCommand) Flags() *FlagSets { - set := c.flagSet(FlagSetHTTP | FlagSetOutputField | FlagSetOutputFormat) - f := set.NewFlagSet("Command Options") - - f.BoolVar(&BoolVar{ - Name: "force", - Aliases: []string{"f"}, - Target: &c.flagForce, - Default: false, - EnvVar: "", - Completion: complete.PredictNothing, - Usage: "Allow the operation to continue with no key=value pairs. This " + - "allows writing to keys that do not need or expect data.", - }) - - return set -} - -func (c *WriteCommand) AutocompleteArgs() complete.Predictor { - // Return an anything predictor here. Without a way to access help - // information, we don't know what paths we could write to. - return complete.PredictAnything -} - -func (c *WriteCommand) AutocompleteFlags() complete.Flags { - return c.Flags().Completions() -} - -func (c *WriteCommand) Run(args []string) int { - f := c.Flags() - - if err := f.Parse(args); err != nil { - c.UI.Error(err.Error()) - return 1 - } - - args = f.Args() - switch { - case len(args) < 1: - c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) - return 1 - case len(args) == 1 && !c.flagForce: - c.UI.Error("Must supply data or use -force") - return 1 - } - - // Pull our fake stdin if needed - stdin := (io.Reader)(os.Stdin) - if c.testStdin != nil { - stdin = c.testStdin - } - - path := sanitizePath(args[0]) - - data, err := parseArgsData(stdin, args[1:]) - if err != nil { - c.UI.Error(fmt.Sprintf("Failed to parse K=V data: %s", err)) - return 1 - } - - client, err := c.Client() - if err != nil { - c.UI.Error(err.Error()) - return 2 - } - - secret, err := client.Logical().Write(path, data) - if err != nil { - c.UI.Error(fmt.Sprintf("Error writing data to %s: %s", path, err)) - if secret != nil { - OutputSecret(c.UI, secret) - } - return 2 - } - if secret == nil { - // Don't output anything unless using the "table" format - if Format(c.UI) == "table" { - c.UI.Info(fmt.Sprintf("Success! Data written to: %s", path)) - } - return 0 - } - - // Handle single field output - if c.flagField != "" { - return PrintRawField(c.UI, secret, c.flagField) - } - - return OutputSecret(c.UI, secret) -} diff --git a/vendor/github.com/hashicorp/vault/helper/base62/base62.go b/vendor/github.com/hashicorp/vault/helper/base62/base62.go deleted file mode 100644 index 6130deda6..000000000 --- a/vendor/github.com/hashicorp/vault/helper/base62/base62.go +++ /dev/null @@ -1,59 +0,0 @@ -// Package base62 provides utilities for working with base62 strings. -// base62 strings will only contain characters: 0-9, a-z, A-Z -package base62 - -import ( - "math/big" - - uuid "github.com/hashicorp/go-uuid" -) - -// Encode converts buf into a base62 string -// -// Note: this should only be used for reducing a string's character set range. -// It is not for use with arbitrary data since leading 0 bytes will be dropped. -func Encode(buf []byte) string { - var encoder big.Int - - encoder.SetBytes(buf) - return encoder.Text(62) -} - -// Decode converts input from base62 to its byte representation -// If the decoding fails, an empty slice is returned. -func Decode(input string) []byte { - var decoder big.Int - - decoder.SetString(input, 62) - return decoder.Bytes() -} - -// Random generates a random base62-encoded string. -// If truncate is true, the result will be a string of the requested length. -// Otherwise, it will be the encoded result of length bytes of random data. -func Random(length int, truncate bool) (string, error) { - bytesNeeded := length - - // ~0.74 bytes are needed per output character in truncate mode. We'll - // ask for just a little more than that. - if truncate { - bytesNeeded = (bytesNeeded * 3 / 4) + 1 - } - - for { - buf, err := uuid.GenerateRandomBytes(bytesNeeded) - if err != nil { - return "", err - } - - result := Encode(buf) - - if truncate { - if len(result) < length { - continue - } - result = result[:length] - } - return result, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/builtinplugins/builtin.go b/vendor/github.com/hashicorp/vault/helper/builtinplugins/builtin.go deleted file mode 100644 index df424cee6..000000000 --- a/vendor/github.com/hashicorp/vault/helper/builtinplugins/builtin.go +++ /dev/null @@ -1,50 +0,0 @@ -package builtinplugins - -import ( - "github.com/hashicorp/vault/plugins/database/cassandra" - "github.com/hashicorp/vault/plugins/database/hana" - "github.com/hashicorp/vault/plugins/database/mongodb" - "github.com/hashicorp/vault/plugins/database/mssql" - "github.com/hashicorp/vault/plugins/database/mysql" - "github.com/hashicorp/vault/plugins/database/postgresql" - "github.com/hashicorp/vault/plugins/helper/database/credsutil" -) - -// BuiltinFactory is the func signature that should be returned by -// the plugin's New() func. -type BuiltinFactory func() (interface{}, error) - -var plugins = map[string]BuiltinFactory{ - // These four plugins all use the same mysql implementation but with - // different username settings passed by the constructor. - "mysql-database-plugin": mysql.New(mysql.MetadataLen, mysql.MetadataLen, mysql.UsernameLen), - "mysql-aurora-database-plugin": mysql.New(credsutil.NoneLength, mysql.LegacyMetadataLen, mysql.LegacyUsernameLen), - "mysql-rds-database-plugin": mysql.New(credsutil.NoneLength, mysql.LegacyMetadataLen, mysql.LegacyUsernameLen), - "mysql-legacy-database-plugin": mysql.New(credsutil.NoneLength, mysql.LegacyMetadataLen, mysql.LegacyUsernameLen), - - "postgresql-database-plugin": postgresql.New, - "mssql-database-plugin": mssql.New, - "cassandra-database-plugin": cassandra.New, - "mongodb-database-plugin": mongodb.New, - "hana-database-plugin": hana.New, -} - -// Get returns the BuiltinFactory func for a particular backend plugin -// from the plugins map. -func Get(name string) (BuiltinFactory, bool) { - f, ok := plugins[name] - return f, ok -} - -// Keys returns the list of plugin names that are considered builtin plugins. -func Keys() []string { - keys := make([]string, len(plugins)) - - i := 0 - for k := range plugins { - keys[i] = k - i++ - } - - return keys -} diff --git a/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go b/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go deleted file mode 100644 index 7c6651942..000000000 --- a/vendor/github.com/hashicorp/vault/helper/certutil/helpers.go +++ /dev/null @@ -1,301 +0,0 @@ -package certutil - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "math/big" - "strconv" - "strings" - - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/mitchellh/mapstructure" -) - -// GetHexFormatted returns the byte buffer formatted in hex with -// the specified separator between bytes. -func GetHexFormatted(buf []byte, sep string) string { - var ret bytes.Buffer - for _, cur := range buf { - if ret.Len() > 0 { - fmt.Fprintf(&ret, sep) - } - fmt.Fprintf(&ret, "%02x", cur) - } - return ret.String() -} - -// ParseHexFormatted returns the raw bytes from a formatted hex string -func ParseHexFormatted(in, sep string) []byte { - var ret bytes.Buffer - var err error - var inBits int64 - inBytes := strings.Split(in, sep) - for _, inByte := range inBytes { - if inBits, err = strconv.ParseInt(inByte, 16, 8); err != nil { - return nil - } - ret.WriteByte(byte(inBits)) - } - return ret.Bytes() -} - -// GetSubjKeyID returns the subject key ID, e.g. the SHA1 sum -// of the marshaled public key -func GetSubjKeyID(privateKey crypto.Signer) ([]byte, error) { - if privateKey == nil { - return nil, errutil.InternalError{Err: "passed-in private key is nil"} - } - - marshaledKey, err := x509.MarshalPKIXPublicKey(privateKey.Public()) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error marshalling public key: %s", err)} - } - - subjKeyID := sha1.Sum(marshaledKey) - - return subjKeyID[:], nil -} - -// ParsePKIMap takes a map (for instance, the Secret.Data -// returned from the PKI backend) and returns a ParsedCertBundle. -func ParsePKIMap(data map[string]interface{}) (*ParsedCertBundle, error) { - result := &CertBundle{} - err := mapstructure.Decode(data, result) - if err != nil { - return nil, errutil.UserError{Err: err.Error()} - } - - return result.ToParsedCertBundle() -} - -// ParsePKIJSON takes a JSON-encoded string and returns a ParsedCertBundle. -// -// This can be either the output of an -// issue call from the PKI backend or just its data member; or, -// JSON not coming from the PKI backend. -func ParsePKIJSON(input []byte) (*ParsedCertBundle, error) { - result := &CertBundle{} - err := jsonutil.DecodeJSON(input, &result) - - if err == nil { - return result.ToParsedCertBundle() - } - - var secret Secret - err = jsonutil.DecodeJSON(input, &secret) - - if err == nil { - return ParsePKIMap(secret.Data) - } - - return nil, errutil.UserError{Err: "unable to parse out of either secret data or a secret object"} -} - -// ParsePEMBundle takes a string of concatenated PEM-format certificate -// and private key values and decodes/parses them, checking validity along -// the way. The first certificate must be the subject certificate and issuing -// certificates may follow. There must be at most one private key. -func ParsePEMBundle(pemBundle string) (*ParsedCertBundle, error) { - if len(pemBundle) == 0 { - return nil, errutil.UserError{Err: "empty pem bundle"} - } - - pemBytes := []byte(pemBundle) - var pemBlock *pem.Block - parsedBundle := &ParsedCertBundle{} - var certPath []*CertBlock - - for len(pemBytes) > 0 { - pemBlock, pemBytes = pem.Decode(pemBytes) - if pemBlock == nil { - return nil, errutil.UserError{Err: "no data found in PEM block"} - } - - if signer, err := x509.ParseECPrivateKey(pemBlock.Bytes); err == nil { - if parsedBundle.PrivateKeyType != UnknownPrivateKey { - return nil, errutil.UserError{Err: "more than one private key given; provide only one private key in the bundle"} - } - parsedBundle.PrivateKeyFormat = ECBlock - parsedBundle.PrivateKeyType = ECPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKey = signer - - } else if signer, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes); err == nil { - if parsedBundle.PrivateKeyType != UnknownPrivateKey { - return nil, errutil.UserError{Err: "more than one private key given; provide only one private key in the bundle"} - } - parsedBundle.PrivateKeyType = RSAPrivateKey - parsedBundle.PrivateKeyFormat = PKCS1Block - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - parsedBundle.PrivateKey = signer - } else if signer, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes); err == nil { - parsedBundle.PrivateKeyFormat = PKCS8Block - - if parsedBundle.PrivateKeyType != UnknownPrivateKey { - return nil, errutil.UserError{Err: "More than one private key given; provide only one private key in the bundle"} - } - switch signer := signer.(type) { - case *rsa.PrivateKey: - parsedBundle.PrivateKey = signer - parsedBundle.PrivateKeyType = RSAPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - case *ecdsa.PrivateKey: - parsedBundle.PrivateKey = signer - parsedBundle.PrivateKeyType = ECPrivateKey - parsedBundle.PrivateKeyBytes = pemBlock.Bytes - } - } else if certificates, err := x509.ParseCertificates(pemBlock.Bytes); err == nil { - certPath = append(certPath, &CertBlock{ - Certificate: certificates[0], - Bytes: pemBlock.Bytes, - }) - } - } - - for i, certBlock := range certPath { - if i == 0 { - parsedBundle.Certificate = certBlock.Certificate - parsedBundle.CertificateBytes = certBlock.Bytes - } else { - parsedBundle.CAChain = append(parsedBundle.CAChain, certBlock) - } - } - - if err := parsedBundle.Verify(); err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("verification of parsed bundle failed: %s", err)} - } - - return parsedBundle, nil -} - -// GeneratePrivateKey generates a private key with the specified type and key bits -func GeneratePrivateKey(keyType string, keyBits int, container ParsedPrivateKeyContainer) error { - var err error - var privateKeyType PrivateKeyType - var privateKeyBytes []byte - var privateKey crypto.Signer - - switch keyType { - case "rsa": - privateKeyType = RSAPrivateKey - privateKey, err = rsa.GenerateKey(rand.Reader, keyBits) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error generating RSA private key: %v", err)} - } - privateKeyBytes = x509.MarshalPKCS1PrivateKey(privateKey.(*rsa.PrivateKey)) - case "ec": - privateKeyType = ECPrivateKey - var curve elliptic.Curve - switch keyBits { - case 224: - curve = elliptic.P224() - case 256: - curve = elliptic.P256() - case 384: - curve = elliptic.P384() - case 521: - curve = elliptic.P521() - default: - return errutil.UserError{Err: fmt.Sprintf("unsupported bit length for EC key: %d", keyBits)} - } - privateKey, err = ecdsa.GenerateKey(curve, rand.Reader) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error generating EC private key: %v", err)} - } - privateKeyBytes, err = x509.MarshalECPrivateKey(privateKey.(*ecdsa.PrivateKey)) - if err != nil { - return errutil.InternalError{Err: fmt.Sprintf("error marshalling EC private key: %v", err)} - } - default: - return errutil.UserError{Err: fmt.Sprintf("unknown key type: %s", keyType)} - } - - container.SetParsedPrivateKey(privateKey, privateKeyType, privateKeyBytes) - return nil -} - -// GenerateSerialNumber generates a serial number suitable for a certificate -func GenerateSerialNumber() (*big.Int, error) { - serial, err := rand.Int(rand.Reader, (&big.Int{}).Exp(big.NewInt(2), big.NewInt(159), nil)) - if err != nil { - return nil, errutil.InternalError{Err: fmt.Sprintf("error generating serial number: %v", err)} - } - return serial, nil -} - -// ComparePublicKeys compares two public keys and returns true if they match -func ComparePublicKeys(key1Iface, key2Iface crypto.PublicKey) (bool, error) { - switch key1Iface.(type) { - case *rsa.PublicKey: - key1 := key1Iface.(*rsa.PublicKey) - key2, ok := key2Iface.(*rsa.PublicKey) - if !ok { - return false, fmt.Errorf("key types do not match: %T and %T", key1Iface, key2Iface) - } - if key1.N.Cmp(key2.N) != 0 || - key1.E != key2.E { - return false, nil - } - return true, nil - - case *ecdsa.PublicKey: - key1 := key1Iface.(*ecdsa.PublicKey) - key2, ok := key2Iface.(*ecdsa.PublicKey) - if !ok { - return false, fmt.Errorf("key types do not match: %T and %T", key1Iface, key2Iface) - } - if key1.X.Cmp(key2.X) != 0 || - key1.Y.Cmp(key2.Y) != 0 { - return false, nil - } - key1Params := key1.Params() - key2Params := key2.Params() - if key1Params.P.Cmp(key2Params.P) != 0 || - key1Params.N.Cmp(key2Params.N) != 0 || - key1Params.B.Cmp(key2Params.B) != 0 || - key1Params.Gx.Cmp(key2Params.Gx) != 0 || - key1Params.Gy.Cmp(key2Params.Gy) != 0 || - key1Params.BitSize != key2Params.BitSize { - return false, nil - } - return true, nil - - default: - return false, fmt.Errorf("cannot compare key with type %T", key1Iface) - } -} - -// PasrsePublicKeyPEM is used to parse RSA and ECDSA public keys from PEMs -func ParsePublicKeyPEM(data []byte) (interface{}, error) { - block, data := pem.Decode(data) - if block != nil { - var rawKey interface{} - var err error - if rawKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - rawKey = cert.PublicKey - } else { - return nil, err - } - } - - if rsaPublicKey, ok := rawKey.(*rsa.PublicKey); ok { - return rsaPublicKey, nil - } - if ecPublicKey, ok := rawKey.(*ecdsa.PublicKey); ok { - return ecPublicKey, nil - } - } - - return nil, errors.New("data does not contain any valid RSA or ECDSA public keys") -} diff --git a/vendor/github.com/hashicorp/vault/helper/certutil/types.go b/vendor/github.com/hashicorp/vault/helper/certutil/types.go deleted file mode 100644 index 9a27a6fb1..000000000 --- a/vendor/github.com/hashicorp/vault/helper/certutil/types.go +++ /dev/null @@ -1,591 +0,0 @@ -// Package certutil contains helper functions that are mostly used -// with the PKI backend but can be generally useful. Functionality -// includes helpers for converting a certificate/private key bundle -// between DER and PEM, printing certificate serial numbers, and more. -// -// Functionality specific to the PKI backend includes some types -// and helper methods to make requesting certificates from the -// backend easy. -package certutil - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/errutil" -) - -// Secret is used to attempt to unmarshal a Vault secret -// JSON response, as a convenience -type Secret struct { - Data map[string]interface{} `json:"data"` -} - -// PrivateKeyType holds a string representation of the type of private key (ec -// or rsa) referenced in CertBundle and ParsedCertBundle. This uses colloquial -// names rather than official names, to eliminate confusion -type PrivateKeyType string - -//Well-known PrivateKeyTypes -const ( - UnknownPrivateKey PrivateKeyType = "" - RSAPrivateKey PrivateKeyType = "rsa" - ECPrivateKey PrivateKeyType = "ec" -) - -// TLSUsage controls whether the intended usage of a *tls.Config -// returned from ParsedCertBundle.getTLSConfig is for server use, -// client use, or both, which affects which values are set -type TLSUsage int - -//Well-known TLSUsage types -const ( - TLSUnknown TLSUsage = 0 - TLSServer TLSUsage = 1 << iota - TLSClient -) - -//BlockType indicates the serialization format of the key -type BlockType string - -//Well-known formats -const ( - PKCS1Block BlockType = "RSA PRIVATE KEY" - PKCS8Block BlockType = "PRIVATE KEY" - ECBlock BlockType = "EC PRIVATE KEY" -) - -//ParsedPrivateKeyContainer allows common key setting for certs and CSRs -type ParsedPrivateKeyContainer interface { - SetParsedPrivateKey(crypto.Signer, PrivateKeyType, []byte) -} - -// CertBlock contains the DER-encoded certificate and the PEM -// block's byte array -type CertBlock struct { - Certificate *x509.Certificate - Bytes []byte -} - -// CertBundle contains a key type, a PEM-encoded private key, -// a PEM-encoded certificate, and a string-encoded serial number, -// returned from a successful Issue request -type CertBundle struct { - PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"` - Certificate string `json:"certificate" structs:"certificate" mapstructure:"certificate"` - IssuingCA string `json:"issuing_ca" structs:"issuing_ca" mapstructure:"issuing_ca"` - CAChain []string `json:"ca_chain" structs:"ca_chain" mapstructure:"ca_chain"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` - SerialNumber string `json:"serial_number" structs:"serial_number" mapstructure:"serial_number"` -} - -// ParsedCertBundle contains a key type, a DER-encoded private key, -// and a DER-encoded certificate -type ParsedCertBundle struct { - PrivateKeyType PrivateKeyType - PrivateKeyFormat BlockType - PrivateKeyBytes []byte - PrivateKey crypto.Signer - CertificateBytes []byte - Certificate *x509.Certificate - CAChain []*CertBlock -} - -// CSRBundle contains a key type, a PEM-encoded private key, -// and a PEM-encoded CSR -type CSRBundle struct { - PrivateKeyType PrivateKeyType `json:"private_key_type" structs:"private_key_type" mapstructure:"private_key_type"` - CSR string `json:"csr" structs:"csr" mapstructure:"csr"` - PrivateKey string `json:"private_key" structs:"private_key" mapstructure:"private_key"` -} - -// ParsedCSRBundle contains a key type, a DER-encoded private key, -// and a DER-encoded certificate request -type ParsedCSRBundle struct { - PrivateKeyType PrivateKeyType - PrivateKeyBytes []byte - PrivateKey crypto.Signer - CSRBytes []byte - CSR *x509.CertificateRequest -} - -// ToPEMBundle converts a string-based certificate bundle -// to a PEM-based string certificate bundle in trust path -// order, leaf certificate first -func (c *CertBundle) ToPEMBundle() string { - var result []string - - if len(c.PrivateKey) > 0 { - result = append(result, c.PrivateKey) - } - if len(c.Certificate) > 0 { - result = append(result, c.Certificate) - } - if len(c.CAChain) > 0 { - result = append(result, c.CAChain...) - } - - return strings.Join(result, "\n") -} - -// ToParsedCertBundle converts a string-based certificate bundle -// to a byte-based raw certificate bundle -func (c *CertBundle) ToParsedCertBundle() (*ParsedCertBundle, error) { - result := &ParsedCertBundle{} - var err error - var pemBlock *pem.Block - - if len(c.PrivateKey) > 0 { - pemBlock, _ = pem.Decode([]byte(c.PrivateKey)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding private key from cert bundle"} - } - - result.PrivateKeyBytes = pemBlock.Bytes - result.PrivateKeyFormat = BlockType(strings.TrimSpace(pemBlock.Type)) - - switch result.PrivateKeyFormat { - case ECBlock: - result.PrivateKeyType, c.PrivateKeyType = ECPrivateKey, ECPrivateKey - case PKCS1Block: - c.PrivateKeyType, result.PrivateKeyType = RSAPrivateKey, RSAPrivateKey - case PKCS8Block: - t, err := getPKCS8Type(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting key type from pkcs#8: %v", err)} - } - result.PrivateKeyType = t - switch t { - case ECPrivateKey: - c.PrivateKeyType = ECPrivateKey - case RSAPrivateKey: - c.PrivateKeyType = RSAPrivateKey - } - default: - return nil, errutil.UserError{Err: fmt.Sprintf("Unsupported key block type: %s", pemBlock.Type)} - } - - result.PrivateKey, err = result.getSigner() - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", err)} - } - } - - if len(c.Certificate) > 0 { - pemBlock, _ = pem.Decode([]byte(c.Certificate)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - result.CertificateBytes = pemBlock.Bytes - result.Certificate, err = x509.ParseCertificate(result.CertificateBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle: %v", err)} - } - } - switch { - case len(c.CAChain) > 0: - for _, cert := range c.CAChain { - pemBlock, _ := pem.Decode([]byte(cert)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - - parsedCert, err := x509.ParseCertificate(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via CA chain: %v", err)} - } - - certBlock := &CertBlock{ - Bytes: pemBlock.Bytes, - Certificate: parsedCert, - } - result.CAChain = append(result.CAChain, certBlock) - } - - // For backwards compatibility - case len(c.IssuingCA) > 0: - pemBlock, _ = pem.Decode([]byte(c.IssuingCA)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding ca certificate from cert bundle"} - } - - parsedCert, err := x509.ParseCertificate(pemBlock.Bytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via issuing CA: %v", err)} - } - - certBlock := &CertBlock{ - Bytes: pemBlock.Bytes, - Certificate: parsedCert, - } - result.CAChain = append(result.CAChain, certBlock) - } - - // Populate if it isn't there already - if len(c.SerialNumber) == 0 && len(c.Certificate) > 0 { - c.SerialNumber = GetHexFormatted(result.Certificate.SerialNumber.Bytes(), ":") - } - - return result, nil -} - -// ToCertBundle converts a byte-based raw DER certificate bundle -// to a PEM-based string certificate bundle -func (p *ParsedCertBundle) ToCertBundle() (*CertBundle, error) { - result := &CertBundle{} - block := pem.Block{ - Type: "CERTIFICATE", - } - - if p.Certificate != nil { - result.SerialNumber = strings.TrimSpace(GetHexFormatted(p.Certificate.SerialNumber.Bytes(), ":")) - } - - if p.CertificateBytes != nil && len(p.CertificateBytes) > 0 { - block.Bytes = p.CertificateBytes - result.Certificate = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - for _, caCert := range p.CAChain { - block.Bytes = caCert.Bytes - certificate := strings.TrimSpace(string(pem.EncodeToMemory(&block))) - - result.CAChain = append(result.CAChain, certificate) - } - - if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 { - block.Type = string(p.PrivateKeyFormat) - block.Bytes = p.PrivateKeyBytes - result.PrivateKeyType = p.PrivateKeyType - - //Handle bundle not parsed by us - if block.Type == "" { - switch p.PrivateKeyType { - case ECPrivateKey: - block.Type = string(ECBlock) - case RSAPrivateKey: - block.Type = string(PKCS1Block) - } - } - - result.PrivateKey = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - return result, nil -} - -// Verify checks if the parsed bundle is valid. It validates the public -// key of the certificate to the private key and checks the certificate trust -// chain for path issues. -func (p *ParsedCertBundle) Verify() error { - // If private key exists, check if it matches the public key of cert - if p.PrivateKey != nil && p.Certificate != nil { - equal, err := ComparePublicKeys(p.Certificate.PublicKey, p.PrivateKey.Public()) - if err != nil { - return errwrap.Wrapf("could not compare public and private keys: {{err}}", err) - } - if !equal { - return fmt.Errorf("public key of certificate does not match private key") - } - } - - certPath := p.GetCertificatePath() - if len(certPath) > 1 { - for i, caCert := range certPath[1:] { - if !caCert.Certificate.IsCA { - return fmt.Errorf("certificate %d of certificate chain is not a certificate authority", i+1) - } - if !bytes.Equal(certPath[i].Certificate.AuthorityKeyId, caCert.Certificate.SubjectKeyId) { - return fmt.Errorf("certificate %d of certificate chain ca trust path is incorrect (%q/%q)", - i+1, certPath[i].Certificate.Subject.CommonName, caCert.Certificate.Subject.CommonName) - } - } - } - - return nil -} - -// GetCertificatePath returns a slice of certificates making up a path, pulled -// from the parsed cert bundle -func (p *ParsedCertBundle) GetCertificatePath() []*CertBlock { - var certPath []*CertBlock - - certPath = append(certPath, &CertBlock{ - Certificate: p.Certificate, - Bytes: p.CertificateBytes, - }) - - if len(p.CAChain) > 0 { - // Root CA puts itself in the chain - if p.CAChain[0].Certificate.SerialNumber != p.Certificate.SerialNumber { - certPath = append(certPath, p.CAChain...) - } - } - - return certPath -} - -// GetSigner returns a crypto.Signer corresponding to the private key -// contained in this ParsedCertBundle. The Signer contains a Public() function -// for getting the corresponding public. The Signer can also be -// type-converted to private keys -func (p *ParsedCertBundle) getSigner() (crypto.Signer, error) { - var signer crypto.Signer - var err error - - if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 { - return nil, errutil.UserError{Err: "Given parsed cert bundle does not have private key information"} - } - - switch p.PrivateKeyFormat { - case ECBlock: - signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private EC key: %s", err)} - } - - case PKCS1Block: - signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)} - } - - case PKCS8Block: - if k, err := x509.ParsePKCS8PrivateKey(p.PrivateKeyBytes); err == nil { - switch k := k.(type) { - case *rsa.PrivateKey, *ecdsa.PrivateKey: - return k.(crypto.Signer), nil - default: - return nil, errutil.UserError{Err: "Found unknown private key type in pkcs#8 wrapping"} - } - } - return nil, errutil.UserError{Err: fmt.Sprintf("Failed to parse pkcs#8 key: %v", err)} - default: - return nil, errutil.UserError{Err: "Unable to determine type of private key; only RSA and EC are supported"} - } - return signer, nil -} - -// SetParsedPrivateKey sets the private key parameters on the bundle -func (p *ParsedCertBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte) { - p.PrivateKey = privateKey - p.PrivateKeyType = privateKeyType - p.PrivateKeyBytes = privateKeyBytes -} - -func getPKCS8Type(bs []byte) (PrivateKeyType, error) { - k, err := x509.ParsePKCS8PrivateKey(bs) - if err != nil { - return UnknownPrivateKey, errutil.UserError{Err: fmt.Sprintf("Failed to parse pkcs#8 key: %v", err)} - } - - switch k.(type) { - case *ecdsa.PrivateKey: - return ECPrivateKey, nil - case *rsa.PrivateKey: - return RSAPrivateKey, nil - default: - return UnknownPrivateKey, errutil.UserError{Err: "Found unknown private key type in pkcs#8 wrapping"} - } -} - -// ToParsedCSRBundle converts a string-based CSR bundle -// to a byte-based raw CSR bundle -func (c *CSRBundle) ToParsedCSRBundle() (*ParsedCSRBundle, error) { - result := &ParsedCSRBundle{} - var err error - var pemBlock *pem.Block - - if len(c.PrivateKey) > 0 { - pemBlock, _ = pem.Decode([]byte(c.PrivateKey)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding private key from cert bundle"} - } - result.PrivateKeyBytes = pemBlock.Bytes - - switch BlockType(pemBlock.Type) { - case ECBlock: - result.PrivateKeyType = ECPrivateKey - case PKCS1Block: - result.PrivateKeyType = RSAPrivateKey - default: - // Try to figure it out and correct - if _, err := x509.ParseECPrivateKey(pemBlock.Bytes); err == nil { - result.PrivateKeyType = ECPrivateKey - c.PrivateKeyType = "ec" - } else if _, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes); err == nil { - result.PrivateKeyType = RSAPrivateKey - c.PrivateKeyType = "rsa" - } else { - return nil, errutil.UserError{Err: fmt.Sprintf("Unknown private key type in bundle: %s", c.PrivateKeyType)} - } - } - - result.PrivateKey, err = result.getSigner() - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error getting signer: %s", err)} - } - } - - if len(c.CSR) > 0 { - pemBlock, _ = pem.Decode([]byte(c.CSR)) - if pemBlock == nil { - return nil, errutil.UserError{Err: "Error decoding certificate from cert bundle"} - } - result.CSRBytes = pemBlock.Bytes - result.CSR, err = x509.ParseCertificateRequest(result.CSRBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Error encountered parsing certificate bytes from raw bundle via CSR: %v", err)} - } - } - - return result, nil -} - -// ToCSRBundle converts a byte-based raw DER certificate bundle -// to a PEM-based string certificate bundle -func (p *ParsedCSRBundle) ToCSRBundle() (*CSRBundle, error) { - result := &CSRBundle{} - block := pem.Block{ - Type: "CERTIFICATE REQUEST", - } - - if p.CSRBytes != nil && len(p.CSRBytes) > 0 { - block.Bytes = p.CSRBytes - result.CSR = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - if p.PrivateKeyBytes != nil && len(p.PrivateKeyBytes) > 0 { - block.Bytes = p.PrivateKeyBytes - switch p.PrivateKeyType { - case RSAPrivateKey: - result.PrivateKeyType = "rsa" - block.Type = "RSA PRIVATE KEY" - case ECPrivateKey: - result.PrivateKeyType = "ec" - block.Type = "EC PRIVATE KEY" - default: - return nil, errutil.InternalError{Err: "Could not determine private key type when creating block"} - } - result.PrivateKey = strings.TrimSpace(string(pem.EncodeToMemory(&block))) - } - - return result, nil -} - -// GetSigner returns a crypto.Signer corresponding to the private key -// contained in this ParsedCSRBundle. The Signer contains a Public() function -// for getting the corresponding public. The Signer can also be -// type-converted to private keys -func (p *ParsedCSRBundle) getSigner() (crypto.Signer, error) { - var signer crypto.Signer - var err error - - if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 { - return nil, errutil.UserError{Err: "Given parsed cert bundle does not have private key information"} - } - - switch p.PrivateKeyType { - case ECPrivateKey: - signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private EC key: %s", err)} - } - - case RSAPrivateKey: - signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes) - if err != nil { - return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)} - } - - default: - return nil, errutil.UserError{Err: "Unable to determine type of private key; only RSA and EC are supported"} - } - return signer, nil -} - -// SetParsedPrivateKey sets the private key parameters on the bundle -func (p *ParsedCSRBundle) SetParsedPrivateKey(privateKey crypto.Signer, privateKeyType PrivateKeyType, privateKeyBytes []byte) { - p.PrivateKey = privateKey - p.PrivateKeyType = privateKeyType - p.PrivateKeyBytes = privateKeyBytes -} - -// getTLSConfig returns a TLS config generally suitable for client -// authentication. The returned TLS config can be modified slightly -// to be made suitable for a server requiring client authentication; -// specifically, you should set the value of ClientAuth in the returned -// config to match your needs. -func (p *ParsedCertBundle) GetTLSConfig(usage TLSUsage) (*tls.Config, error) { - tlsCert := tls.Certificate{ - Certificate: [][]byte{}, - } - - tlsConfig := &tls.Config{ - MinVersion: tls.VersionTLS12, - } - - if p.Certificate != nil { - tlsCert.Leaf = p.Certificate - } - - if p.PrivateKey != nil { - tlsCert.PrivateKey = p.PrivateKey - } - - if p.CertificateBytes != nil && len(p.CertificateBytes) > 0 { - tlsCert.Certificate = append(tlsCert.Certificate, p.CertificateBytes) - } - - if len(p.CAChain) > 0 { - for _, cert := range p.CAChain { - tlsCert.Certificate = append(tlsCert.Certificate, cert.Bytes) - } - - // Technically we only need one cert, but this doesn't duplicate code - certBundle, err := p.ToCertBundle() - if err != nil { - return nil, errwrap.Wrapf("error converting parsed bundle to string bundle when getting TLS config: {{err}}", err) - } - - caPool := x509.NewCertPool() - ok := caPool.AppendCertsFromPEM([]byte(certBundle.CAChain[0])) - if !ok { - return nil, fmt.Errorf("could not append CA certificate") - } - - if usage&TLSServer > 0 { - tlsConfig.ClientCAs = caPool - tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven - } - if usage&TLSClient > 0 { - tlsConfig.RootCAs = caPool - } - } - - if tlsCert.Certificate != nil && len(tlsCert.Certificate) > 0 { - tlsConfig.Certificates = []tls.Certificate{tlsCert} - tlsConfig.BuildNameToCertificate() - } - - return tlsConfig, nil -} - -// IssueData is a structure that is suitable for marshaling into a request; -// either via JSON, or into a map[string]interface{} via the structs package -type IssueData struct { - TTL string `json:"ttl" structs:"ttl" mapstructure:"ttl"` - CommonName string `json:"common_name" structs:"common_name" mapstructure:"common_name"` - OU string `json:"ou" structs:"ou" mapstructure:"ou"` - AltNames string `json:"alt_names" structs:"alt_names" mapstructure:"alt_names"` - IPSANs string `json:"ip_sans" structs:"ip_sans" mapstructure:"ip_sans"` - CSR string `json:"csr" structs:"csr" mapstructure:"csr"` -} diff --git a/vendor/github.com/hashicorp/vault/helper/cidrutil/cidr.go b/vendor/github.com/hashicorp/vault/helper/cidrutil/cidr.go deleted file mode 100644 index 6ecdba71a..000000000 --- a/vendor/github.com/hashicorp/vault/helper/cidrutil/cidr.go +++ /dev/null @@ -1,217 +0,0 @@ -package cidrutil - -import ( - "fmt" - "net" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/strutil" -) - -// RemoteAddrIsOk checks if the given remote address is either: -// - OK because there's no CIDR whitelist -// - OK because it's in the CIDR whitelist -func RemoteAddrIsOk(remoteAddr string, boundCIDRs []*sockaddr.SockAddrMarshaler) bool { - if len(boundCIDRs) == 0 { - // There's no CIDR whitelist. - return true - } - remoteSockAddr, err := sockaddr.NewSockAddr(remoteAddr) - if err != nil { - // Can't tell, err on the side of less access. - return false - } - for _, cidr := range boundCIDRs { - if cidr.Contains(remoteSockAddr) { - // Whitelisted. - return true - } - } - // Not whitelisted. - return false -} - -// IPBelongsToCIDR checks if the given IP is encompassed by the given CIDR block -func IPBelongsToCIDR(ipAddr string, cidr string) (bool, error) { - if ipAddr == "" { - return false, fmt.Errorf("missing IP address") - } - - ip := net.ParseIP(ipAddr) - if ip == nil { - return false, fmt.Errorf("invalid IP address") - } - - _, ipnet, err := net.ParseCIDR(cidr) - if err != nil { - return false, err - } - - if !ipnet.Contains(ip) { - return false, nil - } - - return true, nil -} - -// IPBelongsToCIDRBlocksSlice checks if the given IP is encompassed by any of the given -// CIDR blocks -func IPBelongsToCIDRBlocksSlice(ipAddr string, cidrs []string) (bool, error) { - if ipAddr == "" { - return false, fmt.Errorf("missing IP address") - } - - if len(cidrs) == 0 { - return false, fmt.Errorf("missing CIDR blocks to be checked against") - } - - if ip := net.ParseIP(ipAddr); ip == nil { - return false, fmt.Errorf("invalid IP address") - } - - for _, cidr := range cidrs { - belongs, err := IPBelongsToCIDR(ipAddr, cidr) - if err != nil { - return false, err - } - if belongs { - return true, nil - } - } - - return false, nil -} - -// ValidateCIDRListString checks if the list of CIDR blocks are valid, given -// that the input is a string composed by joining all the CIDR blocks using a -// separator. The input is separated based on the given separator and validity -// of each is checked. -func ValidateCIDRListString(cidrList string, separator string) (bool, error) { - if cidrList == "" { - return false, fmt.Errorf("missing CIDR list that needs validation") - } - if separator == "" { - return false, fmt.Errorf("missing separator") - } - - return ValidateCIDRListSlice(strutil.ParseDedupLowercaseAndSortStrings(cidrList, separator)) -} - -// ValidateCIDRListSlice checks if the given list of CIDR blocks are valid -func ValidateCIDRListSlice(cidrBlocks []string) (bool, error) { - if len(cidrBlocks) == 0 { - return false, fmt.Errorf("missing CIDR blocks that needs validation") - } - - for _, block := range cidrBlocks { - if _, _, err := net.ParseCIDR(strings.TrimSpace(block)); err != nil { - return false, err - } - } - - return true, nil -} - -// Subset checks if the IPs belonging to a given CIDR block is a subset of IPs -// belonging to another CIDR block. -func Subset(cidr1, cidr2 string) (bool, error) { - if cidr1 == "" { - return false, fmt.Errorf("missing CIDR to be checked against") - } - - if cidr2 == "" { - return false, fmt.Errorf("missing CIDR that needs to be checked") - } - - ip1, net1, err := net.ParseCIDR(cidr1) - if err != nil { - return false, errwrap.Wrapf("failed to parse the CIDR to be checked against: {{err}}", err) - } - - zeroAddr := false - if ip := ip1.To4(); ip != nil && ip.Equal(net.IPv4zero) { - zeroAddr = true - } - if ip := ip1.To16(); ip != nil && ip.Equal(net.IPv6zero) { - zeroAddr = true - } - - maskLen1, _ := net1.Mask.Size() - if !zeroAddr && maskLen1 == 0 { - return false, fmt.Errorf("CIDR to be checked against is not in its canonical form") - } - - ip2, net2, err := net.ParseCIDR(cidr2) - if err != nil { - return false, errwrap.Wrapf("failed to parse the CIDR that needs to be checked: {{err}}", err) - } - - zeroAddr = false - if ip := ip2.To4(); ip != nil && ip.Equal(net.IPv4zero) { - zeroAddr = true - } - if ip := ip2.To16(); ip != nil && ip.Equal(net.IPv6zero) { - zeroAddr = true - } - - maskLen2, _ := net2.Mask.Size() - if !zeroAddr && maskLen2 == 0 { - return false, fmt.Errorf("CIDR that needs to be checked is not in its canonical form") - } - - // If the mask length of the CIDR that needs to be checked is smaller - // then the mask length of the CIDR to be checked against, then the - // former will encompass more IPs than the latter, and hence can't be a - // subset of the latter. - if maskLen2 < maskLen1 { - return false, nil - } - - belongs, err := IPBelongsToCIDR(net2.IP.String(), cidr1) - if err != nil { - return false, err - } - - return belongs, nil -} - -// SubsetBlocks checks if each CIDR block of a given set of CIDR blocks, is a -// subset of at least one CIDR block belonging to another set of CIDR blocks. -// First parameter is the set of CIDR blocks to check against and the second -// parameter is the set of CIDR blocks that needs to be checked. -func SubsetBlocks(cidrBlocks1, cidrBlocks2 []string) (bool, error) { - if len(cidrBlocks1) == 0 { - return false, fmt.Errorf("missing CIDR blocks to be checked against") - } - - if len(cidrBlocks2) == 0 { - return false, fmt.Errorf("missing CIDR blocks that needs to be checked") - } - - // Check if all the elements of cidrBlocks2 is a subset of at least one - // element of cidrBlocks1 - for _, cidrBlock2 := range cidrBlocks2 { - isSubset := false - for _, cidrBlock1 := range cidrBlocks1 { - subset, err := Subset(cidrBlock1, cidrBlock2) - if err != nil { - return false, err - } - // If CIDR is a subset of any of the CIDR block, its - // good enough. Break out. - if subset { - isSubset = true - break - } - } - // CIDR block was not a subset of any of the CIDR blocks in the - // set of blocks to check against - if !isSubset { - return false, nil - } - } - - return true, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go b/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go index e485f2f22..a7fb87bcf 100644 --- a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go +++ b/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go @@ -6,6 +6,9 @@ import ( "compress/lzw" "fmt" "io" + + "github.com/golang/snappy" + "github.com/hashicorp/errwrap" ) const ( @@ -20,16 +23,35 @@ const ( // Byte value used as canary when using Lzw format CompressionCanaryLzw byte = 'L' + // Byte value used as canary when using Snappy format + CompressionCanarySnappy byte = 'S' + CompressionTypeLzw = "lzw" CompressionTypeGzip = "gzip" + + CompressionTypeSnappy = "snappy" ) +// SnappyReadCloser embeds the snappy reader which implements the io.Reader +// interface. The decompress procedure in this utility expects an +// io.ReadCloser. This type implements the io.Closer interface to retain the +// generic way of decompression. +type SnappyReadCloser struct { + *snappy.Reader +} + +// Close is a noop method implemented only to satisfy the io.Closer interface +func (s *SnappyReadCloser) Close() error { + return nil +} + // CompressionConfig is used to select a compression type to be performed by // Compress and Decompress utilities. // Supported types are: // * CompressionTypeLzw // * CompressionTypeGzip +// * CompressionTypeSnappy // // When using CompressionTypeGzip, the compression levels can also be chosen: // * gzip.DefaultCompression @@ -78,11 +100,15 @@ func Compress(data []byte, config *CompressionConfig) ([]byte, error) { config.GzipCompressionLevel = gzip.DefaultCompression } writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) + case CompressionTypeSnappy: + buf.Write([]byte{CompressionCanarySnappy}) + writer = snappy.NewBufferedWriter(&buf) default: return nil, fmt.Errorf("unsupported compression type") } + if err != nil { - return nil, fmt.Errorf("failed to create a compression writer; err: %v", err) + return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) } if writer == nil { @@ -92,7 +118,7 @@ func Compress(data []byte, config *CompressionConfig) ([]byte, error) { // Compress the input and place it in the same buffer containing the // canary byte. if _, err = writer.Write(data); err != nil { - return nil, fmt.Errorf("failed to compress input data; err: %v", err) + return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) } // Close the io.WriteCloser @@ -117,22 +143,29 @@ func Decompress(data []byte) ([]byte, bool, error) { } switch { + // If the first byte matches the canary byte, remove the canary + // byte and try to decompress the data that is after the canary. case data[0] == CompressionCanaryGzip: - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. if len(data) < 2 { return nil, false, fmt.Errorf("invalid 'data' after the canary") } data = data[1:] reader, err = gzip.NewReader(bytes.NewReader(data)) case data[0] == CompressionCanaryLzw: - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. if len(data) < 2 { return nil, false, fmt.Errorf("invalid 'data' after the canary") } data = data[1:] reader = lzw.NewReader(bytes.NewReader(data), lzw.LSB, 8) + + case data[0] == CompressionCanarySnappy: + if len(data) < 2 { + return nil, false, fmt.Errorf("invalid 'data' after the canary") + } + data = data[1:] + reader = &SnappyReadCloser{ + Reader: snappy.NewReader(bytes.NewReader(data)), + } default: // If the first byte doesn't match the canary byte, it means // that the content was not compressed at all. Indicate the @@ -140,7 +173,7 @@ func Decompress(data []byte) ([]byte, bool, error) { return nil, true, nil } if err != nil { - return nil, false, fmt.Errorf("failed to create a compression reader; err: %v", err) + return nil, false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) } if reader == nil { return nil, false, fmt.Errorf("failed to create a compression reader") diff --git a/vendor/github.com/hashicorp/vault/helper/dhutil/dhutil.go b/vendor/github.com/hashicorp/vault/helper/dhutil/dhutil.go deleted file mode 100644 index 86e23298e..000000000 --- a/vendor/github.com/hashicorp/vault/helper/dhutil/dhutil.go +++ /dev/null @@ -1,121 +0,0 @@ -package dhutil - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "errors" - "fmt" - "io" - - "golang.org/x/crypto/curve25519" -) - -type PublicKeyInfo struct { - Curve25519PublicKey []byte `json:"curve25519_public_key"` -} - -type Envelope struct { - Curve25519PublicKey []byte `json:"curve25519_public_key"` - Nonce []byte `json:"nonce"` - EncryptedPayload []byte `json:"encrypted_payload"` -} - -// generatePublicPrivateKey uses curve25519 to generate a public and private key -// pair. -func GeneratePublicPrivateKey() ([]byte, []byte, error) { - var scalar, public [32]byte - - if _, err := io.ReadFull(rand.Reader, scalar[:]); err != nil { - return nil, nil, err - } - - curve25519.ScalarBaseMult(&public, &scalar) - return public[:], scalar[:], nil -} - -// generateSharedKey uses the private key and the other party's public key to -// generate the shared secret. -func GenerateSharedKey(ourPrivate, theirPublic []byte) ([]byte, error) { - if len(ourPrivate) != 32 { - return nil, fmt.Errorf("invalid private key length: %d", len(ourPrivate)) - } - if len(theirPublic) != 32 { - return nil, fmt.Errorf("invalid public key length: %d", len(theirPublic)) - } - - var scalar, pub, secret [32]byte - copy(scalar[:], ourPrivate) - copy(pub[:], theirPublic) - - curve25519.ScalarMult(&secret, &scalar, &pub) - - return secret[:], nil -} - -// Use AES256-GCM to encrypt some plaintext with a provided key. The returned values are -// the ciphertext, the nonce, and error respectively. -func EncryptAES(key, plaintext, aad []byte) ([]byte, []byte, error) { - // We enforce AES-256, so check explicitly for 32 bytes on the key - if len(key) != 32 { - return nil, nil, fmt.Errorf("invalid key length: %d", len(key)) - } - - if len(plaintext) == 0 { - return nil, nil, errors.New("empty plaintext provided") - } - - block, err := aes.NewCipher(key) - if err != nil { - return nil, nil, err - } - - // Never use more than 2^32 random nonces with a given key because of the risk of a repeat. - nonce := make([]byte, 12) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return nil, nil, err - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, nil, err - } - - ciphertext := aesgcm.Seal(nil, nonce, plaintext, aad) - - return ciphertext, nonce, nil -} - -// Use AES256-GCM to decrypt some ciphertext with a provided key and nonce. The -// returned values are the plaintext and error respectively. -func DecryptAES(key, ciphertext, nonce, aad []byte) ([]byte, error) { - // We enforce AES-256, so check explicitly for 32 bytes on the key - if len(key) != 32 { - return nil, fmt.Errorf("invalid key length: %d", len(key)) - } - - if len(ciphertext) == 0 { - return nil, errors.New("empty ciphertext provided") - } - - if len(nonce) == 0 { - return nil, errors.New("empty nonce provided") - } - - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - return nil, err - } - - plaintext, err := aesgcm.Open(nil, nonce, ciphertext, aad) - if err != nil { - return nil, err - } - - return plaintext, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/errutil/error.go b/vendor/github.com/hashicorp/vault/helper/errutil/error.go deleted file mode 100644 index 0b95efb40..000000000 --- a/vendor/github.com/hashicorp/vault/helper/errutil/error.go +++ /dev/null @@ -1,20 +0,0 @@ -package errutil - -// UserError represents an error generated due to invalid user input -type UserError struct { - Err string -} - -func (e UserError) Error() string { - return e.Err -} - -// InternalError represents an error generated internally, -// presumably not due to invalid user input -type InternalError struct { - Err string -} - -func (e InternalError) Error() string { - return e.Err -} diff --git a/vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go b/vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go deleted file mode 100644 index 1389fd1d4..000000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/types.pb.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/forwarding/types.proto - -package forwarding // import "github.com/hashicorp/vault/helper/forwarding" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Request struct { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - // uint64 id = 1; - Method string `protobuf:"bytes,2,opt,name=method,proto3" json:"method,omitempty"` - Url *URL `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` - HeaderEntries map[string]*HeaderEntry `protobuf:"bytes,4,rep,name=header_entries,json=headerEntries,proto3" json:"header_entries,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - Body []byte `protobuf:"bytes,5,opt,name=body,proto3" json:"body,omitempty"` - Host string `protobuf:"bytes,6,opt,name=host,proto3" json:"host,omitempty"` - RemoteAddr string `protobuf:"bytes,7,opt,name=remote_addr,json=remoteAddr,proto3" json:"remote_addr,omitempty"` - PeerCertificates [][]byte `protobuf:"bytes,8,rep,name=peer_certificates,json=peerCertificates,proto3" json:"peer_certificates,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_types_7ccf0973261c4726, []int{0} -} -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (dst *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(dst, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -func (m *Request) GetMethod() string { - if m != nil { - return m.Method - } - return "" -} - -func (m *Request) GetUrl() *URL { - if m != nil { - return m.Url - } - return nil -} - -func (m *Request) GetHeaderEntries() map[string]*HeaderEntry { - if m != nil { - return m.HeaderEntries - } - return nil -} - -func (m *Request) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func (m *Request) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *Request) GetRemoteAddr() string { - if m != nil { - return m.RemoteAddr - } - return "" -} - -func (m *Request) GetPeerCertificates() [][]byte { - if m != nil { - return m.PeerCertificates - } - return nil -} - -type URL struct { - Scheme string `protobuf:"bytes,1,opt,name=scheme,proto3" json:"scheme,omitempty"` - Opaque string `protobuf:"bytes,2,opt,name=opaque,proto3" json:"opaque,omitempty"` - // This isn't needed now but might be in the future, so we'll skip the - // number to keep the ordering in net/url - // UserInfo user = 3; - Host string `protobuf:"bytes,4,opt,name=host,proto3" json:"host,omitempty"` - Path string `protobuf:"bytes,5,opt,name=path,proto3" json:"path,omitempty"` - RawPath string `protobuf:"bytes,6,opt,name=raw_path,json=rawPath,proto3" json:"raw_path,omitempty"` - // This also isn't needed right now, but we'll reserve the number - // bool force_query = 7; - RawQuery string `protobuf:"bytes,8,opt,name=raw_query,json=rawQuery,proto3" json:"raw_query,omitempty"` - Fragment string `protobuf:"bytes,9,opt,name=fragment,proto3" json:"fragment,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *URL) Reset() { *m = URL{} } -func (m *URL) String() string { return proto.CompactTextString(m) } -func (*URL) ProtoMessage() {} -func (*URL) Descriptor() ([]byte, []int) { - return fileDescriptor_types_7ccf0973261c4726, []int{1} -} -func (m *URL) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_URL.Unmarshal(m, b) -} -func (m *URL) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_URL.Marshal(b, m, deterministic) -} -func (dst *URL) XXX_Merge(src proto.Message) { - xxx_messageInfo_URL.Merge(dst, src) -} -func (m *URL) XXX_Size() int { - return xxx_messageInfo_URL.Size(m) -} -func (m *URL) XXX_DiscardUnknown() { - xxx_messageInfo_URL.DiscardUnknown(m) -} - -var xxx_messageInfo_URL proto.InternalMessageInfo - -func (m *URL) GetScheme() string { - if m != nil { - return m.Scheme - } - return "" -} - -func (m *URL) GetOpaque() string { - if m != nil { - return m.Opaque - } - return "" -} - -func (m *URL) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *URL) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func (m *URL) GetRawPath() string { - if m != nil { - return m.RawPath - } - return "" -} - -func (m *URL) GetRawQuery() string { - if m != nil { - return m.RawQuery - } - return "" -} - -func (m *URL) GetFragment() string { - if m != nil { - return m.Fragment - } - return "" -} - -type HeaderEntry struct { - Values []string `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HeaderEntry) Reset() { *m = HeaderEntry{} } -func (m *HeaderEntry) String() string { return proto.CompactTextString(m) } -func (*HeaderEntry) ProtoMessage() {} -func (*HeaderEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_types_7ccf0973261c4726, []int{2} -} -func (m *HeaderEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HeaderEntry.Unmarshal(m, b) -} -func (m *HeaderEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HeaderEntry.Marshal(b, m, deterministic) -} -func (dst *HeaderEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_HeaderEntry.Merge(dst, src) -} -func (m *HeaderEntry) XXX_Size() int { - return xxx_messageInfo_HeaderEntry.Size(m) -} -func (m *HeaderEntry) XXX_DiscardUnknown() { - xxx_messageInfo_HeaderEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_HeaderEntry proto.InternalMessageInfo - -func (m *HeaderEntry) GetValues() []string { - if m != nil { - return m.Values - } - return nil -} - -type Response struct { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - // uint64 id = 1; - StatusCode uint32 `protobuf:"varint,2,opt,name=status_code,json=statusCode,proto3" json:"status_code,omitempty"` - Body []byte `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"` - // Added in 0.6.2 to ensure that the content-type is set appropriately, as - // well as any other information - HeaderEntries map[string]*HeaderEntry `protobuf:"bytes,4,rep,name=header_entries,json=headerEntries,proto3" json:"header_entries,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_types_7ccf0973261c4726, []int{3} -} -func (m *Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Response.Unmarshal(m, b) -} -func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Response.Marshal(b, m, deterministic) -} -func (dst *Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Response.Merge(dst, src) -} -func (m *Response) XXX_Size() int { - return xxx_messageInfo_Response.Size(m) -} -func (m *Response) XXX_DiscardUnknown() { - xxx_messageInfo_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Response proto.InternalMessageInfo - -func (m *Response) GetStatusCode() uint32 { - if m != nil { - return m.StatusCode - } - return 0 -} - -func (m *Response) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func (m *Response) GetHeaderEntries() map[string]*HeaderEntry { - if m != nil { - return m.HeaderEntries - } - return nil -} - -func init() { - proto.RegisterType((*Request)(nil), "forwarding.Request") - proto.RegisterMapType((map[string]*HeaderEntry)(nil), "forwarding.Request.HeaderEntriesEntry") - proto.RegisterType((*URL)(nil), "forwarding.URL") - proto.RegisterType((*HeaderEntry)(nil), "forwarding.HeaderEntry") - proto.RegisterType((*Response)(nil), "forwarding.Response") - proto.RegisterMapType((map[string]*HeaderEntry)(nil), "forwarding.Response.HeaderEntriesEntry") -} - -func init() { - proto.RegisterFile("helper/forwarding/types.proto", fileDescriptor_types_7ccf0973261c4726) -} - -var fileDescriptor_types_7ccf0973261c4726 = []byte{ - // 475 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x53, 0x4f, 0x8f, 0xd3, 0x3e, - 0x10, 0x55, 0x9a, 0x6e, 0xff, 0x4c, 0x77, 0x7f, 0xbf, 0xc5, 0x07, 0x30, 0x8b, 0x10, 0xa1, 0x12, - 0x10, 0x09, 0x48, 0xa4, 0x72, 0x41, 0xdc, 0x60, 0x85, 0xc4, 0x61, 0x41, 0x60, 0x69, 0x0f, 0x70, - 0x89, 0xdc, 0x78, 0x5a, 0x47, 0x34, 0x75, 0x6a, 0x3b, 0x5b, 0xe5, 0x63, 0xf1, 0x9d, 0x38, 0xf1, - 0x29, 0x90, 0x9d, 0xb0, 0x0d, 0x5a, 0x21, 0x4e, 0x9c, 0x32, 0xef, 0xbd, 0xc9, 0x78, 0xde, 0x8c, - 0x0d, 0xf7, 0x25, 0x6e, 0x2a, 0xd4, 0xe9, 0x4a, 0xe9, 0x3d, 0xd7, 0xa2, 0xd8, 0xae, 0x53, 0xdb, - 0x54, 0x68, 0x92, 0x4a, 0x2b, 0xab, 0x08, 0x1c, 0xf8, 0xf9, 0xf7, 0x01, 0x8c, 0x19, 0xee, 0x6a, - 0x34, 0x96, 0xdc, 0x86, 0x51, 0x89, 0x56, 0x2a, 0x41, 0x07, 0x51, 0x10, 0x4f, 0x59, 0x87, 0xc8, - 0x43, 0x08, 0x6b, 0xbd, 0xa1, 0x61, 0x14, 0xc4, 0xb3, 0xc5, 0xff, 0xc9, 0xe1, 0xef, 0xe4, 0x92, - 0x5d, 0x30, 0xa7, 0x91, 0xf7, 0xf0, 0x9f, 0x44, 0x2e, 0x50, 0x67, 0xb8, 0xb5, 0xba, 0x40, 0x43, - 0x87, 0x51, 0x18, 0xcf, 0x16, 0x8f, 0xfb, 0xd9, 0xdd, 0x39, 0xc9, 0x3b, 0x9f, 0xf9, 0xb6, 0x4d, - 0x74, 0x9f, 0x86, 0x9d, 0xc8, 0x3e, 0x47, 0x08, 0x0c, 0x97, 0x4a, 0x34, 0xf4, 0x28, 0x0a, 0xe2, - 0x63, 0xe6, 0x63, 0xc7, 0x49, 0x65, 0x2c, 0x1d, 0xf9, 0xde, 0x7c, 0x4c, 0x1e, 0xc0, 0x4c, 0x63, - 0xa9, 0x2c, 0x66, 0x5c, 0x08, 0x4d, 0xc7, 0x5e, 0x82, 0x96, 0x7a, 0x2d, 0x84, 0x26, 0x4f, 0xe1, - 0x56, 0x85, 0xa8, 0xb3, 0x1c, 0xb5, 0x2d, 0x56, 0x45, 0xce, 0x2d, 0x1a, 0x3a, 0x89, 0xc2, 0xf8, - 0x98, 0x9d, 0x3a, 0xe1, 0xbc, 0xc7, 0x9f, 0x7d, 0x06, 0x72, 0xb3, 0x35, 0x72, 0x0a, 0xe1, 0x57, - 0x6c, 0x68, 0xe0, 0x6b, 0xbb, 0x90, 0x3c, 0x87, 0xa3, 0x2b, 0xbe, 0xa9, 0xd1, 0x8f, 0x69, 0xb6, - 0xb8, 0xd3, 0xf7, 0x78, 0x28, 0xd0, 0xb0, 0x36, 0xeb, 0xd5, 0xe0, 0x65, 0x30, 0xff, 0x16, 0x40, - 0x78, 0xc9, 0x2e, 0xdc, 0x88, 0x4d, 0x2e, 0xb1, 0xc4, 0xae, 0x5e, 0x87, 0x1c, 0xaf, 0x2a, 0xbe, - 0xeb, 0x6a, 0x4e, 0x59, 0x87, 0xae, 0x4d, 0x0f, 0x7b, 0xa6, 0x09, 0x0c, 0x2b, 0x6e, 0xa5, 0x1f, - 0xce, 0x94, 0xf9, 0x98, 0xdc, 0x85, 0x89, 0xe6, 0xfb, 0xcc, 0xf3, 0xed, 0x80, 0xc6, 0x9a, 0xef, - 0x3f, 0x3a, 0xe9, 0x1e, 0x4c, 0x9d, 0xb4, 0xab, 0x51, 0x37, 0x74, 0xe2, 0x35, 0x97, 0xfb, 0xc9, - 0x61, 0x72, 0x06, 0x93, 0x95, 0xe6, 0xeb, 0x12, 0xb7, 0x96, 0x4e, 0x5b, 0xed, 0x17, 0x9e, 0x3f, - 0x82, 0x59, 0xcf, 0x8d, 0x6b, 0xd1, 0xfb, 0x31, 0x34, 0x88, 0x42, 0xd7, 0x62, 0x8b, 0xe6, 0x3f, - 0x02, 0x98, 0x30, 0x34, 0x95, 0xda, 0x1a, 0x74, 0x0b, 0x31, 0x96, 0xdb, 0xda, 0x64, 0xb9, 0x12, - 0xad, 0x99, 0x13, 0x06, 0x2d, 0x75, 0xae, 0x04, 0x5e, 0x6f, 0x36, 0xec, 0x6d, 0xf6, 0xc3, 0x1f, - 0x2e, 0xcf, 0x93, 0xdf, 0x2f, 0x4f, 0x7b, 0xc4, 0xdf, 0x6f, 0xcf, 0x3f, 0xdc, 0xe3, 0x9b, 0xe4, - 0xcb, 0xb3, 0x75, 0x61, 0x65, 0xbd, 0x4c, 0x72, 0x55, 0xa6, 0x92, 0x1b, 0x59, 0xe4, 0x4a, 0x57, - 0xe9, 0x15, 0xaf, 0x37, 0x36, 0xbd, 0xf1, 0xec, 0x96, 0x23, 0xff, 0xe2, 0x5e, 0xfc, 0x0c, 0x00, - 0x00, 0xff, 0xff, 0x03, 0xfa, 0xd9, 0x51, 0x92, 0x03, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto b/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto deleted file mode 100644 index 218993492..000000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/types.proto +++ /dev/null @@ -1,48 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/forwarding"; - -package forwarding; - -message Request { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - //uint64 id = 1; - string method = 2; - URL url = 3; - map header_entries = 4; - bytes body = 5; - string host = 6; - string remote_addr = 7; - repeated bytes peer_certificates = 8; -} - -message URL { - string scheme = 1; - string opaque = 2; - // This isn't needed now but might be in the future, so we'll skip the - // number to keep the ordering in net/url - //UserInfo user = 3; - string host = 4; - string path = 5; - string raw_path = 6; - // This also isn't needed right now, but we'll reserve the number - //bool force_query = 7; - string raw_query = 8; - string fragment = 9; -} - -message HeaderEntry { - repeated string values = 1; -} - -message Response { - // Not used right now but reserving in case it turns out that streaming - // makes things more economical on the gRPC side - //uint64 id = 1; - uint32 status_code = 2; - bytes body = 3; - // Added in 0.6.2 to ensure that the content-type is set appropriately, as - // well as any other information - map header_entries = 4; -} diff --git a/vendor/github.com/hashicorp/vault/helper/forwarding/util.go b/vendor/github.com/hashicorp/vault/helper/forwarding/util.go deleted file mode 100644 index 0a4973e9f..000000000 --- a/vendor/github.com/hashicorp/vault/helper/forwarding/util.go +++ /dev/null @@ -1,218 +0,0 @@ -package forwarding - -import ( - "bytes" - "crypto/tls" - "crypto/x509" - "errors" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - - "github.com/golang/protobuf/proto" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/jsonutil" -) - -type bufCloser struct { - *bytes.Buffer -} - -func (b bufCloser) Close() error { - b.Reset() - return nil -} - -// GenerateForwardedRequest generates a new http.Request that contains the -// original requests's information in the new request's body. -func GenerateForwardedHTTPRequest(req *http.Request, addr string) (*http.Request, error) { - fq, err := GenerateForwardedRequest(req) - if err != nil { - return nil, err - } - - var newBody []byte - switch os.Getenv("VAULT_MESSAGE_TYPE") { - case "json": - newBody, err = jsonutil.EncodeJSON(fq) - case "json_compress": - newBody, err = jsonutil.EncodeJSONAndCompress(fq, &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeLzw, - }) - case "proto3": - fallthrough - default: - newBody, err = proto.Marshal(fq) - } - if err != nil { - return nil, err - } - - ret, err := http.NewRequest("POST", addr, bytes.NewBuffer(newBody)) - if err != nil { - return nil, err - } - - return ret, nil -} - -func GenerateForwardedRequest(req *http.Request) (*Request, error) { - var reader io.Reader = req.Body - ctx := req.Context() - maxRequestSize := ctx.Value("max_request_size") - if maxRequestSize != nil { - max, ok := maxRequestSize.(int64) - if !ok { - return nil, errors.New("could not parse max_request_size from request context") - } - if max > 0 { - reader = io.LimitReader(req.Body, max) - } - } - - body, err := ioutil.ReadAll(reader) - if err != nil { - return nil, err - } - - fq := Request{ - Method: req.Method, - HeaderEntries: make(map[string]*HeaderEntry, len(req.Header)), - Host: req.Host, - RemoteAddr: req.RemoteAddr, - Body: body, - } - - reqURL := req.URL - fq.Url = &URL{ - Scheme: reqURL.Scheme, - Opaque: reqURL.Opaque, - Host: reqURL.Host, - Path: reqURL.Path, - RawPath: reqURL.RawPath, - RawQuery: reqURL.RawQuery, - Fragment: reqURL.Fragment, - } - - for k, v := range req.Header { - fq.HeaderEntries[k] = &HeaderEntry{ - Values: v, - } - } - - if req.TLS != nil && req.TLS.PeerCertificates != nil && len(req.TLS.PeerCertificates) > 0 { - fq.PeerCertificates = make([][]byte, len(req.TLS.PeerCertificates)) - for i, cert := range req.TLS.PeerCertificates { - fq.PeerCertificates[i] = cert.Raw - } - } - - return &fq, nil -} - -// ParseForwardedRequest generates a new http.Request that is comprised of the -// values in the given request's body, assuming it correctly parses into a -// ForwardedRequest. -func ParseForwardedHTTPRequest(req *http.Request) (*http.Request, error) { - buf := bytes.NewBuffer(nil) - _, err := buf.ReadFrom(req.Body) - if err != nil { - return nil, err - } - - fq := new(Request) - switch os.Getenv("VAULT_MESSAGE_TYPE") { - case "json", "json_compress": - err = jsonutil.DecodeJSON(buf.Bytes(), fq) - default: - err = proto.Unmarshal(buf.Bytes(), fq) - } - if err != nil { - return nil, err - } - - return ParseForwardedRequest(fq) -} - -func ParseForwardedRequest(fq *Request) (*http.Request, error) { - buf := bufCloser{ - Buffer: bytes.NewBuffer(fq.Body), - } - - ret := &http.Request{ - Method: fq.Method, - Header: make(map[string][]string, len(fq.HeaderEntries)), - Body: buf, - Host: fq.Host, - RemoteAddr: fq.RemoteAddr, - } - - ret.URL = &url.URL{ - Scheme: fq.Url.Scheme, - Opaque: fq.Url.Opaque, - Host: fq.Url.Host, - Path: fq.Url.Path, - RawPath: fq.Url.RawPath, - RawQuery: fq.Url.RawQuery, - Fragment: fq.Url.Fragment, - } - - for k, v := range fq.HeaderEntries { - ret.Header[k] = v.Values - } - - if fq.PeerCertificates != nil && len(fq.PeerCertificates) > 0 { - ret.TLS = &tls.ConnectionState{ - PeerCertificates: make([]*x509.Certificate, len(fq.PeerCertificates)), - } - for i, certBytes := range fq.PeerCertificates { - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, err - } - ret.TLS.PeerCertificates[i] = cert - } - } - - return ret, nil -} - -type RPCResponseWriter struct { - statusCode int - header http.Header - body *bytes.Buffer -} - -// NewRPCResponseWriter returns an initialized RPCResponseWriter -func NewRPCResponseWriter() *RPCResponseWriter { - w := &RPCResponseWriter{ - header: make(http.Header), - body: new(bytes.Buffer), - statusCode: 200, - } - //w.header.Set("Content-Type", "application/octet-stream") - return w -} - -func (w *RPCResponseWriter) Header() http.Header { - return w.header -} - -func (w *RPCResponseWriter) Write(buf []byte) (int, error) { - w.body.Write(buf) - return len(buf), nil -} - -func (w *RPCResponseWriter) WriteHeader(code int) { - w.statusCode = code -} - -func (w *RPCResponseWriter) StatusCode() int { - return w.statusCode -} - -func (w *RPCResponseWriter) Body() *bytes.Buffer { - return w.body -} diff --git a/vendor/github.com/hashicorp/vault/helper/gated-writer/writer.go b/vendor/github.com/hashicorp/vault/helper/gated-writer/writer.go deleted file mode 100644 index 9c5aeba00..000000000 --- a/vendor/github.com/hashicorp/vault/helper/gated-writer/writer.go +++ /dev/null @@ -1,43 +0,0 @@ -package gatedwriter - -import ( - "io" - "sync" -) - -// Writer is an io.Writer implementation that buffers all of its -// data into an internal buffer until it is told to let data through. -type Writer struct { - Writer io.Writer - - buf [][]byte - flush bool - lock sync.RWMutex -} - -// Flush tells the Writer to flush any buffered data and to stop -// buffering. -func (w *Writer) Flush() { - w.lock.Lock() - w.flush = true - w.lock.Unlock() - - for _, p := range w.buf { - w.Write(p) - } - w.buf = nil -} - -func (w *Writer) Write(p []byte) (n int, err error) { - w.lock.RLock() - defer w.lock.RUnlock() - - if w.flush { - return w.Writer.Write(p) - } - - p2 := make([]byte, len(p)) - copy(p2, p) - w.buf = append(w.buf, p2) - return len(p), nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/identity.go b/vendor/github.com/hashicorp/vault/helper/identity/identity.go deleted file mode 100644 index 46789c035..000000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/identity.go +++ /dev/null @@ -1,65 +0,0 @@ -package identity - -import ( - "fmt" - - proto "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" -) - -func (g *Group) Clone() (*Group, error) { - if g == nil { - return nil, fmt.Errorf("nil group") - } - - marshaledGroup, err := proto.Marshal(g) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal group: {{err}}", err) - } - - var clonedGroup Group - err = proto.Unmarshal(marshaledGroup, &clonedGroup) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal group: {{err}}", err) - } - - return &clonedGroup, nil -} - -func (e *Entity) Clone() (*Entity, error) { - if e == nil { - return nil, fmt.Errorf("nil entity") - } - - marshaledEntity, err := proto.Marshal(e) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal entity: {{err}}", err) - } - - var clonedEntity Entity - err = proto.Unmarshal(marshaledEntity, &clonedEntity) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal entity: {{err}}", err) - } - - return &clonedEntity, nil -} - -func (p *Alias) Clone() (*Alias, error) { - if p == nil { - return nil, fmt.Errorf("nil alias") - } - - marshaledAlias, err := proto.Marshal(p) - if err != nil { - return nil, errwrap.Wrapf("failed to marshal alias: {{err}}", err) - } - - var clonedAlias Alias - err = proto.Unmarshal(marshaledAlias, &clonedAlias) - if err != nil { - return nil, errwrap.Wrapf("failed to unmarshal alias: {{err}}", err) - } - - return &clonedAlias, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go b/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go deleted file mode 100644 index bf3cfff55..000000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/sentinel.go +++ /dev/null @@ -1,125 +0,0 @@ -package identity - -import "github.com/golang/protobuf/ptypes" - -func (e *Entity) SentinelGet(key string) (interface{}, error) { - if e == nil { - return nil, nil - } - switch key { - case "aliases": - return e.Aliases, nil - case "id": - return e.ID, nil - case "meta", "metadata": - return e.Metadata, nil - case "name": - return e.Name, nil - case "creation_time": - return ptypes.TimestampString(e.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(e.LastUpdateTime), nil - case "merged_entity_ids": - return e.MergedEntityIDs, nil - case "policies": - return e.Policies, nil - } - - return nil, nil -} - -func (e *Entity) SentinelKeys() []string { - return []string{ - "id", - "aliases", - "metadata", - "meta", - "name", - "creation_time", - "last_update_time", - "merged_entity_ids", - "policies", - } -} - -func (p *Alias) SentinelGet(key string) (interface{}, error) { - if p == nil { - return nil, nil - } - switch key { - case "id": - return p.ID, nil - case "mount_type": - return p.MountType, nil - case "mount_accessor": - return p.MountAccessor, nil - case "mount_path": - return p.MountPath, nil - case "meta", "metadata": - return p.Metadata, nil - case "name": - return p.Name, nil - case "creation_time": - return ptypes.TimestampString(p.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(p.LastUpdateTime), nil - case "merged_from_entity_ids": - return p.MergedFromCanonicalIDs, nil - } - - return nil, nil -} - -func (a *Alias) SentinelKeys() []string { - return []string{ - "id", - "mount_type", - "mount_path", - "meta", - "metadata", - "name", - "creation_time", - "last_update_time", - "merged_from_entity_ids", - } -} - -func (g *Group) SentinelGet(key string) (interface{}, error) { - if g == nil { - return nil, nil - } - switch key { - case "id": - return g.ID, nil - case "name": - return g.Name, nil - case "policies": - return g.Policies, nil - case "parent_group_ids": - return g.ParentGroupIDs, nil - case "member_entity_ids": - return g.MemberEntityIDs, nil - case "meta", "metadata": - return g.Metadata, nil - case "creation_time": - return ptypes.TimestampString(g.CreationTime), nil - case "last_update_time": - return ptypes.TimestampString(g.LastUpdateTime), nil - } - - return nil, nil -} - -func (g *Group) SentinelKeys() []string { - return []string{ - "id", - "name", - "policies", - "parent_group_ids", - "member_entity_ids", - "metadata", - "meta", - "creation_time", - "last_update_time", - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/templating.go b/vendor/github.com/hashicorp/vault/helper/identity/templating.go deleted file mode 100644 index 0848b0c71..000000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/templating.go +++ /dev/null @@ -1,205 +0,0 @@ -package identity - -import ( - "errors" - "fmt" - "strings" -) - -var ( - ErrUnbalancedTemplatingCharacter = errors.New("unbalanced templating characters") - ErrNoEntityAttachedToToken = errors.New("string contains entity template directives but no entity was provided") - ErrNoGroupsAttachedToToken = errors.New("string contains groups template directives but no groups were provided") - ErrTemplateValueNotFound = errors.New("no value could be found for one of the template directives") -) - -type PopulateStringInput struct { - ValidityCheckOnly bool - String string - Entity *Entity - Groups []*Group -} - -func PopulateString(p *PopulateStringInput) (bool, string, error) { - if p == nil { - return false, "", errors.New("nil input") - } - - if p.String == "" { - return false, "", nil - } - - var subst bool - splitStr := strings.Split(p.String, "{{") - - if len(splitStr) >= 1 { - if strings.Index(splitStr[0], "}}") != -1 { - return false, "", ErrUnbalancedTemplatingCharacter - } - if len(splitStr) == 1 { - return false, p.String, nil - } - } - - var b strings.Builder - if !p.ValidityCheckOnly { - b.Grow(2 * len(p.String)) - } - - for i, str := range splitStr { - if i == 0 { - if !p.ValidityCheckOnly { - b.WriteString(str) - } - continue - } - splitPiece := strings.Split(str, "}}") - switch len(splitPiece) { - case 2: - subst = true - if !p.ValidityCheckOnly { - tmplStr, err := performTemplating(strings.TrimSpace(splitPiece[0]), p.Entity, p.Groups) - if err != nil { - return false, "", err - } - b.WriteString(tmplStr) - b.WriteString(splitPiece[1]) - } - default: - return false, "", ErrUnbalancedTemplatingCharacter - } - } - - return subst, b.String(), nil -} - -func performTemplating(input string, entity *Entity, groups []*Group) (string, error) { - performAliasTemplating := func(trimmed string, alias *Alias) (string, error) { - switch { - case trimmed == "id": - return alias.ID, nil - case trimmed == "name": - if alias.Name == "" { - return "", ErrTemplateValueNotFound - } - return alias.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := alias.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - } - - return "", ErrTemplateValueNotFound - } - - performEntityTemplating := func(trimmed string) (string, error) { - switch { - case trimmed == "id": - return entity.ID, nil - case trimmed == "name": - if entity.Name == "" { - return "", ErrTemplateValueNotFound - } - return entity.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := entity.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - case strings.HasPrefix(trimmed, "aliases."): - split := strings.SplitN(strings.TrimPrefix(trimmed, "aliases."), ".", 2) - if len(split) != 2 { - return "", errors.New("invalid alias selector") - } - var found *Alias - for _, alias := range entity.Aliases { - if split[0] == alias.MountAccessor { - found = alias - break - } - } - if found == nil { - return "", errors.New("alias not found") - } - return performAliasTemplating(split[1], found) - } - - return "", ErrTemplateValueNotFound - } - - performGroupsTemplating := func(trimmed string) (string, error) { - var ids bool - - selectorSplit := strings.SplitN(trimmed, ".", 2) - switch { - case len(selectorSplit) != 2: - return "", errors.New("invalid groups selector") - case selectorSplit[0] == "ids": - ids = true - case selectorSplit[0] == "names": - default: - return "", errors.New("invalid groups selector") - } - trimmed = selectorSplit[1] - - accessorSplit := strings.SplitN(trimmed, ".", 2) - if len(accessorSplit) != 2 { - return "", errors.New("invalid groups accessor") - } - var found *Group - for _, group := range groups { - compare := group.Name - if ids { - compare = group.ID - } - - if compare == accessorSplit[0] { - found = group - break - } - } - - if found == nil { - return "", fmt.Errorf("entity is not a member of group %q", accessorSplit[0]) - } - - trimmed = accessorSplit[1] - - switch { - case trimmed == "id": - return found.ID, nil - case trimmed == "name": - if found.Name == "" { - return "", ErrTemplateValueNotFound - } - return found.Name, nil - case strings.HasPrefix(trimmed, "metadata."): - val, ok := found.Metadata[strings.TrimPrefix(trimmed, "metadata.")] - if !ok { - return "", ErrTemplateValueNotFound - } - return val, nil - } - - return "", ErrTemplateValueNotFound - } - - switch { - case strings.HasPrefix(input, "identity.entity."): - if entity == nil { - return "", ErrNoEntityAttachedToToken - } - return performEntityTemplating(strings.TrimPrefix(input, "identity.entity.")) - - case strings.HasPrefix(input, "identity.groups."): - if len(groups) == 0 { - return "", ErrNoGroupsAttachedToToken - } - return performGroupsTemplating(strings.TrimPrefix(input, "identity.groups.")) - } - - return "", ErrTemplateValueNotFound -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go b/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go deleted file mode 100644 index 019c555eb..000000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/types.pb.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/identity/types.proto - -package identity // import "github.com/hashicorp/vault/helper/identity" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Group represents an identity group. -type Group struct { - // ID is the unique identifier for this group - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // Name is the unique name for this group - Name string `sentinel:"" protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Policies are the vault policies to be granted to members of this group - Policies []string `sentinel:"" protobuf:"bytes,3,rep,name=policies,proto3" json:"policies,omitempty"` - // ParentGroupIDs are the identifiers of those groups to which this group is a - // member of. These will serve as references to the parent group in the - // hierarchy. - ParentGroupIDs []string `sentinel:"" protobuf:"bytes,4,rep,name=parent_group_ids,json=parentGroupIds,proto3" json:"parent_group_ids,omitempty"` - // MemberEntityIDs are the identifiers of entities which are members of this - // group - MemberEntityIDs []string `sentinel:"" protobuf:"bytes,5,rep,name=member_entity_ids,json=memberEntityIDs,proto3" json:"member_entity_ids,omitempty"` - // Metadata represents the custom data tied with this group - Metadata map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // CreationTime is the time at which this group was created - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,7,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the time at which this group was last modified - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,8,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // ModifyIndex tracks the number of updates to the group. It is useful to detect - // updates to the groups. - ModifyIndex uint64 `sentinel:"" protobuf:"varint,9,opt,name=modify_index,json=modifyIndex,proto3" json:"modify_index,omitempty"` - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // group is stored in the underlying storage. This is useful to find all - // the groups belonging to a particular bucket during invalidation of the - // storage key. - BucketKeyHash string `sentinel:"" protobuf:"bytes,10,opt,name=bucket_key_hash,json=bucketKeyHash,proto3" json:"bucket_key_hash,omitempty"` - // Alias is used to mark this group as an internal mapping of a group that - // is external to the identity store. Alias can only be set if the 'type' - // is set to 'external'. - Alias *Alias `sentinel:"" protobuf:"bytes,11,opt,name=alias,proto3" json:"alias,omitempty"` - // Type indicates if this group is an internal group or an external group. - // Memberships of the internal groups can be managed over the API whereas - // the memberships on the external group --for which a corresponding alias - // will be set-- will be managed automatically. - Type string `sentinel:"" protobuf:"bytes,12,opt,name=type,proto3" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Group) Reset() { *m = Group{} } -func (m *Group) String() string { return proto.CompactTextString(m) } -func (*Group) ProtoMessage() {} -func (*Group) Descriptor() ([]byte, []int) { - return fileDescriptor_types_0360db4a8e77dd9b, []int{0} -} -func (m *Group) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Group.Unmarshal(m, b) -} -func (m *Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Group.Marshal(b, m, deterministic) -} -func (dst *Group) XXX_Merge(src proto.Message) { - xxx_messageInfo_Group.Merge(dst, src) -} -func (m *Group) XXX_Size() int { - return xxx_messageInfo_Group.Size(m) -} -func (m *Group) XXX_DiscardUnknown() { - xxx_messageInfo_Group.DiscardUnknown(m) -} - -var xxx_messageInfo_Group proto.InternalMessageInfo - -func (m *Group) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Group) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Group) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *Group) GetParentGroupIDs() []string { - if m != nil { - return m.ParentGroupIDs - } - return nil -} - -func (m *Group) GetMemberEntityIDs() []string { - if m != nil { - return m.MemberEntityIDs - } - return nil -} - -func (m *Group) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Group) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Group) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Group) GetModifyIndex() uint64 { - if m != nil { - return m.ModifyIndex - } - return 0 -} - -func (m *Group) GetBucketKeyHash() string { - if m != nil { - return m.BucketKeyHash - } - return "" -} - -func (m *Group) GetAlias() *Alias { - if m != nil { - return m.Alias - } - return nil -} - -func (m *Group) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -// Entity represents an entity that gets persisted and indexed. -// Entity is fundamentally composed of zero or many aliases. -type Entity struct { - // Aliases are the identities that this entity is made of. This can be - // empty as well to favor being able to create the entity first and then - // incrementally adding aliases. - Aliases []*Alias `sentinel:"" protobuf:"bytes,1,rep,name=aliases,proto3" json:"aliases,omitempty"` - // ID is the unique identifier of the entity which always be a UUID. This - // should never be allowed to be updated. - ID string `sentinel:"" protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` - // Name is a unique identifier of the entity which is intended to be - // human-friendly. The default name might not be human friendly since it - // gets suffixed by a UUID, but it can optionally be updated, unlike the ID - // field. - Name string `sentinel:"" protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the explicit metadata which is set by the - // clients. This is useful to tie any information pertaining to the - // aliases. This is a non-unique field of entity, meaning multiple - // entities can have the same metadata set. Entities will be indexed based - // on this explicit metadata. This enables virtual groupings of entities - // based on its metadata. - Metadata map[string]string `sentinel:"" protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // CreationTime is the time at which this entity is first created. - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,5,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the most recent time at which the properties of this - // entity got modified. This is helpful in filtering out entities based on - // its age and to take action on them, if desired. - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,6,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // MergedEntityIDs are the entities which got merged to this one. Entities - // will be indexed based on all the entities that got merged into it. This - // helps to apply the actions on this entity on the tokens that are merged - // to the merged entities. Merged entities will be deleted entirely and - // this is the only trackable trail of its earlier presence. - MergedEntityIDs []string `sentinel:"" protobuf:"bytes,7,rep,name=merged_entity_ids,json=mergedEntityIDs,proto3" json:"merged_entity_ids,omitempty"` - // Policies the entity is entitled to - Policies []string `sentinel:"" protobuf:"bytes,8,rep,name=policies,proto3" json:"policies,omitempty"` - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // entity is stored in the underlying storage. This is useful to find all - // the entities belonging to a particular bucket during invalidation of the - // storage key. - BucketKeyHash string `sentinel:"" protobuf:"bytes,9,opt,name=bucket_key_hash,json=bucketKeyHash,proto3" json:"bucket_key_hash,omitempty"` - // Disabled indicates whether tokens associated with the account should not - // be able to be used - Disabled bool `sentinel:"" protobuf:"varint,11,opt,name=disabled,proto3" json:"disabled,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Entity) Reset() { *m = Entity{} } -func (m *Entity) String() string { return proto.CompactTextString(m) } -func (*Entity) ProtoMessage() {} -func (*Entity) Descriptor() ([]byte, []int) { - return fileDescriptor_types_0360db4a8e77dd9b, []int{1} -} -func (m *Entity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Entity.Unmarshal(m, b) -} -func (m *Entity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Entity.Marshal(b, m, deterministic) -} -func (dst *Entity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Entity.Merge(dst, src) -} -func (m *Entity) XXX_Size() int { - return xxx_messageInfo_Entity.Size(m) -} -func (m *Entity) XXX_DiscardUnknown() { - xxx_messageInfo_Entity.DiscardUnknown(m) -} - -var xxx_messageInfo_Entity proto.InternalMessageInfo - -func (m *Entity) GetAliases() []*Alias { - if m != nil { - return m.Aliases - } - return nil -} - -func (m *Entity) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Entity) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Entity) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Entity) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Entity) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Entity) GetMergedEntityIDs() []string { - if m != nil { - return m.MergedEntityIDs - } - return nil -} - -func (m *Entity) GetPolicies() []string { - if m != nil { - return m.Policies - } - return nil -} - -func (m *Entity) GetBucketKeyHash() string { - if m != nil { - return m.BucketKeyHash - } - return "" -} - -func (m *Entity) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -// Alias represents the alias that gets stored inside of the -// entity object in storage and also represents in an in-memory index of an -// alias object. -type Alias struct { - // ID is the unique identifier that represents this alias - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - // CanonicalID is the entity identifier to which this alias belongs to - CanonicalID string `sentinel:"" protobuf:"bytes,2,opt,name=canonical_id,json=canonicalId,proto3" json:"canonical_id,omitempty"` - // MountType is the backend mount's type to which this alias belongs to. - // This enables categorically querying aliases of specific backend types. - MountType string `sentinel:"" protobuf:"bytes,3,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - // MountAccessor is the backend mount's accessor to which this alias - // belongs to. - MountAccessor string `sentinel:"" protobuf:"bytes,4,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - // MountPath is the backend mount's path to which the Maccessor belongs to. This - // field is not used for any operational purposes. This is only returned when - // alias is read, only as a nicety. - MountPath string `sentinel:"" protobuf:"bytes,5,opt,name=mount_path,json=mountPath,proto3" json:"mount_path,omitempty"` - // Metadata is the explicit metadata that clients set against an entity - // which enables virtual grouping of aliases. Aliases will be indexed - // against their metadata. - Metadata map[string]string `sentinel:"" protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // Name is the identifier of this alias in its authentication source. - // This does not uniquely identify an alias in Vault. This in conjunction - // with MountAccessor form to be the factors that represent an alias in a - // unique way. Aliases will be indexed based on this combined uniqueness - // factor. - Name string `sentinel:"" protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` - // CreationTime is the time at which this alias was first created - CreationTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,8,opt,name=creation_time,json=creationTime,proto3" json:"creation_time,omitempty"` - // LastUpdateTime is the most recent time at which the properties of this - // alias got modified. This is helpful in filtering out aliases based - // on its age and to take action on them, if desired. - LastUpdateTime *timestamp.Timestamp `sentinel:"" protobuf:"bytes,9,opt,name=last_update_time,json=lastUpdateTime,proto3" json:"last_update_time,omitempty"` - // MergedFromCanonicalIDs is the FIFO history of merging activity - MergedFromCanonicalIDs []string `sentinel:"" protobuf:"bytes,10,rep,name=merged_from_canonical_ids,json=mergedFromCanonicalIds,proto3" json:"merged_from_canonical_ids,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Alias) Reset() { *m = Alias{} } -func (m *Alias) String() string { return proto.CompactTextString(m) } -func (*Alias) ProtoMessage() {} -func (*Alias) Descriptor() ([]byte, []int) { - return fileDescriptor_types_0360db4a8e77dd9b, []int{2} -} -func (m *Alias) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Alias.Unmarshal(m, b) -} -func (m *Alias) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Alias.Marshal(b, m, deterministic) -} -func (dst *Alias) XXX_Merge(src proto.Message) { - xxx_messageInfo_Alias.Merge(dst, src) -} -func (m *Alias) XXX_Size() int { - return xxx_messageInfo_Alias.Size(m) -} -func (m *Alias) XXX_DiscardUnknown() { - xxx_messageInfo_Alias.DiscardUnknown(m) -} - -var xxx_messageInfo_Alias proto.InternalMessageInfo - -func (m *Alias) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Alias) GetCanonicalID() string { - if m != nil { - return m.CanonicalID - } - return "" -} - -func (m *Alias) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *Alias) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *Alias) GetMountPath() string { - if m != nil { - return m.MountPath - } - return "" -} - -func (m *Alias) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func (m *Alias) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Alias) GetCreationTime() *timestamp.Timestamp { - if m != nil { - return m.CreationTime - } - return nil -} - -func (m *Alias) GetLastUpdateTime() *timestamp.Timestamp { - if m != nil { - return m.LastUpdateTime - } - return nil -} - -func (m *Alias) GetMergedFromCanonicalIDs() []string { - if m != nil { - return m.MergedFromCanonicalIDs - } - return nil -} - -func init() { - proto.RegisterType((*Group)(nil), "identity.Group") - proto.RegisterMapType((map[string]string)(nil), "identity.Group.MetadataEntry") - proto.RegisterType((*Entity)(nil), "identity.Entity") - proto.RegisterMapType((map[string]string)(nil), "identity.Entity.MetadataEntry") - proto.RegisterType((*Alias)(nil), "identity.Alias") - proto.RegisterMapType((map[string]string)(nil), "identity.Alias.MetadataEntry") -} - -func init() { proto.RegisterFile("helper/identity/types.proto", fileDescriptor_types_0360db4a8e77dd9b) } - -var fileDescriptor_types_0360db4a8e77dd9b = []byte{ - // 656 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x95, 0x5d, 0x6f, 0xd3, 0x3c, - 0x14, 0xc7, 0xd5, 0xa6, 0x2f, 0xe9, 0x69, 0xd7, 0xed, 0xb1, 0x1e, 0xa1, 0x50, 0x34, 0xe8, 0x26, - 0x0d, 0x95, 0x09, 0x25, 0xd2, 0xb8, 0x61, 0xe3, 0x02, 0x0d, 0x18, 0x30, 0x21, 0x24, 0x14, 0x8d, - 0x1b, 0x6e, 0x22, 0x37, 0xf1, 0x1a, 0x6b, 0x49, 0x1c, 0xc5, 0xce, 0x44, 0xbe, 0x0e, 0x5f, 0x8d, - 0x6b, 0xbe, 0x03, 0xf2, 0x71, 0xd3, 0x96, 0x75, 0xbc, 0x4c, 0xdb, 0x9d, 0xfd, 0x3f, 0xc7, 0xc7, - 0xf6, 0xf9, 0xff, 0xe2, 0xc0, 0x83, 0x98, 0x25, 0x39, 0x2b, 0x3c, 0x1e, 0xb1, 0x4c, 0x71, 0x55, - 0x79, 0xaa, 0xca, 0x99, 0x74, 0xf3, 0x42, 0x28, 0x41, 0xec, 0x5a, 0x1d, 0x3d, 0x9a, 0x09, 0x31, - 0x4b, 0x98, 0x87, 0xfa, 0xb4, 0x3c, 0xf7, 0x14, 0x4f, 0x99, 0x54, 0x34, 0xcd, 0x4d, 0xea, 0xee, - 0xb7, 0x16, 0xb4, 0xdf, 0x15, 0xa2, 0xcc, 0xc9, 0x10, 0x9a, 0x3c, 0x72, 0x1a, 0xe3, 0xc6, 0xa4, - 0xe7, 0x37, 0x79, 0x44, 0x08, 0xb4, 0x32, 0x9a, 0x32, 0xa7, 0x89, 0x0a, 0x8e, 0xc9, 0x08, 0xec, - 0x5c, 0x24, 0x3c, 0xe4, 0x4c, 0x3a, 0xd6, 0xd8, 0x9a, 0xf4, 0xfc, 0xc5, 0x9c, 0x4c, 0x60, 0x2b, - 0xa7, 0x05, 0xcb, 0x54, 0x30, 0xd3, 0xf5, 0x02, 0x1e, 0x49, 0xa7, 0x85, 0x39, 0x43, 0xa3, 0xe3, - 0x36, 0xa7, 0x91, 0x24, 0xfb, 0xf0, 0x5f, 0xca, 0xd2, 0x29, 0x2b, 0x02, 0x73, 0x4a, 0x4c, 0x6d, - 0x63, 0xea, 0xa6, 0x09, 0x9c, 0xa0, 0xae, 0x73, 0x0f, 0xc1, 0x4e, 0x99, 0xa2, 0x11, 0x55, 0xd4, - 0xe9, 0x8c, 0xad, 0x49, 0xff, 0x60, 0xdb, 0xad, 0x6f, 0xe7, 0x62, 0x45, 0xf7, 0xe3, 0x3c, 0x7e, - 0x92, 0xa9, 0xa2, 0xf2, 0x17, 0xe9, 0xe4, 0x25, 0x6c, 0x84, 0x05, 0xa3, 0x8a, 0x8b, 0x2c, 0xd0, - 0xd7, 0x76, 0xba, 0xe3, 0xc6, 0xa4, 0x7f, 0x30, 0x72, 0x4d, 0x4f, 0xdc, 0xba, 0x27, 0xee, 0x59, - 0xdd, 0x13, 0x7f, 0x50, 0x2f, 0xd0, 0x12, 0x79, 0x03, 0x5b, 0x09, 0x95, 0x2a, 0x28, 0xf3, 0x88, - 0x2a, 0x66, 0x6a, 0xd8, 0x7f, 0xad, 0x31, 0xd4, 0x6b, 0x3e, 0xe3, 0x12, 0xac, 0xb2, 0x03, 0x83, - 0x54, 0x44, 0xfc, 0xbc, 0x0a, 0x78, 0x16, 0xb1, 0xaf, 0x4e, 0x6f, 0xdc, 0x98, 0xb4, 0xfc, 0xbe, - 0xd1, 0x4e, 0xb5, 0x44, 0x1e, 0xc3, 0xe6, 0xb4, 0x0c, 0x2f, 0x98, 0x0a, 0x2e, 0x58, 0x15, 0xc4, - 0x54, 0xc6, 0x0e, 0x60, 0xd7, 0x37, 0x8c, 0xfc, 0x81, 0x55, 0xef, 0xa9, 0x8c, 0xc9, 0x1e, 0xb4, - 0x69, 0xc2, 0xa9, 0x74, 0xfa, 0x78, 0x8a, 0xcd, 0x65, 0x27, 0x8e, 0xb5, 0xec, 0x9b, 0xa8, 0x76, - 0x4e, 0xd3, 0xe0, 0x0c, 0x8c, 0x73, 0x7a, 0x3c, 0x7a, 0x01, 0x1b, 0xbf, 0xf4, 0x89, 0x6c, 0x81, - 0x75, 0xc1, 0xaa, 0xb9, 0xdf, 0x7a, 0x48, 0xfe, 0x87, 0xf6, 0x25, 0x4d, 0xca, 0xda, 0x71, 0x33, - 0x39, 0x6a, 0x3e, 0x6f, 0xec, 0x7e, 0xb7, 0xa0, 0x63, 0x2c, 0x21, 0x4f, 0xa0, 0x8b, 0x9b, 0x30, - 0xe9, 0x34, 0xd0, 0x8e, 0xb5, 0x43, 0xd4, 0xf1, 0x39, 0x50, 0xcd, 0x35, 0xa0, 0xac, 0x15, 0xa0, - 0x8e, 0x56, 0xec, 0x6d, 0x61, 0xbd, 0x87, 0xcb, 0x7a, 0x66, 0xcb, 0x7f, 0xf7, 0xb7, 0x7d, 0x07, - 0xfe, 0x76, 0x6e, 0xec, 0x2f, 0xd2, 0x5c, 0xcc, 0x58, 0xb4, 0x4a, 0x73, 0xb7, 0xa6, 0x59, 0x07, - 0x96, 0x34, 0xaf, 0x7e, 0x3f, 0xf6, 0x95, 0xef, 0xe7, 0x1a, 0x08, 0x7a, 0xd7, 0x41, 0x30, 0x02, - 0x3b, 0xe2, 0x92, 0x4e, 0x13, 0x16, 0x21, 0x07, 0xb6, 0xbf, 0x98, 0xdf, 0xce, 0xe5, 0x1f, 0x16, - 0xb4, 0xd1, 0xc2, 0xb5, 0xa7, 0x60, 0x07, 0x06, 0x21, 0xcd, 0x44, 0xc6, 0x43, 0x9a, 0x04, 0x0b, - 0x4f, 0xfb, 0x0b, 0xed, 0x34, 0x22, 0xdb, 0x00, 0xa9, 0x28, 0x33, 0x15, 0x20, 0x79, 0xc6, 0xe2, - 0x1e, 0x2a, 0x67, 0x55, 0xce, 0xc8, 0x1e, 0x0c, 0x4d, 0x98, 0x86, 0x21, 0x93, 0x52, 0x14, 0x4e, - 0xcb, 0xdc, 0x0d, 0xd5, 0xe3, 0xb9, 0xb8, 0xac, 0x92, 0x53, 0x15, 0xa3, 0x9f, 0x75, 0x95, 0x4f, - 0x54, 0xc5, 0x7f, 0x7e, 0x0c, 0xf0, 0xe8, 0xbf, 0x85, 0xa5, 0x86, 0xaf, 0xbb, 0x02, 0xdf, 0x1a, - 0x40, 0xf6, 0x1d, 0x00, 0xd4, 0xbb, 0x31, 0x40, 0x87, 0x70, 0x7f, 0x0e, 0xd0, 0x79, 0x21, 0xd2, - 0x60, 0xb5, 0xd3, 0xd2, 0x01, 0xa4, 0xe4, 0x9e, 0x49, 0x78, 0x5b, 0x88, 0xf4, 0xf5, 0xb2, 0xe9, - 0xf2, 0x56, 0x7e, 0xbf, 0x7a, 0xfa, 0x65, 0x7f, 0xc6, 0x55, 0x5c, 0x4e, 0xdd, 0x50, 0xa4, 0x9e, - 0x06, 0x8e, 0x87, 0xa2, 0xc8, 0xbd, 0x4b, 0x5a, 0x26, 0xca, 0xbb, 0xf2, 0x7f, 0x99, 0x76, 0xf0, - 0x26, 0xcf, 0x7e, 0x06, 0x00, 0x00, 0xff, 0xff, 0xf6, 0x89, 0x41, 0x55, 0x79, 0x06, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/identity/types.proto b/vendor/github.com/hashicorp/vault/helper/identity/types.proto deleted file mode 100644 index 6937b7ea3..000000000 --- a/vendor/github.com/hashicorp/vault/helper/identity/types.proto +++ /dev/null @@ -1,178 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/identity"; - -package identity; - -import "google/protobuf/timestamp.proto"; - -// Group represents an identity group. -message Group { - // ID is the unique identifier for this group - string id = 1; - - // Name is the unique name for this group - string name = 2; - - // Policies are the vault policies to be granted to members of this group - repeated string policies = 3; - - // ParentGroupIDs are the identifiers of those groups to which this group is a - // member of. These will serve as references to the parent group in the - // hierarchy. - repeated string parent_group_ids = 4; - - // MemberEntityIDs are the identifiers of entities which are members of this - // group - repeated string member_entity_ids = 5; - - // Metadata represents the custom data tied with this group - map metadata = 6; - - // CreationTime is the time at which this group was created - google.protobuf.Timestamp creation_time = 7; - - // LastUpdateTime is the time at which this group was last modified - google.protobuf.Timestamp last_update_time= 8; - - // ModifyIndex tracks the number of updates to the group. It is useful to detect - // updates to the groups. - uint64 modify_index = 9; - - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // group is stored in the underlying storage. This is useful to find all - // the groups belonging to a particular bucket during invalidation of the - // storage key. - string bucket_key_hash = 10; - - // Alias is used to mark this group as an internal mapping of a group that - // is external to the identity store. Alias can only be set if the 'type' - // is set to 'external'. - Alias alias = 11; - - // Type indicates if this group is an internal group or an external group. - // Memberships of the internal groups can be managed over the API whereas - // the memberships on the external group --for which a corresponding alias - // will be set-- will be managed automatically. - string type = 12; - - // **Enterprise only** - // NamespaceID is the identifier of the namespace to which this group - // belongs to. Do not return this value over the API when reading the - // group. - //string namespace_id = 13; -} - - -// Entity represents an entity that gets persisted and indexed. -// Entity is fundamentally composed of zero or many aliases. -message Entity { - // Aliases are the identities that this entity is made of. This can be - // empty as well to favor being able to create the entity first and then - // incrementally adding aliases. - repeated Alias aliases = 1; - - // ID is the unique identifier of the entity which always be a UUID. This - // should never be allowed to be updated. - string id = 2; - - // Name is a unique identifier of the entity which is intended to be - // human-friendly. The default name might not be human friendly since it - // gets suffixed by a UUID, but it can optionally be updated, unlike the ID - // field. - string name = 3; - - // Metadata represents the explicit metadata which is set by the - // clients. This is useful to tie any information pertaining to the - // aliases. This is a non-unique field of entity, meaning multiple - // entities can have the same metadata set. Entities will be indexed based - // on this explicit metadata. This enables virtual groupings of entities - // based on its metadata. - map metadata = 4; - - // CreationTime is the time at which this entity is first created. - google.protobuf.Timestamp creation_time = 5; - - // LastUpdateTime is the most recent time at which the properties of this - // entity got modified. This is helpful in filtering out entities based on - // its age and to take action on them, if desired. - google.protobuf.Timestamp last_update_time= 6; - - // MergedEntityIDs are the entities which got merged to this one. Entities - // will be indexed based on all the entities that got merged into it. This - // helps to apply the actions on this entity on the tokens that are merged - // to the merged entities. Merged entities will be deleted entirely and - // this is the only trackable trail of its earlier presence. - repeated string merged_entity_ids = 7; - - // Policies the entity is entitled to - repeated string policies = 8; - - // BucketKeyHash is the MD5 hash of the storage bucket key into which this - // entity is stored in the underlying storage. This is useful to find all - // the entities belonging to a particular bucket during invalidation of the - // storage key. - string bucket_key_hash = 9; - - // **Enterprise only** - // MFASecrets holds the MFA secrets indexed by the identifier of the MFA - // method configuration. - //map mfa_secrets = 10; - - // Disabled indicates whether tokens associated with the account should not - // be able to be used - bool disabled = 11; - - // **Enterprise only** - // NamespaceID is the identifier of the namespace to which this entity - // belongs to. Do not return this value over the API when reading the - // entity. - //string namespace_id = 12; -} - -// Alias represents the alias that gets stored inside of the -// entity object in storage and also represents in an in-memory index of an -// alias object. -message Alias { - // ID is the unique identifier that represents this alias - string id = 1; - - // CanonicalID is the entity identifier to which this alias belongs to - string canonical_id = 2; - - // MountType is the backend mount's type to which this alias belongs to. - // This enables categorically querying aliases of specific backend types. - string mount_type = 3; - - // MountAccessor is the backend mount's accessor to which this alias - // belongs to. - string mount_accessor = 4; - - // MountPath is the backend mount's path to which the Maccessor belongs to. This - // field is not used for any operational purposes. This is only returned when - // alias is read, only as a nicety. - string mount_path = 5; - - // Metadata is the explicit metadata that clients set against an entity - // which enables virtual grouping of aliases. Aliases will be indexed - // against their metadata. - map metadata = 6; - - // Name is the identifier of this alias in its authentication source. - // This does not uniquely identify an alias in Vault. This in conjunction - // with MountAccessor form to be the factors that represent an alias in a - // unique way. Aliases will be indexed based on this combined uniqueness - // factor. - string name = 7; - - // CreationTime is the time at which this alias was first created - google.protobuf.Timestamp creation_time = 8; - - // LastUpdateTime is the most recent time at which the properties of this - // alias got modified. This is helpful in filtering out aliases based - // on its age and to take action on them, if desired. - google.protobuf.Timestamp last_update_time = 9; - - // MergedFromCanonicalIDs is the FIFO history of merging activity - repeated string merged_from_canonical_ids = 10; -} diff --git a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go b/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go index a96745be8..d03ddef5f 100644 --- a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go +++ b/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go @@ -7,6 +7,7 @@ import ( "fmt" "io" + "github.com/hashicorp/errwrap" "github.com/hashicorp/vault/helper/compressutil" ) @@ -64,7 +65,7 @@ func DecodeJSON(data []byte, out interface{}) error { // Decompress the data if it was compressed in the first place decompressedBytes, uncompressed, err := compressutil.Decompress(data) if err != nil { - return fmt.Errorf("failed to decompress JSON: err: %v", err) + return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) } if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { return fmt.Errorf("decompressed data being decoded is invalid") @@ -91,7 +92,7 @@ func DecodeJSONFromReader(r io.Reader, out interface{}) error { dec := json.NewDecoder(r) - // While decoding JSON values, intepret the integer values as `json.Number`s instead of `float64`. + // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. dec.UseNumber() // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' diff --git a/vendor/github.com/hashicorp/vault/helper/kv-builder/builder.go b/vendor/github.com/hashicorp/vault/helper/kv-builder/builder.go deleted file mode 100644 index b0292b92e..000000000 --- a/vendor/github.com/hashicorp/vault/helper/kv-builder/builder.go +++ /dev/null @@ -1,132 +0,0 @@ -package kvbuilder - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/mitchellh/mapstructure" -) - -// Builder is a struct to build a key/value mapping based on a list -// of "k=v" pairs, where the value might come from stdin, a file, etc. -type Builder struct { - Stdin io.Reader - - result map[string]interface{} - stdin bool -} - -// Map returns the built map. -func (b *Builder) Map() map[string]interface{} { - return b.result -} - -// Add adds to the mapping with the given args. -func (b *Builder) Add(args ...string) error { - for _, a := range args { - if err := b.add(a); err != nil { - return errwrap.Wrapf(fmt.Sprintf("invalid key/value pair %q: {{err}}", a), err) - } - } - - return nil -} - -func (b *Builder) add(raw string) error { - // Regardless of validity, make sure we make our result - if b.result == nil { - b.result = make(map[string]interface{}) - } - - // Empty strings are fine, just ignored - if raw == "" { - return nil - } - - // Split into key/value - parts := strings.SplitN(raw, "=", 2) - - // If the arg is exactly "-", then we need to read from stdin - // and merge the results into the resulting structure. - if len(parts) == 1 { - if raw == "-" { - if b.Stdin == nil { - return fmt.Errorf("stdin is not supported") - } - if b.stdin { - return fmt.Errorf("stdin already consumed") - } - - b.stdin = true - return b.addReader(b.Stdin) - } - - // If the arg begins with "@" then we need to read a file directly - if raw[0] == '@' { - f, err := os.Open(raw[1:]) - if err != nil { - return err - } - defer f.Close() - - return b.addReader(f) - } - } - - if len(parts) != 2 { - return fmt.Errorf("format must be key=value") - } - key, value := parts[0], parts[1] - - if len(value) > 0 { - if value[0] == '@' { - contents, err := ioutil.ReadFile(value[1:]) - if err != nil { - return errwrap.Wrapf("error reading file: {{err}}", err) - } - - value = string(contents) - } else if value[0] == '\\' && value[1] == '@' { - value = value[1:] - } else if value == "-" { - if b.Stdin == nil { - return fmt.Errorf("stdin is not supported") - } - if b.stdin { - return fmt.Errorf("stdin already consumed") - } - b.stdin = true - - var buf bytes.Buffer - if _, err := io.Copy(&buf, b.Stdin); err != nil { - return err - } - - value = buf.String() - } - } - - // Repeated keys will be converted into a slice - if existingValue, ok := b.result[key]; ok { - var sliceValue []interface{} - if err := mapstructure.WeakDecode(existingValue, &sliceValue); err != nil { - return err - } - sliceValue = append(sliceValue, value) - b.result[key] = sliceValue - return nil - } - - b.result[key] = value - return nil -} - -func (b *Builder) addReader(r io.Reader) error { - return jsonutil.DecodeJSONFromReader(r, &b.result) -} diff --git a/vendor/github.com/hashicorp/vault/helper/ldaputil/client.go b/vendor/github.com/hashicorp/vault/helper/ldaputil/client.go deleted file mode 100644 index 86804c146..000000000 --- a/vendor/github.com/hashicorp/vault/helper/ldaputil/client.go +++ /dev/null @@ -1,470 +0,0 @@ -package ldaputil - -import ( - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/binary" - "fmt" - "math" - "net" - "net/url" - "strings" - "text/template" - - "github.com/go-ldap/ldap" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/tlsutil" -) - -type Client struct { - Logger hclog.Logger - LDAP LDAP -} - -func (c *Client) DialLDAP(cfg *ConfigEntry) (Connection, error) { - var retErr *multierror.Error - var conn Connection - urls := strings.Split(cfg.Url, ",") - for _, uut := range urls { - u, err := url.Parse(uut) - if err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("error parsing url %q: {{err}}", uut), err)) - continue - } - host, port, err := net.SplitHostPort(u.Host) - if err != nil { - host = u.Host - } - - var tlsConfig *tls.Config - switch u.Scheme { - case "ldap": - if port == "" { - port = "389" - } - conn, err = c.LDAP.Dial("tcp", net.JoinHostPort(host, port)) - if err != nil { - break - } - if conn == nil { - err = fmt.Errorf("empty connection after dialing") - break - } - if cfg.StartTLS { - tlsConfig, err = getTLSConfig(cfg, host) - if err != nil { - break - } - err = conn.StartTLS(tlsConfig) - } - case "ldaps": - if port == "" { - port = "636" - } - tlsConfig, err = getTLSConfig(cfg, host) - if err != nil { - break - } - conn, err = c.LDAP.DialTLS("tcp", net.JoinHostPort(host, port), tlsConfig) - default: - retErr = multierror.Append(retErr, fmt.Errorf("invalid LDAP scheme in url %q", net.JoinHostPort(host, port))) - continue - } - if err == nil { - if retErr != nil { - if c.Logger.IsDebug() { - c.Logger.Debug("errors connecting to some hosts: %s", retErr.Error()) - } - } - retErr = nil - break - } - retErr = multierror.Append(retErr, errwrap.Wrapf(fmt.Sprintf("error connecting to host %q: {{err}}", uut), err)) - } - - return conn, retErr.ErrorOrNil() -} - -/* - * Discover and return the bind string for the user attempting to authenticate. - * This is handled in one of several ways: - * - * 1. If DiscoverDN is set, the user object will be searched for using userdn (base search path) - * and userattr (the attribute that maps to the provided username). - * The bind will either be anonymous or use binddn and bindpassword if they were provided. - * 2. If upndomain is set, the user dn is constructed as 'username@upndomain'. See https://msdn.microsoft.com/en-us/library/cc223499.aspx - * - */ -func (c *Client) GetUserBindDN(cfg *ConfigEntry, conn Connection, username string) (string, error) { - bindDN := "" - // Note: The logic below drives the logic in ConfigEntry.Validate(). - // If updated, please update there as well. - if cfg.DiscoverDN || (cfg.BindDN != "" && cfg.BindPassword != "") { - var err error - if cfg.BindPassword != "" { - err = conn.Bind(cfg.BindDN, cfg.BindPassword) - } else { - err = conn.UnauthenticatedBind(cfg.BindDN) - } - if err != nil { - return bindDN, errwrap.Wrapf("LDAP bind (service) failed: {{err}}", err) - } - - filter := fmt.Sprintf("(%s=%s)", cfg.UserAttr, ldap.EscapeFilter(username)) - if c.Logger.IsDebug() { - c.Logger.Debug("discovering user", "userdn", cfg.UserDN, "filter", filter) - } - result, err := conn.Search(&ldap.SearchRequest{ - BaseDN: cfg.UserDN, - Scope: ldap.ScopeWholeSubtree, - Filter: filter, - SizeLimit: math.MaxInt32, - }) - if err != nil { - return bindDN, errwrap.Wrapf("LDAP search for binddn failed: {{err}}", err) - } - if len(result.Entries) != 1 { - return bindDN, fmt.Errorf("LDAP search for binddn 0 or not unique") - } - bindDN = result.Entries[0].DN - } else { - if cfg.UPNDomain != "" { - bindDN = fmt.Sprintf("%s@%s", EscapeLDAPValue(username), cfg.UPNDomain) - } else { - bindDN = fmt.Sprintf("%s=%s,%s", cfg.UserAttr, EscapeLDAPValue(username), cfg.UserDN) - } - } - - return bindDN, nil -} - -/* - * Returns the DN of the object representing the authenticated user. - */ -func (c *Client) GetUserDN(cfg *ConfigEntry, conn Connection, bindDN string) (string, error) { - userDN := "" - if cfg.UPNDomain != "" { - // Find the distinguished name for the user if userPrincipalName used for login - filter := fmt.Sprintf("(userPrincipalName=%s)", ldap.EscapeFilter(bindDN)) - if c.Logger.IsDebug() { - c.Logger.Debug("searching upn", "userdn", cfg.UserDN, "filter", filter) - } - result, err := conn.Search(&ldap.SearchRequest{ - BaseDN: cfg.UserDN, - Scope: ldap.ScopeWholeSubtree, - Filter: filter, - SizeLimit: math.MaxInt32, - }) - if err != nil { - return userDN, errwrap.Wrapf("LDAP search failed for detecting user: {{err}}", err) - } - for _, e := range result.Entries { - userDN = e.DN - } - } else { - userDN = bindDN - } - - return userDN, nil -} - -func (c *Client) performLdapFilterGroupsSearch(cfg *ConfigEntry, conn Connection, userDN string, username string) ([]*ldap.Entry, error) { - if cfg.GroupFilter == "" { - c.Logger.Warn("groupfilter is empty, will not query server") - return make([]*ldap.Entry, 0), nil - } - - if cfg.GroupDN == "" { - c.Logger.Warn("groupdn is empty, will not query server") - return make([]*ldap.Entry, 0), nil - } - - // If groupfilter was defined, resolve it as a Go template and use the query for - // returning the user's groups - if c.Logger.IsDebug() { - c.Logger.Debug("compiling group filter", "group_filter", cfg.GroupFilter) - } - - // Parse the configuration as a template. - // Example template "(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={{.UserDN}}))" - t, err := template.New("queryTemplate").Parse(cfg.GroupFilter) - if err != nil { - return nil, errwrap.Wrapf("LDAP search failed due to template compilation error: {{err}}", err) - } - - // Build context to pass to template - we will be exposing UserDn and Username. - context := struct { - UserDN string - Username string - }{ - ldap.EscapeFilter(userDN), - ldap.EscapeFilter(username), - } - - var renderedQuery bytes.Buffer - t.Execute(&renderedQuery, context) - - if c.Logger.IsDebug() { - c.Logger.Debug("searching", "groupdn", cfg.GroupDN, "rendered_query", renderedQuery.String()) - } - - result, err := conn.Search(&ldap.SearchRequest{ - BaseDN: cfg.GroupDN, - Scope: ldap.ScopeWholeSubtree, - Filter: renderedQuery.String(), - Attributes: []string{ - cfg.GroupAttr, - }, - SizeLimit: math.MaxInt32, - }) - if err != nil { - return nil, errwrap.Wrapf("LDAP search failed: {{err}}", err) - } - - return result.Entries, nil -} - -func sidBytesToString(b []byte) (string, error) { - reader := bytes.NewReader(b) - - var revision, subAuthorityCount uint8 - var identifierAuthorityParts [3]uint16 - - if err := binary.Read(reader, binary.LittleEndian, &revision); err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("SID %#v convert failed reading Revision: {{err}}", b), err) - } - - if err := binary.Read(reader, binary.LittleEndian, &subAuthorityCount); err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("SID %#v convert failed reading SubAuthorityCount: {{err}}", b), err) - } - - if err := binary.Read(reader, binary.BigEndian, &identifierAuthorityParts); err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("SID %#v convert failed reading IdentifierAuthority: {{err}}", b), err) - } - identifierAuthority := (uint64(identifierAuthorityParts[0]) << 32) + (uint64(identifierAuthorityParts[1]) << 16) + uint64(identifierAuthorityParts[2]) - - subAuthority := make([]uint32, subAuthorityCount) - if err := binary.Read(reader, binary.LittleEndian, &subAuthority); err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("SID %#v convert failed reading SubAuthority: {{err}}", b), err) - } - - result := fmt.Sprintf("S-%d-%d", revision, identifierAuthority) - for _, subAuthorityPart := range subAuthority { - result += fmt.Sprintf("-%d", subAuthorityPart) - } - - return result, nil -} - -func (c *Client) performLdapTokenGroupsSearch(cfg *ConfigEntry, conn Connection, userDN string) ([]*ldap.Entry, error) { - result, err := conn.Search(&ldap.SearchRequest{ - BaseDN: userDN, - Scope: ldap.ScopeBaseObject, - Filter: "(objectClass=*)", - Attributes: []string{ - "tokenGroups", - }, - SizeLimit: 1, - }) - if err != nil { - return nil, errwrap.Wrapf("LDAP search failed: {{err}}", err) - } - if len(result.Entries) == 0 { - c.Logger.Warn("unable to read object for group attributes", "userdn", userDN, "groupattr", cfg.GroupAttr) - return make([]*ldap.Entry, 0), nil - } - - userEntry := result.Entries[0] - groupAttrValues := userEntry.GetRawAttributeValues("tokenGroups") - - groupEntries := make([]*ldap.Entry, 0, len(groupAttrValues)) - for _, sidBytes := range groupAttrValues { - sidString, err := sidBytesToString(sidBytes) - if err != nil { - c.Logger.Warn("unable to read sid", "err", err) - continue - } - - groupResult, err := conn.Search(&ldap.SearchRequest{ - BaseDN: fmt.Sprintf("", sidString), - Scope: ldap.ScopeBaseObject, - Filter: "(objectClass=*)", - Attributes: []string{ - "1.1", // RFC no attributes - }, - SizeLimit: 1, - }) - if err != nil { - c.Logger.Warn("unable to read the group sid", "sid", sidString) - continue - } - if len(groupResult.Entries) == 0 { - c.Logger.Warn("unable to find the group", "sid", sidString) - continue - } - - groupEntries = append(groupEntries, groupResult.Entries[0]) - } - - return groupEntries, nil -} - -/* - * getLdapGroups queries LDAP and returns a slice describing the set of groups the authenticated user is a member of. - * - * If cfg.UseTokenGroups is true then the search is performed directly on the userDN. - * The values of those attributes are converted to string SIDs, and then looked up to get ldap.Entry objects. - * Otherwise, the search query is constructed according to cfg.GroupFilter, and run in context of cfg.GroupDN. - * Groups will be resolved from the query results by following the attribute defined in cfg.GroupAttr. - * - * cfg.GroupFilter is a go template and is compiled with the following context: [UserDN, Username] - * UserDN - The DN of the authenticated user - * Username - The Username of the authenticated user - * - * Example: - * cfg.GroupFilter = "(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={{.UserDN}}))" - * cfg.GroupDN = "OU=Groups,DC=myorg,DC=com" - * cfg.GroupAttr = "cn" - * - * NOTE - If cfg.GroupFilter is empty, no query is performed and an empty result slice is returned. - * - */ -func (c *Client) GetLdapGroups(cfg *ConfigEntry, conn Connection, userDN string, username string) ([]string, error) { - var entries []*ldap.Entry - var err error - if cfg.UseTokenGroups { - entries, err = c.performLdapTokenGroupsSearch(cfg, conn, userDN) - } else { - entries, err = c.performLdapFilterGroupsSearch(cfg, conn, userDN, username) - } - if err != nil { - return nil, err - } - - // retrieve the groups in a string/bool map as a structure to avoid duplicates inside - ldapMap := make(map[string]bool) - - for _, e := range entries { - dn, err := ldap.ParseDN(e.DN) - if err != nil || len(dn.RDNs) == 0 { - continue - } - - // Enumerate attributes of each result, parse out CN and add as group - values := e.GetAttributeValues(cfg.GroupAttr) - if len(values) > 0 { - for _, val := range values { - groupCN := getCN(val) - ldapMap[groupCN] = true - } - } else { - // If groupattr didn't resolve, use self (enumerating group objects) - groupCN := getCN(e.DN) - ldapMap[groupCN] = true - } - } - - ldapGroups := make([]string, 0, len(ldapMap)) - for key := range ldapMap { - ldapGroups = append(ldapGroups, key) - } - - return ldapGroups, nil -} - -// EscapeLDAPValue is exported because a plugin uses it outside this package. -func EscapeLDAPValue(input string) string { - // RFC4514 forbids un-escaped: - // - leading space or hash - // - trailing space - // - special characters '"', '+', ',', ';', '<', '>', '\\' - // - null - for i := 0; i < len(input); i++ { - escaped := false - if input[i] == '\\' { - i++ - escaped = true - } - switch input[i] { - case '"', '+', ',', ';', '<', '>', '\\': - if !escaped { - input = input[0:i] + "\\" + input[i:] - i++ - } - continue - } - if escaped { - input = input[0:i] + "\\" + input[i:] - i++ - } - } - if input[0] == ' ' || input[0] == '#' { - input = "\\" + input - } - if input[len(input)-1] == ' ' { - input = input[0:len(input)-1] + "\\ " - } - return input -} - -/* - * Parses a distinguished name and returns the CN portion. - * Given a non-conforming string (such as an already-extracted CN), - * it will be returned as-is. - */ -func getCN(dn string) string { - parsedDN, err := ldap.ParseDN(dn) - if err != nil || len(parsedDN.RDNs) == 0 { - // It was already a CN, return as-is - return dn - } - - for _, rdn := range parsedDN.RDNs { - for _, rdnAttr := range rdn.Attributes { - if rdnAttr.Type == "CN" { - return rdnAttr.Value - } - } - } - - // Default, return self - return dn -} - -func getTLSConfig(cfg *ConfigEntry, host string) (*tls.Config, error) { - tlsConfig := &tls.Config{ - ServerName: host, - } - - if cfg.TLSMinVersion != "" { - tlsMinVersion, ok := tlsutil.TLSLookup[cfg.TLSMinVersion] - if !ok { - return nil, fmt.Errorf("invalid 'tls_min_version' in config") - } - tlsConfig.MinVersion = tlsMinVersion - } - - if cfg.TLSMaxVersion != "" { - tlsMaxVersion, ok := tlsutil.TLSLookup[cfg.TLSMaxVersion] - if !ok { - return nil, fmt.Errorf("invalid 'tls_max_version' in config") - } - tlsConfig.MaxVersion = tlsMaxVersion - } - - if cfg.InsecureTLS { - tlsConfig.InsecureSkipVerify = true - } - if cfg.Certificate != "" { - caPool := x509.NewCertPool() - ok := caPool.AppendCertsFromPEM([]byte(cfg.Certificate)) - if !ok { - return nil, fmt.Errorf("could not append CA certificate") - } - tlsConfig.RootCAs = caPool - } - return tlsConfig, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/ldaputil/config.go b/vendor/github.com/hashicorp/vault/helper/ldaputil/config.go deleted file mode 100644 index 9da1ffd71..000000000 --- a/vendor/github.com/hashicorp/vault/helper/ldaputil/config.go +++ /dev/null @@ -1,336 +0,0 @@ -package ldaputil - -import ( - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "strings" - "text/template" - - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/logical/framework" - - "github.com/hashicorp/errwrap" -) - -// ConfigFields returns all the config fields that can potentially be used by the LDAP client. -// Not all fields will be used by every integration. -func ConfigFields() map[string]*framework.FieldSchema { - return map[string]*framework.FieldSchema{ - "url": { - Type: framework.TypeString, - Default: "ldap://127.0.0.1", - Description: "LDAP URL to connect to (default: ldap://127.0.0.1). Multiple URLs can be specified by concatenating them with commas; they will be tried in-order.", - }, - - "userdn": { - Type: framework.TypeString, - Description: "LDAP domain to use for users (eg: ou=People,dc=example,dc=org)", - }, - - "binddn": { - Type: framework.TypeString, - Description: "LDAP DN for searching for the user DN (optional)", - }, - - "bindpass": { - Type: framework.TypeString, - Description: "LDAP password for searching for the user DN (optional)", - }, - - "groupdn": { - Type: framework.TypeString, - Description: "LDAP search base to use for group membership search (eg: ou=Groups,dc=example,dc=org)", - }, - - "groupfilter": { - Type: framework.TypeString, - Default: "(|(memberUid={{.Username}})(member={{.UserDN}})(uniqueMember={{.UserDN}}))", - Description: `Go template for querying group membership of user (optional) -The template can access the following context variables: UserDN, Username -Example: (&(objectClass=group)(member:1.2.840.113556.1.4.1941:={{.UserDN}})) -Default: (|(memberUid={{.Username}})(member={{.UserDN}})(uniqueMember={{.UserDN}}))`, - }, - - "groupattr": { - Type: framework.TypeString, - Default: "cn", - Description: `LDAP attribute to follow on objects returned by -in order to enumerate user group membership. -Examples: "cn" or "memberOf", etc. -Default: cn`, - }, - - "upndomain": { - Type: framework.TypeString, - Description: "Enables userPrincipalDomain login with [username]@UPNDomain (optional)", - }, - - "userattr": { - Type: framework.TypeString, - Default: "cn", - Description: "Attribute used for users (default: cn)", - }, - - "certificate": { - Type: framework.TypeString, - Description: "CA certificate to use when verifying LDAP server certificate, must be x509 PEM encoded (optional)", - }, - - "discoverdn": { - Type: framework.TypeBool, - Description: "Use anonymous bind to discover the bind DN of a user (optional)", - }, - - "insecure_tls": { - Type: framework.TypeBool, - Description: "Skip LDAP server SSL Certificate verification - VERY insecure (optional)", - }, - - "starttls": { - Type: framework.TypeBool, - Description: "Issue a StartTLS command after establishing unencrypted connection (optional)", - }, - - "tls_min_version": { - Type: framework.TypeString, - Default: "tls12", - Description: "Minimum TLS version to use. Accepted values are 'tls10', 'tls11' or 'tls12'. Defaults to 'tls12'", - }, - - "tls_max_version": { - Type: framework.TypeString, - Default: "tls12", - Description: "Maximum TLS version to use. Accepted values are 'tls10', 'tls11' or 'tls12'. Defaults to 'tls12'", - }, - - "deny_null_bind": { - Type: framework.TypeBool, - Default: true, - Description: "Denies an unauthenticated LDAP bind request if the user's password is empty; defaults to true", - }, - - "case_sensitive_names": { - Type: framework.TypeBool, - Description: "If true, case sensitivity will be used when comparing usernames and groups for matching policies.", - }, - - "use_token_groups": { - Type: framework.TypeBool, - Default: false, - Description: "If true, use the Active Directory tokenGroups constructed attribute of the user to find the group memberships. This will find all security groups including nested ones.", - }, - } -} - -/* - * Creates and initializes a ConfigEntry object with its default values, - * as specified by the passed schema. - */ -func NewConfigEntry(d *framework.FieldData) (*ConfigEntry, error) { - cfg := new(ConfigEntry) - - url := d.Get("url").(string) - if url != "" { - cfg.Url = strings.ToLower(url) - } - userattr := d.Get("userattr").(string) - if userattr != "" { - cfg.UserAttr = strings.ToLower(userattr) - } - userdn := d.Get("userdn").(string) - if userdn != "" { - cfg.UserDN = userdn - } - groupdn := d.Get("groupdn").(string) - if groupdn != "" { - cfg.GroupDN = groupdn - } - groupfilter := d.Get("groupfilter").(string) - if groupfilter != "" { - // Validate the template before proceeding - _, err := template.New("queryTemplate").Parse(groupfilter) - if err != nil { - return nil, errwrap.Wrapf("invalid groupfilter: {{err}}", err) - } - - cfg.GroupFilter = groupfilter - } - groupattr := d.Get("groupattr").(string) - if groupattr != "" { - cfg.GroupAttr = groupattr - } - upndomain := d.Get("upndomain").(string) - if upndomain != "" { - cfg.UPNDomain = upndomain - } - certificate := d.Get("certificate").(string) - if certificate != "" { - block, _ := pem.Decode([]byte(certificate)) - - if block == nil || block.Type != "CERTIFICATE" { - return nil, fmt.Errorf("failed to decode PEM block in the certificate") - } - _, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, errwrap.Wrapf("failed to parse certificate: {{err}}", err) - } - cfg.Certificate = certificate - } - insecureTLS := d.Get("insecure_tls").(bool) - if insecureTLS { - cfg.InsecureTLS = insecureTLS - } - cfg.TLSMinVersion = d.Get("tls_min_version").(string) - if cfg.TLSMinVersion == "" { - return nil, fmt.Errorf("failed to get 'tls_min_version' value") - } - - var ok bool - _, ok = tlsutil.TLSLookup[cfg.TLSMinVersion] - if !ok { - return nil, fmt.Errorf("invalid 'tls_min_version'") - } - - cfg.TLSMaxVersion = d.Get("tls_max_version").(string) - if cfg.TLSMaxVersion == "" { - return nil, fmt.Errorf("failed to get 'tls_max_version' value") - } - - _, ok = tlsutil.TLSLookup[cfg.TLSMaxVersion] - if !ok { - return nil, fmt.Errorf("invalid 'tls_max_version'") - } - if cfg.TLSMaxVersion < cfg.TLSMinVersion { - return nil, fmt.Errorf("'tls_max_version' must be greater than or equal to 'tls_min_version'") - } - - startTLS := d.Get("starttls").(bool) - if startTLS { - cfg.StartTLS = startTLS - } - - bindDN := d.Get("binddn").(string) - if bindDN != "" { - cfg.BindDN = bindDN - } - - bindPass := d.Get("bindpass").(string) - if bindPass != "" { - cfg.BindPassword = bindPass - } - - denyNullBind := d.Get("deny_null_bind").(bool) - if denyNullBind { - cfg.DenyNullBind = denyNullBind - } - - discoverDN := d.Get("discoverdn").(bool) - if discoverDN { - cfg.DiscoverDN = discoverDN - } - - caseSensitiveNames, ok := d.GetOk("case_sensitive_names") - if ok { - cfg.CaseSensitiveNames = new(bool) - *cfg.CaseSensitiveNames = caseSensitiveNames.(bool) - } - - useTokenGroups := d.Get("use_token_groups").(bool) - if useTokenGroups { - cfg.UseTokenGroups = useTokenGroups - } - - return cfg, nil -} - -type ConfigEntry struct { - Url string `json:"url"` - UserDN string `json:"userdn"` - GroupDN string `json:"groupdn"` - GroupFilter string `json:"groupfilter"` - GroupAttr string `json:"groupattr"` - UPNDomain string `json:"upndomain"` - UserAttr string `json:"userattr"` - Certificate string `json:"certificate"` - InsecureTLS bool `json:"insecure_tls"` - StartTLS bool `json:"starttls"` - BindDN string `json:"binddn"` - BindPassword string `json:"bindpass"` - DenyNullBind bool `json:"deny_null_bind"` - DiscoverDN bool `json:"discoverdn"` - TLSMinVersion string `json:"tls_min_version"` - TLSMaxVersion string `json:"tls_max_version"` - UseTokenGroups bool `json:"use_token_groups"` - - // This json tag deviates from snake case because there was a past issue - // where the tag was being ignored, causing it to be jsonified as "CaseSensitiveNames". - // To continue reading in users' previously stored values, - // we chose to carry that forward. - CaseSensitiveNames *bool `json:"CaseSensitiveNames,omitempty"` -} - -func (c *ConfigEntry) Map() map[string]interface{} { - m := c.PasswordlessMap() - m["bindpass"] = c.BindPassword - return m -} - -func (c *ConfigEntry) PasswordlessMap() map[string]interface{} { - m := map[string]interface{}{ - "url": c.Url, - "userdn": c.UserDN, - "groupdn": c.GroupDN, - "groupfilter": c.GroupFilter, - "groupattr": c.GroupAttr, - "upndomain": c.UPNDomain, - "userattr": c.UserAttr, - "certificate": c.Certificate, - "insecure_tls": c.InsecureTLS, - "starttls": c.StartTLS, - "binddn": c.BindDN, - "deny_null_bind": c.DenyNullBind, - "discoverdn": c.DiscoverDN, - "tls_min_version": c.TLSMinVersion, - "tls_max_version": c.TLSMaxVersion, - "use_token_groups": c.UseTokenGroups, - } - if c.CaseSensitiveNames != nil { - m["case_sensitive_names"] = *c.CaseSensitiveNames - } - return m -} - -func (c *ConfigEntry) Validate() error { - if len(c.Url) == 0 { - return errors.New("at least one url must be provided") - } - // Note: This logic is driven by the logic in GetUserBindDN. - // If updating this, please also update the logic there. - if !c.DiscoverDN && (c.BindDN == "" || c.BindPassword == "") && c.UPNDomain == "" && c.UserDN == "" { - return errors.New("cannot derive UserBindDN") - } - tlsMinVersion, ok := tlsutil.TLSLookup[c.TLSMinVersion] - if !ok { - return errors.New("invalid 'tls_min_version' in config") - } - tlsMaxVersion, ok := tlsutil.TLSLookup[c.TLSMaxVersion] - if !ok { - return errors.New("invalid 'tls_max_version' in config") - } - if tlsMaxVersion < tlsMinVersion { - return errors.New("'tls_max_version' must be greater than or equal to 'tls_min_version'") - } - if c.Certificate != "" { - block, _ := pem.Decode([]byte(c.Certificate)) - if block == nil || block.Type != "CERTIFICATE" { - return errors.New("failed to decode PEM block in the certificate") - } - _, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return fmt.Errorf("failed to parse certificate %s", err.Error()) - } - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/ldaputil/connection.go b/vendor/github.com/hashicorp/vault/helper/ldaputil/connection.go deleted file mode 100644 index 61a3d55bc..000000000 --- a/vendor/github.com/hashicorp/vault/helper/ldaputil/connection.go +++ /dev/null @@ -1,18 +0,0 @@ -package ldaputil - -import ( - "crypto/tls" - - "github.com/go-ldap/ldap" -) - -// Connection provides the functionality of an LDAP connection, -// but through an interface. -type Connection interface { - Bind(username, password string) error - Close() - Modify(modifyRequest *ldap.ModifyRequest) error - Search(searchRequest *ldap.SearchRequest) (*ldap.SearchResult, error) - StartTLS(config *tls.Config) error - UnauthenticatedBind(username string) error -} diff --git a/vendor/github.com/hashicorp/vault/helper/ldaputil/ldap.go b/vendor/github.com/hashicorp/vault/helper/ldaputil/ldap.go deleted file mode 100644 index acafe0b19..000000000 --- a/vendor/github.com/hashicorp/vault/helper/ldaputil/ldap.go +++ /dev/null @@ -1,28 +0,0 @@ -package ldaputil - -import ( - "crypto/tls" - - "github.com/go-ldap/ldap" -) - -func NewLDAP() LDAP { - return &ldapIfc{} -} - -// LDAP provides ldap functionality, but through an interface -// rather than statically. This allows faking it for tests. -type LDAP interface { - Dial(network, addr string) (Connection, error) - DialTLS(network, addr string, config *tls.Config) (Connection, error) -} - -type ldapIfc struct{} - -func (l *ldapIfc) Dial(network, addr string) (Connection, error) { - return ldap.Dial(network, addr) -} - -func (l *ldapIfc) DialTLS(network, addr string, config *tls.Config) (Connection, error) { - return ldap.DialTLS(network, addr, config) -} diff --git a/vendor/github.com/hashicorp/vault/helper/locksutil/locks.go b/vendor/github.com/hashicorp/vault/helper/locksutil/locks.go deleted file mode 100644 index e0c2fcdd8..000000000 --- a/vendor/github.com/hashicorp/vault/helper/locksutil/locks.go +++ /dev/null @@ -1,60 +0,0 @@ -package locksutil - -import ( - "crypto/md5" - "sync" -) - -const ( - LockCount = 256 -) - -type LockEntry struct { - sync.RWMutex -} - -// CreateLocks returns an array so that the locks can be iterated over in -// order. -// -// This is only threadsafe if a process is using a single lock, or iterating -// over the entire lock slice in order. Using a consistent order avoids -// deadlocks because you can never have the following: -// -// Lock A, Lock B -// Lock B, Lock A -// -// Where process 1 is now deadlocked trying to lock B, and process 2 deadlocked trying to lock A -// -func CreateLocks() []*LockEntry { - ret := make([]*LockEntry, LockCount) - for i := range ret { - ret[i] = new(LockEntry) - } - return ret -} - -func LockIndexForKey(key string) uint8 { - hf := md5.New() - hf.Write([]byte(key)) - return uint8(hf.Sum(nil)[0]) -} - -func LockForKey(locks []*LockEntry, key string) *LockEntry { - return locks[LockIndexForKey(key)] -} - -func LocksForKeys(locks []*LockEntry, keys []string) []*LockEntry { - lockIndexes := make(map[uint8]struct{}, len(keys)) - for _, k := range keys { - lockIndexes[LockIndexForKey(k)] = struct{}{} - } - - locksToReturn := make([]*LockEntry, 0, len(keys)) - for i, l := range locks { - if _, ok := lockIndexes[uint8(i)]; ok { - locksToReturn = append(locksToReturn, l) - } - } - - return locksToReturn -} diff --git a/vendor/github.com/hashicorp/vault/helper/logging/vault.go b/vendor/github.com/hashicorp/vault/helper/logging/vault.go deleted file mode 100644 index 3e7e4766d..000000000 --- a/vendor/github.com/hashicorp/vault/helper/logging/vault.go +++ /dev/null @@ -1,39 +0,0 @@ -package logging - -import ( - "io" - "os" - "strings" - - log "github.com/hashicorp/go-hclog" -) - -// NewVaultLogger creates a new logger with the specified level and a Vault -// formatter -func NewVaultLogger(level log.Level) log.Logger { - return NewVaultLoggerWithWriter(log.DefaultOutput, level) -} - -// NewVaultLoggerWithWriter creates a new logger with the specified level and -// writer and a Vault formatter -func NewVaultLoggerWithWriter(w io.Writer, level log.Level) log.Logger { - opts := &log.LoggerOptions{ - Level: level, - Output: w, - JSONFormat: useJson(), - } - return log.New(opts) -} - -func useJson() bool { - logFormat := os.Getenv("VAULT_LOG_FORMAT") - if logFormat == "" { - logFormat = os.Getenv("LOGXI_FORMAT") - } - switch strings.ToLower(logFormat) { - case "json", "vault_json", "vault-json", "vaultjson": - return true - default: - return false - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/mfa/mfa.go b/vendor/github.com/hashicorp/vault/helper/mfa/mfa.go deleted file mode 100644 index 69697f3c3..000000000 --- a/vendor/github.com/hashicorp/vault/helper/mfa/mfa.go +++ /dev/null @@ -1,88 +0,0 @@ -// Package mfa provides wrappers to add multi-factor authentication -// to any auth method. -// -// To add MFA to a backend, replace its login path with the -// paths returned by MFAPaths and add the additional root -// paths returned by MFARootPaths. The backend provides -// the username to the MFA wrapper in Auth.Metadata['username']. -// -// To add an additional MFA type, create a subpackage that -// implements [Type]Paths, [Type]RootPaths, and [Type]Handler -// functions and add them to MFAPaths, MFARootPaths, and -// handlers respectively. -package mfa - -import ( - "context" - - "github.com/hashicorp/vault/helper/mfa/duo" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// MFAPaths returns paths to wrap the original login path and configure MFA. -// When adding MFA to a backend, these paths should be included instead of -// the login path in Backend.Paths. -func MFAPaths(originalBackend *framework.Backend, loginPath *framework.Path) []*framework.Path { - var b backend - b.Backend = originalBackend - return append(duo.DuoPaths(), pathMFAConfig(&b), wrapLoginPath(&b, loginPath)) -} - -// MFARootPaths returns path strings used to configure MFA. When adding MFA -// to a backend, these paths should be included in -// Backend.PathsSpecial.Root. -func MFARootPaths() []string { - return append(duo.DuoRootPaths(), "mfa_config") -} - -// HandlerFunc is the callback called to handle MFA for a login request. -type HandlerFunc func(context.Context, *logical.Request, *framework.FieldData, *logical.Response) (*logical.Response, error) - -// handlers maps each supported MFA type to its handler. -var handlers = map[string]HandlerFunc{ - "duo": duo.DuoHandler, -} - -type backend struct { - *framework.Backend -} - -func wrapLoginPath(b *backend, loginPath *framework.Path) *framework.Path { - loginPath.Fields["passcode"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: "One time passcode (optional)", - } - loginPath.Fields["method"] = &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Multi-factor auth method to use (optional)", - } - // wrap write callback to do MFA after auth - loginHandler := loginPath.Callbacks[logical.UpdateOperation] - loginPath.Callbacks[logical.UpdateOperation] = b.wrapLoginHandler(loginHandler) - return loginPath -} - -func (b *backend) wrapLoginHandler(loginHandler framework.OperationFunc) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - // login with original login function first - resp, err := loginHandler(ctx, req, d) - if err != nil || resp.Auth == nil { - return resp, err - } - - // check if multi-factor enabled - mfa_config, err := b.MFAConfig(ctx, req) - if err != nil || mfa_config == nil { - return resp, nil - } - - // perform multi-factor authentication if type supported - handler, ok := handlers[mfa_config.Type] - if ok { - return handler(ctx, req, d, resp) - } else { - return resp, err - } - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/mfa/path_mfa_config.go b/vendor/github.com/hashicorp/vault/helper/mfa/path_mfa_config.go deleted file mode 100644 index d290baa3f..000000000 --- a/vendor/github.com/hashicorp/vault/helper/mfa/path_mfa_config.go +++ /dev/null @@ -1,87 +0,0 @@ -package mfa - -import ( - "context" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func pathMFAConfig(b *backend) *framework.Path { - return &framework.Path{ - Pattern: `mfa_config`, - Fields: map[string]*framework.FieldSchema{ - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Enables MFA with given backend (available: duo)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathMFAConfigWrite, - logical.ReadOperation: b.pathMFAConfigRead, - }, - - HelpSynopsis: pathMFAConfigHelpSyn, - HelpDescription: pathMFAConfigHelpDesc, - } -} - -func (b *backend) MFAConfig(ctx context.Context, req *logical.Request) (*MFAConfig, error) { - entry, err := req.Storage.Get(ctx, "mfa_config") - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - var result MFAConfig - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - return &result, nil -} - -func (b *backend) pathMFAConfigWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entry, err := logical.StorageEntryJSON("mfa_config", MFAConfig{ - Type: d.Get("type").(string), - }) - if err != nil { - return nil, err - } - - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *backend) pathMFAConfigRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - config, err := b.MFAConfig(ctx, req) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "type": config.Type, - }, - }, nil -} - -type MFAConfig struct { - Type string `json:"type"` -} - -const pathMFAConfigHelpSyn = ` -Configure multi factor backend. -` - -const pathMFAConfigHelpDesc = ` -This endpoint allows you to turn on multi-factor authentication with a given backend. -Currently only Duo is supported. -` diff --git a/vendor/github.com/hashicorp/vault/helper/mlock/mlock.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock.go deleted file mode 100644 index 1675633d3..000000000 --- a/vendor/github.com/hashicorp/vault/helper/mlock/mlock.go +++ /dev/null @@ -1,15 +0,0 @@ -package mlock - -// This should be set by the OS-specific packages to tell whether LockMemory -// is supported or not. -var supported bool - -// Supported returns true if LockMemory is functional on this system. -func Supported() bool { - return supported -} - -// LockMemory prevents any memory from being swapped to disk. -func LockMemory() error { - return lockMemory() -} diff --git a/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go deleted file mode 100644 index 8084963f7..000000000 --- a/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unavail.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build android darwin nacl netbsd plan9 windows - -package mlock - -func init() { - supported = false -} - -func lockMemory() error { - // XXX: No good way to do this on Windows. There is the VirtualLock - // method, but it requires a specific address and offset. - return nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go b/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go deleted file mode 100644 index af0a69d48..000000000 --- a/vendor/github.com/hashicorp/vault/helper/mlock/mlock_unix.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build dragonfly freebsd linux openbsd solaris - -package mlock - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -func init() { - supported = true -} - -func lockMemory() error { - // Mlockall prevents all current and future pages from being swapped out. - return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE) -} diff --git a/vendor/github.com/hashicorp/vault/helper/namespace/namespace.go b/vendor/github.com/hashicorp/vault/helper/namespace/namespace.go deleted file mode 100644 index 4b3b92410..000000000 --- a/vendor/github.com/hashicorp/vault/helper/namespace/namespace.go +++ /dev/null @@ -1,107 +0,0 @@ -package namespace - -import ( - "context" - "errors" - "net/http" - "strings" -) - -type contextValues struct{} - -type Namespace struct { - ID string `json:"id"` - Path string `json:"path"` -} - -const ( - RootNamespaceID = "root" -) - -var ( - contextNamespace contextValues = struct{}{} - ErrNoNamespace error = errors.New("no namespace") - RootNamespace *Namespace = &Namespace{ - ID: RootNamespaceID, - Path: "", - } -) - -var AdjustRequest = func(r *http.Request) (*http.Request, int) { - return r.WithContext(ContextWithNamespace(r.Context(), RootNamespace)), 0 -} - -func (n *Namespace) HasParent(possibleParent *Namespace) bool { - switch { - case n.Path == "": - return false - case possibleParent.Path == "": - return true - default: - return strings.HasPrefix(n.Path, possibleParent.Path) - } -} - -func (n *Namespace) TrimmedPath(path string) string { - return strings.TrimPrefix(path, n.Path) -} - -func ContextWithNamespace(ctx context.Context, ns *Namespace) context.Context { - return context.WithValue(ctx, contextNamespace, ns) -} - -func RootContext(ctx context.Context) context.Context { - if ctx == nil { - return ContextWithNamespace(context.Background(), RootNamespace) - } - return ContextWithNamespace(ctx, RootNamespace) -} - -// This function caches the ns to avoid doing a .Value lookup over and over, -// because it's called a *lot* in the request critical path. .Value is -// concurrency-safe so uses some kind of locking/atomicity, but it should never -// be read before first write, plus we don't believe this will be called from -// different goroutines, so it should be safe. -func FromContext(ctx context.Context) (*Namespace, error) { - if ctx == nil { - return nil, errors.New("context was nil") - } - - nsRaw := ctx.Value(contextNamespace) - if nsRaw == nil { - return nil, ErrNoNamespace - } - - ns := nsRaw.(*Namespace) - if ns == nil { - return nil, ErrNoNamespace - } - - return ns, nil -} - -func TestContext() context.Context { - return ContextWithNamespace(context.Background(), TestNamespace()) -} - -func TestNamespace() *Namespace { - return RootNamespace -} - -// Canonicalize trims any prefix '/' and adds a trailing '/' to the -// provided string -func Canonicalize(nsPath string) string { - if nsPath == "" { - return "" - } - - // Canonicalize the path to not have a '/' prefix - nsPath = strings.TrimPrefix(nsPath, "/") - - // Canonicalize the path to always having a '/' suffix - if !strings.HasSuffix(nsPath, "/") { - nsPath += "/" - } - - return nsPath -} diff --git a/vendor/github.com/hashicorp/vault/helper/password/password.go b/vendor/github.com/hashicorp/vault/helper/password/password.go deleted file mode 100644 index 102fbe802..000000000 --- a/vendor/github.com/hashicorp/vault/helper/password/password.go +++ /dev/null @@ -1,64 +0,0 @@ -// password is a package for reading a password securely from a terminal. -// The code in this package disables echo in the terminal so that the -// password is not echoed back in plaintext to the user. -package password - -import ( - "errors" - "io" - "os" - "os/signal" -) - -var ErrInterrupted = errors.New("interrupted") - -// Read reads the password from the given os.File. The password -// will not be echoed back to the user. Ctrl-C will automatically return -// from this function with a blank string and an ErrInterrupted. -func Read(f *os.File) (string, error) { - ch := make(chan os.Signal, 1) - signal.Notify(ch, os.Interrupt) - defer signal.Stop(ch) - - // Run the actual read in a go-routine so that we can still detect signals - var result string - var resultErr error - doneCh := make(chan struct{}) - go func() { - defer close(doneCh) - result, resultErr = read(f) - }() - - // Wait on either the read to finish or the signal to come through - select { - case <-ch: - return "", ErrInterrupted - case <-doneCh: - return result, resultErr - } -} - -func readline(f *os.File) (string, error) { - var buf [1]byte - resultBuf := make([]byte, 0, 64) - for { - n, err := f.Read(buf[:]) - if err != nil && err != io.EOF { - return "", err - } - if n == 0 || buf[0] == '\n' || buf[0] == '\r' { - break - } - - // ASCII code 3 is what is sent for a Ctrl-C while reading raw. - // If we see that, then get the interrupt. We have to do this here - // because terminals in raw mode won't catch it at the shell level. - if buf[0] == 3 { - return "", ErrInterrupted - } - - resultBuf = append(resultBuf, buf[0]) - } - - return string(resultBuf), nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/password/password_solaris.go b/vendor/github.com/hashicorp/vault/helper/password/password_solaris.go deleted file mode 100644 index 66ec86dbc..000000000 --- a/vendor/github.com/hashicorp/vault/helper/password/password_solaris.go +++ /dev/null @@ -1,55 +0,0 @@ -// +build solaris - -package password - -import ( - "fmt" - "os" - "syscall" - - "golang.org/x/sys/unix" -) - -func read(f *os.File) (string, error) { - fd := int(f.Fd()) - if !isTerminal(fd) { - return "", fmt.Errorf("file descriptor %d is not a terminal", fd) - } - - oldState, err := makeRaw(fd) - if err != nil { - return "", err - } - defer unix.IoctlSetTermios(fd, unix.TCSETS, oldState) - - return readline(f) -} - -// isTerminal returns true if there is a terminal attached to the given -// file descriptor. -// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func isTerminal(fd int) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(fd, unix.TCGETA, &termio) - return err == nil -} - -// makeRaw puts the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c -func makeRaw(fd int) (*unix.Termios, error) { - oldTermiosPtr, err := unix.IoctlGetTermios(int(fd), unix.TCGETS) - if err != nil { - return nil, err - } - oldTermios := *oldTermiosPtr - - newTermios := oldTermios - newTermios.Lflag &^= syscall.ECHO | syscall.ECHOE | syscall.ECHOK | syscall.ECHONL - if err := unix.IoctlSetTermios(fd, unix.TCSETS, &newTermios); err != nil { - return nil, err - } - - return oldTermiosPtr, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/password/password_unix.go b/vendor/github.com/hashicorp/vault/helper/password/password_unix.go deleted file mode 100644 index 6d04978c3..000000000 --- a/vendor/github.com/hashicorp/vault/helper/password/password_unix.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build linux darwin freebsd netbsd openbsd - -package password - -import ( - "fmt" - "os" - - "golang.org/x/crypto/ssh/terminal" -) - -func read(f *os.File) (string, error) { - fd := int(f.Fd()) - if !terminal.IsTerminal(fd) { - return "", fmt.Errorf("file descriptor %d is not a terminal", fd) - } - - oldState, err := terminal.MakeRaw(fd) - if err != nil { - return "", err - } - defer terminal.Restore(fd, oldState) - - return readline(f) -} diff --git a/vendor/github.com/hashicorp/vault/helper/password/password_windows.go b/vendor/github.com/hashicorp/vault/helper/password/password_windows.go deleted file mode 100644 index 7325698f8..000000000 --- a/vendor/github.com/hashicorp/vault/helper/password/password_windows.go +++ /dev/null @@ -1,48 +0,0 @@ -// +build windows - -package password - -import ( - "os" - "syscall" -) - -var ( - kernel32 = syscall.MustLoadDLL("kernel32.dll") - setConsoleModeProc = kernel32.MustFindProc("SetConsoleMode") -) - -// Magic constant from MSDN to control whether characters read are -// repeated back on the console. -// -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx -const ENABLE_ECHO_INPUT = 0x0004 - -func read(f *os.File) (string, error) { - handle := syscall.Handle(f.Fd()) - - // Grab the old console mode so we can reset it. We defer the reset - // right away because it doesn't matter (it is idempotent). - var oldMode uint32 - if err := syscall.GetConsoleMode(handle, &oldMode); err != nil { - return "", err - } - defer setConsoleMode(handle, oldMode) - - // The new mode is the old mode WITHOUT the echo input flag set. - var newMode uint32 = uint32(int(oldMode) & ^ENABLE_ECHO_INPUT) - if err := setConsoleMode(handle, newMode); err != nil { - return "", err - } - - return readline(f) -} - -func setConsoleMode(console syscall.Handle, mode uint32) error { - r, _, err := setConsoleModeProc.Call(uintptr(console), uintptr(mode)) - if r == 0 { - return err - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go b/vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go deleted file mode 100644 index e0e39445b..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pathmanager/pathmanager.go +++ /dev/null @@ -1,136 +0,0 @@ -package pathmanager - -import ( - "strings" - "sync" - - iradix "github.com/hashicorp/go-immutable-radix" -) - -// PathManager is a prefix searchable index of paths -type PathManager struct { - l sync.RWMutex - paths *iradix.Tree -} - -// New creates a new path manager -func New() *PathManager { - return &PathManager{ - paths: iradix.New(), - } -} - -// AddPaths adds path to the paths list -func (p *PathManager) AddPaths(paths []string) { - p.l.Lock() - defer p.l.Unlock() - - txn := p.paths.Txn() - for _, prefix := range paths { - if len(prefix) == 0 { - continue - } - - var exception bool - if strings.HasPrefix(prefix, "!") { - prefix = strings.TrimPrefix(prefix, "!") - exception = true - } - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - txn.Insert([]byte(strings.TrimSuffix(prefix, "*")), exception) - } - p.paths = txn.Commit() -} - -// RemovePaths removes paths from the paths list -func (p *PathManager) RemovePaths(paths []string) { - p.l.Lock() - defer p.l.Unlock() - - txn := p.paths.Txn() - for _, prefix := range paths { - if len(prefix) == 0 { - continue - } - - // Exceptions aren't stored with the leading ! so strip it - if strings.HasPrefix(prefix, "!") { - prefix = strings.TrimPrefix(prefix, "!") - } - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - txn.Delete([]byte(strings.TrimSuffix(prefix, "*"))) - } - p.paths = txn.Commit() -} - -// RemovePathPrefix removes all paths with the given prefix -func (p *PathManager) RemovePathPrefix(prefix string) { - p.l.Lock() - defer p.l.Unlock() - - // We trim any trailing *, but we don't touch whether it is a trailing - // slash or not since we want to be able to ignore prefixes that fully - // specify a file - p.paths, _ = p.paths.DeletePrefix([]byte(strings.TrimSuffix(prefix, "*"))) -} - -// Len returns the number of paths -func (p *PathManager) Len() int { - return p.paths.Len() -} - -// Paths returns the path list -func (p *PathManager) Paths() []string { - p.l.RLock() - defer p.l.RUnlock() - - paths := make([]string, 0, p.paths.Len()) - walkFn := func(k []byte, v interface{}) bool { - paths = append(paths, string(k)) - return false - } - p.paths.Root().Walk(walkFn) - return paths -} - -// HasPath returns if the prefix for the path exists regardless if it is a path -// (ending with /) or a prefix for a leaf node -func (p *PathManager) HasPath(path string) bool { - p.l.RLock() - defer p.l.RUnlock() - - if _, exceptionRaw, ok := p.paths.Root().LongestPrefix([]byte(path)); ok { - var exception bool - if exceptionRaw != nil { - exception = exceptionRaw.(bool) - } - return !exception - } - return false -} - -// HasExactPath returns if the longest match is an exact match for the -// full path -func (p *PathManager) HasExactPath(path string) bool { - p.l.RLock() - defer p.l.RUnlock() - - if val, exceptionRaw, ok := p.paths.Root().LongestPrefix([]byte(path)); ok { - var exception bool - if exceptionRaw != nil { - exception = exceptionRaw.(bool) - } - - strVal := string(val) - if strings.HasSuffix(strVal, "/") || strVal == path { - return !exception - } - } - return false -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go deleted file mode 100644 index eef4c5ed0..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go +++ /dev/null @@ -1,118 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// EncryptShares takes an ordered set of byte slices to encrypt and the -// corresponding base64-encoded public keys to encrypt them with, encrypts each -// byte slice with the corresponding public key. -// -// Note: There is no corresponding test function; this functionality is -// thoroughly tested in the init and rekey command unit tests -func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { - if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") - } - encryptedShares := make([][]byte, 0, len(pgpKeys)) - entities, err := GetEntities(pgpKeys) - if err != nil { - return nil, nil, err - } - for i, entity := range entities { - ctBuf := bytes.NewBuffer(nil) - pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) - if err != nil { - return nil, nil, errwrap.Wrapf("error setting up encryption for PGP message: {{err}}", err) - } - _, err = pt.Write(input[i]) - if err != nil { - return nil, nil, errwrap.Wrapf("error encrypting PGP message: {{err}}", err) - } - pt.Close() - encryptedShares = append(encryptedShares, ctBuf.Bytes()) - } - - fingerprints, err := GetFingerprints(nil, entities) - if err != nil { - return nil, nil, err - } - - return fingerprints, encryptedShares, nil -} - -// GetFingerprints takes in a list of openpgp Entities and returns the -// fingerprints. If entities is nil, it will instead parse both entities and -// fingerprints from the pgpKeys string slice. -func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, error) { - if entities == nil { - var err error - entities, err = GetEntities(pgpKeys) - - if err != nil { - return nil, err - } - } - ret := make([]string, 0, len(entities)) - for _, entity := range entities { - ret = append(ret, fmt.Sprintf("%x", entity.PrimaryKey.Fingerprint)) - } - return ret, nil -} - -// GetEntities takes in a string array of base64-encoded PGP keys and returns -// the openpgp Entities -func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { - ret := make([]*openpgp.Entity, 0, len(pgpKeys)) - for _, keystring := range pgpKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return nil, errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return nil, errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - ret = append(ret, entity) - } - return ret, nil -} - -// DecryptBytes takes in base64-encoded encrypted bytes and the base64-encoded -// private key and decrypts it. A bytes.Buffer is returned to allow the caller -// to do useful thing with it (get it as a []byte, get it as a string, use it -// as an io.Reader, etc), and also because this function doesn't know if what -// comes out is binary data or a string, so let the caller decide. -func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) { - privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 private key: {{err}}", err) - } - - cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 crypted bytes: {{err}}", err) - } - - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes))) - if err != nil { - return nil, errwrap.Wrapf("error parsing private key: {{err}}", err) - } - - entityList := &openpgp.EntityList{entity} - md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil) - if err != nil { - return nil, errwrap.Wrapf("error decrypting the messages: {{err}}", err) - } - - ptBuf := bytes.NewBuffer(nil) - ptBuf.ReadFrom(md.UnverifiedBody) - - return ptBuf, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go deleted file mode 100644 index bb0f367d6..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go +++ /dev/null @@ -1,140 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" -) - -// PubKeyFileFlag implements flag.Value and command.Example to receive exactly -// one PGP or keybase key via a flag. -type PubKeyFileFlag string - -func (p *PubKeyFileFlag) String() string { return string(*p) } - -func (p *PubKeyFileFlag) Set(val string) error { - if p != nil && *p != "" { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - if len(keys) > 1 { - return errors.New("can only specify one pgp key") - } - - *p = PubKeyFileFlag(keys[0]) - return nil -} - -func (p *PubKeyFileFlag) Example() string { return "keybase:user" } - -// PGPPubKeyFiles implements the flag.Value interface and allows parsing and -// reading a list of PGP public key files. -type PubKeyFilesFlag []string - -func (p *PubKeyFilesFlag) String() string { - return fmt.Sprint(*p) -} - -func (p *PubKeyFilesFlag) Set(val string) error { - if len(*p) > 0 { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - *p = PubKeyFilesFlag(keys) - return nil -} - -func (p *PubKeyFilesFlag) Example() string { return "keybase:user1, keybase:user2, ..." } - -// ParsePGPKeys takes a list of PGP keys and parses them either using keybase -// or reading them from disk and returns the "expanded" list of pgp keys in -// the same order. -func ParsePGPKeys(keyfiles []string) ([]string, error) { - keys := make([]string, len(keyfiles)) - - keybaseMap, err := FetchKeybasePubkeys(keyfiles) - if err != nil { - return nil, err - } - - for i, keyfile := range keyfiles { - keyfile = strings.TrimSpace(keyfile) - - if strings.HasPrefix(keyfile, kbPrefix) { - key, ok := keybaseMap[keyfile] - if !ok || key == "" { - return nil, fmt.Errorf("keybase user %q not found", strings.TrimPrefix(keyfile, kbPrefix)) - } - keys[i] = key - continue - } - - pgpStr, err := ReadPGPFile(keyfile) - if err != nil { - return nil, err - } - keys[i] = pgpStr - } - - return keys, nil -} - -// ReadPGPFile reads the given PGP file from disk. -func ReadPGPFile(path string) (string, error) { - if path[0] == '@' { - path = path[1:] - } - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - buf := bytes.NewBuffer(nil) - _, err = buf.ReadFrom(f) - if err != nil { - return "", err - } - - // First parse as an armored keyring file, if that doesn't work, treat it as a straight binary/b64 string - keyReader := bytes.NewReader(buf.Bytes()) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err == nil { - if len(entityList) != 1 { - return "", fmt.Errorf("more than one key found in file %q", path) - } - if entityList[0] == nil { - return "", fmt.Errorf("primary key was nil for file %q", path) - } - - serializedEntity := bytes.NewBuffer(nil) - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error serializing entity for file %q: {{err}}", path), err) - } - - return base64.StdEncoding.EncodeToString(serializedEntity.Bytes()), nil - } - - _, err = base64.StdEncoding.DecodeString(buf.String()) - if err == nil { - return buf.String(), nil - } - return base64.StdEncoding.EncodeToString(buf.Bytes()), nil - -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go deleted file mode 100644 index eba067762..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go +++ /dev/null @@ -1,117 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/keybase/go-crypto/openpgp" -) - -const ( - kbPrefix = "keybase:" -) - -// FetchKeybasePubkeys fetches public keys from Keybase given a set of -// usernames, which are derived from correctly formatted input entries. It -// doesn't use their client code due to both the API and the fact that it is -// considered alpha and probably best not to rely on it. The keys are returned -// as base64-encoded strings. -func FetchKeybasePubkeys(input []string) (map[string]string, error) { - client := cleanhttp.DefaultClient() - if client == nil { - return nil, fmt.Errorf("unable to create an http client") - } - - if len(input) == 0 { - return nil, nil - } - - usernames := make([]string, 0, len(input)) - for _, v := range input { - if strings.HasPrefix(v, kbPrefix) { - usernames = append(usernames, strings.TrimPrefix(v, kbPrefix)) - } - } - - if len(usernames) == 0 { - return nil, nil - } - - ret := make(map[string]string, len(usernames)) - url := fmt.Sprintf("https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s&fields=public_keys", strings.Join(usernames, ",")) - resp, err := client.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - type PublicKeys struct { - Primary struct { - Bundle string - } - } - - type LThem struct { - PublicKeys `json:"public_keys"` - } - - type KbResp struct { - Status struct { - Name string - } - Them []LThem - } - - out := &KbResp{ - Them: []LThem{}, - } - - if err := jsonutil.DecodeJSONFromReader(resp.Body, out); err != nil { - return nil, err - } - - if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) - } - - missingNames := make([]string, 0, len(usernames)) - var keyReader *bytes.Reader - serializedEntity := bytes.NewBuffer(nil) - for i, themVal := range out.Them { - if themVal.Primary.Bundle == "" { - missingNames = append(missingNames, usernames[i]) - continue - } - keyReader = bytes.NewReader([]byte(themVal.Primary.Bundle)) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err != nil { - return nil, err - } - if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) - } - if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) - } - - serializedEntity.Reset() - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error serializing entity for user %q: {{err}}", usernames[i]), err) - } - - // The API returns values in the same ordering requested, so this should properly match - ret[kbPrefix+usernames[i]] = base64.StdEncoding.EncodeToString(serializedEntity.Bytes()) - } - - if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go deleted file mode 100644 index c10a9055e..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go +++ /dev/null @@ -1,271 +0,0 @@ -package pgpkeys - -const ( - TestPrivKey1 = `lQOYBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAEAB/wL+KX0mdeISEpX -oDgt766Key1Kthe8nbEs5dOXIsP7OR7ZPcnE2hy6gftgVFnBGEZnWVN70vmJd6Z5y9d1mI+GecXj -UL0EpI0EmohyYDJsHUnght/5ecRNFA+VeNmGPYNQGCeHJyZOiFunGGENpHU7BbubAht8delz37Mx -JQgvMyR6AKvg8HKBoQeqV1uMWNJE/vKwV/z1dh1sjK/GFxu05Qaq0GTfAjVLuFOyJTS95yq6gblD -jUdbHLp7tBeqIKo9voWCJF5mGOlq3973vVoWETy9b0YYPCE/M7fXmK9dJITHqkROLMW6TgcFeIw4 -yL5KOBCHk+QGPSvyQN7R7Fd5BADwuT1HZmvg7Y9GjarKXDjxdNemUiHtba2rUzfH6uNmKNQvwQek -nma5palNUJ4/dz1aPB21FUBXJF5yWwXEdApl+lIDU0J5m4UD26rqEVRq9Kx3GsX+yfcwObkrSzW6 -kmnQSB5KI0fIuegMTM+Jxo3pB/mIRwDTMmk+vfzIGyW+7QQA8aFwFLMdKdfLgSGbl5Z6etmOAVQ2 -Oe2ebegU9z/ewi/Rdt2s9yQiAdGVM8+q15Saz8a+kyS/l1CjNPzr3VpYx1OdZ3gb7i2xoy9GdMYR -ZpTq3TuST95kx/9DqA97JrP23G47U0vwF/cg8ixCYF8Fz5dG4DEsxgMwKqhGdW58wMMD/iytkfMk -Vk6Z958Rpy7lhlC6L3zpO38767bSeZ8gRRi/NMFVOSGYepKFarnfxcTiNa+EoSVA6hUo1N64nALE -sJBpyOoTfKIpz7WwTF1+WogkiYrfM6lHon1+3qlziAcRW0IohM3g2C1i3GWdON4Cl8/PDO3R0E52 -N6iG/ctNNeMiPe60EFZhdWx0IFRlc3QgS2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d -4hIHsG7kmJRTJfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF3 -9jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poe -o+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeUR -BRWdA5gEVduM9QEIAL53hJ5bZJ7oEDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkf -Rqnv981fFwGnh2+I1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a -9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu -9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/z -bfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOleYwxk+FoTqXEAEQEAAQAH+wVyQXaNwnjQ -xfW+M8SJNo0C7e+0d7HsuBTA/d/eP4bj6+X8RaRFVwiMvSAoxsqBNCLJP00qzzKfRQWJseD1H35z -UjM7rNVUEL2k1yppyp61S0qj0TdhVUfJDYZqRYonVgRMvzfDTB1ryKrefKenQYL/jGd9VYMnKmWZ -6GVk4WWXXx61iOt2HNcmSXKetMM1Mg67woPZkA3fJaXZ+zW0zMu4lTSB7yl3+vLGIFYILkCFnREr -drQ+pmIMwozUAt+pBq8dylnkHh6g/FtRfWmLIMDqM1NlyuHRp3dyLDFdTA93osLG0QJblfX54W34 -byX7a4HASelGi3nPjjOAsTFDkuEEANV2viaWk1CV4ryDrXGmy4Xo32Md+laGPRcVfbJ0mjZjhQsO -gWC1tjMs1qZMPhcrKIBCjjdAcAIrGV9h3CXc0uGuez4XxLO+TPBKaS0B8rKhnKph1YZuf+HrOhzS -astDnOjNIT+qucCL/qSbdYpj9of3yY61S59WphPOBjoVM3BFBADka6ZCk81gx8jA2E1e9UqQDmdM -FZaVA1E7++kqVSFRDJGnq+5GrBTwCJ+sevi+Rvf8Nx4AXvpCdtMBPX9RogsUFcR0pMrKBrgRo/Vg -EpuodY2Ef1VtqXR24OxtRf1UwvHKydIsU05rzMAy5uGgQvTzRTXxZFLGUY31wjWqmo9VPQP+PnwA -K83EV2kk2bsXwZ9MXg05iXqGQYR4bEc/12v04BtaNaDS53hBDO4JIa3Bnz+5oUoYhb8FgezUKA9I -n6RdKTTP1BLAu8titeozpNF07V++dPiSE2wrIVsaNHL1pUwW0ql50titVwe+EglWiCKPtJBcCPUA -3oepSPchiDjPqrNCYIkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZAQIABgUCVduM -9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYulEimOPzLUX/Z -XZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr -9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEc -ZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4 -EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY+XsKVYRf -NIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcIPXFv3m3WfUln -G/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O9uK3lQozbw2g -H9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKf -PRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h -7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPrivKey2 = `lQOYBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAEAB/oCBqTIsxlUgLtz -HRpWW5MJ+93xvmVV0JHhRK/ygKghq+zpC6S+cn7dwrEj1JTPh+17lyemYQK+RMeiBEduoWNKuHUd -WX353w2411rrc/VuGTglzhd8Ir2BdJlPesCzw4JQnrWqcBqN52W+iwhnE7PWVhnvItWnx6APK5Se -q7dzFWy8Z8tNIHm0pBQbeyo6x2rHHSWkr2fs7V02qFQhii1ayFRMcgdOWSNX6CaZJuYhk/DyjApN -9pVhi3P1pNMpFeV0Pt8Gl1f/9o6/HpAYYEt/6vtVRhFUGgtNi95oc0oyzIJxliRvd6+Z236osigQ -QEBwj1ImRK8TKyWPlykiJWc5BADfldgOCA55o3Qz/z/oVE1mm+a3FmPPTQlHBXotNEsrWV2wmJHe -lNQPI6ZwMtLrBSg8PUpG2Rvao6XJ4ZBl/VcDwfcLgCnALPCcL0L0Z3vH3Sc9Ta/bQWJODG7uSaI1 -iVJ7ArKNtVzTqRQWK967mol9CCqh4A0jRrH0aVEFbrqQ/QQA58iEJaFhzFZjufjC9N8Isn3Ky7xu -h+dk001RNCb1GnNZcx4Ld2IB+uXyYjtg7dNaUhGgGuCBo9nax89bMsBzzUukx3SHq1pxopMg6Dm8 -ImBoIAicuQWgEkaP2T0rlwCozUalJZaG1gyrzkPhkeY7CglpJycHLHfY2MIb46c8+58D/iJ83Q5j -Y4x+sqW2QeUYFwqCcOW8Urg64UxEkgXZXiNMwTAJCaxp/Pz7cgeUDwgv+6CXEdnT1910+byzK9ha -V1Q/65+/JYuCeyHxcoAb4Wtpdl7GALGd/1G0UAmq47yrefEr/b00uS35i1qUUhOzo1NmEZch/bvF -kmJ+WtAHunZcOCu0EFZhdWx0IFRlc3QgS2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOuDLGfrXolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHip -ZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABq -hb5ojexdnAYRswaHV201ZCclj9rnJN1PAg0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmG -kdrg8K8ARmRILjmwuBAgJM0eXBZHNGWXelk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0 -vDttB+ZXqF88W9jAYlvdgbTtajNF5IDYDjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlx -k4edA5gEVduQkQEIAOjZV5tbpfIh5QefpIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe -4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/t -GF5xE3e5CoZRsHV/c92h3t1LdJNOnC5mUKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBH -yt0tdHtIWuQv6joTJzujqViRhlCwQYzQSKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1r -ENO8JOuPu6tMS+znFu67skq2gFFZwCQWIjdHm+2ukE+PE580WAWudyMAEQEAAQAH/i7ndRPI+t0T -AdEu0dTIdyrrg3g7gd471kQtIVZZwTYSy2yhNY/Ciu72s3ab8QNCxY8dNL5bRk8FKjHslAoNSFdO -8iZSLiDgIHOZOcjYe6pqdgQaeTHodm1Otrn2SbB+K/3oX6W/y1xe18aSojGba/nHMj5PeJbIN9Pi -jmh0WMLD/0rmkTTxR7qQ5+kMV4O29xY4qjdYRD5O0adeZX0mNncmlmQ+rX9yxrtSgFROu1jwVtfP -hcNetifTTshJnTwND8hux5ECEadlIVBHypW28Hth9TRBXmddTmv7L7mdtUO6DybgkpWpw4k4LPsk -uZ6aY4wcGRp7EVfWGr9NHbq/n+0EAOlhDXIGdylkQsndjBMyhPsXZa5fFBmOyHjXj733195Jgr1v -ZjaIomrA9cvYrmN75oKrG1jJsMEl6HfC/ZPzEj6E51/p1PRdHP7CdUUA+DG8x4M3jn+e43psVuAR -a1XbN+8/bOa0ubt7ljVPjAEvWRSvU9dRaQz93w3fduAuM07dBAD/ayK3e0d6JMJMrU50lNOXQBgL -rFbg4rWzPO9BJQdhjOhmOZQiUa1Q+EV+s95yIUg1OAfaMP9KRIljr5RCdGNS6WoMNBAQOSrZpelf -jW4NpzphNfWDGVkUoPoskVtJz/nu9d860dGd3Al0kSmtUpMu5QKlo+sSxXUPbWLUn8V9/wP/ScCW -H+0gtL4R7SFazPeTIP+Cu5oR7A/DlFVLJKa3vo+atkhSvwxHGbg04vb/W4mKhGGVtMBtlhRmaWOe -PhUulU5FdaYsdlpN/Yd+hhgU6NHlyImPGVEHWD8c6CG8qoZfpR33j2sqshs4i/MtJZeBvl62vxPn -9bDN7KAjFNll9axAjIkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZAQIABgUCVduQ -kQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDDhnV3bXQsCvn/ -6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQe3l4CqJvkn6j -ybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4KBIrp/bhG6Pdn -igKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eYENtyOmEMWOFC -LLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H/1trYUtJjXQK -HmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7PkUZTfpaP/L6 -DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0UPEnjvtZTp5yO -hTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQdw/2epIewH0L/ -FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4MFOMVRn1dc3q -dXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPrivKey3 = `lQOXBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAEAB/dQbElFIa0VklZa -39ZLhtbBxACSWH3ql3EtRZaB2Mh4zSALbFyJDQfScOy8AZHmv66Ozxit9X9WsYr9OzcHujgl/2da -A3lybF6iLw1YDNaL11G6kuyn5sFP6lYGMRGOIWSik9oSVF6slo8m8ujRLdBsdMXVcElHKzCJiWmt -JZHEnUkl9X96fIPajMBfWjHHwcaeMOc77nvjwqy5wC4EY8TSVYzxeZHL7DADQ0EHBcThlmfizpCq -26LMVb6ju8STH7uDDFyKmhr/hC2vOkt+PKsvBCmW8/ESanO1zKPD9cvSsOWr2rZWNnkDRftqzOU5 -OCrI+3o9E74+toNb07bPntEEAMEStOzSvqZ6NKdh7EZYPA4mkkFC+EiHYIoinP1sd9V8O2Hq+dzx -yFHtWu0LmP6uWXk45vsP9y1UMJcEa33ew5JJa7zgucI772/BNvd/Oys/PqwIAl6uNIY8uYLgmn4L -1IPatp7vDiXzZSivPZd4yN4S4zCypZp9cnpO3qv8q7CtBADW87IA0TabdoxiN+m4XL7sYDRIfglr -MRPAlfrkAUaGDBx/t1xb6IaKk7giFdwHpTI6+g9XNkqKqogMe4Fp+nsd1xtfsNUBn6iKZavm5kXe -Lp9QgE+K6mvIreOTe2PKQqXqgPRG6+SRGatoKeY76fIpd8AxOJyWERxcq2lUHLn45QP/UXDTcYB7 -gzJtZrfpXN0GqQ0lYXMzbQfLnkUsu3mYzArfNy0otzEmKTkwmKclNY1/EJSzSdHfgmeA260a0nLK -64C0wPgSmOqw90qwi5odAYSjSFBapDbyGF86JpHrLxyEEpGoXanRPwWfbiWp19Nwg6nknA87AtaM -3+AHjbWzwCpHL7QQVmF1bHQgVGVzdCBLZXkgM4kBOAQTAQIAIgUCVduSIwIbLwYLCQgHAwIGFQgC -CQoLBBYCAwECHgECF4AACgkQ9HlLVvwtxt1aMQf/aaGoL1rRWTUjM6DEShXFhWpV29rEjSdNk5N+ -ZwVifgdCVD5IsSjI1Z7mO2SHHiTm4eKnHAofM6/TZgzXg1YLpu8rDYJARMsM8bgK/xgxSamGjm2c -wN220jOnwePIlG0drNTW5N6zb/K6qHoscJ6NUkjS5JPdGJuq7B0bdCM8/xSbG75gL34U5bYqK38B -DwmW4UMl2rf/BJfxV9hmsZ2Cat4TspgyiWEKTMZI+PugXKDDwuoqgm+320K4EqFkwG4y/WwHkKgk -hZ0+io5lzhTsvVd2p8q8VlH9GG5eA3WWQj0yqucsOmKQvcuT5y0vFY6NQJbyuioqgdlgEXtc+p0B -+Z0DmARV25IjAQgA49yN3hCBsuWoiTezoE9FHJXOCVOBR1/4jStQPJtoMl8mhtl3xTp7iGQ+9GhD -y0l5+fP+qcP/rfBq0BslhxVOZ7jQjdUoM6ZUZzJoPGIo/V2KwqpwQl3tdCIjvagCJeYQfTL7lTCc -4ySz+XBoAYMwZVGMcRcjp+JE8Wx9Ovzuq8wnelbU6I5dVJ7O4E1OWbIkLuytDX+fDEvfft6/oPXN -Bl3cm6FzEuQetQQss3DOG9xnvS+DrjmMCbPwR2a++ioQ8+geoqA/kB4cAI6xOb3ncoeGDHc1i4Y9 -T9Ggi+6Aq3girmfDtNYVOM8cZUXcZNCvLkJn8DNeIvnuFUSEO+a5PwARAQABAAf/TPd98CmRNdV/ -VUI8aYT9Kkervdi4DVzsfvrHcoFn88PSJrCkVTmI6qw526Kwa6VZD0YMmll7LszLt5nD1lorDrwN -rir3FmMzlVwge20IvXRwX4rkunYxtA2oFvL+LsEEhtXGx0ERbWRDapk+eGxQ15hxIO4Y/Cdg9E+a -CWfQUrTSnC6qMVfVYMGfnM1yNX3OWattEFfmxQas5XqQk/0FgjCZALixdanjN/r1tjp5/2MiSD8N -Wkemzsr6yPicnc3+BOZc5YOOnH8FqBvVHcDlSJI6pCOCEiO3Pq2QEk/1evONulbF116mLnQoGrpp -W77l+5O42VUpZfjROCPd5DYyMQQA492CFXZpDIJ2emB9/nK8X6IzdVRK3oof8btbSNnme5afIzhs -wR1ruX30O7ThfB+5ezpbgK1C988CWkr9SNSTy43omarafGig6/Y1RzdiITILuIGfbChoSpc70jXx -U0nzJ/1i9yZ/vDgP3EC2miRhlDcp5w0Bu0oMBlgG/1uhj0cEAP/+7aFGP0fo2MZPhyl5feHKWj4k -85XoAIpMBnzF6HTGU3ljAE56a+4sVw3bWB755DPhvpZvDkX60I9iIJxio8TK5ITdfjlLhxuskXyt -ycwWI/4J+soeq4meoxK9jxZJuDl/qvoGfyzNg1oy2OBehX8+6erW46kr6Z/MQutS3zJJBACmJHrK -VR40qD7a8KbvfuM3ruwlm5JqT/Ykq1gfKKxHjWDIUIeyBX/axGQvAGNYeuuQCzZ0+QsEWur3C4kN -U+Pb5K1WGyOKkhJzivSI56AG3d8TA/Q0JhqST6maY0fvUoahWSCcpd7MULa3n1zx5Wsvi8mkVtup -Js/IDi/kqneqM0XviQI+BBgBAgAJBQJV25IjAhsuASkJEPR5S1b8LcbdwF0gBBkBAgAGBQJV25Ij -AAoJEAUj/03Hcrkg84UIAKxn9nizYtwSgDnVNb5PnD5h6+Ui6r7ffYm2o0im4YhakbFTHIPI9PRh -BavRI5sE5Fg2vtE/x38jattoUrJoNoq9Gh9iv5PBfL3amEGjul0RRqYGl+ub+yv7YGAAHbHcdZen -4gx15VWGpB7y3hycWbdzV8h3EAPKIm5XmB7YyXmArnI3CoJA+HtTZGoL6WZWUwka9YichGfaZ/oD -umENg1l87Pp2RqvjLKHmv2tGCtnDzyv/IiWur9zopFQiCc8ysVgRq6CA5x5nzbv6MqRspYUS4e2I -LFbuREA3blR+caw9oX41IYzarW8IbgeIXJ3HqUyhczRKF/z5nDKtX/kHMCqlbAgAnfu0TALnwVuj -KeXLo4Y7OA9LTEqfORcw62q5OjSoQf/VsRSwGSefv3kGZk5N/igELluU3qpG/twZI/TSL6zGqXU2 -FOMlyMm1849TOB9b4B//4dHrjzPhztzowKMMUqeTxmSgYtFTshKN6eQ0XO+7ZuOXEmSKXS4kOUs9 -ttfzSiPNXUZL2D5nFU9H7rw3VAuXYVTrOx+Dfi6mYsscbxUbi8THODI2Q7B9Ni92DJE1OOe4+57o -fXZ9ln24I14bna/uVHd6hBwLEE6eLCCKkHxQnnZFZduXDHMK0a0OL8RYHfMtNSem4pyC5wDQui1u -KFIzGEPKVoBF9U7VBXpyxpsz+A==` - - TestPubKey1 = `mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOfLr44B -HbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRTJfjECi+AuTGeDwBy84TD -cRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3CEe8cMwIPqPT2kajJVdOyrvkyuFOdPFOE -A7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlB -C0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXa -QKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7oEDCn -aY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I1Ktm698UAZS9Jt8y -jak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb -6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5N -ZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu -9p315E87DOleYwxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYu -lEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHN -C1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0 -YwKoz3h9+QEcZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJi -oPn2jVMnXCm4EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH -/AtY+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcI -PXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O -9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx -8iDV+dNtDVKfPRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKd -OIu60YPNE4+h7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPubKey2 = `mQENBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOuDLGfr -XolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHipZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO -2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABqhb5ojexdnAYRswaHV201ZCclj9rnJN1P -Ag0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmGkdrg8K8ARmRILjmwuBAgJM0eXBZHNGWX -elk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0vDttB+ZXqF88W9jAYlvdgbTtajNF5IDY -DjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlxk4e5AQ0EVduQkQEIAOjZV5tbpfIh5Qef -pIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg -+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/tGF5xE3e5CoZRsHV/c92h3t1LdJNOnC5m -UKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBHyt0tdHtIWuQv6joTJzujqViRhlCwQYzQ -SKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1rENO8JOuPu6tMS+znFu67skq2gFFZwCQW -IjdHm+2ukE+PE580WAWudyMAEQEAAYkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZ -AQIABgUCVduQkQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDD -hnV3bXQsCvn/6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQ -e3l4CqJvkn6jybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4K -BIrp/bhG6PdnigKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eY -ENtyOmEMWOFCLLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H -/1trYUtJjXQKHmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7 -PkUZTfpaP/L6DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0U -PEnjvtZTp5yOhTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQd -w/2epIewH0L/FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4 -MFOMVRn1dc3qdXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPubKey3 = `mQENBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDOJATgEEwECACIFAlXbkiMCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEPR5S1b8 -LcbdWjEH/2mhqC9a0Vk1IzOgxEoVxYVqVdvaxI0nTZOTfmcFYn4HQlQ+SLEoyNWe5jtkhx4k5uHi -pxwKHzOv02YM14NWC6bvKw2CQETLDPG4Cv8YMUmpho5tnMDdttIzp8HjyJRtHazU1uTes2/yuqh6 -LHCejVJI0uST3RibquwdG3QjPP8Umxu+YC9+FOW2Kit/AQ8JluFDJdq3/wSX8VfYZrGdgmreE7KY -MolhCkzGSPj7oFygw8LqKoJvt9tCuBKhZMBuMv1sB5CoJIWdPoqOZc4U7L1XdqfKvFZR/RhuXgN1 -lkI9MqrnLDpikL3Lk+ctLxWOjUCW8roqKoHZYBF7XPqdAfm5AQ0EVduSIwEIAOPcjd4QgbLlqIk3 -s6BPRRyVzglTgUdf+I0rUDybaDJfJobZd8U6e4hkPvRoQ8tJefnz/qnD/63watAbJYcVTme40I3V -KDOmVGcyaDxiKP1disKqcEJd7XQiI72oAiXmEH0y+5UwnOMks/lwaAGDMGVRjHEXI6fiRPFsfTr8 -7qvMJ3pW1OiOXVSezuBNTlmyJC7srQ1/nwxL337ev6D1zQZd3JuhcxLkHrUELLNwzhvcZ70vg645 -jAmz8EdmvvoqEPPoHqKgP5AeHACOsTm953KHhgx3NYuGPU/RoIvugKt4Iq5nw7TWFTjPHGVF3GTQ -ry5CZ/AzXiL57hVEhDvmuT8AEQEAAYkCPgQYAQIACQUCVduSIwIbLgEpCRD0eUtW/C3G3cBdIAQZ -AQIABgUCVduSIwAKCRAFI/9Nx3K5IPOFCACsZ/Z4s2LcEoA51TW+T5w+YevlIuq+332JtqNIpuGI -WpGxUxyDyPT0YQWr0SObBORYNr7RP8d/I2rbaFKyaDaKvRofYr+TwXy92phBo7pdEUamBpfrm/sr -+2BgAB2x3HWXp+IMdeVVhqQe8t4cnFm3c1fIdxADyiJuV5ge2Ml5gK5yNwqCQPh7U2RqC+lmVlMJ -GvWInIRn2mf6A7phDYNZfOz6dkar4yyh5r9rRgrZw88r/yIlrq/c6KRUIgnPMrFYEauggOceZ827 -+jKkbKWFEuHtiCxW7kRAN25UfnGsPaF+NSGM2q1vCG4HiFydx6lMoXM0Shf8+ZwyrV/5BzAqpWwI -AJ37tEwC58Fboynly6OGOzgPS0xKnzkXMOtquTo0qEH/1bEUsBknn795BmZOTf4oBC5blN6qRv7c -GSP00i+sxql1NhTjJcjJtfOPUzgfW+Af/+HR648z4c7c6MCjDFKnk8ZkoGLRU7ISjenkNFzvu2bj -lxJkil0uJDlLPbbX80ojzV1GS9g+ZxVPR+68N1QLl2FU6zsfg34upmLLHG8VG4vExzgyNkOwfTYv -dgyRNTjnuPue6H12fZZ9uCNeG52v7lR3eoQcCxBOniwgipB8UJ52RWXblwxzCtGtDi/EWB3zLTUn -puKcgucA0LotbihSMxhDylaARfVO1QV6csabM/g=` - - TestAAPubKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzz -wiMwBS5cD0darGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7 -H+/mhfFvKmgr0Y5kDCF1j0T/063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX -1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0fsF5St9jhO7mbZU9EFkv9O3t3EaUR -fHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg8hQssKeVGpuskTdz -5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3QgS2V5 -IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ -EOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRT -JfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1Z -mumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4z -J2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+ -7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7o -EDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I -1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okj -h5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTj -OleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2o -P/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOle -Ywxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVh -EGipBmpDGRYulEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHk -GRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRd -tPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEcZHvsjSZjgydKvfLY -cm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4EKc7 -fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY -+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7 -moViAAcIPXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWko -jHqyob3cyLgy6z9Q557O9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJ -iEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKfPRENiLOOc19MmS+phmUy -rbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h7u2CfYyF -Pu3AlUaGNMBlvy6PEpU= -=NUTS ------END PGP PUBLIC KEY BLOCK-----` -) diff --git a/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go deleted file mode 100644 index 337c7b736..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/env.go +++ /dev/null @@ -1,66 +0,0 @@ -package pluginutil - -import ( - "os" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/vault/helper/mlock" -) - -var ( - // PluginMlockEnabled is the ENV name used to pass the configuration for - // enabling mlock - PluginMlockEnabled = "VAULT_PLUGIN_MLOCK_ENABLED" - - // PluginVaultVersionEnv is the ENV name used to pass the version of the - // vault server to the plugin - PluginVaultVersionEnv = "VAULT_VERSION" - - // PluginMetadataModeEnv is an ENV name used to disable TLS communication - // to bootstrap mounting plugins. - PluginMetadataModeEnv = "VAULT_PLUGIN_METADATA_MODE" -) - -// OptionallyEnableMlock determines if mlock should be called, and if so enables -// mlock. -func OptionallyEnableMlock() error { - if os.Getenv(PluginMlockEnabled) == "true" { - return mlock.LockMemory() - } - - return nil -} - -// GRPCSupport defaults to returning true, unless VAULT_VERSION is missing or -// it fails to meet the version constraint. -func GRPCSupport() bool { - verString := os.Getenv(PluginVaultVersionEnv) - - // If the env var is empty, we fall back to netrpc for backward compatibility. - if verString == "" { - return false - } - - if verString != "unknown" { - ver, err := version.NewVersion(verString) - if err != nil { - return true - } - - // Due to some regressions on 0.9.2 & 0.9.3 we now require version 0.9.4 - // to allow the plugin framework to default to gRPC. - constraint, err := version.NewConstraint(">= 0.9.4") - if err != nil { - return true - } - - return constraint.Check(ver) - } - - return true -} - -// Returns true if the plugin calling this function is running in metadata mode. -func InMetadataMode() bool { - return os.Getenv(PluginMetadataModeEnv) == "true" -} diff --git a/vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go deleted file mode 100644 index 436e169fe..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/runner.go +++ /dev/null @@ -1,182 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/sha256" - "crypto/tls" - "flag" - "fmt" - "os/exec" - "time" - - log "github.com/hashicorp/go-hclog" - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/version" -) - -// Looker defines the plugin Lookup function that looks into the plugin catalog -// for available plugins and returns a PluginRunner -type Looker interface { - LookupPlugin(context.Context, string) (*PluginRunner, error) -} - -// Wrapper interface defines the functions needed by the runner to wrap the -// metadata needed to run a plugin process. This includes looking up Mlock -// configuration and wrapping data in a response wrapped token. -// logical.SystemView implementations satisfy this interface. -type RunnerUtil interface { - ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) - MlockEnabled() bool -} - -// LookWrapper defines the functions for both Looker and Wrapper -type LookRunnerUtil interface { - Looker - RunnerUtil -} - -// PluginRunner defines the metadata needed to run a plugin securely with -// go-plugin. -type PluginRunner struct { - Name string `json:"name" structs:"name"` - Command string `json:"command" structs:"command"` - Args []string `json:"args" structs:"args"` - Sha256 []byte `json:"sha256" structs:"sha256"` - Builtin bool `json:"builtin" structs:"builtin"` - BuiltinFactory func() (interface{}, error) `json:"-" structs:"-"` -} - -// Run takes a wrapper RunnerUtil instance along with the go-plugin parameters and -// returns a configured plugin.Client with TLS Configured and a wrapping token set -// on PluginUnwrapTokenEnv for plugin process consumption. -func (r *PluginRunner) Run(ctx context.Context, wrapper RunnerUtil, pluginMap map[string]plugin.Plugin, hs plugin.HandshakeConfig, env []string, logger log.Logger) (*plugin.Client, error) { - return r.runCommon(ctx, wrapper, pluginMap, hs, env, logger, false) -} - -// RunMetadataMode returns a configured plugin.Client that will dispense a plugin -// in metadata mode. The PluginMetadataModeEnv is passed in as part of the Cmd to -// plugin.Client, and consumed by the plugin process on pluginutil.VaultPluginTLSProvider. -func (r *PluginRunner) RunMetadataMode(ctx context.Context, wrapper RunnerUtil, pluginMap map[string]plugin.Plugin, hs plugin.HandshakeConfig, env []string, logger log.Logger) (*plugin.Client, error) { - return r.runCommon(ctx, wrapper, pluginMap, hs, env, logger, true) - -} - -func (r *PluginRunner) runCommon(ctx context.Context, wrapper RunnerUtil, pluginMap map[string]plugin.Plugin, hs plugin.HandshakeConfig, env []string, logger log.Logger, isMetadataMode bool) (*plugin.Client, error) { - cmd := exec.Command(r.Command, r.Args...) - cmd.Env = append(cmd.Env, env...) - - // Add the mlock setting to the ENV of the plugin - if wrapper.MlockEnabled() { - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMlockEnabled, "true")) - } - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginVaultVersionEnv, version.GetVersion().Version)) - - var clientTLSConfig *tls.Config - if !isMetadataMode { - // Add the metadata mode ENV and set it to false - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMetadataModeEnv, "false")) - - // Get a CA TLS Certificate - certBytes, key, err := generateCert() - if err != nil { - return nil, err - } - - // Use CA to sign a client cert and return a configured TLS config - clientTLSConfig, err = createClientTLSConfig(certBytes, key) - if err != nil { - return nil, err - } - - // Use CA to sign a server cert and wrap the values in a response wrapped - // token. - wrapToken, err := wrapServerConfig(ctx, wrapper, certBytes, key) - if err != nil { - return nil, err - } - - // Add the response wrap token to the ENV of the plugin - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginUnwrapTokenEnv, wrapToken)) - } else { - logger = logger.With("metadata", "true") - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", PluginMetadataModeEnv, "true")) - } - - secureConfig := &plugin.SecureConfig{ - Checksum: r.Sha256, - Hash: sha256.New(), - } - - clientConfig := &plugin.ClientConfig{ - HandshakeConfig: hs, - Plugins: pluginMap, - Cmd: cmd, - SecureConfig: secureConfig, - TLSConfig: clientTLSConfig, - Logger: logger, - AllowedProtocols: []plugin.Protocol{ - plugin.ProtocolNetRPC, - plugin.ProtocolGRPC, - }, - } - - client := plugin.NewClient(clientConfig) - - return client, nil -} - -type APIClientMeta struct { - // These are set by the command line flags. - flagCACert string - flagCAPath string - flagClientCert string - flagClientKey string - flagInsecure bool -} - -func (f *APIClientMeta) FlagSet() *flag.FlagSet { - fs := flag.NewFlagSet("vault plugin settings", flag.ContinueOnError) - - fs.StringVar(&f.flagCACert, "ca-cert", "", "") - fs.StringVar(&f.flagCAPath, "ca-path", "", "") - fs.StringVar(&f.flagClientCert, "client-cert", "", "") - fs.StringVar(&f.flagClientKey, "client-key", "", "") - fs.BoolVar(&f.flagInsecure, "tls-skip-verify", false, "") - - return fs -} - -func (f *APIClientMeta) GetTLSConfig() *api.TLSConfig { - // If we need custom TLS configuration, then set it - if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure { - t := &api.TLSConfig{ - CACert: f.flagCACert, - CAPath: f.flagCAPath, - ClientCert: f.flagClientCert, - ClientKey: f.flagClientKey, - TLSServerName: "", - Insecure: f.flagInsecure, - } - - return t - } - - return nil -} - -// CancelIfCanceled takes a context cancel func and a context. If the context is -// shutdown the cancelfunc is called. This is useful for merging two cancel -// functions. -func CtxCancelIfCanceled(f context.CancelFunc, ctxCanceler context.Context) chan struct{} { - quitCh := make(chan struct{}) - go func() { - select { - case <-quitCh: - case <-ctxCanceler.Done(): - f() - } - }() - return quitCh -} diff --git a/vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go b/vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go deleted file mode 100644 index d43f77806..000000000 --- a/vendor/github.com/hashicorp/vault/helper/pluginutil/tls.go +++ /dev/null @@ -1,241 +0,0 @@ -package pluginutil - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "errors" - "net/url" - "os" - "time" - - "github.com/SermoDigital/jose/jws" - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/helper/certutil" -) - -var ( - // PluginUnwrapTokenEnv is the ENV name used to pass unwrap tokens to the - // plugin. - PluginUnwrapTokenEnv = "VAULT_UNWRAP_TOKEN" - - // PluginCACertPEMEnv is an ENV name used for holding a CA PEM-encoded - // string. Used for testing. - PluginCACertPEMEnv = "VAULT_TESTING_PLUGIN_CA_PEM" -) - -// generateCert is used internally to create certificates for the plugin -// client and server. -func generateCert() ([]byte, *ecdsa.PrivateKey, error) { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - return nil, nil, err - } - - host, err := uuid.GenerateUUID() - if err != nil { - return nil, nil, err - } - - sn, err := certutil.GenerateSerialNumber() - if err != nil { - return nil, nil, err - } - - template := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: host, - }, - DNSNames: []string{host}, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageClientAuth, - x509.ExtKeyUsageServerAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement, - SerialNumber: sn, - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - IsCA: true, - } - - certBytes, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) - if err != nil { - return nil, nil, errwrap.Wrapf("unable to generate client certificate: {{err}}", err) - } - - return certBytes, key, nil -} - -// createClientTLSConfig creates a signed certificate and returns a configured -// TLS config. -func createClientTLSConfig(certBytes []byte, key *ecdsa.PrivateKey) (*tls.Config, error) { - clientCert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, errwrap.Wrapf("error parsing generated plugin certificate: {{err}}", err) - } - - cert := tls.Certificate{ - Certificate: [][]byte{certBytes}, - PrivateKey: key, - Leaf: clientCert, - } - - clientCertPool := x509.NewCertPool() - clientCertPool.AddCert(clientCert) - - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: clientCertPool, - ClientCAs: clientCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - ServerName: clientCert.Subject.CommonName, - MinVersion: tls.VersionTLS12, - } - - tlsConfig.BuildNameToCertificate() - - return tlsConfig, nil -} - -// wrapServerConfig is used to create a server certificate and private key, then -// wrap them in an unwrap token for later retrieval by the plugin. -func wrapServerConfig(ctx context.Context, sys RunnerUtil, certBytes []byte, key *ecdsa.PrivateKey) (string, error) { - rawKey, err := x509.MarshalECPrivateKey(key) - if err != nil { - return "", err - } - - wrapInfo, err := sys.ResponseWrapData(ctx, map[string]interface{}{ - "ServerCert": certBytes, - "ServerKey": rawKey, - }, time.Second*60, true) - if err != nil { - return "", err - } - - return wrapInfo.Token, nil -} - -// VaultPluginTLSProvider is run inside a plugin and retrieves the response -// wrapped TLS certificate from vault. It returns a configured TLS Config. -func VaultPluginTLSProvider(apiTLSConfig *api.TLSConfig) func() (*tls.Config, error) { - if os.Getenv(PluginMetadataModeEnv) == "true" { - return nil - } - - return func() (*tls.Config, error) { - unwrapToken := os.Getenv(PluginUnwrapTokenEnv) - - // Parse the JWT and retrieve the vault address - wt, err := jws.ParseJWT([]byte(unwrapToken)) - if err != nil { - return nil, errwrap.Wrapf("error decoding token: {{err}}", err) - } - if wt == nil { - return nil, errors.New("nil decoded token") - } - - addrRaw := wt.Claims().Get("addr") - if addrRaw == nil { - return nil, errors.New("decoded token does not contain the active node's api_addr") - } - vaultAddr, ok := addrRaw.(string) - if !ok { - return nil, errors.New("decoded token's api_addr not valid") - } - if vaultAddr == "" { - return nil, errors.New(`no vault api_addr found`) - } - - // Sanity check the value - if _, err := url.Parse(vaultAddr); err != nil { - return nil, errwrap.Wrapf("error parsing the vault api_addr: {{err}}", err) - } - - // Unwrap the token - clientConf := api.DefaultConfig() - clientConf.Address = vaultAddr - if apiTLSConfig != nil { - err := clientConf.ConfigureTLS(apiTLSConfig) - if err != nil { - return nil, errwrap.Wrapf("error configuring api client {{err}}", err) - } - } - client, err := api.NewClient(clientConf) - if err != nil { - return nil, errwrap.Wrapf("error during api client creation: {{err}}", err) - } - - secret, err := client.Logical().Unwrap(unwrapToken) - if err != nil { - return nil, errwrap.Wrapf("error during token unwrap request: {{err}}", err) - } - if secret == nil { - return nil, errors.New("error during token unwrap request: secret is nil") - } - - // Retrieve and parse the server's certificate - serverCertBytesRaw, ok := secret.Data["ServerCert"].(string) - if !ok { - return nil, errors.New("error unmarshalling certificate") - } - - serverCertBytes, err := base64.StdEncoding.DecodeString(serverCertBytesRaw) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - serverCert, err := x509.ParseCertificate(serverCertBytes) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - // Retrieve and parse the server's private key - serverKeyB64, ok := secret.Data["ServerKey"].(string) - if !ok { - return nil, errors.New("error unmarshalling certificate") - } - - serverKeyRaw, err := base64.StdEncoding.DecodeString(serverKeyB64) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - serverKey, err := x509.ParseECPrivateKey(serverKeyRaw) - if err != nil { - return nil, errwrap.Wrapf("error parsing certificate: {{err}}", err) - } - - // Add CA cert to the cert pool - caCertPool := x509.NewCertPool() - caCertPool.AddCert(serverCert) - - // Build a certificate object out of the server's cert and private key. - cert := tls.Certificate{ - Certificate: [][]byte{serverCertBytes}, - PrivateKey: serverKey, - Leaf: serverCert, - } - - // Setup TLS config - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - RootCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - // TLS 1.2 minimum - MinVersion: tls.VersionTLS12, - Certificates: []tls.Certificate{cert}, - ServerName: serverCert.Subject.CommonName, - } - tlsConfig.BuildNameToCertificate() - - return tlsConfig, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go b/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go deleted file mode 100644 index 3d4340ee3..000000000 --- a/vendor/github.com/hashicorp/vault/helper/policyutil/policyutil.go +++ /dev/null @@ -1,131 +0,0 @@ -package policyutil - -import ( - "sort" - "strings" - - "github.com/hashicorp/vault/helper/strutil" -) - -const ( - AddDefaultPolicy = true - DoNotAddDefaultPolicy = false -) - -// ParsePolicies parses a comma-delimited list of policies. -// The resulting collection will have no duplicate elements. -// If 'root' policy was present in the list of policies, then -// all other policies will be ignored, the result will contain -// just the 'root'. In cases where 'root' is not present, if -// 'default' policy is not already present, it will be added. -func ParsePolicies(policiesRaw interface{}) []string { - if policiesRaw == nil { - return []string{"default"} - } - - var policies []string - switch policiesRaw.(type) { - case string: - if policiesRaw.(string) == "" { - return []string{} - } - policies = strings.Split(policiesRaw.(string), ",") - case []string: - policies = policiesRaw.([]string) - } - - return SanitizePolicies(policies, false) -} - -// SanitizePolicies performs the common input validation tasks -// which are performed on the list of policies across Vault. -// The resulting collection will have no duplicate elements. -// If 'root' policy was present in the list of policies, then -// all other policies will be ignored, the result will contain -// just the 'root'. In cases where 'root' is not present, if -// 'default' policy is not already present, it will be added -// if addDefault is set to true. -func SanitizePolicies(policies []string, addDefault bool) []string { - defaultFound := false - for i, p := range policies { - policies[i] = strings.ToLower(strings.TrimSpace(p)) - // Eliminate unnamed policies. - if policies[i] == "" { - continue - } - - // If 'root' policy is present, ignore all other policies. - if policies[i] == "root" { - policies = []string{"root"} - defaultFound = true - break - } - if policies[i] == "default" { - defaultFound = true - } - } - - // Always add 'default' except only if the policies contain 'root'. - if addDefault && (len(policies) == 0 || !defaultFound) { - policies = append(policies, "default") - } - - return strutil.RemoveDuplicates(policies, true) -} - -// EquivalentPolicies checks whether the given policy sets are equivalent, as in, -// they contain the same values. The benefit of this method is that it leaves -// the "default" policy out of its comparisons as it may be added later by core -// after a set of policies has been saved by a backend. -func EquivalentPolicies(a, b []string) bool { - switch { - case a == nil && b == nil: - return true - case a == nil && len(b) == 1 && b[0] == "default": - return true - case b == nil && len(a) == 1 && a[0] == "default": - return true - case a == nil || b == nil: - return false - } - - // First we'll build maps to ensure unique values and filter default - mapA := map[string]bool{} - mapB := map[string]bool{} - for _, keyA := range a { - if keyA == "default" { - continue - } - mapA[keyA] = true - } - for _, keyB := range b { - if keyB == "default" { - continue - } - mapB[keyB] = true - } - - // Now we'll build our checking slices - var sortedA, sortedB []string - for keyA, _ := range mapA { - sortedA = append(sortedA, keyA) - } - for keyB, _ := range mapB { - sortedB = append(sortedB, keyB) - } - sort.Strings(sortedA) - sort.Strings(sortedB) - - // Finally, compare - if len(sortedA) != len(sortedB) { - return false - } - - for i := range sortedA { - if sortedA[i] != sortedB[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/hashicorp/vault/helper/reload/reload.go b/vendor/github.com/hashicorp/vault/helper/reload/reload.go deleted file mode 100644 index 44526c08e..000000000 --- a/vendor/github.com/hashicorp/vault/helper/reload/reload.go +++ /dev/null @@ -1,85 +0,0 @@ -package reload - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "sync" - - "github.com/hashicorp/errwrap" -) - -// ReloadFunc are functions that are called when a reload is requested -type ReloadFunc func(map[string]interface{}) error - -// CertificateGetter satisfies ReloadFunc and its GetCertificate method -// satisfies the tls.GetCertificate function signature. Currently it does not -// allow changing paths after the fact. -type CertificateGetter struct { - sync.RWMutex - - cert *tls.Certificate - - certFile string - keyFile string - passphrase string -} - -func NewCertificateGetter(certFile, keyFile, passphrase string) *CertificateGetter { - return &CertificateGetter{ - certFile: certFile, - keyFile: keyFile, - passphrase: passphrase, - } -} - -func (cg *CertificateGetter) Reload(_ map[string]interface{}) error { - certPEMBlock, err := ioutil.ReadFile(cg.certFile) - if err != nil { - return err - } - keyPEMBlock, err := ioutil.ReadFile(cg.keyFile) - if err != nil { - return err - } - - // Check for encrypted pem block - keyBlock, _ := pem.Decode(keyPEMBlock) - if keyBlock == nil { - return errors.New("decoded PEM is blank") - } - - if x509.IsEncryptedPEMBlock(keyBlock) { - keyBlock.Bytes, err = x509.DecryptPEMBlock(keyBlock, []byte(cg.passphrase)) - if err != nil { - return errwrap.Wrapf("Decrypting PEM block failed {{err}}", err) - } - keyPEMBlock = pem.EncodeToMemory(keyBlock) - } - - cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) - if err != nil { - return err - } - - cg.Lock() - defer cg.Unlock() - - cg.cert = &cert - - return nil -} - -func (cg *CertificateGetter) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { - cg.RLock() - defer cg.RUnlock() - - if cg.cert == nil { - return nil, fmt.Errorf("nil certificate") - } - - return cg.cert, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/salt/salt.go b/vendor/github.com/hashicorp/vault/helper/salt/salt.go deleted file mode 100644 index 4fd562058..000000000 --- a/vendor/github.com/hashicorp/vault/helper/salt/salt.go +++ /dev/null @@ -1,178 +0,0 @@ -package salt - -import ( - "context" - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "encoding/hex" - "fmt" - "hash" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" -) - -const ( - // DefaultLocation is the path in the view we store our key salt - // if no other path is provided. - DefaultLocation = "salt" -) - -// Salt is used to manage a persistent salt key which is used to -// hash values. This allows keys to be generated and recovered -// using the global salt. Primarily, this allows paths in the storage -// backend to be obfuscated if they may contain sensitive information. -type Salt struct { - config *Config - salt string - generated bool -} - -type HashFunc func([]byte) []byte - -// Config is used to parameterize the Salt -type Config struct { - // Location is the path in the storage backend for the - // salt. Uses DefaultLocation if not specified. - Location string - - // HashFunc is the hashing function to use for salting. - // Defaults to SHA1 if not provided. - HashFunc HashFunc - - // HMAC allows specification of a hash function to use for - // the HMAC helpers - HMAC func() hash.Hash - - // String prepended to HMAC strings for identification. - // Required if using HMAC - HMACType string -} - -// NewSalt creates a new salt based on the configuration -func NewSalt(ctx context.Context, view logical.Storage, config *Config) (*Salt, error) { - // Setup the configuration - if config == nil { - config = &Config{} - } - if config.Location == "" { - config.Location = DefaultLocation - } - if config.HashFunc == nil { - config.HashFunc = SHA256Hash - } - if config.HMAC == nil { - config.HMAC = sha256.New - config.HMACType = "hmac-sha256" - } - - // Create the salt - s := &Salt{ - config: config, - } - - // Look for the salt - var raw *logical.StorageEntry - var err error - if view != nil { - raw, err = view.Get(ctx, config.Location) - if err != nil { - return nil, errwrap.Wrapf("failed to read salt: {{err}}", err) - } - } - - // Restore the salt if it exists - if raw != nil { - s.salt = string(raw.Value) - } - - // Generate a new salt if necessary - if s.salt == "" { - s.salt, err = uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("failed to generate uuid: {{err}}", err) - } - s.generated = true - if view != nil { - raw := &logical.StorageEntry{ - Key: config.Location, - Value: []byte(s.salt), - } - if err := view.Put(ctx, raw); err != nil { - return nil, errwrap.Wrapf("failed to persist salt: {{err}}", err) - } - } - } - - if config.HMAC != nil { - if len(config.HMACType) == 0 { - return nil, fmt.Errorf("HMACType must be defined") - } - } - - return s, nil -} - -// SaltID is used to apply a salt and hash function to an ID to make sure -// it is not reversible -func (s *Salt) SaltID(id string) string { - return SaltID(s.salt, id, s.config.HashFunc) -} - -// GetHMAC is used to apply a salt and hash function to data to make sure it is -// not reversible, with an additional HMAC -func (s *Salt) GetHMAC(data string) string { - hm := hmac.New(s.config.HMAC, []byte(s.salt)) - hm.Write([]byte(data)) - return hex.EncodeToString(hm.Sum(nil)) -} - -// GetIdentifiedHMAC is used to apply a salt and hash function to data to make -// sure it is not reversible, with an additional HMAC, and ID prepended -func (s *Salt) GetIdentifiedHMAC(data string) string { - return s.config.HMACType + ":" + s.GetHMAC(data) -} - -// DidGenerate returns if the underlying salt value was generated -// on initialization or if an existing salt value was loaded -func (s *Salt) DidGenerate() bool { - return s.generated -} - -// SaltIDHashFunc uses the supplied hash function instead of the configured -// hash func in the salt. -func (s *Salt) SaltIDHashFunc(id string, hashFunc HashFunc) string { - return SaltID(s.salt, id, hashFunc) -} - -// SaltID is used to apply a salt and hash function to an ID to make sure -// it is not reversible -func SaltID(salt, id string, hash HashFunc) string { - comb := salt + id - hashVal := hash([]byte(comb)) - return hex.EncodeToString(hashVal) -} - -func HMACValue(salt, val string, hashFunc func() hash.Hash) string { - hm := hmac.New(hashFunc, []byte(salt)) - hm.Write([]byte(val)) - return hex.EncodeToString(hm.Sum(nil)) -} - -func HMACIdentifiedValue(salt, val, hmacType string, hashFunc func() hash.Hash) string { - return hmacType + ":" + HMACValue(salt, val, hashFunc) -} - -// SHA1Hash returns the SHA1 of the input -func SHA1Hash(inp []byte) []byte { - hashed := sha1.Sum(inp) - return hashed[:] -} - -// SHA256Hash returns the SHA256 of the input -func SHA256Hash(inp []byte) []byte { - hashed := sha256.Sum256(inp) - return hashed[:] -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go b/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go deleted file mode 100644 index 3518ed8f2..000000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/storagepacker.go +++ /dev/null @@ -1,355 +0,0 @@ -package storagepacker - -import ( - "context" - "crypto/md5" - "encoding/hex" - "fmt" - "strconv" - "strings" - - "github.com/golang/protobuf/proto" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" -) - -const ( - bucketCount = 256 - StoragePackerBucketsPrefix = "packer/buckets/" -) - -// StoragePacker packs the objects into a specific number of buckets by hashing -// its ID and indexing it. Currently this supports only 256 bucket entries and -// hence relies on the first byte of the hash value for indexing. The items -// that gets inserted into the packer should implement StorageBucketItem -// interface. -type StoragePacker struct { - view logical.Storage - logger log.Logger - storageLocks []*locksutil.LockEntry - viewPrefix string -} - -// BucketPath returns the storage entry key for a given bucket key -func (s *StoragePacker) BucketPath(bucketKey string) string { - return s.viewPrefix + bucketKey -} - -// BucketKeyHash returns the MD5 hash of the bucket storage key in which -// the item will be stored. The choice of MD5 is only for hash performance -// reasons since its value is not used for any security sensitive operation. -func (s *StoragePacker) BucketKeyHashByItemID(itemID string) string { - return s.BucketKeyHashByKey(s.BucketPath(s.BucketKey(itemID))) -} - -// BucketKeyHashByKey returns the MD5 hash of the bucket storage key -func (s *StoragePacker) BucketKeyHashByKey(bucketKey string) string { - hf := md5.New() - hf.Write([]byte(bucketKey)) - return hex.EncodeToString(hf.Sum(nil)) -} - -// View returns the storage view configured to be used by the packer -func (s *StoragePacker) View() logical.Storage { - return s.view -} - -// Get returns a bucket for a given key -func (s *StoragePacker) GetBucket(key string) (*Bucket, error) { - if key == "" { - return nil, fmt.Errorf("missing bucket key") - } - - lock := locksutil.LockForKey(s.storageLocks, key) - lock.RLock() - defer lock.RUnlock() - - // Read from the underlying view - storageEntry, err := s.view.Get(context.Background(), key) - if err != nil { - return nil, errwrap.Wrapf("failed to read packed storage entry: {{err}}", err) - } - if storageEntry == nil { - return nil, nil - } - - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return nil, errwrap.Wrapf("failed to decompress packed storage entry: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - var bucket Bucket - err = proto.Unmarshal(uncompressedData, &bucket) - if err != nil { - return nil, errwrap.Wrapf("failed to decode packed storage entry: {{err}}", err) - } - - return &bucket, nil -} - -// upsert either inserts a new item into the bucket or updates an existing one -// if an item with a matching key is already present. -func (s *Bucket) upsert(item *Item) error { - if s == nil { - return fmt.Errorf("nil storage bucket") - } - - if item == nil { - return fmt.Errorf("nil item") - } - - if item.ID == "" { - return fmt.Errorf("missing item ID") - } - - // Look for an item with matching key and don't modify the collection - // while iterating - foundIdx := -1 - for itemIdx, bucketItems := range s.Items { - if bucketItems.ID == item.ID { - foundIdx = itemIdx - break - } - } - - // If there is no match, append the item, otherwise update it - if foundIdx == -1 { - s.Items = append(s.Items, item) - } else { - s.Items[foundIdx] = item - } - - return nil -} - -// BucketIndex returns the bucket key index for a given storage key -func (s *StoragePacker) BucketIndex(key string) uint8 { - hf := md5.New() - hf.Write([]byte(key)) - return uint8(hf.Sum(nil)[0]) -} - -// BucketKey returns the bucket key for a given item ID -func (s *StoragePacker) BucketKey(itemID string) string { - return strconv.Itoa(int(s.BucketIndex(itemID))) -} - -// DeleteItem removes the storage entry which the given key refers to from its -// corresponding bucket. -func (s *StoragePacker) DeleteItem(itemID string) error { - - if itemID == "" { - return fmt.Errorf("empty item ID") - } - - // Get the bucket key - bucketKey := s.BucketKey(itemID) - - // Prepend the view prefix - bucketPath := s.BucketPath(bucketKey) - - // Read from underlying view - storageEntry, err := s.view.Get(context.Background(), bucketPath) - if err != nil { - return errwrap.Wrapf("failed to read packed storage value: {{err}}", err) - } - if storageEntry == nil { - return nil - } - - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return errwrap.Wrapf("failed to decompress packed storage value: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - var bucket Bucket - err = proto.Unmarshal(uncompressedData, &bucket) - if err != nil { - return errwrap.Wrapf("failed decoding packed storage entry: {{err}}", err) - } - - // Look for a matching storage entry - foundIdx := -1 - for itemIdx, item := range bucket.Items { - if item.ID == itemID { - foundIdx = itemIdx - break - } - } - - // If there is a match, remove it from the collection and persist the - // resulting collection - if foundIdx != -1 { - bucket.Items = append(bucket.Items[:foundIdx], bucket.Items[foundIdx+1:]...) - - // Persist bucket entry only if there is an update - err = s.PutBucket(&bucket) - if err != nil { - return err - } - } - - return nil -} - -// Put stores a packed bucket entry -func (s *StoragePacker) PutBucket(bucket *Bucket) error { - if bucket == nil { - return fmt.Errorf("nil bucket entry") - } - - if bucket.Key == "" { - return fmt.Errorf("missing key") - } - - if !strings.HasPrefix(bucket.Key, s.viewPrefix) { - return fmt.Errorf("incorrect prefix; bucket entry key should have %q prefix", s.viewPrefix) - } - - marshaledBucket, err := proto.Marshal(bucket) - if err != nil { - return errwrap.Wrapf("failed to marshal bucket: {{err}}", err) - } - - compressedBucket, err := compressutil.Compress(marshaledBucket, &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeSnappy, - }) - if err != nil { - return errwrap.Wrapf("failed to compress packed bucket: {{err}}", err) - } - - // Store the compressed value - err = s.view.Put(context.Background(), &logical.StorageEntry{ - Key: bucket.Key, - Value: compressedBucket, - }) - if err != nil { - return errwrap.Wrapf("failed to persist packed storage entry: {{err}}", err) - } - - return nil -} - -// GetItem fetches the storage entry for a given key from its corresponding -// bucket. -func (s *StoragePacker) GetItem(itemID string) (*Item, error) { - if itemID == "" { - return nil, fmt.Errorf("empty item ID") - } - - bucketKey := s.BucketKey(itemID) - bucketPath := s.BucketPath(bucketKey) - - // Fetch the bucket entry - bucket, err := s.GetBucket(bucketPath) - if err != nil { - return nil, errwrap.Wrapf("failed to read packed storage item: {{err}}", err) - } - if bucket == nil { - return nil, nil - } - - // Look for a matching storage entry in the bucket items - for _, item := range bucket.Items { - if item.ID == itemID { - return item, nil - } - } - - return nil, nil -} - -// PutItem stores a storage entry in its corresponding bucket -func (s *StoragePacker) PutItem(item *Item) error { - if item == nil { - return fmt.Errorf("nil item") - } - - if item.ID == "" { - return fmt.Errorf("missing ID in item") - } - - var err error - bucketKey := s.BucketKey(item.ID) - bucketPath := s.BucketPath(bucketKey) - - bucket := &Bucket{ - Key: bucketPath, - } - - // In this case, we persist the storage entry regardless of the read - // storageEntry below is nil or not. Hence, directly acquire write lock - // even to read the entry. - lock := locksutil.LockForKey(s.storageLocks, bucketPath) - lock.Lock() - defer lock.Unlock() - - // Check if there is an existing bucket for a given key - storageEntry, err := s.view.Get(context.Background(), bucketPath) - if err != nil { - return errwrap.Wrapf("failed to read packed storage bucket entry: {{err}}", err) - } - - if storageEntry == nil { - // If the bucket entry does not exist, this will be the only item the - // bucket that is going to be persisted. - bucket.Items = []*Item{ - item, - } - } else { - uncompressedData, notCompressed, err := compressutil.Decompress(storageEntry.Value) - if err != nil { - return errwrap.Wrapf("failed to decompress packed storage entry: {{err}}", err) - } - if notCompressed { - uncompressedData = storageEntry.Value - } - - err = proto.Unmarshal(uncompressedData, bucket) - if err != nil { - return errwrap.Wrapf("failed to decode packed storage entry: {{err}}", err) - } - - err = bucket.upsert(item) - if err != nil { - return errwrap.Wrapf("failed to update entry in packed storage entry: {{err}}", err) - } - } - - // Persist the result - return s.PutBucket(bucket) -} - -// NewStoragePacker creates a new storage packer for a given view -func NewStoragePacker(view logical.Storage, logger log.Logger, viewPrefix string) (*StoragePacker, error) { - if view == nil { - return nil, fmt.Errorf("nil view") - } - - if viewPrefix == "" { - viewPrefix = StoragePackerBucketsPrefix - } - - if !strings.HasSuffix(viewPrefix, "/") { - viewPrefix = viewPrefix + "/" - } - - // Create a new packer object for the given view - packer := &StoragePacker{ - view: view, - viewPrefix: viewPrefix, - logger: logger, - storageLocks: locksutil.CreateLocks(), - } - - return packer, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go b/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go deleted file mode 100644 index 68ba2ef6e..000000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.pb.go +++ /dev/null @@ -1,139 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helper/storagepacker/types.proto - -package storagepacker // import "github.com/hashicorp/vault/helper/storagepacker" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Item struct { - ID string `sentinel:"" protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Message *any.Any `sentinel:"" protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Item) Reset() { *m = Item{} } -func (m *Item) String() string { return proto.CompactTextString(m) } -func (*Item) ProtoMessage() {} -func (*Item) Descriptor() ([]byte, []int) { - return fileDescriptor_types_6092d91e5958c3db, []int{0} -} -func (m *Item) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Item.Unmarshal(m, b) -} -func (m *Item) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Item.Marshal(b, m, deterministic) -} -func (dst *Item) XXX_Merge(src proto.Message) { - xxx_messageInfo_Item.Merge(dst, src) -} -func (m *Item) XXX_Size() int { - return xxx_messageInfo_Item.Size(m) -} -func (m *Item) XXX_DiscardUnknown() { - xxx_messageInfo_Item.DiscardUnknown(m) -} - -var xxx_messageInfo_Item proto.InternalMessageInfo - -func (m *Item) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Item) GetMessage() *any.Any { - if m != nil { - return m.Message - } - return nil -} - -type Bucket struct { - Key string `sentinel:"" protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Items []*Item `sentinel:"" protobuf:"bytes,2,rep,name=items,proto3" json:"items,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Bucket) Reset() { *m = Bucket{} } -func (m *Bucket) String() string { return proto.CompactTextString(m) } -func (*Bucket) ProtoMessage() {} -func (*Bucket) Descriptor() ([]byte, []int) { - return fileDescriptor_types_6092d91e5958c3db, []int{1} -} -func (m *Bucket) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Bucket.Unmarshal(m, b) -} -func (m *Bucket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Bucket.Marshal(b, m, deterministic) -} -func (dst *Bucket) XXX_Merge(src proto.Message) { - xxx_messageInfo_Bucket.Merge(dst, src) -} -func (m *Bucket) XXX_Size() int { - return xxx_messageInfo_Bucket.Size(m) -} -func (m *Bucket) XXX_DiscardUnknown() { - xxx_messageInfo_Bucket.DiscardUnknown(m) -} - -var xxx_messageInfo_Bucket proto.InternalMessageInfo - -func (m *Bucket) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *Bucket) GetItems() []*Item { - if m != nil { - return m.Items - } - return nil -} - -func init() { - proto.RegisterType((*Item)(nil), "storagepacker.Item") - proto.RegisterType((*Bucket)(nil), "storagepacker.Bucket") -} - -func init() { - proto.RegisterFile("helper/storagepacker/types.proto", fileDescriptor_types_6092d91e5958c3db) -} - -var fileDescriptor_types_6092d91e5958c3db = []byte{ - // 219 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x8f, 0x41, 0x4b, 0xc3, 0x40, - 0x10, 0x85, 0x49, 0xaa, 0x15, 0xb7, 0x28, 0xb2, 0x7a, 0x88, 0x9e, 0x42, 0x4f, 0xf1, 0x32, 0x83, - 0xf5, 0x17, 0x58, 0x50, 0xf0, 0x9a, 0xa3, 0xb7, 0x4d, 0x3a, 0x6e, 0x96, 0x64, 0xbb, 0xcb, 0xee, - 0xac, 0xb0, 0xff, 0x5e, 0xda, 0xd8, 0x43, 0xc1, 0xdb, 0xc0, 0xfb, 0xf8, 0xe6, 0x3d, 0x51, 0x0f, - 0x34, 0x79, 0x0a, 0x18, 0xd9, 0x05, 0xa5, 0xc9, 0xab, 0x7e, 0xa4, 0x80, 0x9c, 0x3d, 0x45, 0xf0, - 0xc1, 0xb1, 0x93, 0x37, 0x67, 0xd1, 0xd3, 0xa3, 0x76, 0x4e, 0x4f, 0x84, 0xc7, 0xb0, 0x4b, 0xdf, - 0xa8, 0xf6, 0x79, 0x26, 0xd7, 0x1f, 0xe2, 0xe2, 0x93, 0xc9, 0xca, 0x5b, 0x51, 0x9a, 0x5d, 0x55, - 0xd4, 0x45, 0x73, 0xdd, 0x96, 0x66, 0x27, 0x41, 0x5c, 0x59, 0x8a, 0x51, 0x69, 0xaa, 0xca, 0xba, - 0x68, 0x56, 0x9b, 0x07, 0x98, 0x25, 0x70, 0x92, 0xc0, 0xdb, 0x3e, 0xb7, 0x27, 0x68, 0xfd, 0x2e, - 0x96, 0xdb, 0xd4, 0x8f, 0xc4, 0xf2, 0x4e, 0x2c, 0x46, 0xca, 0x7f, 0xaa, 0xc3, 0x29, 0x9f, 0xc5, - 0xa5, 0x61, 0xb2, 0xb1, 0x2a, 0xeb, 0x45, 0xb3, 0xda, 0xdc, 0xc3, 0x59, 0x3b, 0x38, 0xfc, 0x6f, - 0x67, 0x62, 0xfb, 0xf2, 0x85, 0xda, 0xf0, 0x90, 0x3a, 0xe8, 0x9d, 0xc5, 0x41, 0xc5, 0xc1, 0xf4, - 0x2e, 0x78, 0xfc, 0x51, 0x69, 0x62, 0xfc, 0x6f, 0x77, 0xb7, 0x3c, 0x16, 0x7a, 0xfd, 0x0d, 0x00, - 0x00, 0xff, 0xff, 0x1c, 0x8e, 0xb4, 0xa9, 0x16, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto b/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto deleted file mode 100644 index 8d8a998c9..000000000 --- a/vendor/github.com/hashicorp/vault/helper/storagepacker/types.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/helper/storagepacker"; - -package storagepacker; - -import "google/protobuf/any.proto"; - -message Item { - string id = 1; - google.protobuf.Any message = 2; -} - -message Bucket { - string key = 1; - repeated Item items = 2; -} diff --git a/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go b/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go deleted file mode 100644 index 08b3ebd0c..000000000 --- a/vendor/github.com/hashicorp/vault/helper/tlsutil/tlsutil.go +++ /dev/null @@ -1,54 +0,0 @@ -package tlsutil - -import ( - "crypto/tls" - "fmt" - - "github.com/hashicorp/vault/helper/strutil" -) - -// TLSLookup maps the tls_min_version configuration to the internal value -var TLSLookup = map[string]uint16{ - "tls10": tls.VersionTLS10, - "tls11": tls.VersionTLS11, - "tls12": tls.VersionTLS12, -} - -// ParseCiphers parse ciphersuites from the comma-separated string into recognized slice -func ParseCiphers(cipherStr string) ([]uint16, error) { - suites := []uint16{} - ciphers := strutil.ParseStringSlice(cipherStr, ",") - cipherMap := map[string]uint16{ - "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA, - "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, - "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA, - "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA, - "TLS_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_RSA_WITH_AES_128_CBC_SHA256, - "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256, - "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, - "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, - "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, - } - for _, cipher := range ciphers { - if v, ok := cipherMap[cipher]; ok { - suites = append(suites, v) - } else { - return suites, fmt.Errorf("unsupported cipher %q", cipher) - } - } - - return suites, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/useragent/useragent.go b/vendor/github.com/hashicorp/vault/helper/useragent/useragent.go deleted file mode 100644 index 549b71131..000000000 --- a/vendor/github.com/hashicorp/vault/helper/useragent/useragent.go +++ /dev/null @@ -1,47 +0,0 @@ -package useragent - -import ( - "fmt" - "runtime" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/version" -) - -var ( - // projectURL is the project URL. - projectURL = "https://www.vaultproject.io/" - - // rt is the runtime - variable for tests. - rt = runtime.Version() - - // versionFunc is the func that returns the current version. This is a - // function to take into account the different build processes and distinguish - // between enterprise and oss builds. - versionFunc = func() string { - return version.GetVersion().VersionNumber() - } -) - -// String returns the consistent user-agent string for Vault. -// -// e.g. Vault/0.10.4 (+https://www.vaultproject.io/; go1.10.1) -func String() string { - return fmt.Sprintf("Vault/%s (+%s; %s)", - versionFunc(), projectURL, rt) -} - -// PluginString is usable by plugins to return a user-agent string reflecting -// the running Vault version and an optional plugin name. -// -// e.g. Vault/0.10.4 (+https://www.vaultproject.io/; azure-auth; go1.10.1) -func PluginString(env *logical.PluginEnvironment, pluginName string) string { - var name string - - if pluginName != "" { - name = pluginName + "; " - } - - return fmt.Sprintf("Vault/%s (+%s; %s%s)", - env.VaultVersion, projectURL, name, rt) -} diff --git a/vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go b/vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go deleted file mode 100644 index 9c84a1d47..000000000 --- a/vendor/github.com/hashicorp/vault/helper/wrapping/wrapinfo.go +++ /dev/null @@ -1,37 +0,0 @@ -package wrapping - -import "time" - -type ResponseWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl" sentinel:""` - - // The token containing the wrapped response - Token string `json:"token" structs:"token" mapstructure:"token" sentinel:""` - - // The token accessor for the wrapped response token - Accessor string `json:"accessor" structs:"accessor" mapstructure:"accessor"` - - // The creation time. This can be used with the TTL to figure out an - // expected expiration. - CreationTime time.Time `json:"creation_time" structs:"creation_time" mapstructure:"creation_time" sentinel:""` - - // If the contained response is the output of a token creation call, the - // created token's accessor will be accessible here - WrappedAccessor string `json:"wrapped_accessor" structs:"wrapped_accessor" mapstructure:"wrapped_accessor" sentinel:""` - - // WrappedEntityID is the entity identifier of the caller who initiated the - // wrapping request - WrappedEntityID string `json:"wrapped_entity_id" structs:"wrapped_entity_id" mapstructure:"wrapped_entity_id" sentinel:""` - - // The format to use. This doesn't get returned, it's only internal. - Format string `json:"format" structs:"format" mapstructure:"format" sentinel:""` - - // CreationPath is the original request path that was used to create - // the wrapped response. - CreationPath string `json:"creation_path" structs:"creation_path" mapstructure:"creation_path" sentinel:""` - - // Controls seal wrapping behavior downstream for specific use cases - SealWrap bool `json:"seal_wrap" structs:"seal_wrap" mapstructure:"seal_wrap" sentinel:""` -} diff --git a/vendor/github.com/hashicorp/vault/helper/xor/xor.go b/vendor/github.com/hashicorp/vault/helper/xor/xor.go deleted file mode 100644 index 0d9567eb5..000000000 --- a/vendor/github.com/hashicorp/vault/helper/xor/xor.go +++ /dev/null @@ -1,48 +0,0 @@ -package xor - -import ( - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" -) - -// XORBytes takes two byte slices and XORs them together, returning the final -// byte slice. It is an error to pass in two byte slices that do not have the -// same length. -func XORBytes(a, b []byte) ([]byte, error) { - if len(a) != len(b) { - return nil, fmt.Errorf("length of byte slices is not equivalent: %d != %d", len(a), len(b)) - } - - buf := make([]byte, len(a)) - - for i, _ := range a { - buf[i] = a[i] ^ b[i] - } - - return buf, nil -} - -// XORBase64 takes two base64-encoded strings and XORs the decoded byte slices -// together, returning the final byte slice. It is an error to pass in two -// strings that do not have the same length to their base64-decoded byte slice. -func XORBase64(a, b string) ([]byte, error) { - aBytes, err := base64.StdEncoding.DecodeString(a) - if err != nil { - return nil, errwrap.Wrapf("error decoding first base64 value: {{err}}", err) - } - if aBytes == nil || len(aBytes) == 0 { - return nil, fmt.Errorf("decoded first base64 value is nil or empty") - } - - bBytes, err := base64.StdEncoding.DecodeString(b) - if err != nil { - return nil, errwrap.Wrapf("error decoding second base64 value: {{err}}", err) - } - if bBytes == nil || len(bBytes) == 0 { - return nil, fmt.Errorf("decoded second base64 value is nil or empty") - } - - return XORBytes(aBytes, bBytes) -} diff --git a/vendor/github.com/hashicorp/vault/http/cors.go b/vendor/github.com/hashicorp/vault/http/cors.go deleted file mode 100644 index 9e8b6fa19..000000000 --- a/vendor/github.com/hashicorp/vault/http/cors.go +++ /dev/null @@ -1,67 +0,0 @@ -package http - -import ( - "fmt" - "net/http" - "strings" - - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/vault" -) - -var allowedMethods = []string{ - http.MethodDelete, - http.MethodGet, - http.MethodOptions, - http.MethodPost, - http.MethodPut, - "LIST", // LIST is not an official HTTP method, but Vault supports it. -} - -func wrapCORSHandler(h http.Handler, core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - corsConf := core.CORSConfig() - - // If CORS is not enabled or if no Origin header is present (i.e. the request - // is from the Vault CLI. A browser will always send an Origin header), then - // just return a 204. - if !corsConf.IsEnabled() { - h.ServeHTTP(w, req) - return - } - - origin := req.Header.Get("Origin") - requestMethod := req.Header.Get("Access-Control-Request-Method") - - if origin == "" { - h.ServeHTTP(w, req) - return - } - - // Return a 403 if the origin is not allowed to make cross-origin requests. - if !corsConf.IsValidOrigin(origin) { - respondError(w, http.StatusForbidden, fmt.Errorf("origin not allowed")) - return - } - - if req.Method == http.MethodOptions && !strutil.StrListContains(allowedMethods, requestMethod) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - w.Header().Set("Access-Control-Allow-Origin", origin) - w.Header().Set("Vary", "Origin") - - // apply headers for preflight requests - if req.Method == http.MethodOptions { - w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ",")) - w.Header().Set("Access-Control-Allow-Headers", strings.Join(corsConf.AllowedHeaders, ",")) - w.Header().Set("Access-Control-Max-Age", "300") - - return - } - - h.ServeHTTP(w, req) - return - }) -} diff --git a/vendor/github.com/hashicorp/vault/http/handler.go b/vendor/github.com/hashicorp/vault/http/handler.go deleted file mode 100644 index fd381c896..000000000 --- a/vendor/github.com/hashicorp/vault/http/handler.go +++ /dev/null @@ -1,618 +0,0 @@ -package http - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/textproto" - "net/url" - "os" - "strings" - "time" - - "github.com/NYTimes/gziphandler" - "github.com/elazarl/go-bindata-assetfs" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -const ( - // AuthHeaderName is the name of the header containing the token. - AuthHeaderName = "X-Vault-Token" - - // WrapTTLHeaderName is the name of the header containing a directive to - // wrap the response - WrapTTLHeaderName = "X-Vault-Wrap-TTL" - - // WrapFormatHeaderName is the name of the header containing the format to - // wrap in; has no effect if the wrap TTL is not set - WrapFormatHeaderName = "X-Vault-Wrap-Format" - - // NoRequestForwardingHeaderName is the name of the header telling Vault - // not to use request forwarding - NoRequestForwardingHeaderName = "X-Vault-No-Request-Forwarding" - - // MFAHeaderName represents the HTTP header which carries the credentials - // required to perform MFA on any path. - MFAHeaderName = "X-Vault-MFA" - - // canonicalMFAHeaderName is the MFA header value's format in the request - // headers. Do not alter the casing of this string. - canonicalMFAHeaderName = "X-Vault-Mfa" - - // PolicyOverrideHeaderName is the header set to request overriding - // soft-mandatory Sentinel policies. - PolicyOverrideHeaderName = "X-Vault-Policy-Override" - - // DefaultMaxRequestSize is the default maximum accepted request size. This - // is to prevent a denial of service attack where no Content-Length is - // provided and the server is fed ever more data until it exhausts memory. - // Can be overridden per listener. - DefaultMaxRequestSize = 32 * 1024 * 1024 -) - -var ( - ReplicationStaleReadTimeout = 2 * time.Second - - // Set to false by stub_asset if the ui build tag isn't enabled - uiBuiltIn = true - - injectDataIntoTopRoutes = []string{ - "/v1/sys/audit", - "/v1/sys/audit/", - "/v1/sys/audit-hash/", - "/v1/sys/auth", - "/v1/sys/auth/", - "/v1/sys/config/cors", - "/v1/sys/config/auditing/request-headers/", - "/v1/sys/config/auditing/request-headers", - "/v1/sys/capabilities", - "/v1/sys/capabilities-accessor", - "/v1/sys/capabilities-self", - "/v1/sys/key-status", - "/v1/sys/mounts", - "/v1/sys/mounts/", - "/v1/sys/policy", - "/v1/sys/policy/", - "/v1/sys/rekey/backup", - "/v1/sys/rekey/recovery-key-backup", - "/v1/sys/remount", - "/v1/sys/rotate", - "/v1/sys/wrapping/wrap", - } -) - -// Handler returns an http.Handler for the API. This can be used on -// its own to mount the Vault API within another web server. -func Handler(props *vault.HandlerProperties) http.Handler { - core := props.Core - - // Create the muxer to handle the actual endpoints - mux := http.NewServeMux() - mux.Handle("/v1/sys/init", handleSysInit(core)) - mux.Handle("/v1/sys/seal-status", handleSysSealStatus(core)) - mux.Handle("/v1/sys/seal", handleSysSeal(core)) - mux.Handle("/v1/sys/step-down", handleRequestForwarding(core, handleSysStepDown(core))) - mux.Handle("/v1/sys/unseal", handleSysUnseal(core)) - mux.Handle("/v1/sys/leader", handleSysLeader(core)) - mux.Handle("/v1/sys/health", handleSysHealth(core)) - mux.Handle("/v1/sys/generate-root/attempt", handleRequestForwarding(core, handleSysGenerateRootAttempt(core, vault.GenerateStandardRootTokenStrategy))) - mux.Handle("/v1/sys/generate-root/update", handleRequestForwarding(core, handleSysGenerateRootUpdate(core, vault.GenerateStandardRootTokenStrategy))) - mux.Handle("/v1/sys/rekey/init", handleRequestForwarding(core, handleSysRekeyInit(core, false))) - mux.Handle("/v1/sys/rekey/update", handleRequestForwarding(core, handleSysRekeyUpdate(core, false))) - mux.Handle("/v1/sys/rekey/verify", handleRequestForwarding(core, handleSysRekeyVerify(core, false))) - mux.Handle("/v1/sys/rekey-recovery-key/init", handleRequestForwarding(core, handleSysRekeyInit(core, true))) - mux.Handle("/v1/sys/rekey-recovery-key/update", handleRequestForwarding(core, handleSysRekeyUpdate(core, true))) - mux.Handle("/v1/sys/rekey-recovery-key/verify", handleRequestForwarding(core, handleSysRekeyVerify(core, true))) - mux.Handle("/v1/sys/wrapping/lookup", handleRequestForwarding(core, handleLogical(core, wrappingVerificationFunc))) - mux.Handle("/v1/sys/wrapping/rewrap", handleRequestForwarding(core, handleLogical(core, wrappingVerificationFunc))) - mux.Handle("/v1/sys/wrapping/unwrap", handleRequestForwarding(core, handleLogical(core, wrappingVerificationFunc))) - for _, path := range injectDataIntoTopRoutes { - mux.Handle(path, handleRequestForwarding(core, handleLogicalWithInjector(core, nil))) - } - mux.Handle("/v1/sys/", handleRequestForwarding(core, handleLogical(core, nil))) - mux.Handle("/v1/", handleRequestForwarding(core, handleLogical(core, nil))) - if core.UIEnabled() == true { - if uiBuiltIn { - mux.Handle("/ui/", http.StripPrefix("/ui/", gziphandler.GzipHandler(handleUIHeaders(core, handleUI(http.FileServer(&UIAssetWrapper{FileSystem: assetFS()})))))) - } else { - mux.Handle("/ui/", handleUIHeaders(core, handleUIStub())) - } - mux.Handle("/", handleRootRedirect()) - } - - // Wrap the handler in another handler to trigger all help paths. - helpWrappedHandler := wrapHelpHandler(mux, core) - corsWrappedHandler := wrapCORSHandler(helpWrappedHandler, core) - - // Wrap the help wrapped handler with another layer with a generic - // handler - genericWrappedHandler := wrapGenericHandler(corsWrappedHandler, props.MaxRequestSize, props.MaxRequestDuration) - - // Wrap the handler with PrintablePathCheckHandler to check for non-printable - // characters in the request path. - printablePathCheckHandler := genericWrappedHandler - if !props.DisablePrintableCheck { - printablePathCheckHandler = cleanhttp.PrintablePathCheckHandler(genericWrappedHandler, nil) - } - - return printablePathCheckHandler -} - -// wrapGenericHandler wraps the handler with an extra layer of handler where -// tasks that should be commonly handled for all the requests and/or responses -// are performed. -func wrapGenericHandler(h http.Handler, maxRequestSize int64, maxRequestDuration time.Duration) http.Handler { - if maxRequestDuration == 0 { - maxRequestDuration = vault.DefaultMaxRequestDuration - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Set the Cache-Control header for all the responses returned - // by Vault - w.Header().Set("Cache-Control", "no-store") - - // Start with the request context - ctx := r.Context() - var cancelFunc context.CancelFunc - // Add our timeout - ctx, cancelFunc = context.WithTimeout(ctx, maxRequestDuration) - // Add a size limiter if desired - if maxRequestSize > 0 { - ctx = context.WithValue(ctx, "max_request_size", maxRequestSize) - } - r = r.WithContext(ctx) - h.ServeHTTP(w, r) - cancelFunc() - return - }) -} - -func WrapForwardedForHandler(h http.Handler, authorizedAddrs []*sockaddr.SockAddrMarshaler, rejectNotPresent, rejectNonAuthz bool, hopSkips int) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - headers, headersOK := r.Header[textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")] - if !headersOK || len(headers) == 0 { - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, fmt.Errorf("missing x-forwarded-for header and configured to reject when not present")) - return - } - - host, port, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - // If not rejecting treat it like we just don't have a valid - // header because we can't do a comparison against an address we - // can't understand - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client hostport: {{err}}", err)) - return - } - - addr, err := sockaddr.NewIPAddr(host) - if err != nil { - // We treat this the same as the case above - if !rejectNotPresent { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client address: {{err}}", err)) - return - } - - var found bool - for _, authz := range authorizedAddrs { - if authz.Contains(addr) { - found = true - break - } - } - if !found { - // If we didn't find it and aren't configured to reject, simply - // don't trust it - if !rejectNonAuthz { - h.ServeHTTP(w, r) - return - } - respondError(w, http.StatusBadRequest, fmt.Errorf("client address not authorized for x-forwarded-for and configured to reject connection")) - return - } - - // At this point we have at least one value and it's authorized - - // Split comma separated ones, which are common. This brings it in line - // to the multiple-header case. - var acc []string - for _, header := range headers { - vals := strings.Split(header, ",") - for _, v := range vals { - acc = append(acc, strings.TrimSpace(v)) - } - } - - indexToUse := len(acc) - 1 - hopSkips - if indexToUse < 0 { - // This is likely an error in either configuration or other - // infrastructure. We could either deny the request, or we - // could simply not trust the value. Denying the request is - // "safer" since if this logic is configured at all there may - // be an assumption it can always be trusted. Given that we can - // deny accepting the request at all if it's not from an - // authorized address, if we're at this point the address is - // authorized (or we've turned off explicit rejection) and we - // should assume that what comes in should be properly - // formatted. - respondError(w, http.StatusBadRequest, fmt.Errorf("malformed x-forwarded-for configuration or request, hops to skip (%d) would skip before earliest chain link (chain length %d)", hopSkips, len(headers))) - return - } - - r.RemoteAddr = net.JoinHostPort(acc[indexToUse], port) - h.ServeHTTP(w, r) - return - }) -} - -// A lookup on a token that is about to expire returns nil, which means by the -// time we can validate a wrapping token lookup will return nil since it will -// be revoked after the call. So we have to do the validation here. -func wrappingVerificationFunc(core *vault.Core, req *logical.Request) error { - if req == nil { - return fmt.Errorf("invalid request") - } - - valid, err := core.ValidateWrappingToken(req) - if err != nil { - return errwrap.Wrapf("error validating wrapping token: {{err}}", err) - } - if !valid { - return fmt.Errorf("wrapping token is not valid or does not exist") - } - - return nil -} - -// stripPrefix is a helper to strip a prefix from the path. It will -// return false from the second return value if it the prefix doesn't exist. -func stripPrefix(prefix, path string) (string, bool) { - if !strings.HasPrefix(path, prefix) { - return "", false - } - - path = path[len(prefix):] - if path == "" { - return "", false - } - - return path, true -} - -func handleUIHeaders(core *vault.Core, h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - header := w.Header() - - userHeaders, err := core.UIHeaders() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if userHeaders != nil { - for k := range userHeaders { - v := userHeaders.Get(k) - header.Set(k, v) - } - } - h.ServeHTTP(w, req) - }) -} - -func handleUI(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - - // The fileserver handler strips trailing slashes and does a redirect. - // We don't want the redirect to happen so we preemptively trim the slash - // here. - req.URL.Path = strings.TrimSuffix(req.URL.Path, "/") - h.ServeHTTP(w, req) - return - }) -} - -func handleUIStub() http.Handler { - stubHTML := ` - - -

Vault UI is not available in this binary. To get Vault UI do one of the following:

-
    -
  • Download an official release
  • -
  • Run make release to create your own release binaries. -
  • Run make dev-ui to create a development binary with the UI. -
- - ` - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte(stubHTML)) - }) -} - -func handleRootRedirect() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - http.Redirect(w, req, "/ui/", 307) - return - }) -} - -type UIAssetWrapper struct { - FileSystem *assetfs.AssetFS -} - -func (fs *UIAssetWrapper) Open(name string) (http.File, error) { - file, err := fs.FileSystem.Open(name) - if err == nil { - return file, nil - } - // serve index.html instead of 404ing - if err == os.ErrNotExist { - return fs.FileSystem.Open("index.html") - } - return nil, err -} - -func parseRequest(r *http.Request, w http.ResponseWriter, out interface{}) error { - // Limit the maximum number of bytes to MaxRequestSize to protect - // against an indefinite amount of data being read. - reader := r.Body - ctx := r.Context() - maxRequestSize := ctx.Value("max_request_size") - if maxRequestSize != nil { - max, ok := maxRequestSize.(int64) - if !ok { - return errors.New("could not parse max_request_size from request context") - } - if max > 0 { - reader = http.MaxBytesReader(w, r.Body, max) - } - } - err := jsonutil.DecodeJSONFromReader(reader, out) - if err != nil && err != io.EOF { - return errwrap.Wrapf("failed to parse JSON input: {{err}}", err) - } - return err -} - -// handleRequestForwarding determines whether to forward a request or not, -// falling back on the older behavior of redirecting the client -func handleRequestForwarding(core *vault.Core, handler http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get(vault.IntNoForwardingHeaderName) != "" { - handler.ServeHTTP(w, r) - return - } - - if r.Header.Get(NoRequestForwardingHeaderName) != "" { - // Forwarding explicitly disabled, fall back to previous behavior - core.Logger().Debug("handleRequestForwarding: forwarding disabled by client request") - handler.ServeHTTP(w, r) - return - } - - // Note: in an HA setup, this call will also ensure that connections to - // the leader are set up, as that happens once the advertised cluster - // values are read during this function - isLeader, leaderAddr, _, err := core.Leader() - if err != nil { - if err == vault.ErrHANotEnabled { - // Standalone node, serve request normally - handler.ServeHTTP(w, r) - return - } - // Some internal error occurred - respondError(w, http.StatusInternalServerError, err) - return - } - if isLeader { - // No forwarding needed, we're leader - handler.ServeHTTP(w, r) - return - } - if leaderAddr == "" { - respondError(w, http.StatusInternalServerError, fmt.Errorf("local node not active but active cluster node not found")) - return - } - - // Attempt forwarding the request. If we cannot forward -- perhaps it's - // been disabled on the active node -- this will return with an - // ErrCannotForward and we simply fall back - statusCode, header, retBytes, err := core.ForwardRequest(r) - if err != nil { - if err == vault.ErrCannotForward { - core.Logger().Debug("handleRequestForwarding: cannot forward (possibly disabled on active node), falling back") - } else { - core.Logger().Error("handleRequestForwarding: error forwarding request", "error", err) - } - - // Fall back to redirection - handler.ServeHTTP(w, r) - return - } - - if header != nil { - for k, v := range header { - w.Header()[k] = v - } - } - - w.WriteHeader(statusCode) - w.Write(retBytes) - return - }) -} - -// request is a helper to perform a request and properly exit in the -// case of an error. -func request(core *vault.Core, w http.ResponseWriter, rawReq *http.Request, r *logical.Request) (*logical.Response, bool) { - resp, err := core.HandleRequest(rawReq.Context(), r) - if errwrap.Contains(err, consts.ErrStandby.Error()) { - respondStandby(core, w, rawReq.URL) - return resp, false - } - if respondErrorCommon(w, r, resp, err) { - return resp, false - } - - return resp, true -} - -// respondStandby is used to trigger a redirect in the case that this Vault is currently a hot standby -func respondStandby(core *vault.Core, w http.ResponseWriter, reqURL *url.URL) { - // Request the leader address - _, redirectAddr, _, err := core.Leader() - if err != nil { - if err == vault.ErrHANotEnabled { - // Standalone node, serve 503 - err = errors.New("node is not active") - respondError(w, http.StatusServiceUnavailable, err) - return - } - - respondError(w, http.StatusInternalServerError, err) - return - } - - // If there is no leader, generate a 503 error - if redirectAddr == "" { - err = errors.New("no active Vault instance found") - respondError(w, http.StatusServiceUnavailable, err) - return - } - - // Parse the redirect location - redirectURL, err := url.Parse(redirectAddr) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Generate a redirect URL - finalURL := url.URL{ - Scheme: redirectURL.Scheme, - Host: redirectURL.Host, - Path: reqURL.Path, - RawQuery: reqURL.RawQuery, - } - - // Ensure there is a scheme, default to https - if finalURL.Scheme == "" { - finalURL.Scheme = "https" - } - - // If we have an address, redirect! We use a 307 code - // because we don't actually know if its permanent and - // the request method should be preserved. - w.Header().Set("Location", finalURL.String()) - w.WriteHeader(307) -} - -// requestAuth adds the token to the logical.Request if it exists. -func requestAuth(core *vault.Core, r *http.Request, req *logical.Request) *logical.Request { - // Attach the header value if we have it - if v := r.Header.Get(AuthHeaderName); v != "" { - req.ClientToken = v - - // Also attach the accessor if we have it. This doesn't fail if it - // doesn't exist because the request may be to an unauthenticated - // endpoint/login endpoint where a bad current token doesn't matter, or - // a token from a Vault version pre-accessors. - te, err := core.LookupToken(v) - if err == nil && te != nil { - req.ClientTokenAccessor = te.Accessor - req.ClientTokenRemainingUses = te.NumUses - req.SetTokenEntry(te) - } - } - - return req -} - -// requestWrapInfo adds the WrapInfo value to the logical.Request if wrap info exists -func requestWrapInfo(r *http.Request, req *logical.Request) (*logical.Request, error) { - // First try for the header value - wrapTTL := r.Header.Get(WrapTTLHeaderName) - if wrapTTL == "" { - return req, nil - } - - // If it has an allowed suffix parse as a duration string - dur, err := parseutil.ParseDurationSecond(wrapTTL) - if err != nil { - return req, err - } - if int64(dur) < 0 { - return req, fmt.Errorf("requested wrap ttl cannot be negative") - } - - req.WrapInfo = &logical.RequestWrapInfo{ - TTL: dur, - } - - wrapFormat := r.Header.Get(WrapFormatHeaderName) - switch wrapFormat { - case "jwt": - req.WrapInfo.Format = "jwt" - } - - return req, nil -} - -func respondError(w http.ResponseWriter, status int, err error) { - logical.AdjustErrorStatusCode(&status, err) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - - resp := &ErrorResponse{Errors: make([]string, 0, 1)} - if err != nil { - resp.Errors = append(resp.Errors, err.Error()) - } - - enc := json.NewEncoder(w) - enc.Encode(resp) -} - -func respondErrorCommon(w http.ResponseWriter, req *logical.Request, resp *logical.Response, err error) bool { - statusCode, newErr := logical.RespondErrorCommon(req, resp, err) - if newErr == nil && statusCode == 0 { - return false - } - - respondError(w, statusCode, newErr) - return true -} - -func respondOk(w http.ResponseWriter, body interface{}) { - w.Header().Set("Content-Type", "application/json") - - if body == nil { - w.WriteHeader(http.StatusNoContent) - } else { - w.WriteHeader(http.StatusOK) - enc := json.NewEncoder(w) - enc.Encode(body) - } -} - -type ErrorResponse struct { - Errors []string `json:"errors"` -} diff --git a/vendor/github.com/hashicorp/vault/http/help.go b/vendor/github.com/hashicorp/vault/http/help.go deleted file mode 100644 index 597fbb097..000000000 --- a/vendor/github.com/hashicorp/vault/http/help.go +++ /dev/null @@ -1,47 +0,0 @@ -package http - -import ( - "net/http" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -func wrapHelpHandler(h http.Handler, core *vault.Core) http.Handler { - return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) { - // If the help parameter is not blank, then show the help. We request - // forward because standby nodes do not have mounts and other state. - if v := req.URL.Query().Get("help"); v != "" || req.Method == "HELP" { - handleRequestForwarding(core, - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handleHelp(core, w, r) - })).ServeHTTP(writer, req) - return - } - - h.ServeHTTP(writer, req) - return - }) -} - -func handleHelp(core *vault.Core, w http.ResponseWriter, req *http.Request) { - path, ok := stripPrefix("/v1/", req.URL.Path) - if !ok { - respondError(w, http.StatusNotFound, nil) - return - } - - lreq := requestAuth(core, req, &logical.Request{ - Operation: logical.HelpOperation, - Path: path, - Connection: getConnection(req), - }) - - resp, err := core.HandleRequest(req.Context(), lreq) - if err != nil { - respondErrorCommon(w, lreq, resp, err) - return - } - - respondOk(w, resp.Data) -} diff --git a/vendor/github.com/hashicorp/vault/http/logical.go b/vendor/github.com/hashicorp/vault/http/logical.go deleted file mode 100644 index e515e6dee..000000000 --- a/vendor/github.com/hashicorp/vault/http/logical.go +++ /dev/null @@ -1,329 +0,0 @@ -package http - -import ( - "encoding/base64" - "encoding/json" - "io" - "net" - "net/http" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" -) - -type PrepareRequestFunc func(*vault.Core, *logical.Request) error - -func buildLogicalRequest(core *vault.Core, w http.ResponseWriter, r *http.Request) (*logical.Request, int, error) { - // Determine the path... - if !strings.HasPrefix(r.URL.Path, "/v1/") { - return nil, http.StatusNotFound, nil - } - path := r.URL.Path[len("/v1/"):] - if path == "" { - return nil, http.StatusNotFound, nil - } - - var data map[string]interface{} - - // Determine the operation - var op logical.Operation - switch r.Method { - case "DELETE": - op = logical.DeleteOperation - - case "GET": - op = logical.ReadOperation - queryVals := r.URL.Query() - var list bool - var err error - listStr := queryVals.Get("list") - if listStr != "" { - list, err = strconv.ParseBool(listStr) - if err != nil { - return nil, http.StatusBadRequest, nil - } - if list { - op = logical.ListOperation - if !strings.HasSuffix(path, "/") { - path += "/" - } - } - } - - if !list { - getData := map[string]interface{}{} - - for k, v := range r.URL.Query() { - // Skip the help key as this is a reserved parameter - if k == "help" { - continue - } - - switch { - case len(v) == 0: - case len(v) == 1: - getData[k] = v[0] - default: - getData[k] = v - } - } - - if len(getData) > 0 { - data = getData - } - } - - case "POST", "PUT": - op = logical.UpdateOperation - // Parse the request if we can - if op == logical.UpdateOperation { - err := parseRequest(r, w, &data) - if err == io.EOF { - data = nil - err = nil - } - if err != nil { - return nil, http.StatusBadRequest, err - } - } - - case "LIST": - op = logical.ListOperation - if !strings.HasSuffix(path, "/") { - path += "/" - } - - case "OPTIONS": - default: - return nil, http.StatusMethodNotAllowed, nil - } - - var err error - request_id, err := uuid.GenerateUUID() - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf("failed to generate identifier for the request: {{err}}", err) - } - - req := requestAuth(core, r, &logical.Request{ - ID: request_id, - Operation: op, - Path: path, - Data: data, - Connection: getConnection(r), - Headers: r.Header, - }) - - req, err = requestWrapInfo(r, req) - if err != nil { - return nil, http.StatusBadRequest, errwrap.Wrapf("error parsing X-Vault-Wrap-TTL header: {{err}}", err) - } - - return req, 0, nil -} - -func handleLogical(core *vault.Core, prepareRequestCallback PrepareRequestFunc) http.Handler { - return handleLogicalInternal(core, false, prepareRequestCallback) -} - -func handleLogicalWithInjector(core *vault.Core, prepareRequestCallback PrepareRequestFunc) http.Handler { - return handleLogicalInternal(core, true, prepareRequestCallback) -} - -func handleLogicalInternal(core *vault.Core, injectDataIntoTopLevel bool, prepareRequestCallback PrepareRequestFunc) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - // Certain endpoints may require changes to the request object. They - // will have a callback registered to do the needed operations, so - // invoke it before proceeding. - if prepareRequestCallback != nil { - if err := prepareRequestCallback(core, req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - } - - // Make the internal request. We attach the connection info - // as well in case this is an authentication request that requires - // it. Vault core handles stripping this if we need to. This also - // handles all error cases; if we hit respondLogical, the request is a - // success. - resp, ok := request(core, w, r, req) - if !ok { - return - } - - // Build the proper response - respondLogical(w, r, req, resp, injectDataIntoTopLevel) - }) -} - -func respondLogical(w http.ResponseWriter, r *http.Request, req *logical.Request, resp *logical.Response, injectDataIntoTopLevel bool) { - var httpResp *logical.HTTPResponse - var ret interface{} - - if resp != nil { - if resp.Redirect != "" { - // If we have a redirect, redirect! We use a 307 code - // because we don't actually know if its permanent. - http.Redirect(w, r, resp.Redirect, 307) - return - } - - // Check if this is a raw response - if _, ok := resp.Data[logical.HTTPStatusCode]; ok { - respondRaw(w, r, resp) - return - } - - if resp.WrapInfo != nil && resp.WrapInfo.Token != "" { - httpResp = &logical.HTTPResponse{ - WrapInfo: &logical.HTTPWrapInfo{ - Token: resp.WrapInfo.Token, - Accessor: resp.WrapInfo.Accessor, - TTL: int(resp.WrapInfo.TTL.Seconds()), - CreationTime: resp.WrapInfo.CreationTime.Format(time.RFC3339Nano), - CreationPath: resp.WrapInfo.CreationPath, - WrappedAccessor: resp.WrapInfo.WrappedAccessor, - }, - } - } else { - httpResp = logical.LogicalResponseToHTTPResponse(resp) - httpResp.RequestID = req.ID - } - - ret = httpResp - - if injectDataIntoTopLevel { - injector := logical.HTTPSysInjector{ - Response: httpResp, - } - ret = injector - } - } - - // Respond - respondOk(w, ret) - return -} - -// respondRaw is used when the response is using HTTPContentType and HTTPRawBody -// to change the default response handling. This is only used for specific things like -// returning the CRL information on the PKI backends. -func respondRaw(w http.ResponseWriter, r *http.Request, resp *logical.Response) { - retErr := func(w http.ResponseWriter, err string) { - w.Header().Set("X-Vault-Raw-Error", err) - w.WriteHeader(http.StatusInternalServerError) - w.Write(nil) - } - - // Ensure this is never a secret or auth response - if resp.Secret != nil || resp.Auth != nil { - retErr(w, "raw responses cannot contain secrets or auth") - return - } - - // Get the status code - statusRaw, ok := resp.Data[logical.HTTPStatusCode] - if !ok { - retErr(w, "no status code given") - return - } - - var status int - switch statusRaw.(type) { - case int: - status = statusRaw.(int) - case float64: - status = int(statusRaw.(float64)) - case json.Number: - s64, err := statusRaw.(json.Number).Float64() - if err != nil { - retErr(w, "cannot decode status code") - return - } - status = int(s64) - default: - retErr(w, "cannot decode status code") - return - } - - nonEmpty := status != http.StatusNoContent - - var contentType string - var body []byte - - // Get the content type header; don't require it if the body is empty - contentTypeRaw, ok := resp.Data[logical.HTTPContentType] - if !ok && nonEmpty { - retErr(w, "no content type given") - return - } - if ok { - contentType, ok = contentTypeRaw.(string) - if !ok { - retErr(w, "cannot decode content type") - return - } - } - - if nonEmpty { - // Get the body - bodyRaw, ok := resp.Data[logical.HTTPRawBody] - if !ok { - goto WRITE_RESPONSE - } - - switch bodyRaw.(type) { - case string: - // This is best effort. The value may already be base64-decoded so - // if it doesn't work we just use as-is - bodyDec, err := base64.StdEncoding.DecodeString(bodyRaw.(string)) - if err == nil { - body = bodyDec - } else { - body = []byte(bodyRaw.(string)) - } - case []byte: - body = bodyRaw.([]byte) - default: - retErr(w, "cannot decode body") - return - } - } - -WRITE_RESPONSE: - // Write the response - if contentType != "" { - w.Header().Set("Content-Type", contentType) - } - - w.WriteHeader(status) - w.Write(body) -} - -// getConnection is used to format the connection information for -// attaching to a logical request -func getConnection(r *http.Request) (connection *logical.Connection) { - var remoteAddr string - - remoteAddr, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - remoteAddr = "" - } - - connection = &logical.Connection{ - RemoteAddr: remoteAddr, - ConnState: r.TLS, - } - return -} diff --git a/vendor/github.com/hashicorp/vault/http/stub_assets.go b/vendor/github.com/hashicorp/vault/http/stub_assets.go deleted file mode 100644 index c64ac582a..000000000 --- a/vendor/github.com/hashicorp/vault/http/stub_assets.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !ui - -package http - -import ( - assetfs "github.com/elazarl/go-bindata-assetfs" -) - -func init() { - uiBuiltIn = false -} - -// assetFS is a stub for building Vault without a UI. -func assetFS() *assetfs.AssetFS { - return nil -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_generate_root.go b/vendor/github.com/hashicorp/vault/http/sys_generate_root.go deleted file mode 100644 index 74456b943..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_generate_root.go +++ /dev/null @@ -1,192 +0,0 @@ -package http - -import ( - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/vault/vault" -) - -func handleSysGenerateRootAttempt(core *vault.Core, generateStrategy vault.GenerateRootStrategy) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysGenerateRootAttemptGet(core, w, r) - case "POST", "PUT": - handleSysGenerateRootAttemptPut(core, w, r, generateStrategy) - case "DELETE": - handleSysGenerateRootAttemptDelete(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysGenerateRootAttemptGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ctx, cancel := core.GetContext() - defer cancel() - - // Get the current seal configuration - barrierConfig, err := core.SealAccess().BarrierConfig(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - sealConfig := barrierConfig - if core.SealAccess().RecoveryKeySupported() { - sealConfig, err = core.SealAccess().RecoveryConfig(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - } - - // Get the generation configuration - generationConfig, err := core.GenerateRootConfiguration() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Get the progress - progress, err := core.GenerateRootProgress() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - // Format the status - status := &GenerateRootStatusResponse{ - Started: false, - Progress: progress, - Required: sealConfig.SecretThreshold, - Complete: false, - } - if generationConfig != nil { - status.Nonce = generationConfig.Nonce - status.Started = true - status.PGPFingerprint = generationConfig.PGPFingerprint - } - - respondOk(w, status) -} - -func handleSysGenerateRootAttemptPut(core *vault.Core, w http.ResponseWriter, r *http.Request, generateStrategy vault.GenerateRootStrategy) { - // Parse the request - var req GenerateRootInitRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - if len(req.OTP) > 0 && len(req.PGPKey) > 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("only one of \"otp\" and \"pgp_key\" must be specified")) - return - } - - // Attemptialize the generation - err := core.GenerateRootInit(req.OTP, req.PGPKey, generateStrategy) - if err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - handleSysGenerateRootAttemptGet(core, w, r) -} - -func handleSysGenerateRootAttemptDelete(core *vault.Core, w http.ResponseWriter, r *http.Request) { - err := core.GenerateRootCancel() - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - respondOk(w, nil) -} - -func handleSysGenerateRootUpdate(core *vault.Core, generateStrategy vault.GenerateRootStrategy) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Parse the request - var req GenerateRootUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on root generation - result, err := core.GenerateRootUpdate(ctx, key, req.Nonce, generateStrategy) - if err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - resp := &GenerateRootStatusResponse{ - Complete: result.Progress == result.Required, - Nonce: req.Nonce, - Progress: result.Progress, - Required: result.Required, - Started: true, - EncodedToken: result.EncodedToken, - PGPFingerprint: result.PGPFingerprint, - } - - if generateStrategy == vault.GenerateStandardRootTokenStrategy { - resp.EncodedRootToken = result.EncodedToken - } - - respondOk(w, resp) - }) -} - -type GenerateRootInitRequest struct { - OTP string `json:"otp"` - PGPKey string `json:"pgp_key"` -} - -type GenerateRootStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - Progress int `json:"progress"` - Required int `json:"required"` - Complete bool `json:"complete"` - EncodedToken string `json:"encoded_token"` - EncodedRootToken string `json:"encoded_root_token"` - PGPFingerprint string `json:"pgp_fingerprint"` -} - -type GenerateRootUpdateRequest struct { - Nonce string - Key string -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_health.go b/vendor/github.com/hashicorp/vault/http/sys_health.go deleted file mode 100644 index 089b9949a..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_health.go +++ /dev/null @@ -1,196 +0,0 @@ -package http - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/vault" - "github.com/hashicorp/vault/version" -) - -func handleSysHealth(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysHealthGet(core, w, r) - case "HEAD": - handleSysHealthHead(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func fetchStatusCode(r *http.Request, field string) (int, bool, bool) { - var err error - statusCode := http.StatusOK - if statusCodeStr, statusCodeOk := r.URL.Query()[field]; statusCodeOk { - statusCode, err = strconv.Atoi(statusCodeStr[0]) - if err != nil || len(statusCodeStr) < 1 { - return http.StatusBadRequest, false, false - } - return statusCode, true, true - } - return statusCode, false, true -} - -func handleSysHealthGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - code, body, err := getSysHealth(core, r) - if err != nil { - core.Logger().Error("error checking health", "error", err) - respondError(w, http.StatusInternalServerError, nil) - return - } - - if body == nil { - respondError(w, code, nil) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(code) - - // Generate the response - enc := json.NewEncoder(w) - enc.Encode(body) -} - -func handleSysHealthHead(core *vault.Core, w http.ResponseWriter, r *http.Request) { - code, body, err := getSysHealth(core, r) - if err != nil { - code = http.StatusInternalServerError - } - - if body != nil { - w.Header().Set("Content-Type", "application/json") - } - w.WriteHeader(code) -} - -func getSysHealth(core *vault.Core, r *http.Request) (int, *HealthResponse, error) { - // Check if being a standby is allowed for the purpose of a 200 OK - _, standbyOK := r.URL.Query()["standbyok"] - _, perfStandbyOK := r.URL.Query()["perfstandbyok"] - - uninitCode := http.StatusNotImplemented - if code, found, ok := fetchStatusCode(r, "uninitcode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - uninitCode = code - } - - sealedCode := http.StatusServiceUnavailable - if code, found, ok := fetchStatusCode(r, "sealedcode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - sealedCode = code - } - - standbyCode := http.StatusTooManyRequests // Consul warning code - if code, found, ok := fetchStatusCode(r, "standbycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - standbyCode = code - } - - activeCode := http.StatusOK - if code, found, ok := fetchStatusCode(r, "activecode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - activeCode = code - } - - drSecondaryCode := 472 // unofficial 4xx status code - if code, found, ok := fetchStatusCode(r, "drsecondarycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - drSecondaryCode = code - } - - perfStandbyCode := 473 // unofficial 4xx status code - if code, found, ok := fetchStatusCode(r, "performancestandbycode"); !ok { - return http.StatusBadRequest, nil, nil - } else if found { - perfStandbyCode = code - } - - ctx := context.Background() - - // Check system status - sealed := core.Sealed() - standby, _ := core.Standby() - perfStandby := core.PerfStandby() - var replicationState consts.ReplicationState - if standby { - replicationState = core.ActiveNodeReplicationState() - } else { - replicationState = core.ReplicationState() - } - - init, err := core.Initialized(ctx) - if err != nil { - return http.StatusInternalServerError, nil, err - } - - // Determine the status code - code := activeCode - switch { - case !init: - code = uninitCode - case sealed: - code = sealedCode - case replicationState.HasState(consts.ReplicationDRSecondary): - code = drSecondaryCode - case !perfStandbyOK && perfStandby: - code = perfStandbyCode - case !standbyOK && standby: - code = standbyCode - } - - // Fetch the local cluster name and identifier - var clusterName, clusterID string - if !sealed { - cluster, err := core.Cluster(ctx) - if err != nil { - return http.StatusInternalServerError, nil, err - } - if cluster == nil { - return http.StatusInternalServerError, nil, fmt.Errorf("failed to fetch cluster details") - } - clusterName = cluster.Name - clusterID = cluster.ID - } - - // Format the body - body := &HealthResponse{ - Initialized: init, - Sealed: sealed, - Standby: standby, - PerformanceStandby: perfStandby, - ReplicationPerformanceMode: replicationState.GetPerformanceString(), - ReplicationDRMode: replicationState.GetDRString(), - ServerTimeUTC: time.Now().UTC().Unix(), - Version: version.GetVersion().VersionNumber(), - ClusterName: clusterName, - ClusterID: clusterID, - } - return code, body, nil -} - -type HealthResponse struct { - Initialized bool `json:"initialized"` - Sealed bool `json:"sealed"` - Standby bool `json:"standby"` - PerformanceStandby bool `json:"performance_standby"` - ReplicationPerformanceMode string `json:"replication_performance_mode"` - ReplicationDRMode string `json:"replication_dr_mode"` - ServerTimeUTC int64 `json:"server_time_utc"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_init.go b/vendor/github.com/hashicorp/vault/http/sys_init.go deleted file mode 100644 index f13ff5d3b..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_init.go +++ /dev/null @@ -1,165 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/vault" -) - -func handleSysInit(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysInitGet(core, w, r) - case "PUT", "POST": - handleSysInitPut(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysInitGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - init, err := core.Initialized(context.Background()) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - respondOk(w, &InitStatusResponse{ - Initialized: init, - }) -} - -func handleSysInitPut(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - // Parse the request - var req InitRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - // Initialize - barrierConfig := &vault.SealConfig{ - SecretShares: req.SecretShares, - SecretThreshold: req.SecretThreshold, - StoredShares: req.StoredShares, - PGPKeys: req.PGPKeys, - } - - recoveryConfig := &vault.SealConfig{ - SecretShares: req.RecoveryShares, - SecretThreshold: req.RecoveryThreshold, - PGPKeys: req.RecoveryPGPKeys, - } - - // N.B. Although the core is capable of handling situations where some keys - // are stored and some aren't, in practice, replication + HSMs makes this - // extremely hard to reason about, to the point that it will probably never - // be supported. The reason is that each HSM needs to encode the master key - // separately, which means the shares must be generated independently, - // which means both that the shares will be different *AND* there would - // need to be a way to actually allow fetching of the generated keys by - // operators. - if core.SealAccess().StoredKeysSupported() { - if len(barrierConfig.PGPKeys) > 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("PGP keys not supported when storing shares")) - return - } - barrierConfig.SecretShares = 1 - barrierConfig.SecretThreshold = 1 - barrierConfig.StoredShares = 1 - core.Logger().Warn("init: stored keys supported, forcing shares/threshold to 1") - } else { - if barrierConfig.StoredShares > 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("stored keys are not supported by the current seal type")) - return - } - } - - if len(barrierConfig.PGPKeys) > 0 && len(barrierConfig.PGPKeys) != barrierConfig.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys")) - return - } - - if core.SealAccess().RecoveryKeySupported() { - if len(recoveryConfig.PGPKeys) > 0 && len(recoveryConfig.PGPKeys) != recoveryConfig.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys for recovery")) - return - } - } - - initParams := &vault.InitParams{ - BarrierConfig: barrierConfig, - RecoveryConfig: recoveryConfig, - RootTokenPGPKey: req.RootTokenPGPKey, - } - - result, initErr := core.Initialize(ctx, initParams) - if initErr != nil { - if !errwrap.ContainsType(initErr, new(vault.NonFatalError)) { - respondError(w, http.StatusBadRequest, initErr) - return - } else { - // Add a warnings field? The error will be logged in the vault log - // already. - } - } - - // Encode the keys - keys := make([]string, 0, len(result.SecretShares)) - keysB64 := make([]string, 0, len(result.SecretShares)) - for _, k := range result.SecretShares { - keys = append(keys, hex.EncodeToString(k)) - keysB64 = append(keysB64, base64.StdEncoding.EncodeToString(k)) - } - - resp := &InitResponse{ - Keys: keys, - KeysB64: keysB64, - RootToken: result.RootToken, - } - - if len(result.RecoveryShares) > 0 { - resp.RecoveryKeys = make([]string, 0, len(result.RecoveryShares)) - resp.RecoveryKeysB64 = make([]string, 0, len(result.RecoveryShares)) - for _, k := range result.RecoveryShares { - resp.RecoveryKeys = append(resp.RecoveryKeys, hex.EncodeToString(k)) - resp.RecoveryKeysB64 = append(resp.RecoveryKeysB64, base64.StdEncoding.EncodeToString(k)) - } - } - - core.UnsealWithStoredKeys(ctx) - - respondOk(w, resp) -} - -type InitRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - RecoveryShares int `json:"recovery_shares"` - RecoveryThreshold int `json:"recovery_threshold"` - RecoveryPGPKeys []string `json:"recovery_pgp_keys"` - RootTokenPGPKey string `json:"root_token_pgp_key"` -} - -type InitResponse struct { - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - RecoveryKeys []string `json:"recovery_keys,omitempty"` - RecoveryKeysB64 []string `json:"recovery_keys_base64,omitempty"` - RootToken string `json:"root_token"` -} - -type InitStatusResponse struct { - Initialized bool `json:"initialized"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_leader.go b/vendor/github.com/hashicorp/vault/http/sys_leader.go deleted file mode 100644 index 0f5305a3f..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_leader.go +++ /dev/null @@ -1,53 +0,0 @@ -package http - -import ( - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/vault" -) - -func handleSysLeader(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "GET": - handleSysLeaderGet(core, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysLeaderGet(core *vault.Core, w http.ResponseWriter, r *http.Request) { - haEnabled := true - isLeader, address, clusterAddr, err := core.Leader() - if errwrap.Contains(err, vault.ErrHANotEnabled.Error()) { - haEnabled = false - err = nil - } - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - resp := &LeaderResponse{ - HAEnabled: haEnabled, - IsSelf: isLeader, - LeaderAddress: address, - LeaderClusterAddress: clusterAddr, - PerfStandby: core.PerfStandby(), - } - if resp.PerfStandby { - resp.PerfStandbyLastRemoteWAL = vault.LastRemoteWAL(core) - } - - respondOk(w, resp) -} - -type LeaderResponse struct { - HAEnabled bool `json:"ha_enabled"` - IsSelf bool `json:"is_self"` - LeaderAddress string `json:"leader_address"` - LeaderClusterAddress string `json:"leader_cluster_address"` - PerfStandby bool `json:"performance_standby"` - PerfStandbyLastRemoteWAL uint64 `json:"performance_standby_last_remote_wal"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_rekey.go b/vendor/github.com/hashicorp/vault/http/sys_rekey.go deleted file mode 100644 index 54149c448..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_rekey.go +++ /dev/null @@ -1,411 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/vault" -) - -func handleSysRekeyInit(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - repState := core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - respondError(w, http.StatusBadRequest, - fmt.Errorf("rekeying can only be performed on the primary cluster when replication is activated")) - return - } - - ctx, cancel := core.GetContext() - defer cancel() - - switch { - case recovery && !core.SealAccess().RecoveryKeySupported(): - respondError(w, http.StatusBadRequest, fmt.Errorf("recovery rekeying not supported")) - case r.Method == "GET": - handleSysRekeyInitGet(ctx, core, recovery, w, r) - case r.Method == "POST" || r.Method == "PUT": - handleSysRekeyInitPut(ctx, core, recovery, w, r) - case r.Method == "DELETE": - handleSysRekeyInitDelete(ctx, core, recovery, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysRekeyInitGet(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - barrierConfig, barrierConfErr := core.SealAccess().BarrierConfig(ctx) - if barrierConfErr != nil { - respondError(w, http.StatusInternalServerError, barrierConfErr) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - // Get the rekey configuration - rekeyConf, err := core.RekeyConfig(recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - sealThreshold, err := core.RekeyThreshold(ctx, recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - // Format the status - status := &RekeyStatusResponse{ - Started: false, - T: 0, - N: 0, - Required: sealThreshold, - } - if rekeyConf != nil { - // Get the progress - started, progress, err := core.RekeyProgress(recovery, false) - if err != nil { - respondError(w, err.Code(), err) - return - } - - status.Nonce = rekeyConf.Nonce - status.Started = started - status.T = rekeyConf.SecretThreshold - status.N = rekeyConf.SecretShares - status.Progress = progress - status.VerificationRequired = rekeyConf.VerificationRequired - status.VerificationNonce = rekeyConf.VerificationNonce - if rekeyConf.PGPKeys != nil && len(rekeyConf.PGPKeys) != 0 { - pgpFingerprints, err := pgpkeys.GetFingerprints(rekeyConf.PGPKeys, nil) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - status.PGPFingerprints = pgpFingerprints - status.Backup = rekeyConf.Backup - } - } - respondOk(w, status) -} - -func handleSysRekeyInitPut(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - // Parse the request - var req RekeyRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - - if req.Backup && len(req.PGPKeys) == 0 { - respondError(w, http.StatusBadRequest, fmt.Errorf("cannot request a backup of the new keys without providing PGP keys for encryption")) - return - } - - if len(req.PGPKeys) > 0 && len(req.PGPKeys) != req.SecretShares { - respondError(w, http.StatusBadRequest, fmt.Errorf("incorrect number of PGP keys for rekey")) - return - } - - // Initialize the rekey - err := core.RekeyInit(&vault.SealConfig{ - SecretShares: req.SecretShares, - SecretThreshold: req.SecretThreshold, - StoredShares: req.StoredShares, - PGPKeys: req.PGPKeys, - Backup: req.Backup, - VerificationRequired: req.RequireVerification, - }, recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - - handleSysRekeyInitGet(ctx, core, recovery, w, r) -} - -func handleSysRekeyInitDelete(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - if err := core.RekeyCancel(recovery); err != nil { - respondError(w, err.Code(), err) - return - } - respondOk(w, nil) -} - -func handleSysRekeyUpdate(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - // Parse the request - var req RekeyUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on rekey - result, rekeyErr := core.RekeyUpdate(ctx, key, req.Nonce, recovery) - if rekeyErr != nil { - respondError(w, rekeyErr.Code(), rekeyErr) - return - } - - // Format the response - resp := &RekeyUpdateResponse{} - if result != nil { - resp.Complete = true - resp.Nonce = req.Nonce - resp.Backup = result.Backup - resp.PGPFingerprints = result.PGPFingerprints - resp.VerificationRequired = result.VerificationRequired - resp.VerificationNonce = result.VerificationNonce - - // Encode the keys - keys := make([]string, 0, len(result.SecretShares)) - keysB64 := make([]string, 0, len(result.SecretShares)) - for _, k := range result.SecretShares { - keys = append(keys, hex.EncodeToString(k)) - keysB64 = append(keysB64, base64.StdEncoding.EncodeToString(k)) - } - resp.Keys = keys - resp.KeysB64 = keysB64 - respondOk(w, resp) - } else { - handleSysRekeyInitGet(ctx, core, recovery, w, r) - } - }) -} - -func handleSysRekeyVerify(core *vault.Core, recovery bool) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - standby, _ := core.Standby() - if standby { - respondStandby(core, w, r.URL) - return - } - - repState := core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - respondError(w, http.StatusBadRequest, - fmt.Errorf("rekeying can only be performed on the primary cluster when replication is activated")) - return - } - - ctx, cancel := core.GetContext() - defer cancel() - - switch { - case recovery && !core.SealAccess().RecoveryKeySupported(): - respondError(w, http.StatusBadRequest, fmt.Errorf("recovery rekeying not supported")) - case r.Method == "GET": - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) - case r.Method == "POST" || r.Method == "PUT": - handleSysRekeyVerifyPut(ctx, core, recovery, w, r) - case r.Method == "DELETE": - handleSysRekeyVerifyDelete(ctx, core, recovery, w, r) - default: - respondError(w, http.StatusMethodNotAllowed, nil) - } - }) -} - -func handleSysRekeyVerifyGet(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - barrierConfig, barrierConfErr := core.SealAccess().BarrierConfig(ctx) - if barrierConfErr != nil { - respondError(w, http.StatusInternalServerError, barrierConfErr) - return - } - if barrierConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - // Get the rekey configuration - rekeyConf, err := core.RekeyConfig(recovery) - if err != nil { - respondError(w, err.Code(), err) - return - } - if rekeyConf == nil { - respondError(w, http.StatusBadRequest, errors.New("no rekey configuration found")) - return - } - - // Get the progress - started, progress, err := core.RekeyProgress(recovery, true) - if err != nil { - respondError(w, err.Code(), err) - return - } - - // Format the status - status := &RekeyVerificationStatusResponse{ - Started: started, - Nonce: rekeyConf.VerificationNonce, - T: rekeyConf.SecretThreshold, - N: rekeyConf.SecretShares, - Progress: progress, - } - respondOk(w, status) -} - -func handleSysRekeyVerifyDelete(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - if err := core.RekeyVerifyRestart(recovery); err != nil { - respondError(w, err.Code(), err) - return - } - - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) -} - -func handleSysRekeyVerifyPut(ctx context.Context, core *vault.Core, recovery bool, w http.ResponseWriter, r *http.Request) { - // Parse the request - var req RekeyVerificationUpdateRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON")) - return - } - - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - ctx, cancel := core.GetContext() - defer cancel() - - // Use the key to make progress on rekey - result, rekeyErr := core.RekeyVerify(ctx, key, req.Nonce, recovery) - if rekeyErr != nil { - respondError(w, rekeyErr.Code(), rekeyErr) - return - } - - // Format the response - resp := &RekeyVerificationUpdateResponse{} - if result != nil { - resp.Complete = true - resp.Nonce = result.Nonce - respondOk(w, resp) - } else { - handleSysRekeyVerifyGet(ctx, core, recovery, w, r) - } -} - -type RekeyRequest struct { - SecretShares int `json:"secret_shares"` - SecretThreshold int `json:"secret_threshold"` - StoredShares int `json:"stored_shares"` - PGPKeys []string `json:"pgp_keys"` - Backup bool `json:"backup"` - RequireVerification bool `json:"require_verification"` -} - -type RekeyStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Required int `json:"required"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyUpdateRequest struct { - Nonce string - Key string -} - -type RekeyUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` - Keys []string `json:"keys"` - KeysB64 []string `json:"keys_base64"` - PGPFingerprints []string `json:"pgp_fingerprints"` - Backup bool `json:"backup"` - VerificationRequired bool `json:"verification_required"` - VerificationNonce string `json:"verification_nonce,omitempty"` -} - -type RekeyVerificationUpdateRequest struct { - Nonce string `json:"nonce"` - Key string `json:"key"` -} - -type RekeyVerificationStatusResponse struct { - Nonce string `json:"nonce"` - Started bool `json:"started"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` -} - -type RekeyVerificationUpdateResponse struct { - Nonce string `json:"nonce"` - Complete bool `json:"complete"` -} diff --git a/vendor/github.com/hashicorp/vault/http/sys_seal.go b/vendor/github.com/hashicorp/vault/http/sys_seal.go deleted file mode 100644 index ad6aaf9bf..000000000 --- a/vendor/github.com/hashicorp/vault/http/sys_seal.go +++ /dev/null @@ -1,227 +0,0 @@ -package http - -import ( - "context" - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/vault" - "github.com/hashicorp/vault/version" -) - -func handleSysSeal(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - switch req.Operation { - case logical.UpdateOperation: - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Seal with the token above - // We use context.Background since there won't be a request context if the node isn't active - if err := core.SealWithRequest(r.Context(), req); err != nil { - if errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - respondError(w, http.StatusForbidden, err) - return - } else { - respondError(w, http.StatusInternalServerError, err) - return - } - } - - respondOk(w, nil) - }) -} - -func handleSysStepDown(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req, statusCode, err := buildLogicalRequest(core, w, r) - if err != nil || statusCode != 0 { - respondError(w, statusCode, err) - return - } - - switch req.Operation { - case logical.UpdateOperation: - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Seal with the token above - if err := core.StepDown(r.Context(), req); err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - respondOk(w, nil) - }) -} - -func handleSysUnseal(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case "PUT": - case "POST": - default: - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - // Parse the request - var req UnsealRequest - if err := parseRequest(r, w, &req); err != nil { - respondError(w, http.StatusBadRequest, err) - return - } - if !req.Reset && req.Key == "" { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be specified in request body as JSON, or 'reset' set to true")) - return - } - - if req.Reset { - if !core.Sealed() { - respondError(w, http.StatusBadRequest, errors.New("vault is unsealed")) - return - } - core.ResetUnsealProcess() - } else { - // Decode the key, which is base64 or hex encoded - min, max := core.BarrierKeyLength() - key, err := hex.DecodeString(req.Key) - // We check min and max here to ensure that a string that is base64 - // encoded but also valid hex will not be valid and we instead base64 - // decode it - if err != nil || len(key) < min || len(key) > max { - key, err = base64.StdEncoding.DecodeString(req.Key) - if err != nil { - respondError( - w, http.StatusBadRequest, - errors.New("'key' must be a valid hex or base64 string")) - return - } - } - - // Attempt the unseal - ctx := context.Background() - if core.SealAccess().RecoveryKeySupported() { - _, err = core.UnsealWithRecoveryKeys(ctx, key) - } else { - _, err = core.Unseal(key) - } - if err != nil { - switch { - case errwrap.ContainsType(err, new(vault.ErrInvalidKey)): - case errwrap.Contains(err, vault.ErrBarrierInvalidKey.Error()): - case errwrap.Contains(err, vault.ErrBarrierNotInit.Error()): - case errwrap.Contains(err, vault.ErrBarrierSealed.Error()): - case errwrap.Contains(err, consts.ErrStandby.Error()): - default: - respondError(w, http.StatusInternalServerError, err) - return - } - respondError(w, http.StatusBadRequest, err) - return - } - } - - // Return the seal status - handleSysSealStatusRaw(core, w, r) - }) -} - -func handleSysSealStatus(core *vault.Core) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - respondError(w, http.StatusMethodNotAllowed, nil) - return - } - - handleSysSealStatusRaw(core, w, r) - }) -} - -func handleSysSealStatusRaw(core *vault.Core, w http.ResponseWriter, r *http.Request) { - ctx := context.Background() - - sealed := core.Sealed() - - var sealConfig *vault.SealConfig - var err error - if core.SealAccess().RecoveryKeySupported() { - sealConfig, err = core.SealAccess().RecoveryConfig(ctx) - } else { - sealConfig, err = core.SealAccess().BarrierConfig(ctx) - } - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - - if sealConfig == nil { - respondError(w, http.StatusBadRequest, fmt.Errorf("server is not yet initialized")) - return - } - - // Fetch the local cluster name and identifier - var clusterName, clusterID string - if !sealed { - cluster, err := core.Cluster(ctx) - if err != nil { - respondError(w, http.StatusInternalServerError, err) - return - } - if cluster == nil { - respondError(w, http.StatusInternalServerError, fmt.Errorf("failed to fetch cluster details")) - return - } - clusterName = cluster.Name - clusterID = cluster.ID - } - - progress, nonce := core.SecretProgress() - - respondOk(w, &SealStatusResponse{ - Type: sealConfig.Type, - Sealed: sealed, - T: sealConfig.SecretThreshold, - N: sealConfig.SecretShares, - Progress: progress, - Nonce: nonce, - Version: version.GetVersion().VersionNumber(), - ClusterName: clusterName, - ClusterID: clusterID, - }) -} - -type SealStatusResponse struct { - Type string `json:"type"` - Sealed bool `json:"sealed"` - T int `json:"t"` - N int `json:"n"` - Progress int `json:"progress"` - Nonce string `json:"nonce"` - Version string `json:"version"` - ClusterName string `json:"cluster_name,omitempty"` - ClusterID string `json:"cluster_id,omitempty"` -} - -type UnsealRequest struct { - Key string - Reset bool -} diff --git a/vendor/github.com/hashicorp/vault/http/testing.go b/vendor/github.com/hashicorp/vault/http/testing.go deleted file mode 100644 index ebc2edd1b..000000000 --- a/vendor/github.com/hashicorp/vault/http/testing.go +++ /dev/null @@ -1,67 +0,0 @@ -package http - -import ( - "fmt" - "net" - "net/http" - "testing" - - "github.com/hashicorp/vault/vault" -) - -func TestListener(tb testing.TB) (net.Listener, string) { - fail := func(format string, args ...interface{}) { - panic(fmt.Sprintf(format, args...)) - } - if tb != nil { - fail = tb.Fatalf - } - - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - fail("err: %s", err) - } - addr := "http://" + ln.Addr().String() - return ln, addr -} - -func TestServerWithListenerAndProperties(tb testing.TB, ln net.Listener, addr string, core *vault.Core, props *vault.HandlerProperties) { - // Create a muxer to handle our requests so that we can authenticate - // for tests. - mux := http.NewServeMux() - mux.Handle("/_test/auth", http.HandlerFunc(testHandleAuth)) - mux.Handle("/", Handler(props)) - - server := &http.Server{ - Addr: ln.Addr().String(), - Handler: mux, - ErrorLog: core.Logger().StandardLogger(nil), - } - go server.Serve(ln) -} - -func TestServerWithListener(tb testing.TB, ln net.Listener, addr string, core *vault.Core) { - // Create a muxer to handle our requests so that we can authenticate - // for tests. - props := &vault.HandlerProperties{ - Core: core, - MaxRequestSize: DefaultMaxRequestSize, - } - TestServerWithListenerAndProperties(tb, ln, addr, core, props) -} - -func TestServer(tb testing.TB, core *vault.Core) (net.Listener, string) { - ln, addr := TestListener(tb) - TestServerWithListener(tb, ln, addr, core) - return ln, addr -} - -func TestServerAuth(tb testing.TB, addr string, token string) { - if _, err := http.Get(addr + "/_test/auth?token=" + token); err != nil { - tb.Fatalf("error authenticating: %s", err) - } -} - -func testHandleAuth(w http.ResponseWriter, req *http.Request) { - respondOk(w, nil) -} diff --git a/vendor/github.com/hashicorp/vault/logical/auth.go b/vendor/github.com/hashicorp/vault/logical/auth.go deleted file mode 100644 index 68f856f4b..000000000 --- a/vendor/github.com/hashicorp/vault/logical/auth.go +++ /dev/null @@ -1,92 +0,0 @@ -package logical - -import ( - "fmt" - "time" - - "github.com/hashicorp/go-sockaddr" -) - -// Auth is the resulting authentication information that is part of -// Response for credential backends. -type Auth struct { - LeaseOptions - - // InternalData is JSON-encodable data that is stored with the auth struct. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - InternalData map[string]interface{} `json:"internal_data" mapstructure:"internal_data" structs:"internal_data"` - - // DisplayName is a non-security sensitive identifier that is - // applicable to this Auth. It is used for logging and prefixing - // of dynamic secrets. For example, DisplayName may be "armon" for - // the github credential backend. If the client token is used to - // generate a SQL credential, the user may be "github-armon-uuid". - // This is to help identify the source without using audit tables. - DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"` - - // Policies is the list of policies that the authenticated user - // is associated with. - Policies []string `json:"policies" mapstructure:"policies" structs:"policies"` - - // TokenPolicies and IdentityPolicies break down the list in Policies to - // help determine where a policy was sourced - TokenPolicies []string `json:"token_policies" mapstructure:"token_policies" structs:"token_policies"` - IdentityPolicies []string `json:"identity_policies" mapstructure:"identity_policies" structs:"identity_policies"` - - // Metadata is used to attach arbitrary string-type metadata to - // an authenticated user. This metadata will be outputted into the - // audit log. - Metadata map[string]string `json:"metadata" mapstructure:"metadata" structs:"metadata"` - - // ClientToken is the token that is generated for the authentication. - // This will be filled in by Vault core when an auth structure is - // returned. Setting this manually will have no effect. - ClientToken string `json:"client_token" mapstructure:"client_token" structs:"client_token"` - - // Accessor is the identifier for the ClientToken. This can be used - // to perform management functionalities (especially revocation) when - // ClientToken in the audit logs are obfuscated. Accessor can be used - // to revoke a ClientToken and to lookup the capabilities of the ClientToken, - // both without actually knowing the ClientToken. - Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor"` - - // Period indicates that the token generated using this Auth object - // should never expire. The token should be renewed within the duration - // specified by this period. - Period time.Duration `json:"period" mapstructure:"period" structs:"period"` - - // ExplicitMaxTTL is the max TTL that constrains periodic tokens. For normal - // tokens, this value is constrained by the configured max ttl. - ExplicitMaxTTL time.Duration `json:"-" mapstructure:"-" structs:"-"` - - // Number of allowed uses of the issued token - NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` - - // EntityID is the identifier of the entity in identity store to which the - // identity of the authenticating client belongs to. - EntityID string `json:"entity_id" mapstructure:"entity_id" structs:"entity_id"` - - // Alias is the information about the authenticated client returned by - // the auth backend - Alias *Alias `json:"alias" mapstructure:"alias" structs:"alias"` - - // GroupAliases are the informational mappings of external groups which an - // authenticated user belongs to. This is used to check if there are - // mappings groups for the group aliases in identity store. For all the - // matching groups, the entity ID of the user will be added. - GroupAliases []*Alias `json:"group_aliases" mapstructure:"group_aliases" structs:"group_aliases"` - - // The set of CIDRs that this token can be used with - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` - - // CreationPath is a path that the backend can return to use in the lease. - // This is currently only supported for the token store where roles may - // change the perceived path of the lease, even though they don't change - // the request path itself. - CreationPath string `json:"creation_path"` -} - -func (a *Auth) GoString() string { - return fmt.Sprintf("*%#v", *a) -} diff --git a/vendor/github.com/hashicorp/vault/logical/connection.go b/vendor/github.com/hashicorp/vault/logical/connection.go deleted file mode 100644 index a504b10c3..000000000 --- a/vendor/github.com/hashicorp/vault/logical/connection.go +++ /dev/null @@ -1,15 +0,0 @@ -package logical - -import ( - "crypto/tls" -) - -// Connection represents the connection information for a request. This -// is present on the Request structure for credential backends. -type Connection struct { - // RemoteAddr is the network address that sent the request. - RemoteAddr string `json:"remote_addr"` - - // ConnState is the TLS connection state if applicable. - ConnState *tls.ConnectionState `sentinel:""` -} diff --git a/vendor/github.com/hashicorp/vault/logical/error.go b/vendor/github.com/hashicorp/vault/logical/error.go deleted file mode 100644 index b2017000e..000000000 --- a/vendor/github.com/hashicorp/vault/logical/error.go +++ /dev/null @@ -1,78 +0,0 @@ -package logical - -import "errors" - -var ( - // ErrUnsupportedOperation is returned if the operation is not supported - // by the logical backend. - ErrUnsupportedOperation = errors.New("unsupported operation") - - // ErrUnsupportedPath is returned if the path is not supported - // by the logical backend. - ErrUnsupportedPath = errors.New("unsupported path") - - // ErrInvalidRequest is returned if the request is invalid - ErrInvalidRequest = errors.New("invalid request") - - // ErrPermissionDenied is returned if the client is not authorized - ErrPermissionDenied = errors.New("permission denied") - - // ErrMultiAuthzPending is returned if the the request needs more - // authorizations - ErrMultiAuthzPending = errors.New("request needs further approval") - - // ErrUpstreamRateLimited is returned when Vault recieves a rate limited - // response from an upstream - ErrUpstreamRateLimited = errors.New("upstream rate limited") -) - -type HTTPCodedError interface { - Error() string - Code() int -} - -func CodedError(status int, msg string) HTTPCodedError { - return &codedError{ - Status: status, - Message: msg, - } -} - -var _ HTTPCodedError = (*codedError)(nil) - -type codedError struct { - Status int - Message string -} - -func (e *codedError) Error() string { - return e.Message -} - -func (e *codedError) Code() int { - return e.Status -} - -// Struct to identify user input errors. This is helpful in responding the -// appropriate status codes to clients from the HTTP endpoints. -type StatusBadRequest struct { - Err string -} - -// Implementing error interface -func (s *StatusBadRequest) Error() string { - return s.Err -} - -// This is a new type declared to not cause potential compatibility problems if -// the logic around the CodedError changes; in particular for logical request -// paths it is basically ignored, and changing that behavior might cause -// unforseen issues. -type ReplicationCodedError struct { - Msg string - Code int -} - -func (r *ReplicationCodedError) Error() string { - return r.Msg -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/backend.go b/vendor/github.com/hashicorp/vault/logical/framework/backend.go deleted file mode 100644 index 4c787cbed..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/backend.go +++ /dev/null @@ -1,586 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "sort" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/logical" -) - -// Backend is an implementation of logical.Backend that allows -// the implementer to code a backend using a much more programmer-friendly -// framework that handles a lot of the routing and validation for you. -// -// This is recommended over implementing logical.Backend directly. -type Backend struct { - // Help is the help text that is shown when a help request is made - // on the root of this resource. The root help is special since we - // show all the paths that can be requested. - Help string - - // Paths are the various routes that the backend responds to. - // This cannot be modified after construction (i.e. dynamically changing - // paths, including adding or removing, is not allowed once the - // backend is in use). - // - // PathsSpecial is the list of path patterns that denote the - // paths above that require special privileges. These can't be - // regular expressions, it is either exact match or prefix match. - // For prefix match, append '*' as a suffix. - Paths []*Path - PathsSpecial *logical.Paths - - // Secrets is the list of secret types that this backend can - // return. It is used to automatically generate proper responses, - // and ease specifying callbacks for revocation, renewal, etc. - Secrets []*Secret - - // PeriodicFunc is the callback, which if set, will be invoked when the - // periodic timer of RollbackManager ticks. This can be used by - // backends to do anything it wishes to do periodically. - // - // PeriodicFunc can be invoked to, say to periodically delete stale - // entries in backend's storage, while the backend is still being used. - // (Note the different of this action from what `Clean` does, which is - // invoked just before the backend is unmounted). - PeriodicFunc periodicFunc - - // WALRollback is called when a WAL entry (see wal.go) has to be rolled - // back. It is called with the data from the entry. - // - // WALRollbackMinAge is the minimum age of a WAL entry before it is attempted - // to be rolled back. This should be longer than the maximum time it takes - // to successfully create a secret. - WALRollback WALRollbackFunc - WALRollbackMinAge time.Duration - - // Clean is called on unload to clean up e.g any existing connections - // to the backend, if required. - Clean CleanupFunc - - // Invalidate is called when a keys is modified if required - Invalidate InvalidateFunc - - // AuthRenew is the callback to call when a RenewRequest for an - // authentication comes in. By default, renewal won't be allowed. - // See the built-in AuthRenew helpers in lease.go for common callbacks. - AuthRenew OperationFunc - - // Type is the logical.BackendType for the backend implementation - BackendType logical.BackendType - - logger log.Logger - system logical.SystemView - once sync.Once - pathsRe []*regexp.Regexp -} - -// periodicFunc is the callback called when the RollbackManager's timer ticks. -// This can be utilized by the backends to do anything it wants. -type periodicFunc func(context.Context, *logical.Request) error - -// OperationFunc is the callback called for an operation on a path. -type OperationFunc func(context.Context, *logical.Request, *FieldData) (*logical.Response, error) - -// ExistenceFunc is the callback called for an existence check on a path. -type ExistenceFunc func(context.Context, *logical.Request, *FieldData) (bool, error) - -// WALRollbackFunc is the callback for rollbacks. -type WALRollbackFunc func(context.Context, *logical.Request, string, interface{}) error - -// CleanupFunc is the callback for backend unload. -type CleanupFunc func(context.Context) - -// InvalidateFunc is the callback for backend key invalidation. -type InvalidateFunc func(context.Context, string) - -// HandleExistenceCheck is the logical.Backend implementation. -func (b *Backend) HandleExistenceCheck(ctx context.Context, req *logical.Request) (checkFound bool, exists bool, err error) { - b.once.Do(b.init) - - // Ensure we are only doing this when one of the correct operations is in play - switch req.Operation { - case logical.CreateOperation: - case logical.UpdateOperation: - default: - return false, false, fmt.Errorf("incorrect operation type %v for an existence check", req.Operation) - } - - // Find the matching route - path, captures := b.route(req.Path) - if path == nil { - return false, false, logical.ErrUnsupportedPath - } - - if path.ExistenceCheck == nil { - return false, false, nil - } - - checkFound = true - - // Build up the data for the route, with the URL taking priority - // for the fields over the PUT data. - raw := make(map[string]interface{}, len(path.Fields)) - for k, v := range req.Data { - raw[k] = v - } - for k, v := range captures { - raw[k] = v - } - - fd := FieldData{ - Raw: raw, - Schema: path.Fields} - - err = fd.Validate() - if err != nil { - return false, false, errutil.UserError{Err: err.Error()} - } - - // Call the callback with the request and the data - exists, err = path.ExistenceCheck(ctx, req, &fd) - return -} - -// HandleRequest is the logical.Backend implementation. -func (b *Backend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - b.once.Do(b.init) - - // Check for special cased global operations. These don't route - // to a specific Path. - switch req.Operation { - case logical.RenewOperation: - fallthrough - case logical.RevokeOperation: - return b.handleRevokeRenew(ctx, req) - case logical.RollbackOperation: - return b.handleRollback(ctx, req) - } - - // If the path is empty and it is a help operation, handle that. - if req.Path == "" && req.Operation == logical.HelpOperation { - return b.handleRootHelp() - } - - // Find the matching route - path, captures := b.route(req.Path) - if path == nil { - return nil, logical.ErrUnsupportedPath - } - - // Build up the data for the route, with the URL taking priority - // for the fields over the PUT data. - raw := make(map[string]interface{}, len(path.Fields)) - for k, v := range req.Data { - raw[k] = v - } - for k, v := range captures { - raw[k] = v - } - - // Look up the callback for this operation - var callback OperationFunc - var ok bool - if path.Callbacks != nil { - callback, ok = path.Callbacks[req.Operation] - } - if !ok { - if req.Operation == logical.HelpOperation { - callback = path.helpCallback() - ok = true - } - } - if !ok { - return nil, logical.ErrUnsupportedOperation - } - - fd := FieldData{ - Raw: raw, - Schema: path.Fields} - - if req.Operation != logical.HelpOperation { - err := fd.Validate() - if err != nil { - return nil, err - } - } - - // Call the callback with the request and the data - return callback(ctx, req, &fd) -} - -// SpecialPaths is the logical.Backend implementation. -func (b *Backend) SpecialPaths() *logical.Paths { - return b.PathsSpecial -} - -// Cleanup is used to release resources and prepare to stop the backend -func (b *Backend) Cleanup(ctx context.Context) { - if b.Clean != nil { - b.Clean(ctx) - } -} - -// InvalidateKey is used to clear caches and reset internal state on key changes -func (b *Backend) InvalidateKey(ctx context.Context, key string) { - if b.Invalidate != nil { - b.Invalidate(ctx, key) - } -} - -// Setup is used to initialize the backend with the initial backend configuration -func (b *Backend) Setup(ctx context.Context, config *logical.BackendConfig) error { - b.logger = config.Logger - b.system = config.System - return nil -} - -// Logger can be used to get the logger. If no logger has been set, -// the logs will be discarded. -func (b *Backend) Logger() log.Logger { - if b.logger != nil { - return b.logger - } - - return logging.NewVaultLoggerWithWriter(ioutil.Discard, log.NoLevel) -} - -// System returns the backend's system view. -func (b *Backend) System() logical.SystemView { - return b.system -} - -// Type returns the backend type -func (b *Backend) Type() logical.BackendType { - return b.BackendType -} - -// Route looks up the path that would be used for a given path string. -func (b *Backend) Route(path string) *Path { - result, _ := b.route(path) - return result -} - -// Secret is used to look up the secret with the given type. -func (b *Backend) Secret(k string) *Secret { - for _, s := range b.Secrets { - if s.Type == k { - return s - } - } - - return nil -} - -func (b *Backend) init() { - b.pathsRe = make([]*regexp.Regexp, len(b.Paths)) - for i, p := range b.Paths { - if len(p.Pattern) == 0 { - panic(fmt.Sprintf("Routing pattern cannot be blank")) - } - // Automatically anchor the pattern - if p.Pattern[0] != '^' { - p.Pattern = "^" + p.Pattern - } - if p.Pattern[len(p.Pattern)-1] != '$' { - p.Pattern = p.Pattern + "$" - } - b.pathsRe[i] = regexp.MustCompile(p.Pattern) - } -} - -func (b *Backend) route(path string) (*Path, map[string]string) { - b.once.Do(b.init) - - for i, re := range b.pathsRe { - matches := re.FindStringSubmatch(path) - if matches == nil { - continue - } - - // We have a match, determine the mapping of the captures and - // store that for returning. - var captures map[string]string - path := b.Paths[i] - if captureNames := re.SubexpNames(); len(captureNames) > 1 { - captures = make(map[string]string, len(captureNames)) - for i, name := range captureNames { - if name != "" { - captures[name] = matches[i] - } - } - } - - return path, captures - } - - return nil, nil -} - -func (b *Backend) handleRootHelp() (*logical.Response, error) { - // Build a mapping of the paths and get the paths alphabetized to - // make the output prettier. - pathsMap := make(map[string]*Path) - paths := make([]string, 0, len(b.Paths)) - for i, p := range b.pathsRe { - paths = append(paths, p.String()) - pathsMap[p.String()] = b.Paths[i] - } - sort.Strings(paths) - - // Build the path data - pathData := make([]rootHelpTemplatePath, 0, len(paths)) - for _, route := range paths { - p := pathsMap[route] - pathData = append(pathData, rootHelpTemplatePath{ - Path: route, - Help: strings.TrimSpace(p.HelpSynopsis), - }) - } - - help, err := executeTemplate(rootHelpTemplate, &rootHelpTemplateData{ - Help: strings.TrimSpace(b.Help), - Paths: pathData, - }) - if err != nil { - return nil, err - } - - return logical.HelpResponse(help, nil), nil -} - -func (b *Backend) handleRevokeRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - // Special case renewal of authentication for credential backends - if req.Operation == logical.RenewOperation && req.Auth != nil { - return b.handleAuthRenew(ctx, req) - } - - if req.Secret == nil { - return nil, fmt.Errorf("request has no secret") - } - - rawSecretType, ok := req.Secret.InternalData["secret_type"] - if !ok { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - secretType, ok := rawSecretType.(string) - if !ok { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - - secret := b.Secret(secretType) - if secret == nil { - return nil, fmt.Errorf("secret is unsupported by this backend") - } - - switch req.Operation { - case logical.RenewOperation: - return secret.HandleRenew(ctx, req) - case logical.RevokeOperation: - return secret.HandleRevoke(ctx, req) - default: - return nil, fmt.Errorf("invalid operation for revoke/renew: %q", req.Operation) - } -} - -// handleRollback invokes the PeriodicFunc set on the backend. It also does a WAL rollback operation. -func (b *Backend) handleRollback(ctx context.Context, req *logical.Request) (*logical.Response, error) { - // Response is not expected from the periodic operation. - if b.PeriodicFunc != nil { - if err := b.PeriodicFunc(ctx, req); err != nil { - return nil, err - } - } - - return b.handleWALRollback(ctx, req) -} - -func (b *Backend) handleAuthRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.AuthRenew == nil { - return logical.ErrorResponse("this auth type doesn't support renew"), nil - } - - return b.AuthRenew(ctx, req, nil) -} - -func (b *Backend) handleWALRollback(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.WALRollback == nil { - return nil, logical.ErrUnsupportedOperation - } - - var merr error - keys, err := ListWAL(ctx, req.Storage) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - if len(keys) == 0 { - return nil, nil - } - - // Calculate the minimum time that the WAL entries could be - // created in order to be rolled back. - age := b.WALRollbackMinAge - if age == 0 { - age = 10 * time.Minute - } - minAge := time.Now().Add(-1 * age) - if _, ok := req.Data["immediate"]; ok { - minAge = time.Now().Add(1000 * time.Hour) - } - - for _, k := range keys { - entry, err := GetWAL(ctx, req.Storage, k) - if err != nil { - merr = multierror.Append(merr, err) - continue - } - if entry == nil { - continue - } - - // If the entry isn't old enough, then don't roll it back - if !time.Unix(entry.CreatedAt, 0).Before(minAge) { - continue - } - - // Attempt a WAL rollback - err = b.WALRollback(ctx, req, entry.Kind, entry.Data) - if err != nil { - err = errwrap.Wrapf(fmt.Sprintf("error rolling back %q entry: {{err}}", entry.Kind), err) - } - if err == nil { - err = DeleteWAL(ctx, req.Storage, k) - } - if err != nil { - merr = multierror.Append(merr, err) - } - } - - if merr == nil { - return nil, nil - } - - return logical.ErrorResponse(merr.Error()), nil -} - -// FieldSchema is a basic schema to describe the format of a path field. -type FieldSchema struct { - Type FieldType - Default interface{} - Description string -} - -// DefaultOrZero returns the default value if it is set, or otherwise -// the zero value of the type. -func (s *FieldSchema) DefaultOrZero() interface{} { - if s.Default != nil { - switch s.Type { - case TypeDurationSecond: - var result int - switch inp := s.Default.(type) { - case nil: - return s.Type.Zero() - case int: - result = inp - case int64: - result = int(inp) - case float32: - result = int(inp) - case float64: - result = int(inp) - case string: - dur, err := parseutil.ParseDurationSecond(inp) - if err != nil { - return s.Type.Zero() - } - result = int(dur.Seconds()) - case json.Number: - valInt64, err := inp.Int64() - if err != nil { - return s.Type.Zero() - } - result = int(valInt64) - default: - return s.Type.Zero() - } - return result - - default: - return s.Default - } - } - - return s.Type.Zero() -} - -// Zero returns the correct zero-value for a specific FieldType -func (t FieldType) Zero() interface{} { - switch t { - case TypeString, TypeNameString, TypeLowerCaseString: - return "" - case TypeInt: - return 0 - case TypeBool: - return false - case TypeMap: - return map[string]interface{}{} - case TypeKVPairs: - return map[string]string{} - case TypeDurationSecond: - return 0 - case TypeSlice: - return []interface{}{} - case TypeStringSlice, TypeCommaStringSlice: - return []string{} - case TypeCommaIntSlice: - return []int{} - case TypeHeader: - return http.Header{} - default: - panic("unknown type: " + t.String()) - } -} - -type rootHelpTemplateData struct { - Help string - Paths []rootHelpTemplatePath -} - -type rootHelpTemplatePath struct { - Path string - Help string -} - -const rootHelpTemplate = ` -## DESCRIPTION - -{{.Help}} - -## PATHS - -The following paths are supported by this backend. To view help for -any of the paths below, use the help command with any route matching -the path pattern. Note that depending on the policy of your auth token, -you may or may not be able to access certain paths. - -{{range .Paths}}{{indent 4 .Path}} -{{indent 8 .Help}} - -{{end}} - -` diff --git a/vendor/github.com/hashicorp/vault/logical/framework/field_data.go b/vendor/github.com/hashicorp/vault/logical/framework/field_data.go deleted file mode 100644 index 2ee529116..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/field_data.go +++ /dev/null @@ -1,397 +0,0 @@ -package framework - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/mitchellh/mapstructure" -) - -// FieldData is the structure passed to the callback to handle a path -// containing the populated parameters for fields. This should be used -// instead of the raw (*vault.Request).Data to access data in a type-safe -// way. -type FieldData struct { - Raw map[string]interface{} - Schema map[string]*FieldSchema -} - -// Validate cycles through raw data and validate conversions in -// the schema, so we don't get an error/panic later when -// trying to get data out. Data not in the schema is not -// an error at this point, so we don't worry about it. -func (d *FieldData) Validate() error { - for field, value := range d.Raw { - - schema, ok := d.Schema[field] - if !ok { - continue - } - - switch schema.Type { - case TypeBool, TypeInt, TypeMap, TypeDurationSecond, TypeString, TypeLowerCaseString, - TypeNameString, TypeSlice, TypeStringSlice, TypeCommaStringSlice, - TypeKVPairs, TypeCommaIntSlice, TypeHeader: - _, _, err := d.getPrimitive(field, schema) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error converting input %v for field %q: {{err}}", value, field), err) - } - default: - return fmt.Errorf("unknown field type %q for field %q", schema.Type, field) - } - } - - return nil -} - -// Get gets the value for the given field. If the key is an invalid field, -// FieldData will panic. If you want a safer version of this method, use -// GetOk. If the field k is not set, the default value (if set) will be -// returned, otherwise the zero value will be returned. -func (d *FieldData) Get(k string) interface{} { - schema, ok := d.Schema[k] - if !ok { - panic(fmt.Sprintf("field %s not in the schema", k)) - } - - value, ok := d.GetOk(k) - if !ok { - value = schema.DefaultOrZero() - } - - return value -} - -// GetDefaultOrZero gets the default value set on the schema for the given -// field. If there is no default value set, the zero value of the type -// will be returned. -func (d *FieldData) GetDefaultOrZero(k string) interface{} { - schema, ok := d.Schema[k] - if !ok { - panic(fmt.Sprintf("field %s not in the schema", k)) - } - - return schema.DefaultOrZero() -} - -// GetFirst gets the value for the given field names, in order from first -// to last. This can be useful for fields with a current name, and one or -// more deprecated names. The second return value will be false if the keys -// are invalid or the keys are not set at all. -func (d *FieldData) GetFirst(k ...string) (interface{}, bool) { - for _, v := range k { - if result, ok := d.GetOk(v); ok { - return result, ok - } - } - return nil, false -} - -// GetOk gets the value for the given field. The second return value -// will be false if the key is invalid or the key is not set at all. -func (d *FieldData) GetOk(k string) (interface{}, bool) { - schema, ok := d.Schema[k] - if !ok { - return nil, false - } - - result, ok, err := d.GetOkErr(k) - if err != nil { - panic(fmt.Sprintf("error reading %s: %s", k, err)) - } - - if ok && result == nil { - result = schema.DefaultOrZero() - } - - return result, ok -} - -// GetOkErr is the most conservative of all the Get methods. It returns -// whether key is set or not, but also an error value. The error value is -// non-nil if the field doesn't exist or there was an error parsing the -// field value. -func (d *FieldData) GetOkErr(k string) (interface{}, bool, error) { - schema, ok := d.Schema[k] - if !ok { - return nil, false, fmt.Errorf("unknown field: %q", k) - } - - switch schema.Type { - case TypeBool, TypeInt, TypeMap, TypeDurationSecond, TypeString, TypeLowerCaseString, - TypeNameString, TypeSlice, TypeStringSlice, TypeCommaStringSlice, - TypeKVPairs, TypeCommaIntSlice, TypeHeader: - return d.getPrimitive(k, schema) - default: - return nil, false, - fmt.Errorf("unknown field type %q for field %q", schema.Type, k) - } -} - -func (d *FieldData) getPrimitive(k string, schema *FieldSchema) (interface{}, bool, error) { - raw, ok := d.Raw[k] - if !ok { - return nil, false, nil - } - - switch schema.Type { - case TypeBool: - var result bool - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeInt: - var result int - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeLowerCaseString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return strings.ToLower(result), true, nil - - case TypeNameString: - var result string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - matched, err := regexp.MatchString("^\\w(([\\w-.]+)?\\w)?$", result) - if err != nil { - return nil, true, err - } - if !matched { - return nil, true, errors.New("field does not match the formatting rules") - } - return result, true, nil - - case TypeMap: - var result map[string]interface{} - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeDurationSecond: - var result int - switch inp := raw.(type) { - case nil: - return nil, false, nil - case int: - result = inp - case int32: - result = int(inp) - case int64: - result = int(inp) - case uint: - result = int(inp) - case uint32: - result = int(inp) - case uint64: - result = int(inp) - case float32: - result = int(inp) - case float64: - result = int(inp) - case string: - dur, err := parseutil.ParseDurationSecond(inp) - if err != nil { - return nil, true, err - } - result = int(dur.Seconds()) - case json.Number: - valInt64, err := inp.Int64() - if err != nil { - return nil, true, err - } - result = int(valInt64) - default: - return nil, false, fmt.Errorf("invalid input '%v'", raw) - } - if result < 0 { - return nil, true, fmt.Errorf("cannot provide negative value '%d'", result) - } - return result, true, nil - - case TypeCommaIntSlice: - var result []int - config := &mapstructure.DecoderConfig{ - Result: &result, - WeaklyTypedInput: true, - DecodeHook: mapstructure.StringToSliceHookFunc(","), - } - decoder, err := mapstructure.NewDecoder(config) - if err != nil { - return nil, true, err - } - if err := decoder.Decode(raw); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeSlice: - var result []interface{} - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return result, true, nil - - case TypeStringSlice: - var result []string - if err := mapstructure.WeakDecode(raw, &result); err != nil { - return nil, true, err - } - return strutil.TrimStrings(result), true, nil - - case TypeCommaStringSlice: - res, err := parseutil.ParseCommaStringSlice(raw) - if err != nil { - return nil, false, err - } - return res, true, nil - - case TypeKVPairs: - // First try to parse this as a map - var mapResult map[string]string - if err := mapstructure.WeakDecode(raw, &mapResult); err == nil { - return mapResult, true, nil - } - - // If map parse fails, parse as a string list of = delimited pairs - var listResult []string - if err := mapstructure.WeakDecode(raw, &listResult); err != nil { - return nil, true, err - } - - result := make(map[string]string, len(listResult)) - for _, keyPair := range listResult { - keyPairSlice := strings.SplitN(keyPair, "=", 2) - if len(keyPairSlice) != 2 || keyPairSlice[0] == "" { - return nil, false, fmt.Errorf("invalid key pair %q", keyPair) - } - result[keyPairSlice[0]] = keyPairSlice[1] - } - return result, true, nil - - case TypeHeader: - /* - - There are multiple ways a header could be provided: - - 1. As a map[string]interface{} that resolves to a map[string]string or map[string][]string, or a mix of both - because that's permitted for headers. - This mainly comes from the API. - - 2. As a string... - a. That contains JSON that originally was JSON, but then was base64 encoded. - b. That contains JSON, ex. `{"content-type":"text/json","accept":["encoding/json"]}`. - This mainly comes from the API and is used to save space while sending in the header. - - 3. As an array of strings that contains comma-delimited key-value pairs associated via a colon, - ex: `content-type:text/json`,`accept:encoding/json`. - This mainly comes from the CLI. - - We go through these sequentially below. - - */ - result := http.Header{} - - toHeader := func(resultMap map[string]interface{}) (http.Header, error) { - header := http.Header{} - for headerKey, headerValGroup := range resultMap { - switch typedHeader := headerValGroup.(type) { - case string: - header.Add(headerKey, typedHeader) - case []string: - for _, headerVal := range typedHeader { - header.Add(headerKey, headerVal) - } - case []interface{}: - for _, headerVal := range typedHeader { - strHeaderVal, ok := headerVal.(string) - if !ok { - // All header values should already be strings when they're being sent in. - // Even numbers and booleans will be treated as strings. - return nil, fmt.Errorf("received non-string value for header key:%s, val:%s", headerKey, headerValGroup) - } - header.Add(headerKey, strHeaderVal) - } - default: - return nil, fmt.Errorf("unrecognized type for %s", headerValGroup) - } - } - return header, nil - } - - resultMap := make(map[string]interface{}) - - // 1. Are we getting a map from the API? - if err := mapstructure.WeakDecode(raw, &resultMap); err == nil { - result, err = toHeader(resultMap) - if err != nil { - return nil, true, err - } - return result, true, nil - } - - // 2. Are we getting a JSON string? - if headerStr, ok := raw.(string); ok { - // a. Is it base64 encoded? - headerBytes, err := base64.StdEncoding.DecodeString(headerStr) - if err != nil { - // b. It's not base64 encoded, it's a straight-out JSON string. - headerBytes = []byte(headerStr) - } - if err := json.NewDecoder(bytes.NewReader(headerBytes)).Decode(&resultMap); err != nil { - return nil, true, err - } - result, err = toHeader(resultMap) - if err != nil { - return nil, true, err - } - return result, true, nil - } - - // 3. Are we getting an array of fields like "content-type:encoding/json" from the CLI? - var keyPairs []interface{} - if err := mapstructure.WeakDecode(raw, &keyPairs); err == nil { - for _, keyPairIfc := range keyPairs { - keyPair, ok := keyPairIfc.(string) - if !ok { - return nil, true, fmt.Errorf("invalid key pair %q", keyPair) - } - keyPairSlice := strings.SplitN(keyPair, ":", 2) - if len(keyPairSlice) != 2 || keyPairSlice[0] == "" { - return nil, true, fmt.Errorf("invalid key pair %q", keyPair) - } - result.Add(keyPairSlice[0], keyPairSlice[1]) - } - return result, true, nil - } - return nil, true, fmt.Errorf("%s not provided an expected format", raw) - - default: - panic(fmt.Sprintf("Unknown type: %s", schema.Type)) - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/field_type.go b/vendor/github.com/hashicorp/vault/logical/framework/field_type.go deleted file mode 100644 index 64a6a56dc..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/field_type.go +++ /dev/null @@ -1,78 +0,0 @@ -package framework - -// FieldType is the enum of types that a field can be. -type FieldType uint - -const ( - TypeInvalid FieldType = 0 - TypeString FieldType = iota - TypeInt - TypeBool - TypeMap - - // TypeDurationSecond represent as seconds, this can be either an - // integer or go duration format string (e.g. 24h) - TypeDurationSecond - - // TypeSlice represents a slice of any type - TypeSlice - - // TypeStringSlice is a helper for TypeSlice that returns a sanitized - // slice of strings - TypeStringSlice - - // TypeCommaStringSlice is a helper for TypeSlice that returns a sanitized - // slice of strings and also supports parsing a comma-separated list in - // a string field - TypeCommaStringSlice - - // TypeLowerCaseString is a helper for TypeString that returns a lowercase - // version of the provided string - TypeLowerCaseString - - // TypeNameString represents a name that is URI safe and follows specific - // rules. These rules include start and end with an alphanumeric - // character and characters in the middle can be alphanumeric or . or -. - TypeNameString - - // TypeKVPairs allows you to represent the data as a map or a list of - // equal sign delimited key pairs - TypeKVPairs - - // TypeCommaIntSlice is a helper for TypeSlice that returns a sanitized - // slice of Ints - TypeCommaIntSlice - - // TypeHeader is a helper for sending request headers through to Vault. - // For instance, the AWS and AliCloud credential plugins both act as a - // benevolent MITM for a request, and the headers are sent through and - // parsed. - TypeHeader -) - -func (t FieldType) String() string { - switch t { - case TypeString: - return "string" - case TypeLowerCaseString: - return "lowercase string" - case TypeNameString: - return "name string" - case TypeInt: - return "int" - case TypeBool: - return "bool" - case TypeMap: - return "map" - case TypeKVPairs: - return "keypair" - case TypeDurationSecond: - return "duration (sec)" - case TypeSlice, TypeStringSlice, TypeCommaStringSlice, TypeCommaIntSlice: - return "slice" - case TypeHeader: - return "header" - default: - return "unknown type" - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/lease.go b/vendor/github.com/hashicorp/vault/logical/framework/lease.go deleted file mode 100644 index 4f55ae0de..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/lease.go +++ /dev/null @@ -1,106 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/vault/logical" -) - -// LeaseExtend is left for backwards compatibility for plugins. This function -// now just passes back the data that was passed into it to be processed in core. -// DEPRECATED -func LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical.SystemView) OperationFunc { - return func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) { - switch { - case req.Auth != nil: - req.Auth.TTL = backendIncrement - req.Auth.MaxTTL = backendMax - return &logical.Response{Auth: req.Auth}, nil - case req.Secret != nil: - req.Secret.TTL = backendIncrement - req.Secret.MaxTTL = backendMax - return &logical.Response{Secret: req.Secret}, nil - } - return nil, fmt.Errorf("no lease options for request") - } -} - -// CalculateTTL takes all the user-specified, backend, and system inputs and calculates -// a TTL for a lease -func CalculateTTL(sysView logical.SystemView, increment, backendTTL, period, backendMaxTTL, explicitMaxTTL time.Duration, startTime time.Time) (ttl time.Duration, warnings []string, errors error) { - // Truncate all times to the second since that is the lowest precision for - // TTLs - now := time.Now().Truncate(time.Second) - if startTime.IsZero() { - startTime = now - } else { - startTime = startTime.Truncate(time.Second) - } - - // Use the mount's configured max unless the backend specifies - // something more restrictive (perhaps from a role configuration - // parameter) - maxTTL := sysView.MaxLeaseTTL() - if backendMaxTTL > 0 && backendMaxTTL < maxTTL { - maxTTL = backendMaxTTL - } - if explicitMaxTTL > 0 && explicitMaxTTL < maxTTL { - maxTTL = explicitMaxTTL - } - - // Should never happen, but guard anyways - if maxTTL <= 0 { - return 0, nil, fmt.Errorf("max TTL must be greater than zero") - } - - var maxValidTime time.Time - switch { - case period > 0: - // Cap the period value to the sys max_ttl value - if period > maxTTL { - warnings = append(warnings, - fmt.Sprintf("period of %q exceeded the effective max_ttl of %q; period value is capped accordingly", period, maxTTL)) - period = maxTTL - } - ttl = period - - if explicitMaxTTL > 0 { - maxValidTime = startTime.Add(explicitMaxTTL) - } - default: - switch { - case increment > 0: - ttl = increment - case backendTTL > 0: - ttl = backendTTL - default: - ttl = sysView.DefaultLeaseTTL() - } - - // We cannot go past this time - maxValidTime = startTime.Add(maxTTL) - } - - if !maxValidTime.IsZero() { - // Determine the max valid TTL - maxValidTTL := maxValidTime.Sub(now) - - // If we are past the max TTL, we shouldn't be in this function...but - // fast path out if we are - if maxValidTTL < 0 { - return 0, nil, fmt.Errorf("past the max TTL, cannot renew") - } - - // If the proposed expiration is after the maximum TTL of the lease, - // cap the increment to whatever is left - if maxValidTTL-ttl < 0 { - warnings = append(warnings, - fmt.Sprintf("TTL of %q exceeded the effective max_ttl of %q; TTL value is capped accordingly", ttl, maxValidTTL)) - ttl = maxValidTTL - } - } - - return ttl, warnings, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path.go b/vendor/github.com/hashicorp/vault/logical/framework/path.go deleted file mode 100644 index e53dd196c..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path.go +++ /dev/null @@ -1,163 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" -) - -// Helper which returns a generic regex string for creating endpoint patterns -// that are identified by the given name in the backends -func GenericNameRegex(name string) string { - return fmt.Sprintf("(?P<%s>\\w(([\\w-.]+)?\\w)?)", name) -} - -// Helper which returns a regex string for optionally accepting the a field -// from the API URL -func OptionalParamRegex(name string) string { - return fmt.Sprintf("(/(?P<%s>.+))?", name) -} - -// PathAppend is a helper for appending lists of paths into a single -// list. -func PathAppend(paths ...[]*Path) []*Path { - result := make([]*Path, 0, 10) - for _, ps := range paths { - result = append(result, ps...) - } - - return result -} - -// Path is a single path that the backend responds to. -type Path struct { - // Pattern is the pattern of the URL that matches this path. - // - // This should be a valid regular expression. Named captures will be - // exposed as fields that should map to a schema in Fields. If a named - // capture is not a field in the Fields map, then it will be ignored. - Pattern string - - // Fields is the mapping of data fields to a schema describing that - // field. Named captures in the Pattern also map to fields. If a named - // capture name matches a PUT body name, the named capture takes - // priority. - // - // Note that only named capture fields are available in every operation, - // whereas all fields are available in the Write operation. - Fields map[string]*FieldSchema - - // Callbacks are the set of callbacks that are called for a given - // operation. If a callback for a specific operation is not present, - // then logical.ErrUnsupportedOperation is automatically generated. - // - // The help operation is the only operation that the Path will - // automatically handle if the Help field is set. If both the Help - // field is set and there is a callback registered here, then the - // callback will be called. - Callbacks map[logical.Operation]OperationFunc - - // ExistenceCheck, if implemented, is used to query whether a given - // resource exists or not. This is used for ACL purposes: if an Update - // action is specified, and the existence check returns false, the action - // is not allowed since the resource must first be created. The reverse is - // also true. If not specified, the Update action is forced and the user - // must have UpdateCapability on the path. - ExistenceCheck ExistenceFunc - - // Help is text describing how to use this path. This will be used - // to auto-generate the help operation. The Path will automatically - // generate a parameter listing and URL structure based on the - // regular expression, so the help text should just contain a description - // of what happens. - // - // HelpSynopsis is a one-sentence description of the path. This will - // be automatically line-wrapped at 80 characters. - // - // HelpDescription is a long-form description of the path. This will - // be automatically line-wrapped at 80 characters. - HelpSynopsis string - HelpDescription string -} - -func (p *Path) helpCallback() OperationFunc { - return func(ctx context.Context, req *logical.Request, data *FieldData) (*logical.Response, error) { - var tplData pathTemplateData - tplData.Request = req.Path - tplData.RoutePattern = p.Pattern - tplData.Synopsis = strings.TrimSpace(p.HelpSynopsis) - if tplData.Synopsis == "" { - tplData.Synopsis = "" - } - tplData.Description = strings.TrimSpace(p.HelpDescription) - if tplData.Description == "" { - tplData.Description = "" - } - - // Alphabetize the fields - fieldKeys := make([]string, 0, len(p.Fields)) - for k, _ := range p.Fields { - fieldKeys = append(fieldKeys, k) - } - sort.Strings(fieldKeys) - - // Build the field help - tplData.Fields = make([]pathTemplateFieldData, len(fieldKeys)) - for i, k := range fieldKeys { - schema := p.Fields[k] - description := strings.TrimSpace(schema.Description) - if description == "" { - description = "" - } - - tplData.Fields[i] = pathTemplateFieldData{ - Key: k, - Type: schema.Type.String(), - Description: description, - } - } - - help, err := executeTemplate(pathHelpTemplate, &tplData) - if err != nil { - return nil, errwrap.Wrapf("error executing template: {{err}}", err) - } - - return logical.HelpResponse(help, nil), nil - } -} - -type pathTemplateData struct { - Request string - RoutePattern string - Synopsis string - Description string - Fields []pathTemplateFieldData -} - -type pathTemplateFieldData struct { - Key string - Type string - Description string - URL bool -} - -const pathHelpTemplate = ` -Request: {{.Request}} -Matching Route: {{.RoutePattern}} - -{{.Synopsis}} - -{{ if .Fields -}} -## PARAMETERS -{{range .Fields}} -{{indent 4 .Key}} ({{.Type}}) -{{indent 8 .Description}} -{{end}}{{end}} -## DESCRIPTION - -{{.Description}} -` diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path_map.go b/vendor/github.com/hashicorp/vault/logical/framework/path_map.go deleted file mode 100644 index 83aa0bafa..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path_map.go +++ /dev/null @@ -1,283 +0,0 @@ -package framework - -import ( - "context" - "fmt" - "strings" - "sync" - - saltpkg "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -// PathMap can be used to generate a path that stores mappings in the -// storage. It is a structure that also exports functions for querying the -// mappings. -// -// The primary use case for this is for credential providers to do their -// mapping to policies. -type PathMap struct { - Prefix string - Name string - Schema map[string]*FieldSchema - CaseSensitive bool - Salt *saltpkg.Salt - SaltFunc func(context.Context) (*saltpkg.Salt, error) - - once sync.Once -} - -func (p *PathMap) init() { - if p.Prefix == "" { - p.Prefix = "map" - } - - if p.Schema == nil { - p.Schema = map[string]*FieldSchema{ - "value": &FieldSchema{ - Type: TypeString, - Description: fmt.Sprintf("Value for %s mapping", p.Name), - }, - } - } -} - -// pathStruct returns the pathStruct for this mapping -func (p *PathMap) pathStruct(ctx context.Context, s logical.Storage, k string) (*PathStruct, error) { - p.once.Do(p.init) - - // If we don't care about casing, store everything lowercase - if !p.CaseSensitive { - k = strings.ToLower(k) - } - - // The original key before any salting - origKey := k - - // If we have a salt, apply it before lookup - salt := p.Salt - var err error - if p.SaltFunc != nil { - salt, err = p.SaltFunc(ctx) - if err != nil { - return nil, err - } - } - if salt != nil { - k = "s" + salt.SaltIDHashFunc(k, saltpkg.SHA256Hash) - } - - finalName := fmt.Sprintf("map/%s/%s", p.Name, k) - ps := &PathStruct{ - Name: finalName, - Schema: p.Schema, - } - - if !strings.HasPrefix(origKey, "s") && k != origKey { - // Ensure that no matter what happens what is returned is the final - // path - defer func() { - ps.Name = finalName - }() - - // - // Check for unsalted version and upgrade if so - // - - // Generate the unsalted name - unsaltedName := fmt.Sprintf("map/%s/%s", p.Name, origKey) - // Set the path struct to use the unsalted name - ps.Name = unsaltedName - - val, err := ps.Get(ctx, s) - if err != nil { - return nil, err - } - // If not nil, we have an unsalted entry -- upgrade it - if val != nil { - // Set the path struct to use the desired final name - ps.Name = finalName - err = ps.Put(ctx, s, val) - if err != nil { - return nil, err - } - // Set it back to the old path and delete - ps.Name = unsaltedName - err = ps.Delete(ctx, s) - if err != nil { - return nil, err - } - // We'll set this in the deferred function but doesn't hurt here - ps.Name = finalName - } - - // - // Check for SHA1 hashed version and upgrade if so - // - - // Generate the SHA1 hash suffixed path name - sha1SuffixedName := fmt.Sprintf("map/%s/%s", p.Name, salt.SaltID(origKey)) - - // Set the path struct to use the SHA1 hash suffixed path name - ps.Name = sha1SuffixedName - - val, err = ps.Get(ctx, s) - if err != nil { - return nil, err - } - // If not nil, we have an SHA1 hash suffixed entry -- upgrade it - if val != nil { - // Set the path struct to use the desired final name - ps.Name = finalName - err = ps.Put(ctx, s, val) - if err != nil { - return nil, err - } - // Set it back to the old path and delete - ps.Name = sha1SuffixedName - err = ps.Delete(ctx, s) - if err != nil { - return nil, err - } - // We'll set this in the deferred function but doesn't hurt here - ps.Name = finalName - } - } - - return ps, nil -} - -// Get reads a value out of the mapping -func (p *PathMap) Get(ctx context.Context, s logical.Storage, k string) (map[string]interface{}, error) { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return nil, err - } - return ps.Get(ctx, s) -} - -// Put writes a value into the mapping -func (p *PathMap) Put(ctx context.Context, s logical.Storage, k string, v map[string]interface{}) error { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return err - } - return ps.Put(ctx, s, v) -} - -// Delete removes a value from the mapping -func (p *PathMap) Delete(ctx context.Context, s logical.Storage, k string) error { - ps, err := p.pathStruct(ctx, s, k) - if err != nil { - return err - } - return ps.Delete(ctx, s) -} - -// List reads the keys under a given path -func (p *PathMap) List(ctx context.Context, s logical.Storage, prefix string) ([]string, error) { - stripPrefix := fmt.Sprintf("struct/map/%s/", p.Name) - fullPrefix := fmt.Sprintf("%s%s", stripPrefix, prefix) - out, err := s.List(ctx, fullPrefix) - if err != nil { - return nil, err - } - stripped := make([]string, len(out)) - for idx, k := range out { - stripped[idx] = strings.TrimPrefix(k, stripPrefix) - } - return stripped, nil -} - -// Paths are the paths to append to the Backend paths. -func (p *PathMap) Paths() []*Path { - p.once.Do(p.init) - - // Build the schema by simply adding the "key" - schema := make(map[string]*FieldSchema) - for k, v := range p.Schema { - schema[k] = v - } - schema["key"] = &FieldSchema{ - Type: TypeString, - Description: fmt.Sprintf("Key for the %s mapping", p.Name), - } - - return []*Path{ - &Path{ - Pattern: fmt.Sprintf("%s/%s/?$", p.Prefix, p.Name), - - Callbacks: map[logical.Operation]OperationFunc{ - logical.ListOperation: p.pathList(), - logical.ReadOperation: p.pathList(), - }, - - HelpSynopsis: fmt.Sprintf("Read mappings for %s", p.Name), - }, - - &Path{ - Pattern: fmt.Sprintf(`%s/%s/(?P[-\w]+)`, p.Prefix, p.Name), - - Fields: schema, - - Callbacks: map[logical.Operation]OperationFunc{ - logical.CreateOperation: p.pathSingleWrite(), - logical.ReadOperation: p.pathSingleRead(), - logical.UpdateOperation: p.pathSingleWrite(), - logical.DeleteOperation: p.pathSingleDelete(), - }, - - HelpSynopsis: fmt.Sprintf("Read/write/delete a single %s mapping", p.Name), - - ExistenceCheck: p.pathSingleExistenceCheck(), - }, - } -} - -func (p *PathMap) pathList() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - keys, err := p.List(ctx, req.Storage, "") - if err != nil { - return nil, err - } - - return logical.ListResponse(keys), nil - } -} - -func (p *PathMap) pathSingleRead() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - v, err := p.Get(ctx, req.Storage, d.Get("key").(string)) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: v, - }, nil - } -} - -func (p *PathMap) pathSingleWrite() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Put(ctx, req.Storage, d.Get("key").(string), d.Raw) - return nil, err - } -} - -func (p *PathMap) pathSingleDelete() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Delete(ctx, req.Storage, d.Get("key").(string)) - return nil, err - } -} - -func (p *PathMap) pathSingleExistenceCheck() ExistenceFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (bool, error) { - v, err := p.Get(ctx, req.Storage, d.Get("key").(string)) - if err != nil { - return false, err - } - return v != nil, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go b/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go deleted file mode 100644 index beaed52d6..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/path_struct.go +++ /dev/null @@ -1,124 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" -) - -// PathStruct can be used to generate a path that stores a struct -// in the storage. This structure is a map[string]interface{} but the -// types are set according to the schema in this structure. -type PathStruct struct { - Name string - Path string - Schema map[string]*FieldSchema - HelpSynopsis string - HelpDescription string - - Read bool -} - -// Get reads the structure. -func (p *PathStruct) Get(ctx context.Context, s logical.Storage) (map[string]interface{}, error) { - entry, err := s.Get(ctx, fmt.Sprintf("struct/%s", p.Name)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result map[string]interface{} - if err := jsonutil.DecodeJSON(entry.Value, &result); err != nil { - return nil, err - } - - return result, nil -} - -// Put writes the structure. -func (p *PathStruct) Put(ctx context.Context, s logical.Storage, v map[string]interface{}) error { - bytes, err := json.Marshal(v) - if err != nil { - return err - } - - return s.Put(ctx, &logical.StorageEntry{ - Key: fmt.Sprintf("struct/%s", p.Name), - Value: bytes, - }) -} - -// Delete removes the structure. -func (p *PathStruct) Delete(ctx context.Context, s logical.Storage) error { - return s.Delete(ctx, fmt.Sprintf("struct/%s", p.Name)) -} - -// Paths are the paths to append to the Backend paths. -func (p *PathStruct) Paths() []*Path { - // The single path we support to read/write this config - path := &Path{ - Pattern: p.Path, - Fields: p.Schema, - - Callbacks: map[logical.Operation]OperationFunc{ - logical.CreateOperation: p.pathWrite(), - logical.UpdateOperation: p.pathWrite(), - logical.DeleteOperation: p.pathDelete(), - }, - - ExistenceCheck: p.pathExistenceCheck(), - - HelpSynopsis: p.HelpSynopsis, - HelpDescription: p.HelpDescription, - } - - // If we support reads, add that - if p.Read { - path.Callbacks[logical.ReadOperation] = p.pathRead() - } - - return []*Path{path} -} - -func (p *PathStruct) pathRead() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - v, err := p.Get(ctx, req.Storage) - if err != nil { - return nil, err - } - - return &logical.Response{ - Data: v, - }, nil - } -} - -func (p *PathStruct) pathWrite() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Put(ctx, req.Storage, d.Raw) - return nil, err - } -} - -func (p *PathStruct) pathDelete() OperationFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (*logical.Response, error) { - err := p.Delete(ctx, req.Storage) - return nil, err - } -} - -func (p *PathStruct) pathExistenceCheck() ExistenceFunc { - return func(ctx context.Context, req *logical.Request, d *FieldData) (bool, error) { - v, err := p.Get(ctx, req.Storage) - if err != nil { - return false, err - } - - return v != nil, nil - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go b/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go deleted file mode 100644 index 089cf7f2c..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/policy_map.go +++ /dev/null @@ -1,65 +0,0 @@ -package framework - -import ( - "context" - "sort" - "strings" - - "github.com/hashicorp/vault/logical" -) - -// PolicyMap is a specialization of PathMap that expects the values to -// be lists of policies. This assists in querying and loading policies -// from the PathMap. -type PolicyMap struct { - PathMap - - DefaultKey string - PolicyKey string -} - -func (p *PolicyMap) Policies(ctx context.Context, s logical.Storage, names ...string) ([]string, error) { - policyKey := "value" - if p.PolicyKey != "" { - policyKey = p.PolicyKey - } - - if p.DefaultKey != "" { - newNames := make([]string, len(names)+1) - newNames[0] = p.DefaultKey - copy(newNames[1:], names) - names = newNames - } - - set := make(map[string]struct{}) - for _, name := range names { - v, err := p.Get(ctx, s, name) - if err != nil { - return nil, err - } - - valuesRaw, ok := v[policyKey] - if !ok { - continue - } - - values, ok := valuesRaw.(string) - if !ok { - continue - } - - for _, p := range strings.Split(values, ",") { - if p = strings.TrimSpace(p); p != "" { - set[p] = struct{}{} - } - } - } - - list := make([]string, 0, len(set)) - for k, _ := range set { - list = append(list, k) - } - sort.Strings(list) - - return list, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/secret.go b/vendor/github.com/hashicorp/vault/logical/framework/secret.go deleted file mode 100644 index 616a055c8..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/secret.go +++ /dev/null @@ -1,91 +0,0 @@ -package framework - -import ( - "context" - "time" - - "github.com/hashicorp/vault/logical" -) - -// Secret is a type of secret that can be returned from a backend. -type Secret struct { - // Type is the name of this secret type. This is used to setup the - // vault ID and to look up the proper secret structure when revocation/ - // renewal happens. Once this is set this should not be changed. - // - // The format of this must match (case insensitive): ^a-Z0-9_$ - Type string - - // Fields is the mapping of data fields and schema that comprise - // the structure of this secret. - Fields map[string]*FieldSchema - - // DefaultDuration is the default value for the duration of the lease for - // this secret. This can be manually overwritten with the result of - // Response(). - // - // If these aren't set, Vault core will set a default lease period which - // may come from a mount tuning. - DefaultDuration time.Duration - - // Renew is the callback called to renew this secret. If Renew is - // not specified then renewable is set to false in the secret. - // See lease.go for helpers for this value. - Renew OperationFunc - - // Revoke is the callback called to revoke this secret. This is required. - Revoke OperationFunc -} - -func (s *Secret) Renewable() bool { - return s.Renew != nil -} - -func (s *Secret) Response( - data, internal map[string]interface{}) *logical.Response { - internalData := make(map[string]interface{}) - for k, v := range internal { - internalData[k] = v - } - internalData["secret_type"] = s.Type - - return &logical.Response{ - Secret: &logical.Secret{ - LeaseOptions: logical.LeaseOptions{ - TTL: s.DefaultDuration, - Renewable: s.Renewable(), - }, - InternalData: internalData, - }, - - Data: data, - } -} - -// HandleRenew is the request handler for renewing this secret. -func (s *Secret) HandleRenew(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if !s.Renewable() { - return nil, logical.ErrUnsupportedOperation - } - - data := &FieldData{ - Raw: req.Data, - Schema: s.Fields, - } - - return s.Renew(ctx, req, data) -} - -// HandleRevoke is the request handler for renewing this secret. -func (s *Secret) HandleRevoke(ctx context.Context, req *logical.Request) (*logical.Response, error) { - data := &FieldData{ - Raw: req.Data, - Schema: s.Fields, - } - - if s.Revoke != nil { - return s.Revoke(ctx, req, data) - } - - return nil, logical.ErrUnsupportedOperation -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/template.go b/vendor/github.com/hashicorp/vault/logical/framework/template.go deleted file mode 100644 index 3abdd624c..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/template.go +++ /dev/null @@ -1,42 +0,0 @@ -package framework - -import ( - "bufio" - "bytes" - "strings" - "text/template" - - "github.com/hashicorp/errwrap" -) - -func executeTemplate(tpl string, data interface{}) (string, error) { - // Define the functions - funcs := map[string]interface{}{ - "indent": funcIndent, - } - - // Parse the help template - t, err := template.New("root").Funcs(funcs).Parse(tpl) - if err != nil { - return "", errwrap.Wrapf("error parsing template: {{err}}", err) - } - - // Execute the template and store the output - var buf bytes.Buffer - if err := t.Execute(&buf, data); err != nil { - return "", errwrap.Wrapf("error executing template: {{err}}", err) - } - - return strings.TrimSpace(buf.String()), nil -} - -func funcIndent(count int, text string) string { - var buf bytes.Buffer - prefix := strings.Repeat(" ", count) - scan := bufio.NewScanner(strings.NewReader(text)) - for scan.Scan() { - buf.WriteString(prefix + scan.Text() + "\n") - } - - return strings.TrimRight(buf.String(), "\n") -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/testing.go b/vendor/github.com/hashicorp/vault/logical/framework/testing.go deleted file mode 100644 index a00a3241c..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/testing.go +++ /dev/null @@ -1,15 +0,0 @@ -package framework - -import ( - "testing" -) - -// TestBackendRoutes is a helper to test that all the given routes will -// route properly in the backend. -func TestBackendRoutes(t *testing.T, b *Backend, rs []string) { - for _, r := range rs { - if b.Route(r) == nil { - t.Fatalf("bad route: %s", r) - } - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/framework/wal.go b/vendor/github.com/hashicorp/vault/logical/framework/wal.go deleted file mode 100644 index c8fa3b871..000000000 --- a/vendor/github.com/hashicorp/vault/logical/framework/wal.go +++ /dev/null @@ -1,101 +0,0 @@ -package framework - -import ( - "context" - "encoding/json" - "strings" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" -) - -// WALPrefix is the prefix within Storage where WAL entries will be written. -const WALPrefix = "wal/" - -type WALEntry struct { - ID string `json:"-"` - Kind string `json:"type"` - Data interface{} `json:"data"` - CreatedAt int64 `json:"created_at"` -} - -// PutWAL writes some data to the WAL. -// -// The kind parameter is used by the framework to allow users to store -// multiple kinds of WAL data and to easily disambiguate what data they're -// expecting. -// -// Data within the WAL that is uncommitted (CommitWAL hasn't be called) -// will be given to the rollback callback when an rollback operation is -// received, allowing the backend to clean up some partial states. -// -// The data must be JSON encodable. -// -// This returns a unique ID that can be used to reference this WAL data. -// WAL data cannot be modified. You can only add to the WAL and commit existing -// WAL entries. -func PutWAL(ctx context.Context, s logical.Storage, kind string, data interface{}) (string, error) { - value, err := json.Marshal(&WALEntry{ - Kind: kind, - Data: data, - CreatedAt: time.Now().UTC().Unix(), - }) - if err != nil { - return "", err - } - - id, err := uuid.GenerateUUID() - if err != nil { - return "", err - } - - return id, s.Put(ctx, &logical.StorageEntry{ - Key: WALPrefix + id, - Value: value, - }) -} - -// GetWAL reads a specific entry from the WAL. If the entry doesn't exist, -// then nil value is returned. -// -// The kind, value, and error are returned. -func GetWAL(ctx context.Context, s logical.Storage, id string) (*WALEntry, error) { - entry, err := s.Get(ctx, WALPrefix+id) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var raw WALEntry - if err := jsonutil.DecodeJSON(entry.Value, &raw); err != nil { - return nil, err - } - raw.ID = id - - return &raw, nil -} - -// DeleteWAL commits the WAL entry with the given ID. Once committed, -// it is assumed that the operation was a success and doesn't need to -// be rolled back. -func DeleteWAL(ctx context.Context, s logical.Storage, id string) error { - return s.Delete(ctx, WALPrefix+id) -} - -// ListWAL lists all the entries in the WAL. -func ListWAL(ctx context.Context, s logical.Storage) ([]string, error) { - keys, err := s.List(ctx, WALPrefix) - if err != nil { - return nil, err - } - - for i, k := range keys { - keys[i] = strings.TrimPrefix(k, WALPrefix) - } - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/identity.pb.go b/vendor/github.com/hashicorp/vault/logical/identity.pb.go deleted file mode 100644 index 509db57a5..000000000 --- a/vendor/github.com/hashicorp/vault/logical/identity.pb.go +++ /dev/null @@ -1,183 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: logical/identity.proto - -package logical // import "github.com/hashicorp/vault/logical" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Entity struct { - // ID is the unique identifier for the entity - ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"` - // Name is the human-friendly unique identifier for the entity - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Aliases contains thhe alias mappings for the given entity - Aliases []*Alias `protobuf:"bytes,3,rep,name=aliases,proto3" json:"aliases,omitempty"` - // Metadata represents the custom data tied to this entity - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Entity) Reset() { *m = Entity{} } -func (m *Entity) String() string { return proto.CompactTextString(m) } -func (*Entity) ProtoMessage() {} -func (*Entity) Descriptor() ([]byte, []int) { - return fileDescriptor_identity_8ee6f9f1922f77d7, []int{0} -} -func (m *Entity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Entity.Unmarshal(m, b) -} -func (m *Entity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Entity.Marshal(b, m, deterministic) -} -func (dst *Entity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Entity.Merge(dst, src) -} -func (m *Entity) XXX_Size() int { - return xxx_messageInfo_Entity.Size(m) -} -func (m *Entity) XXX_DiscardUnknown() { - xxx_messageInfo_Entity.DiscardUnknown(m) -} - -var xxx_messageInfo_Entity proto.InternalMessageInfo - -func (m *Entity) GetID() string { - if m != nil { - return m.ID - } - return "" -} - -func (m *Entity) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Entity) GetAliases() []*Alias { - if m != nil { - return m.Aliases - } - return nil -} - -func (m *Entity) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -type Alias struct { - // MountType is the backend mount's type to which this identity belongs - MountType string `protobuf:"bytes,1,opt,name=mount_type,json=mountType,proto3" json:"mount_type,omitempty"` - // MountAccessor is the identifier of the mount entry to which this - // identity belongs - MountAccessor string `protobuf:"bytes,2,opt,name=mount_accessor,json=mountAccessor,proto3" json:"mount_accessor,omitempty"` - // Name is the identifier of this identity in its authentication source - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - // Metadata represents the custom data tied to this alias - Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Alias) Reset() { *m = Alias{} } -func (m *Alias) String() string { return proto.CompactTextString(m) } -func (*Alias) ProtoMessage() {} -func (*Alias) Descriptor() ([]byte, []int) { - return fileDescriptor_identity_8ee6f9f1922f77d7, []int{1} -} -func (m *Alias) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Alias.Unmarshal(m, b) -} -func (m *Alias) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Alias.Marshal(b, m, deterministic) -} -func (dst *Alias) XXX_Merge(src proto.Message) { - xxx_messageInfo_Alias.Merge(dst, src) -} -func (m *Alias) XXX_Size() int { - return xxx_messageInfo_Alias.Size(m) -} -func (m *Alias) XXX_DiscardUnknown() { - xxx_messageInfo_Alias.DiscardUnknown(m) -} - -var xxx_messageInfo_Alias proto.InternalMessageInfo - -func (m *Alias) GetMountType() string { - if m != nil { - return m.MountType - } - return "" -} - -func (m *Alias) GetMountAccessor() string { - if m != nil { - return m.MountAccessor - } - return "" -} - -func (m *Alias) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Alias) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func init() { - proto.RegisterType((*Entity)(nil), "logical.Entity") - proto.RegisterMapType((map[string]string)(nil), "logical.Entity.MetadataEntry") - proto.RegisterType((*Alias)(nil), "logical.Alias") - proto.RegisterMapType((map[string]string)(nil), "logical.Alias.MetadataEntry") -} - -func init() { proto.RegisterFile("logical/identity.proto", fileDescriptor_identity_8ee6f9f1922f77d7) } - -var fileDescriptor_identity_8ee6f9f1922f77d7 = []byte{ - // 287 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x91, 0x4f, 0x4b, 0xc3, 0x40, - 0x10, 0xc5, 0x49, 0xd2, 0x3f, 0x76, 0xa4, 0x45, 0x06, 0x91, 0x20, 0x16, 0x4a, 0x50, 0xc8, 0x29, - 0x01, 0xbd, 0x54, 0x3d, 0x55, 0xda, 0x43, 0x0f, 0x5e, 0x82, 0x27, 0x2f, 0x32, 0x4d, 0x97, 0x66, - 0x31, 0xc9, 0x86, 0x64, 0x52, 0xc8, 0x97, 0xf4, 0xec, 0xc7, 0x91, 0x6e, 0xb6, 0xc1, 0xe2, 0xd9, - 0xdb, 0xec, 0xef, 0xcd, 0xce, 0xbe, 0x79, 0x0b, 0x57, 0xa9, 0xda, 0xc9, 0x98, 0xd2, 0x50, 0x6e, - 0x45, 0xce, 0x92, 0x9b, 0xa0, 0x28, 0x15, 0x2b, 0x1c, 0x1a, 0xee, 0x7d, 0x59, 0x30, 0x58, 0x69, - 0x05, 0x27, 0x60, 0xaf, 0x97, 0xae, 0x35, 0xb3, 0xfc, 0x51, 0x64, 0xaf, 0x97, 0x88, 0xd0, 0xcb, - 0x29, 0x13, 0xae, 0xad, 0x89, 0xae, 0xd1, 0x87, 0x21, 0xa5, 0x92, 0x2a, 0x51, 0xb9, 0xce, 0xcc, - 0xf1, 0xcf, 0xef, 0x27, 0x81, 0x99, 0x14, 0x2c, 0x0e, 0x3c, 0x3a, 0xca, 0xf8, 0x08, 0x67, 0x99, - 0x60, 0xda, 0x12, 0x93, 0xdb, 0xd3, 0xad, 0xd3, 0xae, 0xb5, 0x7d, 0x30, 0x78, 0x35, 0xfa, 0x2a, - 0xe7, 0xb2, 0x89, 0xba, 0xf6, 0xeb, 0x67, 0x18, 0x9f, 0x48, 0x78, 0x01, 0xce, 0xa7, 0x68, 0x8c, - 0xb5, 0x43, 0x89, 0x97, 0xd0, 0xdf, 0x53, 0x5a, 0x1f, 0xcd, 0xb5, 0x87, 0x27, 0x7b, 0x6e, 0x79, - 0xdf, 0x16, 0xf4, 0xb5, 0x15, 0x9c, 0x02, 0x64, 0xaa, 0xce, 0xf9, 0x83, 0x9b, 0x42, 0x98, 0xcb, - 0x23, 0x4d, 0xde, 0x9a, 0x42, 0xe0, 0x1d, 0x4c, 0x5a, 0x99, 0xe2, 0x58, 0x54, 0x95, 0x2a, 0xcd, - 0xac, 0xb1, 0xa6, 0x0b, 0x03, 0xbb, 0x14, 0x9c, 0x5f, 0x29, 0xcc, 0xff, 0xec, 0x76, 0x73, 0x1a, - 0xc3, 0xbf, 0xac, 0xf6, 0x72, 0xfb, 0xee, 0xed, 0x24, 0x27, 0xf5, 0x26, 0x88, 0x55, 0x16, 0x26, - 0x54, 0x25, 0x32, 0x56, 0x65, 0x11, 0xee, 0xa9, 0x4e, 0x39, 0x34, 0x06, 0x36, 0x03, 0xfd, 0xc3, - 0x0f, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbf, 0xfb, 0x6f, 0x8c, 0xfb, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/logical/identity.proto b/vendor/github.com/hashicorp/vault/logical/identity.proto deleted file mode 100644 index b9c567138..000000000 --- a/vendor/github.com/hashicorp/vault/logical/identity.proto +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/logical"; - -package logical; - -message Entity { - // ID is the unique identifier for the entity - string ID = 1; - - // Name is the human-friendly unique identifier for the entity - string name = 2; - - // Aliases contains thhe alias mappings for the given entity - repeated Alias aliases = 3; - - // Metadata represents the custom data tied to this entity - map metadata = 4; -} - -message Alias { - // MountType is the backend mount's type to which this identity belongs - string mount_type = 1; - - // MountAccessor is the identifier of the mount entry to which this - // identity belongs - string mount_accessor = 2; - - // Name is the identifier of this identity in its authentication source - string name = 3; - - // Metadata represents the custom data tied to this alias - map metadata = 4; -} diff --git a/vendor/github.com/hashicorp/vault/logical/lease.go b/vendor/github.com/hashicorp/vault/logical/lease.go deleted file mode 100644 index 90c089476..000000000 --- a/vendor/github.com/hashicorp/vault/logical/lease.go +++ /dev/null @@ -1,53 +0,0 @@ -package logical - -import ( - "time" -) - -// LeaseOptions is an embeddable struct to capture common lease -// settings between a Secret and Auth -type LeaseOptions struct { - // TTL is the duration that this secret is valid for. Vault - // will automatically revoke it after the duration. - TTL time.Duration `json:"lease"` - - // MaxTTL is the maximum duration that this secret is valid for. - MaxTTL time.Duration `json:"max_ttl"` - - // Renewable, if true, means that this secret can be renewed. - Renewable bool `json:"renewable"` - - // Increment will be the lease increment that the user requested. - // This is only available on a Renew operation and has no effect - // when returning a response. - Increment time.Duration `json:"-"` - - // IssueTime is the time of issue for the original lease. This is - // only available on a Renew operation and has no effect when returning - // a response. It can be used to enforce maximum lease periods by - // a logical backend. - IssueTime time.Time `json:"-"` -} - -// LeaseEnabled checks if leasing is enabled -func (l *LeaseOptions) LeaseEnabled() bool { - return l.TTL > 0 -} - -// LeaseTotal is the lease duration with a guard against a negative TTL -func (l *LeaseOptions) LeaseTotal() time.Duration { - if l.TTL <= 0 { - return 0 - } - - return l.TTL -} - -// ExpirationTime computes the time until expiration including the grace period -func (l *LeaseOptions) ExpirationTime() time.Time { - var expireTime time.Time - if l.LeaseEnabled() { - expireTime = time.Now().Add(l.LeaseTotal()) - } - return expireTime -} diff --git a/vendor/github.com/hashicorp/vault/logical/logical.go b/vendor/github.com/hashicorp/vault/logical/logical.go deleted file mode 100644 index a3456e967..000000000 --- a/vendor/github.com/hashicorp/vault/logical/logical.go +++ /dev/null @@ -1,126 +0,0 @@ -package logical - -import ( - "context" - - log "github.com/hashicorp/go-hclog" -) - -// BackendType is the type of backend that is being implemented -type BackendType uint32 - -// The these are the types of backends that can be derived from -// logical.Backend -const ( - TypeUnknown BackendType = 0 // This is also the zero-value for BackendType - TypeLogical BackendType = 1 - TypeCredential BackendType = 2 -) - -// Stringer implementation -func (b BackendType) String() string { - switch b { - case TypeLogical: - return "secret" - case TypeCredential: - return "auth" - } - - return "unknown" -} - -// Backend interface must be implemented to be "mountable" at -// a given path. Requests flow through a router which has various mount -// points that flow to a logical backend. The logic of each backend is flexible, -// and this is what allows materialized keys to function. There can be specialized -// logical backends for various upstreams (Consul, PostgreSQL, MySQL, etc) that can -// interact with remote APIs to generate keys dynamically. This interface also -// allows for a "procfs" like interaction, as internal state can be exposed by -// acting like a logical backend and being mounted. -type Backend interface { - // HandleRequest is used to handle a request and generate a response. - // The backends must check the operation type and handle appropriately. - HandleRequest(context.Context, *Request) (*Response, error) - - // SpecialPaths is a list of paths that are special in some way. - // See PathType for the types of special paths. The key is the type - // of the special path, and the value is a list of paths for this type. - // This is not a regular expression but is an exact match. If the path - // ends in '*' then it is a prefix-based match. The '*' can only appear - // at the end. - SpecialPaths() *Paths - - // System provides an interface to access certain system configuration - // information, such as globally configured default and max lease TTLs. - System() SystemView - - // Logger provides an interface to access the underlying logger. This - // is useful when a struct embeds a Backend-implemented struct that - // contains a private instance of logger. - Logger() log.Logger - - // HandleExistenceCheck is used to handle a request and generate a response - // indicating whether the given path exists or not; this is used to - // understand whether the request must have a Create or Update capability - // ACL applied. The first bool indicates whether an existence check - // function was found for the backend; the second indicates whether, if an - // existence check function was found, the item exists or not. - HandleExistenceCheck(context.Context, *Request) (bool, bool, error) - - // Cleanup is invoked during an unmount of a backend to allow it to - // handle any cleanup like connection closing or releasing of file handles. - Cleanup(context.Context) - - // InvalidateKey may be invoked when an object is modified that belongs - // to the backend. The backend can use this to clear any caches or reset - // internal state as needed. - InvalidateKey(context.Context, string) - - // Setup is used to set up the backend based on the provided backend - // configuration. - Setup(context.Context, *BackendConfig) error - - // Type returns the BackendType for the particular backend - Type() BackendType -} - -// BackendConfig is provided to the factory to initialize the backend -type BackendConfig struct { - // View should not be stored, and should only be used for initialization - StorageView Storage - - // The backend should use this logger. The log should not contain any secrets. - Logger log.Logger - - // System provides a view into a subset of safe system information that - // is useful for backends, such as the default/max lease TTLs - System SystemView - - // BackendUUID is a unique identifier provided to this backend. It's useful - // when a backend needs a consistent and unique string without using storage. - BackendUUID string - - // Config is the opaque user configuration provided when mounting - Config map[string]string -} - -// Factory is the factory function to create a logical backend. -type Factory func(context.Context, *BackendConfig) (Backend, error) - -// Paths is the structure of special paths that is used for SpecialPaths. -type Paths struct { - // Root are the paths that require a root token to access - Root []string - - // Unauthenticated are the paths that can be accessed without any auth. - Unauthenticated []string - - // LocalStorage are paths (prefixes) that are local to this instance; this - // indicates that these paths should not be replicated - LocalStorage []string - - // SealWrapStorage are storage paths that, when using a capable seal, - // should be seal wrapped with extra encryption. It is exact matching - // unless it ends with '/' in which case it will be treated as a prefix. - SealWrapStorage []string -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin.pb.go b/vendor/github.com/hashicorp/vault/logical/plugin.pb.go deleted file mode 100644 index 5de3ca7a2..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin.pb.go +++ /dev/null @@ -1,77 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: logical/plugin.proto - -package logical // import "github.com/hashicorp/vault/logical" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type PluginEnvironment struct { - // VaultVersion is the version of the Vault server - VaultVersion string `protobuf:"bytes,1,opt,name=vault_version,json=vaultVersion,proto3" json:"vault_version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PluginEnvironment) Reset() { *m = PluginEnvironment{} } -func (m *PluginEnvironment) String() string { return proto.CompactTextString(m) } -func (*PluginEnvironment) ProtoMessage() {} -func (*PluginEnvironment) Descriptor() ([]byte, []int) { - return fileDescriptor_plugin_c3e74d5a6c13acf1, []int{0} -} -func (m *PluginEnvironment) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PluginEnvironment.Unmarshal(m, b) -} -func (m *PluginEnvironment) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PluginEnvironment.Marshal(b, m, deterministic) -} -func (dst *PluginEnvironment) XXX_Merge(src proto.Message) { - xxx_messageInfo_PluginEnvironment.Merge(dst, src) -} -func (m *PluginEnvironment) XXX_Size() int { - return xxx_messageInfo_PluginEnvironment.Size(m) -} -func (m *PluginEnvironment) XXX_DiscardUnknown() { - xxx_messageInfo_PluginEnvironment.DiscardUnknown(m) -} - -var xxx_messageInfo_PluginEnvironment proto.InternalMessageInfo - -func (m *PluginEnvironment) GetVaultVersion() string { - if m != nil { - return m.VaultVersion - } - return "" -} - -func init() { - proto.RegisterType((*PluginEnvironment)(nil), "logical.PluginEnvironment") -} - -func init() { proto.RegisterFile("logical/plugin.proto", fileDescriptor_plugin_c3e74d5a6c13acf1) } - -var fileDescriptor_plugin_c3e74d5a6c13acf1 = []byte{ - // 133 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc9, 0xc9, 0x4f, 0xcf, - 0x4c, 0x4e, 0xcc, 0xd1, 0x2f, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x62, 0x87, 0x8a, 0x2a, 0x59, 0x70, 0x09, 0x06, 0x80, 0x25, 0x5c, 0xf3, 0xca, 0x32, 0x8b, - 0xf2, 0xf3, 0x72, 0x53, 0xf3, 0x4a, 0x84, 0x94, 0xb9, 0x78, 0xcb, 0x12, 0x4b, 0x73, 0x4a, 0xe2, - 0xcb, 0x52, 0x8b, 0x8a, 0x33, 0xf3, 0xf3, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x78, 0xc0, - 0x82, 0x61, 0x10, 0x31, 0x27, 0x95, 0x28, 0xa5, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, - 0xfc, 0x5c, 0xfd, 0x8c, 0xc4, 0xe2, 0x8c, 0xcc, 0xe4, 0xfc, 0xa2, 0x02, 0x7d, 0xb0, 0x22, 0x7d, - 0xa8, 0xf9, 0x49, 0x6c, 0x60, 0xfb, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa3, 0xff, 0x48, - 0xa9, 0x87, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin.proto b/vendor/github.com/hashicorp/vault/logical/plugin.proto deleted file mode 100644 index ec8493472..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/logical"; - -package logical; - -message PluginEnvironment { - // VaultVersion is the version of the Vault server - string vault_version = 1; -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend.go deleted file mode 100644 index b55a0aaef..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend.go +++ /dev/null @@ -1,64 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - "sync/atomic" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -// BackendPlugin is the plugin.Plugin implementation -type BackendPlugin struct { - Factory logical.Factory - metadataMode bool - Logger log.Logger -} - -// Server gets called when on plugin.Serve() -func (b *BackendPlugin) Server(broker *plugin.MuxBroker) (interface{}, error) { - return &backendPluginServer{ - factory: b.Factory, - broker: broker, - // We pass the logger down into the backend so go-plugin will forward - // logs for us. - logger: b.Logger, - }, nil -} - -// Client gets called on plugin.NewClient() -func (b BackendPlugin) Client(broker *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { - return &backendPluginClient{client: c, broker: broker, metadataMode: b.metadataMode}, nil -} - -func (b BackendPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - pb.RegisterBackendServer(s, &backendGRPCPluginServer{ - broker: broker, - factory: b.Factory, - // We pass the logger down into the backend so go-plugin will forward - // logs for us. - logger: b.Logger, - }) - return nil -} - -func (p *BackendPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - ret := &backendGRPCPluginClient{ - client: pb.NewBackendClient(c), - clientConn: c, - broker: broker, - cleanupCh: make(chan struct{}), - doneCtx: ctx, - } - - // Create the value and set the type - ret.server = new(atomic.Value) - ret.server.Store((*grpc.Server)(nil)) - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go deleted file mode 100644 index 43a442f4b..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend_client.go +++ /dev/null @@ -1,248 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "net/rpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/logical" -) - -var ( - ErrClientInMetadataMode = errors.New("plugin client can not perform action while in metadata mode") -) - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendPluginClient struct { - broker *plugin.MuxBroker - client *rpc.Client - metadataMode bool - - system logical.SystemView - logger log.Logger -} - -// HandleRequestArgs is the args for HandleRequest method. -type HandleRequestArgs struct { - StorageID uint32 - Request *logical.Request -} - -// HandleRequestReply is the reply for HandleRequest method. -type HandleRequestReply struct { - Response *logical.Response - Error error -} - -// SpecialPathsReply is the reply for SpecialPaths method. -type SpecialPathsReply struct { - Paths *logical.Paths -} - -// SystemReply is the reply for System method. -type SystemReply struct { - SystemView logical.SystemView - Error error -} - -// HandleExistenceCheckArgs is the args for HandleExistenceCheck method. -type HandleExistenceCheckArgs struct { - StorageID uint32 - Request *logical.Request -} - -// HandleExistenceCheckReply is the reply for HandleExistenceCheck method. -type HandleExistenceCheckReply struct { - CheckFound bool - Exists bool - Error error -} - -// SetupArgs is the args for Setup method. -type SetupArgs struct { - StorageID uint32 - LoggerID uint32 - SysViewID uint32 - Config map[string]string - BackendUUID string -} - -// SetupReply is the reply for Setup method. -type SetupReply struct { - Error error -} - -// TypeReply is the reply for the Type method. -type TypeReply struct { - Type logical.BackendType -} - -func (b *backendPluginClient) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.metadataMode { - return nil, ErrClientInMetadataMode - } - - // Do not send the storage, since go-plugin cannot serialize - // interfaces. The server will pick up the storage from the shim. - req.Storage = nil - args := &HandleRequestArgs{ - Request: req, - } - var reply HandleRequestReply - - if req.Connection != nil { - oldConnState := req.Connection.ConnState - req.Connection.ConnState = nil - defer func() { - req.Connection.ConnState = oldConnState - }() - } - - err := b.client.Call("Plugin.HandleRequest", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - if reply.Error.Error() == logical.ErrUnsupportedOperation.Error() { - return nil, logical.ErrUnsupportedOperation - } - - return reply.Response, reply.Error - } - - return reply.Response, nil -} - -func (b *backendPluginClient) SpecialPaths() *logical.Paths { - var reply SpecialPathsReply - err := b.client.Call("Plugin.SpecialPaths", new(interface{}), &reply) - if err != nil { - return nil - } - - return reply.Paths -} - -// System returns vault's system view. The backend client stores the view during -// Setup, so there is no need to shim the system just to get it back. -func (b *backendPluginClient) System() logical.SystemView { - return b.system -} - -// Logger returns vault's logger. The backend client stores the logger during -// Setup, so there is no need to shim the logger just to get it back. -func (b *backendPluginClient) Logger() log.Logger { - return b.logger -} - -func (b *backendPluginClient) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - if b.metadataMode { - return false, false, ErrClientInMetadataMode - } - - // Do not send the storage, since go-plugin cannot serialize - // interfaces. The server will pick up the storage from the shim. - req.Storage = nil - args := &HandleExistenceCheckArgs{ - Request: req, - } - var reply HandleExistenceCheckReply - - if req.Connection != nil { - oldConnState := req.Connection.ConnState - req.Connection.ConnState = nil - defer func() { - req.Connection.ConnState = oldConnState - }() - } - - err := b.client.Call("Plugin.HandleExistenceCheck", args, &reply) - if err != nil { - return false, false, err - } - if reply.Error != nil { - // THINKING: Should be be a switch on all error types? - if reply.Error.Error() == logical.ErrUnsupportedPath.Error() { - return false, false, logical.ErrUnsupportedPath - } - return false, false, reply.Error - } - - return reply.CheckFound, reply.Exists, nil -} - -func (b *backendPluginClient) Cleanup(ctx context.Context) { - b.client.Call("Plugin.Cleanup", new(interface{}), &struct{}{}) -} - -func (b *backendPluginClient) Initialize(ctx context.Context) error { - if b.metadataMode { - return ErrClientInMetadataMode - } - err := b.client.Call("Plugin.Initialize", new(interface{}), &struct{}{}) - return err -} - -func (b *backendPluginClient) InvalidateKey(ctx context.Context, key string) { - if b.metadataMode { - return - } - b.client.Call("Plugin.InvalidateKey", key, &struct{}{}) -} - -func (b *backendPluginClient) Setup(ctx context.Context, config *logical.BackendConfig) error { - // Shim logical.Storage - storageImpl := config.StorageView - if b.metadataMode { - storageImpl = &NOOPStorage{} - } - storageID := b.broker.NextId() - go b.broker.AcceptAndServe(storageID, &StorageServer{ - impl: storageImpl, - }) - - // Shim logical.SystemView - sysViewImpl := config.System - if b.metadataMode { - sysViewImpl = &logical.StaticSystemView{} - } - sysViewID := b.broker.NextId() - go b.broker.AcceptAndServe(sysViewID, &SystemViewServer{ - impl: sysViewImpl, - }) - - args := &SetupArgs{ - StorageID: storageID, - SysViewID: sysViewID, - Config: config.Config, - BackendUUID: config.BackendUUID, - } - var reply SetupReply - - err := b.client.Call("Plugin.Setup", args, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - - // Set system and logger for getter methods - b.system = config.System - b.logger = config.Logger - - return nil -} - -func (b *backendPluginClient) Type() logical.BackendType { - var reply TypeReply - err := b.client.Call("Plugin.Type", new(interface{}), &reply) - if err != nil { - return logical.TypeUnknown - } - - return logical.BackendType(reply.Type) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go b/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go deleted file mode 100644 index a03e089fb..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/backend_server.go +++ /dev/null @@ -1,148 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "net/rpc" - - "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -var ( - ErrServerInMetadataMode = errors.New("plugin server can not perform action while in metadata mode") -) - -// backendPluginServer is the RPC server that backendPluginClient talks to, -// it methods conforming to requirements by net/rpc -type backendPluginServer struct { - broker *plugin.MuxBroker - backend logical.Backend - factory logical.Factory - - logger hclog.Logger - sysViewClient *rpc.Client - storageClient *rpc.Client -} - -func (b *backendPluginServer) HandleRequest(args *HandleRequestArgs, reply *HandleRequestReply) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - storage := &StorageClient{client: b.storageClient} - args.Request.Storage = storage - - resp, err := b.backend.HandleRequest(context.Background(), args.Request) - *reply = HandleRequestReply{ - Response: resp, - Error: wrapError(err), - } - - return nil -} - -func (b *backendPluginServer) SpecialPaths(_ interface{}, reply *SpecialPathsReply) error { - *reply = SpecialPathsReply{ - Paths: b.backend.SpecialPaths(), - } - return nil -} - -func (b *backendPluginServer) HandleExistenceCheck(args *HandleExistenceCheckArgs, reply *HandleExistenceCheckReply) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - storage := &StorageClient{client: b.storageClient} - args.Request.Storage = storage - - checkFound, exists, err := b.backend.HandleExistenceCheck(context.TODO(), args.Request) - *reply = HandleExistenceCheckReply{ - CheckFound: checkFound, - Exists: exists, - Error: wrapError(err), - } - - return nil -} - -func (b *backendPluginServer) Cleanup(_ interface{}, _ *struct{}) error { - b.backend.Cleanup(context.Background()) - - // Close rpc clients - b.sysViewClient.Close() - b.storageClient.Close() - return nil -} - -func (b *backendPluginServer) InvalidateKey(args string, _ *struct{}) error { - if pluginutil.InMetadataMode() { - return ErrServerInMetadataMode - } - - b.backend.InvalidateKey(context.Background(), args) - return nil -} - -// Setup dials into the plugin's broker to get a shimmed storage, logger, and -// system view of the backend. This method also instantiates the underlying -// backend through its factory func for the server side of the plugin. -func (b *backendPluginServer) Setup(args *SetupArgs, reply *SetupReply) error { - // Dial for storage - storageConn, err := b.broker.Dial(args.StorageID) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - return nil - } - rawStorageClient := rpc.NewClient(storageConn) - b.storageClient = rawStorageClient - - storage := &StorageClient{client: rawStorageClient} - - // Dial for sys view - sysViewConn, err := b.broker.Dial(args.SysViewID) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - return nil - } - rawSysViewClient := rpc.NewClient(sysViewConn) - b.sysViewClient = rawSysViewClient - - sysView := &SystemViewClient{client: rawSysViewClient} - - config := &logical.BackendConfig{ - StorageView: storage, - Logger: b.logger, - System: sysView, - Config: args.Config, - BackendUUID: args.BackendUUID, - } - - // Call the underlying backend factory after shims have been created - // to set b.backend - backend, err := b.factory(context.Background(), config) - if err != nil { - *reply = SetupReply{ - Error: wrapError(err), - } - } - b.backend = backend - - return nil -} - -func (b *backendPluginServer) Type(_ interface{}, reply *TypeReply) error { - *reply = TypeReply{ - Type: b.backend.Type(), - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go deleted file mode 100644 index a65eeebeb..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend.go +++ /dev/null @@ -1,12 +0,0 @@ -package plugin - -import ( - "math" - - "google.golang.org/grpc" -) - -var largeMsgGRPCCallOpts []grpc.CallOption = []grpc.CallOption{ - grpc.MaxCallSendMsgSize(math.MaxInt32), - grpc.MaxCallRecvMsgSize(math.MaxInt32), -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go deleted file mode 100644 index 60ef18280..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_client.go +++ /dev/null @@ -1,245 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "math" - "sync/atomic" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -var ErrPluginShutdown = errors.New("plugin is shut down") - -// Validate backendGRPCPluginClient satisfies the logical.Backend interface -var _ logical.Backend = &backendGRPCPluginClient{} - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendGRPCPluginClient struct { - broker *plugin.GRPCBroker - client pb.BackendClient - metadataMode bool - - system logical.SystemView - logger log.Logger - - // This is used to signal to the Cleanup function that it can proceed - // because we have a defined server - cleanupCh chan struct{} - - // server is the grpc server used for serving storage and sysview requests. - server *atomic.Value - - // clientConn is the underlying grpc connection to the server, we store it - // so it can be cleaned up. - clientConn *grpc.ClientConn - doneCtx context.Context -} - -func (b *backendGRPCPluginClient) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - if b.metadataMode { - return nil, ErrClientInMetadataMode - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - protoReq, err := pb.LogicalRequestToProtoRequest(req) - if err != nil { - return nil, err - } - - reply, err := b.client.HandleRequest(ctx, &pb.HandleRequestArgs{ - Request: protoReq, - }, largeMsgGRPCCallOpts...) - if err != nil { - if b.doneCtx.Err() != nil { - return nil, ErrPluginShutdown - } - - return nil, err - } - resp, err := pb.ProtoResponseToLogicalResponse(reply.Response) - if err != nil { - return nil, err - } - if reply.Err != nil { - return resp, pb.ProtoErrToErr(reply.Err) - } - - return resp, nil -} - -func (b *backendGRPCPluginClient) SpecialPaths() *logical.Paths { - reply, err := b.client.SpecialPaths(b.doneCtx, &pb.Empty{}) - if err != nil { - return nil - } - - if reply.Paths == nil { - return nil - } - - return &logical.Paths{ - Root: reply.Paths.Root, - Unauthenticated: reply.Paths.Unauthenticated, - LocalStorage: reply.Paths.LocalStorage, - SealWrapStorage: reply.Paths.SealWrapStorage, - } -} - -// System returns vault's system view. The backend client stores the view during -// Setup, so there is no need to shim the system just to get it back. -func (b *backendGRPCPluginClient) System() logical.SystemView { - return b.system -} - -// Logger returns vault's logger. The backend client stores the logger during -// Setup, so there is no need to shim the logger just to get it back. -func (b *backendGRPCPluginClient) Logger() log.Logger { - return b.logger -} - -func (b *backendGRPCPluginClient) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - if b.metadataMode { - return false, false, ErrClientInMetadataMode - } - - protoReq, err := pb.LogicalRequestToProtoRequest(req) - if err != nil { - return false, false, err - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - reply, err := b.client.HandleExistenceCheck(ctx, &pb.HandleExistenceCheckArgs{ - Request: protoReq, - }, largeMsgGRPCCallOpts...) - if err != nil { - if b.doneCtx.Err() != nil { - return false, false, ErrPluginShutdown - } - return false, false, err - } - if reply.Err != nil { - return false, false, pb.ProtoErrToErr(reply.Err) - } - - return reply.CheckFound, reply.Exists, nil -} - -func (b *backendGRPCPluginClient) Cleanup(ctx context.Context) { - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - b.client.Cleanup(ctx, &pb.Empty{}) - - // This will block until Setup has run the function to create a new server - // in b.server. If we stop here before it has a chance to actually start - // listening, when it starts listening it will immediatley error out and - // exit, which is fine. Overall this ensures that we do not miss stopping - // the server if it ends up being created after Cleanup is called. - <-b.cleanupCh - server := b.server.Load() - if server != nil { - server.(*grpc.Server).GracefulStop() - } - b.clientConn.Close() -} - -func (b *backendGRPCPluginClient) InvalidateKey(ctx context.Context, key string) { - if b.metadataMode { - return - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - b.client.InvalidateKey(ctx, &pb.InvalidateKeyArgs{ - Key: key, - }) -} - -func (b *backendGRPCPluginClient) Setup(ctx context.Context, config *logical.BackendConfig) error { - // Shim logical.Storage - storageImpl := config.StorageView - if b.metadataMode { - storageImpl = &NOOPStorage{} - } - storage := &GRPCStorageServer{ - impl: storageImpl, - } - - // Shim logical.SystemView - sysViewImpl := config.System - if b.metadataMode { - sysViewImpl = &logical.StaticSystemView{} - } - sysView := &gRPCSystemViewServer{ - impl: sysViewImpl, - } - - // Register the server in this closure. - serverFunc := func(opts []grpc.ServerOption) *grpc.Server { - opts = append(opts, grpc.MaxRecvMsgSize(math.MaxInt32)) - opts = append(opts, grpc.MaxSendMsgSize(math.MaxInt32)) - - s := grpc.NewServer(opts...) - pb.RegisterSystemViewServer(s, sysView) - pb.RegisterStorageServer(s, storage) - b.server.Store(s) - close(b.cleanupCh) - return s - } - brokerID := b.broker.NextId() - go b.broker.AcceptAndServe(brokerID, serverFunc) - - args := &pb.SetupArgs{ - BrokerID: brokerID, - Config: config.Config, - BackendUUID: config.BackendUUID, - } - - ctx, cancel := context.WithCancel(ctx) - quitCh := pluginutil.CtxCancelIfCanceled(cancel, b.doneCtx) - defer close(quitCh) - defer cancel() - - reply, err := b.client.Setup(ctx, args) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - - // Set system and logger for getter methods - b.system = config.System - b.logger = config.Logger - - return nil -} - -func (b *backendGRPCPluginClient) Type() logical.BackendType { - reply, err := b.client.Type(b.doneCtx, &pb.Empty{}) - if err != nil { - return logical.TypeUnknown - } - - return logical.BackendType(reply.Type) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go deleted file mode 100644 index 7869a70b2..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_backend_server.go +++ /dev/null @@ -1,142 +0,0 @@ -package plugin - -import ( - "context" - - log "github.com/hashicorp/go-hclog" - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" - "google.golang.org/grpc" -) - -type backendGRPCPluginServer struct { - broker *plugin.GRPCBroker - backend logical.Backend - - factory logical.Factory - - brokeredClient *grpc.ClientConn - - logger log.Logger -} - -// Setup dials into the plugin's broker to get a shimmed storage, logger, and -// system view of the backend. This method also instantiates the underlying -// backend through its factory func for the server side of the plugin. -func (b *backendGRPCPluginServer) Setup(ctx context.Context, args *pb.SetupArgs) (*pb.SetupReply, error) { - // Dial for storage - brokeredClient, err := b.broker.Dial(args.BrokerID) - if err != nil { - return &pb.SetupReply{}, err - } - b.brokeredClient = brokeredClient - storage := newGRPCStorageClient(brokeredClient) - sysView := newGRPCSystemView(brokeredClient) - - config := &logical.BackendConfig{ - StorageView: storage, - Logger: b.logger, - System: sysView, - Config: args.Config, - BackendUUID: args.BackendUUID, - } - - // Call the underlying backend factory after shims have been created - // to set b.backend - backend, err := b.factory(ctx, config) - if err != nil { - return &pb.SetupReply{ - Err: pb.ErrToString(err), - }, nil - } - b.backend = backend - - return &pb.SetupReply{}, nil -} - -func (b *backendGRPCPluginServer) HandleRequest(ctx context.Context, args *pb.HandleRequestArgs) (*pb.HandleRequestReply, error) { - if pluginutil.InMetadataMode() { - return &pb.HandleRequestReply{}, ErrServerInMetadataMode - } - - logicalReq, err := pb.ProtoRequestToLogicalRequest(args.Request) - if err != nil { - return &pb.HandleRequestReply{}, err - } - - logicalReq.Storage = newGRPCStorageClient(b.brokeredClient) - - resp, respErr := b.backend.HandleRequest(ctx, logicalReq) - - pbResp, err := pb.LogicalResponseToProtoResponse(resp) - if err != nil { - return &pb.HandleRequestReply{}, err - } - - return &pb.HandleRequestReply{ - Response: pbResp, - Err: pb.ErrToProtoErr(respErr), - }, nil -} - -func (b *backendGRPCPluginServer) SpecialPaths(ctx context.Context, args *pb.Empty) (*pb.SpecialPathsReply, error) { - paths := b.backend.SpecialPaths() - if paths == nil { - return &pb.SpecialPathsReply{ - Paths: nil, - }, nil - } - - return &pb.SpecialPathsReply{ - Paths: &pb.Paths{ - Root: paths.Root, - Unauthenticated: paths.Unauthenticated, - LocalStorage: paths.LocalStorage, - SealWrapStorage: paths.SealWrapStorage, - }, - }, nil -} - -func (b *backendGRPCPluginServer) HandleExistenceCheck(ctx context.Context, args *pb.HandleExistenceCheckArgs) (*pb.HandleExistenceCheckReply, error) { - if pluginutil.InMetadataMode() { - return &pb.HandleExistenceCheckReply{}, ErrServerInMetadataMode - } - - logicalReq, err := pb.ProtoRequestToLogicalRequest(args.Request) - if err != nil { - return &pb.HandleExistenceCheckReply{}, err - } - logicalReq.Storage = newGRPCStorageClient(b.brokeredClient) - - checkFound, exists, err := b.backend.HandleExistenceCheck(ctx, logicalReq) - return &pb.HandleExistenceCheckReply{ - CheckFound: checkFound, - Exists: exists, - Err: pb.ErrToProtoErr(err), - }, nil -} - -func (b *backendGRPCPluginServer) Cleanup(ctx context.Context, _ *pb.Empty) (*pb.Empty, error) { - b.backend.Cleanup(ctx) - - // Close rpc clients - b.brokeredClient.Close() - return &pb.Empty{}, nil -} - -func (b *backendGRPCPluginServer) InvalidateKey(ctx context.Context, args *pb.InvalidateKeyArgs) (*pb.Empty, error) { - if pluginutil.InMetadataMode() { - return &pb.Empty{}, ErrServerInMetadataMode - } - - b.backend.InvalidateKey(ctx, args.Key) - return &pb.Empty{}, nil -} - -func (b *backendGRPCPluginServer) Type(ctx context.Context, _ *pb.Empty) (*pb.TypeReply, error) { - return &pb.TypeReply{ - Type: uint32(b.backend.Type()), - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go deleted file mode 100644 index ffe133900..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_storage.go +++ /dev/null @@ -1,110 +0,0 @@ -package plugin - -import ( - "context" - "errors" - - "google.golang.org/grpc" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -func newGRPCStorageClient(conn *grpc.ClientConn) *GRPCStorageClient { - return &GRPCStorageClient{ - client: pb.NewStorageClient(conn), - } -} - -// GRPCStorageClient is an implementation of logical.Storage that communicates -// over RPC. -type GRPCStorageClient struct { - client pb.StorageClient -} - -func (s *GRPCStorageClient) List(ctx context.Context, prefix string) ([]string, error) { - reply, err := s.client.List(ctx, &pb.StorageListArgs{ - Prefix: prefix, - }, largeMsgGRPCCallOpts...) - if err != nil { - return []string{}, err - } - if reply.Err != "" { - return reply.Keys, errors.New(reply.Err) - } - return reply.Keys, nil -} - -func (s *GRPCStorageClient) Get(ctx context.Context, key string) (*logical.StorageEntry, error) { - reply, err := s.client.Get(ctx, &pb.StorageGetArgs{ - Key: key, - }, largeMsgGRPCCallOpts...) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - return pb.ProtoStorageEntryToLogicalStorageEntry(reply.Entry), nil -} - -func (s *GRPCStorageClient) Put(ctx context.Context, entry *logical.StorageEntry) error { - reply, err := s.client.Put(ctx, &pb.StoragePutArgs{ - Entry: pb.LogicalStorageEntryToProtoStorageEntry(entry), - }, largeMsgGRPCCallOpts...) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - return nil -} - -func (s *GRPCStorageClient) Delete(ctx context.Context, key string) error { - reply, err := s.client.Delete(ctx, &pb.StorageDeleteArgs{ - Key: key, - }) - if err != nil { - return err - } - if reply.Err != "" { - return errors.New(reply.Err) - } - return nil -} - -// StorageServer is a net/rpc compatible structure for serving -type GRPCStorageServer struct { - impl logical.Storage -} - -func (s *GRPCStorageServer) List(ctx context.Context, args *pb.StorageListArgs) (*pb.StorageListReply, error) { - keys, err := s.impl.List(ctx, args.Prefix) - return &pb.StorageListReply{ - Keys: keys, - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Get(ctx context.Context, args *pb.StorageGetArgs) (*pb.StorageGetReply, error) { - storageEntry, err := s.impl.Get(ctx, args.Key) - return &pb.StorageGetReply{ - Entry: pb.LogicalStorageEntryToProtoStorageEntry(storageEntry), - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Put(ctx context.Context, args *pb.StoragePutArgs) (*pb.StoragePutReply, error) { - err := s.impl.Put(ctx, pb.ProtoStorageEntryToLogicalStorageEntry(args.Entry)) - return &pb.StoragePutReply{ - Err: pb.ErrToString(err), - }, nil -} - -func (s *GRPCStorageServer) Delete(ctx context.Context, args *pb.StorageDeleteArgs) (*pb.StorageDeleteReply, error) { - err := s.impl.Delete(ctx, args.Key) - return &pb.StorageDeleteReply{ - Err: pb.ErrToString(err), - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go b/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go deleted file mode 100644 index a0670801d..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/grpc_system.go +++ /dev/null @@ -1,265 +0,0 @@ -package plugin - -import ( - "context" - "encoding/json" - "errors" - "time" - - "google.golang.org/grpc" - - "fmt" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/plugin/pb" -) - -func newGRPCSystemView(conn *grpc.ClientConn) *gRPCSystemViewClient { - return &gRPCSystemViewClient{ - client: pb.NewSystemViewClient(conn), - } -} - -type gRPCSystemViewClient struct { - client pb.SystemViewClient -} - -func (s *gRPCSystemViewClient) DefaultLeaseTTL() time.Duration { - reply, err := s.client.DefaultLeaseTTL(context.Background(), &pb.Empty{}) - if err != nil { - return 0 - } - - return time.Duration(reply.TTL) -} - -func (s *gRPCSystemViewClient) MaxLeaseTTL() time.Duration { - reply, err := s.client.MaxLeaseTTL(context.Background(), &pb.Empty{}) - if err != nil { - return 0 - } - - return time.Duration(reply.TTL) -} - -func (s *gRPCSystemViewClient) SudoPrivilege(ctx context.Context, path string, token string) bool { - reply, err := s.client.SudoPrivilege(ctx, &pb.SudoPrivilegeArgs{ - Path: path, - Token: token, - }) - if err != nil { - return false - } - - return reply.Sudo -} - -func (s *gRPCSystemViewClient) Tainted() bool { - reply, err := s.client.Tainted(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Tainted -} - -func (s *gRPCSystemViewClient) CachingDisabled() bool { - reply, err := s.client.CachingDisabled(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Disabled -} - -func (s *gRPCSystemViewClient) ReplicationState() consts.ReplicationState { - reply, err := s.client.ReplicationState(context.Background(), &pb.Empty{}) - if err != nil { - return consts.ReplicationUnknown - } - - return consts.ReplicationState(reply.State) -} - -func (s *gRPCSystemViewClient) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - buf, err := json.Marshal(data) - if err != nil { - return nil, err - } - - reply, err := s.client.ResponseWrapData(ctx, &pb.ResponseWrapDataArgs{ - Data: string(buf[:]), - TTL: int64(ttl), - JWT: false, - }) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - - info, err := pb.ProtoResponseWrapInfoToLogicalResponseWrapInfo(reply.WrapInfo) - if err != nil { - return nil, err - } - - return info, nil -} - -func (s *gRPCSystemViewClient) LookupPlugin(ctx context.Context, name string) (*pluginutil.PluginRunner, error) { - return nil, fmt.Errorf("cannot call LookupPlugin from a plugin backend") -} - -func (s *gRPCSystemViewClient) MlockEnabled() bool { - reply, err := s.client.MlockEnabled(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Enabled -} - -func (s *gRPCSystemViewClient) LocalMount() bool { - reply, err := s.client.LocalMount(context.Background(), &pb.Empty{}) - if err != nil { - return false - } - - return reply.Local -} - -func (s *gRPCSystemViewClient) EntityInfo(entityID string) (*logical.Entity, error) { - reply, err := s.client.EntityInfo(context.Background(), &pb.EntityInfoArgs{ - EntityID: entityID, - }) - if err != nil { - return nil, err - } - if reply.Err != "" { - return nil, errors.New(reply.Err) - } - - return reply.Entity, nil -} - -func (s *gRPCSystemViewClient) PluginEnv(ctx context.Context) (*logical.PluginEnvironment, error) { - reply, err := s.client.PluginEnv(ctx, &pb.Empty{}) - if err != nil { - return nil, err - } - - return reply.PluginEnvironment, nil -} - -type gRPCSystemViewServer struct { - impl logical.SystemView -} - -func (s *gRPCSystemViewServer) DefaultLeaseTTL(ctx context.Context, _ *pb.Empty) (*pb.TTLReply, error) { - ttl := s.impl.DefaultLeaseTTL() - return &pb.TTLReply{ - TTL: int64(ttl), - }, nil -} - -func (s *gRPCSystemViewServer) MaxLeaseTTL(ctx context.Context, _ *pb.Empty) (*pb.TTLReply, error) { - ttl := s.impl.MaxLeaseTTL() - return &pb.TTLReply{ - TTL: int64(ttl), - }, nil -} - -func (s *gRPCSystemViewServer) SudoPrivilege(ctx context.Context, args *pb.SudoPrivilegeArgs) (*pb.SudoPrivilegeReply, error) { - sudo := s.impl.SudoPrivilege(ctx, args.Path, args.Token) - return &pb.SudoPrivilegeReply{ - Sudo: sudo, - }, nil -} - -func (s *gRPCSystemViewServer) Tainted(ctx context.Context, _ *pb.Empty) (*pb.TaintedReply, error) { - tainted := s.impl.Tainted() - return &pb.TaintedReply{ - Tainted: tainted, - }, nil -} - -func (s *gRPCSystemViewServer) CachingDisabled(ctx context.Context, _ *pb.Empty) (*pb.CachingDisabledReply, error) { - cachingDisabled := s.impl.CachingDisabled() - return &pb.CachingDisabledReply{ - Disabled: cachingDisabled, - }, nil -} - -func (s *gRPCSystemViewServer) ReplicationState(ctx context.Context, _ *pb.Empty) (*pb.ReplicationStateReply, error) { - replicationState := s.impl.ReplicationState() - return &pb.ReplicationStateReply{ - State: int32(replicationState), - }, nil -} - -func (s *gRPCSystemViewServer) ResponseWrapData(ctx context.Context, args *pb.ResponseWrapDataArgs) (*pb.ResponseWrapDataReply, error) { - data := map[string]interface{}{} - err := json.Unmarshal([]byte(args.Data), &data) - if err != nil { - return &pb.ResponseWrapDataReply{}, err - } - - // Do not allow JWTs to be returned - info, err := s.impl.ResponseWrapData(ctx, data, time.Duration(args.TTL), false) - if err != nil { - return &pb.ResponseWrapDataReply{ - Err: pb.ErrToString(err), - }, nil - } - - pbInfo, err := pb.LogicalResponseWrapInfoToProtoResponseWrapInfo(info) - if err != nil { - return &pb.ResponseWrapDataReply{}, err - } - - return &pb.ResponseWrapDataReply{ - WrapInfo: pbInfo, - }, nil -} - -func (s *gRPCSystemViewServer) MlockEnabled(ctx context.Context, _ *pb.Empty) (*pb.MlockEnabledReply, error) { - enabled := s.impl.MlockEnabled() - return &pb.MlockEnabledReply{ - Enabled: enabled, - }, nil -} - -func (s *gRPCSystemViewServer) LocalMount(ctx context.Context, _ *pb.Empty) (*pb.LocalMountReply, error) { - local := s.impl.LocalMount() - return &pb.LocalMountReply{ - Local: local, - }, nil -} - -func (s *gRPCSystemViewServer) EntityInfo(ctx context.Context, args *pb.EntityInfoArgs) (*pb.EntityInfoReply, error) { - entity, err := s.impl.EntityInfo(args.EntityID) - if err != nil { - return &pb.EntityInfoReply{ - Err: pb.ErrToString(err), - }, nil - } - return &pb.EntityInfoReply{ - Entity: entity, - }, nil -} - -func (s *gRPCSystemViewServer) PluginEnv(ctx context.Context, _ *pb.Empty) (*pb.PluginEnvReply, error) { - pluginEnv, err := s.impl.PluginEnv(ctx) - if err != nil { - return &pb.PluginEnvReply{ - Err: pb.ErrToString(err), - }, nil - } - return &pb.PluginEnvReply{ - PluginEnvironment: pluginEnv, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/logger.go b/vendor/github.com/hashicorp/vault/logical/plugin/logger.go deleted file mode 100644 index a59a8a3da..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/logger.go +++ /dev/null @@ -1,134 +0,0 @@ -package plugin - -import hclog "github.com/hashicorp/go-hclog" - -type LoggerServer struct { - logger hclog.Logger -} - -func (l *LoggerServer) Trace(args *LoggerArgs, _ *struct{}) error { - l.logger.Trace(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Debug(args *LoggerArgs, _ *struct{}) error { - l.logger.Debug(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Info(args *LoggerArgs, _ *struct{}) error { - l.logger.Info(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Warn(args *LoggerArgs, reply *LoggerReply) error { - l.logger.Warn(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Error(args *LoggerArgs, reply *LoggerReply) error { - l.logger.Error(args.Msg, args.Args...) - return nil -} - -func (l *LoggerServer) Log(args *LoggerArgs, _ *struct{}) error { - - switch translateLevel(args.Level) { - - case hclog.Trace: - l.logger.Trace(args.Msg, args.Args...) - - case hclog.Debug: - l.logger.Debug(args.Msg, args.Args...) - - case hclog.Info: - l.logger.Info(args.Msg, args.Args...) - - case hclog.Warn: - l.logger.Warn(args.Msg, args.Args...) - - case hclog.Error: - l.logger.Error(args.Msg, args.Args...) - - case hclog.NoLevel: - } - return nil -} - -func (l *LoggerServer) SetLevel(args int, _ *struct{}) error { - level := translateLevel(args) - l.logger = hclog.New(&hclog.LoggerOptions{Level: level}) - return nil -} - -func (l *LoggerServer) IsTrace(args interface{}, reply *LoggerReply) error { - result := l.logger.IsTrace() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsDebug(args interface{}, reply *LoggerReply) error { - result := l.logger.IsDebug() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsInfo(args interface{}, reply *LoggerReply) error { - result := l.logger.IsInfo() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -func (l *LoggerServer) IsWarn(args interface{}, reply *LoggerReply) error { - result := l.logger.IsWarn() - *reply = LoggerReply{ - IsTrue: result, - } - return nil -} - -type LoggerArgs struct { - Level int - Msg string - Args []interface{} -} - -// LoggerReply contains the RPC reply. Not all fields may be used -// for a particular RPC call. -type LoggerReply struct { - IsTrue bool - Error error -} - -func translateLevel(logxiLevel int) hclog.Level { - - switch logxiLevel { - - case 1000, 10: - // logxi.LevelAll, logxi.LevelTrace: - return hclog.Trace - - case 7: - // logxi.LevelDebug: - return hclog.Debug - - case 6, 5: - // logxi.LevelInfo, logxi.LevelNotice: - return hclog.Info - - case 4: - // logxi.LevelWarn: - return hclog.Warn - - case 3, 2, 1, -1: - // logxi.LevelError, logxi.LevelFatal, logxi.LevelAlert, logxi.LevelEmergency: - return hclog.Error - } - return hclog.NoLevel -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go b/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go deleted file mode 100644 index d9aeed0f7..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/middleware.go +++ /dev/null @@ -1,91 +0,0 @@ -package plugin - -import ( - "context" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/logical" -) - -// backendPluginClient implements logical.Backend and is the -// go-plugin client. -type backendTracingMiddleware struct { - logger log.Logger - - next logical.Backend -} - -// Validate the backendTracingMiddle object satisfies the backend interface -var _ logical.Backend = &backendTracingMiddleware{} - -func (b *backendTracingMiddleware) HandleRequest(ctx context.Context, req *logical.Request) (resp *logical.Response, err error) { - defer func(then time.Time) { - b.logger.Trace("handle request", "path", req.Path, "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("handle request", "path", req.Path, "status", "started") - return b.next.HandleRequest(ctx, req) -} - -func (b *backendTracingMiddleware) SpecialPaths() *logical.Paths { - defer func(then time.Time) { - b.logger.Trace("special paths", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("special paths", "status", "started") - return b.next.SpecialPaths() -} - -func (b *backendTracingMiddleware) System() logical.SystemView { - return b.next.System() -} - -func (b *backendTracingMiddleware) Logger() log.Logger { - return b.next.Logger() -} - -func (b *backendTracingMiddleware) HandleExistenceCheck(ctx context.Context, req *logical.Request) (found bool, exists bool, err error) { - defer func(then time.Time) { - b.logger.Trace("handle existence check", "path", req.Path, "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("handle existence check", "path", req.Path, "status", "started") - return b.next.HandleExistenceCheck(ctx, req) -} - -func (b *backendTracingMiddleware) Cleanup(ctx context.Context) { - defer func(then time.Time) { - b.logger.Trace("cleanup", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("cleanup", "status", "started") - b.next.Cleanup(ctx) -} - -func (b *backendTracingMiddleware) InvalidateKey(ctx context.Context, key string) { - defer func(then time.Time) { - b.logger.Trace("invalidate key", "key", key, "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("invalidate key", "key", key, "status", "started") - b.next.InvalidateKey(ctx, key) -} - -func (b *backendTracingMiddleware) Setup(ctx context.Context, config *logical.BackendConfig) (err error) { - defer func(then time.Time) { - b.logger.Trace("setup", "status", "finished", "err", err, "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("setup", "status", "started") - return b.next.Setup(ctx, config) -} - -func (b *backendTracingMiddleware) Type() logical.BackendType { - defer func(then time.Time) { - b.logger.Trace("type", "status", "finished", "took", time.Since(then)) - }(time.Now()) - - b.logger.Trace("type", "status", "started") - return b.next.Type() -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go b/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go deleted file mode 100644 index 754494b8f..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/plugin.go +++ /dev/null @@ -1,176 +0,0 @@ -package plugin - -import ( - "context" - "crypto/ecdsa" - "crypto/rsa" - "encoding/gob" - "errors" - "fmt" - "time" - - "sync" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -// init registers basic structs with gob which will be used to transport complex -// types through the plugin server and client. -func init() { - // Common basic structs - gob.Register([]interface{}{}) - gob.Register(map[string]interface{}{}) - gob.Register(map[string]string{}) - gob.Register(map[string]int{}) - - // Register these types since we have to serialize and de-serialize - // tls.ConnectionState over the wire as part of logical.Request.Connection. - gob.Register(rsa.PublicKey{}) - gob.Register(ecdsa.PublicKey{}) - gob.Register(time.Duration(0)) - - // Custom common error types for requests. If you add something here, you must - // also add it to the switch statement in `wrapError`! - gob.Register(&plugin.BasicError{}) - gob.Register(logical.CodedError(0, "")) - gob.Register(&logical.StatusBadRequest{}) -} - -// BackendPluginClient is a wrapper around backendPluginClient -// that also contains its plugin.Client instance. It's primarily -// used to cleanly kill the client on Cleanup() -type BackendPluginClient struct { - client *plugin.Client - sync.Mutex - - logical.Backend -} - -// Cleanup calls the RPC client's Cleanup() func and also calls -// the go-plugin's client Kill() func -func (b *BackendPluginClient) Cleanup(ctx context.Context) { - b.Backend.Cleanup(ctx) - b.client.Kill() -} - -// NewBackend will return an instance of an RPC-based client implementation of the backend for -// external plugins, or a concrete implementation of the backend if it is a builtin backend. -// The backend is returned as a logical.Backend interface. The isMetadataMode param determines whether -// the plugin should run in metadata mode. -func NewBackend(ctx context.Context, pluginName string, sys pluginutil.LookRunnerUtil, logger log.Logger, isMetadataMode bool) (logical.Backend, error) { - // Look for plugin in the plugin catalog - pluginRunner, err := sys.LookupPlugin(ctx, pluginName) - if err != nil { - return nil, err - } - - var backend logical.Backend - if pluginRunner.Builtin { - // Plugin is builtin so we can retrieve an instance of the interface - // from the pluginRunner. Then cast it to logical.Backend. - backendRaw, err := pluginRunner.BuiltinFactory() - if err != nil { - return nil, errwrap.Wrapf("error getting plugin type: {{err}}", err) - } - - var ok bool - backend, ok = backendRaw.(logical.Backend) - if !ok { - return nil, fmt.Errorf("unsupported backend type: %q", pluginName) - } - - } else { - // create a backendPluginClient instance - backend, err = newPluginClient(ctx, sys, pluginRunner, logger, isMetadataMode) - if err != nil { - return nil, err - } - } - - return backend, nil -} - -func newPluginClient(ctx context.Context, sys pluginutil.RunnerUtil, pluginRunner *pluginutil.PluginRunner, logger log.Logger, isMetadataMode bool) (logical.Backend, error) { - // pluginMap is the map of plugins we can dispense. - pluginMap := map[string]plugin.Plugin{ - "backend": &BackendPlugin{ - metadataMode: isMetadataMode, - }, - } - - namedLogger := logger.Named(pluginRunner.Name) - - var client *plugin.Client - var err error - if isMetadataMode { - client, err = pluginRunner.RunMetadataMode(ctx, sys, pluginMap, handshakeConfig, []string{}, namedLogger) - } else { - client, err = pluginRunner.Run(ctx, sys, pluginMap, handshakeConfig, []string{}, namedLogger) - } - if err != nil { - return nil, err - } - - // Connect via RPC - rpcClient, err := client.Client() - if err != nil { - return nil, err - } - - // Request the plugin - raw, err := rpcClient.Dispense("backend") - if err != nil { - return nil, err - } - - var backend logical.Backend - var transport string - // We should have a logical backend type now. This feels like a normal interface - // implementation but is in fact over an RPC connection. - switch raw.(type) { - case *backendPluginClient: - backend = raw.(*backendPluginClient) - transport = "netRPC" - case *backendGRPCPluginClient: - backend = raw.(*backendGRPCPluginClient) - transport = "gRPC" - default: - return nil, errors.New("unsupported plugin client type") - } - - // Wrap the backend in a tracing middleware - if namedLogger.IsTrace() { - backend = &backendTracingMiddleware{ - logger: namedLogger.With("transport", transport), - next: backend, - } - } - - return &BackendPluginClient{ - client: client, - Backend: backend, - }, nil -} - -// wrapError takes a generic error type and makes it usable with the plugin -// interface. Only errors which have exported fields and have been registered -// with gob can be unwrapped and transported. This checks error types and, if -// none match, wrap the error in a plugin.BasicError. -func wrapError(err error) error { - if err == nil { - return nil - } - - switch err.(type) { - case *plugin.BasicError, - logical.HTTPCodedError, - *logical.StatusBadRequest: - return err - } - - return plugin.NewBasicError(err) -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/serve.go b/vendor/github.com/hashicorp/vault/logical/plugin/serve.go deleted file mode 100644 index 9dd57f8d7..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/serve.go +++ /dev/null @@ -1,85 +0,0 @@ -package plugin - -import ( - "crypto/tls" - "math" - "os" - - "google.golang.org/grpc" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -// BackendPluginName is the name of the plugin that can be -// dispensed rom the plugin server. -const BackendPluginName = "backend" - -type TLSProviderFunc func() (*tls.Config, error) - -type ServeOpts struct { - BackendFactoryFunc logical.Factory - TLSProviderFunc TLSProviderFunc - Logger log.Logger -} - -// Serve is a helper function used to serve a backend plugin. This -// should be ran on the plugin's main process. -func Serve(opts *ServeOpts) error { - logger := opts.Logger - if logger == nil { - logger = log.New(&log.LoggerOptions{ - Level: log.Trace, - Output: os.Stderr, - JSONFormat: true, - }) - } - - // pluginMap is the map of plugins we can dispense. - var pluginMap = map[string]plugin.Plugin{ - "backend": &BackendPlugin{ - Factory: opts.BackendFactoryFunc, - Logger: logger, - }, - } - - err := pluginutil.OptionallyEnableMlock() - if err != nil { - return err - } - - serveOpts := &plugin.ServeConfig{ - HandshakeConfig: handshakeConfig, - Plugins: pluginMap, - TLSProvider: opts.TLSProviderFunc, - Logger: logger, - - // A non-nil value here enables gRPC serving for this plugin... - GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { - opts = append(opts, grpc.MaxRecvMsgSize(math.MaxInt32)) - opts = append(opts, grpc.MaxSendMsgSize(math.MaxInt32)) - return plugin.DefaultGRPCServer(opts) - }, - } - - if !pluginutil.GRPCSupport() { - serveOpts.GRPCServer = nil - } - - // If FetchMetadata is true, run without TLSProvider - plugin.Serve(serveOpts) - - return nil -} - -// handshakeConfigs are used to just do a basic handshake between -// a plugin and host. If the handshake fails, a user friendly error is shown. -// This prevents users from executing bad plugins or executing a plugin -// directory. It is a UX feature, not a security feature. -var handshakeConfig = plugin.HandshakeConfig{ - ProtocolVersion: 3, - MagicCookieKey: "VAULT_BACKEND_PLUGIN", - MagicCookieValue: "6669da05-b1c8-4f49-97d9-c8e5bed98e20", -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/storage.go b/vendor/github.com/hashicorp/vault/logical/plugin/storage.go deleted file mode 100644 index 75cda5500..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/storage.go +++ /dev/null @@ -1,139 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - - "github.com/hashicorp/vault/logical" -) - -// StorageClient is an implementation of logical.Storage that communicates -// over RPC. -type StorageClient struct { - client *rpc.Client -} - -func (s *StorageClient) List(_ context.Context, prefix string) ([]string, error) { - var reply StorageListReply - err := s.client.Call("Plugin.List", prefix, &reply) - if err != nil { - return reply.Keys, err - } - if reply.Error != nil { - return reply.Keys, reply.Error - } - return reply.Keys, nil -} - -func (s *StorageClient) Get(_ context.Context, key string) (*logical.StorageEntry, error) { - var reply StorageGetReply - err := s.client.Call("Plugin.Get", key, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - return reply.StorageEntry, nil -} - -func (s *StorageClient) Put(_ context.Context, entry *logical.StorageEntry) error { - var reply StoragePutReply - err := s.client.Call("Plugin.Put", entry, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - return nil -} - -func (s *StorageClient) Delete(_ context.Context, key string) error { - var reply StorageDeleteReply - err := s.client.Call("Plugin.Delete", key, &reply) - if err != nil { - return err - } - if reply.Error != nil { - return reply.Error - } - return nil -} - -// StorageServer is a net/rpc compatible structure for serving -type StorageServer struct { - impl logical.Storage -} - -func (s *StorageServer) List(prefix string, reply *StorageListReply) error { - keys, err := s.impl.List(context.Background(), prefix) - *reply = StorageListReply{ - Keys: keys, - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Get(key string, reply *StorageGetReply) error { - storageEntry, err := s.impl.Get(context.Background(), key) - *reply = StorageGetReply{ - StorageEntry: storageEntry, - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Put(entry *logical.StorageEntry, reply *StoragePutReply) error { - err := s.impl.Put(context.Background(), entry) - *reply = StoragePutReply{ - Error: wrapError(err), - } - return nil -} - -func (s *StorageServer) Delete(key string, reply *StorageDeleteReply) error { - err := s.impl.Delete(context.Background(), key) - *reply = StorageDeleteReply{ - Error: wrapError(err), - } - return nil -} - -type StorageListReply struct { - Keys []string - Error error -} - -type StorageGetReply struct { - StorageEntry *logical.StorageEntry - Error error -} - -type StoragePutReply struct { - Error error -} - -type StorageDeleteReply struct { - Error error -} - -// NOOPStorage is used to deny access to the storage interface while running a -// backend plugin in metadata mode. -type NOOPStorage struct{} - -func (s *NOOPStorage) List(_ context.Context, prefix string) ([]string, error) { - return []string{}, nil -} - -func (s *NOOPStorage) Get(_ context.Context, key string) (*logical.StorageEntry, error) { - return nil, nil -} - -func (s *NOOPStorage) Put(_ context.Context, entry *logical.StorageEntry) error { - return nil -} - -func (s *NOOPStorage) Delete(_ context.Context, key string) error { - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/plugin/system.go b/vendor/github.com/hashicorp/vault/logical/plugin/system.go deleted file mode 100644 index 21abb3c25..000000000 --- a/vendor/github.com/hashicorp/vault/logical/plugin/system.go +++ /dev/null @@ -1,345 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - "time" - - "fmt" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" -) - -type SystemViewClient struct { - client *rpc.Client -} - -func (s *SystemViewClient) DefaultLeaseTTL() time.Duration { - var reply DefaultLeaseTTLReply - err := s.client.Call("Plugin.DefaultLeaseTTL", new(interface{}), &reply) - if err != nil { - return 0 - } - - return reply.DefaultLeaseTTL -} - -func (s *SystemViewClient) MaxLeaseTTL() time.Duration { - var reply MaxLeaseTTLReply - err := s.client.Call("Plugin.MaxLeaseTTL", new(interface{}), &reply) - if err != nil { - return 0 - } - - return reply.MaxLeaseTTL -} - -func (s *SystemViewClient) SudoPrivilege(ctx context.Context, path string, token string) bool { - var reply SudoPrivilegeReply - args := &SudoPrivilegeArgs{ - Path: path, - Token: token, - } - - err := s.client.Call("Plugin.SudoPrivilege", args, &reply) - if err != nil { - return false - } - - return reply.Sudo -} - -func (s *SystemViewClient) Tainted() bool { - var reply TaintedReply - - err := s.client.Call("Plugin.Tainted", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.Tainted -} - -func (s *SystemViewClient) CachingDisabled() bool { - var reply CachingDisabledReply - - err := s.client.Call("Plugin.CachingDisabled", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.CachingDisabled -} - -func (s *SystemViewClient) ReplicationState() consts.ReplicationState { - var reply ReplicationStateReply - - err := s.client.Call("Plugin.ReplicationState", new(interface{}), &reply) - if err != nil { - return consts.ReplicationUnknown - } - - return reply.ReplicationState -} - -func (s *SystemViewClient) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - var reply ResponseWrapDataReply - // Do not allow JWTs to be returned - args := &ResponseWrapDataArgs{ - Data: data, - TTL: ttl, - JWT: false, - } - - err := s.client.Call("Plugin.ResponseWrapData", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.ResponseWrapInfo, nil -} - -func (s *SystemViewClient) LookupPlugin(ctx context.Context, name string) (*pluginutil.PluginRunner, error) { - return nil, fmt.Errorf("cannot call LookupPlugin from a plugin backend") -} - -func (s *SystemViewClient) MlockEnabled() bool { - var reply MlockEnabledReply - err := s.client.Call("Plugin.MlockEnabled", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.MlockEnabled -} - -func (s *SystemViewClient) LocalMount() bool { - var reply LocalMountReply - err := s.client.Call("Plugin.LocalMount", new(interface{}), &reply) - if err != nil { - return false - } - - return reply.Local -} - -func (s *SystemViewClient) EntityInfo(entityID string) (*logical.Entity, error) { - var reply EntityInfoReply - args := &EntityInfoArgs{ - EntityID: entityID, - } - - err := s.client.Call("Plugin.EntityInfo", args, &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.Entity, nil -} - -func (s *SystemViewClient) PluginEnv(_ context.Context) (*logical.PluginEnvironment, error) { - var reply PluginEnvReply - - err := s.client.Call("Plugin.PluginEnv", new(interface{}), &reply) - if err != nil { - return nil, err - } - if reply.Error != nil { - return nil, reply.Error - } - - return reply.PluginEnvironment, nil -} - -type SystemViewServer struct { - impl logical.SystemView -} - -func (s *SystemViewServer) DefaultLeaseTTL(_ interface{}, reply *DefaultLeaseTTLReply) error { - ttl := s.impl.DefaultLeaseTTL() - *reply = DefaultLeaseTTLReply{ - DefaultLeaseTTL: ttl, - } - - return nil -} - -func (s *SystemViewServer) MaxLeaseTTL(_ interface{}, reply *MaxLeaseTTLReply) error { - ttl := s.impl.MaxLeaseTTL() - *reply = MaxLeaseTTLReply{ - MaxLeaseTTL: ttl, - } - - return nil -} - -func (s *SystemViewServer) SudoPrivilege(args *SudoPrivilegeArgs, reply *SudoPrivilegeReply) error { - sudo := s.impl.SudoPrivilege(context.Background(), args.Path, args.Token) - *reply = SudoPrivilegeReply{ - Sudo: sudo, - } - - return nil -} - -func (s *SystemViewServer) Tainted(_ interface{}, reply *TaintedReply) error { - tainted := s.impl.Tainted() - *reply = TaintedReply{ - Tainted: tainted, - } - - return nil -} - -func (s *SystemViewServer) CachingDisabled(_ interface{}, reply *CachingDisabledReply) error { - cachingDisabled := s.impl.CachingDisabled() - *reply = CachingDisabledReply{ - CachingDisabled: cachingDisabled, - } - - return nil -} - -func (s *SystemViewServer) ReplicationState(_ interface{}, reply *ReplicationStateReply) error { - replicationState := s.impl.ReplicationState() - *reply = ReplicationStateReply{ - ReplicationState: replicationState, - } - - return nil -} - -func (s *SystemViewServer) ResponseWrapData(args *ResponseWrapDataArgs, reply *ResponseWrapDataReply) error { - // Do not allow JWTs to be returned - info, err := s.impl.ResponseWrapData(context.Background(), args.Data, args.TTL, false) - if err != nil { - *reply = ResponseWrapDataReply{ - Error: wrapError(err), - } - return nil - } - *reply = ResponseWrapDataReply{ - ResponseWrapInfo: info, - } - - return nil -} - -func (s *SystemViewServer) MlockEnabled(_ interface{}, reply *MlockEnabledReply) error { - enabled := s.impl.MlockEnabled() - *reply = MlockEnabledReply{ - MlockEnabled: enabled, - } - - return nil -} - -func (s *SystemViewServer) LocalMount(_ interface{}, reply *LocalMountReply) error { - local := s.impl.LocalMount() - *reply = LocalMountReply{ - Local: local, - } - - return nil -} - -func (s *SystemViewServer) EntityInfo(args *EntityInfoArgs, reply *EntityInfoReply) error { - entity, err := s.impl.EntityInfo(args.EntityID) - if err != nil { - *reply = EntityInfoReply{ - Error: wrapError(err), - } - return nil - } - *reply = EntityInfoReply{ - Entity: entity, - } - - return nil -} - -func (s *SystemViewServer) PluginEnv(_ interface{}, reply *PluginEnvReply) error { - pluginEnv, err := s.impl.PluginEnv(context.Background()) - if err != nil { - *reply = PluginEnvReply{ - Error: wrapError(err), - } - return nil - } - *reply = PluginEnvReply{ - PluginEnvironment: pluginEnv, - } - - return nil -} - -type DefaultLeaseTTLReply struct { - DefaultLeaseTTL time.Duration -} - -type MaxLeaseTTLReply struct { - MaxLeaseTTL time.Duration -} - -type SudoPrivilegeArgs struct { - Path string - Token string -} - -type SudoPrivilegeReply struct { - Sudo bool -} - -type TaintedReply struct { - Tainted bool -} - -type CachingDisabledReply struct { - CachingDisabled bool -} - -type ReplicationStateReply struct { - ReplicationState consts.ReplicationState -} - -type ResponseWrapDataArgs struct { - Data map[string]interface{} - TTL time.Duration - JWT bool -} - -type ResponseWrapDataReply struct { - ResponseWrapInfo *wrapping.ResponseWrapInfo - Error error -} - -type MlockEnabledReply struct { - MlockEnabled bool -} - -type LocalMountReply struct { - Local bool -} - -type EntityInfoArgs struct { - EntityID string -} - -type EntityInfoReply struct { - Entity *logical.Entity - Error error -} - -type PluginEnvReply struct { - PluginEnvironment *logical.PluginEnvironment - Error error -} diff --git a/vendor/github.com/hashicorp/vault/logical/request.go b/vendor/github.com/hashicorp/vault/logical/request.go deleted file mode 100644 index 4bc7f50a5..000000000 --- a/vendor/github.com/hashicorp/vault/logical/request.go +++ /dev/null @@ -1,274 +0,0 @@ -package logical - -import ( - "fmt" - "strings" - "time" -) - -// RequestWrapInfo is a struct that stores information about desired response -// and seal wrapping behavior -type RequestWrapInfo struct { - // Setting to non-zero specifies that the response should be wrapped. - // Specifies the desired TTL of the wrapping token. - TTL time.Duration `json:"ttl" structs:"ttl" mapstructure:"ttl" sentinel:""` - - // The format to use for the wrapped response; if not specified it's a bare - // token - Format string `json:"format" structs:"format" mapstructure:"format" sentinel:""` - - // A flag to conforming backends that data for a given request should be - // seal wrapped - SealWrap bool `json:"seal_wrap" structs:"seal_wrap" mapstructure:"seal_wrap" sentinel:""` -} - -func (r *RequestWrapInfo) SentinelGet(key string) (interface{}, error) { - if r == nil { - return nil, nil - } - switch key { - case "ttl": - return r.TTL, nil - case "ttl_seconds": - return int64(r.TTL.Seconds()), nil - } - - return nil, nil -} - -func (r *RequestWrapInfo) SentinelKeys() []string { - return []string{ - "ttl", - "ttl_seconds", - } -} - -// Request is a struct that stores the parameters and context of a request -// being made to Vault. It is used to abstract the details of the higher level -// request protocol from the handlers. -// -// Note: Many of these have Sentinel disabled because they are values populated -// by the router after policy checks; the token namespace would be the right -// place to access them via Sentinel -type Request struct { - // Id is the uuid associated with each request - ID string `json:"id" structs:"id" mapstructure:"id" sentinel:""` - - // If set, the name given to the replication secondary where this request - // originated - ReplicationCluster string `json:"replication_cluster" structs:"replication_cluster" mapstructure:"replication_cluster" sentinel:""` - - // Operation is the requested operation type - Operation Operation `json:"operation" structs:"operation" mapstructure:"operation"` - - // Path is the part of the request path not consumed by the - // routing. As an example, if the original request path is "prod/aws/foo" - // and the AWS logical backend is mounted at "prod/aws/", then the - // final path is "foo" since the mount prefix is trimmed. - Path string `json:"path" structs:"path" mapstructure:"path" sentinel:""` - - // Request data is an opaque map that must have string keys. - Data map[string]interface{} `json:"map" structs:"data" mapstructure:"data"` - - // Storage can be used to durably store and retrieve state. - Storage Storage `json:"-" sentinel:""` - - // Secret will be non-nil only for Revoke and Renew operations - // to represent the secret that was returned prior. - Secret *Secret `json:"secret" structs:"secret" mapstructure:"secret" sentinel:""` - - // Auth will be non-nil only for Renew operations - // to represent the auth that was returned prior. - Auth *Auth `json:"auth" structs:"auth" mapstructure:"auth" sentinel:""` - - // Headers will contain the http headers from the request. This value will - // be used in the audit broker to ensure we are auditing only the allowed - // headers. - Headers map[string][]string `json:"headers" structs:"headers" mapstructure:"headers" sentinel:""` - - // Connection will be non-nil only for credential providers to - // inspect the connection information and potentially use it for - // authentication/protection. - Connection *Connection `json:"connection" structs:"connection" mapstructure:"connection"` - - // ClientToken is provided to the core so that the identity - // can be verified and ACLs applied. This value is passed - // through to the logical backends but after being salted and - // hashed. - ClientToken string `json:"client_token" structs:"client_token" mapstructure:"client_token" sentinel:""` - - // ClientTokenAccessor is provided to the core so that the it can get - // logged as part of request audit logging. - ClientTokenAccessor string `json:"client_token_accessor" structs:"client_token_accessor" mapstructure:"client_token_accessor" sentinel:""` - - // DisplayName is provided to the logical backend to help associate - // dynamic secrets with the source entity. This is not a sensitive - // name, but is useful for operators. - DisplayName string `json:"display_name" structs:"display_name" mapstructure:"display_name" sentinel:""` - - // MountPoint is provided so that a logical backend can generate - // paths relative to itself. The `Path` is effectively the client - // request path with the MountPoint trimmed off. - MountPoint string `json:"mount_point" structs:"mount_point" mapstructure:"mount_point" sentinel:""` - - // MountType is provided so that a logical backend can make decisions - // based on the specific mount type (e.g., if a mount type has different - // aliases, generating different defaults depending on the alias) - MountType string `json:"mount_type" structs:"mount_type" mapstructure:"mount_type" sentinel:""` - - // MountAccessor is provided so that identities returned by the authentication - // backends can be tied to the mount it belongs to. - MountAccessor string `json:"mount_accessor" structs:"mount_accessor" mapstructure:"mount_accessor" sentinel:""` - - // WrapInfo contains requested response wrapping parameters - WrapInfo *RequestWrapInfo `json:"wrap_info" structs:"wrap_info" mapstructure:"wrap_info" sentinel:""` - - // ClientTokenRemainingUses represents the allowed number of uses left on the - // token supplied - ClientTokenRemainingUses int `json:"client_token_remaining_uses" structs:"client_token_remaining_uses" mapstructure:"client_token_remaining_uses"` - - // EntityID is the identity of the caller extracted out of the token used - // to make this request - EntityID string `json:"entity_id" structs:"entity_id" mapstructure:"entity_id" sentinel:""` - - // PolicyOverride indicates that the requestor wishes to override - // soft-mandatory Sentinel policies - PolicyOverride bool `json:"policy_override" structs:"policy_override" mapstructure:"policy_override"` - - // Whether the request is unauthenticated, as in, had no client token - // attached. Useful in some situations where the client token is not made - // accessible. - Unauthenticated bool `json:"unauthenticated" structs:"unauthenticated" mapstructure:"unauthenticated"` - - // Cached token entry. This avoids another lookup in request handling when - // we've already looked it up at http handling time. Note that this token - // has not been "used", as in it will not properly take into account use - // count limitations. As a result this field should only ever be used for - // transport to a function that would otherwise do a lookup and then - // properly use the token. - tokenEntry *TokenEntry - - // For replication, contains the last WAL on the remote side after handling - // the request, used for best-effort avoidance of stale read-after-write - lastRemoteWAL uint64 -} - -// Get returns a data field and guards for nil Data -func (r *Request) Get(key string) interface{} { - if r.Data == nil { - return nil - } - return r.Data[key] -} - -// GetString returns a data field as a string -func (r *Request) GetString(key string) string { - raw := r.Get(key) - s, _ := raw.(string) - return s -} - -func (r *Request) GoString() string { - return fmt.Sprintf("*%#v", *r) -} - -func (r *Request) SentinelGet(key string) (interface{}, error) { - switch key { - case "path": - // Sanitize it here so that it's consistent in policies - return strings.TrimPrefix(r.Path, "/"), nil - - case "wrapping", "wrap_info": - // If the pointer is nil accessing the wrap info is considered - // "undefined" so this allows us to instead discover a TTL of zero - if r.WrapInfo == nil { - return &RequestWrapInfo{}, nil - } - return r.WrapInfo, nil - } - - return nil, nil -} - -func (r *Request) SentinelKeys() []string { - return []string{ - "path", - "wrapping", - "wrap_info", - } -} - -func (r *Request) LastRemoteWAL() uint64 { - return r.lastRemoteWAL -} - -func (r *Request) SetLastRemoteWAL(last uint64) { - r.lastRemoteWAL = last -} - -func (r *Request) TokenEntry() *TokenEntry { - return r.tokenEntry -} - -func (r *Request) SetTokenEntry(te *TokenEntry) { - r.tokenEntry = te -} - -// RenewRequest creates the structure of the renew request. -func RenewRequest(path string, secret *Secret, data map[string]interface{}) *Request { - return &Request{ - Operation: RenewOperation, - Path: path, - Data: data, - Secret: secret, - } -} - -// RenewAuthRequest creates the structure of the renew request for an auth. -func RenewAuthRequest(path string, auth *Auth, data map[string]interface{}) *Request { - return &Request{ - Operation: RenewOperation, - Path: path, - Data: data, - Auth: auth, - } -} - -// RevokeRequest creates the structure of the revoke request. -func RevokeRequest(path string, secret *Secret, data map[string]interface{}) *Request { - return &Request{ - Operation: RevokeOperation, - Path: path, - Data: data, - Secret: secret, - } -} - -// RollbackRequest creates the structure of the revoke request. -func RollbackRequest(path string) *Request { - return &Request{ - Operation: RollbackOperation, - Path: path, - Data: make(map[string]interface{}), - } -} - -// Operation is an enum that is used to specify the type -// of request being made -type Operation string - -const ( - // The operations below are called per path - CreateOperation Operation = "create" - ReadOperation = "read" - UpdateOperation = "update" - DeleteOperation = "delete" - ListOperation = "list" - HelpOperation = "help" - AliasLookaheadOperation = "alias-lookahead" - - // The operations below are called globally, the path is less relevant. - RevokeOperation Operation = "revoke" - RenewOperation = "renew" - RollbackOperation = "rollback" -) diff --git a/vendor/github.com/hashicorp/vault/logical/response.go b/vendor/github.com/hashicorp/vault/logical/response.go deleted file mode 100644 index 96d4cce5e..000000000 --- a/vendor/github.com/hashicorp/vault/logical/response.go +++ /dev/null @@ -1,170 +0,0 @@ -package logical - -import ( - "encoding/json" - "errors" - - "github.com/hashicorp/vault/helper/wrapping" -) - -const ( - // HTTPContentType can be specified in the Data field of a Response - // so that the HTTP front end can specify a custom Content-Type associated - // with the HTTPRawBody. This can only be used for non-secrets, and should - // be avoided unless absolutely necessary, such as implementing a specification. - // The value must be a string. - HTTPContentType = "http_content_type" - - // HTTPRawBody is the raw content of the HTTP body that goes with the HTTPContentType. - // This can only be specified for non-secrets, and should should be similarly - // avoided like the HTTPContentType. The value must be a byte slice. - HTTPRawBody = "http_raw_body" - - // HTTPStatusCode is the response code of the HTTP body that goes with the HTTPContentType. - // This can only be specified for non-secrets, and should should be similarly - // avoided like the HTTPContentType. The value must be an integer. - HTTPStatusCode = "http_status_code" - - // For unwrapping we may need to know whether the value contained in the - // raw body is already JSON-unmarshaled. The presence of this key indicates - // that it has already been unmarshaled. That way we don't need to simply - // ignore errors. - HTTPRawBodyAlreadyJSONDecoded = "http_raw_body_already_json_decoded" -) - -// Response is a struct that stores the response of a request. -// It is used to abstract the details of the higher level request protocol. -type Response struct { - // Secret, if not nil, denotes that this response represents a secret. - Secret *Secret `json:"secret" structs:"secret" mapstructure:"secret"` - - // Auth, if not nil, contains the authentication information for - // this response. This is only checked and means something for - // credential backends. - Auth *Auth `json:"auth" structs:"auth" mapstructure:"auth"` - - // Response data is an opaque map that must have string keys. For - // secrets, this data is sent down to the user as-is. To store internal - // data that you don't want the user to see, store it in - // Secret.InternalData. - Data map[string]interface{} `json:"data" structs:"data" mapstructure:"data"` - - // Redirect is an HTTP URL to redirect to for further authentication. - // This is only valid for credential backends. This will be blanked - // for any logical backend and ignored. - Redirect string `json:"redirect" structs:"redirect" mapstructure:"redirect"` - - // Warnings allow operations or backends to return warnings in response - // to user actions without failing the action outright. - Warnings []string `json:"warnings" structs:"warnings" mapstructure:"warnings"` - - // Information for wrapping the response in a cubbyhole - WrapInfo *wrapping.ResponseWrapInfo `json:"wrap_info" structs:"wrap_info" mapstructure:"wrap_info"` -} - -// AddWarning adds a warning into the response's warning list -func (r *Response) AddWarning(warning string) { - if r.Warnings == nil { - r.Warnings = make([]string, 0, 1) - } - r.Warnings = append(r.Warnings, warning) -} - -// IsError returns true if this response seems to indicate an error. -func (r *Response) IsError() bool { - return r != nil && r.Data != nil && len(r.Data) == 1 && r.Data["error"] != nil -} - -func (r *Response) Error() error { - if !r.IsError() { - return nil - } - switch r.Data["error"].(type) { - case string: - return errors.New(r.Data["error"].(string)) - case error: - return r.Data["error"].(error) - } - return nil -} - -// HelpResponse is used to format a help response -func HelpResponse(text string, seeAlso []string) *Response { - return &Response{ - Data: map[string]interface{}{ - "help": text, - "see_also": seeAlso, - }, - } -} - -// ErrorResponse is used to format an error response -func ErrorResponse(text string) *Response { - return &Response{ - Data: map[string]interface{}{ - "error": text, - }, - } -} - -// ListResponse is used to format a response to a list operation. -func ListResponse(keys []string) *Response { - resp := &Response{ - Data: map[string]interface{}{}, - } - if len(keys) != 0 { - resp.Data["keys"] = keys - } - return resp -} - -// ListResponseWithInfo is used to format a response to a list operation and -// return the keys as well as a map with corresponding key info. -func ListResponseWithInfo(keys []string, keyInfo map[string]interface{}) *Response { - resp := ListResponse(keys) - - keyInfoData := make(map[string]interface{}) - for _, key := range keys { - val, ok := keyInfo[key] - if ok { - keyInfoData[key] = val - } - } - - if len(keyInfoData) > 0 { - resp.Data["key_info"] = keyInfoData - } - - return resp -} - -// RespondWithStatusCode takes a response and converts it to a raw response with -// the provided Status Code. -func RespondWithStatusCode(resp *Response, req *Request, code int) (*Response, error) { - ret := &Response{ - Data: map[string]interface{}{ - HTTPContentType: "application/json", - HTTPStatusCode: code, - }, - } - - if resp != nil { - httpResp := LogicalResponseToHTTPResponse(resp) - - if req != nil { - httpResp.RequestID = req.ID - } - - body, err := json.Marshal(httpResp) - if err != nil { - return nil, err - } - - // We default to string here so that the value is HMAC'd via audit. - // Since this function is always marshaling to JSON, this is - // appropriate. - ret.Data[HTTPRawBody] = string(body) - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/response_util.go b/vendor/github.com/hashicorp/vault/logical/response_util.go deleted file mode 100644 index fbbd021d8..000000000 --- a/vendor/github.com/hashicorp/vault/logical/response_util.go +++ /dev/null @@ -1,145 +0,0 @@ -package logical - -import ( - "errors" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/consts" -) - -// RespondErrorCommon pulls most of the functionality from http's -// respondErrorCommon and some of http's handleLogical and makes it available -// to both the http package and elsewhere. -func RespondErrorCommon(req *Request, resp *Response, err error) (int, error) { - if err == nil && (resp == nil || !resp.IsError()) { - switch { - case req.Operation == ReadOperation: - if resp == nil { - return http.StatusNotFound, nil - } - - // Basically: if we have empty "keys" or no keys at all, 404. This - // provides consistency with GET. - case req.Operation == ListOperation && resp.WrapInfo == nil: - if resp == nil { - return http.StatusNotFound, nil - } - if len(resp.Data) == 0 { - if len(resp.Warnings) > 0 { - return 0, nil - } - return http.StatusNotFound, nil - } - keysRaw, ok := resp.Data["keys"] - if !ok || keysRaw == nil { - // If we don't have keys but have other data, return as-is - if len(resp.Data) > 0 || len(resp.Warnings) > 0 { - return 0, nil - } - return http.StatusNotFound, nil - } - - var keys []string - switch keysRaw.(type) { - case []interface{}: - keys = make([]string, len(keysRaw.([]interface{}))) - for i, el := range keysRaw.([]interface{}) { - s, ok := el.(string) - if !ok { - return http.StatusInternalServerError, nil - } - keys[i] = s - } - - case []string: - keys = keysRaw.([]string) - default: - return http.StatusInternalServerError, nil - } - - if len(keys) == 0 { - return http.StatusNotFound, nil - } - } - - return 0, nil - } - - if errwrap.ContainsType(err, new(ReplicationCodedError)) { - var allErrors error - codedErr := errwrap.GetType(err, new(ReplicationCodedError)).(*ReplicationCodedError) - errwrap.Walk(err, func(inErr error) { - newErr, ok := inErr.(*ReplicationCodedError) - if !ok { - allErrors = multierror.Append(allErrors, newErr) - } - }) - if allErrors != nil { - return codedErr.Code, multierror.Append(errors.New(fmt.Sprintf("errors from both primary and secondary; primary error was %v; secondary errors follow", codedErr.Msg)), allErrors) - } - return codedErr.Code, errors.New(codedErr.Msg) - } - - // Start out with internal server error since in most of these cases there - // won't be a response so this won't be overridden - statusCode := http.StatusInternalServerError - // If we actually have a response, start out with bad request - if resp != nil { - statusCode = http.StatusBadRequest - } - - // Now, check the error itself; if it has a specific logical error, set the - // appropriate code - if err != nil { - switch { - case errwrap.ContainsType(err, new(StatusBadRequest)): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrPermissionDenied.Error()): - statusCode = http.StatusForbidden - case errwrap.Contains(err, ErrUnsupportedOperation.Error()): - statusCode = http.StatusMethodNotAllowed - case errwrap.Contains(err, ErrUnsupportedPath.Error()): - statusCode = http.StatusNotFound - case errwrap.Contains(err, ErrInvalidRequest.Error()): - statusCode = http.StatusBadRequest - case errwrap.Contains(err, ErrUpstreamRateLimited.Error()): - statusCode = http.StatusBadGateway - } - } - - if resp != nil && resp.IsError() { - err = fmt.Errorf("%s", resp.Data["error"].(string)) - } - - return statusCode, err -} - -// AdjustErrorStatusCode adjusts the status that will be sent in error -// conditions in a way that can be shared across http's respondError and other -// locations. -func AdjustErrorStatusCode(status *int, err error) { - // Handle nested errors - if t, ok := err.(*multierror.Error); ok { - for _, e := range t.Errors { - AdjustErrorStatusCode(status, e) - } - } - - // Adjust status code when sealed - if errwrap.Contains(err, consts.ErrSealed.Error()) { - *status = http.StatusServiceUnavailable - } - - // Adjust status code on - if errwrap.Contains(err, "http: request body too large") { - *status = http.StatusRequestEntityTooLarge - } - - // Allow HTTPCoded error passthrough to specify a code - if t, ok := err.(HTTPCodedError); ok { - *status = t.Code() - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/secret.go b/vendor/github.com/hashicorp/vault/logical/secret.go deleted file mode 100644 index a2128d868..000000000 --- a/vendor/github.com/hashicorp/vault/logical/secret.go +++ /dev/null @@ -1,30 +0,0 @@ -package logical - -import "fmt" - -// Secret represents the secret part of a response. -type Secret struct { - LeaseOptions - - // InternalData is JSON-encodable data that is stored with the secret. - // This will be sent back during a Renew/Revoke for storing internal data - // used for those operations. - InternalData map[string]interface{} `json:"internal_data" sentinel:""` - - // LeaseID is the ID returned to the user to manage this secret. - // This is generated by Vault core. Any set value will be ignored. - // For requests, this will always be blank. - LeaseID string `sentinel:""` -} - -func (s *Secret) Validate() error { - if s.TTL < 0 { - return fmt.Errorf("ttl duration must not be less than zero") - } - - return nil -} - -func (s *Secret) GoString() string { - return fmt.Sprintf("*%#v", *s) -} diff --git a/vendor/github.com/hashicorp/vault/logical/storage.go b/vendor/github.com/hashicorp/vault/logical/storage.go deleted file mode 100644 index 116fd301c..000000000 --- a/vendor/github.com/hashicorp/vault/logical/storage.go +++ /dev/null @@ -1,121 +0,0 @@ -package logical - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" -) - -// ErrReadOnly is returned when a backend does not support -// writing. This can be caused by a read-only replica or secondary -// cluster operation. -var ErrReadOnly = errors.New("cannot write to readonly storage") - -// ErrSetupReadOnly is returned when a write operation is attempted on a -// storage while the backend is still being setup. -var ErrSetupReadOnly = errors.New("cannot write to storage during setup") - -// Storage is the way that logical backends are able read/write data. -type Storage interface { - List(context.Context, string) ([]string, error) - Get(context.Context, string) (*StorageEntry, error) - Put(context.Context, *StorageEntry) error - Delete(context.Context, string) error -} - -// StorageEntry is the entry for an item in a Storage implementation. -type StorageEntry struct { - Key string - Value []byte - SealWrap bool -} - -// DecodeJSON decodes the 'Value' present in StorageEntry. -func (e *StorageEntry) DecodeJSON(out interface{}) error { - return jsonutil.DecodeJSON(e.Value, out) -} - -// StorageEntryJSON creates a StorageEntry with a JSON-encoded value. -func StorageEntryJSON(k string, v interface{}) (*StorageEntry, error) { - encodedBytes, err := jsonutil.EncodeJSON(v) - if err != nil { - return nil, errwrap.Wrapf("failed to encode storage entry: {{err}}", err) - } - - return &StorageEntry{ - Key: k, - Value: encodedBytes, - }, nil -} - -type ClearableView interface { - List(context.Context, string) ([]string, error) - Delete(context.Context, string) error -} - -// ScanView is used to scan all the keys in a view iteratively -func ScanView(ctx context.Context, view ClearableView, cb func(path string)) error { - frontier := []string{""} - for len(frontier) > 0 { - n := len(frontier) - current := frontier[n-1] - frontier = frontier[:n-1] - - // List the contents - contents, err := view.List(ctx, current) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("list failed at path %q: {{err}}", current), err) - } - - // Handle the contents in the directory - for _, c := range contents { - fullPath := current + c - if strings.HasSuffix(c, "/") { - frontier = append(frontier, fullPath) - } else { - cb(fullPath) - } - } - } - return nil -} - -// CollectKeys is used to collect all the keys in a view -func CollectKeys(ctx context.Context, view ClearableView) ([]string, error) { - // Accumulate the keys - var existing []string - cb := func(path string) { - existing = append(existing, path) - } - - // Scan for all the keys - if err := ScanView(ctx, view, cb); err != nil { - return nil, err - } - return existing, nil -} - -// ClearView is used to delete all the keys in a view -func ClearView(ctx context.Context, view ClearableView) error { - if view == nil { - return nil - } - - // Collect all the keys - keys, err := CollectKeys(ctx, view) - if err != nil { - return err - } - - // Delete all the keys - for _, key := range keys { - if err := view.Delete(ctx, key); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/storage_inmem.go b/vendor/github.com/hashicorp/vault/logical/storage_inmem.go deleted file mode 100644 index e0ff75f14..000000000 --- a/vendor/github.com/hashicorp/vault/logical/storage_inmem.go +++ /dev/null @@ -1,67 +0,0 @@ -package logical - -import ( - "context" - "sync" - - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/physical/inmem" -) - -// InmemStorage implements Storage and stores all data in memory. It is -// basically a straight copy of physical.Inmem, but it prevents backends from -// having to load all of physical's dependencies (which are legion) just to -// have some testing storage. -type InmemStorage struct { - underlying physical.Backend - once sync.Once -} - -func (s *InmemStorage) Get(ctx context.Context, key string) (*StorageEntry, error) { - s.once.Do(s.init) - - entry, err := s.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - return &StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -func (s *InmemStorage) Put(ctx context.Context, entry *StorageEntry) error { - s.once.Do(s.init) - - return s.underlying.Put(ctx, &physical.Entry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }) -} - -func (s *InmemStorage) Delete(ctx context.Context, key string) error { - s.once.Do(s.init) - - return s.underlying.Delete(ctx, key) -} - -func (s *InmemStorage) List(ctx context.Context, prefix string) ([]string, error) { - s.once.Do(s.init) - - return s.underlying.List(ctx, prefix) -} - -func (s *InmemStorage) Underlying() *inmem.InmemBackend { - s.once.Do(s.init) - - return s.underlying.(*inmem.InmemBackend) -} - -func (s *InmemStorage) init() { - s.underlying, _ = inmem.NewInmem(nil, nil) -} diff --git a/vendor/github.com/hashicorp/vault/logical/system_view.go b/vendor/github.com/hashicorp/vault/logical/system_view.go deleted file mode 100644 index 8eb72cb6e..000000000 --- a/vendor/github.com/hashicorp/vault/logical/system_view.go +++ /dev/null @@ -1,130 +0,0 @@ -package logical - -import ( - "context" - "errors" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" -) - -// SystemView exposes system configuration information in a safe way -// for logical backends to consume -type SystemView interface { - // DefaultLeaseTTL returns the default lease TTL set in Vault configuration - DefaultLeaseTTL() time.Duration - - // MaxLeaseTTL returns the max lease TTL set in Vault configuration; backend - // authors should take care not to issue credentials that last longer than - // this value, as Vault will revoke them - MaxLeaseTTL() time.Duration - - // SudoPrivilege returns true if given path has sudo privileges - // for the given client token - SudoPrivilege(ctx context.Context, path string, token string) bool - - // Returns true if the mount is tainted. A mount is tainted if it is in the - // process of being unmounted. This should only be used in special - // circumstances; a primary use-case is as a guard in revocation functions. - // If revocation of a backend's leases fails it can keep the unmounting - // process from being successful. If the reason for this failure is not - // relevant when the mount is tainted (for instance, saving a CRL to disk - // when the stored CRL will be removed during the unmounting process - // anyways), we can ignore the errors to allow unmounting to complete. - Tainted() bool - - // Returns true if caching is disabled. If true, no caches should be used, - // despite known slowdowns. - CachingDisabled() bool - - // When run from a system view attached to a request, indicates whether the - // request is affecting a local mount or not - LocalMount() bool - - // ReplicationState indicates the state of cluster replication - ReplicationState() consts.ReplicationState - - // ResponseWrapData wraps the given data in a cubbyhole and returns the - // token used to unwrap. - ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) - - // LookupPlugin looks into the plugin catalog for a plugin with the given - // name. Returns a PluginRunner or an error if a plugin can not be found. - LookupPlugin(context.Context, string) (*pluginutil.PluginRunner, error) - - // MlockEnabled returns the configuration setting for enabling mlock on - // plugins. - MlockEnabled() bool - - // EntityInfo returns a subset of information related to the identity entity - // for the given entity id - EntityInfo(entityID string) (*Entity, error) - - // PluginEnv returns Vault environment information used by plugins - PluginEnv(context.Context) (*PluginEnvironment, error) -} - -type StaticSystemView struct { - DefaultLeaseTTLVal time.Duration - MaxLeaseTTLVal time.Duration - SudoPrivilegeVal bool - TaintedVal bool - CachingDisabledVal bool - Primary bool - EnableMlock bool - LocalMountVal bool - ReplicationStateVal consts.ReplicationState - EntityVal *Entity - VaultVersion string - PluginEnvironment *PluginEnvironment -} - -func (d StaticSystemView) DefaultLeaseTTL() time.Duration { - return d.DefaultLeaseTTLVal -} - -func (d StaticSystemView) MaxLeaseTTL() time.Duration { - return d.MaxLeaseTTLVal -} - -func (d StaticSystemView) SudoPrivilege(_ context.Context, path string, token string) bool { - return d.SudoPrivilegeVal -} - -func (d StaticSystemView) Tainted() bool { - return d.TaintedVal -} - -func (d StaticSystemView) CachingDisabled() bool { - return d.CachingDisabledVal -} - -func (d StaticSystemView) LocalMount() bool { - return d.LocalMountVal -} - -func (d StaticSystemView) ReplicationState() consts.ReplicationState { - return d.ReplicationStateVal -} - -func (d StaticSystemView) ResponseWrapData(_ context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - return nil, errors.New("ResponseWrapData is not implemented in StaticSystemView") -} - -func (d StaticSystemView) LookupPlugin(_ context.Context, name string) (*pluginutil.PluginRunner, error) { - return nil, errors.New("LookupPlugin is not implemented in StaticSystemView") -} - -func (d StaticSystemView) MlockEnabled() bool { - return d.EnableMlock -} - -func (d StaticSystemView) EntityInfo(entityID string) (*Entity, error) { - return d.EntityVal, nil -} - -func (d StaticSystemView) PluginEnv(_ context.Context) (*PluginEnvironment, error) { - return d.PluginEnvironment, nil -} diff --git a/vendor/github.com/hashicorp/vault/logical/testing.go b/vendor/github.com/hashicorp/vault/logical/testing.go deleted file mode 100644 index 7c7738996..000000000 --- a/vendor/github.com/hashicorp/vault/logical/testing.go +++ /dev/null @@ -1,84 +0,0 @@ -package logical - -import ( - "context" - "reflect" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/logging" - "github.com/mitchellh/go-testing-interface" -) - -// TestRequest is a helper to create a purely in-memory Request struct. -func TestRequest(t testing.T, op Operation, path string) *Request { - return &Request{ - Operation: op, - Path: path, - Data: make(map[string]interface{}), - Storage: new(InmemStorage), - } -} - -// TestStorage is a helper that can be used from unit tests to verify -// the behavior of a Storage impl. -func TestStorage(t testing.T, s Storage) { - keys, err := s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if len(keys) > 0 { - t.Fatalf("should have no keys to start: %#v", keys) - } - - entry := &StorageEntry{Key: "foo", Value: []byte("bar")} - if err := s.Put(context.Background(), entry); err != nil { - t.Fatalf("put error: %s", err) - } - - actual, err := s.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get error: %s", err) - } - if !reflect.DeepEqual(actual, entry) { - t.Fatalf("wrong value. Expected: %#v\nGot: %#v", entry, actual) - } - - keys, err = s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if !reflect.DeepEqual(keys, []string{"foo"}) { - t.Fatalf("bad keys: %#v", keys) - } - - if err := s.Delete(context.Background(), "foo"); err != nil { - t.Fatalf("put error: %s", err) - } - - keys, err = s.List(context.Background(), "") - if err != nil { - t.Fatalf("list error: %s", err) - } - if len(keys) > 0 { - t.Fatalf("should have no keys to start: %#v", keys) - } -} - -func TestSystemView() *StaticSystemView { - defaultLeaseTTLVal := time.Hour * 24 - maxLeaseTTLVal := time.Hour * 24 * 2 - return &StaticSystemView{ - DefaultLeaseTTLVal: defaultLeaseTTLVal, - MaxLeaseTTLVal: maxLeaseTTLVal, - } -} - -func TestBackendConfig() *BackendConfig { - bc := &BackendConfig{ - Logger: logging.NewVaultLogger(log.Trace), - System: TestSystemView(), - } - - return bc -} diff --git a/vendor/github.com/hashicorp/vault/logical/token.go b/vendor/github.com/hashicorp/vault/logical/token.go deleted file mode 100644 index 337791e48..000000000 --- a/vendor/github.com/hashicorp/vault/logical/token.go +++ /dev/null @@ -1,119 +0,0 @@ -package logical - -import ( - "time" - - sockaddr "github.com/hashicorp/go-sockaddr" -) - -// TokenEntry is used to represent a given token -type TokenEntry struct { - // ID of this entry, generally a random UUID - ID string `json:"id" mapstructure:"id" structs:"id" sentinel:""` - - // Accessor for this token, a random UUID - Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor" sentinel:""` - - // Parent token, used for revocation trees - Parent string `json:"parent" mapstructure:"parent" structs:"parent" sentinel:""` - - // Which named policies should be used - Policies []string `json:"policies" mapstructure:"policies" structs:"policies"` - - // Used for audit trails, this is something like "auth/user/login" - Path string `json:"path" mapstructure:"path" structs:"path"` - - // Used for auditing. This could include things like "source", "user", "ip" - Meta map[string]string `json:"meta" mapstructure:"meta" structs:"meta" sentinel:"meta"` - - // Used for operators to be able to associate with the source - DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"` - - // Used to restrict the number of uses (zero is unlimited). This is to - // support one-time-tokens (generalized). There are a few special values: - // if it's -1 it has run through its use counts and is executing its final - // use; if it's -2 it is tainted, which means revocation is currently - // running on it; and if it's -3 it's also tainted but revocation - // previously ran and failed, so this hints the tidy function to try it - // again. - NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` - - // Time of token creation - CreationTime int64 `json:"creation_time" mapstructure:"creation_time" structs:"creation_time" sentinel:""` - - // Duration set when token was created - TTL time.Duration `json:"ttl" mapstructure:"ttl" structs:"ttl" sentinel:""` - - // Explicit maximum TTL on the token - ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl" sentinel:""` - - // If set, the role that was used for parameters at creation time - Role string `json:"role" mapstructure:"role" structs:"role"` - - // If set, the period of the token. This is only used when created directly - // through the create endpoint; periods managed by roles or other auth - // backends are subject to those renewal rules. - Period time.Duration `json:"period" mapstructure:"period" structs:"period" sentinel:""` - - // These are the deprecated fields - DisplayNameDeprecated string `json:"DisplayName" mapstructure:"DisplayName" structs:"DisplayName" sentinel:""` - NumUsesDeprecated int `json:"NumUses" mapstructure:"NumUses" structs:"NumUses" sentinel:""` - CreationTimeDeprecated int64 `json:"CreationTime" mapstructure:"CreationTime" structs:"CreationTime" sentinel:""` - ExplicitMaxTTLDeprecated time.Duration `json:"ExplicitMaxTTL" mapstructure:"ExplicitMaxTTL" structs:"ExplicitMaxTTL" sentinel:""` - - EntityID string `json:"entity_id" mapstructure:"entity_id" structs:"entity_id"` - - // The set of CIDRs that this token can be used with - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` -} - -func (te *TokenEntry) SentinelGet(key string) (interface{}, error) { - if te == nil { - return nil, nil - } - switch key { - case "period": - return te.Period, nil - - case "period_seconds": - return int64(te.Period.Seconds()), nil - - case "explicit_max_ttl": - return te.ExplicitMaxTTL, nil - - case "explicit_max_ttl_seconds": - return int64(te.ExplicitMaxTTL.Seconds()), nil - - case "creation_ttl": - return te.TTL, nil - - case "creation_ttl_seconds": - return int64(te.TTL.Seconds()), nil - - case "creation_time": - return time.Unix(te.CreationTime, 0).Format(time.RFC3339Nano), nil - - case "creation_time_unix": - return time.Unix(te.CreationTime, 0), nil - - case "meta", "metadata": - return te.Meta, nil - } - - return nil, nil -} - -func (te *TokenEntry) SentinelKeys() []string { - return []string{ - "period", - "period_seconds", - "explicit_max_ttl", - "explicit_max_ttl_seconds", - "creation_ttl", - "creation_ttl_seconds", - "creation_time", - "creation_time_unix", - "meta", - "metadata", - } -} diff --git a/vendor/github.com/hashicorp/vault/logical/translate_response.go b/vendor/github.com/hashicorp/vault/logical/translate_response.go deleted file mode 100644 index 84ed284a1..000000000 --- a/vendor/github.com/hashicorp/vault/logical/translate_response.go +++ /dev/null @@ -1,143 +0,0 @@ -package logical - -import ( - "bytes" - "encoding/json" - "fmt" - "time" -) - -// This logic was pulled from the http package so that it can be used for -// encoding wrapped responses as well. It simply translates the logical -// response to an http response, with the values we want and omitting the -// values we don't. -func LogicalResponseToHTTPResponse(input *Response) *HTTPResponse { - httpResp := &HTTPResponse{ - Data: input.Data, - Warnings: input.Warnings, - } - - if input.Secret != nil { - httpResp.LeaseID = input.Secret.LeaseID - httpResp.Renewable = input.Secret.Renewable - httpResp.LeaseDuration = int(input.Secret.TTL.Seconds()) - } - - // If we have authentication information, then - // set up the result structure. - if input.Auth != nil { - httpResp.Auth = &HTTPAuth{ - ClientToken: input.Auth.ClientToken, - Accessor: input.Auth.Accessor, - Policies: input.Auth.Policies, - TokenPolicies: input.Auth.TokenPolicies, - IdentityPolicies: input.Auth.IdentityPolicies, - Metadata: input.Auth.Metadata, - LeaseDuration: int(input.Auth.TTL.Seconds()), - Renewable: input.Auth.Renewable, - EntityID: input.Auth.EntityID, - } - } - - return httpResp -} - -func HTTPResponseToLogicalResponse(input *HTTPResponse) *Response { - logicalResp := &Response{ - Data: input.Data, - Warnings: input.Warnings, - } - - if input.LeaseID != "" { - logicalResp.Secret = &Secret{ - LeaseID: input.LeaseID, - } - logicalResp.Secret.Renewable = input.Renewable - logicalResp.Secret.TTL = time.Second * time.Duration(input.LeaseDuration) - } - - if input.Auth != nil { - logicalResp.Auth = &Auth{ - ClientToken: input.Auth.ClientToken, - Accessor: input.Auth.Accessor, - Policies: input.Auth.Policies, - TokenPolicies: input.Auth.TokenPolicies, - IdentityPolicies: input.Auth.IdentityPolicies, - Metadata: input.Auth.Metadata, - EntityID: input.Auth.EntityID, - } - logicalResp.Auth.Renewable = input.Auth.Renewable - logicalResp.Auth.TTL = time.Second * time.Duration(input.Auth.LeaseDuration) - } - - return logicalResp -} - -type HTTPResponse struct { - RequestID string `json:"request_id"` - LeaseID string `json:"lease_id"` - Renewable bool `json:"renewable"` - LeaseDuration int `json:"lease_duration"` - Data map[string]interface{} `json:"data"` - WrapInfo *HTTPWrapInfo `json:"wrap_info"` - Warnings []string `json:"warnings"` - Auth *HTTPAuth `json:"auth"` -} - -type HTTPAuth struct { - ClientToken string `json:"client_token"` - Accessor string `json:"accessor"` - Policies []string `json:"policies"` - TokenPolicies []string `json:"token_policies,omitempty"` - IdentityPolicies []string `json:"identity_policies,omitempty"` - Metadata map[string]string `json:"metadata"` - LeaseDuration int `json:"lease_duration"` - Renewable bool `json:"renewable"` - EntityID string `json:"entity_id"` -} - -type HTTPWrapInfo struct { - Token string `json:"token"` - Accessor string `json:"accessor"` - TTL int `json:"ttl"` - CreationTime string `json:"creation_time"` - CreationPath string `json:"creation_path"` - WrappedAccessor string `json:"wrapped_accessor,omitempty"` -} - -type HTTPSysInjector struct { - Response *HTTPResponse -} - -func (h HTTPSysInjector) MarshalJSON() ([]byte, error) { - j, err := json.Marshal(h.Response) - if err != nil { - return nil, err - } - // Fast path no data or empty data - if h.Response.Data == nil || len(h.Response.Data) == 0 { - return j, nil - } - // Marshaling a response will always be a JSON object, meaning it will - // always start with '{', so we hijack this to prepend necessary values - // Make a guess at the capacity, and write the object opener - buf := bytes.NewBuffer(make([]byte, 0, len(j)*2)) - buf.WriteRune('{') - for k, v := range h.Response.Data { - // Marshal each key/value individually - mk, err := json.Marshal(k) - if err != nil { - return nil, err - } - mv, err := json.Marshal(v) - if err != nil { - return nil, err - } - // Write into the final buffer. We'll never have a valid response - // without any fields so we can unconditionally add a comma after each. - buf.WriteString(fmt.Sprintf("%s: %s, ", mk, mv)) - } - // Add the rest, without the first '{' - buf.Write(j[1:]) - return buf.Bytes(), nil -} diff --git a/vendor/github.com/hashicorp/vault/main.go b/vendor/github.com/hashicorp/vault/main.go deleted file mode 100644 index 7e4b1c9d2..000000000 --- a/vendor/github.com/hashicorp/vault/main.go +++ /dev/null @@ -1,11 +0,0 @@ -package main // import "github.com/hashicorp/vault" - -import ( - "os" - - "github.com/hashicorp/vault/command" -) - -func main() { - os.Exit(command.Run(os.Args[1:])) -} diff --git a/vendor/github.com/hashicorp/vault/make.bat b/vendor/github.com/hashicorp/vault/make.bat deleted file mode 100644 index d636b5b03..000000000 --- a/vendor/github.com/hashicorp/vault/make.bat +++ /dev/null @@ -1,113 +0,0 @@ -@echo off -setlocal - -set _EXITCODE=0 - -REM If no target is provided, default to test. -if [%1]==[] goto test - -set _TARGETS=bin,bootstrap,dev,generate,test,testacc,testrace,vet -set _EXTERNAL_TOOLS=github.com/mitchellh/gox,github.com/kardianos/govendor - -REM Run target. -for %%a in (%_TARGETS%) do (if x%1==x%%a goto %%a) -goto usage - -REM bin generates the releasable binaries for Vault -:bin - call :generate - call .\scripts\windows\build.bat "%CD%" - goto :eof - -REM bootstrap downloads required build tools -:bootstrap - for %%t in (%_EXTERNAL_TOOLS%) do (go get -u -v %%t) - goto :eof - -REM dev creates binaries for testing Vault locally. These are put -REM into ./bin/ as well as %GOPATH%/bin -:dev - call :generate - call .\scripts\windows\build.bat "%CD%" VAULT_DEV - goto :eof - -REM generate runs `go generate` to build the dynamically generated -REM source files. -:generate - for /F "usebackq" %%f in (`go list ./... ^| findstr /v vendor`) do @go generate %%f - goto :eof - -REM test runs the unit tests and vets the code. -:test - call :testsetup - go test %_TEST% %TESTARGS% -timeout=30s -parallel=4 - call :setMaxExitCode %ERRORLEVEL% - echo. - goto vet - -REM testacc runs acceptance tests. -:testacc - call :testsetup - if x%_TEST% == x./... goto testacc_fail - if x%_TEST% == x.\... goto testacc_fail - set VAULT_ACC=1 - go test %_TEST% -v %TESTARGS% -timeout 45m - exit /b %ERRORLEVEL% -:testacc_fail - echo ERROR: Set %%TEST%% to a specific package. - exit /b 1 - -REM testrace runs the race checker. -:testrace - call :testsetup - go test -race %_TEST% %TESTARGS% - exit /b %ERRORLEVEL% - -REM testsetup calls `go generate` and defines the variables VAULT_ACC -REM and _TEST. VAULT_ACC is always cleared. _TEST defaults to the value -REM of the TEST environment variable, provided that TEST is defined, -REM otherwise _TEST it is set to "./...". -:testsetup - call :generate - set VAULT_ACC= - set _TEST=./... - if defined TEST set _TEST=%TEST% - goto :eof - -REM vet runs the Go source code static analysis tool `vet` to find -REM any common errors. -:vet - set _VETARGS=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr - if defined VETARGS set _VETARGS=%VETARGS% - - go tool vet 2>nul - if %ERRORLEVEL% equ 3 go get golang.org/x/tools/cmd/vet - - set _vetExitCode=0 - set _VAULT_PKG_DIRS=%TEMP%\vault-pkg-dirs.txt - - go list -f {{.Dir}} ./... | findstr /v vendor >"%_VAULT_PKG_DIRS%" - REM Skip the first row, which is the main vault package (.*github.com/hashicorp/vault$) - for /f "delims= skip=1" %%d in ("%_VAULT_PKG_DIRS%") do ( - go tool vet %_VETARGS% "%%d" - if ERRORLEVEL 1 set _vetExitCode=1 - call :setMaxExitCode %_vetExitCode% - ) - del /f "%_VAULT_PKG_DIRS%" 2>NUL - if %_vetExitCode% equ 0 exit /b %_EXITCODE% - echo. - echo Vet found suspicious constructs. Please check the reported constructs - echo and fix them if necessary before submitting the code for reviewal. - exit /b %_EXITCODE% - -:setMaxExitCode - if %1 gtr %_EXITCODE% set _EXITCODE=%1 - goto :eof - -:usage - echo usage: make [target] - echo. - echo target is in {%_TARGETS%}. - echo target defaults to test if none is provided. - exit /b 2 - goto :eof diff --git a/vendor/github.com/hashicorp/vault/physical/alicloudoss/alicloudoss.go b/vendor/github.com/hashicorp/vault/physical/alicloudoss/alicloudoss.go deleted file mode 100644 index 85d9d583d..000000000 --- a/vendor/github.com/hashicorp/vault/physical/alicloudoss/alicloudoss.go +++ /dev/null @@ -1,223 +0,0 @@ -package alicloudoss - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "sort" - "strconv" - "strings" - "time" - - "github.com/aliyun/aliyun-oss-go-sdk/oss" - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/physical" -) - -// Verify AliCloudOSSBackend satisfies the correct interfaces -var _ physical.Backend = (*AliCloudOSSBackend)(nil) - -// AliCloudOSSBackend is a physical backend that stores data -// within an Alibaba OSS bucket. -type AliCloudOSSBackend struct { - bucket string - client *oss.Client - logger log.Logger - permitPool *physical.PermitPool -} - -// NewAliCloudOSSBackend constructs an OSS backend using a pre-existing -// bucket. Credentials can be provided to the backend, sourced -// from the environment. -func NewAliCloudOSSBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - endpoint := os.Getenv("ALICLOUD_OSS_ENDPOINT") - if endpoint == "" { - endpoint = conf["endpoint"] - if endpoint == "" { - return nil, fmt.Errorf("'endpoint' must be set") - } - } - - bucket := os.Getenv("ALICLOUD_OSS_BUCKET") - if bucket == "" { - bucket = conf["bucket"] - if bucket == "" { - return nil, fmt.Errorf("'bucket' must be set") - } - } - - accessKeyID := os.Getenv("ALICLOUD_ACCESS_KEY") - if accessKeyID == "" { - accessKeyID = conf["access_key"] - if accessKeyID == "" { - return nil, fmt.Errorf("'access_key' must be set") - } - } - - accessKeySecret := os.Getenv("ALICLOUD_SECRET_KEY") - if accessKeySecret == "" { - accessKeySecret = conf["secret_key"] - if accessKeySecret == "" { - return nil, fmt.Errorf("'secret_key' must be set") - } - } - - options := func(c *oss.Client) { - c.Config.Timeout = 30 - } - - client, err := oss.New(endpoint, accessKeyID, accessKeySecret, options) - if err != nil { - return nil, err - } - - bucketObj, err := client.Bucket(bucket) - if err != nil { - return nil, err - } - - _, err = bucketObj.ListObjects() - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("unable to access bucket %q at endpoint %q: {{err}}", bucket, endpoint), err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - a := &AliCloudOSSBackend{ - client: client, - bucket: bucket, - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - return a, nil -} - -// Put is used to insert or update an entry -func (a *AliCloudOSSBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"alibaba", "put"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - bucket, err := a.client.Bucket(a.bucket) - if err != nil { - return err - } - - return bucket.PutObject(entry.Key, bytes.NewReader(entry.Value)) - -} - -// Get is used to fetch an entry -func (a *AliCloudOSSBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"alibaba", "get"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - bucket, err := a.client.Bucket(a.bucket) - if err != nil { - return nil, err - } - - object, err := bucket.GetObject(key) - if err != nil { - switch err := err.(type) { - case oss.ServiceError: - if err.StatusCode == 404 && err.Code == "NoSuchKey" { - return nil, nil - } - } - return nil, err - } - - data := bytes.NewBuffer(nil) - _, err = io.Copy(data, object) - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: data.Bytes(), - } - - return ent, nil -} - -// Delete is used to permanently delete an entry -func (a *AliCloudOSSBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"alibaba", "delete"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - bucket, err := a.client.Bucket(a.bucket) - if err != nil { - return err - } - - return bucket.DeleteObject(key) -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (a *AliCloudOSSBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"alibaba", "list"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - keys := []string{} - - bucket, err := a.client.Bucket(a.bucket) - if err != nil { - return nil, err - } - - marker := oss.Marker("") - - for { - result, err := bucket.ListObjects(oss.Prefix(prefix), oss.Delimiter("/"), marker) - if err != nil { - return nil, err - } - - for _, commonPrefix := range result.CommonPrefixes { - - commonPrefix := strings.TrimPrefix(commonPrefix, prefix) - keys = append(keys, commonPrefix) - } - - for _, object := range result.Objects { - // Add objects only from the current 'folder' - key := strings.TrimPrefix(object.Key, prefix) - keys = append(keys, key) - } - - if !result.IsTruncated { - break - } - - marker = oss.Marker(result.NextMarker) - } - - sort.Strings(keys) - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/azure/azure.go b/vendor/github.com/hashicorp/vault/physical/azure/azure.go deleted file mode 100644 index 17e7eee9e..000000000 --- a/vendor/github.com/hashicorp/vault/physical/azure/azure.go +++ /dev/null @@ -1,234 +0,0 @@ -package azure - -import ( - "context" - "encoding/base64" - "fmt" - "io/ioutil" - "os" - "sort" - "strconv" - "strings" - "time" - - storage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -const ( - // MaxBlobSize at this time - MaxBlobSize = 1024 * 1024 * 4 - // MaxListResults is the current default value, setting explicitly - MaxListResults = 5000 -) - -// AzureBackend is a physical backend that stores data -// within an Azure blob container. -type AzureBackend struct { - container *storage.Container - logger log.Logger - permitPool *physical.PermitPool -} - -// Verify AzureBackend satisfies the correct interfaces -var _ physical.Backend = (*AzureBackend)(nil) - -// NewAzureBackend constructs an Azure backend using a pre-existing -// bucket. Credentials can be provided to the backend, sourced -// from the environment, AWS credential files or by IAM role. -func NewAzureBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - name := os.Getenv("AZURE_BLOB_CONTAINER") - if name == "" { - name = conf["container"] - if name == "" { - return nil, fmt.Errorf("'container' must be set") - } - } - - accountName := os.Getenv("AZURE_ACCOUNT_NAME") - if accountName == "" { - accountName = conf["accountName"] - if accountName == "" { - return nil, fmt.Errorf("'accountName' must be set") - } - } - - accountKey := os.Getenv("AZURE_ACCOUNT_KEY") - if accountKey == "" { - accountKey = conf["accountKey"] - if accountKey == "" { - return nil, fmt.Errorf("'accountKey' must be set") - } - } - - environmentName := os.Getenv("AZURE_ENVIRONMENT") - if environmentName == "" { - environmentName = conf["environment"] - if environmentName == "" { - environmentName = "AzurePublicCloud" - } - } - environment, err := azure.EnvironmentFromName(environmentName) - if err != nil { - errorMsg := fmt.Sprintf("failed to look up Azure environment descriptor for name %q: {{err}}", - environmentName) - return nil, errwrap.Wrapf(errorMsg, err) - } - - client, err := storage.NewBasicClientOnSovereignCloud(accountName, accountKey, environment) - if err != nil { - return nil, errwrap.Wrapf("failed to create Azure client: {{err}}", err) - } - client.HTTPClient = cleanhttp.DefaultPooledClient() - - blobClient := client.GetBlobService() - container := blobClient.GetContainerReference(name) - _, err = container.CreateIfNotExists(&storage.CreateContainerOptions{ - Access: storage.ContainerAccessTypePrivate, - }) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to create %q container: {{err}}", name), err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - a := &AzureBackend{ - container: container, - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - return a, nil -} - -// Put is used to insert or update an entry -func (a *AzureBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"azure", "put"}, time.Now()) - - if len(entry.Value) >= MaxBlobSize { - return fmt.Errorf("value is bigger than the current supported limit of 4MBytes") - } - - blockID := base64.StdEncoding.EncodeToString([]byte("AAAA")) - blocks := make([]storage.Block, 1) - blocks[0] = storage.Block{ID: blockID, Status: storage.BlockStatusLatest} - - a.permitPool.Acquire() - defer a.permitPool.Release() - - blob := &storage.Blob{ - Container: a.container, - Name: entry.Key, - } - if err := blob.PutBlock(blockID, entry.Value, nil); err != nil { - return err - } - - return blob.PutBlockList(blocks, nil) -} - -// Get is used to fetch an entry -func (a *AzureBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"azure", "get"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - blob := &storage.Blob{ - Container: a.container, - Name: key, - } - exists, err := blob.Exists() - if err != nil { - return nil, err - } - if !exists { - return nil, nil - } - - reader, err := blob.Get(nil) - if err != nil { - return nil, err - } - defer reader.Close() - data, err := ioutil.ReadAll(reader) - - ent := &physical.Entry{ - Key: key, - Value: data, - } - - return ent, err -} - -// Delete is used to permanently delete an entry -func (a *AzureBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"azure", "delete"}, time.Now()) - - blob := &storage.Blob{ - Container: a.container, - Name: key, - } - - a.permitPool.Acquire() - defer a.permitPool.Release() - - _, err := blob.DeleteIfExists(nil) - return err -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (a *AzureBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"azure", "list"}, time.Now()) - - a.permitPool.Acquire() - defer a.permitPool.Release() - - var marker string - keys := []string{} - for { - list, err := a.container.ListBlobs(storage.ListBlobsParameters{ - Prefix: prefix, - Marker: marker, - MaxResults: MaxListResults, - }) - if err != nil { - return nil, err - } - - for _, blob := range list.Blobs { - key := strings.TrimPrefix(blob.Name, prefix) - if i := strings.Index(key, "/"); i == -1 { - // file - keys = append(keys, key) - } else { - // subdirectory - keys = strutil.AppendIfMissing(keys, key[:i+1]) - } - } - - if list.NextMarker == "" { - break - } - marker = list.NextMarker - } - - sort.Strings(keys) - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/cache.go b/vendor/github.com/hashicorp/vault/physical/cache.go deleted file mode 100644 index 4e2e5a5d6..000000000 --- a/vendor/github.com/hashicorp/vault/physical/cache.go +++ /dev/null @@ -1,220 +0,0 @@ -package physical - -import ( - "context" - "sync/atomic" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/golang-lru" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/pathmanager" -) - -const ( - // DefaultCacheSize is used if no cache size is specified for NewCache - DefaultCacheSize = 128 * 1024 -) - -// These paths don't need to be cached by the LRU cache. This should -// particularly help memory pressure when unsealing. -var cacheExceptionsPaths = []string{ - "wal/logs/", - "index/pages/", - "index-dr/pages/", - "sys/expire/", -} - -// Cache is used to wrap an underlying physical backend -// and provide an LRU cache layer on top. Most of the reads done by -// Vault are for policy objects so there is a large read reduction -// by using a simple write-through cache. -type Cache struct { - backend Backend - lru *lru.TwoQueueCache - locks []*locksutil.LockEntry - logger log.Logger - enabled *uint32 - cacheExceptions *pathmanager.PathManager -} - -// TransactionalCache is a Cache that wraps the physical that is transactional -type TransactionalCache struct { - *Cache - Transactional -} - -// Verify Cache satisfies the correct interfaces -var _ ToggleablePurgemonster = (*Cache)(nil) -var _ ToggleablePurgemonster = (*TransactionalCache)(nil) -var _ Backend = (*Cache)(nil) -var _ Transactional = (*TransactionalCache)(nil) - -// NewCache returns a physical cache of the given size. -// If no size is provided, the default size is used. -func NewCache(b Backend, size int, logger log.Logger) *Cache { - if logger.IsDebug() { - logger.Debug("creating LRU cache", "size", size) - } - if size <= 0 { - size = DefaultCacheSize - } - - pm := pathmanager.New() - pm.AddPaths(cacheExceptionsPaths) - - cache, _ := lru.New2Q(size) - c := &Cache{ - backend: b, - lru: cache, - locks: locksutil.CreateLocks(), - logger: logger, - // This fails safe. - enabled: new(uint32), - cacheExceptions: pm, - } - return c -} - -func NewTransactionalCache(b Backend, size int, logger log.Logger) *TransactionalCache { - c := &TransactionalCache{ - Cache: NewCache(b, size, logger), - Transactional: b.(Transactional), - } - return c -} - -func (c *Cache) shouldCache(key string) bool { - if atomic.LoadUint32(c.enabled) == 0 { - return false - } - - return !c.cacheExceptions.HasPath(key) -} - -// SetEnabled is used to toggle whether the cache is on or off. It must be -// called with true to actually activate the cache after creation. -func (c *Cache) SetEnabled(enabled bool) { - if enabled { - atomic.StoreUint32(c.enabled, 1) - return - } - atomic.StoreUint32(c.enabled, 0) -} - -// Purge is used to clear the cache -func (c *Cache) Purge(ctx context.Context) { - // Lock the world - for _, lock := range c.locks { - lock.Lock() - defer lock.Unlock() - } - - c.lru.Purge() -} - -func (c *Cache) Put(ctx context.Context, entry *Entry) error { - if entry != nil && !c.shouldCache(entry.Key) { - return c.backend.Put(ctx, entry) - } - - lock := locksutil.LockForKey(c.locks, entry.Key) - lock.Lock() - defer lock.Unlock() - - err := c.backend.Put(ctx, entry) - if err == nil { - c.lru.Add(entry.Key, entry) - } - return err -} - -func (c *Cache) Get(ctx context.Context, key string) (*Entry, error) { - if !c.shouldCache(key) { - return c.backend.Get(ctx, key) - } - - lock := locksutil.LockForKey(c.locks, key) - lock.RLock() - defer lock.RUnlock() - - // Check the LRU first - if raw, ok := c.lru.Get(key); ok { - if raw == nil { - return nil, nil - } - return raw.(*Entry), nil - } - - // Read from the underlying backend - ent, err := c.backend.Get(ctx, key) - if err != nil { - return nil, err - } - - // Cache the result - if ent != nil { - c.lru.Add(key, ent) - } - - return ent, nil -} - -func (c *Cache) Delete(ctx context.Context, key string) error { - if !c.shouldCache(key) { - return c.backend.Delete(ctx, key) - } - - lock := locksutil.LockForKey(c.locks, key) - lock.Lock() - defer lock.Unlock() - - err := c.backend.Delete(ctx, key) - if err == nil { - c.lru.Remove(key) - } - return err -} - -func (c *Cache) List(ctx context.Context, prefix string) ([]string, error) { - // Always pass-through as this would be difficult to cache. For the same - // reason we don't lock as we can't reasonably know which locks to readlock - // ahead of time. - return c.backend.List(ctx, prefix) -} - -func (c *TransactionalCache) Transaction(ctx context.Context, txns []*TxnEntry) error { - // Bypass the locking below - if atomic.LoadUint32(c.enabled) == 0 { - return c.Transactional.Transaction(ctx, txns) - } - - // Collect keys that need to be locked - var keys []string - for _, curr := range txns { - keys = append(keys, curr.Entry.Key) - } - // Lock the keys - for _, l := range locksutil.LocksForKeys(c.locks, keys) { - l.Lock() - defer l.Unlock() - } - - if err := c.Transactional.Transaction(ctx, txns); err != nil { - return err - } - - for _, txn := range txns { - if !c.shouldCache(txn.Entry.Key) { - continue - } - - switch txn.Operation { - case PutOperation: - c.lru.Add(txn.Entry.Key, txn.Entry) - case DeleteOperation: - c.lru.Remove(txn.Entry.Key) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/cassandra/cassandra.go b/vendor/github.com/hashicorp/vault/physical/cassandra/cassandra.go deleted file mode 100644 index 17b09ffce..000000000 --- a/vendor/github.com/hashicorp/vault/physical/cassandra/cassandra.go +++ /dev/null @@ -1,341 +0,0 @@ -package cassandra - -import ( - "context" - "crypto/tls" - "fmt" - "io/ioutil" - "net" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/gocql/gocql" - "github.com/hashicorp/vault/helper/certutil" - "github.com/hashicorp/vault/physical" -) - -// CassandraBackend is a physical backend that stores data in Cassandra. -type CassandraBackend struct { - sess *gocql.Session - table string - - logger log.Logger -} - -// Verify CassandraBackend satisfies the correct interfaces -var _ physical.Backend = (*CassandraBackend)(nil) - -// NewCassandraBackend constructs a Cassandra backend using a pre-existing -// keyspace and table. -func NewCassandraBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - splitArray := func(v string) []string { - return strings.FieldsFunc(v, func(r rune) bool { - return r == ',' - }) - } - - var ( - hosts = splitArray(conf["hosts"]) - port = 9042 - explicitPort = false - keyspace = conf["keyspace"] - table = conf["table"] - consistency = gocql.LocalQuorum - ) - - if len(hosts) == 0 { - hosts = []string{"localhost"} - } - for i, hp := range hosts { - h, ps, err := net.SplitHostPort(hp) - if err != nil { - continue - } - p, err := strconv.Atoi(ps) - if err != nil { - return nil, err - } - - if explicitPort && p != port { - return nil, fmt.Errorf("all hosts must have the same port") - } - hosts[i], port = h, p - explicitPort = true - } - - if keyspace == "" { - keyspace = "vault" - } - if table == "" { - table = "entries" - } - if cs, ok := conf["consistency"]; ok { - switch cs { - case "ANY": - consistency = gocql.Any - case "ONE": - consistency = gocql.One - case "TWO": - consistency = gocql.Two - case "THREE": - consistency = gocql.Three - case "QUORUM": - consistency = gocql.Quorum - case "ALL": - consistency = gocql.All - case "LOCAL_QUORUM": - consistency = gocql.LocalQuorum - case "EACH_QUORUM": - consistency = gocql.EachQuorum - case "LOCAL_ONE": - consistency = gocql.LocalOne - default: - return nil, fmt.Errorf("'consistency' must be one of {ANY, ONE, TWO, THREE, QUORUM, ALL, LOCAL_QUORUM, EACH_QUORUM, LOCAL_ONE}") - } - } - - connectStart := time.Now() - cluster := gocql.NewCluster(hosts...) - cluster.Port = port - cluster.Keyspace = keyspace - - cluster.ProtoVersion = 2 - if protoVersionStr, ok := conf["protocol_version"]; ok { - protoVersion, err := strconv.Atoi(protoVersionStr) - if err != nil { - return nil, fmt.Errorf("'protocol_version' must be an integer") - } - cluster.ProtoVersion = protoVersion - } - - if username, ok := conf["username"]; ok { - if cluster.ProtoVersion < 2 { - return nil, fmt.Errorf("authentication is not supported with protocol version < 2") - } - authenticator := gocql.PasswordAuthenticator{Username: username} - if password, ok := conf["password"]; ok { - authenticator.Password = password - } - cluster.Authenticator = authenticator - } - - if connTimeoutStr, ok := conf["connection_timeout"]; ok { - connectionTimeout, err := strconv.Atoi(connTimeoutStr) - if err != nil { - return nil, fmt.Errorf("'connection_timeout' must be an integer") - } - cluster.Timeout = time.Duration(connectionTimeout) * time.Second - } - - if err := setupCassandraTLS(conf, cluster); err != nil { - return nil, err - } - - sess, err := cluster.CreateSession() - if err != nil { - return nil, err - } - metrics.MeasureSince([]string{"cassandra", "connect"}, connectStart) - sess.SetConsistency(consistency) - - impl := &CassandraBackend{ - sess: sess, - table: table, - logger: logger, - } - return impl, nil -} - -func setupCassandraTLS(conf map[string]string, cluster *gocql.ClusterConfig) error { - tlsOnStr, ok := conf["tls"] - if !ok { - return nil - } - - tlsOn, err := strconv.Atoi(tlsOnStr) - if err != nil { - return fmt.Errorf("'tls' must be an integer (0 or 1)") - } - - if tlsOn == 0 { - return nil - } - - var tlsConfig = &tls.Config{} - if pemBundlePath, ok := conf["pem_bundle_file"]; ok { - pemBundleData, err := ioutil.ReadFile(pemBundlePath) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error reading pem bundle from %q: {{err}}", pemBundlePath), err) - } - pemBundle, err := certutil.ParsePEMBundle(string(pemBundleData)) - if err != nil { - return errwrap.Wrapf("error parsing 'pem_bundle': {{err}}", err) - } - tlsConfig, err = pemBundle.GetTLSConfig(certutil.TLSClient) - if err != nil { - return err - } - } else { - if pemJSONPath, ok := conf["pem_json_file"]; ok { - pemJSONData, err := ioutil.ReadFile(pemJSONPath) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error reading json bundle from %q: {{err}}", pemJSONPath), err) - } - pemJSON, err := certutil.ParsePKIJSON([]byte(pemJSONData)) - if err != nil { - return err - } - tlsConfig, err = pemJSON.GetTLSConfig(certutil.TLSClient) - if err != nil { - return err - } - } - } - - if tlsSkipVerifyStr, ok := conf["tls_skip_verify"]; ok { - tlsSkipVerify, err := strconv.Atoi(tlsSkipVerifyStr) - if err != nil { - return fmt.Errorf("'tls_skip_verify' must be an integer (0 or 1)") - } - if tlsSkipVerify == 0 { - tlsConfig.InsecureSkipVerify = false - } else { - tlsConfig.InsecureSkipVerify = true - } - } - - if tlsMinVersion, ok := conf["tls_min_version"]; ok { - switch tlsMinVersion { - case "tls10": - tlsConfig.MinVersion = tls.VersionTLS10 - case "tls11": - tlsConfig.MinVersion = tls.VersionTLS11 - case "tls12": - tlsConfig.MinVersion = tls.VersionTLS12 - default: - return fmt.Errorf("'tls_min_version' must be one of `tls10`, `tls11` or `tls12`") - } - } - - cluster.SslOpts = &gocql.SslOptions{ - Config: tlsConfig.Clone()} - return nil -} - -// bucketName sanitises a bucket name for Cassandra -func (c *CassandraBackend) bucketName(name string) string { - if name == "" { - name = "." - } - return strings.TrimRight(name, "/") -} - -// bucket returns all the prefix buckets the key should be stored at -func (c *CassandraBackend) buckets(key string) []string { - vals := append([]string{""}, physical.Prefixes(key)...) - for i, v := range vals { - vals[i] = c.bucketName(v) - } - return vals -} - -// bucket returns the most specific bucket for the key -func (c *CassandraBackend) bucket(key string) string { - bs := c.buckets(key) - return bs[len(bs)-1] -} - -// Put is used to insert or update an entry -func (c *CassandraBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"cassandra", "put"}, time.Now()) - - // Execute inserts to each key prefix simultaneously - stmt := fmt.Sprintf(`INSERT INTO "%s" (bucket, key, value) VALUES (?, ?, ?)`, c.table) - results := make(chan error) - buckets := c.buckets(entry.Key) - for _, _bucket := range buckets { - go func(bucket string) { - results <- c.sess.Query(stmt, bucket, entry.Key, entry.Value).Exec() - }(_bucket) - } - for i := 0; i < len(buckets); i++ { - if err := <-results; err != nil { - return err - } - } - return nil -} - -// Get is used to fetch an entry -func (c *CassandraBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"cassandra", "get"}, time.Now()) - - v := []byte(nil) - stmt := fmt.Sprintf(`SELECT value FROM "%s" WHERE bucket = ? AND key = ? LIMIT 1`, c.table) - q := c.sess.Query(stmt, c.bucket(key), key) - if err := q.Scan(&v); err != nil { - if err == gocql.ErrNotFound { - return nil, nil - } - return nil, err - } - - return &physical.Entry{ - Key: key, - Value: v, - }, nil -} - -// Delete is used to permanently delete an entry -func (c *CassandraBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"cassandra", "delete"}, time.Now()) - - stmt := fmt.Sprintf(`DELETE FROM "%s" WHERE bucket = ? AND key = ?`, c.table) - results := make(chan error) - buckets := c.buckets(key) - - for _, bucket := range buckets { - go func(bucket string) { - results <- c.sess.Query(stmt, bucket, key).Exec() - }(bucket) - } - - for i := 0; i < len(buckets); i++ { - if err := <-results; err != nil { - return err - } - } - return nil -} - -// List is used ot list all the keys under a given -// prefix, up to the next prefix. -func (c *CassandraBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"cassandra", "list"}, time.Now()) - - stmt := fmt.Sprintf(`SELECT key FROM "%s" WHERE bucket = ?`, c.table) - q := c.sess.Query(stmt, c.bucketName(prefix)) - iter := q.Iter() - k, keys := "", []string{} - for iter.Scan(&k) { - // Only return the next "component" (with a trailing slash if it has children) - k = strings.TrimPrefix(k, prefix) - if parts := strings.SplitN(k, "/", 2); len(parts) > 1 { - k = parts[0] + "/" - } else { - k = parts[0] - } - - // Deduplicate; this works because the keys are sorted - if len(keys) > 0 && keys[len(keys)-1] == k { - continue - } - keys = append(keys, k) - } - return keys, iter.Close() -} diff --git a/vendor/github.com/hashicorp/vault/physical/cockroachdb/cockroachdb.go b/vendor/github.com/hashicorp/vault/physical/cockroachdb/cockroachdb.go deleted file mode 100644 index 646eb0822..000000000 --- a/vendor/github.com/hashicorp/vault/physical/cockroachdb/cockroachdb.go +++ /dev/null @@ -1,241 +0,0 @@ -package cockroachdb - -import ( - "context" - "database/sql" - "fmt" - "sort" - "strconv" - "strings" - "time" - - "github.com/armon/go-metrics" - "github.com/cockroachdb/cockroach-go/crdb" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" - - // CockroachDB uses the Postgres SQL driver - _ "github.com/lib/pq" -) - -// Verify CockroachDBBackend satisfies the correct interfaces -var _ physical.Backend = (*CockroachDBBackend)(nil) -var _ physical.Transactional = (*CockroachDBBackend)(nil) - -// CockroachDBBackend Backend is a physical backend that stores data -// within a CockroachDB database. -type CockroachDBBackend struct { - table string - client *sql.DB - rawStatements map[string]string - statements map[string]*sql.Stmt - logger log.Logger - permitPool *physical.PermitPool -} - -// NewCockroachDBBackend constructs a CockroachDB backend using the given -// API client, server address, credentials, and database. -func NewCockroachDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the CockroachDB credentials to perform read/write operations. - connURL, ok := conf["connection_url"] - if !ok || connURL == "" { - return nil, fmt.Errorf("missing connection_url") - } - - dbTable, ok := conf["table"] - if !ok { - dbTable = "vault_kv_store" - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - var err error - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - // Create CockroachDB handle for the database. - db, err := sql.Open("postgres", connURL) - if err != nil { - return nil, errwrap.Wrapf("failed to connect to cockroachdb: {{err}}", err) - } - - // Create the required table if it doesn't exists. - createQuery := "CREATE TABLE IF NOT EXISTS " + dbTable + - " (path STRING, value BYTES, PRIMARY KEY (path))" - if _, err := db.Exec(createQuery); err != nil { - return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err) - } - - // Setup the backend - c := &CockroachDBBackend{ - table: dbTable, - client: db, - rawStatements: map[string]string{ - "put": "INSERT INTO " + dbTable + " VALUES($1, $2)" + - " ON CONFLICT (path) DO " + - " UPDATE SET (path, value) = ($1, $2)", - "get": "SELECT value FROM " + dbTable + " WHERE path = $1", - "delete": "DELETE FROM " + dbTable + " WHERE path = $1", - "list": "SELECT path FROM " + dbTable + " WHERE path LIKE $1", - }, - statements: make(map[string]*sql.Stmt), - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - - // Prepare all the statements required - for name, query := range c.rawStatements { - if err := c.prepare(name, query); err != nil { - return nil, err - } - } - return c, nil -} - -// prepare is a helper to prepare a query for future execution -func (c *CockroachDBBackend) prepare(name, query string) error { - stmt, err := c.client.Prepare(query) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) - } - c.statements[name] = stmt - return nil -} - -// Put is used to insert or update an entry. -func (c *CockroachDBBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"cockroachdb", "put"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - _, err := c.statements["put"].Exec(entry.Key, entry.Value) - if err != nil { - return err - } - return nil -} - -// Get is used to fetch and entry. -func (c *CockroachDBBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"cockroachdb", "get"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - var result []byte - err := c.statements["get"].QueryRow(key).Scan(&result) - if err == sql.ErrNoRows { - return nil, nil - } - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: result, - } - return ent, nil -} - -// Delete is used to permanently delete an entry -func (c *CockroachDBBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"cockroachdb", "delete"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - _, err := c.statements["delete"].Exec(key) - if err != nil { - return err - } - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (c *CockroachDBBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"cockroachdb", "list"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - likePrefix := prefix + "%" - rows, err := c.statements["list"].Query(likePrefix) - if err != nil { - return nil, err - } - defer rows.Close() - - var keys []string - for rows.Next() { - var key string - err = rows.Scan(&key) - if err != nil { - return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) - } - - key = strings.TrimPrefix(key, prefix) - if i := strings.Index(key, "/"); i == -1 { - // Add objects only from the current 'folder' - keys = append(keys, key) - } else if i != -1 { - // Add truncated 'folder' paths - keys = strutil.AppendIfMissing(keys, string(key[:i+1])) - } - } - - sort.Strings(keys) - return keys, nil -} - -// Transaction is used to run multiple entries via a transaction -func (c *CockroachDBBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - defer metrics.MeasureSince([]string{"cockroachdb", "transaction"}, time.Now()) - if len(txns) == 0 { - return nil - } - - c.permitPool.Acquire() - defer c.permitPool.Release() - - return crdb.ExecuteTx(context.Background(), c.client, nil, func(tx *sql.Tx) error { - return c.transaction(tx, txns) - }) -} - -func (c *CockroachDBBackend) transaction(tx *sql.Tx, txns []*physical.TxnEntry) error { - deleteStmt, err := tx.Prepare(c.rawStatements["delete"]) - if err != nil { - return err - } - putStmt, err := tx.Prepare(c.rawStatements["put"]) - if err != nil { - return err - } - - for _, op := range txns { - switch op.Operation { - case physical.DeleteOperation: - _, err = deleteStmt.Exec(op.Entry.Key) - case physical.PutOperation: - _, err = putStmt.Exec(op.Entry.Key, op.Entry.Value) - default: - return fmt.Errorf("%q is not a supported transaction operation", op.Operation) - } - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/consul/consul.go b/vendor/github.com/hashicorp/vault/physical/consul/consul.go deleted file mode 100644 index 554ab1a33..000000000 --- a/vendor/github.com/hashicorp/vault/physical/consul/consul.go +++ /dev/null @@ -1,880 +0,0 @@ -package consul - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "golang.org/x/net/http2" - - log "github.com/hashicorp/go-hclog" - - "crypto/tls" - "crypto/x509" - - "github.com/armon/go-metrics" - "github.com/hashicorp/consul/api" - "github.com/hashicorp/consul/lib" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/physical" -) - -const ( - // checkJitterFactor specifies the jitter factor used to stagger checks - checkJitterFactor = 16 - - // checkMinBuffer specifies provides a guarantee that a check will not - // be executed too close to the TTL check timeout - checkMinBuffer = 100 * time.Millisecond - - // consulRetryInterval specifies the retry duration to use when an - // API call to the Consul agent fails. - consulRetryInterval = 1 * time.Second - - // defaultCheckTimeout changes the timeout of TTL checks - defaultCheckTimeout = 5 * time.Second - - // DefaultServiceName is the default Consul service name used when - // advertising a Vault instance. - DefaultServiceName = "vault" - - // reconcileTimeout is how often Vault should query Consul to detect - // and fix any state drift. - reconcileTimeout = 60 * time.Second - - // consistencyModeDefault is the configuration value used to tell - // consul to use default consistency. - consistencyModeDefault = "default" - - // consistencyModeStrong is the configuration value used to tell - // consul to use strong consistency. - consistencyModeStrong = "strong" -) - -type notifyEvent struct{} - -// Verify ConsulBackend satisfies the correct interfaces -var _ physical.Backend = (*ConsulBackend)(nil) -var _ physical.HABackend = (*ConsulBackend)(nil) -var _ physical.Lock = (*ConsulLock)(nil) -var _ physical.Transactional = (*ConsulBackend)(nil) - -var ( - hostnameRegex = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`) -) - -// ConsulBackend is a physical backend that stores data at specific -// prefix within Consul. It is used for most production situations as -// it allows Vault to run on multiple machines in a highly-available manner. -type ConsulBackend struct { - path string - logger log.Logger - client *api.Client - kv *api.KV - permitPool *physical.PermitPool - serviceLock sync.RWMutex - redirectHost string - redirectPort int64 - serviceName string - serviceTags []string - serviceAddress *string - disableRegistration bool - checkTimeout time.Duration - consistencyMode string - - notifyActiveCh chan notifyEvent - notifySealedCh chan notifyEvent - - sessionTTL string - lockWaitTime time.Duration -} - -// NewConsulBackend constructs a Consul backend using the given API client -// and the prefix in the KV store. -func NewConsulBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the path in Consul - path, ok := conf["path"] - if !ok { - path = "vault/" - } - if logger.IsDebug() { - logger.Debug("config path set", "path", path) - } - - // Ensure path is suffixed but not prefixed - if !strings.HasSuffix(path, "/") { - logger.Warn("appending trailing forward slash to path") - path += "/" - } - if strings.HasPrefix(path, "/") { - logger.Warn("trimming path of its forward slash") - path = strings.TrimPrefix(path, "/") - } - - // Allow admins to disable consul integration - disableReg, ok := conf["disable_registration"] - var disableRegistration bool - if ok && disableReg != "" { - b, err := parseutil.ParseBool(disableReg) - if err != nil { - return nil, errwrap.Wrapf("failed parsing disable_registration parameter: {{err}}", err) - } - disableRegistration = b - } - if logger.IsDebug() { - logger.Debug("config disable_registration set", "disable_registration", disableRegistration) - } - - // Get the service name to advertise in Consul - service, ok := conf["service"] - if !ok { - service = DefaultServiceName - } - if !hostnameRegex.MatchString(service) { - return nil, errors.New("service name must be valid per RFC 1123 and can contain only alphanumeric characters or dashes") - } - if logger.IsDebug() { - logger.Debug("config service set", "service", service) - } - - // Get the additional tags to attach to the registered service name - tags := conf["service_tags"] - if logger.IsDebug() { - logger.Debug("config service_tags set", "service_tags", tags) - } - - // Get the service-specific address to override the use of the HA redirect address - var serviceAddr *string - serviceAddrStr, ok := conf["service_address"] - if ok { - serviceAddr = &serviceAddrStr - } - if logger.IsDebug() { - logger.Debug("config service_address set", "service_address", serviceAddr) - } - - checkTimeout := defaultCheckTimeout - checkTimeoutStr, ok := conf["check_timeout"] - if ok { - d, err := parseutil.ParseDurationSecond(checkTimeoutStr) - if err != nil { - return nil, err - } - - min, _ := lib.DurationMinusBufferDomain(d, checkMinBuffer, checkJitterFactor) - if min < checkMinBuffer { - return nil, fmt.Errorf("consul check_timeout must be greater than %v", min) - } - - checkTimeout = d - if logger.IsDebug() { - logger.Debug("config check_timeout set", "check_timeout", d) - } - } - - sessionTTL := api.DefaultLockSessionTTL - sessionTTLStr, ok := conf["session_ttl"] - if ok { - _, err := parseutil.ParseDurationSecond(sessionTTLStr) - if err != nil { - return nil, errwrap.Wrapf("invalid session_ttl: {{err}}", err) - } - sessionTTL = sessionTTLStr - if logger.IsDebug() { - logger.Debug("config session_ttl set", "session_ttl", sessionTTL) - } - } - - lockWaitTime := api.DefaultLockWaitTime - lockWaitTimeRaw, ok := conf["lock_wait_time"] - if ok { - d, err := parseutil.ParseDurationSecond(lockWaitTimeRaw) - if err != nil { - return nil, errwrap.Wrapf("invalid lock_wait_time: {{err}}", err) - } - lockWaitTime = d - if logger.IsDebug() { - logger.Debug("config lock_wait_time set", "lock_wait_time", d) - } - } - - // Configure the client - consulConf := api.DefaultConfig() - // Set MaxIdleConnsPerHost to the number of processes used in expiration.Restore - consulConf.Transport.MaxIdleConnsPerHost = consts.ExpirationRestoreWorkerCount - - if addr, ok := conf["address"]; ok { - consulConf.Address = addr - if logger.IsDebug() { - logger.Debug("config address set", "address", addr) - } - } - if scheme, ok := conf["scheme"]; ok { - consulConf.Scheme = scheme - if logger.IsDebug() { - logger.Debug("config scheme set", "scheme", scheme) - } - } - if token, ok := conf["token"]; ok { - consulConf.Token = token - logger.Debug("config token set") - } - - if consulConf.Scheme == "https" { - tlsClientConfig, err := setupTLSConfig(conf) - if err != nil { - return nil, err - } - - consulConf.Transport.TLSClientConfig = tlsClientConfig - if err := http2.ConfigureTransport(consulConf.Transport); err != nil { - return nil, err - } - logger.Debug("configured TLS") - } - - consulConf.HttpClient = &http.Client{Transport: consulConf.Transport} - client, err := api.NewClient(consulConf) - if err != nil { - return nil, errwrap.Wrapf("client setup failed: {{err}}", err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - consistencyMode, ok := conf["consistency_mode"] - if ok { - switch consistencyMode { - case consistencyModeDefault, consistencyModeStrong: - default: - return nil, fmt.Errorf("invalid consistency_mode value: %q", consistencyMode) - } - } else { - consistencyMode = consistencyModeDefault - } - - // Setup the backend - c := &ConsulBackend{ - path: path, - logger: logger, - client: client, - kv: client.KV(), - permitPool: physical.NewPermitPool(maxParInt), - serviceName: service, - serviceTags: strutil.ParseDedupLowercaseAndSortStrings(tags, ","), - serviceAddress: serviceAddr, - checkTimeout: checkTimeout, - disableRegistration: disableRegistration, - consistencyMode: consistencyMode, - notifyActiveCh: make(chan notifyEvent), - notifySealedCh: make(chan notifyEvent), - sessionTTL: sessionTTL, - lockWaitTime: lockWaitTime, - } - return c, nil -} - -func setupTLSConfig(conf map[string]string) (*tls.Config, error) { - serverName, _, err := net.SplitHostPort(conf["address"]) - switch { - case err == nil: - case strings.Contains(err.Error(), "missing port"): - serverName = conf["address"] - default: - return nil, err - } - - insecureSkipVerify := false - tlsSkipVerify, ok := conf["tls_skip_verify"] - - if ok && tlsSkipVerify != "" { - b, err := parseutil.ParseBool(tlsSkipVerify) - if err != nil { - return nil, errwrap.Wrapf("failed parsing tls_skip_verify parameter: {{err}}", err) - } - insecureSkipVerify = b - } - - tlsMinVersionStr, ok := conf["tls_min_version"] - if !ok { - // Set the default value - tlsMinVersionStr = "tls12" - } - - tlsMinVersion, ok := tlsutil.TLSLookup[tlsMinVersionStr] - if !ok { - return nil, fmt.Errorf("invalid 'tls_min_version'") - } - - tlsClientConfig := &tls.Config{ - MinVersion: tlsMinVersion, - InsecureSkipVerify: insecureSkipVerify, - ServerName: serverName, - } - - _, okCert := conf["tls_cert_file"] - _, okKey := conf["tls_key_file"] - - if okCert && okKey { - tlsCert, err := tls.LoadX509KeyPair(conf["tls_cert_file"], conf["tls_key_file"]) - if err != nil { - return nil, errwrap.Wrapf("client tls setup failed: {{err}}", err) - } - - tlsClientConfig.Certificates = []tls.Certificate{tlsCert} - } - - if tlsCaFile, ok := conf["tls_ca_file"]; ok { - caPool := x509.NewCertPool() - - data, err := ioutil.ReadFile(tlsCaFile) - if err != nil { - return nil, errwrap.Wrapf("failed to read CA file: {{err}}", err) - } - - if !caPool.AppendCertsFromPEM(data) { - return nil, fmt.Errorf("failed to parse CA certificate") - } - - tlsClientConfig.RootCAs = caPool - } - - return tlsClientConfig, nil -} - -// Used to run multiple entries via a transaction -func (c *ConsulBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - if len(txns) == 0 { - return nil - } - - ops := make([]*api.KVTxnOp, 0, len(txns)) - - for _, op := range txns { - cop := &api.KVTxnOp{ - Key: c.path + op.Entry.Key, - } - switch op.Operation { - case physical.DeleteOperation: - cop.Verb = api.KVDelete - case physical.PutOperation: - cop.Verb = api.KVSet - cop.Value = op.Entry.Value - default: - return fmt.Errorf("%q is not a supported transaction operation", op.Operation) - } - - ops = append(ops, cop) - } - - c.permitPool.Acquire() - defer c.permitPool.Release() - - queryOpts := &api.QueryOptions{} - queryOpts = queryOpts.WithContext(ctx) - - ok, resp, _, err := c.kv.Txn(ops, queryOpts) - if err != nil { - return err - } - if ok && len(resp.Errors) == 0 { - return nil - } - - var retErr *multierror.Error - for _, res := range resp.Errors { - retErr = multierror.Append(retErr, errors.New(res.What)) - } - - return retErr -} - -// Put is used to insert or update an entry -func (c *ConsulBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"consul", "put"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - pair := &api.KVPair{ - Key: c.path + entry.Key, - Value: entry.Value, - } - - writeOpts := &api.WriteOptions{} - writeOpts = writeOpts.WithContext(ctx) - - _, err := c.kv.Put(pair, writeOpts) - return err -} - -// Get is used to fetch an entry -func (c *ConsulBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"consul", "get"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - queryOpts := &api.QueryOptions{} - queryOpts = queryOpts.WithContext(ctx) - - if c.consistencyMode == consistencyModeStrong { - queryOpts.RequireConsistent = true - } - - pair, _, err := c.kv.Get(c.path+key, queryOpts) - if err != nil { - return nil, err - } - if pair == nil { - return nil, nil - } - ent := &physical.Entry{ - Key: key, - Value: pair.Value, - } - return ent, nil -} - -// Delete is used to permanently delete an entry -func (c *ConsulBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"consul", "delete"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - writeOpts := &api.WriteOptions{} - writeOpts = writeOpts.WithContext(ctx) - - _, err := c.kv.Delete(c.path+key, writeOpts) - return err -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (c *ConsulBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"consul", "list"}, time.Now()) - scan := c.path + prefix - - // The TrimPrefix call below will not work correctly if we have "//" at the - // end. This can happen in cases where you are e.g. listing the root of a - // prefix in a logical backend via "/" instead of "" - if strings.HasSuffix(scan, "//") { - scan = scan[:len(scan)-1] - } - - c.permitPool.Acquire() - defer c.permitPool.Release() - - queryOpts := &api.QueryOptions{} - queryOpts = queryOpts.WithContext(ctx) - - out, _, err := c.kv.Keys(scan, "/", queryOpts) - for idx, val := range out { - out[idx] = strings.TrimPrefix(val, scan) - } - - return out, err -} - -// Lock is used for mutual exclusion based on the given key. -func (c *ConsulBackend) LockWith(key, value string) (physical.Lock, error) { - // Create the lock - opts := &api.LockOptions{ - Key: c.path + key, - Value: []byte(value), - SessionName: "Vault Lock", - MonitorRetries: 5, - SessionTTL: c.sessionTTL, - LockWaitTime: c.lockWaitTime, - } - lock, err := c.client.LockOpts(opts) - if err != nil { - return nil, errwrap.Wrapf("failed to create lock: {{err}}", err) - } - cl := &ConsulLock{ - client: c.client, - key: c.path + key, - lock: lock, - consistencyMode: c.consistencyMode, - } - return cl, nil -} - -// HAEnabled indicates whether the HA functionality should be exposed. -// Currently always returns true. -func (c *ConsulBackend) HAEnabled() bool { - return true -} - -// DetectHostAddr is used to detect the host address by asking the Consul agent -func (c *ConsulBackend) DetectHostAddr() (string, error) { - agent := c.client.Agent() - self, err := agent.Self() - if err != nil { - return "", err - } - addr, ok := self["Member"]["Addr"].(string) - if !ok { - return "", fmt.Errorf("unable to convert an address to string") - } - return addr, nil -} - -// ConsulLock is used to provide the Lock interface backed by Consul -type ConsulLock struct { - client *api.Client - key string - lock *api.Lock - consistencyMode string -} - -func (c *ConsulLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - return c.lock.Lock(stopCh) -} - -func (c *ConsulLock) Unlock() error { - return c.lock.Unlock() -} - -func (c *ConsulLock) Value() (bool, string, error) { - kv := c.client.KV() - - var queryOptions *api.QueryOptions - if c.consistencyMode == consistencyModeStrong { - queryOptions = &api.QueryOptions{ - RequireConsistent: true, - } - } - - pair, _, err := kv.Get(c.key, queryOptions) - if err != nil { - return false, "", err - } - if pair == nil { - return false, "", nil - } - held := pair.Session != "" - value := string(pair.Value) - return held, value, nil -} - -func (c *ConsulBackend) NotifyActiveStateChange() error { - select { - case c.notifyActiveCh <- notifyEvent{}: - default: - // NOTE: If this occurs Vault's active status could be out of - // sync with Consul until reconcileTimer expires. - c.logger.Warn("concurrent state change notify dropped") - } - - return nil -} - -func (c *ConsulBackend) NotifySealedStateChange() error { - select { - case c.notifySealedCh <- notifyEvent{}: - default: - // NOTE: If this occurs Vault's sealed status could be out of - // sync with Consul until checkTimer expires. - c.logger.Warn("concurrent sealed state change notify dropped") - } - - return nil -} - -func (c *ConsulBackend) checkDuration() time.Duration { - return lib.DurationMinusBuffer(c.checkTimeout, checkMinBuffer, checkJitterFactor) -} - -func (c *ConsulBackend) RunServiceDiscovery(waitGroup *sync.WaitGroup, shutdownCh physical.ShutdownChannel, redirectAddr string, activeFunc physical.ActiveFunction, sealedFunc physical.SealedFunction) (err error) { - if err := c.setRedirectAddr(redirectAddr); err != nil { - return err - } - - // 'server' command will wait for the below goroutine to complete - waitGroup.Add(1) - - go c.runEventDemuxer(waitGroup, shutdownCh, redirectAddr, activeFunc, sealedFunc) - - return nil -} - -func (c *ConsulBackend) runEventDemuxer(waitGroup *sync.WaitGroup, shutdownCh physical.ShutdownChannel, redirectAddr string, activeFunc physical.ActiveFunction, sealedFunc physical.SealedFunction) { - // This defer statement should be executed last. So push it first. - defer waitGroup.Done() - - // Fire the reconcileTimer immediately upon starting the event demuxer - reconcileTimer := time.NewTimer(0) - defer reconcileTimer.Stop() - - // Schedule the first check. Consul TTL checks are passing by - // default, checkTimer does not need to be run immediately. - checkTimer := time.NewTimer(c.checkDuration()) - defer checkTimer.Stop() - - // Use a reactor pattern to handle and dispatch events to singleton - // goroutine handlers for execution. It is not acceptable to drop - // inbound events from Notify*(). - // - // goroutines are dispatched if the demuxer can acquire a lock (via - // an atomic CAS incr) on the handler. Handlers are responsible for - // deregistering themselves (atomic CAS decr). Handlers and the - // demuxer share a lock to synchronize information at the beginning - // and end of a handler's life (or after a handler wakes up from - // sleeping during a back-off/retry). - var shutdown bool - var registeredServiceID string - checkLock := new(int32) - serviceRegLock := new(int32) - - for !shutdown { - select { - case <-c.notifyActiveCh: - // Run reconcile immediately upon active state change notification - reconcileTimer.Reset(0) - case <-c.notifySealedCh: - // Run check timer immediately upon a seal state change notification - checkTimer.Reset(0) - case <-reconcileTimer.C: - // Unconditionally rearm the reconcileTimer - reconcileTimer.Reset(reconcileTimeout - lib.RandomStagger(reconcileTimeout/checkJitterFactor)) - - // Abort if service discovery is disabled or a - // reconcile handler is already active - if !c.disableRegistration && atomic.CompareAndSwapInt32(serviceRegLock, 0, 1) { - // Enter handler with serviceRegLock held - go func() { - defer atomic.CompareAndSwapInt32(serviceRegLock, 1, 0) - for !shutdown { - serviceID, err := c.reconcileConsul(registeredServiceID, activeFunc, sealedFunc) - if err != nil { - if c.logger.IsWarn() { - c.logger.Warn("reconcile unable to talk with Consul backend", "error", err) - } - time.Sleep(consulRetryInterval) - continue - } - - c.serviceLock.Lock() - defer c.serviceLock.Unlock() - - registeredServiceID = serviceID - return - } - }() - } - case <-checkTimer.C: - checkTimer.Reset(c.checkDuration()) - // Abort if service discovery is disabled or a - // reconcile handler is active - if !c.disableRegistration && atomic.CompareAndSwapInt32(checkLock, 0, 1) { - // Enter handler with checkLock held - go func() { - defer atomic.CompareAndSwapInt32(checkLock, 1, 0) - for !shutdown { - sealed := sealedFunc() - if err := c.runCheck(sealed); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("check unable to talk with Consul backend", "error", err) - } - time.Sleep(consulRetryInterval) - continue - } - return - } - }() - } - case <-shutdownCh: - c.logger.Info("shutting down consul backend") - shutdown = true - } - } - - c.serviceLock.RLock() - defer c.serviceLock.RUnlock() - if err := c.client.Agent().ServiceDeregister(registeredServiceID); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("service deregistration failed", "error", err) - } - } -} - -// checkID returns the ID used for a Consul Check. Assume at least a read -// lock is held. -func (c *ConsulBackend) checkID() string { - return fmt.Sprintf("%s:vault-sealed-check", c.serviceID()) -} - -// serviceID returns the Vault ServiceID for use in Consul. Assume at least -// a read lock is held. -func (c *ConsulBackend) serviceID() string { - return fmt.Sprintf("%s:%s:%d", c.serviceName, c.redirectHost, c.redirectPort) -} - -// reconcileConsul queries the state of Vault Core and Consul and fixes up -// Consul's state according to what's in Vault. reconcileConsul is called -// without any locks held and can be run concurrently, therefore no changes -// to ConsulBackend can be made in this method (i.e. wtb const receiver for -// compiler enforced safety). -func (c *ConsulBackend) reconcileConsul(registeredServiceID string, activeFunc physical.ActiveFunction, sealedFunc physical.SealedFunction) (serviceID string, err error) { - // Query vault Core for its current state - active := activeFunc() - sealed := sealedFunc() - - agent := c.client.Agent() - catalog := c.client.Catalog() - - serviceID = c.serviceID() - - // Get the current state of Vault from Consul - var currentVaultService *api.CatalogService - if services, _, err := catalog.Service(c.serviceName, "", &api.QueryOptions{AllowStale: true}); err == nil { - for _, service := range services { - if serviceID == service.ServiceID { - currentVaultService = service - break - } - } - } - - tags := c.fetchServiceTags(active) - - var reregister bool - - switch { - case currentVaultService == nil, registeredServiceID == "": - reregister = true - default: - switch { - case !strutil.EquivalentSlices(currentVaultService.ServiceTags, tags): - reregister = true - } - } - - if !reregister { - // When re-registration is not required, return a valid serviceID - // to avoid registration in the next cycle. - return serviceID, nil - } - - // If service address was set explicitly in configuration, use that - // as the service-specific address instead of the HA redirect address. - var serviceAddress string - if c.serviceAddress == nil { - serviceAddress = c.redirectHost - } else { - serviceAddress = *c.serviceAddress - } - - service := &api.AgentServiceRegistration{ - ID: serviceID, - Name: c.serviceName, - Tags: tags, - Port: int(c.redirectPort), - Address: serviceAddress, - EnableTagOverride: false, - } - - checkStatus := api.HealthCritical - if !sealed { - checkStatus = api.HealthPassing - } - - sealedCheck := &api.AgentCheckRegistration{ - ID: c.checkID(), - Name: "Vault Sealed Status", - Notes: "Vault service is healthy when Vault is in an unsealed status and can become an active Vault server", - ServiceID: serviceID, - AgentServiceCheck: api.AgentServiceCheck{ - TTL: c.checkTimeout.String(), - Status: checkStatus, - }, - } - - if err := agent.ServiceRegister(service); err != nil { - return "", errwrap.Wrapf(`service registration failed: {{err}}`, err) - } - - if err := agent.CheckRegister(sealedCheck); err != nil { - return serviceID, errwrap.Wrapf(`service check registration failed: {{err}}`, err) - } - - return serviceID, nil -} - -// runCheck immediately pushes a TTL check. -func (c *ConsulBackend) runCheck(sealed bool) error { - // Run a TTL check - agent := c.client.Agent() - if !sealed { - return agent.PassTTL(c.checkID(), "Vault Unsealed") - } else { - return agent.FailTTL(c.checkID(), "Vault Sealed") - } -} - -// fetchServiceTags returns all of the relevant tags for Consul. -func (c *ConsulBackend) fetchServiceTags(active bool) []string { - activeTag := "standby" - if active { - activeTag = "active" - } - return append(c.serviceTags, activeTag) -} - -func (c *ConsulBackend) setRedirectAddr(addr string) (err error) { - if addr == "" { - return fmt.Errorf("redirect address must not be empty") - } - - url, err := url.Parse(addr) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to parse redirect URL %q: {{err}}", addr), err) - } - - var portStr string - c.redirectHost, portStr, err = net.SplitHostPort(url.Host) - if err != nil { - if url.Scheme == "http" { - portStr = "80" - } else if url.Scheme == "https" { - portStr = "443" - } else if url.Scheme == "unix" { - portStr = "-1" - c.redirectHost = url.Path - } else { - return errwrap.Wrapf(fmt.Sprintf(`failed to find a host:port in redirect address "%v": {{err}}`, url.Host), err) - } - } - c.redirectPort, err = strconv.ParseInt(portStr, 10, 0) - if err != nil || c.redirectPort < -1 || c.redirectPort > 65535 { - return errwrap.Wrapf(fmt.Sprintf(`failed to parse valid port "%v": {{err}}`, portStr), err) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/couchdb/couchdb.go b/vendor/github.com/hashicorp/vault/physical/couchdb/couchdb.go deleted file mode 100644 index a239d8894..000000000 --- a/vendor/github.com/hashicorp/vault/physical/couchdb/couchdb.go +++ /dev/null @@ -1,310 +0,0 @@ -package couchdb - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" -) - -// CouchDBBackend allows the management of couchdb users -type CouchDBBackend struct { - logger log.Logger - client *couchDBClient - permitPool *physical.PermitPool -} - -// Verify CouchDBBackend satisfies the correct interfaces -var _ physical.Backend = (*CouchDBBackend)(nil) -var _ physical.PseudoTransactional = (*CouchDBBackend)(nil) -var _ physical.PseudoTransactional = (*TransactionalCouchDBBackend)(nil) - -type couchDBClient struct { - endpoint string - username string - password string - *http.Client -} - -type couchDBListItem struct { - ID string `json:"id"` - Key string `json:"key"` - Value struct { - Revision string - } `json:"value"` -} - -type couchDBList struct { - TotalRows int `json:"total_rows"` - Offset int `json:"offset"` - Rows []couchDBListItem `json:"rows"` -} - -func (m *couchDBClient) rev(key string) (string, error) { - req, err := http.NewRequest("HEAD", fmt.Sprintf("%s/%s", m.endpoint, key), nil) - if err != nil { - return "", err - } - req.SetBasicAuth(m.username, m.password) - - resp, err := m.Client.Do(req) - if err != nil { - return "", err - } - resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return "", nil - } - etag := resp.Header.Get("Etag") - if len(etag) < 2 { - return "", nil - } - return etag[1 : len(etag)-1], nil -} - -func (m *couchDBClient) put(e couchDBEntry) error { - bs, err := json.Marshal(e) - if err != nil { - return err - } - - req, err := http.NewRequest("PUT", fmt.Sprintf("%s/%s", m.endpoint, e.ID), bytes.NewReader(bs)) - if err != nil { - return err - } - req.SetBasicAuth(m.username, m.password) - _, err = m.Client.Do(req) - - return err -} - -func (m *couchDBClient) get(key string) (*physical.Entry, error) { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", m.endpoint, url.PathEscape(key)), nil) - if err != nil { - return nil, err - } - req.SetBasicAuth(m.username, m.password) - resp, err := m.Client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode == http.StatusNotFound { - return nil, nil - } else if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("GET returned %q", resp.Status) - } - bs, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - entry := couchDBEntry{} - if err := json.Unmarshal(bs, &entry); err != nil { - return nil, err - } - return entry.Entry, nil -} - -func (m *couchDBClient) list(prefix string) ([]couchDBListItem, error) { - req, _ := http.NewRequest("GET", fmt.Sprintf("%s/_all_docs", m.endpoint), nil) - req.SetBasicAuth(m.username, m.password) - values := req.URL.Query() - values.Set("skip", "0") - values.Set("include_docs", "false") - if prefix != "" { - values.Set("startkey", fmt.Sprintf("%q", prefix)) - values.Set("endkey", fmt.Sprintf("%q", prefix+"{}")) - } - req.URL.RawQuery = values.Encode() - - resp, err := m.Client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - results := couchDBList{} - if err := json.Unmarshal(data, &results); err != nil { - return nil, err - } - - return results.Rows, nil -} - -func buildCouchDBBackend(conf map[string]string, logger log.Logger) (*CouchDBBackend, error) { - endpoint := os.Getenv("COUCHDB_ENDPOINT") - if endpoint == "" { - endpoint = conf["endpoint"] - } - if endpoint == "" { - return nil, fmt.Errorf("missing endpoint") - } - - username := os.Getenv("COUCHDB_USERNAME") - if username == "" { - username = conf["username"] - } - - password := os.Getenv("COUCHDB_PASSWORD") - if password == "" { - password = conf["password"] - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - var err error - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - return &CouchDBBackend{ - client: &couchDBClient{ - endpoint: endpoint, - username: username, - password: password, - Client: cleanhttp.DefaultPooledClient(), - }, - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - }, nil -} - -func NewCouchDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - return buildCouchDBBackend(conf, logger) -} - -type couchDBEntry struct { - Entry *physical.Entry `json:"entry"` - Rev string `json:"_rev,omitempty"` - ID string `json:"_id"` - Deleted *bool `json:"_deleted,omitempty"` -} - -// Put is used to insert or update an entry -func (m *CouchDBBackend) Put(ctx context.Context, entry *physical.Entry) error { - m.permitPool.Acquire() - defer m.permitPool.Release() - - return m.PutInternal(ctx, entry) -} - -// Get is used to fetch an entry -func (m *CouchDBBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - m.permitPool.Acquire() - defer m.permitPool.Release() - - return m.GetInternal(ctx, key) -} - -// Delete is used to permanently delete an entry -func (m *CouchDBBackend) Delete(ctx context.Context, key string) error { - m.permitPool.Acquire() - defer m.permitPool.Release() - - return m.DeleteInternal(ctx, key) -} - -// List is used to list all the keys under a given prefix -func (m *CouchDBBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"couchdb", "list"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - items, err := m.client.list(prefix) - if err != nil { - return nil, err - } - - var out []string - seen := make(map[string]interface{}) - for _, result := range items { - trimmed := strings.TrimPrefix(result.ID, prefix) - sep := strings.Index(trimmed, "/") - if sep == -1 { - out = append(out, trimmed) - } else { - trimmed = trimmed[:sep+1] - if _, ok := seen[trimmed]; !ok { - out = append(out, trimmed) - seen[trimmed] = struct{}{} - } - } - } - return out, nil -} - -// TransactionalCouchDBBackend creates a couchdb backend that forces all operations to happen -// in serial -type TransactionalCouchDBBackend struct { - CouchDBBackend -} - -func NewTransactionalCouchDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - backend, err := buildCouchDBBackend(conf, logger) - if err != nil { - return nil, err - } - backend.permitPool = physical.NewPermitPool(1) - - return &TransactionalCouchDBBackend{ - CouchDBBackend: *backend, - }, nil -} - -// GetInternal is used to fetch an entry -func (m *CouchDBBackend) GetInternal(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"couchdb", "get"}, time.Now()) - - return m.client.get(key) -} - -// PutInternal is used to insert or update an entry -func (m *CouchDBBackend) PutInternal(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"couchdb", "put"}, time.Now()) - - revision, _ := m.client.rev(url.PathEscape(entry.Key)) - - return m.client.put(couchDBEntry{ - Entry: entry, - Rev: revision, - ID: url.PathEscape(entry.Key), - }) -} - -// DeleteInternal is used to permanently delete an entry -func (m *CouchDBBackend) DeleteInternal(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"couchdb", "delete"}, time.Now()) - - revision, _ := m.client.rev(url.PathEscape(key)) - deleted := true - return m.client.put(couchDBEntry{ - ID: url.PathEscape(key), - Rev: revision, - Deleted: &deleted, - }) -} diff --git a/vendor/github.com/hashicorp/vault/physical/dynamodb/dynamodb.go b/vendor/github.com/hashicorp/vault/physical/dynamodb/dynamodb.go deleted file mode 100644 index 3a08cca17..000000000 --- a/vendor/github.com/hashicorp/vault/physical/dynamodb/dynamodb.go +++ /dev/null @@ -1,837 +0,0 @@ -package dynamodb - -import ( - "context" - "fmt" - "math" - "net/http" - "os" - pkgPath "path" - "sort" - "strconv" - "strings" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/awsutil" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/physical" -) - -const ( - // DefaultDynamoDBRegion is used when no region is configured - // explicitly. - DefaultDynamoDBRegion = "us-east-1" - // DefaultDynamoDBTableName is used when no table name - // is configured explicitly. - DefaultDynamoDBTableName = "vault-dynamodb-backend" - - // DefaultDynamoDBReadCapacity is the default read capacity - // that is used when none is configured explicitly. - DefaultDynamoDBReadCapacity = 5 - // DefaultDynamoDBWriteCapacity is the default write capacity - // that is used when none is configured explicitly. - DefaultDynamoDBWriteCapacity = 5 - - // DynamoDBEmptyPath is the string that is used instead of - // empty strings when stored in DynamoDB. - DynamoDBEmptyPath = " " - // DynamoDBLockPrefix is the prefix used to mark DynamoDB records - // as locks. This prefix causes them not to be returned by - // List operations. - DynamoDBLockPrefix = "_" - - // The lock TTL matches the default that Consul API uses, 15 seconds. - DynamoDBLockTTL = 15 * time.Second - - // The amount of time to wait between the lock renewals - DynamoDBLockRenewInterval = 5 * time.Second - - // DynamoDBLockRetryInterval is the amount of time to wait - // if a lock fails before trying again. - DynamoDBLockRetryInterval = time.Second - // DynamoDBWatchRetryMax is the number of times to re-try a - // failed watch before signaling that leadership is lost. - DynamoDBWatchRetryMax = 5 - // DynamoDBWatchRetryInterval is the amount of time to wait - // if a watch fails before trying again. - DynamoDBWatchRetryInterval = 5 * time.Second -) - -// Verify DynamoDBBackend satisfies the correct interfaces -var _ physical.Backend = (*DynamoDBBackend)(nil) -var _ physical.HABackend = (*DynamoDBBackend)(nil) -var _ physical.Lock = (*DynamoDBLock)(nil) - -// DynamoDBBackend is a physical backend that stores data in -// a DynamoDB table. It can be run in high-availability mode -// as DynamoDB has locking capabilities. -type DynamoDBBackend struct { - table string - client *dynamodb.DynamoDB - logger log.Logger - haEnabled bool - permitPool *physical.PermitPool -} - -// DynamoDBRecord is the representation of a vault entry in -// DynamoDB. The vault key is split up into two components -// (Path and Key) in order to allow more efficient listings. -type DynamoDBRecord struct { - Path string - Key string - Value []byte -} - -// DynamoDBLock implements a lock using an DynamoDB client. -type DynamoDBLock struct { - backend *DynamoDBBackend - value, key string - identity string - held bool - lock sync.Mutex - // Allow modifying the Lock durations for ease of unit testing. - renewInterval time.Duration - ttl time.Duration - watchRetryInterval time.Duration -} - -type DynamoDBLockRecord struct { - Path string - Key string - Value []byte - Identity []byte - Expires int64 -} - -// NewDynamoDBBackend constructs a DynamoDB backend. If the -// configured DynamoDB table does not exist, it creates it. -func NewDynamoDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - table := os.Getenv("AWS_DYNAMODB_TABLE") - if table == "" { - table = conf["table"] - if table == "" { - table = DefaultDynamoDBTableName - } - } - readCapacityString := os.Getenv("AWS_DYNAMODB_READ_CAPACITY") - if readCapacityString == "" { - readCapacityString = conf["read_capacity"] - if readCapacityString == "" { - readCapacityString = "0" - } - } - readCapacity, err := strconv.Atoi(readCapacityString) - if err != nil { - return nil, fmt.Errorf("invalid read capacity: %q", readCapacityString) - } - if readCapacity == 0 { - readCapacity = DefaultDynamoDBReadCapacity - } - - writeCapacityString := os.Getenv("AWS_DYNAMODB_WRITE_CAPACITY") - if writeCapacityString == "" { - writeCapacityString = conf["write_capacity"] - if writeCapacityString == "" { - writeCapacityString = "0" - } - } - writeCapacity, err := strconv.Atoi(writeCapacityString) - if err != nil { - return nil, fmt.Errorf("invalid write capacity: %q", writeCapacityString) - } - if writeCapacity == 0 { - writeCapacity = DefaultDynamoDBWriteCapacity - } - - accessKey := os.Getenv("AWS_ACCESS_KEY_ID") - if accessKey == "" { - accessKey = conf["access_key"] - } - secretKey := os.Getenv("AWS_SECRET_ACCESS_KEY") - if secretKey == "" { - secretKey = conf["secret_key"] - } - sessionToken := os.Getenv("AWS_SESSION_TOKEN") - if sessionToken == "" { - sessionToken = conf["session_token"] - } - - endpoint := os.Getenv("AWS_DYNAMODB_ENDPOINT") - if endpoint == "" { - endpoint = conf["endpoint"] - } - region := os.Getenv("AWS_REGION") - if region == "" { - region = os.Getenv("AWS_DEFAULT_REGION") - if region == "" { - region = conf["region"] - if region == "" { - region = DefaultDynamoDBRegion - } - } - } - - dynamodbMaxRetryString := os.Getenv("AWS_DYNAMODB_MAX_RETRIES") - if dynamodbMaxRetryString == "" { - dynamodbMaxRetryString = conf["dynamodb_max_retries"] - } - var dynamodbMaxRetry int = aws.UseServiceDefaultRetries - if dynamodbMaxRetryString != "" { - var err error - dynamodbMaxRetry, err = strconv.Atoi(dynamodbMaxRetryString) - if err != nil { - return nil, fmt.Errorf("invalid max retry: %q", dynamodbMaxRetryString) - } - } - - credsConfig := &awsutil.CredentialsConfig{ - AccessKey: accessKey, - SecretKey: secretKey, - SessionToken: sessionToken, - } - creds, err := credsConfig.GenerateCredentialChain() - if err != nil { - return nil, err - } - - pooledTransport := cleanhttp.DefaultPooledTransport() - pooledTransport.MaxIdleConnsPerHost = consts.ExpirationRestoreWorkerCount - - awsConf := aws.NewConfig(). - WithCredentials(creds). - WithRegion(region). - WithEndpoint(endpoint). - WithHTTPClient(&http.Client{ - Transport: pooledTransport, - }). - WithMaxRetries(dynamodbMaxRetry) - - awsSession, err := session.NewSession(awsConf) - if err != nil { - return nil, errwrap.Wrapf("Could not establish AWS session: {{err}}", err) - } - - client := dynamodb.New(awsSession) - - if err := ensureTableExists(client, table, readCapacity, writeCapacity); err != nil { - return nil, err - } - - haEnabled := os.Getenv("DYNAMODB_HA_ENABLED") - if haEnabled == "" { - haEnabled = conf["ha_enabled"] - } - haEnabledBool, _ := strconv.ParseBool(haEnabled) - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - return &DynamoDBBackend{ - table: table, - client: client, - permitPool: physical.NewPermitPool(maxParInt), - haEnabled: haEnabledBool, - logger: logger, - }, nil -} - -// Put is used to insert or update an entry -func (d *DynamoDBBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"dynamodb", "put"}, time.Now()) - - record := DynamoDBRecord{ - Path: recordPathForVaultKey(entry.Key), - Key: recordKeyForVaultKey(entry.Key), - Value: entry.Value, - } - item, err := dynamodbattribute.MarshalMap(record) - if err != nil { - return errwrap.Wrapf("could not convert prefix record to DynamoDB item: {{err}}", err) - } - requests := []*dynamodb.WriteRequest{{ - PutRequest: &dynamodb.PutRequest{ - Item: item, - }, - }} - - for _, prefix := range physical.Prefixes(entry.Key) { - record = DynamoDBRecord{ - Path: recordPathForVaultKey(prefix), - Key: fmt.Sprintf("%s/", recordKeyForVaultKey(prefix)), - } - item, err := dynamodbattribute.MarshalMap(record) - if err != nil { - return errwrap.Wrapf("could not convert prefix record to DynamoDB item: {{err}}", err) - } - requests = append(requests, &dynamodb.WriteRequest{ - PutRequest: &dynamodb.PutRequest{ - Item: item, - }, - }) - } - - return d.batchWriteRequests(requests) -} - -// Get is used to fetch an entry -func (d *DynamoDBBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"dynamodb", "get"}, time.Now()) - - d.permitPool.Acquire() - defer d.permitPool.Release() - - resp, err := d.client.GetItem(&dynamodb.GetItemInput{ - TableName: aws.String(d.table), - ConsistentRead: aws.Bool(true), - Key: map[string]*dynamodb.AttributeValue{ - "Path": {S: aws.String(recordPathForVaultKey(key))}, - "Key": {S: aws.String(recordKeyForVaultKey(key))}, - }, - }) - if err != nil { - return nil, err - } - if resp.Item == nil { - return nil, nil - } - - record := &DynamoDBRecord{} - if err := dynamodbattribute.UnmarshalMap(resp.Item, record); err != nil { - return nil, err - } - - return &physical.Entry{ - Key: vaultKey(record), - Value: record.Value, - }, nil -} - -// Delete is used to permanently delete an entry -func (d *DynamoDBBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"dynamodb", "delete"}, time.Now()) - - requests := []*dynamodb.WriteRequest{{ - DeleteRequest: &dynamodb.DeleteRequest{ - Key: map[string]*dynamodb.AttributeValue{ - "Path": {S: aws.String(recordPathForVaultKey(key))}, - "Key": {S: aws.String(recordKeyForVaultKey(key))}, - }, - }, - }} - - // Clean up empty "folders" by looping through all levels of the path to the item being deleted looking for - // children. Loop from deepest path to shallowest, and only consider items children if they are not going to be - // deleted by our batch delete request. If a path has no valid children, then it should be considered an empty - // "folder" and be deleted along with the original item in our batch job. Because we loop from deepest path to - // shallowest, once we find a path level that contains valid children we can stop the cleanup operation. - prefixes := physical.Prefixes(key) - sort.Sort(sort.Reverse(sort.StringSlice(prefixes))) - for index, prefix := range prefixes { - // Because delete batches its requests, we need to pass keys we know are going to be deleted into - // hasChildren so it can exclude those when it determines if there WILL be any children left after - // the delete operations have completed. - var excluded []string - if index == 0 { - // This is the value we know for sure is being deleted - excluded = append(excluded, recordKeyForVaultKey(key)) - } else { - // The previous path doesn't count as a child, since if we're still looping, we've found no children - excluded = append(excluded, recordKeyForVaultKey(prefixes[index-1])) - } - - hasChildren, err := d.hasChildren(prefix, excluded) - if err != nil { - return err - } - - if !hasChildren { - // If there are no children other than ones we know are being deleted then cleanup empty "folder" pointers - requests = append(requests, &dynamodb.WriteRequest{ - DeleteRequest: &dynamodb.DeleteRequest{ - Key: map[string]*dynamodb.AttributeValue{ - "Path": {S: aws.String(recordPathForVaultKey(prefix))}, - "Key": {S: aws.String(fmt.Sprintf("%s/", recordKeyForVaultKey(prefix)))}, - }, - }, - }) - } else { - // This loop starts at the deepest path and works backwards looking for children - // once a deeper level of the path has been found to have children there is no - // more cleanup that needs to happen, otherwise we might remove folder pointers - // to that deeper path making it "undiscoverable" with the list operation - break - } - } - - return d.batchWriteRequests(requests) -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (d *DynamoDBBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"dynamodb", "list"}, time.Now()) - - prefix = strings.TrimSuffix(prefix, "/") - - keys := []string{} - prefix = escapeEmptyPath(prefix) - queryInput := &dynamodb.QueryInput{ - TableName: aws.String(d.table), - ConsistentRead: aws.Bool(true), - KeyConditions: map[string]*dynamodb.Condition{ - "Path": { - ComparisonOperator: aws.String("EQ"), - AttributeValueList: []*dynamodb.AttributeValue{{ - S: aws.String(prefix), - }}, - }, - }, - } - - d.permitPool.Acquire() - defer d.permitPool.Release() - - err := d.client.QueryPages(queryInput, func(out *dynamodb.QueryOutput, lastPage bool) bool { - var record DynamoDBRecord - for _, item := range out.Items { - dynamodbattribute.UnmarshalMap(item, &record) - if !strings.HasPrefix(record.Key, DynamoDBLockPrefix) { - keys = append(keys, record.Key) - } - } - return !lastPage - }) - if err != nil { - return nil, err - } - - return keys, nil -} - -// hasChildren returns true if there exist items below a certain path prefix. -// To do so, the method fetches such items from DynamoDB. This method is primarily -// used by Delete. Because DynamoDB requests are batched this method is being called -// before any deletes take place. To account for that hasChildren accepts a slice of -// strings representing values we expect to find that should NOT be counted as children -// because they are going to be deleted. -func (d *DynamoDBBackend) hasChildren(prefix string, exclude []string) (bool, error) { - prefix = strings.TrimSuffix(prefix, "/") - prefix = escapeEmptyPath(prefix) - - queryInput := &dynamodb.QueryInput{ - TableName: aws.String(d.table), - ConsistentRead: aws.Bool(true), - KeyConditions: map[string]*dynamodb.Condition{ - "Path": { - ComparisonOperator: aws.String("EQ"), - AttributeValueList: []*dynamodb.AttributeValue{{ - S: aws.String(prefix), - }}, - }, - }, - // Avoid fetching too many items from DynamoDB for performance reasons. - // We want to know if there are any children we don't expect to see. - // Answering that question requires fetching a minimum of one more item - // than the number we expect. In most cases this value will be 2 - Limit: aws.Int64(int64(len(exclude) + 1)), - } - - d.permitPool.Acquire() - defer d.permitPool.Release() - - out, err := d.client.Query(queryInput) - if err != nil { - return false, err - } - var childrenExist bool - for _, item := range out.Items { - for _, excluded := range exclude { - // Check if we've found an item we didn't expect to. Look for "folder" pointer keys (trailing slash) - // and regular value keys (no trailing slash) - if *item["Key"].S != excluded && *item["Key"].S != fmt.Sprintf("%s/", excluded) { - childrenExist = true - break - } - } - if childrenExist { - // We only need to find ONE child we didn't expect to. - break - } - } - - return childrenExist, nil -} - -// LockWith is used for mutual exclusion based on the given key. -func (d *DynamoDBBackend) LockWith(key, value string) (physical.Lock, error) { - identity, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - return &DynamoDBLock{ - backend: d, - key: pkgPath.Join(pkgPath.Dir(key), DynamoDBLockPrefix+pkgPath.Base(key)), - value: value, - identity: identity, - renewInterval: DynamoDBLockRenewInterval, - ttl: DynamoDBLockTTL, - watchRetryInterval: DynamoDBWatchRetryInterval, - }, nil -} - -func (d *DynamoDBBackend) HAEnabled() bool { - return d.haEnabled -} - -// batchWriteRequests takes a list of write requests and executes them in badges -// with a maximum size of 25 (which is the limit of BatchWriteItem requests). -func (d *DynamoDBBackend) batchWriteRequests(requests []*dynamodb.WriteRequest) error { - for len(requests) > 0 { - batchSize := int(math.Min(float64(len(requests)), 25)) - batch := requests[:batchSize] - requests = requests[batchSize:] - - d.permitPool.Acquire() - _, err := d.client.BatchWriteItem(&dynamodb.BatchWriteItemInput{ - RequestItems: map[string][]*dynamodb.WriteRequest{ - d.table: batch, - }, - }) - d.permitPool.Release() - if err != nil { - return err - } - } - return nil -} - -// Lock tries to acquire the lock by repeatedly trying to create -// a record in the DynamoDB table. It will block until either the -// stop channel is closed or the lock could be acquired successfully. -// The returned channel will be closed once the lock is deleted or -// changed in the DynamoDB table. -func (l *DynamoDBLock) Lock(stopCh <-chan struct{}) (doneCh <-chan struct{}, retErr error) { - l.lock.Lock() - defer l.lock.Unlock() - if l.held { - return nil, fmt.Errorf("lock already held") - } - - done := make(chan struct{}) - // close done channel even in case of error - defer func() { - if retErr != nil { - close(done) - } - }() - - var ( - stop = make(chan struct{}) - success = make(chan struct{}) - errors = make(chan error) - leader = make(chan struct{}) - ) - // try to acquire the lock asynchronously - go l.tryToLock(stop, success, errors) - - select { - case <-success: - l.held = true - // after acquiring it successfully, we must renew the lock periodically, - // and watch the lock in order to close the leader channel - // once it is lost. - go l.periodicallyRenewLock(leader) - go l.watch(leader) - case retErr = <-errors: - close(stop) - return nil, retErr - case <-stopCh: - close(stop) - return nil, nil - } - - return leader, retErr -} - -// Unlock releases the lock by deleting the lock record from the -// DynamoDB table. -func (l *DynamoDBLock) Unlock() error { - l.lock.Lock() - defer l.lock.Unlock() - if !l.held { - return nil - } - - l.held = false - if err := l.backend.Delete(context.Background(), l.key); err != nil { - return err - } - return nil -} - -// Value checks whether or not the lock is held by any instance of DynamoDBLock, -// including this one, and returns the current value. -func (l *DynamoDBLock) Value() (bool, string, error) { - entry, err := l.backend.Get(context.Background(), l.key) - if err != nil { - return false, "", err - } - if entry == nil { - return false, "", nil - } - - return true, string(entry.Value), nil -} - -// tryToLock tries to create a new item in DynamoDB -// every `DynamoDBLockRetryInterval`. As long as the item -// cannot be created (because it already exists), it will -// be retried. If the operation fails due to an error, it -// is sent to the errors channel. -// When the lock could be acquired successfully, the success -// channel is closed. -func (l *DynamoDBLock) tryToLock(stop, success chan struct{}, errors chan error) { - ticker := time.NewTicker(DynamoDBLockRetryInterval) - - for { - select { - case <-stop: - ticker.Stop() - case <-ticker.C: - err := l.writeItem() - if err != nil { - if err, ok := err.(awserr.Error); ok { - // Don't report a condition check failure, this means that the lock - // is already being held. - if err.Code() != dynamodb.ErrCodeConditionalCheckFailedException { - errors <- err - } - } else { - // Its not an AWS error, and is probably not transient, bail out. - errors <- err - return - } - } else { - ticker.Stop() - close(success) - return - } - } - } -} - -func (l *DynamoDBLock) periodicallyRenewLock(done chan struct{}) { - ticker := time.NewTicker(l.renewInterval) - for { - select { - case <-ticker.C: - l.writeItem() - case <-done: - ticker.Stop() - return - } - } -} - -// Attempts to put/update the dynamodb item using condition expressions to -// evaluate the TTL. -func (l *DynamoDBLock) writeItem() error { - now := time.Now() - - _, err := l.backend.client.UpdateItem(&dynamodb.UpdateItemInput{ - TableName: aws.String(l.backend.table), - Key: map[string]*dynamodb.AttributeValue{ - "Path": &dynamodb.AttributeValue{S: aws.String(recordPathForVaultKey(l.key))}, - "Key": &dynamodb.AttributeValue{S: aws.String(recordKeyForVaultKey(l.key))}, - }, - UpdateExpression: aws.String("SET #value=:value, #identity=:identity, #expires=:expires"), - // If both key and path already exist, we can only write if - // A. identity is equal to our identity (or the identity doesn't exist) - // or - // B. The ttl on the item is <= to the current time - ConditionExpression: aws.String( - "attribute_not_exists(#path) or " + - "attribute_not_exists(#key) or " + - // To work when upgrading from older versions that did not include the - // Identity attribute, we first check if the attr doesn't exist, and if - // it does, then we check if the identity is equal to our own. - "(attribute_not_exists(#identity) or #identity = :identity) or " + - "#expires <= :now", - ), - ExpressionAttributeNames: map[string]*string{ - "#path": aws.String("Path"), - "#key": aws.String("Key"), - "#identity": aws.String("Identity"), - "#expires": aws.String("Expires"), - "#value": aws.String("Value"), - }, - ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ - ":identity": &dynamodb.AttributeValue{B: []byte(l.identity)}, - ":value": &dynamodb.AttributeValue{B: []byte(l.value)}, - ":now": &dynamodb.AttributeValue{N: aws.String(strconv.FormatInt(now.UnixNano(), 10))}, - ":expires": &dynamodb.AttributeValue{N: aws.String(strconv.FormatInt(now.Add(l.ttl).UnixNano(), 10))}, - }, - }) - return err -} - -// watch checks whether the lock has changed in the -// DynamoDB table and closes the leader channel if so. -// The interval is set by `DynamoDBWatchRetryInterval`. -// If an error occurs during the check, watch will retry -// the operation for `DynamoDBWatchRetryMax` times and -// close the leader channel if it can't succeed. -func (l *DynamoDBLock) watch(lost chan struct{}) { - retries := DynamoDBWatchRetryMax - - ticker := time.NewTicker(l.watchRetryInterval) -WatchLoop: - for { - select { - case <-ticker.C: - resp, err := l.backend.client.GetItem(&dynamodb.GetItemInput{ - TableName: aws.String(l.backend.table), - ConsistentRead: aws.Bool(true), - Key: map[string]*dynamodb.AttributeValue{ - "Path": {S: aws.String(recordPathForVaultKey(l.key))}, - "Key": {S: aws.String(recordKeyForVaultKey(l.key))}, - }, - }) - if err != nil { - retries-- - if retries == 0 { - break WatchLoop - } - continue - } - - if resp == nil { - break WatchLoop - } - record := &DynamoDBLockRecord{} - err = dynamodbattribute.UnmarshalMap(resp.Item, record) - if err != nil || string(record.Identity) != l.identity { - break WatchLoop - } - } - } - - close(lost) -} - -// ensureTableExists creates a DynamoDB table with a given -// DynamoDB client. If the table already exists, it is not -// being reconfigured. -func ensureTableExists(client *dynamodb.DynamoDB, table string, readCapacity, writeCapacity int) error { - _, err := client.DescribeTable(&dynamodb.DescribeTableInput{ - TableName: aws.String(table), - }) - if awsError, ok := err.(awserr.Error); ok { - if awsError.Code() == "ResourceNotFoundException" { - _, err = client.CreateTable(&dynamodb.CreateTableInput{ - TableName: aws.String(table), - ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ - ReadCapacityUnits: aws.Int64(int64(readCapacity)), - WriteCapacityUnits: aws.Int64(int64(writeCapacity)), - }, - KeySchema: []*dynamodb.KeySchemaElement{{ - AttributeName: aws.String("Path"), - KeyType: aws.String("HASH"), - }, { - AttributeName: aws.String("Key"), - KeyType: aws.String("RANGE"), - }}, - AttributeDefinitions: []*dynamodb.AttributeDefinition{{ - AttributeName: aws.String("Path"), - AttributeType: aws.String("S"), - }, { - AttributeName: aws.String("Key"), - AttributeType: aws.String("S"), - }}, - }) - if err != nil { - return err - } - - err = client.WaitUntilTableExists(&dynamodb.DescribeTableInput{ - TableName: aws.String(table), - }) - if err != nil { - return err - } - } - } - if err != nil { - return err - } - return nil -} - -// recordPathForVaultKey transforms a vault key into -// a value suitable for the `DynamoDBRecord`'s `Path` -// property. This path equals the the vault key without -// its last component. -func recordPathForVaultKey(key string) string { - if strings.Contains(key, "/") { - return pkgPath.Dir(key) - } - return DynamoDBEmptyPath -} - -// recordKeyForVaultKey transforms a vault key into -// a value suitable for the `DynamoDBRecord`'s `Key` -// property. This path equals the the vault key's -// last component. -func recordKeyForVaultKey(key string) string { - return pkgPath.Base(key) -} - -// vaultKey returns the vault key for a given record -// from the DynamoDB table. This is the combination of -// the records Path and Key. -func vaultKey(record *DynamoDBRecord) string { - path := unescapeEmptyPath(record.Path) - if path == "" { - return record.Key - } - return pkgPath.Join(record.Path, record.Key) -} - -// escapeEmptyPath is used to escape the root key's path -// with a value that can be stored in DynamoDB. DynamoDB -// does not allow values to be empty strings. -func escapeEmptyPath(s string) string { - if s == "" { - return DynamoDBEmptyPath - } - return s -} - -// unescapeEmptyPath is the opposite of `escapeEmptyPath`. -func unescapeEmptyPath(s string) string { - if s == DynamoDBEmptyPath { - return "" - } - return s -} diff --git a/vendor/github.com/hashicorp/vault/physical/etcd/etcd.go b/vendor/github.com/hashicorp/vault/physical/etcd/etcd.go deleted file mode 100644 index 985d8def7..000000000 --- a/vendor/github.com/hashicorp/vault/physical/etcd/etcd.go +++ /dev/null @@ -1,146 +0,0 @@ -package etcd - -import ( - "context" - "errors" - "net/url" - "os" - "strings" - - "github.com/coreos/etcd/client" - "github.com/coreos/go-semver/semver" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" -) - -var ( - EtcdSyncConfigError = errors.New("client setup failed: unable to parse etcd sync field in config") - EtcdSyncClusterError = errors.New("client setup failed: unable to sync etcd cluster") - EtcdMultipleBootstrapError = errors.New("client setup failed: multiple discovery or bootstrap flags specified, use either \"address\" or \"discovery_srv\"") - EtcdAddressError = errors.New("client setup failed: address must be valid URL (ex. 'scheme://host:port')") - EtcdSemaphoreKeysEmptyError = errors.New("lock queue is empty") - EtcdLockHeldError = errors.New("lock already held") - EtcdLockNotHeldError = errors.New("lock not held") - EtcdSemaphoreKeyRemovedError = errors.New("semaphore key removed before lock acquisition") - EtcdVersionUnknown = errors.New("etcd: unknown API version") -) - -// NewEtcdBackend constructs a etcd backend using a given machine address. -func NewEtcdBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - var ( - apiVersion string - ok bool - ) - - // v2 client can talk to both etcd2 and etcd3 thought API v2 - c, err := newEtcdV2Client(conf) - if err != nil { - return nil, errors.New("failed to create etcd client: " + err.Error()) - } - - remoteAPIVersion, err := getEtcdAPIVersion(c) - if err != nil { - return nil, errors.New("failed to get etcd API version: " + err.Error()) - } - - if apiVersion, ok = conf["etcd_api"]; !ok { - apiVersion = os.Getenv("ETCD_API") - } - - if apiVersion == "" { - path, ok := conf["path"] - if !ok { - path = "/vault" - } - kAPI := client.NewKeysAPI(c) - - // keep using v2 if vault data exists in v2 and user does not explicitly - // ask for v3. - _, err := kAPI.Get(context.Background(), path, &client.GetOptions{}) - if errorIsMissingKey(err) { - apiVersion = remoteAPIVersion - } else if err == nil { - apiVersion = "2" - } else { - return nil, errors.New("failed to check etcd status: " + err.Error()) - } - } - - switch apiVersion { - case "2", "etcd2", "v2": - return newEtcd2Backend(conf, logger) - case "3", "etcd3", "v3": - if remoteAPIVersion == "2" { - return nil, errors.New("etcd3 is required: etcd2 is running") - } - return newEtcd3Backend(conf, logger) - default: - return nil, EtcdVersionUnknown - } -} - -// getEtcdAPIVersion gets the latest supported API version. -// If etcd cluster version >= 3.1, "3" will be returned. -// Otherwise, "2" will be returned. -func getEtcdAPIVersion(c client.Client) (string, error) { - v, err := c.GetVersion(context.Background()) - if err != nil { - return "", err - } - - sv, err := semver.NewVersion(v.Cluster) - if err != nil { - return "", nil - } - - if sv.LessThan(*semver.Must(semver.NewVersion("3.1.0"))) { - return "2", nil - } - - return "3", nil -} - -// Retrieves the config option in order of priority: -// 1. The named environment variable if it exist -// 2. The key in the config map -func getEtcdOption(conf map[string]string, confKey, envVar string) (string, bool) { - confVal, inConf := conf[confKey] - envVal, inEnv := os.LookupEnv(envVar) - if inEnv { - return envVal, true - } - return confVal, inConf -} - -func getEtcdEndpoints(conf map[string]string) ([]string, error) { - address, staticBootstrap := getEtcdOption(conf, "address", "ETCD_ADDR") - domain, useSrv := getEtcdOption(conf, "discovery_srv", "ETCD_DISCOVERY_SRV") - if useSrv && staticBootstrap { - return nil, EtcdMultipleBootstrapError - } - - if staticBootstrap { - endpoints := strings.Split(address, Etcd2MachineDelimiter) - // Verify that the machines are valid URLs - for _, e := range endpoints { - u, urlErr := url.Parse(e) - if urlErr != nil || u.Scheme == "" { - return nil, EtcdAddressError - } - } - return endpoints, nil - } - - if useSrv { - discoverer := client.NewSRVDiscover() - endpoints, err := discoverer.Discover(domain) - if err != nil { - return nil, errwrap.Wrapf("failed to discover etcd endpoints through SRV discovery: {{err}}", err) - } - return endpoints, nil - } - - // Set a default endpoints list if no option was set - return []string{"http://127.0.0.1:2379"}, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/etcd/etcd2.go b/vendor/github.com/hashicorp/vault/physical/etcd/etcd2.go deleted file mode 100644 index b8e84a417..000000000 --- a/vendor/github.com/hashicorp/vault/physical/etcd/etcd2.go +++ /dev/null @@ -1,603 +0,0 @@ -package etcd - -import ( - "context" - "encoding/base64" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/coreos/etcd/client" - "github.com/coreos/etcd/pkg/transport" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/physical" -) - -const ( - // Ideally, this prefix would match the "_" used in the file backend, but - // that prefix has special meaning in etcd. Specifically, it excludes those - // entries from directory listings. - Etcd2NodeFilePrefix = "." - - // The lock prefix can (and probably should) cause an entry to be excluded - // from directory listings, so "_" works here. - Etcd2NodeLockPrefix = "_" - - // The delimiter is the same as the `-C` flag of etcdctl. - Etcd2MachineDelimiter = "," - - // The lock TTL matches the default that Consul API uses, 15 seconds. - Etcd2LockTTL = 15 * time.Second - - // The amount of time to wait between the semaphore key renewals - Etcd2LockRenewInterval = 5 * time.Second - - // The amount of time to wait if a watch fails before trying again. - Etcd2WatchRetryInterval = time.Second - - // The number of times to re-try a failed watch before signaling that leadership is lost. - Etcd2WatchRetryMax = 5 -) - -// Etcd2Backend is a physical backend that stores data at specific -// prefix within etcd. It is used for most production situations as -// it allows Vault to run on multiple machines in a highly-available manner. -type Etcd2Backend struct { - path string - kAPI client.KeysAPI - permitPool *physical.PermitPool - logger log.Logger - haEnabled bool -} - -// Verify Etcd2Backend satisfies the correct interfaces -var _ physical.Backend = (*Etcd2Backend)(nil) -var _ physical.HABackend = (*Etcd2Backend)(nil) -var _ physical.Lock = (*Etcd2Lock)(nil) - -func newEtcd2Backend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the etcd path form the configuration. - path, ok := conf["path"] - if !ok { - path = "/vault" - } - - // Ensure path is prefixed. - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - - c, err := newEtcdV2Client(conf) - if err != nil { - return nil, err - } - - haEnabled := os.Getenv("ETCD_HA_ENABLED") - if haEnabled == "" { - haEnabled = conf["ha_enabled"] - } - if haEnabled == "" { - haEnabled = "false" - } - haEnabledBool, err := strconv.ParseBool(haEnabled) - if err != nil { - return nil, fmt.Errorf("value [%v] of 'ha_enabled' could not be understood", haEnabled) - } - - // Should we sync the cluster state? There are three available options - // for our client library: don't sync (required for some proxies), sync - // once, or sync periodically with AutoSync. We currently support the - // first two. - sync, ok := conf["sync"] - if !ok { - sync = "yes" - } - switch sync { - case "yes", "true", "y", "1": - ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout) - syncErr := c.Sync(ctx) - cancel() - if syncErr != nil { - return nil, multierror.Append(EtcdSyncClusterError, syncErr) - } - case "no", "false", "n", "0": - default: - return nil, fmt.Errorf("value of 'sync' could not be understood") - } - - kAPI := client.NewKeysAPI(c) - - // Setup the backend. - return &Etcd2Backend{ - path: path, - kAPI: kAPI, - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - logger: logger, - haEnabled: haEnabledBool, - }, nil -} - -func newEtcdV2Client(conf map[string]string) (client.Client, error) { - endpoints, err := getEtcdEndpoints(conf) - if err != nil { - return nil, err - } - - // Create a new client from the supplied address and attempt to sync with the - // cluster. - var cTransport client.CancelableTransport - cert, hasCert := conf["tls_cert_file"] - key, hasKey := conf["tls_key_file"] - ca, hasCa := conf["tls_ca_file"] - if (hasCert && hasKey) || hasCa { - var transportErr error - tls := transport.TLSInfo{ - TrustedCAFile: ca, - CertFile: cert, - KeyFile: key, - } - cTransport, transportErr = transport.NewTransport(tls, 30*time.Second) - - if transportErr != nil { - return nil, transportErr - } - } else { - cTransport = client.DefaultTransport - } - - cfg := client.Config{ - Endpoints: endpoints, - Transport: cTransport, - } - - // Set credentials. - username := os.Getenv("ETCD_USERNAME") - if username == "" { - username, _ = conf["username"] - } - - password := os.Getenv("ETCD_PASSWORD") - if password == "" { - password, _ = conf["password"] - } - - if username != "" && password != "" { - cfg.Username = username - cfg.Password = password - } - - return client.New(cfg) -} - -// Put is used to insert or update an entry. -func (c *Etcd2Backend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"etcd", "put"}, time.Now()) - value := base64.StdEncoding.EncodeToString(entry.Value) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - _, err := c.kAPI.Set(context.Background(), c.nodePath(entry.Key), value, nil) - return err -} - -// Get is used to fetch an entry. -func (c *Etcd2Backend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"etcd", "get"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - getOpts := &client.GetOptions{ - Recursive: false, - Sort: false, - } - response, err := c.kAPI.Get(context.Background(), c.nodePath(key), getOpts) - if err != nil { - if errorIsMissingKey(err) { - return nil, nil - } - return nil, err - } - - // Decode the stored value from base-64. - value, err := base64.StdEncoding.DecodeString(response.Node.Value) - if err != nil { - return nil, err - } - - // Construct and return a new entry. - return &physical.Entry{ - Key: key, - Value: value, - }, nil -} - -// Delete is used to permanently delete an entry. -func (c *Etcd2Backend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"etcd", "delete"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - // Remove the key, non-recursively. - delOpts := &client.DeleteOptions{ - Recursive: false, - } - _, err := c.kAPI.Delete(context.Background(), c.nodePath(key), delOpts) - if err != nil && !errorIsMissingKey(err) { - return err - } - return nil -} - -// List is used to list all the keys under a given prefix, up to the next -// prefix. -func (c *Etcd2Backend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"etcd", "list"}, time.Now()) - - // Set a directory path from the given prefix. - path := c.nodePathDir(prefix) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - // Get the directory, non-recursively, from etcd. If the directory is - // missing, we just return an empty list of contents. - getOpts := &client.GetOptions{ - Recursive: false, - Sort: true, - } - response, err := c.kAPI.Get(context.Background(), path, getOpts) - if err != nil { - if errorIsMissingKey(err) { - return []string{}, nil - } - return nil, err - } - - out := make([]string, len(response.Node.Nodes)) - for i, node := range response.Node.Nodes { - - // etcd keys include the full path, so let's trim the prefix directory - // path. - name := strings.TrimPrefix(node.Key, path) - - // Check if this node is itself a directory. If it is, add a trailing - // slash; if it isn't remove the node file prefix. - if node.Dir { - out[i] = name + "/" - } else { - out[i] = name[1:] - } - } - return out, nil -} - -// nodePath returns an etcd filepath based on the given key. -func (b *Etcd2Backend) nodePath(key string) string { - return filepath.Join(b.path, filepath.Dir(key), Etcd2NodeFilePrefix+filepath.Base(key)) -} - -// nodePathDir returns an etcd directory path based on the given key. -func (b *Etcd2Backend) nodePathDir(key string) string { - return filepath.Join(b.path, key) + "/" -} - -// nodePathLock returns an etcd directory path used specifically for semaphore -// indices based on the given key. -func (b *Etcd2Backend) nodePathLock(key string) string { - return filepath.Join(b.path, filepath.Dir(key), Etcd2NodeLockPrefix+filepath.Base(key)+"/") -} - -// Lock is used for mutual exclusion based on the given key. -func (c *Etcd2Backend) LockWith(key, value string) (physical.Lock, error) { - return &Etcd2Lock{ - kAPI: c.kAPI, - value: value, - semaphoreDirKey: c.nodePathLock(key), - }, nil -} - -// HAEnabled indicates whether the HA functionality should be exposed. -// Currently always returns true. -func (e *Etcd2Backend) HAEnabled() bool { - return e.haEnabled -} - -// Etcd2Lock implements a lock using and Etcd2 backend. -type Etcd2Lock struct { - kAPI client.KeysAPI - value, semaphoreDirKey, semaphoreKey string - lock sync.Mutex -} - -// addSemaphoreKey acquires a new ordered semaphore key. -func (c *Etcd2Lock) addSemaphoreKey() (string, uint64, error) { - // CreateInOrder is an atomic operation that can be used to enqueue a - // request onto a semaphore. In the rest of the comments, we refer to the - // resulting key as a "semaphore key". - // https://coreos.com/etcd/docs/2.0.8/api.html#atomically-creating-in-order-keys - opts := &client.CreateInOrderOptions{ - TTL: Etcd2LockTTL, - } - response, err := c.kAPI.CreateInOrder(context.Background(), c.semaphoreDirKey, c.value, opts) - if err != nil { - return "", 0, err - } - return response.Node.Key, response.Index, nil -} - -// renewSemaphoreKey renews an existing semaphore key. -func (c *Etcd2Lock) renewSemaphoreKey() (string, uint64, error) { - setOpts := &client.SetOptions{ - TTL: Etcd2LockTTL, - PrevExist: client.PrevExist, - } - response, err := c.kAPI.Set(context.Background(), c.semaphoreKey, c.value, setOpts) - if err != nil { - return "", 0, err - } - return response.Node.Key, response.Index, nil -} - -// getSemaphoreKey determines which semaphore key holder has acquired the lock -// and its value. -func (c *Etcd2Lock) getSemaphoreKey() (string, string, uint64, error) { - // Get the list of waiters in order to see if we are next. - getOpts := &client.GetOptions{ - Recursive: false, - Sort: true, - } - response, err := c.kAPI.Get(context.Background(), c.semaphoreDirKey, getOpts) - if err != nil { - return "", "", 0, err - } - - // Make sure the list isn't empty. - if response.Node.Nodes.Len() == 0 { - return "", "", response.Index, nil - } - return response.Node.Nodes[0].Key, response.Node.Nodes[0].Value, response.Index, nil -} - -// isHeld determines if we are the current holders of the lock. -func (c *Etcd2Lock) isHeld() (bool, error) { - if c.semaphoreKey == "" { - return false, nil - } - - // Get the key of the current holder of the lock. - currentSemaphoreKey, _, _, err := c.getSemaphoreKey() - if err != nil { - return false, err - } - return c.semaphoreKey == currentSemaphoreKey, nil -} - -// assertHeld determines whether or not we are the current holders of the lock -// and returns an Etcd2LockNotHeldError if we are not. -func (c *Etcd2Lock) assertHeld() error { - held, err := c.isHeld() - if err != nil { - return err - } - - // Check if we don't hold the lock. - if !held { - return EtcdLockNotHeldError - } - return nil -} - -// assertNotHeld determines whether or not we are the current holders of the -// lock and returns an Etcd2LockHeldError if we are. -func (c *Etcd2Lock) assertNotHeld() error { - held, err := c.isHeld() - if err != nil { - return err - } - - // Check if we hold the lock. - if held { - return EtcdLockHeldError - } - return nil -} - -// periodically renew our semaphore key so that it doesn't expire -func (c *Etcd2Lock) periodicallyRenewSemaphoreKey(stopCh chan struct{}) { - for { - select { - case <-time.After(Etcd2LockRenewInterval): - c.renewSemaphoreKey() - case <-stopCh: - return - } - } -} - -// watchForKeyRemoval continuously watches a single non-directory key starting -// from the provided etcd index and closes the provided channel when it's -// deleted, expires, or appears to be missing. -func (c *Etcd2Lock) watchForKeyRemoval(key string, etcdIndex uint64, closeCh chan struct{}) { - retries := Etcd2WatchRetryMax - - for { - // Start a non-recursive watch of the given key. - w := c.kAPI.Watcher(key, &client.WatcherOptions{AfterIndex: etcdIndex, Recursive: false}) - response, err := w.Next(context.TODO()) - if err != nil { - - // If the key is just missing, we can exit the loop. - if errorIsMissingKey(err) { - break - } - - // If the error is something else, there's nothing we can do but retry - // the watch. Check that we still have retries left. - retries -= 1 - if retries == 0 { - break - } - - // Sleep for a period of time to avoid slamming etcd. - time.Sleep(Etcd2WatchRetryInterval) - continue - } - - // Check if the key we are concerned with has been removed. If it has, we - // can exit the loop. - if response.Node.Key == key && - (response.Action == "delete" || response.Action == "expire") { - break - } - - // Update the etcd index. - etcdIndex = response.Index + 1 - } - - // Regardless of what happened, we need to close the close channel. - close(closeCh) -} - -// Lock attempts to acquire the lock by waiting for a new semaphore key in etcd -// to become the first in the queue and will block until it is successful or -// it receives a signal on the provided channel. The returned channel will be -// closed when the lock is lost, either by an explicit call to Unlock or by -// the associated semaphore key in etcd otherwise being deleted or expiring. -// -// If the lock is currently held by this instance of Etcd2Lock, Lock will -// return an Etcd2LockHeldError error. -func (c *Etcd2Lock) Lock(stopCh <-chan struct{}) (doneCh <-chan struct{}, retErr error) { - // Get the local lock before interacting with etcd. - c.lock.Lock() - defer c.lock.Unlock() - - // Check if the lock is already held. - if err := c.assertNotHeld(); err != nil { - return nil, err - } - - // Add a new semaphore key that we will track. - semaphoreKey, _, err := c.addSemaphoreKey() - if err != nil { - return nil, err - } - c.semaphoreKey = semaphoreKey - - // Get the current semaphore key. - currentSemaphoreKey, _, currentEtcdIndex, err := c.getSemaphoreKey() - if err != nil { - return nil, err - } - - // Create an etcd-compatible boolean stop channel from the provided - // interface stop channel. - ctx, cancel := context.WithCancel(context.Background()) - go func() { - <-stopCh - cancel() - }() - defer cancel() - - // Create a channel to signal when we lose the semaphore key. - done := make(chan struct{}) - defer func() { - if retErr != nil { - close(done) - } - }() - - go c.periodicallyRenewSemaphoreKey(done) - - // Loop until the we current semaphore key matches ours. - for semaphoreKey != currentSemaphoreKey { - var err error - - // Start a watch of the entire lock directory - w := c.kAPI.Watcher(c.semaphoreDirKey, &client.WatcherOptions{AfterIndex: currentEtcdIndex, Recursive: true}) - response, err := w.Next(ctx) - if err != nil { - - // If the error is not an etcd error, we can assume it's a notification - // of the stop channel having closed. In this scenario, we also want to - // remove our semaphore key as we are no longer waiting to acquire the - // lock. - if _, ok := err.(*client.Error); !ok { - delOpts := &client.DeleteOptions{ - Recursive: false, - } - _, err = c.kAPI.Delete(context.Background(), c.semaphoreKey, delOpts) - } - return nil, err - } - - // Make sure the index we are waiting for has not been removed. If it has, - // this is an error and nothing else needs to be done. - if response.Node.Key == semaphoreKey && - (response.Action == "delete" || response.Action == "expire") { - return nil, EtcdSemaphoreKeyRemovedError - } - - // Get the current semaphore key and etcd index. - currentSemaphoreKey, _, currentEtcdIndex, err = c.getSemaphoreKey() - if err != nil { - return nil, err - } - } - - go c.watchForKeyRemoval(c.semaphoreKey, currentEtcdIndex, done) - return done, nil -} - -// Unlock releases the lock by deleting the associated semaphore key in etcd. -// -// If the lock is not currently held by this instance of Etcd2Lock, Unlock will -// return an Etcd2LockNotHeldError error. -func (c *Etcd2Lock) Unlock() error { - // Get the local lock before interacting with etcd. - c.lock.Lock() - defer c.lock.Unlock() - - // Check that the lock is held. - if err := c.assertHeld(); err != nil { - return err - } - - // Delete our semaphore key. - delOpts := &client.DeleteOptions{ - Recursive: false, - } - if _, err := c.kAPI.Delete(context.Background(), c.semaphoreKey, delOpts); err != nil { - return err - } - return nil -} - -// Value checks whether or not the lock is held by any instance of Etcd2Lock, -// including this one, and returns the current value. -func (c *Etcd2Lock) Value() (bool, string, error) { - semaphoreKey, semaphoreValue, _, err := c.getSemaphoreKey() - if err != nil { - return false, "", err - } - - if semaphoreKey == "" { - return false, "", nil - } - return true, semaphoreValue, nil -} - -// errorIsMissingKey returns true if the given error is an etcd error with an -// error code corresponding to a missing key. -func errorIsMissingKey(err error) bool { - etcdErr, ok := err.(client.Error) - return ok && etcdErr.Code == client.ErrorCodeKeyNotFound -} diff --git a/vendor/github.com/hashicorp/vault/physical/etcd/etcd3.go b/vendor/github.com/hashicorp/vault/physical/etcd/etcd3.go deleted file mode 100644 index 94e617997..000000000 --- a/vendor/github.com/hashicorp/vault/physical/etcd/etcd3.go +++ /dev/null @@ -1,358 +0,0 @@ -package etcd - -import ( - "context" - "errors" - "fmt" - "os" - "path" - "strconv" - "strings" - "sync" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/coreos/etcd/clientv3" - "github.com/coreos/etcd/clientv3/concurrency" - "github.com/coreos/etcd/pkg/transport" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -// EtcdBackend is a physical backend that stores data at specific -// prefix within etcd. It is used for most production situations as -// it allows Vault to run on multiple machines in a highly-available manner. -type EtcdBackend struct { - logger log.Logger - path string - haEnabled bool - - permitPool *physical.PermitPool - - etcd *clientv3.Client -} - -const ( - // etcd3 default lease duration is 60s. set to 15s for faster recovery. - etcd3LockTimeoutInSeconds = 15 - // etcd3 default request timeout is set to 5s. It should be long enough - // for most cases, even with internal retry. - etcd3RequestTimeout = 5 * time.Second -) - -// Verify EtcdBackend satisfies the correct interfaces -var _ physical.Backend = (*EtcdBackend)(nil) -var _ physical.HABackend = (*EtcdBackend)(nil) -var _ physical.Lock = (*EtcdLock)(nil) - -// newEtcd3Backend constructs a etcd3 backend. -func newEtcd3Backend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the etcd path form the configuration. - path, ok := conf["path"] - if !ok { - path = "/vault" - } - - // Ensure path is prefixed. - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - - endpoints, err := getEtcdEndpoints(conf) - if err != nil { - return nil, err - } - - cfg := clientv3.Config{ - Endpoints: endpoints, - } - - haEnabled := os.Getenv("ETCD_HA_ENABLED") - if haEnabled == "" { - haEnabled = conf["ha_enabled"] - } - if haEnabled == "" { - haEnabled = "false" - } - haEnabledBool, err := strconv.ParseBool(haEnabled) - if err != nil { - return nil, fmt.Errorf("value [%v] of 'ha_enabled' could not be understood", haEnabled) - } - - cert, hasCert := conf["tls_cert_file"] - key, hasKey := conf["tls_key_file"] - ca, hasCa := conf["tls_ca_file"] - if (hasCert && hasKey) || hasCa { - tls := transport.TLSInfo{ - TrustedCAFile: ca, - CertFile: cert, - KeyFile: key, - } - - tlscfg, err := tls.ClientConfig() - if err != nil { - return nil, err - } - cfg.TLS = tlscfg - } - - // Set credentials. - username := os.Getenv("ETCD_USERNAME") - if username == "" { - username, _ = conf["username"] - } - - password := os.Getenv("ETCD_PASSWORD") - if password == "" { - password, _ = conf["password"] - } - - if username != "" && password != "" { - cfg.Username = username - cfg.Password = password - } - - if maxReceive, ok := conf["max_receive_size"]; ok { - // grpc converts this to uint32 internally, so parse as that to avoid passing invalid values - val, err := strconv.ParseUint(maxReceive, 10, 32) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("value of 'max_receive_size' (%v) could not be understood: {{err}}", maxReceive), err) - } - cfg.MaxCallRecvMsgSize = int(val) - } - - etcd, err := clientv3.New(cfg) - if err != nil { - return nil, err - } - - ssync, ok := conf["sync"] - if !ok { - ssync = "true" - } - sync, err := strconv.ParseBool(ssync) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("value of 'sync' (%v) could not be understood: {{err}}", ssync), err) - } - - if sync { - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - err := etcd.Sync(ctx) - cancel() - if err != nil { - return nil, err - } - } - - return &EtcdBackend{ - path: path, - etcd: etcd, - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - logger: logger, - haEnabled: haEnabledBool, - }, nil -} - -func (c *EtcdBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"etcd", "put"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - _, err := c.etcd.Put(ctx, path.Join(c.path, entry.Key), string(entry.Value)) - return err -} - -func (c *EtcdBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"etcd", "get"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - resp, err := c.etcd.Get(ctx, path.Join(c.path, key)) - if err != nil { - return nil, err - } - - if len(resp.Kvs) == 0 { - return nil, nil - } - if len(resp.Kvs) > 1 { - return nil, errors.New("unexpected number of keys from a get request") - } - return &physical.Entry{ - Key: key, - Value: resp.Kvs[0].Value, - }, nil -} - -func (c *EtcdBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"etcd", "delete"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - _, err := c.etcd.Delete(ctx, path.Join(c.path, key)) - if err != nil { - return err - } - return nil -} - -func (c *EtcdBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"etcd", "list"}, time.Now()) - - c.permitPool.Acquire() - defer c.permitPool.Release() - - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - prefix = path.Join(c.path, prefix) + "/" - resp, err := c.etcd.Get(ctx, prefix, clientv3.WithPrefix()) - if err != nil { - return nil, err - } - - keys := []string{} - for _, kv := range resp.Kvs { - key := strings.TrimPrefix(string(kv.Key), prefix) - key = strings.TrimPrefix(key, "/") - - if len(key) == 0 { - continue - } - - if i := strings.Index(key, "/"); i == -1 { - keys = append(keys, key) - } else if i != -1 { - keys = strutil.AppendIfMissing(keys, key[:i+1]) - } - } - return keys, nil -} - -func (e *EtcdBackend) HAEnabled() bool { - return e.haEnabled -} - -// EtcdLock implements a lock using and etcd backend. -type EtcdLock struct { - lock sync.Mutex - held bool - - etcdSession *concurrency.Session - etcdMu *concurrency.Mutex - - prefix string - value string - - etcd *clientv3.Client -} - -// Lock is used for mutual exclusion based on the given key. -func (c *EtcdBackend) LockWith(key, value string) (physical.Lock, error) { - p := path.Join(c.path, key) - return &EtcdLock{ - prefix: p, - value: value, - etcd: c.etcd, - }, nil -} - -func (c *EtcdLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - c.lock.Lock() - defer c.lock.Unlock() - - if c.etcdMu == nil { - if err := c.initMu(); err != nil { - return nil, err - } - } - - if c.held { - return nil, EtcdLockHeldError - } - - select { - case _, ok := <-c.etcdSession.Done(): - if !ok { - // The session's done channel is closed, so the session is over, - // and we need a new lock with a new session. - if err := c.initMu(); err != nil { - return nil, err - } - } - default: - } - - ctx, cancel := context.WithCancel(context.Background()) - go func() { - <-stopCh - cancel() - }() - if err := c.etcdMu.Lock(ctx); err != nil { - if err == context.Canceled { - return nil, nil - } - return nil, err - } - - pctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - if _, err := c.etcd.Put(pctx, c.etcdMu.Key(), c.value, clientv3.WithLease(c.etcdSession.Lease())); err != nil { - return nil, err - } - - c.held = true - - return c.etcdSession.Done(), nil -} - -func (c *EtcdLock) Unlock() error { - c.lock.Lock() - defer c.lock.Unlock() - - if !c.held { - return EtcdLockNotHeldError - } - - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - return c.etcdMu.Unlock(ctx) -} - -func (c *EtcdLock) Value() (bool, string, error) { - ctx, cancel := context.WithTimeout(context.Background(), etcd3RequestTimeout) - defer cancel() - - resp, err := c.etcd.Get(ctx, - c.prefix, clientv3.WithPrefix(), - clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortAscend)) - - if err != nil { - return false, "", err - } - if len(resp.Kvs) == 0 { - return false, "", nil - } - - return true, string(resp.Kvs[0].Value), nil -} - -func (c *EtcdLock) initMu() error { - session, err := concurrency.NewSession(c.etcd, concurrency.WithTTL(etcd3LockTimeoutInSeconds)) - if err != nil { - return err - } - c.etcdSession = session - c.etcdMu = concurrency.NewMutex(session, c.prefix) - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/file/file.go b/vendor/github.com/hashicorp/vault/physical/file/file.go deleted file mode 100644 index cf22f2b32..000000000 --- a/vendor/github.com/hashicorp/vault/physical/file/file.go +++ /dev/null @@ -1,374 +0,0 @@ -package file - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/physical" -) - -// Verify FileBackend satisfies the correct interfaces -var _ physical.Backend = (*FileBackend)(nil) -var _ physical.Transactional = (*TransactionalFileBackend)(nil) -var _ physical.PseudoTransactional = (*FileBackend)(nil) - -// FileBackend is a physical backend that stores data on disk -// at a given file path. It can be used for durable single server -// situations, or to develop locally where durability is not critical. -// -// WARNING: the file backend implementation is currently extremely unsafe -// and non-performant. It is meant mostly for local testing and development. -// It can be improved in the future. -type FileBackend struct { - sync.RWMutex - path string - logger log.Logger - permitPool *physical.PermitPool -} - -type TransactionalFileBackend struct { - FileBackend -} - -type fileEntry struct { - Value []byte -} - -// NewFileBackend constructs a FileBackend using the given directory -func NewFileBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - path, ok := conf["path"] - if !ok { - return nil, fmt.Errorf("'path' must be set") - } - - return &FileBackend{ - path: path, - logger: logger, - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - }, nil -} - -func NewTransactionalFileBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - path, ok := conf["path"] - if !ok { - return nil, fmt.Errorf("'path' must be set") - } - - // Create a pool of size 1 so only one operation runs at a time - return &TransactionalFileBackend{ - FileBackend: FileBackend{ - path: path, - logger: logger, - permitPool: physical.NewPermitPool(1), - }, - }, nil -} - -func (b *FileBackend) Delete(ctx context.Context, path string) error { - b.permitPool.Acquire() - defer b.permitPool.Release() - - b.Lock() - defer b.Unlock() - - return b.DeleteInternal(ctx, path) -} - -func (b *FileBackend) DeleteInternal(ctx context.Context, path string) error { - if path == "" { - return nil - } - - if err := b.validatePath(path); err != nil { - return err - } - - basePath, key := b.expandPath(path) - fullPath := filepath.Join(basePath, key) - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - err := os.Remove(fullPath) - if err != nil && !os.IsNotExist(err) { - return errwrap.Wrapf(fmt.Sprintf("failed to remove %q: {{err}}", fullPath), err) - } - - err = b.cleanupLogicalPath(path) - - return err -} - -// cleanupLogicalPath is used to remove all empty nodes, beginning with deepest -// one, aborting on first non-empty one, up to top-level node. -func (b *FileBackend) cleanupLogicalPath(path string) error { - nodes := strings.Split(path, fmt.Sprintf("%c", os.PathSeparator)) - for i := len(nodes) - 1; i > 0; i-- { - fullPath := filepath.Join(b.path, filepath.Join(nodes[:i]...)) - - dir, err := os.Open(fullPath) - if err != nil { - if dir != nil { - dir.Close() - } - if os.IsNotExist(err) { - return nil - } else { - return err - } - } - - list, err := dir.Readdir(1) - dir.Close() - if err != nil && err != io.EOF { - return err - } - - // If we have no entries, it's an empty directory; remove it - if err == io.EOF || list == nil || len(list) == 0 { - err = os.Remove(fullPath) - if err != nil { - return err - } - } - } - - return nil -} - -func (b *FileBackend) Get(ctx context.Context, k string) (*physical.Entry, error) { - b.permitPool.Acquire() - defer b.permitPool.Release() - - b.RLock() - defer b.RUnlock() - - return b.GetInternal(ctx, k) -} - -func (b *FileBackend) GetInternal(ctx context.Context, k string) (*physical.Entry, error) { - if err := b.validatePath(k); err != nil { - return nil, err - } - - path, key := b.expandPath(k) - path = filepath.Join(path, key) - - // If we stat it and it exists but is size zero, it may be left from some - // previous FS error like out-of-space. No Vault entry will ever be zero - // length, so simply remove it and return nil. - fi, err := os.Stat(path) - if err == nil { - if fi.Size() == 0 { - // Best effort, ignore errors - os.Remove(path) - return nil, nil - } - } - - f, err := os.Open(path) - if f != nil { - defer f.Close() - } - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - - return nil, err - } - - var entry fileEntry - if err := jsonutil.DecodeJSONFromReader(f, &entry); err != nil { - return nil, err - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - return &physical.Entry{ - Key: k, - Value: entry.Value, - }, nil -} - -func (b *FileBackend) Put(ctx context.Context, entry *physical.Entry) error { - b.permitPool.Acquire() - defer b.permitPool.Release() - - b.Lock() - defer b.Unlock() - - return b.PutInternal(ctx, entry) -} - -func (b *FileBackend) PutInternal(ctx context.Context, entry *physical.Entry) error { - if err := b.validatePath(entry.Key); err != nil { - return err - } - - path, key := b.expandPath(entry.Key) - - // Make the parent tree - if err := os.MkdirAll(path, 0700); err != nil { - return err - } - - // JSON encode the entry and write it - fullPath := filepath.Join(path, key) - f, err := os.OpenFile( - fullPath, - os.O_CREATE|os.O_TRUNC|os.O_WRONLY, - 0600) - if err != nil { - if f != nil { - f.Close() - } - return err - } - if f == nil { - return errors.New("could not successfully get a file handle") - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - enc := json.NewEncoder(f) - encErr := enc.Encode(&fileEntry{ - Value: entry.Value, - }) - f.Close() - if encErr == nil { - return nil - } - - // Everything below is best-effort and will result in encErr being returned - - // See if we ended up with a zero-byte file and if so delete it, might be a - // case of disk being full but the file info is in metadata that is - // reserved. - fi, err := os.Stat(fullPath) - if err != nil { - return encErr - } - if fi == nil { - return encErr - } - if fi.Size() == 0 { - os.Remove(fullPath) - } - return encErr -} - -func (b *FileBackend) List(ctx context.Context, prefix string) ([]string, error) { - b.permitPool.Acquire() - defer b.permitPool.Release() - - b.RLock() - defer b.RUnlock() - - return b.ListInternal(ctx, prefix) -} - -func (b *FileBackend) ListInternal(ctx context.Context, prefix string) ([]string, error) { - if err := b.validatePath(prefix); err != nil { - return nil, err - } - - path := b.path - if prefix != "" { - path = filepath.Join(path, prefix) - } - - // Read the directory contents - f, err := os.Open(path) - if f != nil { - defer f.Close() - } - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - - return nil, err - } - - names, err := f.Readdirnames(-1) - if err != nil { - return nil, err - } - - for i, name := range names { - fi, err := os.Stat(filepath.Join(path, name)) - if err != nil { - return nil, err - } - if fi.IsDir() { - names[i] = name + "/" - } else { - if name[0] == '_' { - names[i] = name[1:] - } - } - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - if len(names) > 0 { - sort.Strings(names) - } - - return names, nil -} - -func (b *FileBackend) expandPath(k string) (string, string) { - path := filepath.Join(b.path, k) - key := filepath.Base(path) - path = filepath.Dir(path) - return path, "_" + key -} - -func (b *FileBackend) validatePath(path string) error { - switch { - case strings.Contains(path, ".."): - return consts.ErrPathContainsParentReferences - } - - return nil -} - -func (b *TransactionalFileBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - b.permitPool.Acquire() - defer b.permitPool.Release() - - b.Lock() - defer b.Unlock() - - return physical.GenericTransactionHandler(ctx, b, txns) -} diff --git a/vendor/github.com/hashicorp/vault/physical/foundationdb/README.md b/vendor/github.com/hashicorp/vault/physical/foundationdb/README.md deleted file mode 100644 index fcf08b7f8..000000000 --- a/vendor/github.com/hashicorp/vault/physical/foundationdb/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# FoundationDB storage backend - -Extra steps are required to produce a Vault build containing the FoundationDB -backend; attempts to use the backend on a build produced without following -this procedure will fail with a descriptive error message at runtime. - -## Installing the Go bindings - -You will need to install the FoundationDB Go bindings to build the FoundationDB -backend. Make sure you have the FoundationDB client library installed on your -system, along with Mono (core is enough), then install the Go bindings using -the `fdb-go-install.sh` script: - -``` -$ physical/foundationdb/fdb-go-install.sh -``` - -## Building Vault - -To build Vault the FoundationDB backend, add FDB_ENABLED=1 when invoking -`make`, e.g. - -``` -$ make dev FDB_ENABLED=1 -``` - -## Running tests - -Similarly, add FDB_ENABLED=1 to your `make` invocation when running tests, -e.g. - -``` -$ make test TEST=./physical/foundationdb FDB_ENABLED=1 -``` diff --git a/vendor/github.com/hashicorp/vault/physical/foundationdb/fdb-go-install.sh b/vendor/github.com/hashicorp/vault/physical/foundationdb/fdb-go-install.sh deleted file mode 100755 index ddb8260da..000000000 --- a/vendor/github.com/hashicorp/vault/physical/foundationdb/fdb-go-install.sh +++ /dev/null @@ -1,330 +0,0 @@ -#!/bin/bash -eu -# -# fdb-go-install.sh -# -# Installs the FoundationDB Go bindings for a client. This will download -# the repository from the remote repo either into the go directory -# with the appropriate semantic version. It will then build a few -# generated files that need to be present for the go build to work. -# At the end, it has some advice for flags to modify within your -# go environment so that other packages may successfully use this -# library. -# - -DESTDIR="${DESTDIR:-}" -FDBVER="${FDBVER:-5.1.0}" -REMOTE="${REMOTE:-github.com}" -FDBREPO="${FDBREPO:-apple/foundationdb}" - -status=0 - -platform=$(uname) -if [[ "${platform}" == "Darwin" ]] ; then - FDBLIBDIR="${FDBLIBDIR:-/usr/local/lib}" - libfdbc="libfdb_c.dylib" -elif [[ "${platform}" == "Linux" ]] ; then - libfdbc="libfdb_c.so" - custom_libdir="${FDBLIBDIR:-}" - FDBLIBDIR="" - - if [[ -z "${custom_libdir}" ]]; then - search_libdirs=( '/usr/lib' '/usr/lib64' ) - else - search_libdirs=( "${custom_libdir}" ) - fi - - for libdir in "${search_libdirs[@]}" ; do - if [[ -e "${libdir}/${libfdbc}" ]]; then - FDBLIBDIR="${libdir}" - break - fi - done - - if [[ -z "${FDBLIBDIR}" ]]; then - echo "The FoundationDB C library could not be found in any of:" - for libdir in "${search_libdirs[@]}" ; do - echo " ${libdir}" - done - echo "Your installation may be incomplete, or you need to set a custom FDBLIBDIR." - let status="${status} + 1" - fi - -else - echo "Unsupported platform ${platform}". - echo "At the moment, only macOS and Linux are supported by this script." - let status="${status} + 1" -fi - -filedir=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd) -destdir="" - -function printUsage() { - echo "Usage: fdb-go-install.sh " - echo - echo "cmd: One of the commands to run. The options are:" - echo " install Download the FDB go bindings and install them" - echo " localinstall Install a into the go path a local copy of the repo" - echo " download Download but do not prepare the FoundationDB bindings" - echo " help Print this help message and then quit" - echo - echo "Command Line Options:" - echo " --fdbver FoundationDB semantic version (default is ${FDBVER})" - echo " -d/--dest-dir Local location for the repo (default is to place in go path)" - echo - echo "Environment Variable Options:" - echo " REMOTE Remote repository to download from (currently ${REMOTE})" - echo " FDBREPO Repository of FoundationDB library to download (currently ${FDBREPO})" - echo " FDBLIBDIR Directory within which should be the FoundationDB c library (currently ${FDBLIBDIR})" -} - -function parseArgs() { - local status=0 - - if [[ "${#}" -lt 0 ]] ; then - printUsage - let status="${status} + 1" - else - operation="${1}" - shift - if [[ "${operation}" != "install" ]] && [[ "${operation}" != "localinstall" ]] && [[ "${operation}" != "download" ]] && [[ "${operation}" != "help" ]] ; then - echo "Unknown command: ${operation}" - printUsage - let status="${status} + 1" - fi - fi - - while [[ "${#}" -gt 0 ]] && [[ "${status}" -eq 0 ]] ; do - local key="${1}" - case "${key}" in - --fdbver) - if [[ "${#}" -lt 2 ]] ; then - echo "No version specified with --fdbver flag" - printUsage - let status="${status} + 1" - else - FDBVER="${2}" - fi - shift - ;; - - -d|--dest-dir) - if [[ "${#}" -lt 2 ]] ; then - echo "No destination specified with ${key} flag" - printUsage - let status="${status} + 1" - else - destdir="${2}" - fi - shift - ;; - - *) - echo "Unrecognized argument ${key}" - printUsage - let status="${status} + 1" - esac - shift - done - - return "${status}" -} - -function checkBin() { - if [[ "${#}" -lt 1 ]] ; then - echo "Usage: checkBin " - return 1 - else - if [[ -n $(which "${1}") ]] ; then - return 0 - else - return 1 - fi - fi -} - -if [[ "${status}" -gt 0 ]] ; then - # We have already failed. - : -elif [[ "${#}" -lt 1 ]] ; then - printUsage -else - required_bins=( 'go' 'git' 'make' 'mono' ) - - missing_bins=() - for bin in "${required_bins[@]}" ; do - if ! checkBin "${bin}" ; then - missing_bins+=("${bin}") - let status="${status} + 1" - fi - done - - if [[ "${status}" -gt 0 ]] ; then - echo "Missing binaries: ${missing_bins[*]}" - elif ! parseArgs ${@} ; then - let status="${status} + 1" - elif [[ "${operation}" == "help" ]] ; then - printUsage - else - # Add go-specific environment variables. - eval $(go env) - - golibdir=$(dirname "${GOPATH}/src/${REMOTE}/${FDBREPO}") - if [[ -z "${destdir}" ]] ; then - if [[ "${operation}" == "localinstall" ]] ; then - # Assume its the local directory. - destdir=$(cd "${filedir}/../../.." && pwd) - else - destdir="${golibdir}" - fi - fi - - if [[ ! -d "${destdir}" ]] ; then - cmd=( 'mkdir' '-p' "${destdir}" ) - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - let status="${status} + 1" - echo "Could not create destination directory ${destdir}." - fi - fi - - # Step 1: Make sure repository is present. - - if [[ "${status}" -eq 0 ]] ; then - destdir=$( cd "${destdir}" && pwd ) # Get absolute path of destination dir. - fdbdir="${destdir}/foundationdb" - - if [[ ! -d "${destdir}" ]] ; then - cmd=("mkdir" "-p" "${destdir}") - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - echo "Could not create destination directory ${destdir}." - let status="${status} + 1" - fi - fi - fi - - if [[ "${operation}" == "localinstall" ]] ; then - # No download occurs in this case. - : - else - if [[ -d "${fdbdir}" ]] ; then - echo "Directory ${fdbdir} already exists ; checking out appropriate tag" - cmd1=( 'git' '-C' "${fdbdir}" 'fetch' 'origin' ) - cmd2=( 'git' '-C' "${fdbdir}" 'checkout' "release-${FDBVER}" ) - - if ! echo "${cmd1[*]}" || ! "${cmd1[@]}" ; then - let status="${status} + 1" - echo "Could not pull latest changes from origin" - elif ! echo "${cmd2[*]}" || ! "${cmd2[@]}" ; then - let status="${status} + 1" - echo "Could not checkout tag release-${FDBVER}." - fi - else - echo "Downloading foundation repository into ${destdir}:" - cmd=( 'git' '-C' "${destdir}" 'clone' '--branch' "release-${FDBVER}" "https://${REMOTE}/${FDBREPO}.git" ) - - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - let status="${status} + 1" - echo "Could not download repository." - fi - fi - fi - - # Step 2: Build generated things. - - if [[ "${operation}" == "download" ]] ; then - # The generated files are not created under a strict download. - : - elif [[ "${status}" -eq 0 ]] ; then - echo "Building generated files." - # FoundationDB starting with 5.2 can figure that out on its own - if [ -e '/usr/bin/mcs' ]; then - MCS_BIN=/usr/bin/mcs - else - MCS_BIN=/usr/bin/dmcs - fi - cmd=( 'make' '-C' "${fdbdir}" 'bindings/c/foundationdb/fdb_c_options.g.h' "MCS=$MCS_BIN" ) - - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - let status="${status} + 1" - echo "Could not generate required c header" - else - infile="${fdbdir}/fdbclient/vexillographer/fdb.options" - outfile="${fdbdir}/bindings/go/src/fdb/generated.go" - cmd=( 'go' 'run' "${fdbdir}/bindings/go/src/_util/translate_fdb_options.go" ) - echo "${cmd[*]} < ${infile} > ${outfile}" - if ! "${cmd[@]}" < "${infile}" > "${outfile}" ; then - let status="${status} + 1" - echo "Could not generate generated go file." - fi - fi - fi - - # Step 3: Add to go path. - - if [[ "${operation}" == "download" ]] ; then - # The files are not moved under a strict download. - : - elif [[ "${status}" -eq 0 ]] ; then - linkpath="${GOPATH}/src/${REMOTE}/${FDBREPO}" - if [[ "${linkpath}" == "${fdbdir}" ]] ; then - # Downloaded directly into go path. Skip making the link. - : - elif [[ -e "${linkpath}" ]] ; then - echo "Warning: link path (${linkpath}) already exists. Leaving in place." - else - dirpath=$(dirname "${linkpath}") - if [[ ! -d "${dirpath}" ]] ; then - cmd=( 'mkdir' '-p' "${dirpath}" ) - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - let status="${status} + 1" - echo "Could not create directory for link." - fi - fi - - if [[ "${status}" -eq 0 ]] ; then - cmd=( 'ln' '-s' "${fdbdir}" "${linkpath}" ) - echo "${cmd[*]}" - if ! "${cmd[@]}" ; then - let status="${status} + 1" - echo "Could not create link within go path." - fi - fi - fi - fi - - # Step 4: Build the binaries. - - if [[ "${operation}" == "download" ]] ; then - # Do not install if only downloading - : - elif [[ "${status}" -eq 0 ]] ; then - cgo_cppflags="-I${linkpath}/bindings/c" - cgo_cflags="-g -O2" - cgo_ldflags="-L${FDBLIBDIR}" - fdb_go_path="${REMOTE}/${FDBREPO}/bindings/go/src" - - if ! CGO_CPPFLAGS="${cgo_cppflags}" CGO_CFLAGS="${cgo_cflags}" CGO_LDFLAGS="${cgo_ldflags}" go install "${fdb_go_path}/fdb" "${fdb_go_path}/fdb/tuple" "${fdb_go_path}/fdb/subspace" "${fdb_go_path}/fdb/directory" ; then - let status="${status} + 1" - echo "Could not build FoundationDB go libraries." - fi - fi - - # Step 5: Explain CGO flags. - - if [[ "${status}" -eq 0 && ("${operation}" == "localinstall" || "${operation}" == "install" ) ]] ; then - echo - echo "The FoundationDB go bindings were successfully installed." - echo "To build packages which use the go bindings, you will need to" - echo "set the following environment variables:" - echo " CGO_CPPFLAGS=\"${cgo_cppflags}\"" - echo " CGO_CFLAGS=\"${cgo_cflags}\"" - echo " CGO_LDFLAGS=\"${cgo_ldflags}\"" - fi - fi -fi - -exit "${status}" diff --git a/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdb.go b/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdb.go deleted file mode 100644 index 39955a87d..000000000 --- a/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdb.go +++ /dev/null @@ -1,836 +0,0 @@ -// +build foundationdb - -package foundationdb - -import ( - "context" - "fmt" - "strconv" - "strings" - "sync" - "time" - - "bytes" - "encoding/binary" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/go-uuid" - - "github.com/apple/foundationdb/bindings/go/src/fdb" - "github.com/apple/foundationdb/bindings/go/src/fdb/directory" - "github.com/apple/foundationdb/bindings/go/src/fdb/subspace" - "github.com/apple/foundationdb/bindings/go/src/fdb/tuple" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/physical" -) - -const ( - // The namespace under our top directory containing keys only for list operations - metaKeysNamespace = "_meta-keys" - - // The namespace under our top directory containing the actual data - dataNamespace = "_data" - - // The namespace under our top directory containing locks - lockNamespace = "_lock" - - // Path hierarchy markers - // - an entry in a directory (included in list) - dirEntryMarker = "/\x01" - // - a path component (excluded from list) - dirPathMarker = "/\x02" -) - -var ( - // 64bit 1 and -1 for FDB atomic Add() - atomicArgOne = []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - atomicArgMinusOne = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} -) - -// Verify FDBBackend satisfies the correct interfaces -var _ physical.Backend = (*FDBBackend)(nil) -var _ physical.Transactional = (*FDBBackend)(nil) -var _ physical.HABackend = (*FDBBackend)(nil) -var _ physical.Lock = (*FDBBackendLock)(nil) - -// FDBBackend is a physical backend that stores data at a specific -// prefix within FoundationDB. -type FDBBackend struct { - logger log.Logger - haEnabled bool - db fdb.Database - metaKeysSpace subspace.Subspace - dataSpace subspace.Subspace - lockSpace subspace.Subspace - instanceUUID string -} - -func concat(a []byte, b ...byte) []byte { - r := make([]byte, len(a)+len(b)) - - copy(r, a) - copy(r[len(a):], b) - - return r -} - -func decoratePrefix(prefix string) ([]byte, error) { - pathElements := strings.Split(prefix, "/") - decoratedPrefix := strings.Join(pathElements[:len(pathElements)-1], dirPathMarker) - - return []byte(decoratedPrefix + dirEntryMarker), nil -} - -// Turn a path string into a decorated byte array to be used as (part of) a key -// foo /\x01foo -// foo/ /\x01foo/ -// foo/bar /\x02foo/\x01bar -// foo/bar/ /\x02foo/\x01bar/ -// foo/bar/baz /\x02foo/\x02bar/\x01baz -// foo/bar/baz/ /\x02foo/\x02bar/\x01baz/ -// foo/bar/baz/quux /\x02foo/\x02bar/\x02baz/\x01quux -// This allows for range queries to retrieve the "directory" listing. The -// decoratePrefix() function builds the path leading up to the leaf. -func decoratePath(path string) ([]byte, error) { - if path == "" { - return nil, fmt.Errorf("Invalid empty path") - } - - path = "/" + path - - isDir := strings.HasSuffix(path, "/") - path = strings.TrimRight(path, "/") - - lastSlash := strings.LastIndexByte(path, '/') - decoratedPrefix, err := decoratePrefix(path[:lastSlash+1]) - if err != nil { - return nil, err - } - - leaf := path[lastSlash+1:] - if isDir { - leaf += "/" - } - - return concat(decoratedPrefix, []byte(leaf)...), nil -} - -// Turn a decorated byte array back into a path string -func undecoratePath(decoratedPath []byte) string { - ret := strings.Replace(string(decoratedPath), dirPathMarker, "/", -1) - ret = strings.Replace(ret, dirEntryMarker, "/", -1) - - return strings.TrimLeft(ret, "/") -} - -// NewFDBBackend constructs a FoundationDB backend storing keys in the -// top-level directory designated by path -func NewFDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the top-level directory name - path, ok := conf["path"] - if !ok { - path = "vault" - } - logger.Debug("config path set", "path", path) - - dirPath := strings.Split(strings.Trim(path, "/"), "/") - - // FoundationDB API version - fdbApiVersionStr, ok := conf["api_version"] - if !ok { - return nil, fmt.Errorf("FoundationDB API version not specified") - } - - fdbApiVersionInt, err := strconv.Atoi(fdbApiVersionStr) - if err != nil { - return nil, errwrap.Wrapf("failed to parse fdb_api_version parameter: {{err}}", err) - } - logger.Debug("FoundationDB API version set", "fdb_api_version", fdbApiVersionInt) - - // FoundationDB cluster file - fdbClusterFile, ok := conf["cluster_file"] - if !ok { - return nil, fmt.Errorf("FoundationDB cluster file not specified") - } - - haEnabled := false - haEnabledStr, ok := conf["ha_enabled"] - if ok { - haEnabled, err = strconv.ParseBool(haEnabledStr) - if err != nil { - return nil, errwrap.Wrapf("failed to parse ha_enabled parameter: {{err}}", err) - } - } - - instanceUUID, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("could not generate instance UUID: {{err}}", err) - } - logger.Debug("Instance UUID", "uuid", instanceUUID) - - if err := fdb.APIVersion(fdbApiVersionInt); err != nil { - return nil, errwrap.Wrapf("failed to set FDB API version: {{err}}", err) - } - - db, err := fdb.Open(fdbClusterFile, []byte("DB")) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to open database with cluster file '%s': {{err}}", fdbClusterFile), err) - } - - topDir, err := directory.CreateOrOpen(db, dirPath, nil) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to create/open top-level directory '%s': {{err}}", path), err) - } - - // Setup the backend - f := &FDBBackend{ - logger: logger, - haEnabled: haEnabled, - db: db, - metaKeysSpace: topDir.Sub(metaKeysNamespace), - dataSpace: topDir.Sub(dataNamespace), - lockSpace: topDir.Sub(lockNamespace), - instanceUUID: instanceUUID, - } - return f, nil -} - -// Increase refcount on directories in the path, from the bottom -> up -func (f *FDBBackend) incDirsRefcount(tr fdb.Transaction, path string) error { - pathElements := strings.Split(strings.TrimRight(path, "/"), "/") - - for i := len(pathElements) - 1; i != 0; i-- { - dPath, err := decoratePath(strings.Join(pathElements[:i], "/") + "/") - if err != nil { - return errwrap.Wrapf("error incrementing directories refcount: {{err}}", err) - } - - // Atomic +1 - tr.Add(fdb.Key(concat(f.metaKeysSpace.Bytes(), dPath...)), atomicArgOne) - tr.Add(fdb.Key(concat(f.dataSpace.Bytes(), dPath...)), atomicArgOne) - } - - return nil -} - -type DirsDecTodo struct { - fkey fdb.Key - future fdb.FutureByteSlice -} - -// Decrease refcount on directories in the path, from the bottom -> up, and remove empty ones -func (f *FDBBackend) decDirsRefcount(tr fdb.Transaction, path string) error { - pathElements := strings.Split(strings.TrimRight(path, "/"), "/") - - dirsTodo := make([]DirsDecTodo, 0, len(pathElements)*2) - - for i := len(pathElements) - 1; i != 0; i-- { - dPath, err := decoratePath(strings.Join(pathElements[:i], "/") + "/") - if err != nil { - return errwrap.Wrapf("error decrementing directories refcount: {{err}}", err) - } - - metaFKey := fdb.Key(concat(f.metaKeysSpace.Bytes(), dPath...)) - dirsTodo = append(dirsTodo, DirsDecTodo{ - fkey: metaFKey, - future: tr.Get(metaFKey), - }) - - dataFKey := fdb.Key(concat(f.dataSpace.Bytes(), dPath...)) - dirsTodo = append(dirsTodo, DirsDecTodo{ - fkey: dataFKey, - future: tr.Get(dataFKey), - }) - } - - for _, todo := range dirsTodo { - value, err := todo.future.Get() - if err != nil { - return errwrap.Wrapf("error getting directory refcount while decrementing: {{err}}", err) - } - - // The directory entry does not exist; this is not expected - if value == nil { - return fmt.Errorf("non-existent directory while decrementing directory refcount") - } - - var count int64 - err = binary.Read(bytes.NewReader(value), binary.LittleEndian, &count) - if err != nil { - return errwrap.Wrapf("error reading directory refcount while decrementing: {{err}}", err) - } - - if count > 1 { - // Atomic -1 - tr.Add(todo.fkey, atomicArgMinusOne) - } else { - // Directory is empty, remove it - tr.Clear(todo.fkey) - } - } - - return nil -} - -func (f *FDBBackend) internalPut(tr fdb.Transaction, decoratedPath []byte, path string, value []byte) error { - // Check that the meta key exists before blindly increasing the refcounts - // in the directory hierarchy; this protects against commit_unknown_result - // and other similar cases where a previous transaction may have gone - // through without us knowing for sure. - - metaFKey := fdb.Key(concat(f.metaKeysSpace.Bytes(), decoratedPath...)) - metaFuture := tr.Get(metaFKey) - - dataFKey := fdb.Key(concat(f.dataSpace.Bytes(), decoratedPath...)) - tr.Set(dataFKey, value) - - value, err := metaFuture.Get() - if err != nil { - return errwrap.Wrapf("Put error while getting meta key: {{err}}", err) - } - - if value == nil { - tr.Set(metaFKey, []byte{}) - return f.incDirsRefcount(tr, path) - } - - return nil -} - -func (f *FDBBackend) internalClear(tr fdb.Transaction, decoratedPath []byte, path string) error { - // Same as above - check existence of the meta key before taking any - // action, to protect against a possible previous commit_unknown_result - // error. - - metaFKey := fdb.Key(concat(f.metaKeysSpace.Bytes(), decoratedPath...)) - - value, err := tr.Get(metaFKey).Get() - if err != nil { - return errwrap.Wrapf("Delete error while getting meta key: {{err}}", err) - } - - if value != nil { - dataFKey := fdb.Key(concat(f.dataSpace.Bytes(), decoratedPath...)) - tr.Clear(dataFKey) - tr.Clear(metaFKey) - return f.decDirsRefcount(tr, path) - } - - return nil -} - -type TxnTodo struct { - decoratedPath []byte - op *physical.TxnEntry -} - -// Used to run multiple entries via a transaction -func (f *FDBBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - if len(txns) == 0 { - return nil - } - - todo := make([]*TxnTodo, len(txns)) - - for i, op := range txns { - if op.Operation != physical.DeleteOperation && op.Operation != physical.PutOperation { - return fmt.Errorf("%q is not a supported transaction operation", op.Operation) - } - - decoratedPath, err := decoratePath(op.Entry.Key) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("could not build decorated path for transaction item %s: {{err}}", op.Entry.Key), err) - } - - todo[i] = &TxnTodo{ - decoratedPath: decoratedPath, - op: op, - } - } - - _, err := f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - for _, txnTodo := range todo { - var err error - switch txnTodo.op.Operation { - case physical.DeleteOperation: - err = f.internalClear(tr, txnTodo.decoratedPath, txnTodo.op.Entry.Key) - case physical.PutOperation: - err = f.internalPut(tr, txnTodo.decoratedPath, txnTodo.op.Entry.Key, txnTodo.op.Entry.Value) - } - - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("operation %s failed for transaction item %s: {{err}}", txnTodo.op.Operation, txnTodo.op.Entry.Key), err) - } - } - - return nil, nil - }) - - if err != nil { - return errwrap.Wrapf("transaction failed: {{err}}", err) - } - - return nil -} - -// Put is used to insert or update an entry -func (f *FDBBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"foundationdb", "put"}, time.Now()) - - decoratedPath, err := decoratePath(entry.Key) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("could not build decorated path to put item %s: {{err}}", entry.Key), err) - } - - _, err = f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - err := f.internalPut(tr, decoratedPath, entry.Key, entry.Value) - if err != nil { - return nil, err - } - - return nil, nil - }) - - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("put failed for item %s: {{err}}", entry.Key), err) - } - - return nil -} - -// Get is used to fetch an entry -// Return nil for non-existent keys -func (f *FDBBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"foundationdb", "get"}, time.Now()) - - decoratedPath, err := decoratePath(key) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("could not build decorated path to get item %s: {{err}}", key), err) - } - - fkey := fdb.Key(concat(f.dataSpace.Bytes(), decoratedPath...)) - - value, err := f.db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) { - value, err := rtr.Get(fkey).Get() - if err != nil { - return nil, err - } - - return value, nil - }) - - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("get failed for item %s: {{err}}", key), err) - } - if value.([]byte) == nil { - return nil, nil - } - - return &physical.Entry{ - Key: key, - Value: value.([]byte), - }, nil -} - -// Delete is used to permanently delete an entry -func (f *FDBBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"foundationdb", "delete"}, time.Now()) - - decoratedPath, err := decoratePath(key) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("could not build decorated path to delete item %s: {{err}}", key), err) - } - - _, err = f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - err := f.internalClear(tr, decoratedPath, key) - if err != nil { - return nil, err - } - - return nil, nil - }) - - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("delete failed for item %s: {{err}}", key), err) - } - - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -// Return empty string slice for non-existent directories -func (f *FDBBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"foundationdb", "list"}, time.Now()) - - prefix = strings.TrimRight("/"+prefix, "/") + "/" - - decoratedPrefix, err := decoratePrefix(prefix) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("could not build decorated path to list prefix %s: {{err}}", prefix), err) - } - - // The beginning of the range is /\x02foo/\x02bar/\x01 (the decorated prefix) to list foo/bar/ - rangeBegin := fdb.Key(concat(f.metaKeysSpace.Bytes(), decoratedPrefix...)) - rangeEnd := fdb.Key(concat(rangeBegin, 0xff)) - pathRange := fdb.KeyRange{rangeBegin, rangeEnd} - keyPrefixLen := len(rangeBegin) - - content, err := f.db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) { - dirList := make([]string, 0, 0) - - ri := rtr.GetRange(pathRange, fdb.RangeOptions{Mode: fdb.StreamingModeWantAll}).Iterator() - - for ri.Advance() { - kv := ri.MustGet() - - // Strip length of the rangeBegin key off the FDB key, yielding - // the part of the key we're interested in, which does not need - // to be undecorated, by construction. - dirList = append(dirList, string(kv.Key[keyPrefixLen:])) - } - - return dirList, nil - }) - - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("could not list prefix %s: {{err}}", prefix), err) - } - - return content.([]string), nil -} - -type FDBBackendLock struct { - f *FDBBackend - key string - value string - fkey fdb.Key - lock sync.Mutex -} - -// LockWith is used for mutual exclusion based on the given key. -func (f *FDBBackend) LockWith(key, value string) (physical.Lock, error) { - return &FDBBackendLock{ - f: f, - key: key, - value: value, - fkey: f.lockSpace.Pack(tuple.Tuple{key}), - }, nil -} - -func (f *FDBBackend) HAEnabled() bool { - return f.haEnabled -} - -const ( - // Position of elements in the lock content tuple - lockContentValueIdx = 0 - lockContentOwnerIdx = 1 - lockContentExpiresIdx = 2 - - // Number of elements in the lock content tuple - lockTupleContentElts = 3 - - lockTTL = 15 * time.Second - lockRenewInterval = 5 * time.Second - lockAcquireRetryInterval = 5 * time.Second -) - -type FDBBackendLockContent struct { - value string - ownerUUID string - expires time.Time -} - -func packLock(content *FDBBackendLockContent) []byte { - t := tuple.Tuple{content.value, content.ownerUUID, content.expires.UnixNano()} - - return t.Pack() -} - -func unpackLock(tupleContent []byte) (*FDBBackendLockContent, error) { - t, err := tuple.Unpack(tupleContent) - if err != nil { - return nil, err - } - - if len(t) != lockTupleContentElts { - return nil, fmt.Errorf("unexpected lock content, len %d != %d", len(t), lockTupleContentElts) - } - - return &FDBBackendLockContent{ - value: t[lockContentValueIdx].(string), - ownerUUID: t[lockContentOwnerIdx].(string), - expires: time.Unix(0, t[lockContentExpiresIdx].(int64)), - }, nil -} - -func (fl *FDBBackendLock) getLockContent(tr fdb.Transaction) (*FDBBackendLockContent, error) { - tupleContent, err := tr.Get(fl.fkey).Get() - if err != nil { - return nil, err - } - - // Lock doesn't exist - if tupleContent == nil { - return nil, fmt.Errorf("non-existent lock %s", fl.key) - } - - content, err := unpackLock(tupleContent) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to unpack lock %s: {{err}}", fl.key), err) - } - - return content, nil -} - -func (fl *FDBBackendLock) setLockContent(tr fdb.Transaction, content *FDBBackendLockContent) { - tr.Set(fl.fkey, packLock(content)) -} - -func (fl *FDBBackendLock) isOwned(content *FDBBackendLockContent) bool { - return content.ownerUUID == fl.f.instanceUUID -} - -func (fl *FDBBackendLock) isExpired(content *FDBBackendLockContent) bool { - return time.Now().After(content.expires) -} - -func (fl *FDBBackendLock) acquireTryLock(acquired chan struct{}, errors chan error) (bool, error) { - wonTheRace, err := fl.f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - tupleContent, err := tr.Get(fl.fkey).Get() - if err != nil { - return nil, errwrap.Wrapf("could not read lock: {{err}}", err) - } - - // Lock exists - if tupleContent != nil { - content, err := unpackLock(tupleContent) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to unpack lock %s: {{err}}", fl.key), err) - } - - if fl.isOwned(content) { - return nil, fmt.Errorf("lock %s already held", fl.key) - } - - // The lock already exists, is not owned by us, and is not expired - if !fl.isExpired(content) { - return false, nil - } - } - - // Lock doesn't exist, or exists but is expired, we can go ahead - content := &FDBBackendLockContent{ - value: fl.value, - ownerUUID: fl.f.instanceUUID, - expires: time.Now().Add(lockTTL), - } - - fl.setLockContent(tr, content) - - return true, nil - }) - - if err != nil { - errors <- err - return false, err - } - - if wonTheRace.(bool) { - close(acquired) - } - - return wonTheRace.(bool), nil -} - -func (fl *FDBBackendLock) acquireLock(abandon chan struct{}, acquired chan struct{}, errors chan error) { - ticker := time.NewTicker(lockAcquireRetryInterval) - defer ticker.Stop() - - lockAcquired, err := fl.acquireTryLock(acquired, errors) - if lockAcquired || err != nil { - return - } - - for { - select { - case <-abandon: - return - case <-ticker.C: - lockAcquired, err := fl.acquireTryLock(acquired, errors) - if lockAcquired || err != nil { - return - } - } - } -} - -func (fl *FDBBackendLock) maintainLock(lost <-chan struct{}) { - ticker := time.NewTicker(lockRenewInterval) - for { - select { - case <-ticker.C: - _, err := fl.f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - content, err := fl.getLockContent(tr) - if err != nil { - return nil, err - } - - // We don't own the lock - if !fl.isOwned(content) { - return nil, fmt.Errorf("lost lock %s", fl.key) - } - - // The lock is expired - if fl.isExpired(content) { - return nil, fmt.Errorf("lock %s expired", fl.key) - } - - content.expires = time.Now().Add(lockTTL) - - fl.setLockContent(tr, content) - - return nil, nil - }) - - if err != nil { - fl.f.logger.Error("lock maintain", "error", err) - } - - // Failure to renew the lock will cause another node to take over - // and the watch to fire. DB errors will also be caught by the watch. - case <-lost: - ticker.Stop() - return - } - } -} - -func (fl *FDBBackendLock) watchLock(lost chan struct{}) { - for { - watch, err := fl.f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - content, err := fl.getLockContent(tr) - if err != nil { - return nil, err - } - - // We don't own the lock - if !fl.isOwned(content) { - return nil, fmt.Errorf("lost lock %s", fl.key) - } - - // The lock is expired - if fl.isExpired(content) { - return nil, fmt.Errorf("lock %s expired", fl.key) - } - - // Set FDB watch on the lock - future := tr.Watch(fl.fkey) - - return future, nil - }) - - if err != nil { - fl.f.logger.Error("lock watch", "error", err) - break - } - - // Wait for the watch to fire, and go again - watch.(fdb.FutureNil).Get() - } - - close(lost) -} - -func (fl *FDBBackendLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - fl.lock.Lock() - defer fl.lock.Unlock() - - var ( - // Inform the lock owner that we lost the lock - lost = make(chan struct{}) - - // Tell our watch and renewal routines the lock has been abandoned - abandon = make(chan struct{}) - - // Feedback from lock acquisition routine - acquired = make(chan struct{}) - errors = make(chan error) - ) - - // try to acquire the lock asynchronously - go fl.acquireLock(abandon, acquired, errors) - - select { - case <-acquired: - // Maintain the lock after initial acquisition - go fl.maintainLock(lost) - // Watch the lock for changes - go fl.watchLock(lost) - case err := <-errors: - // Initial acquisition failed - close(abandon) - return nil, err - case <-stopCh: - // Prospective lock owner cancelling lock acquisition - close(abandon) - return nil, nil - } - - return lost, nil -} - -func (fl *FDBBackendLock) Unlock() error { - fl.lock.Lock() - defer fl.lock.Unlock() - - _, err := fl.f.db.Transact(func(tr fdb.Transaction) (interface{}, error) { - content, err := fl.getLockContent(tr) - if err != nil { - return nil, errwrap.Wrapf("could not get lock content: {{err}}", err) - } - - // We don't own the lock - if !fl.isOwned(content) { - return nil, nil - } - - tr.Clear(fl.fkey) - - return nil, nil - }) - - if err != nil { - return errwrap.Wrapf("unlock failed: {{err}}", err) - } - - return nil -} - -func (fl *FDBBackendLock) Value() (bool, string, error) { - tupleContent, err := fl.f.db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) { - tupleContent, err := rtr.Get(fl.fkey).Get() - if err != nil { - return nil, errwrap.Wrapf("could not read lock: {{err}}", err) - } - - return tupleContent, nil - }) - - if err != nil { - return false, "", errwrap.Wrapf(fmt.Sprintf("get lock value failed for lock %s: {{err}}", fl.key), err) - } - if tupleContent.([]byte) == nil { - return false, "", nil - } - - content, err := unpackLock(tupleContent.([]byte)) - if err != nil { - return false, "", errwrap.Wrapf(fmt.Sprintf("get lock value failed to unpack lock %s: {{err}}", fl.key), err) - } - - return true, content.value, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdbstub.go b/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdbstub.go deleted file mode 100644 index ed74990dd..000000000 --- a/vendor/github.com/hashicorp/vault/physical/foundationdb/foundationdbstub.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !foundationdb - -package foundationdb - -import ( - "fmt" - - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/vault/physical" -) - -func NewFDBBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - return nil, fmt.Errorf("FoundationDB backend not available in this Vault build") -} diff --git a/vendor/github.com/hashicorp/vault/physical/gcs/gcs.go b/vendor/github.com/hashicorp/vault/physical/gcs/gcs.go deleted file mode 100644 index 68930fb55..000000000 --- a/vendor/github.com/hashicorp/vault/physical/gcs/gcs.go +++ /dev/null @@ -1,296 +0,0 @@ -package gcs - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "os" - "sort" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/useragent" - "github.com/hashicorp/vault/physical" - - "cloud.google.com/go/storage" - "github.com/armon/go-metrics" - "google.golang.org/api/iterator" - "google.golang.org/api/option" -) - -// Verify Backend satisfies the correct interfaces -var _ physical.Backend = (*Backend)(nil) - -const ( - // envBucket is the name of the environment variable to search for the - // storage bucket name. - envBucket = "GOOGLE_STORAGE_BUCKET" - - // envChunkSize is the environment variable to serach for the chunk size for - // requests. - envChunkSize = "GOOGLE_STORAGE_CHUNK_SIZE" - - // envHAEnabled is the name of the environment variable to search for the - // boolean indicating if HA is enabled. - envHAEnabled = "GOOGLE_STORAGE_HA_ENABLED" - - // defaultChunkSize is the number of bytes the writer will attempt to write in - // a single request. - defaultChunkSize = "8192" - - // objectDelimiter is the string to use to delimit objects. - objectDelimiter = "/" -) - -var ( - // metricDelete is the key for the metric for measuring a Delete call. - metricDelete = []string{"gcs", "delete"} - - // metricGet is the key for the metric for measuring a Get call. - metricGet = []string{"gcs", "get"} - - // metricList is the key for the metric for measuring a List call. - metricList = []string{"gcs", "list"} - - // metricPut is the key for the metric for measuring a Put call. - metricPut = []string{"gcs", "put"} -) - -// Backend implements physical.Backend and describes the steps necessary to -// persist data in Google Cloud Storage. -type Backend struct { - // bucket is the name of the bucket to use for data storage and retrieval. - bucket string - - // chunkSize is the chunk size to use for requests. - chunkSize int - - // client is the underlying API client for talking to gcs. - client *storage.Client - - // haEnabled indicates if HA is enabled. - haEnabled bool - - // logger and permitPool are internal constructs - logger log.Logger - permitPool *physical.PermitPool -} - -// NewBackend constructs a Google Cloud Storage backend with the given -// configuration. This uses the official Golang Cloud SDK and therefore supports -// specifying credentials via envvars, credential files, etc. from environment -// variables or a service account file -func NewBackend(c map[string]string, logger log.Logger) (physical.Backend, error) { - logger.Debug("configuring backend") - - // Bucket name - bucket := os.Getenv(envBucket) - if bucket == "" { - bucket = c["bucket"] - } - if bucket == "" { - return nil, errors.New("missing bucket name") - } - - // Chunk size - chunkSizeStr := os.Getenv(envChunkSize) - if chunkSizeStr == "" { - chunkSizeStr = c["chunk_size"] - } - if chunkSizeStr == "" { - chunkSizeStr = defaultChunkSize - } - chunkSize, err := strconv.Atoi(chunkSizeStr) - if err != nil { - return nil, errwrap.Wrapf("failed to parse chunk_size: {{err}}", err) - } - - // Values are specified as kb, but the API expects them as bytes. - chunkSize = chunkSize * 1024 - - // HA configuration - haEnabled := false - haEnabledStr := os.Getenv(envHAEnabled) - if haEnabledStr == "" { - haEnabledStr = c["ha_enabled"] - } - if haEnabledStr != "" { - var err error - haEnabled, err = strconv.ParseBool(haEnabledStr) - if err != nil { - return nil, errwrap.Wrapf("failed to parse HA enabled: {{err}}", err) - } - } - - // Max parallel - maxParallel, err := extractInt(c["max_parallel"]) - if err != nil { - return nil, errwrap.Wrapf("failed to parse max_parallel: {{err}}", err) - } - - logger.Debug("configuration", - "bucket", bucket, - "chunk_size", chunkSize, - "ha_enabled", haEnabled, - "max_parallel", maxParallel, - ) - logger.Debug("creating client") - - // Client - opts := []option.ClientOption{option.WithUserAgent(useragent.String())} - if credentialsFile := c["credentials_file"]; credentialsFile != "" { - logger.Warn("physical.gcs: specifying credentials_file as an option is " + - "deprecated. Please use the GOOGLE_APPLICATION_CREDENTIALS environment " + - "variable or instance credentials instead.") - opts = append(opts, option.WithServiceAccountFile(credentialsFile)) - } - - ctx := context.Background() - client, err := storage.NewClient(ctx, opts...) - if err != nil { - return nil, errwrap.Wrapf("failed to create storage client: {{err}}", err) - } - - return &Backend{ - bucket: bucket, - haEnabled: haEnabled, - - client: client, - permitPool: physical.NewPermitPool(maxParallel), - logger: logger, - }, nil -} - -// Put is used to insert or update an entry -func (b *Backend) Put(ctx context.Context, entry *physical.Entry) (retErr error) { - defer metrics.MeasureSince(metricPut, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Insert - w := b.client.Bucket(b.bucket).Object(entry.Key).NewWriter(ctx) - w.ChunkSize = b.chunkSize - defer func() { - closeErr := w.Close() - if closeErr != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("error closing connection: {{err}}", closeErr)) - } - }() - - if _, err := w.Write(entry.Value); err != nil { - return errwrap.Wrapf("failed to put data: {{err}}", err) - } - return nil -} - -// Get fetches an entry. If no entry exists, this function returns nil. -func (b *Backend) Get(ctx context.Context, key string) (retEntry *physical.Entry, retErr error) { - defer metrics.MeasureSince(metricGet, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Read - r, err := b.client.Bucket(b.bucket).Object(key).NewReader(ctx) - if err == storage.ErrObjectNotExist { - return nil, nil - } - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read value for %q: {{err}}", key), err) - } - - defer func() { - closeErr := r.Close() - if closeErr != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("error closing connection: {{err}}", closeErr)) - } - }() - - value, err := ioutil.ReadAll(r) - if err != nil { - return nil, errwrap.Wrapf("failed to read value into a string: {{err}}", err) - } - - return &physical.Entry{ - Key: key, - Value: value, - }, nil -} - -// Delete deletes an entry with the given key -func (b *Backend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince(metricDelete, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Delete - err := b.client.Bucket(b.bucket).Object(key).Delete(ctx) - if err != nil && err != storage.ErrObjectNotExist { - return errwrap.Wrapf(fmt.Sprintf("failed to delete key %q: {{err}}", key), err) - } - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (b *Backend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince(metricList, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - iter := b.client.Bucket(b.bucket).Objects(ctx, &storage.Query{ - Prefix: prefix, - Delimiter: objectDelimiter, - Versions: false, - }) - - keys := []string{} - - for { - objAttrs, err := iter.Next() - if err == iterator.Done { - break - } - if err != nil { - return nil, errwrap.Wrapf("failed to read object: {{err}}", err) - } - - var path string - if objAttrs.Prefix != "" { - // "subdirectory" - path = objAttrs.Prefix - } else { - // file - path = objAttrs.Name - } - - // get relative file/dir just like "basename" - key := strings.TrimPrefix(path, prefix) - keys = append(keys, key) - } - - sort.Strings(keys) - - return keys, nil -} - -// extractInt is a helper function that takes a string and converts that string -// to an int, but accounts for the empty string. -func extractInt(s string) (int, error) { - if s == "" { - return 0, nil - } - return strconv.Atoi(s) -} diff --git a/vendor/github.com/hashicorp/vault/physical/gcs/gcs_ha.go b/vendor/github.com/hashicorp/vault/physical/gcs/gcs_ha.go deleted file mode 100644 index e6934df68..000000000 --- a/vendor/github.com/hashicorp/vault/physical/gcs/gcs_ha.go +++ /dev/null @@ -1,419 +0,0 @@ -package gcs - -import ( - "context" - "encoding/json" - "fmt" - "sync" - "time" - - "cloud.google.com/go/storage" - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/physical" - "github.com/pkg/errors" - "google.golang.org/api/googleapi" -) - -// Verify Backend satisfies the correct interfaces -var _ physical.HABackend = (*Backend)(nil) -var _ physical.Lock = (*Lock)(nil) - -const ( - // LockRenewInterval is the time to wait between lock renewals. - LockRenewInterval = 5 * time.Second - - // LockRetryInterval is the amount of time to wait if the lock fails before - // trying again. - LockRetryInterval = 5 * time.Second - - // LockTTL is the default lock TTL. - LockTTL = 15 * time.Second - - // LockWatchRetryInterval is the amount of time to wait if a watch fails - // before trying again. - LockWatchRetryInterval = 5 * time.Second - - // LockWatchRetryMax is the number of times to retry a failed watch before - // signaling that leadership is lost. - LockWatchRetryMax = 5 -) - -var ( - // metricLockUnlock is the metric to register for a lock delete. - metricLockUnlock = []string{"gcs", "lock", "unlock"} - - // metricLockGet is the metric to register for a lock get. - metricLockLock = []string{"gcs", "lock", "lock"} - - // metricLockValue is the metric to register for a lock create/update. - metricLockValue = []string{"gcs", "lock", "value"} -) - -// Lock is the HA lock. -type Lock struct { - // backend is the underlying physical backend. - backend *Backend - - // key is the name of the key. value is the value of the key. - key, value string - - // held is a boolean indicating if the lock is currently held. - held bool - - // identity is the internal identity of this key (unique to this server - // instance). - identity string - - // lock is an internal lock - lock sync.Mutex - - // stopCh is the channel that stops all operations. It may be closed in the - // event of a leader loss or graceful shutdown. stopped is a boolean - // indicating if we are stopped - it exists to prevent double closing the - // channel. stopLock is a mutex around the locks. - stopCh chan struct{} - stopped bool - stopLock sync.Mutex - - // Allow modifying the Lock durations for ease of unit testing. - renewInterval time.Duration - retryInterval time.Duration - ttl time.Duration - watchRetryInterval time.Duration - watchRetryMax int -} - -// LockRecord is the struct that corresponds to a lock. -type LockRecord struct { - Key string `json:"key"` - Value string `json:"value"` - Identity string `json:"identity"` - Timestamp time.Time `json:"timestamp"` - - // attrs are the internal object attributes. This is stored internally, for - // internal consumption only. - attrs *storage.ObjectAttrs -} - -// HAEnabled implements HABackend and indicates that this backend supports high -// availability. -func (b *Backend) HAEnabled() bool { - return b.haEnabled -} - -// LockWith acquires a mutual exclusion based on the given key. -func (b *Backend) LockWith(key, value string) (physical.Lock, error) { - identity, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("lock with: {{err}}", err) - } - return &Lock{ - backend: b, - key: key, - value: value, - identity: identity, - stopped: true, - - renewInterval: LockRenewInterval, - retryInterval: LockRetryInterval, - ttl: LockTTL, - watchRetryInterval: LockWatchRetryInterval, - watchRetryMax: LockWatchRetryMax, - }, nil -} - -// Lock acquires the given lock. The stopCh is optional. If closed, it -// interrupts the lock acquisition attempt. The returned channel should be -// closed when leadership is lost. -func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - defer metrics.MeasureSince(metricLockLock, time.Now()) - - l.lock.Lock() - defer l.lock.Unlock() - if l.held { - return nil, errors.New("lock already held") - } - - // Attempt to lock - this function blocks until a lock is acquired or an error - // occurs. - acquired, err := l.attemptLock(stopCh) - if err != nil { - return nil, errwrap.Wrapf("lock: {{err}}", err) - } - if !acquired { - return nil, nil - } - - // We have the lock now - l.held = true - - // Build the locks - l.stopLock.Lock() - l.stopCh = make(chan struct{}) - l.stopped = false - l.stopLock.Unlock() - - // Periodically renew and watch the lock - go l.renewLock() - go l.watchLock() - - return l.stopCh, nil -} - -// Unlock releases the lock. -func (l *Lock) Unlock() error { - defer metrics.MeasureSince(metricLockUnlock, time.Now()) - - l.lock.Lock() - defer l.lock.Unlock() - if !l.held { - return nil - } - - // Stop any existing locking or renewal attempts - l.stopLock.Lock() - if !l.stopped { - l.stopped = true - close(l.stopCh) - } - l.stopLock.Unlock() - - // Read the record value before deleting. This needs to be a CAS operation or - // else we might be deleting someone else's lock. - ctx := context.Background() - r, err := l.get(ctx) - if err != nil { - return errwrap.Wrapf("failed to read lock for deletion: {{err}}", err) - } - if r != nil && r.Identity == l.identity { - ctx := context.Background() - conds := storage.Conditions{ - GenerationMatch: r.attrs.Generation, - MetagenerationMatch: r.attrs.Metageneration, - } - - obj := l.backend.client.Bucket(l.backend.bucket).Object(l.key) - if err := obj.If(conds).Delete(ctx); err != nil { - // If the pre-condition failed, it means that someone else has already - // acquired the lock and we don't want to delete it. - if terr, ok := err.(*googleapi.Error); ok && terr.Code == 412 { - l.backend.logger.Debug("unlock: preconditions failed (lock already taken by someone else?)") - } else { - return errwrap.Wrapf("failed to delete lock: {{err}}", err) - } - } - } - - // We are no longer holding the lock - l.held = false - - return nil -} - -// Value returns the value of the lock and if it is held. -func (l *Lock) Value() (bool, string, error) { - defer metrics.MeasureSince(metricLockValue, time.Now()) - - r, err := l.get(context.Background()) - if err != nil { - return false, "", err - } - if r == nil { - return false, "", err - } - return true, string(r.Value), nil -} - -// attemptLock attempts to acquire a lock. If the given channel is closed, the -// acquisition attempt stops. This function returns when a lock is acquired or -// an error occurs. -func (l *Lock) attemptLock(stopCh <-chan struct{}) (bool, error) { - ticker := time.NewTicker(l.retryInterval) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - acquired, err := l.writeLock() - if err != nil { - return false, errwrap.Wrapf("attempt lock: {{err}}", err) - } - if !acquired { - continue - } - - return true, nil - case <-stopCh: - return false, nil - } - } -} - -// renewLock renews the given lock until the channel is closed. -func (l *Lock) renewLock() { - ticker := time.NewTicker(l.renewInterval) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - l.writeLock() - case <-l.stopCh: - return - } - } -} - -// watchLock checks whether the lock has changed in the table and closes the -// leader channel accordingly. If an error occurs during the check, watchLock -// will retry the operation and then close the leader channel if it can't -// succeed after retries. -func (l *Lock) watchLock() { - retries := 0 - ticker := time.NewTicker(l.watchRetryInterval) - -OUTER: - for { - // Check if the channel is already closed - select { - case <-l.stopCh: - break OUTER - default: - } - - // Check if we've exceeded retries - if retries >= l.watchRetryMax-1 { - break OUTER - } - - // Wait for the timer - select { - case <-ticker.C: - case <-l.stopCh: - break OUTER - } - - // Attempt to read the key - r, err := l.get(context.Background()) - if err != nil { - retries++ - continue - } - - // Verify the identity is the same - if r == nil || r.Identity != l.identity { - break OUTER - } - } - - l.stopLock.Lock() - defer l.stopLock.Unlock() - if !l.stopped { - l.stopped = true - close(l.stopCh) - } -} - -// writeLock writes the given lock using the following algorithm: -// -// - lock does not exist -// - write the lock -// - lock exists -// - if key is empty or identity is the same or timestamp exceeds TTL -// - update the lock to self -func (l *Lock) writeLock() (bool, error) { - // Pooling - l.backend.permitPool.Acquire() - defer l.backend.permitPool.Release() - - // Create a transaction to read and the update (maybe) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - // The operation may be retried, so we need to stop it if we lose leadership. - go func() { - select { - case <-l.stopCh: - cancel() - case <-ctx.Done(): - } - }() - - // Build up the list of conditions - var conds storage.Conditions - - // Read the record - r, err := l.get(ctx) - if err != nil { - return false, errwrap.Wrapf("write lock: {{err}}", err) - } - if r != nil { - // If the key is empty or the identity is ours or the ttl expired, we can - // write. Otherwise, return now because we cannot. - if r.Key != "" && r.Identity != l.identity && time.Now().UTC().Sub(r.Timestamp) < l.ttl { - return false, nil - } - - // CAS operation - conds.GenerationMatch = r.attrs.Generation - conds.MetagenerationMatch = r.attrs.Metageneration - } else { - // Ensure no one created while we were working - conds.DoesNotExist = true - } - - // Update the lock to now - lockData, err := json.Marshal(&LockRecord{ - Key: l.key, - Value: l.value, - Identity: l.identity, - Timestamp: time.Now().UTC(), - }) - if err != nil { - return false, errwrap.Wrapf("write lock: failed to encode JSON: {{err}}", err) - } - - // Write the object - obj := l.backend.client.Bucket(l.backend.bucket).Object(l.key) - w := obj.If(conds).NewWriter(ctx) - w.ObjectAttrs.CacheControl = "no-cache; no-store; max-age=0" - w.ObjectAttrs.Metadata = map[string]string{ - "lock": string(lockData), - } - if err := w.Close(); err != nil { - // If the pre-condition failed, it means that we already have a lock. - if terr, ok := err.(*googleapi.Error); ok && terr.Code == 412 { - return false, nil - } - return false, err - } - - return true, nil -} - -// get retrieves the value for the lock. -func (l *Lock) get(ctx context.Context) (*LockRecord, error) { - // Pooling - l.backend.permitPool.Acquire() - defer l.backend.permitPool.Release() - - // Read - attrs, err := l.backend.client.Bucket(l.backend.bucket).Object(l.key).Attrs(ctx) - if err == storage.ErrObjectNotExist { - return nil, nil - } - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read attrs for %q: {{err}}", l.key), err) - } - - // If we got this far, we have attributes, meaning the lockfile exists. - var r LockRecord - r.attrs = attrs - lockData := []byte(attrs.Metadata["lock"]) - if err := json.Unmarshal(lockData, &r); err != nil { - return nil, errwrap.Wrapf("failed to decode lock: {{err}}", err) - } - return &r, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/inmem/inmem.go b/vendor/github.com/hashicorp/vault/physical/inmem/inmem.go deleted file mode 100644 index 0616738c1..000000000 --- a/vendor/github.com/hashicorp/vault/physical/inmem/inmem.go +++ /dev/null @@ -1,247 +0,0 @@ -package inmem - -import ( - "context" - "errors" - "strings" - "sync" - "sync/atomic" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" - - "github.com/armon/go-radix" -) - -// Verify interfaces are satisfied -var _ physical.Backend = (*InmemBackend)(nil) -var _ physical.HABackend = (*InmemHABackend)(nil) -var _ physical.HABackend = (*TransactionalInmemHABackend)(nil) -var _ physical.Lock = (*InmemLock)(nil) -var _ physical.Transactional = (*TransactionalInmemBackend)(nil) -var _ physical.Transactional = (*TransactionalInmemHABackend)(nil) - -var ( - PutDisabledError = errors.New("put operations disabled in inmem backend") - GetDisabledError = errors.New("get operations disabled in inmem backend") - DeleteDisabledError = errors.New("delete operations disabled in inmem backend") - ListDisabledError = errors.New("list operations disabled in inmem backend") -) - -// InmemBackend is an in-memory only physical backend. It is useful -// for testing and development situations where the data is not -// expected to be durable. -type InmemBackend struct { - sync.RWMutex - root *radix.Tree - permitPool *physical.PermitPool - logger log.Logger - failGet *uint32 - failPut *uint32 - failDelete *uint32 - failList *uint32 -} - -type TransactionalInmemBackend struct { - InmemBackend -} - -// NewInmem constructs a new in-memory backend -func NewInmem(_ map[string]string, logger log.Logger) (physical.Backend, error) { - in := &InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(physical.DefaultParallelOperations), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - } - return in, nil -} - -// Basically for now just creates a permit pool of size 1 so only one operation -// can run at a time -func NewTransactionalInmem(_ map[string]string, logger log.Logger) (physical.Backend, error) { - in := &TransactionalInmemBackend{ - InmemBackend: InmemBackend{ - root: radix.New(), - permitPool: physical.NewPermitPool(1), - logger: logger, - failGet: new(uint32), - failPut: new(uint32), - failDelete: new(uint32), - failList: new(uint32), - }, - } - return in, nil -} - -// Put is used to insert or update an entry -func (i *InmemBackend) Put(ctx context.Context, entry *physical.Entry) error { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.Lock() - defer i.Unlock() - - return i.PutInternal(ctx, entry) -} - -func (i *InmemBackend) PutInternal(ctx context.Context, entry *physical.Entry) error { - if atomic.LoadUint32(i.failPut) != 0 { - return PutDisabledError - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - i.root.Insert(entry.Key, entry.Value) - return nil -} - -func (i *InmemBackend) FailPut(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failPut, val) -} - -// Get is used to fetch an entry -func (i *InmemBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.RLock() - defer i.RUnlock() - - return i.GetInternal(ctx, key) -} - -func (i *InmemBackend) GetInternal(ctx context.Context, key string) (*physical.Entry, error) { - if atomic.LoadUint32(i.failGet) != 0 { - return nil, GetDisabledError - } - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - if raw, ok := i.root.Get(key); ok { - return &physical.Entry{ - Key: key, - Value: raw.([]byte), - }, nil - } - return nil, nil -} - -func (i *InmemBackend) FailGet(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failGet, val) -} - -// Delete is used to permanently delete an entry -func (i *InmemBackend) Delete(ctx context.Context, key string) error { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.Lock() - defer i.Unlock() - - return i.DeleteInternal(ctx, key) -} - -func (i *InmemBackend) DeleteInternal(ctx context.Context, key string) error { - if atomic.LoadUint32(i.failDelete) != 0 { - return DeleteDisabledError - } - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - i.root.Delete(key) - return nil -} - -func (i *InmemBackend) FailDelete(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failDelete, val) -} - -// List is used ot list all the keys under a given -// prefix, up to the next prefix. -func (i *InmemBackend) List(ctx context.Context, prefix string) ([]string, error) { - i.permitPool.Acquire() - defer i.permitPool.Release() - - i.RLock() - defer i.RUnlock() - - return i.ListInternal(ctx, prefix) -} - -func (i *InmemBackend) ListInternal(ctx context.Context, prefix string) ([]string, error) { - if atomic.LoadUint32(i.failList) != 0 { - return nil, ListDisabledError - } - - var out []string - seen := make(map[string]interface{}) - walkFn := func(s string, v interface{}) bool { - trimmed := strings.TrimPrefix(s, prefix) - sep := strings.Index(trimmed, "/") - if sep == -1 { - out = append(out, trimmed) - } else { - trimmed = trimmed[:sep+1] - if _, ok := seen[trimmed]; !ok { - out = append(out, trimmed) - seen[trimmed] = struct{}{} - } - } - return false - } - i.root.WalkPrefix(prefix, walkFn) - - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - return out, nil -} - -func (i *InmemBackend) FailList(fail bool) { - var val uint32 - if fail { - val = 1 - } - atomic.StoreUint32(i.failList, val) -} - -// Implements the transaction interface -func (t *TransactionalInmemBackend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - t.permitPool.Acquire() - defer t.permitPool.Release() - - t.Lock() - defer t.Unlock() - - return physical.GenericTransactionHandler(ctx, t, txns) -} diff --git a/vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go b/vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go deleted file mode 100644 index 675510070..000000000 --- a/vendor/github.com/hashicorp/vault/physical/inmem/inmem_ha.go +++ /dev/null @@ -1,167 +0,0 @@ -package inmem - -import ( - "fmt" - "sync" - - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" -) - -type InmemHABackend struct { - physical.Backend - locks map[string]string - l *sync.Mutex - cond *sync.Cond - logger log.Logger -} - -type TransactionalInmemHABackend struct { - physical.Transactional - InmemHABackend -} - -// NewInmemHA constructs a new in-memory HA backend. This is only for testing. -func NewInmemHA(_ map[string]string, logger log.Logger) (physical.Backend, error) { - be, err := NewInmem(nil, logger) - if err != nil { - return nil, err - } - - in := &InmemHABackend{ - Backend: be, - locks: make(map[string]string), - logger: logger, - l: new(sync.Mutex), - } - in.cond = sync.NewCond(in.l) - return in, nil -} - -func NewTransactionalInmemHA(_ map[string]string, logger log.Logger) (physical.Backend, error) { - transInmem, err := NewTransactionalInmem(nil, logger) - if err != nil { - return nil, err - } - inmemHA := InmemHABackend{ - Backend: transInmem, - locks: make(map[string]string), - logger: logger, - l: new(sync.Mutex), - } - - in := &TransactionalInmemHABackend{ - InmemHABackend: inmemHA, - Transactional: transInmem.(physical.Transactional), - } - in.cond = sync.NewCond(in.l) - return in, nil -} - -// LockWith is used for mutual exclusion based on the given key. -func (i *InmemHABackend) LockWith(key, value string) (physical.Lock, error) { - l := &InmemLock{ - in: i, - key: key, - value: value, - } - return l, nil -} - -// LockMapSize is used in some tests to determine whether this backend has ever -// been used for HA purposes rather than simply for storage -func (i *InmemHABackend) LockMapSize() int { - return len(i.locks) -} - -// HAEnabled indicates whether the HA functionality should be exposed. -// Currently always returns true. -func (i *InmemHABackend) HAEnabled() bool { - return true -} - -// InmemLock is an in-memory Lock implementation for the HABackend -type InmemLock struct { - in *InmemHABackend - key string - value string - - held bool - leaderCh chan struct{} - l sync.Mutex -} - -func (i *InmemLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - i.l.Lock() - defer i.l.Unlock() - if i.held { - return nil, fmt.Errorf("lock already held") - } - - // Attempt an async acquisition - didLock := make(chan struct{}) - releaseCh := make(chan bool, 1) - go func() { - // Wait to acquire the lock - i.in.l.Lock() - _, ok := i.in.locks[i.key] - for ok { - i.in.cond.Wait() - _, ok = i.in.locks[i.key] - } - i.in.locks[i.key] = i.value - i.in.l.Unlock() - - // Signal that lock is held - close(didLock) - - // Handle an early abort - release := <-releaseCh - if release { - i.in.l.Lock() - delete(i.in.locks, i.key) - i.in.l.Unlock() - i.in.cond.Broadcast() - } - }() - - // Wait for lock acquisition or shutdown - select { - case <-didLock: - releaseCh <- false - case <-stopCh: - releaseCh <- true - return nil, nil - } - - // Create the leader channel - i.held = true - i.leaderCh = make(chan struct{}) - return i.leaderCh, nil -} - -func (i *InmemLock) Unlock() error { - i.l.Lock() - defer i.l.Unlock() - - if !i.held { - return nil - } - - close(i.leaderCh) - i.leaderCh = nil - i.held = false - - i.in.l.Lock() - delete(i.in.locks, i.key) - i.in.l.Unlock() - i.in.cond.Broadcast() - return nil -} - -func (i *InmemLock) Value() (bool, string, error) { - i.in.l.Lock() - val, ok := i.in.locks[i.key] - i.in.l.Unlock() - return ok, val, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/latency.go b/vendor/github.com/hashicorp/vault/physical/latency.go deleted file mode 100644 index 7aa9fab98..000000000 --- a/vendor/github.com/hashicorp/vault/physical/latency.go +++ /dev/null @@ -1,95 +0,0 @@ -package physical - -import ( - "context" - "math/rand" - "time" - - log "github.com/hashicorp/go-hclog" -) - -const ( - // DefaultJitterPercent is used if no cache size is specified for NewCache - DefaultJitterPercent = 20 -) - -// LatencyInjector is used to add latency into underlying physical requests -type LatencyInjector struct { - backend Backend - latency time.Duration - jitterPercent int - random *rand.Rand -} - -// TransactionalLatencyInjector is the transactional version of the latency -// injector -type TransactionalLatencyInjector struct { - *LatencyInjector - Transactional -} - -// Verify LatencyInjector satisfies the correct interfaces -var _ Backend = (*LatencyInjector)(nil) -var _ Transactional = (*TransactionalLatencyInjector)(nil) - -// NewLatencyInjector returns a wrapped physical backend to simulate latency -func NewLatencyInjector(b Backend, latency time.Duration, jitter int, logger log.Logger) *LatencyInjector { - if jitter < 0 || jitter > 100 { - jitter = DefaultJitterPercent - } - logger.Info("creating latency injector") - - return &LatencyInjector{ - backend: b, - latency: latency, - jitterPercent: jitter, - random: rand.New(rand.NewSource(int64(time.Now().Nanosecond()))), - } -} - -// NewTransactionalLatencyInjector creates a new transactional LatencyInjector -func NewTransactionalLatencyInjector(b Backend, latency time.Duration, jitter int, logger log.Logger) *TransactionalLatencyInjector { - return &TransactionalLatencyInjector{ - LatencyInjector: NewLatencyInjector(b, latency, jitter, logger), - Transactional: b.(Transactional), - } -} - -func (l *LatencyInjector) addLatency() { - // Calculate a value between 1 +- jitter% - min := 100 - l.jitterPercent - max := 100 + l.jitterPercent - percent := l.random.Intn(max-min) + min - latencyDuration := time.Duration(int(l.latency) * percent / 100) - time.Sleep(latencyDuration) -} - -// Put is a latent put request -func (l *LatencyInjector) Put(ctx context.Context, entry *Entry) error { - l.addLatency() - return l.backend.Put(ctx, entry) -} - -// Get is a latent get request -func (l *LatencyInjector) Get(ctx context.Context, key string) (*Entry, error) { - l.addLatency() - return l.backend.Get(ctx, key) -} - -// Delete is a latent delete request -func (l *LatencyInjector) Delete(ctx context.Context, key string) error { - l.addLatency() - return l.backend.Delete(ctx, key) -} - -// List is a latent list request -func (l *LatencyInjector) List(ctx context.Context, prefix string) ([]string, error) { - l.addLatency() - return l.backend.List(ctx, prefix) -} - -// Transaction is a latent transaction request -func (l *TransactionalLatencyInjector) Transaction(ctx context.Context, txns []*TxnEntry) error { - l.addLatency() - return l.Transactional.Transaction(ctx, txns) -} diff --git a/vendor/github.com/hashicorp/vault/physical/manta/manta.go b/vendor/github.com/hashicorp/vault/physical/manta/manta.go deleted file mode 100644 index bb17e7499..000000000 --- a/vendor/github.com/hashicorp/vault/physical/manta/manta.go +++ /dev/null @@ -1,264 +0,0 @@ -package manta - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "path" - "sort" - "strconv" - "strings" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" - "github.com/joyent/triton-go" - "github.com/joyent/triton-go/authentication" - "github.com/joyent/triton-go/errors" - "github.com/joyent/triton-go/storage" -) - -const mantaDefaultRootStore = "/stor" - -type MantaBackend struct { - logger log.Logger - permitPool *physical.PermitPool - client *storage.StorageClient - directory string -} - -func NewMantaBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - user := os.Getenv("MANTA_USER") - if user == "" { - user = conf["user"] - } - - keyId := os.Getenv("MANTA_KEY_ID") - if keyId == "" { - keyId = conf["key_id"] - } - - url := os.Getenv("MANTA_URL") - if url == "" { - url = conf["url"] - } else { - url = "https://us-east.manta.joyent.com" - } - - subuser := os.Getenv("MANTA_SUBUSER") - if subuser == "" { - if confUser, ok := conf["subuser"]; ok { - subuser = confUser - } - } - - input := authentication.SSHAgentSignerInput{ - KeyID: keyId, - AccountName: user, - Username: subuser, - } - signer, err := authentication.NewSSHAgentSigner(input) - if err != nil { - return nil, errwrap.Wrapf("Error Creating SSH Agent Signer: {{err}}", err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - config := &triton.ClientConfig{ - MantaURL: url, - AccountName: user, - Signers: []authentication.Signer{signer}, - } - - client, err := storage.NewClient(config) - if err != nil { - return nil, errwrap.Wrapf("failed initialising Storage client: {{err}}", err) - } - - return &MantaBackend{ - client: client, - directory: conf["directory"], - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - }, nil -} - -// Put is used to insert or update an entry -func (m *MantaBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"manta", "put"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - r := bytes.NewReader(entry.Value) - r.Seek(0, 0) - - return m.client.Objects().Put(ctx, &storage.PutObjectInput{ - ObjectPath: path.Join(mantaDefaultRootStore, m.directory, entry.Key, ".vault_value"), - ObjectReader: r, - ContentLength: uint64(len(entry.Value)), - ForceInsert: true, - }) -} - -// Get is used to fetch an entry -func (m *MantaBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"manta", "get"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - output, err := m.client.Objects().Get(ctx, &storage.GetObjectInput{ - ObjectPath: path.Join(mantaDefaultRootStore, m.directory, key, ".vault_value"), - }) - if err != nil { - if strings.Contains(err.Error(), "ResourceNotFound") { - return nil, nil - } - return nil, err - } - - defer output.ObjectReader.Close() - - data := make([]byte, output.ContentLength) - _, err = io.ReadFull(output.ObjectReader, data) - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: data, - } - - return ent, nil -} - -// Delete is used to permanently delete an entry -func (m *MantaBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"manta", "delete"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - if strings.HasSuffix(key, "/") { - err := m.client.Dir().Delete(ctx, &storage.DeleteDirectoryInput{ - DirectoryName: path.Join(mantaDefaultRootStore, m.directory, key), - ForceDelete: true, - }) - if err != nil { - return err - } - } else { - err := m.client.Objects().Delete(ctx, &storage.DeleteObjectInput{ - ObjectPath: path.Join(mantaDefaultRootStore, m.directory, key, ".vault_value"), - }) - if err != nil { - if errors.IsResourceNotFound(err) { - return nil - } - return err - } - - return tryDeleteDirectory(ctx, m, path.Join(mantaDefaultRootStore, m.directory, key)) - } - - return nil -} - -func tryDeleteDirectory(ctx context.Context, m *MantaBackend, directoryPath string) error { - objs, err := m.client.Dir().List(ctx, &storage.ListDirectoryInput{ - DirectoryName: directoryPath, - }) - if err != nil { - if errors.IsResourceNotFound(err) { - return nil - } - return err - } - if objs != nil && len(objs.Entries) == 0 { - err := m.client.Dir().Delete(ctx, &storage.DeleteDirectoryInput{ - DirectoryName: directoryPath, - }) - if err != nil { - return err - } - - return tryDeleteDirectory(ctx, m, path.Dir(directoryPath)) - } - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (m *MantaBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"manta", "list"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - objs, err := m.client.Dir().List(ctx, &storage.ListDirectoryInput{ - DirectoryName: path.Join(mantaDefaultRootStore, m.directory, prefix), - }) - if err != nil { - if errors.IsResourceNotFound(err) { - return []string{}, nil - } - return nil, err - } - - keys := []string{} - for _, obj := range objs.Entries { - if obj.Type == "directory" { - objs, err := m.client.Dir().List(ctx, &storage.ListDirectoryInput{ - DirectoryName: path.Join(mantaDefaultRootStore, m.directory, prefix, obj.Name), - }) - if err != nil { - if !errors.IsResourceNotFound(err) { - return nil, err - } - } - - //We need to check to see if there is something more than just the `value` file - //if the length of the children is: - // > 1 and includes the value `index` then we need to add foo and foo/ - // = 1 and the value is `index` then we need to add foo - // = 1 and the value is not `index` then we need to add foo/ - if len(objs.Entries) == 1 { - if objs.Entries[0].Name != ".vault_value" { - keys = append(keys, fmt.Sprintf("%s/", obj.Name)) - } else { - keys = append(keys, obj.Name) - } - } else if len(objs.Entries) > 1 { - for _, childObj := range objs.Entries { - if childObj.Name == ".vault_value" { - keys = append(keys, obj.Name) - } else { - keys = append(keys, fmt.Sprintf("%s/", obj.Name)) - } - } - } else { - keys = append(keys, obj.Name) - } - } - } - - sort.Strings(keys) - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/mssql/mssql.go b/vendor/github.com/hashicorp/vault/physical/mssql/mssql.go deleted file mode 100644 index a3d73c163..000000000 --- a/vendor/github.com/hashicorp/vault/physical/mssql/mssql.go +++ /dev/null @@ -1,257 +0,0 @@ -package mssql - -import ( - "context" - "database/sql" - "fmt" - "sort" - "strconv" - "strings" - "time" - - "github.com/armon/go-metrics" - _ "github.com/denisenkom/go-mssqldb" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -// Verify MSSQLBackend satisfies the correct interfaces -var _ physical.Backend = (*MSSQLBackend)(nil) - -type MSSQLBackend struct { - dbTable string - client *sql.DB - statements map[string]*sql.Stmt - logger log.Logger - permitPool *physical.PermitPool -} - -func NewMSSQLBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - username, ok := conf["username"] - if !ok { - username = "" - } - - password, ok := conf["password"] - if !ok { - password = "" - } - - server, ok := conf["server"] - if !ok || server == "" { - return nil, fmt.Errorf("missing server") - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - var err error - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } else { - maxParInt = physical.DefaultParallelOperations - } - - database, ok := conf["database"] - if !ok { - database = "Vault" - } - - table, ok := conf["table"] - if !ok { - table = "Vault" - } - - appname, ok := conf["appname"] - if !ok { - appname = "Vault" - } - - connectionTimeout, ok := conf["connectiontimeout"] - if !ok { - connectionTimeout = "30" - } - - logLevel, ok := conf["loglevel"] - if !ok { - logLevel = "0" - } - - schema, ok := conf["schema"] - if !ok || schema == "" { - schema = "dbo" - } - - connectionString := fmt.Sprintf("server=%s;app name=%s;connection timeout=%s;log=%s", server, appname, connectionTimeout, logLevel) - if username != "" { - connectionString += ";user id=" + username - } - - if password != "" { - connectionString += ";password=" + password - } - - db, err := sql.Open("mssql", connectionString) - if err != nil { - return nil, errwrap.Wrapf("failed to connect to mssql: {{err}}", err) - } - - db.SetMaxOpenConns(maxParInt) - - if _, err := db.Exec("IF NOT EXISTS(SELECT * FROM sys.databases WHERE name = '" + database + "') CREATE DATABASE " + database); err != nil { - return nil, errwrap.Wrapf("failed to create mssql database: {{err}}", err) - } - - dbTable := database + "." + schema + "." + table - createQuery := "IF NOT EXISTS(SELECT 1 FROM " + database + ".INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='" + table + "' AND TABLE_SCHEMA='" + schema + - "') CREATE TABLE " + dbTable + " (Path VARCHAR(512) PRIMARY KEY, Value VARBINARY(MAX))" - - if schema != "dbo" { - if _, err := db.Exec("USE " + database); err != nil { - return nil, errwrap.Wrapf("failed to switch mssql database: {{err}}", err) - } - - var num int - err = db.QueryRow("SELECT 1 FROM sys.schemas WHERE name = '" + schema + "'").Scan(&num) - - switch { - case err == sql.ErrNoRows: - if _, err := db.Exec("CREATE SCHEMA " + schema); err != nil { - return nil, errwrap.Wrapf("failed to create mssql schema: {{err}}", err) - } - - case err != nil: - return nil, errwrap.Wrapf("failed to check if mssql schema exists: {{err}}", err) - } - } - - if _, err := db.Exec(createQuery); err != nil { - return nil, errwrap.Wrapf("failed to create mssql table: {{err}}", err) - } - - m := &MSSQLBackend{ - dbTable: dbTable, - client: db, - statements: make(map[string]*sql.Stmt), - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - - statements := map[string]string{ - "put": "IF EXISTS(SELECT 1 FROM " + dbTable + " WHERE Path = ?) UPDATE " + dbTable + " SET Value = ? WHERE Path = ?" + - " ELSE INSERT INTO " + dbTable + " VALUES(?, ?)", - "get": "SELECT Value FROM " + dbTable + " WHERE Path = ?", - "delete": "DELETE FROM " + dbTable + " WHERE Path = ?", - "list": "SELECT Path FROM " + dbTable + " WHERE Path LIKE ?", - } - - for name, query := range statements { - if err := m.prepare(name, query); err != nil { - return nil, err - } - } - - return m, nil -} - -func (m *MSSQLBackend) prepare(name, query string) error { - stmt, err := m.client.Prepare(query) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) - } - - m.statements[name] = stmt - - return nil -} - -func (m *MSSQLBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"mssql", "put"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, err := m.statements["put"].Exec(entry.Key, entry.Value, entry.Key, entry.Key, entry.Value) - if err != nil { - return err - } - - return nil -} - -func (m *MSSQLBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"mssql", "get"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - var result []byte - err := m.statements["get"].QueryRow(key).Scan(&result) - if err == sql.ErrNoRows { - return nil, nil - } - - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: result, - } - - return ent, nil -} - -func (m *MSSQLBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"mssql", "delete"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, err := m.statements["delete"].Exec(key) - if err != nil { - return err - } - - return nil -} - -func (m *MSSQLBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"mssql", "list"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - likePrefix := prefix + "%" - rows, err := m.statements["list"].Query(likePrefix) - if err != nil { - return nil, err - } - var keys []string - for rows.Next() { - var key string - err = rows.Scan(&key) - if err != nil { - return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) - } - - key = strings.TrimPrefix(key, prefix) - if i := strings.Index(key, "/"); i == -1 { - keys = append(keys, key) - } else if i != -1 { - keys = strutil.AppendIfMissing(keys, string(key[:i+1])) - } - } - - sort.Strings(keys) - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/mysql/mysql.go b/vendor/github.com/hashicorp/vault/physical/mysql/mysql.go deleted file mode 100644 index 6500d2915..000000000 --- a/vendor/github.com/hashicorp/vault/physical/mysql/mysql.go +++ /dev/null @@ -1,701 +0,0 @@ -package mysql - -import ( - "context" - "crypto/tls" - "crypto/x509" - "database/sql" - "errors" - "fmt" - "io/ioutil" - "net/url" - "sort" - "strconv" - "strings" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - mysql "github.com/go-sql-driver/mysql" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -// Verify MySQLBackend satisfies the correct interfaces -var _ physical.Backend = (*MySQLBackend)(nil) -var _ physical.HABackend = (*MySQLBackend)(nil) -var _ physical.Lock = (*MySQLHALock)(nil) - -// Unreserved tls key -// Reserved values are "true", "false", "skip-verify" -const mysqlTLSKey = "default" - -// MySQLBackend is a physical backend that stores data -// within MySQL database. -type MySQLBackend struct { - dbTable string - dbLockTable string - client *sql.DB - statements map[string]*sql.Stmt - logger log.Logger - permitPool *physical.PermitPool - conf map[string]string - redirectHost string - redirectPort int64 - haEnabled bool -} - -// NewMySQLBackend constructs a MySQL backend using the given API client and -// server address and credential for accessing mysql database. -func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - var err error - - db, err := NewMySQLClient(conf, logger) - if err != nil { - return nil, err - } - - database, ok := conf["database"] - if !ok { - database = "vault" - } - table, ok := conf["table"] - if !ok { - table = "vault" - } - dbTable := "`" + database + "`.`" + table + "`" - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } else { - maxParInt = physical.DefaultParallelOperations - } - - // Check schema exists - var schemaExist bool - schemaRows, err := db.Query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?", database) - if err != nil { - return nil, errwrap.Wrapf("failed to check mysql schema exist: {{err}}", err) - } - defer schemaRows.Close() - schemaExist = schemaRows.Next() - - // Check table exists - var tableExist bool - tableRows, err := db.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", table, database) - - if err != nil { - return nil, errwrap.Wrapf("failed to check mysql table exist: {{err}}", err) - } - defer tableRows.Close() - tableExist = tableRows.Next() - - // Create the required database if it doesn't exists. - if !schemaExist { - if _, err := db.Exec("CREATE DATABASE IF NOT EXISTS `" + database + "`"); err != nil { - return nil, errwrap.Wrapf("failed to create mysql database: {{err}}", err) - } - } - - // Create the required table if it doesn't exists. - if !tableExist { - create_query := "CREATE TABLE IF NOT EXISTS " + dbTable + - " (vault_key varbinary(512), vault_value mediumblob, PRIMARY KEY (vault_key))" - if _, err := db.Exec(create_query); err != nil { - return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err) - } - } - - // Default value for ha_enabled - haEnabledStr, ok := conf["ha_enabled"] - if !ok { - haEnabledStr = "false" - } - haEnabled, err := strconv.ParseBool(haEnabledStr) - if err != nil { - return nil, fmt.Errorf("value [%v] of 'ha_enabled' could not be understood", haEnabledStr) - } - - locktable, ok := conf["lock_table"] - if !ok { - locktable = table + "_lock" - } - - dbLockTable := "`" + database + "`.`" + locktable + "`" - - // Only create lock table if ha_enabled is true - if haEnabled { - // Check table exists - var lockTableExist bool - lockTableRows, err := db.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", locktable, database) - - if err != nil { - return nil, errwrap.Wrapf("failed to check mysql table exist: {{err}}", err) - } - defer lockTableRows.Close() - lockTableExist = lockTableRows.Next() - - // Create the required table if it doesn't exists. - if !lockTableExist { - create_query := "CREATE TABLE IF NOT EXISTS " + dbLockTable + - " (node_job varchar(512), current_leader varchar(512), PRIMARY KEY (node_job))" - if _, err := db.Exec(create_query); err != nil { - return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err) - } - } - } - - // Setup the backend. - m := &MySQLBackend{ - dbTable: dbTable, - dbLockTable: dbLockTable, - client: db, - statements: make(map[string]*sql.Stmt), - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - conf: conf, - haEnabled: haEnabled, - } - - // Prepare all the statements required - statements := map[string]string{ - "put": "INSERT INTO " + dbTable + - " VALUES( ?, ? ) ON DUPLICATE KEY UPDATE vault_value=VALUES(vault_value)", - "get": "SELECT vault_value FROM " + dbTable + " WHERE vault_key = ?", - "delete": "DELETE FROM " + dbTable + " WHERE vault_key = ?", - "list": "SELECT vault_key FROM " + dbTable + " WHERE vault_key LIKE ?", - } - - // Only prepare ha-related statements if we need them - if haEnabled { - statements["get_lock"] = "SELECT current_leader FROM " + dbLockTable + " WHERE node_job = ?" - statements["used_lock"] = "SELECT IS_USED_LOCK(?)" - } - - for name, query := range statements { - if err := m.prepare(name, query); err != nil { - return nil, err - } - } - - return m, nil -} - -func NewMySQLClient(conf map[string]string, logger log.Logger) (*sql.DB, error) { - var err error - - // Get the MySQL credentials to perform read/write operations. - username, ok := conf["username"] - if !ok || username == "" { - return nil, fmt.Errorf("missing username") - } - password, ok := conf["password"] - if !ok || password == "" { - return nil, fmt.Errorf("missing password") - } - - // Get or set MySQL server address. Defaults to localhost and default port(3306) - address, ok := conf["address"] - if !ok { - address = "127.0.0.1:3306" - } - - maxIdleConnStr, ok := conf["max_idle_connections"] - var maxIdleConnInt int - if ok { - maxIdleConnInt, err = strconv.Atoi(maxIdleConnStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_idle_connections parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_idle_connections set", "max_idle_connections", maxIdleConnInt) - } - } - - maxConnLifeStr, ok := conf["max_connection_lifetime"] - var maxConnLifeInt int - if ok { - maxConnLifeInt, err = strconv.Atoi(maxConnLifeStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_connection_lifetime parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_connection_lifetime set", "max_connection_lifetime", maxConnLifeInt) - } - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } else { - maxParInt = physical.DefaultParallelOperations - } - - dsnParams := url.Values{} - tlsCaFile, ok := conf["tls_ca_file"] - if ok { - if err := setupMySQLTLSConfig(tlsCaFile); err != nil { - return nil, errwrap.Wrapf("failed register TLS config: {{err}}", err) - } - - dsnParams.Add("tls", mysqlTLSKey) - } - - // Create MySQL handle for the database. - dsn := username + ":" + password + "@tcp(" + address + ")/?" + dsnParams.Encode() - db, err := sql.Open("mysql", dsn) - if err != nil { - return nil, errwrap.Wrapf("failed to connect to mysql: {{err}}", err) - } - db.SetMaxOpenConns(maxParInt) - if maxIdleConnInt != 0 { - db.SetMaxIdleConns(maxIdleConnInt) - } - if maxConnLifeInt != 0 { - db.SetConnMaxLifetime(time.Duration(maxConnLifeInt) * time.Second) - } - - return db, err -} - -// prepare is a helper to prepare a query for future execution -func (m *MySQLBackend) prepare(name, query string) error { - stmt, err := m.client.Prepare(query) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) - } - m.statements[name] = stmt - return nil -} - -// Put is used to insert or update an entry. -func (m *MySQLBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"mysql", "put"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, err := m.statements["put"].Exec(entry.Key, entry.Value) - if err != nil { - return err - } - return nil -} - -// Get is used to fetch an entry. -func (m *MySQLBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"mysql", "get"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - var result []byte - err := m.statements["get"].QueryRow(key).Scan(&result) - if err == sql.ErrNoRows { - return nil, nil - } - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: result, - } - return ent, nil -} - -// Delete is used to permanently delete an entry -func (m *MySQLBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"mysql", "delete"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, err := m.statements["delete"].Exec(key) - if err != nil { - return err - } - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (m *MySQLBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"mysql", "list"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - // Add the % wildcard to the prefix to do the prefix search - likePrefix := prefix + "%" - rows, err := m.statements["list"].Query(likePrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to execute statement: {{err}}", err) - } - - var keys []string - for rows.Next() { - var key string - err = rows.Scan(&key) - if err != nil { - return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) - } - - key = strings.TrimPrefix(key, prefix) - if i := strings.Index(key, "/"); i == -1 { - // Add objects only from the current 'folder' - keys = append(keys, key) - } else if i != -1 { - // Add truncated 'folder' paths - keys = strutil.AppendIfMissing(keys, string(key[:i+1])) - } - } - - sort.Strings(keys) - return keys, nil -} - -// LockWith is used for mutual exclusion based on the given key. -func (m *MySQLBackend) LockWith(key, value string) (physical.Lock, error) { - l := &MySQLHALock{ - in: m, - key: key, - value: value, - logger: m.logger, - } - return l, nil -} - -func (m *MySQLBackend) HAEnabled() bool { - return m.haEnabled -} - -// MySQLHALock is a MySQL Lock implementation for the HABackend -type MySQLHALock struct { - in *MySQLBackend - key string - value string - logger log.Logger - - held bool - localLock sync.Mutex - leaderCh chan struct{} - stopCh <-chan struct{} - lock *MySQLLock -} - -func (i *MySQLHALock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - i.localLock.Lock() - defer i.localLock.Unlock() - if i.held { - return nil, fmt.Errorf("lock already held") - } - - // Attempt an async acquisition - didLock := make(chan struct{}) - failLock := make(chan error, 1) - releaseCh := make(chan bool, 1) - go i.attemptLock(i.key, i.value, didLock, failLock, releaseCh) - - // Wait for lock acquisition, failure, or shutdown - select { - case <-didLock: - releaseCh <- false - case err := <-failLock: - return nil, err - case <-stopCh: - releaseCh <- true - return nil, nil - } - - // Create the leader channel - i.held = true - i.leaderCh = make(chan struct{}) - - go i.monitorLock(i.leaderCh) - - i.stopCh = stopCh - - return i.leaderCh, nil -} - -func (i *MySQLHALock) attemptLock(key, value string, didLock chan struct{}, failLock chan error, releaseCh chan bool) { - lock, err := NewMySQLLock(i.in, i.logger, key, value) - - // Set node value - i.lock = lock - - if err != nil { - failLock <- err - } - - err = lock.Lock() - if err != nil { - failLock <- err - return - } - - // Signal that lock is held - close(didLock) - - // Handle an early abort - release := <-releaseCh - if release { - lock.Unlock() - } -} - -func (i *MySQLHALock) monitorLock(leaderCh chan struct{}) { - for { - // The only way to lose this lock is if someone is - // logging into the DB and altering system tables or you lose a connection in - // which case you will lose the lock anyway. - err := i.hasLock(i.key) - if err != nil { - // Somehow we lost the lock.... likely because the connection holding - // the lock was closed or someone was playing around with the locks in the DB. - close(leaderCh) - return - } - - time.Sleep(5 * time.Second) - } -} - -func (i *MySQLHALock) Unlock() error { - i.localLock.Lock() - defer i.localLock.Unlock() - if !i.held { - return nil - } - - err := i.lock.Unlock() - - if err == nil { - i.held = false - return nil - } - - return err -} - -// hasLock will check if a lock is held by checking the current lock id against our known ID. -func (i *MySQLHALock) hasLock(key string) error { - var result sql.NullInt64 - err := i.in.statements["used_lock"].QueryRow(key).Scan(&result) - if err == sql.ErrNoRows || !result.Valid { - // This is not an error to us since it just means the lock isn't held - return nil - } - - if err != nil { - return err - } - - // IS_USED_LOCK will return the ID of the connection that created the lock. - if result.Int64 != GlobalLockID { - return ErrLockHeld - } - - return nil -} - -func (i *MySQLHALock) GetLeader() (string, error) { - defer metrics.MeasureSince([]string{"mysql", "lock_get"}, time.Now()) - var result string - err := i.in.statements["get_lock"].QueryRow("leader").Scan(&result) - if err == sql.ErrNoRows { - return "", err - } - - return result, nil -} - -func (i *MySQLHALock) Value() (bool, string, error) { - leaderkey, err := i.GetLeader() - if err != nil { - return false, "", err - } - - return true, leaderkey, err -} - -// MySQLLock provides an easy way to grab and release mysql -// locks using the built in GET_LOCK function. Note that these -// locks are released when you lose connection to the server. -type MySQLLock struct { - parentConn *MySQLBackend - in *sql.DB - logger log.Logger - statements map[string]*sql.Stmt - key string - value string -} - -// Errors specific to trying to grab a lock in MySQL -var ( - // This is the GlobalLockID for checking if the lock we got is still the current lock - GlobalLockID int64 - // ErrLockHeld is returned when another vault instance already has a lock held for the given key. - ErrLockHeld = errors.New("mysql: lock already held") - // ErrUnlockFailed - ErrUnlockFailed = errors.New("mysql: unable to release lock, already released or not held by this session") - // You were unable to update that you are the new leader in the DB - ErrClaimFailed = errors.New("mysql: unable to update DB with new leader infromation") - // Error to thow if inbetween getting the lock and checking the ID of it we lost it. - ErrSettingGlobalID = errors.New("mysql: getting global lock id failed") -) - -// NewMySQLLock helper function -func NewMySQLLock(in *MySQLBackend, l log.Logger, key, value string) (*MySQLLock, error) { - // Create a new MySQL connection so we can close this and have no effect on - // the rest of the MySQL backend and any cleanup that might need to be done. - conn, _ := NewMySQLClient(in.conf, in.logger) - - m := &MySQLLock{ - parentConn: in, - in: conn, - logger: l, - statements: make(map[string]*sql.Stmt), - key: key, - value: value, - } - - statements := map[string]string{ - "put": "INSERT INTO " + in.dbLockTable + - " VALUES( ?, ? ) ON DUPLICATE KEY UPDATE current_leader=VALUES(current_leader)", - } - - for name, query := range statements { - if err := m.prepare(name, query); err != nil { - return nil, err - } - } - - return m, nil -} - -// prepare is a helper to prepare a query for future execution -func (m *MySQLLock) prepare(name, query string) error { - stmt, err := m.in.Prepare(query) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err) - } - m.statements[name] = stmt - return nil -} - -// update the current cluster leader in the DB. This is used so -// we can tell the servers in standby who the active leader is. -func (i *MySQLLock) becomeLeader() error { - _, err := i.statements["put"].Exec("leader", i.value) - if err != nil { - return err - } - - return nil -} - -// Lock will try to get a lock for an indefinite amount of time -// based on the given key that has been requested. -func (i *MySQLLock) Lock() error { - defer metrics.MeasureSince([]string{"mysql", "get_lock"}, time.Now()) - - rows, err := i.in.Query("SELECT GET_LOCK(?, -1), IS_USED_LOCK(?)", i.key, i.key) - if err != nil { - return err - } - - defer rows.Close() - rows.Next() - var lock sql.NullInt64 - var connectionID sql.NullInt64 - rows.Scan(&lock, &connectionID) - - if rows.Err() != nil { - return rows.Err() - } - - // 1 is returned from GET_LOCK if it was able to get the lock - // 0 if it failed and NULL if some stange error happened. - // https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_get-lock - if !lock.Valid || lock.Int64 != 1 { - return ErrLockHeld - } - - // Since we have the lock alert the rest of the cluster - // that we are now the active leader. - err = i.becomeLeader() - if err != nil { - return ErrLockHeld - } - - // This will return the connection ID of NULL if an error happens - // https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-used-lock - if !connectionID.Valid { - return ErrSettingGlobalID - } - - GlobalLockID = connectionID.Int64 - - return nil -} - -// Unlock just closes the connection. This is because closing the MySQL connection -// is a 100% reliable way to close the lock. If you just release the lock you must -// do it from the same mysql connection_id that you originally created it from. This -// is a huge hastle and I actually couldn't find a clean way to do this although one -// likely does exist. Closing the connection however ensures we don't ever get into a -// state where we try to release the lock and it hangs it is also much less code. -func (i *MySQLLock) Unlock() error { - err := i.in.Close() - if err != nil { - return ErrUnlockFailed - } - - return nil -} - -// Establish a TLS connection with a given CA certificate -// Register a tsl.Config associated with the same key as the dns param from sql.Open -// foo:bar@tcp(127.0.0.1:3306)/dbname?tls=default -func setupMySQLTLSConfig(tlsCaFile string) error { - rootCertPool := x509.NewCertPool() - - pem, err := ioutil.ReadFile(tlsCaFile) - if err != nil { - return err - } - - if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { - return err - } - - err = mysql.RegisterTLSConfig(mysqlTLSKey, &tls.Config{ - RootCAs: rootCertPool, - }) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/physical.go b/vendor/github.com/hashicorp/vault/physical/physical.go deleted file mode 100644 index 9325186a4..000000000 --- a/vendor/github.com/hashicorp/vault/physical/physical.go +++ /dev/null @@ -1,158 +0,0 @@ -package physical - -import ( - "context" - "strings" - "sync" - - log "github.com/hashicorp/go-hclog" -) - -const DefaultParallelOperations = 128 - -// The operation type -type Operation string - -const ( - DeleteOperation Operation = "delete" - GetOperation = "get" - ListOperation = "list" - PutOperation = "put" -) - -// ShutdownSignal -type ShutdownChannel chan struct{} - -// Backend is the interface required for a physical -// backend. A physical backend is used to durably store -// data outside of Vault. As such, it is completely untrusted, -// and is only accessed via a security barrier. The backends -// must represent keys in a hierarchical manner. All methods -// are expected to be thread safe. -type Backend interface { - // Put is used to insert or update an entry - Put(ctx context.Context, entry *Entry) error - - // Get is used to fetch an entry - Get(ctx context.Context, key string) (*Entry, error) - - // Delete is used to permanently delete an entry - Delete(ctx context.Context, key string) error - - // List is used to list all the keys under a given - // prefix, up to the next prefix. - List(ctx context.Context, prefix string) ([]string, error) -} - -// HABackend is an extensions to the standard physical -// backend to support high-availability. Vault only expects to -// use mutual exclusion to allow multiple instances to act as a -// hot standby for a leader that services all requests. -type HABackend interface { - // LockWith is used for mutual exclusion based on the given key. - LockWith(key, value string) (Lock, error) - - // Whether or not HA functionality is enabled - HAEnabled() bool -} - -// ToggleablePurgemonster is an interface for backends that can toggle on or -// off special functionality and/or support purging. This is only used for the -// cache, don't use it for other things. -type ToggleablePurgemonster interface { - Purge(ctx context.Context) - SetEnabled(bool) -} - -// RedirectDetect is an optional interface that an HABackend -// can implement. If they do, a redirect address can be automatically -// detected. -type RedirectDetect interface { - // DetectHostAddr is used to detect the host address - DetectHostAddr() (string, error) -} - -// Callback signatures for RunServiceDiscovery -type ActiveFunction func() bool -type SealedFunction func() bool - -// ServiceDiscovery is an optional interface that an HABackend can implement. -// If they do, the state of a backend is advertised to the service discovery -// network. -type ServiceDiscovery interface { - // NotifyActiveStateChange is used by Core to notify a backend - // capable of ServiceDiscovery that this Vault instance has changed - // its status to active or standby. - NotifyActiveStateChange() error - - // NotifySealedStateChange is used by Core to notify a backend - // capable of ServiceDiscovery that Vault has changed its Sealed - // status to sealed or unsealed. - NotifySealedStateChange() error - - // Run executes any background service discovery tasks until the - // shutdown channel is closed. - RunServiceDiscovery(waitGroup *sync.WaitGroup, shutdownCh ShutdownChannel, redirectAddr string, activeFunc ActiveFunction, sealedFunc SealedFunction) error -} - -type Lock interface { - // Lock is used to acquire the given lock - // The stopCh is optional and if closed should interrupt the lock - // acquisition attempt. The return struct should be closed when - // leadership is lost. - Lock(stopCh <-chan struct{}) (<-chan struct{}, error) - - // Unlock is used to release the lock - Unlock() error - - // Returns the value of the lock and if it is held - Value() (bool, string, error) -} - -// Entry is used to represent data stored by the physical backend -type Entry struct { - Key string - Value []byte - SealWrap bool `json:"seal_wrap,omitempty"` -} - -// Factory is the factory function to create a physical backend. -type Factory func(config map[string]string, logger log.Logger) (Backend, error) - -// PermitPool is used to limit maximum outstanding requests -type PermitPool struct { - sem chan int -} - -// NewPermitPool returns a new permit pool with the provided -// number of permits -func NewPermitPool(permits int) *PermitPool { - if permits < 1 { - permits = DefaultParallelOperations - } - return &PermitPool{ - sem: make(chan int, permits), - } -} - -// Acquire returns when a permit has been acquired -func (c *PermitPool) Acquire() { - c.sem <- 1 -} - -// Release returns a permit to the pool -func (c *PermitPool) Release() { - <-c.sem -} - -// Prefixes is a shared helper function returns all parent 'folders' for a -// given vault key. -// e.g. for 'foo/bar/baz', it returns ['foo', 'foo/bar'] -func Prefixes(s string) []string { - components := strings.Split(s, "/") - result := []string{} - for i := 1; i < len(components); i++ { - result = append(result, strings.Join(components[:i], "/")) - } - return result -} diff --git a/vendor/github.com/hashicorp/vault/physical/physical_access.go b/vendor/github.com/hashicorp/vault/physical/physical_access.go deleted file mode 100644 index 58ac9739a..000000000 --- a/vendor/github.com/hashicorp/vault/physical/physical_access.go +++ /dev/null @@ -1,38 +0,0 @@ -package physical - -import "context" - -// PhysicalAccess is a wrapper around physical.Backend that allows Core to -// expose its physical storage operations through PhysicalAccess() while -// restricting the ability to modify Core.physical itself. -type PhysicalAccess struct { - physical Backend -} - -var _ Backend = (*PhysicalAccess)(nil) - -func NewPhysicalAccess(physical Backend) *PhysicalAccess { - return &PhysicalAccess{physical: physical} -} - -func (p *PhysicalAccess) Put(ctx context.Context, entry *Entry) error { - return p.physical.Put(ctx, entry) -} - -func (p *PhysicalAccess) Get(ctx context.Context, key string) (*Entry, error) { - return p.physical.Get(ctx, key) -} - -func (p *PhysicalAccess) Delete(ctx context.Context, key string) error { - return p.physical.Delete(ctx, key) -} - -func (p *PhysicalAccess) List(ctx context.Context, prefix string) ([]string, error) { - return p.physical.List(ctx, prefix) -} - -func (p *PhysicalAccess) Purge(ctx context.Context) { - if purgeable, ok := p.physical.(ToggleablePurgemonster); ok { - purgeable.Purge(ctx) - } -} diff --git a/vendor/github.com/hashicorp/vault/physical/physical_view.go b/vendor/github.com/hashicorp/vault/physical/physical_view.go deleted file mode 100644 index da505a4f1..000000000 --- a/vendor/github.com/hashicorp/vault/physical/physical_view.go +++ /dev/null @@ -1,98 +0,0 @@ -package physical - -import ( - "context" - "errors" - "strings" -) - -var ( - ErrRelativePath = errors.New("relative paths not supported") -) - -// View represents a prefixed view of a physical backend -type View struct { - backend Backend - prefix string -} - -// Verify View satisfies the correct interfaces -var _ Backend = (*View)(nil) - -// NewView takes an underlying physical backend and returns -// a view of it that can only operate with the given prefix. -func NewView(backend Backend, prefix string) *View { - return &View{ - backend: backend, - prefix: prefix, - } -} - -// List the contents of the prefixed view -func (v *View) List(ctx context.Context, prefix string) ([]string, error) { - if err := v.sanityCheck(prefix); err != nil { - return nil, err - } - return v.backend.List(ctx, v.expandKey(prefix)) -} - -// Get the key of the prefixed view -func (v *View) Get(ctx context.Context, key string) (*Entry, error) { - if err := v.sanityCheck(key); err != nil { - return nil, err - } - entry, err := v.backend.Get(ctx, v.expandKey(key)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - if entry != nil { - entry.Key = v.truncateKey(entry.Key) - } - - return &Entry{ - Key: entry.Key, - Value: entry.Value, - }, nil -} - -// Put the entry into the prefix view -func (v *View) Put(ctx context.Context, entry *Entry) error { - if err := v.sanityCheck(entry.Key); err != nil { - return err - } - - nested := &Entry{ - Key: v.expandKey(entry.Key), - Value: entry.Value, - } - return v.backend.Put(ctx, nested) -} - -// Delete the entry from the prefix view -func (v *View) Delete(ctx context.Context, key string) error { - if err := v.sanityCheck(key); err != nil { - return err - } - return v.backend.Delete(ctx, v.expandKey(key)) -} - -// sanityCheck is used to perform a sanity check on a key -func (v *View) sanityCheck(key string) error { - if strings.Contains(key, "..") { - return ErrRelativePath - } - return nil -} - -// expandKey is used to expand to the full key path with the prefix -func (v *View) expandKey(suffix string) string { - return v.prefix + suffix -} - -// truncateKey is used to remove the prefix of the key -func (v *View) truncateKey(full string) string { - return strings.TrimPrefix(full, v.prefix) -} diff --git a/vendor/github.com/hashicorp/vault/physical/postgresql/postgresql.go b/vendor/github.com/hashicorp/vault/physical/postgresql/postgresql.go deleted file mode 100644 index a4332be88..000000000 --- a/vendor/github.com/hashicorp/vault/physical/postgresql/postgresql.go +++ /dev/null @@ -1,215 +0,0 @@ -package postgresql - -import ( - "context" - "database/sql" - "fmt" - "strconv" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/physical" - //log "github.com/hashicorp/go-hclog" - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/lib/pq" -) - -// Verify PostgreSQLBackend satisfies the correct interfaces -var _ physical.Backend = (*PostgreSQLBackend)(nil) - -// PostgreSQL Backend is a physical backend that stores data -// within a PostgreSQL database. -type PostgreSQLBackend struct { - table string - client *sql.DB - put_query string - get_query string - delete_query string - list_query string - logger log.Logger - permitPool *physical.PermitPool -} - -// NewPostgreSQLBackend constructs a PostgreSQL backend using the given -// API client, server address, credentials, and database. -func NewPostgreSQLBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the PostgreSQL credentials to perform read/write operations. - connURL, ok := conf["connection_url"] - if !ok || connURL == "" { - return nil, fmt.Errorf("missing connection_url") - } - - unquoted_table, ok := conf["table"] - if !ok { - unquoted_table = "vault_kv_store" - } - quoted_table := pq.QuoteIdentifier(unquoted_table) - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - var err error - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } else { - maxParInt = physical.DefaultParallelOperations - } - - // Create PostgreSQL handle for the database. - db, err := sql.Open("postgres", connURL) - if err != nil { - return nil, errwrap.Wrapf("failed to connect to postgres: {{err}}", err) - } - db.SetMaxOpenConns(maxParInt) - - // Determine if we should use an upsert function (versions < 9.5) - var upsert_required bool - upsert_required_query := "SELECT current_setting('server_version_num')::int < 90500" - if err := db.QueryRow(upsert_required_query).Scan(&upsert_required); err != nil { - return nil, errwrap.Wrapf("failed to check for native upsert: {{err}}", err) - } - - // Setup our put strategy based on the presence or absence of a native - // upsert. - var put_query string - if upsert_required { - put_query = "SELECT vault_kv_put($1, $2, $3, $4)" - } else { - put_query = "INSERT INTO " + quoted_table + " VALUES($1, $2, $3, $4)" + - " ON CONFLICT (path, key) DO " + - " UPDATE SET (parent_path, path, key, value) = ($1, $2, $3, $4)" - } - - // Setup the backend. - m := &PostgreSQLBackend{ - table: quoted_table, - client: db, - put_query: put_query, - get_query: "SELECT value FROM " + quoted_table + " WHERE path = $1 AND key = $2", - delete_query: "DELETE FROM " + quoted_table + " WHERE path = $1 AND key = $2", - list_query: "SELECT key FROM " + quoted_table + " WHERE path = $1" + - "UNION SELECT DISTINCT substring(substr(path, length($1)+1) from '^.*?/') FROM " + - quoted_table + " WHERE parent_path LIKE $1 || '%'", - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - - return m, nil -} - -// splitKey is a helper to split a full path key into individual -// parts: parentPath, path, key -func (m *PostgreSQLBackend) splitKey(fullPath string) (string, string, string) { - var parentPath string - var path string - - pieces := strings.Split(fullPath, "/") - depth := len(pieces) - key := pieces[depth-1] - - if depth == 1 { - parentPath = "" - path = "/" - } else if depth == 2 { - parentPath = "/" - path = "/" + pieces[0] + "/" - } else { - parentPath = "/" + strings.Join(pieces[:depth-2], "/") + "/" - path = "/" + strings.Join(pieces[:depth-1], "/") + "/" - } - - return parentPath, path, key -} - -// Put is used to insert or update an entry. -func (m *PostgreSQLBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"postgres", "put"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - parentPath, path, key := m.splitKey(entry.Key) - - _, err := m.client.Exec(m.put_query, parentPath, path, key, entry.Value) - if err != nil { - return err - } - return nil -} - -// Get is used to fetch and entry. -func (m *PostgreSQLBackend) Get(ctx context.Context, fullPath string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"postgres", "get"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, path, key := m.splitKey(fullPath) - - var result []byte - err := m.client.QueryRow(m.get_query, path, key).Scan(&result) - if err == sql.ErrNoRows { - return nil, nil - } - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: result, - } - return ent, nil -} - -// Delete is used to permanently delete an entry -func (m *PostgreSQLBackend) Delete(ctx context.Context, fullPath string) error { - defer metrics.MeasureSince([]string{"postgres", "delete"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - _, path, key := m.splitKey(fullPath) - - _, err := m.client.Exec(m.delete_query, path, key) - if err != nil { - return err - } - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (m *PostgreSQLBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"postgres", "list"}, time.Now()) - - m.permitPool.Acquire() - defer m.permitPool.Release() - - rows, err := m.client.Query(m.list_query, "/"+prefix) - if err != nil { - return nil, err - } - defer rows.Close() - - var keys []string - for rows.Next() { - var key string - err = rows.Scan(&key) - if err != nil { - return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err) - } - - keys = append(keys, key) - } - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/s3/s3.go b/vendor/github.com/hashicorp/vault/physical/s3/s3.go deleted file mode 100644 index c30a20387..000000000 --- a/vendor/github.com/hashicorp/vault/physical/s3/s3.go +++ /dev/null @@ -1,281 +0,0 @@ -package s3 - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "os" - "sort" - "strconv" - "strings" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/awsutil" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/physical" -) - -// Verify S3Backend satisfies the correct interfaces -var _ physical.Backend = (*S3Backend)(nil) - -// S3Backend is a physical backend that stores data -// within an S3 bucket. -type S3Backend struct { - bucket string - client *s3.S3 - logger log.Logger - permitPool *physical.PermitPool -} - -// NewS3Backend constructs a S3 backend using a pre-existing -// bucket. Credentials can be provided to the backend, sourced -// from the environment, AWS credential files or by IAM role. -func NewS3Backend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - bucket := os.Getenv("AWS_S3_BUCKET") - if bucket == "" { - bucket = conf["bucket"] - if bucket == "" { - return nil, fmt.Errorf("'bucket' must be set") - } - } - - accessKey, ok := conf["access_key"] - if !ok { - accessKey = "" - } - secretKey, ok := conf["secret_key"] - if !ok { - secretKey = "" - } - sessionToken, ok := conf["session_token"] - if !ok { - sessionToken = "" - } - endpoint := os.Getenv("AWS_S3_ENDPOINT") - if endpoint == "" { - endpoint = conf["endpoint"] - } - region := os.Getenv("AWS_REGION") - if region == "" { - region = os.Getenv("AWS_DEFAULT_REGION") - if region == "" { - region = conf["region"] - if region == "" { - region = "us-east-1" - } - } - } - s3ForcePathStyleStr, ok := conf["s3_force_path_style"] - if !ok { - s3ForcePathStyleStr = "false" - } - s3ForcePathStyleBool, err := parseutil.ParseBool(s3ForcePathStyleStr) - if err != nil { - return nil, fmt.Errorf("invalid boolean set for s3_force_path_style: %q", s3ForcePathStyleStr) - } - disableSSLStr, ok := conf["disable_ssl"] - if !ok { - disableSSLStr = "false" - } - disableSSLBool, err := parseutil.ParseBool(disableSSLStr) - if err != nil { - return nil, fmt.Errorf("invalid boolean set for disable_ssl: %q", disableSSLStr) - } - - credsConfig := &awsutil.CredentialsConfig{ - AccessKey: accessKey, - SecretKey: secretKey, - SessionToken: sessionToken, - } - creds, err := credsConfig.GenerateCredentialChain() - if err != nil { - return nil, err - } - - pooledTransport := cleanhttp.DefaultPooledTransport() - pooledTransport.MaxIdleConnsPerHost = consts.ExpirationRestoreWorkerCount - - s3conn := s3.New(session.New(&aws.Config{ - Credentials: creds, - HTTPClient: &http.Client{ - Transport: pooledTransport, - }, - Endpoint: aws.String(endpoint), - Region: aws.String(region), - S3ForcePathStyle: aws.Bool(s3ForcePathStyleBool), - DisableSSL: aws.Bool(disableSSLBool), - })) - - _, err = s3conn.ListObjects(&s3.ListObjectsInput{Bucket: &bucket}) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("unable to access bucket %q in region %q: {{err}}", bucket, region), err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - s := &S3Backend{ - client: s3conn, - bucket: bucket, - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - return s, nil -} - -// Put is used to insert or update an entry -func (s *S3Backend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"s3", "put"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - _, err := s.client.PutObject(&s3.PutObjectInput{ - Bucket: aws.String(s.bucket), - Key: aws.String(entry.Key), - Body: bytes.NewReader(entry.Value), - }) - - if err != nil { - return err - } - - return nil -} - -// Get is used to fetch an entry -func (s *S3Backend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"s3", "get"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - resp, err := s.client.GetObject(&s3.GetObjectInput{ - Bucket: aws.String(s.bucket), - Key: aws.String(key), - }) - if resp != nil && resp.Body != nil { - defer resp.Body.Close() - } - if awsErr, ok := err.(awserr.RequestFailure); ok { - // Return nil on 404s, error on anything else - if awsErr.StatusCode() == 404 { - return nil, nil - } - return nil, err - } - if err != nil { - return nil, err - } - if resp == nil { - return nil, fmt.Errorf("got nil response from S3 but no error") - } - - data := bytes.NewBuffer(nil) - if resp.ContentLength != nil { - data = bytes.NewBuffer(make([]byte, 0, *resp.ContentLength)) - } - _, err = io.Copy(data, resp.Body) - if err != nil { - return nil, err - } - - ent := &physical.Entry{ - Key: key, - Value: data.Bytes(), - } - - return ent, nil -} - -// Delete is used to permanently delete an entry -func (s *S3Backend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"s3", "delete"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - _, err := s.client.DeleteObject(&s3.DeleteObjectInput{ - Bucket: aws.String(s.bucket), - Key: aws.String(key), - }) - - if err != nil { - return err - } - - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (s *S3Backend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"s3", "list"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - params := &s3.ListObjectsV2Input{ - Bucket: aws.String(s.bucket), - Prefix: aws.String(prefix), - Delimiter: aws.String("/"), - } - - keys := []string{} - - err := s.client.ListObjectsV2Pages(params, - func(page *s3.ListObjectsV2Output, lastPage bool) bool { - if page != nil { - // Add truncated 'folder' paths - for _, commonPrefix := range page.CommonPrefixes { - // Avoid panic - if commonPrefix == nil { - continue - } - - commonPrefix := strings.TrimPrefix(*commonPrefix.Prefix, prefix) - keys = append(keys, commonPrefix) - } - // Add objects only from the current 'folder' - for _, key := range page.Contents { - // Avoid panic - if key == nil { - continue - } - - key := strings.TrimPrefix(*key.Key, prefix) - keys = append(keys, key) - } - } - return true - }) - - if err != nil { - return nil, err - } - - sort.Strings(keys) - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/spanner/spanner.go b/vendor/github.com/hashicorp/vault/physical/spanner/spanner.go deleted file mode 100644 index 4724bec18..000000000 --- a/vendor/github.com/hashicorp/vault/physical/spanner/spanner.go +++ /dev/null @@ -1,347 +0,0 @@ -package spanner - -import ( - "context" - "fmt" - "os" - "sort" - "strconv" - "strings" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/useragent" - "github.com/hashicorp/vault/physical" - "google.golang.org/api/iterator" - "google.golang.org/api/option" - "google.golang.org/grpc/codes" - - "cloud.google.com/go/spanner" - "github.com/pkg/errors" -) - -// Verify Backend satisfies the correct interfaces -var _ physical.Backend = (*Backend)(nil) -var _ physical.Transactional = (*Backend)(nil) - -const ( - // envDatabase is the name of the environment variable to search for the - // database name. - envDatabase = "GOOGLE_SPANNER_DATABASE" - - // envHAEnabled is the name of the environment variable to search for the - // boolean indicating if HA is enabled. - envHAEnabled = "GOOGLE_SPANNER_HA_ENABLED" - - // envHATable is the name of the environment variable to search for the table - // name to use for HA. - envHATable = "GOOGLE_SPANNER_HA_TABLE" - - // envTable is the name of the environment variable to search for the table - // name. - envTable = "GOOGLE_SPANNER_TABLE" - - // defaultTable is the default table name if none is specified. - defaultTable = "Vault" - - // defaultHASuffix is the default suffix to apply to the table name if no - // HA table is provided. - defaultHASuffix = "HA" -) - -var ( - // metricDelete is the key for the metric for measuring a Delete call. - metricDelete = []string{"spanner", "delete"} - - // metricGet is the key for the metric for measuring a Get call. - metricGet = []string{"spanner", "get"} - - // metricList is the key for the metric for measuring a List call. - metricList = []string{"spanner", "list"} - - // metricPut is the key for the metric for measuring a Put call. - metricPut = []string{"spanner", "put"} -) - -// Backend implements physical.Backend and describes the steps necessary to -// persist data using Google Cloud Spanner. -type Backend struct { - // database is the name of the database to use for data storage and retrieval. - // This is supplied as part of user configuration. - database string - - // table is the name of the table in the database. - table string - - // haTable is the name of the table to use for HA in the database. - haTable string - - // haEnabled indicates if high availability is enabled. Default: true. - haEnabled bool - - // client is the underlying API client for talking to spanner. - client *spanner.Client - - // logger and permitPool are internal constructs. - logger log.Logger - permitPool *physical.PermitPool -} - -// NewBackend creates a new Google Spanner storage backend with the given -// configuration. This uses the official Golang Cloud SDK and therefore supports -// specifying credentials via envvars, credential files, etc. -func NewBackend(c map[string]string, logger log.Logger) (physical.Backend, error) { - logger.Debug("configuring backend") - - // Database name - database := os.Getenv(envDatabase) - if database == "" { - database = c["database"] - } - if database == "" { - return nil, errors.New("missing database name") - } - - // Table name - table := os.Getenv(envTable) - if table == "" { - table = c["table"] - } - if table == "" { - table = defaultTable - } - - // HA table name - haTable := os.Getenv(envHATable) - if haTable == "" { - haTable = c["ha_table"] - } - if haTable == "" { - haTable = table + defaultHASuffix - } - - // HA configuration - haEnabled := false - haEnabledStr := os.Getenv(envHAEnabled) - if haEnabledStr == "" { - haEnabledStr = c["ha_enabled"] - } - if haEnabledStr != "" { - var err error - haEnabled, err = strconv.ParseBool(haEnabledStr) - if err != nil { - return nil, errwrap.Wrapf("failed to parse HA enabled: {{err}}", err) - } - } - - // Max parallel - maxParallel, err := extractInt(c["max_parallel"]) - if err != nil { - return nil, errwrap.Wrapf("failed to parse max_parallel: {{err}}", err) - } - - logger.Debug("configuration", - "database", database, - "table", table, - "haEnabled", haEnabled, - "haTable", haTable, - "maxParallel", maxParallel, - ) - logger.Debug("creating client") - - ctx := context.Background() - client, err := spanner.NewClient(ctx, database, - option.WithUserAgent(useragent.String()), - ) - if err != nil { - return nil, errwrap.Wrapf("failed to create spanner client: {{err}}", err) - } - - return &Backend{ - database: database, - table: table, - haEnabled: haEnabled, - haTable: haTable, - - client: client, - permitPool: physical.NewPermitPool(maxParallel), - logger: logger, - }, nil -} - -// Put creates or updates an entry. -func (b *Backend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince(metricPut, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Insert - m := spanner.InsertOrUpdateMap(b.table, map[string]interface{}{ - "Key": entry.Key, - "Value": entry.Value, - }) - if _, err := b.client.Apply(ctx, []*spanner.Mutation{m}); err != nil { - return errwrap.Wrapf("failed to put data: {{err}}", err) - } - return nil -} - -// Get fetches an entry. If there is no entry, this function returns nil. -func (b *Backend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince(metricList, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Read - row, err := b.client.Single().ReadRow(ctx, b.table, spanner.Key{key}, []string{"Value"}) - if spanner.ErrCode(err) == codes.NotFound { - return nil, nil - } - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read value for %q: {{err}}", key), err) - } - - var value []byte - if err := row.Column(0, &value); err != nil { - return nil, errwrap.Wrapf("failed to decode value into bytes: {{err}}", err) - } - - return &physical.Entry{ - Key: key, - Value: value, - }, nil -} - -// Delete deletes an entry with the given key. -func (b *Backend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince(metricDelete, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Delete - m := spanner.Delete(b.table, spanner.Key{key}) - if _, err := b.client.Apply(ctx, []*spanner.Mutation{m}); err != nil { - return errwrap.Wrapf("failed to delete key: {{err}}", err) - } - - return nil -} - -// List enumerates all keys with the given prefix. -func (b *Backend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince(metricList, time.Now()) - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Sanitize - safeTable := sanitizeTable(b.table) - - // List - iter := b.client.Single().Query(ctx, spanner.Statement{ - SQL: "SELECT Key FROM " + safeTable + " WHERE STARTS_WITH(Key, @prefix)", - Params: map[string]interface{}{ - "prefix": prefix, - }, - }) - defer iter.Stop() - - var keys []string - - for { - row, err := iter.Next() - if err == iterator.Done { - break - } - if err != nil { - return nil, errwrap.Wrapf("failed to read row: {{err}}", err) - } - - var key string - if err := row.Column(0, &key); err != nil { - return nil, errwrap.Wrapf("failed to decode key into string: {{err}}", err) - } - - // The results will include the full prefix (folder) and any deeply-nested - // prefixes (subfolders). Vault expects only the top-most things to be - // included. - key = strings.TrimPrefix(key, prefix) - if i := strings.Index(key, "/"); i == -1 { - // Add objects only from the current 'folder' - keys = append(keys, key) - } else { - // Add truncated 'folder' paths - keys = strutil.AppendIfMissing(keys, string(key[:i+1])) - } - } - - // Sort because the resulting order is not predictable - sort.Strings(keys) - - return keys, nil -} - -// Transaction runs multiple entries via a single transaction. -func (b *Backend) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - // Quit early if we can - if len(txns) == 0 { - return nil - } - - // Build all the ops before taking out the pool - ms := make([]*spanner.Mutation, len(txns)) - for i, tx := range txns { - op, key, value := tx.Operation, tx.Entry.Key, tx.Entry.Value - - switch op { - case physical.DeleteOperation: - ms[i] = spanner.Delete(b.table, spanner.Key{key}) - case physical.PutOperation: - ms[i] = spanner.InsertOrUpdateMap(b.table, map[string]interface{}{ - "Key": key, - "Value": value, - }) - default: - return fmt.Errorf("unsupported transaction operation: %q", op) - } - } - - // Pooling - b.permitPool.Acquire() - defer b.permitPool.Release() - - // Transactivate! - if _, err := b.client.Apply(ctx, ms); err != nil { - return errwrap.Wrapf("failed to commit transaction: {{err}}", err) - } - - return nil -} - -// extractInt is a helper function that takes a string and converts that string -// to an int, but accounts for the empty string. -func extractInt(s string) (int, error) { - if s == "" { - return 0, nil - } - return strconv.Atoi(s) -} - -// sanitizeTable attempts to sanitize the table name. -func sanitizeTable(s string) string { - end := strings.IndexRune(s, 0) - if end > -1 { - s = s[:end] - } - return strings.Replace(s, `"`, `""`, -1) -} diff --git a/vendor/github.com/hashicorp/vault/physical/spanner/spanner_ha.go b/vendor/github.com/hashicorp/vault/physical/spanner/spanner_ha.go deleted file mode 100644 index 2e7b73965..000000000 --- a/vendor/github.com/hashicorp/vault/physical/spanner/spanner_ha.go +++ /dev/null @@ -1,417 +0,0 @@ -package spanner - -import ( - "context" - "fmt" - "sync" - "time" - - "cloud.google.com/go/spanner" - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/physical" - "github.com/pkg/errors" - "google.golang.org/grpc/codes" -) - -// Verify Backend satisfies the correct interfaces -var _ physical.HABackend = (*Backend)(nil) -var _ physical.Lock = (*Lock)(nil) - -const ( - // LockRenewInterval is the time to wait between lock renewals. - LockRenewInterval = 5 * time.Second - - // LockRetryInterval is the amount of time to wait if the lock fails before - // trying again. - LockRetryInterval = 5 * time.Second - - // LockTTL is the default lock TTL. - LockTTL = 15 * time.Second - - // LockWatchRetryInterval is the amount of time to wait if a watch fails - // before trying again. - LockWatchRetryInterval = 5 * time.Second - - // LockWatchRetryMax is the number of times to retry a failed watch before - // signaling that leadership is lost. - LockWatchRetryMax = 5 -) - -var ( - // metricLockUnlock is the metric to register for a lock delete. - metricLockUnlock = []string{"spanner", "lock", "unlock"} - - // metricLockGet is the metric to register for a lock get. - metricLockLock = []string{"spanner", "lock", "lock"} - - // metricLockValue is the metric to register for a lock create/update. - metricLockValue = []string{"spanner", "lock", "value"} -) - -// Lock is the HA lock. -type Lock struct { - // backend is the underlying physical backend. - backend *Backend - - // key is the name of the key. value is the value of the key. - key, value string - - // held is a boolean indicating if the lock is currently held. - held bool - - // identity is the internal identity of this key (unique to this server - // instance). - identity string - - // lock is an internal lock - lock sync.Mutex - - // stopCh is the channel that stops all operations. It may be closed in the - // event of a leader loss or graceful shutdown. stopped is a boolean - // indicating if we are stopped - it exists to prevent double closing the - // channel. stopLock is a mutex around the locks. - stopCh chan struct{} - stopped bool - stopLock sync.Mutex - - // Allow modifying the Lock durations for ease of unit testing. - renewInterval time.Duration - retryInterval time.Duration - ttl time.Duration - watchRetryInterval time.Duration - watchRetryMax int -} - -// LockRecord is the struct that corresponds to a lock. -type LockRecord struct { - Key string - Value string - Identity string - Timestamp time.Time -} - -// HAEnabled implements HABackend and indicates that this backend supports high -// availability. -func (b *Backend) HAEnabled() bool { - return b.haEnabled -} - -// LockWith acquires a mutual exclusion based on the given key. -func (b *Backend) LockWith(key, value string) (physical.Lock, error) { - identity, err := uuid.GenerateUUID() - if err != nil { - return nil, errwrap.Wrapf("lock with: {{err}}", err) - } - return &Lock{ - backend: b, - key: key, - value: value, - identity: identity, - stopped: true, - - renewInterval: LockRenewInterval, - retryInterval: LockRetryInterval, - ttl: LockTTL, - watchRetryInterval: LockWatchRetryInterval, - watchRetryMax: LockWatchRetryMax, - }, nil -} - -// Lock acquires the given lock. The stopCh is optional. If closed, it -// interrupts the lock acquisition attempt. The returned channel should be -// closed when leadership is lost. -func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - defer metrics.MeasureSince(metricLockLock, time.Now()) - - l.lock.Lock() - defer l.lock.Unlock() - if l.held { - return nil, errors.New("lock already held") - } - - // Attempt to lock - this function blocks until a lock is acquired or an error - // occurs. - acquired, err := l.attemptLock(stopCh) - if err != nil { - return nil, errwrap.Wrapf("lock: {{err}}", err) - } - if !acquired { - return nil, nil - } - - // We have the lock now - l.held = true - - // Build the locks - l.stopLock.Lock() - l.stopCh = make(chan struct{}) - l.stopped = false - l.stopLock.Unlock() - - // Periodically renew and watch the lock - go l.renewLock() - go l.watchLock() - - return l.stopCh, nil -} - -// Unlock releases the lock. -func (l *Lock) Unlock() error { - defer metrics.MeasureSince(metricLockUnlock, time.Now()) - - l.lock.Lock() - defer l.lock.Unlock() - if !l.held { - return nil - } - - // Stop any existing locking or renewal attempts - l.stopLock.Lock() - if !l.stopped { - l.stopped = true - close(l.stopCh) - } - l.stopLock.Unlock() - - // Pooling - l.backend.permitPool.Acquire() - defer l.backend.permitPool.Release() - - // Delete - ctx := context.Background() - if _, err := l.backend.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { - row, err := txn.ReadRow(ctx, l.backend.haTable, spanner.Key{l.key}, []string{"Identity"}) - if err != nil { - if spanner.ErrCode(err) != codes.NotFound { - return nil - } - return err - } - - var r LockRecord - if derr := row.ToStruct(&r); derr != nil { - return errwrap.Wrapf("failed to decode to struct: {{err}}", derr) - } - - // If the identity is different, that means that between the time that after - // we stopped acquisition, the TTL expired and someone else grabbed the - // lock. We do not want to delete a lock that is not our own. - if r.Identity != l.identity { - return nil - } - - return txn.BufferWrite([]*spanner.Mutation{ - spanner.Delete(l.backend.haTable, spanner.Key{l.key}), - }) - }); err != nil { - return errwrap.Wrapf("unlock: {{err}}", err) - } - - // We are no longer holding the lock - l.held = false - - return nil -} - -// Value returns the value of the lock and if it is held. -func (l *Lock) Value() (bool, string, error) { - defer metrics.MeasureSince(metricLockValue, time.Now()) - - r, err := l.get(context.Background()) - if err != nil { - return false, "", err - } - if r == nil { - return false, "", err - } - return true, string(r.Value), nil -} - -// attemptLock attempts to acquire a lock. If the given channel is closed, the -// acquisition attempt stops. This function returns when a lock is acquired or -// an error occurs. -func (l *Lock) attemptLock(stopCh <-chan struct{}) (bool, error) { - ticker := time.NewTicker(l.retryInterval) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - acquired, err := l.writeLock() - if err != nil { - return false, errwrap.Wrapf("attempt lock: {{err}}", err) - } - if !acquired { - continue - } - - return true, nil - case <-stopCh: - return false, nil - } - } -} - -// renewLock renews the given lock until the channel is closed. -func (l *Lock) renewLock() { - ticker := time.NewTicker(l.renewInterval) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - l.writeLock() - case <-l.stopCh: - return - } - } -} - -// watchLock checks whether the lock has changed in the table and closes the -// leader channel accordingly. If an error occurs during the check, watchLock -// will retry the operation and then close the leader channel if it can't -// succeed after retries. -func (l *Lock) watchLock() { - retries := 0 - ticker := time.NewTicker(l.watchRetryInterval) - -OUTER: - for { - // Check if the channel is already closed - select { - case <-l.stopCh: - break OUTER - default: - } - - // Check if we've exceeded retries - if retries >= l.watchRetryMax-1 { - break OUTER - } - - // Wait for the timer - select { - case <-ticker.C: - case <-l.stopCh: - break OUTER - } - - // Attempt to read the key - r, err := l.get(context.Background()) - if err != nil { - retries++ - continue - } - - // Verify the identity is the same - if r == nil || r.Identity != l.identity { - break OUTER - } - } - - l.stopLock.Lock() - defer l.stopLock.Unlock() - if !l.stopped { - l.stopped = true - close(l.stopCh) - } -} - -// writeLock writes the given lock using the following algorithm: -// -// - lock does not exist -// - write the lock -// - lock exists -// - if key is empty or identity is the same or timestamp exceeds TTL -// - update the lock to self -func (l *Lock) writeLock() (bool, error) { - // Pooling - l.backend.permitPool.Acquire() - defer l.backend.permitPool.Release() - - // Keep track of whether the lock was written - lockWritten := false - - // Create a transaction to read and the update (maybe) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - // The transaction will be retried, and it could sit in a queue behind, say, - // the delete operation. To stop the transaction, we close the context when - // the associated stopCh is received. - go func() { - select { - case <-l.stopCh: - cancel() - case <-ctx.Done(): - } - }() - - _, err := l.backend.client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error { - row, err := txn.ReadRow(ctx, l.backend.haTable, spanner.Key{l.key}, []string{"Key", "Identity", "Timestamp"}) - if err != nil && spanner.ErrCode(err) != codes.NotFound { - return err - } - - // If there was a record, verify that the record is still trustable. - if row != nil { - var r LockRecord - if derr := row.ToStruct(&r); derr != nil { - return errwrap.Wrapf("failed to decode to struct: {{err}}", derr) - } - - // If the key is empty or the identity is ours or the ttl expired, we can - // write. Otherwise, return now because we cannot. - if r.Key != "" && r.Identity != l.identity && time.Now().UTC().Sub(r.Timestamp) < l.ttl { - return nil - } - } - - m, err := spanner.InsertOrUpdateStruct(l.backend.haTable, &LockRecord{ - Key: l.key, - Value: l.value, - Identity: l.identity, - Timestamp: time.Now().UTC(), - }) - if err != nil { - return errwrap.Wrapf("failed to generate struct: {{err}}", err) - } - if err := txn.BufferWrite([]*spanner.Mutation{m}); err != nil { - return errwrap.Wrapf("failed to write: {{err}}", err) - } - - // Mark that the lock was acquired - lockWritten = true - - return nil - }) - if err != nil { - return false, errwrap.Wrapf("write lock: {{err}}", err) - } - - return lockWritten, nil -} - -// get retrieves the value for the lock. -func (l *Lock) get(ctx context.Context) (*LockRecord, error) { - // Pooling - l.backend.permitPool.Acquire() - defer l.backend.permitPool.Release() - - // Read - row, err := l.backend.client.Single().ReadRow(ctx, l.backend.haTable, spanner.Key{l.key}, []string{"Key", "Value", "Timestamp", "Identity"}) - if spanner.ErrCode(err) == codes.NotFound { - return nil, nil - } - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to read value for %q: {{err}}", l.key), err) - } - - var r LockRecord - if err := row.ToStruct(&r); err != nil { - return nil, errwrap.Wrapf("failed to decode lock: {{err}}", err) - } - return &r, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/swift/swift.go b/vendor/github.com/hashicorp/vault/physical/swift/swift.go deleted file mode 100644 index 37f5b4f4e..000000000 --- a/vendor/github.com/hashicorp/vault/physical/swift/swift.go +++ /dev/null @@ -1,248 +0,0 @@ -package swift - -import ( - "context" - "fmt" - "os" - "sort" - "strconv" - "strings" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" - "github.com/ncw/swift" -) - -// Verify SwiftBackend satisfies the correct interfaces -var _ physical.Backend = (*SwiftBackend)(nil) - -// SwiftBackend is a physical backend that stores data -// within an OpenStack Swift container. -type SwiftBackend struct { - container string - client *swift.Connection - logger log.Logger - permitPool *physical.PermitPool -} - -// NewSwiftBackend constructs a Swift backend using a pre-existing -// container. Credentials can be provided to the backend, sourced -// from the environment. -func NewSwiftBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - var ok bool - - username := os.Getenv("OS_USERNAME") - if username == "" { - username = conf["username"] - if username == "" { - return nil, fmt.Errorf("missing username") - } - } - password := os.Getenv("OS_PASSWORD") - if password == "" { - password = conf["password"] - if password == "" { - return nil, fmt.Errorf("missing password") - } - } - authUrl := os.Getenv("OS_AUTH_URL") - if authUrl == "" { - authUrl = conf["auth_url"] - if authUrl == "" { - return nil, fmt.Errorf("missing auth_url") - } - } - container := os.Getenv("OS_CONTAINER") - if container == "" { - container = conf["container"] - if container == "" { - return nil, fmt.Errorf("missing container") - } - } - project := os.Getenv("OS_PROJECT_NAME") - if project == "" { - if project, ok = conf["project"]; !ok { - // Check for KeyStone naming prior to V3 - project = os.Getenv("OS_TENANT_NAME") - if project == "" { - project = conf["tenant"] - } - } - } - - domain := os.Getenv("OS_USER_DOMAIN_NAME") - if domain == "" { - domain = conf["domain"] - } - projectDomain := os.Getenv("OS_PROJECT_DOMAIN_NAME") - if projectDomain == "" { - projectDomain = conf["project-domain"] - } - - region := os.Getenv("OS_REGION_NAME") - if region == "" { - region = conf["region"] - } - tenantID := os.Getenv("OS_TENANT_ID") - if tenantID == "" { - tenantID = conf["tenant_id"] - } - trustID := os.Getenv("OS_TRUST_ID") - if trustID == "" { - trustID = conf["trust_id"] - } - storageUrl := os.Getenv("OS_STORAGE_URL") - if storageUrl == "" { - storageUrl = conf["storage_url"] - } - authToken := os.Getenv("OS_AUTH_TOKEN") - if authToken == "" { - authToken = conf["auth_token"] - } - - c := swift.Connection{ - Domain: domain, - UserName: username, - ApiKey: password, - AuthUrl: authUrl, - Tenant: project, - TenantDomain: projectDomain, - Region: region, - TenantId: tenantID, - TrustId: trustID, - StorageUrl: storageUrl, - AuthToken: authToken, - Transport: cleanhttp.DefaultPooledTransport(), - } - - err := c.Authenticate() - if err != nil { - return nil, err - } - - _, _, err = c.Container(container) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("Unable to access container %q: {{err}}", container), err) - } - - maxParStr, ok := conf["max_parallel"] - var maxParInt int - if ok { - maxParInt, err = strconv.Atoi(maxParStr) - if err != nil { - return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err) - } - if logger.IsDebug() { - logger.Debug("max_parallel set", "max_parallel", maxParInt) - } - } - - s := &SwiftBackend{ - client: &c, - container: container, - logger: logger, - permitPool: physical.NewPermitPool(maxParInt), - } - return s, nil -} - -// Put is used to insert or update an entry -func (s *SwiftBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"swift", "put"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - err := s.client.ObjectPutBytes(s.container, entry.Key, entry.Value, "") - - if err != nil { - return err - } - - return nil -} - -// Get is used to fetch an entry -func (s *SwiftBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"swift", "get"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - //Do a list of names with the key first since eventual consistency means - //it might be deleted, but a node might return a read of bytes which fails - //the physical test - list, err := s.client.ObjectNames(s.container, &swift.ObjectsOpts{Prefix: key}) - if err != nil { - return nil, err - } - if 0 == len(list) { - return nil, nil - } - data, err := s.client.ObjectGetBytes(s.container, key) - if err == swift.ObjectNotFound { - return nil, nil - } - if err != nil { - return nil, err - } - ent := &physical.Entry{ - Key: key, - Value: data, - } - - return ent, nil -} - -// Delete is used to permanently delete an entry -func (s *SwiftBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"swift", "delete"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - err := s.client.ObjectDelete(s.container, key) - - if err != nil && err != swift.ObjectNotFound { - return err - } - - return nil -} - -// List is used to list all the keys under a given -// prefix, up to the next prefix. -func (s *SwiftBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"swift", "list"}, time.Now()) - - s.permitPool.Acquire() - defer s.permitPool.Release() - - list, err := s.client.ObjectNamesAll(s.container, &swift.ObjectsOpts{Prefix: prefix}) - if nil != err { - return nil, err - } - - keys := []string{} - for _, key := range list { - key := strings.TrimPrefix(key, prefix) - - if i := strings.Index(key, "/"); i == -1 { - // Add objects only from the current 'folder' - keys = append(keys, key) - } else if i != -1 { - // Add truncated 'folder' paths - keys = strutil.AppendIfMissing(keys, key[:i+1]) - } - } - - sort.Strings(keys) - - return keys, nil -} diff --git a/vendor/github.com/hashicorp/vault/physical/testing.go b/vendor/github.com/hashicorp/vault/physical/testing.go deleted file mode 100644 index 375d9053e..000000000 --- a/vendor/github.com/hashicorp/vault/physical/testing.go +++ /dev/null @@ -1,488 +0,0 @@ -package physical - -import ( - "context" - "reflect" - "sort" - "testing" - "time" -) - -func ExerciseBackend(t testing.TB, b Backend) { - t.Helper() - - // Should be empty - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatalf("initial list failed: %v", err) - } - if len(keys) != 0 { - t.Errorf("initial not empty: %v", keys) - } - - // Delete should work if it does not exist - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("idempotent delete: %v", err) - } - - // Get should not fail, but be nil - out, err := b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("initial get failed: %v", err) - } - if out != nil { - t.Errorf("initial get was not nil: %v", out) - } - - // Make an entry - e := &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("put failed: %v", err) - } - - // Get should work - out, err = b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get failed: %v", err) - } - if !reflect.DeepEqual(out, e) { - t.Errorf("bad: %v expected: %v", out, e) - } - - // List should not be empty - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list failed: %v", err) - } - if len(keys) != 1 || keys[0] != "foo" { - t.Errorf("keys[0] did not equal foo: %v", keys) - } - - // Delete should work - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("delete: %v", err) - } - - // Should be empty - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list after delete: %v", err) - } - if len(keys) != 0 { - t.Errorf("list after delete not empty: %v", keys) - } - - // Get should fail - out, err = b.Get(context.Background(), "foo") - if err != nil { - t.Fatalf("get after delete: %v", err) - } - if out != nil { - t.Errorf("get after delete not nil: %v", out) - } - - // Multiple Puts should work; GH-189 - e = &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("multi put 1 failed: %v", err) - } - e = &Entry{Key: "foo", Value: []byte("test")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("multi put 2 failed: %v", err) - } - - // Make a nested entry - e = &Entry{Key: "foo/bar", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("nested put failed: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list multi failed: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "foo" || keys[1] != "foo/" { - t.Errorf("expected 2 keys [foo, foo/]: %v", keys) - } - - // Delete with children should work - err = b.Delete(context.Background(), "foo") - if err != nil { - t.Fatalf("delete after multi: %v", err) - } - - // Get should return the child - out, err = b.Get(context.Background(), "foo/bar") - if err != nil { - t.Fatalf("get after multi delete: %v", err) - } - if out == nil { - t.Errorf("get after multi delete not nil: %v", out) - } - - // Removal of nested secret should not leave artifacts - e = &Entry{Key: "foo/nested1/nested2/nested3", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - err = b.Delete(context.Background(), "foo/nested1/nested2/nested3") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "foo/") - if err != nil { - t.Fatalf("err: %v", err) - } - if len(keys) != 1 || keys[0] != "bar" { - t.Errorf("should be exactly 1 key == bar: %v", keys) - } - - // Make a second nested entry to test prefix removal - e = &Entry{Key: "foo/zip", Value: []byte("zap")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("failed to create second nested: %v", err) - } - - // Delete should not remove the prefix - err = b.Delete(context.Background(), "foo/bar") - if err != nil { - t.Fatalf("failed to delete nested prefix: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("list nested prefix: %v", err) - } - if len(keys) != 1 || keys[0] != "foo/" { - t.Errorf("should be exactly 1 key == foo/: %v", keys) - } - - // Delete should remove the prefix - err = b.Delete(context.Background(), "foo/zip") - if err != nil { - t.Fatalf("failed to delete second prefix: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing after second delete failed: %v", err) - } - if len(keys) != 0 { - t.Errorf("should be empty at end: %v", keys) - } - - // When the root path is empty, adding and removing deep nested values should not break listing - e = &Entry{Key: "foo/nested1/nested2/value1", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - e = &Entry{Key: "foo/nested1/nested2/value2", Value: []byte("baz")} - err = b.Put(context.Background(), e) - if err != nil { - t.Fatalf("deep nest: %v", err) - } - - err = b.Delete(context.Background(), "foo/nested1/nested2/value2") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing of root failed after deletion: %v", err) - } - if len(keys) == 0 { - t.Errorf("root is returning empty after deleting a single nested value, expected nested1/: %v", keys) - keys, err = b.List(context.Background(), "foo/nested1") - if err != nil { - t.Fatalf("listing of expected nested path 'foo/nested1' failed: %v", err) - } - // prove that the root should not be empty and that foo/nested1 exists - if len(keys) != 0 { - t.Logf(" keys can still be listed from nested1/ so it's not empty, expected nested2/: %v", keys) - } - } - - // cleanup left over listing bug test value - err = b.Delete(context.Background(), "foo/nested1/nested2/value1") - if err != nil { - t.Fatalf("failed to remove deep nest: %v", err) - } - - keys, err = b.List(context.Background(), "") - if err != nil { - t.Fatalf("listing of root failed after delete of deep nest: %v", err) - } - if len(keys) != 0 { - t.Errorf("should be empty at end: %v", keys) - } -} - -func ExerciseBackend_ListPrefix(t testing.TB, b Backend) { - t.Helper() - - e1 := &Entry{Key: "foo", Value: []byte("test")} - e2 := &Entry{Key: "foo/bar", Value: []byte("test")} - e3 := &Entry{Key: "foo/bar/baz", Value: []byte("test")} - - defer func() { - b.Delete(context.Background(), "foo") - b.Delete(context.Background(), "foo/bar") - b.Delete(context.Background(), "foo/bar/baz") - }() - - err := b.Put(context.Background(), e1) - if err != nil { - t.Fatalf("failed to put entry 1: %v", err) - } - err = b.Put(context.Background(), e2) - if err != nil { - t.Fatalf("failed to put entry 2: %v", err) - } - err = b.Put(context.Background(), e3) - if err != nil { - t.Fatalf("failed to put entry 3: %v", err) - } - - // Scan the root - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatalf("list root: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "foo" || keys[1] != "foo/" { - t.Errorf("root expected [foo foo/]: %v", keys) - } - - // Scan foo/ - keys, err = b.List(context.Background(), "foo/") - if err != nil { - t.Fatalf("list level 1: %v", err) - } - sort.Strings(keys) - if len(keys) != 2 || keys[0] != "bar" || keys[1] != "bar/" { - t.Errorf("level 1 expected [bar bar/]: %v", keys) - } - - // Scan foo/bar/ - keys, err = b.List(context.Background(), "foo/bar/") - if err != nil { - t.Fatalf("list level 2: %v", err) - } - sort.Strings(keys) - if len(keys) != 1 || keys[0] != "baz" { - t.Errorf("level 1 expected [baz]: %v", keys) - } -} - -func ExerciseHABackend(t testing.TB, b HABackend, b2 HABackend) { - t.Helper() - - // Get the lock - lock, err := b.LockWith("foo", "bar") - if err != nil { - t.Fatalf("initial lock: %v", err) - } - - // Attempt to lock - leaderCh, err := lock.Lock(nil) - if err != nil { - t.Fatalf("lock attempt 1: %v", err) - } - if leaderCh == nil { - t.Fatalf("missing leaderCh") - } - - // Check the value - held, val, err := lock.Value() - if err != nil { - t.Fatalf("err: %v", err) - } - if !held { - t.Errorf("should be held") - } - if val != "bar" { - t.Errorf("expected value bar: %v", err) - } - - // Second acquisition should fail - lock2, err := b2.LockWith("foo", "baz") - if err != nil { - t.Fatalf("lock 2: %v", err) - } - - // Cancel attempt in 50 msec - stopCh := make(chan struct{}) - time.AfterFunc(50*time.Millisecond, func() { - close(stopCh) - }) - - // Attempt to lock - leaderCh2, err := lock2.Lock(stopCh) - if err != nil { - t.Fatalf("stop lock 2: %v", err) - } - if leaderCh2 != nil { - t.Errorf("should not have gotten leaderCh: %v", leaderCh) - } - - // Release the first lock - lock.Unlock() - - // Attempt to lock should work - leaderCh2, err = lock2.Lock(nil) - if err != nil { - t.Fatalf("lock 2 lock: %v", err) - } - if leaderCh2 == nil { - t.Errorf("should get leaderCh") - } - - // Check the value - held, val, err = lock.Value() - if err != nil { - t.Fatalf("value: %v", err) - } - if !held { - t.Errorf("should still be held") - } - if val != "baz" { - t.Errorf("expected value baz: %v", err) - } - - // Cleanup - lock2.Unlock() -} - -func ExerciseTransactionalBackend(t testing.TB, b Backend) { - t.Helper() - tb, ok := b.(Transactional) - if !ok { - t.Fatal("Not a transactional backend") - } - - txns := SetupTestingTransactions(t, b) - - if err := tb.Transaction(context.Background(), txns); err != nil { - t.Fatal(err) - } - - keys, err := b.List(context.Background(), "") - if err != nil { - t.Fatal(err) - } - - expected := []string{"foo", "zip"} - - sort.Strings(keys) - sort.Strings(expected) - if !reflect.DeepEqual(keys, expected) { - t.Fatalf("mismatch: expected\n%#v\ngot\n%#v\n", expected, keys) - } - - entry, err := b.Get(context.Background(), "foo") - if err != nil { - t.Fatal(err) - } - if entry == nil { - t.Fatal("got nil entry") - } - if entry.Value == nil { - t.Fatal("got nil value") - } - if string(entry.Value) != "bar3" { - t.Fatal("updates did not apply correctly") - } - - entry, err = b.Get(context.Background(), "zip") - if err != nil { - t.Fatal(err) - } - if entry == nil { - t.Fatal("got nil entry") - } - if entry.Value == nil { - t.Fatal("got nil value") - } - if string(entry.Value) != "zap3" { - t.Fatal("updates did not apply correctly") - } -} - -func SetupTestingTransactions(t testing.TB, b Backend) []*TxnEntry { - t.Helper() - // Add a few keys so that we test rollback with deletion - if err := b.Put(context.Background(), &Entry{ - Key: "foo", - Value: []byte("bar"), - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "zip", - Value: []byte("zap"), - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "deleteme", - }); err != nil { - t.Fatal(err) - } - if err := b.Put(context.Background(), &Entry{ - Key: "deleteme2", - }); err != nil { - t.Fatal(err) - } - - txns := []*TxnEntry{ - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar2"), - }, - }, - &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme", - }, - }, - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "foo", - Value: []byte("bar3"), - }, - }, - &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: "deleteme2", - }, - }, - &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: "zip", - Value: []byte("zap3"), - }, - }, - } - - return txns -} diff --git a/vendor/github.com/hashicorp/vault/physical/transactions.go b/vendor/github.com/hashicorp/vault/physical/transactions.go deleted file mode 100644 index 5c43e57dc..000000000 --- a/vendor/github.com/hashicorp/vault/physical/transactions.go +++ /dev/null @@ -1,126 +0,0 @@ -package physical - -import ( - "context" - - multierror "github.com/hashicorp/go-multierror" -) - -// TxnEntry is an operation that takes atomically as part of -// a transactional update. Only supported by Transactional backends. -type TxnEntry struct { - Operation Operation - Entry *Entry -} - -// Transactional is an optional interface for backends that -// support doing transactional updates of multiple keys. This is -// required for some features such as replication. -type Transactional interface { - // The function to run a transaction - Transaction(context.Context, []*TxnEntry) error -} - -type PseudoTransactional interface { - // An internal function should do no locking or permit pool acquisition. - // Depending on the backend and if it natively supports transactions, these - // may simply chain to the normal backend functions. - GetInternal(context.Context, string) (*Entry, error) - PutInternal(context.Context, *Entry) error - DeleteInternal(context.Context, string) error -} - -// Implements the transaction interface -func GenericTransactionHandler(ctx context.Context, t PseudoTransactional, txns []*TxnEntry) (retErr error) { - rollbackStack := make([]*TxnEntry, 0, len(txns)) - var dirty bool - - // We walk the transactions in order; each successful operation goes into a - // LIFO for rollback if we hit an error along the way -TxnWalk: - for _, txn := range txns { - switch txn.Operation { - case DeleteOperation: - entry, err := t.GetInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - if entry == nil { - // Nothing to delete or roll back - continue - } - rollbackEntry := &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: entry.Key, - Value: entry.Value, - }, - } - err = t.DeleteInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...) - - case PutOperation: - entry, err := t.GetInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - // Nothing existed so in fact rolling back requires a delete - var rollbackEntry *TxnEntry - if entry == nil { - rollbackEntry = &TxnEntry{ - Operation: DeleteOperation, - Entry: &Entry{ - Key: txn.Entry.Key, - }, - } - } else { - rollbackEntry = &TxnEntry{ - Operation: PutOperation, - Entry: &Entry{ - Key: entry.Key, - Value: entry.Value, - }, - } - } - - err = t.PutInternal(ctx, txn.Entry) - if err != nil { - retErr = multierror.Append(retErr, err) - dirty = true - break TxnWalk - } - rollbackStack = append([]*TxnEntry{rollbackEntry}, rollbackStack...) - } - } - - // Need to roll back because we hit an error along the way - if dirty { - // While traversing this, if we get an error, we continue anyways in - // best-effort fashion - for _, txn := range rollbackStack { - switch txn.Operation { - case DeleteOperation: - err := t.DeleteInternal(ctx, txn.Entry.Key) - if err != nil { - retErr = multierror.Append(retErr, err) - } - case PutOperation: - err := t.PutInternal(ctx, txn.Entry) - if err != nil { - retErr = multierror.Append(retErr, err) - } - } - } - } - - return -} diff --git a/vendor/github.com/hashicorp/vault/physical/types.pb.go b/vendor/github.com/hashicorp/vault/physical/types.pb.go deleted file mode 100644 index 5f189d2ec..000000000 --- a/vendor/github.com/hashicorp/vault/physical/types.pb.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: physical/types.proto - -package physical // import "github.com/hashicorp/vault/physical" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SealWrapEntry struct { - Ciphertext []byte `protobuf:"bytes,1,opt,name=ciphertext,proto3" json:"ciphertext,omitempty"` - Wrapped bool `protobuf:"varint,4,opt,name=wrapped,proto3" json:"wrapped,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SealWrapEntry) Reset() { *m = SealWrapEntry{} } -func (m *SealWrapEntry) String() string { return proto.CompactTextString(m) } -func (*SealWrapEntry) ProtoMessage() {} -func (*SealWrapEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_types_80e2b3c13a71f106, []int{0} -} -func (m *SealWrapEntry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SealWrapEntry.Unmarshal(m, b) -} -func (m *SealWrapEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SealWrapEntry.Marshal(b, m, deterministic) -} -func (dst *SealWrapEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_SealWrapEntry.Merge(dst, src) -} -func (m *SealWrapEntry) XXX_Size() int { - return xxx_messageInfo_SealWrapEntry.Size(m) -} -func (m *SealWrapEntry) XXX_DiscardUnknown() { - xxx_messageInfo_SealWrapEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_SealWrapEntry proto.InternalMessageInfo - -func (m *SealWrapEntry) GetCiphertext() []byte { - if m != nil { - return m.Ciphertext - } - return nil -} - -func (m *SealWrapEntry) GetWrapped() bool { - if m != nil { - return m.Wrapped - } - return false -} - -func init() { - proto.RegisterType((*SealWrapEntry)(nil), "physical.SealWrapEntry") -} - -func init() { proto.RegisterFile("physical/types.proto", fileDescriptor_types_80e2b3c13a71f106) } - -var fileDescriptor_types_80e2b3c13a71f106 = []byte{ - // 148 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x29, 0xc8, 0xa8, 0x2c, - 0xce, 0x4c, 0x4e, 0xcc, 0xd1, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0xe2, 0x80, 0x89, 0x2a, 0x79, 0x72, 0xf1, 0x06, 0xa7, 0x26, 0xe6, 0x84, 0x17, 0x25, 0x16, - 0xb8, 0xe6, 0x95, 0x14, 0x55, 0x0a, 0xc9, 0x71, 0x71, 0x25, 0x67, 0x16, 0x64, 0xa4, 0x16, 0x95, - 0xa4, 0x56, 0x94, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x04, 0x21, 0x89, 0x08, 0x49, 0x70, 0xb1, - 0x97, 0x17, 0x25, 0x16, 0x14, 0xa4, 0xa6, 0x48, 0xb0, 0x28, 0x30, 0x6a, 0x70, 0x04, 0xc1, 0xb8, - 0x4e, 0xaa, 0x51, 0xca, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x19, - 0x89, 0xc5, 0x19, 0x99, 0xc9, 0xf9, 0x45, 0x05, 0xfa, 0x65, 0x89, 0xa5, 0x39, 0x25, 0xfa, 0x30, - 0x1b, 0x93, 0xd8, 0xc0, 0x4e, 0x30, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x71, 0xf9, 0x7a, 0x09, - 0x9a, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/physical/types.proto b/vendor/github.com/hashicorp/vault/physical/types.proto deleted file mode 100644 index 4633717d5..000000000 --- a/vendor/github.com/hashicorp/vault/physical/types.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/physical"; - -package physical; - -message SealWrapEntry { - bytes ciphertext = 1; - bool wrapped = 4; -} diff --git a/vendor/github.com/hashicorp/vault/physical/zookeeper/zookeeper.go b/vendor/github.com/hashicorp/vault/physical/zookeeper/zookeeper.go deleted file mode 100644 index e0e03ccbc..000000000 --- a/vendor/github.com/hashicorp/vault/physical/zookeeper/zookeeper.go +++ /dev/null @@ -1,504 +0,0 @@ -package zookeeper - -import ( - "context" - "fmt" - "path/filepath" - "sort" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/physical" - - metrics "github.com/armon/go-metrics" - "github.com/samuel/go-zookeeper/zk" -) - -const ( - // ZKNodeFilePrefix is prefixed to any "files" in ZooKeeper, - // so that they do not collide with directory entries. Otherwise, - // we cannot delete a file if the path is a full-prefix of another - // key. - ZKNodeFilePrefix = "_" -) - -// Verify ZooKeeperBackend satisfies the correct interfaces -var _ physical.Backend = (*ZooKeeperBackend)(nil) -var _ physical.HABackend = (*ZooKeeperBackend)(nil) -var _ physical.Lock = (*ZooKeeperHALock)(nil) - -// ZooKeeperBackend is a physical backend that stores data at specific -// prefix within ZooKeeper. It is used in production situations as -// it allows Vault to run on multiple machines in a highly-available manner. -type ZooKeeperBackend struct { - path string - client *zk.Conn - acl []zk.ACL - logger log.Logger -} - -// NewZooKeeperBackend constructs a ZooKeeper backend using the given API client -// and the prefix in the KV store. -func NewZooKeeperBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) { - // Get the path in ZooKeeper - path, ok := conf["path"] - if !ok { - path = "vault/" - } - - // Ensure path is suffixed and prefixed (zk requires prefix /) - if !strings.HasSuffix(path, "/") { - path += "/" - } - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - - // Configure the client, default to localhost instance - var machines string - machines, ok = conf["address"] - if !ok { - machines = "localhost:2181" - } - - // zNode owner and schema. - var owner string - var schema string - var schemaAndOwner string - schemaAndOwner, ok = conf["znode_owner"] - if !ok { - owner = "anyone" - schema = "world" - } else { - parsedSchemaAndOwner := strings.SplitN(schemaAndOwner, ":", 2) - if len(parsedSchemaAndOwner) != 2 { - return nil, fmt.Errorf("znode_owner expected format is 'schema:owner'") - } else { - schema = parsedSchemaAndOwner[0] - owner = parsedSchemaAndOwner[1] - - // znode_owner is in config and structured correctly - but does it make any sense? - // Either 'owner' or 'schema' was set but not both - this seems like a failed attempt - // (e.g. ':MyUser' which omit the schema, or ':' omitting both) - if owner == "" || schema == "" { - return nil, fmt.Errorf("znode_owner expected format is 'schema:auth'") - } - } - } - - acl := []zk.ACL{ - { - Perms: zk.PermAll, - Scheme: schema, - ID: owner, - }, - } - - // Authentication info - var schemaAndUser string - var useAddAuth bool - schemaAndUser, useAddAuth = conf["auth_info"] - if useAddAuth { - parsedSchemaAndUser := strings.SplitN(schemaAndUser, ":", 2) - if len(parsedSchemaAndUser) != 2 { - return nil, fmt.Errorf("auth_info expected format is 'schema:auth'") - } else { - schema = parsedSchemaAndUser[0] - owner = parsedSchemaAndUser[1] - - // auth_info is in config and structured correctly - but does it make any sense? - // Either 'owner' or 'schema' was set but not both - this seems like a failed attempt - // (e.g. ':MyUser' which omit the schema, or ':' omitting both) - if owner == "" || schema == "" { - return nil, fmt.Errorf("auth_info expected format is 'schema:auth'") - } - } - } - - // We have all of the configuration in hand - let's try and connect to ZK - client, _, err := zk.Connect(strings.Split(machines, ","), time.Second) - if err != nil { - return nil, errwrap.Wrapf("client setup failed: {{err}}", err) - } - - // ZK AddAuth API if the user asked for it - if useAddAuth { - err = client.AddAuth(schema, []byte(owner)) - if err != nil { - return nil, errwrap.Wrapf("ZooKeeper rejected authentication information provided at auth_info: {{err}}", err) - } - } - - // Setup the backend - c := &ZooKeeperBackend{ - path: path, - client: client, - acl: acl, - logger: logger, - } - return c, nil -} - -// ensurePath is used to create each node in the path hierarchy. -// We avoid calling this optimistically, and invoke it when we get -// an error during an operation -func (c *ZooKeeperBackend) ensurePath(path string, value []byte) error { - nodes := strings.Split(path, "/") - fullPath := "" - for index, node := range nodes { - if strings.TrimSpace(node) != "" { - fullPath += "/" + node - isLastNode := index+1 == len(nodes) - - // set parent nodes to nil, leaf to value - // this block reduces round trips by being smart on the leaf create/set - if exists, _, _ := c.client.Exists(fullPath); !isLastNode && !exists { - if _, err := c.client.Create(fullPath, nil, int32(0), c.acl); err != nil { - return err - } - } else if isLastNode && !exists { - if _, err := c.client.Create(fullPath, value, int32(0), c.acl); err != nil { - return err - } - } else if isLastNode && exists { - if _, err := c.client.Set(fullPath, value, int32(-1)); err != nil { - return err - } - } - } - } - return nil -} - -// cleanupLogicalPath is used to remove all empty nodes, beginning with deepest one, -// aborting on first non-empty one, up to top-level node. -func (c *ZooKeeperBackend) cleanupLogicalPath(path string) error { - nodes := strings.Split(path, "/") - for i := len(nodes) - 1; i > 0; i-- { - fullPath := c.path + strings.Join(nodes[:i], "/") - - _, stat, err := c.client.Exists(fullPath) - if err != nil { - return errwrap.Wrapf("failed to acquire node data: {{err}}", err) - } - - if stat.DataLength > 0 && stat.NumChildren > 0 { - panic(fmt.Sprintf("node %q is both of data and leaf type", fullPath)) - } else if stat.DataLength > 0 { - panic(fmt.Sprintf("node %q is a data node, this is either a bug or backend data is corrupted", fullPath)) - } else if stat.NumChildren > 0 { - return nil - } else { - // Empty node, lets clean it up! - if err := c.client.Delete(fullPath, -1); err != nil && err != zk.ErrNoNode { - return errwrap.Wrapf(fmt.Sprintf("removal of node %q failed: {{err}}", fullPath), err) - } - } - } - return nil -} - -// nodePath returns an zk path based on the given key. -func (c *ZooKeeperBackend) nodePath(key string) string { - return filepath.Join(c.path, filepath.Dir(key), ZKNodeFilePrefix+filepath.Base(key)) -} - -// Put is used to insert or update an entry -func (c *ZooKeeperBackend) Put(ctx context.Context, entry *physical.Entry) error { - defer metrics.MeasureSince([]string{"zookeeper", "put"}, time.Now()) - - // Attempt to set the full path - fullPath := c.nodePath(entry.Key) - _, err := c.client.Set(fullPath, entry.Value, -1) - - // If we get ErrNoNode, we need to construct the path hierarchy - if err == zk.ErrNoNode { - return c.ensurePath(fullPath, entry.Value) - } - return err -} - -// Get is used to fetch an entry -func (c *ZooKeeperBackend) Get(ctx context.Context, key string) (*physical.Entry, error) { - defer metrics.MeasureSince([]string{"zookeeper", "get"}, time.Now()) - - // Attempt to read the full path - fullPath := c.nodePath(key) - value, _, err := c.client.Get(fullPath) - - // Ignore if the node does not exist - if err == zk.ErrNoNode { - err = nil - } - if err != nil { - return nil, err - } - - // Handle a non-existing value - if value == nil { - return nil, nil - } - ent := &physical.Entry{ - Key: key, - Value: value, - } - return ent, nil -} - -// Delete is used to permanently delete an entry -func (c *ZooKeeperBackend) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"zookeeper", "delete"}, time.Now()) - - if key == "" { - return nil - } - - // Delete the full path - fullPath := c.nodePath(key) - err := c.client.Delete(fullPath, -1) - - // Mask if the node does not exist - if err != nil && err != zk.ErrNoNode { - return errwrap.Wrapf(fmt.Sprintf("failed to remove %q: {{err}}", fullPath), err) - } - - err = c.cleanupLogicalPath(key) - - return err -} - -// List is used ot list all the keys under a given -// prefix, up to the next prefix. -func (c *ZooKeeperBackend) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"zookeeper", "list"}, time.Now()) - - // Query the children at the full path - fullPath := strings.TrimSuffix(c.path+prefix, "/") - result, _, err := c.client.Children(fullPath) - - // If the path nodes are missing, no children! - if err == zk.ErrNoNode { - return []string{}, nil - } else if err != nil { - return []string{}, err - } - - children := []string{} - for _, key := range result { - childPath := fullPath + "/" + key - _, stat, err := c.client.Exists(childPath) - if err != nil { - // Node is ought to exists, so it must be something different - return []string{}, err - } - - // Check if this entry is a leaf of a node, - // and append the slash which is what Vault depends on - // for iteration - if stat.DataLength > 0 && stat.NumChildren > 0 { - if childPath == c.nodePath("core/lock") { - // go-zookeeper Lock() breaks Vault semantics and creates a directory - // under the lock file; just treat it like the file Vault expects - children = append(children, key[1:]) - } else { - panic(fmt.Sprintf("node %q is both of data and leaf type", childPath)) - } - } else if stat.DataLength == 0 { - // No, we cannot differentiate here on number of children as node - // can have all it leafs removed, and it still is a node. - children = append(children, key+"/") - } else { - children = append(children, key[1:]) - } - } - sort.Strings(children) - return children, nil -} - -// LockWith is used for mutual exclusion based on the given key. -func (c *ZooKeeperBackend) LockWith(key, value string) (physical.Lock, error) { - l := &ZooKeeperHALock{ - in: c, - key: key, - value: value, - logger: c.logger, - } - return l, nil -} - -// HAEnabled indicates whether the HA functionality should be exposed. -// Currently always returns true. -func (c *ZooKeeperBackend) HAEnabled() bool { - return true -} - -// ZooKeeperHALock is a ZooKeeper Lock implementation for the HABackend -type ZooKeeperHALock struct { - in *ZooKeeperBackend - key string - value string - logger log.Logger - - held bool - localLock sync.Mutex - leaderCh chan struct{} - stopCh <-chan struct{} - zkLock *zk.Lock -} - -func (i *ZooKeeperHALock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) { - i.localLock.Lock() - defer i.localLock.Unlock() - if i.held { - return nil, fmt.Errorf("lock already held") - } - - // Attempt an async acquisition - didLock := make(chan struct{}) - failLock := make(chan error, 1) - releaseCh := make(chan bool, 1) - lockpath := i.in.nodePath(i.key) - go i.attemptLock(lockpath, didLock, failLock, releaseCh) - - // Wait for lock acquisition, failure, or shutdown - select { - case <-didLock: - releaseCh <- false - case err := <-failLock: - return nil, err - case <-stopCh: - releaseCh <- true - return nil, nil - } - - // Create the leader channel - i.held = true - i.leaderCh = make(chan struct{}) - - // Watch for Events which could result in loss of our zkLock and close(i.leaderCh) - currentVal, _, lockeventCh, err := i.in.client.GetW(lockpath) - if err != nil { - return nil, errwrap.Wrapf("unable to watch HA lock: {{err}}", err) - } - if i.value != string(currentVal) { - return nil, fmt.Errorf("lost HA lock immediately before watch") - } - go i.monitorLock(lockeventCh, i.leaderCh) - - i.stopCh = stopCh - - return i.leaderCh, nil -} - -func (i *ZooKeeperHALock) attemptLock(lockpath string, didLock chan struct{}, failLock chan error, releaseCh chan bool) { - // Wait to acquire the lock in ZK - lock := zk.NewLock(i.in.client, lockpath, i.in.acl) - err := lock.Lock() - if err != nil { - failLock <- err - return - } - // Set node value - data := []byte(i.value) - err = i.in.ensurePath(lockpath, data) - if err != nil { - failLock <- err - lock.Unlock() - return - } - i.zkLock = lock - - // Signal that lock is held - close(didLock) - - // Handle an early abort - release := <-releaseCh - if release { - lock.Unlock() - } -} - -func (i *ZooKeeperHALock) monitorLock(lockeventCh <-chan zk.Event, leaderCh chan struct{}) { - for { - select { - case event := <-lockeventCh: - // Lost connection? - switch event.State { - case zk.StateConnected: - case zk.StateHasSession: - default: - close(leaderCh) - return - } - - // Lost lock? - switch event.Type { - case zk.EventNodeChildrenChanged: - case zk.EventSession: - default: - close(leaderCh) - return - } - } - } -} - -func (i *ZooKeeperHALock) unlockInternal() error { - i.localLock.Lock() - defer i.localLock.Unlock() - if !i.held { - return nil - } - - err := i.zkLock.Unlock() - - if err == nil { - i.held = false - return nil - } - - return err -} - -func (i *ZooKeeperHALock) Unlock() error { - var err error - - if err = i.unlockInternal(); err != nil { - i.logger.Error("zookeeper: failed to release distributed lock", "error", err) - - go func(i *ZooKeeperHALock) { - attempts := 0 - i.logger.Info("zookeeper: launching automated distributed lock release") - - for { - if err := i.unlockInternal(); err == nil { - i.logger.Info("zookeeper: distributed lock released") - return - } - - select { - case <-time.After(time.Second): - attempts := attempts + 1 - if attempts >= 10 { - i.logger.Error("zookeeper: release lock max attempts reached. Lock may not be released", "error", err) - return - } - continue - case <-i.stopCh: - return - } - } - }(i) - } - - return err -} - -func (i *ZooKeeperHALock) Value() (bool, string, error) { - lockpath := i.in.nodePath(i.key) - value, _, err := i.in.client.Get(lockpath) - return (value != nil), string(value), err -} diff --git a/vendor/github.com/hashicorp/vault/shamir/shamir.go b/vendor/github.com/hashicorp/vault/shamir/shamir.go deleted file mode 100644 index 04650868c..000000000 --- a/vendor/github.com/hashicorp/vault/shamir/shamir.go +++ /dev/null @@ -1,262 +0,0 @@ -package shamir - -import ( - "crypto/rand" - "crypto/subtle" - "fmt" - mathrand "math/rand" - "time" - - "github.com/hashicorp/errwrap" -) - -const ( - // ShareOverhead is the byte size overhead of each share - // when using Split on a secret. This is caused by appending - // a one byte tag to the share. - ShareOverhead = 1 -) - -// polynomial represents a polynomial of arbitrary degree -type polynomial struct { - coefficients []uint8 -} - -// makePolynomial constructs a random polynomial of the given -// degree but with the provided intercept value. -func makePolynomial(intercept, degree uint8) (polynomial, error) { - // Create a wrapper - p := polynomial{ - coefficients: make([]byte, degree+1), - } - - // Ensure the intercept is set - p.coefficients[0] = intercept - - // Assign random co-efficients to the polynomial - if _, err := rand.Read(p.coefficients[1:]); err != nil { - return p, err - } - - return p, nil -} - -// evaluate returns the value of the polynomial for the given x -func (p *polynomial) evaluate(x uint8) uint8 { - // Special case the origin - if x == 0 { - return p.coefficients[0] - } - - // Compute the polynomial value using Horner's method. - degree := len(p.coefficients) - 1 - out := p.coefficients[degree] - for i := degree - 1; i >= 0; i-- { - coeff := p.coefficients[i] - out = add(mult(out, x), coeff) - } - return out -} - -// interpolatePolynomial takes N sample points and returns -// the value at a given x using a lagrange interpolation. -func interpolatePolynomial(x_samples, y_samples []uint8, x uint8) uint8 { - limit := len(x_samples) - var result, basis uint8 - for i := 0; i < limit; i++ { - basis = 1 - for j := 0; j < limit; j++ { - if i == j { - continue - } - num := add(x, x_samples[j]) - denom := add(x_samples[i], x_samples[j]) - term := div(num, denom) - basis = mult(basis, term) - } - group := mult(y_samples[i], basis) - result = add(result, group) - } - return result -} - -// div divides two numbers in GF(2^8) -func div(a, b uint8) uint8 { - if b == 0 { - // leaks some timing information but we don't care anyways as this - // should never happen, hence the panic - panic("divide by zero") - } - - var goodVal, zero uint8 - log_a := logTable[a] - log_b := logTable[b] - diff := (int(log_a) - int(log_b)) % 255 - if diff < 0 { - diff += 255 - } - - ret := expTable[diff] - - // Ensure we return zero if a is zero but aren't subject to timing attacks - goodVal = ret - - if subtle.ConstantTimeByteEq(a, 0) == 1 { - ret = zero - } else { - ret = goodVal - } - - return ret -} - -// mult multiplies two numbers in GF(2^8) -func mult(a, b uint8) (out uint8) { - var goodVal, zero uint8 - log_a := logTable[a] - log_b := logTable[b] - sum := (int(log_a) + int(log_b)) % 255 - - ret := expTable[sum] - - // Ensure we return zero if either a or be are zero but aren't subject to - // timing attacks - goodVal = ret - - if subtle.ConstantTimeByteEq(a, 0) == 1 { - ret = zero - } else { - ret = goodVal - } - - if subtle.ConstantTimeByteEq(b, 0) == 1 { - ret = zero - } else { - // This operation does not do anything logically useful. It - // only ensures a constant number of assignments to thwart - // timing attacks. - goodVal = zero - } - - return ret -} - -// add combines two numbers in GF(2^8) -// This can also be used for subtraction since it is symmetric. -func add(a, b uint8) uint8 { - return a ^ b -} - -// Split takes an arbitrarily long secret and generates a `parts` -// number of shares, `threshold` of which are required to reconstruct -// the secret. The parts and threshold must be at least 2, and less -// than 256. The returned shares are each one byte longer than the secret -// as they attach a tag used to reconstruct the secret. -func Split(secret []byte, parts, threshold int) ([][]byte, error) { - // Sanity check the input - if parts < threshold { - return nil, fmt.Errorf("parts cannot be less than threshold") - } - if parts > 255 { - return nil, fmt.Errorf("parts cannot exceed 255") - } - if threshold < 2 { - return nil, fmt.Errorf("threshold must be at least 2") - } - if threshold > 255 { - return nil, fmt.Errorf("threshold cannot exceed 255") - } - if len(secret) == 0 { - return nil, fmt.Errorf("cannot split an empty secret") - } - - // Generate random list of x coordinates - mathrand.Seed(time.Now().UnixNano()) - xCoordinates := mathrand.Perm(255) - - // Allocate the output array, initialize the final byte - // of the output with the offset. The representation of each - // output is {y1, y2, .., yN, x}. - out := make([][]byte, parts) - for idx := range out { - out[idx] = make([]byte, len(secret)+1) - out[idx][len(secret)] = uint8(xCoordinates[idx]) + 1 - } - - // Construct a random polynomial for each byte of the secret. - // Because we are using a field of size 256, we can only represent - // a single byte as the intercept of the polynomial, so we must - // use a new polynomial for each byte. - for idx, val := range secret { - p, err := makePolynomial(val, uint8(threshold-1)) - if err != nil { - return nil, errwrap.Wrapf("failed to generate polynomial: {{err}}", err) - } - - // Generate a `parts` number of (x,y) pairs - // We cheat by encoding the x value once as the final index, - // so that it only needs to be stored once. - for i := 0; i < parts; i++ { - x := uint8(xCoordinates[i]) + 1 - y := p.evaluate(x) - out[i][idx] = y - } - } - - // Return the encoded secrets - return out, nil -} - -// Combine is used to reverse a Split and reconstruct a secret -// once a `threshold` number of parts are available. -func Combine(parts [][]byte) ([]byte, error) { - // Verify enough parts provided - if len(parts) < 2 { - return nil, fmt.Errorf("less than two parts cannot be used to reconstruct the secret") - } - - // Verify the parts are all the same length - firstPartLen := len(parts[0]) - if firstPartLen < 2 { - return nil, fmt.Errorf("parts must be at least two bytes") - } - for i := 1; i < len(parts); i++ { - if len(parts[i]) != firstPartLen { - return nil, fmt.Errorf("all parts must be the same length") - } - } - - // Create a buffer to store the reconstructed secret - secret := make([]byte, firstPartLen-1) - - // Buffer to store the samples - x_samples := make([]uint8, len(parts)) - y_samples := make([]uint8, len(parts)) - - // Set the x value for each sample and ensure no x_sample values are the same, - // otherwise div() can be unhappy - checkMap := map[byte]bool{} - for i, part := range parts { - samp := part[firstPartLen-1] - if exists := checkMap[samp]; exists { - return nil, fmt.Errorf("duplicate part detected") - } - checkMap[samp] = true - x_samples[i] = samp - } - - // Reconstruct each byte - for idx := range secret { - // Set the y value for each sample - for i, part := range parts { - y_samples[i] = part[idx] - } - - // Interpolate the polynomial and compute the value at 0 - val := interpolatePolynomial(x_samples, y_samples, 0) - - // Evaluate the 0th value to get the intercept - secret[idx] = val - } - return secret, nil -} diff --git a/vendor/github.com/hashicorp/vault/shamir/tables.go b/vendor/github.com/hashicorp/vault/shamir/tables.go deleted file mode 100644 index 76c245e79..000000000 --- a/vendor/github.com/hashicorp/vault/shamir/tables.go +++ /dev/null @@ -1,77 +0,0 @@ -package shamir - -// Tables taken from http://www.samiam.org/galois.html -// They use 0xe5 (229) as the generator - -var ( - // logTable provides the log(X)/log(g) at each index X - logTable = [256]uint8{ - 0x00, 0xff, 0xc8, 0x08, 0x91, 0x10, 0xd0, 0x36, - 0x5a, 0x3e, 0xd8, 0x43, 0x99, 0x77, 0xfe, 0x18, - 0x23, 0x20, 0x07, 0x70, 0xa1, 0x6c, 0x0c, 0x7f, - 0x62, 0x8b, 0x40, 0x46, 0xc7, 0x4b, 0xe0, 0x0e, - 0xeb, 0x16, 0xe8, 0xad, 0xcf, 0xcd, 0x39, 0x53, - 0x6a, 0x27, 0x35, 0x93, 0xd4, 0x4e, 0x48, 0xc3, - 0x2b, 0x79, 0x54, 0x28, 0x09, 0x78, 0x0f, 0x21, - 0x90, 0x87, 0x14, 0x2a, 0xa9, 0x9c, 0xd6, 0x74, - 0xb4, 0x7c, 0xde, 0xed, 0xb1, 0x86, 0x76, 0xa4, - 0x98, 0xe2, 0x96, 0x8f, 0x02, 0x32, 0x1c, 0xc1, - 0x33, 0xee, 0xef, 0x81, 0xfd, 0x30, 0x5c, 0x13, - 0x9d, 0x29, 0x17, 0xc4, 0x11, 0x44, 0x8c, 0x80, - 0xf3, 0x73, 0x42, 0x1e, 0x1d, 0xb5, 0xf0, 0x12, - 0xd1, 0x5b, 0x41, 0xa2, 0xd7, 0x2c, 0xe9, 0xd5, - 0x59, 0xcb, 0x50, 0xa8, 0xdc, 0xfc, 0xf2, 0x56, - 0x72, 0xa6, 0x65, 0x2f, 0x9f, 0x9b, 0x3d, 0xba, - 0x7d, 0xc2, 0x45, 0x82, 0xa7, 0x57, 0xb6, 0xa3, - 0x7a, 0x75, 0x4f, 0xae, 0x3f, 0x37, 0x6d, 0x47, - 0x61, 0xbe, 0xab, 0xd3, 0x5f, 0xb0, 0x58, 0xaf, - 0xca, 0x5e, 0xfa, 0x85, 0xe4, 0x4d, 0x8a, 0x05, - 0xfb, 0x60, 0xb7, 0x7b, 0xb8, 0x26, 0x4a, 0x67, - 0xc6, 0x1a, 0xf8, 0x69, 0x25, 0xb3, 0xdb, 0xbd, - 0x66, 0xdd, 0xf1, 0xd2, 0xdf, 0x03, 0x8d, 0x34, - 0xd9, 0x92, 0x0d, 0x63, 0x55, 0xaa, 0x49, 0xec, - 0xbc, 0x95, 0x3c, 0x84, 0x0b, 0xf5, 0xe6, 0xe7, - 0xe5, 0xac, 0x7e, 0x6e, 0xb9, 0xf9, 0xda, 0x8e, - 0x9a, 0xc9, 0x24, 0xe1, 0x0a, 0x15, 0x6b, 0x3a, - 0xa0, 0x51, 0xf4, 0xea, 0xb2, 0x97, 0x9e, 0x5d, - 0x22, 0x88, 0x94, 0xce, 0x19, 0x01, 0x71, 0x4c, - 0xa5, 0xe3, 0xc5, 0x31, 0xbb, 0xcc, 0x1f, 0x2d, - 0x3b, 0x52, 0x6f, 0xf6, 0x2e, 0x89, 0xf7, 0xc0, - 0x68, 0x1b, 0x64, 0x04, 0x06, 0xbf, 0x83, 0x38} - - // expTable provides the anti-log or exponentiation value - // for the equivalent index - expTable = [256]uint8{ - 0x01, 0xe5, 0x4c, 0xb5, 0xfb, 0x9f, 0xfc, 0x12, - 0x03, 0x34, 0xd4, 0xc4, 0x16, 0xba, 0x1f, 0x36, - 0x05, 0x5c, 0x67, 0x57, 0x3a, 0xd5, 0x21, 0x5a, - 0x0f, 0xe4, 0xa9, 0xf9, 0x4e, 0x64, 0x63, 0xee, - 0x11, 0x37, 0xe0, 0x10, 0xd2, 0xac, 0xa5, 0x29, - 0x33, 0x59, 0x3b, 0x30, 0x6d, 0xef, 0xf4, 0x7b, - 0x55, 0xeb, 0x4d, 0x50, 0xb7, 0x2a, 0x07, 0x8d, - 0xff, 0x26, 0xd7, 0xf0, 0xc2, 0x7e, 0x09, 0x8c, - 0x1a, 0x6a, 0x62, 0x0b, 0x5d, 0x82, 0x1b, 0x8f, - 0x2e, 0xbe, 0xa6, 0x1d, 0xe7, 0x9d, 0x2d, 0x8a, - 0x72, 0xd9, 0xf1, 0x27, 0x32, 0xbc, 0x77, 0x85, - 0x96, 0x70, 0x08, 0x69, 0x56, 0xdf, 0x99, 0x94, - 0xa1, 0x90, 0x18, 0xbb, 0xfa, 0x7a, 0xb0, 0xa7, - 0xf8, 0xab, 0x28, 0xd6, 0x15, 0x8e, 0xcb, 0xf2, - 0x13, 0xe6, 0x78, 0x61, 0x3f, 0x89, 0x46, 0x0d, - 0x35, 0x31, 0x88, 0xa3, 0x41, 0x80, 0xca, 0x17, - 0x5f, 0x53, 0x83, 0xfe, 0xc3, 0x9b, 0x45, 0x39, - 0xe1, 0xf5, 0x9e, 0x19, 0x5e, 0xb6, 0xcf, 0x4b, - 0x38, 0x04, 0xb9, 0x2b, 0xe2, 0xc1, 0x4a, 0xdd, - 0x48, 0x0c, 0xd0, 0x7d, 0x3d, 0x58, 0xde, 0x7c, - 0xd8, 0x14, 0x6b, 0x87, 0x47, 0xe8, 0x79, 0x84, - 0x73, 0x3c, 0xbd, 0x92, 0xc9, 0x23, 0x8b, 0x97, - 0x95, 0x44, 0xdc, 0xad, 0x40, 0x65, 0x86, 0xa2, - 0xa4, 0xcc, 0x7f, 0xec, 0xc0, 0xaf, 0x91, 0xfd, - 0xf7, 0x4f, 0x81, 0x2f, 0x5b, 0xea, 0xa8, 0x1c, - 0x02, 0xd1, 0x98, 0x71, 0xed, 0x25, 0xe3, 0x24, - 0x06, 0x68, 0xb3, 0x93, 0x2c, 0x6f, 0x3e, 0x6c, - 0x0a, 0xb8, 0xce, 0xae, 0x74, 0xb1, 0x42, 0xb4, - 0x1e, 0xd3, 0x49, 0xe9, 0x9c, 0xc8, 0xc6, 0xc7, - 0x22, 0x6e, 0xdb, 0x20, 0xbf, 0x43, 0x51, 0x52, - 0x66, 0xb2, 0x76, 0x60, 0xda, 0xc5, 0xf3, 0xf6, - 0xaa, 0xcd, 0x9a, 0xa0, 0x75, 0x54, 0x0e, 0x01} -) diff --git a/vendor/github.com/hashicorp/vault/vault/acl.go b/vendor/github.com/hashicorp/vault/vault/acl.go deleted file mode 100644 index d027729d3..000000000 --- a/vendor/github.com/hashicorp/vault/vault/acl.go +++ /dev/null @@ -1,481 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "reflect" - "strings" - - "github.com/armon/go-radix" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -// ACL is used to wrap a set of policies to provide -// an efficient interface for access control. -type ACL struct { - // exactRules contains the path policies that are exact - exactRules *radix.Tree - - // globRules contains the path policies that glob - globRules *radix.Tree - - // root is enabled if the "root" named policy is present. - root bool -} - -type PolicyCheckOpts struct { - RootPrivsRequired bool - Unauth bool -} - -type AuthResults struct { - ACLResults *ACLResults - Allowed bool - RootPrivs bool - DeniedError bool - Error *multierror.Error -} - -type ACLResults struct { - Allowed bool - RootPrivs bool - IsRoot bool - MFAMethods []string -} - -// New is used to construct a policy based ACL from a set of policies. -func NewACL(policies []*Policy) (*ACL, error) { - // Initialize - a := &ACL{ - exactRules: radix.New(), - globRules: radix.New(), - root: false, - } - - // Inject each policy - for _, policy := range policies { - // Ignore a nil policy object - if policy == nil { - continue - } - - switch policy.Type { - case PolicyTypeACL: - default: - return nil, fmt.Errorf("unable to parse policy (wrong type)") - } - - // Check if this is root - if policy.Name == "root" { - if len(policies) != 1 { - return nil, fmt.Errorf("other policies present along with root") - } - a.root = true - } - - for _, pc := range policy.Paths { - // Check which tree to use - tree := a.exactRules - if pc.Glob { - tree = a.globRules - } - - // Check for an existing policy - raw, ok := tree.Get(pc.Prefix) - if !ok { - clonedPerms, err := pc.Permissions.Clone() - if err != nil { - return nil, errwrap.Wrapf("error cloning ACL permissions: {{err}}", err) - } - tree.Insert(pc.Prefix, clonedPerms) - continue - } - - // these are the ones already in the tree - existingPerms := raw.(*ACLPermissions) - - switch { - case existingPerms.CapabilitiesBitmap&DenyCapabilityInt > 0: - // If we are explicitly denied in the existing capability set, - // don't save anything else - continue - - case pc.Permissions.CapabilitiesBitmap&DenyCapabilityInt > 0: - // If this new policy explicitly denies, only save the deny value - existingPerms.CapabilitiesBitmap = DenyCapabilityInt - existingPerms.AllowedParameters = nil - existingPerms.DeniedParameters = nil - goto INSERT - - default: - // Insert the capabilities in this new policy into the existing - // value - existingPerms.CapabilitiesBitmap = existingPerms.CapabilitiesBitmap | pc.Permissions.CapabilitiesBitmap - } - - // Note: In these stanzas, we're preferring minimum lifetimes. So - // we take the lesser of two specified max values, or we take the - // lesser of two specified min values, the idea being, allowing - // token lifetime to be minimum possible. - // - // If we have an existing max, and we either don't have a current - // max, or the current is greater than the previous, use the - // existing. - if pc.Permissions.MaxWrappingTTL > 0 && - (existingPerms.MaxWrappingTTL == 0 || - pc.Permissions.MaxWrappingTTL < existingPerms.MaxWrappingTTL) { - existingPerms.MaxWrappingTTL = pc.Permissions.MaxWrappingTTL - } - // If we have an existing min, and we either don't have a current - // min, or the current is greater than the previous, use the - // existing - if pc.Permissions.MinWrappingTTL > 0 && - (existingPerms.MinWrappingTTL == 0 || - pc.Permissions.MinWrappingTTL < existingPerms.MinWrappingTTL) { - existingPerms.MinWrappingTTL = pc.Permissions.MinWrappingTTL - } - - if len(pc.Permissions.AllowedParameters) > 0 { - if existingPerms.AllowedParameters == nil { - clonedAllowed, err := copystructure.Copy(pc.Permissions.AllowedParameters) - if err != nil { - return nil, err - } - existingPerms.AllowedParameters = clonedAllowed.(map[string][]interface{}) - } else { - for key, value := range pc.Permissions.AllowedParameters { - pcValue, ok := existingPerms.AllowedParameters[key] - // If an empty array exist it should overwrite any other - // value. - if len(value) == 0 || (ok && len(pcValue) == 0) { - existingPerms.AllowedParameters[key] = []interface{}{} - } else { - // Merge the two maps, appending values on key conflict. - existingPerms.AllowedParameters[key] = append(value, existingPerms.AllowedParameters[key]...) - } - } - } - } - - if len(pc.Permissions.DeniedParameters) > 0 { - if existingPerms.DeniedParameters == nil { - clonedDenied, err := copystructure.Copy(pc.Permissions.DeniedParameters) - if err != nil { - return nil, err - } - existingPerms.DeniedParameters = clonedDenied.(map[string][]interface{}) - } else { - for key, value := range pc.Permissions.DeniedParameters { - pcValue, ok := existingPerms.DeniedParameters[key] - // If an empty array exist it should overwrite any other - // value. - if len(value) == 0 || (ok && len(pcValue) == 0) { - existingPerms.DeniedParameters[key] = []interface{}{} - } else { - // Merge the two maps, appending values on key conflict. - existingPerms.DeniedParameters[key] = append(value, existingPerms.DeniedParameters[key]...) - } - } - } - } - - if len(pc.Permissions.RequiredParameters) > 0 { - if len(existingPerms.RequiredParameters) == 0 { - existingPerms.RequiredParameters = pc.Permissions.RequiredParameters - } else { - for _, v := range pc.Permissions.RequiredParameters { - if !strutil.StrListContains(existingPerms.RequiredParameters, v) { - existingPerms.RequiredParameters = append(existingPerms.RequiredParameters, v) - } - } - } - } - - INSERT: - tree.Insert(pc.Prefix, existingPerms) - } - } - return a, nil -} - -func (a *ACL) Capabilities(path string) (pathCapabilities []string) { - // Fast-path root - if a.root { - return []string{RootCapability} - } - - // Find an exact matching rule, look for glob if no match - var capabilities uint32 - raw, ok := a.exactRules.Get(path) - - if ok { - perm := raw.(*ACLPermissions) - capabilities = perm.CapabilitiesBitmap - goto CHECK - } - if strings.HasSuffix(path, "/") { - raw, ok = a.exactRules.Get(strings.TrimSuffix(path, "/")) - if ok { - perm := raw.(*ACLPermissions) - capabilities = perm.CapabilitiesBitmap - goto CHECK - } - } - - // Find a glob rule, default deny if no match - _, raw, ok = a.globRules.LongestPrefix(path) - if !ok { - return []string{DenyCapability} - } else { - perm := raw.(*ACLPermissions) - capabilities = perm.CapabilitiesBitmap - } - -CHECK: - if capabilities&SudoCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, SudoCapability) - } - if capabilities&ReadCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, ReadCapability) - } - if capabilities&ListCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, ListCapability) - } - if capabilities&UpdateCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, UpdateCapability) - } - if capabilities&DeleteCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, DeleteCapability) - } - if capabilities&CreateCapabilityInt > 0 { - pathCapabilities = append(pathCapabilities, CreateCapability) - } - - // If "deny" is explicitly set or if the path has no capabilities at all, - // set the path capabilities to "deny" - if capabilities&DenyCapabilityInt > 0 || len(pathCapabilities) == 0 { - pathCapabilities = []string{DenyCapability} - } - return -} - -// AllowOperation is used to check if the given operation is permitted. -func (a *ACL) AllowOperation(req *logical.Request) (ret *ACLResults) { - ret = new(ACLResults) - - // Fast-path root - if a.root { - ret.Allowed = true - ret.RootPrivs = true - ret.IsRoot = true - return - } - op := req.Operation - path := req.Path - - // Help is always allowed - if op == logical.HelpOperation { - ret.Allowed = true - return - } - - var permissions *ACLPermissions - - // Find an exact matching rule, look for glob if no match - var capabilities uint32 - raw, ok := a.exactRules.Get(path) - if ok { - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - goto CHECK - } - if op == logical.ListOperation { - raw, ok = a.exactRules.Get(strings.TrimSuffix(path, "/")) - if ok { - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - goto CHECK - } - } - - // Find a glob rule, default deny if no match - _, raw, ok = a.globRules.LongestPrefix(path) - if !ok { - return - } else { - permissions = raw.(*ACLPermissions) - capabilities = permissions.CapabilitiesBitmap - } - -CHECK: - // Check if the minimum permissions are met - // If "deny" has been explicitly set, only deny will be in the map, so we - // only need to check for the existence of other values - ret.RootPrivs = capabilities&SudoCapabilityInt > 0 - - operationAllowed := false - switch op { - case logical.ReadOperation: - operationAllowed = capabilities&ReadCapabilityInt > 0 - case logical.ListOperation: - operationAllowed = capabilities&ListCapabilityInt > 0 - case logical.UpdateOperation: - operationAllowed = capabilities&UpdateCapabilityInt > 0 - case logical.DeleteOperation: - operationAllowed = capabilities&DeleteCapabilityInt > 0 - case logical.CreateOperation: - operationAllowed = capabilities&CreateCapabilityInt > 0 - - // These three re-use UpdateCapabilityInt since that's the most appropriate - // capability/operation mapping - case logical.RevokeOperation, logical.RenewOperation, logical.RollbackOperation: - operationAllowed = capabilities&UpdateCapabilityInt > 0 - - default: - return - } - - if !operationAllowed { - return - } - - if permissions.MaxWrappingTTL > 0 { - if req.WrapInfo == nil || req.WrapInfo.TTL > permissions.MaxWrappingTTL { - return - } - } - if permissions.MinWrappingTTL > 0 { - if req.WrapInfo == nil || req.WrapInfo.TTL < permissions.MinWrappingTTL { - return - } - } - // This situation can happen because of merging, even though in a single - // path statement we check on ingress - if permissions.MinWrappingTTL != 0 && - permissions.MaxWrappingTTL != 0 && - permissions.MaxWrappingTTL < permissions.MinWrappingTTL { - return - } - - // Only check parameter permissions for operations that can modify - // parameters. - if op == logical.ReadOperation || op == logical.UpdateOperation || op == logical.CreateOperation { - for _, parameter := range permissions.RequiredParameters { - if _, ok := req.Data[strings.ToLower(parameter)]; !ok { - return - } - } - - // If there are no data fields, allow - if len(req.Data) == 0 { - ret.Allowed = true - return - } - - if len(permissions.DeniedParameters) == 0 { - goto ALLOWED_PARAMETERS - } - - // Check if all parameters have been denied - if _, ok := permissions.DeniedParameters["*"]; ok { - return - } - - for parameter, value := range req.Data { - // Check if parameter has been explicitly denied - if valueSlice, ok := permissions.DeniedParameters[strings.ToLower(parameter)]; ok { - // If the value exists in denied values slice, deny - if valueInParameterList(value, valueSlice) { - return - } - } - } - - ALLOWED_PARAMETERS: - // If we don't have any allowed parameters set, allow - if len(permissions.AllowedParameters) == 0 { - ret.Allowed = true - return - } - - _, allowedAll := permissions.AllowedParameters["*"] - if len(permissions.AllowedParameters) == 1 && allowedAll { - ret.Allowed = true - return - } - - for parameter, value := range req.Data { - valueSlice, ok := permissions.AllowedParameters[strings.ToLower(parameter)] - // Requested parameter is not in allowed list - if !ok && !allowedAll { - return - } - - // If the value doesn't exists in the allowed values slice, - // deny - if ok && !valueInParameterList(value, valueSlice) { - return - } - } - } - - ret.Allowed = true - return -} -func (c *Core) performPolicyChecks(ctx context.Context, acl *ACL, te *logical.TokenEntry, req *logical.Request, inEntity *identity.Entity, opts *PolicyCheckOpts) (ret *AuthResults) { - ret = new(AuthResults) - - // First, perform normal ACL checks if requested. The only time no ACL - // should be applied is if we are only processing EGPs against a login - // path in which case opts.Unauth will be set. - if acl != nil && !opts.Unauth { - ret.ACLResults = acl.AllowOperation(req) - ret.RootPrivs = ret.ACLResults.RootPrivs - // Root is always allowed; skip Sentinel/MFA checks - if ret.ACLResults.IsRoot { - //c.logger.Warn("policy: token is root, skipping checks") - ret.Allowed = true - return - } - if !ret.ACLResults.Allowed { - return - } - if !ret.RootPrivs && opts.RootPrivsRequired { - return - } - } - - ret.Allowed = true - return -} - -func valueInParameterList(v interface{}, list []interface{}) bool { - // Empty list is equivalent to the item always existing in the list - if len(list) == 0 { - return true - } - - return valueInSlice(v, list) -} - -func valueInSlice(v interface{}, list []interface{}) bool { - for _, el := range list { - if reflect.TypeOf(el).String() == "string" && reflect.TypeOf(v).String() == "string" { - item := el.(string) - val := v.(string) - - if strutil.GlobbedStringsMatch(item, val) { - return true - } - } else if reflect.DeepEqual(el, v) { - return true - } - } - - return false -} diff --git a/vendor/github.com/hashicorp/vault/vault/audit.go b/vendor/github.com/hashicorp/vault/vault/audit.go deleted file mode 100644 index 491f47196..000000000 --- a/vendor/github.com/hashicorp/vault/vault/audit.go +++ /dev/null @@ -1,464 +0,0 @@ -package vault - -import ( - "context" - "crypto/sha256" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -const ( - // coreAuditConfigPath is used to store the audit configuration. - // Audit configuration is protected within the Vault itself, which means it - // can only be viewed or modified after an unseal. - coreAuditConfigPath = "core/audit" - - // coreLocalAuditConfigPath is used to store audit information for local - // (non-replicated) mounts - coreLocalAuditConfigPath = "core/local-audit" - - // auditBarrierPrefix is the prefix to the UUID used in the - // barrier view for the audit backends. - auditBarrierPrefix = "audit/" - - // auditTableType is the value we expect to find for the audit table and - // corresponding entries - auditTableType = "audit" -) - -var ( - // loadAuditFailed if loading audit tables encounters an error - errLoadAuditFailed = errors.New("failed to setup audit table") -) - -// enableAudit is used to enable a new audit backend -func (c *Core) enableAudit(ctx context.Context, entry *MountEntry) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Ensure there is a name - if entry.Path == "/" { - return fmt.Errorf("backend path must be specified") - } - - // Update the audit table - c.auditLock.Lock() - defer c.auditLock.Unlock() - - // Look for matching name - for _, ent := range c.audit.Entries { - switch { - // Existing is sql/mysql/ new is sql/ or - // existing is sql/ and new is sql/mysql/ - case strings.HasPrefix(ent.Path, entry.Path): - fallthrough - case strings.HasPrefix(entry.Path, ent.Path): - return fmt.Errorf("path already in use") - } - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("audit_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - viewPath := auditBarrierPrefix + entry.UUID + "/" - view := NewBarrierView(c.barrier, viewPath) - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - defer view.setReadOnlyErr(nil) - - // Lookup the new backend - backend, err := c.newAuditBackend(ctx, entry, view, entry.Options) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil audit backend of type %q returned from factory", entry.Type) - } - - newTable := c.audit.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - if err := c.persistAudit(ctx, newTable, entry.Local); err != nil { - return errors.New("failed to update audit table") - } - - c.audit = newTable - - // Register the backend - c.auditBroker.Register(entry.Path, backend, view) - if c.logger.IsInfo() { - c.logger.Info("enabled audit backend", "path", entry.Path, "type", entry.Type) - } - return nil -} - -// disableAudit is used to disable an existing audit backend -func (c *Core) disableAudit(ctx context.Context, path string) (bool, error) { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Remove the entry from the mount table - c.auditLock.Lock() - defer c.auditLock.Unlock() - - newTable := c.audit.shallowClone() - entry := newTable.remove(path) - - // Ensure there was a match - if entry == nil { - return false, fmt.Errorf("no matching backend") - } - - c.removeAuditReloadFunc(entry) - - // When unmounting all entries the JSON code will load back up from storage - // as a nil slice, which kills tests...just set it nil explicitly - if len(newTable.Entries) == 0 { - newTable.Entries = nil - } - - // Update the audit table - if err := c.persistAudit(ctx, newTable, entry.Local); err != nil { - return true, errors.New("failed to update audit table") - } - - c.audit = newTable - - // Unmount the backend - c.auditBroker.Deregister(path) - if c.logger.IsInfo() { - c.logger.Info("disabled audit backend", "path", path) - } - - return true, nil -} - -// loadAudits is invoked as part of postUnseal to load the audit table -func (c *Core) loadAudits(ctx context.Context) error { - auditTable := &MountTable{} - localAuditTable := &MountTable{} - - // Load the existing audit table - raw, err := c.barrier.Get(ctx, coreAuditConfigPath) - if err != nil { - c.logger.Error("failed to read audit table", "error", err) - return errLoadAuditFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalAuditConfigPath) - if err != nil { - c.logger.Error("failed to read local audit table", "error", err) - return errLoadAuditFailed - } - - c.auditLock.Lock() - defer c.auditLock.Unlock() - - if raw != nil { - if err := jsonutil.DecodeJSON(raw.Value, auditTable); err != nil { - c.logger.Error("failed to decode audit table", "error", err) - return errLoadAuditFailed - } - c.audit = auditTable - } - - var needPersist bool - if c.audit == nil { - c.audit = defaultAuditTable() - needPersist = true - } - - if rawLocal != nil { - if err := jsonutil.DecodeJSON(rawLocal.Value, localAuditTable); err != nil { - c.logger.Error("failed to decode local audit table", "error", err) - return errLoadAuditFailed - } - if localAuditTable != nil && len(localAuditTable.Entries) > 0 { - c.audit.Entries = append(c.audit.Entries, localAuditTable.Entries...) - } - } - - // Upgrade to typed auth table - if c.audit.Type == "" { - c.audit.Type = auditTableType - needPersist = true - } - - // Upgrade to table-scoped entries - for _, entry := range c.audit.Entries { - if entry.Table == "" { - entry.Table = c.audit.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("audit_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - } - - if !needPersist { - return nil - } - - if err := c.persistAudit(ctx, c.audit, false); err != nil { - return errLoadAuditFailed - } - return nil -} - -// persistAudit is used to persist the audit table after modification -func (c *Core) persistAudit(ctx context.Context, table *MountTable, localOnly bool) error { - if table.Type != auditTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", auditTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in audit table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid audit entry found, not persisting") - } - } - - nonLocalAudit := &MountTable{ - Type: auditTableType, - } - - localAudit := &MountTable{ - Type: auditTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localAudit.Entries = append(localAudit.Entries, entry) - } else { - nonLocalAudit.Entries = append(nonLocalAudit.Entries, entry) - } - } - - if !localOnly { - // Marshal the table - compressedBytes, err := jsonutil.EncodeJSONAndCompress(nonLocalAudit, nil) - if err != nil { - c.logger.Error("failed to encode and/or compress audit table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: coreAuditConfigPath, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist audit table", "error", err) - return err - } - } - - // Repeat with local audit - compressedBytes, err := jsonutil.EncodeJSONAndCompress(localAudit, nil) - if err != nil { - c.logger.Error("failed to encode and/or compress local audit table", "error", err) - return err - } - - entry := &Entry{ - Key: coreLocalAuditConfigPath, - Value: compressedBytes, - } - - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist local audit table", "error", err) - return err - } - - return nil -} - -// setupAudit is invoked after we've loaded the audit able to -// initialize the audit backends -func (c *Core) setupAudits(ctx context.Context) error { - brokerLogger := c.baseLogger.Named("audit") - c.AddLogger(brokerLogger) - broker := NewAuditBroker(brokerLogger) - - c.auditLock.Lock() - defer c.auditLock.Unlock() - - var successCount int - - for _, entry := range c.audit.Entries { - // Create a barrier view using the UUID - viewPath := auditBarrierPrefix + entry.UUID + "/" - view := NewBarrierView(c.barrier, viewPath) - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(nil) - }) - - // Initialize the backend - backend, err := c.newAuditBackend(ctx, entry, view, entry.Options) - if err != nil { - c.logger.Error("failed to create audit entry", "path", entry.Path, "error", err) - continue - } - if backend == nil { - c.logger.Error("created audit entry was nil", "path", entry.Path, "type", entry.Type) - continue - } - - // Mount the backend - broker.Register(entry.Path, backend, view) - - successCount += 1 - } - - if len(c.audit.Entries) > 0 && successCount == 0 { - return errLoadAuditFailed - } - - c.auditBroker = broker - return nil -} - -// teardownAudit is used before we seal the vault to reset the audit -// backends to their unloaded state. This is reversed by loadAudits. -func (c *Core) teardownAudits() error { - c.auditLock.Lock() - defer c.auditLock.Unlock() - - if c.audit != nil { - for _, entry := range c.audit.Entries { - c.removeAuditReloadFunc(entry) - } - } - - c.audit = nil - c.auditBroker = nil - return nil -} - -// removeAuditReloadFunc removes the reload func from the working set. The -// audit lock needs to be held before calling this. -func (c *Core) removeAuditReloadFunc(entry *MountEntry) { - switch entry.Type { - case "file": - key := "audit_file|" + entry.Path - c.reloadFuncsLock.Lock() - - if c.logger.IsDebug() { - c.baseLogger.Named("audit").Debug("removing reload function", "path", entry.Path) - } - - delete(c.reloadFuncs, key) - - c.reloadFuncsLock.Unlock() - } -} - -// newAuditBackend is used to create and configure a new audit backend by name -func (c *Core) newAuditBackend(ctx context.Context, entry *MountEntry, view logical.Storage, conf map[string]string) (audit.Backend, error) { - f, ok := c.auditBackends[entry.Type] - if !ok { - return nil, fmt.Errorf("unknown backend type: %q", entry.Type) - } - saltConfig := &salt.Config{ - HMAC: sha256.New, - HMACType: "hmac-sha256", - Location: salt.DefaultLocation, - } - - be, err := f(ctx, &audit.BackendConfig{ - SaltView: view, - SaltConfig: saltConfig, - Config: conf, - }) - if err != nil { - return nil, err - } - if be == nil { - return nil, fmt.Errorf("nil backend returned from %q factory function", entry.Type) - } - - auditLogger := c.baseLogger.Named("audit") - c.AddLogger(auditLogger) - - switch entry.Type { - case "file": - key := "audit_file|" + entry.Path - - c.reloadFuncsLock.Lock() - - if auditLogger.IsDebug() { - auditLogger.Debug("adding reload function", "path", entry.Path) - if entry.Options != nil { - auditLogger.Debug("file backend options", "path", entry.Path, "file_path", entry.Options["file_path"]) - } - } - - c.reloadFuncs[key] = append(c.reloadFuncs[key], func(map[string]interface{}) error { - if auditLogger.IsInfo() { - auditLogger.Info("reloading file audit backend", "path", entry.Path) - } - return be.Reload(ctx) - }) - - c.reloadFuncsLock.Unlock() - case "socket": - if auditLogger.IsDebug() { - if entry.Options != nil { - auditLogger.Debug("socket backend options", "path", entry.Path, "address", entry.Options["address"], "socket type", entry.Options["socket_type"]) - } - } - case "syslog": - if auditLogger.IsDebug() { - if entry.Options != nil { - auditLogger.Debug("syslog backend options", "path", entry.Path, "facility", entry.Options["facility"], "tag", entry.Options["tag"]) - } - } - } - - return be, err -} - -// defaultAuditTable creates a default audit table -func defaultAuditTable() *MountTable { - table := &MountTable{ - Type: auditTableType, - } - return table -} diff --git a/vendor/github.com/hashicorp/vault/vault/audit_broker.go b/vendor/github.com/hashicorp/vault/vault/audit_broker.go deleted file mode 100644 index ae6f48ecc..000000000 --- a/vendor/github.com/hashicorp/vault/vault/audit_broker.go +++ /dev/null @@ -1,200 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "sync" - "time" - - metrics "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/audit" -) - -type backendEntry struct { - backend audit.Backend - view *BarrierView -} - -// AuditBroker is used to provide a single ingest interface to auditable -// events given that multiple backends may be configured. -type AuditBroker struct { - sync.RWMutex - backends map[string]backendEntry - logger log.Logger -} - -// NewAuditBroker creates a new audit broker -func NewAuditBroker(log log.Logger) *AuditBroker { - b := &AuditBroker{ - backends: make(map[string]backendEntry), - logger: log, - } - return b -} - -// Register is used to add new audit backend to the broker -func (a *AuditBroker) Register(name string, b audit.Backend, v *BarrierView) { - a.Lock() - defer a.Unlock() - a.backends[name] = backendEntry{ - backend: b, - view: v, - } -} - -// Deregister is used to remove an audit backend from the broker -func (a *AuditBroker) Deregister(name string) { - a.Lock() - defer a.Unlock() - delete(a.backends, name) -} - -// IsRegistered is used to check if a given audit backend is registered -func (a *AuditBroker) IsRegistered(name string) bool { - a.RLock() - defer a.RUnlock() - _, ok := a.backends[name] - return ok -} - -// GetHash returns a hash using the salt of the given backend -func (a *AuditBroker) GetHash(ctx context.Context, name string, input string) (string, error) { - a.RLock() - defer a.RUnlock() - be, ok := a.backends[name] - if !ok { - return "", fmt.Errorf("unknown audit backend %q", name) - } - - return be.backend.GetHash(ctx, input) -} - -// LogRequest is used to ensure all the audit backends have an opportunity to -// log the given request and that *at least one* succeeds. -func (a *AuditBroker) LogRequest(ctx context.Context, in *audit.LogInput, headersConfig *AuditedHeadersConfig) (ret error) { - defer metrics.MeasureSince([]string{"audit", "log_request"}, time.Now()) - a.RLock() - defer a.RUnlock() - - var retErr *multierror.Error - - defer func() { - if r := recover(); r != nil { - a.logger.Error("panic during logging", "request_path", in.Request.Path, "error", r) - retErr = multierror.Append(retErr, fmt.Errorf("panic generating audit log")) - } - - ret = retErr.ErrorOrNil() - failure := float32(0.0) - if ret != nil { - failure = 1.0 - } - metrics.IncrCounter([]string{"audit", "log_request_failure"}, failure) - }() - - // All logged requests must have an identifier - //if req.ID == "" { - // a.logger.Error("missing identifier in request object", "request_path", req.Path) - // retErr = multierror.Append(retErr, fmt.Errorf("missing identifier in request object: %s", req.Path)) - // return - //} - - headers := in.Request.Headers - defer func() { - in.Request.Headers = headers - }() - - // Ensure at least one backend logs - anyLogged := false - for name, be := range a.backends { - in.Request.Headers = nil - transHeaders, thErr := headersConfig.ApplyConfig(ctx, headers, be.backend.GetHash) - if thErr != nil { - a.logger.Error("backend failed to include headers", "backend", name, "error", thErr) - continue - } - in.Request.Headers = transHeaders - - start := time.Now() - lrErr := be.backend.LogRequest(ctx, in) - metrics.MeasureSince([]string{"audit", name, "log_request"}, start) - if lrErr != nil { - a.logger.Error("backend failed to log request", "backend", name, "error", lrErr) - } else { - anyLogged = true - } - } - if !anyLogged && len(a.backends) > 0 { - retErr = multierror.Append(retErr, fmt.Errorf("no audit backend succeeded in logging the request")) - } - - return retErr.ErrorOrNil() -} - -// LogResponse is used to ensure all the audit backends have an opportunity to -// log the given response and that *at least one* succeeds. -func (a *AuditBroker) LogResponse(ctx context.Context, in *audit.LogInput, headersConfig *AuditedHeadersConfig) (ret error) { - defer metrics.MeasureSince([]string{"audit", "log_response"}, time.Now()) - a.RLock() - defer a.RUnlock() - - var retErr *multierror.Error - - defer func() { - if r := recover(); r != nil { - a.logger.Error("panic during logging", "request_path", in.Request.Path, "error", r) - retErr = multierror.Append(retErr, fmt.Errorf("panic generating audit log")) - } - - ret = retErr.ErrorOrNil() - - failure := float32(0.0) - if ret != nil { - failure = 1.0 - } - metrics.IncrCounter([]string{"audit", "log_response_failure"}, failure) - }() - - headers := in.Request.Headers - defer func() { - in.Request.Headers = headers - }() - - // Ensure at least one backend logs - anyLogged := false - for name, be := range a.backends { - in.Request.Headers = nil - transHeaders, thErr := headersConfig.ApplyConfig(ctx, headers, be.backend.GetHash) - if thErr != nil { - a.logger.Error("backend failed to include headers", "backend", name, "error", thErr) - continue - } - in.Request.Headers = transHeaders - - start := time.Now() - lrErr := be.backend.LogResponse(ctx, in) - metrics.MeasureSince([]string{"audit", name, "log_response"}, start) - if lrErr != nil { - a.logger.Error("backend failed to log response", "backend", name, "error", lrErr) - } else { - anyLogged = true - } - } - if !anyLogged && len(a.backends) > 0 { - retErr = multierror.Append(retErr, fmt.Errorf("no audit backend succeeded in logging the response")) - } - - return retErr.ErrorOrNil() -} - -func (a *AuditBroker) Invalidate(ctx context.Context, key string) { - // For now we ignore the key as this would only apply to salts. We just - // sort of brute force it on each one. - a.Lock() - defer a.Unlock() - for _, be := range a.backends { - be.backend.Invalidate(ctx) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/audited_headers.go b/vendor/github.com/hashicorp/vault/vault/audited_headers.go deleted file mode 100644 index ca8383ea8..000000000 --- a/vendor/github.com/hashicorp/vault/vault/audited_headers.go +++ /dev/null @@ -1,162 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/logical" -) - -// N.B.: While we could use textproto to get the canonical mime header, HTTP/2 -// requires all headers to be converted to lower case, so we just do that. - -const ( - // Key used in the BarrierView to store and retrieve the header config - auditedHeadersEntry = "audited-headers" - // Path used to create a sub view off of BarrierView - auditedHeadersSubPath = "audited-headers-config/" -) - -type auditedHeaderSettings struct { - HMAC bool `json:"hmac"` -} - -// AuditedHeadersConfig is used by the Audit Broker to write only approved -// headers to the audit logs. It uses a BarrierView to persist the settings. -type AuditedHeadersConfig struct { - Headers map[string]*auditedHeaderSettings - - view *BarrierView - sync.RWMutex -} - -// add adds or overwrites a header in the config and updates the barrier view -func (a *AuditedHeadersConfig) add(ctx context.Context, header string, hmac bool) error { - if header == "" { - return fmt.Errorf("header value cannot be empty") - } - - // Grab a write lock - a.Lock() - defer a.Unlock() - - if a.Headers == nil { - a.Headers = make(map[string]*auditedHeaderSettings, 1) - } - - a.Headers[strings.ToLower(header)] = &auditedHeaderSettings{hmac} - entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) - if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - return nil -} - -// remove deletes a header out of the header config and updates the barrier view -func (a *AuditedHeadersConfig) remove(ctx context.Context, header string) error { - if header == "" { - return fmt.Errorf("header value cannot be empty") - } - - // Grab a write lock - a.Lock() - defer a.Unlock() - - // Nothing to delete - if len(a.Headers) == 0 { - return nil - } - - delete(a.Headers, strings.ToLower(header)) - entry, err := logical.StorageEntryJSON(auditedHeadersEntry, a.Headers) - if err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - if err := a.view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist audited headers config: {{err}}", err) - } - - return nil -} - -// ApplyConfig returns a map of approved headers and their values, either -// hmac'ed or plaintext -func (a *AuditedHeadersConfig) ApplyConfig(ctx context.Context, headers map[string][]string, hashFunc func(context.Context, string) (string, error)) (result map[string][]string, retErr error) { - // Grab a read lock - a.RLock() - defer a.RUnlock() - - // Make a copy of the incoming headers with everything lower so we can - // case-insensitively compare - lowerHeaders := make(map[string][]string, len(headers)) - for k, v := range headers { - lowerHeaders[strings.ToLower(k)] = v - } - - result = make(map[string][]string, len(a.Headers)) - for key, settings := range a.Headers { - if val, ok := lowerHeaders[key]; ok { - // copy the header values so we don't overwrite them - hVals := make([]string, len(val)) - copy(hVals, val) - - // Optionally hmac the values - if settings.HMAC { - for i, el := range hVals { - hVal, err := hashFunc(ctx, el) - if err != nil { - return nil, err - } - hVals[i] = hVal - } - } - - result[key] = hVals - } - } - - return result, nil -} - -// Initialize the headers config by loading from the barrier view -func (c *Core) setupAuditedHeadersConfig(ctx context.Context) error { - // Create a sub-view - view := c.systemBarrierView.SubView(auditedHeadersSubPath) - - // Create the config - out, err := view.Get(ctx, auditedHeadersEntry) - if err != nil { - return errwrap.Wrapf("failed to read config: {{err}}", err) - } - - headers := make(map[string]*auditedHeaderSettings) - if out != nil { - err = out.DecodeJSON(&headers) - if err != nil { - return err - } - } - - // Ensure that we are able to case-sensitively access the headers; - // necessary for the upgrade case - lowerHeaders := make(map[string]*auditedHeaderSettings, len(headers)) - for k, v := range headers { - lowerHeaders[strings.ToLower(k)] = v - } - - c.auditedHeaders = &AuditedHeadersConfig{ - Headers: lowerHeaders, - view: view, - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/auth.go b/vendor/github.com/hashicorp/vault/vault/auth.go deleted file mode 100644 index 594c46ccb..000000000 --- a/vendor/github.com/hashicorp/vault/vault/auth.go +++ /dev/null @@ -1,627 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - // coreAuthConfigPath is used to store the auth configuration. - // Auth configuration is protected within the Vault itself, which means it - // can only be viewed or modified after an unseal. - coreAuthConfigPath = "core/auth" - - // coreLocalAuthConfigPath is used to store credential configuration for - // local (non-replicated) mounts - coreLocalAuthConfigPath = "core/local-auth" - - // credentialBarrierPrefix is the prefix to the UUID used in the - // barrier view for the credential backends. - credentialBarrierPrefix = "auth/" - - // credentialRoutePrefix is the mount prefix used for the router - credentialRoutePrefix = "auth/" - - // credentialTableType is the value we expect to find for the credential - // table and corresponding entries - credentialTableType = "auth" -) - -var ( - // errLoadAuthFailed if loadCredentials encounters an error - errLoadAuthFailed = errors.New("failed to setup auth table") - - // credentialAliases maps old backend names to new backend names, allowing us - // to move/rename backends but maintain backwards compatibility - credentialAliases = map[string]string{"aws-ec2": "aws"} -) - -// enableCredential is used to enable a new credential backend -func (c *Core) enableCredential(ctx context.Context, entry *MountEntry) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Ensure there is a name - if entry.Path == "/" { - return fmt.Errorf("backend path must be specified") - } - - c.authLock.Lock() - defer c.authLock.Unlock() - - // Look for matching name - for _, ent := range c.auth.Entries { - switch { - // Existing is oauth/github/ new is oauth/ or - // existing is oauth/ and new is oauth/github/ - case strings.HasPrefix(ent.Path, entry.Path): - fallthrough - case strings.HasPrefix(entry.Path, ent.Path): - return logical.CodedError(409, "path is already in use") - } - } - - // Ensure the token backend is a singleton - if entry.Type == "token" { - return fmt.Errorf("token credential backend cannot be instantiated") - } - - if conflict := c.router.MountConflict(credentialRoutePrefix + entry.Path); conflict != "" { - return logical.CodedError(409, fmt.Sprintf("existing mount at %s", conflict)) - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("auth_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - // Sync values to the cache - entry.SyncCache() - - viewPath := credentialBarrierPrefix + entry.UUID + "/" - view := NewBarrierView(c.barrier, viewPath) - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - defer view.setReadOnlyErr(nil) - - var err error - var backend logical.Backend - sysView := c.mountEntrySysView(entry) - - // Create the new backend - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend returned from %q factory", entry.Type) - } - - // Check for the correct backend type - backendType := backend.Type() - if entry.Type == "plugin" && backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount %q of type %q as an auth method", entry.Config.PluginName, backendType) - } - - // Update the auth table - newTable := c.auth.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - if err := c.persistAuth(ctx, newTable, &entry.Local); err != nil { - return errors.New("failed to update auth table") - } - - c.auth = newTable - - path := credentialRoutePrefix + entry.Path - if err := c.router.Mount(backend, path, entry, view); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("enabled credential backend", "path", entry.Path, "type", entry.Type) - } - return nil -} - -// disableCredential is used to disable an existing credential backend; the -// boolean indicates if it existed -func (c *Core) disableCredential(ctx context.Context, path string) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Ensure the token backend is not affected - if path == "token/" { - return fmt.Errorf("token credential backend cannot be disabled") - } - - // Store the view for this backend - fullPath := credentialRoutePrefix + path - view := c.router.MatchingStorageByAPIPath(fullPath) - if view == nil { - return fmt.Errorf("no matching backend %q", fullPath) - } - - // Get the backend/mount entry for this path, used to remove ignored - // replication prefixes - backend := c.router.MatchingBackend(fullPath) - entry := c.router.MatchingMountEntry(fullPath) - - // Mark the entry as tainted - if err := c.taintCredEntry(ctx, path); err != nil { - return err - } - - // Taint the router path to prevent routing - if err := c.router.Taint(fullPath); err != nil { - return err - } - - if backend != nil { - // Revoke credentials from this path - if err := c.expiration.RevokePrefix(c.activeContext, fullPath, true); err != nil { - return err - } - - // Call cleanup function if it exists - backend.Cleanup(ctx) - } - - // Unmount the backend - if err := c.router.Unmount(ctx, fullPath); err != nil { - return err - } - - switch { - case entry.Local, !c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - // Have writable storage, remove the whole thing - if err := logical.ClearView(ctx, view); err != nil { - c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path) - return err - } - - } - - // Remove the mount table entry - if err := c.removeCredEntry(ctx, path); err != nil { - return err - } - if c.logger.IsInfo() { - c.logger.Info("disabled credential backend", "path", path) - } - return nil -} - -// removeCredEntry is used to remove an entry in the auth table -func (c *Core) removeCredEntry(ctx context.Context, path string) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - // Taint the entry from the auth table - newTable := c.auth.shallowClone() - entry := newTable.remove(path) - if entry == nil { - c.logger.Error("nil entry found removing entry in auth table", "path", path) - return logical.CodedError(500, "failed to remove entry in auth table") - } - - // Update the auth table - if err := c.persistAuth(ctx, newTable, &entry.Local); err != nil { - return errors.New("failed to update auth table") - } - - c.auth = newTable - - return nil -} - -// remountCredEntryForce takes a copy of the mount entry for the path and fully -// unmounts and remounts the backend to pick up any changes, such as filtered -// paths -func (c *Core) remountCredEntryForce(ctx context.Context, path string) error { - fullPath := credentialRoutePrefix + path - me := c.router.MatchingMountEntry(fullPath) - if me == nil { - return fmt.Errorf("cannot find mount for path %q", path) - } - - me, err := me.Clone() - if err != nil { - return err - } - - if err := c.disableCredential(ctx, path); err != nil { - return err - } - return c.enableCredential(ctx, me) -} - -// taintCredEntry is used to mark an entry in the auth table as tainted -func (c *Core) taintCredEntry(ctx context.Context, path string) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - // Taint the entry from the auth table - // We do this on the original since setting the taint operates - // on the entries which a shallow clone shares anyways - entry := c.auth.setTaint(path, true) - - // Ensure there was a match - if entry == nil { - return fmt.Errorf("no matching backend") - } - - // Update the auth table - if err := c.persistAuth(ctx, c.auth, &entry.Local); err != nil { - return errors.New("failed to update auth table") - } - - return nil -} - -// loadCredentials is invoked as part of postUnseal to load the auth table -func (c *Core) loadCredentials(ctx context.Context) error { - authTable := &MountTable{} - localAuthTable := &MountTable{} - - // Load the existing mount table - raw, err := c.barrier.Get(ctx, coreAuthConfigPath) - if err != nil { - c.logger.Error("failed to read auth table", "error", err) - return errLoadAuthFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalAuthConfigPath) - if err != nil { - c.logger.Error("failed to read local auth table", "error", err) - return errLoadAuthFailed - } - - c.authLock.Lock() - defer c.authLock.Unlock() - - if raw != nil { - if err := jsonutil.DecodeJSON(raw.Value, authTable); err != nil { - c.logger.Error("failed to decode auth table", "error", err) - return errLoadAuthFailed - } - c.auth = authTable - } - - var needPersist bool - if c.auth == nil { - c.auth = c.defaultAuthTable() - needPersist = true - } - - if rawLocal != nil { - if err := jsonutil.DecodeJSON(rawLocal.Value, localAuthTable); err != nil { - c.logger.Error("failed to decode local auth table", "error", err) - return errLoadAuthFailed - } - if localAuthTable != nil && len(localAuthTable.Entries) > 0 { - c.auth.Entries = append(c.auth.Entries, localAuthTable.Entries...) - } - } - - // Upgrade to typed auth table - if c.auth.Type == "" { - c.auth.Type = credentialTableType - needPersist = true - } - - // Upgrade to table-scoped entries - for _, entry := range c.auth.Entries { - if entry.Table == "" { - entry.Table = c.auth.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor("auth_" + entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - needPersist = true - } - - // Sync values to the cache - entry.SyncCache() - } - - if !needPersist { - return nil - } - - if err := c.persistAuth(ctx, c.auth, nil); err != nil { - c.logger.Error("failed to persist auth table", "error", err) - return errLoadAuthFailed - } - return nil -} - -// persistAuth is used to persist the auth table after modification -func (c *Core) persistAuth(ctx context.Context, table *MountTable, local *bool) error { - if table.Type != credentialTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", credentialTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in auth table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid auth entry found, not persisting") - } - } - - nonLocalAuth := &MountTable{ - Type: credentialTableType, - } - - localAuth := &MountTable{ - Type: credentialTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localAuth.Entries = append(localAuth.Entries, entry) - } else { - nonLocalAuth.Entries = append(nonLocalAuth.Entries, entry) - } - } - - writeTable := func(mt *MountTable, path string) error { - // Encode the mount table into JSON and compress it (lzw). - compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil) - if err != nil { - c.logger.Error("failed to encode or compress auth mount table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: path, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist auth mount table", "error", err) - return err - } - return nil - } - - var err error - switch { - case local == nil: - // Write non-local mounts - err := writeTable(nonLocalAuth, coreAuthConfigPath) - if err != nil { - return err - } - - // Write local mounts - err = writeTable(localAuth, coreLocalAuthConfigPath) - if err != nil { - return err - } - case *local: - err = writeTable(localAuth, coreLocalAuthConfigPath) - default: - err = writeTable(nonLocalAuth, coreAuthConfigPath) - } - - return err -} - -// setupCredentials is invoked after we've loaded the auth table to -// initialize the credential backends and setup the router -func (c *Core) setupCredentials(ctx context.Context) error { - var err error - var persistNeeded bool - var backendType logical.BackendType - - c.authLock.Lock() - defer c.authLock.Unlock() - - for _, entry := range c.auth.Entries { - var backend logical.Backend - - // Create a barrier view using the UUID - viewPath := credentialBarrierPrefix + entry.UUID + "/" - view := NewBarrierView(c.barrier, viewPath) - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - if strutil.StrListContains(singletonMounts, entry.Type) { - defer view.setReadOnlyErr(nil) - } else { - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(nil) - }) - } - - // Initialize the backend - sysView := c.mountEntrySysView(entry) - - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - if err != nil { - c.logger.Error("failed to create credential entry", "path", entry.Path, "error", err) - if entry.Type == "plugin" { - // If we encounter an error instantiating the backend due to an error, - // skip backend initialization but register the entry to the mount table - // to preserve storage and path. - c.logger.Warn("skipping plugin-based credential entry", "path", entry.Path) - goto ROUTER_MOUNT - } - return errLoadAuthFailed - } - if backend == nil { - return fmt.Errorf("nil backend returned from %q factory", entry.Type) - } - - // Check for the correct backend type - backendType = backend.Type() - if entry.Type == "plugin" && backendType != logical.TypeCredential { - return fmt.Errorf("cannot mount %q of type %q as an auth backend", entry.Config.PluginName, backendType) - } - - ROUTER_MOUNT: - // Mount the backend - path := credentialRoutePrefix + entry.Path - err = c.router.Mount(backend, path, entry, view) - if err != nil { - c.logger.Error("failed to mount auth entry", "path", entry.Path, "error", err) - return errLoadAuthFailed - } - - // Ensure the path is tainted if set in the mount table - if entry.Tainted { - c.router.Taint(path) - } - - // Check if this is the token store - if entry.Type == "token" { - c.tokenStore = backend.(*TokenStore) - - // this is loaded *after* the normal mounts, including cubbyhole - c.router.tokenStoreSaltFunc = c.tokenStore.Salt - c.tokenStore.cubbyholeBackend = c.router.MatchingBackend("cubbyhole/").(*CubbyholeBackend) - } - } - - if persistNeeded { - return c.persistAuth(ctx, c.auth, nil) - } - - return nil -} - -// teardownCredentials is used before we seal the vault to reset the credential -// backends to their unloaded state. This is reversed by loadCredentials. -func (c *Core) teardownCredentials(ctx context.Context) error { - c.authLock.Lock() - defer c.authLock.Unlock() - - if c.auth != nil { - authTable := c.auth.shallowClone() - for _, e := range authTable.Entries { - backend := c.router.MatchingBackend(credentialRoutePrefix + e.Path) - if backend != nil { - backend.Cleanup(ctx) - } - } - } - - c.auth = nil - c.tokenStore = nil - return nil -} - -// newCredentialBackend is used to create and configure a new credential backend by name -func (c *Core) newCredentialBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) { - t := entry.Type - if alias, ok := credentialAliases[t]; ok { - t = alias - } - f, ok := c.credentialBackends[t] - if !ok { - return nil, fmt.Errorf("unknown backend type: %q", t) - } - - // Set up conf to pass in plugin_name - conf := make(map[string]string, len(entry.Options)+1) - for k, v := range entry.Options { - conf[k] = v - } - if entry.Config.PluginName != "" { - conf["plugin_name"] = entry.Config.PluginName - } - - authLogger := c.baseLogger.Named(fmt.Sprintf("auth.%s.%s", t, entry.Accessor)) - c.AddLogger(authLogger) - config := &logical.BackendConfig{ - StorageView: view, - Logger: authLogger, - Config: conf, - System: sysView, - BackendUUID: entry.BackendAwareUUID, - } - - b, err := f(ctx, config) - if err != nil { - return nil, err - } - - return b, nil -} - -// defaultAuthTable creates a default auth table -func (c *Core) defaultAuthTable() *MountTable { - table := &MountTable{ - Type: credentialTableType, - } - tokenUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not generate UUID for default auth table token entry: %v", err)) - } - tokenAccessor, err := c.generateMountAccessor("auth_token") - if err != nil { - panic(fmt.Sprintf("could not generate accessor for default auth table token entry: %v", err)) - } - tokenBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity backend UUID: %v", err)) - } - tokenAuth := &MountEntry{ - Table: credentialTableType, - Path: "token/", - Type: "token", - Description: "token based credentials", - UUID: tokenUUID, - Accessor: tokenAccessor, - BackendAwareUUID: tokenBackendUUID, - } - table.Entries = append(table.Entries, tokenAuth) - return table -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier.go b/vendor/github.com/hashicorp/vault/vault/barrier.go deleted file mode 100644 index 7f8a31381..000000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier.go +++ /dev/null @@ -1,183 +0,0 @@ -package vault - -import ( - "context" - "errors" - "time" - - "github.com/hashicorp/vault/logical" -) - -var ( - // ErrBarrierSealed is returned if an operation is performed on - // a sealed barrier. No operation is expected to succeed before unsealing - ErrBarrierSealed = errors.New("Vault is sealed") - - // ErrBarrierAlreadyInit is returned if the barrier is already - // initialized. This prevents a re-initialization. - ErrBarrierAlreadyInit = errors.New("Vault is already initialized") - - // ErrBarrierNotInit is returned if a non-initialized barrier - // is attempted to be unsealed. - ErrBarrierNotInit = errors.New("Vault is not initialized") - - // ErrBarrierInvalidKey is returned if the Unseal key is invalid - ErrBarrierInvalidKey = errors.New("Unseal failed, invalid key") -) - -const ( - // barrierInitPath is the path used to store our init sentinel file - barrierInitPath = "barrier/init" - - // keyringPath is the location of the keyring data. This is encrypted - // by the master key. - keyringPath = "core/keyring" - keyringPrefix = "core/" - - // keyringUpgradePrefix is the path used to store keyring update entries. - // When running in HA mode, the active instance will install the new key - // and re-write the keyring. For standby instances, they need an upgrade - // path from key N to N+1. They cannot just use the master key because - // in the event of a rekey, that master key can no longer decrypt the keyring. - // When key N+1 is installed, we create an entry at "prefix/N" which uses - // encryption key N to provide the N+1 key. The standby instances scan - // for this periodically and refresh their keyring. The upgrade keys - // are deleted after a few minutes, but this provides enough time for the - // standby instances to upgrade without causing any disruption. - keyringUpgradePrefix = "core/upgrade/" - - // masterKeyPath is the location of the master key. This is encrypted - // by the latest key in the keyring. This is only used by standby instances - // to handle the case of a rekey. If the active instance does a rekey, - // the standby instances can no longer reload the keyring since they - // have the old master key. This key can be decrypted if you have the - // keyring to discover the new master key. The new master key is then - // used to reload the keyring itself. - masterKeyPath = "core/master" -) - -// SecurityBarrier is a critical component of Vault. It is used to wrap -// an untrusted physical backend and provide a single point of encryption, -// decryption and checksum verification. The goal is to ensure that any -// data written to the barrier is confidential and that integrity is preserved. -// As a real-world analogy, this is the steel and concrete wrapper around -// a Vault. The barrier should only be Unlockable given its key. -type SecurityBarrier interface { - // Initialized checks if the barrier has been initialized - // and has a master key set. - Initialized(ctx context.Context) (bool, error) - - // Initialize works only if the barrier has not been initialized - // and makes use of the given master key. - Initialize(context.Context, []byte) error - - // GenerateKey is used to generate a new key - GenerateKey() ([]byte, error) - - // KeyLength is used to sanity check a key - KeyLength() (int, int) - - // Sealed checks if the barrier has been unlocked yet. The Barrier - // is not expected to be able to perform any CRUD until it is unsealed. - Sealed() (bool, error) - - // Unseal is used to provide the master key which permits the barrier - // to be unsealed. If the key is not correct, the barrier remains sealed. - Unseal(ctx context.Context, key []byte) error - - // VerifyMaster is used to check if the given key matches the master key - VerifyMaster(key []byte) error - - // SetMasterKey is used to directly set a new master key. This is used in - // replicated scenarios due to the chicken and egg problem of reloading the - // keyring from disk before we have the master key to decrypt it. - SetMasterKey(key []byte) error - - // ReloadKeyring is used to re-read the underlying keyring. - // This is used for HA deployments to ensure the latest keyring - // is present in the leader. - ReloadKeyring(ctx context.Context) error - - // ReloadMasterKey is used to re-read the underlying masterkey. - // This is used for HA deployments to ensure the latest master key - // is available for keyring reloading. - ReloadMasterKey(ctx context.Context) error - - // Seal is used to re-seal the barrier. This requires the barrier to - // be unsealed again to perform any further operations. - Seal() error - - // Rotate is used to create a new encryption key. All future writes - // should use the new key, while old values should still be decryptable. - Rotate(ctx context.Context) (uint32, error) - - // CreateUpgrade creates an upgrade path key to the given term from the previous term - CreateUpgrade(ctx context.Context, term uint32) error - - // DestroyUpgrade destroys the upgrade path key to the given term - DestroyUpgrade(ctx context.Context, term uint32) error - - // CheckUpgrade looks for an upgrade to the current term and installs it - CheckUpgrade(ctx context.Context) (bool, uint32, error) - - // ActiveKeyInfo is used to inform details about the active key - ActiveKeyInfo() (*KeyInfo, error) - - // Rekey is used to change the master key used to protect the keyring - Rekey(context.Context, []byte) error - - // For replication we must send over the keyring, so this must be available - Keyring() (*Keyring, error) - - // SecurityBarrier must provide the storage APIs - BarrierStorage - - // SecurityBarrier must provide the encryption APIs - BarrierEncryptor -} - -// BarrierStorage is the storage only interface required for a Barrier. -type BarrierStorage interface { - // Put is used to insert or update an entry - Put(ctx context.Context, entry *Entry) error - - // Get is used to fetch an entry - Get(ctx context.Context, key string) (*Entry, error) - - // Delete is used to permanently delete an entry - Delete(ctx context.Context, key string) error - - // List is used ot list all the keys under a given - // prefix, up to the next prefix. - List(ctx context.Context, prefix string) ([]string, error) -} - -// BarrierEncryptor is the in memory only interface that does not actually -// use the underlying barrier. It is used for lower level modules like the -// Write-Ahead-Log and Merkle index to allow them to use the barrier. -type BarrierEncryptor interface { - Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) - Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) -} - -// Entry is used to represent data stored by the security barrier -type Entry struct { - Key string - Value []byte - SealWrap bool -} - -// Logical turns the Entry into a logical storage entry. -func (e *Entry) Logical() *logical.StorageEntry { - return &logical.StorageEntry{ - Key: e.Key, - Value: e.Value, - SealWrap: e.SealWrap, - } -} - -// KeyInfo is used to convey information about the encryption key -type KeyInfo struct { - Term int - InstallTime time.Time -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_access.go b/vendor/github.com/hashicorp/vault/vault/barrier_access.go deleted file mode 100644 index 84e6e7475..000000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_access.go +++ /dev/null @@ -1,24 +0,0 @@ -package vault - -import "context" - -// BarrierEncryptorAccess is a wrapper around BarrierEncryptor that allows Core -// to expose its barrier encrypt/decrypt operations through BarrierEncryptorAccess() -// while restricting the ability to modify Core.barrier itself. -type BarrierEncryptorAccess struct { - barrierEncryptor BarrierEncryptor -} - -var _ BarrierEncryptor = (*BarrierEncryptorAccess)(nil) - -func NewBarrierEncryptorAccess(barrierEncryptor BarrierEncryptor) *BarrierEncryptorAccess { - return &BarrierEncryptorAccess{barrierEncryptor: barrierEncryptor} -} - -func (b *BarrierEncryptorAccess) Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) { - return b.barrierEncryptor.Encrypt(ctx, key, plaintext) -} - -func (b *BarrierEncryptorAccess) Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) { - return b.barrierEncryptor.Decrypt(ctx, key, ciphertext) -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go b/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go deleted file mode 100644 index 7dfdc1b84..000000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_aes_gcm.go +++ /dev/null @@ -1,936 +0,0 @@ -package vault - -import ( - "context" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/subtle" - "encoding/binary" - "errors" - "fmt" - "strings" - "sync" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/physical" -) - -const ( - // initialKeyTerm is the hard coded initial key term. This is - // used only for values that are not encrypted with the keyring. - initialKeyTerm = 1 - - // termSize the number of bytes used for the key term. - termSize = 4 -) - -// Versions of the AESGCM storage methodology -const ( - AESGCMVersion1 = 0x1 - AESGCMVersion2 = 0x2 -) - -// barrierInit is the JSON encoded value stored -type barrierInit struct { - Version int // Version is the current format version - Key []byte // Key is the primary encryption key -} - -// Validate AESGCMBarrier satisfies SecurityBarrier interface -var _ SecurityBarrier = &AESGCMBarrier{} - -// AESGCMBarrier is a SecurityBarrier implementation that uses the AES -// cipher core and the Galois Counter Mode block mode. It defaults to -// the golang NONCE default value of 12 and a key size of 256 -// bit. AES-GCM is high performance, and provides both confidentiality -// and integrity. -type AESGCMBarrier struct { - backend physical.Backend - - l sync.RWMutex - sealed bool - - // keyring is used to maintain all of the encryption keys, including - // the active key used for encryption, but also prior keys to allow - // decryption of keys encrypted under previous terms. - keyring *Keyring - - // cache is used to reduce the number of AEAD constructions we do - cache map[uint32]cipher.AEAD - cacheLock sync.RWMutex - - // currentAESGCMVersionByte is prefixed to a message to allow for - // future versioning of barrier implementations. It's var instead - // of const to allow for testing - currentAESGCMVersionByte byte -} - -// NewAESGCMBarrier is used to construct a new barrier that uses -// the provided physical backend for storage. -func NewAESGCMBarrier(physical physical.Backend) (*AESGCMBarrier, error) { - b := &AESGCMBarrier{ - backend: physical, - sealed: true, - cache: make(map[uint32]cipher.AEAD), - currentAESGCMVersionByte: byte(AESGCMVersion2), - } - return b, nil -} - -// Initialized checks if the barrier has been initialized -// and has a master key set. -func (b *AESGCMBarrier) Initialized(ctx context.Context) (bool, error) { - // Read the keyring file - keys, err := b.backend.List(ctx, keyringPrefix) - if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - if strutil.StrListContains(keys, "keyring") { - return true, nil - } - - // Fallback, check for the old sentinel file - out, err := b.backend.Get(ctx, barrierInitPath) - if err != nil { - return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - return out != nil, nil -} - -// Initialize works only if the barrier has not been initialized -// and makes use of the given master key. -func (b *AESGCMBarrier) Initialize(ctx context.Context, key []byte) error { - // Verify the key size - min, max := b.KeyLength() - if len(key) < min || len(key) > max { - return fmt.Errorf("key size must be %d or %d", min, max) - } - - // Check if already initialized - if alreadyInit, err := b.Initialized(ctx); err != nil { - return err - } else if alreadyInit { - return ErrBarrierAlreadyInit - } - - // Generate encryption key - encrypt, err := b.GenerateKey() - if err != nil { - return errwrap.Wrapf("failed to generate encryption key: {{err}}", err) - } - - // Create a new keyring, install the keys - keyring := NewKeyring() - keyring = keyring.SetMasterKey(key) - keyring, err = keyring.AddKey(&Key{ - Term: 1, - Version: 1, - Value: encrypt, - }) - if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) - } - return b.persistKeyring(ctx, keyring) -} - -// persistKeyring is used to write out the keyring using the -// master key to encrypt it. -func (b *AESGCMBarrier) persistKeyring(ctx context.Context, keyring *Keyring) error { - // Create the keyring entry - keyringBuf, err := keyring.Serialize() - defer memzero(keyringBuf) - if err != nil { - return errwrap.Wrapf("failed to serialize keyring: {{err}}", err) - } - - // Create the AES-GCM - gcm, err := b.aeadFromKey(keyring.MasterKey()) - if err != nil { - return err - } - - // Encrypt the barrier init value - value, err := b.encrypt(keyringPath, initialKeyTerm, gcm, keyringBuf) - if err != nil { - return err - } - - // Create the keyring physical entry - pe := &physical.Entry{ - Key: keyringPath, - Value: value, - } - if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist keyring: {{err}}", err) - } - - // Serialize the master key value - key := &Key{ - Term: 1, - Version: 1, - Value: keyring.MasterKey(), - } - keyBuf, err := key.Serialize() - defer memzero(keyBuf) - if err != nil { - return errwrap.Wrapf("failed to serialize master key: {{err}}", err) - } - - // Encrypt the master key - activeKey := keyring.ActiveKey() - aead, err := b.aeadFromKey(activeKey.Value) - if err != nil { - return err - } - value, err = b.encrypt(masterKeyPath, activeKey.Term, aead, keyBuf) - if err != nil { - return err - } - - // Update the masterKeyPath for standby instances - pe = &physical.Entry{ - Key: masterKeyPath, - Value: value, - } - if err := b.backend.Put(ctx, pe); err != nil { - return errwrap.Wrapf("failed to persist master key: {{err}}", err) - } - return nil -} - -// GenerateKey is used to generate a new key -func (b *AESGCMBarrier) GenerateKey() ([]byte, error) { - // Generate a 256bit key - buf := make([]byte, 2*aes.BlockSize) - _, err := rand.Read(buf) - return buf, err -} - -// KeyLength is used to sanity check a key -func (b *AESGCMBarrier) KeyLength() (int, int) { - return aes.BlockSize, 2 * aes.BlockSize -} - -// Sealed checks if the barrier has been unlocked yet. The Barrier -// is not expected to be able to perform any CRUD until it is unsealed. -func (b *AESGCMBarrier) Sealed() (bool, error) { - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - return sealed, nil -} - -// VerifyMaster is used to check if the given key matches the master key -func (b *AESGCMBarrier) VerifyMaster(key []byte) error { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return ErrBarrierSealed - } - if subtle.ConstantTimeCompare(key, b.keyring.MasterKey()) != 1 { - return ErrBarrierInvalidKey - } - return nil -} - -// ReloadKeyring is used to re-read the underlying keyring. -// This is used for HA deployments to ensure the latest keyring -// is present in the leader. -func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { - b.l.Lock() - defer b.l.Unlock() - - // Create the AES-GCM - gcm, err := b.aeadFromKey(b.keyring.MasterKey()) - if err != nil { - return err - } - - // Read in the keyring - out, err := b.backend.Get(ctx, keyringPath) - if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) - } - - // Ensure that the keyring exists. This should never happen, - // and indicates something really bad has happened. - if out == nil { - return errors.New("keyring unexpectedly missing") - } - - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(keyringPath, gcm, out.Value) - defer memzero(plain) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - - // Recover the keyring - keyring, err := DeserializeKeyring(plain) - if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) - } - - // Setup the keyring and finish - b.keyring = keyring - return nil -} - -// ReloadMasterKey is used to re-read the underlying masterkey. -// This is used for HA deployments to ensure the latest master key -// is available for keyring reloading. -func (b *AESGCMBarrier) ReloadMasterKey(ctx context.Context) error { - // Read the masterKeyPath upgrade - out, err := b.Get(ctx, masterKeyPath) - if err != nil { - return errwrap.Wrapf("failed to read master key path: {{err}}", err) - } - - // The masterKeyPath could be missing (backwards incompatible), - // we can ignore this and attempt to make progress with the current - // master key. - if out == nil { - return nil - } - - defer memzero(out.Value) - - // Deserialize the master key - key, err := DeserializeKey(out.Value) - if err != nil { - return errwrap.Wrapf("failed to deserialize key: {{err}}", err) - } - - b.l.Lock() - defer b.l.Unlock() - - // Check if the master key is the same - if subtle.ConstantTimeCompare(b.keyring.MasterKey(), key.Value) == 1 { - return nil - } - - // Update the master key - oldKeyring := b.keyring - b.keyring = b.keyring.SetMasterKey(key.Value) - oldKeyring.Zeroize(false) - return nil -} - -// Unseal is used to provide the master key which permits the barrier -// to be unsealed. If the key is not correct, the barrier remains sealed. -func (b *AESGCMBarrier) Unseal(ctx context.Context, key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - // Do nothing if already unsealed - if !b.sealed { - return nil - } - - // Create the AES-GCM - gcm, err := b.aeadFromKey(key) - if err != nil { - return err - } - - // Read in the keyring - out, err := b.backend.Get(ctx, keyringPath) - if err != nil { - return errwrap.Wrapf("failed to check for keyring: {{err}}", err) - } - if out != nil { - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(keyringPath, gcm, out.Value) - defer memzero(plain) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - - // Recover the keyring - keyring, err := DeserializeKeyring(plain) - if err != nil { - return errwrap.Wrapf("keyring deserialization failed: {{err}}", err) - } - - // Setup the keyring and finish - b.keyring = keyring - b.sealed = false - return nil - } - - // Read the barrier initialization key - out, err = b.backend.Get(ctx, barrierInitPath) - if err != nil { - return errwrap.Wrapf("failed to check for initialization: {{err}}", err) - } - if out == nil { - return ErrBarrierNotInit - } - - // Verify the term is always just one - term := binary.BigEndian.Uint32(out.Value[:4]) - if term != initialKeyTerm { - return errors.New("term mis-match") - } - - // Decrypt the barrier init key - plain, err := b.decrypt(barrierInitPath, gcm, out.Value) - if err != nil { - if strings.Contains(err.Error(), "message authentication failed") { - return ErrBarrierInvalidKey - } - return err - } - defer memzero(plain) - - // Unmarshal the barrier init - var init barrierInit - if err := jsonutil.DecodeJSON(plain, &init); err != nil { - return fmt.Errorf("failed to unmarshal barrier init file") - } - - // Setup a new keyring, this is for backwards compatibility - keyringNew := NewKeyring() - keyring := keyringNew.SetMasterKey(key) - - // AddKey reuses the master, so we are only zeroizing after this call - defer keyringNew.Zeroize(false) - - keyring, err = keyring.AddKey(&Key{ - Term: 1, - Version: 1, - Value: init.Key, - }) - if err != nil { - return errwrap.Wrapf("failed to create keyring: {{err}}", err) - } - if err := b.persistKeyring(ctx, keyring); err != nil { - return err - } - - // Delete the old barrier entry - if err := b.backend.Delete(ctx, barrierInitPath); err != nil { - return errwrap.Wrapf("failed to delete barrier init file: {{err}}", err) - } - - // Set the vault as unsealed - b.keyring = keyring - b.sealed = false - return nil -} - -// Seal is used to re-seal the barrier. This requires the barrier to -// be unsealed again to perform any further operations. -func (b *AESGCMBarrier) Seal() error { - b.l.Lock() - defer b.l.Unlock() - - // Remove the primary key, and seal the vault - b.cache = make(map[uint32]cipher.AEAD) - b.keyring.Zeroize(true) - b.keyring = nil - b.sealed = true - return nil -} - -// Rotate is used to create a new encryption key. All future writes -// should use the new key, while old values should still be decryptable. -func (b *AESGCMBarrier) Rotate(ctx context.Context) (uint32, error) { - b.l.Lock() - defer b.l.Unlock() - if b.sealed { - return 0, ErrBarrierSealed - } - - // Generate a new key - encrypt, err := b.GenerateKey() - if err != nil { - return 0, errwrap.Wrapf("failed to generate encryption key: {{err}}", err) - } - - // Get the next term - term := b.keyring.ActiveTerm() - newTerm := term + 1 - - // Add a new encryption key - newKeyring, err := b.keyring.AddKey(&Key{ - Term: newTerm, - Version: 1, - Value: encrypt, - }) - if err != nil { - return 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) - } - - // Persist the new keyring - if err := b.persistKeyring(ctx, newKeyring); err != nil { - return 0, err - } - - // Swap the keyrings - b.keyring = newKeyring - return newTerm, nil -} - -// CreateUpgrade creates an upgrade path key to the given term from the previous term -func (b *AESGCMBarrier) CreateUpgrade(ctx context.Context, term uint32) error { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return ErrBarrierSealed - } - - // Get the key for this term - termKey := b.keyring.TermKey(term) - buf, err := termKey.Serialize() - defer memzero(buf) - if err != nil { - return err - } - - // Get the AEAD for the previous term - prevTerm := term - 1 - primary, err := b.aeadForTerm(prevTerm) - if err != nil { - return err - } - - key := fmt.Sprintf("%s%d", keyringUpgradePrefix, prevTerm) - value, err := b.encrypt(key, prevTerm, primary, buf) - if err != nil { - return err - } - // Create upgrade key - pe := &physical.Entry{ - Key: key, - Value: value, - } - return b.backend.Put(ctx, pe) -} - -// DestroyUpgrade destroys the upgrade path key to the given term -func (b *AESGCMBarrier) DestroyUpgrade(ctx context.Context, term uint32) error { - path := fmt.Sprintf("%s%d", keyringUpgradePrefix, term-1) - return b.Delete(ctx, path) -} - -// CheckUpgrade looks for an upgrade to the current term and installs it -func (b *AESGCMBarrier) CheckUpgrade(ctx context.Context) (bool, uint32, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return false, 0, ErrBarrierSealed - } - - // Get the current term - activeTerm := b.keyring.ActiveTerm() - - // Check for an upgrade key - upgrade := fmt.Sprintf("%s%d", keyringUpgradePrefix, activeTerm) - entry, err := b.Get(ctx, upgrade) - if err != nil { - return false, 0, err - } - - // Nothing to do if no upgrade - if entry == nil { - return false, 0, nil - } - - defer memzero(entry.Value) - - // Deserialize the key - key, err := DeserializeKey(entry.Value) - if err != nil { - return false, 0, err - } - - // Upgrade from read lock to write lock - b.l.RUnlock() - defer b.l.RLock() - b.l.Lock() - defer b.l.Unlock() - - // Update the keyring - newKeyring, err := b.keyring.AddKey(key) - if err != nil { - return false, 0, errwrap.Wrapf("failed to add new encryption key: {{err}}", err) - } - b.keyring = newKeyring - - // Done! - return true, key.Term, nil -} - -// ActiveKeyInfo is used to inform details about the active key -func (b *AESGCMBarrier) ActiveKeyInfo() (*KeyInfo, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return nil, ErrBarrierSealed - } - - // Determine the key install time - term := b.keyring.ActiveTerm() - key := b.keyring.TermKey(term) - - // Return the key info - info := &KeyInfo{ - Term: int(term), - InstallTime: key.InstallTime, - } - return info, nil -} - -// Rekey is used to change the master key used to protect the keyring -func (b *AESGCMBarrier) Rekey(ctx context.Context, key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - newKeyring, err := b.updateMasterKeyCommon(key) - if err != nil { - return err - } - - // Persist the new keyring - if err := b.persistKeyring(ctx, newKeyring); err != nil { - return err - } - - // Swap the keyrings - oldKeyring := b.keyring - b.keyring = newKeyring - oldKeyring.Zeroize(false) - return nil -} - -// SetMasterKey updates the keyring's in-memory master key but does not persist -// anything to storage -func (b *AESGCMBarrier) SetMasterKey(key []byte) error { - b.l.Lock() - defer b.l.Unlock() - - newKeyring, err := b.updateMasterKeyCommon(key) - if err != nil { - return err - } - - // Swap the keyrings - oldKeyring := b.keyring - b.keyring = newKeyring - oldKeyring.Zeroize(false) - return nil -} - -// Performs common tasks related to updating the master key; note that the lock -// must be held before calling this function -func (b *AESGCMBarrier) updateMasterKeyCommon(key []byte) (*Keyring, error) { - if b.sealed { - return nil, ErrBarrierSealed - } - - // Verify the key size - min, max := b.KeyLength() - if len(key) < min || len(key) > max { - return nil, fmt.Errorf("key size must be %d or %d", min, max) - } - - return b.keyring.SetMasterKey(key), nil -} - -// Put is used to insert or update an entry -func (b *AESGCMBarrier) Put(ctx context.Context, entry *Entry) error { - defer metrics.MeasureSince([]string{"barrier", "put"}, time.Now()) - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return ErrBarrierSealed - } - - term := b.keyring.ActiveTerm() - primary, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return err - } - - value, err := b.encrypt(entry.Key, term, primary, entry.Value) - if err != nil { - return err - } - pe := &physical.Entry{ - Key: entry.Key, - Value: value, - SealWrap: entry.SealWrap, - } - return b.backend.Put(ctx, pe) -} - -// Get is used to fetch an entry -func (b *AESGCMBarrier) Get(ctx context.Context, key string) (*Entry, error) { - defer metrics.MeasureSince([]string{"barrier", "get"}, time.Now()) - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - // Read the key from the backend - pe, err := b.backend.Get(ctx, key) - if err != nil { - b.l.RUnlock() - return nil, err - } else if pe == nil { - b.l.RUnlock() - return nil, nil - } - - // Verify the term - term := binary.BigEndian.Uint32(pe.Value[:4]) - - // Get the GCM by term - // It is expensive to do this first but it is not a - // normal case that this won't match - gcm, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - if gcm == nil { - return nil, fmt.Errorf("no decryption key available for term %d", term) - } - - // Decrypt the ciphertext - plain, err := b.decrypt(key, gcm, pe.Value) - if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) - } - - // Wrap in a logical entry - entry := &Entry{ - Key: key, - Value: plain, - SealWrap: pe.SealWrap, - } - return entry, nil -} - -// Delete is used to permanently delete an entry -func (b *AESGCMBarrier) Delete(ctx context.Context, key string) error { - defer metrics.MeasureSince([]string{"barrier", "delete"}, time.Now()) - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - if sealed { - return ErrBarrierSealed - } - - return b.backend.Delete(ctx, key) -} - -// List is used ot list all the keys under a given -// prefix, up to the next prefix. -func (b *AESGCMBarrier) List(ctx context.Context, prefix string) ([]string, error) { - defer metrics.MeasureSince([]string{"barrier", "list"}, time.Now()) - b.l.RLock() - sealed := b.sealed - b.l.RUnlock() - if sealed { - return nil, ErrBarrierSealed - } - - return b.backend.List(ctx, prefix) -} - -// aeadForTerm returns the AES-GCM AEAD for the given term -func (b *AESGCMBarrier) aeadForTerm(term uint32) (cipher.AEAD, error) { - // Check for the keyring - keyring := b.keyring - if keyring == nil { - return nil, nil - } - - // Check the cache for the aead - b.cacheLock.RLock() - aead, ok := b.cache[term] - b.cacheLock.RUnlock() - if ok { - return aead, nil - } - - // Read the underlying key - key := keyring.TermKey(term) - if key == nil { - return nil, nil - } - - // Create a new aead - aead, err := b.aeadFromKey(key.Value) - if err != nil { - return nil, err - } - - // Update the cache - b.cacheLock.Lock() - b.cache[term] = aead - b.cacheLock.Unlock() - return aead, nil -} - -// aeadFromKey returns an AES-GCM AEAD using the given key. -func (b *AESGCMBarrier) aeadFromKey(key []byte) (cipher.AEAD, error) { - // Create the AES cipher - aesCipher, err := aes.NewCipher(key) - if err != nil { - return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err) - } - - // Create the GCM mode AEAD - gcm, err := cipher.NewGCM(aesCipher) - if err != nil { - return nil, fmt.Errorf("failed to initialize GCM mode") - } - return gcm, nil -} - -// encrypt is used to encrypt a value -func (b *AESGCMBarrier) encrypt(path string, term uint32, gcm cipher.AEAD, plain []byte) ([]byte, error) { - // Allocate the output buffer with room for tern, version byte, - // nonce, GCM tag and the plaintext - capacity := termSize + 1 + gcm.NonceSize() + gcm.Overhead() + len(plain) - size := termSize + 1 + gcm.NonceSize() - out := make([]byte, size, capacity) - - // Set the key term - binary.BigEndian.PutUint32(out[:4], term) - - // Set the version byte - out[4] = b.currentAESGCMVersionByte - - // Generate a random nonce - nonce := out[5 : 5+gcm.NonceSize()] - n, err := rand.Read(nonce) - if err != nil { - return nil, err - } - if n != len(nonce) { - return nil, errors.New("unable to read enough random bytes to fill gcm nonce") - } - - // Seal the output - switch b.currentAESGCMVersionByte { - case AESGCMVersion1: - out = gcm.Seal(out, nonce, plain, nil) - case AESGCMVersion2: - out = gcm.Seal(out, nonce, plain, []byte(path)) - default: - panic("Unknown AESGCM version") - } - - return out, nil -} - -// decrypt is used to decrypt a value using the keyring -func (b *AESGCMBarrier) decrypt(path string, gcm cipher.AEAD, cipher []byte) ([]byte, error) { - // Capture the parts - nonce := cipher[5 : 5+gcm.NonceSize()] - raw := cipher[5+gcm.NonceSize():] - out := make([]byte, 0, len(raw)-gcm.NonceSize()) - - // Attempt to open - switch cipher[4] { - case AESGCMVersion1: - return gcm.Open(out, nonce, raw, nil) - case AESGCMVersion2: - return gcm.Open(out, nonce, raw, []byte(path)) - default: - return nil, fmt.Errorf("version bytes mis-match") - } -} - -// Encrypt is used to encrypt in-memory for the BarrierEncryptor interface -func (b *AESGCMBarrier) Encrypt(ctx context.Context, key string, plaintext []byte) ([]byte, error) { - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - term := b.keyring.ActiveTerm() - primary, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - - ciphertext, err := b.encrypt(key, term, primary, plaintext) - if err != nil { - return nil, err - } - return ciphertext, nil -} - -// Decrypt is used to decrypt in-memory for the BarrierEncryptor interface -func (b *AESGCMBarrier) Decrypt(ctx context.Context, key string, ciphertext []byte) ([]byte, error) { - b.l.RLock() - if b.sealed { - b.l.RUnlock() - return nil, ErrBarrierSealed - } - - // Verify the term - term := binary.BigEndian.Uint32(ciphertext[:4]) - - // Get the GCM by term - // It is expensive to do this first but it is not a - // normal case that this won't match - gcm, err := b.aeadForTerm(term) - b.l.RUnlock() - if err != nil { - return nil, err - } - if gcm == nil { - return nil, fmt.Errorf("no decryption key available for term %d", term) - } - - // Decrypt the ciphertext - plain, err := b.decrypt(key, gcm, ciphertext) - if err != nil { - return nil, errwrap.Wrapf("decryption failed: {{err}}", err) - } - - return plain, nil -} - -func (b *AESGCMBarrier) Keyring() (*Keyring, error) { - b.l.RLock() - defer b.l.RUnlock() - if b.sealed { - return nil, ErrBarrierSealed - } - - return b.keyring.Clone(), nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/barrier_view.go b/vendor/github.com/hashicorp/vault/vault/barrier_view.go deleted file mode 100644 index cc1a4251c..000000000 --- a/vendor/github.com/hashicorp/vault/vault/barrier_view.go +++ /dev/null @@ -1,145 +0,0 @@ -package vault - -import ( - "context" - "errors" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" -) - -// BarrierView wraps a SecurityBarrier and ensures all access is automatically -// prefixed. This is used to prevent anyone with access to the view to access -// any data in the durable storage outside of their prefix. Conceptually this -// is like a "chroot" into the barrier. -// -// BarrierView implements logical.Storage so it can be passed in as the -// durable storage mechanism for logical views. -type BarrierView struct { - barrier BarrierStorage - prefix string - readOnlyErr error - readOnlyErrLock sync.RWMutex -} - -var ( - ErrRelativePath = errors.New("relative paths not supported") -) - -// NewBarrierView takes an underlying security barrier and returns -// a view of it that can only operate with the given prefix. -func NewBarrierView(barrier BarrierStorage, prefix string) *BarrierView { - return &BarrierView{ - barrier: barrier, - prefix: prefix, - } -} - -func (v *BarrierView) setReadOnlyErr(readOnlyErr error) { - v.readOnlyErrLock.Lock() - defer v.readOnlyErrLock.Unlock() - v.readOnlyErr = readOnlyErr -} - -func (v *BarrierView) getReadOnlyErr() error { - v.readOnlyErrLock.RLock() - defer v.readOnlyErrLock.RUnlock() - return v.readOnlyErr -} - -// sanityCheck is used to perform a sanity check on a key -func (v *BarrierView) sanityCheck(key string) error { - if strings.Contains(key, "..") { - return ErrRelativePath - } - return nil -} - -// logical.Storage impl. -func (v *BarrierView) List(ctx context.Context, prefix string) ([]string, error) { - if err := v.sanityCheck(prefix); err != nil { - return nil, err - } - return v.barrier.List(ctx, v.expandKey(prefix)) -} - -// logical.Storage impl. -func (v *BarrierView) Get(ctx context.Context, key string) (*logical.StorageEntry, error) { - if err := v.sanityCheck(key); err != nil { - return nil, err - } - entry, err := v.barrier.Get(ctx, v.expandKey(key)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - if entry != nil { - entry.Key = v.truncateKey(entry.Key) - } - - return &logical.StorageEntry{ - Key: entry.Key, - Value: entry.Value, - SealWrap: entry.SealWrap, - }, nil -} - -// logical.Storage impl. -func (v *BarrierView) Put(ctx context.Context, entry *logical.StorageEntry) error { - if entry == nil { - return errors.New("cannot write nil entry") - } - - if err := v.sanityCheck(entry.Key); err != nil { - return err - } - - expandedKey := v.expandKey(entry.Key) - - roErr := v.getReadOnlyErr() - if roErr != nil { - return roErr - } - - nested := &Entry{ - Key: expandedKey, - Value: entry.Value, - SealWrap: entry.SealWrap, - } - return v.barrier.Put(ctx, nested) -} - -// logical.Storage impl. -func (v *BarrierView) Delete(ctx context.Context, key string) error { - if err := v.sanityCheck(key); err != nil { - return err - } - - expandedKey := v.expandKey(key) - - roErr := v.getReadOnlyErr() - if roErr != nil { - return roErr - } - - return v.barrier.Delete(ctx, expandedKey) -} - -// SubView constructs a nested sub-view using the given prefix -func (v *BarrierView) SubView(prefix string) *BarrierView { - sub := v.expandKey(prefix) - return &BarrierView{barrier: v.barrier, prefix: sub, readOnlyErr: v.getReadOnlyErr()} -} - -// expandKey is used to expand to the full key path with the prefix -func (v *BarrierView) expandKey(suffix string) string { - return v.prefix + suffix -} - -// truncateKey is used to remove the prefix of the key -func (v *BarrierView) truncateKey(full string) string { - return strings.TrimPrefix(full, v.prefix) -} diff --git a/vendor/github.com/hashicorp/vault/vault/capabilities.go b/vendor/github.com/hashicorp/vault/vault/capabilities.go deleted file mode 100644 index 842123979..000000000 --- a/vendor/github.com/hashicorp/vault/vault/capabilities.go +++ /dev/null @@ -1,58 +0,0 @@ -package vault - -import ( - "context" - "sort" - - "github.com/hashicorp/vault/logical" -) - -// Capabilities is used to fetch the capabilities of the given token on the given path -func (c *Core) Capabilities(ctx context.Context, token, path string) ([]string, error) { - if path == "" { - return nil, &logical.StatusBadRequest{Err: "missing path"} - } - - if token == "" { - return nil, &logical.StatusBadRequest{Err: "missing token"} - } - - te, err := c.tokenStore.Lookup(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, &logical.StatusBadRequest{Err: "invalid token"} - } - - // Start with token entry policies - policies := te.Policies - - // Fetch entity and entity group policies - entity, derivedPolicies, err := c.fetchEntityAndDerivedPolicies(te.EntityID) - if err != nil { - return nil, err - } - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - return nil, logical.ErrPermissionDenied - } - if te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - policies = append(policies, derivedPolicies...) - - if len(policies) == 0 { - return []string{DenyCapability}, nil - } - - acl, err := c.policyStore.ACL(ctx, entity, policies...) - if err != nil { - return nil, err - } - - capabilities := acl.Capabilities(path) - sort.Strings(capabilities) - return capabilities, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/cluster.go b/vendor/github.com/hashicorp/vault/vault/cluster.go deleted file mode 100644 index cbe51cdbb..000000000 --- a/vendor/github.com/hashicorp/vault/vault/cluster.go +++ /dev/null @@ -1,458 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/json" - "errors" - "fmt" - "math/big" - mathrand "math/rand" - "net" - "net/http" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/jsonutil" -) - -const ( - // Storage path where the local cluster name and identifier are stored - coreLocalClusterInfoPath = "core/cluster/local/info" - - corePrivateKeyTypeP521 = "p521" - corePrivateKeyTypeED25519 = "ed25519" - - // Internal so as not to log a trace message - IntNoForwardingHeaderName = "X-Vault-Internal-No-Request-Forwarding" -) - -var ( - ErrCannotForward = errors.New("cannot forward request; no connection or address not known") -) - -// This is used for enterprise replication information -type ReplicatedClusters struct { -} - -// This can be one of a few key types so the different params may or may not be filled -type clusterKeyParams struct { - Type string `json:"type" structs:"type" mapstructure:"type"` - X *big.Int `json:"x" structs:"x" mapstructure:"x"` - Y *big.Int `json:"y" structs:"y" mapstructure:"y"` - D *big.Int `json:"d" structs:"d" mapstructure:"d"` -} - -// Structure representing the storage entry that holds cluster information -type Cluster struct { - // Name of the cluster - Name string `json:"name" structs:"name" mapstructure:"name"` - - // Identifier of the cluster - ID string `json:"id" structs:"id" mapstructure:"id"` -} - -// Cluster fetches the details of the local cluster. This method errors out -// when Vault is sealed. -func (c *Core) Cluster(ctx context.Context) (*Cluster, error) { - var cluster Cluster - - // Fetch the storage entry. This call fails when Vault is sealed. - entry, err := c.barrier.Get(ctx, coreLocalClusterInfoPath) - if err != nil { - return nil, err - } - if entry == nil { - return &cluster, nil - } - - // Decode the cluster information - if err = jsonutil.DecodeJSON(entry.Value, &cluster); err != nil { - return nil, errwrap.Wrapf("failed to decode cluster details: {{err}}", err) - } - - // Set in config file - if c.clusterName != "" { - cluster.Name = c.clusterName - } - - return &cluster, nil -} - -// This sets our local cluster cert and private key based on the advertisement. -// It also ensures the cert is in our local cluster cert pool. -func (c *Core) loadLocalClusterTLS(adv activeAdvertisement) (retErr error) { - defer func() { - if retErr != nil { - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - } - }() - - switch { - case adv.ClusterAddr == "": - // Clustering disabled on the server, don't try to look for params - return nil - - case adv.ClusterKeyParams == nil: - c.logger.Error("no key params found loading local cluster TLS information") - return fmt.Errorf("no local cluster key params found") - - case adv.ClusterKeyParams.X == nil, adv.ClusterKeyParams.Y == nil, adv.ClusterKeyParams.D == nil: - c.logger.Error("failed to parse local cluster key due to missing params") - return fmt.Errorf("failed to parse local cluster key") - - case adv.ClusterKeyParams.Type != corePrivateKeyTypeP521: - c.logger.Error("unknown local cluster key type", "key_type", adv.ClusterKeyParams.Type) - return fmt.Errorf("failed to find valid local cluster key type") - - case adv.ClusterCert == nil || len(adv.ClusterCert) == 0: - c.logger.Error("no local cluster cert found") - return fmt.Errorf("no local cluster cert found") - - } - - c.localClusterPrivateKey.Store(&ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: adv.ClusterKeyParams.X, - Y: adv.ClusterKeyParams.Y, - }, - D: adv.ClusterKeyParams.D, - }) - - locCert := make([]byte, len(adv.ClusterCert)) - copy(locCert, adv.ClusterCert) - c.localClusterCert.Store(locCert) - - cert, err := x509.ParseCertificate(adv.ClusterCert) - if err != nil { - c.logger.Error("failed parsing local cluster certificate", "error", err) - return errwrap.Wrapf("error parsing local cluster certificate: {{err}}", err) - } - - c.localClusterParsedCert.Store(cert) - - return nil -} - -// setupCluster creates storage entries for holding Vault cluster information. -// Entries will be created only if they are not already present. If clusterName -// is not supplied, this method will auto-generate it. -func (c *Core) setupCluster(ctx context.Context) error { - // Prevent data races with the TLS parameters - c.clusterParamsLock.Lock() - defer c.clusterParamsLock.Unlock() - - // Check if storage index is already present or not - cluster, err := c.Cluster(ctx) - if err != nil { - c.logger.Error("failed to get cluster details", "error", err) - return err - } - - var modified bool - - if cluster == nil { - cluster = &Cluster{} - } - - if cluster.Name == "" { - // If cluster name is not supplied, generate one - if c.clusterName == "" { - c.logger.Debug("cluster name not found/set, generating new") - clusterNameBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - c.logger.Error("failed to generate cluster name", "error", err) - return err - } - - c.clusterName = fmt.Sprintf("vault-cluster-%08x", clusterNameBytes) - } - - cluster.Name = c.clusterName - if c.logger.IsDebug() { - c.logger.Debug("cluster name set", "name", cluster.Name) - } - modified = true - } - - if cluster.ID == "" { - c.logger.Debug("cluster ID not found, generating new") - // Generate a clusterID - cluster.ID, err = uuid.GenerateUUID() - if err != nil { - c.logger.Error("failed to generate cluster identifier", "error", err) - return err - } - if c.logger.IsDebug() { - c.logger.Debug("cluster ID set", "id", cluster.ID) - } - modified = true - } - - // If we're using HA, generate server-to-server parameters - if c.ha != nil { - // Create a private key - if c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey) == nil { - c.logger.Trace("generating cluster private key") - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - c.logger.Error("failed to generate local cluster key", "error", err) - return err - } - - c.localClusterPrivateKey.Store(key) - } - - // Create a certificate - if c.localClusterCert.Load().([]byte) == nil { - c.logger.Debug("generating local cluster certificate") - - host, err := uuid.GenerateUUID() - if err != nil { - return err - } - host = fmt.Sprintf("fw-%s", host) - template := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: host, - }, - DNSNames: []string{host}, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageServerAuth, - x509.ExtKeyUsageClientAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign, - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - // 30 years of single-active uptime ought to be enough for anybody - NotAfter: time.Now().Add(262980 * time.Hour), - BasicConstraintsValid: true, - IsCA: true, - } - - certBytes, err := x509.CreateCertificate(rand.Reader, template, template, c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey).Public(), c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey)) - if err != nil { - c.logger.Error("error generating self-signed cert", "error", err) - return errwrap.Wrapf("unable to generate local cluster certificate: {{err}}", err) - } - - parsedCert, err := x509.ParseCertificate(certBytes) - if err != nil { - c.logger.Error("error parsing self-signed cert", "error", err) - return errwrap.Wrapf("error parsing generated certificate: {{err}}", err) - } - - c.localClusterCert.Store(certBytes) - c.localClusterParsedCert.Store(parsedCert) - } - } - - if modified { - // Encode the cluster information into as a JSON string - rawCluster, err := json.Marshal(cluster) - if err != nil { - c.logger.Error("failed to encode cluster details", "error", err) - return err - } - - // Store it - err = c.barrier.Put(ctx, &Entry{ - Key: coreLocalClusterInfoPath, - Value: rawCluster, - }) - if err != nil { - c.logger.Error("failed to store cluster details", "error", err) - return err - } - } - - return nil -} - -// startClusterListener starts cluster request listeners during postunseal. It -// is assumed that the state lock is held while this is run. Right now this -// only starts forwarding listeners; it's TBD whether other request types will -// be built in the same mechanism or started independently. -func (c *Core) startClusterListener(ctx context.Context) error { - if c.clusterAddr == "" { - c.logger.Info("clustering disabled, not starting listeners") - return nil - } - - if c.clusterListenerAddrs == nil || len(c.clusterListenerAddrs) == 0 { - c.logger.Warn("clustering not disabled but no addresses to listen on") - return fmt.Errorf("cluster addresses not found") - } - - c.logger.Debug("starting cluster listeners") - - err := c.startForwarding(ctx) - if err != nil { - return err - } - - return nil -} - -// stopClusterListener stops any existing listeners during preseal. It is -// assumed that the state lock is held while this is run. -func (c *Core) stopClusterListener() { - if c.clusterAddr == "" { - - c.logger.Debug("clustering disabled, not stopping listeners") - return - } - - if !c.clusterListenersRunning { - c.logger.Info("cluster listeners not running") - return - } - c.logger.Info("stopping cluster listeners") - - // Tell the goroutine managing the listeners to perform the shutdown - // process - c.clusterListenerShutdownCh <- struct{}{} - - // The reason for this loop-de-loop is that we may be unsealing again - // quickly, and if the listeners are not yet closed, we will get socket - // bind errors. This ensures proper ordering. - - c.logger.Debug("waiting for success notification while stopping cluster listeners") - <-c.clusterListenerShutdownSuccessCh - c.clusterListenersRunning = false - - c.logger.Info("cluster listeners successfully shut down") -} - -// ClusterTLSConfig generates a TLS configuration based on the local/replicated -// cluster key and cert. -func (c *Core) ClusterTLSConfig(ctx context.Context, repClusters *ReplicatedClusters) (*tls.Config, error) { - // Using lookup functions allows just-in-time lookup of the current state - // of clustering as connections come and go - - serverLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { - switch { - default: - currCert := c.localClusterCert.Load().([]byte) - if len(currCert) == 0 { - return nil, fmt.Errorf("got forwarding connection but no local cert") - } - - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - return &tls.Certificate{ - Certificate: [][]byte{localCert}, - PrivateKey: c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey), - Leaf: c.localClusterParsedCert.Load().(*x509.Certificate), - }, nil - } - } - - clientLookup := func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) { - - if len(requestInfo.AcceptableCAs) != 1 { - return nil, fmt.Errorf("expected only a single acceptable CA") - } - - currCert := c.localClusterCert.Load().([]byte) - if len(currCert) == 0 { - return nil, fmt.Errorf("forwarding connection client but no local cert") - } - - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - return &tls.Certificate{ - Certificate: [][]byte{localCert}, - PrivateKey: c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey), - Leaf: c.localClusterParsedCert.Load().(*x509.Certificate), - }, nil - } - - serverConfigLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) { - - for _, v := range clientHello.SupportedProtos { - switch v { - case "h2", requestForwardingALPN: - default: - return nil, fmt.Errorf("unknown ALPN proto %s", v) - } - } - - caPool := x509.NewCertPool() - - ret := &tls.Config{ - ClientAuth: tls.RequireAndVerifyClientCert, - GetCertificate: serverLookup, - GetClientCertificate: clientLookup, - MinVersion: tls.VersionTLS12, - RootCAs: caPool, - ClientCAs: caPool, - NextProtos: clientHello.SupportedProtos, - CipherSuites: c.clusterCipherSuites, - } - - switch { - default: - parsedCert := c.localClusterParsedCert.Load().(*x509.Certificate) - - if parsedCert == nil { - return nil, fmt.Errorf("forwarding connection client but no local cert") - } - - caPool.AddCert(parsedCert) - } - - return ret, nil - } - - tlsConfig := &tls.Config{ - ClientAuth: tls.RequireAndVerifyClientCert, - GetCertificate: serverLookup, - GetClientCertificate: clientLookup, - GetConfigForClient: serverConfigLookup, - MinVersion: tls.VersionTLS12, - CipherSuites: c.clusterCipherSuites, - } - - parsedCert := c.localClusterParsedCert.Load().(*x509.Certificate) - currCert := c.localClusterCert.Load().([]byte) - localCert := make([]byte, len(currCert)) - copy(localCert, currCert) - - if parsedCert != nil { - tlsConfig.ServerName = parsedCert.Subject.CommonName - - pool := x509.NewCertPool() - pool.AddCert(parsedCert) - tlsConfig.RootCAs = pool - tlsConfig.ClientCAs = pool - } - - return tlsConfig, nil -} - -func (c *Core) SetClusterListenerAddrs(addrs []*net.TCPAddr) { - c.clusterListenerAddrs = addrs - if c.clusterAddr == "" && len(addrs) == 1 { - c.clusterAddr = fmt.Sprintf("https://%s", addrs[0].String()) - } -} - -func (c *Core) SetClusterHandler(handler http.Handler) { - c.clusterHandler = handler -} diff --git a/vendor/github.com/hashicorp/vault/vault/core.go b/vendor/github.com/hashicorp/vault/vault/core.go deleted file mode 100644 index b6ea19c35..000000000 --- a/vendor/github.com/hashicorp/vault/vault/core.go +++ /dev/null @@ -1,1490 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "net" - "net/http" - "net/url" - "path/filepath" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - - "google.golang.org/grpc" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/mlock" - "github.com/hashicorp/vault/helper/reload" - "github.com/hashicorp/vault/helper/tlsutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/shamir" - cache "github.com/patrickmn/go-cache" -) - -const ( - // coreLockPath is the path used to acquire a coordinating lock - // for a highly-available deploy. - coreLockPath = "core/lock" - - // The poison pill is used as a check during certain scenarios to indicate - // to standby nodes that they should seal - poisonPillPath = "core/poison-pill" - - // coreLeaderPrefix is the prefix used for the UUID that contains - // the currently elected leader. - coreLeaderPrefix = "core/leader/" - - // knownPrimaryAddrsPrefix is used to store last-known cluster address - // information for primaries - knownPrimaryAddrsPrefix = "core/primary-addrs/" - - // coreKeyringCanaryPath is used as a canary to indicate to replicated - // clusters that they need to perform a rekey operation synchronously; this - // isn't keyring-canary to avoid ignoring it when ignoring core/keyring - coreKeyringCanaryPath = "core/canary-keyring" -) - -var ( - // ErrAlreadyInit is returned if the core is already - // initialized. This prevents a re-initialization. - ErrAlreadyInit = errors.New("Vault is already initialized") - - // ErrNotInit is returned if a non-initialized barrier - // is attempted to be unsealed. - ErrNotInit = errors.New("Vault is not initialized") - - // ErrInternalError is returned when we don't want to leak - // any information about an internal error - ErrInternalError = errors.New("internal error") - - // ErrHANotEnabled is returned if the operation only makes sense - // in an HA setting - ErrHANotEnabled = errors.New("Vault is not configured for highly-available mode") - - // manualStepDownSleepPeriod is how long to sleep after a user-initiated - // step down of the active node, to prevent instantly regrabbing the lock. - // It's var not const so that tests can manipulate it. - manualStepDownSleepPeriod = 10 * time.Second - - // Functions only in the Enterprise version - enterprisePostUnseal = enterprisePostUnsealImpl - enterprisePreSeal = enterprisePreSealImpl - startReplication = startReplicationImpl - stopReplication = stopReplicationImpl - LastRemoteWAL = lastRemoteWALImpl -) - -// NonFatalError is an error that can be returned during NewCore that should be -// displayed but not cause a program exit -type NonFatalError struct { - Err error -} - -func (e *NonFatalError) WrappedErrors() []error { - return []error{e.Err} -} - -func (e *NonFatalError) Error() string { - return e.Err.Error() -} - -// ErrInvalidKey is returned if there is a user-based error with a provided -// unseal key. This will be shown to the user, so should not contain -// information that is sensitive. -type ErrInvalidKey struct { - Reason string -} - -func (e *ErrInvalidKey) Error() string { - return fmt.Sprintf("invalid key: %v", e.Reason) -} - -type activeAdvertisement struct { - RedirectAddr string `json:"redirect_addr"` - ClusterAddr string `json:"cluster_addr,omitempty"` - ClusterCert []byte `json:"cluster_cert,omitempty"` - ClusterKeyParams *clusterKeyParams `json:"cluster_key_params,omitempty"` -} - -type unlockInformation struct { - Parts [][]byte - Nonce string -} - -// Core is used as the central manager of Vault activity. It is the primary point of -// interface for API handlers and is responsible for managing the logical and physical -// backends, router, security barrier, and audit trails. -type Core struct { - // N.B.: This is used to populate a dev token down replication, as - // otherwise, after replication is started, a dev would have to go through - // the generate-root process simply to talk to the new follower cluster. - devToken string - - // HABackend may be available depending on the physical backend - ha physical.HABackend - - // redirectAddr is the address we advertise as leader if held - redirectAddr string - - // clusterAddr is the address we use for clustering - clusterAddr string - - // physical backend is the un-trusted backend with durable data - physical physical.Backend - - // Our Seal, for seal configuration information - seal Seal - - // barrier is the security barrier wrapping the physical backend - barrier SecurityBarrier - - // router is responsible for managing the mount points for logical backends. - router *Router - - // logicalBackends is the mapping of backends to use for this core - logicalBackends map[string]logical.Factory - - // credentialBackends is the mapping of backends to use for this core - credentialBackends map[string]logical.Factory - - // auditBackends is the mapping of backends to use for this core - auditBackends map[string]audit.Factory - - // stateLock protects mutable state - stateLock sync.RWMutex - sealed *uint32 - - standby bool - perfStandby bool - standbyDoneCh chan struct{} - standbyStopCh chan struct{} - manualStepDownCh chan struct{} - keepHALockOnStepDown *uint32 - heldHALock physical.Lock - - // unlockInfo has the keys provided to Unseal until the threshold number of parts is available, as well as the operation nonce - unlockInfo *unlockInformation - - // generateRootProgress holds the shares until we reach enough - // to verify the master key - generateRootConfig *GenerateRootConfig - generateRootProgress [][]byte - generateRootLock sync.Mutex - - // These variables holds the config and shares we have until we reach - // enough to verify the appropriate master key. Note that the same lock is - // used; this isn't time-critical so this shouldn't be a problem. - barrierRekeyConfig *SealConfig - recoveryRekeyConfig *SealConfig - rekeyLock sync.RWMutex - - // mounts is loaded after unseal since it is a protected - // configuration - mounts *MountTable - - // mountsLock is used to ensure that the mounts table does not - // change underneath a calling function - mountsLock sync.RWMutex - - // auth is loaded after unseal since it is a protected - // configuration - auth *MountTable - - // authLock is used to ensure that the auth table does not - // change underneath a calling function - authLock sync.RWMutex - - // audit is loaded after unseal since it is a protected - // configuration - audit *MountTable - - // auditLock is used to ensure that the audit table does not - // change underneath a calling function - auditLock sync.RWMutex - - // auditBroker is used to ingest the audit events and fan - // out into the configured audit backends - auditBroker *AuditBroker - - // auditedHeaders is used to configure which http headers - // can be output in the audit logs - auditedHeaders *AuditedHeadersConfig - - // systemBackend is the backend which is used to manage internal operations - systemBackend *SystemBackend - - // systemBarrierView is the barrier view for the system backend - systemBarrierView *BarrierView - - // expiration manager is used for managing LeaseIDs, - // renewal, expiration and revocation - expiration *ExpirationManager - - // rollback manager is used to run rollbacks periodically - rollback *RollbackManager - - // policy store is used to manage named ACL policies - policyStore *PolicyStore - - // token store is used to manage authentication tokens - tokenStore *TokenStore - - // identityStore is used to manage client entities - identityStore *IdentityStore - - // metricsCh is used to stop the metrics streaming - metricsCh chan struct{} - - // metricsMutex is used to prevent a race condition between - // metrics emission and sealing leading to a nil pointer - metricsMutex sync.Mutex - - defaultLeaseTTL time.Duration - maxLeaseTTL time.Duration - - // baseLogger is used to avoid ResetNamed as it strips useful prefixes in - // e.g. testing - baseLogger log.Logger - logger log.Logger - - // cachingDisabled indicates whether caches are disabled - cachingDisabled bool - // Cache stores the actual cache; we always have this but may bypass it if - // disabled - physicalCache physical.ToggleablePurgemonster - - // reloadFuncs is a map containing reload functions - reloadFuncs map[string][]reload.ReloadFunc - - // reloadFuncsLock controls access to the funcs - reloadFuncsLock sync.RWMutex - - // wrappingJWTKey is the key used for generating JWTs containing response - // wrapping information - wrappingJWTKey *ecdsa.PrivateKey - - // - // Cluster information - // - // Name - clusterName string - // Specific cipher suites to use for clustering, if any - clusterCipherSuites []uint16 - // Used to modify cluster parameters - clusterParamsLock sync.RWMutex - // The private key stored in the barrier used for establishing - // mutually-authenticated connections between Vault cluster members - localClusterPrivateKey *atomic.Value - // The local cluster cert - localClusterCert *atomic.Value - // The parsed form of the local cluster cert - localClusterParsedCert *atomic.Value - // The TCP addresses we should use for clustering - clusterListenerAddrs []*net.TCPAddr - // The handler to use for request forwarding - clusterHandler http.Handler - // Tracks whether cluster listeners are running, e.g. it's safe to send a - // shutdown down the channel - clusterListenersRunning bool - // Shutdown channel for the cluster listeners - clusterListenerShutdownCh chan struct{} - // Shutdown success channel. We need this to be done serially to ensure - // that binds are removed before they might be reinstated. - clusterListenerShutdownSuccessCh chan struct{} - // Write lock used to ensure that we don't have multiple connections adjust - // this value at the same time - requestForwardingConnectionLock sync.RWMutex - // Most recent leader UUID. Used to avoid repeatedly JSON parsing the same - // values. - clusterLeaderUUID string - // Most recent leader redirect addr - clusterLeaderRedirectAddr string - // Most recent leader cluster addr - clusterLeaderClusterAddr string - // Lock for the cluster leader values - clusterLeaderParamsLock sync.RWMutex - // Info on cluster members - clusterPeerClusterAddrsCache *cache.Cache - // Stores whether we currently have a server running - rpcServerActive *uint32 - // The context for the client - rpcClientConnContext context.Context - // The function for canceling the client connection - rpcClientConnCancelFunc context.CancelFunc - // The grpc ClientConn for RPC calls - rpcClientConn *grpc.ClientConn - // The grpc forwarding client - rpcForwardingClient *forwardingClient - - // CORS Information - corsConfig *CORSConfig - - // The active set of upstream cluster addresses; stored via the Echo - // mechanism, loaded by the balancer - atomicPrimaryClusterAddrs *atomic.Value - - atomicPrimaryFailoverAddrs *atomic.Value - // replicationState keeps the current replication state cached for quick - // lookup; activeNodeReplicationState stores the active value on standbys - replicationState *uint32 - activeNodeReplicationState *uint32 - - // uiConfig contains UI configuration - uiConfig *UIConfig - - // rawEnabled indicates whether the Raw endpoint is enabled - rawEnabled bool - - // pluginDirectory is the location vault will look for plugin binaries - pluginDirectory string - - // pluginCatalog is used to manage plugin configurations - pluginCatalog *PluginCatalog - - enableMlock bool - - // This can be used to trigger operations to stop running when Vault is - // going to be shut down, stepped down, or sealed - activeContext context.Context - activeContextCancelFunc *atomic.Value - - // Stores the sealunwrapper for downgrade needs - sealUnwrapper physical.Backend - - // Stores any funcs that should be run on successful postUnseal - postUnsealFuncs []func() - - // Stores loggers so we can reset the level - allLoggers []log.Logger - allLoggersLock sync.RWMutex -} - -// CoreConfig is used to parameterize a core -type CoreConfig struct { - DevToken string `json:"dev_token" structs:"dev_token" mapstructure:"dev_token"` - - LogicalBackends map[string]logical.Factory `json:"logical_backends" structs:"logical_backends" mapstructure:"logical_backends"` - - CredentialBackends map[string]logical.Factory `json:"credential_backends" structs:"credential_backends" mapstructure:"credential_backends"` - - AuditBackends map[string]audit.Factory `json:"audit_backends" structs:"audit_backends" mapstructure:"audit_backends"` - - Physical physical.Backend `json:"physical" structs:"physical" mapstructure:"physical"` - - // May be nil, which disables HA operations - HAPhysical physical.HABackend `json:"ha_physical" structs:"ha_physical" mapstructure:"ha_physical"` - - Seal Seal `json:"seal" structs:"seal" mapstructure:"seal"` - - Logger log.Logger `json:"logger" structs:"logger" mapstructure:"logger"` - - // Disables the LRU cache on the physical backend - DisableCache bool `json:"disable_cache" structs:"disable_cache" mapstructure:"disable_cache"` - - // Disables mlock syscall - DisableMlock bool `json:"disable_mlock" structs:"disable_mlock" mapstructure:"disable_mlock"` - - // Custom cache size for the LRU cache on the physical backend, or zero for default - CacheSize int `json:"cache_size" structs:"cache_size" mapstructure:"cache_size"` - - // Set as the leader address for HA - RedirectAddr string `json:"redirect_addr" structs:"redirect_addr" mapstructure:"redirect_addr"` - - // Set as the cluster address for HA - ClusterAddr string `json:"cluster_addr" structs:"cluster_addr" mapstructure:"cluster_addr"` - - DefaultLeaseTTL time.Duration `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` - - MaxLeaseTTL time.Duration `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` - - ClusterName string `json:"cluster_name" structs:"cluster_name" mapstructure:"cluster_name"` - - ClusterCipherSuites string `json:"cluster_cipher_suites" structs:"cluster_cipher_suites" mapstructure:"cluster_cipher_suites"` - - EnableUI bool `json:"ui" structs:"ui" mapstructure:"ui"` - - // Enable the raw endpoint - EnableRaw bool `json:"enable_raw" structs:"enable_raw" mapstructure:"enable_raw"` - - PluginDirectory string `json:"plugin_directory" structs:"plugin_directory" mapstructure:"plugin_directory"` - - ReloadFuncs *map[string][]reload.ReloadFunc - ReloadFuncsLock *sync.RWMutex - - AllLoggers []log.Logger -} - -// NewCore is used to construct a new core -func NewCore(conf *CoreConfig) (*Core, error) { - if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() { - if conf.RedirectAddr == "" { - return nil, fmt.Errorf("missing API address, please set in configuration or via environment") - } - } - - if conf.DefaultLeaseTTL == 0 { - conf.DefaultLeaseTTL = defaultLeaseTTL - } - if conf.MaxLeaseTTL == 0 { - conf.MaxLeaseTTL = maxLeaseTTL - } - if conf.DefaultLeaseTTL > conf.MaxLeaseTTL { - return nil, fmt.Errorf("cannot have DefaultLeaseTTL larger than MaxLeaseTTL") - } - - // Validate the advertise addr if its given to us - if conf.RedirectAddr != "" { - u, err := url.Parse(conf.RedirectAddr) - if err != nil { - return nil, errwrap.Wrapf("redirect address is not valid url: {{err}}", err) - } - - if u.Scheme == "" { - return nil, fmt.Errorf("redirect address must include scheme (ex. 'http')") - } - } - - // Make a default logger if not provided - if conf.Logger == nil { - conf.Logger = logging.NewVaultLogger(log.Trace) - } - - // Setup the core - c := &Core{ - devToken: conf.DevToken, - physical: conf.Physical, - redirectAddr: conf.RedirectAddr, - clusterAddr: conf.ClusterAddr, - seal: conf.Seal, - router: NewRouter(), - sealed: new(uint32), - standby: true, - baseLogger: conf.Logger, - logger: conf.Logger.Named("core"), - defaultLeaseTTL: conf.DefaultLeaseTTL, - maxLeaseTTL: conf.MaxLeaseTTL, - cachingDisabled: conf.DisableCache, - clusterName: conf.ClusterName, - clusterListenerShutdownCh: make(chan struct{}), - clusterListenerShutdownSuccessCh: make(chan struct{}), - clusterPeerClusterAddrsCache: cache.New(3*HeartbeatInterval, time.Second), - enableMlock: !conf.DisableMlock, - rawEnabled: conf.EnableRaw, - replicationState: new(uint32), - rpcServerActive: new(uint32), - atomicPrimaryClusterAddrs: new(atomic.Value), - atomicPrimaryFailoverAddrs: new(atomic.Value), - localClusterPrivateKey: new(atomic.Value), - localClusterCert: new(atomic.Value), - localClusterParsedCert: new(atomic.Value), - activeNodeReplicationState: new(uint32), - keepHALockOnStepDown: new(uint32), - activeContextCancelFunc: new(atomic.Value), - allLoggers: conf.AllLoggers, - } - - atomic.StoreUint32(c.sealed, 1) - c.allLoggers = append(c.allLoggers, c.logger) - - atomic.StoreUint32(c.replicationState, uint32(consts.ReplicationDRDisabled|consts.ReplicationPerformanceDisabled)) - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - c.activeContextCancelFunc.Store((context.CancelFunc)(nil)) - - if conf.ClusterCipherSuites != "" { - suites, err := tlsutil.ParseCiphers(conf.ClusterCipherSuites) - if err != nil { - return nil, errwrap.Wrapf("error parsing cluster cipher suites: {{err}}", err) - } - c.clusterCipherSuites = suites - } - - // Load CORS config and provide a value for the core field. - c.corsConfig = &CORSConfig{ - core: c, - Enabled: new(uint32), - } - - phys := conf.Physical - _, txnOK := conf.Physical.(physical.Transactional) - if c.seal == nil { - c.seal = NewDefaultSeal() - } - c.seal.SetCore(c) - - unwrapperLogger := c.baseLogger.Named("storage.sealunwrapper") - c.allLoggers = append(c.allLoggers, unwrapperLogger) - c.sealUnwrapper = NewSealUnwrapper(phys, unwrapperLogger) - - var ok bool - - // Wrap the physical backend in a cache layer if enabled - cacheLogger := c.baseLogger.Named("storage.cache") - c.allLoggers = append(c.allLoggers, cacheLogger) - if txnOK { - c.physical = physical.NewTransactionalCache(c.sealUnwrapper, conf.CacheSize, cacheLogger) - } else { - c.physical = physical.NewCache(c.sealUnwrapper, conf.CacheSize, cacheLogger) - } - c.physicalCache = c.physical.(physical.ToggleablePurgemonster) - - if !conf.DisableMlock { - // Ensure our memory usage is locked into physical RAM - if err := mlock.LockMemory(); err != nil { - return nil, fmt.Errorf( - "Failed to lock memory: %v\n\n"+ - "This usually means that the mlock syscall is not available.\n"+ - "Vault uses mlock to prevent memory from being swapped to\n"+ - "disk. This requires root privileges as well as a machine\n"+ - "that supports mlock. Please enable mlock on your system or\n"+ - "disable Vault from using it. To disable Vault from using it,\n"+ - "set the `disable_mlock` configuration option in your configuration\n"+ - "file.", - err) - } - } - - var err error - if conf.PluginDirectory != "" { - c.pluginDirectory, err = filepath.Abs(conf.PluginDirectory) - if err != nil { - return nil, errwrap.Wrapf("core setup failed, could not verify plugin directory: {{err}}", err) - } - } - - // Construct a new AES-GCM barrier - c.barrier, err = NewAESGCMBarrier(c.physical) - if err != nil { - return nil, errwrap.Wrapf("barrier setup failed: {{err}}", err) - } - - if conf.HAPhysical != nil && conf.HAPhysical.HAEnabled() { - c.ha = conf.HAPhysical - } - - // We create the funcs here, then populate the given config with it so that - // the caller can share state - conf.ReloadFuncsLock = &c.reloadFuncsLock - c.reloadFuncsLock.Lock() - c.reloadFuncs = make(map[string][]reload.ReloadFunc) - c.reloadFuncsLock.Unlock() - conf.ReloadFuncs = &c.reloadFuncs - - // Setup the backends - logicalBackends := make(map[string]logical.Factory) - for k, f := range conf.LogicalBackends { - logicalBackends[k] = f - } - _, ok = logicalBackends["kv"] - if !ok { - logicalBackends["kv"] = PassthroughBackendFactory - } - logicalBackends["cubbyhole"] = CubbyholeBackendFactory - logicalBackends["system"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - sysBackendLogger := conf.Logger.Named("system") - c.AddLogger(sysBackendLogger) - b := NewSystemBackend(c, sysBackendLogger) - if err := b.Setup(ctx, config); err != nil { - return nil, err - } - return b, nil - } - - logicalBackends["identity"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - identityLogger := conf.Logger.Named("identity") - c.AddLogger(identityLogger) - return NewIdentityStore(ctx, c, config, identityLogger) - } - - c.logicalBackends = logicalBackends - - credentialBackends := make(map[string]logical.Factory) - for k, f := range conf.CredentialBackends { - credentialBackends[k] = f - } - credentialBackends["token"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - tsLogger := conf.Logger.Named("token") - c.AddLogger(tsLogger) - return NewTokenStore(ctx, tsLogger, c, config) - } - c.credentialBackends = credentialBackends - - auditBackends := make(map[string]audit.Factory) - for k, f := range conf.AuditBackends { - auditBackends[k] = f - } - c.auditBackends = auditBackends - - uiStoragePrefix := systemBarrierPrefix + "ui" - c.uiConfig = NewUIConfig(conf.EnableUI, physical.NewView(c.physical, uiStoragePrefix), NewBarrierView(c.barrier, uiStoragePrefix)) - - return c, nil -} - -// Shutdown is invoked when the Vault instance is about to be terminated. It -// should not be accessible as part of an API call as it will cause an availability -// problem. It is only used to gracefully quit in the case of HA so that failover -// happens as quickly as possible. -func (c *Core) Shutdown() error { - c.logger.Debug("shutdown called") - return c.sealInternal() -} - -// CORSConfig returns the current CORS configuration -func (c *Core) CORSConfig() *CORSConfig { - return c.corsConfig -} - -func (c *Core) GetContext() (context.Context, context.CancelFunc) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - - return context.WithCancel(c.activeContext) -} - -// Sealed checks if the Vault is current sealed -func (c *Core) Sealed() bool { - return atomic.LoadUint32(c.sealed) == 1 -} - -// SecretProgress returns the number of keys provided so far -func (c *Core) SecretProgress() (int, string) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - switch c.unlockInfo { - case nil: - return 0, "" - default: - return len(c.unlockInfo.Parts), c.unlockInfo.Nonce - } -} - -// ResetUnsealProcess removes the current unlock parts from memory, to reset -// the unsealing process -func (c *Core) ResetUnsealProcess() { - c.stateLock.Lock() - defer c.stateLock.Unlock() - c.unlockInfo = nil -} - -// Unseal is used to provide one of the key parts to unseal the Vault. -// -// They key given as a parameter will automatically be zerod after -// this method is done with it. If you want to keep the key around, a copy -// should be made. -func (c *Core) Unseal(key []byte) (bool, error) { - defer metrics.MeasureSince([]string{"core", "unseal"}, time.Now()) - - c.stateLock.Lock() - defer c.stateLock.Unlock() - - ctx := context.Background() - - // Explicitly check for init status. This also checks if the seal - // configuration is valid (i.e. non-nil). - init, err := c.Initialized(ctx) - if err != nil { - return false, err - } - if !init { - return false, ErrNotInit - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return false, &ErrInvalidKey{fmt.Sprintf("key is shorter than minimum %d bytes", min)} - } - if len(key) > max { - return false, &ErrInvalidKey{fmt.Sprintf("key is longer than maximum %d bytes", max)} - } - - // Get the barrier seal configuration - config, err := c.seal.BarrierConfig(ctx) - if err != nil { - return false, err - } - - // Check if already unsealed - if !c.Sealed() { - return true, nil - } - - masterKey, err := c.unsealPart(ctx, config, key, false) - if err != nil { - return false, err - } - if masterKey != nil { - return c.unsealInternal(ctx, masterKey) - } - - return false, nil -} - -// UnsealWithRecoveryKeys is used to provide one of the recovery key shares to -// unseal the Vault. -func (c *Core) UnsealWithRecoveryKeys(ctx context.Context, key []byte) (bool, error) { - defer metrics.MeasureSince([]string{"core", "unseal_with_recovery_keys"}, time.Now()) - - c.stateLock.Lock() - defer c.stateLock.Unlock() - - // Explicitly check for init status - init, err := c.Initialized(ctx) - if err != nil { - return false, err - } - if !init { - return false, ErrNotInit - } - - var config *SealConfig - // If recovery keys are supported then use recovery seal config to unseal - if c.seal.RecoveryKeySupported() { - config, err = c.seal.RecoveryConfig(ctx) - if err != nil { - return false, err - } - } - - // Check if already unsealed - if !c.Sealed() { - return true, nil - } - - masterKey, err := c.unsealPart(ctx, config, key, true) - if err != nil { - return false, err - } - if masterKey != nil { - return c.unsealInternal(ctx, masterKey) - } - - return false, nil -} - -// unsealPart takes in a key share, and returns the master key if the threshold -// is met. If recovery keys are supported, recovery key shares may be provided. -func (c *Core) unsealPart(ctx context.Context, config *SealConfig, key []byte, useRecoveryKeys bool) ([]byte, error) { - // Check if we already have this piece - if c.unlockInfo != nil { - for _, existing := range c.unlockInfo.Parts { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, nil - } - } - } else { - uuid, err := uuid.GenerateUUID() - if err != nil { - return nil, err - } - c.unlockInfo = &unlockInformation{ - Nonce: uuid, - } - } - - // Store this key - c.unlockInfo.Parts = append(c.unlockInfo.Parts, key) - - // Check if we don't have enough keys to unlock, proceed through the rest of - // the call only if we have met the threshold - if len(c.unlockInfo.Parts) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot unseal, not enough keys", "keys", len(c.unlockInfo.Parts), "threshold", config.SecretThreshold, "nonce", c.unlockInfo.Nonce) - } - return nil, nil - } - - // Best-effort memzero of unlock parts once we're done with them - defer func() { - for i := range c.unlockInfo.Parts { - memzero(c.unlockInfo.Parts[i]) - } - c.unlockInfo = nil - }() - - // Recover the split key. recoveredKey is the shamir combined - // key, or the single provided key if the threshold is 1. - var recoveredKey []byte - var err error - if config.SecretThreshold == 1 { - recoveredKey = make([]byte, len(c.unlockInfo.Parts[0])) - copy(recoveredKey, c.unlockInfo.Parts[0]) - } else { - recoveredKey, err = shamir.Combine(c.unlockInfo.Parts) - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - - if c.seal.RecoveryKeySupported() && useRecoveryKeys { - // Verify recovery key - if err := c.seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil { - return nil, err - } - - // Get stored keys and shamir combine into single master key. Unsealing with - // recovery keys currently does not support: 1) mixed stored and non-stored - // keys setup, nor 2) seals that support recovery keys but not stored keys. - // If insufficient shares are provided, shamir.Combine will error, and if - // no stored keys are found it will return masterKey as nil. - var masterKey []byte - if c.seal.StoredKeysSupported() { - masterKeyShares, err := c.seal.GetStoredKeys(ctx) - if err != nil { - return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err) - } - - if len(masterKeyShares) == 1 { - return masterKeyShares[0], nil - } - - masterKey, err = shamir.Combine(masterKeyShares) - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - return masterKey, nil - } - - // If this is not a recovery key-supported seal, then the recovered key is - // the master key to be returned. - return recoveredKey, nil -} - -// unsealInternal takes in the master key and attempts to unseal the barrier. -// N.B.: This must be called with the state write lock held. -func (c *Core) unsealInternal(ctx context.Context, masterKey []byte) (bool, error) { - defer memzero(masterKey) - - // Attempt to unlock - if err := c.barrier.Unseal(ctx, masterKey); err != nil { - return false, err - } - if c.logger.IsInfo() { - c.logger.Info("vault is unsealed") - } - - // Do post-unseal setup if HA is not enabled - if c.ha == nil { - // We still need to set up cluster info even if it's not part of a - // cluster right now. This also populates the cached cluster object. - if err := c.setupCluster(ctx); err != nil { - c.logger.Error("cluster setup failed", "error", err) - c.barrier.Seal() - c.logger.Warn("vault is sealed") - return false, err - } - - ctx, ctxCancel := context.WithCancel(context.Background()) - if err := c.postUnseal(ctx, ctxCancel); err != nil { - c.logger.Error("post-unseal setup failed", "error", err) - c.barrier.Seal() - c.logger.Warn("vault is sealed") - return false, err - } - - c.standby = false - } else { - // Go to standby mode, wait until we are active to unseal - c.standbyDoneCh = make(chan struct{}) - c.manualStepDownCh = make(chan struct{}) - c.standbyStopCh = make(chan struct{}) - go c.runStandby(c.standbyDoneCh, c.manualStepDownCh, c.standbyStopCh) - } - - // Force a cache bust here, which will also run migration code - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(ctx, nil) - } - - // Success! - atomic.StoreUint32(c.sealed, 0) - - if c.ha != nil { - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifySealedStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify unsealed status", "error", err) - } - } - } - } - return true, nil -} - -// SealWithRequest takes in a logical.Request, acquires the lock, and passes -// through to sealInternal -func (c *Core) SealWithRequest(httpCtx context.Context, req *logical.Request) error { - defer metrics.MeasureSince([]string{"core", "seal-with-request"}, time.Now()) - - if c.Sealed() { - return nil - } - - c.stateLock.RLock() - - // This will unlock the read lock - // We use background context since we may not be active - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - go func() { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }() - - // This will unlock the read lock - return c.sealInitCommon(ctx, req) -} - -// Seal takes in a token and creates a logical.Request, acquires the lock, and -// passes through to sealInternal -func (c *Core) Seal(token string) error { - defer metrics.MeasureSince([]string{"core", "seal"}, time.Now()) - - if c.Sealed() { - return nil - } - - c.stateLock.RLock() - - req := &logical.Request{ - Operation: logical.UpdateOperation, - Path: "sys/seal", - ClientToken: token, - } - - // This will unlock the read lock - // We use background context since we may not be active - return c.sealInitCommon(context.Background(), req) -} - -// sealInitCommon is common logic for Seal and SealWithRequest and is used to -// re-seal the Vault. This requires the Vault to be unsealed again to perform -// any further operations. Note: this function will read-unlock the state lock. -func (c *Core) sealInitCommon(ctx context.Context, req *logical.Request) (retErr error) { - defer metrics.MeasureSince([]string{"core", "seal-internal"}, time.Now()) - - if req == nil { - retErr = multierror.Append(retErr, errors.New("nil request to seal")) - c.stateLock.RUnlock() - return retErr - } - - // Since there is no token store in standby nodes, sealing cannot be done. - // Ideally, the request has to be forwarded to leader node for validation - // and the operation should be performed. But for now, just returning with - // an error and recommending a vault restart, which essentially does the - // same thing. - if c.standby { - c.logger.Error("vault cannot seal when in standby mode; please restart instead") - retErr = multierror.Append(retErr, errors.New("vault cannot seal when in standby mode; please restart instead")) - c.stateLock.RUnlock() - return retErr - } - - acl, te, entity, identityPolicies, err := c.fetchACLTokenEntryAndEntity(req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - retErr = multierror.Append(retErr, err) - c.stateLock.RUnlock() - return retErr - } - - // Audit-log the request before going any further - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Policies: identityPolicies, - IdentityPolicies: identityPolicies, - } - if te != nil { - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, errors.New("failed to audit request, cannot continue")) - c.stateLock.RUnlock() - return retErr - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - // Attempt to use the token (decrement num_uses) - // On error bail out; if the token has been revoked, bail out too - if te != nil { - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - c.stateLock.RUnlock() - return retErr - } - if te == nil { - // Token is no longer valid - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - } - - // Verify that this operation is allowed - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - RootPrivsRequired: true, - }) - if !authResults.Allowed { - c.stateLock.RUnlock() - retErr = multierror.Append(retErr, authResults.Error) - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return retErr - } - - if te != nil && te.NumUses == tokenRevocationPending { - // Token needs to be revoked. We do this immediately here because - // we won't have a token store after sealing. - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(c.activeContext, te) - if err == nil { - err = c.expiration.Revoke(c.activeContext, leaseID) - } - if err != nil { - c.logger.Error("token needed revocation before seal but failed to revoke", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - } - } - - // Unlock; sealing will grab the lock when needed - c.stateLock.RUnlock() - - sealErr := c.sealInternal() - - if sealErr != nil { - retErr = multierror.Append(retErr, sealErr) - } - - return -} - -// UIEnabled returns if the UI is enabled -func (c *Core) UIEnabled() bool { - return c.uiConfig.Enabled() -} - -// UIHeaders returns configured UI headers -func (c *Core) UIHeaders() (http.Header, error) { - return c.uiConfig.Headers(context.Background()) -} - -// sealInternal is an internal method used to seal the vault. It does not do -// any authorization checking. -func (c *Core) sealInternal() error { - return c.sealInternalWithOptions(true, false) -} - -func (c *Core) sealInternalWithOptions(grabStateLock, keepHALock bool) error { - // Mark sealed, and if already marked return - if swapped := atomic.CompareAndSwapUint32(c.sealed, 0, 1); !swapped { - return nil - } - - c.logger.Info("marked as sealed") - - // Clear forwarding clients - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - activeCtxCancel := c.activeContextCancelFunc.Load().(context.CancelFunc) - cancelCtxAndLock := func() { - doneCh := make(chan struct{}) - go func() { - select { - case <-doneCh: - // Attempt to drain any inflight requests - case <-time.After(DefaultMaxRequestDuration): - if activeCtxCancel != nil { - activeCtxCancel() - } - } - }() - - c.stateLock.Lock() - close(doneCh) - // Stop requests from processing - if activeCtxCancel != nil { - activeCtxCancel() - } - } - - // Do pre-seal teardown if HA is not enabled - if c.ha == nil { - if grabStateLock { - cancelCtxAndLock() - defer c.stateLock.Unlock() - } - // Even in a non-HA context we key off of this for some things - c.standby = true - - // Stop requests from processing - if activeCtxCancel != nil { - activeCtxCancel() - } - - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - return fmt.Errorf("internal error") - } - } else { - // If we are keeping the lock we already have the state write lock - // held. Otherwise grab it here so that when stopCh is triggered we are - // locked. - if keepHALock { - atomic.StoreUint32(c.keepHALockOnStepDown, 1) - } - if grabStateLock { - cancelCtxAndLock() - defer c.stateLock.Unlock() - } - - // If we are trying to acquire the lock, force it to return with nil so - // runStandby will exit - // If we are active, signal the standby goroutine to shut down and wait - // for completion. We have the state lock here so nothing else should - // be toggling standby status. - close(c.standbyStopCh) - c.logger.Debug("finished triggering standbyStopCh for runStandby") - - // Wait for runStandby to stop - <-c.standbyDoneCh - atomic.StoreUint32(c.keepHALockOnStepDown, 0) - c.logger.Debug("runStandby done") - } - - c.logger.Debug("sealing barrier") - if err := c.barrier.Seal(); err != nil { - c.logger.Error("error sealing barrier", "error", err) - return err - } - - if c.ha != nil { - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifySealedStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify sealed status", "error", err) - } - } - } - } - - c.logger.Info("vault is sealed") - - return nil -} - -// postUnseal is invoked after the barrier is unsealed, but before -// allowing any user operations. This allows us to setup any state that -// requires the Vault to be unsealed such as mount tables, logical backends, -// credential stores, etc. -func (c *Core) postUnseal(ctx context.Context, ctxCancelFunc context.CancelFunc) (retErr error) { - defer metrics.MeasureSince([]string{"core", "post_unseal"}, time.Now()) - - // Clear any out - c.postUnsealFuncs = nil - - // Create a new request context - c.activeContext = ctx - c.activeContextCancelFunc.Store(ctxCancelFunc) - - defer func() { - if retErr != nil { - ctxCancelFunc() - c.preSeal() - } - }() - c.logger.Info("post-unseal setup starting") - - // Clear forwarding clients; we're active - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - // Enable the cache - c.physicalCache.Purge(ctx) - if !c.cachingDisabled { - c.physicalCache.SetEnabled(true) - } - - switch c.sealUnwrapper.(type) { - case *sealUnwrapper: - c.sealUnwrapper.(*sealUnwrapper).runUnwraps() - case *transactionalSealUnwrapper: - c.sealUnwrapper.(*transactionalSealUnwrapper).runUnwraps() - } - - // Purge these for safety in case of a rekey - c.seal.SetBarrierConfig(ctx, nil) - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(ctx, nil) - } - - if err := enterprisePostUnseal(c); err != nil { - return err - } - if err := c.ensureWrappingKey(ctx); err != nil { - return err - } - if err := c.setupPluginCatalog(); err != nil { - return err - } - if err := c.loadMounts(ctx); err != nil { - return err - } - if err := c.setupMounts(ctx); err != nil { - return err - } - if err := c.setupPolicyStore(ctx); err != nil { - return err - } - if err := c.loadCORSConfig(ctx); err != nil { - return err - } - if err := c.loadCredentials(ctx); err != nil { - return err - } - if err := c.setupCredentials(ctx); err != nil { - return err - } - if err := c.startRollback(); err != nil { - return err - } - if err := c.setupExpiration(); err != nil { - return err - } - if err := c.loadAudits(ctx); err != nil { - return err - } - if err := c.setupAudits(ctx); err != nil { - return err - } - if err := c.loadIdentityStoreArtifacts(ctx); err != nil { - return err - } - if err := c.setupAuditedHeadersConfig(ctx); err != nil { - return err - } - - if c.ha != nil { - if err := c.startClusterListener(ctx); err != nil { - return err - } - } - c.metricsCh = make(chan struct{}) - go c.emitMetrics(c.metricsCh) - - // This is intentionally the last block in this function. We want to allow - // writes just before allowing client requests, to ensure everything has - // been set up properly before any writes can have happened. - for _, v := range c.postUnsealFuncs { - v() - } - - c.logger.Info("post-unseal setup complete") - return nil -} - -// preSeal is invoked before the barrier is sealed, allowing -// for any state teardown required. -func (c *Core) preSeal() error { - defer metrics.MeasureSince([]string{"core", "pre_seal"}, time.Now()) - c.logger.Info("pre-seal teardown starting") - - // Clear any pending funcs - c.postUnsealFuncs = nil - - // Clear any rekey progress - c.barrierRekeyConfig = nil - c.recoveryRekeyConfig = nil - - if c.metricsCh != nil { - close(c.metricsCh) - c.metricsCh = nil - } - var result error - - c.stopClusterListener() - - if err := c.teardownAudits(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down audits: {{err}}", err)) - } - if err := c.stopExpiration(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping expiration: {{err}}", err)) - } - if err := c.teardownCredentials(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down credentials: {{err}}", err)) - } - if err := c.teardownPolicyStore(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error tearing down policy store: {{err}}", err)) - } - if err := c.stopRollback(); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error stopping rollback: {{err}}", err)) - } - if err := c.unloadMounts(context.Background()); err != nil { - result = multierror.Append(result, errwrap.Wrapf("error unloading mounts: {{err}}", err)) - } - if err := enterprisePreSeal(c); err != nil { - result = multierror.Append(result, err) - } - - switch c.sealUnwrapper.(type) { - case *sealUnwrapper: - c.sealUnwrapper.(*sealUnwrapper).stopUnwraps() - case *transactionalSealUnwrapper: - c.sealUnwrapper.(*transactionalSealUnwrapper).stopUnwraps() - } - - // Purge the cache - c.physicalCache.SetEnabled(false) - c.physicalCache.Purge(context.Background()) - - c.logger.Info("pre-seal teardown complete") - return result -} - -func enterprisePostUnsealImpl(c *Core) error { - return nil -} - -func enterprisePreSealImpl(c *Core) error { - return nil -} - -func startReplicationImpl(c *Core) error { - return nil -} - -func stopReplicationImpl(c *Core) error { - return nil -} - -// emitMetrics is used to periodically expose metrics while running -func (c *Core) emitMetrics(stopCh chan struct{}) { - for { - select { - case <-time.After(time.Second): - c.metricsMutex.Lock() - if c.expiration != nil { - c.expiration.emitMetrics() - } - c.metricsMutex.Unlock() - case <-stopCh: - return - } - } -} - -func (c *Core) ReplicationState() consts.ReplicationState { - return consts.ReplicationState(atomic.LoadUint32(c.replicationState)) -} - -func (c *Core) ActiveNodeReplicationState() consts.ReplicationState { - return consts.ReplicationState(atomic.LoadUint32(c.activeNodeReplicationState)) -} - -func (c *Core) SealAccess() *SealAccess { - return NewSealAccess(c.seal) -} - -func (c *Core) Logger() log.Logger { - return c.logger -} - -func (c *Core) BarrierKeyLength() (min, max int) { - min, max = c.barrier.KeyLength() - max += shamir.ShareOverhead - return -} - -func (c *Core) AuditedHeadersConfig() *AuditedHeadersConfig { - return c.auditedHeaders -} - -func lastRemoteWALImpl(c *Core) uint64 { - return 0 -} - -func (c *Core) BarrierEncryptorAccess() *BarrierEncryptorAccess { - return NewBarrierEncryptorAccess(c.barrier) -} - -func (c *Core) PhysicalAccess() *physical.PhysicalAccess { - return physical.NewPhysicalAccess(c.physical) -} - -func (c *Core) RouterAccess() *RouterAccess { - return NewRouterAccess(c) -} - -// IsDRSecondary returns if the current cluster state is a DR secondary. -func (c *Core) IsDRSecondary() bool { - return c.ReplicationState().HasState(consts.ReplicationDRSecondary) -} - -func (c *Core) AddLogger(logger log.Logger) { - c.allLoggersLock.Lock() - defer c.allLoggersLock.Unlock() - c.allLoggers = append(c.allLoggers, logger) -} - -func (c *Core) SetLogLevel(level log.Level) { - c.allLoggersLock.RLock() - defer c.allLoggersLock.RUnlock() - for _, logger := range c.allLoggers { - logger.SetLevel(level) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/cors.go b/vendor/github.com/hashicorp/vault/vault/cors.go deleted file mode 100644 index c389a6e6d..000000000 --- a/vendor/github.com/hashicorp/vault/vault/cors.go +++ /dev/null @@ -1,161 +0,0 @@ -package vault - -import ( - "context" - "errors" - "sync" - "sync/atomic" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - CORSDisabled uint32 = iota - CORSEnabled -) - -var StdAllowedHeaders = []string{ - "Content-Type", - "X-Requested-With", - "X-Vault-AWS-IAM-Server-ID", - "X-Vault-MFA", - "X-Vault-No-Request-Forwarding", - "X-Vault-Token", - "X-Vault-Wrap-Format", - "X-Vault-Wrap-TTL", - "X-Vault-Policy-Override", -} - -// CORSConfig stores the state of the CORS configuration. -type CORSConfig struct { - sync.RWMutex `json:"-"` - core *Core - Enabled *uint32 `json:"enabled"` - AllowedOrigins []string `json:"allowed_origins,omitempty"` - AllowedHeaders []string `json:"allowed_headers,omitempty"` -} - -func (c *Core) saveCORSConfig(ctx context.Context) error { - view := c.systemBarrierView.SubView("config/") - - enabled := atomic.LoadUint32(c.corsConfig.Enabled) - localConfig := &CORSConfig{ - Enabled: &enabled, - } - c.corsConfig.RLock() - localConfig.AllowedOrigins = c.corsConfig.AllowedOrigins - localConfig.AllowedHeaders = c.corsConfig.AllowedHeaders - c.corsConfig.RUnlock() - - entry, err := logical.StorageEntryJSON("cors", localConfig) - if err != nil { - return errwrap.Wrapf("failed to create CORS config entry: {{err}}", err) - } - - if err := view.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to save CORS config: {{err}}", err) - } - - return nil -} - -// This should only be called with the core state lock held for writing -func (c *Core) loadCORSConfig(ctx context.Context) error { - view := c.systemBarrierView.SubView("config/") - - // Load the config in - out, err := view.Get(ctx, "cors") - if err != nil { - return errwrap.Wrapf("failed to read CORS config: {{err}}", err) - } - if out == nil { - return nil - } - - newConfig := new(CORSConfig) - err = out.DecodeJSON(newConfig) - if err != nil { - return err - } - - if newConfig.Enabled == nil { - newConfig.Enabled = new(uint32) - } - - newConfig.core = c - - c.corsConfig = newConfig - - return nil -} - -// Enable takes either a '*' or a comma-separated list of URLs that can make -// cross-origin requests to Vault. -func (c *CORSConfig) Enable(ctx context.Context, urls []string, headers []string) error { - if len(urls) == 0 { - return errors.New("at least one origin or the wildcard must be provided") - } - - if strutil.StrListContains(urls, "*") && len(urls) > 1 { - return errors.New("to allow all origins the '*' must be the only value for allowed_origins") - } - - c.Lock() - c.AllowedOrigins = urls - - // Start with the standard headers to Vault accepts. - c.AllowedHeaders = append(c.AllowedHeaders, StdAllowedHeaders...) - - // Allow the user to add additional headers to the list of - // headers allowed on cross-origin requests. - if len(headers) > 0 { - c.AllowedHeaders = append(c.AllowedHeaders, headers...) - } - c.Unlock() - - atomic.StoreUint32(c.Enabled, CORSEnabled) - - return c.core.saveCORSConfig(ctx) -} - -// IsEnabled returns the value of CORSConfig.isEnabled -func (c *CORSConfig) IsEnabled() bool { - return atomic.LoadUint32(c.Enabled) == CORSEnabled -} - -// Disable sets CORS to disabled and clears the allowed origins & headers. -func (c *CORSConfig) Disable(ctx context.Context) error { - atomic.StoreUint32(c.Enabled, CORSDisabled) - c.Lock() - - c.AllowedOrigins = nil - c.AllowedHeaders = nil - - c.Unlock() - - return c.core.saveCORSConfig(ctx) -} - -// IsValidOrigin determines if the origin of the request is allowed to make -// cross-origin requests based on the CORSConfig. -func (c *CORSConfig) IsValidOrigin(origin string) bool { - // If we aren't enabling CORS then all origins are valid - if !c.IsEnabled() { - return true - } - - c.RLock() - defer c.RUnlock() - - if len(c.AllowedOrigins) == 0 { - return false - } - - if len(c.AllowedOrigins) == 1 && (c.AllowedOrigins)[0] == "*" { - return true - } - - return strutil.StrListContains(c.AllowedOrigins, origin) -} diff --git a/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go b/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go deleted file mode 100644 index 52cb6a588..000000000 --- a/vendor/github.com/hashicorp/vault/vault/dynamic_system_view.go +++ /dev/null @@ -1,221 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/version" -) - -type dynamicSystemView struct { - core *Core - mountEntry *MountEntry -} - -func (d dynamicSystemView) DefaultLeaseTTL() time.Duration { - def, _ := d.fetchTTLs() - return def -} - -func (d dynamicSystemView) MaxLeaseTTL() time.Duration { - _, max := d.fetchTTLs() - return max -} - -func (d dynamicSystemView) SudoPrivilege(ctx context.Context, path string, token string) bool { - // Resolve the token policy - te, err := d.core.tokenStore.Lookup(ctx, token) - if err != nil { - d.core.logger.Error("failed to lookup token", "error", err) - return false - } - - // Ensure the token is valid - if te == nil { - d.core.logger.Error("entry not found for given token") - return false - } - - // Construct the corresponding ACL object - entity, entityPolicies, err := d.core.fetchEntityAndDerivedPolicies(te.EntityID) - if err != nil { - d.core.logger.Error("failed to fetch entity information", "error", err) - return false - } - - acl, err := d.core.policyStore.ACL(ctx, entity, append(entityPolicies, te.Policies...)...) - if err != nil { - d.core.logger.Error("failed to retrieve ACL for token's policies", "token_policies", te.Policies, "error", err) - return false - } - - // The operation type isn't important here as this is run from a path the - // user has already been given access to; we only care about whether they - // have sudo - req := new(logical.Request) - req.Operation = logical.ReadOperation - req.Path = path - authResults := acl.AllowOperation(req) - return authResults.RootPrivs -} - -// TTLsByPath returns the default and max TTLs corresponding to a particular -// mount point, or the system default -func (d dynamicSystemView) fetchTTLs() (def, max time.Duration) { - def = d.core.defaultLeaseTTL - max = d.core.maxLeaseTTL - - if d.mountEntry.Config.DefaultLeaseTTL != 0 { - def = d.mountEntry.Config.DefaultLeaseTTL - } - if d.mountEntry.Config.MaxLeaseTTL != 0 { - max = d.mountEntry.Config.MaxLeaseTTL - } - - return -} - -// Tainted indicates that the mount is in the process of being removed -func (d dynamicSystemView) Tainted() bool { - return d.mountEntry.Tainted -} - -// CachingDisabled indicates whether to use caching behavior -func (d dynamicSystemView) CachingDisabled() bool { - return d.core.cachingDisabled || (d.mountEntry != nil && d.mountEntry.Config.ForceNoCache) -} - -func (d dynamicSystemView) LocalMount() bool { - return d.mountEntry != nil && d.mountEntry.Local -} - -// Checks if this is a primary Vault instance. Caller should hold the stateLock -// in read mode. -func (d dynamicSystemView) ReplicationState() consts.ReplicationState { - return d.core.ReplicationState() -} - -// ResponseWrapData wraps the given data in a cubbyhole and returns the -// token used to unwrap. -func (d dynamicSystemView) ResponseWrapData(ctx context.Context, data map[string]interface{}, ttl time.Duration, jwt bool) (*wrapping.ResponseWrapInfo, error) { - req := &logical.Request{ - Operation: logical.CreateOperation, - Path: "sys/wrapping/wrap", - } - - resp := &logical.Response{ - WrapInfo: &wrapping.ResponseWrapInfo{ - TTL: ttl, - }, - Data: data, - } - - if jwt { - resp.WrapInfo.Format = "jwt" - } - - _, err := d.core.wrapInCubbyhole(ctx, req, resp, nil) - if err != nil { - return nil, err - } - - return resp.WrapInfo, nil -} - -// LookupPlugin looks for a plugin with the given name in the plugin catalog. It -// returns a PluginRunner or an error if no plugin was found. -func (d dynamicSystemView) LookupPlugin(ctx context.Context, name string) (*pluginutil.PluginRunner, error) { - if d.core == nil { - return nil, fmt.Errorf("system view core is nil") - } - if d.core.pluginCatalog == nil { - return nil, fmt.Errorf("system view core plugin catalog is nil") - } - r, err := d.core.pluginCatalog.Get(ctx, name) - if err != nil { - return nil, err - } - if r == nil { - return nil, errwrap.Wrapf(fmt.Sprintf("{{err}}: %s", name), ErrPluginNotFound) - } - - return r, nil -} - -// MlockEnabled returns the configuration setting for enabling mlock on plugins. -func (d dynamicSystemView) MlockEnabled() bool { - return d.core.enableMlock -} - -func (d dynamicSystemView) EntityInfo(entityID string) (*logical.Entity, error) { - // Requests from token created from the token backend will not have entity information. - // Return missing entity instead of error when requesting from MemDB. - if entityID == "" { - return nil, nil - } - - if d.core == nil { - return nil, fmt.Errorf("system view core is nil") - } - if d.core.identityStore == nil { - return nil, fmt.Errorf("system view identity store is nil") - } - - // Retrieve the entity from MemDB - entity, err := d.core.identityStore.MemDBEntityByID(entityID, false) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - // Return a subset of the data - ret := &logical.Entity{ - ID: entity.ID, - Name: entity.Name, - } - - if entity.Metadata != nil { - ret.Metadata = make(map[string]string, len(entity.Metadata)) - for k, v := range entity.Metadata { - ret.Metadata[k] = v - } - } - - aliases := make([]*logical.Alias, len(entity.Aliases)) - for i, a := range entity.Aliases { - alias := &logical.Alias{ - MountAccessor: a.MountAccessor, - Name: a.Name, - } - // MountType is not stored with the entity and must be looked up - if mount := d.core.router.validateMountByAccessor(a.MountAccessor); mount != nil { - alias.MountType = mount.MountType - } - - if a.Metadata != nil { - alias.Metadata = make(map[string]string, len(a.Metadata)) - for k, v := range a.Metadata { - alias.Metadata[k] = v - } - } - - aliases[i] = alias - } - ret.Aliases = aliases - - return ret, nil -} - -func (d dynamicSystemView) PluginEnv(_ context.Context) (*logical.PluginEnvironment, error) { - return &logical.PluginEnvironment{ - VaultVersion: version.GetVersion().Version, - }, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/expiration.go b/vendor/github.com/hashicorp/vault/vault/expiration.go deleted file mode 100644 index 191b1de11..000000000 --- a/vendor/github.com/hashicorp/vault/vault/expiration.go +++ /dev/null @@ -1,1492 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "path" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - log "github.com/hashicorp/go-hclog" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // expirationSubPath is the sub-path used for the expiration manager - // view. This is nested under the system view. - expirationSubPath = "expire/" - - // leaseViewPrefix is the prefix used for the ID based lookup of leases. - leaseViewPrefix = "id/" - - // tokenViewPrefix is the prefix used for the token based lookup of leases. - tokenViewPrefix = "token/" - - // maxRevokeAttempts limits how many revoke attempts are made - maxRevokeAttempts = 6 - - // revokeRetryBase is a baseline retry time - revokeRetryBase = 10 * time.Second - - // maxLeaseDuration is the default maximum lease duration - maxLeaseTTL = 32 * 24 * time.Hour - - // defaultLeaseDuration is the default lease duration used when no lease is specified - defaultLeaseTTL = maxLeaseTTL - - //maxLeaseThreshold is the maximum lease count before generating log warning - maxLeaseThreshold = 256000 -) - -type pendingInfo struct { - exportLeaseTimes *leaseEntry - timer *time.Timer -} - -// ExpirationManager is used by the Core to manage leases. Secrets -// can provide a lease, meaning that they can be renewed or revoked. -// If a secret is not renewed in timely manner, it may be expired, and -// the ExpirationManager will handle doing automatic revocation. -type ExpirationManager struct { - core *Core - router *Router - idView *BarrierView - tokenView *BarrierView - tokenStore *TokenStore - logger log.Logger - - pending map[string]pendingInfo - pendingLock sync.RWMutex - - tidyLock *int32 - - restoreMode *int32 - restoreModeLock sync.RWMutex - restoreRequestLock sync.RWMutex - restoreLocks []*locksutil.LockEntry - restoreLoaded sync.Map - quitCh chan struct{} - - coreStateLock *sync.RWMutex - quitContext context.Context - leaseCheckCounter *uint32 - - logLeaseExpirations bool -} - -// NewExpirationManager creates a new ExpirationManager that is backed -// using a given view, and uses the provided router for revocation. -func NewExpirationManager(c *Core, view *BarrierView, logger log.Logger) *ExpirationManager { - exp := &ExpirationManager{ - core: c, - router: c.router, - idView: view.SubView(leaseViewPrefix), - tokenView: view.SubView(tokenViewPrefix), - tokenStore: c.tokenStore, - logger: logger, - pending: make(map[string]pendingInfo), - tidyLock: new(int32), - - // new instances of the expiration manager will go immediately into - // restore mode - restoreMode: new(int32), - restoreLocks: locksutil.CreateLocks(), - quitCh: make(chan struct{}), - - coreStateLock: &c.stateLock, - quitContext: c.activeContext, - leaseCheckCounter: new(uint32), - - logLeaseExpirations: os.Getenv("VAULT_SKIP_LOGGING_LEASE_EXPIRATIONS") == "", - } - *exp.restoreMode = 1 - - if exp.logger == nil { - opts := log.LoggerOptions{Name: "expiration_manager"} - exp.logger = log.New(&opts) - } - - return exp -} - -// setupExpiration is invoked after we've loaded the mount table to -// initialize the expiration manager -func (c *Core) setupExpiration() error { - c.metricsMutex.Lock() - defer c.metricsMutex.Unlock() - // Create a sub-view - view := c.systemBarrierView.SubView(expirationSubPath) - - // Create the manager - expLogger := c.baseLogger.Named("expiration") - c.AddLogger(expLogger) - mgr := NewExpirationManager(c, view, expLogger) - c.expiration = mgr - - // Link the token store to this - c.tokenStore.SetExpirationManager(mgr) - - // Restore the existing state - c.logger.Info("restoring leases") - errorFunc := func() { - c.logger.Error("shutting down") - if err := c.Shutdown(); err != nil { - c.logger.Error("error shutting down core: %v", err) - } - } - go c.expiration.Restore(errorFunc) - - return nil -} - -// stopExpiration is used to stop the expiration manager before -// sealing the Vault. -func (c *Core) stopExpiration() error { - if c.expiration != nil { - if err := c.expiration.Stop(); err != nil { - return err - } - c.metricsMutex.Lock() - defer c.metricsMutex.Unlock() - c.expiration = nil - } - return nil -} - -// lockLease takes out a lock for a given lease ID -func (m *ExpirationManager) lockLease(leaseID string) { - locksutil.LockForKey(m.restoreLocks, leaseID).Lock() -} - -// unlockLease unlocks a given lease ID -func (m *ExpirationManager) unlockLease(leaseID string) { - locksutil.LockForKey(m.restoreLocks, leaseID).Unlock() -} - -// inRestoreMode returns if we are currently in restore mode -func (m *ExpirationManager) inRestoreMode() bool { - return atomic.LoadInt32(m.restoreMode) == 1 -} - -// Tidy cleans up the dangling storage entries for leases. It scans the storage -// view to find all the available leases, checks if the token embedded in it is -// either empty or invalid and in both the cases, it revokes them. It also uses -// a token cache to avoid multiple lookups of the same token ID. It is normally -// not required to use the API that invokes this. This is only intended to -// clean up the corrupt storage due to bugs. -func (m *ExpirationManager) Tidy() error { - if m.inRestoreMode() { - return errors.New("cannot run tidy while restoring leases") - } - - var tidyErrors *multierror.Error - - logger := m.logger.Named("tidy") - m.core.AddLogger(logger) - - if !atomic.CompareAndSwapInt32(m.tidyLock, 0, 1) { - logger.Warn("tidy operation on leases is already in progress") - return nil - } - - defer atomic.CompareAndSwapInt32(m.tidyLock, 1, 0) - - logger.Info("beginning tidy operation on leases") - defer logger.Info("finished tidy operation on leases") - - // Create a cache to keep track of looked up tokens - tokenCache := make(map[string]bool) - var countLease, revokedCount, deletedCountInvalidToken, deletedCountEmptyToken int64 - - tidyFunc := func(leaseID string) { - countLease++ - if countLease%500 == 0 { - logger.Info("tidying leases", "progress", countLease) - } - - le, err := m.loadEntry(m.quitContext, leaseID) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to load the lease ID %q: {{err}}", leaseID), err)) - return - } - - if le == nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("nil entry for lease ID %q: {{err}}", leaseID), err)) - return - } - - var isValid, ok bool - revokeLease := false - if le.ClientToken == "" { - logger.Debug("revoking lease which has an empty token", "lease_id", leaseID) - revokeLease = true - deletedCountEmptyToken++ - goto REVOKE_CHECK - } - - isValid, ok = tokenCache[le.ClientToken] - if !ok { - saltedID, err := m.tokenStore.SaltID(m.quitContext, le.ClientToken) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup salt id: {{err}}", err)) - return - } - lock := locksutil.LockForKey(m.tokenStore.tokenLocks, le.ClientToken) - lock.RLock() - te, err := m.tokenStore.lookupSalted(m.quitContext, saltedID, true) - lock.RUnlock() - - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup token: {{err}}", err)) - return - } - - if te == nil { - logger.Debug("revoking lease which holds an invalid token", "lease_id", leaseID) - revokeLease = true - deletedCountInvalidToken++ - tokenCache[le.ClientToken] = false - } else { - tokenCache[le.ClientToken] = true - } - goto REVOKE_CHECK - } else { - if isValid { - return - } - - logger.Debug("revoking lease which contains an invalid token", "lease_id", leaseID) - revokeLease = true - deletedCountInvalidToken++ - goto REVOKE_CHECK - } - - REVOKE_CHECK: - if revokeLease { - // Force the revocation and skip going through the token store - // again - err = m.revokeCommon(m.quitContext, leaseID, true, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf(fmt.Sprintf("failed to revoke an invalid lease with ID %q: {{err}}", leaseID), err)) - return - } - revokedCount++ - } - } - - if err := logical.ScanView(m.quitContext, m.idView, tidyFunc); err != nil { - return err - } - - logger.Info("number of leases scanned", "count", countLease) - logger.Info("number of leases which had empty tokens", "count", deletedCountEmptyToken) - logger.Info("number of leases which had invalid tokens", "count", deletedCountInvalidToken) - logger.Info("number of leases successfully revoked", "count", revokedCount) - - return tidyErrors.ErrorOrNil() -} - -// Restore is used to recover the lease states when starting. -// This is used after starting the vault. -func (m *ExpirationManager) Restore(errorFunc func()) (retErr error) { - defer func() { - // Turn off restore mode. We can do this safely without the lock because - // if restore mode finished successfully, restore mode was already - // disabled with the lock. In an error state, this will allow the - // Stop() function to shut everything down. - atomic.StoreInt32(m.restoreMode, 0) - - switch { - case retErr == nil: - case strings.Contains(retErr.Error(), context.Canceled.Error()): - // Don't run error func because we lost leadership - m.logger.Warn("context cancled while restoring leases, stopping lease loading") - retErr = nil - case errwrap.Contains(retErr, ErrBarrierSealed.Error()): - // Don't run error func because we're likely already shutting down - m.logger.Warn("barrier sealed while restoring leases, stopping lease loading") - retErr = nil - default: - m.logger.Error("error restoring leases", "error", retErr) - if errorFunc != nil { - errorFunc() - } - } - }() - - // Accumulate existing leases - m.logger.Debug("collecting leases") - existing, err := logical.CollectKeys(m.quitContext, m.idView) - if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - m.logger.Debug("leases collected", "num_existing", len(existing)) - - // Make the channels used for the worker pool - broker := make(chan string) - quit := make(chan bool) - // Buffer these channels to prevent deadlocks - errs := make(chan error, len(existing)) - result := make(chan struct{}, len(existing)) - - // Use a wait group - wg := &sync.WaitGroup{} - - // Create 64 workers to distribute work to - for i := 0; i < consts.ExpirationRestoreWorkerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() - - for { - select { - case leaseID, ok := <-broker: - // broker has been closed, we are done - if !ok { - return - } - - err := m.processRestore(leaseID) - if err != nil { - errs <- err - continue - } - - // Send message that lease is done - result <- struct{}{} - - // quit early - case <-quit: - return - - case <-m.quitCh: - return - } - } - }() - } - - // Distribute the collected keys to the workers in a go routine - wg.Add(1) - go func() { - defer wg.Done() - for i, leaseID := range existing { - if i > 0 && i%500 == 0 { - m.logger.Debug("leases loading", "progress", i) - } - - select { - case <-quit: - return - - case <-m.quitCh: - return - - default: - broker <- leaseID - } - } - - // Close the broker, causing worker routines to exit - close(broker) - }() - - // Ensure all keys on the chan are processed - for i := 0; i < len(existing); i++ { - select { - case err := <-errs: - // Close all go routines - close(quit) - return err - - case <-m.quitCh: - close(quit) - return nil - - case <-result: - } - } - - // Let all go routines finish - wg.Wait() - - m.restoreModeLock.Lock() - m.restoreLoaded = sync.Map{} - m.restoreLocks = nil - atomic.StoreInt32(m.restoreMode, 0) - m.restoreModeLock.Unlock() - - m.logger.Info("lease restore complete") - return nil -} - -// processRestore takes a lease and restores it in the expiration manager if it has -// not already been seen -func (m *ExpirationManager) processRestore(leaseID string) error { - m.restoreRequestLock.RLock() - defer m.restoreRequestLock.RUnlock() - - // Check if the lease has been seen - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return nil - } - - m.lockLease(leaseID) - defer m.unlockLease(leaseID) - - // Check again with the lease locked - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return nil - } - - // Load lease and restore expiration timer - _, err := m.loadEntryInternal(m.quitContext, leaseID, true, false) - if err != nil { - return err - } - return nil -} - -// Stop is used to prevent further automatic revocations. -// This must be called before sealing the view. -func (m *ExpirationManager) Stop() error { - // Stop all the pending expiration timers - m.logger.Debug("stop triggered") - defer m.logger.Debug("finished stopping") - - // Do this before stopping pending timers to avoid potential races with - // expiring timers - close(m.quitCh) - - m.pendingLock.Lock() - for _, pending := range m.pending { - pending.timer.Stop() - } - m.pending = make(map[string]pendingInfo) - m.pendingLock.Unlock() - - if m.inRestoreMode() { - for { - if !m.inRestoreMode() { - break - } - time.Sleep(10 * time.Millisecond) - } - } - - return nil -} - -// Revoke is used to revoke a secret named by the given LeaseID -func (m *ExpirationManager) Revoke(ctx context.Context, leaseID string) error { - defer metrics.MeasureSince([]string{"expire", "revoke"}, time.Now()) - - return m.revokeCommon(ctx, leaseID, false, false) -} - -// LazyRevoke is used to queue revocation for a secret named by the given -// LeaseID. If the lease was not found it returns nil; if the lease was found -// it triggers a return of a 202. -func (m *ExpirationManager) LazyRevoke(ctx context.Context, leaseID string) error { - defer metrics.MeasureSince([]string{"expire", "lazy-revoke"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there is no entry, nothing to revoke - if le == nil { - return nil - } - - le.ExpireTime = time.Now() - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return err - } - - m.updatePendingInternal(le, 0) - m.pendingLock.Unlock() - } - - return nil -} - -// revokeCommon does the heavy lifting. If force is true, we ignore a problem -// during revocation and still remove entries/index/lease timers -func (m *ExpirationManager) revokeCommon(ctx context.Context, leaseID string, force, skipToken bool) error { - defer metrics.MeasureSince([]string{"expire", "revoke-common"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there is no entry, nothing to revoke - if le == nil { - return nil - } - - // Revoke the entry - if !skipToken || le.Auth == nil { - if err := m.revokeEntry(ctx, le); err != nil { - if !force { - return err - } - - if m.logger.IsWarn() { - m.logger.Warn("revocation from the backend failed, but in force mode so ignoring", "error", err) - } - } - } - - // Delete the entry - if err := m.deleteEntry(ctx, leaseID); err != nil { - return err - } - - // Delete the secondary index, but only if it's a leased secret (not auth) - if le.Secret != nil { - if err := m.removeIndexByToken(ctx, le.ClientToken, le.LeaseID); err != nil { - return err - } - } - - // Clear the expiration handler - m.pendingLock.Lock() - if pending, ok := m.pending[leaseID]; ok { - pending.timer.Stop() - delete(m.pending, leaseID) - } - m.pendingLock.Unlock() - - if m.logger.IsInfo() && !skipToken && m.logLeaseExpirations { - m.logger.Info("revoked lease", "lease_id", leaseID) - } - - return nil -} - -// RevokeForce works similarly to RevokePrefix but continues in the case of a -// revocation error; this is mostly meant for recovery operations -func (m *ExpirationManager) RevokeForce(ctx context.Context, prefix string) error { - defer metrics.MeasureSince([]string{"expire", "revoke-force"}, time.Now()) - - return m.revokePrefixCommon(ctx, prefix, true, true) -} - -// RevokePrefix is used to revoke all secrets with a given prefix. -// The prefix maps to that of the mount table to make this simpler -// to reason about. -func (m *ExpirationManager) RevokePrefix(ctx context.Context, prefix string, sync bool) error { - defer metrics.MeasureSince([]string{"expire", "revoke-prefix"}, time.Now()) - - return m.revokePrefixCommon(ctx, prefix, false, sync) -} - -// RevokeByToken is used to revoke all the secrets issued with a given token. -// This is done by using the secondary index. It also removes the lease entry -// for the token itself. As a result it should *ONLY* ever be called from the -// token store's revokeSalted function. -func (m *ExpirationManager) RevokeByToken(ctx context.Context, te *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"expire", "revoke-by-token"}, time.Now()) - - // Lookup the leases - existing, err := m.lookupLeasesByToken(ctx, te.ID) - if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - - // Revoke all the keys - for _, leaseID := range existing { - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return err - } - - // If there's a lease, set expiration to now, persist, and call - // updatePending to hand off revocation to the expiration manager's pending - // timer map - if le != nil { - le.ExpireTime = time.Now() - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return err - } - - m.updatePendingInternal(le, 0) - m.pendingLock.Unlock() - } - } - } - - // te.Path should never be empty, but we check just in case - if te.Path != "" { - saltedID, err := m.tokenStore.SaltID(ctx, te.ID) - if err != nil { - return err - } - tokenLeaseID := path.Join(te.Path, saltedID) - - // We want to skip the revokeEntry call as that will call back into - // revocation logic in the token store, which is what is running this - // function in the first place -- it'd be a deadlock loop. Since the only - // place that this function is called is revokeSalted in the token store, - // we're already revoking the token, so we just want to clean up the lease. - // This avoids spurious revocations later in the log when the timer runs - // out, and eases up resource usage. - return m.revokeCommon(ctx, tokenLeaseID, false, true) - } - - return nil -} - -func (m *ExpirationManager) revokePrefixCommon(ctx context.Context, prefix string, force, sync bool) error { - if m.inRestoreMode() { - m.restoreRequestLock.Lock() - defer m.restoreRequestLock.Unlock() - } - - // Ensure there is a trailing slash; or, if there is no slash, see if there - // is a matching specific ID - if !strings.HasSuffix(prefix, "/") { - le, err := m.loadEntry(ctx, prefix) - if err == nil && le != nil { - if sync { - if err := m.revokeCommon(ctx, prefix, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q: {{err}}", prefix), err) - } - return nil - } - return m.LazyRevoke(ctx, prefix) - } - prefix = prefix + "/" - } - - // Accumulate existing leases - sub := m.idView.SubView(prefix) - existing, err := logical.CollectKeys(ctx, sub) - if err != nil { - return errwrap.Wrapf("failed to scan for leases: {{err}}", err) - } - - // Revoke all the keys - for idx, suffix := range existing { - leaseID := prefix + suffix - switch { - case sync: - if err := m.revokeCommon(ctx, leaseID, force, false); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) - } - default: - if err := m.LazyRevoke(ctx, leaseID); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke %q (%d / %d): {{err}}", leaseID, idx+1, len(existing)), err) - } - } - } - - return nil -} - -// Renew is used to renew a secret using the given leaseID -// and a renew interval. The increment may be ignored. -func (m *ExpirationManager) Renew(ctx context.Context, leaseID string, increment time.Duration) (*logical.Response, error) { - defer metrics.MeasureSince([]string{"expire", "renew"}, time.Now()) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return nil, err - } - - // Check if the lease is renewable - if _, err := le.renewable(); err != nil { - return nil, err - } - - if le.Secret == nil { - if le.Auth != nil { - return logical.ErrorResponse("tokens cannot be renewed through this endpoint"), logical.ErrPermissionDenied - } - return logical.ErrorResponse("lease does not correspond to a secret"), nil - } - - sysView := m.router.MatchingSystemView(le.Path) - if sysView == nil { - return nil, fmt.Errorf("unable to retrieve system view from router") - } - - // Attempt to renew the entry - resp, err := m.renewEntry(ctx, le, increment) - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - if resp.IsError() { - return &logical.Response{ - Data: resp.Data, - }, nil - } - if resp.Secret == nil { - return nil, nil - } - - ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Secret.TTL, 0, resp.Secret.MaxTTL, 0, le.IssueTime) - if err != nil { - return nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - resp.Secret.TTL = ttl - - // Attach the LeaseID - resp.Secret.LeaseID = leaseID - - // Update the lease entry - le.Data = resp.Data - le.Secret = resp.Secret - le.ExpireTime = resp.Secret.ExpirationTime() - le.LastRenewalTime = time.Now() - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return nil, err - } - - // Update the expiration time - m.updatePendingInternal(le, resp.Secret.LeaseTotal()) - m.pendingLock.Unlock() - } - - // Return the response - return resp, nil -} - -// RenewToken is used to renew a token which does not need to -// invoke a logical backend. -func (m *ExpirationManager) RenewToken(ctx context.Context, req *logical.Request, source string, token string, - increment time.Duration) (*logical.Response, error) { - defer metrics.MeasureSince([]string{"expire", "renew-token"}, time.Now()) - - // Compute the Lease ID - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return nil, err - } - leaseID := path.Join(source, saltedID) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return nil, err - } - - // Check if the lease is renewable. Note that this also checks for a nil - // lease and errors in that case as well. - if _, err := le.renewable(); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - // Attempt to renew the auth entry - resp, err := m.renewAuthEntry(ctx, req, le, increment) - if err != nil { - return nil, err - } - if resp == nil { - return nil, nil - } - if resp.IsError() { - return &logical.Response{ - Data: resp.Data, - }, nil - } - if resp.Auth == nil { - return nil, nil - } - - sysView := m.router.MatchingSystemView(le.Path) - if sysView == nil { - return nil, fmt.Errorf("unable to retrieve system view from router") - } - - ttl, warnings, err := framework.CalculateTTL(sysView, increment, resp.Auth.TTL, resp.Auth.Period, resp.Auth.MaxTTL, resp.Auth.ExplicitMaxTTL, le.IssueTime) - if err != nil { - return nil, err - } - retResp := &logical.Response{} - for _, warning := range warnings { - retResp.AddWarning(warning) - } - resp.Auth.TTL = ttl - - // Attach the ClientToken - resp.Auth.ClientToken = token - - // Refresh groups - if resp.Auth.EntityID != "" && - resp.Auth.GroupAliases != nil && - m.core.identityStore != nil { - validAliases, err := m.core.identityStore.refreshExternalGroupMembershipsByEntityID(resp.Auth.EntityID, resp.Auth.GroupAliases) - if err != nil { - return nil, err - } - resp.Auth.GroupAliases = validAliases - } - - // Update the lease entry - le.Auth = resp.Auth - le.ExpireTime = resp.Auth.ExpirationTime() - le.LastRenewalTime = time.Now() - - { - m.pendingLock.Lock() - if err := m.persistEntry(ctx, le); err != nil { - m.pendingLock.Unlock() - return nil, err - } - - // Update the expiration time - m.updatePendingInternal(le, resp.Auth.LeaseTotal()) - m.pendingLock.Unlock() - } - - retResp.Auth = resp.Auth - return retResp, nil -} - -// Register is used to take a request and response with an associated -// lease. The secret gets assigned a LeaseID and the management of -// of lease is assumed by the expiration manager. -func (m *ExpirationManager) Register(ctx context.Context, req *logical.Request, resp *logical.Response) (id string, retErr error) { - defer metrics.MeasureSince([]string{"expire", "register"}, time.Now()) - - if req.ClientToken == "" { - return "", fmt.Errorf("cannot register a lease with an empty client token") - } - - // Ignore if there is no leased secret - if resp == nil || resp.Secret == nil { - return "", nil - } - - // Validate the secret - if err := resp.Secret.Validate(); err != nil { - return "", err - } - - // Create a lease entry - leaseUUID, err := uuid.GenerateUUID() - if err != nil { - return "", err - } - - leaseID := path.Join(req.Path, leaseUUID) - - defer func() { - // If there is an error we want to rollback as much as possible (note - // that errors here are ignored to do as much cleanup as we can). We - // want to revoke a generated secret (since an error means we may not - // be successfully tracking it), remove indexes, and delete the entry. - if retErr != nil { - revResp, err := m.router.Route(m.quitContext, logical.RevokeRequest(req.Path, resp.Secret, resp.Data)) - if err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional internal error was encountered revoking the newly-generated secret: {{err}}", err)) - } else if revResp != nil && revResp.IsError() { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered revoking the newly-generated secret: {{err}}", revResp.Error())) - } - - if err := m.deleteEntry(ctx, leaseID); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered deleting any lease associated with the newly-generated secret: {{err}}", err)) - } - - if err := m.removeIndexByToken(ctx, req.ClientToken, leaseID); err != nil { - retErr = multierror.Append(retErr, errwrap.Wrapf("an additional error was encountered removing lease indexes associated with the newly-generated secret: {{err}}", err)) - } - } - }() - - le := leaseEntry{ - LeaseID: leaseID, - ClientToken: req.ClientToken, - Path: req.Path, - Data: resp.Data, - Secret: resp.Secret, - IssueTime: time.Now(), - ExpireTime: resp.Secret.ExpirationTime(), - } - - // Encode the entry - if err := m.persistEntry(ctx, &le); err != nil { - return "", err - } - - // Maintain secondary index by token - if err := m.createIndexByToken(ctx, le.ClientToken, le.LeaseID); err != nil { - return "", err - } - - // Setup revocation timer if there is a lease - m.updatePending(&le, resp.Secret.LeaseTotal()) - - // Done - return le.LeaseID, nil -} - -// RegisterAuth is used to take an Auth response with an associated lease. -// The token does not get a LeaseID, but the lease management is handled by -// the expiration manager. -func (m *ExpirationManager) RegisterAuth(ctx context.Context, source string, auth *logical.Auth) error { - defer metrics.MeasureSince([]string{"expire", "register-auth"}, time.Now()) - - if auth.ClientToken == "" { - return fmt.Errorf("cannot register an auth lease with an empty token") - } - - if strings.Contains(source, "..") { - return consts.ErrPathContainsParentReferences - } - - saltedID, err := m.tokenStore.SaltID(ctx, auth.ClientToken) - if err != nil { - return err - } - - // Create a lease entry - le := leaseEntry{ - LeaseID: path.Join(source, saltedID), - ClientToken: auth.ClientToken, - Auth: auth, - Path: source, - IssueTime: time.Now(), - ExpireTime: auth.ExpirationTime(), - } - - // Encode the entry - if err := m.persistEntry(ctx, &le); err != nil { - return err - } - - // Setup revocation timer - m.updatePending(&le, auth.LeaseTotal()) - - return nil -} - -// FetchLeaseTimesByToken is a helper function to use token values to compute -// the leaseID, rather than pushing that logic back into the token store. -func (m *ExpirationManager) FetchLeaseTimesByToken(ctx context.Context, source, token string) (*leaseEntry, error) { - defer metrics.MeasureSince([]string{"expire", "fetch-lease-times-by-token"}, time.Now()) - - // Compute the Lease ID - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return nil, err - } - leaseID := path.Join(source, saltedID) - return m.FetchLeaseTimes(ctx, leaseID) -} - -// FetchLeaseTimes is used to fetch the issue time, expiration time, and last -// renewed time of a lease entry. It returns a leaseEntry itself, but with only -// those values copied over. -func (m *ExpirationManager) FetchLeaseTimes(ctx context.Context, leaseID string) (*leaseEntry, error) { - defer metrics.MeasureSince([]string{"expire", "fetch-lease-times"}, time.Now()) - - m.pendingLock.RLock() - val := m.pending[leaseID] - m.pendingLock.RUnlock() - - if val.exportLeaseTimes != nil { - return val.exportLeaseTimes, nil - } - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return nil, err - } - if le == nil { - return nil, nil - } - - return m.leaseTimesForExport(le), nil -} - -// Returns lease times for outside callers based on the full leaseEntry passed in -func (m *ExpirationManager) leaseTimesForExport(le *leaseEntry) *leaseEntry { - ret := &leaseEntry{ - IssueTime: le.IssueTime, - ExpireTime: le.ExpireTime, - LastRenewalTime: le.LastRenewalTime, - } - if le.Secret != nil { - ret.Secret = &logical.Secret{} - ret.Secret.Renewable = le.Secret.Renewable - ret.Secret.TTL = le.Secret.TTL - } - if le.Auth != nil { - ret.Auth = &logical.Auth{} - ret.Auth.Renewable = le.Auth.Renewable - ret.Auth.TTL = le.Auth.TTL - } - - return ret -} - -// updatePending is used to update a pending invocation for a lease -func (m *ExpirationManager) updatePending(le *leaseEntry, leaseTotal time.Duration) { - m.pendingLock.Lock() - defer m.pendingLock.Unlock() - - m.updatePendingInternal(le, leaseTotal) -} - -// updatePendingInternal is the locked version of updatePending; do not call -// this without a write lock on m.pending -func (m *ExpirationManager) updatePendingInternal(le *leaseEntry, leaseTotal time.Duration) { - // Check for an existing timer - pending, ok := m.pending[le.LeaseID] - - // If there is no expiry time, don't do anything - if le.ExpireTime.IsZero() { - // if the timer happened to exist, stop the time and delete it from the - // pending timers. - if ok { - pending.timer.Stop() - delete(m.pending, le.LeaseID) - } - return - } - - // Create entry if it does not exist or reset if it does - if ok { - pending.timer.Reset(leaseTotal) - } else { - timer := time.AfterFunc(leaseTotal, func() { - m.expireID(le.LeaseID) - }) - pending = pendingInfo{ - timer: timer, - } - } - - // Extend the timer by the lease total - pending.exportLeaseTimes = m.leaseTimesForExport(le) - - m.pending[le.LeaseID] = pending -} - -// expireID is invoked when a given ID is expired -func (m *ExpirationManager) expireID(leaseID string) { - // Clear from the pending expiration - m.pendingLock.Lock() - delete(m.pending, leaseID) - m.pendingLock.Unlock() - - for attempt := uint(0); attempt < maxRevokeAttempts; attempt++ { - ctx, cancel := context.WithTimeout(m.quitContext, DefaultMaxRequestDuration) - - go func() { - select { - case <-ctx.Done(): - case <-m.quitCh: - cancel() - } - }() - - select { - case <-m.quitCh: - m.logger.Error("shutting down, not attempting further revocation of lease", "lease_id", leaseID) - return - case <-m.quitContext.Done(): - m.logger.Error("core context canceled, not attempting further revocation of lease", "lease_id", leaseID) - return - default: - } - - m.coreStateLock.RLock() - err := m.Revoke(ctx, leaseID) - m.coreStateLock.RUnlock() - cancel() - if err == nil { - return - } - - m.logger.Error("failed to revoke lease", "lease_id", leaseID, "error", err) - time.Sleep((1 << attempt) * revokeRetryBase) - } - m.logger.Error("maximum revoke attempts reached", "lease_id", leaseID) -} - -// revokeEntry is used to attempt revocation of an internal entry -func (m *ExpirationManager) revokeEntry(ctx context.Context, le *leaseEntry) error { - // Revocation of login tokens is special since we can by-pass the - // backend and directly interact with the token store - if le.Auth != nil { - if err := m.tokenStore.revokeTree(ctx, le.ClientToken); err != nil { - return errwrap.Wrapf("failed to revoke token: {{err}}", err) - } - - return nil - } - - // Handle standard revocation via backends - resp, err := m.router.Route(m.quitContext, logical.RevokeRequest(le.Path, le.Secret, le.Data)) - if err != nil || (resp != nil && resp.IsError()) { - return errwrap.Wrapf(fmt.Sprintf("failed to revoke entry: resp: %#v err: {{err}}", resp), err) - } - return nil -} - -// renewEntry is used to attempt renew of an internal entry -func (m *ExpirationManager) renewEntry(ctx context.Context, le *leaseEntry, increment time.Duration) (*logical.Response, error) { - secret := *le.Secret - secret.IssueTime = le.IssueTime - secret.Increment = increment - secret.LeaseID = "" - req := logical.RenewRequest(le.Path, &secret, le.Data) - resp, err := m.router.Route(ctx, req) - if err != nil || (resp != nil && resp.IsError()) { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to renew entry: resp: %#v err: {{err}}", resp), err) - } - return resp, nil -} - -// renewAuthEntry is used to attempt renew of an auth entry. Only the token -// store should get the actual token ID intact. -func (m *ExpirationManager) renewAuthEntry(ctx context.Context, req *logical.Request, le *leaseEntry, increment time.Duration) (*logical.Response, error) { - auth := *le.Auth - auth.IssueTime = le.IssueTime - auth.Increment = increment - if strings.HasPrefix(le.Path, "auth/token/") { - auth.ClientToken = le.ClientToken - } else { - auth.ClientToken = "" - } - - authReq := logical.RenewAuthRequest(le.Path, &auth, nil) - authReq.Connection = req.Connection - resp, err := m.router.Route(ctx, authReq) - if err != nil { - return nil, errwrap.Wrapf("failed to renew entry: {{err}}", err) - } - return resp, nil -} - -// loadEntry is used to read a lease entry -func (m *ExpirationManager) loadEntry(ctx context.Context, leaseID string) (*leaseEntry, error) { - // Take out the lease locks after we ensure we are in restore mode - restoreMode := m.inRestoreMode() - if restoreMode { - m.restoreModeLock.RLock() - defer m.restoreModeLock.RUnlock() - - restoreMode = m.inRestoreMode() - if restoreMode { - m.lockLease(leaseID) - defer m.unlockLease(leaseID) - } - } - return m.loadEntryInternal(ctx, leaseID, restoreMode, true) -} - -// loadEntryInternal is used when you need to load an entry but also need to -// control the lifecycle of the restoreLock -func (m *ExpirationManager) loadEntryInternal(ctx context.Context, leaseID string, restoreMode bool, checkRestored bool) (*leaseEntry, error) { - out, err := m.idView.Get(ctx, leaseID) - if err != nil { - return nil, errwrap.Wrapf("failed to read lease entry: {{err}}", err) - } - if out == nil { - return nil, nil - } - le, err := decodeLeaseEntry(out.Value) - if err != nil { - return nil, errwrap.Wrapf("failed to decode lease entry: {{err}}", err) - } - - if restoreMode { - if checkRestored { - // If we have already loaded this lease, we don't need to update on - // load. In the case of renewal and revocation, updatePending will be - // done after making the appropriate modifications to the lease. - if _, ok := m.restoreLoaded.Load(leaseID); ok { - return le, nil - } - } - - // Update the cache of restored leases, either synchronously or through - // the lazy loaded restore process - m.restoreLoaded.Store(le.LeaseID, struct{}{}) - - // Setup revocation timer - m.updatePending(le, le.ExpireTime.Sub(time.Now())) - } - return le, nil -} - -// persistEntry is used to persist a lease entry -func (m *ExpirationManager) persistEntry(ctx context.Context, le *leaseEntry) error { - // Encode the entry - buf, err := le.encode() - if err != nil { - return errwrap.Wrapf("failed to encode lease entry: {{err}}", err) - } - - // Write out to the view - ent := logical.StorageEntry{ - Key: le.LeaseID, - Value: buf, - } - if le.Auth != nil && len(le.Auth.Policies) == 1 && le.Auth.Policies[0] == "root" { - ent.SealWrap = true - } - if err := m.idView.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease entry: {{err}}", err) - } - return nil -} - -// deleteEntry is used to delete a lease entry -func (m *ExpirationManager) deleteEntry(ctx context.Context, leaseID string) error { - if err := m.idView.Delete(ctx, leaseID); err != nil { - return errwrap.Wrapf("failed to delete lease entry: {{err}}", err) - } - return nil -} - -// createIndexByToken creates a secondary index from the token to a lease entry -func (m *ExpirationManager) createIndexByToken(ctx context.Context, token, leaseID string) error { - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return err - } - - leaseSaltedID, err := m.tokenStore.SaltID(ctx, leaseID) - if err != nil { - return err - } - - ent := logical.StorageEntry{ - Key: saltedID + "/" + leaseSaltedID, - Value: []byte(leaseID), - } - if err := m.tokenView.Put(ctx, &ent); err != nil { - return errwrap.Wrapf("failed to persist lease index entry: {{err}}", err) - } - return nil -} - -// indexByToken looks up the secondary index from the token to a lease entry -func (m *ExpirationManager) indexByToken(ctx context.Context, token, leaseID string) (*logical.StorageEntry, error) { - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return nil, err - } - - leaseSaltedID, err := m.tokenStore.SaltID(ctx, leaseID) - if err != nil { - return nil, err - } - - key := saltedID + "/" + leaseSaltedID - entry, err := m.tokenView.Get(ctx, key) - if err != nil { - return nil, fmt.Errorf("failed to look up secondary index entry") - } - return entry, nil -} - -// removeIndexByToken removes the secondary index from the token to a lease entry -func (m *ExpirationManager) removeIndexByToken(ctx context.Context, token, leaseID string) error { - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return err - } - - leaseSaltedID, err := m.tokenStore.SaltID(ctx, leaseID) - if err != nil { - return err - } - - key := saltedID + "/" + leaseSaltedID - if err := m.tokenView.Delete(ctx, key); err != nil { - return errwrap.Wrapf("failed to delete lease index entry: {{err}}", err) - } - return nil -} - -// CreateOrFetchRevocationLeaseByToken is used to create or fetch the matching -// leaseID for a particular token. The lease is set to expire immediately after -// it's created. -func (m *ExpirationManager) CreateOrFetchRevocationLeaseByToken(ctx context.Context, te *logical.TokenEntry) (string, error) { - // Fetch the saltedID of the token and construct the leaseID - saltedID, err := m.tokenStore.SaltID(ctx, te.ID) - if err != nil { - return "", err - } - leaseID := path.Join(te.Path, saltedID) - - // Load the entry - le, err := m.loadEntry(ctx, leaseID) - if err != nil { - return "", err - } - - // If there's no associated leaseEntry for the token, we create one - if le == nil { - auth := &logical.Auth{ - ClientToken: te.ID, - LeaseOptions: logical.LeaseOptions{ - TTL: time.Nanosecond, - }, - } - - if strings.Contains(te.Path, "..") { - return "", consts.ErrPathContainsParentReferences - } - - // Create a lease entry - now := time.Now() - le = &leaseEntry{ - LeaseID: leaseID, - ClientToken: auth.ClientToken, - Auth: auth, - Path: te.Path, - IssueTime: now, - ExpireTime: now.Add(time.Nanosecond), - } - - // Encode the entry - if err := m.persistEntry(ctx, le); err != nil { - return "", err - } - } - - return le.LeaseID, nil -} - -// lookupLeasesByToken is used to lookup all the leaseID's via the tokenID -func (m *ExpirationManager) lookupLeasesByToken(ctx context.Context, token string) ([]string, error) { - saltedID, err := m.tokenStore.SaltID(ctx, token) - if err != nil { - return nil, err - } - - // Scan via the index for sub-leases - prefix := saltedID + "/" - subKeys, err := m.tokenView.List(ctx, prefix) - if err != nil { - return nil, errwrap.Wrapf("failed to list leases: {{err}}", err) - } - - // Read each index entry - leaseIDs := make([]string, 0, len(subKeys)) - for _, sub := range subKeys { - out, err := m.tokenView.Get(ctx, prefix+sub) - if err != nil { - return nil, errwrap.Wrapf("failed to read lease index: {{err}}", err) - } - if out == nil { - continue - } - leaseIDs = append(leaseIDs, string(out.Value)) - } - return leaseIDs, nil -} - -// emitMetrics is invoked periodically to emit statistics -func (m *ExpirationManager) emitMetrics() { - m.pendingLock.RLock() - num := len(m.pending) - m.pendingLock.RUnlock() - metrics.SetGauge([]string{"expire", "num_leases"}, float32(num)) - // Check if lease count is greater than the threshold - if num > maxLeaseThreshold { - if atomic.LoadUint32(m.leaseCheckCounter) > 59 { - m.logger.Warn("lease count exceeds warning lease threshold") - atomic.StoreUint32(m.leaseCheckCounter, 0) - } else { - atomic.AddUint32(m.leaseCheckCounter, 1) - } - } -} - -// leaseEntry is used to structure the values the expiration -// manager stores. This is used to handle renew and revocation. -type leaseEntry struct { - LeaseID string `json:"lease_id"` - ClientToken string `json:"client_token"` - Path string `json:"path"` - Data map[string]interface{} `json:"data"` - Secret *logical.Secret `json:"secret"` - Auth *logical.Auth `json:"auth"` - IssueTime time.Time `json:"issue_time"` - ExpireTime time.Time `json:"expire_time"` - LastRenewalTime time.Time `json:"last_renewal_time"` -} - -// encode is used to JSON encode the lease entry -func (le *leaseEntry) encode() ([]byte, error) { - return json.Marshal(le) -} - -func (le *leaseEntry) renewable() (bool, error) { - var err error - switch { - // If there is no entry, cannot review - case le == nil || le.ExpireTime.IsZero(): - err = fmt.Errorf("lease not found or lease is not renewable") - // Determine if the lease is expired - case le.ExpireTime.Before(time.Now()): - err = fmt.Errorf("lease expired") - // Determine if the lease is renewable - case le.Secret != nil && !le.Secret.Renewable: - err = fmt.Errorf("lease is not renewable") - case le.Auth != nil && !le.Auth.Renewable: - err = fmt.Errorf("lease is not renewable") - } - - if err != nil { - return false, err - } - return true, nil -} - -func (le *leaseEntry) ttl() int64 { - return int64(le.ExpireTime.Sub(time.Now().Round(time.Second)).Seconds()) -} - -// decodeLeaseEntry is used to reverse encode and return a new entry -func decodeLeaseEntry(buf []byte) (*leaseEntry, error) { - out := new(leaseEntry) - return out, jsonutil.DecodeJSON(buf, out) -} diff --git a/vendor/github.com/hashicorp/vault/vault/generate_root.go b/vendor/github.com/hashicorp/vault/vault/generate_root.go deleted file mode 100644 index 9a8750a0e..000000000 --- a/vendor/github.com/hashicorp/vault/vault/generate_root.go +++ /dev/null @@ -1,366 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/helper/xor" - "github.com/hashicorp/vault/shamir" -) - -const coreDROperationTokenPath = "core/dr-operation-token" - -var ( - // GenerateStandardRootTokenStrategy is the strategy used to generate a - // typical root token - GenerateStandardRootTokenStrategy GenerateRootStrategy = generateStandardRootToken{} -) - -// GenerateRootStrategy allows us to swap out the strategy we want to use to -// create a token upon completion of the generate root process. -type GenerateRootStrategy interface { - generate(context.Context, *Core) (string, func(), error) -} - -// generateStandardRootToken implements the GenerateRootStrategy and is in -// charge of creating standard root tokens. -type generateStandardRootToken struct{} - -func (g generateStandardRootToken) generate(ctx context.Context, c *Core) (string, func(), error) { - te, err := c.tokenStore.rootToken(ctx) - if err != nil { - c.logger.Error("root token generation failed", "error", err) - return "", nil, err - } - if te == nil { - c.logger.Error("got nil token entry back from root generation") - return "", nil, fmt.Errorf("got nil token entry back from root generation") - } - - cleanupFunc := func() { - c.tokenStore.revokeOrphan(ctx, te.ID) - } - - return te.ID, cleanupFunc, nil -} - -// GenerateRootConfig holds the configuration for a root generation -// command. -type GenerateRootConfig struct { - Nonce string - PGPKey string - PGPFingerprint string - OTP string - Strategy GenerateRootStrategy -} - -// GenerateRootResult holds the result of a root generation update -// command -type GenerateRootResult struct { - Progress int - Required int - EncodedToken string - PGPFingerprint string -} - -// GenerateRootProgress is used to return the root generation progress (num shares) -func (c *Core) GenerateRootProgress() (int, error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return 0, consts.ErrSealed - } - if c.standby { - return 0, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - return len(c.generateRootProgress), nil -} - -// GenerateRootConfiguration is used to read the root generation configuration -// It stubbornly refuses to return the OTP if one is there. -func (c *Core) GenerateRootConfiguration() (*GenerateRootConfig, error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby { - return nil, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Copy the config if any - var conf *GenerateRootConfig - if c.generateRootConfig != nil { - conf = new(GenerateRootConfig) - *conf = *c.generateRootConfig - conf.OTP = "" - conf.Strategy = nil - } - return conf, nil -} - -// GenerateRootInit is used to initialize the root generation settings -func (c *Core) GenerateRootInit(otp, pgpKey string, strategy GenerateRootStrategy) error { - var fingerprint string - switch { - case len(otp) > 0: - otpBytes, err := base64.StdEncoding.DecodeString(otp) - if err != nil { - return errwrap.Wrapf("error decoding base64 OTP value: {{err}}", err) - } - if otpBytes == nil || len(otpBytes) != 16 { - return fmt.Errorf("decoded OTP value is invalid or wrong length") - } - - case len(pgpKey) > 0: - fingerprints, err := pgpkeys.GetFingerprints([]string{pgpKey}, nil) - if err != nil { - return errwrap.Wrapf("error parsing PGP key: {{err}}", err) - } - if len(fingerprints) != 1 || fingerprints[0] == "" { - return fmt.Errorf("could not acquire PGP key entity") - } - fingerprint = fingerprints[0] - - default: - return fmt.Errorf("unreachable condition") - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return consts.ErrSealed - } - if c.standby { - return consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Prevent multiple concurrent root generations - if c.generateRootConfig != nil { - return fmt.Errorf("root generation already in progress") - } - - // Copy the configuration - generationNonce, err := uuid.GenerateUUID() - if err != nil { - return err - } - - c.generateRootConfig = &GenerateRootConfig{ - Nonce: generationNonce, - OTP: otp, - PGPKey: pgpKey, - PGPFingerprint: fingerprint, - Strategy: strategy, - } - - if c.logger.IsInfo() { - c.logger.Info("root generation initialized", "nonce", c.generateRootConfig.Nonce) - } - return nil -} - -// GenerateRootUpdate is used to provide a new key part -func (c *Core) GenerateRootUpdate(ctx context.Context, key []byte, nonce string, strategy GenerateRootStrategy) (*GenerateRootResult, error) { - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, &ErrInvalidKey{fmt.Sprintf("key is shorter than minimum %d bytes", min)} - } - if len(key) > max { - return nil, &ErrInvalidKey{fmt.Sprintf("key is longer than maximum %d bytes", max)} - } - - // Get the seal configuration - var config *SealConfig - var err error - if c.seal.RecoveryKeySupported() { - config, err = c.seal.RecoveryConfig(ctx) - if err != nil { - return nil, err - } - } else { - config, err = c.seal.BarrierConfig(ctx) - if err != nil { - return nil, err - } - } - - // Ensure the barrier is initialized - if config == nil { - return nil, ErrNotInit - } - - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby { - return nil, consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Ensure a generateRoot is in progress - if c.generateRootConfig == nil { - return nil, fmt.Errorf("no root generation in progress") - } - - if nonce != c.generateRootConfig.Nonce { - return nil, fmt.Errorf("incorrect nonce supplied; nonce for this root generation operation is %q", c.generateRootConfig.Nonce) - } - - if strategy != c.generateRootConfig.Strategy { - return nil, fmt.Errorf("incorrect strategy supplied; a generate root operation of another type is already in progress") - } - - // Check if we already have this piece - for _, existing := range c.generateRootProgress { - if bytes.Equal(existing, key) { - return nil, fmt.Errorf("given key has already been provided during this generation operation") - } - } - - // Store this key - c.generateRootProgress = append(c.generateRootProgress, key) - progress := len(c.generateRootProgress) - - // Check if we don't have enough keys to unlock - if len(c.generateRootProgress) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot generate root, not enough keys", "keys", progress, "threshold", config.SecretThreshold) - } - return &GenerateRootResult{ - Progress: progress, - Required: config.SecretThreshold, - PGPFingerprint: c.generateRootConfig.PGPFingerprint, - }, nil - } - - // Recover the master key - var masterKey []byte - if config.SecretThreshold == 1 { - masterKey = c.generateRootProgress[0] - c.generateRootProgress = nil - } else { - masterKey, err = shamir.Combine(c.generateRootProgress) - c.generateRootProgress = nil - if err != nil { - return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err) - } - } - - // Verify the master key - if c.seal.RecoveryKeySupported() { - if err := c.seal.VerifyRecoveryKey(ctx, masterKey); err != nil { - c.logger.Error("root generation aborted, recovery key verification failed", "error", err) - return nil, err - } - } else { - if err := c.barrier.VerifyMaster(masterKey); err != nil { - c.logger.Error("root generation aborted, master key verification failed", "error", err) - return nil, err - } - } - - // Run the generate strategy - tokenUUID, cleanupFunc, err := strategy.generate(ctx, c) - if err != nil { - return nil, err - } - - uuidBytes, err := uuid.ParseUUID(tokenUUID) - if err != nil { - cleanupFunc() - c.logger.Error("error getting generated token bytes", "error", err) - return nil, err - } - if uuidBytes == nil { - cleanupFunc() - c.logger.Error("got nil parsed UUID bytes") - return nil, fmt.Errorf("got nil parsed UUID bytes") - } - - var tokenBytes []byte - // Get the encoded value first so that if there is an error we don't create - // the root token. - switch { - case len(c.generateRootConfig.OTP) > 0: - // This function performs decoding checks so rather than decode the OTP, - // just encode the value we're passing in. - tokenBytes, err = xor.XORBase64(c.generateRootConfig.OTP, base64.StdEncoding.EncodeToString(uuidBytes)) - if err != nil { - cleanupFunc() - c.logger.Error("xor of root token failed", "error", err) - return nil, err - } - - case len(c.generateRootConfig.PGPKey) > 0: - _, tokenBytesArr, err := pgpkeys.EncryptShares([][]byte{[]byte(tokenUUID)}, []string{c.generateRootConfig.PGPKey}) - if err != nil { - cleanupFunc() - c.logger.Error("error encrypting new root token", "error", err) - return nil, err - } - tokenBytes = tokenBytesArr[0] - - default: - cleanupFunc() - return nil, fmt.Errorf("unreachable condition") - } - - results := &GenerateRootResult{ - Progress: progress, - Required: config.SecretThreshold, - EncodedToken: base64.StdEncoding.EncodeToString(tokenBytes), - PGPFingerprint: c.generateRootConfig.PGPFingerprint, - } - - if c.logger.IsInfo() { - c.logger.Info("root generation finished", "nonce", c.generateRootConfig.Nonce) - } - - c.generateRootProgress = nil - c.generateRootConfig = nil - return results, nil -} - -// GenerateRootCancel is used to cancel an in-progress root generation -func (c *Core) GenerateRootCancel() error { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return consts.ErrSealed - } - if c.standby { - return consts.ErrStandby - } - - c.generateRootLock.Lock() - defer c.generateRootLock.Unlock() - - // Clear any progress or config - c.generateRootConfig = nil - c.generateRootProgress = nil - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/ha.go b/vendor/github.com/hashicorp/vault/vault/ha.go deleted file mode 100644 index 29ffc3141..000000000 --- a/vendor/github.com/hashicorp/vault/vault/ha.go +++ /dev/null @@ -1,871 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/x509" - "errors" - "fmt" - "sync/atomic" - "time" - - metrics "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/namespace" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/oklog/run" -) - -const ( - // lockRetryInterval is the interval we re-attempt to acquire the - // HA lock if an error is encountered - lockRetryInterval = 10 * time.Second - - // leaderCheckInterval is how often a standby checks for a new leader - leaderCheckInterval = 2500 * time.Millisecond - - // keyRotateCheckInterval is how often a standby checks for a key - // rotation taking place. - keyRotateCheckInterval = 10 * time.Second - - // keyRotateGracePeriod is how long we allow an upgrade path - // for standby instances before we delete the upgrade keys - keyRotateGracePeriod = 2 * time.Minute - - // leaderPrefixCleanDelay is how long to wait between deletions - // of orphaned leader keys, to prevent slamming the backend. - leaderPrefixCleanDelay = 200 * time.Millisecond -) - -var ( - addEnterpriseHaActors func(*Core, *run.Group) chan func() = addEnterpriseHaActorsNoop - interruptPerfStandby func(chan func(), chan struct{}) chan struct{} = interruptPerfStandbyNoop -) - -func addEnterpriseHaActorsNoop(*Core, *run.Group) chan func() { return nil } -func interruptPerfStandbyNoop(chan func(), chan struct{}) chan struct{} { - return make(chan struct{}) -} - -// Standby checks if the Vault is in standby mode -func (c *Core) Standby() (bool, error) { - c.stateLock.RLock() - standby := c.standby - c.stateLock.RUnlock() - return standby, nil -} - -// PerfStandby checks if the vault is a performance standby -func (c *Core) PerfStandby() bool { - c.stateLock.RLock() - perfStandby := c.perfStandby - c.stateLock.RUnlock() - return perfStandby -} - -// Leader is used to get the current active leader -func (c *Core) Leader() (isLeader bool, leaderAddr, clusterAddr string, err error) { - // Check if HA enabled. We don't need the lock for this check as it's set - // on startup and never modified - if c.ha == nil { - return false, "", "", ErrHANotEnabled - } - - // Check if sealed - if c.Sealed() { - return false, "", "", consts.ErrSealed - } - - c.stateLock.RLock() - - // Check if we are the leader - if !c.standby { - c.stateLock.RUnlock() - return true, c.redirectAddr, c.clusterAddr, nil - } - - // Initialize a lock - lock, err := c.ha.LockWith(coreLockPath, "read") - if err != nil { - c.stateLock.RUnlock() - return false, "", "", err - } - - // Read the value - held, leaderUUID, err := lock.Value() - if err != nil { - c.stateLock.RUnlock() - return false, "", "", err - } - if !held { - c.stateLock.RUnlock() - return false, "", "", nil - } - - c.clusterLeaderParamsLock.RLock() - localLeaderUUID := c.clusterLeaderUUID - localRedirAddr := c.clusterLeaderRedirectAddr - localClusterAddr := c.clusterLeaderClusterAddr - c.clusterLeaderParamsLock.RUnlock() - - // If the leader hasn't changed, return the cached value; nothing changes - // mid-leadership, and the barrier caches anyways - if leaderUUID == localLeaderUUID && localRedirAddr != "" { - c.stateLock.RUnlock() - return false, localRedirAddr, localClusterAddr, nil - } - - c.logger.Trace("found new active node information, refreshing") - - defer c.stateLock.RUnlock() - c.clusterLeaderParamsLock.Lock() - defer c.clusterLeaderParamsLock.Unlock() - - // Validate base conditions again - if leaderUUID == c.clusterLeaderUUID && c.clusterLeaderRedirectAddr != "" { - return false, localRedirAddr, localClusterAddr, nil - } - - key := coreLeaderPrefix + leaderUUID - // Use background because postUnseal isn't run on standby - entry, err := c.barrier.Get(context.Background(), key) - if err != nil { - return false, "", "", err - } - if entry == nil { - return false, "", "", nil - } - - var oldAdv bool - - var adv activeAdvertisement - err = jsonutil.DecodeJSON(entry.Value, &adv) - if err != nil { - // Fall back to pre-struct handling - adv.RedirectAddr = string(entry.Value) - c.logger.Debug("parsed redirect addr for new active node", "redirect_addr", adv.RedirectAddr) - oldAdv = true - } - - if !oldAdv { - c.logger.Debug("parsing information for new active node", "active_cluster_addr", adv.ClusterAddr, "active_redirect_addr", adv.RedirectAddr) - - // Ensure we are using current values - err = c.loadLocalClusterTLS(adv) - if err != nil { - return false, "", "", err - } - - // This will ensure that we both have a connection at the ready and that - // the address is the current known value - // Since this is standby, we don't use the active context. Later we may - // use a process-scoped context - err = c.refreshRequestForwardingConnection(context.Background(), adv.ClusterAddr) - if err != nil { - return false, "", "", err - } - } - - // Don't set these until everything has been parsed successfully or we'll - // never try again - c.clusterLeaderRedirectAddr = adv.RedirectAddr - c.clusterLeaderClusterAddr = adv.ClusterAddr - c.clusterLeaderUUID = leaderUUID - - return false, adv.RedirectAddr, adv.ClusterAddr, nil -} - -// StepDown is used to step down from leadership -func (c *Core) StepDown(httpCtx context.Context, req *logical.Request) (retErr error) { - defer metrics.MeasureSince([]string{"core", "step_down"}, time.Now()) - - if req == nil { - retErr = multierror.Append(retErr, errors.New("nil request to step-down")) - return retErr - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil - } - if c.ha == nil || c.standby { - return nil - } - - ctx, cancel := context.WithCancel(namespace.RootContext(nil)) - defer cancel() - - go func() { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }() - - acl, te, entity, identityPolicies, err := c.fetchACLTokenEntryAndEntity(req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - retErr = multierror.Append(retErr, err) - return retErr - } - - // Audit-log the request before going any further - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Policies: identityPolicies, - IdentityPolicies: identityPolicies, - } - if te != nil { - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, errors.New("failed to audit request, cannot continue")) - return retErr - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - c.stateLock.RUnlock() - return retErr - } - - // Attempt to use the token (decrement num_uses) - if te != nil { - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return retErr - } - if te == nil { - // Token has been revoked - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - return retErr - } - } - - // Verify that this operation is allowed - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - RootPrivsRequired: true, - }) - if !authResults.Allowed { - retErr = multierror.Append(retErr, authResults.Error) - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return retErr - } - - if te != nil && te.NumUses == tokenRevocationPending { - // Token needs to be revoked. We do this immediately here because - // we won't have a token store after sealing. - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(c.activeContext, te) - if err == nil { - err = c.expiration.Revoke(c.activeContext, leaseID) - } - if err != nil { - c.logger.Error("token needed revocation before step-down but failed to revoke", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - } - } - - select { - case c.manualStepDownCh <- struct{}{}: - default: - c.logger.Warn("manual step-down operation already queued") - } - - return retErr -} - -// runStandby is a long running process that manages a number of the HA -// subsystems. -func (c *Core) runStandby(doneCh, manualStepDownCh, stopCh chan struct{}) { - defer close(doneCh) - defer close(manualStepDownCh) - c.logger.Info("entering standby mode") - - var g run.Group - newLeaderCh := addEnterpriseHaActors(c, &g) - { - // This will cause all the other actors to close when the stop channel - // is closed. - g.Add(func() error { - <-stopCh - return nil - }, func(error) {}) - } - { - // Monitor for key rotation - keyRotateStop := make(chan struct{}) - - g.Add(func() error { - c.periodicCheckKeyUpgrade(context.Background(), keyRotateStop) - return nil - }, func(error) { - close(keyRotateStop) - c.logger.Debug("shutting down periodic key rotation checker") - }) - } - { - // Monitor for new leadership - checkLeaderStop := make(chan struct{}) - - g.Add(func() error { - c.periodicLeaderRefresh(newLeaderCh, checkLeaderStop) - return nil - }, func(error) { - close(checkLeaderStop) - c.logger.Debug("shutting down periodic leader refresh") - }) - } - { - // Wait for leadership - leaderStopCh := make(chan struct{}) - - g.Add(func() error { - c.waitForLeadership(newLeaderCh, manualStepDownCh, leaderStopCh) - return nil - }, func(error) { - close(leaderStopCh) - c.logger.Debug("shutting down leader elections") - }) - } - - // Start all the actors - g.Run() -} - -// waitForLeadership is a long running routine that is used when an HA backend -// is enabled. It waits until we are leader and switches this Vault to -// active. -func (c *Core) waitForLeadership(newLeaderCh chan func(), manualStepDownCh, stopCh chan struct{}) { - var manualStepDown bool - for { - // Check for a shutdown - select { - case <-stopCh: - c.logger.Debug("stop channel triggered in runStandby") - return - default: - // If we've just down, we could instantly grab the lock again. Give - // the other nodes a chance. - if manualStepDown { - time.Sleep(manualStepDownSleepPeriod) - manualStepDown = false - } - } - - // Create a lock - uuid, err := uuid.GenerateUUID() - if err != nil { - c.logger.Error("failed to generate uuid", "error", err) - return - } - lock, err := c.ha.LockWith(coreLockPath, uuid) - if err != nil { - c.logger.Error("failed to create lock", "error", err) - return - } - - // Attempt the acquisition - leaderLostCh := c.acquireLock(lock, stopCh) - - // Bail if we are being shutdown - if leaderLostCh == nil { - return - } - c.logger.Info("acquired lock, enabling active operation") - - // This is used later to log a metrics event; this can be helpful to - // detect flapping - activeTime := time.Now() - - continueCh := interruptPerfStandby(newLeaderCh, stopCh) - // Grab the statelock or stop - if stopped := grabLockOrStop(c.stateLock.Lock, c.stateLock.Unlock, stopCh); stopped { - lock.Unlock() - close(continueCh) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - - if c.Sealed() { - c.logger.Warn("grabbed HA lock but already sealed, exiting") - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - - // Store the lock so that we can manually clear it later if needed - c.heldHALock = lock - - // Create the active context - activeCtx, activeCtxCancel := context.WithCancel(namespace.RootContext(nil)) - c.activeContext = activeCtx - c.activeContextCancelFunc.Store(activeCtxCancel) - - // This block is used to wipe barrier/seal state and verify that - // everything is sane. If we have no sanity in the barrier, we actually - // seal, as there's little we can do. - { - c.seal.SetBarrierConfig(activeCtx, nil) - if c.seal.RecoveryKeySupported() { - c.seal.SetRecoveryConfig(activeCtx, nil) - } - - if err := c.performKeyUpgrades(activeCtx); err != nil { - // We call this in a goroutine so that we can give up the - // statelock and have this shut us down; sealInternal has a - // workflow where it watches for the stopCh to close so we want - // to return from here - c.logger.Error("error performing key upgrades", "error", err) - go c.Shutdown() - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - return - } - } - - { - // Clear previous local cluster cert info so we generate new. Since the - // UUID will have changed, standbys will know to look for new info - c.localClusterParsedCert.Store((*x509.Certificate)(nil)) - c.localClusterCert.Store(([]byte)(nil)) - c.localClusterPrivateKey.Store((*ecdsa.PrivateKey)(nil)) - - if err := c.setupCluster(activeCtx); err != nil { - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - c.logger.Error("cluster setup failed", "error", err) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - } - // Advertise as leader - if err := c.advertiseLeader(activeCtx, uuid, leaderLostCh); err != nil { - c.heldHALock = nil - lock.Unlock() - close(continueCh) - c.stateLock.Unlock() - c.logger.Error("leader advertisement setup failed", "error", err) - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - - // Attempt the post-unseal process - err = c.postUnseal(activeCtx, activeCtxCancel) - if err == nil { - c.standby = false - } - - close(continueCh) - c.stateLock.Unlock() - - // Handle a failure to unseal - if err != nil { - c.logger.Error("post-unseal setup failed", "error", err) - lock.Unlock() - metrics.MeasureSince([]string{"core", "leadership_setup_failed"}, activeTime) - continue - } - - // Monitor a loss of leadership - select { - case <-leaderLostCh: - c.logger.Warn("leadership lost, stopping active operation") - case <-stopCh: - case <-manualStepDownCh: - manualStepDown = true - c.logger.Warn("stepping down from active operation to standby") - } - - // Stop Active Duty - { - // Spawn this in a go routine so we can cancel the context and - // unblock any inflight requests that are holding the statelock. - go func() { - select { - case <-activeCtx.Done(): - // Attempt to drain any inflight requests - case <-time.After(DefaultMaxRequestDuration): - activeCtxCancel() - } - }() - - // Grab lock if we are not stopped - stopped := grabLockOrStop(c.stateLock.Lock, c.stateLock.Unlock, stopCh) - - // Cancel the context incase the above go routine hasn't done it - // yet - activeCtxCancel() - metrics.MeasureSince([]string{"core", "leadership_lost"}, activeTime) - - // Mark as standby - c.standby = true - - // Seal - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - } - - // If we are not meant to keep the HA lock, clear it - if atomic.LoadUint32(c.keepHALockOnStepDown) == 0 { - if err := c.clearLeader(uuid); err != nil { - c.logger.Error("clearing leader advertisement failed", "error", err) - } - - c.heldHALock.Unlock() - c.heldHALock = nil - } - - // If we are stopped return, otherwise unlock the statelock - if stopped { - return - } - c.stateLock.Unlock() - } - } -} - -func grabLockOrStop(lockFunc, unlockFunc func(), stopCh chan struct{}) (stopped bool) { - // Grab the lock as we need it for cluster setup, which needs to happen - // before advertising; - lockGrabbedCh := make(chan struct{}) - go func() { - // Grab the lock - lockFunc() - // If stopCh has been closed, which only happens while the - // stateLock is held, we have actually terminated, so we just - // instantly give up the lock, otherwise we notify that it's ready - // for consumption - select { - case <-stopCh: - unlockFunc() - default: - close(lockGrabbedCh) - } - }() - - select { - case <-stopCh: - return true - case <-lockGrabbedCh: - // We now have the lock and can use it - } - - return false -} - -// This checks the leader periodically to ensure that we switch RPC to a new -// leader pretty quickly. There is logic in Leader() already to not make this -// onerous and avoid more traffic than needed, so we just call that and ignore -// the result. -func (c *Core) periodicLeaderRefresh(newLeaderCh chan func(), stopCh chan struct{}) { - opCount := new(int32) - - clusterAddr := "" - for { - select { - case <-time.After(leaderCheckInterval): - count := atomic.AddInt32(opCount, 1) - if count > 1 { - atomic.AddInt32(opCount, -1) - continue - } - // We do this in a goroutine because otherwise if this refresh is - // called while we're shutting down the call to Leader() can - // deadlock, which then means stopCh can never been seen and we can - // block shutdown - go func() { - // Bind locally, as the race detector is tripping here - lopCount := opCount - isLeader, _, newClusterAddr, _ := c.Leader() - - if !isLeader && newClusterAddr != clusterAddr && newLeaderCh != nil { - select { - case newLeaderCh <- nil: - c.logger.Debug("new leader found, triggering new leader channel") - clusterAddr = newClusterAddr - default: - c.logger.Debug("new leader found, but still processing previous leader change") - } - - } - atomic.AddInt32(lopCount, -1) - }() - case <-stopCh: - return - } - } -} - -// periodicCheckKeyUpgrade is used to watch for key rotation events as a standby -func (c *Core) periodicCheckKeyUpgrade(ctx context.Context, stopCh chan struct{}) { - opCount := new(int32) - for { - select { - case <-time.After(keyRotateCheckInterval): - count := atomic.AddInt32(opCount, 1) - if count > 1 { - atomic.AddInt32(opCount, -1) - continue - } - - go func() { - // Bind locally, as the race detector is tripping here - lopCount := opCount - - // Only check if we are a standby - c.stateLock.RLock() - standby := c.standby - c.stateLock.RUnlock() - if !standby { - atomic.AddInt32(lopCount, -1) - return - } - - // Check for a poison pill. If we can read it, it means we have stale - // keys (e.g. from replication being activated) and we need to seal to - // be unsealed again. - entry, _ := c.barrier.Get(ctx, poisonPillPath) - if entry != nil && len(entry.Value) > 0 { - c.logger.Warn("encryption keys have changed out from underneath us (possibly due to replication enabling), must be unsealed again") - go c.Shutdown() - atomic.AddInt32(lopCount, -1) - return - } - - if err := c.checkKeyUpgrades(ctx); err != nil { - c.logger.Error("key rotation periodic upgrade check failed", "error", err) - } - - atomic.AddInt32(lopCount, -1) - return - }() - case <-stopCh: - return - } - } -} - -// checkKeyUpgrades is used to check if there have been any key rotations -// and if there is a chain of upgrades available -func (c *Core) checkKeyUpgrades(ctx context.Context) error { - for { - // Check for an upgrade - didUpgrade, newTerm, err := c.barrier.CheckUpgrade(ctx) - if err != nil { - return err - } - - // Nothing to do if no upgrade - if !didUpgrade { - break - } - if c.logger.IsInfo() { - c.logger.Info("upgraded to new key term", "term", newTerm) - } - } - return nil -} - -func (c *Core) performKeyUpgrades(ctx context.Context) error { - if err := c.checkKeyUpgrades(ctx); err != nil { - return errwrap.Wrapf("error checking for key upgrades: {{err}}", err) - } - - if err := c.barrier.ReloadMasterKey(ctx); err != nil { - return errwrap.Wrapf("error reloading master key: {{err}}", err) - } - - if err := c.barrier.ReloadKeyring(ctx); err != nil { - return errwrap.Wrapf("error reloading keyring: {{err}}", err) - } - - if err := c.scheduleUpgradeCleanup(ctx); err != nil { - return errwrap.Wrapf("error scheduling upgrade cleanup: {{err}}", err) - } - - return nil -} - -// scheduleUpgradeCleanup is used to ensure that all the upgrade paths -// are cleaned up in a timely manner if a leader failover takes place -func (c *Core) scheduleUpgradeCleanup(ctx context.Context) error { - // List the upgrades - upgrades, err := c.barrier.List(ctx, keyringUpgradePrefix) - if err != nil { - return errwrap.Wrapf("failed to list upgrades: {{err}}", err) - } - - // Nothing to do if no upgrades - if len(upgrades) == 0 { - return nil - } - - // Schedule cleanup for all of them - time.AfterFunc(keyRotateGracePeriod, func() { - sealed, err := c.barrier.Sealed() - if err != nil { - c.logger.Warn("failed to check barrier status at upgrade cleanup time") - return - } - if sealed { - c.logger.Warn("barrier sealed at upgrade cleanup time") - return - } - for _, upgrade := range upgrades { - path := fmt.Sprintf("%s%s", keyringUpgradePrefix, upgrade) - if err := c.barrier.Delete(ctx, path); err != nil { - c.logger.Error("failed to cleanup upgrade", "path", path, "error", err) - } - } - }) - return nil -} - -// acquireLock blocks until the lock is acquired, returning the leaderLostCh -func (c *Core) acquireLock(lock physical.Lock, stopCh <-chan struct{}) <-chan struct{} { - for { - // Attempt lock acquisition - leaderLostCh, err := lock.Lock(stopCh) - if err == nil { - return leaderLostCh - } - - // Retry the acquisition - c.logger.Error("failed to acquire lock", "error", err) - select { - case <-time.After(lockRetryInterval): - case <-stopCh: - return nil - } - } -} - -// advertiseLeader is used to advertise the current node as leader -func (c *Core) advertiseLeader(ctx context.Context, uuid string, leaderLostCh <-chan struct{}) error { - go c.cleanLeaderPrefix(ctx, uuid, leaderLostCh) - - var key *ecdsa.PrivateKey - switch c.localClusterPrivateKey.Load().(type) { - case *ecdsa.PrivateKey: - key = c.localClusterPrivateKey.Load().(*ecdsa.PrivateKey) - default: - c.logger.Error("unknown cluster private key type", "key_type", fmt.Sprintf("%T", c.localClusterPrivateKey.Load())) - return fmt.Errorf("unknown cluster private key type %T", c.localClusterPrivateKey.Load()) - } - - keyParams := &clusterKeyParams{ - Type: corePrivateKeyTypeP521, - X: key.X, - Y: key.Y, - D: key.D, - } - - locCert := c.localClusterCert.Load().([]byte) - localCert := make([]byte, len(locCert)) - copy(localCert, locCert) - adv := &activeAdvertisement{ - RedirectAddr: c.redirectAddr, - ClusterAddr: c.clusterAddr, - ClusterCert: localCert, - ClusterKeyParams: keyParams, - } - val, err := jsonutil.EncodeJSON(adv) - if err != nil { - return err - } - ent := &Entry{ - Key: coreLeaderPrefix + uuid, - Value: val, - } - err = c.barrier.Put(ctx, ent) - if err != nil { - return err - } - - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifyActiveStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify active status", "error", err) - } - } - } - return nil -} - -func (c *Core) cleanLeaderPrefix(ctx context.Context, uuid string, leaderLostCh <-chan struct{}) { - keys, err := c.barrier.List(ctx, coreLeaderPrefix) - if err != nil { - c.logger.Error("failed to list entries in core/leader", "error", err) - return - } - for len(keys) > 0 { - select { - case <-time.After(leaderPrefixCleanDelay): - if keys[0] != uuid { - c.barrier.Delete(ctx, coreLeaderPrefix+keys[0]) - } - keys = keys[1:] - case <-leaderLostCh: - return - } - } -} - -// clearLeader is used to clear our leadership entry -func (c *Core) clearLeader(uuid string) error { - key := coreLeaderPrefix + uuid - err := c.barrier.Delete(context.Background(), key) - - // Advertise ourselves as a standby - sd, ok := c.ha.(physical.ServiceDiscovery) - if ok { - if err := sd.NotifyActiveStateChange(); err != nil { - if c.logger.IsWarn() { - c.logger.Warn("failed to notify standby status", "error", err) - } - } - } - - return err -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_lookup.go b/vendor/github.com/hashicorp/vault/vault/identity_lookup.go deleted file mode 100644 index 20d7ea0b6..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_lookup.go +++ /dev/null @@ -1,329 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func lookupPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "lookup/entity$", - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the entity.", - }, - "id": { - Type: framework.TypeString, - Description: "ID of the entity.", - }, - "alias_id": { - Type: framework.TypeString, - Description: "ID of the alias.", - }, - "alias_name": { - Type: framework.TypeString, - Description: "Name of the alias. This should be supplied in conjunction with 'alias_mount_accessor'.", - }, - "alias_mount_accessor": { - Type: framework.TypeString, - Description: "Accessor of the mount to which the alias belongs to. This should be supplied in conjunction with 'alias_name'.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathLookupEntityUpdate(), - }, - - HelpSynopsis: strings.TrimSpace(lookupHelp["lookup-entity"][0]), - HelpDescription: strings.TrimSpace(lookupHelp["lookup-entity"][1]), - }, - { - Pattern: "lookup/group$", - Fields: map[string]*framework.FieldSchema{ - "name": { - Type: framework.TypeString, - Description: "Name of the group.", - }, - "id": { - Type: framework.TypeString, - Description: "ID of the group.", - }, - "alias_id": { - Type: framework.TypeString, - Description: "ID of the alias.", - }, - "alias_name": { - Type: framework.TypeString, - Description: "Name of the alias. This should be supplied in conjunction with 'alias_mount_accessor'.", - }, - "alias_mount_accessor": { - Type: framework.TypeString, - Description: "Accessor of the mount to which the alias belongs to. This should be supplied in conjunction with 'alias_name'.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathLookupGroupUpdate(), - }, - - HelpSynopsis: strings.TrimSpace(lookupHelp["lookup-group"][0]), - HelpDescription: strings.TrimSpace(lookupHelp["lookup-group"][1]), - }, - } -} - -func (i *IdentityStore) pathLookupEntityUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var entity *identity.Entity - var err error - - inputCount := 0 - - id := "" - idRaw, ok := d.GetOk("id") - if ok { - inputCount++ - id = idRaw.(string) - } - - name := "" - nameRaw, ok := d.GetOk("name") - if ok { - inputCount++ - name = nameRaw.(string) - } - - aliasID := "" - aliasIDRaw, ok := d.GetOk("alias_id") - if ok { - inputCount++ - aliasID = aliasIDRaw.(string) - } - - aliasName := "" - aliasNameRaw, ok := d.GetOk("alias_name") - if ok { - inputCount++ - aliasName = aliasNameRaw.(string) - } - - aliasMountAccessor := "" - aliasMountAccessorRaw, ok := d.GetOk("alias_mount_accessor") - if ok { - inputCount++ - aliasMountAccessor = aliasMountAccessorRaw.(string) - } - - switch { - case inputCount == 0: - return logical.ErrorResponse(fmt.Sprintf("query parameter not supplied")), nil - - case inputCount != 1: - switch { - case inputCount == 2 && aliasName != "" && aliasMountAccessor != "": - default: - return logical.ErrorResponse(fmt.Sprintf("query parameter conflict; please supply distinct set of query parameters")), nil - } - - case inputCount == 1: - switch { - case aliasName != "" || aliasMountAccessor != "": - return logical.ErrorResponse(fmt.Sprintf("both 'alias_name' and 'alias_mount_accessor' needs to be set")), nil - } - } - - switch { - case id != "": - entity, err = i.MemDBEntityByID(id, false) - if err != nil { - return nil, err - } - - case name != "": - entity, err = i.MemDBEntityByName(name, false) - if err != nil { - return nil, err - } - - case aliasID != "": - alias, err := i.MemDBAliasByID(aliasID, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - entity, err = i.MemDBEntityByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - - case aliasName != "" && aliasMountAccessor != "": - alias, err := i.MemDBAliasByFactors(aliasMountAccessor, aliasName, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - entity, err = i.MemDBEntityByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - } - - if entity == nil { - return nil, nil - } - - return i.handleEntityReadCommon(entity) - } -} - -func (i *IdentityStore) pathLookupGroupUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var group *identity.Group - var err error - - inputCount := 0 - - id := "" - idRaw, ok := d.GetOk("id") - if ok { - inputCount++ - id = idRaw.(string) - } - - name := "" - nameRaw, ok := d.GetOk("name") - if ok { - inputCount++ - name = nameRaw.(string) - } - - aliasID := "" - aliasIDRaw, ok := d.GetOk("alias_id") - if ok { - inputCount++ - aliasID = aliasIDRaw.(string) - } - - aliasName := "" - aliasNameRaw, ok := d.GetOk("alias_name") - if ok { - inputCount++ - aliasName = aliasNameRaw.(string) - } - - aliasMountAccessor := "" - aliasMountAccessorRaw, ok := d.GetOk("alias_mount_accessor") - if ok { - inputCount++ - aliasMountAccessor = aliasMountAccessorRaw.(string) - } - - switch { - case inputCount == 0: - return logical.ErrorResponse(fmt.Sprintf("query parameter not supplied")), nil - - case inputCount != 1: - switch { - case inputCount == 2 && aliasName != "" && aliasMountAccessor != "": - default: - return logical.ErrorResponse(fmt.Sprintf("query parameter conflict; please supply distinct set of query parameters")), nil - } - - case inputCount == 1: - switch { - case aliasName != "" || aliasMountAccessor != "": - return logical.ErrorResponse(fmt.Sprintf("both 'alias_name' and 'alias_mount_accessor' needs to be set")), nil - } - } - - switch { - case id != "": - group, err = i.MemDBGroupByID(id, false) - if err != nil { - return nil, err - } - case name != "": - group, err = i.MemDBGroupByName(name, false) - if err != nil { - return nil, err - } - case aliasID != "": - alias, err := i.MemDBAliasByID(aliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - group, err = i.MemDBGroupByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - - case aliasName != "" && aliasMountAccessor != "": - alias, err := i.MemDBAliasByFactors(aliasMountAccessor, aliasName, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - break - } - - group, err = i.MemDBGroupByAliasID(alias.ID, false) - if err != nil { - return nil, err - } - } - - if group == nil { - return nil, nil - } - - return i.handleGroupReadCommon(group) - } -} - -var lookupHelp = map[string][2]string{ - "lookup-entity": { - "Query entities based on various properties.", - `Distinct query parameters to be set: - - 'id' - To query the entity by its ID. - - 'name' - To query the entity by its name. - - 'alias_id' - To query the entity by the ID of any of its aliases. - - 'alias_name' and 'alias_mount_accessor' - To query the entity by the unique factors that represent an alias; the name and the mount accessor. - `, - }, - "lookup-group": { - "Query groups based on various properties.", - `Distinct query parameters to be set: - - 'id' - To query the group by its ID. - - 'name' - To query the group by its name. - - 'alias_id' - To query the group by the ID of any of its aliases. - - 'alias_name' and 'alias_mount_accessor' - To query the group by the unique factors that represent an alias; the name and the mount accessor. - `, - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store.go b/vendor/github.com/hashicorp/vault/vault/identity_store.go deleted file mode 100644 index 318c48a88..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store.go +++ /dev/null @@ -1,396 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - groupBucketsPrefix = "packer/group/buckets/" -) - -func (c *Core) IdentityStore() *IdentityStore { - return c.identityStore -} - -// NewIdentityStore creates a new identity store -func NewIdentityStore(ctx context.Context, core *Core, config *logical.BackendConfig, logger log.Logger) (*IdentityStore, error) { - var err error - - // Create a new in-memory database for the identity store - db, err := memdb.NewMemDB(identityStoreSchema()) - if err != nil { - return nil, errwrap.Wrapf("failed to create memdb for identity store: {{err}}", err) - } - - iStore := &IdentityStore{ - view: config.StorageView, - db: db, - logger: logger, - core: core, - } - - entitiesPackerLogger := iStore.logger.Named("storagepacker").Named("entities") - core.AddLogger(entitiesPackerLogger) - groupsPackerLogger := iStore.logger.Named("storagepacker").Named("groups") - core.AddLogger(groupsPackerLogger) - iStore.entityPacker, err = storagepacker.NewStoragePacker(iStore.view, entitiesPackerLogger, "") - if err != nil { - return nil, errwrap.Wrapf("failed to create entity packer: {{err}}", err) - } - - iStore.groupPacker, err = storagepacker.NewStoragePacker(iStore.view, groupsPackerLogger, groupBucketsPrefix) - if err != nil { - return nil, errwrap.Wrapf("failed to create group packer: {{err}}", err) - } - - iStore.Backend = &framework.Backend{ - BackendType: logical.TypeLogical, - Paths: framework.PathAppend( - entityPaths(iStore), - aliasPaths(iStore), - groupAliasPaths(iStore), - groupPaths(iStore), - lookupPaths(iStore), - upgradePaths(iStore), - ), - Invalidate: iStore.Invalidate, - } - - err = iStore.Setup(ctx, config) - if err != nil { - return nil, err - } - - return iStore, nil -} - -// Invalidate is a callback wherein the backend is informed that the value at -// the given key is updated. In identity store's case, it would be the entity -// storage entries that get updated. The value needs to be read and MemDB needs -// to be updated accordingly. -func (i *IdentityStore) Invalidate(ctx context.Context, key string) { - i.logger.Debug("invalidate notification received", "key", key) - - switch { - // Check if the key is a storage entry key for an entity bucket - case strings.HasPrefix(key, storagepacker.StoragePackerBucketsPrefix): - // Get the hash value of the storage bucket entry key - bucketKeyHash := i.entityPacker.BucketKeyHashByKey(key) - if len(bucketKeyHash) == 0 { - i.logger.Error("failed to get the bucket entry key hash") - return - } - - // Create a MemDB transaction - txn := i.db.Txn(true) - defer txn.Abort() - - // Each entity object in MemDB holds the MD5 hash of the storage - // entry key of the entity bucket. Fetch all the entities that - // belong to this bucket using the hash value. Remove these entities - // from MemDB along with all the aliases of each entity. - entitiesFetched, err := i.MemDBEntitiesByBucketEntryKeyHashInTxn(txn, string(bucketKeyHash)) - if err != nil { - i.logger.Error("failed to fetch entities using the bucket entry key hash", "bucket_entry_key_hash", bucketKeyHash) - return - } - - for _, entity := range entitiesFetched { - // Delete all the aliases in the entity. This function will also remove - // the corresponding alias indexes too. - err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases) - if err != nil { - i.logger.Error("failed to delete aliases in entity", "entity_id", entity.ID, "error", err) - return - } - - // Delete the entity using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID) - if err != nil { - i.logger.Error("failed to delete entity from MemDB", "entity_id", entity.ID, "error", err) - return - } - } - - // Get the storage bucket entry - bucket, err := i.entityPacker.GetBucket(key) - if err != nil { - i.logger.Error("failed to refresh entities", "key", key, "error", err) - return - } - - // If the underlying entry is nil, it means that this invalidation - // notification is for the deletion of the underlying storage entry. At - // this point, since all the entities belonging to this bucket are - // already removed, there is nothing else to be done. But, if the - // storage entry is non-nil, its an indication of an update. In this - // case, entities in the updated bucket needs to be reinserted into - // MemDB. - if bucket != nil { - for _, item := range bucket.Items { - entity, err := i.parseEntityFromBucketItem(ctx, item) - if err != nil { - i.logger.Error("failed to parse entity from bucket entry item", "error", err) - return - } - - // Only update MemDB and don't touch the storage - err = i.upsertEntityInTxn(txn, entity, nil, false) - if err != nil { - i.logger.Error("failed to update entity in MemDB", "error", err) - return - } - } - } - - txn.Commit() - return - - // Check if the key is a storage entry key for an group bucket - case strings.HasPrefix(key, groupBucketsPrefix): - // Get the hash value of the storage bucket entry key - bucketKeyHash := i.groupPacker.BucketKeyHashByKey(key) - if len(bucketKeyHash) == 0 { - i.logger.Error("failed to get the bucket entry key hash") - return - } - - // Create a MemDB transaction - txn := i.db.Txn(true) - defer txn.Abort() - - groupsFetched, err := i.MemDBGroupsByBucketEntryKeyHashInTxn(txn, string(bucketKeyHash)) - if err != nil { - i.logger.Error("failed to fetch groups using the bucket entry key hash", "bucket_entry_key_hash", bucketKeyHash) - return - } - - for _, group := range groupsFetched { - // Delete the group using the same transaction - err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID) - if err != nil { - i.logger.Error("failed to delete group from MemDB", "group_id", group.ID, "error", err) - return - } - } - - // Get the storage bucket entry - bucket, err := i.groupPacker.GetBucket(key) - if err != nil { - i.logger.Error("failed to refresh group", "key", key, "error", err) - return - } - - if bucket != nil { - for _, item := range bucket.Items { - group, err := i.parseGroupFromBucketItem(item) - if err != nil { - i.logger.Error("failed to parse group from bucket entry item", "error", err) - return - } - - // Before updating the group, check if the group exists. If it - // does, then delete the group alias from memdb, for the - // invalidation would have sent an update. - groupFetched, err := i.MemDBGroupByIDInTxn(txn, group.ID, true) - if err != nil { - i.logger.Error("failed to fetch group from MemDB", "error", err) - return - } - - // If the group has an alias remove it from memdb - if groupFetched != nil && groupFetched.Alias != nil { - err := i.MemDBDeleteAliasByIDInTxn(txn, groupFetched.Alias.ID, true) - if err != nil { - i.logger.Error("failed to delete old group alias from MemDB", "error", err) - return - } - } - - // Only update MemDB and don't touch the storage - err = i.UpsertGroupInTxn(txn, group, false) - if err != nil { - i.logger.Error("failed to update group in MemDB", "error", err) - return - } - } - } - - txn.Commit() - return - } -} - -func (i *IdentityStore) parseEntityFromBucketItem(ctx context.Context, item *storagepacker.Item) (*identity.Entity, error) { - if item == nil { - return nil, fmt.Errorf("nil item") - } - - var entity identity.Entity - err := ptypes.UnmarshalAny(item.Message, &entity) - if err != nil { - return nil, errwrap.Wrapf("failed to decode entity from storage bucket item: {{err}}", err) - } - - return &entity, nil -} - -func (i *IdentityStore) parseGroupFromBucketItem(item *storagepacker.Item) (*identity.Group, error) { - if item == nil { - return nil, fmt.Errorf("nil item") - } - - var group identity.Group - err := ptypes.UnmarshalAny(item.Message, &group) - if err != nil { - return nil, errwrap.Wrapf("failed to decode group from storage bucket item: {{err}}", err) - } - - return &group, nil -} - -// entityByAliasFactors fetches the entity based on factors of alias, i.e mount -// accessor and the alias name. -func (i *IdentityStore) entityByAliasFactors(mountAccessor, aliasName string, clone bool) (*identity.Entity, error) { - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - txn := i.db.Txn(false) - - return i.entityByAliasFactorsInTxn(txn, mountAccessor, aliasName, clone) -} - -// entityByAlaisFactorsInTxn fetches the entity based on factors of alias, i.e -// mount accessor and the alias name. -func (i *IdentityStore) entityByAliasFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool) (*identity.Entity, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - alias, err := i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBEntityByAliasIDInTxn(txn, alias.ID, clone) -} - -// CreateOrFetchEntity creates a new entity. This is used by core to -// associate each login attempt by an alias to a unified entity in Vault. -func (i *IdentityStore) CreateOrFetchEntity(alias *logical.Alias) (*identity.Entity, error) { - var entity *identity.Entity - var err error - - if alias == nil { - return nil, fmt.Errorf("alias is nil") - } - - if alias.Name == "" { - return nil, fmt.Errorf("empty alias name") - } - - mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor) - if mountValidationResp == nil { - return nil, fmt.Errorf("invalid mount accessor %q", alias.MountAccessor) - } - - if mountValidationResp.MountLocal { - return nil, fmt.Errorf("mount_accessor %q is of a local mount", alias.MountAccessor) - } - - if mountValidationResp.MountType != alias.MountType { - return nil, fmt.Errorf("mount accessor %q is not a mount of type %q", alias.MountAccessor, alias.MountType) - } - - // Check if an entity already exists for the given alais - entity, err = i.entityByAliasFactors(alias.MountAccessor, alias.Name, false) - if err != nil { - return nil, err - } - if entity != nil { - return entity, nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to update both alias and entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Check if an entity was created before acquiring the lock - entity, err = i.entityByAliasFactorsInTxn(txn, alias.MountAccessor, alias.Name, false) - if err != nil { - return nil, err - } - if entity != nil { - return entity, nil - } - - entity = &identity.Entity{} - - err = i.sanitizeEntity(entity) - if err != nil { - return nil, err - } - - // Create a new alias - newAlias := &identity.Alias{ - CanonicalID: entity.ID, - Name: alias.Name, - MountAccessor: alias.MountAccessor, - Metadata: alias.Metadata, - MountPath: mountValidationResp.MountPath, - MountType: mountValidationResp.MountType, - } - - err = i.sanitizeAlias(newAlias) - if err != nil { - return nil, err - } - - i.logger.Debug("creating a new entity", "alias", newAlias) - - // Append the new alias to the new entity - entity.Aliases = []*identity.Alias{ - newAlias, - } - - // Update MemDB and persist entity object - err = i.upsertEntityInTxn(txn, entity, nil, true) - if err != nil { - return nil, err - } - - txn.Commit() - - return entity, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go b/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go deleted file mode 100644 index d4debc4c0..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_aliases.go +++ /dev/null @@ -1,465 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// aliasPaths returns the API endpoints to operate on aliases. -// Following are the paths supported: -// entity-alias - To register/modify an alias -// entity-alias/id - To read, modify, delete and list aliases based on their ID -func aliasPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "entity-alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the entity alias. If set, updates the corresponding entity alias.", - }, - // entity_id is deprecated in favor of canonical_id - "entity_id": { - Type: framework.TypeString, - Description: `Entity ID to which this alias belongs. -This field is deprecated, use canonical_id.`, - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to; unused for a modify", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias; unused for a modify", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - { - Pattern: "entity-alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - // entity_id is deprecated - "entity_id": { - Type: framework.TypeString, - Description: `Entity ID to which this alias belongs to. -This field is deprecated, use canonical_id.`, - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "(Unused)", - }, - "name": { - Type: framework.TypeString, - Description: "(Unused)", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "entity-alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - } -} - -// handleAliasUpdateCommon is used to update an alias -func (i *IdentityStore) handleAliasUpdateCommon() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var err error - var alias *identity.Alias - var entity *identity.Entity - var previousEntity *identity.Entity - - i.lock.Lock() - defer i.lock.Unlock() - - // Check for update or create - aliasID := d.Get("id").(string) - if aliasID != "" { - alias, err = i.MemDBAliasByID(aliasID, true, false) - if err != nil { - return nil, err - } - if alias == nil { - return logical.ErrorResponse("invalid alias id"), nil - } - } else { - alias = &identity.Alias{} - } - - // Get entity id - canonicalID := d.Get("canonical_id").(string) - if canonicalID == "" { - // For backwards compatibility - canonicalID = d.Get("entity_id").(string) - } - - // Get alias name - if aliasName := d.Get("name").(string); aliasName == "" { - if alias.Name == "" { - return logical.ErrorResponse("missing alias name"), nil - } - } else { - alias.Name = aliasName - } - - // Get mount accessor - if mountAccessor := d.Get("mount_accessor").(string); mountAccessor == "" { - if alias.MountAccessor == "" { - return logical.ErrorResponse("missing mount_accessor"), nil - } - } else { - alias.MountAccessor = mountAccessor - } - - mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor) - if mountValidationResp == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid mount accessor %q", alias.MountAccessor)), nil - } - if mountValidationResp.MountLocal { - return logical.ErrorResponse(fmt.Sprintf("mount_accessor %q is of a local mount", alias.MountAccessor)), nil - } - - // Verify that the combination of alias name and mount is not - // already tied to a different alias - aliasByFactors, err := i.MemDBAliasByFactors(mountValidationResp.MountAccessor, alias.Name, false, false) - if err != nil { - return nil, err - } - if aliasByFactors != nil { - // If it's a create we won't have an alias ID so this will correctly - // bail. If it's an update alias will be the same as aliasbyfactors so - // we don't need to transfer any info over - if aliasByFactors.ID != alias.ID { - return logical.ErrorResponse("combination of mount and alias name is already in use"), nil - } - - // Fetch the entity to which the alias is tied. We don't need to append - // here, so the only further checking is whether the canonical ID is - // different - entity, err = i.MemDBEntityByAliasID(alias.ID, true) - if err != nil { - return nil, err - } - if entity == nil { - return nil, fmt.Errorf("existing alias is not associated with an entity") - } - if canonicalID == "" || entity.ID == canonicalID { - // Nothing to do - return nil, nil - } - } - - resp := &logical.Response{} - - // If we found an exisitng alias we won't hit this condition because - // canonicalID being empty will result in nil being returned in the block - // above, so in this case we know that creating a new entity is the right - // thing. - if canonicalID == "" { - entity = &identity.Entity{ - Aliases: []*identity.Alias{ - alias, - }, - } - } else { - // If we can look up by the given canonical ID, see if this is a - // transfer; otherwise if we found no previous entity but we find one - // here, use it. - canonicalEntity, err := i.MemDBEntityByID(canonicalID, true) - if err != nil { - return nil, err - } - if canonicalEntity == nil { - return logical.ErrorResponse("invalid canonical ID"), nil - } - if entity == nil { - // If entity is nil, we didn't find a previous alias from factors, - // so append to this entity - entity = canonicalEntity - entity.Aliases = append(entity.Aliases, alias) - } else if entity.ID != canonicalEntity.ID { - // In this case we found an entity from alias factors but it's not - // the same, so it's a migration - previousEntity = entity - entity = canonicalEntity - - for aliasIndex, item := range previousEntity.Aliases { - if item.ID == alias.ID { - previousEntity.Aliases = append(previousEntity.Aliases[:aliasIndex], previousEntity.Aliases[aliasIndex+1:]...) - break - } - } - - entity.Aliases = append(entity.Aliases, alias) - resp.AddWarning(fmt.Sprintf("alias is being transferred from entity %q to %q", previousEntity.ID, entity.ID)) - } - } - - // ID creation and other validations; This is more useful for new entities - // and may not perform anything for the existing entities. Placing the - // check here to make the flow common for both new and existing entities. - err = i.sanitizeEntity(entity) - if err != nil { - return nil, err - } - - // Explicitly set to empty as in the past we incorrectly saved it - alias.MountPath = "" - alias.MountType = "" - - // Set the canonical ID in the alias index. This should be done after - // sanitizing entity. - alias.CanonicalID = entity.ID - - // ID creation and other validations - err = i.sanitizeAlias(alias) - if err != nil { - return nil, err - } - - // Index entity and its aliases in MemDB and persist entity along with - // aliases in storage. If the alias is being transferred over from - // one entity to another, previous entity needs to get refreshed in MemDB - // and persisted in storage as well. - if err := i.upsertEntity(entity, previousEntity, true); err != nil { - return nil, err - } - - // Return ID of both alias and entity - resp.Data = map[string]interface{}{ - "id": alias.ID, - "canonical_id": entity.ID, - } - - return resp, nil - } -} - -// pathAliasIDRead returns the properties of an alias for a given -// alias ID -func (i *IdentityStore) pathAliasIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - aliasID := d.Get("id").(string) - if aliasID == "" { - return logical.ErrorResponse("missing alias id"), nil - } - - alias, err := i.MemDBAliasByID(aliasID, false, false) - if err != nil { - return nil, err - } - - return i.handleAliasReadCommon(alias) - } -} - -func (i *IdentityStore) handleAliasReadCommon(alias *identity.Alias) (*logical.Response, error) { - if alias == nil { - return nil, nil - } - - respData := map[string]interface{}{} - respData["id"] = alias.ID - respData["canonical_id"] = alias.CanonicalID - respData["mount_accessor"] = alias.MountAccessor - respData["metadata"] = alias.Metadata - respData["name"] = alias.Name - respData["merged_from_canonical_ids"] = alias.MergedFromCanonicalIDs - - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - respData["mount_path"] = mountValidationResp.MountPath - respData["mount_type"] = mountValidationResp.MountType - } - - // Convert protobuf timestamp into RFC3339 format - respData["creation_time"] = ptypes.TimestampString(alias.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(alias.LastUpdateTime) - - return &logical.Response{ - Data: respData, - }, nil -} - -// pathAliasIDDelete deletes the alias for a given alias ID -func (i *IdentityStore) pathAliasIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - aliasID := d.Get("id").(string) - if aliasID == "" { - return logical.ErrorResponse("missing alias ID"), nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to delete entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Fetch the alias - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, false) - if err != nil { - return nil, err - } - - // If there is no alias for the ID, do nothing - if alias == nil { - return nil, nil - } - - // Fetch the associated entity - entity, err := i.MemDBEntityByAliasIDInTxn(txn, alias.ID, true) - if err != nil { - return nil, err - } - - // If there is no entity tied to a valid alias, something is wrong - if entity == nil { - return nil, fmt.Errorf("alias not associated to an entity") - } - - aliases := []*identity.Alias{ - alias, - } - - // Delete alias from the entity object - err = i.deleteAliasesInEntityInTxn(txn, entity, aliases) - if err != nil { - return nil, err - } - - // Update the entity index in the entities table - err = i.MemDBUpsertEntityInTxn(txn, entity) - if err != nil { - return nil, err - } - - // Persist the entity object - entityAsAny, err := ptypes.MarshalAny(entity) - if err != nil { - return nil, err - } - item := &storagepacker.Item{ - ID: entity.ID, - Message: entityAsAny, - } - - err = i.entityPacker.PutItem(item) - if err != nil { - return nil, err - } - - // Committing the transaction *after* successfully updating entity in - // storage - txn.Commit() - - return nil, nil - } -} - -// pathAliasIDList lists the IDs of all the valid aliases in the identity -// store -func (i *IdentityStore) pathAliasIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ws := memdb.NewWatchSet() - iter, err := i.MemDBAliases(ws, false) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for aliases in memdb: {{err}}", err) - } - - var aliasIDs []string - aliasInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - alias := raw.(*identity.Alias) - aliasIDs = append(aliasIDs, alias.ID) - aliasInfoEntry := map[string]interface{}{ - "name": alias.Name, - "canonical_id": alias.CanonicalID, - "mount_accessor": alias.MountAccessor, - } - - mi, ok := mountAccessorMap[alias.MountAccessor] - if ok { - aliasInfoEntry["mount_type"] = mi.MountType - aliasInfoEntry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - aliasInfoEntry["mount_type"] = mi.MountType - aliasInfoEntry["mount_path"] = mi.MountPath - } - mountAccessorMap[alias.MountAccessor] = mi - } - - aliasInfo[alias.ID] = aliasInfoEntry - } - - return logical.ListResponseWithInfo(aliasIDs, aliasInfo), nil - } -} - -var aliasHelp = map[string][2]string{ - "alias": { - "Create a new alias.", - "", - }, - "alias-id": { - "Update, read or delete an alias ID.", - "", - }, - "alias-id-list": { - "List all the alias IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go b/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go deleted file mode 100644 index f75a3b27b..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_entities.go +++ /dev/null @@ -1,589 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// entityPaths returns the API endpoints supported to operate on entities. -// Following are the paths supported: -// entity - To register a new entity -// entity/id - To lookup, modify, delete and list entities based on ID -// entity/merge - To merge entities based on ID -func entityPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "entity$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the entity. If set, updates the corresponding existing entity.", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the entity", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the entity. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the entity.", - }, - "disabled": { - Type: framework.TypeBool, - Description: "If set true, tokens tied to this identity will not be able to be used (but will not be revoked).", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity"][1]), - }, - { - Pattern: "entity/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the entity.", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the entity.", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the entity. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the entity.", - }, - "disabled": { - Type: framework.TypeBool, - Description: "If set true, tokens tied to this identity will not be able to be used (but will not be revoked).", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - logical.ReadOperation: i.pathEntityIDRead(), - logical.DeleteOperation: i.pathEntityIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-id"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-id"][1]), - }, - { - Pattern: "entity/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathEntityIDList(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-id-list"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-id-list"][1]), - }, - { - Pattern: "entity/merge/?$", - Fields: map[string]*framework.FieldSchema{ - "from_entity_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Entity IDs which needs to get merged", - }, - "to_entity_id": { - Type: framework.TypeString, - Description: "Entity ID into which all the other entities need to get merged", - }, - "force": { - Type: framework.TypeBool, - Description: "Setting this will follow the 'mine' strategy for merging MFA secrets. If there are secrets of the same type both in entities that are merged from and in entity into which all others are getting merged, secrets in the destination will be unaltered. If not set, this API will throw an error containing all the conflicts.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathEntityMergeID(), - }, - - HelpSynopsis: strings.TrimSpace(entityHelp["entity-merge-id"][0]), - HelpDescription: strings.TrimSpace(entityHelp["entity-merge-id"][1]), - }, - } -} - -// pathEntityMergeID merges two or more entities into a single entity -func (i *IdentityStore) pathEntityMergeID() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - toEntityID := d.Get("to_entity_id").(string) - if toEntityID == "" { - return logical.ErrorResponse("missing entity id to merge to"), nil - } - - fromEntityIDs := d.Get("from_entity_ids").([]string) - if len(fromEntityIDs) == 0 { - return logical.ErrorResponse("missing entity ids to merge from"), nil - } - - force := d.Get("force").(bool) - - // Create a MemDB transaction to merge entities - txn := i.db.Txn(true) - defer txn.Abort() - - toEntity, err := i.MemDBEntityByID(toEntityID, true) - if err != nil { - return nil, err - } - - userErr, intErr := i.mergeEntity(txn, toEntity, fromEntityIDs, force, true, false) - if userErr != nil { - return logical.ErrorResponse(userErr.Error()), nil - } - if intErr != nil { - return nil, intErr - } - - // Committing the transaction *after* successfully performing storage - // persistence - txn.Commit() - - return nil, nil - } -} - -// handleEntityUpdateCommon is used to update an entity -func (i *IdentityStore) handleEntityUpdateCommon() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - i.lock.Lock() - defer i.lock.Unlock() - - var entity *identity.Entity - var err error - - entityID := d.Get("id").(string) - if entityID != "" { - entity, err = i.MemDBEntityByID(entityID, true) - if err != nil { - return nil, err - } - if entity == nil { - return logical.ErrorResponse("entity not found from id"), nil - } - } - - // Get the name - entityName := d.Get("name").(string) - if entityName != "" { - entityByName, err := i.MemDBEntityByName(entityName, false) - if err != nil { - return nil, err - } - switch { - case entityByName == nil: - // Not found, safe to use this name with an existing or new entity - case entity == nil: - // We found an entity by name, but we don't currently allow - // updating based on name, only ID, so return an error - return logical.ErrorResponse("entity name is already in use"), nil - case entity.ID == entityByName.ID: - // Same exact entity, carry on (this is basically a noop then) - default: - return logical.ErrorResponse("entity name is already in use"), nil - } - } - - // Entity will be nil when a new entity is being registered; create a new - // struct in that case. - if entity == nil { - entity = &identity.Entity{} - } - if entityName != "" { - entity.Name = entityName - } - - // Update the policies if supplied - entityPoliciesRaw, ok := d.GetOk("policies") - if ok { - entity.Policies = entityPoliciesRaw.([]string) - } - - if strutil.StrListContains(entity.Policies, "root") { - return logical.ErrorResponse("policies cannot contain root"), nil - } - - disabledRaw, ok := d.GetOk("disabled") - if ok { - entity.Disabled = disabledRaw.(bool) - } - - // Get entity metadata - metadata, ok, err := d.GetOkErr("metadata") - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil - } - if ok { - entity.Metadata = metadata.(map[string]string) - } - // ID creation and some validations - err = i.sanitizeEntity(entity) - if err != nil { - return nil, err - } - - // Prepare the response - respData := map[string]interface{}{ - "id": entity.ID, - } - - var aliasIDs []string - for _, alias := range entity.Aliases { - aliasIDs = append(aliasIDs, alias.ID) - } - - respData["aliases"] = aliasIDs - - // Update MemDB and persist entity object. New entities have not been - // looked up yet so we need to take the lock on the entity on upsert - if err := i.upsertEntity(entity, nil, true); err != nil { - return nil, err - } - - // Return ID of the entity that was either created or updated along with - // its aliases - return &logical.Response{ - Data: respData, - }, nil - } -} - -// pathEntityIDRead returns the properties of an entity for a given entity ID -func (i *IdentityStore) pathEntityIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityID := d.Get("id").(string) - if entityID == "" { - return logical.ErrorResponse("missing entity id"), nil - } - - entity, err := i.MemDBEntityByID(entityID, false) - if err != nil { - return nil, err - } - if entity == nil { - return nil, nil - } - - return i.handleEntityReadCommon(entity) - } -} - -func (i *IdentityStore) handleEntityReadCommon(entity *identity.Entity) (*logical.Response, error) { - respData := map[string]interface{}{} - respData["id"] = entity.ID - respData["name"] = entity.Name - respData["metadata"] = entity.Metadata - respData["merged_entity_ids"] = entity.MergedEntityIDs - respData["policies"] = entity.Policies - respData["disabled"] = entity.Disabled - - // Convert protobuf timestamp into RFC3339 format - respData["creation_time"] = ptypes.TimestampString(entity.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(entity.LastUpdateTime) - - // Convert each alias into a map and replace the time format in each - aliasesToReturn := make([]interface{}, len(entity.Aliases)) - for aliasIdx, alias := range entity.Aliases { - aliasMap := map[string]interface{}{} - aliasMap["id"] = alias.ID - aliasMap["canonical_id"] = alias.CanonicalID - aliasMap["mount_accessor"] = alias.MountAccessor - aliasMap["metadata"] = alias.Metadata - aliasMap["name"] = alias.Name - aliasMap["merged_from_canonical_ids"] = alias.MergedFromCanonicalIDs - aliasMap["creation_time"] = ptypes.TimestampString(alias.CreationTime) - aliasMap["last_update_time"] = ptypes.TimestampString(alias.LastUpdateTime) - - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - aliasMap["mount_type"] = mountValidationResp.MountType - aliasMap["mount_path"] = mountValidationResp.MountPath - } - - aliasesToReturn[aliasIdx] = aliasMap - } - - // Add the aliases information to the response which has the correct time - // formats - respData["aliases"] = aliasesToReturn - - // Fetch the groups this entity belongs to and return their identifiers - groups, inheritedGroups, err := i.groupsByEntityID(entity.ID) - if err != nil { - return nil, err - } - - groupIDs := make([]string, len(groups)) - for i, group := range groups { - groupIDs[i] = group.ID - } - respData["direct_group_ids"] = groupIDs - - inheritedGroupIDs := make([]string, len(inheritedGroups)) - for i, group := range inheritedGroups { - inheritedGroupIDs[i] = group.ID - } - respData["inherited_group_ids"] = inheritedGroupIDs - - respData["group_ids"] = append(groupIDs, inheritedGroupIDs...) - - return &logical.Response{ - Data: respData, - }, nil -} - -// pathEntityIDDelete deletes the entity for a given entity ID -func (i *IdentityStore) pathEntityIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entityID := d.Get("id").(string) - if entityID == "" { - return logical.ErrorResponse("missing entity id"), nil - } - - i.lock.Lock() - defer i.lock.Unlock() - - // Create a MemDB transaction to delete entity - txn := i.db.Txn(true) - defer txn.Abort() - - // Fetch the entity using its ID - entity, err := i.MemDBEntityByIDInTxn(txn, entityID, true) - if err != nil { - return nil, err - } - - // If there is no entity for the ID, do nothing - if entity == nil { - return nil, nil - } - - // Delete all the aliases in the entity. This function will also remove - // the corresponding alias indexes too. - err = i.deleteAliasesInEntityInTxn(txn, entity, entity.Aliases) - if err != nil { - return nil, err - } - - // Delete the entity using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, entity.ID) - if err != nil { - return nil, err - } - - // Delete the entity from storage - err = i.entityPacker.DeleteItem(entity.ID) - if err != nil { - return nil, err - } - - // Committing the transaction *after* successfully deleting entity - txn.Commit() - - return nil, nil - } -} - -// pathEntityIDList lists the IDs of all the valid entities in the identity -// store -func (i *IdentityStore) pathEntityIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ws := memdb.NewWatchSet() - - txn := i.db.Txn(false) - - iter, err := txn.Get(entitiesTable, "id") - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for entities in memdb: {{err}}", err) - } - - ws.Add(iter.WatchCh()) - - var entityIDs []string - entityInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - entity := raw.(*identity.Entity) - entityIDs = append(entityIDs, entity.ID) - entityInfoEntry := map[string]interface{}{ - "name": entity.Name, - } - if len(entity.Aliases) > 0 { - aliasList := make([]interface{}, 0, len(entity.Aliases)) - for _, alias := range entity.Aliases { - entry := map[string]interface{}{ - "id": alias.ID, - "name": alias.Name, - "mount_accessor": alias.MountAccessor, - } - - mi, ok := mountAccessorMap[alias.MountAccessor] - if ok { - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } - mountAccessorMap[alias.MountAccessor] = mi - } - - aliasList = append(aliasList, entry) - } - entityInfoEntry["aliases"] = aliasList - } - entityInfo[entity.ID] = entityInfoEntry - } - - return logical.ListResponseWithInfo(entityIDs, entityInfo), nil - } -} - -func (i *IdentityStore) mergeEntity(txn *memdb.Txn, toEntity *identity.Entity, fromEntityIDs []string, force, grabLock, mergePolicies bool) (error, error) { - if grabLock { - i.lock.Lock() - defer i.lock.Unlock() - } - - if toEntity == nil { - return errors.New("entity id to merge to is invalid"), nil - } - - for _, fromEntityID := range fromEntityIDs { - if fromEntityID == toEntity.ID { - return errors.New("to_entity_id should not be present in from_entity_ids"), nil - } - - fromEntity, err := i.MemDBEntityByID(fromEntityID, false) - if err != nil { - return nil, err - } - - if fromEntity == nil { - return errors.New("entity id to merge from is invalid"), nil - } - - for _, alias := range fromEntity.Aliases { - // Set the desired canonical ID - alias.CanonicalID = toEntity.ID - - alias.MergedFromCanonicalIDs = append(alias.MergedFromCanonicalIDs, fromEntity.ID) - - err = i.MemDBUpsertAliasInTxn(txn, alias, false) - if err != nil { - return nil, errwrap.Wrapf("failed to update alias during merge: {{err}}", err) - } - - // Add the alias to the desired entity - toEntity.Aliases = append(toEntity.Aliases, alias) - } - - // If told to, merge policies - if mergePolicies { - toEntity.Policies = strutil.MergeSlices(toEntity.Policies, fromEntity.Policies) - } - - // If the entity from which we are merging from was already a merged - // entity, transfer over the Merged set to the entity we are - // merging into. - toEntity.MergedEntityIDs = append(toEntity.MergedEntityIDs, fromEntity.MergedEntityIDs...) - - // Add the entity from which we are merging from to the list of entities - // the entity we are merging into is composed of. - toEntity.MergedEntityIDs = append(toEntity.MergedEntityIDs, fromEntity.ID) - - // Delete the entity which we are merging from in MemDB using the same transaction - err = i.MemDBDeleteEntityByIDInTxn(txn, fromEntity.ID) - if err != nil { - return nil, err - } - - // Delete the entity which we are merging from in storage - err = i.entityPacker.DeleteItem(fromEntity.ID) - if err != nil { - return nil, err - } - } - - // Update MemDB with changes to the entity we are merging to - err := i.MemDBUpsertEntityInTxn(txn, toEntity) - if err != nil { - return nil, err - } - - // Persist the entity which we are merging to - toEntityAsAny, err := ptypes.MarshalAny(toEntity) - if err != nil { - return nil, err - } - item := &storagepacker.Item{ - ID: toEntity.ID, - Message: toEntityAsAny, - } - - err = i.entityPacker.PutItem(item) - if err != nil { - return nil, err - } - - return nil, nil -} - -var entityHelp = map[string][2]string{ - "entity": { - "Create a new entity", - "", - }, - "entity-id": { - "Update, read or delete an entity using entity ID", - "", - }, - "entity-id-list": { - "List all the entity IDs", - "", - }, - "entity-merge-id": { - "Merge two or more entities together", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go b/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go deleted file mode 100644 index 57b873448..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_group_aliases.go +++ /dev/null @@ -1,368 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func groupAliasPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "group-alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group alias.", - }, - "name": { - Type: framework.TypeString, - Description: "Alias of the group.", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "ID of the group to which this is an alias.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupAliasRegister(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias"][1]), - }, - { - Pattern: "group-alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group alias.", - }, - "name": { - Type: framework.TypeString, - Description: "Alias of the group.", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "ID of the group to which this is an alias.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupAliasIDUpdate(), - logical.ReadOperation: i.pathGroupAliasIDRead(), - logical.DeleteOperation: i.pathGroupAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias-by-id"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias-by-id"][1]), - }, - { - Pattern: "group-alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathGroupAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(groupAliasHelp["group-alias-id-list"][0]), - HelpDescription: strings.TrimSpace(groupAliasHelp["group-alias-id-list"][1]), - }, - } -} - -func (i *IdentityStore) pathGroupAliasRegister() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - _, ok := d.GetOk("id") - if ok { - return i.pathGroupAliasIDUpdate()(ctx, req, d) - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - return i.handleGroupAliasUpdateCommon(req, d, nil) - } -} - -func (i *IdentityStore) pathGroupAliasIDUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("empty group alias ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - groupAlias, err := i.MemDBAliasByID(groupAliasID, true, true) - if err != nil { - return nil, err - } - if groupAlias == nil { - return logical.ErrorResponse("invalid group alias ID"), nil - } - - return i.handleGroupAliasUpdateCommon(req, d, groupAlias) - } -} - -func (i *IdentityStore) handleGroupAliasUpdateCommon(req *logical.Request, d *framework.FieldData, groupAlias *identity.Alias) (*logical.Response, error) { - var err error - var newGroupAlias bool - var group *identity.Group - - if groupAlias == nil { - groupAlias = &identity.Alias{} - newGroupAlias = true - } - - groupID := d.Get("canonical_id").(string) - if groupID != "" { - group, err = i.MemDBGroupByID(groupID, true) - if err != nil { - return nil, err - } - if group == nil { - return logical.ErrorResponse("invalid group ID"), nil - } - if group.Type != groupTypeExternal { - return logical.ErrorResponse("alias can't be set on an internal group"), nil - } - } - - // Get group alias name - groupAliasName := d.Get("name").(string) - if groupAliasName == "" { - return logical.ErrorResponse("missing alias name"), nil - } - - mountAccessor := d.Get("mount_accessor").(string) - if mountAccessor == "" { - return logical.ErrorResponse("missing mount_accessor"), nil - } - - mountValidationResp := i.core.router.validateMountByAccessor(mountAccessor) - if mountValidationResp == nil { - return logical.ErrorResponse(fmt.Sprintf("invalid mount accessor %q", mountAccessor)), nil - } - - if mountValidationResp.MountLocal { - return logical.ErrorResponse(fmt.Sprintf("mount_accessor %q is of a local mount", mountAccessor)), nil - } - - groupAliasByFactors, err := i.MemDBAliasByFactors(mountValidationResp.MountAccessor, groupAliasName, false, true) - if err != nil { - return nil, err - } - - resp := &logical.Response{} - - if newGroupAlias { - if groupAliasByFactors != nil { - return logical.ErrorResponse("combination of mount and group alias name is already in use"), nil - } - - // If this is an alias being tied to a non-existent group, create - // a new group for it. - if group == nil { - group = &identity.Group{ - Type: groupTypeExternal, - Alias: groupAlias, - } - } else { - group.Alias = groupAlias - } - } else { - // Verify that the combination of group alias name and mount is not - // already tied to a different alias - if groupAliasByFactors != nil && groupAliasByFactors.ID != groupAlias.ID { - return logical.ErrorResponse("combination of mount and group alias name is already in use"), nil - } - - // Fetch the group to which the alias is tied to - existingGroup, err := i.MemDBGroupByAliasID(groupAlias.ID, true) - if err != nil { - return nil, err - } - - if existingGroup == nil { - return nil, fmt.Errorf("group alias is not associated with a group") - } - - if group != nil && group.ID != existingGroup.ID { - return logical.ErrorResponse("alias is already tied to a different group"), nil - } - - group = existingGroup - group.Alias = groupAlias - } - - group.Alias.Name = groupAliasName - group.Alias.MountAccessor = mountValidationResp.MountAccessor - // Explicitly correct for previous versions that persisted this - group.Alias.MountType = "" - - err = i.sanitizeAndUpsertGroup(group, nil) - if err != nil { - return nil, err - } - - resp.Data = map[string]interface{}{ - "id": groupAlias.ID, - "canonical_id": group.ID, - } - - return resp, nil -} - -// pathGroupAliasIDRead returns the properties of an alias for a given -// alias ID -func (i *IdentityStore) pathGroupAliasIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("empty group alias id"), nil - } - - groupAlias, err := i.MemDBAliasByID(groupAliasID, false, true) - if err != nil { - return nil, err - } - - return i.handleAliasReadCommon(groupAlias) - } -} - -// pathGroupAliasIDDelete deletes the group's alias for a given group alias ID -func (i *IdentityStore) pathGroupAliasIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupAliasID := d.Get("id").(string) - if groupAliasID == "" { - return logical.ErrorResponse("missing group alias ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - txn := i.db.Txn(true) - defer txn.Abort() - - alias, err := i.MemDBAliasByIDInTxn(txn, groupAliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - group, err := i.MemDBGroupByAliasIDInTxn(txn, alias.ID, true) - if err != nil { - return nil, err - } - - // If there is no group tied to a valid alias, something is wrong - if group == nil { - return nil, fmt.Errorf("alias not associated to a group") - } - - // Delete group alias in memdb - err = i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true) - if err != nil { - return nil, err - } - - // Delete the alias - group.Alias = nil - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - - txn.Commit() - - return nil, nil - } -} - -// pathGroupAliasIDList lists the IDs of all the valid group aliases in the -// identity store -func (i *IdentityStore) pathGroupAliasIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ws := memdb.NewWatchSet() - iter, err := i.MemDBAliases(ws, true) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for group aliases in memdb: {{err}}", err) - } - - var groupAliasIDs []string - aliasInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - alias := raw.(*identity.Alias) - groupAliasIDs = append(groupAliasIDs, alias.ID) - entry := map[string]interface{}{ - "name": alias.Name, - "canonical_id": alias.CanonicalID, - "mount_accessor": alias.MountAccessor, - } - - mi, ok := mountAccessorMap[alias.MountAccessor] - if ok { - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } - mountAccessorMap[alias.MountAccessor] = mi - } - - aliasInfo[alias.ID] = entry - } - - return logical.ListResponseWithInfo(groupAliasIDs, aliasInfo), nil - } -} - -var groupAliasHelp = map[string][2]string{ - "group-alias": { - "Creates a new group alias, or updates an existing one.", - "", - }, - "group-alias-id": { - "Update, read or delete a group alias using ID.", - "", - }, - "group-alias-id-list": { - "List all the group alias IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go b/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go deleted file mode 100644 index f61c1fd49..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_groups.go +++ /dev/null @@ -1,463 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - groupTypeInternal = "internal" - groupTypeExternal = "external" -) - -func groupPaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "group$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group. If set, updates the corresponding existing group.", - }, - "type": { - Type: framework.TypeString, - Description: "Type of the group, 'internal' or 'external'. Defaults to 'internal'", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the group.", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the group. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the group.", - }, - "member_group_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Group IDs to be assigned as group members.", - }, - "member_entity_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Entity IDs to be assigned as group members.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupRegister(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["register"][0]), - HelpDescription: strings.TrimSpace(groupHelp["register"][1]), - }, - { - Pattern: "group/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the group.", - }, - "type": { - Type: framework.TypeString, - Default: groupTypeInternal, - Description: "Type of the group, 'internal' or 'external'. Defaults to 'internal'", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the group.", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the group. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 - `, - }, - "policies": { - Type: framework.TypeCommaStringSlice, - Description: "Policies to be tied to the group.", - }, - "member_group_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Group IDs to be assigned as group members.", - }, - "member_entity_ids": { - Type: framework.TypeCommaStringSlice, - Description: "Entity IDs to be assigned as group members.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.pathGroupIDUpdate(), - logical.ReadOperation: i.pathGroupIDRead(), - logical.DeleteOperation: i.pathGroupIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-by-id"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-by-id"][1]), - }, - { - Pattern: "group/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathGroupIDList(), - }, - - HelpSynopsis: strings.TrimSpace(groupHelp["group-id-list"][0]), - HelpDescription: strings.TrimSpace(groupHelp["group-id-list"][1]), - }, - } -} - -func (i *IdentityStore) pathGroupRegister() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - _, ok := d.GetOk("id") - if ok { - return i.pathGroupIDUpdate()(ctx, req, d) - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - return i.handleGroupUpdateCommon(req, d, nil) - } -} - -func (i *IdentityStore) pathGroupIDUpdate() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group ID"), nil - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - group, err := i.MemDBGroupByID(groupID, true) - if err != nil { - return nil, err - } - if group == nil { - return logical.ErrorResponse("invalid group ID"), nil - } - - return i.handleGroupUpdateCommon(req, d, group) - } -} - -func (i *IdentityStore) handleGroupUpdateCommon(req *logical.Request, d *framework.FieldData, group *identity.Group) (*logical.Response, error) { - var err error - var newGroup bool - if group == nil { - group = &identity.Group{} - newGroup = true - } - - // Update the policies if supplied - policiesRaw, ok := d.GetOk("policies") - if ok { - group.Policies = policiesRaw.([]string) - } - - if strutil.StrListContains(group.Policies, "root") { - return logical.ErrorResponse("policies cannot contain root"), nil - } - - groupTypeRaw, ok := d.GetOk("type") - if ok { - groupType := groupTypeRaw.(string) - if group.Type != "" && groupType != group.Type { - return logical.ErrorResponse(fmt.Sprintf("group type cannot be changed")), nil - } - - group.Type = groupType - } - - // If group type is not set, default to internal type - if group.Type == "" { - group.Type = groupTypeInternal - } - - if group.Type != groupTypeInternal && group.Type != groupTypeExternal { - return logical.ErrorResponse(fmt.Sprintf("invalid group type %q", group.Type)), nil - } - - // Get the name - groupName := d.Get("name").(string) - if groupName != "" { - // Check if there is a group already existing for the given name - groupByName, err := i.MemDBGroupByName(groupName, false) - if err != nil { - return nil, err - } - - // If this is a new group and if there already exists a group by this - // name, error out. If the name of an existing group is about to be - // modified into something which is already tied to a different group, - // error out. - switch { - case (newGroup && groupByName != nil), (groupByName != nil && group.ID != "" && groupByName.ID != group.ID): - return logical.ErrorResponse("group name is already in use"), nil - } - group.Name = groupName - } - - metadata, ok, err := d.GetOkErr("metadata") - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil - } - if ok { - group.Metadata = metadata.(map[string]string) - } - - memberEntityIDsRaw, ok := d.GetOk("member_entity_ids") - if ok { - if group.Type == groupTypeExternal { - return logical.ErrorResponse("member entities can't be set manually for external groups"), nil - } - group.MemberEntityIDs = memberEntityIDsRaw.([]string) - if len(group.MemberEntityIDs) > 512 { - return logical.ErrorResponse("member entity IDs exceeding the limit of 512"), nil - } - } - - memberGroupIDsRaw, ok := d.GetOk("member_group_ids") - var memberGroupIDs []string - if ok { - if group.Type == groupTypeExternal { - return logical.ErrorResponse("member groups can't be set for external groups"), nil - } - memberGroupIDs = memberGroupIDsRaw.([]string) - } - - err = i.sanitizeAndUpsertGroup(group, memberGroupIDs) - if err != nil { - return nil, err - } - - respData := map[string]interface{}{ - "id": group.ID, - "name": group.Name, - } - return &logical.Response{ - Data: respData, - }, nil -} - -func (i *IdentityStore) pathGroupIDRead() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group id"), nil - } - - group, err := i.MemDBGroupByID(groupID, false) - if err != nil { - return nil, err - } - - return i.handleGroupReadCommon(group) - } -} - -func (i *IdentityStore) handleGroupReadCommon(group *identity.Group) (*logical.Response, error) { - if group == nil { - return nil, nil - } - - respData := map[string]interface{}{} - respData["id"] = group.ID - respData["name"] = group.Name - respData["policies"] = group.Policies - respData["member_entity_ids"] = group.MemberEntityIDs - respData["parent_group_ids"] = group.ParentGroupIDs - respData["metadata"] = group.Metadata - respData["creation_time"] = ptypes.TimestampString(group.CreationTime) - respData["last_update_time"] = ptypes.TimestampString(group.LastUpdateTime) - respData["modify_index"] = group.ModifyIndex - respData["type"] = group.Type - - aliasMap := map[string]interface{}{} - if group.Alias != nil { - aliasMap["id"] = group.Alias.ID - aliasMap["canonical_id"] = group.Alias.CanonicalID - aliasMap["mount_accessor"] = group.Alias.MountAccessor - aliasMap["metadata"] = group.Alias.Metadata - aliasMap["name"] = group.Alias.Name - aliasMap["merged_from_canonical_ids"] = group.Alias.MergedFromCanonicalIDs - aliasMap["creation_time"] = ptypes.TimestampString(group.Alias.CreationTime) - aliasMap["last_update_time"] = ptypes.TimestampString(group.Alias.LastUpdateTime) - - if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil { - aliasMap["mount_path"] = mountValidationResp.MountPath - aliasMap["mount_type"] = mountValidationResp.MountType - } - } - - respData["alias"] = aliasMap - - var memberGroupIDs []string - memberGroups, err := i.MemDBGroupsByParentGroupID(group.ID, false) - if err != nil { - return nil, err - } - for _, memberGroup := range memberGroups { - memberGroupIDs = append(memberGroupIDs, memberGroup.ID) - } - - respData["member_group_ids"] = memberGroupIDs - - return &logical.Response{ - Data: respData, - }, nil -} - -func (i *IdentityStore) pathGroupIDDelete() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - groupID := d.Get("id").(string) - if groupID == "" { - return logical.ErrorResponse("empty group ID"), nil - } - - if groupID == "" { - return nil, fmt.Errorf("missing group ID") - } - - // Acquire the lock to modify the group storage entry - i.groupLock.Lock() - defer i.groupLock.Unlock() - - // Create a MemDB transaction to delete group - txn := i.db.Txn(true) - defer txn.Abort() - - group, err := i.MemDBGroupByIDInTxn(txn, groupID, false) - if err != nil { - return nil, err - } - - // If there is no group for the ID, do nothing - if group == nil { - return nil, nil - } - - // Delete group alias from memdb - if group.Type == groupTypeExternal && group.Alias != nil { - err = i.MemDBDeleteAliasByIDInTxn(txn, group.Alias.ID, true) - if err != nil { - return nil, err - } - } - - // Delete the group using the same transaction - err = i.MemDBDeleteGroupByIDInTxn(txn, group.ID) - if err != nil { - return nil, err - } - - // Delete the group from storage - err = i.groupPacker.DeleteItem(group.ID) - if err != nil { - return nil, err - } - - // Committing the transaction *after* successfully deleting group - txn.Commit() - - return nil, nil - } -} - -// pathGroupIDList lists the IDs of all the groups in the identity store -func (i *IdentityStore) pathGroupIDList() framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - ws := memdb.NewWatchSet() - - txn := i.db.Txn(false) - - iter, err := txn.Get(groupsTable, "id") - if err != nil { - return nil, errwrap.Wrapf("failed to fetch iterator for group in memdb: {{err}}", err) - } - - ws.Add(iter.WatchCh()) - - var groupIDs []string - groupInfo := map[string]interface{}{} - - type mountInfo struct { - MountType string - MountPath string - } - mountAccessorMap := map[string]mountInfo{} - - for { - raw := iter.Next() - if raw == nil { - break - } - group := raw.(*identity.Group) - groupIDs = append(groupIDs, group.ID) - groupInfoEntry := map[string]interface{}{ - "name": group.Name, - "num_member_entities": len(group.MemberEntityIDs), - "num_parent_groups": len(group.ParentGroupIDs), - } - if group.Alias != nil { - entry := map[string]interface{}{ - "id": group.Alias.ID, - "name": group.Alias.Name, - "mount_accessor": group.Alias.MountAccessor, - } - - mi, ok := mountAccessorMap[group.Alias.MountAccessor] - if ok { - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } else { - mi = mountInfo{} - if mountValidationResp := i.core.router.validateMountByAccessor(group.Alias.MountAccessor); mountValidationResp != nil { - mi.MountType = mountValidationResp.MountType - mi.MountPath = mountValidationResp.MountPath - entry["mount_type"] = mi.MountType - entry["mount_path"] = mi.MountPath - } - mountAccessorMap[group.Alias.MountAccessor] = mi - } - - groupInfoEntry["alias"] = entry - } - groupInfo[group.ID] = groupInfoEntry - } - - return logical.ListResponseWithInfo(groupIDs, groupInfo), nil - } -} - -var groupHelp = map[string][2]string{ - "register": { - "Create a new group.", - "", - }, - "group-by-id": { - "Update or delete an existing group using its ID.", - "", - }, - "group-id-list": { - "List all the group IDs.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go b/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go deleted file mode 100644 index 23c0239ec..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_schema.go +++ /dev/null @@ -1,179 +0,0 @@ -package vault - -import ( - "fmt" - - memdb "github.com/hashicorp/go-memdb" -) - -const ( - entitiesTable = "entities" - entityAliasesTable = "entity_aliases" - groupsTable = "groups" - groupAliasesTable = "group_aliases" -) - -func identityStoreSchema() *memdb.DBSchema { - iStoreSchema := &memdb.DBSchema{ - Tables: make(map[string]*memdb.TableSchema), - } - - schemas := []func() *memdb.TableSchema{ - entitiesTableSchema, - aliasesTableSchema, - groupsTableSchema, - groupAliasesTableSchema, - } - - for _, schemaFunc := range schemas { - schema := schemaFunc() - if _, ok := iStoreSchema.Tables[schema.Name]; ok { - panic(fmt.Sprintf("duplicate table name: %s", schema.Name)) - } - iStoreSchema.Tables[schema.Name] = schema - } - - return iStoreSchema -} - -func aliasesTableSchema() *memdb.TableSchema { - return &memdb.TableSchema{ - Name: entityAliasesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "factors": &memdb.IndexSchema{ - Name: "factors", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "MountAccessor", - }, - &memdb.StringFieldIndex{ - Field: "Name", - }, - }, - }, - }, - }, - } -} - -func entitiesTableSchema() *memdb.TableSchema { - return &memdb.TableSchema{ - Name: entitiesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "name": &memdb.IndexSchema{ - Name: "name", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "Name", - }, - }, - "merged_entity_ids": &memdb.IndexSchema{ - Name: "merged_entity_ids", - Unique: true, - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "MergedEntityIDs", - }, - }, - "bucket_key_hash": &memdb.IndexSchema{ - Name: "bucket_key_hash", - Unique: false, - AllowMissing: false, - Indexer: &memdb.StringFieldIndex{ - Field: "BucketKeyHash", - }, - }, - }, - } -} - -func groupsTableSchema() *memdb.TableSchema { - return &memdb.TableSchema{ - Name: groupsTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": { - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "name": { - Name: "name", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "Name", - }, - }, - "member_entity_ids": { - Name: "member_entity_ids", - Unique: false, - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "MemberEntityIDs", - }, - }, - "parent_group_ids": { - Name: "parent_group_ids", - Unique: false, - AllowMissing: true, - Indexer: &memdb.StringSliceFieldIndex{ - Field: "ParentGroupIDs", - }, - }, - "bucket_key_hash": &memdb.IndexSchema{ - Name: "bucket_key_hash", - Unique: false, - AllowMissing: false, - Indexer: &memdb.StringFieldIndex{ - Field: "BucketKeyHash", - }, - }, - }, - } -} - -func groupAliasesTableSchema() *memdb.TableSchema { - return &memdb.TableSchema{ - Name: groupAliasesTable, - Indexes: map[string]*memdb.IndexSchema{ - "id": &memdb.IndexSchema{ - Name: "id", - Unique: true, - Indexer: &memdb.StringFieldIndex{ - Field: "ID", - }, - }, - "factors": &memdb.IndexSchema{ - Name: "factors", - Unique: true, - Indexer: &memdb.CompoundIndex{ - Indexes: []memdb.Indexer{ - &memdb.StringFieldIndex{ - Field: "MountAccessor", - }, - &memdb.StringFieldIndex{ - Field: "Name", - }, - }, - }, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go b/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go deleted file mode 100644 index c9ddb245b..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_structs.go +++ /dev/null @@ -1,79 +0,0 @@ -package vault - -import ( - "regexp" - "sync" - - log "github.com/hashicorp/go-hclog" - memdb "github.com/hashicorp/go-memdb" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - // Storage prefixes - entityPrefix = "entity/" -) - -var ( - // metaKeyFormatRegEx checks if a metadata key string is valid - metaKeyFormatRegEx = regexp.MustCompile(`^[a-zA-Z0-9=/+_-]+$`).MatchString -) - -const ( - // The meta key prefix reserved for Vault's internal use - metaKeyReservedPrefix = "vault-" - - // The maximum number of metadata key pairs allowed to be registered - metaMaxKeyPairs = 64 - - // The maximum allowed length of a metadata key - metaKeyMaxLength = 128 - - // The maximum allowed length of a metadata value - metaValueMaxLength = 512 -) - -// IdentityStore is composed of its own storage view and a MemDB which -// maintains active in-memory replicas of the storage contents indexed by -// multiple fields. -type IdentityStore struct { - // IdentityStore is a secret backend in Vault - *framework.Backend - - // view is the storage sub-view where all the artifacts of identity store - // gets persisted - view logical.Storage - - // db is the in-memory database where the storage artifacts gets replicated - // to enable richer queries based on multiple indexes. - db *memdb.MemDB - - // A lock to make sure things are consistent - lock sync.RWMutex - - // groupLock is used to protect modifications to group entries - groupLock sync.RWMutex - - // logger is the server logger copied over from core - logger log.Logger - - // entityPacker is used to pack multiple entity storage entries into 256 - // buckets - entityPacker *storagepacker.StoragePacker - - // groupPacker is used to pack multiple group storage entries into 256 - // buckets - groupPacker *storagepacker.StoragePacker - - // core is the pointer to Vault's core - core *Core -} - -type groupDiff struct { - New []*identity.Group - Deleted []*identity.Group - Unmodified []*identity.Group -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go b/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go deleted file mode 100644 index ebf3e5582..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_upgrade.go +++ /dev/null @@ -1,168 +0,0 @@ -package vault - -import ( - "strings" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -func upgradePaths(i *IdentityStore) []*framework.Path { - return []*framework.Path{ - { - Pattern: "persona$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the persona", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this persona belongs to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this persona belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the persona", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the persona. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 -`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - { - Pattern: "persona/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the persona", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this persona should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this persona belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the persona", - }, - "metadata": { - Type: framework.TypeKVPairs, - Description: `Metadata to be associated with the persona. -In CLI, this parameter can be repeated multiple times, and it all gets merged together. -For example: -vault metadata=key1=value1 metadata=key2=value2 -`, - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleEntityUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "persona/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - { - Pattern: "alias$", - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs to. This field is deprecated in favor of 'canonical_id'.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias belongs to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias"][1]), - }, - - { - Pattern: "alias/id/" + framework.GenericNameRegex("id"), - Fields: map[string]*framework.FieldSchema{ - "id": { - Type: framework.TypeString, - Description: "ID of the alias", - }, - "entity_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to. This field is deprecated in favor of 'canonical_id'.", - }, - "canonical_id": { - Type: framework.TypeString, - Description: "Entity ID to which this alias should be tied to", - }, - "mount_accessor": { - Type: framework.TypeString, - Description: "Mount accessor to which this alias belongs to", - }, - "name": { - Type: framework.TypeString, - Description: "Name of the alias", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: i.handleAliasUpdateCommon(), - logical.ReadOperation: i.pathAliasIDRead(), - logical.DeleteOperation: i.pathAliasIDDelete(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id"][1]), - }, - { - Pattern: "alias/id/?$", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: i.pathAliasIDList(), - }, - - HelpSynopsis: strings.TrimSpace(aliasHelp["alias-id-list"][0]), - HelpDescription: strings.TrimSpace(aliasHelp["alias-id-list"][1]), - }, - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/identity_store_util.go b/vendor/github.com/hashicorp/vault/vault/identity_store_util.go deleted file mode 100644 index 668fabd5a..000000000 --- a/vendor/github.com/hashicorp/vault/vault/identity_store_util.go +++ /dev/null @@ -1,1675 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - - "github.com/golang/protobuf/ptypes" - "github.com/hashicorp/errwrap" - memdb "github.com/hashicorp/go-memdb" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/storagepacker" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -func (c *Core) loadIdentityStoreArtifacts(ctx context.Context) error { - var err error - if c.identityStore == nil { - c.logger.Warn("identity store is not setup, skipping loading") - return nil - } - - err = c.identityStore.loadEntities(ctx) - if err != nil { - return err - } - - err = c.identityStore.loadGroups(ctx) - if err != nil { - return err - } - - return nil -} - -func (i *IdentityStore) loadGroups(ctx context.Context) error { - i.logger.Debug("identity loading groups") - existing, err := i.groupPacker.View().List(ctx, groupBucketsPrefix) - if err != nil { - return errwrap.Wrapf("failed to scan for groups: {{err}}", err) - } - i.logger.Debug("groups collected", "num_existing", len(existing)) - - for _, key := range existing { - bucket, err := i.groupPacker.GetBucket(i.groupPacker.BucketPath(key)) - if err != nil { - return err - } - - if bucket == nil { - continue - } - - for _, item := range bucket.Items { - group, err := i.parseGroupFromBucketItem(item) - if err != nil { - return err - } - if group == nil { - continue - } - - if i.logger.IsDebug() { - i.logger.Debug("loading group", "name", group.Name, "id", group.ID) - } - - txn := i.db.Txn(true) - - err = i.UpsertGroupInTxn(txn, group, false) - if err != nil { - txn.Abort() - return errwrap.Wrapf("failed to update group in memdb: {{err}}", err) - } - - txn.Commit() - } - } - - if i.logger.IsInfo() { - i.logger.Info("groups restored") - } - - return nil -} - -func (i *IdentityStore) loadEntities(ctx context.Context) error { - // Accumulate existing entities - i.logger.Debug("loading entities") - existing, err := i.entityPacker.View().List(ctx, storagepacker.StoragePackerBucketsPrefix) - if err != nil { - return errwrap.Wrapf("failed to scan for entities: {{err}}", err) - } - i.logger.Debug("entities collected", "num_existing", len(existing)) - - // Make the channels used for the worker pool - broker := make(chan string) - quit := make(chan bool) - - // Buffer these channels to prevent deadlocks - errs := make(chan error, len(existing)) - result := make(chan *storagepacker.Bucket, len(existing)) - - // Use a wait group - wg := &sync.WaitGroup{} - - // Create 64 workers to distribute work to - for j := 0; j < consts.ExpirationRestoreWorkerCount; j++ { - wg.Add(1) - go func() { - defer wg.Done() - - for { - select { - case bucketKey, ok := <-broker: - // broker has been closed, we are done - if !ok { - return - } - - bucket, err := i.entityPacker.GetBucket(i.entityPacker.BucketPath(bucketKey)) - if err != nil { - errs <- err - continue - } - - // Write results out to the result channel - result <- bucket - - // quit early - case <-quit: - return - } - } - }() - } - - // Distribute the collected keys to the workers in a go routine - wg.Add(1) - go func() { - defer wg.Done() - for j, bucketKey := range existing { - if j%500 == 0 { - i.logger.Debug("entities loading", "progress", j) - } - - select { - case <-quit: - return - - default: - broker <- bucketKey - } - } - - // Close the broker, causing worker routines to exit - close(broker) - }() - - // Restore each key by pulling from the result chan - for j := 0; j < len(existing); j++ { - select { - case err := <-errs: - // Close all go routines - close(quit) - - return err - - case bucket := <-result: - // If there is no entry, nothing to restore - if bucket == nil { - continue - } - - for _, item := range bucket.Items { - entity, err := i.parseEntityFromBucketItem(ctx, item) - if err != nil { - return err - } - - if entity == nil { - continue - } - - // Only update MemDB and don't hit the storage again - err = i.upsertEntity(entity, nil, false) - if err != nil { - return errwrap.Wrapf("failed to update entity in MemDB: {{err}}", err) - } - } - } - } - - // Let all go routines finish - wg.Wait() - - if i.logger.IsInfo() { - i.logger.Info("entities restored") - } - - return nil -} - -// upsertEntityInTxn either creates or updates an existing entity. The -// operations will be updated in both MemDB and storage. If 'persist' is set to -// false, then storage will not be updated. When an alias is transferred from -// one entity to another, both the source and destination entities should get -// updated, in which case, callers should send in both entity and -// previousEntity. -func (i *IdentityStore) upsertEntityInTxn(txn *memdb.Txn, entity *identity.Entity, previousEntity *identity.Entity, persist bool) error { - var err error - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - for _, alias := range entity.Aliases { - // Verify that alias is not associated to a different one already - aliasByFactors, err := i.MemDBAliasByFactors(alias.MountAccessor, alias.Name, false, false) - if err != nil { - return err - } - - if aliasByFactors != nil && aliasByFactors.CanonicalID != entity.ID { - i.logger.Warn("alias is already tied to a different entity; these entities are being merged", "alias_id", alias.ID, "other_entity_id", aliasByFactors.CanonicalID) - respErr, intErr := i.mergeEntity(txn, entity, []string{aliasByFactors.CanonicalID}, true, false, true) - switch { - case respErr != nil: - return respErr - case intErr != nil: - return intErr - } - // The entity and aliases will be loaded into memdb and persisted - // as a result of the merge so we are done here - return nil - } - - // Insert or update alias in MemDB using the transaction created above - err = i.MemDBUpsertAliasInTxn(txn, alias, false) - if err != nil { - return err - } - } - - // If previous entity is set, update it in MemDB and persist it - if previousEntity != nil && persist { - err = i.MemDBUpsertEntityInTxn(txn, previousEntity) - if err != nil { - return err - } - - // Persist the previous entity object - marshaledPreviousEntity, err := ptypes.MarshalAny(previousEntity) - if err != nil { - return err - } - err = i.entityPacker.PutItem(&storagepacker.Item{ - ID: previousEntity.ID, - Message: marshaledPreviousEntity, - }) - if err != nil { - return err - } - } - - // Insert or update entity in MemDB using the transaction created above - err = i.MemDBUpsertEntityInTxn(txn, entity) - if err != nil { - return err - } - - if persist { - entityAsAny, err := ptypes.MarshalAny(entity) - if err != nil { - return err - } - item := &storagepacker.Item{ - ID: entity.ID, - Message: entityAsAny, - } - - // Persist the entity object - err = i.entityPacker.PutItem(item) - if err != nil { - return err - } - } - - return nil -} - -// upsertEntity either creates or updates an existing entity. The operations -// will be updated in both MemDB and storage. If 'persist' is set to false, -// then storage will not be updated. When an alias is transferred from one -// entity to another, both the source and destination entities should get -// updated, in which case, callers should send in both entity and -// previousEntity. -func (i *IdentityStore) upsertEntity(entity *identity.Entity, previousEntity *identity.Entity, persist bool) error { - - // Create a MemDB transaction to update both alias and entity - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.upsertEntityInTxn(txn, entity, previousEntity, persist) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) MemDBUpsertAliasInTxn(txn *memdb.Txn, alias *identity.Alias, groupAlias bool) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if alias == nil { - return fmt.Errorf("alias is nil") - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "id", alias.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup alias from memdb using alias ID: {{err}}", err) - } - - if aliasRaw != nil { - err = txn.Delete(tableName, aliasRaw) - if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) - } - } - - if err := txn.Insert(tableName, alias); err != nil { - return errwrap.Wrapf("failed to update alias into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBAliasByIDInTxn(txn *memdb.Txn, aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "id", aliasID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using alias ID: {{err}}", err) - } - - if aliasRaw == nil { - return nil, nil - } - - alias, ok := aliasRaw.(*identity.Alias) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched alias") - } - - if clone { - return alias.Clone() - } - - return alias, nil -} - -func (i *IdentityStore) MemDBAliasByID(aliasID string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBAliasByIDInTxn(txn, aliasID, clone, groupAlias) -} - -func (i *IdentityStore) MemDBAliasByFactors(mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) { - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - txn := i.db.Txn(false) - - return i.MemDBAliasByFactorsInTxn(txn, mountAccessor, aliasName, clone, groupAlias) -} - -func (i *IdentityStore) MemDBAliasByFactorsInTxn(txn *memdb.Txn, mountAccessor, aliasName string, clone bool, groupAlias bool) (*identity.Alias, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if aliasName == "" { - return nil, fmt.Errorf("missing alias name") - } - - if mountAccessor == "" { - return nil, fmt.Errorf("missing mount accessor") - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - aliasRaw, err := txn.First(tableName, "factors", mountAccessor, aliasName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch alias from memdb using factors: {{err}}", err) - } - - if aliasRaw == nil { - return nil, nil - } - - alias, ok := aliasRaw.(*identity.Alias) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched alias") - } - - if clone { - return alias.Clone() - } - - return alias, nil -} - -func (i *IdentityStore) MemDBDeleteAliasByIDInTxn(txn *memdb.Txn, aliasID string, groupAlias bool) error { - if aliasID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, groupAlias) - if err != nil { - return err - } - - if alias == nil { - return nil - } - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - err = txn.Delete(tableName, alias) - if err != nil { - return errwrap.Wrapf("failed to delete alias from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBAliases(ws memdb.WatchSet, groupAlias bool) (memdb.ResultIterator, error) { - txn := i.db.Txn(false) - - tableName := entityAliasesTable - if groupAlias { - tableName = groupAliasesTable - } - - iter, err := txn.Get(tableName, "id") - if err != nil { - return nil, err - } - - ws.Add(iter.WatchCh()) - - return iter, nil -} - -func (i *IdentityStore) MemDBUpsertEntityInTxn(txn *memdb.Txn, entity *identity.Entity) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - entityRaw, err := txn.First(entitiesTable, "id", entity.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup entity from memdb using entity id: {{err}}", err) - } - - if entityRaw != nil { - err = txn.Delete(entitiesTable, entityRaw) - if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) - } - } - - if err := txn.Insert(entitiesTable, entity); err != nil { - return errwrap.Wrapf("failed to update entity into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBEntityByIDInTxn(txn *memdb.Txn, entityID string, clone bool) (*identity.Entity, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity id") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - entityRaw, err := txn.First(entitiesTable, "id", entityID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity id: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntityByID(entityID string, clone bool) (*identity.Entity, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity id") - } - - txn := i.db.Txn(false) - - return i.MemDBEntityByIDInTxn(txn, entityID, clone) -} - -func (i *IdentityStore) MemDBEntityByName(entityName string, clone bool) (*identity.Entity, error) { - if entityName == "" { - return nil, fmt.Errorf("missing entity name") - } - - txn := i.db.Txn(false) - - entityRaw, err := txn.First(entitiesTable, "name", entityName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using entity name: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntitiesByBucketEntryKeyHashInTxn(txn *memdb.Txn, hashValue string) ([]*identity.Entity, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if hashValue == "" { - return nil, fmt.Errorf("empty hash value") - } - - entitiesIter, err := txn.Get(entitiesTable, "bucket_key_hash", hashValue) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup entities using bucket entry key hash: {{err}}", err) - } - - var entities []*identity.Entity - for entity := entitiesIter.Next(); entity != nil; entity = entitiesIter.Next() { - entities = append(entities, entity.(*identity.Entity)) - } - - return entities, nil -} - -func (i *IdentityStore) MemDBEntityByMergedEntityID(mergedEntityID string, clone bool) (*identity.Entity, error) { - if mergedEntityID == "" { - return nil, fmt.Errorf("missing merged entity id") - } - - txn := i.db.Txn(false) - - entityRaw, err := txn.First(entitiesTable, "merged_entity_ids", mergedEntityID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch entity from memdb using merged entity id: {{err}}", err) - } - - if entityRaw == nil { - return nil, nil - } - - entity, ok := entityRaw.(*identity.Entity) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched entity") - } - - if clone { - return entity.Clone() - } - - return entity, nil -} - -func (i *IdentityStore) MemDBEntityByAliasIDInTxn(txn *memdb.Txn, aliasID string, clone bool) (*identity.Entity, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, false) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBEntityByIDInTxn(txn, alias.CanonicalID, clone) -} - -func (i *IdentityStore) MemDBEntityByAliasID(aliasID string, clone bool) (*identity.Entity, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBEntityByAliasIDInTxn(txn, aliasID, clone) -} - -func (i *IdentityStore) MemDBDeleteEntityByID(entityID string) error { - if entityID == "" { - return nil - } - - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.MemDBDeleteEntityByIDInTxn(txn, entityID) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) MemDBDeleteEntityByIDInTxn(txn *memdb.Txn, entityID string) error { - if entityID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - entity, err := i.MemDBEntityByIDInTxn(txn, entityID, false) - if err != nil { - return err - } - - if entity == nil { - return nil - } - - err = txn.Delete(entitiesTable, entity) - if err != nil { - return errwrap.Wrapf("failed to delete entity from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) sanitizeAlias(alias *identity.Alias) error { - var err error - - if alias == nil { - return fmt.Errorf("alias is nil") - } - - // Alias must always be tied to a canonical object - if alias.CanonicalID == "" { - return fmt.Errorf("missing canonical ID") - } - - // Alias must have a name - if alias.Name == "" { - return fmt.Errorf("missing alias name %q", alias.Name) - } - - // Alias metadata should always be map[string]string - err = validateMetadata(alias.Metadata) - if err != nil { - return errwrap.Wrapf("invalid alias metadata: {{err}}", err) - } - - // Create an ID if there isn't one already - if alias.ID == "" { - alias.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate alias ID") - } - } - - // Set the creation and last update times - if alias.CreationTime == nil { - alias.CreationTime = ptypes.TimestampNow() - alias.LastUpdateTime = alias.CreationTime - } else { - alias.LastUpdateTime = ptypes.TimestampNow() - } - - return nil -} - -func (i *IdentityStore) sanitizeEntity(entity *identity.Entity) error { - var err error - - if entity == nil { - return fmt.Errorf("entity is nil") - } - - // Create an ID if there isn't one already - if entity.ID == "" { - entity.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate entity id") - } - - // Set the hash value of the storage bucket key in entity - entity.BucketKeyHash = i.entityPacker.BucketKeyHashByItemID(entity.ID) - } - - // Create a name if there isn't one already - if entity.Name == "" { - entity.Name, err = i.generateName("entity") - if err != nil { - return fmt.Errorf("failed to generate entity name") - } - } - - // Entity metadata should always be map[string]string - err = validateMetadata(entity.Metadata) - if err != nil { - return errwrap.Wrapf("invalid entity metadata: {{err}}", err) - } - - // Set the creation and last update times - if entity.CreationTime == nil { - entity.CreationTime = ptypes.TimestampNow() - entity.LastUpdateTime = entity.CreationTime - } else { - entity.LastUpdateTime = ptypes.TimestampNow() - } - - return nil -} - -func (i *IdentityStore) sanitizeAndUpsertGroup(group *identity.Group, memberGroupIDs []string) error { - var err error - - if group == nil { - return fmt.Errorf("group is nil") - } - - // Create an ID if there isn't one already - if group.ID == "" { - group.ID, err = uuid.GenerateUUID() - if err != nil { - return fmt.Errorf("failed to generate group id") - } - - // Set the hash value of the storage bucket key in group - group.BucketKeyHash = i.groupPacker.BucketKeyHashByItemID(group.ID) - } - - // Create a name if there isn't one already - if group.Name == "" { - group.Name, err = i.generateName("group") - if err != nil { - return fmt.Errorf("failed to generate group name") - } - } - - // Entity metadata should always be map[string]string - err = validateMetadata(group.Metadata) - if err != nil { - return errwrap.Wrapf("invalid group metadata: {{err}}", err) - } - - // Set the creation and last update times - if group.CreationTime == nil { - group.CreationTime = ptypes.TimestampNow() - group.LastUpdateTime = group.CreationTime - } else { - group.LastUpdateTime = ptypes.TimestampNow() - } - - // Remove duplicate entity IDs and check if all IDs are valid - group.MemberEntityIDs = strutil.RemoveDuplicates(group.MemberEntityIDs, false) - for _, entityID := range group.MemberEntityIDs { - entity, err := i.MemDBEntityByID(entityID, false) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to validate entity ID %q: {{err}}", entityID), err) - } - if entity == nil { - return fmt.Errorf("invalid entity ID %q", entityID) - } - } - - txn := i.db.Txn(true) - defer txn.Abort() - - memberGroupIDs = strutil.RemoveDuplicates(memberGroupIDs, false) - // After the group lock is held, make membership updates to all the - // relevant groups - for _, memberGroupID := range memberGroupIDs { - memberGroup, err := i.MemDBGroupByID(memberGroupID, true) - if err != nil { - return err - } - if memberGroup == nil { - return fmt.Errorf("invalid member group ID %q", memberGroupID) - } - - // Skip if memberGroupID is already a member of group.ID - if strutil.StrListContains(memberGroup.ParentGroupIDs, group.ID) { - continue - } - - // Ensure that adding memberGroupID does not lead to cyclic - // relationships - // Detect self loop - if group.ID == memberGroupID { - return fmt.Errorf("member group ID %q is same as the ID of the group", group.ID) - } - - groupByID, err := i.MemDBGroupByID(group.ID, true) - if err != nil { - return err - } - - // If group is nil, that means that a group doesn't already exist and its - // okay to add any group as its member group. - if groupByID != nil { - // If adding the memberGroupID to groupID creates a cycle, then groupID must - // be a hop in that loop. Start a DFS traversal from memberGroupID and see if - // it reaches back to groupID. If it does, then it's a loop. - - // Created a visited set - visited := make(map[string]bool) - cycleDetected, err := i.detectCycleDFS(visited, groupByID.ID, memberGroupID) - if err != nil { - return fmt.Errorf("failed to perform cyclic relationship detection for member group ID %q", memberGroupID) - } - if cycleDetected { - return fmt.Errorf("cyclic relationship detected for member group ID %q", memberGroupID) - } - } - - memberGroup.ParentGroupIDs = append(memberGroup.ParentGroupIDs, group.ID) - - // This technically is not upsert. It is only update, only the method - // name is upsert here. - err = i.UpsertGroupInTxn(txn, memberGroup, true) - if err != nil { - // Ideally we would want to revert the whole operation in case of - // errors while persisting in member groups. But there is no - // storage transaction support yet. When we do have it, this will need - // an update. - return err - } - } - - // Sanitize the group alias - if group.Alias != nil { - group.Alias.CanonicalID = group.ID - err = i.sanitizeAlias(group.Alias) - if err != nil { - return err - } - } - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) deleteAliasesInEntityInTxn(txn *memdb.Txn, entity *identity.Entity, aliases []*identity.Alias) error { - if entity == nil { - return fmt.Errorf("entity is nil") - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - var remainList []*identity.Alias - var removeList []*identity.Alias - - for _, item := range aliases { - for _, alias := range entity.Aliases { - if alias.ID == item.ID { - removeList = append(removeList, alias) - } else { - remainList = append(remainList, alias) - } - } - } - - // Remove identity indices from aliases table for those that needs to - // be removed - for _, alias := range removeList { - aliasToBeRemoved, err := i.MemDBAliasByIDInTxn(txn, alias.ID, false, false) - if err != nil { - return err - } - if aliasToBeRemoved == nil { - return fmt.Errorf("alias was not indexed") - } - err = i.MemDBDeleteAliasByIDInTxn(txn, aliasToBeRemoved.ID, false) - if err != nil { - return err - } - } - - // Update the entity with remaining items - entity.Aliases = remainList - - return nil -} - -// validateMeta validates a set of key/value pairs from the agent config -func validateMetadata(meta map[string]string) error { - if len(meta) > metaMaxKeyPairs { - return fmt.Errorf("metadata cannot contain more than %d key/value pairs", metaMaxKeyPairs) - } - - for key, value := range meta { - if err := validateMetaPair(key, value); err != nil { - return errwrap.Wrapf(fmt.Sprintf("failed to load metadata pair (%q, %q): {{err}}", key, value), err) - } - } - - return nil -} - -// validateMetaPair checks that the given key/value pair is in a valid format -func validateMetaPair(key, value string) error { - if key == "" { - return fmt.Errorf("key cannot be blank") - } - if !metaKeyFormatRegEx(key) { - return fmt.Errorf("key contains invalid characters") - } - if len(key) > metaKeyMaxLength { - return fmt.Errorf("key is too long (limit: %d characters)", metaKeyMaxLength) - } - if strings.HasPrefix(key, metaKeyReservedPrefix) { - return fmt.Errorf("key prefix %q is reserved for internal use", metaKeyReservedPrefix) - } - if len(value) > metaValueMaxLength { - return fmt.Errorf("value is too long (limit: %d characters)", metaValueMaxLength) - } - return nil -} - -func (i *IdentityStore) MemDBGroupByNameInTxn(txn *memdb.Txn, groupName string, clone bool) (*identity.Group, error) { - if groupName == "" { - return nil, fmt.Errorf("missing group name") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - groupRaw, err := txn.First(groupsTable, "name", groupName) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group name: {{err}}", err) - } - - if groupRaw == nil { - return nil, nil - } - - group, ok := groupRaw.(*identity.Group) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched group") - } - - if clone { - return group.Clone() - } - - return group, nil -} - -func (i *IdentityStore) MemDBGroupByName(groupName string, clone bool) (*identity.Group, error) { - if groupName == "" { - return nil, fmt.Errorf("missing group name") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByNameInTxn(txn, groupName, clone) -} - -func (i *IdentityStore) UpsertGroup(group *identity.Group, persist bool) error { - txn := i.db.Txn(true) - defer txn.Abort() - - err := i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return err - } - - txn.Commit() - - return nil -} - -func (i *IdentityStore) UpsertGroupInTxn(txn *memdb.Txn, group *identity.Group, persist bool) error { - var err error - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - if group == nil { - return fmt.Errorf("group is nil") - } - - // Increment the modify index of the group - group.ModifyIndex++ - - if group.Alias != nil { - err = i.MemDBUpsertAliasInTxn(txn, group.Alias, true) - if err != nil { - return err - } - } - // Insert or update group in MemDB using the transaction created above - err = i.MemDBUpsertGroupInTxn(txn, group) - if err != nil { - return err - } - - if persist { - groupAsAny, err := ptypes.MarshalAny(group) - if err != nil { - return err - } - - item := &storagepacker.Item{ - ID: group.ID, - Message: groupAsAny, - } - - err = i.groupPacker.PutItem(item) - if err != nil { - return err - } - } - - return nil -} - -func (i *IdentityStore) MemDBUpsertGroupInTxn(txn *memdb.Txn, group *identity.Group) error { - if txn == nil { - return fmt.Errorf("nil txn") - } - - if group == nil { - return fmt.Errorf("group is nil") - } - - groupRaw, err := txn.First(groupsTable, "id", group.ID) - if err != nil { - return errwrap.Wrapf("failed to lookup group from memdb using group id: {{err}}", err) - } - - if groupRaw != nil { - err = txn.Delete(groupsTable, groupRaw) - if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) - } - } - - if err := txn.Insert(groupsTable, group); err != nil { - return errwrap.Wrapf("failed to update group into memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBDeleteGroupByIDInTxn(txn *memdb.Txn, groupID string) error { - if groupID == "" { - return nil - } - - if txn == nil { - return fmt.Errorf("txn is nil") - } - - group, err := i.MemDBGroupByIDInTxn(txn, groupID, false) - if err != nil { - return err - } - - if group == nil { - return nil - } - - err = txn.Delete("groups", group) - if err != nil { - return errwrap.Wrapf("failed to delete group from memdb: {{err}}", err) - } - - return nil -} - -func (i *IdentityStore) MemDBGroupByIDInTxn(txn *memdb.Txn, groupID string, clone bool) (*identity.Group, error) { - if groupID == "" { - return nil, fmt.Errorf("missing group ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - groupRaw, err := txn.First(groupsTable, "id", groupID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group from memdb using group ID: {{err}}", err) - } - - if groupRaw == nil { - return nil, nil - } - - group, ok := groupRaw.(*identity.Group) - if !ok { - return nil, fmt.Errorf("failed to declare the type of fetched group") - } - - if clone { - return group.Clone() - } - - return group, nil -} - -func (i *IdentityStore) MemDBGroupByID(groupID string, clone bool) (*identity.Group, error) { - if groupID == "" { - return nil, fmt.Errorf("missing group ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByIDInTxn(txn, groupID, clone) -} - -func (i *IdentityStore) MemDBGroupsByParentGroupIDInTxn(txn *memdb.Txn, memberGroupID string, clone bool) ([]*identity.Group, error) { - if memberGroupID == "" { - return nil, fmt.Errorf("missing member group ID") - } - - groupsIter, err := txn.Get(groupsTable, "parent_group_ids", memberGroupID) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using member group ID: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - entry := group.(*identity.Group) - if clone { - entry, err = entry.Clone() - if err != nil { - return nil, err - } - } - groups = append(groups, entry) - } - - return groups, nil -} - -func (i *IdentityStore) MemDBGroupsByParentGroupID(memberGroupID string, clone bool) ([]*identity.Group, error) { - if memberGroupID == "" { - return nil, fmt.Errorf("missing member group ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupsByParentGroupIDInTxn(txn, memberGroupID, clone) -} - -func (i *IdentityStore) MemDBGroupsByMemberEntityID(entityID string, clone bool, externalOnly bool) ([]*identity.Group, error) { - txn := i.db.Txn(false) - defer txn.Abort() - - return i.MemDBGroupsByMemberEntityIDInTxn(txn, entityID, clone, externalOnly) -} - -func (i *IdentityStore) MemDBGroupsByMemberEntityIDInTxn(txn *memdb.Txn, entityID string, clone bool, externalOnly bool) ([]*identity.Group, error) { - if entityID == "" { - return nil, fmt.Errorf("missing entity ID") - } - - groupsIter, err := txn.Get(groupsTable, "member_entity_ids", entityID) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using entity ID: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - entry := group.(*identity.Group) - if externalOnly && entry.Type == groupTypeInternal { - continue - } - if clone { - entry, err = entry.Clone() - if err != nil { - return nil, err - } - } - groups = append(groups, entry) - } - - return groups, nil -} - -func (i *IdentityStore) groupPoliciesByEntityID(entityID string) ([]string, error) { - if entityID == "" { - return nil, fmt.Errorf("empty entity ID") - } - - groups, err := i.MemDBGroupsByMemberEntityID(entityID, false, false) - if err != nil { - return nil, err - } - - visited := make(map[string]bool) - var policies []string - for _, group := range groups { - groupPolicies, err := i.collectPoliciesReverseDFS(group, visited, nil) - if err != nil { - return nil, err - } - policies = append(policies, groupPolicies...) - } - - return strutil.RemoveDuplicates(policies, false), nil -} - -func (i *IdentityStore) groupsByEntityID(entityID string) ([]*identity.Group, []*identity.Group, error) { - if entityID == "" { - return nil, nil, fmt.Errorf("empty entity ID") - } - - groups, err := i.MemDBGroupsByMemberEntityID(entityID, true, false) - if err != nil { - return nil, nil, err - } - - visited := make(map[string]bool) - var tGroups []*identity.Group - for _, group := range groups { - gGroups, err := i.collectGroupsReverseDFS(group, visited, nil) - if err != nil { - return nil, nil, err - } - tGroups = append(tGroups, gGroups...) - } - - // Remove duplicates - groupMap := make(map[string]*identity.Group) - for _, group := range tGroups { - groupMap[group.ID] = group - } - - tGroups = make([]*identity.Group, 0, len(groupMap)) - for _, group := range groupMap { - tGroups = append(tGroups, group) - } - - diff := diffGroups(groups, tGroups) - - // For sanity - // There should not be any group that gets deleted - if len(diff.Deleted) != 0 { - return nil, nil, fmt.Errorf("failed to diff group memberships") - } - - return diff.Unmodified, diff.New, nil -} - -func (i *IdentityStore) collectGroupsReverseDFS(group *identity.Group, visited map[string]bool, groups []*identity.Group) ([]*identity.Group, error) { - if group == nil { - return nil, fmt.Errorf("nil group") - } - - // If traversal for a groupID is performed before, skip it - if visited[group.ID] { - return groups, nil - } - visited[group.ID] = true - - groups = append(groups, group) - - // Traverse all the parent groups - for _, parentGroupID := range group.ParentGroupIDs { - parentGroup, err := i.MemDBGroupByID(parentGroupID, false) - if err != nil { - return nil, err - } - if parentGroup == nil { - continue - } - pGroups, err := i.collectGroupsReverseDFS(parentGroup, visited, groups) - if err != nil { - return nil, fmt.Errorf("failed to collect group at parent group ID %q", parentGroup.ID) - } - groups = append(groups, pGroups...) - } - - return groups, nil -} - -func (i *IdentityStore) collectPoliciesReverseDFS(group *identity.Group, visited map[string]bool, policies []string) ([]string, error) { - if group == nil { - return nil, fmt.Errorf("nil group") - } - - // If traversal for a groupID is performed before, skip it - if visited[group.ID] { - return policies, nil - } - visited[group.ID] = true - - policies = append(policies, group.Policies...) - - // Traverse all the parent groups - for _, parentGroupID := range group.ParentGroupIDs { - parentGroup, err := i.MemDBGroupByID(parentGroupID, false) - if err != nil { - return nil, err - } - if parentGroup == nil { - continue - } - parentPolicies, err := i.collectPoliciesReverseDFS(parentGroup, visited, policies) - if err != nil { - return nil, fmt.Errorf("failed to collect policies at parent group ID %q", parentGroup.ID) - } - policies = append(policies, parentPolicies...) - } - - return strutil.RemoveDuplicates(policies, false), nil -} - -func (i *IdentityStore) detectCycleDFS(visited map[string]bool, startingGroupID, groupID string) (bool, error) { - // If the traversal reaches the startingGroupID, a loop is detected - if startingGroupID == groupID { - return true, nil - } - - // If traversal for a groupID is performed before, skip it - if visited[groupID] { - return false, nil - } - visited[groupID] = true - - group, err := i.MemDBGroupByID(groupID, true) - if err != nil { - return false, err - } - if group == nil { - return false, nil - } - - // Fetch all groups in which groupID is present as a ParentGroupID. In - // other words, find all the subgroups of groupID. - memberGroups, err := i.MemDBGroupsByParentGroupID(groupID, false) - if err != nil { - return false, err - } - - // DFS traverse the member groups - for _, memberGroup := range memberGroups { - cycleDetected, err := i.detectCycleDFS(visited, startingGroupID, memberGroup.ID) - if err != nil { - return false, fmt.Errorf("failed to perform cycle detection at member group ID %q", memberGroup.ID) - } - if cycleDetected { - return true, fmt.Errorf("cycle detected at member group ID %q", memberGroup.ID) - } - } - - return false, nil -} - -func (i *IdentityStore) memberGroupIDsByID(groupID string) ([]string, error) { - var memberGroupIDs []string - memberGroups, err := i.MemDBGroupsByParentGroupID(groupID, false) - if err != nil { - return nil, err - } - for _, memberGroup := range memberGroups { - memberGroupIDs = append(memberGroupIDs, memberGroup.ID) - } - return memberGroupIDs, nil -} - -func (i *IdentityStore) generateName(entryType string) (string, error) { - var name string -OUTER: - for { - randBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - return "", err - } - name = fmt.Sprintf("%s_%s", entryType, fmt.Sprintf("%08x", randBytes[0:4])) - - switch entryType { - case "entity": - entity, err := i.MemDBEntityByName(name, false) - if err != nil { - return "", err - } - if entity == nil { - break OUTER - } - case "group": - group, err := i.MemDBGroupByName(name, false) - if err != nil { - return "", err - } - if group == nil { - break OUTER - } - default: - return "", fmt.Errorf("unrecognized type %q", entryType) - } - } - - return name, nil -} - -func (i *IdentityStore) MemDBGroupsByBucketEntryKeyHashInTxn(txn *memdb.Txn, hashValue string) ([]*identity.Group, error) { - if txn == nil { - return nil, fmt.Errorf("nil txn") - } - - if hashValue == "" { - return nil, fmt.Errorf("empty hash value") - } - - groupsIter, err := txn.Get(groupsTable, "bucket_key_hash", hashValue) - if err != nil { - return nil, errwrap.Wrapf("failed to lookup groups using bucket entry key hash: {{err}}", err) - } - - var groups []*identity.Group - for group := groupsIter.Next(); group != nil; group = groupsIter.Next() { - groups = append(groups, group.(*identity.Group)) - } - - return groups, nil -} - -func (i *IdentityStore) MemDBGroupByAliasIDInTxn(txn *memdb.Txn, aliasID string, clone bool) (*identity.Group, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - if txn == nil { - return nil, fmt.Errorf("txn is nil") - } - - alias, err := i.MemDBAliasByIDInTxn(txn, aliasID, false, true) - if err != nil { - return nil, err - } - - if alias == nil { - return nil, nil - } - - return i.MemDBGroupByIDInTxn(txn, alias.CanonicalID, clone) -} - -func (i *IdentityStore) MemDBGroupByAliasID(aliasID string, clone bool) (*identity.Group, error) { - if aliasID == "" { - return nil, fmt.Errorf("missing alias ID") - } - - txn := i.db.Txn(false) - - return i.MemDBGroupByAliasIDInTxn(txn, aliasID, clone) -} - -func (i *IdentityStore) refreshExternalGroupMembershipsByEntityID(entityID string, groupAliases []*logical.Alias) ([]*logical.Alias, error) { - if entityID == "" { - return nil, fmt.Errorf("empty entity ID") - } - - i.groupLock.Lock() - defer i.groupLock.Unlock() - - txn := i.db.Txn(true) - defer txn.Abort() - - oldGroups, err := i.MemDBGroupsByMemberEntityIDInTxn(txn, entityID, true, true) - if err != nil { - return nil, err - } - - mountAccessor := "" - if len(groupAliases) != 0 { - mountAccessor = groupAliases[0].MountAccessor - } - - var newGroups []*identity.Group - var validAliases []*logical.Alias - for _, alias := range groupAliases { - aliasByFactors, err := i.MemDBAliasByFactors(alias.MountAccessor, alias.Name, true, true) - if err != nil { - return nil, err - } - if aliasByFactors == nil { - continue - } - mappingGroup, err := i.MemDBGroupByAliasID(aliasByFactors.ID, true) - if err != nil { - return nil, err - } - if mappingGroup == nil { - return nil, fmt.Errorf("group unavailable for a valid alias ID %q", aliasByFactors.ID) - } - newGroups = append(newGroups, mappingGroup) - validAliases = append(validAliases, alias) - } - - diff := diffGroups(oldGroups, newGroups) - - // Add the entity ID to all the new groups - for _, group := range diff.New { - if group.Type != groupTypeExternal { - continue - } - - i.logger.Debug("adding member entity ID to external group", "member_entity_id", entityID, "group_id", group.ID) - - group.MemberEntityIDs = append(group.MemberEntityIDs, entityID) - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - } - - // Remove the entity ID from all the deleted groups - for _, group := range diff.Deleted { - if group.Type != groupTypeExternal { - continue - } - - // If the external group is from a different mount, don't remove the - // entity ID from it. - if mountAccessor != "" && group.Alias.MountAccessor != mountAccessor { - continue - } - - i.logger.Debug("removing member entity ID from external group", "member_entity_id", entityID, "group_id", group.ID) - - group.MemberEntityIDs = strutil.StrListDelete(group.MemberEntityIDs, entityID) - - err = i.UpsertGroupInTxn(txn, group, true) - if err != nil { - return nil, err - } - } - - txn.Commit() - - return validAliases, nil -} - -// diffGroups is used to diff two sets of groups -func diffGroups(old, new []*identity.Group) *groupDiff { - diff := &groupDiff{} - - existing := make(map[string]*identity.Group) - for _, group := range old { - existing[group.ID] = group - } - - for _, group := range new { - // Check if the entry in new is present in the old - _, ok := existing[group.ID] - - // If its not present, then its a new entry - if !ok { - diff.New = append(diff.New, group) - continue - } - - // If its present, it means that its unmodified - diff.Unmodified = append(diff.Unmodified, group) - - // By deleting the unmodified from the old set, we could determine the - // ones that are stale by looking at the remaining ones. - delete(existing, group.ID) - } - - // Any remaining entries must have been deleted - for _, me := range existing { - diff.Deleted = append(diff.Deleted, me) - } - - return diff -} diff --git a/vendor/github.com/hashicorp/vault/vault/init.go b/vendor/github.com/hashicorp/vault/vault/init.go deleted file mode 100644 index d6b7de4e7..000000000 --- a/vendor/github.com/hashicorp/vault/vault/init.go +++ /dev/null @@ -1,303 +0,0 @@ -package vault - -import ( - "context" - "encoding/base64" - "encoding/hex" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/shamir" -) - -// InitParams keeps the init function from being littered with too many -// params, that's it! -type InitParams struct { - BarrierConfig *SealConfig - RecoveryConfig *SealConfig - RootTokenPGPKey string -} - -// InitResult is used to provide the key parts back after -// they are generated as part of the initialization. -type InitResult struct { - SecretShares [][]byte - RecoveryShares [][]byte - RootToken string -} - -// Initialized checks if the Vault is already initialized -func (c *Core) Initialized(ctx context.Context) (bool, error) { - // Check the barrier first - init, err := c.barrier.Initialized(ctx) - if err != nil { - c.logger.Error("barrier init check failed", "error", err) - return false, err - } - if !init { - c.logger.Info("security barrier not initialized") - return false, nil - } - - // Verify the seal configuration - sealConf, err := c.seal.BarrierConfig(ctx) - if err != nil { - return false, err - } - if sealConf == nil { - return false, fmt.Errorf("core: barrier reports initialized but no seal configuration found") - } - - return true, nil -} - -func (c *Core) generateShares(sc *SealConfig) ([]byte, [][]byte, error) { - // Generate a master key - masterKey, err := c.barrier.GenerateKey() - if err != nil { - return nil, nil, errwrap.Wrapf("key generation failed: {{err}}", err) - } - - // Return the master key if only a single key part is used - var unsealKeys [][]byte - if sc.SecretShares == 1 { - unsealKeys = append(unsealKeys, masterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(masterKey, sc.SecretShares, sc.SecretThreshold) - if err != nil { - return nil, nil, errwrap.Wrapf("failed to generate barrier shares: {{err}}", err) - } - unsealKeys = shares - } - - // If we have PGP keys, perform the encryption - if len(sc.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(unsealKeys)) - for i, _ := range unsealKeys { - hexEncodedShares[i] = []byte(hex.EncodeToString(unsealKeys[i])) - } - _, encryptedShares, err := pgpkeys.EncryptShares(hexEncodedShares, sc.PGPKeys) - if err != nil { - return nil, nil, err - } - unsealKeys = encryptedShares - } - - return masterKey, unsealKeys, nil -} - -// Initialize is used to initialize the Vault with the given -// configurations. -func (c *Core) Initialize(ctx context.Context, initParams *InitParams) (*InitResult, error) { - barrierConfig := initParams.BarrierConfig - recoveryConfig := initParams.RecoveryConfig - - if c.seal.RecoveryKeySupported() { - if recoveryConfig == nil { - return nil, fmt.Errorf("recovery configuration must be supplied") - } - - if recoveryConfig.SecretShares < 1 { - return nil, fmt.Errorf("recovery configuration must specify a positive number of shares") - } - - // Check if the seal configuration is valid - if err := recoveryConfig.Validate(); err != nil { - c.logger.Error("invalid recovery configuration", "error", err) - return nil, errwrap.Wrapf("invalid recovery configuration: {{err}}", err) - } - } - - // Check if the seal configuration is valid - if err := barrierConfig.Validate(); err != nil { - c.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("invalid seal configuration: {{err}}", err) - } - - // Avoid an initialization race - c.stateLock.Lock() - defer c.stateLock.Unlock() - - // Check if we are initialized - init, err := c.Initialized(ctx) - if err != nil { - return nil, err - } - if init { - return nil, ErrAlreadyInit - } - - err = c.seal.Init(ctx) - if err != nil { - c.logger.Error("failed to initialize seal", "error", err) - return nil, errwrap.Wrapf("error initializing seal: {{err}}", err) - } - - barrierKey, barrierUnsealKeys, err := c.generateShares(barrierConfig) - if err != nil { - c.logger.Error("error generating shares", "error", err) - return nil, err - } - - // Initialize the barrier - if err := c.barrier.Initialize(ctx, barrierKey); err != nil { - c.logger.Error("failed to initialize barrier", "error", err) - return nil, errwrap.Wrapf("failed to initialize barrier: {{err}}", err) - } - if c.logger.IsInfo() { - c.logger.Info("security barrier initialized", "shares", barrierConfig.SecretShares, "threshold", barrierConfig.SecretThreshold) - } - - // Unseal the barrier - if err := c.barrier.Unseal(ctx, barrierKey); err != nil { - c.logger.Error("failed to unseal barrier", "error", err) - return nil, errwrap.Wrapf("failed to unseal barrier: {{err}}", err) - } - - // Ensure the barrier is re-sealed - defer func() { - // Defers are LIFO so we need to run this here too to ensure the stop - // happens before sealing. preSeal also stops, so we just make the - // stopping safe against multiple calls. - if err := c.barrier.Seal(); err != nil { - c.logger.Error("failed to seal barrier", "error", err) - } - }() - - err = c.seal.SetBarrierConfig(ctx, barrierConfig) - if err != nil { - c.logger.Error("failed to save barrier configuration", "error", err) - return nil, errwrap.Wrapf("barrier configuration saving failed: {{err}}", err) - } - - // If we are storing shares, pop them out of the returned results and push - // them through the seal - if barrierConfig.StoredShares > 0 { - var keysToStore [][]byte - for i := 0; i < barrierConfig.StoredShares; i++ { - keysToStore = append(keysToStore, barrierUnsealKeys[0]) - barrierUnsealKeys = barrierUnsealKeys[1:] - } - if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { - c.logger.Error("failed to store keys", "error", err) - return nil, errwrap.Wrapf("failed to store keys: {{err}}", err) - } - } - - results := &InitResult{ - SecretShares: barrierUnsealKeys, - } - - // Perform initial setup - if err := c.setupCluster(ctx); err != nil { - c.logger.Error("cluster setup failed during init", "error", err) - return nil, err - } - - activeCtx, ctxCancel := context.WithCancel(context.Background()) - if err := c.postUnseal(activeCtx, ctxCancel); err != nil { - c.logger.Error("post-unseal setup failed during init", "error", err) - return nil, err - } - - // Save the configuration regardless, but only generate a key if it's not - // disabled. When using recovery keys they are stored in the barrier, so - // this must happen post-unseal. - if c.seal.RecoveryKeySupported() { - err = c.seal.SetRecoveryConfig(ctx, recoveryConfig) - if err != nil { - c.logger.Error("failed to save recovery configuration", "error", err) - return nil, errwrap.Wrapf("recovery configuration saving failed: {{err}}", err) - } - - if recoveryConfig.SecretShares > 0 { - recoveryKey, recoveryUnsealKeys, err := c.generateShares(recoveryConfig) - if err != nil { - c.logger.Error("failed to generate recovery shares", "error", err) - return nil, err - } - - err = c.seal.SetRecoveryKey(ctx, recoveryKey) - if err != nil { - return nil, err - } - - results.RecoveryShares = recoveryUnsealKeys - } - } - - // Generate a new root token - rootToken, err := c.tokenStore.rootToken(ctx) - if err != nil { - c.logger.Error("root token generation failed", "error", err) - return nil, err - } - results.RootToken = rootToken.ID - c.logger.Info("root token generated") - - if initParams.RootTokenPGPKey != "" { - _, encryptedVals, err := pgpkeys.EncryptShares([][]byte{[]byte(results.RootToken)}, []string{initParams.RootTokenPGPKey}) - if err != nil { - c.logger.Error("root token encryption failed", "error", err) - return nil, err - } - results.RootToken = base64.StdEncoding.EncodeToString(encryptedVals[0]) - } - - // Prepare to re-seal - if err := c.preSeal(); err != nil { - c.logger.Error("pre-seal teardown failed", "error", err) - return nil, err - } - - return results, nil -} - -// UnsealWithStoredKeys performs auto-unseal using stored keys. -func (c *Core) UnsealWithStoredKeys(ctx context.Context) error { - if !c.seal.StoredKeysSupported() { - return nil - } - - sealed := c.Sealed() - if !sealed { - return nil - } - - c.logger.Info("stored unseal keys supported, attempting fetch") - keys, err := c.seal.GetStoredKeys(ctx) - if err != nil { - c.logger.Error("fetching stored unseal keys failed", "error", err) - return &NonFatalError{Err: errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err)} - } - if len(keys) == 0 { - c.logger.Warn("stored unseal key(s) supported but none found") - } else { - unsealed := false - keysUsed := 0 - for _, key := range keys { - unsealed, err = c.Unseal(key) - if err != nil { - c.logger.Error("unseal with stored unseal key failed", "error", err) - return &NonFatalError{Err: errwrap.Wrapf("unseal with stored key failed: {{err}}", err)} - } - keysUsed += 1 - if unsealed { - break - } - } - if !unsealed { - if c.logger.IsWarn() { - c.logger.Warn("stored unseal key(s) used but Vault not unsealed yet", "stored_keys_used", keysUsed) - } - } else { - if c.logger.IsInfo() { - c.logger.Info("successfully unsealed with stored key(s)", "stored_keys_used", keysUsed) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/keyring.go b/vendor/github.com/hashicorp/vault/vault/keyring.go deleted file mode 100644 index fd6564790..000000000 --- a/vendor/github.com/hashicorp/vault/vault/keyring.go +++ /dev/null @@ -1,203 +0,0 @@ -package vault - -import ( - "bytes" - "encoding/json" - "fmt" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" -) - -// Keyring is used to manage multiple encryption keys used by -// the barrier. New keys can be installed and each has a sequential term. -// The term used to encrypt a key is prefixed to the key written out. -// All data is encrypted with the latest key, but storing the old keys -// allows for decryption of keys written previously. Along with the encryption -// keys, the keyring also tracks the master key. This is necessary so that -// when a new key is added to the keyring, we can encrypt with the master key -// and write out the new keyring. -type Keyring struct { - masterKey []byte - keys map[uint32]*Key - activeTerm uint32 -} - -// EncodedKeyring is used for serialization of the keyring -type EncodedKeyring struct { - MasterKey []byte - Keys []*Key -} - -// Key represents a single term, along with the key used. -type Key struct { - Term uint32 - Version int - Value []byte - InstallTime time.Time -} - -// Serialize is used to create a byte encoded key -func (k *Key) Serialize() ([]byte, error) { - return json.Marshal(k) -} - -// DeserializeKey is used to deserialize and return a new key -func DeserializeKey(buf []byte) (*Key, error) { - k := new(Key) - if err := jsonutil.DecodeJSON(buf, k); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) - } - return k, nil -} - -// NewKeyring creates a new keyring -func NewKeyring() *Keyring { - k := &Keyring{ - keys: make(map[uint32]*Key), - activeTerm: 0, - } - return k -} - -// Clone returns a new copy of the keyring -func (k *Keyring) Clone() *Keyring { - clone := &Keyring{ - masterKey: k.masterKey, - keys: make(map[uint32]*Key, len(k.keys)), - activeTerm: k.activeTerm, - } - for idx, key := range k.keys { - clone.keys[idx] = key - } - return clone -} - -// AddKey adds a new key to the keyring -func (k *Keyring) AddKey(key *Key) (*Keyring, error) { - // Ensure there is no conflict - if exist, ok := k.keys[key.Term]; ok { - if !bytes.Equal(key.Value, exist.Value) { - return nil, fmt.Errorf("conflicting key for term %d already installed", key.Term) - } - return k, nil - } - - // Add a time if none - if key.InstallTime.IsZero() { - key.InstallTime = time.Now() - } - - // Make a new keyring - clone := k.Clone() - - // Install the new key - clone.keys[key.Term] = key - - // Update the active term if newer - if key.Term > clone.activeTerm { - clone.activeTerm = key.Term - } - return clone, nil -} - -// RemoveKey removes a key from the keyring -func (k *Keyring) RemoveKey(term uint32) (*Keyring, error) { - // Ensure this is not the active key - if term == k.activeTerm { - return nil, fmt.Errorf("cannot remove active key") - } - - // Check if this term does not exist - if _, ok := k.keys[term]; !ok { - return k, nil - } - - // Delete the key - clone := k.Clone() - delete(clone.keys, term) - return clone, nil -} - -// ActiveTerm returns the currently active term -func (k *Keyring) ActiveTerm() uint32 { - return k.activeTerm -} - -// ActiveKey returns the active encryption key, or nil -func (k *Keyring) ActiveKey() *Key { - return k.keys[k.activeTerm] -} - -// TermKey returns the key for the given term, or nil -func (k *Keyring) TermKey(term uint32) *Key { - return k.keys[term] -} - -// SetMasterKey is used to update the master key -func (k *Keyring) SetMasterKey(val []byte) *Keyring { - valCopy := make([]byte, len(val)) - copy(valCopy, val) - clone := k.Clone() - clone.masterKey = valCopy - return clone -} - -// MasterKey returns the master key -func (k *Keyring) MasterKey() []byte { - return k.masterKey -} - -// Serialize is used to create a byte encoded keyring -func (k *Keyring) Serialize() ([]byte, error) { - // Create the encoded entry - enc := EncodedKeyring{ - MasterKey: k.masterKey, - } - for _, key := range k.keys { - enc.Keys = append(enc.Keys, key) - } - - // JSON encode the keyring - buf, err := json.Marshal(enc) - return buf, err -} - -// DeserializeKeyring is used to deserialize and return a new keyring -func DeserializeKeyring(buf []byte) (*Keyring, error) { - // Deserialize the keyring - var enc EncodedKeyring - if err := jsonutil.DecodeJSON(buf, &enc); err != nil { - return nil, errwrap.Wrapf("deserialization failed: {{err}}", err) - } - - // Create a new keyring - k := NewKeyring() - k.masterKey = enc.MasterKey - for _, key := range enc.Keys { - k.keys[key.Term] = key - if key.Term > k.activeTerm { - k.activeTerm = key.Term - } - } - return k, nil -} - -// N.B.: -// Since Go 1.5 these are not reliable; see the documentation around the memzero -// function. These are best-effort. -func (k *Keyring) Zeroize(keysToo bool) { - if k == nil { - return - } - if k.masterKey != nil { - memzero(k.masterKey) - } - if !keysToo || k.keys == nil { - return - } - for _, key := range k.keys { - memzero(key.Value) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go b/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go deleted file mode 100644 index 08055ddb3..000000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_cubbyhole.go +++ /dev/null @@ -1,207 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// CubbyholeBackendFactory constructs a new cubbyhole backend -func CubbyholeBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - var b CubbyholeBackend - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(cubbyholeHelp), - - Paths: []*framework.Path{ - &framework.Path{ - Pattern: ".*", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRead, - logical.CreateOperation: b.handleWrite, - logical.UpdateOperation: b.handleWrite, - logical.DeleteOperation: b.handleDelete, - logical.ListOperation: b.handleList, - }, - - ExistenceCheck: b.handleExistenceCheck, - - HelpSynopsis: strings.TrimSpace(cubbyholeHelpSynopsis), - HelpDescription: strings.TrimSpace(cubbyholeHelpDescription), - }, - }, - } - - if conf == nil { - return nil, fmt.Errorf("configuration passed into backend is nil") - } - b.Backend.Setup(ctx, conf) - - return &b, nil -} - -// CubbyholeBackend is used for storing secrets directly into the physical -// backend. The secrets are encrypted in the durable storage. -// This differs from kv in that every token has its own private -// storage view. The view is removed when the token expires. -type CubbyholeBackend struct { - *framework.Backend - - saltUUID string - storageView logical.Storage -} - -func (b *CubbyholeBackend) revoke(ctx context.Context, saltedToken string) error { - if saltedToken == "" { - return fmt.Errorf("client token empty during revocation") - } - - if err := logical.ClearView(ctx, b.storageView.(*BarrierView).SubView(saltedToken+"/")); err != nil { - return err - } - - return nil -} - -func (b *CubbyholeBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - out, err := req.Storage.Get(ctx, req.ClientToken+"/"+req.Path) - if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) - } - - return out != nil, nil -} - -func (b *CubbyholeBackend) handleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - // Read the path - out, err := req.Storage.Get(ctx, req.ClientToken+"/"+req.Path) - if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) - } - - // Fast-path the no data case - if out == nil { - return nil, nil - } - - // Decode the data - var rawData map[string]interface{} - if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) - } - - // Generate the response - resp := &logical.Response{ - Data: rawData, - } - - return resp, nil -} - -func (b *CubbyholeBackend) handleWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - // Check that some fields are given - if len(req.Data) == 0 { - return nil, fmt.Errorf("missing data fields") - } - - // JSON encode the data - buf, err := json.Marshal(req.Data) - if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) - } - - // Write out a new key - entry := &logical.StorageEntry{ - Key: req.ClientToken + "/" + req.Path, - Value: buf, - } - if req.WrapInfo != nil && req.WrapInfo.SealWrap { - entry.SealWrap = true - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) - } - - return nil, nil -} - -func (b *CubbyholeBackend) handleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - // Delete the key at the request path - if err := req.Storage.Delete(ctx, req.ClientToken+"/"+req.Path); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *CubbyholeBackend) handleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - return nil, fmt.Errorf("client token empty") - } - - // Right now we only handle directories, so ensure it ends with / We also - // check if it's empty so we don't end up doing a listing on '//' - path := req.Path - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // List the keys at the prefix given by the request - keys, err := req.Storage.List(ctx, req.ClientToken+"/"+path) - if err != nil { - return nil, err - } - - // Strip the token - strippedKeys := make([]string, len(keys)) - for i, key := range keys { - strippedKeys[i] = strings.TrimPrefix(key, req.ClientToken+"/") - } - - // Generate the response - return logical.ListResponse(strippedKeys), nil -} - -const cubbyholeHelp = ` -The cubbyhole backend reads and writes arbitrary secrets to the backend. -The secrets are encrypted/decrypted by Vault: they are never stored -unencrypted in the backend and the backend never has an opportunity to -see the unencrypted value. - -This backend differs from the 'kv' backend in that it is namespaced -per-token. Tokens can only read and write their own values, with no -sharing possible (per-token cubbyholes). This can be useful for implementing -certain authentication workflows, as well as "scratch" areas for individual -clients. When the token is revoked, the entire set of stored values for that -token is also removed. -` - -const cubbyholeHelpSynopsis = ` -Pass-through secret storage to a token-specific cubbyhole in the storage -backend, allowing you to read/write arbitrary data into secret storage. -` - -const cubbyholeHelpDescription = ` -The cubbyhole backend reads and writes arbitrary data into secret storage, -encrypting it along the way. - -The view into the cubbyhole storage space is different for each token; it is -a per-token cubbyhole. When the token is revoked all values are removed. -` diff --git a/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go b/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go deleted file mode 100644 index 3a40da251..000000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_passthrough.go +++ /dev/null @@ -1,247 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -// PassthroughBackendFactory returns a PassthroughBackend -// with leases switched off -func PassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, false) -} - -// LeasedPassthroughBackendFactory returns a PassthroughBackend -// with leases switched on -func LeasedPassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) { - return LeaseSwitchedPassthroughBackend(ctx, conf, true) -} - -// LeaseSwitchedPassthroughBackend returns a PassthroughBackend -// with leases switched on or off -func LeaseSwitchedPassthroughBackend(ctx context.Context, conf *logical.BackendConfig, leases bool) (logical.Backend, error) { - var b PassthroughBackend - b.generateLeases = leases - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(passthroughHelp), - - PathsSpecial: &logical.Paths{ - SealWrapStorage: []string{ - "*", - }, - }, - - Paths: []*framework.Path{ - &framework.Path{ - Pattern: ".*", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRead, - logical.CreateOperation: b.handleWrite, - logical.UpdateOperation: b.handleWrite, - logical.DeleteOperation: b.handleDelete, - logical.ListOperation: b.handleList, - }, - - ExistenceCheck: b.handleExistenceCheck, - - HelpSynopsis: strings.TrimSpace(passthroughHelpSynopsis), - HelpDescription: strings.TrimSpace(passthroughHelpDescription), - }, - }, - } - - b.Backend.Secrets = []*framework.Secret{ - &framework.Secret{ - Type: "kv", - - Renew: b.handleRead, - Revoke: b.handleRevoke, - }, - } - - if conf == nil { - return nil, fmt.Errorf("configuration passed into backend is nil") - } - b.Backend.Setup(ctx, conf) - - return &b, nil -} - -// PassthroughBackend is used storing secrets directly into the physical -// backend. The secrets are encrypted in the durable storage and custom TTL -// information can be specified, but otherwise this backend doesn't do anything -// fancy. -type PassthroughBackend struct { - *framework.Backend - generateLeases bool -} - -func (b *PassthroughBackend) handleRevoke(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // This is a no-op - return nil, nil -} - -func (b *PassthroughBackend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return false, errwrap.Wrapf("existence check failed: {{err}}", err) - } - - return out != nil, nil -} - -func (b *PassthroughBackend) handleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Read the path - out, err := req.Storage.Get(ctx, req.Path) - if err != nil { - return nil, errwrap.Wrapf("read failed: {{err}}", err) - } - - // Fast-path the no data case - if out == nil { - return nil, nil - } - - // Decode the data - var rawData map[string]interface{} - - if err := jsonutil.DecodeJSON(out.Value, &rawData); err != nil { - return nil, errwrap.Wrapf("json decoding failed: {{err}}", err) - } - - var resp *logical.Response - if b.generateLeases { - // Generate the response - resp = b.Secret("kv").Response(rawData, nil) - resp.Secret.Renewable = false - } else { - resp = &logical.Response{ - Secret: &logical.Secret{}, - Data: rawData, - } - } - - // Ensure seal wrapping is carried through if the response is - // response-wrapped - if out.SealWrap { - if resp.WrapInfo == nil { - resp.WrapInfo = &wrapping.ResponseWrapInfo{} - } - resp.WrapInfo.SealWrap = out.SealWrap - } - - // Check if there is a ttl key - ttlDuration := b.System().DefaultLeaseTTL() - ttlRaw, ok := rawData["ttl"] - if !ok { - ttlRaw, ok = rawData["lease"] - } - if ok { - dur, err := parseutil.ParseDurationSecond(ttlRaw) - if err == nil { - ttlDuration = dur - } - - if b.generateLeases { - resp.Secret.Renewable = true - } - } - - resp.Secret.TTL = ttlDuration - - return resp, nil -} - -func (b *PassthroughBackend) GeneratesLeases() bool { - return b.generateLeases -} - -func (b *PassthroughBackend) handleWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Check that some fields are given - if len(req.Data) == 0 { - return logical.ErrorResponse("missing data fields"), nil - } - - // JSON encode the data - buf, err := json.Marshal(req.Data) - if err != nil { - return nil, errwrap.Wrapf("json encoding failed: {{err}}", err) - } - - // Write out a new key - entry := &logical.StorageEntry{ - Key: req.Path, - Value: buf, - } - if err := req.Storage.Put(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to write: {{err}}", err) - } - - return nil, nil -} - -func (b *PassthroughBackend) handleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Delete the key at the request path - if err := req.Storage.Delete(ctx, req.Path); err != nil { - return nil, err - } - - return nil, nil -} - -func (b *PassthroughBackend) handleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Right now we only handle directories, so ensure it ends with /; however, - // some physical backends may not handle the "/" case properly, so only add - // it if we're not listing the root - path := req.Path - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // List the keys at the prefix given by the request - keys, err := req.Storage.List(ctx, path) - if err != nil { - return nil, err - } - - // Generate the response - return logical.ListResponse(keys), nil -} - -const passthroughHelp = ` -The kv backend reads and writes arbitrary secrets to the backend. -The secrets are encrypted/decrypted by Vault: they are never stored -unencrypted in the backend and the backend never has an opportunity to -see the unencrypted value. - -TTLs can be set on a per-secret basis. These TTLs will be sent down -when that secret is read, and it is assumed that some outside process will -revoke and/or replace the secret at that path. -` - -const passthroughHelpSynopsis = ` -Pass-through secret storage to the storage backend, allowing you to -read/write arbitrary data into secret storage. -` - -const passthroughHelpDescription = ` -The pass-through backend reads and writes arbitrary data into secret storage, -encrypting it along the way. - -A TTL can be specified when writing with the "ttl" field. If given, the -duration of leases returned by this backend will be set to this value. This -can be used as a hint from the writer of a secret to the consumer of a secret -that the consumer should re-read the value before the TTL has expired. -However, any revocation must be handled by the user of this backend; the lease -duration does not affect the provided data in any way. -` diff --git a/vendor/github.com/hashicorp/vault/vault/logical_system.go b/vendor/github.com/hashicorp/vault/vault/logical_system.go deleted file mode 100644 index a39bb6178..000000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_system.go +++ /dev/null @@ -1,4377 +0,0 @@ -package vault - -import ( - "context" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "net/http" - "path/filepath" - "strconv" - "strings" - "sync" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - uuid "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/compressutil" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -var ( - // protectedPaths cannot be accessed via the raw APIs. - // This is both for security and to prevent disrupting Vault. - protectedPaths = []string{ - keyringPath, - coreLocalClusterInfoPath, - } - - replicationPaths = func(b *SystemBackend) []*framework.Path { - return []*framework.Path{ - &framework.Path{ - Pattern: "replication/status", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - resp := &logical.Response{ - Data: map[string]interface{}{ - "mode": "disabled", - }, - } - return resp, nil - }, - }, - }, - } - } -) - -func NewSystemBackend(core *Core, logger log.Logger) *SystemBackend { - b := &SystemBackend{ - Core: core, - logger: logger, - } - - b.Backend = &framework.Backend{ - Help: strings.TrimSpace(sysHelpRoot), - - PathsSpecial: &logical.Paths{ - Root: []string{ - "auth/*", - "remount", - "audit", - "audit/*", - "raw", - "raw/*", - "replication/primary/secondary-token", - "replication/reindex", - "rotate", - "config/cors", - "config/auditing/*", - "config/ui/headers/*", - "plugins/catalog/*", - "revoke-prefix/*", - "revoke-force/*", - "leases/revoke-prefix/*", - "leases/revoke-force/*", - "leases/lookup/*", - }, - - Unauthenticated: []string{ - "wrapping/lookup", - "wrapping/pubkey", - "replication/status", - "internal/ui/mounts", - "internal/ui/mounts/*", - }, - }, - - Paths: []*framework.Path{ - &framework.Path{ - Pattern: "capabilities-accessor$", - - Fields: map[string]*framework.FieldSchema{ - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilitiesAccessor, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities_accessor"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities_accessor"][1]), - }, - - &framework.Path{ - Pattern: "config/cors$", - - Fields: map[string]*framework.FieldSchema{ - "enable": &framework.FieldSchema{ - Type: framework.TypeBool, - Description: "Enables or disables CORS headers on requests.", - }, - "allowed_origins": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "A comma-separated string or array of strings indicating origins that may make cross-origin requests.", - }, - "allowed_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "A comma-separated string or array of strings indicating headers that are allowed on cross-origin requests.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleCORSRead, - logical.UpdateOperation: b.handleCORSUpdate, - logical.DeleteOperation: b.handleCORSDelete, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/cors"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/cors"][1]), - }, - - &framework.Path{ - Pattern: "config/ui/headers/" + framework.GenericNameRegex("header"), - - Fields: map[string]*framework.FieldSchema{ - "header": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The name of the header.", - }, - "values": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: "The values to set the header.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleConfigUIHeadersRead, - logical.UpdateOperation: b.handleConfigUIHeadersUpdate, - logical.DeleteOperation: b.handleConfigUIHeadersDelete, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/ui/headers"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/ui/headers"][1]), - }, - - &framework.Path{ - Pattern: "config/ui/headers/$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.handleConfigUIHeadersList, - }, - - HelpDescription: strings.TrimSpace(sysHelp["config/ui/headers"][0]), - HelpSynopsis: strings.TrimSpace(sysHelp["config/ui/headers"][1]), - }, - - &framework.Path{ - Pattern: "capabilities$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilities, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities"][1]), - }, - - &framework.Path{ - Pattern: "capabilities-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token for which capabilities are being queried.", - }, - "path": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "(DEPRECATED) Path on which capabilities are being queried. Use 'paths' instead.", - }, - "paths": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: "Paths on which capabilities are being queried.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleCapabilities, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["capabilities_self"][0]), - HelpDescription: strings.TrimSpace(sysHelp["capabilities_self"][1]), - }, - - &framework.Path{ - Pattern: "generate-root(/attempt)?$", - HelpSynopsis: strings.TrimSpace(sysHelp["generate-root"][0]), - HelpDescription: strings.TrimSpace(sysHelp["generate-root"][1]), - }, - - &framework.Path{ - Pattern: "init$", - HelpSynopsis: strings.TrimSpace(sysHelp["init"][0]), - HelpDescription: strings.TrimSpace(sysHelp["init"][1]), - }, - - &framework.Path{ - Pattern: "rekey/backup$", - - Fields: map[string]*framework.FieldSchema{}, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRekeyRetrieveBarrier, - logical.DeleteOperation: b.handleRekeyDeleteBarrier, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rekey_backup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rekey_backup"][0]), - }, - - &framework.Path{ - Pattern: "rekey/recovery-key-backup$", - - Fields: map[string]*framework.FieldSchema{}, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRekeyRetrieveRecovery, - logical.DeleteOperation: b.handleRekeyDeleteRecovery, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rekey_backup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rekey_backup"][0]), - }, - - &framework.Path{ - Pattern: "auth/(?P.+?)/tune$", - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_tune"][0]), - }, - "default_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_default_lease_ttl"][0]), - }, - "max_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_max_lease_ttl"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "audit_non_hmac_request_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_request_keys"][0]), - }, - "audit_non_hmac_response_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_response_keys"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["tune_mount_options"][0]), - }, - "listing_visibility": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["listing_visibility"][0]), - }, - "passthrough_request_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["passthrough_request_headers"][0]), - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleAuthTuneRead, - logical.UpdateOperation: b.handleAuthTuneWrite, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["auth_tune"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth_tune"][1]), - }, - - &framework.Path{ - Pattern: "mounts/(?P.+?)/tune$", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_path"][0]), - }, - "default_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_default_lease_ttl"][0]), - }, - "max_lease_ttl": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["tune_max_lease_ttl"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "audit_non_hmac_request_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_request_keys"][0]), - }, - "audit_non_hmac_response_keys": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["tune_audit_non_hmac_response_keys"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["tune_mount_options"][0]), - }, - "listing_visibility": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["listing_visibility"][0]), - }, - "passthrough_request_headers": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["passthrough_request_headers"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleMountTuneRead, - logical.UpdateOperation: b.handleMountTuneWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["mount_tune"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mount_tune"][1]), - }, - - &framework.Path{ - Pattern: "mounts/(?P.+?)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_desc"][0]), - }, - "config": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: strings.TrimSpace(sysHelp["mount_config"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - "seal_wrap": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["seal_wrap"][0]), - }, - "plugin_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["mount_plugin_name"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["mount_options"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleMount, - logical.DeleteOperation: b.handleUnmount, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["mount"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mount"][1]), - }, - - &framework.Path{ - Pattern: "mounts$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleMountTable, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["mounts"][1]), - }, - - &framework.Path{ - Pattern: "remount", - - Fields: map[string]*framework.FieldSchema{ - "from": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The previous mount point.", - }, - "to": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The new mount point.", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRemount, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["remount"][0]), - HelpDescription: strings.TrimSpace(sysHelp["remount"][1]), - }, - - &framework.Path{ - Pattern: "leases/lookup/(?P.+?)?", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["leases-list-prefix"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.handleLeaseLookupList, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["leases"][1]), - }, - - &framework.Path{ - Pattern: "leases/lookup", - - Fields: map[string]*framework.FieldSchema{ - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleLeaseLookup, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["leases"][1]), - }, - - &framework.Path{ - Pattern: "(leases/)?renew" + framework.OptionalParamRegex("url_lease_id"), - - Fields: map[string]*framework.FieldSchema{ - "url_lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Description: strings.TrimSpace(sysHelp["increment"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRenew, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["renew"][0]), - HelpDescription: strings.TrimSpace(sysHelp["renew"][1]), - }, - - &framework.Path{ - Pattern: "(leases/)?revoke" + framework.OptionalParamRegex("url_lease_id"), - - Fields: map[string]*framework.FieldSchema{ - "url_lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "lease_id": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["lease_id"][0]), - }, - "sync": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: strings.TrimSpace(sysHelp["revoke-sync"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRevoke, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke"][1]), - }, - - &framework.Path{ - Pattern: "(leases/)?revoke-force/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["revoke-force-path"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRevokeForce, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke-force"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke-force"][1]), - }, - - &framework.Path{ - Pattern: "(leases/)?revoke-prefix/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "prefix": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["revoke-prefix-path"][0]), - }, - "sync": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: strings.TrimSpace(sysHelp["revoke-sync"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRevokePrefix, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["revoke-prefix"][0]), - HelpDescription: strings.TrimSpace(sysHelp["revoke-prefix"][1]), - }, - - &framework.Path{ - Pattern: "leases/tidy$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleTidyLeases, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["tidy_leases"][0]), - HelpDescription: strings.TrimSpace(sysHelp["tidy_leases"][1]), - }, - - &framework.Path{ - Pattern: "auth$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleAuthTable, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["auth-table"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth-table"][1]), - }, - - &framework.Path{ - Pattern: "auth/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_desc"][0]), - }, - "config": &framework.FieldSchema{ - Type: framework.TypeMap, - Description: strings.TrimSpace(sysHelp["auth_config"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - "seal_wrap": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["seal_wrap"][0]), - }, - "plugin_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["auth_plugin"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["auth_options"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleEnableAuth, - logical.DeleteOperation: b.handleDisableAuth, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["auth"][0]), - HelpDescription: strings.TrimSpace(sysHelp["auth"][1]), - }, - - &framework.Path{ - Pattern: "policy/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handlePoliciesList(PolicyTypeACL), - logical.ListOperation: b.handlePoliciesList(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy-list"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy-list"][1]), - }, - - &framework.Path{ - Pattern: "policy/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-name"][0]), - }, - "rules": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - }, - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handlePoliciesRead(PolicyTypeACL), - logical.UpdateOperation: b.handlePoliciesSet(PolicyTypeACL), - logical.DeleteOperation: b.handlePoliciesDelete(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy"][1]), - }, - - &framework.Path{ - Pattern: "policies/acl/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.handlePoliciesList(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy-list"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy-list"][1]), - }, - - &framework.Path{ - Pattern: "policies/acl/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-name"][0]), - }, - "policy": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["policy-rules"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handlePoliciesRead(PolicyTypeACL), - logical.UpdateOperation: b.handlePoliciesSet(PolicyTypeACL), - logical.DeleteOperation: b.handlePoliciesDelete(PolicyTypeACL), - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["policy"][0]), - HelpDescription: strings.TrimSpace(sysHelp["policy"][1]), - }, - - &framework.Path{ - Pattern: "seal-status$", - HelpSynopsis: strings.TrimSpace(sysHelp["seal-status"][0]), - HelpDescription: strings.TrimSpace(sysHelp["seal-status"][1]), - }, - - &framework.Path{ - Pattern: "seal$", - HelpSynopsis: strings.TrimSpace(sysHelp["seal"][0]), - HelpDescription: strings.TrimSpace(sysHelp["seal"][1]), - }, - - &framework.Path{ - Pattern: "unseal$", - HelpSynopsis: strings.TrimSpace(sysHelp["unseal"][0]), - HelpDescription: strings.TrimSpace(sysHelp["unseal"][1]), - }, - - &framework.Path{ - Pattern: "audit-hash/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_path"][0]), - }, - - "input": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleAuditHash, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit-hash"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit-hash"][1]), - }, - - &framework.Path{ - Pattern: "audit$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleAuditTable, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit-table"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit-table"][1]), - }, - - &framework.Path{ - Pattern: "audit/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_path"][0]), - }, - "type": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_type"][0]), - }, - "description": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["audit_desc"][0]), - }, - "options": &framework.FieldSchema{ - Type: framework.TypeKVPairs, - Description: strings.TrimSpace(sysHelp["audit_opts"][0]), - }, - "local": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: strings.TrimSpace(sysHelp["mount_local"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleEnableAudit, - logical.DeleteOperation: b.handleDisableAudit, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audit"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audit"][1]), - }, - - &framework.Path{ - Pattern: "key-status$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleKeyStatus, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["key-status"][0]), - HelpDescription: strings.TrimSpace(sysHelp["key-status"][1]), - }, - - &framework.Path{ - Pattern: "rotate$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleRotate, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rotate"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rotate"][1]), - }, - - &framework.Path{ - Pattern: "wrapping/wrap$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingWrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["wrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["wrap"][1]), - }, - - &framework.Path{ - Pattern: "wrapping/unwrap$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingUnwrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["unwrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["unwrap"][1]), - }, - - &framework.Path{ - Pattern: "wrapping/lookup$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingLookup, - logical.ReadOperation: b.handleWrappingLookup, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["wraplookup"][0]), - HelpDescription: strings.TrimSpace(sysHelp["wraplookup"][1]), - }, - - &framework.Path{ - Pattern: "wrapping/rewrap$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleWrappingRewrap, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["rewrap"][0]), - HelpDescription: strings.TrimSpace(sysHelp["rewrap"][1]), - }, - - &framework.Path{ - Pattern: "config/auditing/request-headers/(?P
.+)", - - Fields: map[string]*framework.FieldSchema{ - "header": &framework.FieldSchema{ - Type: framework.TypeString, - }, - "hmac": &framework.FieldSchema{ - Type: framework.TypeBool, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handleAuditedHeaderUpdate, - logical.DeleteOperation: b.handleAuditedHeaderDelete, - logical.ReadOperation: b.handleAuditedHeaderRead, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audited-headers-name"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audited-headers-name"][1]), - }, - - &framework.Path{ - Pattern: "config/auditing/request-headers$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleAuditedHeadersRead, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["audited-headers"][0]), - HelpDescription: strings.TrimSpace(sysHelp["audited-headers"][1]), - }, - - &framework.Path{ - Pattern: "plugins/catalog/?$", - - Fields: map[string]*framework.FieldSchema{}, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: b.handlePluginCatalogList, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-catalog"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-catalog"][1]), - }, - - &framework.Path{ - Pattern: "plugins/catalog/(?P.+)", - - Fields: map[string]*framework.FieldSchema{ - "name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_name"][0]), - }, - "sha256": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_sha-256"][0]), - }, - "sha_256": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_sha-256"][0]), - }, - "command": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-catalog_command"][0]), - }, - "args": &framework.FieldSchema{ - Type: framework.TypeStringSlice, - Description: strings.TrimSpace(sysHelp["plugin-catalog_args"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handlePluginCatalogUpdate, - logical.DeleteOperation: b.handlePluginCatalogDelete, - logical.ReadOperation: b.handlePluginCatalogRead, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-catalog"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-catalog"][1]), - }, - &framework.Path{ - Pattern: "plugins/reload/backend$", - - Fields: map[string]*framework.FieldSchema{ - "plugin": &framework.FieldSchema{ - Type: framework.TypeString, - Description: strings.TrimSpace(sysHelp["plugin-backend-reload-plugin"][0]), - }, - "mounts": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: strings.TrimSpace(sysHelp["plugin-backend-reload-mounts"][0]), - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.handlePluginReloadUpdate, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["plugin-reload"][0]), - HelpDescription: strings.TrimSpace(sysHelp["plugin-reload"][1]), - }, - &framework.Path{ - Pattern: "tools/hash" + framework.OptionalParamRegex("urlalgorithm"), - Fields: map[string]*framework.FieldSchema{ - "input": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The base64-encoded input data", - }, - - "algorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "sha2-256", - Description: `Algorithm to use (POST body parameter). Valid values are: - - * sha2-224 - * sha2-256 - * sha2-384 - * sha2-512 - - Defaults to "sha2-256".`, - }, - - "urlalgorithm": &framework.FieldSchema{ - Type: framework.TypeString, - Description: `Algorithm to use (POST URL parameter)`, - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "hex", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "hex".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathHashWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["hash"][0]), - HelpDescription: strings.TrimSpace(sysHelp["hash"][1]), - }, - - &framework.Path{ - Pattern: "tools/random" + framework.OptionalParamRegex("urlbytes"), - Fields: map[string]*framework.FieldSchema{ - "urlbytes": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The number of bytes to generate (POST URL parameter)", - }, - - "bytes": &framework.FieldSchema{ - Type: framework.TypeInt, - Default: 32, - Description: "The number of bytes to generate (POST body parameter). Defaults to 32 (256 bits).", - }, - - "format": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "base64", - Description: `Encoding format to use. Can be "hex" or "base64". Defaults to "base64".`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: b.pathRandomWrite, - }, - - HelpSynopsis: strings.TrimSpace(sysHelp["random"][0]), - HelpDescription: strings.TrimSpace(sysHelp["random"][1]), - }, - &framework.Path{ - Pattern: "internal/ui/mounts", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathInternalUIMountsRead, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-mounts"][1]), - }, - &framework.Path{ - Pattern: "internal/ui/mounts/(?P.+)", - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "The path of the mount.", - }, - }, - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathInternalUIMountRead, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-mounts"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-mounts"][1]), - }, - &framework.Path{ - Pattern: "internal/ui/resultant-acl", - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.pathInternalUIResultantACL, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["internal-ui-resultant-acl"][0]), - HelpDescription: strings.TrimSpace(sysHelp["internal-ui-resultant-acl"][1]), - }, - }, - } - - b.Backend.Paths = append(b.Backend.Paths, replicationPaths(b)...) - - if core.rawEnabled { - b.Backend.Paths = append(b.Backend.Paths, &framework.Path{ - Pattern: "(raw/?$|raw/(?P.+))", - - Fields: map[string]*framework.FieldSchema{ - "path": &framework.FieldSchema{ - Type: framework.TypeString, - }, - "value": &framework.FieldSchema{ - Type: framework.TypeString, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: b.handleRawRead, - logical.UpdateOperation: b.handleRawWrite, - logical.DeleteOperation: b.handleRawDelete, - logical.ListOperation: b.handleRawList, - }, - HelpSynopsis: strings.TrimSpace(sysHelp["raw"][0]), - HelpDescription: strings.TrimSpace(sysHelp["raw"][1]), - }) - } - - b.Backend.Invalidate = b.invalidate - - return b -} - -// SystemBackend implements logical.Backend and is used to interact with -// the core of the system. This backend is hardcoded to exist at the "sys" -// prefix. Conceptually it is similar to procfs on Linux. -type SystemBackend struct { - *framework.Backend - Core *Core - logger log.Logger -} - -// handleCORSRead returns the current CORS configuration -func (b *SystemBackend) handleCORSRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - corsConf := b.Core.corsConfig - - enabled := corsConf.IsEnabled() - - resp := &logical.Response{ - Data: map[string]interface{}{ - "enabled": enabled, - }, - } - - if enabled { - corsConf.RLock() - resp.Data["allowed_origins"] = corsConf.AllowedOrigins - resp.Data["allowed_headers"] = corsConf.AllowedHeaders - corsConf.RUnlock() - } - - return resp, nil -} - -// handleCORSUpdate sets the list of origins that are allowed to make -// cross-origin requests and sets the CORS enabled flag to true -func (b *SystemBackend) handleCORSUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - origins := d.Get("allowed_origins").([]string) - headers := d.Get("allowed_headers").([]string) - - return nil, b.Core.corsConfig.Enable(ctx, origins, headers) -} - -// handleCORSDelete sets the CORS enabled flag to false and clears the list of -// allowed origins & headers. -func (b *SystemBackend) handleCORSDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return nil, b.Core.corsConfig.Disable(ctx) -} - -func (b *SystemBackend) handleTidyLeases(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - go func() { - err := b.Core.expiration.Tidy() - if err != nil { - b.Backend.Logger().Error("failed to tidy leases", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -func (b *SystemBackend) invalidate(ctx context.Context, key string) { - /* - if b.Core.logger.IsTrace() { - b.Core.logger.Trace("invalidating key", "key", key) - } - */ - switch { - case strings.HasPrefix(key, policyACLSubPath): - b.Core.stateLock.RLock() - defer b.Core.stateLock.RUnlock() - if b.Core.policyStore != nil { - b.Core.policyStore.invalidate(ctx, strings.TrimPrefix(key, policyACLSubPath), PolicyTypeACL) - } - case strings.HasPrefix(key, tokenSubPath): - b.Core.stateLock.RLock() - defer b.Core.stateLock.RUnlock() - if b.Core.tokenStore != nil { - b.Core.tokenStore.Invalidate(ctx, key) - } - } -} - -func (b *SystemBackend) handlePluginCatalogList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - plugins, err := b.Core.pluginCatalog.List(ctx) - if err != nil { - return nil, err - } - - return logical.ListResponse(plugins), nil -} - -func (b *SystemBackend) handlePluginCatalogUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - - sha256 := d.Get("sha256").(string) - if sha256 == "" { - sha256 = d.Get("sha_256").(string) - if sha256 == "" { - return logical.ErrorResponse("missing SHA-256 value"), nil - } - } - - command := d.Get("command").(string) - if command == "" { - return logical.ErrorResponse("missing command value"), nil - } - - // For backwards compatibility, also accept args as part of command. Don't - // accepts args in both command and args. - args := d.Get("args").([]string) - parts := strings.Split(command, " ") - if len(parts) <= 0 { - return logical.ErrorResponse("missing command value"), nil - } else if len(parts) > 1 && len(args) > 0 { - return logical.ErrorResponse("must not specify args in command and args field"), nil - } else if len(parts) > 1 { - args = parts[1:] - } - - sha256Bytes, err := hex.DecodeString(sha256) - if err != nil { - return logical.ErrorResponse("Could not decode SHA-256 value from Hex"), err - } - - err = b.Core.pluginCatalog.Set(ctx, pluginName, parts[0], args, sha256Bytes) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *SystemBackend) handlePluginCatalogRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - plugin, err := b.Core.pluginCatalog.Get(ctx, pluginName) - if err != nil { - return nil, err - } - if plugin == nil { - return nil, nil - } - - command := "" - if !plugin.Builtin { - command, err = filepath.Rel(b.Core.pluginCatalog.directory, plugin.Command) - if err != nil { - return nil, err - } - } - - data := map[string]interface{}{ - "name": plugin.Name, - "args": plugin.Args, - "command": command, - "sha256": hex.EncodeToString(plugin.Sha256), - "builtin": plugin.Builtin, - } - - return &logical.Response{ - Data: data, - }, nil -} - -func (b *SystemBackend) handlePluginCatalogDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("name").(string) - if pluginName == "" { - return logical.ErrorResponse("missing plugin name"), nil - } - err := b.Core.pluginCatalog.Delete(ctx, pluginName) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (b *SystemBackend) handlePluginReloadUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - pluginName := d.Get("plugin").(string) - pluginMounts := d.Get("mounts").([]string) - - if pluginName != "" && len(pluginMounts) > 0 { - return logical.ErrorResponse("plugin and mounts cannot be set at the same time"), nil - } - if pluginName == "" && len(pluginMounts) == 0 { - return logical.ErrorResponse("plugin or mounts must be provided"), nil - } - - if pluginName != "" { - err := b.Core.reloadMatchingPlugin(ctx, pluginName) - if err != nil { - return nil, err - } - } else if len(pluginMounts) > 0 { - err := b.Core.reloadMatchingPluginMounts(ctx, pluginMounts) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -// handleAuditedHeaderUpdate creates or overwrites a header entry -func (b *SystemBackend) handleAuditedHeaderUpdate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - hmac := d.Get("hmac").(bool) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - err := headerConfig.add(ctx, header, hmac) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleAuditedHeaderDelete deletes the header with the given name -func (b *SystemBackend) handleAuditedHeaderDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - err := headerConfig.remove(ctx, header) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleAuditedHeaderRead returns the header configuration for the given header name -func (b *SystemBackend) handleAuditedHeaderRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - header := d.Get("header").(string) - if header == "" { - return logical.ErrorResponse("missing header name"), nil - } - - headerConfig := b.Core.AuditedHeadersConfig() - settings, ok := headerConfig.Headers[strings.ToLower(header)] - if !ok { - return logical.ErrorResponse("Could not find header in config"), nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - header: settings, - }, - }, nil -} - -// handleAuditedHeadersRead returns the whole audited headers config -func (b *SystemBackend) handleAuditedHeadersRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - headerConfig := b.Core.AuditedHeadersConfig() - - return &logical.Response{ - Data: map[string]interface{}{ - "headers": headerConfig.Headers, - }, - }, nil -} - -// handleCapabilitiesAccessor returns the ACL capabilities of the -// token associated with the given accessor for a given path. -func (b *SystemBackend) handleCapabilitiesAccessor(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - accessor := d.Get("accessor").(string) - if accessor == "" { - return logical.ErrorResponse("missing accessor"), nil - } - - aEntry, err := b.Core.tokenStore.lookupByAccessor(ctx, accessor, false) - if err != nil { - return nil, err - } - - d.Raw["token"] = aEntry.TokenID - return b.handleCapabilities(ctx, req, d) -} - -// handleCapabilities returns the ACL capabilities of the token for a given path -func (b *SystemBackend) handleCapabilities(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - var token string - if strings.HasSuffix(req.Path, "capabilities-self") { - token = req.ClientToken - } else { - tokenRaw, ok := d.Raw["token"] - if ok { - token, _ = tokenRaw.(string) - } - } - if token == "" { - return nil, fmt.Errorf("no token found") - } - - ret := &logical.Response{ - Data: map[string]interface{}{}, - } - - paths := d.Get("paths").([]string) - if len(paths) == 0 { - // Read from the deprecated field - paths = d.Get("path").([]string) - } - - if len(paths) == 0 { - return logical.ErrorResponse("paths must be supplied"), nil - } - - for _, path := range paths { - pathCap, err := b.Core.Capabilities(ctx, token, path) - if err != nil { - if !strings.HasSuffix(req.Path, "capabilities-self") && errwrap.Contains(err, logical.ErrPermissionDenied.Error()) { - return nil, &logical.StatusBadRequest{Err: "invalid token"} - } - return nil, err - } - ret.Data[path] = pathCap - } - - // This is only here for backwards compatibility - if len(paths) == 1 { - ret.Data["capabilities"] = ret.Data[paths[0]] - } - - return ret, nil -} - -// handleRekeyRetrieve returns backed-up, PGP-encrypted unseal keys from a -// rekey operation -func (b *SystemBackend) handleRekeyRetrieve( - ctx context.Context, - req *logical.Request, - data *framework.FieldData, - recovery bool) (*logical.Response, error) { - backup, err := b.Core.RekeyRetrieveBackup(ctx, recovery) - if err != nil { - return nil, errwrap.Wrapf("unable to look up backed-up keys: {{err}}", err) - } - if backup == nil { - return logical.ErrorResponse("no backed-up keys found"), nil - } - - keysB64 := map[string][]string{} - for k, v := range backup.Keys { - for _, j := range v { - currB64Keys := keysB64[k] - if currB64Keys == nil { - currB64Keys = []string{} - } - key, err := hex.DecodeString(j) - if err != nil { - return nil, errwrap.Wrapf("error decoding hex-encoded backup key: {{err}}", err) - } - currB64Keys = append(currB64Keys, base64.StdEncoding.EncodeToString(key)) - keysB64[k] = currB64Keys - } - } - - // Format the status - resp := &logical.Response{ - Data: map[string]interface{}{ - "nonce": backup.Nonce, - "keys": backup.Keys, - "keys_base64": keysB64, - }, - } - - return resp, nil -} - -func (b *SystemBackend) handleRekeyRetrieveBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyRetrieve(ctx, req, data, false) -} - -func (b *SystemBackend) handleRekeyRetrieveRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyRetrieve(ctx, req, data, true) -} - -// handleRekeyDelete deletes backed-up, PGP-encrypted unseal keys from a rekey -// operation -func (b *SystemBackend) handleRekeyDelete( - ctx context.Context, - req *logical.Request, - data *framework.FieldData, - recovery bool) (*logical.Response, error) { - err := b.Core.RekeyDeleteBackup(ctx, recovery) - if err != nil { - return nil, errwrap.Wrapf("error during deletion of backed-up keys: {{err}}", err) - } - - return nil, nil -} - -func (b *SystemBackend) handleRekeyDeleteBarrier(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyDelete(ctx, req, data, false) -} - -func (b *SystemBackend) handleRekeyDeleteRecovery(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRekeyDelete(ctx, req, data, true) -} - -func mountInfo(entry *MountEntry) map[string]interface{} { - info := map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "accessor": entry.Accessor, - "local": entry.Local, - "seal_wrap": entry.SealWrap, - "options": entry.Options, - } - entryConfig := map[string]interface{}{ - "default_lease_ttl": int64(entry.Config.DefaultLeaseTTL.Seconds()), - "max_lease_ttl": int64(entry.Config.MaxLeaseTTL.Seconds()), - "force_no_cache": entry.Config.ForceNoCache, - "plugin_name": entry.Config.PluginName, - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - entryConfig["audit_non_hmac_request_keys"] = rawVal.([]string) - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - entryConfig["audit_non_hmac_response_keys"] = rawVal.([]string) - } - // Even though empty value is valid for ListingVisibility, we can ignore - // this case during mount since there's nothing to unset/hide. - if len(entry.Config.ListingVisibility) > 0 { - entryConfig["listing_visibility"] = entry.Config.ListingVisibility - } - if rawVal, ok := entry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - entryConfig["passthrough_request_headers"] = rawVal.([]string) - } - - info["config"] = entryConfig - - return info -} - -// handleMountTable handles the "mounts" endpoint to provide the mount table -func (b *SystemBackend) handleMountTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.Core.mountsLock.RLock() - defer b.Core.mountsLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - - for _, entry := range b.Core.mounts.Entries { - // Populate mount info - info := mountInfo(entry) - resp.Data[entry.Path] = info - } - - return resp, nil -} - -// handleMount is used to mount a new path -func (b *SystemBackend) handleMount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - logicalType := data.Get("type").(string) - description := data.Get("description").(string) - pluginName := data.Get("plugin_name").(string) - sealWrap := data.Get("seal_wrap").(bool) - options := data.Get("options").(map[string]string) - - var config MountConfig - var apiConfig APIMountConfig - - configMap := data.Get("config").(map[string]interface{}) - if configMap != nil && len(configMap) != 0 { - err := mapstructure.Decode(configMap, &apiConfig) - if err != nil { - return logical.ErrorResponse( - "unable to convert given mount config information"), - logical.ErrInvalidRequest - } - } - - switch apiConfig.DefaultLeaseTTL { - case "": - case "system": - default: - tmpDef, err := parseutil.ParseDurationSecond(apiConfig.DefaultLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse default TTL of %s: %s", apiConfig.DefaultLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.DefaultLeaseTTL = tmpDef - } - - switch apiConfig.MaxLeaseTTL { - case "": - case "system": - default: - tmpMax, err := parseutil.ParseDurationSecond(apiConfig.MaxLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse max TTL of %s: %s", apiConfig.MaxLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.MaxLeaseTTL = tmpMax - } - - if config.MaxLeaseTTL != 0 && config.DefaultLeaseTTL > config.MaxLeaseTTL { - return logical.ErrorResponse( - "given default lease TTL greater than given max lease TTL"), - logical.ErrInvalidRequest - } - - if config.DefaultLeaseTTL > b.Core.maxLeaseTTL && config.MaxLeaseTTL == 0 { - return logical.ErrorResponse(fmt.Sprintf( - "given default lease TTL greater than system max lease TTL of %d", int(b.Core.maxLeaseTTL.Seconds()))), - logical.ErrInvalidRequest - } - - switch logicalType { - case "": - return logical.ErrorResponse( - "backend type must be specified as a string"), - logical.ErrInvalidRequest - - case "plugin": - // Only set plugin-name if mount is of type plugin, with apiConfig.PluginName - // option taking precedence. - switch { - case apiConfig.PluginName != "": - config.PluginName = apiConfig.PluginName - case pluginName != "": - config.PluginName = pluginName - default: - return logical.ErrorResponse( - "plugin_name must be provided for plugin backend"), - logical.ErrInvalidRequest - } - } - - switch logicalType { - case "kv": - case "kv-v1": - // Alias KV v1 - logicalType = "kv" - if options == nil { - options = map[string]string{} - } - options["version"] = "1" - - case "kv-v2": - // Alias KV v2 - logicalType = "kv" - if options == nil { - options = map[string]string{} - } - options["version"] = "2" - - default: - if options != nil && options["version"] != "" { - return logical.ErrorResponse(fmt.Sprintf( - "secrets engine %q does not allow setting a version", logicalType)), - logical.ErrInvalidRequest - } - } - - // Copy over the force no cache if set - if apiConfig.ForceNoCache { - config.ForceNoCache = true - } - - if err := checkListingVisibility(apiConfig.ListingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", apiConfig.ListingVisibility)), nil - } - config.ListingVisibility = apiConfig.ListingVisibility - - if len(apiConfig.AuditNonHMACRequestKeys) > 0 { - config.AuditNonHMACRequestKeys = apiConfig.AuditNonHMACRequestKeys - } - if len(apiConfig.AuditNonHMACResponseKeys) > 0 { - config.AuditNonHMACResponseKeys = apiConfig.AuditNonHMACResponseKeys - } - if len(apiConfig.PassthroughRequestHeaders) > 0 { - config.PassthroughRequestHeaders = apiConfig.PassthroughRequestHeaders - } - - // Create the mount entry - me := &MountEntry{ - Table: mountTableType, - Path: path, - Type: logicalType, - Description: description, - Config: config, - Local: local, - SealWrap: sealWrap, - Options: options, - } - - // Attempt mount - if err := b.Core.mount(ctx, me); err != nil { - b.Backend.Logger().Error("mount failed", "path", me.Path, "error", err) - return handleError(err) - } - - return nil, nil -} - -// used to intercept an HTTPCodedError so it goes back to callee -func handleError( - err error) (*logical.Response, error) { - if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return logical.ErrorResponse(err.Error()), err - } - switch err.(type) { - case logical.HTTPCodedError: - return logical.ErrorResponse(err.Error()), err - default: - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } -} - -// Performs a similar function to handleError, but upon seeing a ReadOnlyError -// will actually strip it out to prevent forwarding -func handleErrorNoReadOnlyForward( - err error) (*logical.Response, error) { - if strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - return nil, fmt.Errorf("operation could not be completed as storage is read-only") - } - switch err.(type) { - case logical.HTTPCodedError: - return logical.ErrorResponse(err.Error()), err - default: - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } -} - -// handleUnmount is used to unmount a path -func (b *SystemBackend) handleUnmount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - repState := b.Core.ReplicationState() - entry := b.Core.router.MatchingMountEntry(path) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot unmount a non-local mount on a replication secondary"), nil - } - - // We return success when the mount does not exists to not expose if the - // mount existed or not - match := b.Core.router.MatchingMount(path) - if match == "" || path != match { - return nil, nil - } - - // Attempt unmount - if err := b.Core.unmount(ctx, path); err != nil { - b.Backend.Logger().Error("unmount failed", "path", path, "error", err) - return handleError(err) - } - - return nil, nil -} - -// handleRemount is used to remount a path -func (b *SystemBackend) handleRemount(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - // Get the paths - fromPath := data.Get("from").(string) - toPath := data.Get("to").(string) - if fromPath == "" || toPath == "" { - return logical.ErrorResponse( - "both 'from' and 'to' path must be specified as a string"), - logical.ErrInvalidRequest - } - - fromPath = sanitizeMountPath(fromPath) - toPath = sanitizeMountPath(toPath) - - entry := b.Core.router.MatchingMountEntry(fromPath) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot remount a non-local mount on a replication secondary"), nil - } - - // Attempt remount - if err := b.Core.remount(ctx, fromPath, toPath); err != nil { - b.Backend.Logger().Error("remount failed", "from_path", fromPath, "to_path", toPath, "error", err) - return handleError(err) - } - - return nil, nil -} - -// handleAuthTuneRead is used to get config settings on a auth path -func (b *SystemBackend) handleAuthTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse( - "path must be specified as a string"), - logical.ErrInvalidRequest - } - return b.handleTuneReadCommon("auth/" + path) -} - -// handleMountTuneRead is used to get config settings on a backend -func (b *SystemBackend) handleMountTuneRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse( - "path must be specified as a string"), - logical.ErrInvalidRequest - } - - // This call will read both logical backend's configuration as well as auth methods'. - // Retaining this behavior for backward compatibility. If this behavior is not desired, - // an error can be returned if path has a prefix of "auth/". - return b.handleTuneReadCommon(path) -} - -// handleTuneReadCommon returns the config settings of a path -func (b *SystemBackend) handleTuneReadCommon(path string) (*logical.Response, error) { - path = sanitizeMountPath(path) - - sysView := b.Core.router.MatchingSystemView(path) - if sysView == nil { - b.Backend.Logger().Error("cannot fetch sysview", "path", path) - return handleError(fmt.Errorf("sys: cannot fetch sysview for path %q", path)) - } - - mountEntry := b.Core.router.MatchingMountEntry(path) - if mountEntry == nil { - b.Backend.Logger().Error("cannot fetch mount entry", "path", path) - return handleError(fmt.Errorf("sys: cannot fetch mount entry for path %q", path)) - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "default_lease_ttl": int(sysView.DefaultLeaseTTL().Seconds()), - "max_lease_ttl": int(sysView.MaxLeaseTTL().Seconds()), - "force_no_cache": mountEntry.Config.ForceNoCache, - }, - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - resp.Data["audit_non_hmac_request_keys"] = rawVal.([]string) - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - resp.Data["audit_non_hmac_response_keys"] = rawVal.([]string) - } - - if len(mountEntry.Config.ListingVisibility) > 0 { - resp.Data["listing_visibility"] = mountEntry.Config.ListingVisibility - } - - if rawVal, ok := mountEntry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - resp.Data["passthrough_request_headers"] = rawVal.([]string) - } - - if len(mountEntry.Options) > 0 { - resp.Data["options"] = mountEntry.Options - } - - return resp, nil -} - -// handleAuthTuneWrite is used to set config settings on an auth path -func (b *SystemBackend) handleAuthTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse("path must be specified as a string"), - logical.ErrInvalidRequest - } - return b.handleTuneWriteCommon(ctx, "auth/"+path, data) -} - -// handleMountTuneWrite is used to set config settings on a backend -func (b *SystemBackend) handleMountTuneWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path == "" { - return logical.ErrorResponse("path must be specified as a string"), - logical.ErrInvalidRequest - } - // This call will write both logical backend's configuration as well as auth methods'. - // Retaining this behavior for backward compatibility. If this behavior is not desired, - // an error can be returned if path has a prefix of "auth/". - return b.handleTuneWriteCommon(ctx, path, data) -} - -// handleTuneWriteCommon is used to set config settings on a path -func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - path = sanitizeMountPath(path) - - // Prevent protected paths from being changed - for _, p := range untunableMounts { - if strings.HasPrefix(path, p) { - b.Backend.Logger().Error("cannot tune this mount", "path", path) - return handleError(fmt.Errorf("cannot tune %q", path)) - } - } - - mountEntry := b.Core.router.MatchingMountEntry(path) - if mountEntry == nil { - b.Backend.Logger().Error("tune failed: no mount entry found", "path", path) - return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) - } - if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil - } - - var lock *sync.RWMutex - switch { - case strings.HasPrefix(path, credentialRoutePrefix): - lock = &b.Core.authLock - default: - lock = &b.Core.mountsLock - } - - lock.Lock() - defer lock.Unlock() - - // Check again after grabbing the lock - mountEntry = b.Core.router.MatchingMountEntry(path) - if mountEntry == nil { - b.Backend.Logger().Error("tune failed: no mount entry found", "path", path) - return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path)) - } - if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot tune a non-local mount on a replication secondary"), nil - } - - // Timing configuration parameters - { - var newDefault, newMax time.Duration - defTTL := data.Get("default_lease_ttl").(string) - switch defTTL { - case "": - newDefault = mountEntry.Config.DefaultLeaseTTL - case "system": - newDefault = time.Duration(0) - default: - tmpDef, err := parseutil.ParseDurationSecond(defTTL) - if err != nil { - return handleError(err) - } - newDefault = tmpDef - } - - maxTTL := data.Get("max_lease_ttl").(string) - switch maxTTL { - case "": - newMax = mountEntry.Config.MaxLeaseTTL - case "system": - newMax = time.Duration(0) - default: - tmpMax, err := parseutil.ParseDurationSecond(maxTTL) - if err != nil { - return handleError(err) - } - newMax = tmpMax - } - - if newDefault != mountEntry.Config.DefaultLeaseTTL || - newMax != mountEntry.Config.MaxLeaseTTL { - - if err := b.tuneMountTTLs(ctx, path, mountEntry, newDefault, newMax); err != nil { - b.Backend.Logger().Error("tuning failed", "path", path, "error", err) - return handleError(err) - } - } - } - - if rawVal, ok := data.GetOk("description"); ok { - description := rawVal.(string) - - oldDesc := mountEntry.Description - mountEntry.Description = description - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Description = oldDesc - return handleError(err) - } - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of description successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("audit_non_hmac_request_keys"); ok { - auditNonHMACRequestKeys := rawVal.([]string) - - oldVal := mountEntry.Config.AuditNonHMACRequestKeys - mountEntry.Config.AuditNonHMACRequestKeys = auditNonHMACRequestKeys - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.AuditNonHMACRequestKeys = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of audit_non_hmac_request_keys successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("audit_non_hmac_response_keys"); ok { - auditNonHMACResponseKeys := rawVal.([]string) - - oldVal := mountEntry.Config.AuditNonHMACResponseKeys - mountEntry.Config.AuditNonHMACResponseKeys = auditNonHMACResponseKeys - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.AuditNonHMACResponseKeys = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of audit_non_hmac_response_keys successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("listing_visibility"); ok { - lvString := rawVal.(string) - listingVisibility := ListingVisibilityType(lvString) - - if err := checkListingVisibility(listingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", listingVisibility)), nil - } - - oldVal := mountEntry.Config.ListingVisibility - mountEntry.Config.ListingVisibility = listingVisibility - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.ListingVisibility = oldVal - return handleError(err) - } - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of listing_visibility successful", "path", path) - } - } - - if rawVal, ok := data.GetOk("passthrough_request_headers"); ok { - headers := rawVal.([]string) - - oldVal := mountEntry.Config.PassthroughRequestHeaders - mountEntry.Config.PassthroughRequestHeaders = headers - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Config.PassthroughRequestHeaders = oldVal - return handleError(err) - } - - mountEntry.SyncCache() - - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of passthrough_request_headers successful", "path", path) - } - } - - var err error - var resp *logical.Response - var options map[string]string - if optionsRaw, ok := data.GetOk("options"); ok { - options = optionsRaw.(map[string]string) - } - if len(options) > 0 { - b.Core.logger.Info("mount tuning of options", "path", path, "options", options) - - var changed bool - var numBuiltIn int - if v, ok := options["version"]; ok { - changed = true - numBuiltIn++ - // Special case to make sure we can not disable versioning once it's - // enabled. If the vkv backend suports downgrading this can be removed. - meVersion, err := parseutil.ParseInt(mountEntry.Options["version"]) - if err != nil { - return nil, errwrap.Wrapf("unable to parse mount entry: {{err}}", err) - } - optVersion, err := parseutil.ParseInt(v) - if err != nil { - return handleError(errwrap.Wrapf("unable to parse options: {{err}}", err)) - } - if meVersion > optVersion { - return logical.ErrorResponse(fmt.Sprintf("cannot downgrade mount from version %d", meVersion)), logical.ErrInvalidRequest - } - if meVersion < optVersion { - resp = &logical.Response{} - resp.AddWarning(fmt.Sprintf("Upgrading mount from version %d to version %d. This mount will be unavailable for a brief period and will resume service shortly.", meVersion, optVersion)) - } - } - if options != nil { - // For anything we don't recognize and provide special handling, - // always write - if len(options) > numBuiltIn { - changed = true - } - } - - if changed { - oldVal := mountEntry.Options - mountEntry.Options = options - // Update the mount table - switch { - case strings.HasPrefix(path, "auth/"): - err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local) - } - if err != nil { - mountEntry.Options = oldVal - return handleError(err) - } - - // Reload the backend to kick off the upgrade process. - b.Core.reloadBackendCommon(ctx, mountEntry, strings.HasPrefix(path, credentialRoutePrefix)) - } - } - - return resp, nil -} - -// handleLease is use to view the metadata for a given LeaseID -func (b *SystemBackend) handleLeaseLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - - leaseTimes, err := b.Core.expiration.FetchLeaseTimes(ctx, leaseID) - if err != nil { - b.Backend.Logger().Error("error retrieving lease", "lease_id", leaseID, "error", err) - return handleError(err) - } - if leaseTimes == nil { - return logical.ErrorResponse("invalid lease"), logical.ErrInvalidRequest - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "id": leaseID, - "issue_time": leaseTimes.IssueTime, - "expire_time": nil, - "last_renewal": nil, - "ttl": int64(0), - }, - } - renewable, _ := leaseTimes.renewable() - resp.Data["renewable"] = renewable - - if !leaseTimes.LastRenewalTime.IsZero() { - resp.Data["last_renewal"] = leaseTimes.LastRenewalTime - } - if !leaseTimes.ExpireTime.IsZero() { - resp.Data["expire_time"] = leaseTimes.ExpireTime - resp.Data["ttl"] = leaseTimes.ttl() - } - return resp, nil -} - -func (b *SystemBackend) handleLeaseLookupList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - prefix := data.Get("prefix").(string) - if prefix != "" && !strings.HasSuffix(prefix, "/") { - prefix = prefix + "/" - } - - keys, err := b.Core.expiration.idView.List(ctx, prefix) - if err != nil { - b.Backend.Logger().Error("error listing leases", "prefix", prefix, "error", err) - return handleErrorNoReadOnlyForward(err) - } - return logical.ListResponse(keys), nil -} - -// handleRenew is used to renew a lease with a given LeaseID -func (b *SystemBackend) handleRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get all the options - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - leaseID = data.Get("url_lease_id").(string) - } - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - incrementRaw := data.Get("increment").(int) - - // Convert the increment - increment := time.Duration(incrementRaw) * time.Second - - // Invoke the expiration manager directly - resp, err := b.Core.expiration.Renew(ctx, leaseID, increment) - if err != nil { - b.Backend.Logger().Error("lease renewal failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - return resp, err -} - -// handleRevoke is used to revoke a given LeaseID -func (b *SystemBackend) handleRevoke(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get all the options - leaseID := data.Get("lease_id").(string) - if leaseID == "" { - leaseID = data.Get("url_lease_id").(string) - } - if leaseID == "" { - return logical.ErrorResponse("lease_id must be specified"), - logical.ErrInvalidRequest - } - - if data.Get("sync").(bool) { - // Invoke the expiration manager directly - if err := b.Core.expiration.Revoke(b.Core.activeContext, leaseID); err != nil { - b.Backend.Logger().Error("lease revocation failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - return nil, nil - } - - if err := b.Core.expiration.LazyRevoke(b.Core.activeContext, leaseID); err != nil { - b.Backend.Logger().Error("lease revocation failed", "lease_id", leaseID, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - return logical.RespondWithStatusCode(nil, nil, http.StatusAccepted) -} - -// handleRevokePrefix is used to revoke a prefix with many LeaseIDs -func (b *SystemBackend) handleRevokePrefix(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRevokePrefixCommon(ctx, req, data, false, data.Get("sync").(bool)) -} - -// handleRevokeForce is used to revoke a prefix with many LeaseIDs, ignoring errors -func (b *SystemBackend) handleRevokeForce(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - return b.handleRevokePrefixCommon(ctx, req, data, true, true) -} - -// handleRevokePrefixCommon is used to revoke a prefix with many LeaseIDs -func (b *SystemBackend) handleRevokePrefixCommon(ctx context.Context, - req *logical.Request, data *framework.FieldData, force, sync bool) (*logical.Response, error) { - // Get all the options - prefix := data.Get("prefix").(string) - - // Invoke the expiration manager directly - var err error - if force { - err = b.Core.expiration.RevokeForce(b.Core.activeContext, prefix) - } else { - err = b.Core.expiration.RevokePrefix(b.Core.activeContext, prefix, sync) - } - if err != nil { - b.Backend.Logger().Error("revoke prefix failed", "prefix", prefix, "error", err) - return handleErrorNoReadOnlyForward(err) - } - - if sync { - return nil, nil - } - - return logical.RespondWithStatusCode(nil, nil, http.StatusAccepted) -} - -// handleAuthTable handles the "auth" endpoint to provide the auth table -func (b *SystemBackend) handleAuthTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.Core.authLock.RLock() - defer b.Core.authLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - for _, entry := range b.Core.auth.Entries { - info := map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "accessor": entry.Accessor, - "local": entry.Local, - "seal_wrap": entry.SealWrap, - "options": entry.Options, - } - entryConfig := map[string]interface{}{ - "default_lease_ttl": int64(entry.Config.DefaultLeaseTTL.Seconds()), - "max_lease_ttl": int64(entry.Config.MaxLeaseTTL.Seconds()), - "plugin_name": entry.Config.PluginName, - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - entryConfig["audit_non_hmac_request_keys"] = rawVal.([]string) - } - if rawVal, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - entryConfig["audit_non_hmac_response_keys"] = rawVal.([]string) - } - // Even though empty value is valid for ListingVisibility, we can ignore - // this case during mount since there's nothing to unset/hide. - if len(entry.Config.ListingVisibility) > 0 { - entryConfig["listing_visibility"] = entry.Config.ListingVisibility - } - if rawVal, ok := entry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - entryConfig["passthrough_request_headers"] = rawVal.([]string) - } - - info["config"] = entryConfig - resp.Data[entry.Path] = info - } - return resp, nil -} - -// handleEnableAuth is used to enable a new credential backend -func (b *SystemBackend) handleEnableAuth(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - path = sanitizeMountPath(path) - logicalType := data.Get("type").(string) - description := data.Get("description").(string) - pluginName := data.Get("plugin_name").(string) - sealWrap := data.Get("seal_wrap").(bool) - options := data.Get("options").(map[string]string) - - var config MountConfig - var apiConfig APIMountConfig - - configMap := data.Get("config").(map[string]interface{}) - if configMap != nil && len(configMap) != 0 { - err := mapstructure.Decode(configMap, &apiConfig) - if err != nil { - return logical.ErrorResponse( - "unable to convert given auth config information"), - logical.ErrInvalidRequest - } - } - - switch apiConfig.DefaultLeaseTTL { - case "": - case "system": - default: - tmpDef, err := parseutil.ParseDurationSecond(apiConfig.DefaultLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse default TTL of %s: %s", apiConfig.DefaultLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.DefaultLeaseTTL = tmpDef - } - - switch apiConfig.MaxLeaseTTL { - case "": - case "system": - default: - tmpMax, err := parseutil.ParseDurationSecond(apiConfig.MaxLeaseTTL) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "unable to parse max TTL of %s: %s", apiConfig.MaxLeaseTTL, err)), - logical.ErrInvalidRequest - } - config.MaxLeaseTTL = tmpMax - } - - if config.MaxLeaseTTL != 0 && config.DefaultLeaseTTL > config.MaxLeaseTTL { - return logical.ErrorResponse( - "given default lease TTL greater than given max lease TTL"), - logical.ErrInvalidRequest - } - - if config.DefaultLeaseTTL > b.Core.maxLeaseTTL && config.MaxLeaseTTL == 0 { - return logical.ErrorResponse(fmt.Sprintf( - "given default lease TTL greater than system max lease TTL of %d", int(b.Core.maxLeaseTTL.Seconds()))), - logical.ErrInvalidRequest - } - - switch logicalType { - case "": - return logical.ErrorResponse( - "backend type must be specified as a string"), - logical.ErrInvalidRequest - - case "plugin": - // Only set plugin name if mount is of type plugin, with apiConfig.PluginName - // option taking precedence. - switch { - case apiConfig.PluginName != "": - config.PluginName = apiConfig.PluginName - case pluginName != "": - config.PluginName = pluginName - default: - return logical.ErrorResponse( - "plugin_name must be provided for plugin backend"), - logical.ErrInvalidRequest - } - } - - if options != nil && options["version"] != "" { - return logical.ErrorResponse(fmt.Sprintf( - "auth method %q does not allow setting a version", logicalType)), - logical.ErrInvalidRequest - } - - if err := checkListingVisibility(apiConfig.ListingVisibility); err != nil { - return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", apiConfig.ListingVisibility)), nil - } - config.ListingVisibility = apiConfig.ListingVisibility - - if len(apiConfig.AuditNonHMACRequestKeys) > 0 { - config.AuditNonHMACRequestKeys = apiConfig.AuditNonHMACRequestKeys - } - if len(apiConfig.AuditNonHMACResponseKeys) > 0 { - config.AuditNonHMACResponseKeys = apiConfig.AuditNonHMACResponseKeys - } - if len(apiConfig.PassthroughRequestHeaders) > 0 { - config.PassthroughRequestHeaders = apiConfig.PassthroughRequestHeaders - } - - // Create the mount entry - me := &MountEntry{ - Table: credentialTableType, - Path: path, - Type: logicalType, - Description: description, - Config: config, - Local: local, - SealWrap: sealWrap, - Options: options, - } - - // Attempt enabling - if err := b.Core.enableCredential(ctx, me); err != nil { - b.Backend.Logger().Error("enable auth mount failed", "path", me.Path, "error", err) - return handleError(err) - } - return nil, nil -} - -// handleDisableAuth is used to disable a credential backend -func (b *SystemBackend) handleDisableAuth(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - path = sanitizeMountPath(path) - - fullPath := credentialRoutePrefix + path - - repState := b.Core.ReplicationState() - entry := b.Core.router.MatchingMountEntry(fullPath) - if entry != nil && !entry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot unmount a non-local mount on a replication secondary"), nil - } - - // We return success when the mount does not exists to not expose if the - // mount existed or not - match := b.Core.router.MatchingMount(fullPath) - if match == "" || fullPath != match { - return nil, nil - } - - // Attempt disable - if err := b.Core.disableCredential(ctx, path); err != nil { - b.Backend.Logger().Error("disable auth mount failed", "path", path, "error", err) - return handleError(err) - } - return nil, nil -} - -// handlePoliciesList handles /sys/policy/ and /sys/policies/ endpoints to provide the enabled policies -func (b *SystemBackend) handlePoliciesList(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - policies, err := b.Core.policyStore.ListPolicies(ctx, policyType) - if err != nil { - return nil, err - } - - switch policyType { - case PolicyTypeACL: - // Add the special "root" policy if not egp - policies = append(policies, "root") - resp := logical.ListResponse(policies) - - // If the request is from sys/policy/ we handle backwards compatibility - if strings.HasPrefix(req.Path, "policy") { - resp.Data["policies"] = resp.Data["keys"] - } - - return resp, nil - } - - return logical.ErrorResponse("unknown policy type"), nil - } -} - -// handlePoliciesRead handles the "/sys/policy/" and "/sys/policies//" endpoints to read a policy -func (b *SystemBackend) handlePoliciesRead(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - policy, err := b.Core.policyStore.GetPolicy(ctx, name, policyType) - if err != nil { - return handleError(err) - } - - if policy == nil { - return nil, nil - } - - // If the request is from sys/policy/ we handle backwards compatibility - var respDataPolicyName string - if policyType == PolicyTypeACL && strings.HasPrefix(req.Path, "policy") { - respDataPolicyName = "rules" - } else { - respDataPolicyName = "policy" - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "name": policy.Name, - respDataPolicyName: policy.Raw, - }, - } - - return resp, nil - } -} - -// handlePoliciesSet handles the "/sys/policy/" and "/sys/policies//" endpoints to set a policy -func (b *SystemBackend) handlePoliciesSet(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var resp *logical.Response - - policy := &Policy{ - Name: strings.ToLower(data.Get("name").(string)), - Type: policyType, - } - if policy.Name == "" { - return logical.ErrorResponse("policy name must be provided in the URL"), nil - } - - policy.Raw = data.Get("policy").(string) - if policy.Raw == "" && policyType == PolicyTypeACL && strings.HasPrefix(req.Path, "policy") { - policy.Raw = data.Get("rules").(string) - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning("'rules' is deprecated, please use 'policy' instead") - } - if policy.Raw == "" { - return logical.ErrorResponse("'policy' parameter not supplied or empty"), nil - } - - if polBytes, err := base64.StdEncoding.DecodeString(policy.Raw); err == nil { - policy.Raw = string(polBytes) - } - - switch policyType { - case PolicyTypeACL: - p, err := ParseACLPolicy(policy.Raw) - if err != nil { - return handleError(err) - } - policy.Paths = p.Paths - policy.Templated = p.Templated - - default: - return logical.ErrorResponse("unknown policy type"), nil - } - - // Update the policy - if err := b.Core.policyStore.SetPolicy(ctx, policy); err != nil { - return handleError(err) - } - return resp, nil - } -} - -func (b *SystemBackend) handlePoliciesDelete(policyType PolicyType) framework.OperationFunc { - return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("name").(string) - - if err := b.Core.policyStore.DeletePolicy(ctx, name, policyType); err != nil { - return handleError(err) - } - return nil, nil - } -} - -// handleAuditTable handles the "audit" endpoint to provide the audit table -func (b *SystemBackend) handleAuditTable(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - b.Core.auditLock.RLock() - defer b.Core.auditLock.RUnlock() - - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - for _, entry := range b.Core.audit.Entries { - info := map[string]interface{}{ - "path": entry.Path, - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - "local": entry.Local, - } - resp.Data[entry.Path] = info - } - return resp, nil -} - -// handleAuditHash is used to fetch the hash of the given input data with the -// specified audit backend's salt -func (b *SystemBackend) handleAuditHash(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - input := data.Get("input").(string) - if input == "" { - return logical.ErrorResponse("the \"input\" parameter is empty"), nil - } - - path = sanitizeMountPath(path) - - hash, err := b.Core.auditBroker.GetHash(ctx, path, input) - if err != nil { - return logical.ErrorResponse(err.Error()), nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "hash": hash, - }, - }, nil -} - -// handleEnableAudit is used to enable a new audit backend -func (b *SystemBackend) handleEnableAudit(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - - local := data.Get("local").(bool) - if !local && repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot add a non-local mount to a replication secondary"), nil - } - - // Get all the options - path := data.Get("path").(string) - backendType := data.Get("type").(string) - description := data.Get("description").(string) - options := data.Get("options").(map[string]string) - - // Create the mount entry - me := &MountEntry{ - Table: auditTableType, - Path: path, - Type: backendType, - Description: description, - Options: options, - Local: local, - } - - // Attempt enabling - if err := b.Core.enableAudit(ctx, me); err != nil { - b.Backend.Logger().Error("enable audit mount failed", "path", me.Path, "error", err) - return handleError(err) - } - return nil, nil -} - -// handleDisableAudit is used to disable an audit backend -func (b *SystemBackend) handleDisableAudit(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Attempt disable - if existed, err := b.Core.disableAudit(ctx, path); existed && err != nil { - b.Backend.Logger().Error("disable audit mount failed", "path", path, "error", err) - return handleError(err) - } - return nil, nil -} - -func (b *SystemBackend) handleConfigUIHeadersRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - - value, err := b.Core.uiConfig.GetHeader(ctx, header) - if err != nil { - return nil, err - } - if value == "" { - return nil, nil - } - - return &logical.Response{ - Data: map[string]interface{}{ - "value": value, - }, - }, nil -} - -func (b *SystemBackend) handleConfigUIHeadersList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - headers, err := b.Core.uiConfig.HeaderKeys(ctx) - if err != nil { - return nil, err - } - if len(headers) == 0 { - return nil, nil - } - - return logical.ListResponse(headers), nil -} - -func (b *SystemBackend) handleConfigUIHeadersUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - values := data.Get("values").([]string) - if header == "" || len(values) == 0 { - return logical.ErrorResponse("header and values must be specified"), logical.ErrInvalidRequest - } - - lowerHeader := strings.ToLower(header) - if strings.HasPrefix(lowerHeader, "x-vault-") { - return logical.ErrorResponse("X-Vault headers cannot be set"), logical.ErrInvalidRequest - } - - // Translate the list of values to the valid header string - value := http.Header{} - for _, v := range values { - value.Add(header, v) - } - err := b.Core.uiConfig.SetHeader(ctx, header, value.Get(header)) - if err != nil { - return nil, err - } - - // Warn when overriding the CSP - resp := &logical.Response{} - if lowerHeader == "content-security-policy" { - resp.AddWarning("overriding default Content-Security-Policy which is secure by default, proceed with caution") - } - - return resp, nil -} - -func (b *SystemBackend) handleConfigUIHeadersDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - header := data.Get("header").(string) - err := b.Core.uiConfig.DeleteHeader(ctx, header) - if err != nil { - return nil, err - } - return nil, nil -} - -// handleRawRead is used to read directly from the barrier -func (b *SystemBackend) handleRawRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot read '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - entry, err := b.Core.barrier.Get(ctx, path) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - if entry == nil { - return nil, nil - } - - // Run this through the decompression helper to see if it's been compressed. - // If the input contained the compression canary, `outputBytes` will hold - // the decompressed data. If the input was not compressed, then `outputBytes` - // will be nil. - outputBytes, _, err := compressutil.Decompress(entry.Value) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - - // `outputBytes` is nil if the input is uncompressed. In that case set it to the original input. - if outputBytes == nil { - outputBytes = entry.Value - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "value": string(outputBytes), - }, - } - return resp, nil -} - -// handleRawWrite is used to write directly to the barrier -func (b *SystemBackend) handleRawWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot write '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - value := data.Get("value").(string) - entry := &Entry{ - Key: path, - Value: []byte(value), - } - if err := b.Core.barrier.Put(ctx, entry); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - return nil, nil -} - -// handleRawDelete is used to delete directly from the barrier -func (b *SystemBackend) handleRawDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot delete '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - if err := b.Core.barrier.Delete(ctx, path); err != nil { - return handleErrorNoReadOnlyForward(err) - } - return nil, nil -} - -// handleRawList is used to list directly from the barrier -func (b *SystemBackend) handleRawList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - path := data.Get("path").(string) - if path != "" && !strings.HasSuffix(path, "/") { - path = path + "/" - } - - // Prevent access of protected paths - for _, p := range protectedPaths { - if strings.HasPrefix(path, p) { - err := fmt.Sprintf("cannot list '%s'", path) - return logical.ErrorResponse(err), logical.ErrInvalidRequest - } - } - - keys, err := b.Core.barrier.List(ctx, path) - if err != nil { - return handleErrorNoReadOnlyForward(err) - } - return logical.ListResponse(keys), nil -} - -// handleKeyStatus returns status information about the backend key -func (b *SystemBackend) handleKeyStatus(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // Get the key info - info, err := b.Core.barrier.ActiveKeyInfo() - if err != nil { - return nil, err - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "term": info.Term, - "install_time": info.InstallTime.Format(time.RFC3339Nano), - }, - } - return resp, nil -} - -// handleRotate is used to trigger a key rotation -func (b *SystemBackend) handleRotate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - repState := b.Core.ReplicationState() - if repState.HasState(consts.ReplicationPerformanceSecondary) { - return logical.ErrorResponse("cannot rotate on a replication secondary"), nil - } - - // Rotate to the new term - newTerm, err := b.Core.barrier.Rotate(ctx) - if err != nil { - b.Backend.Logger().Error("failed to create new encryption key", "error", err) - return handleError(err) - } - b.Backend.Logger().Info("installed new encryption key") - - // In HA mode, we need to an upgrade path for the standby instances - if b.Core.ha != nil { - // Create the upgrade path to the new term - if err := b.Core.barrier.CreateUpgrade(ctx, newTerm); err != nil { - b.Backend.Logger().Error("failed to create new upgrade", "term", newTerm, "error", err) - } - - // Schedule the destroy of the upgrade path - time.AfterFunc(keyRotateGracePeriod, func() { - if err := b.Core.barrier.DestroyUpgrade(ctx, newTerm); err != nil { - b.Backend.Logger().Error("failed to destroy upgrade", "term", newTerm, "error", err) - } - }) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := b.Core.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(fmt.Sprintf("new-rotation-term-%d", newTerm)), - }); err != nil { - b.Core.logger.Error("error saving keyring canary", "error", err) - return nil, errwrap.Wrapf("failed to save keyring canary: {{err}}", err) - } - - return nil, nil -} - -func (b *SystemBackend) handleWrappingPubkey(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - x, _ := b.Core.wrappingJWTKey.X.MarshalText() - y, _ := b.Core.wrappingJWTKey.Y.MarshalText() - return &logical.Response{ - Data: map[string]interface{}{ - "jwt_x": string(x), - "jwt_y": string(y), - "jwt_curve": corePrivateKeyTypeP521, - }, - }, nil -} - -func (b *SystemBackend) handleWrappingWrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if req.WrapInfo == nil || req.WrapInfo.TTL == 0 { - return logical.ErrorResponse("endpoint requires response wrapping to be used"), logical.ErrInvalidRequest - } - - // N.B.: Do *NOT* allow JWT wrapping tokens to be created through this - // endpoint. JWTs are signed so if we don't allow users to create wrapping - // tokens using them we can ensure that an operator can't spoof a legit JWT - // wrapped token, which makes certain init/rekey/generate-root cases have - // better properties. - req.WrapInfo.Format = "uuid" - - return &logical.Response{ - Data: data.Raw, - }, nil -} - -func (b *SystemBackend) handleWrappingUnwrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // If a third party is unwrapping (rather than the calling token being the - // wrapping token) we detect this so that we can revoke the original - // wrapping token after reading it - var thirdParty bool - - token := data.Get("token").(string) - if token != "" { - thirdParty = true - } else { - token = req.ClientToken - } - - // Get the policies so we can determine if this is a normal response - // wrapping request or a control group token. - // - // We use lookupTainted here because the token might have already been used - // by handleRequest(), this happens when it's a normal response wrapping - // request and the token was provided "first party". We want to inspect the - // token policies but will not use this token entry for anything else. - te, err := b.Core.tokenStore.lookupTainted(ctx, token) - if err != nil { - return nil, err - } - if te == nil { - return nil, errors.New("could not find token") - } - if len(te.Policies) != 1 { - return nil, errors.New("token is not a valid unwrap token") - } - - var response string - switch te.Policies[0] { - case responseWrappingPolicyName: - response, err = b.responseWrappingUnwrap(ctx, token, thirdParty) - } - if err != nil { - var respErr *logical.Response - if len(response) > 0 { - respErr = logical.ErrorResponse(response) - } - - return respErr, err - } - - resp := &logical.Response{ - Data: map[string]interface{}{}, - } - - // Most of the time we want to just send over the marshalled HTTP bytes. - // However there is a sad separate case: if the original response was using - // bare values we need to use those or else what comes back is garbled. - httpResp := &logical.HTTPResponse{} - err = jsonutil.DecodeJSON([]byte(response), httpResp) - if err != nil { - return nil, errwrap.Wrapf("error decoding wrapped response: {{err}}", err) - } - if httpResp.Data != nil && - (httpResp.Data[logical.HTTPStatusCode] != nil || - httpResp.Data[logical.HTTPRawBody] != nil || - httpResp.Data[logical.HTTPContentType] != nil) { - if httpResp.Data[logical.HTTPStatusCode] != nil { - resp.Data[logical.HTTPStatusCode] = httpResp.Data[logical.HTTPStatusCode] - } - if httpResp.Data[logical.HTTPContentType] != nil { - resp.Data[logical.HTTPContentType] = httpResp.Data[logical.HTTPContentType] - } - - rawBody := httpResp.Data[logical.HTTPRawBody] - if rawBody != nil { - // Decode here so that we can audit properly - switch rawBody.(type) { - case string: - // Best effort decoding; if this works, the original value was - // probably a []byte instead of a string, but was marshaled - // when the value was saved, so this restores it as it was - decBytes, err := base64.StdEncoding.DecodeString(rawBody.(string)) - if err == nil { - // We end up with []byte, will not be HMAC'd - resp.Data[logical.HTTPRawBody] = decBytes - } else { - // We end up with string, will be HMAC'd - resp.Data[logical.HTTPRawBody] = rawBody - } - default: - b.Core.Logger().Error("unexpected type of raw body when decoding wrapped token", "type", fmt.Sprintf("%T", rawBody)) - } - - resp.Data[logical.HTTPRawBodyAlreadyJSONDecoded] = true - } - - return resp, nil - } - - if len(response) == 0 { - resp.Data[logical.HTTPStatusCode] = 204 - } else { - resp.Data[logical.HTTPStatusCode] = 200 - resp.Data[logical.HTTPRawBody] = []byte(response) - resp.Data[logical.HTTPContentType] = "application/json" - } - - return resp, nil -} - -// responseWrappingUnwrap will read the stored response in the cubbyhole and -// return the raw HTTP response. -func (b *SystemBackend) responseWrappingUnwrap(ctx context.Context, token string, thirdParty bool) (string, error) { - if thirdParty { - // Use the token to decrement the use count to avoid a second operation on the token. - _, err := b.Core.tokenStore.UseTokenByID(ctx, token) - if err != nil { - return "", errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) - } - - defer b.Core.tokenStore.revokeOrphan(ctx, token) - } - - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/response", - ClientToken: token, - } - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return "", errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return "no information found; wrapping token may be from a previous Vault version", ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp.Error().Error(), nil - } - if cubbyResp.Data == nil { - return "wrapping information was nil; wrapping token may be from a previous Vault version", ErrInternalError - } - - responseRaw := cubbyResp.Data["response"] - if responseRaw == nil { - return "", fmt.Errorf("no response found inside the cubbyhole") - } - response, ok := responseRaw.(string) - if !ok { - return "", fmt.Errorf("could not decode response inside the cubbyhole") - } - - return response, nil -} - -func (b *SystemBackend) handleWrappingLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // This ordering of lookups has been validated already in the wrapping - // validation func, we're just doing this for a safety check - token := data.Get("token").(string) - if token == "" { - token = req.ClientToken - if token == "" { - return logical.ErrorResponse("missing \"token\" value in input"), logical.ErrInvalidRequest - } - } - - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/wrapinfo", - ClientToken: token, - } - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - creationTTLRaw := cubbyResp.Data["creation_ttl"] - creationTime := cubbyResp.Data["creation_time"] - creationPath := cubbyResp.Data["creation_path"] - - resp := &logical.Response{ - Data: map[string]interface{}{}, - } - if creationTTLRaw != nil { - creationTTL, err := creationTTLRaw.(json.Number).Int64() - if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) - } - resp.Data["creation_ttl"] = time.Duration(creationTTL).Seconds() - } - if creationTime != nil { - // This was JSON marshaled so it's already a string in RFC3339 format - resp.Data["creation_time"] = cubbyResp.Data["creation_time"] - } - if creationPath != nil { - resp.Data["creation_path"] = cubbyResp.Data["creation_path"] - } - - return resp, nil -} - -func (b *SystemBackend) handleWrappingRewrap(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - // If a third party is rewrapping (rather than the calling token being the - // wrapping token) we detect this so that we can revoke the original - // wrapping token after reading it. Right now wrapped tokens can't unwrap - // themselves, but in case we change it, this will be ready to do the right - // thing. - var thirdParty bool - - token := data.Get("token").(string) - if token != "" { - thirdParty = true - } else { - token = req.ClientToken - } - - if thirdParty { - // Use the token to decrement the use count to avoid a second operation on the token. - _, err := b.Core.tokenStore.UseTokenByID(ctx, token) - if err != nil { - return nil, errwrap.Wrapf("error decrementing wrapping token's use-count: {{err}}", err) - } - defer b.Core.tokenStore.revokeOrphan(ctx, token) - } - - // Fetch the original TTL - cubbyReq := &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/wrapinfo", - ClientToken: token, - } - cubbyResp, err := b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up wrapping information: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - // Set the creation TTL on the request - creationTTLRaw := cubbyResp.Data["creation_ttl"] - if creationTTLRaw == nil { - return nil, fmt.Errorf("creation_ttl value in wrapping information was nil") - } - creationTTL, err := cubbyResp.Data["creation_ttl"].(json.Number).Int64() - if err != nil { - return nil, errwrap.Wrapf("error reading creation_ttl value from wrapping information: {{err}}", err) - } - - // Get creation_path to return as the response later - creationPathRaw := cubbyResp.Data["creation_path"] - if creationPathRaw == nil { - return nil, fmt.Errorf("creation_path value in wrapping information was nil") - } - creationPath := creationPathRaw.(string) - - // Fetch the original response and return it as the data for the new response - cubbyReq = &logical.Request{ - Operation: logical.ReadOperation, - Path: "cubbyhole/response", - ClientToken: token, - } - cubbyResp, err = b.Core.router.Route(ctx, cubbyReq) - if err != nil { - return nil, errwrap.Wrapf("error looking up response: {{err}}", err) - } - if cubbyResp == nil { - return logical.ErrorResponse("no information found; wrapping token may be from a previous Vault version"), nil - } - if cubbyResp != nil && cubbyResp.IsError() { - return cubbyResp, nil - } - if cubbyResp.Data == nil { - return logical.ErrorResponse("wrapping information was nil; wrapping token may be from a previous Vault version"), nil - } - - response := cubbyResp.Data["response"] - if response == nil { - return nil, fmt.Errorf("no response found inside the cubbyhole") - } - - // Return response in "response"; wrapping code will detect the rewrap and - // slot in instead of nesting - return &logical.Response{ - Data: map[string]interface{}{ - "response": response, - }, - WrapInfo: &wrapping.ResponseWrapInfo{ - TTL: time.Duration(creationTTL), - CreationPath: creationPath, - }, - }, nil -} - -func (b *SystemBackend) pathHashWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - inputB64 := d.Get("input").(string) - format := d.Get("format").(string) - algorithm := d.Get("urlalgorithm").(string) - if algorithm == "" { - algorithm = d.Get("algorithm").(string) - } - - input, err := base64.StdEncoding.DecodeString(inputB64) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("unable to decode input as base64: %s", err)), logical.ErrInvalidRequest - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - var hf hash.Hash - switch algorithm { - case "sha2-224": - hf = sha256.New224() - case "sha2-256": - hf = sha256.New() - case "sha2-384": - hf = sha512.New384() - case "sha2-512": - hf = sha512.New() - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported algorithm %s", algorithm)), nil - } - hf.Write(input) - retBytes := hf.Sum(nil) - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(retBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(retBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "sum": retStr, - }, - } - return resp, nil -} - -func (b *SystemBackend) pathRandomWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - bytes := 0 - var err error - strBytes := d.Get("urlbytes").(string) - if strBytes != "" { - bytes, err = strconv.Atoi(strBytes) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("error parsing url-set byte count: %s", err)), nil - } - } else { - bytes = d.Get("bytes").(int) - } - format := d.Get("format").(string) - - if bytes < 1 { - return logical.ErrorResponse(`"bytes" cannot be less than 1`), nil - } - - switch format { - case "hex": - case "base64": - default: - return logical.ErrorResponse(fmt.Sprintf("unsupported encoding format %s; must be \"hex\" or \"base64\"", format)), nil - } - - randBytes, err := uuid.GenerateRandomBytes(bytes) - if err != nil { - return nil, err - } - - var retStr string - switch format { - case "hex": - retStr = hex.EncodeToString(randBytes) - case "base64": - retStr = base64.StdEncoding.EncodeToString(randBytes) - } - - // Generate the response - resp := &logical.Response{ - Data: map[string]interface{}{ - "random_bytes": retStr, - }, - } - return resp, nil -} - -func hasMountAccess(acl *ACL, path string) bool { - // If an ealier policy is giving us access to the mount path then we can do - // a fast return. - capabilities := acl.Capabilities(path) - if !strutil.StrListContains(capabilities, DenyCapability) { - return true - } - - var aclCapabilitiesGiven bool - walkFn := func(s string, v interface{}) bool { - if v == nil { - return false - } - - perms := v.(*ACLPermissions) - - switch { - case perms.CapabilitiesBitmap&DenyCapabilityInt > 0: - return false - - case perms.CapabilitiesBitmap&CreateCapabilityInt > 0, - perms.CapabilitiesBitmap&DeleteCapabilityInt > 0, - perms.CapabilitiesBitmap&ListCapabilityInt > 0, - perms.CapabilitiesBitmap&ReadCapabilityInt > 0, - perms.CapabilitiesBitmap&SudoCapabilityInt > 0, - perms.CapabilitiesBitmap&UpdateCapabilityInt > 0: - - aclCapabilitiesGiven = true - return true - } - - return false - } - - acl.exactRules.WalkPrefix(path, walkFn) - if !aclCapabilitiesGiven { - acl.globRules.WalkPrefix(path, walkFn) - } - - return aclCapabilitiesGiven -} - -func (b *SystemBackend) pathInternalUIMountsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - resp := &logical.Response{ - Data: make(map[string]interface{}), - } - - secretMounts := make(map[string]interface{}) - authMounts := make(map[string]interface{}) - resp.Data["secret"] = secretMounts - resp.Data["auth"] = authMounts - - var acl *ACL - var isAuthed bool - var err error - if req.ClientToken != "" { - isAuthed = true - - var entity *identity.Entity - var te *logical.TokenEntry - // Load the ACL policies so we can walk the prefix for this mount - acl, te, entity, _, err = b.Core.fetchACLTokenEntryAndEntity(req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return nil, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - } - - hasAccess := func(me *MountEntry) bool { - if me.Config.ListingVisibility == ListingVisibilityUnauth { - return true - } - - if isAuthed { - return hasMountAccess(acl, me.Path) - } - - return false - } - - b.Core.mountsLock.RLock() - for _, entry := range b.Core.mounts.Entries { - if hasAccess(entry) { - if isAuthed { - // If this is an authed request return all the mount info - secretMounts[entry.Path] = mountInfo(entry) - } else { - secretMounts[entry.Path] = map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - } - } - } - } - b.Core.mountsLock.RUnlock() - - b.Core.authLock.RLock() - for _, entry := range b.Core.auth.Entries { - if hasAccess(entry) { - if isAuthed { - // If this is an authed request return all the mount info - authMounts[entry.Path] = mountInfo(entry) - } else { - authMounts[entry.Path] = map[string]interface{}{ - "type": entry.Type, - "description": entry.Description, - "options": entry.Options, - } - } - } - } - b.Core.authLock.RUnlock() - - return resp, nil -} - -func (b *SystemBackend) pathInternalUIMountRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - path := d.Get("path").(string) - if path == "" { - return logical.ErrorResponse("path not set"), logical.ErrInvalidRequest - } - path = sanitizeMountPath(path) - - errResp := logical.ErrorResponse(fmt.Sprintf("Preflight capability check returned 403, please ensure client's policies grant access to path \"%s\"", path)) - - me := b.Core.router.MatchingMountEntry(path) - if me == nil { - // Return a permission denied error here so this path cannot be used to - // brute force a list of mounts. - return errResp, logical.ErrPermissionDenied - } - - resp := &logical.Response{ - Data: mountInfo(me), - } - resp.Data["path"] = me.Path - - // Load the ACL policies so we can walk the prefix for this mount - acl, te, entity, _, err := b.Core.fetchACLTokenEntryAndEntity(req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return errResp, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return nil, logical.ErrPermissionDenied - } - - if !hasMountAccess(acl, me.Path) { - return errResp, logical.ErrPermissionDenied - } - - return resp, nil -} - -func (b *SystemBackend) pathInternalUIResultantACL(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.ClientToken == "" { - // 204 -- no ACL - return nil, nil - } - - acl, te, entity, _, err := b.Core.fetchACLTokenEntryAndEntity(req) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - b.Core.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor", "error", err) - err = logical.ErrPermissionDenied - } - return nil, err - } - - if entity != nil && entity.Disabled { - b.logger.Warn("permission denied as the entity on the token is disabled") - return logical.ErrorResponse(logical.ErrPermissionDenied.Error()), nil - } - if te != nil && te.EntityID != "" && entity == nil { - b.logger.Warn("permission denied as the entity on the token is invalid") - return logical.ErrorResponse(logical.ErrPermissionDenied.Error()), nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "root": false, - }, - } - - if acl.root { - resp.Data["root"] = true - return resp, nil - } - - exact := map[string]interface{}{} - glob := map[string]interface{}{} - - walkFn := func(pt map[string]interface{}, s string, v interface{}) { - if v == nil { - return - } - - perms := v.(*ACLPermissions) - capabilities := []string{} - - if perms.CapabilitiesBitmap&CreateCapabilityInt > 0 { - capabilities = append(capabilities, CreateCapability) - } - if perms.CapabilitiesBitmap&DeleteCapabilityInt > 0 { - capabilities = append(capabilities, DeleteCapability) - } - if perms.CapabilitiesBitmap&ListCapabilityInt > 0 { - capabilities = append(capabilities, ListCapability) - } - if perms.CapabilitiesBitmap&ReadCapabilityInt > 0 { - capabilities = append(capabilities, ReadCapability) - } - if perms.CapabilitiesBitmap&SudoCapabilityInt > 0 { - capabilities = append(capabilities, SudoCapability) - } - if perms.CapabilitiesBitmap&UpdateCapabilityInt > 0 { - capabilities = append(capabilities, UpdateCapability) - } - - // If "deny" is explicitly set or if the path has no capabilities at all, - // set the path capabilities to "deny" - if perms.CapabilitiesBitmap&DenyCapabilityInt > 0 || len(capabilities) == 0 { - capabilities = []string{DenyCapability} - } - - res := map[string]interface{}{} - if len(capabilities) > 0 { - res["capabilities"] = capabilities - } - if perms.MinWrappingTTL != 0 { - res["min_wrapping_ttl"] = int64(perms.MinWrappingTTL.Seconds()) - } - if perms.MaxWrappingTTL != 0 { - res["max_wrapping_ttl"] = int64(perms.MaxWrappingTTL.Seconds()) - } - if len(perms.AllowedParameters) > 0 { - res["allowed_parameters"] = perms.AllowedParameters - } - if len(perms.DeniedParameters) > 0 { - res["denied_parameters"] = perms.DeniedParameters - } - if len(perms.RequiredParameters) > 0 { - res["required_parameters"] = perms.RequiredParameters - } - - pt[s] = res - } - - exactWalkFn := func(s string, v interface{}) bool { - walkFn(exact, s, v) - return false - } - - globWalkFn := func(s string, v interface{}) bool { - walkFn(glob, s, v) - return false - } - - acl.exactRules.Walk(exactWalkFn) - acl.globRules.Walk(globWalkFn) - - resp.Data["exact_paths"] = exact - resp.Data["glob_paths"] = glob - - return resp, nil -} - -func sanitizeMountPath(path string) string { - if !strings.HasSuffix(path, "/") { - path += "/" - } - - if strings.HasPrefix(path, "/") { - path = path[1:] - } - - return path -} - -func checkListingVisibility(visibility ListingVisibilityType) error { - switch visibility { - case ListingVisibilityDefault: - case ListingVisibilityHidden: - case ListingVisibilityUnauth: - default: - return fmt.Errorf("invalid listing visilibity type") - } - - return nil -} - -const sysHelpRoot = ` -The system backend is built-in to Vault and cannot be remounted or -unmounted. It contains the paths that are used to configure Vault itself -as well as perform core operations. -` - -// sysHelp is all the help text for the sys backend. -var sysHelp = map[string][2]string{ - "config/cors": { - "Configures or returns the current configuration of CORS settings.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the configuration of the CORS setting. - - POST / - Sets the comma-separated list of origins that can make cross-origin requests. - - DELETE / - Clears the CORS configuration and disables acceptance of CORS requests. - `, - }, - "config/ui/headers": { - "Configures response headers that should be returned from the UI.", - ` -This path responds to the following HTTP methods. - GET /
- Returns the header value. - POST /
- Sets the header value for the UI. - DELETE /
- Clears the header value for UI. - - LIST / - List the headers configured for the UI. - `, - }, - "init": { - "Initializes or returns the initialization status of the Vault.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the initialization status of the Vault. - - POST / - Initializes a new vault. - `, - }, - "generate-root": { - "Reads, generates, or deletes a root token regeneration process.", - ` -This path responds to multiple HTTP methods which change the behavior. Those -HTTP methods are listed below. - - GET /attempt - Reads the configuration and progress of the current root generation - attempt. - - POST /attempt - Initializes a new root generation attempt. Only a single root generation - attempt can take place at a time. One (and only one) of otp or pgp_key - are required. - - DELETE /attempt - Cancels any in-progress root generation attempt. This clears any - progress made. This must be called to change the OTP or PGP key being - used. - `, - }, - "seal-status": { - "Returns the seal status of the Vault.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the seal status of the Vault. This is an unauthenticated - endpoint. - `, - }, - "seal": { - "Seals the Vault.", - ` -This path responds to the following HTTP methods. - - PUT / - Seals the Vault. - `, - }, - "unseal": { - "Unseals the Vault.", - ` -This path responds to the following HTTP methods. - - PUT / - Unseals the Vault. - `, - }, - "mounts": { - "List the currently mounted backends.", - ` -This path responds to the following HTTP methods. - - GET / - Lists all the mounted secret backends. - - GET / - Get information about the mount at the specified path. - - POST / - Mount a new secret backend to the mount point in the URL. - - POST //tune - Tune configuration parameters for the given mount point. - - DELETE / - Unmount the specified mount point. - `, - }, - - "mount": { - `Mount a new backend at a new path.`, - ` -Mount a backend at a new path. A backend can be mounted multiple times at -multiple paths in order to configure multiple separately configured backends. -Example: you might have an AWS backend for the east coast, and one for the -west coast. - `, - }, - - "mount_path": { - `The path to mount to. Example: "aws/east"`, - "", - }, - - "mount_type": { - `The type of the backend. Example: "passthrough"`, - "", - }, - - "mount_desc": { - `User-friendly description for this mount.`, - "", - }, - - "mount_config": { - `Configuration for this mount, such as default_lease_ttl -and max_lease_ttl.`, - }, - - "mount_local": { - `Mark the mount as a local mount, which is not replicated -and is unaffected by replication.`, - }, - - "mount_plugin_name": { - `Name of the plugin to mount based from the name registered -in the plugin catalog.`, - }, - - "mount_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "seal_wrap": { - `Whether to turn on seal wrapping for the mount.`, - }, - - "tune_default_lease_ttl": { - `The default lease TTL for this mount.`, - }, - - "tune_max_lease_ttl": { - `The max lease TTL for this mount.`, - }, - - "tune_audit_non_hmac_request_keys": { - `The list of keys in the request data object that will not be HMAC'ed by audit devices.`, - }, - - "tune_audit_non_hmac_response_keys": { - `The list of keys in the response data object that will not be HMAC'ed by audit devices.`, - }, - - "tune_mount_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "remount": { - "Move the mount point of an already-mounted backend.", - ` -This path responds to the following HTTP methods. - - POST /sys/remount - Changes the mount point of an already-mounted backend. - `, - }, - - "auth_tune": { - "Tune the configuration parameters for an auth path.", - `Read and write the 'default-lease-ttl' and 'max-lease-ttl' values of -the auth path.`, - }, - - "mount_tune": { - "Tune backend configuration parameters for this mount.", - `Read and write the 'default-lease-ttl' and 'max-lease-ttl' values of -the mount.`, - }, - - "renew": { - "Renew a lease on a secret", - ` -When a secret is read, it may optionally include a lease interval -and a boolean indicating if renew is possible. For secrets that support -lease renewal, this endpoint is used to extend the validity of the -lease and to prevent an automatic revocation. - `, - }, - - "lease_id": { - "The lease identifier to renew. This is included with a lease.", - "", - }, - - "increment": { - "The desired increment in seconds to the lease", - "", - }, - - "revoke": { - "Revoke a leased secret immediately", - ` -When a secret is generated with a lease, it is automatically revoked -at the end of the lease period if not renewed. However, in some cases -you may want to force an immediate revocation. This endpoint can be -used to revoke the secret with the given Lease ID. - `, - }, - - "revoke-sync": { - "Whether or not to perform the revocation synchronously", - ` -If false, the call will return immediately and revocation will be queued; if it -fails, Vault will keep trying. If true, if the revocation fails, Vault will not -automatically try again and will return an error. For revoke-prefix, this -setting will apply to all leases being revoked. For revoke-force, since errors -are ignored, this setting is not supported. -`, - }, - - "revoke-prefix": { - "Revoke all secrets generated in a given prefix", - ` -Revokes all the secrets generated under a given mount prefix. As -an example, "prod/aws/" might be the AWS logical backend, and due to -a change in the "ops" policy, we may want to invalidate all the secrets -generated. We can do a revoke prefix at "prod/aws/ops" to revoke all -the ops secrets. This does a prefix match on the Lease IDs and revokes -all matching leases. - `, - }, - - "revoke-prefix-path": { - `The path to revoke keys under. Example: "prod/aws/ops"`, - "", - }, - - "revoke-force": { - "Revoke all secrets generated in a given prefix, ignoring errors.", - ` -See the path help for 'revoke-prefix'; this behaves the same, except that it -ignores errors encountered during revocation. This can be used in certain -recovery situations; for instance, when you want to unmount a backend, but it -is impossible to fix revocation errors and these errors prevent the unmount -from proceeding. This is a DANGEROUS operation as it removes Vault's oversight -of external secrets. Access to this prefix should be tightly controlled. - `, - }, - - "revoke-force-path": { - `The path to revoke keys under. Example: "prod/aws/ops"`, - "", - }, - - "auth-table": { - "List the currently enabled credential backends.", - ` -This path responds to the following HTTP methods. - - GET / - List the currently enabled credential backends: the name, the type of - the backend, and a user friendly description of the purpose for the - credential backend. - - POST / - Enable a new auth method. - - DELETE / - Disable the auth method at the given mount point. - `, - }, - - "auth": { - `Enable a new credential backend with a name.`, - ` -Enable a credential mechanism at a new path. A backend can be mounted multiple times at -multiple paths in order to configure multiple separately configured backends. -Example: you might have an OAuth backend for GitHub, and one for Google Apps. - `, - }, - - "auth_path": { - `The path to mount to. Cannot be delimited. Example: "user"`, - "", - }, - - "auth_type": { - `The type of the backend. Example: "userpass"`, - "", - }, - - "auth_desc": { - `User-friendly description for this credential backend.`, - "", - }, - - "auth_config": { - `Configuration for this mount, such as plugin_name.`, - }, - - "auth_plugin": { - `Name of the auth plugin to use based from the name in the plugin catalog.`, - "", - }, - - "auth_options": { - `The options to pass into the backend. Should be a json object with string keys and values.`, - }, - - "policy-list": { - `List the configured access control policies.`, - ` -This path responds to the following HTTP methods. - - GET / - List the names of the configured access control policies. - - GET / - Retrieve the rules for the named policy. - - PUT / - Add or update a policy. - - DELETE / - Delete the policy with the given name. - `, - }, - - "policy": { - `Read, Modify, or Delete an access control policy.`, - ` -Read the rules of an existing policy, create or update the rules of a policy, -or delete a policy. - `, - }, - - "policy-name": { - `The name of the policy. Example: "ops"`, - "", - }, - - "policy-rules": { - `The rules of the policy. Either given in HCL or JSON format.`, - "", - }, - - "audit-hash": { - "The hash of the given string via the given audit backend", - "", - }, - - "audit-table": { - "List the currently enabled audit backends.", - ` -This path responds to the following HTTP methods. - - GET / - List the currently enabled audit backends. - - PUT / - Enable an audit backend at the given path. - - DELETE / - Disable the given audit backend. - `, - }, - - "audit_path": { - `The name of the backend. Cannot be delimited. Example: "mysql"`, - "", - }, - - "audit_type": { - `The type of the backend. Example: "mysql"`, - "", - }, - - "audit_desc": { - `User-friendly description for this audit backend.`, - "", - }, - - "audit_opts": { - `Configuration options for the audit backend.`, - "", - }, - - "audit": { - `Enable or disable audit backends.`, - ` -Enable a new audit backend or disable an existing backend. - `, - }, - - "key-status": { - "Provides information about the backend encryption key.", - ` - Provides the current backend encryption key term and installation time. - `, - }, - - "rotate": { - "Rotates the backend encryption key used to persist data.", - ` - Rotate generates a new encryption key which is used to encrypt all - data going to the storage backend. The old encryption keys are kept so - that data encrypted using those keys can still be decrypted. - `, - }, - - "rekey_backup": { - "Allows fetching or deleting the backup of the rotated unseal keys.", - "", - }, - - "capabilities": { - "Fetches the capabilities of the given token on the given path.", - `Returns the capabilities of the given token on the path. - The path will be searched for a path match in all the policies associated with the token.`, - }, - - "capabilities_self": { - "Fetches the capabilities of the given token on the given path.", - `Returns the capabilities of the client token on the path. - The path will be searched for a path match in all the policies associated with the client token.`, - }, - - "capabilities_accessor": { - "Fetches the capabilities of the token associated with the given token, on the given path.", - `When there is no access to the token, token accessor can be used to fetch the token's capabilities - on a given path.`, - }, - - "tidy_leases": { - `This endpoint performs cleanup tasks that can be run if certain error -conditions have occurred.`, - `This endpoint performs cleanup tasks that can be run to clean up the -lease entries after certain error conditions. Usually running this is not -necessary, and is only required if upgrade notes or support personnel suggest -it.`, - }, - - "wrap": { - "Response-wraps an arbitrary JSON object.", - `Round trips the given input data into a response-wrapped token.`, - }, - - "wrappubkey": { - "Returns pubkeys used in some wrapping formats.", - "Returns pubkeys used in some wrapping formats.", - }, - - "unwrap": { - "Unwraps a response-wrapped token.", - `Unwraps a response-wrapped token. Unlike simply reading from cubbyhole/response, - this provides additional validation on the token, and rather than a JSON-escaped - string, the returned response is the exact same as the contained wrapped response.`, - }, - - "wraplookup": { - "Looks up the properties of a response-wrapped token.", - `Returns the creation TTL and creation time of a response-wrapped token.`, - }, - - "rewrap": { - "Rotates a response-wrapped token.", - `Rotates a response-wrapped token; the output is a new token with the same - response wrapped inside and the same creation TTL. The original token is revoked.`, - }, - "audited-headers-name": { - "Configures the headers sent to the audit logs.", - ` -This path responds to the following HTTP methods. - - GET / - Returns the setting for the header with the given name. - - POST / - Enable auditing of the given header. - - DELETE / - Disable auditing of the given header. - `, - }, - "audited-headers": { - "Lists the headers configured to be audited.", - `Returns a list of headers that have been configured to be audited.`, - }, - "plugin-catalog": { - "Configures the plugins known to vault", - ` -This path responds to the following HTTP methods. - LIST / - Returns a list of names of configured plugins. - - GET / - Retrieve the metadata for the named plugin. - - PUT / - Add or update plugin. - - DELETE / - Delete the plugin with the given name. - `, - }, - "plugin-catalog_name": { - "The name of the plugin", - "", - }, - "plugin-catalog_sha-256": { - `The SHA256 sum of the executable used in the -command field. This should be HEX encoded.`, - "", - }, - "plugin-catalog_command": { - `The command used to start the plugin. The -executable defined in this command must exist in vault's -plugin directory.`, - "", - }, - "plugin-catalog_args": { - `The args passed to plugin command.`, - "", - }, - "leases": { - `View or list lease metadata.`, - ` -This path responds to the following HTTP methods. - - PUT / - Retrieve the metadata for the provided lease id. - - LIST / - Lists the leases for the named prefix. - `, - }, - - "leases-list-prefix": { - `The path to list leases under. Example: "aws/creds/deploy"`, - "", - }, - "plugin-reload": { - "Reload mounts that use a particular backend plugin.", - `Reload mounts that use a particular backend plugin. Either the plugin name - or the desired plugin backend mounts must be provided, but not both. In the - case that the plugin name is provided, all mounted paths that use that plugin - backend will be reloaded.`, - }, - "plugin-backend-reload-plugin": { - `The name of the plugin to reload, as registered in the plugin catalog.`, - "", - }, - "plugin-backend-reload-mounts": { - `The mount paths of the plugin backends to reload.`, - "", - }, - "hash": { - "Generate a hash sum for input data", - "Generates a hash sum of the given algorithm against the given input data.", - }, - "random": { - "Generate random bytes", - "This function can be used to generate high-entropy random bytes.", - }, - "listing_visibility": { - "Determines the visibility of the mount in the UI-specific listing endpoint. Accepted value are 'unauth' and ''.", - "", - }, - "passthrough_request_headers": { - "A list of headers to whitelist and pass from the request to the backend.", - "", - }, - "raw": { - "Write, Read, and Delete data directly in the Storage backend.", - "", - }, - "internal-ui-mounts": { - "Information about mounts returned according to their tuned visibility. Internal API; its location, inputs, and outputs may change.", - "", - }, - "internal-ui-resultant-acl": { - "Information about a token's resultant ACL. Internal API; its location, inputs, and outputs may change.", - "", - }, -} diff --git a/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go b/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go deleted file mode 100644 index d9fdb046b..000000000 --- a/vendor/github.com/hashicorp/vault/vault/logical_system_helpers.go +++ /dev/null @@ -1,54 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "time" -) - -// tuneMount is used to set config on a mount point -func (b *SystemBackend) tuneMountTTLs(ctx context.Context, path string, me *MountEntry, newDefault, newMax time.Duration) error { - zero := time.Duration(0) - - switch { - case newDefault == zero && newMax == zero: - // No checks needed - - case newDefault == zero && newMax != zero: - // No default/max conflict, no checks needed - - case newDefault != zero && newMax == zero: - // No default/max conflict, no checks needed - - case newDefault != zero && newMax != zero: - if newMax < newDefault { - return fmt.Errorf("backend max lease TTL of %d would be less than backend default lease TTL of %d", int(newMax.Seconds()), int(newDefault.Seconds())) - } - } - - origMax := me.Config.MaxLeaseTTL - origDefault := me.Config.DefaultLeaseTTL - - me.Config.MaxLeaseTTL = newMax - me.Config.DefaultLeaseTTL = newDefault - - // Update the mount table - var err error - switch { - case strings.HasPrefix(path, credentialRoutePrefix): - err = b.Core.persistAuth(ctx, b.Core.auth, &me.Local) - default: - err = b.Core.persistMounts(ctx, b.Core.mounts, &me.Local) - } - if err != nil { - me.Config.MaxLeaseTTL = origMax - me.Config.DefaultLeaseTTL = origDefault - return fmt.Errorf("failed to update mount table, rolling back TTL changes") - } - if b.Core.logger.IsInfo() { - b.Core.logger.Info("mount tuning of leases successful", "path", path) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/mount.go b/vendor/github.com/hashicorp/vault/vault/mount.go deleted file mode 100644 index 2eba6bd6a..000000000 --- a/vendor/github.com/hashicorp/vault/vault/mount.go +++ /dev/null @@ -1,1115 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "os" - "sort" - "strings" - "sync" - "time" - - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/mitchellh/copystructure" -) - -const ( - // coreMountConfigPath is used to store the mount configuration. - // Mounts are protected within the Vault itself, which means they - // can only be viewed or modified after an unseal. - coreMountConfigPath = "core/mounts" - - // coreLocalMountConfigPath is used to store mount configuration for local - // (non-replicated) mounts - coreLocalMountConfigPath = "core/local-mounts" - - // backendBarrierPrefix is the prefix to the UUID used in the - // barrier view for the backends. - backendBarrierPrefix = "logical/" - - // systemBarrierPrefix is the prefix used for the - // system logical backend. - systemBarrierPrefix = "sys/" - - // mountTableType is the value we expect to find for the mount table and - // corresponding entries - mountTableType = "mounts" -) - -// ListingVisibilityType represents the types for listing visibility -type ListingVisibilityType string - -const ( - // ListingVisibilityDefault is the default value for listing visibility - ListingVisibilityDefault ListingVisibilityType = "" - // ListingVisibilityHidden is the hidden type for listing visibility - ListingVisibilityHidden ListingVisibilityType = "hidden" - // ListingVisibilityUnauth is the unauth type for listing visibility - ListingVisibilityUnauth ListingVisibilityType = "unauth" -) - -var ( - // loadMountsFailed if loadMounts encounters an error - errLoadMountsFailed = errors.New("failed to setup mount table") - - // protectedMounts cannot be remounted - protectedMounts = []string{ - "audit/", - "auth/", - "sys/", - "cubbyhole/", - "identity/", - } - - untunableMounts = []string{ - "cubbyhole/", - "sys/", - "audit/", - "identity/", - } - - // singletonMounts can only exist in one location and are - // loaded by default. These are types, not paths. - singletonMounts = []string{ - "cubbyhole", - "system", - "token", - "identity", - } - - // mountAliases maps old backend names to new backend names, allowing us - // to move/rename backends but maintain backwards compatibility - mountAliases = map[string]string{"generic": "kv"} -) - -func collectBackendLocalPaths(backend logical.Backend, viewPath string) []string { - if backend == nil || backend.SpecialPaths() == nil || len(backend.SpecialPaths().LocalStorage) == 0 { - return nil - } - - var paths []string - for _, path := range backend.SpecialPaths().LocalStorage { - paths = append(paths, viewPath+path) - } - - return paths -} - -func (c *Core) generateMountAccessor(entryType string) (string, error) { - var accessor string - for { - randBytes, err := uuid.GenerateRandomBytes(4) - if err != nil { - return "", err - } - accessor = fmt.Sprintf("%s_%s", entryType, fmt.Sprintf("%08x", randBytes[0:4])) - if entry := c.router.MatchingMountByAccessor(accessor); entry == nil { - break - } - } - - return accessor, nil -} - -// MountTable is used to represent the internal mount table -type MountTable struct { - Type string `json:"type"` - Entries []*MountEntry `json:"entries"` -} - -// shallowClone returns a copy of the mount table that -// keeps the MountEntry locations, so as not to invalidate -// other locations holding pointers. Care needs to be taken -// if modifying entries rather than modifying the table itself -func (t *MountTable) shallowClone() *MountTable { - mt := &MountTable{ - Type: t.Type, - Entries: make([]*MountEntry, len(t.Entries)), - } - for i, e := range t.Entries { - mt.Entries[i] = e - } - return mt -} - -// setTaint is used to set the taint on given entry -func (t *MountTable) setTaint(path string, value bool) *MountEntry { - n := len(t.Entries) - for i := 0; i < n; i++ { - if t.Entries[i].Path == path { - t.Entries[i].Tainted = value - return t.Entries[i] - } - } - return nil -} - -// remove is used to remove a given path entry; returns the entry that was -// removed -func (t *MountTable) remove(path string) *MountEntry { - n := len(t.Entries) - for i := 0; i < n; i++ { - if entry := t.Entries[i]; entry.Path == path { - t.Entries[i], t.Entries[n-1] = t.Entries[n-1], nil - t.Entries = t.Entries[:n-1] - return entry - } - } - return nil -} - -// sortEntriesByPath sorts the entries in the table by path and returns the -// table; this is useful for tests -func (t *MountTable) sortEntriesByPath() *MountTable { - sort.Slice(t.Entries, func(i, j int) bool { - return t.Entries[i].Path < t.Entries[j].Path - }) - return t -} - -// MountEntry is used to represent a mount table entry -type MountEntry struct { - Table string `json:"table"` // The table it belongs to - Path string `json:"path"` // Mount Path - Type string `json:"type"` // Logical backend Type - Description string `json:"description"` // User-provided description - UUID string `json:"uuid"` // Barrier view UUID - BackendAwareUUID string `json:"backend_aware_uuid"` // UUID that can be used by the backend as a helper when a consistent value is needed outside of storage. - Accessor string `json:"accessor"` // Unique but more human-friendly ID. Does not change, not used for any sensitive things (like as a salt, which the UUID sometimes is). - Config MountConfig `json:"config"` // Configuration related to this mount (but not backend-derived) - Options map[string]string `json:"options"` // Backend options - Local bool `json:"local"` // Local mounts are not replicated or affected by replication - SealWrap bool `json:"seal_wrap"` // Whether to wrap CSPs - Tainted bool `json:"tainted,omitempty"` // Set as a Write-Ahead flag for unmount/remount - - // synthesizedConfigCache is used to cache configuration values. These - // particular values are cached since we want to get them at a point-in-time - // without separately managing their locks individually. See SyncCache() for - // the specific values that are being cached. - synthesizedConfigCache sync.Map -} - -// MountConfig is used to hold settable options -type MountConfig struct { - DefaultLeaseTTL time.Duration `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` // Override for global default - MaxLeaseTTL time.Duration `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` // Override for global default - ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` // Override for global default - PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"` -} - -// APIMountConfig is an embedded struct of api.MountConfigInput -type APIMountConfig struct { - DefaultLeaseTTL string `json:"default_lease_ttl" structs:"default_lease_ttl" mapstructure:"default_lease_ttl"` - MaxLeaseTTL string `json:"max_lease_ttl" structs:"max_lease_ttl" mapstructure:"max_lease_ttl"` - ForceNoCache bool `json:"force_no_cache" structs:"force_no_cache" mapstructure:"force_no_cache"` - PluginName string `json:"plugin_name,omitempty" structs:"plugin_name,omitempty" mapstructure:"plugin_name"` - AuditNonHMACRequestKeys []string `json:"audit_non_hmac_request_keys,omitempty" structs:"audit_non_hmac_request_keys" mapstructure:"audit_non_hmac_request_keys"` - AuditNonHMACResponseKeys []string `json:"audit_non_hmac_response_keys,omitempty" structs:"audit_non_hmac_response_keys" mapstructure:"audit_non_hmac_response_keys"` - ListingVisibility ListingVisibilityType `json:"listing_visibility,omitempty" structs:"listing_visibility" mapstructure:"listing_visibility"` - PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" structs:"passthrough_request_headers" mapstructure:"passthrough_request_headers"` -} - -// Clone returns a deep copy of the mount entry -func (e *MountEntry) Clone() (*MountEntry, error) { - cp, err := copystructure.Copy(e) - if err != nil { - return nil, err - } - return cp.(*MountEntry), nil -} - -// SyncCache syncs tunable configuration values to the cache. In the case of -// cached values, they should be retrieved via synthesizedConfigCache.Load() -// instead of accessing them directly through MountConfig. -func (e *MountEntry) SyncCache() { - if len(e.Config.AuditNonHMACRequestKeys) == 0 { - e.synthesizedConfigCache.Delete("audit_non_hmac_request_keys") - } else { - e.synthesizedConfigCache.Store("audit_non_hmac_request_keys", e.Config.AuditNonHMACRequestKeys) - } - - if len(e.Config.AuditNonHMACResponseKeys) == 0 { - e.synthesizedConfigCache.Delete("audit_non_hmac_response_keys") - } else { - e.synthesizedConfigCache.Store("audit_non_hmac_response_keys", e.Config.AuditNonHMACResponseKeys) - } - - if len(e.Config.PassthroughRequestHeaders) == 0 { - e.synthesizedConfigCache.Delete("passthrough_request_headers") - } else { - e.synthesizedConfigCache.Store("passthrough_request_headers", e.Config.PassthroughRequestHeaders) - } -} - -// Mount is used to mount a new backend to the mount table. -func (c *Core) mount(ctx context.Context, entry *MountEntry) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(entry.Path, "/") { - entry.Path += "/" - } - - // Prevent protected paths from being mounted - for _, p := range protectedMounts { - if strings.HasPrefix(entry.Path, p) { - return logical.CodedError(403, fmt.Sprintf("cannot mount '%s'", entry.Path)) - } - } - - // Do not allow more than one instance of a singleton mount - for _, p := range singletonMounts { - if entry.Type == p { - return logical.CodedError(403, fmt.Sprintf("Cannot mount more than one instance of '%s'", entry.Type)) - } - } - return c.mountInternal(ctx, entry) -} - -func (c *Core) mountInternal(ctx context.Context, entry *MountEntry) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // Verify there are no conflicting mounts - if match := c.router.MountConflict(entry.Path); match != "" { - return logical.CodedError(409, fmt.Sprintf("existing mount at %s", match)) - } - - // Generate a new UUID and view - if entry.UUID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.UUID = entryUUID - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor(entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - } - // Sync values to the cache - entry.SyncCache() - - viewPath := backendBarrierPrefix + entry.UUID + "/" - view := NewBarrierView(c.barrier, viewPath) - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - // We defer this because we're already up and running so we don't need to - // time it for after postUnseal - defer view.setReadOnlyErr(nil) - - var backend logical.Backend - var err error - sysView := c.mountEntrySysView(entry) - - // Consider having plugin name under entry.Options - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend of type %q returned from creation function", entry.Type) - } - - // Check for the correct backend type - backendType := backend.Type() - if entry.Type == "plugin" && backendType != logical.TypeLogical { - return fmt.Errorf("cannot mount %q of type %q as a logical backend", entry.Config.PluginName, backendType) - } - - c.setCoreBackend(entry, backend, view) - - newTable := c.mounts.shallowClone() - newTable.Entries = append(newTable.Entries, entry) - if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil { - c.logger.Error("failed to update mount table", "error", err) - return logical.CodedError(500, "failed to update mount table") - } - c.mounts = newTable - - if err := c.router.Mount(backend, entry.Path, entry, view); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("successful mount", "path", entry.Path, "type", entry.Type) - } - return nil -} - -// Unmount is used to unmount a path. The boolean indicates whether the mount -// was found. -func (c *Core) unmount(ctx context.Context, path string) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(path, "/") { - path += "/" - } - - // Prevent protected paths from being unmounted - for _, p := range protectedMounts { - if strings.HasPrefix(path, p) { - return fmt.Errorf("cannot unmount %q", path) - } - } - return c.unmountInternal(ctx, path) -} - -func (c *Core) unmountInternal(ctx context.Context, path string) error { - // Verify exact match of the route - match := c.router.MatchingMount(path) - if match == "" || path != match { - return fmt.Errorf("no matching mount") - } - - // Get the view for this backend - view := c.router.MatchingStorageByAPIPath(path) - - // Get the backend/mount entry for this path, used to remove ignored - // replication prefixes - backend := c.router.MatchingBackend(path) - entry := c.router.MatchingMountEntry(path) - - // Mark the entry as tainted - if err := c.taintMountEntry(ctx, path); err != nil { - c.logger.Error("failed to taint mount entry for path being unmounted", "error", err, "path", path) - return err - } - - // Taint the router path to prevent routing. Note that in-flight requests - // are uncertain, right now. - if err := c.router.Taint(path); err != nil { - return err - } - - if backend != nil { - // Invoke the rollback manager a final time - if err := c.rollback.Rollback(path); err != nil { - return err - } - - // Revoke all the dynamic keys - if err := c.expiration.RevokePrefix(c.activeContext, path, true); err != nil { - return err - } - - // Call cleanup function if it exists - backend.Cleanup(ctx) - } - - // Unmount the backend entirely - if err := c.router.Unmount(ctx, path); err != nil { - return err - } - - switch { - case entry.Local, !c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary): - // Have writable storage, remove the whole thing - if err := logical.ClearView(ctx, view); err != nil { - c.logger.Error("failed to clear view for path being unmounted", "error", err, "path", path) - return err - } - } - - // Remove the mount table entry - if err := c.removeMountEntry(ctx, path); err != nil { - c.logger.Error("failed to remove mount entry for path being unmounted", "error", err, "path", path) - return err - } - - if c.logger.IsInfo() { - c.logger.Info("successfully unmounted", "path", path) - } - return nil -} - -// removeMountEntry is used to remove an entry from the mount table -func (c *Core) removeMountEntry(ctx context.Context, path string) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // Remove the entry from the mount table - newTable := c.mounts.shallowClone() - entry := newTable.remove(path) - if entry == nil { - c.logger.Error("nil entry found removing entry in mounts table", "path", path) - return logical.CodedError(500, "failed to remove entry in mounts table") - } - - // When unmounting all entries the JSON code will load back up from storage - // as a nil slice, which kills tests...just set it nil explicitly - if len(newTable.Entries) == 0 { - newTable.Entries = nil - } - - // Update the mount table - if err := c.persistMounts(ctx, newTable, &entry.Local); err != nil { - c.logger.Error("failed to remove entry from mounts table", "error", err) - return logical.CodedError(500, "failed to remove entry from mounts table") - } - - c.mounts = newTable - return nil -} - -// taintMountEntry is used to mark an entry in the mount table as tainted -func (c *Core) taintMountEntry(ctx context.Context, path string) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // As modifying the taint of an entry affects shallow clones, - // we simply use the original - entry := c.mounts.setTaint(path, true) - if entry == nil { - c.logger.Error("nil entry found tainting entry in mounts table", "path", path) - return logical.CodedError(500, "failed to taint entry in mounts table") - } - - // Update the mount table - if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil { - c.logger.Error("failed to taint entry in mounts table", "error", err) - return logical.CodedError(500, "failed to taint entry in mounts table") - } - - return nil -} - -// remountForce takes a copy of the mount entry for the path and fully unmounts -// and remounts the backend to pick up any changes, such as filtered paths -func (c *Core) remountForce(ctx context.Context, path string) error { - me := c.router.MatchingMountEntry(path) - if me == nil { - return fmt.Errorf("cannot find mount for path %q", path) - } - - me, err := me.Clone() - if err != nil { - return err - } - - if err := c.unmount(ctx, path); err != nil { - return err - } - return c.mount(ctx, me) -} - -// Remount is used to remount a path at a new mount point. -func (c *Core) remount(ctx context.Context, src, dst string) error { - // Ensure we end the path in a slash - if !strings.HasSuffix(src, "/") { - src += "/" - } - if !strings.HasSuffix(dst, "/") { - dst += "/" - } - - // Prevent protected paths from being remounted - for _, p := range protectedMounts { - if strings.HasPrefix(src, p) { - return fmt.Errorf("cannot remount %q", src) - } - } - - // Verify exact match of the route - match := c.router.MatchingMount(src) - if match == "" || src != match { - return fmt.Errorf("no matching mount at %q", src) - } - - if match := c.router.MatchingMount(dst); match != "" { - return fmt.Errorf("existing mount at %q", match) - } - - // Mark the entry as tainted - if err := c.taintMountEntry(ctx, src); err != nil { - return err - } - - // Taint the router path to prevent routing - if err := c.router.Taint(src); err != nil { - return err - } - - // Invoke the rollback manager a final time - if err := c.rollback.Rollback(src); err != nil { - return err - } - - // Revoke all the dynamic keys - if err := c.expiration.RevokePrefix(c.activeContext, src, true); err != nil { - return err - } - - c.mountsLock.Lock() - var entry *MountEntry - for _, entry = range c.mounts.Entries { - if entry.Path == src { - entry.Path = dst - entry.Tainted = false - break - } - } - - if entry == nil { - c.mountsLock.Unlock() - c.logger.Error("failed to find entry in mounts table") - return logical.CodedError(500, "failed to find entry in mounts table") - } - - // Update the mount table - if err := c.persistMounts(ctx, c.mounts, &entry.Local); err != nil { - entry.Path = src - entry.Tainted = true - c.mountsLock.Unlock() - c.logger.Error("failed to update mounts table", "error", err) - return logical.CodedError(500, "failed to update mounts table") - } - c.mountsLock.Unlock() - - // Remount the backend - if err := c.router.Remount(src, dst); err != nil { - return err - } - - // Un-taint the path - if err := c.router.Untaint(dst); err != nil { - return err - } - - if c.logger.IsInfo() { - c.logger.Info("successful remount", "old_path", src, "new_path", dst) - } - return nil -} - -// loadMounts is invoked as part of postUnseal to load the mount table -func (c *Core) loadMounts(ctx context.Context) error { - mountTable := &MountTable{} - localMountTable := &MountTable{} - // Load the existing mount table - raw, err := c.barrier.Get(ctx, coreMountConfigPath) - if err != nil { - c.logger.Error("failed to read mount table", "error", err) - return errLoadMountsFailed - } - rawLocal, err := c.barrier.Get(ctx, coreLocalMountConfigPath) - if err != nil { - c.logger.Error("failed to read local mount table", "error", err) - return errLoadMountsFailed - } - - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - if raw != nil { - // Check if the persisted value has canary in the beginning. If - // yes, decompress the table and then JSON decode it. If not, - // simply JSON decode it. - if err := jsonutil.DecodeJSON(raw.Value, mountTable); err != nil { - c.logger.Error("failed to decompress and/or decode the mount table", "error", err) - return err - } - c.mounts = mountTable - } - - var needPersist bool - if c.mounts == nil { - c.logger.Info("no mounts; adding default mount table") - c.mounts = c.defaultMountTable() - needPersist = true - } - - if rawLocal != nil { - if err := jsonutil.DecodeJSON(rawLocal.Value, localMountTable); err != nil { - c.logger.Error("failed to decompress and/or decode the local mount table", "error", err) - return err - } - if localMountTable != nil && len(localMountTable.Entries) > 0 { - c.mounts.Entries = append(c.mounts.Entries, localMountTable.Entries...) - } - } - - // Note that this is only designed to work with singletons, as it checks by - // type only. - - // Upgrade to typed mount table - if c.mounts.Type == "" { - c.mounts.Type = mountTableType - needPersist = true - } - - for _, requiredMount := range c.requiredMountTable().Entries { - foundRequired := false - for _, coreMount := range c.mounts.Entries { - if coreMount.Type == requiredMount.Type { - foundRequired = true - break - } - } - - // In a replication scenario we will let sync invalidation take - // care of creating a new required mount that doesn't exist yet. - // This should only happen in the upgrade case where a new one is - // introduced on the primary; otherwise initial bootstrapping will - // ensure this comes over. If we upgrade first, we simply don't - // create the mount, so we won't conflict when we sync. If this is - // local (e.g. cubbyhole) we do still add it. - if !foundRequired && (!c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) || requiredMount.Local) { - c.mounts.Entries = append(c.mounts.Entries, requiredMount) - needPersist = true - } - } - - // Upgrade to table-scoped entries - for _, entry := range c.mounts.Entries { - if entry.Type == "cubbyhole" && !entry.Local { - entry.Local = true - needPersist = true - } - if entry.Table == "" { - entry.Table = c.mounts.Type - needPersist = true - } - if entry.Accessor == "" { - accessor, err := c.generateMountAccessor(entry.Type) - if err != nil { - return err - } - entry.Accessor = accessor - needPersist = true - } - if entry.BackendAwareUUID == "" { - bUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.BackendAwareUUID = bUUID - needPersist = true - } - - // Sync values to the cache - entry.SyncCache() - } - - // Done if we have restored the mount table and we don't need - // to persist - if !needPersist { - return nil - } - - if err := c.persistMounts(ctx, c.mounts, nil); err != nil { - c.logger.Error("failed to persist mount table", "error", err) - return errLoadMountsFailed - } - return nil -} - -// persistMounts is used to persist the mount table after modification -func (c *Core) persistMounts(ctx context.Context, table *MountTable, local *bool) error { - if table.Type != mountTableType { - c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", mountTableType) - return fmt.Errorf("invalid table type given, not persisting") - } - - for _, entry := range table.Entries { - if entry.Table != table.Type { - c.logger.Error("given entry to persist in mount table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type) - return fmt.Errorf("invalid mount entry found, not persisting") - } - } - - nonLocalMounts := &MountTable{ - Type: mountTableType, - } - - localMounts := &MountTable{ - Type: mountTableType, - } - - for _, entry := range table.Entries { - if entry.Local { - localMounts.Entries = append(localMounts.Entries, entry) - } else { - nonLocalMounts.Entries = append(nonLocalMounts.Entries, entry) - } - } - - writeTable := func(mt *MountTable, path string) error { - // Encode the mount table into JSON and compress it (lzw). - compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil) - if err != nil { - c.logger.Error("failed to encode or compress mount table", "error", err) - return err - } - - // Create an entry - entry := &Entry{ - Key: path, - Value: compressedBytes, - } - - // Write to the physical backend - if err := c.barrier.Put(ctx, entry); err != nil { - c.logger.Error("failed to persist mount table", "error", err) - return err - } - - return nil - } - - var err error - switch { - case local == nil: - // Write non-local mounts - err := writeTable(nonLocalMounts, coreMountConfigPath) - if err != nil { - return err - } - - // Write local mounts - err = writeTable(localMounts, coreLocalMountConfigPath) - if err != nil { - return err - } - case *local: - // Write local mounts - err = writeTable(localMounts, coreLocalMountConfigPath) - default: - // Write non-local mounts - err = writeTable(nonLocalMounts, coreMountConfigPath) - } - - return err -} - -// setupMounts is invoked after we've loaded the mount table to -// initialize the logical backends and setup the router -func (c *Core) setupMounts(ctx context.Context) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - var backendType logical.BackendType - - for _, entry := range c.mounts.Entries { - - // Initialize the backend, special casing for system - barrierPath := backendBarrierPrefix + entry.UUID + "/" - if entry.Type == "system" { - barrierPath = systemBarrierPrefix - } - - // Create a barrier view using the UUID - view := NewBarrierView(c.barrier, barrierPath) - - // Mark the view as read-only until the mounting is complete and - // ensure that it is reset after. This ensures that there will be no - // writes during the construction of the backend. - view.setReadOnlyErr(logical.ErrSetupReadOnly) - if strutil.StrListContains(singletonMounts, entry.Type) { - defer view.setReadOnlyErr(nil) - } else { - c.postUnsealFuncs = append(c.postUnsealFuncs, func() { - view.setReadOnlyErr(nil) - }) - } - - var backend logical.Backend - var err error - sysView := c.mountEntrySysView(entry) - - // Create the new backend - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - if err != nil { - c.logger.Error("failed to create mount entry", "path", entry.Path, "error", err) - if entry.Type == "plugin" { - // If we encounter an error instantiating the backend due to an error, - // skip backend initialization but register the entry to the mount table - // to preserve storage and path. - c.logger.Warn("skipping plugin-based mount entry", "path", entry.Path) - goto ROUTER_MOUNT - } - return errLoadMountsFailed - } - if backend == nil { - return fmt.Errorf("created mount entry of type %q is nil", entry.Type) - } - - // Check for the correct backend type - backendType = backend.Type() - if entry.Type == "plugin" && backendType != logical.TypeLogical { - return fmt.Errorf("cannot mount %q of type %q as a logical backend", entry.Config.PluginName, backendType) - } - - c.setCoreBackend(entry, backend, view) - - ROUTER_MOUNT: - // Mount the backend - err = c.router.Mount(backend, entry.Path, entry, view) - if err != nil { - c.logger.Error("failed to mount entry", "path", entry.Path, "error", err) - return errLoadMountsFailed - } - - if c.logger.IsInfo() { - c.logger.Info("successfully mounted backend", "type", entry.Type, "path", entry.Path) - } - - // Ensure the path is tainted if set in the mount table - if entry.Tainted { - c.router.Taint(entry.Path) - } - } - return nil -} - -// unloadMounts is used before we seal the vault to reset the mounts to -// their unloaded state, calling Cleanup if defined. This is reversed by load and setup mounts. -func (c *Core) unloadMounts(ctx context.Context) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - if c.mounts != nil { - mountTable := c.mounts.shallowClone() - for _, e := range mountTable.Entries { - backend := c.router.MatchingBackend(e.Path) - if backend != nil { - backend.Cleanup(ctx) - } - } - } - - c.mounts = nil - c.router = NewRouter() - c.systemBarrierView = nil - return nil -} - -// newLogicalBackend is used to create and configure a new logical backend by name -func (c *Core) newLogicalBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) { - t := entry.Type - if alias, ok := mountAliases[t]; ok { - t = alias - } - f, ok := c.logicalBackends[t] - if !ok { - return nil, fmt.Errorf("unknown backend type: %q", t) - } - - // Set up conf to pass in plugin_name - conf := make(map[string]string, len(entry.Options)+1) - for k, v := range entry.Options { - conf[k] = v - } - if entry.Config.PluginName != "" { - conf["plugin_name"] = entry.Config.PluginName - } - - backendLogger := c.baseLogger.Named(fmt.Sprintf("secrets.%s.%s", t, entry.Accessor)) - c.AddLogger(backendLogger) - config := &logical.BackendConfig{ - StorageView: view, - Logger: backendLogger, - Config: conf, - System: sysView, - BackendUUID: entry.BackendAwareUUID, - } - - b, err := f(ctx, config) - if err != nil { - return nil, err - } - if b == nil { - return nil, fmt.Errorf("nil backend of type %q returned from factory", t) - } - return b, nil -} - -// mountEntrySysView creates a logical.SystemView from global and -// mount-specific entries; because this should be called when setting -// up a mountEntry, it doesn't check to ensure that me is not nil -func (c *Core) mountEntrySysView(entry *MountEntry) logical.SystemView { - return dynamicSystemView{ - core: c, - mountEntry: entry, - } -} - -// defaultMountTable creates a default mount table -func (c *Core) defaultMountTable() *MountTable { - table := &MountTable{ - Type: mountTableType, - } - mountUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create default secret mount UUID: %v", err)) - } - mountAccessor, err := c.generateMountAccessor("kv") - if err != nil { - panic(fmt.Sprintf("could not generate default secret mount accessor: %v", err)) - } - bUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create default secret mount backend UUID: %v", err)) - } - - kvMount := &MountEntry{ - Table: mountTableType, - Path: "secret/", - Type: "kv", - Description: "key/value secret storage", - UUID: mountUUID, - Accessor: mountAccessor, - BackendAwareUUID: bUUID, - Options: map[string]string{ - "version": "1", - }, - } - if os.Getenv("VAULT_INTERACTIVE_DEMO_SERVER") != "" { - kvMount.Options["version"] = "2" - } - table.Entries = append(table.Entries, kvMount) - table.Entries = append(table.Entries, c.requiredMountTable().Entries...) - return table -} - -// requiredMountTable() creates a mount table with entries required -// to be available -func (c *Core) requiredMountTable() *MountTable { - table := &MountTable{ - Type: mountTableType, - } - cubbyholeUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create cubbyhole UUID: %v", err)) - } - cubbyholeAccessor, err := c.generateMountAccessor("cubbyhole") - if err != nil { - panic(fmt.Sprintf("could not generate cubbyhole accessor: %v", err)) - } - cubbyholeBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create cubbyhole backend UUID: %v", err)) - } - cubbyholeMount := &MountEntry{ - Table: mountTableType, - Path: "cubbyhole/", - Type: "cubbyhole", - Description: "per-token private secret storage", - UUID: cubbyholeUUID, - Accessor: cubbyholeAccessor, - Local: true, - BackendAwareUUID: cubbyholeBackendUUID, - } - - sysUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create sys UUID: %v", err)) - } - sysAccessor, err := c.generateMountAccessor("system") - if err != nil { - panic(fmt.Sprintf("could not generate sys accessor: %v", err)) - } - sysBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create sys backend UUID: %v", err)) - } - sysMount := &MountEntry{ - Table: mountTableType, - Path: "sys/", - Type: "system", - Description: "system endpoints used for control, policy and debugging", - UUID: sysUUID, - Accessor: sysAccessor, - BackendAwareUUID: sysBackendUUID, - } - - identityUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity mount entry UUID: %v", err)) - } - identityAccessor, err := c.generateMountAccessor("identity") - if err != nil { - panic(fmt.Sprintf("could not generate identity accessor: %v", err)) - } - identityBackendUUID, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Sprintf("could not create identity backend UUID: %v", err)) - } - identityMount := &MountEntry{ - Table: mountTableType, - Path: "identity/", - Type: "identity", - Description: "identity store", - UUID: identityUUID, - Accessor: identityAccessor, - BackendAwareUUID: identityBackendUUID, - } - - table.Entries = append(table.Entries, cubbyholeMount) - table.Entries = append(table.Entries, sysMount) - table.Entries = append(table.Entries, identityMount) - - return table -} - -// This function returns tables that are singletons. The main usage of this is -// for replication, so we can send over mount info (especially, UUIDs of -// mounts, which are used for salts) for mounts that may not be able to be -// handled normally. After saving these values on the secondary, we let normal -// sync invalidation do its thing. Because of its use for replication, we -// exclude local mounts. -func (c *Core) singletonMountTables() (mounts, auth *MountTable) { - mounts = &MountTable{} - auth = &MountTable{} - - c.mountsLock.RLock() - for _, entry := range c.mounts.Entries { - if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local { - mounts.Entries = append(mounts.Entries, entry) - } - } - c.mountsLock.RUnlock() - - c.authLock.RLock() - for _, entry := range c.auth.Entries { - if strutil.StrListContains(singletonMounts, entry.Type) && !entry.Local { - auth.Entries = append(auth.Entries, entry) - } - } - c.authLock.RUnlock() - - return -} - -func (c *Core) setCoreBackend(entry *MountEntry, backend logical.Backend, view *BarrierView) { - switch entry.Type { - case "system": - c.systemBackend = backend.(*SystemBackend) - c.systemBarrierView = view - case "cubbyhole": - ch := backend.(*CubbyholeBackend) - ch.saltUUID = entry.UUID - ch.storageView = view - case "identity": - c.identityStore = backend.(*IdentityStore) - } -} diff --git a/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go b/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go deleted file mode 100644 index 633b7c341..000000000 --- a/vendor/github.com/hashicorp/vault/vault/plugin_catalog.go +++ /dev/null @@ -1,189 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "path/filepath" - "sort" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/builtinplugins" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/pluginutil" - "github.com/hashicorp/vault/logical" -) - -var ( - pluginCatalogPath = "core/plugin-catalog/" - ErrDirectoryNotConfigured = errors.New("could not set plugin, plugin directory is not configured") - ErrPluginNotFound = errors.New("plugin not found in the catalog") -) - -// PluginCatalog keeps a record of plugins known to vault. External plugins need -// to be registered to the catalog before they can be used in backends. Builtin -// plugins are automatically detected and included in the catalog. -type PluginCatalog struct { - catalogView *BarrierView - directory string - - lock sync.RWMutex -} - -func (c *Core) setupPluginCatalog() error { - c.pluginCatalog = &PluginCatalog{ - catalogView: NewBarrierView(c.barrier, pluginCatalogPath), - directory: c.pluginDirectory, - } - - if c.logger.IsInfo() { - c.logger.Info("successfully setup plugin catalog", "plugin-directory", c.pluginDirectory) - } - - return nil -} - -// Get retrieves a plugin with the specified name from the catalog. It first -// looks for external plugins with this name and then looks for builtin plugins. -// It returns a PluginRunner or an error if no plugin was found. -func (c *PluginCatalog) Get(ctx context.Context, name string) (*pluginutil.PluginRunner, error) { - c.lock.RLock() - defer c.lock.RUnlock() - - // If the directory isn't set only look for builtin plugins. - if c.directory != "" { - // Look for external plugins in the barrier - out, err := c.catalogView.Get(ctx, name) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("failed to retrieve plugin %q: {{err}}", name), err) - } - if out != nil { - entry := new(pluginutil.PluginRunner) - if err := jsonutil.DecodeJSON(out.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode plugin entry: {{err}}", err) - } - - // prepend the plugin directory to the command - entry.Command = filepath.Join(c.directory, entry.Command) - - return entry, nil - } - } - // Look for builtin plugins - if factory, ok := builtinplugins.Get(name); ok { - return &pluginutil.PluginRunner{ - Name: name, - Builtin: true, - BuiltinFactory: factory, - }, nil - } - - return nil, nil -} - -// Set registers a new external plugin with the catalog, or updates an existing -// external plugin. It takes the name, command and SHA256 of the plugin. -func (c *PluginCatalog) Set(ctx context.Context, name, command string, args []string, sha256 []byte) error { - if c.directory == "" { - return ErrDirectoryNotConfigured - } - - switch { - case strings.Contains(name, ".."): - fallthrough - case strings.Contains(command, ".."): - return consts.ErrPathContainsParentReferences - } - - c.lock.Lock() - defer c.lock.Unlock() - - // Best effort check to make sure the command isn't breaking out of the - // configured plugin directory. - commandFull := filepath.Join(c.directory, command) - sym, err := filepath.EvalSymlinks(commandFull) - if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) - } - symAbs, err := filepath.Abs(filepath.Dir(sym)) - if err != nil { - return errwrap.Wrapf("error while validating the command path: {{err}}", err) - } - - if symAbs != c.directory { - return errors.New("can not execute files outside of configured plugin directory") - } - - entry := &pluginutil.PluginRunner{ - Name: name, - Command: command, - Args: args, - Sha256: sha256, - Builtin: false, - } - - buf, err := json.Marshal(entry) - if err != nil { - return errwrap.Wrapf("failed to encode plugin entry: {{err}}", err) - } - - logicalEntry := logical.StorageEntry{ - Key: name, - Value: buf, - } - if err := c.catalogView.Put(ctx, &logicalEntry); err != nil { - return errwrap.Wrapf("failed to persist plugin entry: {{err}}", err) - } - return nil -} - -// Delete is used to remove an external plugin from the catalog. Builtin plugins -// can not be deleted. -func (c *PluginCatalog) Delete(ctx context.Context, name string) error { - c.lock.Lock() - defer c.lock.Unlock() - - return c.catalogView.Delete(ctx, name) -} - -// List returns a list of all the known plugin names. If an external and builtin -// plugin share the same name, only one instance of the name will be returned. -func (c *PluginCatalog) List(ctx context.Context) ([]string, error) { - c.lock.RLock() - defer c.lock.RUnlock() - - // Collect keys for external plugins in the barrier. - keys, err := logical.CollectKeys(ctx, c.catalogView) - if err != nil { - return nil, err - } - - // Get the keys for builtin plugins - builtinKeys := builtinplugins.Keys() - - // Use a map to unique the two lists - mapKeys := make(map[string]bool) - - for _, plugin := range keys { - mapKeys[plugin] = true - } - - for _, plugin := range builtinKeys { - mapKeys[plugin] = true - } - - retList := make([]string, len(mapKeys)) - i := 0 - for k := range mapKeys { - retList[i] = k - i++ - } - // sort for consistent ordering of builtin plugins - sort.Strings(retList) - - return retList, nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/plugin_reload.go b/vendor/github.com/hashicorp/vault/vault/plugin_reload.go deleted file mode 100644 index e130df8ba..000000000 --- a/vendor/github.com/hashicorp/vault/vault/plugin_reload.go +++ /dev/null @@ -1,143 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -// reloadPluginMounts reloads provided mounts, regardless of -// plugin name, as long as the backend type is plugin. -func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - var errors error - for _, mount := range mounts { - entry := c.router.MatchingMountEntry(mount) - if entry == nil { - errors = multierror.Append(errors, fmt.Errorf("cannot fetch mount entry on %q", mount)) - continue - } - - var isAuth bool - fullPath := c.router.MatchingMount(mount) - if strings.HasPrefix(fullPath, credentialRoutePrefix) { - isAuth = true - } - - if entry.Type == "plugin" { - err := c.reloadBackendCommon(ctx, entry, isAuth) - if err != nil { - errors = multierror.Append(errors, errwrap.Wrapf(fmt.Sprintf("cannot reload plugin on %q: {{err}}", mount), err)) - continue - } - c.logger.Info("successfully reloaded plugin", "plugin", entry.Config.PluginName, "path", entry.Path) - } - } - return errors -} - -// reloadPlugin reloads all mounted backends that are of -// plugin pluginName (name of the plugin as registered in -// the plugin catalog). -func (c *Core) reloadMatchingPlugin(ctx context.Context, pluginName string) error { - c.mountsLock.Lock() - defer c.mountsLock.Unlock() - - // Filter mount entries that only matches the plugin name - for _, entry := range c.mounts.Entries { - if entry.Config.PluginName == pluginName && entry.Type == "plugin" { - err := c.reloadBackendCommon(ctx, entry, false) - if err != nil { - return err - } - c.logger.Info("successfully reloaded plugin", "plugin", pluginName, "path", entry.Path) - } - } - - // Filter auth mount entries that ony matches the plugin name - for _, entry := range c.auth.Entries { - if entry.Config.PluginName == pluginName && entry.Type == "plugin" { - err := c.reloadBackendCommon(ctx, entry, true) - if err != nil { - return err - } - c.logger.Info("successfully reloaded plugin", "plugin", pluginName, "path", entry.Path) - } - } - - return nil -} - -// reloadBackendCommon is a generic method to reload a backend provided a -// MountEntry. -func (c *Core) reloadBackendCommon(ctx context.Context, entry *MountEntry, isAuth bool) error { - // We don't want to reload the singleton mounts. They often have specific - // inmemory elements and we don't want to touch them here. - if strutil.StrListContains(singletonMounts, entry.Type) { - c.logger.Debug("Skipping reload of singleton mount", "type", entry.Type) - return nil - } - - path := entry.Path - - if isAuth { - path = credentialRoutePrefix + path - } - - // Fast-path out if the backend doesn't exist - raw, ok := c.router.root.Get(path) - if !ok { - return nil - } - - re := raw.(*routeEntry) - - // Grab the lock, this allows requests to drain before we cleanup the - // client. - re.l.Lock() - defer re.l.Unlock() - - // Only call Cleanup if backend is initialized - if re.backend != nil { - // Call backend's Cleanup routine - re.backend.Cleanup(ctx) - } - - view := re.storageView - - sysView := c.mountEntrySysView(entry) - - var backend logical.Backend - var err error - if !isAuth { - // Dispense a new backend - backend, err = c.newLogicalBackend(ctx, entry, sysView, view) - } else { - backend, err = c.newCredentialBackend(ctx, entry, sysView, view) - } - if err != nil { - return err - } - if backend == nil { - return fmt.Errorf("nil backend of type %q returned from creation function", entry.Type) - } - - // Set the backend back - re.backend = backend - - // Set paths as well - paths := backend.SpecialPaths() - if paths != nil { - re.rootPaths.Store(pathsToRadix(paths.Root)) - re.loginPaths.Store(pathsToRadix(paths.Unauthenticated)) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy.go b/vendor/github.com/hashicorp/vault/vault/policy.go deleted file mode 100644 index 3eddc1b67..000000000 --- a/vendor/github.com/hashicorp/vault/vault/policy.go +++ /dev/null @@ -1,345 +0,0 @@ -package vault - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl" - "github.com/hashicorp/hcl/hcl/ast" - "github.com/hashicorp/vault/helper/hclutil" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/mitchellh/copystructure" -) - -const ( - DenyCapability = "deny" - CreateCapability = "create" - ReadCapability = "read" - UpdateCapability = "update" - DeleteCapability = "delete" - ListCapability = "list" - SudoCapability = "sudo" - RootCapability = "root" - - // Backwards compatibility - OldDenyPathPolicy = "deny" - OldReadPathPolicy = "read" - OldWritePathPolicy = "write" - OldSudoPathPolicy = "sudo" -) - -const ( - DenyCapabilityInt uint32 = 1 << iota - CreateCapabilityInt - ReadCapabilityInt - UpdateCapabilityInt - DeleteCapabilityInt - ListCapabilityInt - SudoCapabilityInt -) - -type PolicyType uint32 - -const ( - PolicyTypeACL PolicyType = iota - PolicyTypeRGP - PolicyTypeEGP - - // Triggers a lookup in the map to figure out if ACL or RGP - PolicyTypeToken -) - -func (p PolicyType) String() string { - switch p { - case PolicyTypeACL: - return "acl" - case PolicyTypeRGP: - return "rgp" - case PolicyTypeEGP: - return "egp" - } - - return "" -} - -var ( - cap2Int = map[string]uint32{ - DenyCapability: DenyCapabilityInt, - CreateCapability: CreateCapabilityInt, - ReadCapability: ReadCapabilityInt, - UpdateCapability: UpdateCapabilityInt, - DeleteCapability: DeleteCapabilityInt, - ListCapability: ListCapabilityInt, - SudoCapability: SudoCapabilityInt, - } -) - -// Policy is used to represent the policy specified by -// an ACL configuration. -type Policy struct { - Name string `hcl:"name"` - Paths []*PathRules `hcl:"-"` - Raw string - Type PolicyType - Templated bool -} - -// PathRules represents a policy for a path in the namespace. -type PathRules struct { - Prefix string - Policy string - Permissions *ACLPermissions - Glob bool - Capabilities []string - - // These keys are used at the top level to make the HCL nicer; we store in - // the ACLPermissions object though - MinWrappingTTLHCL interface{} `hcl:"min_wrapping_ttl"` - MaxWrappingTTLHCL interface{} `hcl:"max_wrapping_ttl"` - AllowedParametersHCL map[string][]interface{} `hcl:"allowed_parameters"` - DeniedParametersHCL map[string][]interface{} `hcl:"denied_parameters"` - RequiredParametersHCL []string `hcl:"required_parameters"` -} - -type ACLPermissions struct { - CapabilitiesBitmap uint32 - MinWrappingTTL time.Duration - MaxWrappingTTL time.Duration - AllowedParameters map[string][]interface{} - DeniedParameters map[string][]interface{} - RequiredParameters []string -} - -func (p *ACLPermissions) Clone() (*ACLPermissions, error) { - ret := &ACLPermissions{ - CapabilitiesBitmap: p.CapabilitiesBitmap, - MinWrappingTTL: p.MinWrappingTTL, - MaxWrappingTTL: p.MaxWrappingTTL, - RequiredParameters: p.RequiredParameters[:], - } - - switch { - case p.AllowedParameters == nil: - case len(p.AllowedParameters) == 0: - ret.AllowedParameters = make(map[string][]interface{}) - default: - clonedAllowed, err := copystructure.Copy(p.AllowedParameters) - if err != nil { - return nil, err - } - ret.AllowedParameters = clonedAllowed.(map[string][]interface{}) - } - - switch { - case p.DeniedParameters == nil: - case len(p.DeniedParameters) == 0: - ret.DeniedParameters = make(map[string][]interface{}) - default: - clonedDenied, err := copystructure.Copy(p.DeniedParameters) - if err != nil { - return nil, err - } - ret.DeniedParameters = clonedDenied.(map[string][]interface{}) - } - - return ret, nil -} - -// ParseACLPolicy is used to parse the specified ACL rules into an -// intermediary set of policies, before being compiled into -// the ACL -func ParseACLPolicy(rules string) (*Policy, error) { - return parseACLPolicyWithTemplating(rules, false, nil, nil) -} - -// parseACLPolicyWithTemplating performs the actual work and checks whether we -// should perform substitutions. If performTemplating is true we know that it -// is templated so we don't check again, otherwise we check to see if it's a -// templated policy. -func parseACLPolicyWithTemplating(rules string, performTemplating bool, entity *identity.Entity, groups []*identity.Group) (*Policy, error) { - // Parse the rules - root, err := hcl.Parse(rules) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Top-level item should be the object list - list, ok := root.Node.(*ast.ObjectList) - if !ok { - return nil, fmt.Errorf("failed to parse policy: does not contain a root object") - } - - // Check for invalid top-level keys - valid := []string{ - "name", - "path", - } - if err := hclutil.CheckHCLKeys(list, valid); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Create the initial policy and store the raw text of the rules - var p Policy - p.Raw = rules - p.Type = PolicyTypeACL - if err := hcl.DecodeObject(&p, list); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - if o := list.Filter("path"); len(o.Items) > 0 { - if err := parsePaths(&p, o, performTemplating, entity, groups); err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - } - - return &p, nil -} - -func parsePaths(result *Policy, list *ast.ObjectList, performTemplating bool, entity *identity.Entity, groups []*identity.Group) error { - paths := make([]*PathRules, 0, len(list.Items)) - for _, item := range list.Items { - key := "path" - if len(item.Keys) > 0 { - key = item.Keys[0].Token.Value().(string) - } - - // Check the path - if performTemplating { - _, templated, err := identity.PopulateString(&identity.PopulateStringInput{ - String: key, - Entity: entity, - Groups: groups, - }) - if err != nil { - continue - } - key = templated - } else { - hasTemplating, _, err := identity.PopulateString(&identity.PopulateStringInput{ - ValidityCheckOnly: true, - String: key, - }) - if err != nil { - return errwrap.Wrapf("failed to validate policy templating: {{err}}", err) - } - if hasTemplating { - result.Templated = true - } - } - - valid := []string{ - "comment", - "policy", - "capabilities", - "allowed_parameters", - "denied_parameters", - "required_parameters", - "min_wrapping_ttl", - "max_wrapping_ttl", - } - if err := hclutil.CheckHCLKeys(item.Val, valid); err != nil { - return multierror.Prefix(err, fmt.Sprintf("path %q:", key)) - } - - var pc PathRules - - // allocate memory so that DecodeObject can initialize the ACLPermissions struct - pc.Permissions = new(ACLPermissions) - - pc.Prefix = key - - if err := hcl.DecodeObject(&pc, item.Val); err != nil { - return multierror.Prefix(err, fmt.Sprintf("path %q:", key)) - } - - // Strip a leading '/' as paths in Vault start after the / in the API path - if len(pc.Prefix) > 0 && pc.Prefix[0] == '/' { - pc.Prefix = pc.Prefix[1:] - } - - // Strip the glob character if found - if strings.HasSuffix(pc.Prefix, "*") { - pc.Prefix = strings.TrimSuffix(pc.Prefix, "*") - pc.Glob = true - } - - // Map old-style policies into capabilities - if len(pc.Policy) > 0 { - switch pc.Policy { - case OldDenyPathPolicy: - pc.Capabilities = []string{DenyCapability} - case OldReadPathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{ReadCapability, ListCapability}...) - case OldWritePathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability}...) - case OldSudoPathPolicy: - pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability}...) - default: - return fmt.Errorf("path %q: invalid policy %q", key, pc.Policy) - } - } - - // Initialize the map - pc.Permissions.CapabilitiesBitmap = 0 - for _, cap := range pc.Capabilities { - switch cap { - // If it's deny, don't include any other capability - case DenyCapability: - pc.Capabilities = []string{DenyCapability} - pc.Permissions.CapabilitiesBitmap = DenyCapabilityInt - goto PathFinished - case CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability: - pc.Permissions.CapabilitiesBitmap |= cap2Int[cap] - default: - return fmt.Errorf("path %q: invalid capability %q", key, cap) - } - } - - if pc.AllowedParametersHCL != nil { - pc.Permissions.AllowedParameters = make(map[string][]interface{}, len(pc.AllowedParametersHCL)) - for key, val := range pc.AllowedParametersHCL { - pc.Permissions.AllowedParameters[strings.ToLower(key)] = val - } - } - if pc.DeniedParametersHCL != nil { - pc.Permissions.DeniedParameters = make(map[string][]interface{}, len(pc.DeniedParametersHCL)) - - for key, val := range pc.DeniedParametersHCL { - pc.Permissions.DeniedParameters[strings.ToLower(key)] = val - } - } - if pc.MinWrappingTTLHCL != nil { - dur, err := parseutil.ParseDurationSecond(pc.MinWrappingTTLHCL) - if err != nil { - return errwrap.Wrapf("error parsing min_wrapping_ttl: {{err}}", err) - } - pc.Permissions.MinWrappingTTL = dur - } - if pc.MaxWrappingTTLHCL != nil { - dur, err := parseutil.ParseDurationSecond(pc.MaxWrappingTTLHCL) - if err != nil { - return errwrap.Wrapf("error parsing max_wrapping_ttl: {{err}}", err) - } - pc.Permissions.MaxWrappingTTL = dur - } - if pc.Permissions.MinWrappingTTL != 0 && - pc.Permissions.MaxWrappingTTL != 0 && - pc.Permissions.MaxWrappingTTL < pc.Permissions.MinWrappingTTL { - return errors.New("max_wrapping_ttl cannot be less than min_wrapping_ttl") - } - if len(pc.RequiredParametersHCL) > 0 { - pc.Permissions.RequiredParameters = pc.RequiredParametersHCL[:] - } - - PathFinished: - paths = append(paths, &pc) - } - - result.Paths = paths - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/policy_store.go b/vendor/github.com/hashicorp/vault/vault/policy_store.go deleted file mode 100644 index b2d8cea03..000000000 --- a/vendor/github.com/hashicorp/vault/vault/policy_store.go +++ /dev/null @@ -1,567 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/golang-lru" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" -) - -const ( - // policySubPath is the sub-path used for the policy store - // view. This is nested under the system view. - policyACLSubPath = "policy/" - - // policyCacheSize is the number of policies that are kept cached - policyCacheSize = 1024 - - // defaultPolicyName is the name of the default policy - defaultPolicyName = "default" - - // responseWrappingPolicyName is the name of the fixed policy - responseWrappingPolicyName = "response-wrapping" - - // controlGroupPolicyName is the name of the fixed policy for control group - // tokens - controlGroupPolicyName = "control-group" - - // responseWrappingPolicy is the policy that ensures cubbyhole response - // wrapping can always succeed. - responseWrappingPolicy = ` -path "cubbyhole/response" { - capabilities = ["create", "read"] -} - -path "sys/wrapping/unwrap" { - capabilities = ["update"] -} -` - - // defaultPolicy is the "default" policy - defaultPolicy = ` -# Allow tokens to look up their own properties -path "auth/token/lookup-self" { - capabilities = ["read"] -} - -# Allow tokens to renew themselves -path "auth/token/renew-self" { - capabilities = ["update"] -} - -# Allow tokens to revoke themselves -path "auth/token/revoke-self" { - capabilities = ["update"] -} - -# Allow a token to look up its own capabilities on a path -path "sys/capabilities-self" { - capabilities = ["update"] -} - -# Allow a token to look up its resultant ACL from all policies. This is useful -# for UIs. It is an internal path because the format may change at any time -# based on how the internal ACL features and capabilities change. -path "sys/internal/ui/resultant-acl" { - capabilities = ["read"] -} - -# Allow a token to renew a lease via lease_id in the request body; old path for -# old clients, new path for newer -path "sys/renew" { - capabilities = ["update"] -} -path "sys/leases/renew" { - capabilities = ["update"] -} - -# Allow looking up lease properties. This requires knowing the lease ID ahead -# of time and does not divulge any sensitive information. -path "sys/leases/lookup" { - capabilities = ["update"] -} - -# Allow a token to manage its own cubbyhole -path "cubbyhole/*" { - capabilities = ["create", "read", "update", "delete", "list"] -} - -# Allow a token to wrap arbitrary values in a response-wrapping token -path "sys/wrapping/wrap" { - capabilities = ["update"] -} - -# Allow a token to look up the creation time and TTL of a given -# response-wrapping token -path "sys/wrapping/lookup" { - capabilities = ["update"] -} - -# Allow a token to unwrap a response-wrapping token. This is a convenience to -# avoid client token swapping since this is also part of the response wrapping -# policy. -path "sys/wrapping/unwrap" { - capabilities = ["update"] -} - -# Allow general purpose tools -path "sys/tools/hash" { - capabilities = ["update"] -} -path "sys/tools/hash/*" { - capabilities = ["update"] -} -path "sys/tools/random" { - capabilities = ["update"] -} -path "sys/tools/random/*" { - capabilities = ["update"] -} - -# Allow checking the status of a Control Group request if the user has the -# accessor -path "sys/control-group/request" { - capabilities = ["update"] -} -` -) - -var ( - immutablePolicies = []string{ - "root", - responseWrappingPolicyName, - controlGroupPolicyName, - } - nonAssignablePolicies = []string{ - responseWrappingPolicyName, - controlGroupPolicyName, - } -) - -// PolicyStore is used to provide durable storage of policy, and to -// manage ACLs associated with them. -type PolicyStore struct { - core *Core - aclView *BarrierView - tokenPoliciesLRU *lru.TwoQueueCache - // This is used to ensure that writes to the store (acl/rgp) or to the egp - // path tree don't happen concurrently. We are okay reading stale data so - // long as there aren't concurrent writes. - modifyLock *sync.RWMutex - // Stores whether a token policy is ACL or RGP - policyTypeMap sync.Map - // logger is the server logger copied over from core - logger log.Logger -} - -// PolicyEntry is used to store a policy by name -type PolicyEntry struct { - Version int - Raw string - Templated bool - Type PolicyType -} - -// NewPolicyStore creates a new PolicyStore that is backed -// using a given view. It used used to durable store and manage named policy. -func NewPolicyStore(ctx context.Context, core *Core, baseView *BarrierView, system logical.SystemView, logger log.Logger) *PolicyStore { - ps := &PolicyStore{ - aclView: baseView.SubView(policyACLSubPath), - modifyLock: new(sync.RWMutex), - logger: logger, - core: core, - } - if !system.CachingDisabled() { - cache, _ := lru.New2Q(policyCacheSize) - ps.tokenPoliciesLRU = cache - } - - keys, err := logical.CollectKeys(ctx, ps.aclView) - if err != nil { - ps.logger.Error("error collecting acl policy keys", "error", err) - return nil - } - for _, key := range keys { - ps.policyTypeMap.Store(ps.sanitizeName(key), PolicyTypeACL) - } - // Special-case root; doesn't exist on disk but does need to be found - ps.policyTypeMap.Store("root", PolicyTypeACL) - return ps -} - -// setupPolicyStore is used to initialize the policy store -// when the vault is being unsealed. -func (c *Core) setupPolicyStore(ctx context.Context) error { - // Create the policy store - sysView := &dynamicSystemView{core: c} - psLogger := c.baseLogger.Named("policy") - c.AddLogger(psLogger) - c.policyStore = NewPolicyStore(ctx, c, c.systemBarrierView, sysView, psLogger) - - if c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) { - // Policies will sync from the primary - return nil - } - - // Ensure that the default policy exists, and if not, create it - if err := c.policyStore.loadACLPolicy(ctx, defaultPolicyName, defaultPolicy); err != nil { - return err - } - // Ensure that the response wrapping policy exists - if err := c.policyStore.loadACLPolicy(ctx, responseWrappingPolicyName, responseWrappingPolicy); err != nil { - return err - } - - return nil -} - -// teardownPolicyStore is used to reverse setupPolicyStore -// when the vault is being sealed. -func (c *Core) teardownPolicyStore() error { - c.policyStore = nil - return nil -} - -func (ps *PolicyStore) invalidate(ctx context.Context, name string, policyType PolicyType) { - // This may come with a prefixed "/" due to joining the file path - saneName := strings.TrimPrefix(name, "/") - - // We don't lock before removing from the LRU here because the worst that - // can happen is we load again if something since added it - switch policyType { - case PolicyTypeACL: - if ps.tokenPoliciesLRU != nil { - ps.tokenPoliciesLRU.Remove(saneName) - } - - default: - // Can't do anything - return - } - - // Force a reload - _, err := ps.GetPolicy(ctx, name, policyType) - if err != nil { - ps.logger.Error("error fetching policy after invalidation", "name", saneName) - } -} - -// SetPolicy is used to create or update the given policy -func (ps *PolicyStore) SetPolicy(ctx context.Context, p *Policy) error { - defer metrics.MeasureSince([]string{"policy", "set_policy"}, time.Now()) - if p == nil { - return fmt.Errorf("nil policy passed in for storage") - } - if p.Name == "" { - return fmt.Errorf("policy name missing") - } - // Policies are normalized to lower-case - p.Name = ps.sanitizeName(p.Name) - if strutil.StrListContains(immutablePolicies, p.Name) { - return fmt.Errorf("cannot update %q policy", p.Name) - } - - return ps.setPolicyInternal(ctx, p) -} - -func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error { - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - // Create the entry - entry, err := logical.StorageEntryJSON(p.Name, &PolicyEntry{ - Version: 2, - Raw: p.Raw, - Type: p.Type, - Templated: p.Templated, - }) - if err != nil { - return errwrap.Wrapf("failed to create entry: {{err}}", err) - } - switch p.Type { - case PolicyTypeACL: - if err := ps.aclView.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to persist policy: {{err}}", err) - } - ps.policyTypeMap.Store(p.Name, PolicyTypeACL) - - if ps.tokenPoliciesLRU != nil { - // Update the LRU cache - ps.tokenPoliciesLRU.Add(p.Name, p) - } - - default: - return fmt.Errorf("unknown policy type, cannot set") - } - - return nil -} - -// GetPolicy is used to fetch the named policy -func (ps *PolicyStore) GetPolicy(ctx context.Context, name string, policyType PolicyType) (*Policy, error) { - defer metrics.MeasureSince([]string{"policy", "get_policy"}, time.Now()) - - // Policies are normalized to lower-case - name = ps.sanitizeName(name) - - var cache *lru.TwoQueueCache - var view *BarrierView - switch policyType { - case PolicyTypeACL: - cache = ps.tokenPoliciesLRU - view = ps.aclView - case PolicyTypeToken: - cache = ps.tokenPoliciesLRU - val, ok := ps.policyTypeMap.Load(name) - if !ok { - // Doesn't exist - return nil, nil - } - policyType = val.(PolicyType) - switch policyType { - case PolicyTypeACL: - view = ps.aclView - default: - return nil, fmt.Errorf("invalid type of policy in type map: %q", policyType) - } - } - - if cache != nil { - // Check for cached policy - if raw, ok := cache.Get(name); ok { - return raw.(*Policy), nil - } - } - - // Special case the root policy - if policyType == PolicyTypeACL && name == "root" { - p := &Policy{Name: "root"} - if cache != nil { - cache.Add(p.Name, p) - } - return p, nil - } - - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - - // See if anything has added it since we got the lock - if cache != nil { - if raw, ok := cache.Get(name); ok { - return raw.(*Policy), nil - } - } - - out, err := view.Get(ctx, name) - if err != nil { - return nil, errwrap.Wrapf("failed to read policy: {{err}}", err) - } - - if out == nil { - return nil, nil - } - - policyEntry := new(PolicyEntry) - policy := new(Policy) - err = out.DecodeJSON(policyEntry) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - - // Set these up here so that they're available for loading into - // Sentinel - policy.Name = name - policy.Raw = policyEntry.Raw - policy.Type = policyEntry.Type - policy.Templated = policyEntry.Templated - switch policyEntry.Type { - case PolicyTypeACL: - // Parse normally - p, err := ParseACLPolicy(policyEntry.Raw) - if err != nil { - return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err) - } - policy.Paths = p.Paths - // Reset this in case they set the name in the policy itself - policy.Name = name - - ps.policyTypeMap.Store(name, PolicyTypeACL) - - default: - return nil, fmt.Errorf("unknown policy type %q", policyEntry.Type.String()) - } - - if cache != nil { - // Update the LRU cache - cache.Add(name, policy) - } - - return policy, nil -} - -// ListPolicies is used to list the available policies -func (ps *PolicyStore) ListPolicies(ctx context.Context, policyType PolicyType) ([]string, error) { - defer metrics.MeasureSince([]string{"policy", "list_policies"}, time.Now()) - // Scan the view, since the policy names are the same as the - // key names. - var keys []string - var err error - switch policyType { - case PolicyTypeACL: - keys, err = logical.CollectKeys(ctx, ps.aclView) - default: - return nil, fmt.Errorf("unknown policy type %q", policyType) - } - - // We only have non-assignable ACL policies at the moment - for _, nonAssignable := range nonAssignablePolicies { - deleteIndex := -1 - //Find indices of non-assignable policies in keys - for index, key := range keys { - if key == nonAssignable { - // Delete collection outside the loop - deleteIndex = index - break - } - } - // Remove non-assignable policies when found - if deleteIndex != -1 { - keys = append(keys[:deleteIndex], keys[deleteIndex+1:]...) - } - } - - return keys, err -} - -// DeletePolicy is used to delete the named policy -func (ps *PolicyStore) DeletePolicy(ctx context.Context, name string, policyType PolicyType) error { - defer metrics.MeasureSince([]string{"policy", "delete_policy"}, time.Now()) - - ps.modifyLock.Lock() - defer ps.modifyLock.Unlock() - - // Policies are normalized to lower-case - name = ps.sanitizeName(name) - - switch policyType { - case PolicyTypeACL: - if strutil.StrListContains(immutablePolicies, name) { - return fmt.Errorf("cannot delete %q policy", name) - } - if name == "default" { - return fmt.Errorf("cannot delete default policy") - } - - err := ps.aclView.Delete(ctx, name) - if err != nil { - return errwrap.Wrapf("failed to delete policy: {{err}}", err) - } - - if ps.tokenPoliciesLRU != nil { - // Clear the cache - ps.tokenPoliciesLRU.Remove(name) - } - - ps.policyTypeMap.Delete(name) - - } - return nil -} - -type TemplateError struct { - Err error -} - -func (t *TemplateError) WrappedErrors() []error { - return []error{t.Err} -} - -func (t *TemplateError) Error() string { - return t.Err.Error() -} - -// ACL is used to return an ACL which is built using the -// named policies. -func (ps *PolicyStore) ACL(ctx context.Context, entity *identity.Entity, names ...string) (*ACL, error) { - // Fetch the policies - var policies []*Policy - for _, name := range names { - p, err := ps.GetPolicy(ctx, name, PolicyTypeToken) - if err != nil { - return nil, errwrap.Wrapf("failed to get policy: {{err}}", err) - } - if p != nil { - policies = append(policies, p) - } - } - - var fetchedGroups bool - var groups []*identity.Group - for i, policy := range policies { - if policy.Type == PolicyTypeACL && policy.Templated { - if !fetchedGroups { - fetchedGroups = true - if entity != nil { - directGroups, inheritedGroups, err := ps.core.identityStore.groupsByEntityID(entity.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch group memberships: {{err}}", err) - } - groups = append(directGroups, inheritedGroups...) - } - } - p, err := parseACLPolicyWithTemplating(policy.Raw, true, entity, groups) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error parsing templated policy %q: {{err}}", policy.Name), err) - } - policies[i] = p - } - } - - // Construct the ACL - acl, err := NewACL(policies) - if err != nil { - return nil, errwrap.Wrapf("failed to construct ACL: {{err}}", err) - } - return acl, nil -} - -func (ps *PolicyStore) loadACLPolicy(ctx context.Context, policyName, policyText string) error { - // Check if the policy already exists - policy, err := ps.GetPolicy(ctx, policyName, PolicyTypeACL) - - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error fetching %s policy from store: {{err}}", policyName), err) - } - - if policy != nil { - if !strutil.StrListContains(immutablePolicies, policyName) || policyText == policy.Raw { - return nil - } - } - - policy, err = ParseACLPolicy(policyText) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("error parsing %s policy: {{err}}", policyName), err) - } - - if policy == nil { - return fmt.Errorf("parsing %q policy resulted in nil policy", policyName) - } - - policy.Name = policyName - policy.Type = PolicyTypeACL - return ps.setPolicyInternal(ctx, policy) -} - -func (ps *PolicyStore) sanitizeName(name string) string { - return strings.ToLower(strings.TrimSpace(name)) -} diff --git a/vendor/github.com/hashicorp/vault/vault/rekey.go b/vendor/github.com/hashicorp/vault/vault/rekey.go deleted file mode 100644 index 89b357370..000000000 --- a/vendor/github.com/hashicorp/vault/vault/rekey.go +++ /dev/null @@ -1,968 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/subtle" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/pgpkeys" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" - "github.com/hashicorp/vault/shamir" -) - -const ( - // coreUnsealKeysBackupPath is the path used to backup encrypted unseal - // keys if specified during a rekey operation. This is outside of the - // barrier. - coreBarrierUnsealKeysBackupPath = "core/unseal-keys-backup" - - // coreRecoveryUnsealKeysBackupPath is the path used to backup encrypted - // recovery keys if specified during a rekey operation. This is outside of - // the barrier. - coreRecoveryUnsealKeysBackupPath = "core/recovery-keys-backup" -) - -// RekeyResult is used to provide the key parts back after -// they are generated as part of the rekey. -type RekeyResult struct { - SecretShares [][]byte - PGPFingerprints []string - Backup bool - RecoveryKey bool - VerificationRequired bool - VerificationNonce string -} - -type RekeyVerifyResult struct { - Complete bool - Nonce string -} - -// RekeyBackup stores the backup copy of PGP-encrypted keys -type RekeyBackup struct { - Nonce string - Keys map[string][]string -} - -// RekeyThreshold returns the secret threshold for the current seal -// config. This threshold can either be the barrier key threshold or -// the recovery key threshold, depending on whether rekey is being -// performed on the recovery key, or whether the seal supports -// recovery keys. -func (c *Core) RekeyThreshold(ctx context.Context, recovery bool) (int, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return 0, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return 0, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var config *SealConfig - var err error - // If we are rekeying the recovery key, or if the seal supports - // recovery keys and we are rekeying the barrier key, we use the - // recovery config as the threshold instead. - if recovery || c.seal.RecoveryKeySupported() { - config, err = c.seal.RecoveryConfig(ctx) - } else { - config, err = c.seal.BarrierConfig(ctx) - } - if err != nil { - return 0, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("unable to look up config: {{err}}", err).Error()) - } - if config == nil { - return 0, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - return config.SecretThreshold, nil -} - -// RekeyProgress is used to return the rekey progress (num shares). -func (c *Core) RekeyProgress(recovery, verification bool) (bool, int, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return false, 0, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return false, 0, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var conf *SealConfig - if recovery { - conf = c.recoveryRekeyConfig - } else { - conf = c.barrierRekeyConfig - } - - if conf == nil { - return false, 0, logical.CodedError(http.StatusBadRequest, "rekey operation not in progress") - } - - if verification { - return len(conf.VerificationKey) > 0, len(conf.VerificationProgress), nil - } - return true, len(conf.RekeyProgress), nil -} - -// RekeyConfig is used to read the rekey configuration -func (c *Core) RekeyConfig(recovery bool) (*SealConfig, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Copy the seal config if any - var conf *SealConfig - if recovery { - if c.recoveryRekeyConfig != nil { - conf = c.recoveryRekeyConfig.Clone() - } - } else { - if c.barrierRekeyConfig != nil { - conf = c.barrierRekeyConfig.Clone() - } - } - - return conf, nil -} - -// RekeyInit will either initialize the rekey of barrier or recovery key. -// recovery determines whether this is a rekey on the barrier or recovery key. -func (c *Core) RekeyInit(config *SealConfig, recovery bool) logical.HTTPCodedError { - if config.SecretThreshold > config.SecretShares { - return logical.CodedError(http.StatusBadRequest, "provided threshold greater than the total shares") - } - - if recovery { - return c.RecoveryRekeyInit(config) - } - return c.BarrierRekeyInit(config) -} - -// BarrierRekeyInit is used to initialize the rekey settings for the barrier key -func (c *Core) BarrierRekeyInit(config *SealConfig) logical.HTTPCodedError { - if c.seal.StoredKeysSupported() { - c.logger.Warn("stored keys supported, forcing rekey shares/threshold to 1") - config.SecretShares = 1 - config.SecretThreshold = 1 - config.StoredShares = 1 - } - - if config.StoredShares > 0 { - if !c.seal.StoredKeysSupported() { - return logical.CodedError(http.StatusBadRequest, "storing keys not supported by barrier seal") - } - if len(config.PGPKeys) > 0 { - return logical.CodedError(http.StatusBadRequest, "PGP key encryption not supported when using stored keys") - } - if config.Backup { - return logical.CodedError(http.StatusBadRequest, "key backup not supported when using stored keys") - } - - if c.seal.RecoveryKeySupported() { - if config.VerificationRequired { - return logical.CodedError(http.StatusBadRequest, "requiring verification not supported when rekeying the barrier key with recovery keys") - } - c.logger.Debug("using recovery seal configuration to rekey barrier key") - } - } - - // Check if the seal configuration is valid - if err := config.Validate(); err != nil { - c.logger.Error("invalid rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid rekey seal configuration: {{err}}", err).Error()) - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Prevent multiple concurrent re-keys - if c.barrierRekeyConfig != nil { - return logical.CodedError(http.StatusBadRequest, "rekey already in progress") - } - - // Copy the configuration - c.barrierRekeyConfig = config.Clone() - - // Initialize the nonce - nonce, err := uuid.GenerateUUID() - if err != nil { - c.barrierRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) - } - c.barrierRekeyConfig.Nonce = nonce - - if c.logger.IsInfo() { - c.logger.Info("rekey initialized", "nonce", c.barrierRekeyConfig.Nonce, "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold, "validation_required", c.barrierRekeyConfig.VerificationRequired) - } - return nil -} - -// RecoveryRekeyInit is used to initialize the rekey settings for the recovery key -func (c *Core) RecoveryRekeyInit(config *SealConfig) logical.HTTPCodedError { - if config.StoredShares > 0 { - return logical.CodedError(http.StatusBadRequest, "stored shares not supported by recovery key") - } - - // Check if the seal configuration is valid - if err := config.Validate(); err != nil { - c.logger.Error("invalid recovery configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid recovery configuration: {{err}}", err).Error()) - } - - if !c.seal.RecoveryKeySupported() { - return logical.CodedError(http.StatusBadRequest, "recovery keys not supported") - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Prevent multiple concurrent re-keys - if c.recoveryRekeyConfig != nil { - return logical.CodedError(http.StatusBadRequest, "rekey already in progress") - } - - // Copy the configuration - c.recoveryRekeyConfig = config.Clone() - - // Initialize the nonce - nonce, err := uuid.GenerateUUID() - if err != nil { - c.recoveryRekeyConfig = nil - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error()) - } - c.recoveryRekeyConfig.Nonce = nonce - - if c.logger.IsInfo() { - c.logger.Info("rekey initialized", "nonce", c.recoveryRekeyConfig.Nonce, "shares", c.recoveryRekeyConfig.SecretShares, "threshold", c.recoveryRekeyConfig.SecretThreshold, "validation_required", c.recoveryRekeyConfig.VerificationRequired) - } - return nil -} - -// RekeyUpdate is used to provide a new key part for the barrier or recovery key. -func (c *Core) RekeyUpdate(ctx context.Context, key []byte, nonce string, recovery bool) (*RekeyResult, logical.HTTPCodedError) { - if recovery { - return c.RecoveryRekeyUpdate(ctx, key, nonce) - } - return c.BarrierRekeyUpdate(ctx, key, nonce) -} - -// BarrierRekeyUpdate is used to provide a new key part. Barrier rekey can be done -// with unseal keys, or recovery keys if that's supported and we are storing the barrier -// key. -// -// N.B.: If recovery keys are used to rekey, the new barrier key shares are not returned. -func (c *Core) BarrierRekeyUpdate(ctx context.Context, key []byte, nonce string) (*RekeyResult, logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Get the seal configuration - var existingConfig *SealConfig - var err error - var useRecovery bool // Determines whether recovery key is being used to rekey the master key - if c.seal.StoredKeysSupported() && c.seal.RecoveryKeySupported() { - existingConfig, err = c.seal.RecoveryConfig(ctx) - useRecovery = true - } else { - existingConfig, err = c.seal.BarrierConfig(ctx) - } - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing config: {{err}}", err).Error()) - } - // Ensure the barrier is initialized - if existingConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - // Ensure a rekey is in progress - if c.barrierRekeyConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no barrier rekey in progress") - } - - if len(c.barrierRekeyConfig.VerificationKey) > 0 { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("rekey operation already finished; verification must be performed; nonce for the verification operation is %q", c.barrierRekeyConfig.VerificationNonce)) - } - - if nonce != c.barrierRekeyConfig.Nonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this rekey operation is %q", c.barrierRekeyConfig.Nonce)) - } - - // Check if we already have this piece - for _, existing := range c.barrierRekeyConfig.RekeyProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this generation operation") - } - } - - // Store this key - c.barrierRekeyConfig.RekeyProgress = append(c.barrierRekeyConfig.RekeyProgress, key) - - // Check if we don't have enough keys to unlock - if len(c.barrierRekeyConfig.RekeyProgress) < existingConfig.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot rekey yet, not enough keys", "keys", len(c.barrierRekeyConfig.RekeyProgress), "threshold", existingConfig.SecretThreshold) - } - return nil, nil - } - - // Recover the master key or recovery key - var recoveredKey []byte - if existingConfig.SecretThreshold == 1 { - recoveredKey = c.barrierRekeyConfig.RekeyProgress[0] - } else { - recoveredKey, err = shamir.Combine(c.barrierRekeyConfig.RekeyProgress) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute master key: {{err}}", err).Error()) - } - } - - if useRecovery { - if err := c.seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil { - c.logger.Error("rekey recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) - } - } else { - if err := c.barrier.VerifyMaster(recoveredKey); err != nil { - c.logger.Error("master key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("master key verification failed: {{err}}", err).Error()) - } - } - - // Generate a new master key - newMasterKey, err := c.barrier.GenerateKey() - if err != nil { - c.logger.Error("failed to generate master key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("master key generation failed: {{err}}", err).Error()) - } - - results := &RekeyResult{ - Backup: c.barrierRekeyConfig.Backup, - } - // Set result.SecretShares to the master key if only a single key - // part is used -- no Shamir split required. - if c.barrierRekeyConfig.SecretShares == 1 { - results.SecretShares = append(results.SecretShares, newMasterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(newMasterKey, c.barrierRekeyConfig.SecretShares, c.barrierRekeyConfig.SecretThreshold) - if err != nil { - c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) - } - results.SecretShares = shares - } - - // If we are storing any shares, add them to the shares to store and remove - // from the returned keys - var keysToStore [][]byte - if c.seal.StoredKeysSupported() && c.barrierRekeyConfig.StoredShares > 0 { - for i := 0; i < c.barrierRekeyConfig.StoredShares; i++ { - keysToStore = append(keysToStore, results.SecretShares[0]) - results.SecretShares = results.SecretShares[1:] - } - } - - // If PGP keys are passed in, encrypt shares with corresponding PGP keys. - if len(c.barrierRekeyConfig.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(results.SecretShares)) - for i, _ := range results.SecretShares { - hexEncodedShares[i] = []byte(hex.EncodeToString(results.SecretShares[i])) - } - results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.barrierRekeyConfig.PGPKeys) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) - } - - // If backup is enabled, store backup info in vault.coreBarrierUnsealKeysBackupPath - if c.barrierRekeyConfig.Backup { - backupInfo := map[string][]string{} - for i := 0; i < len(results.PGPFingerprints); i++ { - encShare := bytes.NewBuffer(results.SecretShares[i]) - if backupInfo[results.PGPFingerprints[i]] == nil { - backupInfo[results.PGPFingerprints[i]] = []string{hex.EncodeToString(encShare.Bytes())} - } else { - backupInfo[results.PGPFingerprints[i]] = append(backupInfo[results.PGPFingerprints[i]], hex.EncodeToString(encShare.Bytes())) - } - } - - backupVals := &RekeyBackup{ - Nonce: c.barrierRekeyConfig.Nonce, - Keys: backupInfo, - } - buf, err := json.Marshal(backupVals) - if err != nil { - c.logger.Error("failed to marshal unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal unseal key backup: {{err}}", err).Error()) - } - pe := &physical.Entry{ - Key: coreBarrierUnsealKeysBackupPath, - Value: buf, - } - if err = c.physical.Put(ctx, pe); err != nil { - c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) - } - } - } - - if keysToStore != nil { - if err := c.seal.SetStoredKeys(ctx, keysToStore); err != nil { - c.logger.Error("failed to store keys", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to store keys: {{err}}", err).Error()) - } - } - - // If we are requiring validation, return now; otherwise rekey the barrier - if c.barrierRekeyConfig.VerificationRequired { - nonce, err := uuid.GenerateUUID() - if err != nil { - c.barrierRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) - } - c.barrierRekeyConfig.VerificationNonce = nonce - c.barrierRekeyConfig.VerificationKey = newMasterKey - - results.VerificationRequired = true - results.VerificationNonce = nonce - return results, nil - } - - if err := c.performBarrierRekey(ctx, newMasterKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform barrier rekey: {{err}}", err).Error()) - } - - c.barrierRekeyConfig = nil - return results, nil -} - -func (c *Core) performBarrierRekey(ctx context.Context, newMasterKey []byte) logical.HTTPCodedError { - // Rekey the barrier - if err := c.barrier.Rekey(ctx, newMasterKey); err != nil { - c.logger.Error("failed to rekey barrier", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to rekey barrier: {{err}}", err).Error()) - } - if c.logger.IsInfo() { - c.logger.Info("security barrier rekeyed", "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold) - } - - c.barrierRekeyConfig.VerificationKey = nil - - if err := c.seal.SetBarrierConfig(ctx, c.barrierRekeyConfig); err != nil { - c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := c.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(c.barrierRekeyConfig.Nonce), - }); err != nil { - c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) - } - - c.barrierRekeyConfig.RekeyProgress = nil - - return nil -} - -// RecoveryRekeyUpdate is used to provide a new key part -func (c *Core) RecoveryRekeyUpdate(ctx context.Context, key []byte, nonce string) (*RekeyResult, logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Get the seal configuration - existingConfig, err := c.seal.RecoveryConfig(ctx) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to fetch existing recovery config: {{err}}", err).Error()) - } - // Ensure the seal is initialized - if existingConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, ErrNotInit.Error()) - } - - // Ensure a rekey is in progress - if c.recoveryRekeyConfig == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no recovery rekey in progress") - } - - if len(c.recoveryRekeyConfig.VerificationKey) > 0 { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("rekey operation already finished; verification must be performed; nonce for the verification operation is %q", c.recoveryRekeyConfig.VerificationNonce)) - } - - if nonce != c.recoveryRekeyConfig.Nonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this rekey operation is %q", c.recoveryRekeyConfig.Nonce)) - } - - // Check if we already have this piece - for _, existing := range c.recoveryRekeyConfig.RekeyProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this rekey operation") - } - } - - // Store this key - c.recoveryRekeyConfig.RekeyProgress = append(c.recoveryRekeyConfig.RekeyProgress, key) - - // Check if we don't have enough keys to unlock - if len(c.recoveryRekeyConfig.RekeyProgress) < existingConfig.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot rekey yet, not enough keys", "keys", len(c.recoveryRekeyConfig.RekeyProgress), "threshold", existingConfig.SecretThreshold) - } - return nil, nil - } - - // Recover the master key - var recoveryKey []byte - if existingConfig.SecretThreshold == 1 { - recoveryKey = c.recoveryRekeyConfig.RekeyProgress[0] - } else { - recoveryKey, err = shamir.Combine(c.recoveryRekeyConfig.RekeyProgress) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute recovery key: {{err}}", err).Error()) - } - } - - // Verify the recovery key - if err := c.seal.VerifyRecoveryKey(ctx, recoveryKey); err != nil { - c.logger.Error("recovery key verification failed", "error", err) - return nil, logical.CodedError(http.StatusBadRequest, errwrap.Wrapf("recovery key verification failed: {{err}}", err).Error()) - } - - // Generate a new master key - newMasterKey, err := c.barrier.GenerateKey() - if err != nil { - c.logger.Error("failed to generate recovery key", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("recovery key generation failed: {{err}}", err).Error()) - } - - // Return the master key if only a single key part is used - results := &RekeyResult{ - Backup: c.recoveryRekeyConfig.Backup, - } - - if c.recoveryRekeyConfig.SecretShares == 1 { - results.SecretShares = append(results.SecretShares, newMasterKey) - } else { - // Split the master key using the Shamir algorithm - shares, err := shamir.Split(newMasterKey, c.recoveryRekeyConfig.SecretShares, c.recoveryRekeyConfig.SecretThreshold) - if err != nil { - c.logger.Error("failed to generate shares", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate shares: {{err}}", err).Error()) - } - results.SecretShares = shares - } - - if len(c.recoveryRekeyConfig.PGPKeys) > 0 { - hexEncodedShares := make([][]byte, len(results.SecretShares)) - for i, _ := range results.SecretShares { - hexEncodedShares[i] = []byte(hex.EncodeToString(results.SecretShares[i])) - } - results.PGPFingerprints, results.SecretShares, err = pgpkeys.EncryptShares(hexEncodedShares, c.recoveryRekeyConfig.PGPKeys) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to encrypt shares: {{err}}", err).Error()) - } - - if c.recoveryRekeyConfig.Backup { - backupInfo := map[string][]string{} - for i := 0; i < len(results.PGPFingerprints); i++ { - encShare := bytes.NewBuffer(results.SecretShares[i]) - if backupInfo[results.PGPFingerprints[i]] == nil { - backupInfo[results.PGPFingerprints[i]] = []string{hex.EncodeToString(encShare.Bytes())} - } else { - backupInfo[results.PGPFingerprints[i]] = append(backupInfo[results.PGPFingerprints[i]], hex.EncodeToString(encShare.Bytes())) - } - } - - backupVals := &RekeyBackup{ - Nonce: c.recoveryRekeyConfig.Nonce, - Keys: backupInfo, - } - buf, err := json.Marshal(backupVals) - if err != nil { - c.logger.Error("failed to marshal recovery key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to marshal recovery key backup: {{err}}", err).Error()) - } - pe := &physical.Entry{ - Key: coreRecoveryUnsealKeysBackupPath, - Value: buf, - } - if err = c.physical.Put(ctx, pe); err != nil { - c.logger.Error("failed to save unseal key backup", "error", err) - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save unseal key backup: {{err}}", err).Error()) - } - } - } - - // If we are requiring validation, return now; otherwise save the recovery - // key - if c.recoveryRekeyConfig.VerificationRequired { - nonce, err := uuid.GenerateUUID() - if err != nil { - c.recoveryRekeyConfig = nil - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to generate verification nonce: {{err}}", err).Error()) - } - c.recoveryRekeyConfig.VerificationNonce = nonce - c.recoveryRekeyConfig.VerificationKey = newMasterKey - - results.VerificationRequired = true - results.VerificationNonce = nonce - return results, nil - } - - if err := c.performRecoveryRekey(ctx, newMasterKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery rekey: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig = nil - return results, nil -} - -func (c *Core) performRecoveryRekey(ctx context.Context, newMasterKey []byte) logical.HTTPCodedError { - if err := c.seal.SetRecoveryKey(ctx, newMasterKey); err != nil { - c.logger.Error("failed to set recovery key", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to set recovery key: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig.VerificationKey = nil - - if err := c.seal.SetRecoveryConfig(ctx, c.recoveryRekeyConfig); err != nil { - c.logger.Error("error saving rekey seal configuration", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save rekey seal configuration: {{err}}", err).Error()) - } - - // Write to the canary path, which will force a synchronous truing during - // replication - if err := c.barrier.Put(ctx, &Entry{ - Key: coreKeyringCanaryPath, - Value: []byte(c.recoveryRekeyConfig.Nonce), - }); err != nil { - c.logger.Error("error saving keyring canary", "error", err) - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to save keyring canary: {{err}}", err).Error()) - } - - c.recoveryRekeyConfig.RekeyProgress = nil - - return nil -} - -func (c *Core) RekeyVerify(ctx context.Context, key []byte, nonce string, recovery bool) (ret *RekeyVerifyResult, retErr logical.HTTPCodedError) { - // Ensure we are already unsealed - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - // Verify the key length - min, max := c.barrier.KeyLength() - max += shamir.ShareOverhead - if len(key) < min { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is shorter than minimum %d bytes", min)) - } - if len(key) > max { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("key is longer than maximum %d bytes", max)) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - config := c.barrierRekeyConfig - if recovery { - config = c.recoveryRekeyConfig - } - - // Ensure a rekey is in progress - if config == nil { - return nil, logical.CodedError(http.StatusBadRequest, "no rekey in progress") - } - - if len(config.VerificationKey) == 0 { - return nil, logical.CodedError(http.StatusBadRequest, "no rekey verification in progress") - } - - if nonce != config.VerificationNonce { - return nil, logical.CodedError(http.StatusBadRequest, fmt.Sprintf("incorrect nonce supplied; nonce for this verify operation is %q", config.VerificationNonce)) - } - - // Check if we already have this piece - for _, existing := range config.VerificationProgress { - if subtle.ConstantTimeCompare(existing, key) == 1 { - return nil, logical.CodedError(http.StatusBadRequest, "given key has already been provided during this verify operation") - } - } - - // Store this key - config.VerificationProgress = append(config.VerificationProgress, key) - - // Check if we don't have enough keys to unlock - if len(config.VerificationProgress) < config.SecretThreshold { - if c.logger.IsDebug() { - c.logger.Debug("cannot verify yet, not enough keys", "keys", len(config.VerificationProgress), "threshold", config.SecretThreshold) - } - return nil, nil - } - - // Schedule the progress for forgetting and rotate the nonce if possible - defer func() { - config.VerificationProgress = nil - if ret != nil && ret.Complete { - return - } - // Not complete, so rotate nonce - nonce, err := uuid.GenerateUUID() - if err == nil { - config.VerificationNonce = nonce - if ret != nil { - ret.Nonce = nonce - } - } - }() - - // Recover the master key or recovery key - var recoveredKey []byte - if config.SecretThreshold == 1 { - recoveredKey = config.VerificationProgress[0] - } else { - var err error - recoveredKey, err = shamir.Combine(config.VerificationProgress) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to compute key for verification: {{err}}", err).Error()) - } - } - - if subtle.ConstantTimeCompare(recoveredKey, config.VerificationKey) != 1 { - c.logger.Error("rekey verification failed") - return nil, logical.CodedError(http.StatusBadRequest, "rekey verification failed; incorrect key shares supplied") - } - - switch recovery { - case false: - if err := c.performBarrierRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform rekey: {{err}}", err).Error()) - } - c.barrierRekeyConfig = nil - default: - if err := c.performRecoveryRekey(ctx, recoveredKey); err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("failed to perform recovery key rekey: {{err}}", err).Error()) - } - c.recoveryRekeyConfig = nil - } - - res := &RekeyVerifyResult{ - Nonce: config.VerificationNonce, - Complete: true, - } - - return res, nil -} - -// RekeyCancel is used to cancel an in-progress rekey -func (c *Core) RekeyCancel(recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Clear any progress or config - if recovery { - c.recoveryRekeyConfig = nil - } else { - c.barrierRekeyConfig = nil - } - return nil -} - -// RekeyVerifyRestart is used to start the verification process over -func (c *Core) RekeyVerifyRestart(recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - // Attempt to generate a new nonce, but don't bail if it doesn't succeed - // (which is extraordinarily unlikely) - nonce, nonceErr := uuid.GenerateUUID() - - // Clear any progress or config - if recovery { - c.recoveryRekeyConfig.VerificationProgress = nil - if nonceErr == nil { - c.recoveryRekeyConfig.VerificationNonce = nonce - } - } else { - c.barrierRekeyConfig.VerificationProgress = nil - if nonceErr == nil { - c.barrierRekeyConfig.VerificationNonce = nonce - } - } - - return nil -} - -// RekeyRetrieveBackup is used to retrieve any backed-up PGP-encrypted unseal -// keys -func (c *Core) RekeyRetrieveBackup(ctx context.Context, recovery bool) (*RekeyBackup, logical.HTTPCodedError) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return nil, logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.RLock() - defer c.rekeyLock.RUnlock() - - var entry *physical.Entry - var err error - if recovery { - entry, err = c.physical.Get(ctx, coreRecoveryUnsealKeysBackupPath) - } else { - entry, err = c.physical.Get(ctx, coreBarrierUnsealKeysBackupPath) - } - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error getting keys from backup: {{err}}", err).Error()) - } - if entry == nil { - return nil, nil - } - - ret := &RekeyBackup{} - err = jsonutil.DecodeJSON(entry.Value, ret) - if err != nil { - return nil, logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error decoding backup keys: {{err}}", err).Error()) - } - - return ret, nil -} - -// RekeyDeleteBackup is used to delete any backed-up PGP-encrypted unseal keys -func (c *Core) RekeyDeleteBackup(ctx context.Context, recovery bool) logical.HTTPCodedError { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error()) - } - if c.standby { - return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error()) - } - - c.rekeyLock.Lock() - defer c.rekeyLock.Unlock() - - if recovery { - err := c.physical.Delete(ctx, coreRecoveryUnsealKeysBackupPath) - if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) - } - return nil - } - err := c.physical.Delete(ctx, coreBarrierUnsealKeysBackupPath) - if err != nil { - return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error deleting backup keys: {{err}}", err).Error()) - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding.go deleted file mode 100644 index 5732183c2..000000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding.go +++ /dev/null @@ -1,521 +0,0 @@ -package vault - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - math "math" - "net" - "net/http" - "net/url" - "runtime" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/forwarding" - "golang.org/x/net/http2" - "google.golang.org/grpc" - "google.golang.org/grpc/keepalive" -) - -const ( - clusterListenerAcceptDeadline = 500 * time.Millisecond - requestForwardingALPN = "req_fw_sb-act_v1" -) - -var ( - // Making this a package var allows tests to modify - HeartbeatInterval = 5 * time.Second -) - -// Starts the listeners and servers necessary to handle forwarded requests -func (c *Core) startForwarding(ctx context.Context) error { - c.logger.Debug("cluster listener setup function") - defer c.logger.Debug("leaving cluster listener setup function") - - // Clean up in case we have transitioned from a client to a server - c.requestForwardingConnectionLock.Lock() - c.clearForwardingClients() - c.requestForwardingConnectionLock.Unlock() - - // Resolve locally to avoid races - ha := c.ha != nil - - // Get our TLS config - tlsConfig, err := c.ClusterTLSConfig(ctx, nil) - if err != nil { - c.logger.Error("failed to get tls configuration when starting forwarding", "error", err) - return err - } - - // The server supports all of the possible protos - tlsConfig.NextProtos = []string{"h2", requestForwardingALPN} - - if !atomic.CompareAndSwapUint32(c.rpcServerActive, 0, 1) { - c.logger.Warn("forwarding rpc server already running") - return nil - } - - fwRPCServer := grpc.NewServer( - grpc.KeepaliveParams(keepalive.ServerParameters{ - Time: 2 * HeartbeatInterval, - }), - grpc.MaxRecvMsgSize(math.MaxInt32), - grpc.MaxSendMsgSize(math.MaxInt32), - ) - - if ha && c.clusterHandler != nil { - RegisterRequestForwardingServer(fwRPCServer, &forwardedRequestRPCServer{ - core: c, - handler: c.clusterHandler, - }) - } - - // Create the HTTP/2 server that will be shared by both RPC and regular - // duties. Doing it this way instead of listening via the server and gRPC - // allows us to re-use the same port via ALPN. We can just tell the server - // to serve a given conn and which handler to use. - fws := &http2.Server{ - // Our forwarding connections heartbeat regularly so anything else we - // want to go away/get cleaned up pretty rapidly - IdleTimeout: 5 * HeartbeatInterval, - } - - // Shutdown coordination logic - shutdown := new(uint32) - shutdownWg := &sync.WaitGroup{} - - for _, addr := range c.clusterListenerAddrs { - shutdownWg.Add(1) - - // Force a local resolution to avoid data races - laddr := addr - - // Start our listening loop - go func() { - defer shutdownWg.Done() - - // closeCh is used to shutdown the spawned goroutines once this - // function returns - closeCh := make(chan struct{}) - defer func() { - close(closeCh) - }() - - if c.logger.IsInfo() { - c.logger.Info("core/startClusterListener: starting listener", "listener_address", laddr) - } - - // Create a TCP listener. We do this separately and specifically - // with TCP so that we can set deadlines. - tcpLn, err := net.ListenTCP("tcp", laddr) - if err != nil { - c.logger.Error("core/startClusterListener: error starting listener", "error", err) - return - } - - // Wrap the listener with TLS - tlsLn := tls.NewListener(tcpLn, tlsConfig) - defer tlsLn.Close() - - if c.logger.IsInfo() { - c.logger.Info("core/startClusterListener: serving cluster requests", "cluster_listen_address", tlsLn.Addr()) - } - - for { - if atomic.LoadUint32(shutdown) > 0 { - return - } - - // Set the deadline for the accept call. If it passes we'll get - // an error, causing us to check the condition at the top - // again. - tcpLn.SetDeadline(time.Now().Add(clusterListenerAcceptDeadline)) - - // Accept the connection - conn, err := tlsLn.Accept() - if err != nil { - if err, ok := err.(net.Error); ok && !err.Timeout() { - c.logger.Debug("non-timeout error accepting on cluster port", "error", err) - } - if conn != nil { - conn.Close() - } - continue - } - if conn == nil { - continue - } - - // Type assert to TLS connection and handshake to populate the - // connection state - tlsConn := conn.(*tls.Conn) - - // Set a deadline for the handshake. This will cause clients - // that don't successfully auth to be kicked out quickly. - // Cluster connections should be reliable so being marginally - // aggressive here is fine. - err = tlsConn.SetDeadline(time.Now().Add(30 * time.Second)) - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error setting deadline for cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - err = tlsConn.Handshake() - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error handshaking cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - // Now, set it back to unlimited - err = tlsConn.SetDeadline(time.Time{}) - if err != nil { - if c.logger.IsDebug() { - c.logger.Debug("error setting deadline for cluster connection", "error", err) - } - tlsConn.Close() - continue - } - - switch tlsConn.ConnectionState().NegotiatedProtocol { - case requestForwardingALPN: - if !ha { - tlsConn.Close() - continue - } - - c.logger.Debug("got request forwarding connection") - - shutdownWg.Add(2) - // quitCh is used to close the connection and the second - // goroutine if the server closes before closeCh. - quitCh := make(chan struct{}) - go func() { - select { - case <-quitCh: - case <-closeCh: - } - tlsConn.Close() - shutdownWg.Done() - }() - - go func() { - fws.ServeConn(tlsConn, &http2.ServeConnOpts{ - Handler: fwRPCServer, - BaseConfig: &http.Server{ - ErrorLog: c.logger.StandardLogger(nil), - }, - }) - // close the quitCh which will close the connection and - // the other goroutine. - close(quitCh) - shutdownWg.Done() - }() - - default: - c.logger.Debug("unknown negotiated protocol on cluster port") - tlsConn.Close() - continue - } - } - }() - } - - // This is in its own goroutine so that we don't block the main thread, and - // thus we use atomic and channels to coordinate - // However, because you can't query the status of a channel, we set a bool - // here while we have the state lock to know whether to actually send a - // shutdown (e.g. whether the channel will block). See issue #2083. - c.clusterListenersRunning = true - go func() { - // If we get told to shut down... - <-c.clusterListenerShutdownCh - - // Stop the RPC server - c.logger.Info("shutting down forwarding rpc listeners") - fwRPCServer.Stop() - - // Set the shutdown flag. This will cause the listeners to shut down - // within the deadline in clusterListenerAcceptDeadline - atomic.StoreUint32(shutdown, 1) - c.logger.Info("forwarding rpc listeners stopped") - - // Wait for them all to shut down - shutdownWg.Wait() - c.logger.Info("rpc listeners successfully shut down") - - // Clear us up to run this function again - atomic.StoreUint32(c.rpcServerActive, 0) - - // Tell the main thread that shutdown is done. - c.clusterListenerShutdownSuccessCh <- struct{}{} - }() - - return nil -} - -// refreshRequestForwardingConnection ensures that the client/transport are -// alive and that the current active address value matches the most -// recently-known address. -func (c *Core) refreshRequestForwardingConnection(ctx context.Context, clusterAddr string) error { - c.logger.Debug("refreshing forwarding connection") - defer c.logger.Debug("done refreshing forwarding connection") - - c.requestForwardingConnectionLock.Lock() - defer c.requestForwardingConnectionLock.Unlock() - - // Clean things up first - c.clearForwardingClients() - - // If we don't have anything to connect to, just return - if clusterAddr == "" { - return nil - } - - clusterURL, err := url.Parse(clusterAddr) - if err != nil { - c.logger.Error("error parsing cluster address attempting to refresh forwarding connection", "error", err) - return err - } - - // Set up grpc forwarding handling - // It's not really insecure, but we have to dial manually to get the - // ALPN header right. It's just "insecure" because GRPC isn't managing - // the TLS state. - dctx, cancelFunc := context.WithCancel(ctx) - c.rpcClientConn, err = grpc.DialContext(dctx, clusterURL.Host, - grpc.WithDialer(c.getGRPCDialer(ctx, requestForwardingALPN, "", nil, nil)), - grpc.WithInsecure(), // it's not, we handle it in the dialer - grpc.WithKeepaliveParams(keepalive.ClientParameters{ - Time: 2 * HeartbeatInterval, - }), - grpc.WithDefaultCallOptions( - grpc.MaxCallRecvMsgSize(math.MaxInt32), - grpc.MaxCallSendMsgSize(math.MaxInt32), - )) - if err != nil { - cancelFunc() - c.logger.Error("err setting up forwarding rpc client", "error", err) - return err - } - c.rpcClientConnContext = dctx - c.rpcClientConnCancelFunc = cancelFunc - c.rpcForwardingClient = &forwardingClient{ - RequestForwardingClient: NewRequestForwardingClient(c.rpcClientConn), - core: c, - echoTicker: time.NewTicker(HeartbeatInterval), - echoContext: dctx, - } - c.rpcForwardingClient.startHeartbeat() - - return nil -} - -func (c *Core) clearForwardingClients() { - c.logger.Debug("clearing forwarding clients") - defer c.logger.Debug("done clearing forwarding clients") - - if c.rpcClientConnCancelFunc != nil { - c.rpcClientConnCancelFunc() - c.rpcClientConnCancelFunc = nil - } - if c.rpcClientConn != nil { - c.rpcClientConn.Close() - c.rpcClientConn = nil - } - - c.rpcClientConnContext = nil - c.rpcForwardingClient = nil -} - -// ForwardRequest forwards a given request to the active node and returns the -// response. -func (c *Core) ForwardRequest(req *http.Request) (int, http.Header, []byte, error) { - c.requestForwardingConnectionLock.RLock() - defer c.requestForwardingConnectionLock.RUnlock() - - if c.rpcForwardingClient == nil { - return 0, nil, nil, ErrCannotForward - } - - freq, err := forwarding.GenerateForwardedRequest(req) - if err != nil { - c.logger.Error("error creating forwarding RPC request", "error", err) - return 0, nil, nil, fmt.Errorf("error creating forwarding RPC request") - } - if freq == nil { - c.logger.Error("got nil forwarding RPC request") - return 0, nil, nil, fmt.Errorf("got nil forwarding RPC request") - } - resp, err := c.rpcForwardingClient.ForwardRequest(c.rpcClientConnContext, freq) - if err != nil { - c.logger.Error("error during forwarded RPC request", "error", err) - return 0, nil, nil, fmt.Errorf("error during forwarding RPC request") - } - - var header http.Header - if resp.HeaderEntries != nil { - header = make(http.Header) - for k, v := range resp.HeaderEntries { - header[k] = v.Values - } - } - - return int(resp.StatusCode), header, resp.Body, nil -} - -// getGRPCDialer is used to return a dialer that has the correct TLS -// configuration. Otherwise gRPC tries to be helpful and stomps all over our -// NextProtos. -func (c *Core) getGRPCDialer(ctx context.Context, alpnProto, serverName string, caCert *x509.Certificate, repClusters *ReplicatedClusters) func(string, time.Duration) (net.Conn, error) { - return func(addr string, timeout time.Duration) (net.Conn, error) { - tlsConfig, err := c.ClusterTLSConfig(ctx, repClusters) - if err != nil { - c.logger.Error("failed to get tls configuration", "error", err) - return nil, err - } - if serverName != "" { - tlsConfig.ServerName = serverName - } - if caCert != nil { - pool := x509.NewCertPool() - pool.AddCert(caCert) - tlsConfig.RootCAs = pool - tlsConfig.ClientCAs = pool - } - c.logger.Debug("creating rpc dialer", "host", tlsConfig.ServerName) - - tlsConfig.NextProtos = []string{alpnProto} - dialer := &net.Dialer{ - Timeout: timeout, - } - return tls.DialWithDialer(dialer, "tcp", addr, tlsConfig) - } -} - -type forwardedRequestRPCServer struct { - core *Core - handler http.Handler -} - -func (s *forwardedRequestRPCServer) ForwardRequest(ctx context.Context, freq *forwarding.Request) (*forwarding.Response, error) { - //s.core.logger.Debug("forwarding: serving rpc forwarded request") - - // Parse an http.Request out of it - req, err := forwarding.ParseForwardedRequest(freq) - if err != nil { - return nil, err - } - - // A very dummy response writer that doesn't follow normal semantics, just - // lets you write a status code (last written wins) and a body. But it - // meets the interface requirements. - w := forwarding.NewRPCResponseWriter() - - resp := &forwarding.Response{} - - runRequest := func() { - defer func() { - // Logic here comes mostly from the Go source code - if err := recover(); err != nil { - const size = 64 << 10 - buf := make([]byte, size) - buf = buf[:runtime.Stack(buf, false)] - s.core.logger.Error("forwarding: panic serving request", "path", req.URL.Path, "error", err, "stacktrace", string(buf)) - } - }() - s.handler.ServeHTTP(w, req) - } - runRequest() - resp.StatusCode = uint32(w.StatusCode()) - resp.Body = w.Body().Bytes() - - header := w.Header() - if header != nil { - resp.HeaderEntries = make(map[string]*forwarding.HeaderEntry, len(header)) - for k, v := range header { - resp.HeaderEntries[k] = &forwarding.HeaderEntry{ - Values: v, - } - } - } - - return resp, nil -} - -func (s *forwardedRequestRPCServer) Echo(ctx context.Context, in *EchoRequest) (*EchoReply, error) { - if in.ClusterAddr != "" { - s.core.clusterPeerClusterAddrsCache.Set(in.ClusterAddr, nil, 0) - } - return &EchoReply{ - Message: "pong", - ReplicationState: uint32(s.core.ReplicationState()), - }, nil -} - -type forwardingClient struct { - RequestForwardingClient - - core *Core - - echoTicker *time.Ticker - echoContext context.Context -} - -// NOTE: we also take advantage of gRPC's keepalive bits, but as we send data -// with these requests it's useful to keep this as well -func (c *forwardingClient) startHeartbeat() { - go func() { - tick := func() { - c.core.stateLock.RLock() - clusterAddr := c.core.clusterAddr - c.core.stateLock.RUnlock() - - ctx, cancel := context.WithTimeout(c.echoContext, 2*time.Second) - resp, err := c.RequestForwardingClient.Echo(ctx, &EchoRequest{ - Message: "ping", - ClusterAddr: clusterAddr, - }) - cancel() - if err != nil { - c.core.logger.Debug("forwarding: error sending echo request to active node", "error", err) - return - } - if resp == nil { - c.core.logger.Debug("forwarding: empty echo response from active node") - return - } - if resp.Message != "pong" { - c.core.logger.Debug("forwarding: unexpected echo response from active node", "message", resp.Message) - return - } - // Store the active node's replication state to display in - // sys/health calls - atomic.StoreUint32(c.core.activeNodeReplicationState, resp.ReplicationState) - //c.core.logger.Debug("forwarding: successful heartbeat") - } - - tick() - - for { - select { - case <-c.echoContext.Done(): - c.echoTicker.Stop() - c.core.logger.Debug("forwarding: stopping heartbeating") - atomic.StoreUint32(c.core.activeNodeReplicationState, uint32(consts.ReplicationUnknown)) - return - case <-c.echoTicker.C: - tick() - } - } - }() -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go b/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go deleted file mode 100644 index 1461feced..000000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.pb.go +++ /dev/null @@ -1,274 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: vault/request_forwarding_service.proto - -package vault // import "github.com/hashicorp/vault/vault" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import forwarding "github.com/hashicorp/vault/helper/forwarding" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type EchoRequest struct { - Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - // ClusterAddr is used to send up a standby node's address to the active - // node upon heartbeat - ClusterAddr string `protobuf:"bytes,2,opt,name=cluster_addr,json=clusterAddr,proto3" json:"cluster_addr,omitempty"` - // ClusterAddrs is used to send up a list of cluster addresses to a dr - // primary from a dr secondary - ClusterAddrs []string `protobuf:"bytes,3,rep,name=cluster_addrs,json=clusterAddrs,proto3" json:"cluster_addrs,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoRequest) Reset() { *m = EchoRequest{} } -func (m *EchoRequest) String() string { return proto.CompactTextString(m) } -func (*EchoRequest) ProtoMessage() {} -func (*EchoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_request_forwarding_service_9602fb43b1d0ebdf, []int{0} -} -func (m *EchoRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoRequest.Unmarshal(m, b) -} -func (m *EchoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoRequest.Marshal(b, m, deterministic) -} -func (dst *EchoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoRequest.Merge(dst, src) -} -func (m *EchoRequest) XXX_Size() int { - return xxx_messageInfo_EchoRequest.Size(m) -} -func (m *EchoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_EchoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoRequest proto.InternalMessageInfo - -func (m *EchoRequest) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *EchoRequest) GetClusterAddr() string { - if m != nil { - return m.ClusterAddr - } - return "" -} - -func (m *EchoRequest) GetClusterAddrs() []string { - if m != nil { - return m.ClusterAddrs - } - return nil -} - -type EchoReply struct { - Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - ClusterAddrs []string `protobuf:"bytes,2,rep,name=cluster_addrs,json=clusterAddrs,proto3" json:"cluster_addrs,omitempty"` - ReplicationState uint32 `protobuf:"varint,3,opt,name=replication_state,json=replicationState,proto3" json:"replication_state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoReply) Reset() { *m = EchoReply{} } -func (m *EchoReply) String() string { return proto.CompactTextString(m) } -func (*EchoReply) ProtoMessage() {} -func (*EchoReply) Descriptor() ([]byte, []int) { - return fileDescriptor_request_forwarding_service_9602fb43b1d0ebdf, []int{1} -} -func (m *EchoReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoReply.Unmarshal(m, b) -} -func (m *EchoReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoReply.Marshal(b, m, deterministic) -} -func (dst *EchoReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoReply.Merge(dst, src) -} -func (m *EchoReply) XXX_Size() int { - return xxx_messageInfo_EchoReply.Size(m) -} -func (m *EchoReply) XXX_DiscardUnknown() { - xxx_messageInfo_EchoReply.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoReply proto.InternalMessageInfo - -func (m *EchoReply) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *EchoReply) GetClusterAddrs() []string { - if m != nil { - return m.ClusterAddrs - } - return nil -} - -func (m *EchoReply) GetReplicationState() uint32 { - if m != nil { - return m.ReplicationState - } - return 0 -} - -func init() { - proto.RegisterType((*EchoRequest)(nil), "vault.EchoRequest") - proto.RegisterType((*EchoReply)(nil), "vault.EchoReply") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// RequestForwardingClient is the client API for RequestForwarding service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RequestForwardingClient interface { - ForwardRequest(ctx context.Context, in *forwarding.Request, opts ...grpc.CallOption) (*forwarding.Response, error) - Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error) -} - -type requestForwardingClient struct { - cc *grpc.ClientConn -} - -func NewRequestForwardingClient(cc *grpc.ClientConn) RequestForwardingClient { - return &requestForwardingClient{cc} -} - -func (c *requestForwardingClient) ForwardRequest(ctx context.Context, in *forwarding.Request, opts ...grpc.CallOption) (*forwarding.Response, error) { - out := new(forwarding.Response) - err := c.cc.Invoke(ctx, "/vault.RequestForwarding/ForwardRequest", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *requestForwardingClient) Echo(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoReply, error) { - out := new(EchoReply) - err := c.cc.Invoke(ctx, "/vault.RequestForwarding/Echo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// RequestForwardingServer is the server API for RequestForwarding service. -type RequestForwardingServer interface { - ForwardRequest(context.Context, *forwarding.Request) (*forwarding.Response, error) - Echo(context.Context, *EchoRequest) (*EchoReply, error) -} - -func RegisterRequestForwardingServer(s *grpc.Server, srv RequestForwardingServer) { - s.RegisterService(&_RequestForwarding_serviceDesc, srv) -} - -func _RequestForwarding_ForwardRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(forwarding.Request) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RequestForwardingServer).ForwardRequest(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/vault.RequestForwarding/ForwardRequest", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RequestForwardingServer).ForwardRequest(ctx, req.(*forwarding.Request)) - } - return interceptor(ctx, in, info, handler) -} - -func _RequestForwarding_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EchoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RequestForwardingServer).Echo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/vault.RequestForwarding/Echo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RequestForwardingServer).Echo(ctx, req.(*EchoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _RequestForwarding_serviceDesc = grpc.ServiceDesc{ - ServiceName: "vault.RequestForwarding", - HandlerType: (*RequestForwardingServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ForwardRequest", - Handler: _RequestForwarding_ForwardRequest_Handler, - }, - { - MethodName: "Echo", - Handler: _RequestForwarding_Echo_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "vault/request_forwarding_service.proto", -} - -func init() { - proto.RegisterFile("vault/request_forwarding_service.proto", fileDescriptor_request_forwarding_service_9602fb43b1d0ebdf) -} - -var fileDescriptor_request_forwarding_service_9602fb43b1d0ebdf = []byte{ - // 297 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x41, 0x4b, 0xfb, 0x40, - 0x10, 0xc5, 0x9b, 0xf6, 0xff, 0x57, 0xba, 0x6d, 0xa5, 0x5d, 0x3d, 0x84, 0x82, 0x10, 0x23, 0x48, - 0x40, 0xd8, 0x80, 0x9e, 0x3d, 0x28, 0xe8, 0x07, 0x88, 0x37, 0x2f, 0x61, 0xbb, 0x19, 0x93, 0x85, - 0x6d, 0x76, 0xdd, 0xd9, 0xb4, 0xe4, 0xea, 0x27, 0x97, 0x26, 0xa9, 0x4d, 0x29, 0x78, 0x19, 0x98, - 0x37, 0x8f, 0x37, 0xcc, 0x6f, 0xc8, 0xdd, 0x86, 0x57, 0xca, 0xc5, 0x16, 0xbe, 0x2a, 0x40, 0x97, - 0x7e, 0x6a, 0xbb, 0xe5, 0x36, 0x93, 0x65, 0x9e, 0x22, 0xd8, 0x8d, 0x14, 0xc0, 0x8c, 0xd5, 0x4e, - 0xd3, 0xff, 0x8d, 0x6f, 0x79, 0x5d, 0x80, 0x32, 0x60, 0xe3, 0x83, 0x2f, 0x76, 0xb5, 0x01, 0x6c, - 0x5d, 0xa1, 0x26, 0x93, 0x57, 0x51, 0xe8, 0xa4, 0x4d, 0xa3, 0x3e, 0x39, 0x5f, 0x03, 0x22, 0xcf, - 0xc1, 0xf7, 0x02, 0x2f, 0x1a, 0x27, 0xfb, 0x96, 0xde, 0x90, 0xa9, 0x50, 0x15, 0x3a, 0xb0, 0x29, - 0xcf, 0x32, 0xeb, 0x0f, 0x9b, 0xf1, 0xa4, 0xd3, 0x9e, 0xb3, 0xcc, 0xd2, 0x5b, 0x32, 0xeb, 0x5b, - 0xd0, 0x1f, 0x05, 0xa3, 0x68, 0x9c, 0x4c, 0x7b, 0x1e, 0x0c, 0xb7, 0x64, 0xdc, 0x2e, 0x34, 0xaa, - 0xfe, 0x63, 0xdd, 0x49, 0xd6, 0xf0, 0x34, 0x8b, 0xde, 0x93, 0x85, 0x05, 0xa3, 0xa4, 0xe0, 0x4e, - 0xea, 0x32, 0x45, 0xc7, 0x1d, 0xf8, 0xa3, 0xc0, 0x8b, 0x66, 0xc9, 0xbc, 0x37, 0x78, 0xdf, 0xe9, - 0x0f, 0xdf, 0x1e, 0x59, 0x74, 0x67, 0xbe, 0xfd, 0xb2, 0xa0, 0x4f, 0xe4, 0xa2, 0xeb, 0xf6, 0x08, - 0x2e, 0xd9, 0x01, 0x15, 0xeb, 0xc4, 0xe5, 0xd5, 0xb1, 0x88, 0x46, 0x97, 0x08, 0xe1, 0x80, 0x32, - 0xf2, 0x6f, 0x77, 0x0d, 0xa5, 0xac, 0xa1, 0xcd, 0x7a, 0x2c, 0x97, 0xf3, 0x23, 0xcd, 0xa8, 0x3a, - 0x1c, 0xbc, 0x84, 0x1f, 0x41, 0x2e, 0x5d, 0x51, 0xad, 0x98, 0xd0, 0xeb, 0xb8, 0xe0, 0x58, 0x48, - 0xa1, 0xad, 0x89, 0xdb, 0x9f, 0x36, 0x75, 0x75, 0xd6, 0x7c, 0xe6, 0xf1, 0x27, 0x00, 0x00, 0xff, - 0xff, 0xfe, 0x9f, 0x88, 0xc6, 0xe9, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto b/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto deleted file mode 100644 index ba32f7dfb..000000000 --- a/vendor/github.com/hashicorp/vault/vault/request_forwarding_service.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/hashicorp/vault/vault"; - -import "helper/forwarding/types.proto"; - -package vault; - -message EchoRequest { - string message = 1; - // ClusterAddr is used to send up a standby node's address to the active - // node upon heartbeat - string cluster_addr = 2; - // ClusterAddrs is used to send up a list of cluster addresses to a dr - // primary from a dr secondary - repeated string cluster_addrs = 3; -} - -message EchoReply { - string message = 1; - repeated string cluster_addrs = 2; - uint32 replication_state = 3; -} - -service RequestForwarding { - rpc ForwardRequest(forwarding.Request) returns (forwarding.Response) {} - rpc Echo(EchoRequest) returns (EchoReply) {} -} diff --git a/vendor/github.com/hashicorp/vault/vault/request_handling.go b/vendor/github.com/hashicorp/vault/vault/request_handling.go deleted file mode 100644 index 8b5b8d5b1..000000000 --- a/vendor/github.com/hashicorp/vault/vault/request_handling.go +++ /dev/null @@ -1,896 +0,0 @@ -package vault - -import ( - "context" - "errors" - "fmt" - "strings" - "time" - - "github.com/armon/go-metrics" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - sockaddr "github.com/hashicorp/go-sockaddr" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/errutil" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/helper/wrapping" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" -) - -const ( - replTimeout = 10 * time.Second -) - -var ( - // DefaultMaxRequestDuration is the amount of time we'll wait for a request - // to complete, unless overridden on a per-handler basis - DefaultMaxRequestDuration = 90 * time.Second -) - -// HandlerProperties is used to seed configuration into a vaulthttp.Handler. -// It's in this package to avoid a circular dependency -type HandlerProperties struct { - Core *Core - MaxRequestSize int64 - MaxRequestDuration time.Duration - DisablePrintableCheck bool -} - -// fetchEntityAndDerivedPolicies returns the entity object for the given entity -// ID. If the entity is merged into a different entity object, the entity into -// which the given entity ID is merged into will be returned. This function -// also returns the cumulative list of policies that the entity is entitled to. -// This list includes the policies from the entity itself and from all the -// groups in which the given entity ID is a member of. -func (c *Core) fetchEntityAndDerivedPolicies(entityID string) (*identity.Entity, []string, error) { - if entityID == "" || c.identityStore == nil { - return nil, nil, nil - } - - //c.logger.Debug("entity set on the token", "entity_id", te.EntityID) - - // Fetch the entity - entity, err := c.identityStore.MemDBEntityByID(entityID, false) - if err != nil { - c.logger.Error("failed to lookup entity using its ID", "error", err) - return nil, nil, err - } - - if entity == nil { - // If there was no corresponding entity object found, it is - // possible that the entity got merged into another entity. Try - // finding entity based on the merged entity index. - entity, err = c.identityStore.MemDBEntityByMergedEntityID(entityID, false) - if err != nil { - c.logger.Error("failed to lookup entity in merged entity ID index", "error", err) - return nil, nil, err - } - } - - var policies []string - if entity != nil { - //c.logger.Debug("entity successfully fetched; adding entity policies to token's policies to create ACL") - - // Attach the policies on the entity - policies = append(policies, entity.Policies...) - - groupPolicies, err := c.identityStore.groupPoliciesByEntityID(entity.ID) - if err != nil { - c.logger.Error("failed to fetch group policies", "error", err) - return nil, nil, err - } - - // Attach the policies from all the groups - policies = append(policies, groupPolicies...) - } - - return entity, policies, err -} - -func (c *Core) fetchACLTokenEntryAndEntity(req *logical.Request) (*ACL, *logical.TokenEntry, *identity.Entity, []string, error) { - defer metrics.MeasureSince([]string{"core", "fetch_acl_and_token"}, time.Now()) - - // Ensure there is a client token - if req.ClientToken == "" { - return nil, nil, nil, nil, fmt.Errorf("missing client token") - } - - if c.tokenStore == nil { - c.logger.Error("token store is unavailable") - return nil, nil, nil, nil, ErrInternalError - } - - // Resolve the token policy - var te *logical.TokenEntry - switch req.TokenEntry() { - case nil: - var err error - te, err = c.tokenStore.Lookup(c.activeContext, req.ClientToken) - if err != nil { - c.logger.Error("failed to lookup token", "error", err) - return nil, nil, nil, nil, ErrInternalError - } - default: - te = req.TokenEntry() - } - - // Ensure the token is valid - if te == nil { - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - - // CIDR checks bind all tokens except non-expiring root tokens - if te.TTL != 0 && len(te.BoundCIDRs) > 0 { - var valid bool - remoteSockAddr, err := sockaddr.NewSockAddr(req.Connection.RemoteAddr) - if err != nil { - if c.Logger().IsDebug() { - c.Logger().Debug("could not parse remote addr into sockaddr", "error", err, "remote_addr", req.Connection.RemoteAddr) - } - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - for _, cidr := range te.BoundCIDRs { - if cidr.Contains(remoteSockAddr) { - valid = true - break - } - } - if !valid { - return nil, nil, nil, nil, logical.ErrPermissionDenied - } - } - - entity, identityPolicies, err := c.fetchEntityAndDerivedPolicies(te.EntityID) - if err != nil { - return nil, nil, nil, nil, ErrInternalError - } - - allPolicies := append(te.Policies, identityPolicies...) - - // Construct the corresponding ACL object - acl, err := c.policyStore.ACL(c.activeContext, entity, allPolicies...) - if err != nil { - if errwrap.ContainsType(err, new(TemplateError)) { - return nil, nil, nil, nil, err - } - c.logger.Error("failed to construct ACL", "error", err) - return nil, nil, nil, nil, ErrInternalError - } - - return acl, te, entity, identityPolicies, nil -} - -func (c *Core) checkToken(ctx context.Context, req *logical.Request, unauth bool) (*logical.Auth, *logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"core", "check_token"}, time.Now()) - - var acl *ACL - var te *logical.TokenEntry - var entity *identity.Entity - var identityPolicies []string - var err error - - // Even if unauth, if a token is provided, there's little reason not to - // gather as much info as possible for the audit log and to e.g. control - // trace mode for EGPs. - if !unauth || (unauth && req.ClientToken != "") { - acl, te, entity, identityPolicies, err = c.fetchACLTokenEntryAndEntity(req) - // In the unauth case we don't want to fail the command, since it's - // unauth, we just have no information to attach to the request, so - // ignore errors...this was best-effort anyways - if err != nil && !unauth { - if errwrap.ContainsType(err, new(TemplateError)) { - c.logger.Warn("permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor") - err = logical.ErrPermissionDenied - } - return nil, te, err - } - } - - if entity != nil && entity.Disabled { - c.logger.Warn("permission denied as the entity on the token is disabled") - return nil, te, logical.ErrPermissionDenied - } - if te != nil && te.EntityID != "" && entity == nil { - c.logger.Warn("permission denied as the entity on the token is invalid") - return nil, te, logical.ErrPermissionDenied - } - - // Check if this is a root protected path - rootPath := c.router.RootPath(req.Path) - - if rootPath && unauth { - return nil, nil, errors.New("cannot access root path in unauthenticated request") - } - - // When we receive a write of either type, rather than require clients to - // PUT/POST and trust the operation, we ask the backend to give us the real - // skinny -- if the backend implements an existence check, it can tell us - // whether a particular resource exists. Then we can mark it as an update - // or creation as appropriate. - if req.Operation == logical.CreateOperation || req.Operation == logical.UpdateOperation { - checkExists, resourceExists, err := c.router.RouteExistenceCheck(ctx, req) - switch err { - case logical.ErrUnsupportedPath: - // fail later via bad path to avoid confusing items in the log - checkExists = false - case nil: - // Continue on - default: - c.logger.Error("failed to run existence check", "error", err) - if _, ok := err.(errutil.UserError); ok { - return nil, nil, err - } else { - return nil, nil, ErrInternalError - } - } - - switch { - case checkExists == false: - // No existence check, so always treat it as an update operation, which is how it is pre 0.5 - req.Operation = logical.UpdateOperation - case resourceExists == true: - // It exists, so force an update operation - req.Operation = logical.UpdateOperation - case resourceExists == false: - // It doesn't exist, force a create operation - req.Operation = logical.CreateOperation - default: - panic("unreachable code") - } - } - // Create the auth response - auth := &logical.Auth{ - ClientToken: req.ClientToken, - Accessor: req.ClientTokenAccessor, - Policies: identityPolicies, - IdentityPolicies: identityPolicies, - } - - if te != nil { - auth.TokenPolicies = te.Policies - auth.Policies = append(te.Policies, identityPolicies...) - auth.Metadata = te.Meta - auth.DisplayName = te.DisplayName - auth.EntityID = te.EntityID - // Store the entity ID in the request object - req.EntityID = te.EntityID - } - - // Check the standard non-root ACLs. Return the token entry if it's not - // allowed so we can decrement the use count. - authResults := c.performPolicyChecks(ctx, acl, te, req, entity, &PolicyCheckOpts{ - Unauth: unauth, - RootPrivsRequired: rootPath, - }) - if !authResults.Allowed { - retErr := authResults.Error - if authResults.Error.ErrorOrNil() == nil || authResults.DeniedError { - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - } - return auth, te, retErr - } - - return auth, te, nil -} - -// HandleRequest is used to handle a new incoming request -func (c *Core) HandleRequest(httpCtx context.Context, req *logical.Request) (resp *logical.Response, err error) { - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.Sealed() { - return nil, consts.ErrSealed - } - if c.standby { - return nil, consts.ErrStandby - } - - ctx, cancel := context.WithCancel(c.activeContext) - defer cancel() - - go func(ctx context.Context, httpCtx context.Context) { - select { - case <-ctx.Done(): - case <-httpCtx.Done(): - cancel() - } - }(ctx, httpCtx) - - // Allowing writing to a path ending in / makes it extremely difficult to - // understand user intent for the filesystem-like backends (kv, - // cubbyhole) -- did they want a key named foo/ or did they want to write - // to a directory foo/ with no (or forgotten) key, or...? It also affects - // lookup, because paths ending in / are considered prefixes by some - // backends. Basically, it's all just terrible, so don't allow it. - if strings.HasSuffix(req.Path, "/") && - (req.Operation == logical.UpdateOperation || - req.Operation == logical.CreateOperation) { - return logical.ErrorResponse("cannot write to a path ending in '/'"), nil - } - - var auth *logical.Auth - if c.router.LoginPath(req.Path) { - resp, auth, err = c.handleLoginRequest(ctx, req) - } else { - resp, auth, err = c.handleRequest(ctx, req) - } - - // Ensure we don't leak internal data - if resp != nil { - if resp.Secret != nil { - resp.Secret.InternalData = nil - } - if resp.Auth != nil { - resp.Auth.InternalData = nil - } - } - - // We are wrapping if there is anything to wrap (not a nil response) and a - // TTL was specified for the token. Errors on a call should be returned to - // the caller, so wrapping is turned off if an error is hit and the error - // is logged to the audit log. - wrapping := resp != nil && - err == nil && - !resp.IsError() && - resp.WrapInfo != nil && - resp.WrapInfo.TTL != 0 && - resp.WrapInfo.Token == "" - - if wrapping { - cubbyResp, cubbyErr := c.wrapInCubbyhole(ctx, req, resp, auth) - // If not successful, returns either an error response from the - // cubbyhole backend or an error; if either is set, set resp and err to - // those and continue so that that's what we audit log. Otherwise - // finish the wrapping and audit log that. - if cubbyResp != nil || cubbyErr != nil { - resp = cubbyResp - err = cubbyErr - } else { - wrappingResp := &logical.Response{ - WrapInfo: resp.WrapInfo, - Warnings: resp.Warnings, - } - resp = wrappingResp - } - } - - auditResp := resp - // When unwrapping we want to log the actual response that will be written - // out. We still want to return the raw value to avoid automatic updating - // to any of it. - if req.Path == "sys/wrapping/unwrap" && - resp != nil && - resp.Data != nil && - resp.Data[logical.HTTPRawBody] != nil { - - // Decode the JSON - if resp.Data[logical.HTTPRawBodyAlreadyJSONDecoded] != nil { - delete(resp.Data, logical.HTTPRawBodyAlreadyJSONDecoded) - } else { - httpResp := &logical.HTTPResponse{} - err := jsonutil.DecodeJSON(resp.Data[logical.HTTPRawBody].([]byte), httpResp) - if err != nil { - c.logger.Error("failed to unmarshal wrapped HTTP response for audit logging", "error", err) - return nil, ErrInternalError - } - - auditResp = logical.HTTPResponseToLogicalResponse(httpResp) - } - } - - var nonHMACReqDataKeys []string - var nonHMACRespDataKeys []string - entry := c.router.MatchingMountEntry(req.Path) - if entry != nil { - // Get and set ignored HMAC'd value. Reset those back to empty afterwards. - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - nonHMACReqDataKeys = rawVals.([]string) - } - - // Get and set ignored HMAC'd value. Reset those back to empty afterwards. - if auditResp != nil { - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_response_keys"); ok { - nonHMACRespDataKeys = rawVals.([]string) - } - } - } - - // Create an audit trail of the response - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - Response: auditResp, - OuterErr: err, - NonHMACReqDataKeys: nonHMACReqDataKeys, - NonHMACRespDataKeys: nonHMACRespDataKeys, - } - if auditErr := c.auditBroker.LogResponse(ctx, logInput, c.auditedHeaders); auditErr != nil { - c.logger.Error("failed to audit response", "request_path", req.Path, "error", auditErr) - return nil, ErrInternalError - } - - return -} - -func (c *Core) handleRequest(ctx context.Context, req *logical.Request) (retResp *logical.Response, retAuth *logical.Auth, retErr error) { - defer metrics.MeasureSince([]string{"core", "handle_request"}, time.Now()) - - var nonHMACReqDataKeys []string - entry := c.router.MatchingMountEntry(req.Path) - if entry != nil { - // Get and set ignored HMAC'd value. - if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok { - nonHMACReqDataKeys = rawVals.([]string) - } - } - - // Validate the token - auth, te, ctErr := c.checkToken(ctx, req, false) - // We run this logic first because we want to decrement the use count even in the case of an error - if te != nil { - // Attempt to use the token (decrement NumUses) - var err error - te, err = c.tokenStore.UseToken(ctx, te) - if err != nil { - c.logger.Error("failed to use token", "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, nil, retErr - } - if te == nil { - // Token has been revoked by this point - retErr = multierror.Append(retErr, logical.ErrPermissionDenied) - return nil, nil, retErr - } - if te.NumUses == tokenRevocationPending { - // We defer a revocation until after logic has run, since this is a - // valid request (this is the token's final use). We pass the ID in - // directly just to be safe in case something else modifies te later. - defer func(id string) { - leaseID, err := c.expiration.CreateOrFetchRevocationLeaseByToken(c.activeContext, te) - if err == nil { - err = c.expiration.LazyRevoke(ctx, leaseID) - } - if err != nil { - c.logger.Error("failed to revoke token", "error", err) - retResp = nil - retAuth = nil - retErr = multierror.Append(retErr, ErrInternalError) - } - if retResp != nil && retResp.Secret != nil && - // Some backends return a TTL even without a Lease ID - retResp.Secret.LeaseID != "" { - retResp = logical.ErrorResponse("Secret cannot be returned; token had one use left, so leased credentials were immediately revoked.") - return - } - }(te.ID) - } - } - if ctErr != nil { - // If it is an internal error we return that, otherwise we - // return invalid request so that the status codes can be correct - switch { - case ctErr == ErrInternalError, - errwrap.Contains(ctErr, ErrInternalError.Error()), - ctErr == logical.ErrPermissionDenied, - errwrap.Contains(ctErr, logical.ErrPermissionDenied.Error()): - switch ctErr.(type) { - case *multierror.Error: - retErr = ctErr - default: - retErr = multierror.Append(retErr, ctErr) - } - default: - retErr = multierror.Append(retErr, logical.ErrInvalidRequest) - } - - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - OuterErr: ctErr, - NonHMACReqDataKeys: nonHMACReqDataKeys, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - } - - if errwrap.Contains(retErr, ErrInternalError.Error()) { - return nil, auth, retErr - } - return logical.ErrorResponse(ctErr.Error()), auth, retErr - } - - // Attach the display name - req.DisplayName = auth.DisplayName - - // Create an audit trail of the request - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - NonHMACReqDataKeys: nonHMACReqDataKeys, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - // Route the request - resp, routeErr := c.router.Route(ctx, req) - if resp != nil { - // If wrapping is used, use the shortest between the request and response - var wrapTTL time.Duration - var wrapFormat, creationPath string - var sealWrap bool - - // Ensure no wrap info information is set other than, possibly, the TTL - if resp.WrapInfo != nil { - if resp.WrapInfo.TTL > 0 { - wrapTTL = resp.WrapInfo.TTL - } - wrapFormat = resp.WrapInfo.Format - creationPath = resp.WrapInfo.CreationPath - sealWrap = resp.WrapInfo.SealWrap - resp.WrapInfo = nil - } - - if req.WrapInfo != nil { - if req.WrapInfo.TTL > 0 { - switch { - case wrapTTL == 0: - wrapTTL = req.WrapInfo.TTL - case req.WrapInfo.TTL < wrapTTL: - wrapTTL = req.WrapInfo.TTL - } - } - // If the wrap format hasn't been set by the response, set it to - // the request format - if req.WrapInfo.Format != "" && wrapFormat == "" { - wrapFormat = req.WrapInfo.Format - } - } - - if wrapTTL > 0 { - resp.WrapInfo = &wrapping.ResponseWrapInfo{ - TTL: wrapTTL, - Format: wrapFormat, - CreationPath: creationPath, - SealWrap: sealWrap, - } - } - } - - // If there is a secret, we must register it with the expiration manager. - // We exclude renewal of a lease, since it does not need to be re-registered - if resp != nil && resp.Secret != nil && !strings.HasPrefix(req.Path, "sys/renew") && - !strings.HasPrefix(req.Path, "sys/leases/renew") { - // KV mounts should return the TTL but not register - // for a lease as this provides a massive slowdown - registerLease := true - - matchingMountEntry := c.router.MatchingMountEntry(req.Path) - if matchingMountEntry == nil { - c.logger.Error("unable to retrieve kv mount entry from router") - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - switch matchingMountEntry.Type { - case "kv", "generic": - // If we are kv type, first see if we are an older passthrough - // backend, and otherwise check the mount entry options. - matchingBackend := c.router.MatchingBackend(req.Path) - if matchingBackend == nil { - c.logger.Error("unable to retrieve kv backend from router") - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - if ptbe, ok := matchingBackend.(*PassthroughBackend); ok { - if !ptbe.GeneratesLeases() { - registerLease = false - resp.Secret.Renewable = false - } - } else if matchingMountEntry.Options == nil || matchingMountEntry.Options["leased_passthrough"] != "true" { - registerLease = false - resp.Secret.Renewable = false - } - - case "plugin": - // If we are a plugin type and the plugin name is "kv" check the - // mount entry options. - if matchingMountEntry.Config.PluginName == "kv" && (matchingMountEntry.Options == nil || matchingMountEntry.Options["leased_passthrough"] != "true") { - registerLease = false - resp.Secret.Renewable = false - } - } - - if registerLease { - sysView := c.router.MatchingSystemView(req.Path) - if sysView == nil { - c.logger.Error("unable to look up sys view for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - ttl, warnings, err := framework.CalculateTTL(sysView, 0, resp.Secret.TTL, 0, resp.Secret.MaxTTL, 0, time.Time{}) - if err != nil { - return nil, nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - resp.Secret.TTL = ttl - - leaseID, err := c.expiration.Register(ctx, req, resp) - if err != nil { - c.logger.Error("failed to register lease", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - resp.Secret.LeaseID = leaseID - } - } - - // Only the token store is allowed to return an auth block, for any - // other request this is an internal error. We exclude renewal of a token, - // since it does not need to be re-registered - if resp != nil && resp.Auth != nil && !strings.HasPrefix(req.Path, "auth/token/renew") { - if !strings.HasPrefix(req.Path, "auth/token/") { - c.logger.Error("unexpected Auth response for non-token backend", "request_path", req.Path) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - _, identityPolicies, err := c.fetchEntityAndDerivedPolicies(resp.Auth.EntityID) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - return nil, nil, ErrInternalError - } - - resp.Auth.TokenPolicies = policyutil.SanitizePolicies(resp.Auth.Policies, policyutil.DoNotAddDefaultPolicy) - if err := c.expiration.RegisterAuth(ctx, resp.Auth.CreationPath, resp.Auth); err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register token lease", "request_path", req.Path, "error", err) - retErr = multierror.Append(retErr, ErrInternalError) - return nil, auth, retErr - } - - // We do these later since it's not meaningful for backends/expmgr to - // have what is purely a snapshot of current identity policies, and - // plugins can be confused if they are checking contents of - // Auth.Policies instead of Auth.TokenPolicies - resp.Auth.IdentityPolicies = policyutil.SanitizePolicies(identityPolicies, policyutil.DoNotAddDefaultPolicy) - resp.Auth.Policies = policyutil.SanitizePolicies(append(resp.Auth.Policies, identityPolicies...), policyutil.DoNotAddDefaultPolicy) - } - - if resp != nil && - req.Path == "cubbyhole/response" && - len(te.Policies) == 1 && - te.Policies[0] == responseWrappingPolicyName { - resp.AddWarning("Reading from 'cubbyhole/response' is deprecated. Please use sys/wrapping/unwrap to unwrap responses, as it provides additional security checks and other benefits.") - } - - // Return the response and error - if routeErr != nil { - retErr = multierror.Append(retErr, routeErr) - } - - return resp, auth, retErr -} - -// handleLoginRequest is used to handle a login request, which is an -// unauthenticated request to the backend. -func (c *Core) handleLoginRequest(ctx context.Context, req *logical.Request) (retResp *logical.Response, retAuth *logical.Auth, retErr error) { - defer metrics.MeasureSince([]string{"core", "handle_login_request"}, time.Now()) - - req.Unauthenticated = true - - var auth *logical.Auth - // Create an audit trail of the request, auth is not available on login requests - // Create an audit trail of the request. Attach auth if it was returned, - // e.g. if a token was provided. - logInput := &audit.LogInput{ - Auth: auth, - Request: req, - } - if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil { - c.logger.Error("failed to audit request", "path", req.Path, "error", err) - return nil, nil, ErrInternalError - } - - // The token store uses authentication even when creating a new token, - // so it's handled in handleRequest. It should not be reached here. - if strings.HasPrefix(req.Path, "auth/token/") { - c.logger.Error("unexpected login request for token backend", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - // Route the request - resp, routeErr := c.router.Route(ctx, req) - if resp != nil { - // If wrapping is used, use the shortest between the request and response - var wrapTTL time.Duration - var wrapFormat, creationPath string - var sealWrap bool - - // Ensure no wrap info information is set other than, possibly, the TTL - if resp.WrapInfo != nil { - if resp.WrapInfo.TTL > 0 { - wrapTTL = resp.WrapInfo.TTL - } - wrapFormat = resp.WrapInfo.Format - creationPath = resp.WrapInfo.CreationPath - sealWrap = resp.WrapInfo.SealWrap - resp.WrapInfo = nil - } - - if req.WrapInfo != nil { - if req.WrapInfo.TTL > 0 { - switch { - case wrapTTL == 0: - wrapTTL = req.WrapInfo.TTL - case req.WrapInfo.TTL < wrapTTL: - wrapTTL = req.WrapInfo.TTL - } - } - if req.WrapInfo.Format != "" && wrapFormat == "" { - wrapFormat = req.WrapInfo.Format - } - } - - if wrapTTL > 0 { - resp.WrapInfo = &wrapping.ResponseWrapInfo{ - TTL: wrapTTL, - Format: wrapFormat, - CreationPath: creationPath, - SealWrap: sealWrap, - } - } - } - - // A login request should never return a secret! - if resp != nil && resp.Secret != nil { - c.logger.Error("unexpected Secret response for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - // If the response generated an authentication, then generate the token - if resp != nil && resp.Auth != nil { - - var entity *identity.Entity - auth = resp.Auth - - mEntry := c.router.MatchingMountEntry(req.Path) - - if auth.Alias != nil && - mEntry != nil && - !mEntry.Local && - c.identityStore != nil { - // Overwrite the mount type and mount path in the alias - // information - auth.Alias.MountType = req.MountType - auth.Alias.MountAccessor = req.MountAccessor - - if auth.Alias.Name == "" { - return nil, nil, fmt.Errorf("missing name in alias") - } - - var err error - - // Fetch the entity for the alias, or create an entity if one - // doesn't exist. - entity, err = c.identityStore.CreateOrFetchEntity(auth.Alias) - if err != nil { - return nil, nil, err - } - - if entity == nil { - return nil, nil, fmt.Errorf("failed to create an entity for the authenticated alias") - } - - if entity.Disabled { - return nil, nil, logical.ErrPermissionDenied - } - - auth.EntityID = entity.ID - if auth.GroupAliases != nil { - validAliases, err := c.identityStore.refreshExternalGroupMembershipsByEntityID(auth.EntityID, auth.GroupAliases) - if err != nil { - return nil, nil, err - } - auth.GroupAliases = validAliases - } - } - - // Determine the source of the login - source := c.router.MatchingMount(req.Path) - source = strings.TrimPrefix(source, credentialRoutePrefix) - source = strings.Replace(source, "/", "-", -1) - - // Prepend the source to the display name - auth.DisplayName = strings.TrimSuffix(source+auth.DisplayName, "-") - - sysView := c.router.MatchingSystemView(req.Path) - if sysView == nil { - c.logger.Error("unable to look up sys view for login path", "request_path", req.Path) - return nil, nil, ErrInternalError - } - - tokenTTL, warnings, err := framework.CalculateTTL(sysView, 0, auth.TTL, auth.Period, auth.MaxTTL, auth.ExplicitMaxTTL, time.Time{}) - if err != nil { - return nil, nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - - // We first assign token policies to what was returned from the backend - // via auth.Policies. Then, we get the full set of policies into - // auth.Policies from the backend + entity information -- this is not - // stored in the token, but we perform sanity checks on it and return - // that information to the user. - - // Generate a token - te := logical.TokenEntry{ - Path: req.Path, - Meta: auth.Metadata, - DisplayName: auth.DisplayName, - CreationTime: time.Now().Unix(), - TTL: tokenTTL, - NumUses: auth.NumUses, - EntityID: auth.EntityID, - BoundCIDRs: auth.BoundCIDRs, - } - - te.Policies = policyutil.SanitizePolicies(auth.Policies, policyutil.AddDefaultPolicy) - - _, identityPolicies, err := c.fetchEntityAndDerivedPolicies(auth.EntityID) - if err != nil { - return nil, nil, ErrInternalError - } - - auth.TokenPolicies = te.Policies - allPolicies := policyutil.SanitizePolicies(append(te.Policies, identityPolicies...), policyutil.DoNotAddDefaultPolicy) - - // Prevent internal policies from being assigned to tokens. We check - // this on auth.Policies including derived ones from Identity before - // actually making the token. - for _, policy := range allPolicies { - if policy == "root" { - return logical.ErrorResponse("auth methods cannot create root tokens"), nil, logical.ErrInvalidRequest - } - if strutil.StrListContains(nonAssignablePolicies, policy) { - return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil, logical.ErrInvalidRequest - } - } - - if err := c.tokenStore.create(ctx, &te); err != nil { - c.logger.Error("failed to create token", "error", err) - return nil, auth, ErrInternalError - } - - // Populate the client token, accessor, and TTL - auth.ClientToken = te.ID - auth.Accessor = te.Accessor - auth.TTL = te.TTL - - // Register with the expiration manager - if err := c.expiration.RegisterAuth(ctx, te.Path, auth); err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register token lease", "request_path", req.Path, "error", err) - return nil, auth, ErrInternalError - } - - auth.IdentityPolicies = policyutil.SanitizePolicies(identityPolicies, policyutil.DoNotAddDefaultPolicy) - auth.Policies = allPolicies - - // Attach the display name, might be used by audit backends - req.DisplayName = auth.DisplayName - } - - return resp, auth, routeErr -} diff --git a/vendor/github.com/hashicorp/vault/vault/rollback.go b/vendor/github.com/hashicorp/vault/vault/rollback.go deleted file mode 100644 index 7d9d87311..000000000 --- a/vendor/github.com/hashicorp/vault/vault/rollback.go +++ /dev/null @@ -1,259 +0,0 @@ -package vault - -import ( - "context" - "strings" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - - "github.com/armon/go-metrics" - "github.com/hashicorp/vault/logical" -) - -const ( - // rollbackPeriod is how often we attempt rollbacks for all the backends - rollbackPeriod = time.Minute -) - -// RollbackManager is responsible for performing rollbacks of partial -// secrets within logical backends. -// -// During normal operations, it is possible for logical backends to -// error partially through an operation. These are called "partial secrets": -// they are never sent back to a user, but they do need to be cleaned up. -// This manager handles that by periodically (on a timer) requesting that the -// backends clean up. -// -// The RollbackManager periodically initiates a logical.RollbackOperation -// on every mounted logical backend. It ensures that only one rollback operation -// is in-flight at any given time within a single seal/unseal phase. -type RollbackManager struct { - logger log.Logger - - // This gives the current mount table of both logical and credential backends, - // plus a RWMutex that is locked for reading. It is up to the caller to RUnlock - // it when done with the mount table. - backends func() []*MountEntry - - router *Router - period time.Duration - - inflightAll sync.WaitGroup - inflight map[string]*rollbackState - inflightLock sync.RWMutex - - doneCh chan struct{} - shutdown bool - shutdownCh chan struct{} - shutdownLock sync.Mutex - quitContext context.Context - - core *Core -} - -// rollbackState is used to track the state of a single rollback attempt -type rollbackState struct { - lastError error - sync.WaitGroup -} - -// NewRollbackManager is used to create a new rollback manager -func NewRollbackManager(ctx context.Context, logger log.Logger, backendsFunc func() []*MountEntry, router *Router, core *Core) *RollbackManager { - r := &RollbackManager{ - logger: logger, - backends: backendsFunc, - router: router, - period: rollbackPeriod, - inflight: make(map[string]*rollbackState), - doneCh: make(chan struct{}), - shutdownCh: make(chan struct{}), - quitContext: ctx, - core: core, - } - return r -} - -// Start starts the rollback manager -func (m *RollbackManager) Start() { - go m.run() -} - -// Stop stops the running manager. This will wait for any in-flight -// rollbacks to complete. -func (m *RollbackManager) Stop() { - m.shutdownLock.Lock() - defer m.shutdownLock.Unlock() - if !m.shutdown { - m.shutdown = true - close(m.shutdownCh) - <-m.doneCh - } - m.inflightAll.Wait() -} - -// run is a long running routine to periodically invoke rollback -func (m *RollbackManager) run() { - m.logger.Info("starting rollback manager") - tick := time.NewTicker(m.period) - defer tick.Stop() - defer close(m.doneCh) - for { - select { - case <-tick.C: - m.triggerRollbacks() - - case <-m.shutdownCh: - m.logger.Info("stopping rollback manager") - return - } - } -} - -// triggerRollbacks is used to trigger the rollbacks across all the backends -func (m *RollbackManager) triggerRollbacks() { - - backends := m.backends() - - for _, e := range backends { - path := e.Path - if e.Table == credentialTableType { - path = credentialRoutePrefix + path - } - - // When the mount is filtered, the backend will be nil - backend := m.router.MatchingBackend(path) - if backend == nil { - continue - } - - m.inflightLock.RLock() - _, ok := m.inflight[path] - m.inflightLock.RUnlock() - if !ok { - m.startRollback(path, true) - } - } -} - -// startRollback is used to start an async rollback attempt. -// This must be called with the inflightLock held. -func (m *RollbackManager) startRollback(path string, grabStatelock bool) *rollbackState { - rs := &rollbackState{} - rs.Add(1) - m.inflightAll.Add(1) - m.inflightLock.Lock() - m.inflight[path] = rs - m.inflightLock.Unlock() - go m.attemptRollback(m.quitContext, path, rs, grabStatelock) - return rs -} - -// attemptRollback invokes a RollbackOperation for the given path -func (m *RollbackManager) attemptRollback(ctx context.Context, path string, rs *rollbackState, grabStatelock bool) (err error) { - defer metrics.MeasureSince([]string{"rollback", "attempt", strings.Replace(path, "/", "-", -1)}, time.Now()) - if m.logger.IsDebug() { - m.logger.Debug("attempting rollback", "path", path) - } - - defer func() { - rs.lastError = err - rs.Done() - m.inflightAll.Done() - m.inflightLock.Lock() - delete(m.inflight, path) - m.inflightLock.Unlock() - }() - - // Invoke a RollbackOperation - req := &logical.Request{ - Operation: logical.RollbackOperation, - Path: path, - } - var cancelFunc context.CancelFunc - ctx, cancelFunc = context.WithTimeout(ctx, DefaultMaxRequestDuration) - if grabStatelock { - m.core.stateLock.RLock() - } - _, err = m.router.Route(ctx, req) - if grabStatelock { - m.core.stateLock.RUnlock() - } - cancelFunc() - - // If the error is an unsupported operation, then it doesn't - // matter, the backend doesn't support it. - if err == logical.ErrUnsupportedOperation { - err = nil - } - // If we failed due to read-only storage, we can't do anything; ignore - if err != nil && strings.Contains(err.Error(), logical.ErrReadOnly.Error()) { - err = nil - } - if err != nil { - m.logger.Error("error rolling back", "path", path, "error", err) - } - return -} - -// Rollback is used to trigger an immediate rollback of the path, -// or to join an existing rollback operation if in flight. Caller should have -// core's statelock held -func (m *RollbackManager) Rollback(path string) error { - // Check for an existing attempt and start one if none - m.inflightLock.RLock() - rs, ok := m.inflight[path] - m.inflightLock.RUnlock() - if !ok { - rs = m.startRollback(path, false) - } - - // Wait for the attempt to finish - rs.Wait() - - // Return the last error - return rs.lastError -} - -// The methods below are the hooks from core that are called pre/post seal. - -// startRollback is used to start the rollback manager after unsealing -func (c *Core) startRollback() error { - backendsFunc := func() []*MountEntry { - ret := []*MountEntry{} - c.mountsLock.RLock() - defer c.mountsLock.RUnlock() - // During teardown/setup after a leader change or unseal there could be - // something racy here so make sure the table isn't nil - if c.mounts != nil { - for _, entry := range c.mounts.Entries { - ret = append(ret, entry) - } - } - c.authLock.RLock() - defer c.authLock.RUnlock() - // During teardown/setup after a leader change or unseal there could be - // something racy here so make sure the table isn't nil - if c.auth != nil { - for _, entry := range c.auth.Entries { - ret = append(ret, entry) - } - } - return ret - } - rollbackLogger := c.baseLogger.Named("rollback") - c.AddLogger(rollbackLogger) - c.rollback = NewRollbackManager(c.activeContext, rollbackLogger, backendsFunc, c.router, c) - c.rollback.Start() - return nil -} - -// stopRollback is used to stop running the rollback manager before sealing -func (c *Core) stopRollback() error { - if c.rollback != nil { - c.rollback.Stop() - c.rollback = nil - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/router.go b/vendor/github.com/hashicorp/vault/vault/router.go deleted file mode 100644 index cced9b579..000000000 --- a/vendor/github.com/hashicorp/vault/vault/router.go +++ /dev/null @@ -1,655 +0,0 @@ -package vault - -import ( - "context" - "fmt" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/armon/go-metrics" - "github.com/armon/go-radix" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" -) - -// Router is used to do prefix based routing of a request to a logical backend -type Router struct { - l sync.RWMutex - root *radix.Tree - mountUUIDCache *radix.Tree - mountAccessorCache *radix.Tree - tokenStoreSaltFunc func(context.Context) (*salt.Salt, error) - // storagePrefix maps the prefix used for storage (ala the BarrierView) - // to the backend. This is used to map a key back into the backend that owns it. - // For example, logical/uuid1/foobar -> secrets/ (kv backend) + foobar - storagePrefix *radix.Tree -} - -// NewRouter returns a new router -func NewRouter() *Router { - r := &Router{ - root: radix.New(), - storagePrefix: radix.New(), - mountUUIDCache: radix.New(), - mountAccessorCache: radix.New(), - } - return r -} - -// routeEntry is used to represent a mount point in the router -type routeEntry struct { - tainted bool - backend logical.Backend - mountEntry *MountEntry - storageView logical.Storage - storagePrefix string - rootPaths atomic.Value - loginPaths atomic.Value - l sync.RWMutex -} - -type validateMountResponse struct { - MountType string `json:"mount_type" structs:"mount_type" mapstructure:"mount_type"` - MountAccessor string `json:"mount_accessor" structs:"mount_accessor" mapstructure:"mount_accessor"` - MountPath string `json:"mount_path" structs:"mount_path" mapstructure:"mount_path"` - MountLocal bool `json:"mount_local" structs:"mount_local" mapstructure:"mount_local"` -} - -// validateMountByAccessor returns the mount type and ID for a given mount -// accessor -func (r *Router) validateMountByAccessor(accessor string) *validateMountResponse { - if accessor == "" { - return nil - } - - mountEntry := r.MatchingMountByAccessor(accessor) - if mountEntry == nil { - return nil - } - - mountPath := mountEntry.Path - if mountEntry.Table == credentialTableType { - mountPath = credentialRoutePrefix + mountPath - } - - return &validateMountResponse{ - MountAccessor: mountEntry.Accessor, - MountType: mountEntry.Type, - MountPath: mountPath, - MountLocal: mountEntry.Local, - } -} - -// SaltID is used to apply a salt and hash to an ID to make sure its not reversible -func (re *routeEntry) SaltID(id string) string { - return salt.SaltID(re.mountEntry.UUID, id, salt.SHA1Hash) -} - -// Mount is used to expose a logical backend at a given prefix, using a unique salt, -// and the barrier view for that path. -func (r *Router) Mount(backend logical.Backend, prefix string, mountEntry *MountEntry, storageView *BarrierView) error { - r.l.Lock() - defer r.l.Unlock() - - // Check if this is a nested mount - if existing, _, ok := r.root.LongestPrefix(prefix); ok && existing != "" { - return fmt.Errorf("cannot mount under existing mount %q", existing) - } - - // Build the paths - paths := new(logical.Paths) - if backend != nil { - specialPaths := backend.SpecialPaths() - if specialPaths != nil { - paths = specialPaths - } - } - - // Create a mount entry - re := &routeEntry{ - tainted: false, - backend: backend, - mountEntry: mountEntry, - storagePrefix: storageView.prefix, - storageView: storageView, - } - re.rootPaths.Store(pathsToRadix(paths.Root)) - re.loginPaths.Store(pathsToRadix(paths.Unauthenticated)) - - switch { - case prefix == "": - return fmt.Errorf("missing prefix to be used for router entry; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.storagePrefix == "": - return fmt.Errorf("missing storage view prefix; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.mountEntry.UUID == "": - return fmt.Errorf("missing mount identifier; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - case re.mountEntry.Accessor == "": - return fmt.Errorf("missing mount accessor; mount_path: %q, mount_type: %q", re.mountEntry.Path, re.mountEntry.Type) - } - - r.root.Insert(prefix, re) - r.storagePrefix.Insert(re.storagePrefix, re) - r.mountUUIDCache.Insert(re.mountEntry.UUID, re.mountEntry) - r.mountAccessorCache.Insert(re.mountEntry.Accessor, re.mountEntry) - - return nil -} - -// Unmount is used to remove a logical backend from a given prefix -func (r *Router) Unmount(ctx context.Context, prefix string) error { - r.l.Lock() - defer r.l.Unlock() - - // Fast-path out if the backend doesn't exist - raw, ok := r.root.Get(prefix) - if !ok { - return nil - } - - // Call backend's Cleanup routine - re := raw.(*routeEntry) - if re.backend != nil { - re.backend.Cleanup(ctx) - } - - // Purge from the radix trees - r.root.Delete(prefix) - r.storagePrefix.Delete(re.storagePrefix) - r.mountUUIDCache.Delete(re.mountEntry.UUID) - r.mountAccessorCache.Delete(re.mountEntry.Accessor) - - return nil -} - -// Remount is used to change the mount location of a logical backend -func (r *Router) Remount(src, dst string) error { - r.l.Lock() - defer r.l.Unlock() - - // Check for existing mount - raw, ok := r.root.Get(src) - if !ok { - return fmt.Errorf("no mount at %q", src) - } - - // Update the mount point - r.root.Delete(src) - r.root.Insert(dst, raw) - return nil -} - -// Taint is used to mark a path as tainted. This means only RollbackOperation -// RevokeOperation requests are allowed to proceed -func (r *Router) Taint(path string) error { - r.l.Lock() - defer r.l.Unlock() - _, raw, ok := r.root.LongestPrefix(path) - if ok { - raw.(*routeEntry).tainted = true - } - return nil -} - -// Untaint is used to unmark a path as tainted. -func (r *Router) Untaint(path string) error { - r.l.Lock() - defer r.l.Unlock() - _, raw, ok := r.root.LongestPrefix(path) - if ok { - raw.(*routeEntry).tainted = false - } - return nil -} - -func (r *Router) MatchingMountByUUID(mountID string) *MountEntry { - if mountID == "" { - return nil - } - - r.l.RLock() - - _, raw, ok := r.mountUUIDCache.LongestPrefix(mountID) - if !ok { - r.l.RUnlock() - return nil - } - - r.l.RUnlock() - return raw.(*MountEntry) -} - -// MatchingMountByAccessor returns the MountEntry by accessor lookup -func (r *Router) MatchingMountByAccessor(mountAccessor string) *MountEntry { - if mountAccessor == "" { - return nil - } - - r.l.RLock() - - _, raw, ok := r.mountAccessorCache.LongestPrefix(mountAccessor) - if !ok { - r.l.RUnlock() - return nil - } - - r.l.RUnlock() - return raw.(*MountEntry) -} - -// MatchingMount returns the mount prefix that would be used for a path -func (r *Router) MatchingMount(path string) string { - r.l.RLock() - mount := r.matchingMountInternal(path) - r.l.RUnlock() - return mount -} - -func (r *Router) matchingMountInternal(path string) string { - mount, _, ok := r.root.LongestPrefix(path) - if !ok { - return "" - } - return mount -} - -// matchingPrefixInternal returns a mount prefix that a path may be a part of -func (r *Router) matchingPrefixInternal(path string) string { - var existing string = "" - fn := func(existing_path string, _v interface{}) bool { - if strings.HasPrefix(existing_path, path) { - existing = existing_path - return true - } - return false - } - r.root.WalkPrefix(path, fn) - return existing -} - -// MountConflict determines if there are potential path conflicts -func (r *Router) MountConflict(path string) string { - r.l.RLock() - defer r.l.RUnlock() - if exact_match := r.matchingMountInternal(path); exact_match != "" { - return exact_match - } - if prefix_match := r.matchingPrefixInternal(path); prefix_match != "" { - return prefix_match - } - return "" -} - -// MatchingStorageByAPIPath/StoragePath returns the storage used for -// API/Storage paths respectively -func (r *Router) MatchingStorageByAPIPath(path string) logical.Storage { - return r.matchingStorage(path, true) -} -func (r *Router) MatchingStorageByStoragePath(path string) logical.Storage { - return r.matchingStorage(path, false) -} -func (r *Router) matchingStorage(path string, apiPath bool) logical.Storage { - var raw interface{} - var ok bool - r.l.RLock() - if apiPath { - _, raw, ok = r.root.LongestPrefix(path) - } else { - _, raw, ok = r.storagePrefix.LongestPrefix(path) - } - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).storageView -} - -// MatchingMountEntry returns the MountEntry used for a path -func (r *Router) MatchingMountEntry(path string) *MountEntry { - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).mountEntry -} - -// MatchingBackend returns the backend used for a path -func (r *Router) MatchingBackend(path string) logical.Backend { - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).backend -} - -// MatchingSystemView returns the SystemView used for a path -func (r *Router) MatchingSystemView(path string) logical.SystemView { - r.l.RLock() - _, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return nil - } - return raw.(*routeEntry).backend.System() -} - -// MatchingStoragePrefixByAPIPath/StoragePath returns the mount path matching -// and storage prefix matching the given API/Storage path respectively -func (r *Router) MatchingStoragePrefixByAPIPath(path string) (string, string, bool) { - return r.matchingStoragePrefix(path, true) -} -func (r *Router) MatchingStoragePrefixByStoragePath(path string) (string, string, bool) { - return r.matchingStoragePrefix(path, false) -} -func (r *Router) matchingStoragePrefix(path string, apiPath bool) (string, string, bool) { - var raw interface{} - var ok bool - r.l.RLock() - if apiPath { - _, raw, ok = r.root.LongestPrefix(path) - } else { - _, raw, ok = r.storagePrefix.LongestPrefix(path) - } - r.l.RUnlock() - if !ok { - return "", "", false - } - - // Extract the mount path and storage prefix - re := raw.(*routeEntry) - mountPath := re.mountEntry.Path - prefix := re.storagePrefix - - // Add back the prefix for credential backends - if !apiPath && strings.HasPrefix(path, credentialBarrierPrefix) { - mountPath = credentialRoutePrefix + mountPath - } - - return mountPath, prefix, true -} - -// Route is used to route a given request -func (r *Router) Route(ctx context.Context, req *logical.Request) (*logical.Response, error) { - resp, _, _, err := r.routeCommon(ctx, req, false) - return resp, err -} - -// Route is used to route a given existence check request -func (r *Router) RouteExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - _, ok, exists, err := r.routeCommon(ctx, req, true) - return ok, exists, err -} - -func (r *Router) routeCommon(ctx context.Context, req *logical.Request, existenceCheck bool) (*logical.Response, bool, bool, error) { - // Find the mount point - r.l.RLock() - adjustedPath := req.Path - mount, raw, ok := r.root.LongestPrefix(adjustedPath) - if !ok && !strings.HasSuffix(adjustedPath, "/") { - // Re-check for a backend by appending a slash. This lets "foo" mean - // "foo/" at the root level which is almost always what we want. - adjustedPath += "/" - mount, raw, ok = r.root.LongestPrefix(adjustedPath) - } - r.l.RUnlock() - if !ok { - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - req.Path = adjustedPath - defer metrics.MeasureSince([]string{"route", string(req.Operation), - strings.Replace(mount, "/", "-", -1)}, time.Now()) - re := raw.(*routeEntry) - - // Grab a read lock on the route entry, this protects against the backend - // being reloaded during a request. - re.l.RLock() - defer re.l.RUnlock() - - // Filtered mounts will have a nil backend - if re.backend == nil { - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - - // If the path is tainted, we reject any operation except for - // Rollback and Revoke - if re.tainted { - switch req.Operation { - case logical.RevokeOperation, logical.RollbackOperation: - default: - return logical.ErrorResponse(fmt.Sprintf("no handler for route '%s'", req.Path)), false, false, logical.ErrUnsupportedPath - } - } - - // Adjust the path to exclude the routing prefix - originalPath := req.Path - req.Path = strings.TrimPrefix(req.Path, mount) - req.MountPoint = mount - req.MountType = re.mountEntry.Type - if req.Path == "/" { - req.Path = "" - } - - // Attach the storage view for the request - req.Storage = re.storageView - - originalEntityID := req.EntityID - - // Hash the request token unless the request is being routed to the token - // or system backend. - clientToken := req.ClientToken - switch { - case strings.HasPrefix(originalPath, "auth/token/"): - case strings.HasPrefix(originalPath, "sys/"): - case strings.HasPrefix(originalPath, "cubbyhole/"): - // In order for the token store to revoke later, we need to have the same - // salted ID, so we double-salt what's going to the cubbyhole backend - salt, err := r.tokenStoreSaltFunc(ctx) - if err != nil { - return nil, false, false, err - } - req.ClientToken = re.SaltID(salt.SaltID(req.ClientToken)) - default: - req.ClientToken = re.SaltID(req.ClientToken) - } - - // Cache the pointer to the original connection object - originalConn := req.Connection - - // Cache the identifier of the request - originalReqID := req.ID - - // Cache the client token's number of uses in the request - originalClientTokenRemainingUses := req.ClientTokenRemainingUses - req.ClientTokenRemainingUses = 0 - - // Cache the headers - headers := req.Headers - - // Filter and add passthrough headers to the backend - var passthroughRequestHeaders []string - if rawVal, ok := re.mountEntry.synthesizedConfigCache.Load("passthrough_request_headers"); ok { - passthroughRequestHeaders = rawVal.([]string) - } - req.Headers = filteredPassthroughHeaders(headers, passthroughRequestHeaders) - - // Cache the wrap info of the request - var wrapInfo *logical.RequestWrapInfo - if req.WrapInfo != nil { - wrapInfo = &logical.RequestWrapInfo{ - TTL: req.WrapInfo.TTL, - Format: req.WrapInfo.Format, - SealWrap: req.WrapInfo.SealWrap, - } - } - - reqTokenEntry := req.TokenEntry() - req.SetTokenEntry(nil) - - // Reset the request before returning - defer func() { - req.Path = originalPath - req.MountPoint = mount - req.MountType = re.mountEntry.Type - req.Connection = originalConn - req.ID = originalReqID - req.Storage = nil - req.ClientToken = clientToken - req.ClientTokenRemainingUses = originalClientTokenRemainingUses - req.WrapInfo = wrapInfo - req.Headers = headers - // This is only set in one place, after routing, so should never be set - // by a backend - req.SetLastRemoteWAL(0) - - // This will be used for attaching the mount accessor for the identities - // returned by the authentication backends - req.MountAccessor = re.mountEntry.Accessor - - req.EntityID = originalEntityID - - req.SetTokenEntry(reqTokenEntry) - }() - - // Invoke the backend - if existenceCheck { - ok, exists, err := re.backend.HandleExistenceCheck(ctx, req) - return nil, ok, exists, err - } else { - resp, err := re.backend.HandleRequest(ctx, req) - // When a token gets renewed, the request hits this path and reaches - // token store. Token store delegates the renewal to the expiration - // manager. Expiration manager in-turn creates a different logical - // request and forwards the request to the auth backend that had - // initially authenticated the login request. The forwarding to auth - // backend will make this code path hit for the second time for the - // same renewal request. The accessors in the Alias structs should be - // of the auth backend and not of the token store. Therefore, avoiding - // the overwriting of accessors by having a check for path prefix - // having "renew". This gets applied for "renew" and "renew-self" - // requests. - if resp != nil && - resp.Auth != nil && - !strings.HasPrefix(req.Path, "renew") { - if resp.Auth.Alias != nil { - resp.Auth.Alias.MountAccessor = re.mountEntry.Accessor - } - for _, alias := range resp.Auth.GroupAliases { - alias.MountAccessor = re.mountEntry.Accessor - } - } - return resp, false, false, err - } -} - -// RootPath checks if the given path requires root privileges -func (r *Router) RootPath(path string) bool { - r.l.RLock() - mount, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return false - } - re := raw.(*routeEntry) - - // Trim to get remaining path - remain := strings.TrimPrefix(path, mount) - - // Check the rootPaths of this backend - rootPaths := re.rootPaths.Load().(*radix.Tree) - match, raw, ok := rootPaths.LongestPrefix(remain) - if !ok { - return false - } - prefixMatch := raw.(bool) - - // Handle the prefix match case - if prefixMatch { - return strings.HasPrefix(remain, match) - } - - // Handle the exact match case - return match == remain -} - -// LoginPath checks if the given path is used for logins -func (r *Router) LoginPath(path string) bool { - r.l.RLock() - mount, raw, ok := r.root.LongestPrefix(path) - r.l.RUnlock() - if !ok { - return false - } - re := raw.(*routeEntry) - - // Trim to get remaining path - remain := strings.TrimPrefix(path, mount) - - // Check the loginPaths of this backend - loginPaths := re.loginPaths.Load().(*radix.Tree) - match, raw, ok := loginPaths.LongestPrefix(remain) - if !ok { - return false - } - prefixMatch := raw.(bool) - - // Handle the prefix match case - if prefixMatch { - return strings.HasPrefix(remain, match) - } - - // Handle the exact match case - return match == remain -} - -// pathsToRadix converts a the mapping of special paths to a mapping -// of special paths to radix trees. -func pathsToRadix(paths []string) *radix.Tree { - tree := radix.New() - for _, path := range paths { - // Check if this is a prefix or exact match - prefixMatch := len(path) >= 1 && path[len(path)-1] == '*' - if prefixMatch { - path = path[:len(path)-1] - } - - tree.Insert(path, prefixMatch) - } - - return tree -} - -// filteredPassthroughHeaders returns a headers map[string][]string that -// contains the filtered values contained in passthroughHeaders, as well as the -// values in whitelistedHeaders. Filtering of passthroughHeaders from the -// origHeaders is done is a case-insensitive manner. -func filteredPassthroughHeaders(origHeaders map[string][]string, passthroughHeaders []string) map[string][]string { - retHeaders := make(map[string][]string) - - // Short-circuit if there's nothing to filter - if len(passthroughHeaders) == 0 { - return retHeaders - } - - // Create a map that uses lowercased header values as the key and the original - // header naming as the value for comparison down below. - lowerHeadersRef := make(map[string]string, len(origHeaders)) - for key := range origHeaders { - lowerHeadersRef[strings.ToLower(key)] = key - } - - // Case-insensitive compare of passthrough headers against originating - // headers. The returned headers will be the same casing as the originating - // header name. - for _, ph := range passthroughHeaders { - if header, ok := lowerHeadersRef[strings.ToLower(ph)]; ok { - retHeaders[header] = origHeaders[header] - } - } - - return retHeaders -} diff --git a/vendor/github.com/hashicorp/vault/vault/router_access.go b/vendor/github.com/hashicorp/vault/vault/router_access.go deleted file mode 100644 index fc6790ff6..000000000 --- a/vendor/github.com/hashicorp/vault/vault/router_access.go +++ /dev/null @@ -1,14 +0,0 @@ -package vault - -// RouterAccess provides access into some things necessary for testing -type RouterAccess struct { - c *Core -} - -func NewRouterAccess(c *Core) *RouterAccess { - return &RouterAccess{c: c} -} - -func (r *RouterAccess) StoragePrefixByAPIPath(path string) (string, string, bool) { - return r.c.router.MatchingStoragePrefixByAPIPath(path) -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal.go b/vendor/github.com/hashicorp/vault/vault/seal.go deleted file mode 100644 index 363a47daf..000000000 --- a/vendor/github.com/hashicorp/vault/vault/seal.go +++ /dev/null @@ -1,383 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/subtle" - "encoding/base64" - "encoding/json" - "fmt" - "sync/atomic" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/physical" - - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -const ( - // barrierSealConfigPath is the path used to store our seal configuration. - // This value is stored in plaintext, since we must be able to read it even - // with the Vault sealed. This is required so that we know how many secret - // parts must be used to reconstruct the master key. - barrierSealConfigPath = "core/seal-config" - - // recoverySealConfigPath is the path to the recovery key seal - // configuration. It lives inside the barrier. - // DEPRECATED: Use recoverySealConfigPlaintextPath instead. - recoverySealConfigPath = "core/recovery-seal-config" - - // recoverySealConfigPlaintextPath is the path to the recovery key seal - // configuration. This is stored in plaintext so that we can perform - // auto-unseal. - recoverySealConfigPlaintextPath = "core/recovery-config" - - // recoveryKeyPath is the path to the recovery key - recoveryKeyPath = "core/recovery-key" - - // storedBarrierKeysPath is the path used for storing HSM-encrypted unseal keys - storedBarrierKeysPath = "core/hsm/barrier-unseal-keys" - - // hsmStoredIVPath is the path to the initialization vector for stored keys - hsmStoredIVPath = "core/hsm/iv" -) - -const ( - SealTypeShamir = "shamir" - SealTypePKCS11 = "pkcs11" - SealTypeAWSKMS = "awskms" - SealTypeTest = "test-auto" - - RecoveryTypeUnsupported = "unsupported" - RecoveryTypeShamir = "shamir" -) - -type KeyNotFoundError struct { - Err error -} - -func (e *KeyNotFoundError) WrappedErrors() []error { - return []error{e.Err} -} - -func (e *KeyNotFoundError) Error() string { - return e.Err.Error() -} - -type Seal interface { - SetCore(*Core) - Init(context.Context) error - Finalize(context.Context) error - - StoredKeysSupported() bool - SetStoredKeys(context.Context, [][]byte) error - GetStoredKeys(context.Context) ([][]byte, error) - - BarrierType() string - BarrierConfig(context.Context) (*SealConfig, error) - SetBarrierConfig(context.Context, *SealConfig) error - - RecoveryKeySupported() bool - RecoveryType() string - RecoveryConfig(context.Context) (*SealConfig, error) - SetRecoveryConfig(context.Context, *SealConfig) error - SetRecoveryKey(context.Context, []byte) error - VerifyRecoveryKey(context.Context, []byte) error -} - -type defaultSeal struct { - config atomic.Value - core *Core - PretendToAllowStoredShares bool - PretendToAllowRecoveryKeys bool - PretendRecoveryKey []byte -} - -func NewDefaultSeal() Seal { - ret := &defaultSeal{} - ret.config.Store((*SealConfig)(nil)) - return ret -} - -func (d *defaultSeal) checkCore() error { - if d.core == nil { - return fmt.Errorf("seal does not have a core set") - } - return nil -} - -func (d *defaultSeal) SetCore(core *Core) { - d.core = core -} - -func (d *defaultSeal) Init(ctx context.Context) error { - return nil -} - -func (d *defaultSeal) Finalize(ctx context.Context) error { - return nil -} - -func (d *defaultSeal) BarrierType() string { - return SealTypeShamir -} - -func (d *defaultSeal) StoredKeysSupported() bool { - return d.PretendToAllowStoredShares -} - -func (d *defaultSeal) RecoveryKeySupported() bool { - return d.PretendToAllowRecoveryKeys -} - -func (d *defaultSeal) SetStoredKeys(ctx context.Context, keys [][]byte) error { - return fmt.Errorf("stored keys are not supported") -} - -func (d *defaultSeal) GetStoredKeys(ctx context.Context) ([][]byte, error) { - return nil, fmt.Errorf("stored keys are not supported") -} - -func (d *defaultSeal) BarrierConfig(ctx context.Context) (*SealConfig, error) { - if d.config.Load().(*SealConfig) != nil { - return d.config.Load().(*SealConfig).Clone(), nil - } - - if err := d.checkCore(); err != nil { - return nil, err - } - - // Fetch the core configuration - pe, err := d.core.physical.Get(ctx, barrierSealConfigPath) - if err != nil { - d.core.logger.Error("failed to read seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to check seal configuration: {{err}}", err) - } - - // If the seal configuration is missing, we are not initialized - if pe == nil { - d.core.logger.Info("seal configuration missing, not initialized") - return nil, nil - } - - var conf SealConfig - - // Decode the barrier entry - if err := jsonutil.DecodeJSON(pe.Value, &conf); err != nil { - d.core.logger.Error("failed to decode seal configuration", "error", err) - return nil, errwrap.Wrapf("failed to decode seal configuration: {{err}}", err) - } - - switch conf.Type { - // This case should not be valid for other types as only this is the default - case "": - conf.Type = d.BarrierType() - case d.BarrierType(): - default: - d.core.logger.Error("barrier seal type does not match loaded type", "barrier_seal_type", conf.Type, "loaded_seal_type", d.BarrierType()) - return nil, fmt.Errorf("barrier seal type of %q does not match loaded type of %q", conf.Type, d.BarrierType()) - } - - // Check for a valid seal configuration - if err := conf.Validate(); err != nil { - d.core.logger.Error("invalid seal configuration", "error", err) - return nil, errwrap.Wrapf("seal validation failed: {{err}}", err) - } - - d.config.Store(&conf) - return conf.Clone(), nil -} - -func (d *defaultSeal) SetBarrierConfig(ctx context.Context, config *SealConfig) error { - if err := d.checkCore(); err != nil { - return err - } - - // Provide a way to wipe out the cached value (also prevents actually - // saving a nil config) - if config == nil { - d.config.Store((*SealConfig)(nil)) - return nil - } - - config.Type = d.BarrierType() - - // Encode the seal configuration - buf, err := json.Marshal(config) - if err != nil { - return errwrap.Wrapf("failed to encode seal configuration: {{err}}", err) - } - - // Store the seal configuration - pe := &physical.Entry{ - Key: barrierSealConfigPath, - Value: buf, - } - - if err := d.core.physical.Put(ctx, pe); err != nil { - d.core.logger.Error("failed to write seal configuration", "error", err) - return errwrap.Wrapf("failed to write seal configuration: {{err}}", err) - } - - d.config.Store(config.Clone()) - - return nil -} - -func (d *defaultSeal) RecoveryType() string { - if d.PretendToAllowRecoveryKeys { - return RecoveryTypeShamir - } - return RecoveryTypeUnsupported -} - -func (d *defaultSeal) RecoveryConfig(ctx context.Context) (*SealConfig, error) { - if d.PretendToAllowRecoveryKeys { - return &SealConfig{ - SecretShares: 5, - SecretThreshold: 3, - }, nil - } - return nil, fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) SetRecoveryConfig(ctx context.Context, config *SealConfig) error { - if d.PretendToAllowRecoveryKeys { - return nil - } - return fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) VerifyRecoveryKey(ctx context.Context, key []byte) error { - if d.PretendToAllowRecoveryKeys { - if subtle.ConstantTimeCompare(key, d.PretendRecoveryKey) == 1 { - return nil - } - return fmt.Errorf("mismatch") - } - return fmt.Errorf("recovery not supported") -} - -func (d *defaultSeal) SetRecoveryKey(ctx context.Context, key []byte) error { - if d.PretendToAllowRecoveryKeys { - d.PretendRecoveryKey = key - return nil - } - return fmt.Errorf("recovery not supported") -} - -// SealConfig is used to describe the seal configuration -type SealConfig struct { - // The type, for sanity checking - Type string `json:"type"` - - // SecretShares is the number of shares the secret is split into. This is - // the N value of Shamir. - SecretShares int `json:"secret_shares"` - - // SecretThreshold is the number of parts required to open the vault. This - // is the T value of Shamir. - SecretThreshold int `json:"secret_threshold"` - - // PGPKeys is the array of public PGP keys used, if requested, to encrypt - // the output unseal tokens. If provided, it sets the value of - // SecretShares. Ordering is important. - PGPKeys []string `json:"pgp_keys"` - - // Nonce is a nonce generated by Vault used to ensure that when unseal keys - // are submitted for a rekey operation, the rekey operation itself is the - // one intended. This prevents hijacking of the rekey operation, since it - // is unauthenticated. - Nonce string `json:"nonce"` - - // Backup indicates whether or not a backup of PGP-encrypted unseal keys - // should be stored at coreUnsealKeysBackupPath after successful rekeying. - Backup bool `json:"backup"` - - // How many keys to store, for seals that support storage. - StoredShares int `json:"stored_shares"` - - // Stores the progress of the rekey operation (key shares) - RekeyProgress [][]byte `json:"-"` - - // VerificationRequired indicates that after a rekey validation must be - // performed (via providing shares from the new key) before the new key is - // actually installed. This is omitted from JSON as we don't persist the - // new key, it lives only in memory. - VerificationRequired bool `json:"-"` - - // VerificationKey is the new key that we will roll to after successful - // validation - VerificationKey []byte `json:"-"` - - // VerificationNonce stores the current operation nonce for verification - VerificationNonce string `json:"-"` - - // Stores the progress of the verification operation (key shares) - VerificationProgress [][]byte `json:"-"` -} - -// Validate is used to sanity check the seal configuration -func (s *SealConfig) Validate() error { - if s.SecretShares < 1 { - return fmt.Errorf("shares must be at least one") - } - if s.SecretThreshold < 1 { - return fmt.Errorf("threshold must be at least one") - } - if s.SecretShares > 1 && s.SecretThreshold == 1 { - return fmt.Errorf("threshold must be greater than one for multiple shares") - } - if s.SecretShares > 255 { - return fmt.Errorf("shares must be less than 256") - } - if s.SecretThreshold > 255 { - return fmt.Errorf("threshold must be less than 256") - } - if s.SecretThreshold > s.SecretShares { - return fmt.Errorf("threshold cannot be larger than shares") - } - if s.StoredShares > s.SecretShares { - return fmt.Errorf("stored keys cannot be larger than shares") - } - if len(s.PGPKeys) > 0 && len(s.PGPKeys) != s.SecretShares-s.StoredShares { - return fmt.Errorf("count mismatch between number of provided PGP keys and number of shares") - } - if len(s.PGPKeys) > 0 { - for _, keystring := range s.PGPKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - _, err = openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - } - } - return nil -} - -func (s *SealConfig) Clone() *SealConfig { - ret := &SealConfig{ - Type: s.Type, - SecretShares: s.SecretShares, - SecretThreshold: s.SecretThreshold, - Nonce: s.Nonce, - Backup: s.Backup, - StoredShares: s.StoredShares, - VerificationRequired: s.VerificationRequired, - VerificationNonce: s.VerificationNonce, - } - if len(s.PGPKeys) > 0 { - ret.PGPKeys = make([]string, len(s.PGPKeys)) - copy(ret.PGPKeys, s.PGPKeys) - } - if len(s.VerificationKey) > 0 { - ret.VerificationKey = make([]byte, len(s.VerificationKey)) - copy(ret.VerificationKey, s.VerificationKey) - } - return ret -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_access.go b/vendor/github.com/hashicorp/vault/vault/seal_access.go deleted file mode 100644 index 5c44bd184..000000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_access.go +++ /dev/null @@ -1,63 +0,0 @@ -package vault - -import ( - "context" - "fmt" -) - -// SealAccess is a wrapper around Seal that exposes accessor methods -// through Core.SealAccess() while restricting the ability to modify -// Core.seal itself. -type SealAccess struct { - seal Seal -} - -func NewSealAccess(seal Seal) *SealAccess { - return &SealAccess{seal: seal} -} - -func (s *SealAccess) StoredKeysSupported() bool { - return s.seal.StoredKeysSupported() -} - -func (s *SealAccess) BarrierConfig(ctx context.Context) (*SealConfig, error) { - return s.seal.BarrierConfig(ctx) -} - -func (s *SealAccess) RecoveryKeySupported() bool { - return s.seal.RecoveryKeySupported() -} - -func (s *SealAccess) RecoveryConfig(ctx context.Context) (*SealConfig, error) { - return s.seal.RecoveryConfig(ctx) -} - -func (s *SealAccess) VerifyRecoveryKey(ctx context.Context, key []byte) error { - return s.seal.VerifyRecoveryKey(ctx, key) -} - -func (s *SealAccess) ClearCaches(ctx context.Context) { - s.seal.SetBarrierConfig(ctx, nil) - if s.RecoveryKeySupported() { - s.seal.SetRecoveryConfig(ctx, nil) - } -} - -type SealAccessTestingParams struct { - PretendToAllowStoredShares bool - PretendToAllowRecoveryKeys bool - PretendRecoveryKey []byte -} - -func (s *SealAccess) SetTestingParams(params *SealAccessTestingParams) error { - d, ok := s.seal.(*defaultSeal) - if !ok { - return fmt.Errorf("not a defaultseal") - } - d.PretendToAllowRecoveryKeys = params.PretendToAllowRecoveryKeys - d.PretendToAllowStoredShares = params.PretendToAllowStoredShares - if params.PretendRecoveryKey != nil { - d.PretendRecoveryKey = params.PretendRecoveryKey - } - return nil -} diff --git a/vendor/github.com/hashicorp/vault/vault/seal_testing.go b/vendor/github.com/hashicorp/vault/vault/seal_testing.go deleted file mode 100644 index 4f6b1d125..000000000 --- a/vendor/github.com/hashicorp/vault/vault/seal_testing.go +++ /dev/null @@ -1,80 +0,0 @@ -package vault - -import ( - "context" - - "github.com/mitchellh/go-testing-interface" -) - -var ( - TestCoreUnsealedWithConfigs = testCoreUnsealedWithConfigs - TestSealDefConfigs = testSealDefConfigs -) - -type TestSealOpts struct { - StoredKeysDisabled bool - RecoveryKeysDisabled bool -} - -func NewTestSeal(t testing.T, opts *TestSealOpts) Seal { - return NewDefaultSeal() -} - -func testCoreUnsealedWithConfigs(t testing.T, barrierConf, recoveryConf *SealConfig) (*Core, [][]byte, [][]byte, string) { - seal := NewTestSeal(t, nil) - core := TestCoreWithSeal(t, seal, false) - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConf, - RecoveryConfig: recoveryConf, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - err = core.UnsealWithStoredKeys(context.Background()) - if err != nil { - t.Fatalf("err: %s", err) - } - if core.Sealed() { - for _, key := range result.SecretShares { - if _, err := core.Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - } - - return core, result.SecretShares, result.RecoveryShares, result.RootToken -} - -func testSealDefConfigs() (*SealConfig, *SealConfig) { - return &SealConfig{ - SecretShares: 5, - SecretThreshold: 3, - }, nil -} - -func TestCoreUnsealedWithConfigSealOpts(t testing.T, barrierConf, recoveryConf *SealConfig, sealOpts *TestSealOpts) (*Core, [][]byte, [][]byte, string) { - seal := NewTestSeal(t, sealOpts) - core := TestCoreWithSeal(t, seal, false) - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConf, - RecoveryConfig: recoveryConf, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - for _, key := range result.SecretShares { - if _, err := core.Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - - return core, result.SecretShares, result.RecoveryShares, result.RootToken -} diff --git a/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go b/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go deleted file mode 100644 index a7e6fc222..000000000 --- a/vendor/github.com/hashicorp/vault/vault/sealunwrapper.go +++ /dev/null @@ -1,183 +0,0 @@ -// +build !ent -// +build !prem -// +build !pro -// +build !hsm - -package vault - -import ( - "context" - "fmt" - "sync/atomic" - - proto "github.com/golang/protobuf/proto" - log "github.com/hashicorp/go-hclog" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/physical" -) - -// NewSealUnwrapper creates a new seal unwrapper -func NewSealUnwrapper(underlying physical.Backend, logger log.Logger) physical.Backend { - ret := &sealUnwrapper{ - underlying: underlying, - logger: logger, - locks: locksutil.CreateLocks(), - allowUnwraps: new(uint32), - } - - if underTxn, ok := underlying.(physical.Transactional); ok { - return &transactionalSealUnwrapper{ - sealUnwrapper: ret, - Transactional: underTxn, - } - } - - return ret -} - -var _ physical.Backend = (*sealUnwrapper)(nil) -var _ physical.Transactional = (*transactionalSealUnwrapper)(nil) - -type sealUnwrapper struct { - underlying physical.Backend - logger log.Logger - locks []*locksutil.LockEntry - allowUnwraps *uint32 -} - -// transactionalSealUnwrapper is a seal unwrapper that wraps a physical that is transactional -type transactionalSealUnwrapper struct { - *sealUnwrapper - physical.Transactional -} - -func (d *sealUnwrapper) Put(ctx context.Context, entry *physical.Entry) error { - if entry == nil { - return nil - } - - locksutil.LockForKey(d.locks, entry.Key).Lock() - defer locksutil.LockForKey(d.locks, entry.Key).Unlock() - - return d.underlying.Put(ctx, entry) -} - -func (d *sealUnwrapper) Get(ctx context.Context, key string) (*physical.Entry, error) { - entry, err := d.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var performUnwrap bool - se := &physical.SealWrapEntry{} - // If the value ends in our canary value, try to decode the bytes. - eLen := len(entry.Value) - if eLen > 0 && entry.Value[eLen-1] == 's' { - if err := proto.Unmarshal(entry.Value[:eLen-1], se); err == nil { - // We unmarshaled successfully which means we need to store it as a - // non-proto message - performUnwrap = true - } - } - if !performUnwrap { - return entry, nil - } - // It's actually encrypted and we can't read it - if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) - } - if atomic.LoadUint32(d.allowUnwraps) != 1 { - return &physical.Entry{ - Key: entry.Key, - Value: se.Ciphertext, - }, nil - } - - locksutil.LockForKey(d.locks, key).Lock() - defer locksutil.LockForKey(d.locks, key).Unlock() - - // At this point we need to re-read and re-check - entry, err = d.underlying.Get(ctx, key) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - performUnwrap = false - se = &physical.SealWrapEntry{} - // If the value ends in our canary value, try to decode the bytes. - eLen = len(entry.Value) - if eLen > 0 && entry.Value[eLen-1] == 's' { - // We ignore an error because the canary is not a guarantee; if it - // doesn't decode, proceed normally - if err := proto.Unmarshal(entry.Value[:eLen-1], se); err == nil { - // We unmarshaled successfully which means we need to store it as a - // non-proto message - performUnwrap = true - } - } - if !performUnwrap { - return entry, nil - } - if se.Wrapped { - return nil, fmt.Errorf("cannot decode sealwrapped storage entry %q", entry.Key) - } - - entry = &physical.Entry{ - Key: entry.Key, - Value: se.Ciphertext, - } - - if atomic.LoadUint32(d.allowUnwraps) != 1 { - return entry, nil - } - return entry, d.underlying.Put(ctx, entry) -} - -func (d *sealUnwrapper) Delete(ctx context.Context, key string) error { - locksutil.LockForKey(d.locks, key).Lock() - defer locksutil.LockForKey(d.locks, key).Unlock() - - return d.underlying.Delete(ctx, key) -} - -func (d *sealUnwrapper) List(ctx context.Context, prefix string) ([]string, error) { - return d.underlying.List(ctx, prefix) -} - -func (d *transactionalSealUnwrapper) Transaction(ctx context.Context, txns []*physical.TxnEntry) error { - // Collect keys that need to be locked - var keys []string - for _, curr := range txns { - keys = append(keys, curr.Entry.Key) - } - // Lock the keys - for _, l := range locksutil.LocksForKeys(d.locks, keys) { - l.Lock() - defer l.Unlock() - } - - if err := d.Transactional.Transaction(ctx, txns); err != nil { - return err - } - - return nil -} - -// This should only run during preSeal which ensures that it can't be run -// concurrently and that it will be run only by the active node -func (d *sealUnwrapper) stopUnwraps() { - atomic.StoreUint32(d.allowUnwraps, 0) -} - -func (d *sealUnwrapper) runUnwraps() { - // Allow key unwraps on key gets. This gets set only when running on the - // active node to prevent standbys from changing data underneath the - // primary - atomic.StoreUint32(d.allowUnwraps, 1) -} diff --git a/vendor/github.com/hashicorp/vault/vault/testing.go b/vendor/github.com/hashicorp/vault/vault/testing.go deleted file mode 100644 index 38dc423ca..000000000 --- a/vendor/github.com/hashicorp/vault/vault/testing.go +++ /dev/null @@ -1,1416 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/sha256" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/base64" - "encoding/pem" - "errors" - "fmt" - "io" - "io/ioutil" - "math/big" - mathrand "math/rand" - "net" - "net/http" - "os" - "os/exec" - "path/filepath" - "sync" - "time" - - log "github.com/hashicorp/go-hclog" - "github.com/mitchellh/copystructure" - - "golang.org/x/crypto/ssh" - "golang.org/x/net/http2" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/api" - "github.com/hashicorp/vault/audit" - "github.com/hashicorp/vault/helper/logging" - "github.com/hashicorp/vault/helper/reload" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/hashicorp/vault/physical" - "github.com/mitchellh/go-testing-interface" - - physInmem "github.com/hashicorp/vault/physical/inmem" -) - -// This file contains a number of methods that are useful for unit -// tests within other packages. - -const ( - testSharedPublicKey = ` -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9i+hFxZHGo6KblVme4zrAcJstR6I0PTJozW286X4WyvPnkMYDQ5mnhEYC7UWCvjoTWbPEXPX7NjhRtwQTGD67bV+lrxgfyzK1JZbUXK4PwgKJvQD+XyyWYMzDgGSQY61KUSqCxymSm/9NZkPU3ElaQ9xQuTzPpztM4ROfb8f2Yv6/ZESZsTo0MTAkp8Pcy+WkioI/uJ1H7zqs0EA4OMY4aDJRu0UtP4rTVeYNEAuRXdX+eH4aW3KMvhzpFTjMbaJHJXlEeUm2SaX5TNQyTOvghCeQILfYIL/Ca2ij8iwCmulwdV6eQGfd4VDu40PvSnmfoaE38o6HaPnX0kUcnKiT -` - testSharedPrivateKey = ` ------BEGIN RSA PRIVATE KEY----- -MIIEogIBAAKCAQEAvYvoRcWRxqOim5VZnuM6wHCbLUeiND0yaM1tvOl+Fsrz55DG -A0OZp4RGAu1Fgr46E1mzxFz1+zY4UbcEExg+u21fpa8YH8sytSWW1FyuD8ICib0A -/l8slmDMw4BkkGOtSlEqgscpkpv/TWZD1NxJWkPcULk8z6c7TOETn2/H9mL+v2RE -mbE6NDEwJKfD3MvlpIqCP7idR+86rNBAODjGOGgyUbtFLT+K01XmDRALkV3V/nh+ -GltyjL4c6RU4zG2iRyV5RHlJtkml+UzUMkzr4IQnkCC32CC/wmtoo/IsAprpcHVe -nkBn3eFQ7uND70p5n6GhN/KOh2j519JFHJyokwIDAQABAoIBAHX7VOvBC3kCN9/x -+aPdup84OE7Z7MvpX6w+WlUhXVugnmsAAVDczhKoUc/WktLLx2huCGhsmKvyVuH+ -MioUiE+vx75gm3qGx5xbtmOfALVMRLopjCnJYf6EaFA0ZeQ+NwowNW7Lu0PHmAU8 -Z3JiX8IwxTz14DU82buDyewO7v+cEr97AnERe3PUcSTDoUXNaoNxjNpEJkKREY6h -4hAY676RT/GsRcQ8tqe/rnCqPHNd7JGqL+207FK4tJw7daoBjQyijWuB7K5chSal -oPInylM6b13ASXuOAOT/2uSUBWmFVCZPDCmnZxy2SdnJGbsJAMl7Ma3MUlaGvVI+ -Tfh1aQkCgYEA4JlNOabTb3z42wz6mz+Nz3JRwbawD+PJXOk5JsSnV7DtPtfgkK9y -6FTQdhnozGWShAvJvc+C4QAihs9AlHXoaBY5bEU7R/8UK/pSqwzam+MmxmhVDV7G -IMQPV0FteoXTaJSikhZ88mETTegI2mik+zleBpVxvfdhE5TR+lq8Br0CgYEA2AwJ -CUD5CYUSj09PluR0HHqamWOrJkKPFPwa+5eiTTCzfBBxImYZh7nXnWuoviXC0sg2 -AuvCW+uZ48ygv/D8gcz3j1JfbErKZJuV+TotK9rRtNIF5Ub7qysP7UjyI7zCssVM -kuDd9LfRXaB/qGAHNkcDA8NxmHW3gpln4CFdSY8CgYANs4xwfercHEWaJ1qKagAe -rZyrMpffAEhicJ/Z65lB0jtG4CiE6w8ZeUMWUVJQVcnwYD+4YpZbX4S7sJ0B8Ydy -AhkSr86D/92dKTIt2STk6aCN7gNyQ1vW198PtaAWH1/cO2UHgHOy3ZUt5X/Uwxl9 -cex4flln+1Viumts2GgsCQKBgCJH7psgSyPekK5auFdKEr5+Gc/jB8I/Z3K9+g4X -5nH3G1PBTCJYLw7hRzw8W/8oALzvddqKzEFHphiGXK94Lqjt/A4q1OdbCrhiE68D -My21P/dAKB1UYRSs9Y8CNyHCjuZM9jSMJ8vv6vG/SOJPsnVDWVAckAbQDvlTHC9t -O98zAoGAcbW6uFDkrv0XMCpB9Su3KaNXOR0wzag+WIFQRXCcoTvxVi9iYfUReQPi -oOyBJU/HMVvBfv4g+OVFLVgSwwm6owwsouZ0+D/LasbuHqYyqYqdyPJQYzWA2Y+F -+B6f4RoPdSXj24JHPg/ioRxjaj094UXJxua2yfkcecGNEuBQHSs= ------END RSA PRIVATE KEY----- -` -) - -// TestCore returns a pure in-memory, uninitialized core for testing. -func TestCore(t testing.T) *Core { - return TestCoreWithSeal(t, nil, false) -} - -// TestCoreRaw returns a pure in-memory, uninitialized core for testing. The raw -// storage endpoints are enabled with this core. -func TestCoreRaw(t testing.T) *Core { - return TestCoreWithSeal(t, nil, true) -} - -// TestCoreNewSeal returns a pure in-memory, uninitialized core with -// the new seal configuration. -func TestCoreNewSeal(t testing.T) *Core { - seal := NewTestSeal(t, nil) - return TestCoreWithSeal(t, seal, false) -} - -// TestCoreWithSeal returns a pure in-memory, uninitialized core with the -// specified seal for testing. -func TestCoreWithSeal(t testing.T, testSeal Seal, enableRaw bool) *Core { - logger := logging.NewVaultLogger(log.Trace) - physicalBackend, err := physInmem.NewInmem(nil, logger) - if err != nil { - t.Fatal(err) - } - - conf := testCoreConfig(t, physicalBackend, logger) - - if enableRaw { - conf.EnableRaw = true - } - - if testSeal != nil { - conf.Seal = testSeal - } - - c, err := NewCore(conf) - if err != nil { - t.Fatalf("err: %s", err) - } - - return c -} - -func testCoreConfig(t testing.T, physicalBackend physical.Backend, logger log.Logger) *CoreConfig { - t.Helper() - noopAudits := map[string]audit.Factory{ - "noop": func(_ context.Context, config *audit.BackendConfig) (audit.Backend, error) { - view := &logical.InmemStorage{} - view.Put(context.Background(), &logical.StorageEntry{ - Key: "salt", - Value: []byte("foo"), - }) - config.SaltConfig = &salt.Config{ - HMAC: sha256.New, - HMACType: "hmac-sha256", - } - config.SaltView = view - return &noopAudit{ - Config: config, - }, nil - }, - } - - noopBackends := make(map[string]logical.Factory) - noopBackends["noop"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - b := new(framework.Backend) - b.Setup(ctx, config) - return b, nil - } - noopBackends["http"] = func(ctx context.Context, config *logical.BackendConfig) (logical.Backend, error) { - return new(rawHTTP), nil - } - - credentialBackends := make(map[string]logical.Factory) - for backendName, backendFactory := range noopBackends { - credentialBackends[backendName] = backendFactory - } - for backendName, backendFactory := range testCredentialBackends { - credentialBackends[backendName] = backendFactory - } - - logicalBackends := make(map[string]logical.Factory) - for backendName, backendFactory := range noopBackends { - logicalBackends[backendName] = backendFactory - } - - logicalBackends["kv"] = LeasedPassthroughBackendFactory - for backendName, backendFactory := range testLogicalBackends { - logicalBackends[backendName] = backendFactory - } - - conf := &CoreConfig{ - Physical: physicalBackend, - AuditBackends: noopAudits, - LogicalBackends: logicalBackends, - CredentialBackends: credentialBackends, - DisableMlock: true, - Logger: logger, - } - - return conf -} - -// TestCoreInit initializes the core with a single key, and returns -// the key that must be used to unseal the core and a root token. -func TestCoreInit(t testing.T, core *Core) ([][]byte, string) { - t.Helper() - secretShares, _, root := TestCoreInitClusterWrapperSetup(t, core, nil, nil) - return secretShares, root -} - -func TestCoreInitClusterWrapperSetup(t testing.T, core *Core, clusterAddrs []*net.TCPAddr, handler http.Handler) ([][]byte, [][]byte, string) { - t.Helper() - core.SetClusterListenerAddrs(clusterAddrs) - core.SetClusterHandler(handler) - - barrierConfig := &SealConfig{ - SecretShares: 3, - SecretThreshold: 3, - } - - // If we support storing barrier keys, then set that to equal the min threshold to unseal - if core.seal.StoredKeysSupported() { - barrierConfig.StoredShares = barrierConfig.SecretThreshold - } - - recoveryConfig := &SealConfig{ - SecretShares: 3, - SecretThreshold: 3, - } - - result, err := core.Initialize(context.Background(), &InitParams{ - BarrierConfig: barrierConfig, - RecoveryConfig: recoveryConfig, - }) - if err != nil { - t.Fatalf("err: %s", err) - } - return result.SecretShares, result.RecoveryShares, result.RootToken -} - -func TestCoreUnseal(core *Core, key []byte) (bool, error) { - return core.Unseal(key) -} - -func TestCoreUnsealWithRecoveryKeys(core *Core, key []byte) (bool, error) { - return core.UnsealWithRecoveryKeys(context.Background(), key) -} - -// TestCoreUnsealed returns a pure in-memory core that is already -// initialized and unsealed. -func TestCoreUnsealed(t testing.T) (*Core, [][]byte, string) { - t.Helper() - core := TestCore(t) - return testCoreUnsealed(t, core) -} - -// TestCoreUnsealedRaw returns a pure in-memory core that is already -// initialized, unsealed, and with raw endpoints enabled. -func TestCoreUnsealedRaw(t testing.T) (*Core, [][]byte, string) { - t.Helper() - core := TestCoreRaw(t) - return testCoreUnsealed(t, core) -} - -func testCoreUnsealed(t testing.T, core *Core) (*Core, [][]byte, string) { - t.Helper() - keys, token := TestCoreInit(t, core) - for _, key := range keys { - if _, err := TestCoreUnseal(core, TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - - return core, keys, token -} - -func TestCoreUnsealedBackend(t testing.T, backend physical.Backend) (*Core, [][]byte, string) { - t.Helper() - logger := logging.NewVaultLogger(log.Trace) - conf := testCoreConfig(t, backend, logger) - conf.Seal = NewTestSeal(t, nil) - - core, err := NewCore(conf) - if err != nil { - t.Fatalf("err: %s", err) - } - - keys, token := TestCoreInit(t, core) - for _, key := range keys { - if _, err := TestCoreUnseal(core, TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - if err := core.UnsealWithStoredKeys(context.Background()); err != nil { - t.Fatal(err) - } - - if core.Sealed() { - t.Fatal("should not be sealed") - } - - return core, keys, token -} - -// TestKeyCopy is a silly little function to just copy the key so that -// it can be used with Unseal easily. -func TestKeyCopy(key []byte) []byte { - result := make([]byte, len(key)) - copy(result, key) - return result -} - -func TestDynamicSystemView(c *Core) *dynamicSystemView { - me := &MountEntry{ - Config: MountConfig{ - DefaultLeaseTTL: 24 * time.Hour, - MaxLeaseTTL: 2 * 24 * time.Hour, - }, - } - - return &dynamicSystemView{c, me} -} - -// TestAddTestPlugin registers the testFunc as part of the plugin command to the -// plugin catalog. -func TestAddTestPlugin(t testing.T, c *Core, name, testFunc string) { - file, err := os.Open(os.Args[0]) - if err != nil { - t.Fatal(err) - } - defer file.Close() - - hash := sha256.New() - - _, err = io.Copy(hash, file) - if err != nil { - t.Fatal(err) - } - - sum := hash.Sum(nil) - - // Determine plugin directory path - fullPath, err := filepath.EvalSymlinks(os.Args[0]) - if err != nil { - t.Fatal(err) - } - directoryPath := filepath.Dir(fullPath) - - // Set core's plugin directory and plugin catalog directory - c.pluginDirectory = directoryPath - c.pluginCatalog.directory = directoryPath - - command := fmt.Sprintf("%s", filepath.Base(os.Args[0])) - args := []string{fmt.Sprintf("--test.run=%s", testFunc)} - err = c.pluginCatalog.Set(context.Background(), name, command, args, sum) - if err != nil { - t.Fatal(err) - } -} - -// TestAddTestPluginTempDir registers the testFunc as part of the plugin command to the -// plugin catalog. It uses tmpDir as the plugin directory. -func TestAddTestPluginTempDir(t testing.T, c *Core, name, testFunc, tempDir string) { - file, err := os.Open(os.Args[0]) - if err != nil { - t.Fatal(err) - } - defer file.Close() - - fi, err := file.Stat() - if err != nil { - t.Fatal(err) - } - - // Copy over the file to the temp dir - dst := filepath.Join(tempDir, filepath.Base(os.Args[0])) - out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode()) - if err != nil { - t.Fatal(err) - } - defer out.Close() - - if _, err = io.Copy(out, file); err != nil { - t.Fatal(err) - } - err = out.Sync() - if err != nil { - t.Fatal(err) - } - - // Determine plugin directory full path - fullPath, err := filepath.EvalSymlinks(tempDir) - if err != nil { - t.Fatal(err) - } - - reader, err := os.Open(filepath.Join(fullPath, filepath.Base(os.Args[0]))) - if err != nil { - t.Fatal(err) - } - defer reader.Close() - - // Find out the sha256 - hash := sha256.New() - - _, err = io.Copy(hash, reader) - if err != nil { - t.Fatal(err) - } - - sum := hash.Sum(nil) - - // Set core's plugin directory and plugin catalog directory - c.pluginDirectory = fullPath - c.pluginCatalog.directory = fullPath - - command := fmt.Sprintf("%s", filepath.Base(os.Args[0])) - args := []string{fmt.Sprintf("--test.run=%s", testFunc)} - err = c.pluginCatalog.Set(context.Background(), name, command, args, sum) - if err != nil { - t.Fatal(err) - } -} - -var testLogicalBackends = map[string]logical.Factory{} -var testCredentialBackends = map[string]logical.Factory{} - -// StartSSHHostTestServer starts the test server which responds to SSH -// authentication. Used to test the SSH secret backend. -func StartSSHHostTestServer() (string, error) { - pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(testSharedPublicKey)) - if err != nil { - return "", fmt.Errorf("error parsing public key") - } - serverConfig := &ssh.ServerConfig{ - PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { - if bytes.Compare(pubKey.Marshal(), key.Marshal()) == 0 { - return &ssh.Permissions{}, nil - } else { - return nil, fmt.Errorf("key does not match") - } - }, - } - signer, err := ssh.ParsePrivateKey([]byte(testSharedPrivateKey)) - if err != nil { - panic("Error parsing private key") - } - serverConfig.AddHostKey(signer) - - soc, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", fmt.Errorf("error listening to connection") - } - - go func() { - for { - conn, err := soc.Accept() - if err != nil { - panic(fmt.Sprintf("Error accepting incoming connection: %s", err)) - } - defer conn.Close() - sshConn, chanReqs, _, err := ssh.NewServerConn(conn, serverConfig) - if err != nil { - panic(fmt.Sprintf("Handshaking error: %v", err)) - } - - go func() { - for chanReq := range chanReqs { - go func(chanReq ssh.NewChannel) { - if chanReq.ChannelType() != "session" { - chanReq.Reject(ssh.UnknownChannelType, "unknown channel type") - return - } - - ch, requests, err := chanReq.Accept() - if err != nil { - panic(fmt.Sprintf("Error accepting channel: %s", err)) - } - - go func(ch ssh.Channel, in <-chan *ssh.Request) { - for req := range in { - executeServerCommand(ch, req) - } - }(ch, requests) - }(chanReq) - } - sshConn.Close() - }() - } - }() - return soc.Addr().String(), nil -} - -// This executes the commands requested to be run on the server. -// Used to test the SSH secret backend. -func executeServerCommand(ch ssh.Channel, req *ssh.Request) { - command := string(req.Payload[4:]) - cmd := exec.Command("/bin/bash", []string{"-c", command}...) - req.Reply(true, nil) - - cmd.Stdout = ch - cmd.Stderr = ch - cmd.Stdin = ch - - err := cmd.Start() - if err != nil { - panic(fmt.Sprintf("Error starting the command: '%s'", err)) - } - - go func() { - _, err := cmd.Process.Wait() - if err != nil { - panic(fmt.Sprintf("Error while waiting for command to finish:'%s'", err)) - } - ch.Close() - }() -} - -// This adds a credential backend for the test core. This needs to be -// invoked before the test core is created. -func AddTestCredentialBackend(name string, factory logical.Factory) error { - if name == "" { - return fmt.Errorf("missing backend name") - } - if factory == nil { - return fmt.Errorf("missing backend factory function") - } - testCredentialBackends[name] = factory - return nil -} - -// This adds a logical backend for the test core. This needs to be -// invoked before the test core is created. -func AddTestLogicalBackend(name string, factory logical.Factory) error { - if name == "" { - return fmt.Errorf("missing backend name") - } - if factory == nil { - return fmt.Errorf("missing backend factory function") - } - testLogicalBackends[name] = factory - return nil -} - -type noopAudit struct { - Config *audit.BackendConfig - salt *salt.Salt - saltMutex sync.RWMutex -} - -func (n *noopAudit) GetHash(ctx context.Context, data string) (string, error) { - salt, err := n.Salt(ctx) - if err != nil { - return "", err - } - return salt.GetIdentifiedHMAC(data), nil -} - -func (n *noopAudit) LogRequest(_ context.Context, _ *audit.LogInput) error { - return nil -} - -func (n *noopAudit) LogResponse(_ context.Context, _ *audit.LogInput) error { - return nil -} - -func (n *noopAudit) Reload(_ context.Context) error { - return nil -} - -func (n *noopAudit) Invalidate(_ context.Context) { - n.saltMutex.Lock() - defer n.saltMutex.Unlock() - n.salt = nil -} - -func (n *noopAudit) Salt(ctx context.Context) (*salt.Salt, error) { - n.saltMutex.RLock() - if n.salt != nil { - defer n.saltMutex.RUnlock() - return n.salt, nil - } - n.saltMutex.RUnlock() - n.saltMutex.Lock() - defer n.saltMutex.Unlock() - if n.salt != nil { - return n.salt, nil - } - salt, err := salt.NewSalt(ctx, n.Config.SaltView, n.Config.SaltConfig) - if err != nil { - return nil, err - } - n.salt = salt - return salt, nil -} - -type rawHTTP struct{} - -func (n *rawHTTP) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) { - return &logical.Response{ - Data: map[string]interface{}{ - logical.HTTPStatusCode: 200, - logical.HTTPContentType: "plain/text", - logical.HTTPRawBody: []byte("hello world"), - }, - }, nil -} - -func (n *rawHTTP) HandleExistenceCheck(ctx context.Context, req *logical.Request) (bool, bool, error) { - return false, false, nil -} - -func (n *rawHTTP) SpecialPaths() *logical.Paths { - return &logical.Paths{Unauthenticated: []string{"*"}} -} - -func (n *rawHTTP) System() logical.SystemView { - return logical.StaticSystemView{ - DefaultLeaseTTLVal: time.Hour * 24, - MaxLeaseTTLVal: time.Hour * 24 * 32, - } -} - -func (n *rawHTTP) Logger() log.Logger { - return logging.NewVaultLogger(log.Trace) -} - -func (n *rawHTTP) Cleanup(ctx context.Context) { - // noop -} - -func (n *rawHTTP) Initialize(ctx context.Context) error { - // noop - return nil -} - -func (n *rawHTTP) InvalidateKey(context.Context, string) { - // noop -} - -func (n *rawHTTP) Setup(ctx context.Context, config *logical.BackendConfig) error { - // noop - return nil -} - -func (n *rawHTTP) Type() logical.BackendType { - return logical.TypeUnknown -} - -func GenerateRandBytes(length int) ([]byte, error) { - if length < 0 { - return nil, fmt.Errorf("length must be >= 0") - } - - buf := make([]byte, length) - if length == 0 { - return buf, nil - } - - n, err := rand.Read(buf) - if err != nil { - return nil, err - } - if n != length { - return nil, fmt.Errorf("unable to read %d bytes; only read %d", length, n) - } - - return buf, nil -} - -func TestWaitActive(t testing.T, core *Core) { - t.Helper() - if err := TestWaitActiveWithError(core); err != nil { - t.Fatal(err) - } -} - -func TestWaitActiveWithError(core *Core) error { - start := time.Now() - var standby bool - var err error - for time.Now().Sub(start) < time.Second { - standby, err = core.Standby() - if err != nil { - return err - } - if !standby { - break - } - } - if standby { - return errors.New("should not be in standby mode") - } - return nil -} - -type TestCluster struct { - BarrierKeys [][]byte - RecoveryKeys [][]byte - CACert *x509.Certificate - CACertBytes []byte - CACertPEM []byte - CACertPEMFile string - CAKey *ecdsa.PrivateKey - CAKeyPEM []byte - Cores []*TestClusterCore - ID string - RootToken string - RootCAs *x509.CertPool - TempDir string -} - -func (c *TestCluster) Start() { - for _, core := range c.Cores { - if core.Server != nil { - for _, ln := range core.Listeners { - go core.Server.Serve(ln) - } - } - } -} - -// UnsealCores uses the cluster barrier keys to unseal the test cluster cores -func (c *TestCluster) UnsealCores(t testing.T) { - if err := c.UnsealCoresWithError(); err != nil { - t.Fatal(err) - } -} - -func (c *TestCluster) UnsealCoresWithError() error { - numCores := len(c.Cores) - - // Unseal first core - for _, key := range c.BarrierKeys { - if _, err := c.Cores[0].Unseal(TestKeyCopy(key)); err != nil { - return fmt.Errorf("unseal err: %s", err) - } - } - - // Verify unsealed - if c.Cores[0].Sealed() { - return fmt.Errorf("should not be sealed") - } - - if err := TestWaitActiveWithError(c.Cores[0].Core); err != nil { - return err - } - - // Unseal other cores - for i := 1; i < numCores; i++ { - for _, key := range c.BarrierKeys { - if _, err := c.Cores[i].Core.Unseal(TestKeyCopy(key)); err != nil { - return fmt.Errorf("unseal err: %s", err) - } - } - } - - // Let them come fully up to standby - time.Sleep(2 * time.Second) - - // Ensure cluster connection info is populated. - // Other cores should not come up as leaders. - for i := 1; i < numCores; i++ { - isLeader, _, _, err := c.Cores[i].Leader() - if err != nil { - return err - } - if isLeader { - return fmt.Errorf("core[%d] should not be leader", i) - } - } - - return nil -} - -func (c *TestCluster) EnsureCoresSealed(t testing.T) { - t.Helper() - if err := c.ensureCoresSealed(); err != nil { - t.Fatal(err) - } -} - -func (c *TestCluster) Cleanup() { - // Close listeners - for _, core := range c.Cores { - if core.Listeners != nil { - for _, ln := range core.Listeners { - ln.Close() - } - } - } - - // Seal the cores - c.ensureCoresSealed() - - // Remove any temp dir that exists - if c.TempDir != "" { - os.RemoveAll(c.TempDir) - } - - // Give time to actually shut down/clean up before the next test - time.Sleep(time.Second) -} - -func (c *TestCluster) ensureCoresSealed() error { - for _, core := range c.Cores { - if err := core.Shutdown(); err != nil { - return err - } - timeout := time.Now().Add(60 * time.Second) - for { - if time.Now().After(timeout) { - return fmt.Errorf("timeout waiting for core to seal") - } - if core.Sealed() { - break - } - time.Sleep(250 * time.Millisecond) - } - } - return nil -} - -// UnsealWithStoredKeys uses stored keys to unseal the test cluster cores -func (c *TestCluster) UnsealWithStoredKeys(t testing.T) error { - for _, core := range c.Cores { - if err := core.UnsealWithStoredKeys(context.Background()); err != nil { - return err - } - timeout := time.Now().Add(60 * time.Second) - for { - if time.Now().After(timeout) { - return fmt.Errorf("timeout waiting for core to unseal") - } - if !core.Sealed() { - break - } - time.Sleep(250 * time.Millisecond) - } - } - return nil -} - -type TestListener struct { - net.Listener - Address *net.TCPAddr -} - -type TestClusterCore struct { - *Core - Client *api.Client - Handler http.Handler - Listeners []*TestListener - ReloadFuncs *map[string][]reload.ReloadFunc - ReloadFuncsLock *sync.RWMutex - Server *http.Server - ServerCert *x509.Certificate - ServerCertBytes []byte - ServerCertPEM []byte - ServerKey *ecdsa.PrivateKey - ServerKeyPEM []byte - TLSConfig *tls.Config - UnderlyingStorage physical.Backend -} - -type TestClusterOptions struct { - KeepStandbysSealed bool - SkipInit bool - HandlerFunc func(*HandlerProperties) http.Handler - BaseListenAddress string - NumCores int - SealFunc func() Seal - Logger log.Logger - TempDir string - CACert []byte - CAKey *ecdsa.PrivateKey -} - -var DefaultNumCores = 3 - -type certInfo struct { - cert *x509.Certificate - certPEM []byte - certBytes []byte - key *ecdsa.PrivateKey - keyPEM []byte -} - -// NewTestCluster creates a new test cluster based on the provided core config -// and test cluster options. -// -// N.B. Even though a single base CoreConfig is provided, NewTestCluster will instantiate a -// core config for each core it creates. If separate seal per core is desired, opts.SealFunc -// can be provided to generate a seal for each one. Otherwise, the provided base.Seal will be -// shared among cores. NewCore's default behavior is to generate a new DefaultSeal if the -// provided Seal in coreConfig (i.e. base.Seal) is nil. -func NewTestCluster(t testing.T, base *CoreConfig, opts *TestClusterOptions) *TestCluster { - var err error - - var numCores int - if opts == nil || opts.NumCores == 0 { - numCores = DefaultNumCores - } else { - numCores = opts.NumCores - } - - certIPs := []net.IP{ - net.IPv6loopback, - net.ParseIP("127.0.0.1"), - } - var baseAddr *net.TCPAddr - if opts != nil && opts.BaseListenAddress != "" { - baseAddr, err = net.ResolveTCPAddr("tcp", opts.BaseListenAddress) - if err != nil { - t.Fatal("could not parse given base IP") - } - certIPs = append(certIPs, baseAddr.IP) - } - - var testCluster TestCluster - if opts != nil && opts.TempDir != "" { - if _, err := os.Stat(opts.TempDir); os.IsNotExist(err) { - if err := os.MkdirAll(opts.TempDir, 0700); err != nil { - t.Fatal(err) - } - } - testCluster.TempDir = opts.TempDir - } else { - tempDir, err := ioutil.TempDir("", "vault-test-cluster-") - if err != nil { - t.Fatal(err) - } - testCluster.TempDir = tempDir - } - - var caKey *ecdsa.PrivateKey - if opts != nil && opts.CAKey != nil { - caKey = opts.CAKey - } else { - caKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - } - testCluster.CAKey = caKey - var caBytes []byte - if opts != nil && len(opts.CACert) > 0 { - caBytes = opts.CACert - } else { - caCertTemplate := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: "localhost", - }, - DNSNames: []string{"localhost"}, - IPAddresses: certIPs, - KeyUsage: x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign), - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - BasicConstraintsValid: true, - IsCA: true, - } - caBytes, err = x509.CreateCertificate(rand.Reader, caCertTemplate, caCertTemplate, caKey.Public(), caKey) - if err != nil { - t.Fatal(err) - } - } - caCert, err := x509.ParseCertificate(caBytes) - if err != nil { - t.Fatal(err) - } - testCluster.CACert = caCert - testCluster.CACertBytes = caBytes - testCluster.RootCAs = x509.NewCertPool() - testCluster.RootCAs.AddCert(caCert) - caCertPEMBlock := &pem.Block{ - Type: "CERTIFICATE", - Bytes: caBytes, - } - testCluster.CACertPEM = pem.EncodeToMemory(caCertPEMBlock) - testCluster.CACertPEMFile = filepath.Join(testCluster.TempDir, "ca_cert.pem") - err = ioutil.WriteFile(testCluster.CACertPEMFile, testCluster.CACertPEM, 0755) - if err != nil { - t.Fatal(err) - } - marshaledCAKey, err := x509.MarshalECPrivateKey(caKey) - if err != nil { - t.Fatal(err) - } - caKeyPEMBlock := &pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: marshaledCAKey, - } - testCluster.CAKeyPEM = pem.EncodeToMemory(caKeyPEMBlock) - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "ca_key.pem"), testCluster.CAKeyPEM, 0755) - if err != nil { - t.Fatal(err) - } - - var certInfoSlice []*certInfo - - // - // Certs generation - // - for i := 0; i < numCores; i++ { - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatal(err) - } - certTemplate := &x509.Certificate{ - Subject: pkix.Name{ - CommonName: "localhost", - }, - DNSNames: []string{"localhost"}, - IPAddresses: certIPs, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageServerAuth, - x509.ExtKeyUsageClientAuth, - }, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement, - SerialNumber: big.NewInt(mathrand.Int63()), - NotBefore: time.Now().Add(-30 * time.Second), - NotAfter: time.Now().Add(262980 * time.Hour), - } - certBytes, err := x509.CreateCertificate(rand.Reader, certTemplate, caCert, key.Public(), caKey) - if err != nil { - t.Fatal(err) - } - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - t.Fatal(err) - } - certPEMBlock := &pem.Block{ - Type: "CERTIFICATE", - Bytes: certBytes, - } - certPEM := pem.EncodeToMemory(certPEMBlock) - marshaledKey, err := x509.MarshalECPrivateKey(key) - if err != nil { - t.Fatal(err) - } - keyPEMBlock := &pem.Block{ - Type: "EC PRIVATE KEY", - Bytes: marshaledKey, - } - keyPEM := pem.EncodeToMemory(keyPEMBlock) - - certInfoSlice = append(certInfoSlice, &certInfo{ - cert: cert, - certPEM: certPEM, - certBytes: certBytes, - key: key, - keyPEM: keyPEM, - }) - } - - // - // Listener setup - // - logger := logging.NewVaultLogger(log.Trace) - ports := make([]int, numCores) - if baseAddr != nil { - for i := 0; i < numCores; i++ { - ports[i] = baseAddr.Port + i - } - } else { - baseAddr = &net.TCPAddr{ - IP: net.ParseIP("127.0.0.1"), - Port: 0, - } - } - - listeners := [][]*TestListener{} - servers := []*http.Server{} - handlers := []http.Handler{} - tlsConfigs := []*tls.Config{} - certGetters := []*reload.CertificateGetter{} - for i := 0; i < numCores; i++ { - baseAddr.Port = ports[i] - ln, err := net.ListenTCP("tcp", baseAddr) - if err != nil { - t.Fatal(err) - } - certFile := filepath.Join(testCluster.TempDir, fmt.Sprintf("node%d_port_%d_cert.pem", i+1, ln.Addr().(*net.TCPAddr).Port)) - keyFile := filepath.Join(testCluster.TempDir, fmt.Sprintf("node%d_port_%d_key.pem", i+1, ln.Addr().(*net.TCPAddr).Port)) - err = ioutil.WriteFile(certFile, certInfoSlice[i].certPEM, 0755) - if err != nil { - t.Fatal(err) - } - err = ioutil.WriteFile(keyFile, certInfoSlice[i].keyPEM, 0755) - if err != nil { - t.Fatal(err) - } - tlsCert, err := tls.X509KeyPair(certInfoSlice[i].certPEM, certInfoSlice[i].keyPEM) - if err != nil { - t.Fatal(err) - } - certGetter := reload.NewCertificateGetter(certFile, keyFile, "") - certGetters = append(certGetters, certGetter) - tlsConfig := &tls.Config{ - Certificates: []tls.Certificate{tlsCert}, - RootCAs: testCluster.RootCAs, - ClientCAs: testCluster.RootCAs, - ClientAuth: tls.RequestClientCert, - NextProtos: []string{"h2", "http/1.1"}, - GetCertificate: certGetter.GetCertificate, - } - tlsConfig.BuildNameToCertificate() - tlsConfigs = append(tlsConfigs, tlsConfig) - lns := []*TestListener{&TestListener{ - Listener: tls.NewListener(ln, tlsConfig), - Address: ln.Addr().(*net.TCPAddr), - }, - } - listeners = append(listeners, lns) - var handler http.Handler = http.NewServeMux() - handlers = append(handlers, handler) - server := &http.Server{ - Handler: handler, - ErrorLog: logger.StandardLogger(nil), - } - servers = append(servers, server) - } - - // Create three cores with the same physical and different redirect/cluster - // addrs. - // N.B.: On OSX, instead of random ports, it assigns new ports to new - // listeners sequentially. Aside from being a bad idea in a security sense, - // it also broke tests that assumed it was OK to just use the port above - // the redirect addr. This has now been changed to 105 ports above, but if - // we ever do more than three nodes in a cluster it may need to be bumped. - // Note: it's 105 so that we don't conflict with a running Consul by - // default. - coreConfig := &CoreConfig{ - LogicalBackends: make(map[string]logical.Factory), - CredentialBackends: make(map[string]logical.Factory), - AuditBackends: make(map[string]audit.Factory), - RedirectAddr: fmt.Sprintf("https://127.0.0.1:%d", listeners[0][0].Address.Port), - ClusterAddr: fmt.Sprintf("https://127.0.0.1:%d", listeners[0][0].Address.Port+105), - DisableMlock: true, - EnableUI: true, - EnableRaw: true, - } - - if base != nil { - coreConfig.DisableCache = base.DisableCache - coreConfig.EnableUI = base.EnableUI - coreConfig.DefaultLeaseTTL = base.DefaultLeaseTTL - coreConfig.MaxLeaseTTL = base.MaxLeaseTTL - coreConfig.CacheSize = base.CacheSize - coreConfig.PluginDirectory = base.PluginDirectory - coreConfig.Seal = base.Seal - coreConfig.DevToken = base.DevToken - coreConfig.EnableRaw = base.EnableRaw - - if !coreConfig.DisableMlock { - base.DisableMlock = false - } - - if base.Physical != nil { - coreConfig.Physical = base.Physical - } - - if base.HAPhysical != nil { - coreConfig.HAPhysical = base.HAPhysical - } - - // Used to set something non-working to test fallback - switch base.ClusterAddr { - case "empty": - coreConfig.ClusterAddr = "" - case "": - default: - coreConfig.ClusterAddr = base.ClusterAddr - } - - if base.LogicalBackends != nil { - for k, v := range base.LogicalBackends { - coreConfig.LogicalBackends[k] = v - } - } - if base.CredentialBackends != nil { - for k, v := range base.CredentialBackends { - coreConfig.CredentialBackends[k] = v - } - } - if base.AuditBackends != nil { - for k, v := range base.AuditBackends { - coreConfig.AuditBackends[k] = v - } - } - if base.Logger != nil { - coreConfig.Logger = base.Logger - } - - coreConfig.ClusterCipherSuites = base.ClusterCipherSuites - - coreConfig.DisableCache = base.DisableCache - - coreConfig.DevToken = base.DevToken - } - - if coreConfig.Physical == nil { - coreConfig.Physical, err = physInmem.NewInmem(nil, logger) - if err != nil { - t.Fatal(err) - } - } - if coreConfig.HAPhysical == nil { - haPhys, err := physInmem.NewInmemHA(nil, logger) - if err != nil { - t.Fatal(err) - } - coreConfig.HAPhysical = haPhys.(physical.HABackend) - } - - cores := []*Core{} - for i := 0; i < numCores; i++ { - coreConfig.RedirectAddr = fmt.Sprintf("https://127.0.0.1:%d", listeners[i][0].Address.Port) - if coreConfig.ClusterAddr != "" { - coreConfig.ClusterAddr = fmt.Sprintf("https://127.0.0.1:%d", listeners[i][0].Address.Port+105) - } - - // if opts.SealFunc is provided, use that to generate a seal for the config instead - if opts != nil && opts.SealFunc != nil { - coreConfig.Seal = opts.SealFunc() - } - - if opts != nil && opts.Logger != nil { - coreConfig.Logger = opts.Logger.Named(fmt.Sprintf("core%d", i)) - } - - c, err := NewCore(coreConfig) - if err != nil { - t.Fatalf("err: %v", err) - } - cores = append(cores, c) - if opts != nil && opts.HandlerFunc != nil { - handlers[i] = opts.HandlerFunc(&HandlerProperties{ - Core: c, - MaxRequestDuration: DefaultMaxRequestDuration, - }) - servers[i].Handler = handlers[i] - } - } - - // - // Clustering setup - // - clusterAddrGen := func(lns []*TestListener) []*net.TCPAddr { - ret := make([]*net.TCPAddr, len(lns)) - for i, ln := range lns { - ret[i] = &net.TCPAddr{ - IP: ln.Address.IP, - Port: ln.Address.Port + 105, - } - } - return ret - } - - if numCores > 1 { - for i := 1; i < numCores; i++ { - cores[i].SetClusterListenerAddrs(clusterAddrGen(listeners[i])) - cores[i].SetClusterHandler(handlers[i]) - } - } - - if opts == nil || !opts.SkipInit { - bKeys, rKeys, root := TestCoreInitClusterWrapperSetup(t, cores[0], clusterAddrGen(listeners[0]), handlers[0]) - barrierKeys, _ := copystructure.Copy(bKeys) - testCluster.BarrierKeys = barrierKeys.([][]byte) - recoveryKeys, _ := copystructure.Copy(rKeys) - testCluster.RecoveryKeys = recoveryKeys.([][]byte) - testCluster.RootToken = root - - // Write root token and barrier keys - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "root_token"), []byte(root), 0755) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - for i, key := range testCluster.BarrierKeys { - buf.Write([]byte(base64.StdEncoding.EncodeToString(key))) - if i < len(testCluster.BarrierKeys)-1 { - buf.WriteRune('\n') - } - } - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "barrier_keys"), buf.Bytes(), 0755) - if err != nil { - t.Fatal(err) - } - for i, key := range testCluster.RecoveryKeys { - buf.Write([]byte(base64.StdEncoding.EncodeToString(key))) - if i < len(testCluster.RecoveryKeys)-1 { - buf.WriteRune('\n') - } - } - err = ioutil.WriteFile(filepath.Join(testCluster.TempDir, "recovery_keys"), buf.Bytes(), 0755) - if err != nil { - t.Fatal(err) - } - - // Unseal first core - for _, key := range bKeys { - if _, err := cores[0].Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - ctx := context.Background() - - // If stored keys is supported, the above will no no-op, so trigger auto-unseal - // using stored keys to try to unseal - if err := cores[0].UnsealWithStoredKeys(ctx); err != nil { - t.Fatal(err) - } - - // Verify unsealed - if cores[0].Sealed() { - t.Fatal("should not be sealed") - } - - TestWaitActive(t, cores[0]) - - // Unseal other cores unless otherwise specified - if (opts == nil || !opts.KeepStandbysSealed) && numCores > 1 { - for i := 1; i < numCores; i++ { - for _, key := range bKeys { - if _, err := cores[i].Unseal(TestKeyCopy(key)); err != nil { - t.Fatalf("unseal err: %s", err) - } - } - - // If stored keys is supported, the above will no no-op, so trigger auto-unseal - // using stored keys - if err := cores[i].UnsealWithStoredKeys(ctx); err != nil { - t.Fatal(err) - } - } - - // Let them come fully up to standby - time.Sleep(2 * time.Second) - - // Ensure cluster connection info is populated. - // Other cores should not come up as leaders. - for i := 1; i < numCores; i++ { - isLeader, _, _, err := cores[i].Leader() - if err != nil { - t.Fatal(err) - } - if isLeader { - t.Fatalf("core[%d] should not be leader", i) - } - } - } - - // - // Set test cluster core(s) and test cluster - // - cluster, err := cores[0].Cluster(context.Background()) - if err != nil { - t.Fatal(err) - } - testCluster.ID = cluster.ID - } - - getAPIClient := func(port int, tlsConfig *tls.Config) *api.Client { - transport := cleanhttp.DefaultPooledTransport() - transport.TLSClientConfig = tlsConfig.Clone() - if err := http2.ConfigureTransport(transport); err != nil { - t.Fatal(err) - } - client := &http.Client{ - Transport: transport, - CheckRedirect: func(*http.Request, []*http.Request) error { - // This can of course be overridden per-test by using its own client - return fmt.Errorf("redirects not allowed in these tests") - }, - } - config := api.DefaultConfig() - if config.Error != nil { - t.Fatal(config.Error) - } - config.Address = fmt.Sprintf("https://127.0.0.1:%d", port) - config.HttpClient = client - config.MaxRetries = 0 - apiClient, err := api.NewClient(config) - if err != nil { - t.Fatal(err) - } - if opts == nil || !opts.SkipInit { - apiClient.SetToken(testCluster.RootToken) - } - return apiClient - } - - var ret []*TestClusterCore - for i := 0; i < numCores; i++ { - tcc := &TestClusterCore{ - Core: cores[i], - ServerKey: certInfoSlice[i].key, - ServerKeyPEM: certInfoSlice[i].keyPEM, - ServerCert: certInfoSlice[i].cert, - ServerCertBytes: certInfoSlice[i].certBytes, - ServerCertPEM: certInfoSlice[i].certPEM, - Listeners: listeners[i], - Handler: handlers[i], - Server: servers[i], - TLSConfig: tlsConfigs[i], - Client: getAPIClient(listeners[i][0].Address.Port, tlsConfigs[i]), - } - tcc.ReloadFuncs = &cores[i].reloadFuncs - tcc.ReloadFuncsLock = &cores[i].reloadFuncsLock - tcc.ReloadFuncsLock.Lock() - (*tcc.ReloadFuncs)["listener|tcp"] = []reload.ReloadFunc{certGetters[i].Reload} - tcc.ReloadFuncsLock.Unlock() - ret = append(ret, tcc) - } - - testCluster.Cores = ret - return &testCluster -} diff --git a/vendor/github.com/hashicorp/vault/vault/token_store.go b/vendor/github.com/hashicorp/vault/vault/token_store.go deleted file mode 100644 index 77f1ce14c..000000000 --- a/vendor/github.com/hashicorp/vault/vault/token_store.go +++ /dev/null @@ -1,2626 +0,0 @@ -package vault - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "sync" - "sync/atomic" - - "regexp" - "strings" - "time" - - "github.com/hashicorp/errwrap" - log "github.com/hashicorp/go-hclog" - sockaddr "github.com/hashicorp/go-sockaddr" - - "github.com/armon/go-metrics" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-uuid" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/identity" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/helper/locksutil" - "github.com/hashicorp/vault/helper/parseutil" - "github.com/hashicorp/vault/helper/policyutil" - "github.com/hashicorp/vault/helper/salt" - "github.com/hashicorp/vault/helper/strutil" - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/logical/framework" - "github.com/mitchellh/mapstructure" -) - -const ( - // lookupPrefix is the prefix used to store tokens for their - // primary ID based index - lookupPrefix = "id/" - - // accessorPrefix is the prefix used to store the index from - // Accessor to Token ID - accessorPrefix = "accessor/" - - // parentPrefix is the prefix used to store tokens for their - // secondar parent based index - parentPrefix = "parent/" - - // tokenSubPath is the sub-path used for the token store - // view. This is nested under the system view. - tokenSubPath = "token/" - - // rolesPrefix is the prefix used to store role information - rolesPrefix = "roles/" - - // tokenRevocationPending indicates that the token should not be used - // again. If this is encountered during an existing request flow, it means - // that the token is but is currently fulfilling its final use; after this - // request it will not be able to be looked up as being valid. - tokenRevocationPending = -1 -) - -var ( - // displayNameSanitize is used to sanitize a display name given to a token. - displayNameSanitize = regexp.MustCompile("[^a-zA-Z0-9-]") - - // pathSuffixSanitize is used to ensure a path suffix in a role is valid. - pathSuffixSanitize = regexp.MustCompile("\\w[\\w-.]+\\w") - - destroyCubbyhole = func(ctx context.Context, ts *TokenStore, saltedID string) error { - if ts.cubbyholeBackend == nil { - // Should only ever happen in testing - return nil - } - return ts.cubbyholeBackend.revoke(ctx, salt.SaltID(ts.cubbyholeBackend.saltUUID, saltedID, salt.SHA1Hash)) - } -) - -// LookupToken returns the properties of the token from the token store. This -// is particularly useful to fetch the accessor of the client token and get it -// populated in the logical request along with the client token. The accessor -// of the client token can get audit logged. -func (c *Core) LookupToken(token string) (*logical.TokenEntry, error) { - if token == "" { - return nil, fmt.Errorf("missing client token") - } - - if c.Sealed() { - return nil, consts.ErrSealed - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - - if c.standby { - return nil, consts.ErrStandby - } - - // Many tests don't have a token store running - if c.tokenStore == nil { - return nil, nil - } - - return c.tokenStore.Lookup(c.activeContext, token) -} - -// TokenStore is used to manage client tokens. Tokens are used for -// clients to authenticate, and each token is mapped to an applicable -// set of policy which is used for authorization. -type TokenStore struct { - *framework.Backend - - view *BarrierView - - expiration *ExpirationManager - - cubbyholeBackend *CubbyholeBackend - - policyLookupFunc func(string) (*Policy, error) - - tokenLocks []*locksutil.LockEntry - - // tokenPendingDeletion stores tokens that are being revoked. If the token is - // not in the map, it means that there's no deletion in progress. If the value - // is true it means deletion is in progress, and if false it means deletion - // failed. Revocation needs to handle these states accordingly. - tokensPendingDeletion *sync.Map - - cubbyholeDestroyer func(context.Context, *TokenStore, string) error - - logger log.Logger - - saltLock sync.RWMutex - salt *salt.Salt - - tidyLock *uint32 - - core *Core - - identityPoliciesDeriverFunc func(string) (*identity.Entity, []string, error) - - quitContext context.Context -} - -// NewTokenStore is used to construct a token store that is -// backed by the given barrier view. -func NewTokenStore(ctx context.Context, logger log.Logger, c *Core, config *logical.BackendConfig) (*TokenStore, error) { - // Create a sub-view - view := c.systemBarrierView.SubView(tokenSubPath) - - // Initialize the store - t := &TokenStore{ - view: view, - cubbyholeDestroyer: destroyCubbyhole, - logger: logger, - tokenLocks: locksutil.CreateLocks(), - tokensPendingDeletion: &sync.Map{}, - saltLock: sync.RWMutex{}, - core: c, - identityPoliciesDeriverFunc: c.fetchEntityAndDerivedPolicies, - tidyLock: new(uint32), - quitContext: c.activeContext, - } - - if c.policyStore != nil { - t.policyLookupFunc = func(name string) (*Policy, error) { - return c.policyStore.GetPolicy(ctx, name, PolicyTypeToken) - } - } - - // Setup the framework endpoints - t.Backend = &framework.Backend{ - AuthRenew: t.authRenew, - - PathsSpecial: &logical.Paths{ - Root: []string{ - "revoke-orphan/*", - "accessors*", - }, - - // Most token store items are local since tokens are local, but a - // notable exception is roles - LocalStorage: []string{ - lookupPrefix, - accessorPrefix, - parentPrefix, - salt.DefaultLocation, - }, - }, - - Paths: []*framework.Path{ - &framework.Path{ - Pattern: "roles/?$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: t.tokenStoreRoleList, - }, - - HelpSynopsis: tokenListRolesHelp, - HelpDescription: tokenListRolesHelp, - }, - - &framework.Path{ - Pattern: "accessors/$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ListOperation: t.tokenStoreAccessorList, - }, - - HelpSynopsis: tokenListAccessorsHelp, - HelpDescription: tokenListAccessorsHelp, - }, - - &framework.Path{ - Pattern: "roles/" + framework.GenericNameRegex("role_name"), - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - - "allowed_policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: tokenAllowedPoliciesHelp, - }, - - "disallowed_policies": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: tokenDisallowedPoliciesHelp, - }, - - "orphan": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: false, - Description: tokenOrphanHelp, - }, - - "period": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: tokenPeriodHelp, - }, - - "path_suffix": &framework.FieldSchema{ - Type: framework.TypeString, - Default: "", - Description: tokenPathSuffixHelp + pathSuffixSanitize.String(), - }, - - "explicit_max_ttl": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: tokenExplicitMaxTTLHelp, - }, - - "renewable": &framework.FieldSchema{ - Type: framework.TypeBool, - Default: true, - Description: tokenRenewableHelp, - }, - - "bound_cidrs": &framework.FieldSchema{ - Type: framework.TypeCommaStringSlice, - Description: `Comma separated string or JSON list of CIDR blocks. If set, specifies the blocks of IP addresses which are allowed to use the generated token.`, - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: t.tokenStoreRoleRead, - logical.CreateOperation: t.tokenStoreRoleCreateUpdate, - logical.UpdateOperation: t.tokenStoreRoleCreateUpdate, - logical.DeleteOperation: t.tokenStoreRoleDelete, - }, - - ExistenceCheck: t.tokenStoreRoleExistenceCheck, - - HelpSynopsis: tokenPathRolesHelp, - HelpDescription: tokenPathRolesHelp, - }, - - &framework.Path{ - Pattern: "create-orphan$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleCreateOrphan, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateOrphanHelp), - HelpDescription: strings.TrimSpace(tokenCreateOrphanHelp), - }, - - &framework.Path{ - Pattern: "create/" + framework.GenericNameRegex("role_name"), - - Fields: map[string]*framework.FieldSchema{ - "role_name": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Name of the role", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleCreateAgainstRole, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateRoleHelp), - HelpDescription: strings.TrimSpace(tokenCreateRoleHelp), - }, - - &framework.Path{ - Pattern: "create$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleCreate, - }, - - HelpSynopsis: strings.TrimSpace(tokenCreateHelp), - HelpDescription: strings.TrimSpace(tokenCreateHelp), - }, - - &framework.Path{ - Pattern: "lookup" + framework.OptionalParamRegex("urltoken"), - - Fields: map[string]*framework.FieldSchema{ - "urltoken": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Token to lookup (URL parameter). Do not use this; use the POST version instead with the token in the body.", - }, - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to lookup (POST request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.ReadOperation: t.handleLookup, - logical.UpdateOperation: t.handleLookup, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupHelp), - HelpDescription: strings.TrimSpace(tokenLookupHelp), - }, - - &framework.Path{ - Pattern: "lookup-accessor" + framework.OptionalParamRegex("urlaccessor"), - - Fields: map[string]*framework.FieldSchema{ - "urlaccessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Accessor of the token to lookup (URL parameter). Do not use this; use the POST version instead with the accessor in the body.", - }, - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token to look up (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleUpdateLookupAccessor, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupAccessorHelp), - HelpDescription: strings.TrimSpace(tokenLookupAccessorHelp), - }, - - &framework.Path{ - Pattern: "lookup-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to look up (unused, does not need to be set)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleLookupSelf, - logical.ReadOperation: t.handleLookupSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenLookupHelp), - HelpDescription: strings.TrimSpace(tokenLookupHelp), - }, - - &framework.Path{ - Pattern: "revoke-accessor" + framework.OptionalParamRegex("urlaccessor"), - - Fields: map[string]*framework.FieldSchema{ - "urlaccessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Accessor of the token to revoke (URL parameter). Do not use this; use the POST version instead with the accessor in the body.", - }, - "accessor": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Accessor of the token (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleUpdateRevokeAccessor, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeAccessorHelp), - HelpDescription: strings.TrimSpace(tokenRevokeAccessorHelp), - }, - - &framework.Path{ - Pattern: "revoke-self$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleRevokeSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeSelfHelp), - HelpDescription: strings.TrimSpace(tokenRevokeSelfHelp), - }, - - &framework.Path{ - Pattern: "revoke" + framework.OptionalParamRegex("urltoken"), - - Fields: map[string]*framework.FieldSchema{ - "urltoken": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Token to revoke (URL parameter). Do not use this; use the POST version instead with the token in the body.", - }, - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to revoke (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleRevokeTree, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeHelp), - HelpDescription: strings.TrimSpace(tokenRevokeHelp), - }, - - &framework.Path{ - Pattern: "revoke-orphan" + framework.OptionalParamRegex("urltoken"), - - Fields: map[string]*framework.FieldSchema{ - "urltoken": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Token to revoke (URL parameter). Do not use this; use the POST version instead with the token in the body.", - }, - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to revoke (request body)", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleRevokeOrphan, - }, - - HelpSynopsis: strings.TrimSpace(tokenRevokeOrphanHelp), - HelpDescription: strings.TrimSpace(tokenRevokeOrphanHelp), - }, - - &framework.Path{ - Pattern: "renew-self$", - - Fields: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to renew (unused, does not need to be set)", - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The desired increment in seconds to the token expiration", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleRenewSelf, - }, - - HelpSynopsis: strings.TrimSpace(tokenRenewSelfHelp), - HelpDescription: strings.TrimSpace(tokenRenewSelfHelp), - }, - - &framework.Path{ - Pattern: "renew" + framework.OptionalParamRegex("urltoken"), - - Fields: map[string]*framework.FieldSchema{ - "urltoken": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "DEPRECATED: Token to renew (URL parameter). Do not use this; use the POST version instead with the token in the body.", - }, - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to renew (request body)", - }, - "increment": &framework.FieldSchema{ - Type: framework.TypeDurationSecond, - Default: 0, - Description: "The desired increment in seconds to the token expiration", - }, - }, - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleRenew, - }, - - HelpSynopsis: strings.TrimSpace(tokenRenewHelp), - HelpDescription: strings.TrimSpace(tokenRenewHelp), - }, - - &framework.Path{ - Pattern: "tidy$", - - Callbacks: map[logical.Operation]framework.OperationFunc{ - logical.UpdateOperation: t.handleTidy, - }, - - HelpSynopsis: strings.TrimSpace(tokenTidyHelp), - HelpDescription: strings.TrimSpace(tokenTidyDesc), - }, - }, - } - - t.Backend.Setup(ctx, config) - - return t, nil -} - -func (ts *TokenStore) Invalidate(ctx context.Context, key string) { - //ts.logger.Debug("invalidating key", "key", key) - - switch key { - case tokenSubPath + salt.DefaultLocation: - ts.saltLock.Lock() - ts.salt = nil - ts.saltLock.Unlock() - } -} - -func (ts *TokenStore) Salt(ctx context.Context) (*salt.Salt, error) { - ts.saltLock.RLock() - if ts.salt != nil { - defer ts.saltLock.RUnlock() - return ts.salt, nil - } - ts.saltLock.RUnlock() - ts.saltLock.Lock() - defer ts.saltLock.Unlock() - if ts.salt != nil { - return ts.salt, nil - } - salt, err := salt.NewSalt(ctx, ts.view, &salt.Config{ - HashFunc: salt.SHA1Hash, - Location: salt.DefaultLocation, - }) - if err != nil { - return nil, err - } - ts.salt = salt - return salt, nil -} - -// tsRoleEntry contains token store role information -type tsRoleEntry struct { - // The name of the role. Embedded so it can be used for pathing - Name string `json:"name" mapstructure:"name" structs:"name"` - - // The policies that creation functions using this role can assign to a token, - // escaping or further locking down normal subset checking - AllowedPolicies []string `json:"allowed_policies" mapstructure:"allowed_policies" structs:"allowed_policies"` - - // List of policies to be not allowed during token creation using this role - DisallowedPolicies []string `json:"disallowed_policies" mapstructure:"disallowed_policies" structs:"disallowed_policies"` - - // If true, tokens created using this role will be orphans - Orphan bool `json:"orphan" mapstructure:"orphan" structs:"orphan"` - - // If non-zero, tokens created using this role will be able to be renewed - // forever, but will have a fixed renewal period of this value - Period time.Duration `json:"period" mapstructure:"period" structs:"period"` - - // If set, a suffix will be set on the token path, making it easier to - // revoke using 'revoke-prefix' - PathSuffix string `json:"path_suffix" mapstructure:"path_suffix" structs:"path_suffix"` - - // If set, controls whether created tokens are marked as being renewable - Renewable bool `json:"renewable" mapstructure:"renewable" structs:"renewable"` - - // If set, the token entry will have an explicit maximum TTL set, rather - // than deferring to role/mount values - ExplicitMaxTTL time.Duration `json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl"` - - // The set of CIDRs that tokens generated using this role will be bound to - BoundCIDRs []*sockaddr.SockAddrMarshaler `json:"bound_cidrs"` -} - -type accessorEntry struct { - TokenID string `json:"token_id"` - AccessorID string `json:"accessor_id"` -} - -// SetExpirationManager is used to provide the token store with -// an expiration manager. This is used to manage prefix based revocation -// of tokens and to tidy entries when removed from the token store. -func (ts *TokenStore) SetExpirationManager(exp *ExpirationManager) { - ts.expiration = exp -} - -// SaltID is used to apply a salt and hash to an ID to make sure its not reversible -func (ts *TokenStore) SaltID(ctx context.Context, id string) (string, error) { - s, err := ts.Salt(ctx) - if err != nil { - return "", err - } - - return s.SaltID(id), nil -} - -// RootToken is used to generate a new token with root privileges and no parent -func (ts *TokenStore) rootToken(ctx context.Context) (*logical.TokenEntry, error) { - te := &logical.TokenEntry{ - Policies: []string{"root"}, - Path: "auth/token/root", - DisplayName: "root", - CreationTime: time.Now().Unix(), - } - if err := ts.create(ctx, te); err != nil { - return nil, err - } - return te, nil -} - -func (ts *TokenStore) tokenStoreAccessorList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := ts.view.List(ctx, accessorPrefix) - if err != nil { - return nil, err - } - - resp := &logical.Response{} - - ret := make([]string, 0, len(entries)) - for _, entry := range entries { - aEntry, err := ts.lookupBySaltedAccessor(ctx, entry, false) - if err != nil { - resp.AddWarning("Found an accessor entry that could not be successfully decoded") - continue - } - if aEntry.TokenID == "" { - resp.AddWarning(fmt.Sprintf("Found an accessor entry missing a token: %v", aEntry.AccessorID)) - } else { - ret = append(ret, aEntry.AccessorID) - } - } - - resp.Data = map[string]interface{}{ - "keys": ret, - } - return resp, nil -} - -// createAccessor is used to create an identifier for the token ID. -// A storage index, mapping the accessor to the token ID is also created. -func (ts *TokenStore) createAccessor(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "createAccessor"}, time.Now()) - - // Create a random accessor - accessorUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.Accessor = accessorUUID - - // Create index entry, mapping the accessor to the token ID - saltID, err := ts.SaltID(ctx, entry.Accessor) - if err != nil { - return err - } - - path := accessorPrefix + saltID - aEntry := &accessorEntry{ - TokenID: entry.ID, - AccessorID: entry.Accessor, - } - aEntryBytes, err := jsonutil.EncodeJSON(aEntry) - if err != nil { - return errwrap.Wrapf("failed to marshal accessor index entry: {{err}}", err) - } - - le := &logical.StorageEntry{Key: path, Value: aEntryBytes} - if err := ts.view.Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist accessor index entry: {{err}}", err) - } - return nil -} - -// Create is used to create a new token entry. The entry is assigned -// a newly generated ID if not provided. -func (ts *TokenStore) create(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "create"}, time.Now()) - // Generate an ID if necessary - if entry.ID == "" { - entryUUID, err := uuid.GenerateUUID() - if err != nil { - return err - } - entry.ID = entryUUID - } - - saltedID, err := ts.SaltID(ctx, entry.ID) - if err != nil { - return err - } - exist, _ := ts.lookupSalted(ctx, saltedID, true) - if exist != nil { - return fmt.Errorf("cannot create a token with a duplicate ID") - } - - entry.Policies = policyutil.SanitizePolicies(entry.Policies, policyutil.DoNotAddDefaultPolicy) - - err = ts.createAccessor(ctx, entry) - if err != nil { - return err - } - - return ts.storeCommon(ctx, entry, true) -} - -// Store is used to store an updated token entry without writing the -// secondary index. -func (ts *TokenStore) store(ctx context.Context, entry *logical.TokenEntry) error { - defer metrics.MeasureSince([]string{"token", "store"}, time.Now()) - return ts.storeCommon(ctx, entry, false) -} - -// storeCommon handles the actual storage of an entry, possibly generating -// secondary indexes -func (ts *TokenStore) storeCommon(ctx context.Context, entry *logical.TokenEntry, writeSecondary bool) error { - saltedID, err := ts.SaltID(ctx, entry.ID) - if err != nil { - return err - } - - // Marshal the entry - enc, err := json.Marshal(entry) - if err != nil { - return errwrap.Wrapf("failed to encode entry: {{err}}", err) - } - - if writeSecondary { - // Write the secondary index if necessary. This is done before the - // primary index because we'd rather have a dangling pointer with - // a missing primary instead of missing the parent index and potentially - // escaping the revocation chain. - if entry.Parent != "" { - // Ensure the parent exists - parent, err := ts.Lookup(ctx, entry.Parent) - if err != nil { - return errwrap.Wrapf("failed to lookup parent: {{err}}", err) - } - if parent == nil { - return fmt.Errorf("parent token not found") - } - - // Create the index entry - parentSaltedID, err := ts.SaltID(ctx, entry.Parent) - if err != nil { - return err - } - path := parentPrefix + parentSaltedID + "/" + saltedID - le := &logical.StorageEntry{Key: path} - if err := ts.view.Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) - } - } - } - - // Write the primary ID - path := lookupPrefix + saltedID - le := &logical.StorageEntry{Key: path, Value: enc} - if len(entry.Policies) == 1 && entry.Policies[0] == "root" { - le.SealWrap = true - } - if err := ts.view.Put(ctx, le); err != nil { - return errwrap.Wrapf("failed to persist entry: {{err}}", err) - } - return nil -} - -// UseToken is used to manage restricted use tokens and decrement their -// available uses. Returns two values: a potentially updated entry or, if the -// token has been revoked, nil; and whether an error was encountered. The -// locking here isn't perfect, as other parts of the code may update an entry, -// but usually none after the entry is already created...so this is pretty -// good. -func (ts *TokenStore) UseToken(ctx context.Context, te *logical.TokenEntry) (*logical.TokenEntry, error) { - if te == nil { - return nil, fmt.Errorf("invalid token entry provided for use count decrementing") - } - - // This case won't be hit with a token with restricted uses because we go - // from 1 to -1. So it's a nice optimization to check this without a read - // lock. - if te.NumUses == 0 { - return te, nil - } - - // If we are attempting to unwrap a control group request, don't use the token. - // It will be manually revoked by the handler. - if len(te.Policies) == 1 && te.Policies[0] == controlGroupPolicyName { - return te, nil - } - - lock := locksutil.LockForKey(ts.tokenLocks, te.ID) - lock.Lock() - defer lock.Unlock() - - // Call lookupSalted instead of Lookup to avoid deadlocking since Lookup grabs a read lock - saltedID, err := ts.SaltID(ctx, te.ID) - if err != nil { - return nil, err - } - - te, err = ts.lookupSalted(ctx, saltedID, false) - if err != nil { - return nil, errwrap.Wrapf("failed to refresh entry: {{err}}", err) - } - // If it can't be found we shouldn't be trying to use it, so if we get nil - // back, it is because it has been revoked in the interim or will be - // revoked (NumUses is -1) - if te == nil { - return nil, fmt.Errorf("token not found or fully used already") - } - - // Decrement the count. If this is our last use count, we need to indicate - // that this is no longer valid, but revocation is deferred to the end of - // the call, so this will make sure that any Lookup that happens doesn't - // return an entry. This essentially acts as a write-ahead lock and is - // especially useful since revocation can end up (via the expiration - // manager revoking children) attempting to acquire the same lock - // repeatedly. - if te.NumUses == 1 { - te.NumUses = tokenRevocationPending - } else { - te.NumUses-- - } - - err = ts.store(ctx, te) - if err != nil { - return nil, err - } - - return te, nil -} - -func (ts *TokenStore) UseTokenByID(ctx context.Context, id string) (*logical.TokenEntry, error) { - te, err := ts.Lookup(ctx, id) - if err != nil { - return te, err - } - - return ts.UseToken(ctx, te) -} - -// Lookup is used to find a token given its ID. It acquires a read lock, then calls lookupSalted. -func (ts *TokenStore) Lookup(ctx context.Context, id string) (*logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"token", "lookup"}, time.Now()) - if id == "" { - return nil, fmt.Errorf("cannot lookup blank token") - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return nil, err - } - return ts.lookupSalted(ctx, saltedID, false) -} - -// lookupTainted is used to find a token that may or maynot be tainted given its -// ID. It acquires a read lock, then calls lookupSalted. -func (ts *TokenStore) lookupTainted(ctx context.Context, id string) (*logical.TokenEntry, error) { - defer metrics.MeasureSince([]string{"token", "lookup"}, time.Now()) - if id == "" { - return nil, fmt.Errorf("cannot lookup blank token") - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return nil, err - } - return ts.lookupSalted(ctx, saltedID, true) -} - -// lookupSalted is used to find a token given its salted ID. If tainted is -// true, entries that are in some revocation state (currently, indicated by num -// uses < 0), the entry will be returned anyways -func (ts *TokenStore) lookupSalted(ctx context.Context, saltedID string, tainted bool) (*logical.TokenEntry, error) { - // Lookup token - path := lookupPrefix + saltedID - raw, err := ts.view.Get(ctx, path) - if err != nil { - return nil, errwrap.Wrapf("failed to read entry: {{err}}", err) - } - - // Bail if not found - if raw == nil { - return nil, nil - } - - // Unmarshal the token - entry := new(logical.TokenEntry) - if err := jsonutil.DecodeJSON(raw.Value, entry); err != nil { - return nil, errwrap.Wrapf("failed to decode entry: {{err}}", err) - } - - // This is a token that is awaiting deferred revocation or tainted - if entry.NumUses < 0 && !tainted { - return nil, nil - } - - persistNeeded := false - - // Upgrade the deprecated fields - if entry.DisplayNameDeprecated != "" { - if entry.DisplayName == "" { - entry.DisplayName = entry.DisplayNameDeprecated - } - entry.DisplayNameDeprecated = "" - persistNeeded = true - } - - if entry.CreationTimeDeprecated != 0 { - if entry.CreationTime == 0 { - entry.CreationTime = entry.CreationTimeDeprecated - } - entry.CreationTimeDeprecated = 0 - persistNeeded = true - } - - if entry.ExplicitMaxTTLDeprecated != 0 { - if entry.ExplicitMaxTTL == 0 { - entry.ExplicitMaxTTL = entry.ExplicitMaxTTLDeprecated - } - entry.ExplicitMaxTTLDeprecated = 0 - persistNeeded = true - } - - if entry.NumUsesDeprecated != 0 { - if entry.NumUses == 0 || entry.NumUsesDeprecated < entry.NumUses { - entry.NumUses = entry.NumUsesDeprecated - } - entry.NumUsesDeprecated = 0 - persistNeeded = true - } - - // It's a root token with unlimited creation TTL (so never had an - // expiration); this may or may not have a lease (based on when it was - // generated, for later revocation purposes) but it doesn't matter, it's - // allowed. Fast-path this. - if len(entry.Policies) == 1 && entry.Policies[0] == "root" && entry.TTL == 0 { - // If fields are getting upgraded, store the changes - if persistNeeded { - if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) - } - } - return entry, nil - } - - // Perform these checks on upgraded fields, but before persisting - - // If we are still restoring the expiration manager, we want to ensure the - // token is not expired - if ts.expiration == nil { - return nil, errors.New("expiration manager is nil on tokenstore") - } - le, err := ts.expiration.FetchLeaseTimesByToken(ctx, entry.Path, entry.ID) - if err != nil { - return nil, errwrap.Wrapf("failed to fetch lease times: {{err}}", err) - } - - var ret *logical.TokenEntry - - switch { - // It's any kind of expiring token with no lease, immediately delete it - case le == nil: - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(ctx, entry) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(ts.quitContext, leaseID) - if err != nil { - return nil, err - } - - // Only return if we're not past lease expiration (or if tainted is true), - // otherwise assume expmgr is working on revocation - default: - if !le.ExpireTime.Before(time.Now()) || tainted { - ret = entry - } - } - - // If fields are getting upgraded, store the changes - if persistNeeded { - if err := ts.store(ctx, entry); err != nil { - return nil, errwrap.Wrapf("failed to persist token upgrade: {{err}}", err) - } - } - - return ret, nil -} - -// Revoke is used to invalidate a given token, any child tokens -// will be orphaned. -func (ts *TokenStore) revokeOrphan(ctx context.Context, id string) error { - defer metrics.MeasureSince([]string{"token", "revoke"}, time.Now()) - if id == "" { - return fmt.Errorf("cannot revoke blank token") - } - - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return err - } - return ts.revokeSalted(ctx, saltedID, false) -} - -// revokeSalted is used to invalidate a given salted token, any child tokens -// will be orphaned unless otherwise specified. skipOrphan should be used -// whenever we are revoking the entire tree starting from a particular parent -// (e.g. revokeTreeSalted). -func (ts *TokenStore) revokeSalted(ctx context.Context, saltedID string, skipOrphan bool) (ret error) { - // Check and set the token deletion state. We only proceed with the deletion - // if we don't have a pending deletion (empty), or if the deletion previously - // failed (state is false) - state, loaded := ts.tokensPendingDeletion.LoadOrStore(saltedID, true) - - // If the entry was loaded and its state is true, we short-circuit - if loaded && state == true { - return nil - } - - // The map check above should protect use from any concurrent revocations, so - // doing a bare lookup here should be fine. - entry, err := ts.lookupSalted(ctx, saltedID, true) - if err != nil { - return err - } - if entry == nil { - return nil - } - - if entry.NumUses != tokenRevocationPending { - entry.NumUses = tokenRevocationPending - if err := ts.store(ctx, entry); err != nil { - // The only real reason for this is an underlying storage error - // which also means that nothing else in this func or expmgr will - // really work either. So we clear revocation state so the user can - // try again. - ts.logger.Error("failed to mark token as revoked") - ts.tokensPendingDeletion.Store(saltedID, false) - return err - } - } - - defer func() { - // If we succeeded in all other revocation operations after this defer and - // before we return, we can remove the token store entry - if ret == nil { - path := lookupPrefix + saltedID - if err := ts.view.Delete(ctx, path); err != nil { - ret = errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - // Check on ret again and update the sync.Map accordingly - if ret != nil { - // If we failed on any of the calls within, we store the state as false - // so that the next call to revokeSalted will retry - ts.tokensPendingDeletion.Store(saltedID, false) - } else { - ts.tokensPendingDeletion.Delete(saltedID) - } - }() - - // Destroy the token's cubby. This should go first as it's a - // security-sensitive item. - err = ts.cubbyholeDestroyer(ctx, ts, saltedID) - if err != nil { - return err - } - - // Revoke all secrets under this token. This should go first as it's a - // security-sensitive item. - if err := ts.expiration.RevokeByToken(ts.quitContext, entry); err != nil { - return err - } - - // Clear the secondary index if any - if entry.Parent != "" { - parentSaltedID, err := ts.SaltID(ctx, entry.Parent) - if err != nil { - return err - } - - path := parentPrefix + parentSaltedID + "/" + saltedID - if err = ts.view.Delete(ctx, path); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - // Clear the accessor index if any - if entry.Accessor != "" { - accessorSaltedID, err := ts.SaltID(ctx, entry.Accessor) - if err != nil { - return err - } - - path := accessorPrefix + accessorSaltedID - if err = ts.view.Delete(ctx, path); err != nil { - return errwrap.Wrapf("failed to delete entry: {{err}}", err) - } - } - - if !skipOrphan { - // Mark all children token as orphan by removing - // their parent index, and clear the parent entry. - // - // Marking the token as orphan should be skipped if it's called by - // revokeTreeSalted to avoid unnecessary view.List operations. Since - // the deletion occurs in a DFS fashion we don't need to perform a delete - // on child prefixes as there will be none (as saltedID entry is a leaf node). - parentPath := parentPrefix + saltedID + "/" - children, err := ts.view.List(ctx, parentPath) - if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) - } - for _, child := range children { - entry, err := ts.lookupSalted(ctx, child, true) - if err != nil { - return errwrap.Wrapf("failed to get child token: {{err}}", err) - } - lock := locksutil.LockForKey(ts.tokenLocks, entry.ID) - lock.Lock() - - entry.Parent = "" - err = ts.store(ctx, entry) - if err != nil { - lock.Unlock() - return errwrap.Wrapf("failed to update child token: {{err}}", err) - } - lock.Unlock() - - // Delete the the child storage entry after we update the token entry Since - // paths are not deeply nested (i.e. they are simply - // parenPrefix//), we can simply call view.Delete instead - // of logical.ClearView - index := parentPath + child - err = ts.view.Delete(ctx, index) - if err != nil { - return errwrap.Wrapf("failed to delete child entry: {{err}}", err) - } - } - } - - return nil -} - -// revokeTree is used to invalidate a given token and all -// child tokens. -func (ts *TokenStore) revokeTree(ctx context.Context, id string) error { - defer metrics.MeasureSince([]string{"token", "revoke-tree"}, time.Now()) - // Verify the token is not blank - if id == "" { - return fmt.Errorf("cannot tree-revoke blank token") - } - - // Get the salted ID - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return err - } - - // Nuke the entire tree recursively - return ts.revokeTreeSalted(ctx, saltedID) -} - -// revokeTreeSalted is used to invalidate a given token and all -// child tokens using a saltedID. -// Updated to be non-recursive and revoke child tokens -// before parent tokens(DFS). -func (ts *TokenStore) revokeTreeSalted(ctx context.Context, saltedID string) error { - var dfs []string - dfs = append(dfs, saltedID) - - for l := len(dfs); l > 0; l = len(dfs) { - id := dfs[0] - path := parentPrefix + id + "/" - children, err := ts.view.List(ctx, path) - if err != nil { - return errwrap.Wrapf("failed to scan for children: {{err}}", err) - } - // If the length of the children array is zero, - // then we are at a leaf node. - if len(children) == 0 { - // Whenever revokeSalted is called, the token will be removed immediately and - // any underlying secrets will be handed off to the expiration manager which will - // take care of expiring them. If Vault is restarted, any revoked tokens - // would have been deleted, and any pending leases for deletion will be restored - // by the expiration manager. - if err := ts.revokeSalted(ctx, id, true); err != nil { - - return errwrap.Wrapf("failed to revoke entry: {{err}}", err) - } - // If the length of l is equal to 1, then the last token has been deleted - if l == 1 { - return nil - } - dfs = dfs[1:] - } else { - // If we make it here, there are children and they must - // be prepended. - dfs = append(children, dfs...) - } - } - - return nil -} - -// handleCreateAgainstRole handles the auth/token/create path for a role -func (ts *TokenStore) handleCreateAgainstRole(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - name := d.Get("role_name").(string) - roleEntry, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return nil, err - } - if roleEntry == nil { - return logical.ErrorResponse(fmt.Sprintf("unknown role %s", name)), nil - } - - return ts.handleCreateCommon(ctx, req, d, false, roleEntry) -} - -func (ts *TokenStore) lookupByAccessor(ctx context.Context, accessor string, tainted bool) (accessorEntry, error) { - saltedID, err := ts.SaltID(ctx, accessor) - if err != nil { - return accessorEntry{}, err - } - return ts.lookupBySaltedAccessor(ctx, saltedID, tainted) -} - -func (ts *TokenStore) lookupBySaltedAccessor(ctx context.Context, saltedAccessor string, tainted bool) (accessorEntry, error) { - entry, err := ts.view.Get(ctx, accessorPrefix+saltedAccessor) - var aEntry accessorEntry - - if err != nil { - return aEntry, errwrap.Wrapf("failed to read index using accessor: {{err}}", err) - } - if entry == nil { - return aEntry, &logical.StatusBadRequest{Err: "invalid accessor"} - } - - err = jsonutil.DecodeJSON(entry.Value, &aEntry) - // If we hit an error, assume it's a pre-struct straight token ID - if err != nil { - saltedID, err := ts.SaltID(ctx, string(entry.Value)) - if err != nil { - return accessorEntry{}, err - } - - te, err := ts.lookupSalted(ctx, saltedID, tainted) - if err != nil { - return accessorEntry{}, errwrap.Wrapf("failed to look up token using accessor index: {{err}}", err) - } - // It's hard to reason about what to do here -- it may be that the - // token was revoked async, or that it's an old accessor index entry - // that was somehow not cleared up, or or or. A nonexistent token entry - // on lookup is nil, not an error, so we keep that behavior here to be - // safe...the token ID is simply not filled in. - if te != nil { - aEntry.TokenID = te.ID - aEntry.AccessorID = te.Accessor - } - } - - return aEntry, nil -} - -// handleTidy handles the cleaning up of leaked accessor storage entries and -// cleaning up of leases that are associated to tokens that are expired. -func (ts *TokenStore) handleTidy(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - if !atomic.CompareAndSwapUint32(ts.tidyLock, 0, 1) { - resp := &logical.Response{} - resp.AddWarning("Tidy operation already in progress.") - return resp, nil - } - - go func() { - defer atomic.StoreUint32(ts.tidyLock, 0) - - // Don't cancel when the original client request goes away - ctx = ts.quitContext - - logger := ts.logger.Named("tidy") - ts.core.AddLogger(logger) - - var tidyErrors *multierror.Error - - doTidy := func() error { - - ts.logger.Info("beginning tidy operation on tokens") - defer ts.logger.Info("finished tidy operation on tokens") - - // List out all the accessors - saltedAccessorList, err := ts.view.List(ctx, accessorPrefix) - if err != nil { - return errwrap.Wrapf("failed to fetch accessor index entries: {{err}}", err) - } - - // First, clean up secondary index entries that are no longer valid - parentList, err := ts.view.List(ctx, parentPrefix) - if err != nil { - return errwrap.Wrapf("failed to fetch secondary index entries: {{err}}", err) - } - - var countParentEntries, deletedCountParentEntries, countParentList, deletedCountParentList int64 - - // Scan through the secondary index entries; if there is an entry - // with the token's salt ID at the end, remove it - for _, parent := range parentList { - countParentEntries++ - - // Get the children - children, err := ts.view.List(ctx, parentPrefix+parent) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read secondary index: {{err}}", err)) - continue - } - - // First check if the salt ID of the parent exists, and if not mark this so - // that deletion of children later with this loop below applies to all - // children - originalChildrenCount := int64(len(children)) - exists, _ := ts.lookupSalted(ctx, strings.TrimSuffix(parent, "/"), true) - if exists == nil { - ts.logger.Debug("deleting invalid parent prefix entry", "index", parentPrefix+parent) - } - - var deletedChildrenCount int64 - for _, child := range children { - countParentList++ - if countParentList%500 == 0 { - ts.logger.Info("checking validity of tokens in secondary index list", "progress", countParentList) - } - - // Look up tainted entries so we can be sure that if this isn't - // found, it doesn't exist. Doing the following without locking - // since appropriate locks cannot be held with salted token IDs. - // Also perform deletion if the parent doesn't exist any more. - te, _ := ts.lookupSalted(ctx, child, true) - // If the child entry is not nil, but the parent doesn't exist, then turn - // that child token into an orphan token. Theres no deletion in this case. - if te != nil && exists == nil { - lock := locksutil.LockForKey(ts.tokenLocks, te.ID) - lock.Lock() - - te.Parent = "" - err = ts.store(ctx, te) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to convert child token into an orphan token: {{err}}", err)) - } - lock.Unlock() - continue - } - // Otherwise, if the entry doesn't exist, or if the parent doesn't exist go - // on with the delete on the secondary index - if te == nil || exists == nil { - index := parentPrefix + parent + child - ts.logger.Debug("deleting invalid secondary index", "index", index) - err = ts.view.Delete(ctx, index) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete secondary index: {{err}}", err)) - continue - } - deletedChildrenCount++ - } - } - // Add current children deleted count to the total count - deletedCountParentList += deletedChildrenCount - // N.B.: We don't call delete on the parent prefix since physical.Backend.Delete - // implementations should be in charge of deleting empty prefixes. - // If we deleted all the children, then add that to our deleted parent entries count. - if originalChildrenCount == deletedChildrenCount { - deletedCountParentEntries++ - } - } - - var countAccessorList, - deletedCountAccessorEmptyToken, - deletedCountAccessorInvalidToken, - deletedCountInvalidTokenInAccessor int64 - - // For each of the accessor, see if the token ID associated with it is - // a valid one. If not, delete the leases associated with that token - // and delete the accessor as well. - for _, saltedAccessor := range saltedAccessorList { - countAccessorList++ - if countAccessorList%500 == 0 { - ts.logger.Info("checking if accessors contain valid tokens", "progress", countAccessorList) - } - - accessorEntry, err := ts.lookupBySaltedAccessor(ctx, saltedAccessor, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read the accessor index: {{err}}", err)) - continue - } - - // A valid accessor storage entry should always have a token ID - // in it. If not, it is an invalid accessor entry and needs to - // be deleted. - if accessorEntry.TokenID == "" { - index := accessorPrefix + saltedAccessor - // If deletion of accessor fails, move on to the next - // item since this is just a best-effort operation - err = ts.view.Delete(ctx, index) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete the accessor index: {{err}}", err)) - continue - } - deletedCountAccessorEmptyToken++ - } - - lock := locksutil.LockForKey(ts.tokenLocks, accessorEntry.TokenID) - lock.RLock() - - // Look up tainted variants so we only find entries that truly don't - // exist - saltedID, err := ts.SaltID(ctx, accessorEntry.TokenID) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to read salt id: {{err}}", err)) - lock.RUnlock() - continue - } - te, err := ts.lookupSalted(ctx, saltedID, true) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to lookup tainted ID: {{err}}", err)) - lock.RUnlock() - continue - } - - lock.RUnlock() - - // If token entry is not found assume that the token is not valid any - // more and conclude that accessor, leases, and secondary index entries - // for this token should not exist as well. - if te == nil { - ts.logger.Info("deleting token with nil entry", "salted_token", saltedID) - - // RevokeByToken expects a '*logical.TokenEntry'. For the - // purposes of tidying, it is sufficient if the token - // entry only has ID set. - tokenEntry := &logical.TokenEntry{ - ID: accessorEntry.TokenID, - } - - // Attempt to revoke the token. This will also revoke - // the leases associated with the token. - err := ts.expiration.RevokeByToken(ctx, tokenEntry) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to revoke leases of expired token: {{err}}", err)) - continue - } - deletedCountInvalidTokenInAccessor++ - - index := accessorPrefix + saltedAccessor - - // If deletion of accessor fails, move on to the next item since - // this is just a best-effort operation. We do this last so that on - // next run if something above failed we still have the accessor - // entry to try again. - err = ts.view.Delete(ctx, index) - if err != nil { - tidyErrors = multierror.Append(tidyErrors, errwrap.Wrapf("failed to delete accessor entry: {{err}}", err)) - continue - } - deletedCountAccessorInvalidToken++ - } - } - - ts.logger.Info("number of entries scanned in parent prefix", "count", countParentEntries) - ts.logger.Info("number of entries deleted in parent prefix", "count", deletedCountParentEntries) - ts.logger.Info("number of tokens scanned in parent index list", "count", countParentList) - ts.logger.Info("number of tokens revoked in parent index list", "count", deletedCountParentList) - ts.logger.Info("number of accessors scanned", "count", countAccessorList) - ts.logger.Info("number of deleted accessors which had empty tokens", "count", deletedCountAccessorEmptyToken) - ts.logger.Info("number of revoked tokens which were invalid but present in accessors", "count", deletedCountInvalidTokenInAccessor) - ts.logger.Info("number of deleted accessors which had invalid tokens", "count", deletedCountAccessorInvalidToken) - - return tidyErrors.ErrorOrNil() - } - - if err := doTidy(); err != nil { - logger.Error("error running tidy", "error", err) - return - } - }() - - resp := &logical.Response{} - resp.AddWarning("Tidy operation successfully started. Any information from the operation will be printed to Vault's server logs.") - return logical.RespondWithStatusCode(resp, req, http.StatusAccepted) -} - -// handleUpdateLookupAccessor handles the auth/token/lookup-accessor path for returning -// the properties of the token associated with the accessor -func (ts *TokenStore) handleUpdateLookupAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urlaccessor bool - accessor := data.Get("accessor").(string) - if accessor == "" { - accessor = data.Get("urlaccessor").(string) - if accessor == "" { - return nil, &logical.StatusBadRequest{Err: "missing accessor"} - } - urlaccessor = true - } - - aEntry, err := ts.lookupByAccessor(ctx, accessor, false) - if err != nil { - return nil, err - } - - // Prepare the field data required for a lookup call - d := &framework.FieldData{ - Raw: map[string]interface{}{ - "token": aEntry.TokenID, - }, - Schema: map[string]*framework.FieldSchema{ - "token": &framework.FieldSchema{ - Type: framework.TypeString, - Description: "Token to lookup", - }, - }, - } - resp, err := ts.handleLookup(ctx, req, d) - if err != nil { - return nil, err - } - if resp == nil { - return nil, fmt.Errorf("failed to lookup the token") - } - if resp.IsError() { - return resp, nil - - } - - // Remove the token ID from the response - if resp.Data != nil { - resp.Data["id"] = "" - } - - if urlaccessor { - resp.AddWarning(`Using an accessor in the path is unsafe as the accessor can be logged in many places. Please use POST or PUT with the accessor passed in via the "accessor" parameter.`) - } - - return resp, nil -} - -// handleUpdateRevokeAccessor handles the auth/token/revoke-accessor path for revoking -// the token associated with the accessor -func (ts *TokenStore) handleUpdateRevokeAccessor(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urlaccessor bool - accessor := data.Get("accessor").(string) - if accessor == "" { - accessor = data.Get("urlaccessor").(string) - if accessor == "" { - return nil, &logical.StatusBadRequest{Err: "missing accessor"} - } - urlaccessor = true - } - - aEntry, err := ts.lookupByAccessor(ctx, accessor, true) - if err != nil { - return nil, err - } - - te, err := ts.Lookup(ctx, aEntry.TokenID) - if err != nil { - return nil, err - } - - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(ctx, te) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(ts.quitContext, leaseID) - if err != nil { - return nil, err - } - - if urlaccessor { - resp := &logical.Response{} - resp.AddWarning(`Using an accessor in the path is unsafe as the accessor can be logged in many places. Please use POST or PUT with the accessor passed in via the "accessor" parameter.`) - return resp, nil - } - - return nil, nil -} - -// handleCreate handles the auth/token/create path for creation of new orphan -// tokens -func (ts *TokenStore) handleCreateOrphan(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return ts.handleCreateCommon(ctx, req, d, true, nil) -} - -// handleCreate handles the auth/token/create path for creation of new non-orphan -// tokens -func (ts *TokenStore) handleCreate(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - return ts.handleCreateCommon(ctx, req, d, false, nil) -} - -// handleCreateCommon handles the auth/token/create path for creation of new tokens -func (ts *TokenStore) handleCreateCommon(ctx context.Context, req *logical.Request, d *framework.FieldData, orphan bool, role *tsRoleEntry) (*logical.Response, error) { - // Read the parent policy - parent, err := ts.Lookup(ctx, req.ClientToken) - if err != nil { - return nil, errwrap.Wrapf("parent token lookup failed: {{err}}", err) - } - if parent == nil { - return logical.ErrorResponse("parent token lookup failed: no parent found"), logical.ErrInvalidRequest - } - - // A token with a restricted number of uses cannot create a new token - // otherwise it could escape the restriction count. - if parent.NumUses > 0 { - return logical.ErrorResponse("restricted use token cannot generate child tokens"), - logical.ErrInvalidRequest - } - - // Check if the client token has sudo/root privileges for the requested path - isSudo := ts.System().SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken) - - // Read and parse the fields - var data struct { - ID string - Policies []string - Metadata map[string]string `mapstructure:"meta"` - NoParent bool `mapstructure:"no_parent"` - NoDefaultPolicy bool `mapstructure:"no_default_policy"` - Lease string - TTL string - Renewable *bool - ExplicitMaxTTL string `mapstructure:"explicit_max_ttl"` - DisplayName string `mapstructure:"display_name"` - NumUses int `mapstructure:"num_uses"` - Period string - } - if err := mapstructure.WeakDecode(req.Data, &data); err != nil { - return logical.ErrorResponse(fmt.Sprintf( - "Error decoding request: %s", err)), logical.ErrInvalidRequest - } - - // Verify the number of uses is positive - if data.NumUses < 0 { - return logical.ErrorResponse("number of uses cannot be negative"), - logical.ErrInvalidRequest - } - - // Setup the token entry - te := logical.TokenEntry{ - Parent: req.ClientToken, - - // The mount point is always the same since we have only one token - // store; using req.MountPoint causes trouble in tests since they don't - // have an official mount - Path: fmt.Sprintf("auth/token/%s", req.Path), - - Meta: data.Metadata, - DisplayName: "token", - NumUses: data.NumUses, - CreationTime: time.Now().Unix(), - } - - renewable := true - if data.Renewable != nil { - renewable = *data.Renewable - } - - // If the role is not nil, we add the role name as part of the token's - // path. This makes it much easier to later revoke tokens that were issued - // by a role (using revoke-prefix). Users can further specify a PathSuffix - // in the role; that way they can use something like "v1", "v2" to indicate - // role revisions, and revoke only tokens issued with a previous revision. - if role != nil { - te.Role = role.Name - - // If renewable hasn't been disabled in the call and the role has - // renewability disabled, set renewable false - if renewable && !role.Renewable { - renewable = false - } - - if role.PathSuffix != "" { - te.Path = fmt.Sprintf("%s/%s", te.Path, role.PathSuffix) - } - } - - // Attach the given display name if any - if data.DisplayName != "" { - full := "token-" + data.DisplayName - full = displayNameSanitize.ReplaceAllString(full, "-") - full = strings.TrimSuffix(full, "-") - te.DisplayName = full - } - - // Allow specifying the ID of the token if the client has root or sudo privileges - if data.ID != "" { - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to specify token id"), - logical.ErrInvalidRequest - } - te.ID = data.ID - } - - resp := &logical.Response{} - - var addDefault bool - - // N.B.: The logic here uses various calculations as to whether default - // should be added. In the end we decided that if NoDefaultPolicy is set it - // should be stripped out regardless, *but*, the logic of when it should - // and shouldn't be added is kept because we want to do subset comparisons - // based on adding default when it's correct to do so. - switch { - case role != nil && (len(role.AllowedPolicies) > 0 || len(role.DisallowedPolicies) > 0): - // Holds the final set of policies as they get munged - var finalPolicies []string - - // We don't make use of the global one because roles with allowed or - // disallowed set do their own policy rules - var localAddDefault bool - - // If the request doesn't say not to add "default" and if "default" - // isn't in the disallowed list, add it. This is in line with the idea - // that roles, when allowed/disallowed ar set, allow a subset of - // policies to be set disjoint from the parent token's policies. - if !data.NoDefaultPolicy && !strutil.StrListContains(role.DisallowedPolicies, "default") { - localAddDefault = true - } - - // Start with passed-in policies as a baseline, if they exist - if len(data.Policies) > 0 { - finalPolicies = policyutil.SanitizePolicies(data.Policies, localAddDefault) - } - - var sanitizedRolePolicies []string - - // First check allowed policies; if policies are specified they will be - // checked, otherwise if an allowed set exists that will be the set - // that is used - if len(role.AllowedPolicies) > 0 { - // Note that if "default" is already in allowed, and also in - // disallowed, this will still result in an error later since this - // doesn't strip out default - sanitizedRolePolicies = policyutil.SanitizePolicies(role.AllowedPolicies, localAddDefault) - - if len(finalPolicies) == 0 { - finalPolicies = sanitizedRolePolicies - } else { - if !strutil.StrListSubset(sanitizedRolePolicies, finalPolicies) { - return logical.ErrorResponse(fmt.Sprintf("token policies (%q) must be subset of the role's allowed policies (%q)", finalPolicies, sanitizedRolePolicies)), logical.ErrInvalidRequest - } - } - } else { - // Assign parent policies if none have been requested. As this is a - // role, add default unless explicitly disabled. - if len(finalPolicies) == 0 { - finalPolicies = policyutil.SanitizePolicies(parent.Policies, localAddDefault) - } - } - - if len(role.DisallowedPolicies) > 0 { - // We don't add the default here because we only want to disallow it if it's explicitly set - sanitizedRolePolicies = strutil.RemoveDuplicates(role.DisallowedPolicies, true) - - for _, finalPolicy := range finalPolicies { - if strutil.StrListContains(sanitizedRolePolicies, finalPolicy) { - return logical.ErrorResponse(fmt.Sprintf("token policy %q is disallowed by this role", finalPolicy)), logical.ErrInvalidRequest - } - } - } - - data.Policies = finalPolicies - - // No policies specified, inherit parent - case len(data.Policies) == 0: - // Only inherit "default" if the parent already has it, so don't touch addDefault here - data.Policies = policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy) - - // When a role is not in use or does not specify allowed/disallowed, only - // permit policies to be a subset unless the client has root or sudo - // privileges. Default is added in this case if the parent has it, unless - // the client specified for it not to be added. - case !isSudo: - // Sanitize passed-in and parent policies before comparison - sanitizedInputPolicies := policyutil.SanitizePolicies(data.Policies, policyutil.DoNotAddDefaultPolicy) - sanitizedParentPolicies := policyutil.SanitizePolicies(parent.Policies, policyutil.DoNotAddDefaultPolicy) - - if !strutil.StrListSubset(sanitizedParentPolicies, sanitizedInputPolicies) { - return logical.ErrorResponse("child policies must be subset of parent"), logical.ErrInvalidRequest - } - - // If the parent has default, and they haven't requested not to get it, - // add it. Note that if they have explicitly put "default" in - // data.Policies it will still be added because NoDefaultPolicy - // controls *automatic* adding. - if !data.NoDefaultPolicy && strutil.StrListContains(parent.Policies, "default") { - addDefault = true - } - - // Add default by default in this case unless requested not to - case isSudo: - addDefault = !data.NoDefaultPolicy - } - - te.Policies = policyutil.SanitizePolicies(data.Policies, addDefault) - - // Yes, this is a little inefficient to do it like this, but meh - if data.NoDefaultPolicy { - te.Policies = strutil.StrListDelete(te.Policies, "default") - } - - // Prevent internal policies from being assigned to tokens - for _, policy := range te.Policies { - if strutil.StrListContains(nonAssignablePolicies, policy) { - return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil - } - } - - // Prevent attempts to create a root token without an actual root token as parent. - // This is to thwart privilege escalation by tokens having 'sudo' privileges. - if strutil.StrListContains(data.Policies, "root") && !strutil.StrListContains(parent.Policies, "root") { - return logical.ErrorResponse("root tokens may not be created without parent token being root"), logical.ErrInvalidRequest - } - - // - // NOTE: Do not modify policies below this line. We need the checks above - // to be the last checks as they must look at the final policy set. - // - - switch { - case role != nil: - if role.Orphan { - te.Parent = "" - } - - if len(role.BoundCIDRs) > 0 { - te.BoundCIDRs = role.BoundCIDRs - } - - case data.NoParent: - // Only allow an orphan token if the client has sudo policy - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to create orphan token"), - logical.ErrInvalidRequest - } - - te.Parent = "" - - default: - // This comes from create-orphan, which can be properly ACLd - if orphan { - te.Parent = "" - } - } - - // At this point, it is clear whether the token is going to be an orphan or - // not. If the token is not going to be an orphan, inherit the parent's - // entity identifier into the child token. - if te.Parent != "" { - te.EntityID = parent.EntityID - } - - var explicitMaxTTLToUse time.Duration - if data.ExplicitMaxTTL != "" { - dur, err := parseutil.ParseDurationSecond(data.ExplicitMaxTTL) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("explicit_max_ttl must be positive"), logical.ErrInvalidRequest - } - te.ExplicitMaxTTL = dur - explicitMaxTTLToUse = dur - } - - var periodToUse time.Duration - if data.Period != "" { - dur, err := parseutil.ParseDurationSecond(data.Period) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - switch { - case dur < 0: - return logical.ErrorResponse("period must be positive"), logical.ErrInvalidRequest - case dur == 0: - default: - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to create periodic token"), - logical.ErrInvalidRequest - } - te.Period = dur - periodToUse = dur - } - } - - // Parse the TTL/lease if any - if data.TTL != "" { - dur, err := parseutil.ParseDurationSecond(data.TTL) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("ttl must be positive"), logical.ErrInvalidRequest - } - te.TTL = dur - } else if data.Lease != "" { - // This block is compatibility - dur, err := time.ParseDuration(data.Lease) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if dur < 0 { - return logical.ErrorResponse("lease must be positive"), logical.ErrInvalidRequest - } - te.TTL = dur - } - - // Set the lesser period/explicit max TTL if defined both in arguments and in role - if role != nil { - if role.ExplicitMaxTTL != 0 { - switch { - case explicitMaxTTLToUse == 0: - explicitMaxTTLToUse = role.ExplicitMaxTTL - default: - if role.ExplicitMaxTTL < explicitMaxTTLToUse { - explicitMaxTTLToUse = role.ExplicitMaxTTL - } - resp.AddWarning(fmt.Sprintf("Explicit max TTL specified both during creation call and in role; using the lesser value of %d seconds", int64(explicitMaxTTLToUse.Seconds()))) - } - } - if role.Period != 0 { - switch { - case periodToUse == 0: - periodToUse = role.Period - default: - if role.Period < periodToUse { - periodToUse = role.Period - } - resp.AddWarning(fmt.Sprintf("Period specified both during creation call and in role; using the lesser value of %d seconds", int64(periodToUse.Seconds()))) - } - } - } - - sysView := ts.System() - - // Only calculate a TTL if you are A) periodic, B) have a TTL, C) do not have a TTL and are not a root token - if periodToUse > 0 || te.TTL > 0 || (te.TTL == 0 && !strutil.StrListContains(te.Policies, "root")) { - ttl, warnings, err := framework.CalculateTTL(sysView, 0, te.TTL, periodToUse, 0, explicitMaxTTLToUse, time.Unix(te.CreationTime, 0)) - if err != nil { - return nil, err - } - for _, warning := range warnings { - resp.AddWarning(warning) - } - te.TTL = ttl - } - - // Root tokens are still bound by explicit max TTL - if te.TTL == 0 && explicitMaxTTLToUse > 0 { - te.TTL = explicitMaxTTLToUse - } - - // Don't advertise non-expiring root tokens as renewable, as attempts to - // renew them are denied. Don't CIDR-restrict these either. - if te.TTL == 0 { - if parent.TTL != 0 { - return logical.ErrorResponse("expiring root tokens cannot create non-expiring root tokens"), logical.ErrInvalidRequest - } - renewable = false - te.BoundCIDRs = nil - } - - // Create the token - if err := ts.create(ctx, &te); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - // Generate the response - resp.Auth = &logical.Auth{ - NumUses: te.NumUses, - DisplayName: te.DisplayName, - Policies: te.Policies, - Metadata: te.Meta, - LeaseOptions: logical.LeaseOptions{ - TTL: te.TTL, - Renewable: renewable, - }, - ClientToken: te.ID, - Accessor: te.Accessor, - EntityID: te.EntityID, - Period: periodToUse, - ExplicitMaxTTL: explicitMaxTTLToUse, - CreationPath: te.Path, - } - - if ts.policyLookupFunc != nil { - for _, p := range te.Policies { - policy, err := ts.policyLookupFunc(p) - if err != nil { - return logical.ErrorResponse(fmt.Sprintf("could not look up policy %s", p)), nil - } - if policy == nil { - resp.AddWarning(fmt.Sprintf("Policy %q does not exist", p)) - } - } - } - - return resp, nil -} - -// handleRevokeSelf handles the auth/token/revoke-self path for revocation of tokens -// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke -// the token and all children anyways, but that is only available when there is a lease. -func (ts *TokenStore) handleRevokeSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - te, err := ts.Lookup(ctx, req.ClientToken) - if err != nil { - return nil, err - } - - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(ctx, te) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(ts.quitContext, leaseID) - if err != nil { - return nil, err - } - - return nil, nil -} - -// handleRevokeTree handles the auth/token/revoke/id path for revocation of tokens -// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke -// the token and all children anyways, but that is only available when there is a lease. -func (ts *TokenStore) handleRevokeTree(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urltoken bool - id := data.Get("token").(string) - if id == "" { - id = data.Get("urltoken").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - urltoken = true - } - - te, err := ts.Lookup(ctx, id) - if err != nil { - return nil, err - } - - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - leaseID, err := ts.expiration.CreateOrFetchRevocationLeaseByToken(ctx, te) - if err != nil { - return nil, err - } - - err = ts.expiration.Revoke(ts.quitContext, leaseID) - if err != nil { - return nil, err - } - - if urltoken { - resp := &logical.Response{} - resp.AddWarning(`Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter.`) - return resp, nil - } - - return nil, nil -} - -// handleRevokeOrphan handles the auth/token/revoke-orphan/id path for revocation of tokens -// in a way that leaves child tokens orphaned. Normally, using sys/revoke/leaseID will revoke -// the token and all children. -func (ts *TokenStore) handleRevokeOrphan(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urltoken bool - // Parse the id - id := data.Get("token").(string) - if id == "" { - id = data.Get("urltoken").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - urltoken = true - } - - parent, err := ts.Lookup(ctx, req.ClientToken) - if err != nil { - return nil, errwrap.Wrapf("parent token lookup failed: {{err}}", err) - } - if parent == nil { - return logical.ErrorResponse("parent token lookup failed: no parent found"), logical.ErrInvalidRequest - } - - // Check if the client token has sudo/root privileges for the requested path - isSudo := ts.System().SudoPrivilege(ctx, req.MountPoint+req.Path, req.ClientToken) - - if !isSudo { - return logical.ErrorResponse("root or sudo privileges required to revoke and orphan"), - logical.ErrInvalidRequest - } - - // Revoke and orphan - if err := ts.revokeOrphan(ctx, id); err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - if urltoken { - resp := &logical.Response{} - resp.AddWarning(`Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter.`) - return resp, nil - } - - return nil, nil -} - -func (ts *TokenStore) handleLookupSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - data.Raw["token"] = req.ClientToken - return ts.handleLookup(ctx, req, data) -} - -// handleLookup handles the auth/token/lookup/id path for querying information about -// a particular token. This can be used to see which policies are applicable. -func (ts *TokenStore) handleLookup(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urltoken bool - id := data.Get("token").(string) - if id == "" { - id = data.Get("urltoken").(string) - if id != "" { - urltoken = true - } - } - if id == "" { - id = req.ClientToken - } - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - - lock := locksutil.LockForKey(ts.tokenLocks, id) - lock.RLock() - defer lock.RUnlock() - - // Lookup the token - saltedID, err := ts.SaltID(ctx, id) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - out, err := ts.lookupSalted(ctx, saltedID, true) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - - if out == nil { - return logical.ErrorResponse("bad token"), logical.ErrPermissionDenied - } - - // Generate a response. We purposely omit the parent reference otherwise - // you could escalate your privileges. - resp := &logical.Response{ - Data: map[string]interface{}{ - "id": out.ID, - "accessor": out.Accessor, - "policies": out.Policies, - "path": out.Path, - "meta": out.Meta, - "display_name": out.DisplayName, - "num_uses": out.NumUses, - "orphan": false, - "creation_time": int64(out.CreationTime), - "creation_ttl": int64(out.TTL.Seconds()), - "expire_time": nil, - "ttl": int64(0), - "explicit_max_ttl": int64(out.ExplicitMaxTTL.Seconds()), - "entity_id": out.EntityID, - }, - } - - if out.Parent == "" { - resp.Data["orphan"] = true - } - - if out.Role != "" { - resp.Data["role"] = out.Role - } - - if out.Period != 0 { - resp.Data["period"] = int64(out.Period.Seconds()) - } - - if len(out.BoundCIDRs) > 0 { - resp.Data["bound_cidrs"] = out.BoundCIDRs - } - - // Fetch the last renewal time - leaseTimes, err := ts.expiration.FetchLeaseTimesByToken(ctx, out.Path, out.ID) - if err != nil { - return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest - } - if leaseTimes != nil { - if !leaseTimes.LastRenewalTime.IsZero() { - resp.Data["last_renewal_time"] = leaseTimes.LastRenewalTime.Unix() - resp.Data["last_renewal"] = leaseTimes.LastRenewalTime - } - if !leaseTimes.ExpireTime.IsZero() { - resp.Data["expire_time"] = leaseTimes.ExpireTime - resp.Data["ttl"] = leaseTimes.ttl() - } - renewable, _ := leaseTimes.renewable() - resp.Data["renewable"] = renewable - resp.Data["issue_time"] = leaseTimes.IssueTime - } - - if out.EntityID != "" { - _, identityPolicies, err := ts.identityPoliciesDeriverFunc(out.EntityID) - if err != nil { - return nil, err - } - if len(identityPolicies) != 0 { - resp.Data["identity_policies"] = identityPolicies - } - } - - if urltoken { - resp.AddWarning(`Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter.`) - } - - return resp, nil -} - -func (ts *TokenStore) handleRenewSelf(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - data.Raw["token"] = req.ClientToken - return ts.handleRenew(ctx, req, data) -} - -// handleRenew handles the auth/token/renew/id path for renewal of tokens. -// This is used to prevent token expiration and revocation. -func (ts *TokenStore) handleRenew(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - var urltoken bool - id := data.Get("token").(string) - if id == "" { - id = data.Get("urltoken").(string) - if id == "" { - return logical.ErrorResponse("missing token ID"), logical.ErrInvalidRequest - } - urltoken = true - } - incrementRaw := data.Get("increment").(int) - - // Convert the increment - increment := time.Duration(incrementRaw) * time.Second - - // Lookup the token - te, err := ts.Lookup(ctx, id) - if err != nil { - return nil, errwrap.Wrapf("error looking up token: {{err}}", err) - } - - // Verify the token exists - if te == nil { - return logical.ErrorResponse("token not found"), logical.ErrInvalidRequest - } - - // Renew the token and its children - resp, err := ts.expiration.RenewToken(ctx, req, te.Path, te.ID, increment) - - if urltoken { - resp.AddWarning(`Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter.`) - } - - return resp, err -} - -func (ts *TokenStore) destroyCubbyhole(ctx context.Context, saltedID string) error { - if ts.cubbyholeBackend == nil { - // Should only ever happen in testing - return nil - } - return ts.cubbyholeBackend.revoke(ctx, salt.SaltID(ts.cubbyholeBackend.saltUUID, saltedID, salt.SHA1Hash)) -} - -func (ts *TokenStore) authRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - if req.Auth == nil { - return nil, fmt.Errorf("request auth is nil") - } - - te, err := ts.Lookup(ctx, req.Auth.ClientToken) - if err != nil { - return nil, errwrap.Wrapf("error looking up token: {{err}}", err) - } - if te == nil { - return nil, fmt.Errorf("no token entry found during lookup") - } - - if te.Role == "" { - req.Auth.Period = te.Period - req.Auth.ExplicitMaxTTL = te.ExplicitMaxTTL - return &logical.Response{Auth: req.Auth}, nil - } - - role, err := ts.tokenStoreRole(ctx, te.Role) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error looking up role %q: {{err}}", te.Role), err) - } - if role == nil { - return nil, fmt.Errorf("original token role %q could not be found, not renewing", te.Role) - } - - req.Auth.Period = role.Period - req.Auth.ExplicitMaxTTL = role.ExplicitMaxTTL - return &logical.Response{Auth: req.Auth}, nil -} - -func (ts *TokenStore) tokenStoreRole(ctx context.Context, name string) (*tsRoleEntry, error) { - entry, err := ts.view.Get(ctx, fmt.Sprintf("%s%s", rolesPrefix, name)) - if err != nil { - return nil, err - } - if entry == nil { - return nil, nil - } - - var result tsRoleEntry - if err := entry.DecodeJSON(&result); err != nil { - return nil, err - } - - return &result, nil -} - -func (ts *TokenStore) tokenStoreRoleList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { - entries, err := ts.view.List(ctx, rolesPrefix) - if err != nil { - return nil, err - } - - ret := make([]string, len(entries)) - for i, entry := range entries { - ret[i] = strings.TrimPrefix(entry, rolesPrefix) - } - - return logical.ListResponse(ret), nil -} - -func (ts *TokenStore) tokenStoreRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - err := ts.view.Delete(ctx, fmt.Sprintf("%s%s", rolesPrefix, data.Get("role_name").(string))) - if err != nil { - return nil, err - } - - return nil, nil -} - -func (ts *TokenStore) tokenStoreRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - role, err := ts.tokenStoreRole(ctx, data.Get("role_name").(string)) - if err != nil { - return nil, err - } - if role == nil { - return nil, nil - } - - resp := &logical.Response{ - Data: map[string]interface{}{ - "period": int64(role.Period.Seconds()), - "explicit_max_ttl": int64(role.ExplicitMaxTTL.Seconds()), - "disallowed_policies": role.DisallowedPolicies, - "allowed_policies": role.AllowedPolicies, - "name": role.Name, - "orphan": role.Orphan, - "path_suffix": role.PathSuffix, - "renewable": role.Renewable, - }, - } - - if len(role.BoundCIDRs) > 0 { - resp.Data["bound_cidrs"] = role.BoundCIDRs - } - - return resp, nil -} - -func (ts *TokenStore) tokenStoreRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) { - name := data.Get("role_name").(string) - if name == "" { - return false, fmt.Errorf("role name cannot be empty") - } - role, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return false, err - } - - return role != nil, nil -} - -func (ts *TokenStore) tokenStoreRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { - name := data.Get("role_name").(string) - if name == "" { - return logical.ErrorResponse("role name cannot be empty"), nil - } - entry, err := ts.tokenStoreRole(ctx, name) - if err != nil { - return nil, err - } - - // Due to the existence check, entry will only be nil if it's a create - // operation, so just create a new one - if entry == nil { - entry = &tsRoleEntry{ - Name: name, - } - } - - // In this series of blocks, if we do not find a user-provided value and - // it's a creation operation, we call data.Get to get the appropriate - // default - - orphanInt, ok := data.GetOk("orphan") - if ok { - entry.Orphan = orphanInt.(bool) - } else if req.Operation == logical.CreateOperation { - entry.Orphan = data.Get("orphan").(bool) - } - - periodInt, ok := data.GetOk("period") - if ok { - entry.Period = time.Second * time.Duration(periodInt.(int)) - } else if req.Operation == logical.CreateOperation { - entry.Period = time.Second * time.Duration(data.Get("period").(int)) - } - - renewableInt, ok := data.GetOk("renewable") - if ok { - entry.Renewable = renewableInt.(bool) - } else if req.Operation == logical.CreateOperation { - entry.Renewable = data.Get("renewable").(bool) - } - - boundCIDRsRaw, ok := data.GetOk("bound_cidrs") - if ok { - boundCIDRs := boundCIDRsRaw.([]string) - if len(boundCIDRs) > 0 { - var parsedCIDRs []*sockaddr.SockAddrMarshaler - for _, v := range boundCIDRs { - parsedCIDR, err := sockaddr.NewSockAddr(v) - if err != nil { - return logical.ErrorResponse(errwrap.Wrapf(fmt.Sprintf("invalid value %q when parsing bound cidrs: {{err}}", v), err).Error()), nil - } - parsedCIDRs = append(parsedCIDRs, &sockaddr.SockAddrMarshaler{parsedCIDR}) - } - entry.BoundCIDRs = parsedCIDRs - } - } - - var resp *logical.Response - - explicitMaxTTLInt, ok := data.GetOk("explicit_max_ttl") - if ok { - entry.ExplicitMaxTTL = time.Second * time.Duration(explicitMaxTTLInt.(int)) - } else if req.Operation == logical.CreateOperation { - entry.ExplicitMaxTTL = time.Second * time.Duration(data.Get("explicit_max_ttl").(int)) - } - if entry.ExplicitMaxTTL != 0 { - sysView := ts.System() - - if sysView.MaxLeaseTTL() != time.Duration(0) && entry.ExplicitMaxTTL > sysView.MaxLeaseTTL() { - if resp == nil { - resp = &logical.Response{} - } - resp.AddWarning(fmt.Sprintf( - "Given explicit max TTL of %d is greater than system/mount allowed value of %d seconds; until this is fixed attempting to create tokens against this role will result in an error", - int64(entry.ExplicitMaxTTL.Seconds()), int64(sysView.MaxLeaseTTL().Seconds()))) - } - } - - pathSuffixInt, ok := data.GetOk("path_suffix") - if ok { - pathSuffix := pathSuffixInt.(string) - if pathSuffix != "" { - matched := pathSuffixSanitize.MatchString(pathSuffix) - if !matched { - return logical.ErrorResponse(fmt.Sprintf( - "given role path suffix contains invalid characters; must match %s", - pathSuffixSanitize.String())), nil - } - entry.PathSuffix = pathSuffix - } - } else if req.Operation == logical.CreateOperation { - entry.PathSuffix = data.Get("path_suffix").(string) - } - - if strings.Contains(entry.PathSuffix, "..") { - return logical.ErrorResponse(fmt.Sprintf("error registering path suffix: %s", consts.ErrPathContainsParentReferences)), nil - } - - allowedPoliciesRaw, ok := data.GetOk("allowed_policies") - if ok { - entry.AllowedPolicies = policyutil.SanitizePolicies(allowedPoliciesRaw.([]string), policyutil.DoNotAddDefaultPolicy) - } else if req.Operation == logical.CreateOperation { - entry.AllowedPolicies = policyutil.SanitizePolicies(data.Get("allowed_policies").([]string), policyutil.DoNotAddDefaultPolicy) - } - - disallowedPoliciesRaw, ok := data.GetOk("disallowed_policies") - if ok { - entry.DisallowedPolicies = strutil.RemoveDuplicates(disallowedPoliciesRaw.([]string), true) - } else if req.Operation == logical.CreateOperation { - entry.DisallowedPolicies = strutil.RemoveDuplicates(data.Get("disallowed_policies").([]string), true) - } - - // Store it - jsonEntry, err := logical.StorageEntryJSON(fmt.Sprintf("%s%s", rolesPrefix, name), entry) - if err != nil { - return nil, err - } - if err := ts.view.Put(ctx, jsonEntry); err != nil { - return nil, err - } - - return resp, nil -} - -const ( - tokenTidyHelp = ` -This endpoint performs cleanup tasks that can be run if certain error -conditions have occurred. -` - tokenTidyDesc = ` -This endpoint performs cleanup tasks that can be run to clean up token and -lease entries after certain error conditions. Usually running this is not -necessary, and is only required if upgrade notes or support personnel suggest -it. -` - tokenBackendHelp = `The token credential backend is always enabled and builtin to Vault. -Client tokens are used to identify a client and to allow Vault to associate policies and ACLs -which are enforced on every request. This backend also allows for generating sub-tokens as well -as revocation of tokens. The tokens are renewable if associated with a lease.` - tokenCreateHelp = `The token create path is used to create new tokens.` - tokenCreateOrphanHelp = `The token create path is used to create new orphan tokens.` - tokenCreateRoleHelp = `This token create path is used to create new tokens adhering to the given role.` - tokenListRolesHelp = `This endpoint lists configured roles.` - tokenLookupAccessorHelp = `This endpoint will lookup a token associated with the given accessor and its properties. Response will not contain the token ID.` - tokenLookupHelp = `This endpoint will lookup a token and its properties.` - tokenPathRolesHelp = `This endpoint allows creating, reading, and deleting roles.` - tokenRevokeAccessorHelp = `This endpoint will delete the token associated with the accessor and all of its child tokens.` - tokenRevokeHelp = `This endpoint will delete the given token and all of its child tokens.` - tokenRevokeSelfHelp = `This endpoint will delete the token used to call it and all of its child tokens.` - tokenRevokeOrphanHelp = `This endpoint will delete the token and orphan its child tokens.` - tokenRenewHelp = `This endpoint will renew the given token and prevent expiration.` - tokenRenewSelfHelp = `This endpoint will renew the token used to call it and prevent expiration.` - tokenAllowedPoliciesHelp = `If set, tokens can be created with any subset of the policies in this -list, rather than the normal semantics of tokens being a subset of the -calling token's policies. The parameter is a comma-delimited string of -policy names.` - tokenDisallowedPoliciesHelp = `If set, successful token creation via this role will require that -no policies in the given list are requested. The parameter is a comma-delimited string of policy names.` - tokenOrphanHelp = `If true, tokens created via this role -will be orphan tokens (have no parent)` - tokenPeriodHelp = `If set, tokens created via this role -will have no max lifetime; instead, their -renewal period will be fixed to this value. -This takes an integer number of seconds, -or a string duration (e.g. "24h").` - tokenPathSuffixHelp = `If set, tokens created via this role -will contain the given suffix as a part of -their path. This can be used to assist use -of the 'revoke-prefix' endpoint later on. -The given suffix must match the regular -expression.` - tokenExplicitMaxTTLHelp = `If set, tokens created via this role -carry an explicit maximum TTL. During renewal, -the current maximum TTL values of the role -and the mount are not checked for changes, -and any updates to these values will have -no effect on the token being renewed.` - tokenRenewableHelp = `Tokens created via this role will be -renewable or not according to this value. -Defaults to "true".` - tokenListAccessorsHelp = `List token accessors, which can then be -be used to iterate and discover their properties -or revoke them. Because this can be used to -cause a denial of service, this endpoint -requires 'sudo' capability in addition to -'list'.` -) diff --git a/vendor/github.com/hashicorp/vault/vault/ui.go b/vendor/github.com/hashicorp/vault/vault/ui.go deleted file mode 100644 index 7a637f20a..000000000 --- a/vendor/github.com/hashicorp/vault/vault/ui.go +++ /dev/null @@ -1,217 +0,0 @@ -package vault - -import ( - "bytes" - "context" - "encoding/json" - "net/http" - "strings" - "sync" - - "github.com/hashicorp/vault/logical" - "github.com/hashicorp/vault/physical" -) - -const ( - uiConfigKey = "config" - uiConfigPlaintextKey = "config_plaintext" -) - -// UIConfig contains UI configuration. This takes both a physical view and a barrier view -// because it is stored in both plaintext and encrypted to allow for getting the header -// values before the barrier is unsealed -type UIConfig struct { - l sync.RWMutex - physicalStorage physical.Backend - barrierStorage logical.Storage - - enabled bool - defaultHeaders http.Header -} - -// NewUIConfig creates a new UI config -func NewUIConfig(enabled bool, physicalStorage physical.Backend, barrierStorage logical.Storage) *UIConfig { - defaultHeaders := http.Header{} - defaultHeaders.Set("Content-Security-Policy", "default-src 'none'; connect-src 'self'; img-src 'self' data:; script-src 'self'; style-src 'unsafe-inline' 'self'; form-action 'none'; frame-ancestors 'none'") - - return &UIConfig{ - physicalStorage: physicalStorage, - barrierStorage: barrierStorage, - enabled: enabled, - defaultHeaders: defaultHeaders, - } -} - -// Enabled returns if the UI is enabled -func (c *UIConfig) Enabled() bool { - c.l.RLock() - defer c.l.RUnlock() - return c.enabled -} - -// Headers returns the response headers that should be returned in the UI -func (c *UIConfig) Headers(ctx context.Context) (http.Header, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return nil, err - } - headers := make(http.Header) - if config != nil { - headers = config.Headers - } - - for k := range c.defaultHeaders { - if headers.Get(k) == "" { - v := c.defaultHeaders.Get(k) - headers.Set(k, v) - } - } - return headers, nil -} - -// HeaderKeys returns the list of the configured headers -func (c *UIConfig) HeaderKeys(ctx context.Context) ([]string, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return nil, err - } - if config == nil { - return nil, nil - } - var keys []string - for k := range config.Headers { - keys = append(keys, k) - } - return keys, nil -} - -// GetHeader retrieves the configured value for the given header -func (c *UIConfig) GetHeader(ctx context.Context, header string) (string, error) { - c.l.RLock() - defer c.l.RUnlock() - - config, err := c.get(ctx) - if err != nil { - return "", err - } - if config == nil { - return "", nil - } - - value := config.Headers.Get(header) - return value, nil -} - -// SetHeader sets the value for the given header -func (c *UIConfig) SetHeader(ctx context.Context, header, value string) error { - c.l.Lock() - defer c.l.Unlock() - - config, err := c.get(ctx) - if err != nil { - return err - } - if config == nil { - config = &uiConfigEntry{ - Headers: http.Header{}, - } - } - config.Headers.Set(header, value) - return c.save(ctx, config) -} - -// DeleteHeader deletes the header configuration for the given header -func (c *UIConfig) DeleteHeader(ctx context.Context, header string) error { - c.l.Lock() - defer c.l.Unlock() - - config, err := c.get(ctx) - if err != nil { - return err - } - if config == nil { - return nil - } - - config.Headers.Del(header) - return c.save(ctx, config) -} - -func (c *UIConfig) get(ctx context.Context) (*uiConfigEntry, error) { - // Read plaintext always to ensure in sync with barrier value - plaintextConfigRaw, err := c.physicalStorage.Get(ctx, uiConfigPlaintextKey) - if err != nil { - return nil, err - } - - configRaw, err := c.barrierStorage.Get(ctx, uiConfigKey) - if err == nil { - if configRaw == nil { - return nil, nil - } - config := new(uiConfigEntry) - if err := json.Unmarshal(configRaw.Value, config); err != nil { - return nil, err - } - // Check that plaintext value matches barrier value, if not sync values - if plaintextConfigRaw == nil || bytes.Compare(plaintextConfigRaw.Value, configRaw.Value) != 0 { - if err := c.save(ctx, config); err != nil { - return nil, err - } - } - return config, nil - } - - // Respond with error if not sealed - if !strings.Contains(err.Error(), ErrBarrierSealed.Error()) { - return nil, err - } - - // Respond with plaintext value - if configRaw == nil { - return nil, nil - } - config := new(uiConfigEntry) - if err := json.Unmarshal(plaintextConfigRaw.Value, config); err != nil { - return nil, err - } - return config, nil -} - -func (c *UIConfig) save(ctx context.Context, config *uiConfigEntry) error { - if len(config.Headers) == 0 { - if err := c.physicalStorage.Delete(ctx, uiConfigPlaintextKey); err != nil { - return err - } - return c.barrierStorage.Delete(ctx, uiConfigKey) - } - - configRaw, err := json.Marshal(config) - if err != nil { - return err - } - - entry := &physical.Entry{ - Key: uiConfigPlaintextKey, - Value: configRaw, - } - if err := c.physicalStorage.Put(ctx, entry); err != nil { - return err - } - - barrEntry := &logical.StorageEntry{ - Key: uiConfigKey, - Value: configRaw, - } - return c.barrierStorage.Put(ctx, barrEntry) -} - -type uiConfigEntry struct { - Headers http.Header `json:"headers"` -} diff --git a/vendor/github.com/hashicorp/vault/vault/util.go b/vendor/github.com/hashicorp/vault/vault/util.go deleted file mode 100644 index 9e03afd29..000000000 --- a/vendor/github.com/hashicorp/vault/vault/util.go +++ /dev/null @@ -1,42 +0,0 @@ -package vault - -import ( - "crypto/rand" - "fmt" -) - -// memzero is used to zero out a byte buffer. This specific format is optimized -// by the compiler to use memclr to improve performance. See this code review: -// https://codereview.appspot.com/137880043 -// -// Use of memzero is not a guarantee against memory analysis as described in -// the Vault threat model: -// https://www.vaultproject.io/docs/internals/security.html . Vault does not -// provide guarantees against memory analysis or raw memory dumping by -// operators, however it does minimize this exposure by zeroing out buffers -// that contain secrets as soon as they are no longer used. Starting with Go -// 1.5, the garbage collector was changed to become a "generational copying -// garbage collector." This change to the garbage collector makes it -// impossible for Vault to guarantee a buffer with a secret has not been -// copied during a garbage collection. It is therefore possible that secrets -// may be exist in memory that have not been wiped despite a pending memzero -// call. Over time any copied data with a secret will be reused and the -// memory overwritten thereby mitigating some of the risk from this threat -// vector. -func memzero(b []byte) { - if b == nil { - return - } - for i := range b { - b[i] = 0 - } -} - -// randbytes is used to create a buffer of size n filled with random bytes -func randbytes(n int) []byte { - buf := make([]byte, n) - if _, err := rand.Read(buf); err != nil { - panic(fmt.Sprintf("failed to generate %d random bytes: %v", n, err)) - } - return buf -} diff --git a/vendor/github.com/hashicorp/vault/vault/wrapping.go b/vendor/github.com/hashicorp/vault/vault/wrapping.go deleted file mode 100644 index 177b7bbcc..000000000 --- a/vendor/github.com/hashicorp/vault/vault/wrapping.go +++ /dev/null @@ -1,349 +0,0 @@ -package vault - -import ( - "context" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/SermoDigital/jose/crypto" - "github.com/SermoDigital/jose/jws" - "github.com/SermoDigital/jose/jwt" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/consts" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/hashicorp/vault/logical" -) - -const ( - // The location of the key used to generate response-wrapping JWTs - coreWrappingJWTKeyPath = "core/wrapping/jwtkey" -) - -func (c *Core) ensureWrappingKey(ctx context.Context) error { - entry, err := c.barrier.Get(ctx, coreWrappingJWTKeyPath) - if err != nil { - return err - } - - var keyParams clusterKeyParams - - if entry == nil { - key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - return errwrap.Wrapf("failed to generate wrapping key: {{err}}", err) - } - keyParams.D = key.D - keyParams.X = key.X - keyParams.Y = key.Y - keyParams.Type = corePrivateKeyTypeP521 - val, err := jsonutil.EncodeJSON(keyParams) - if err != nil { - return errwrap.Wrapf("failed to encode wrapping key: {{err}}", err) - } - entry = &Entry{ - Key: coreWrappingJWTKeyPath, - Value: val, - } - if err = c.barrier.Put(ctx, entry); err != nil { - return errwrap.Wrapf("failed to store wrapping key: {{err}}", err) - } - } - - // Redundant if we just created it, but in this case serves as a check anyways - if err = jsonutil.DecodeJSON(entry.Value, &keyParams); err != nil { - return errwrap.Wrapf("failed to decode wrapping key parameters: {{err}}", err) - } - - c.wrappingJWTKey = &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: keyParams.X, - Y: keyParams.Y, - }, - D: keyParams.D, - } - - c.logger.Info("loaded wrapping token key") - - return nil -} - -func (c *Core) wrapInCubbyhole(ctx context.Context, req *logical.Request, resp *logical.Response, auth *logical.Auth) (*logical.Response, error) { - // Before wrapping, obey special rules for listing: if no entries are - // found, 404. This prevents unwrapping only to find empty data. - if req.Operation == logical.ListOperation { - if resp == nil || (len(resp.Data) == 0 && len(resp.Warnings) == 0) { - return nil, logical.ErrUnsupportedPath - } - - keysRaw, ok := resp.Data["keys"] - if !ok || keysRaw == nil { - if len(resp.Data) > 0 || len(resp.Warnings) > 0 { - // We could be returning extra metadata on a list, or returning - // warnings with no data, so handle these cases - goto DONELISTHANDLING - } - return nil, logical.ErrUnsupportedPath - } - - keys, ok := keysRaw.([]string) - if !ok { - return nil, logical.ErrUnsupportedPath - } - if len(keys) == 0 { - return nil, logical.ErrUnsupportedPath - } - } - -DONELISTHANDLING: - var err error - sealWrap := resp.WrapInfo.SealWrap - - // If we are wrapping, the first part (performed in this functions) happens - // before auditing so that resp.WrapInfo.Token can contain the HMAC'd - // wrapping token ID in the audit logs, so that it can be determined from - // the audit logs whether the token was ever actually used. - creationTime := time.Now() - te := logical.TokenEntry{ - Path: req.Path, - Policies: []string{"response-wrapping"}, - CreationTime: creationTime.Unix(), - TTL: resp.WrapInfo.TTL, - NumUses: 1, - ExplicitMaxTTL: resp.WrapInfo.TTL, - } - - if err := c.tokenStore.create(ctx, &te); err != nil { - c.logger.Error("failed to create wrapping token", "error", err) - return nil, ErrInternalError - } - - resp.WrapInfo.Token = te.ID - resp.WrapInfo.Accessor = te.Accessor - resp.WrapInfo.CreationTime = creationTime - // If this is not a rewrap, store the request path as creation_path - if req.Path != "sys/wrapping/rewrap" { - resp.WrapInfo.CreationPath = req.Path - } - - if auth != nil && auth.EntityID != "" { - resp.WrapInfo.WrappedEntityID = auth.EntityID - } - - // This will only be non-nil if this response contains a token, so in that - // case put the accessor in the wrap info. - if resp.Auth != nil { - resp.WrapInfo.WrappedAccessor = resp.Auth.Accessor - } - - switch resp.WrapInfo.Format { - case "jwt": - // Create the JWT - claims := jws.Claims{} - // Map the JWT ID to the token ID for ease of use - claims.SetJWTID(te.ID) - // Set the issue time to the creation time - claims.SetIssuedAt(creationTime) - // Set the expiration to the TTL - claims.SetExpiration(creationTime.Add(resp.WrapInfo.TTL)) - if resp.Auth != nil { - claims.Set("accessor", resp.Auth.Accessor) - } - claims.Set("type", "wrapping") - claims.Set("addr", c.redirectAddr) - jwt := jws.NewJWT(claims, crypto.SigningMethodES512) - serWebToken, err := jwt.Serialize(c.wrappingJWTKey) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to serialize JWT", "error", err) - return nil, ErrInternalError - } - resp.WrapInfo.Token = string(serWebToken) - if c.redirectAddr == "" { - resp.AddWarning("No redirect address set in Vault so none could be encoded in the token. You may need to supply Vault's API address when unwrapping the token.") - } - } - - cubbyReq := &logical.Request{ - Operation: logical.CreateOperation, - Path: "cubbyhole/response", - ClientToken: te.ID, - } - if sealWrap { - cubbyReq.WrapInfo = &logical.RequestWrapInfo{ - SealWrap: true, - } - } - - // During a rewrap, store the original response, don't wrap it again. - if req.Path == "sys/wrapping/rewrap" { - cubbyReq.Data = map[string]interface{}{ - "response": resp.Data["response"], - } - } else { - httpResponse := logical.LogicalResponseToHTTPResponse(resp) - - // Add the unique identifier of the original request to the response - httpResponse.RequestID = req.ID - - // Because of the way that JSON encodes (likely just in Go) we actually get - // mixed-up values for ints if we simply put this object in the response - // and encode the whole thing; so instead we marshal it first, then store - // the string response. This actually ends up making it easier on the - // client side, too, as it becomes a straight read-string-pass-to-unmarshal - // operation. - - marshaledResponse, err := json.Marshal(httpResponse) - if err != nil { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to marshal wrapped response", "error", err) - return nil, ErrInternalError - } - - cubbyReq.Data = map[string]interface{}{ - "response": string(marshaledResponse), - } - } - - cubbyResp, err := c.router.Route(ctx, cubbyReq) - if err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapped response information", "error", err) - return nil, ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapped response information", "error", cubbyResp.Data["error"]) - return cubbyResp, nil - } - - // Store info for lookup - cubbyReq.WrapInfo = nil - cubbyReq.Path = "cubbyhole/wrapinfo" - cubbyReq.Data = map[string]interface{}{ - "creation_ttl": resp.WrapInfo.TTL, - "creation_time": creationTime, - } - // Store creation_path if not a rewrap - if req.Path != "sys/wrapping/rewrap" { - cubbyReq.Data["creation_path"] = req.Path - } else { - cubbyReq.Data["creation_path"] = resp.WrapInfo.CreationPath - } - cubbyResp, err = c.router.Route(ctx, cubbyReq) - if err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapping information", "error", err) - return nil, ErrInternalError - } - if cubbyResp != nil && cubbyResp.IsError() { - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to store wrapping information", "error", cubbyResp.Data["error"]) - return cubbyResp, nil - } - - wAuth := &logical.Auth{ - ClientToken: te.ID, - Policies: []string{"response-wrapping"}, - LeaseOptions: logical.LeaseOptions{ - TTL: te.TTL, - Renewable: false, - }, - } - - // Register the wrapped token with the expiration manager - if err := c.expiration.RegisterAuth(ctx, te.Path, wAuth); err != nil { - // Revoke since it's not yet being tracked for expiration - c.tokenStore.revokeOrphan(ctx, te.ID) - c.logger.Error("failed to register cubbyhole wrapping token lease", "request_path", req.Path, "error", err) - return nil, ErrInternalError - } - - return nil, nil -} - -// ValidateWrappingToken checks whether a token is a wrapping token. -func (c *Core) ValidateWrappingToken(req *logical.Request) (bool, error) { - if req == nil { - return false, fmt.Errorf("invalid request") - } - - var err error - - var token string - var thirdParty bool - if req.Data != nil && req.Data["token"] != nil { - thirdParty = true - if tokenStr, ok := req.Data["token"].(string); !ok { - return false, fmt.Errorf("could not decode token in request body") - } else if tokenStr == "" { - return false, fmt.Errorf("empty token in request body") - } else { - token = tokenStr - } - } else { - token = req.ClientToken - } - - // Check for it being a JWT. If it is, and it is valid, we extract the - // internal client token from it and use that during lookup. - if strings.Count(token, ".") == 2 { - wt, err := jws.ParseJWT([]byte(token)) - // If there's an error we simply fall back to attempting to use it as a regular token - if err == nil && wt != nil { - validator := &jwt.Validator{} - validator.SetClaim("type", "wrapping") - if err = wt.Validate(&c.wrappingJWTKey.PublicKey, crypto.SigningMethodES512, []*jwt.Validator{validator}...); err != nil { - return false, errwrap.Wrapf("wrapping token signature could not be validated: {{err}}", err) - } - token, _ = wt.Claims().JWTID() - // We override the given request client token so that the rest of - // Vault sees the real value. This also ensures audit logs are - // consistent with the actual token that was issued. - if !thirdParty { - req.ClientToken = token - } else { - req.Data["token"] = token - } - } - } - - if token == "" { - return false, fmt.Errorf("token is empty") - } - - if c.Sealed() { - return false, consts.ErrSealed - } - - c.stateLock.RLock() - defer c.stateLock.RUnlock() - if c.standby { - return false, consts.ErrStandby - } - - te, err := c.tokenStore.Lookup(c.activeContext, token) - if err != nil { - return false, err - } - if te == nil { - return false, nil - } - - if len(te.Policies) != 1 { - return false, nil - } - - if te.Policies[0] != responseWrappingPolicyName && te.Policies[0] != controlGroupPolicyName { - return false, nil - } - - return true, nil -} diff --git a/vendor/github.com/hashicorp/vault/version/cgo.go b/vendor/github.com/hashicorp/vault/version/cgo.go deleted file mode 100644 index 2ed493a1f..000000000 --- a/vendor/github.com/hashicorp/vault/version/cgo.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build cgo - -package version - -func init() { - CgoEnabled = true -} diff --git a/vendor/github.com/hashicorp/vault/version/version.go b/vendor/github.com/hashicorp/vault/version/version.go deleted file mode 100644 index 0f8193335..000000000 --- a/vendor/github.com/hashicorp/vault/version/version.go +++ /dev/null @@ -1,87 +0,0 @@ -package version - -import ( - "bytes" - "fmt" -) - -var ( - // The git commit that was compiled. This will be filled in by the compiler. - GitCommit string - GitDescribe string - - // Whether cgo is enabled or not; set at build time - CgoEnabled bool - - Version = "unknown" - VersionPrerelease = "unknown" - VersionMetadata = "" -) - -// VersionInfo -type VersionInfo struct { - Revision string - Version string - VersionPrerelease string - VersionMetadata string -} - -func GetVersion() *VersionInfo { - ver := Version - rel := VersionPrerelease - md := VersionMetadata - if GitDescribe != "" { - ver = GitDescribe - } - if GitDescribe == "" && rel == "" && VersionPrerelease != "" { - rel = "dev" - } - - return &VersionInfo{ - Revision: GitCommit, - Version: ver, - VersionPrerelease: rel, - VersionMetadata: md, - } -} - -func (c *VersionInfo) VersionNumber() string { - if Version == "unknown" && VersionPrerelease == "unknown" { - return "(version unknown)" - } - - version := fmt.Sprintf("%s", c.Version) - - if c.VersionPrerelease != "" { - version = fmt.Sprintf("%s-%s", version, c.VersionPrerelease) - } - - if c.VersionMetadata != "" { - version = fmt.Sprintf("%s+%s", version, c.VersionMetadata) - } - - return version -} - -func (c *VersionInfo) FullVersionNumber(rev bool) string { - var versionString bytes.Buffer - - if Version == "unknown" && VersionPrerelease == "unknown" { - return "Vault (version unknown)" - } - - fmt.Fprintf(&versionString, "Vault v%s", c.Version) - if c.VersionPrerelease != "" { - fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease) - } - - if c.VersionMetadata != "" { - fmt.Fprintf(&versionString, "+%s", c.VersionMetadata) - } - - if rev && c.Revision != "" { - fmt.Fprintf(&versionString, " (%s)", c.Revision) - } - - return versionString.String() -} diff --git a/vendor/github.com/hashicorp/vault/version/version_base.go b/vendor/github.com/hashicorp/vault/version/version_base.go deleted file mode 100644 index 648aafc77..000000000 --- a/vendor/github.com/hashicorp/vault/version/version_base.go +++ /dev/null @@ -1,11 +0,0 @@ -package version - -func init() { - // The main version number that is being run at the moment. - Version = "0.11.1" - - // A pre-release marker for the version. If this is "" (empty string) - // then it means that it is a final release. Otherwise, this is a pre-release - // such as "dev" (in development), "beta", "rc1", etc. - VersionPrerelease = "" -} diff --git a/vendor/github.com/hashicorp/yamux/.gitignore b/vendor/github.com/hashicorp/yamux/.gitignore new file mode 100644 index 000000000..836562412 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/.gitignore @@ -0,0 +1,23 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test diff --git a/vendor/github.com/hashicorp/yamux/go.mod b/vendor/github.com/hashicorp/yamux/go.mod new file mode 100644 index 000000000..672a0e581 --- /dev/null +++ b/vendor/github.com/hashicorp/yamux/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/yamux diff --git a/vendor/github.com/hashicorp/yamux/mux.go b/vendor/github.com/hashicorp/yamux/mux.go index 7abc7c744..18a078c8a 100644 --- a/vendor/github.com/hashicorp/yamux/mux.go +++ b/vendor/github.com/hashicorp/yamux/mux.go @@ -3,6 +3,7 @@ package yamux import ( "fmt" "io" + "log" "os" "time" ) @@ -30,8 +31,13 @@ type Config struct { // window size that we allow for a stream. MaxStreamWindowSize uint32 - // LogOutput is used to control the log destination + // LogOutput is used to control the log destination. Either Logger or + // LogOutput can be set, not both. LogOutput io.Writer + + // Logger is used to pass in the logger to be used. Either Logger or + // LogOutput can be set, not both. + Logger *log.Logger } // DefaultConfig is used to return a default configuration @@ -57,6 +63,11 @@ func VerifyConfig(config *Config) error { if config.MaxStreamWindowSize < initialStreamWindow { return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow) } + if config.LogOutput != nil && config.Logger != nil { + return fmt.Errorf("both Logger and LogOutput may not be set, select one") + } else if config.LogOutput == nil && config.Logger == nil { + return fmt.Errorf("one of Logger or LogOutput must be set, select one") + } return nil } diff --git a/vendor/github.com/hashicorp/yamux/session.go b/vendor/github.com/hashicorp/yamux/session.go index e17981839..a80ddec35 100644 --- a/vendor/github.com/hashicorp/yamux/session.go +++ b/vendor/github.com/hashicorp/yamux/session.go @@ -86,9 +86,14 @@ type sendReady struct { // newSession is used to construct a new session func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { + logger := config.Logger + if logger == nil { + logger = log.New(config.LogOutput, "", log.LstdFlags) + } + s := &Session{ config: config, - logger: log.New(config.LogOutput, "", log.LstdFlags), + logger: logger, conn: conn, bufRead: bufio.NewReader(conn), pings: make(map[uint32]chan struct{}), @@ -123,6 +128,12 @@ func (s *Session) IsClosed() bool { } } +// CloseChan returns a read-only channel which is closed as +// soon as the session is closed. +func (s *Session) CloseChan() <-chan struct{} { + return s.shutdownCh +} + // NumStreams returns the number of currently open streams func (s *Session) NumStreams() int { s.streamLock.Lock() @@ -303,8 +314,10 @@ func (s *Session) keepalive() { case <-time.After(s.config.KeepAliveInterval): _, err := s.Ping() if err != nil { - s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) - s.exitErr(ErrKeepAliveTimeout) + if err != ErrSessionShutdown { + s.logger.Printf("[ERR] yamux: keepalive failed: %v", err) + s.exitErr(ErrKeepAliveTimeout) + } return } case <-s.shutdownCh: @@ -323,8 +336,17 @@ func (s *Session) waitForSend(hdr header, body io.Reader) error { // potential shutdown. Since there's the expectation that sends can happen // in a timely manner, we enforce the connection write timeout here. func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) error { - timer := time.NewTimer(s.config.ConnectionWriteTimeout) - defer timer.Stop() + t := timerPool.Get() + timer := t.(*time.Timer) + timer.Reset(s.config.ConnectionWriteTimeout) + defer func() { + timer.Stop() + select { + case <-timer.C: + default: + } + timerPool.Put(t) + }() ready := sendReady{Hdr: hdr, Body: body, Err: errCh} select { @@ -349,8 +371,17 @@ func (s *Session) waitForSendErr(hdr header, body io.Reader, errCh chan error) e // the send happens right here, we enforce the connection write timeout if we // can't queue the header to be sent. func (s *Session) sendNoWait(hdr header) error { - timer := time.NewTimer(s.config.ConnectionWriteTimeout) - defer timer.Stop() + t := timerPool.Get() + timer := t.(*time.Timer) + timer.Reset(s.config.ConnectionWriteTimeout) + defer func() { + timer.Stop() + select { + case <-timer.C: + default: + } + timerPool.Put(t) + }() select { case s.sendCh <- sendReady{Hdr: hdr}: @@ -408,11 +439,20 @@ func (s *Session) recv() { } } +// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type +var ( + handlers = []func(*Session, header) error{ + typeData: (*Session).handleStreamMessage, + typeWindowUpdate: (*Session).handleStreamMessage, + typePing: (*Session).handlePing, + typeGoAway: (*Session).handleGoAway, + } +) + // recvLoop continues to receive data until a fatal error is encountered func (s *Session) recvLoop() error { defer close(s.recvDoneCh) hdr := header(make([]byte, headerSize)) - var handler func(header) error for { // Read the header if _, err := io.ReadFull(s.bufRead, hdr); err != nil { @@ -428,22 +468,12 @@ func (s *Session) recvLoop() error { return ErrInvalidVersion } - // Switch on the type - switch hdr.MsgType() { - case typeData: - handler = s.handleStreamMessage - case typeWindowUpdate: - handler = s.handleStreamMessage - case typeGoAway: - handler = s.handleGoAway - case typePing: - handler = s.handlePing - default: + mt := hdr.MsgType() + if mt < typeData || mt > typeGoAway { return ErrInvalidMsgType } - // Invoke the handler - if err := handler(hdr); err != nil { + if err := handlers[mt](s, hdr); err != nil { return err } } diff --git a/vendor/github.com/hashicorp/yamux/stream.go b/vendor/github.com/hashicorp/yamux/stream.go index d216e281c..aa2391973 100644 --- a/vendor/github.com/hashicorp/yamux/stream.go +++ b/vendor/github.com/hashicorp/yamux/stream.go @@ -47,8 +47,8 @@ type Stream struct { recvNotifyCh chan struct{} sendNotifyCh chan struct{} - readDeadline time.Time - writeDeadline time.Time + readDeadline atomic.Value // time.Time + writeDeadline atomic.Value // time.Time } // newStream is used to construct a new stream within @@ -67,6 +67,8 @@ func newStream(session *Session, id uint32, state streamState) *Stream { recvNotifyCh: make(chan struct{}, 1), sendNotifyCh: make(chan struct{}, 1), } + s.readDeadline.Store(time.Time{}) + s.writeDeadline.Store(time.Time{}) return s } @@ -122,8 +124,9 @@ START: WAIT: var timeout <-chan time.Time var timer *time.Timer - if !s.readDeadline.IsZero() { - delay := s.readDeadline.Sub(time.Now()) + readDeadline := s.readDeadline.Load().(time.Time) + if !readDeadline.IsZero() { + delay := readDeadline.Sub(time.Now()) timer = time.NewTimer(delay) timeout = timer.C } @@ -188,7 +191,7 @@ START: // Send the header s.sendHdr.encode(typeData, flags, s.id, max) - if err := s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { + if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { return 0, err } @@ -200,8 +203,9 @@ START: WAIT: var timeout <-chan time.Time - if !s.writeDeadline.IsZero() { - delay := s.writeDeadline.Sub(time.Now()) + writeDeadline := s.writeDeadline.Load().(time.Time) + if !writeDeadline.IsZero() { + delay := writeDeadline.Sub(time.Now()) timeout = time.After(delay) } select { @@ -238,18 +242,25 @@ func (s *Stream) sendWindowUpdate() error { // Determine the delta update max := s.session.config.MaxStreamWindowSize - delta := max - atomic.LoadUint32(&s.recvWindow) + var bufLen uint32 + s.recvLock.Lock() + if s.recvBuf != nil { + bufLen = uint32(s.recvBuf.Len()) + } + delta := (max - bufLen) - s.recvWindow // Determine the flags if any flags := s.sendFlags() // Check if we can omit the update if delta < (max/2) && flags == 0 { + s.recvLock.Unlock() return nil } // Update our window - atomic.AddUint32(&s.recvWindow, delta) + s.recvWindow += delta + s.recvLock.Unlock() // Send the header s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) @@ -392,16 +403,18 @@ func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { if length == 0 { return nil } - if remain := atomic.LoadUint32(&s.recvWindow); length > remain { - s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, remain, length) - return ErrRecvWindowExceeded - } // Wrap in a limited reader conn = &io.LimitedReader{R: conn, N: int64(length)} // Copy into buffer s.recvLock.Lock() + + if length > s.recvWindow { + s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length) + return ErrRecvWindowExceeded + } + if s.recvBuf == nil { // Allocate the receive buffer just-in-time to fit the full data frame. // This way we can read in the whole packet without further allocations. @@ -414,7 +427,7 @@ func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error { } // Decrement the receive window - atomic.AddUint32(&s.recvWindow, ^uint32(length-1)) + s.recvWindow -= length s.recvLock.Unlock() // Unblock any readers @@ -435,13 +448,13 @@ func (s *Stream) SetDeadline(t time.Time) error { // SetReadDeadline sets the deadline for future Read calls. func (s *Stream) SetReadDeadline(t time.Time) error { - s.readDeadline = t + s.readDeadline.Store(t) return nil } // SetWriteDeadline sets the deadline for future Write calls func (s *Stream) SetWriteDeadline(t time.Time) error { - s.writeDeadline = t + s.writeDeadline.Store(t) return nil } diff --git a/vendor/github.com/hashicorp/yamux/util.go b/vendor/github.com/hashicorp/yamux/util.go index 5fe45afcd..8a73e9249 100644 --- a/vendor/github.com/hashicorp/yamux/util.go +++ b/vendor/github.com/hashicorp/yamux/util.go @@ -1,5 +1,20 @@ package yamux +import ( + "sync" + "time" +) + +var ( + timerPool = &sync.Pool{ + New: func() interface{} { + timer := time.NewTimer(time.Hour * 1e6) + timer.Stop() + return timer + }, + } +) + // asyncSendErr is used to try an async send of an error func asyncSendErr(ch chan error, err error) { if ch == nil { diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore new file mode 100644 index 000000000..5091fb073 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/.gitignore @@ -0,0 +1,4 @@ +/jpgo +jmespath-fuzz.zip +cpu.out +go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.travis.yml b/vendor/github.com/jmespath/go-jmespath/.travis.yml new file mode 100644 index 000000000..1f9807757 --- /dev/null +++ b/vendor/github.com/jmespath/go-jmespath/.travis.yml @@ -0,0 +1,9 @@ +language: go + +sudo: false + +go: + - 1.4 + +install: go get -v -t ./... +script: make test diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go index 9cfa988bc..8e26ffeec 100644 --- a/vendor/github.com/jmespath/go-jmespath/api.go +++ b/vendor/github.com/jmespath/go-jmespath/api.go @@ -2,7 +2,7 @@ package jmespath import "strconv" -// JmesPath is the epresentation of a compiled JMES path query. A JmesPath is +// JMESPath is the epresentation of a compiled JMES path query. A JMESPath is // safe for concurrent use by multiple goroutines. type JMESPath struct { ast ASTNode diff --git a/vendor/github.com/keybase/go-crypto/LICENSE b/vendor/github.com/keybase/go-crypto/LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/vendor/github.com/keybase/go-crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/keybase/go-crypto/PATENTS b/vendor/github.com/keybase/go-crypto/PATENTS deleted file mode 100644 index 733099041..000000000 --- a/vendor/github.com/keybase/go-crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google hereby grants to You a perpetual, worldwide, non-exclusive, -no-charge, royalty-free, irrevocable (except as stated in this section) -patent license to make, have made, use, offer to sell, sell, import, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go b/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go deleted file mode 100644 index e601e389f..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/canonical_text.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package openpgp - -import "hash" - -// NewCanonicalTextHash reformats text written to it into the canonical -// form and then applies the hash h. See RFC 4880, section 5.2.1. -func NewCanonicalTextHash(h hash.Hash) hash.Hash { - return &canonicalTextHash{h, 0} -} - -type canonicalTextHash struct { - h hash.Hash - s int -} - -var newline = []byte{'\r', '\n'} - -func (cth *canonicalTextHash) Write(buf []byte) (int, error) { - start := 0 - - for i, c := range buf { - switch cth.s { - case 0: - if c == '\r' { - cth.s = 1 - } else if c == '\n' { - cth.h.Write(buf[start:i]) - cth.h.Write(newline) - start = i + 1 - } - case 1: - cth.s = 0 - } - } - - cth.h.Write(buf[start:]) - return len(buf), nil -} - -func (cth *canonicalTextHash) Sum(in []byte) []byte { - return cth.h.Sum(in) -} - -func (cth *canonicalTextHash) Reset() { - cth.h.Reset() - cth.s = 0 -} - -func (cth *canonicalTextHash) Size() int { - return cth.h.Size() -} - -func (cth *canonicalTextHash) BlockSize() int { - return cth.h.BlockSize() -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/keys.go b/vendor/github.com/keybase/go-crypto/openpgp/keys.go deleted file mode 100644 index 6ec1548e3..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/keys.go +++ /dev/null @@ -1,917 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package openpgp - -import ( - "crypto/hmac" - "crypto/rsa" - "encoding/binary" - "io" - "time" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// PublicKeyType is the armor type for a PGP public key. -var PublicKeyType = "PGP PUBLIC KEY BLOCK" - -// PrivateKeyType is the armor type for a PGP private key. -var PrivateKeyType = "PGP PRIVATE KEY BLOCK" - -// An Entity represents the components of an OpenPGP key: a primary public key -// (which must be a signing key), one or more identities claimed by that key, -// and zero or more subkeys, which may be encryption keys. -type Entity struct { - PrimaryKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Identities map[string]*Identity // indexed by Identity.Name - Revocations []*packet.Signature - // Revocations that are signed by designated revokers. Reading keys - // will not verify these revocations, because it won't have access to - // issuers' public keys, API consumers should do this instead (or - // not, and just assume that the key is probably revoked). - UnverifiedRevocations []*packet.Signature - Subkeys []Subkey - BadSubkeys []BadSubkey -} - -// An Identity represents an identity claimed by an Entity and zero or more -// assertions by other entities about that claim. -type Identity struct { - Name string // by convention, has the form "Full Name (comment) " - UserId *packet.UserId - SelfSignature *packet.Signature - Signatures []*packet.Signature - Revocation *packet.Signature -} - -// A Subkey is an additional public key in an Entity. Subkeys can be used for -// encryption. -type Subkey struct { - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Sig *packet.Signature - Revocation *packet.Signature -} - -// BadSubkey is one that failed reconstruction, but we'll keep it around for -// informational purposes. -type BadSubkey struct { - Subkey - Err error -} - -// A Key identifies a specific public key in an Entity. This is either the -// Entity's primary key or a subkey. -type Key struct { - Entity *Entity - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - SelfSignature *packet.Signature - KeyFlags packet.KeyFlagBits -} - -// A KeyRing provides access to public and private keys. -type KeyRing interface { - - // KeysById returns the set of keys that have the given key id. - // fp can be optionally supplied, which is the full key fingerprint. - // If it's provided, then it must match. This comes up in the case - // of GPG subpacket 33. - KeysById(id uint64, fp []byte) []Key - - // KeysByIdAndUsage returns the set of keys with the given id - // that also meet the key usage given by requiredUsage. - // The requiredUsage is expressed as the bitwise-OR of - // packet.KeyFlag* values. - // fp can be optionally supplied, which is the full key fingerprint. - // If it's provided, then it must match. This comes up in the case - // of GPG subpacket 33. - KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) []Key - - // DecryptionKeys returns all private keys that are valid for - // decryption. - DecryptionKeys() []Key -} - -// primaryIdentity returns the Identity marked as primary or the first identity -// if none are so marked. -func (e *Entity) primaryIdentity() *Identity { - var firstIdentity *Identity - for _, ident := range e.Identities { - if firstIdentity == nil { - firstIdentity = ident - } - if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { - return ident - } - } - return firstIdentity -} - -// encryptionKey returns the best candidate Key for encrypting a message to the -// given Entity. -func (e *Entity) encryptionKey(now time.Time) (Key, bool) { - candidateSubkey := -1 - - // Iterate the keys to find the newest, non-revoked key that can - // encrypt. - var maxTime time.Time - for i, subkey := range e.Subkeys { - - // NOTE(maxtaco) - // If there is a Flags subpacket, then we have to follow it, and only - // use keys that are marked for Encryption of Communication. If there - // isn't a Flags subpacket, and this is an Encrypt-Only key (right now only ElGamal - // suffices), then we implicitly use it. The check for primary below is a little - // more open-ended, but for now, let's be strict and potentially open up - // if we see bugs in the wild. - // - // One more note: old DSA/ElGamal keys tend not to have the Flags subpacket, - // so this sort of thing is pretty important for encrypting to older keys. - // - if ((subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications) || - (!subkey.Sig.FlagsValid && subkey.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal)) && - subkey.PublicKey.PubKeyAlgo.CanEncrypt() && - !subkey.Sig.KeyExpired(now) && - subkey.Revocation == nil && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { - candidateSubkey = i - maxTime = subkey.Sig.CreationTime - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true - } - - // If we don't have any candidate subkeys for encryption and - // the primary key doesn't have any usage metadata then we - // assume that the primary key is ok. Or, if the primary key is - // marked as ok to encrypt to, then we can obviously use it. - // - // NOTE(maxtaco) - see note above, how this policy is a little too open-ended - // for my liking, but leave it for now. - i := e.primaryIdentity() - if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications) && - e.PrimaryKey.PubKeyAlgo.CanEncrypt() && - !i.SelfSignature.KeyExpired(now) { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true - } - - // This Entity appears to be signing only. - return Key{}, false -} - -// signingKey return the best candidate Key for signing a message with this -// Entity. -func (e *Entity) signingKey(now time.Time) (Key, bool) { - candidateSubkey := -1 - - // Iterate the keys to find the newest, non-revoked key that can - // sign. - var maxTime time.Time - for i, subkey := range e.Subkeys { - if (!subkey.Sig.FlagsValid || subkey.Sig.FlagSign) && - subkey.PrivateKey.PrivateKey != nil && - subkey.PublicKey.PubKeyAlgo.CanSign() && - !subkey.Sig.KeyExpired(now) && - subkey.Revocation == nil && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { - candidateSubkey = i - maxTime = subkey.Sig.CreationTime - break - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Sig.GetKeyFlags()}, true - } - - // If we have no candidate subkey then we assume that it's ok to sign - // with the primary key. - i := e.primaryIdentity() - if (!i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign) && - e.PrimaryKey.PubKeyAlgo.CanSign() && - !i.SelfSignature.KeyExpired(now) && - e.PrivateKey.PrivateKey != nil { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, i.SelfSignature.GetKeyFlags()}, true - } - - return Key{}, false -} - -// An EntityList contains one or more Entities. -type EntityList []*Entity - -func keyMatchesIdAndFingerprint(key *packet.PublicKey, id uint64, fp []byte) bool { - if key.KeyId != id { - return false - } - if fp == nil { - return true - } - return hmac.Equal(fp, key.Fingerprint[:]) -} - -// KeysById returns the set of keys that have the given key id. -// fp can be optionally supplied, which is the full key fingerprint. -// If it's provided, then it must match. This comes up in the case -// of GPG subpacket 33. -func (el EntityList) KeysById(id uint64, fp []byte) (keys []Key) { - for _, e := range el { - if keyMatchesIdAndFingerprint(e.PrimaryKey, id, fp) { - var selfSig *packet.Signature - for _, ident := range e.Identities { - if selfSig == nil { - selfSig = ident.SelfSignature - } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { - selfSig = ident.SelfSignature - break - } - } - - var keyFlags packet.KeyFlagBits - for _, ident := range e.Identities { - keyFlags.Merge(ident.SelfSignature.GetKeyFlags()) - } - - keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, keyFlags}) - } - - for _, subKey := range e.Subkeys { - if keyMatchesIdAndFingerprint(subKey.PublicKey, id, fp) { - - // If there's both a a revocation and a sig, then take the - // revocation. Otherwise, we can proceed with the sig. - sig := subKey.Revocation - if sig == nil { - sig = subKey.Sig - } - - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, sig, sig.GetKeyFlags()}) - } - } - } - return -} - -// KeysByIdAndUsage returns the set of keys with the given id that also meet -// the key usage given by requiredUsage. The requiredUsage is expressed as -// the bitwise-OR of packet.KeyFlag* values. -// fp can be optionally supplied, which is the full key fingerprint. -// If it's provided, then it must match. This comes up in the case -// of GPG subpacket 33. -func (el EntityList) KeysByIdUsage(id uint64, fp []byte, requiredUsage byte) (keys []Key) { - for _, key := range el.KeysById(id, fp) { - if len(key.Entity.Revocations) > 0 { - continue - } - - if key.SelfSignature.RevocationReason != nil { - continue - } - - if requiredUsage != 0 { - var usage byte - - switch { - case key.KeyFlags.Valid: - usage = key.KeyFlags.BitField - - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoElGamal: - // We also need to handle the case where, although the sig's - // flags aren't valid, the key can is implicitly usable for - // encryption by virtue of being ElGamal. See also the comment - // in encryptionKey() above. - usage |= packet.KeyFlagEncryptCommunications - usage |= packet.KeyFlagEncryptStorage - - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoDSA || - key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoECDSA || - key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoEdDSA: - usage |= packet.KeyFlagSign - - // For a primary RSA key without any key flags, be as permissiable - // as possible. - case key.PublicKey.PubKeyAlgo == packet.PubKeyAlgoRSA && - keyMatchesIdAndFingerprint(key.Entity.PrimaryKey, id, fp): - usage = (packet.KeyFlagCertify | packet.KeyFlagSign | - packet.KeyFlagEncryptCommunications | packet.KeyFlagEncryptStorage) - } - - if usage&requiredUsage != requiredUsage { - continue - } - } - - keys = append(keys, key) - } - return -} - -// DecryptionKeys returns all private keys that are valid for decryption. -func (el EntityList) DecryptionKeys() (keys []Key) { - for _, e := range el { - for _, subKey := range e.Subkeys { - if subKey.PrivateKey != nil && subKey.PrivateKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Sig.GetKeyFlags()}) - } - } - } - return -} - -// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. -func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { - block, err := armor.Decode(r) - if err == io.EOF { - return nil, errors.InvalidArgumentError("no armored data found") - } - if err != nil { - return nil, err - } - if block.Type != PublicKeyType && block.Type != PrivateKeyType { - return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) - } - - return ReadKeyRing(block.Body) -} - -// ReadKeyRing reads one or more public/private keys. Unsupported keys are -// ignored as long as at least a single valid key is found. -func ReadKeyRing(r io.Reader) (el EntityList, err error) { - packets := packet.NewReader(r) - var lastUnsupportedError error - - for { - var e *Entity - e, err = ReadEntity(packets) - if err != nil { - // TODO: warn about skipped unsupported/unreadable keys - if _, ok := err.(errors.UnsupportedError); ok { - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } else if _, ok := err.(errors.StructuralError); ok { - // Skip unreadable, badly-formatted keys - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } - if err == io.EOF { - err = nil - break - } - if err != nil { - el = nil - break - } - } else { - el = append(el, e) - } - } - - if len(el) == 0 && err == nil { - err = lastUnsupportedError - } - return -} - -// readToNextPublicKey reads packets until the start of the entity and leaves -// the first packet of the new entity in the Reader. -func readToNextPublicKey(packets *packet.Reader) (err error) { - var p packet.Packet - for { - p, err = packets.Next() - if err == io.EOF { - return - } else if err != nil { - if _, ok := err.(errors.UnsupportedError); ok { - err = nil - continue - } - return - } - - if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { - packets.Unread(p) - return - } - } - - panic("unreachable") -} - -// ReadEntity reads an entity (public key, identities, subkeys etc) from the -// given Reader. -func ReadEntity(packets *packet.Reader) (*Entity, error) { - e := new(Entity) - e.Identities = make(map[string]*Identity) - - p, err := packets.Next() - if err != nil { - return nil, err - } - - var ok bool - if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { - if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { - packets.Unread(p) - return nil, errors.StructuralError("first packet was not a public/private key") - } else { - e.PrimaryKey = &e.PrivateKey.PublicKey - } - } - - if !e.PrimaryKey.PubKeyAlgo.CanSign() { - return nil, errors.StructuralError("primary key cannot be used for signatures") - } - - var current *Identity - var revocations []*packet.Signature - - designatedRevokers := make(map[uint64]bool) -EachPacket: - for { - p, err := packets.Next() - if err == io.EOF { - break - } else if err != nil { - return nil, err - } - switch pkt := p.(type) { - case *packet.UserId: - - // Make a new Identity object, that we might wind up throwing away. - // We'll only add it if we get a valid self-signature over this - // userID. - current = new(Identity) - current.Name = pkt.Id - current.UserId = pkt - case *packet.Signature: - if pkt.SigType == packet.SigTypeKeyRevocation { - // These revocations won't revoke UIDs (see - // SigTypeIdentityRevocation). Handle these first, - // because key might have revocation coming from - // another key (designated revoke). - revocations = append(revocations, pkt) - continue - } - - // These are signatures by other people on this key. Let's just ignore them - // from the beginning, since they shouldn't affect our key decoding one way - // or the other. - if pkt.IssuerKeyId != nil && *pkt.IssuerKeyId != e.PrimaryKey.KeyId { - continue - } - - // If this is a signature made by the keyholder, and the signature has stubbed out - // critical packets, then *now* we need to bail out. - if e := pkt.StubbedOutCriticalError; e != nil { - return nil, e - } - - // Next handle the case of a self-signature. According to RFC8440, - // Section 5.2.3.3, if there are several self-signatures, - // we should take the newer one. If they were both created - // at the same time, but one of them has keyflags specified and the - // other doesn't, keep the one with the keyflags. We have actually - // seen this in the wild (see the 'Yield' test in read_test.go). - // If there is a tie, and both have the same value for FlagsValid, - // then "last writer wins." - // - // HOWEVER! We have seen yet more keys in the wild (see the 'Spiros' - // test in read_test.go), in which the later self-signature is a bunch - // of junk, and doesn't even specify key flags. Does it really make - // sense to overwrite reasonable key flags with the empty set? I'm not - // sure what that would be trying to achieve, and plus GPG seems to be - // ok with this situation, and ignores the later (empty) keyflag set. - // So further tighten our overwrite rules, and only allow the later - // signature to overwrite the earlier signature if so doing won't - // trash the key flags. - if current != nil && - (current.SelfSignature == nil || - (!pkt.CreationTime.Before(current.SelfSignature.CreationTime) && - (pkt.FlagsValid || !current.SelfSignature.FlagsValid))) && - (pkt.SigType == packet.SigTypePositiveCert || pkt.SigType == packet.SigTypeGenericCert) && - pkt.IssuerKeyId != nil && - *pkt.IssuerKeyId == e.PrimaryKey.KeyId { - - if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil { - - current.SelfSignature = pkt - - // NOTE(maxtaco) 2016.01.11 - // Only register an identity once we've gotten a valid self-signature. - // It's possible therefore for us to throw away `current` in the case - // no valid self-signatures were found. That's OK as long as there are - // other identies that make sense. - // - // NOTE! We might later see a revocation for this very same UID, and it - // won't be undone. We've preserved this feature from the original - // Google OpenPGP we forked from. - e.Identities[current.Name] = current - } else { - // We really should warn that there was a failure here. Not raise an error - // since this really shouldn't be a fail-stop error. - } - } else if current != nil && pkt.SigType == packet.SigTypeIdentityRevocation { - if err = e.PrimaryKey.VerifyUserIdSignature(current.Name, e.PrimaryKey, pkt); err == nil { - // Note: we are not removing the identity from - // e.Identities. Caller can always filter by Revocation - // field to ignore revoked identities. - current.Revocation = pkt - } - } else if pkt.SigType == packet.SigTypeDirectSignature { - if err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, pkt); err == nil { - if desig := pkt.DesignatedRevoker; desig != nil { - // If it's a designated revoker signature, take last 8 octects - // of fingerprint as Key ID and save it to designatedRevokers - // map. We consult this map later to see if a foreign - // revocation should be added to UnverifiedRevocations. - keyID := binary.BigEndian.Uint64(desig.Fingerprint[len(desig.Fingerprint)-8:]) - designatedRevokers[keyID] = true - } - } - } else if current == nil { - // NOTE(maxtaco) - // - // See https://github.com/keybase/client/issues/2666 - // - // There might have been a user attribute picture before this signature, - // in which case this is still a valid PGP key. In the future we might - // not ignore user attributes (like picture). But either way, it doesn't - // make sense to bail out here. Keep looking for other valid signatures. - // - // Used to be: - // return nil, errors.StructuralError("signature packet found before user id packet") - } else { - current.Signatures = append(current.Signatures, pkt) - } - case *packet.PrivateKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, &pkt.PublicKey, pkt) - if err != nil { - return nil, err - } - case *packet.PublicKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, pkt, nil) - if err != nil { - return nil, err - } - default: - // we ignore unknown packets - } - } - - if len(e.Identities) == 0 { - return nil, errors.StructuralError("entity without any identities") - } - - for _, revocation := range revocations { - if revocation.IssuerKeyId == nil || *revocation.IssuerKeyId == e.PrimaryKey.KeyId { - // Key revokes itself, something that we can verify. - err = e.PrimaryKey.VerifyRevocationSignature(e.PrimaryKey, revocation) - if err == nil { - e.Revocations = append(e.Revocations, revocation) - } else { - return nil, errors.StructuralError("revocation signature signed by alternate key") - } - } else if revocation.IssuerKeyId != nil { - if _, ok := designatedRevokers[*revocation.IssuerKeyId]; ok { - // Revocation is done by certified designated revoker, - // but we can't verify the revocation. - e.UnverifiedRevocations = append(e.UnverifiedRevocations, revocation) - } - } - } - - return e, nil -} - -func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { - var subKey Subkey - subKey.PublicKey = pub - subKey.PrivateKey = priv - var lastErr error - for { - p, err := packets.Next() - if err == io.EOF { - break - } - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } - sig, ok := p.(*packet.Signature) - if !ok { - // Hit a non-signature packet, so assume we're up to the next key - packets.Unread(p) - break - } - if st := sig.SigType; st != packet.SigTypeSubkeyBinding && st != packet.SigTypeSubkeyRevocation { - - // Note(maxtaco): - // We used to error out here, but instead, let's fast-forward past - // packets that are in the wrong place (like misplaced 0x13 signatures) - // until we get to one that works. For a test case, - // see TestWithBadSubkeySignaturePackets. - - continue - } - err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig) - if err != nil { - // Non valid signature, so again, no need to abandon all hope, just continue; - // make a note of the error we hit. - lastErr = errors.StructuralError("subkey signature invalid: " + err.Error()) - continue - } - switch sig.SigType { - case packet.SigTypeSubkeyBinding: - // Does the "new" sig set expiration to later date than - // "previous" sig? - if subKey.Sig == nil || subKey.Sig.ExpiresBeforeOther(sig) { - subKey.Sig = sig - } - case packet.SigTypeSubkeyRevocation: - // First writer wins - if subKey.Revocation == nil { - subKey.Revocation = sig - } - } - } - - if subKey.Sig != nil { - if err := subKey.PublicKey.ErrorIfDeprecated(); err != nil { - // Key passed signature check but is deprecated. - subKey.Sig = nil - lastErr = err - } - } - - if subKey.Sig != nil { - e.Subkeys = append(e.Subkeys, subKey) - } else { - if lastErr == nil { - lastErr = errors.StructuralError("Subkey wasn't signed; expected a 'binding' signature") - } - e.BadSubkeys = append(e.BadSubkeys, BadSubkey{Subkey: subKey, Err: lastErr}) - } - return nil -} - -const defaultRSAKeyBits = 2048 - -// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a -// single identity composed of the given full name, comment and email, any of -// which may be empty but must not contain any of "()<>\x00". -// If config is nil, sensible defaults will be used. -func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { - currentTime := config.Now() - - bits := defaultRSAKeyBits - if config != nil && config.RSABits != 0 { - bits = config.RSABits - } - - uid := packet.NewUserId(name, comment, email) - if uid == nil { - return nil, errors.InvalidArgumentError("user id field contained invalid characters") - } - signingPriv, err := rsa.GenerateKey(config.Random(), bits) - if err != nil { - return nil, err - } - encryptingPriv, err := rsa.GenerateKey(config.Random(), bits) - if err != nil { - return nil, err - } - - e := &Entity{ - PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey), - PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv), - Identities: make(map[string]*Identity), - } - isPrimaryId := true - e.Identities[uid.Id] = &Identity{ - Name: uid.Name, - UserId: uid, - SelfSignature: &packet.Signature{ - CreationTime: currentTime, - SigType: packet.SigTypePositiveCert, - PubKeyAlgo: packet.PubKeyAlgoRSA, - Hash: config.Hash(), - IsPrimaryId: &isPrimaryId, - FlagsValid: true, - FlagSign: true, - FlagCertify: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - } - - e.Subkeys = make([]Subkey, 1) - e.Subkeys[0] = Subkey{ - PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), - PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv), - Sig: &packet.Signature{ - CreationTime: currentTime, - SigType: packet.SigTypeSubkeyBinding, - PubKeyAlgo: packet.PubKeyAlgoRSA, - Hash: config.Hash(), - FlagsValid: true, - FlagEncryptStorage: true, - FlagEncryptCommunications: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - } - e.Subkeys[0].PublicKey.IsSubkey = true - e.Subkeys[0].PrivateKey.IsSubkey = true - - return e, nil -} - -// SerializePrivate serializes an Entity, including private key material, to -// the given Writer. For now, it must only be used on an Entity returned from -// NewEntity. -// If config is nil, sensible defaults will be used. -func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { - err = e.PrivateKey.Serialize(w) - if err != nil { - return - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return - } - if e.PrivateKey.PrivateKey != nil { - err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config) - if err != nil { - return - } - } - err = ident.SelfSignature.Serialize(w) - if err != nil { - return - } - } - for _, subkey := range e.Subkeys { - err = subkey.PrivateKey.Serialize(w) - if err != nil { - return - } - // Workaround shortcoming of SignKey(), which doesn't work to reverse-sign - // sub-signing keys. So if requested, just reuse the signatures already - // available to us (if we read this key from a keyring). - if e.PrivateKey.PrivateKey != nil && !config.ReuseSignatures() { - err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) - if err != nil { - return - } - } - - if subkey.Revocation != nil { - err = subkey.Revocation.Serialize(w) - if err != nil { - return - } - } - - err = subkey.Sig.Serialize(w) - if err != nil { - return - } - } - return nil -} - -// Serialize writes the public part of the given Entity to w. (No private -// key material will be output). -func (e *Entity) Serialize(w io.Writer) error { - err := e.PrimaryKey.Serialize(w) - if err != nil { - return err - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return err - } - err = ident.SelfSignature.Serialize(w) - if err != nil { - return err - } - for _, sig := range ident.Signatures { - err = sig.Serialize(w) - if err != nil { - return err - } - } - } - for _, subkey := range e.Subkeys { - err = subkey.PublicKey.Serialize(w) - if err != nil { - return err - } - - if subkey.Revocation != nil { - err = subkey.Revocation.Serialize(w) - if err != nil { - return err - } - } - err = subkey.Sig.Serialize(w) - if err != nil { - return err - } - } - return nil -} - -// SignIdentity adds a signature to e, from signer, attesting that identity is -// associated with e. The provided identity must already be an element of -// e.Identities and the private key of signer must have been decrypted if -// necessary. -// If config is nil, sensible defaults will be used. -func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error { - if signer.PrivateKey == nil { - return errors.InvalidArgumentError("signing Entity must have a private key") - } - if signer.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing Entity's private key must be decrypted") - } - ident, ok := e.Identities[identity] - if !ok { - return errors.InvalidArgumentError("given identity string not found in Entity") - } - - sig := &packet.Signature{ - SigType: packet.SigTypeGenericCert, - PubKeyAlgo: signer.PrivateKey.PubKeyAlgo, - Hash: config.Hash(), - CreationTime: config.Now(), - IssuerKeyId: &signer.PrivateKey.KeyId, - } - if err := sig.SignUserId(identity, e.PrimaryKey, signer.PrivateKey, config); err != nil { - return err - } - ident.Signatures = append(ident.Signatures, sig) - return nil -} - -// CopySubkeyRevocations copies subkey revocations from the src Entity over -// to the receiver entity. We need this because `gpg --export-secret-key` does -// not appear to output subkey revocations. In this case we need to manually -// merge with the output of `gpg --export`. -func (e *Entity) CopySubkeyRevocations(src *Entity) { - m := make(map[[20]byte]*packet.Signature) - for _, subkey := range src.Subkeys { - if subkey.Revocation != nil { - m[subkey.PublicKey.Fingerprint] = subkey.Revocation - } - } - for i, subkey := range e.Subkeys { - if r := m[subkey.PublicKey.Fingerprint]; r != nil { - e.Subkeys[i].Revocation = r - } - } -} - -// CheckDesignatedRevokers will try to confirm any of designated -// revocation of entity. For this function to work, revocation -// issuer's key should be found in keyring. First successfully -// verified designated revocation is returned along with the key that -// verified it. -func FindVerifiedDesignatedRevoke(keyring KeyRing, entity *Entity) (*packet.Signature, *Key) { - for _, sig := range entity.UnverifiedRevocations { - if sig.IssuerKeyId == nil { - continue - } - - issuerKeyId := *sig.IssuerKeyId - issuerFingerprint := sig.IssuerFingerprint - keys := keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign) - if len(keys) == 0 { - continue - } - for _, key := range keys { - err := key.PublicKey.VerifyRevocationSignature(entity.PrimaryKey, sig) - if err == nil { - return sig, &key - } - } - } - - return nil, nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go deleted file mode 100644 index f023fe533..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/compressed.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "compress/bzip2" - "compress/flate" - "compress/zlib" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// Compressed represents a compressed OpenPGP packet. The decompressed contents -// will contain more OpenPGP packets. See RFC 4880, section 5.6. -type Compressed struct { - Body io.Reader -} - -const ( - NoCompression = flate.NoCompression - BestSpeed = flate.BestSpeed - BestCompression = flate.BestCompression - DefaultCompression = flate.DefaultCompression -) - -// CompressionConfig contains compressor configuration settings. -type CompressionConfig struct { - // Level is the compression level to use. It must be set to - // between -1 and 9, with -1 causing the compressor to use the - // default compression level, 0 causing the compressor to use - // no compression and 1 to 9 representing increasing (better, - // slower) compression levels. If Level is less than -1 or - // more then 9, a non-nil error will be returned during - // encryption. See the constants above for convenient common - // settings for Level. - Level int -} - -func (c *Compressed) parse(r io.Reader) error { - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - - switch buf[0] { - case 1: - c.Body = flate.NewReader(r) - case 2: - c.Body, err = zlib.NewReader(r) - case 3: - c.Body = bzip2.NewReader(r) - default: - err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) - } - - return err -} - -// compressedWriterCloser represents the serialized compression stream -// header and the compressor. Its Close() method ensures that both the -// compressor and serialized stream header are closed. Its Write() -// method writes to the compressor. -type compressedWriteCloser struct { - sh io.Closer // Stream Header - c io.WriteCloser // Compressor -} - -func (cwc compressedWriteCloser) Write(p []byte) (int, error) { - return cwc.c.Write(p) -} - -func (cwc compressedWriteCloser) Close() (err error) { - err = cwc.c.Close() - if err != nil { - return err - } - - return cwc.sh.Close() -} - -// SerializeCompressed serializes a compressed data packet to w and -// returns a WriteCloser to which the literal data packets themselves -// can be written and which MUST be closed on completion. If cc is -// nil, sensible defaults will be used to configure the compression -// algorithm. -func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) { - compressed, err := serializeStreamHeader(w, packetTypeCompressed) - if err != nil { - return - } - - _, err = compressed.Write([]byte{uint8(algo)}) - if err != nil { - return - } - - level := DefaultCompression - if cc != nil { - level = cc.Level - } - - var compressor io.WriteCloser - switch algo { - case CompressionZIP: - compressor, err = flate.NewWriter(compressed, level) - case CompressionZLIB: - compressor, err = zlib.NewWriterLevel(compressed, level) - default: - s := strconv.Itoa(int(algo)) - err = errors.UnsupportedError("Unsupported compression algorithm: " + s) - } - if err != nil { - return - } - - literaldata = compressedWriteCloser{compressed, compressor} - - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go deleted file mode 100644 index f4125e189..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/config.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto" - "crypto/rand" - "io" - "time" -) - -// Config collects a number of parameters along with sensible defaults. -// A nil *Config is valid and results in all default values. -type Config struct { - // Rand provides the source of entropy. - // If nil, the crypto/rand Reader is used. - Rand io.Reader - // DefaultHash is the default hash function to be used. - // If zero, SHA-256 is used. - DefaultHash crypto.Hash - // DefaultCipher is the cipher to be used. - // If zero, AES-128 is used. - DefaultCipher CipherFunction - // Time returns the current time as the number of seconds since the - // epoch. If Time is nil, time.Now is used. - Time func() time.Time - // DefaultCompressionAlgo is the compression algorithm to be - // applied to the plaintext before encryption. If zero, no - // compression is done. - DefaultCompressionAlgo CompressionAlgo - // CompressionConfig configures the compression settings. - CompressionConfig *CompressionConfig - // S2KCount is only used for symmetric encryption. It - // determines the strength of the passphrase stretching when - // the said passphrase is hashed to produce a key. S2KCount - // should be between 1024 and 65011712, inclusive. If Config - // is nil or S2KCount is 0, the value 65536 used. Not all - // values in the above range can be represented. S2KCount will - // be rounded up to the next representable value if it cannot - // be encoded exactly. When set, it is strongly encrouraged to - // use a value that is at least 65536. See RFC 4880 Section - // 3.7.1.3. - S2KCount int - // RSABits is the number of bits in new RSA keys made with NewEntity. - // If zero, then 2048 bit keys are created. - RSABits int - // ReuseSignatures tells us to reuse existing Signatures - // on serialized output. - ReuseSignaturesOnSerialize bool -} - -func (c *Config) Random() io.Reader { - if c == nil || c.Rand == nil { - return rand.Reader - } - return c.Rand -} - -func (c *Config) Hash() crypto.Hash { - if c == nil || uint(c.DefaultHash) == 0 { - return crypto.SHA256 - } - return c.DefaultHash -} - -func (c *Config) Cipher() CipherFunction { - if c == nil || uint8(c.DefaultCipher) == 0 { - return CipherAES128 - } - return c.DefaultCipher -} - -func (c *Config) Now() time.Time { - if c == nil || c.Time == nil { - return time.Now() - } - return c.Time() -} - -func (c *Config) Compression() CompressionAlgo { - if c == nil { - return CompressionNone - } - return c.DefaultCompressionAlgo -} - -func (c *Config) PasswordHashIterations() int { - if c == nil || c.S2KCount == 0 { - return 0 - } - return c.S2KCount -} - -func (c *Config) ReuseSignatures() bool { - return c != nil && c.ReuseSignaturesOnSerialize -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go deleted file mode 100644 index 41de661d7..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/ecdh.go +++ /dev/null @@ -1,104 +0,0 @@ -package packet - -import ( - "bytes" - "io" - "math/big" - - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// ECDHKdfParams generates KDF parameters sequence for given -// PublicKey. See https://tools.ietf.org/html/rfc6637#section-8 -func ECDHKdfParams(pub *PublicKey) []byte { - buf := new(bytes.Buffer) - oid := pub.ec.oid - buf.WriteByte(byte(len(oid))) - buf.Write(oid) - buf.WriteByte(18) // ECDH TYPE - pub.ecdh.serialize(buf) - buf.WriteString("Anonymous Sender ") - buf.Write(pub.Fingerprint[:]) - return buf.Bytes() -} - -func decryptKeyECDH(priv *PrivateKey, X, Y *big.Int, C []byte) (out []byte, err error) { - ecdhpriv, ok := priv.PrivateKey.(*ecdh.PrivateKey) - if !ok { - return nil, errors.InvalidArgumentError("bad internal ECDH key") - } - - Sx := ecdhpriv.DecryptShared(X, Y) - - kdfParams := ECDHKdfParams(&priv.PublicKey) - hash, ok := s2k.HashIdToHash(byte(priv.ecdh.KdfHash)) - if !ok { - return nil, errors.InvalidArgumentError("invalid hash id in private key") - } - - key := ecdhpriv.KDF(Sx, kdfParams, hash) - keySize := CipherFunction(priv.ecdh.KdfAlgo).KeySize() - - decrypted, err := ecdh.AESKeyUnwrap(key[:keySize], C) - if err != nil { - return nil, err - } - - // We have to "read ahead" to discover real length of the - // encryption key and properly unpad buffer. - cipherFunc := CipherFunction(decrypted[0]) - // +3 bytes = 1-byte cipher id and checksum 2-byte checksum. - out = ecdh.UnpadBuffer(decrypted, cipherFunc.KeySize()+3) - if out == nil { - return nil, errors.InvalidArgumentError("invalid padding while ECDH") - } - return out, nil -} - -func serializeEncryptedKeyECDH(w io.Writer, rand io.Reader, header [10]byte, pub *PublicKey, keyBlock []byte) error { - ecdhpub := pub.PublicKey.(*ecdh.PublicKey) - kdfParams := ECDHKdfParams(pub) - - hash, ok := s2k.HashIdToHash(byte(pub.ecdh.KdfHash)) - if !ok { - return errors.InvalidArgumentError("invalid hash id in private key") - } - - kdfKeySize := CipherFunction(pub.ecdh.KdfAlgo).KeySize() - Vx, Vy, C, err := ecdhpub.Encrypt(rand, kdfParams, keyBlock, hash, kdfKeySize) - if err != nil { - return err - } - - mpis, mpiBitLen := ecdh.Marshal(ecdhpub.Curve, Vx, Vy) - - packetLen := len(header) /* header length in bytes */ - packetLen += 2 /* mpi length in bits */ + len(mpis) - packetLen += 1 /* ciphertext size in bytes */ + len(C) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - - _, err = w.Write(header[:]) - if err != nil { - return err - } - - _, err = w.Write([]byte{byte(mpiBitLen >> 8), byte(mpiBitLen)}) - if err != nil { - return err - } - - _, err = w.Write(mpis[:]) - if err != nil { - return err - } - - w.Write([]byte{byte(len(C))}) - w.Write(C[:]) - return nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go deleted file mode 100644 index c224c105c..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/encrypted_key.go +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto/rsa" - "encoding/binary" - "io" - "math/big" - "strconv" - - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" -) - -const encryptedKeyVersion = 3 - -// EncryptedKey represents a public-key encrypted session key. See RFC 4880, -// section 5.1. -type EncryptedKey struct { - KeyId uint64 - Algo PublicKeyAlgorithm - CipherFunc CipherFunction // only valid after a successful Decrypt - Key []byte // only valid after a successful Decrypt - - encryptedMPI1, encryptedMPI2 parsedMPI - ecdh_C []byte -} - -func (e *EncryptedKey) parse(r io.Reader) (err error) { - var buf [10]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != encryptedKeyVersion { - return errors.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) - } - e.KeyId = binary.BigEndian.Uint64(buf[1:9]) - e.Algo = PublicKeyAlgorithm(buf[9]) - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - case PubKeyAlgoElGamal: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - if err != nil { - return - } - e.encryptedMPI2.bytes, e.encryptedMPI2.bitLength, err = readMPI(r) - case PubKeyAlgoECDH: - e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) - if err != nil { - return err - } - _, err = readFull(r, buf[:1]) // read C len (1 byte) - if err != nil { - return err - } - e.ecdh_C = make([]byte, int(buf[0])) - _, err = readFull(r, e.ecdh_C) - } - - if err != nil { - return err - } - - _, err = consumeAll(r) - return err -} - -func checksumKeyMaterial(key []byte) uint16 { - var checksum uint16 - for _, v := range key { - checksum += uint16(v) - } - return checksum -} - -// Decrypt decrypts an encrypted session key with the given private key. The -// private key must have been decrypted first. -// If config is nil, sensible defaults will be used. -func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error { - var err error - var b []byte - - // TODO(agl): use session key decryption routines here to avoid - // padding oracle attacks. - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - k := priv.PrivateKey.(*rsa.PrivateKey) - b, err = rsa.DecryptPKCS1v15(config.Random(), k, padToKeySize(&k.PublicKey, e.encryptedMPI1.bytes)) - case PubKeyAlgoElGamal: - c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes) - c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes) - b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) - case PubKeyAlgoECDH: - // Note: Unmarshal checks if point is on the curve. - c1, c2 := ecdh.Unmarshal(priv.PrivateKey.(*ecdh.PrivateKey).Curve, e.encryptedMPI1.bytes) - if c1 == nil { - return errors.InvalidArgumentError("failed to parse EC point for encryption key") - } - b, err = decryptKeyECDH(priv, c1, c2, e.ecdh_C) - default: - err = errors.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - - if err != nil { - return err - } - - e.CipherFunc = CipherFunction(b[0]) - e.Key = b[1 : len(b)-2] - expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) - checksum := checksumKeyMaterial(e.Key) - if checksum != expectedChecksum { - return errors.StructuralError("EncryptedKey checksum incorrect") - } - - return nil -} - -// Serialize writes the encrypted key packet, e, to w. -func (e *EncryptedKey) Serialize(w io.Writer) error { - var mpiLen int - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - mpiLen = 2 + len(e.encryptedMPI1.bytes) - case PubKeyAlgoElGamal: - mpiLen = 2 + len(e.encryptedMPI1.bytes) + 2 + len(e.encryptedMPI2.bytes) - default: - return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo))) - } - - serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) - - w.Write([]byte{encryptedKeyVersion}) - binary.Write(w, binary.BigEndian, e.KeyId) - w.Write([]byte{byte(e.Algo)}) - - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - writeMPIs(w, e.encryptedMPI1) - case PubKeyAlgoElGamal: - writeMPIs(w, e.encryptedMPI1, e.encryptedMPI2) - default: - panic("internal error") - } - - return nil -} - -// SerializeEncryptedKey serializes an encrypted key packet to w that contains -// key, encrypted to pub. -// If config is nil, sensible defaults will be used. -func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error { - var buf [10]byte - buf[0] = encryptedKeyVersion - binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) - buf[9] = byte(pub.PubKeyAlgo) - - keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */) - keyBlock[0] = byte(cipherFunc) - copy(keyBlock[1:], key) - checksum := checksumKeyMaterial(key) - keyBlock[1+len(key)] = byte(checksum >> 8) - keyBlock[1+len(key)+1] = byte(checksum) - - switch pub.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock) - case PubKeyAlgoElGamal: - return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) - case PubKeyAlgoECDH: - return serializeEncryptedKeyECDH(w, config.Random(), buf, pub, keyBlock) - case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: - return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) - } - - return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) -} - -func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error { - cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("RSA encryption failed: " + err.Error()) - } - - packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - return writeMPI(w, 8*uint16(len(cipherText)), cipherText) -} - -func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error { - c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error()) - } - - packetLen := 10 /* header length */ - packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8 - packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8 - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - err = writeBig(w, c1) - if err != nil { - return err - } - return writeBig(w, c2) -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go deleted file mode 100644 index 1a9ec6e51..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/literal.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "encoding/binary" - "io" -) - -// LiteralData represents an encrypted file. See RFC 4880, section 5.9. -type LiteralData struct { - IsBinary bool - FileName string - Time uint32 // Unix epoch time. Either creation time or modification time. 0 means undefined. - Body io.Reader -} - -// ForEyesOnly returns whether the contents of the LiteralData have been marked -// as especially sensitive. -func (l *LiteralData) ForEyesOnly() bool { - return l.FileName == "_CONSOLE" -} - -func (l *LiteralData) parse(r io.Reader) (err error) { - var buf [256]byte - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - - l.IsBinary = buf[0] == 'b' - fileNameLen := int(buf[1]) - - _, err = readFull(r, buf[:fileNameLen]) - if err != nil { - return - } - - l.FileName = string(buf[:fileNameLen]) - - _, err = readFull(r, buf[:4]) - if err != nil { - return - } - - l.Time = binary.BigEndian.Uint32(buf[:4]) - l.Body = r - return -} - -// SerializeLiteral serializes a literal data packet to w and returns a -// WriteCloser to which the data itself can be written and which MUST be closed -// on completion. The fileName is truncated to 255 bytes. -func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) { - var buf [4]byte - buf[0] = 't' - if isBinary { - buf[0] = 'b' - } - if len(fileName) > 255 { - fileName = fileName[:255] - } - buf[1] = byte(len(fileName)) - - inner, err := serializeStreamHeader(w, packetTypeLiteralData) - if err != nil { - return - } - - _, err = inner.Write(buf[:2]) - if err != nil { - return - } - _, err = inner.Write([]byte(fileName)) - if err != nil { - return - } - binary.BigEndian.PutUint32(buf[:], time) - _, err = inner.Write(buf[:]) - if err != nil { - return - } - - plaintext = inner - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go deleted file mode 100644 index ce2a33a54..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/ocfb.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// OpenPGP CFB Mode. http://tools.ietf.org/html/rfc4880#section-13.9 - -package packet - -import ( - "crypto/cipher" -) - -type ocfbEncrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// An OCFBResyncOption determines if the "resynchronization step" of OCFB is -// performed. -type OCFBResyncOption bool - -const ( - OCFBResync OCFBResyncOption = true - OCFBNoResync OCFBResyncOption = false -) - -// NewOCFBEncrypter returns a cipher.Stream which encrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block, and an initial amount of -// ciphertext. randData must be random bytes and be the same length as the -// cipher.Block's block size. Resync determines if the "resynchronization step" -// from RFC 4880, 13.9 step 7 is performed. Different parts of OpenPGP vary on -// this point. -func NewOCFBEncrypter(block cipher.Block, randData []byte, resync OCFBResyncOption) (cipher.Stream, []byte) { - blockSize := block.BlockSize() - if len(randData) != blockSize { - return nil, nil - } - - x := &ocfbEncrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefix := make([]byte, blockSize+2) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefix[i] = randData[i] ^ x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefix[blockSize] = x.fre[0] ^ randData[blockSize-2] - prefix[blockSize+1] = x.fre[1] ^ randData[blockSize-1] - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - return x, prefix -} - -func (x *ocfbEncrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - x.fre[x.outUsed] ^= src[i] - dst[i] = x.fre[x.outUsed] - x.outUsed++ - } -} - -type ocfbDecrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// NewOCFBDecrypter returns a cipher.Stream which decrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block. Prefix must be the first -// blockSize + 2 bytes of the ciphertext, where blockSize is the cipher.Block's -// block size. If an incorrect key is detected then nil is returned. On -// successful exit, blockSize+2 bytes of decrypted data are written into -// prefix. Resync determines if the "resynchronization step" from RFC 4880, -// 13.9 step 7 is performed. Different parts of OpenPGP vary on this point. -func NewOCFBDecrypter(block cipher.Block, prefix []byte, resync OCFBResyncOption) cipher.Stream { - blockSize := block.BlockSize() - if len(prefix) != blockSize+2 { - return nil - } - - x := &ocfbDecrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefixCopy := make([]byte, len(prefix)) - copy(prefixCopy, prefix) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefixCopy[i] ^= x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefixCopy[blockSize] ^= x.fre[0] - prefixCopy[blockSize+1] ^= x.fre[1] - - if prefixCopy[blockSize-2] != prefixCopy[blockSize] || - prefixCopy[blockSize-1] != prefixCopy[blockSize+1] { - return nil - } - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - copy(prefix, prefixCopy) - return x -} - -func (x *ocfbDecrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - c := src[i] - dst[i] = x.fre[x.outUsed] ^ src[i] - x.fre[x.outUsed] = c - x.outUsed++ - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go deleted file mode 100644 index af404bb10..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/one_pass_signature.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto" - "encoding/binary" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// OnePassSignature represents a one-pass signature packet. See RFC 4880, -// section 5.4. -type OnePassSignature struct { - SigType SignatureType - Hash crypto.Hash - PubKeyAlgo PublicKeyAlgorithm - KeyId uint64 - IsLast bool -} - -const onePassSignatureVersion = 3 - -func (ops *OnePassSignature) parse(r io.Reader) (err error) { - var buf [13]byte - - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != onePassSignatureVersion { - err = errors.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) - } - - var ok bool - ops.Hash, ok = s2k.HashIdToHash(buf[2]) - if !ok { - return errors.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) - } - - ops.SigType = SignatureType(buf[1]) - ops.PubKeyAlgo = PublicKeyAlgorithm(buf[3]) - ops.KeyId = binary.BigEndian.Uint64(buf[4:12]) - ops.IsLast = buf[12] != 0 - return -} - -// Serialize marshals the given OnePassSignature to w. -func (ops *OnePassSignature) Serialize(w io.Writer) error { - var buf [13]byte - buf[0] = onePassSignatureVersion - buf[1] = uint8(ops.SigType) - var ok bool - buf[2], ok = s2k.HashToHashId(ops.Hash) - if !ok { - return errors.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) - } - buf[3] = uint8(ops.PubKeyAlgo) - binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) - if ops.IsLast { - buf[12] = 1 - } - - if err := serializeHeader(w, packetTypeOnePassSignature, len(buf)); err != nil { - return err - } - _, err := w.Write(buf[:]) - return err -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go deleted file mode 100644 index cdeea012f..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/opaque.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// OpaquePacket represents an OpenPGP packet as raw, unparsed data. This is -// useful for splitting and storing the original packet contents separately, -// handling unsupported packet types or accessing parts of the packet not yet -// implemented by this package. -type OpaquePacket struct { - // Packet type - Tag uint8 - // Reason why the packet was parsed opaquely - Reason error - // Binary contents of the packet data - Contents []byte -} - -func (op *OpaquePacket) parse(r io.Reader) (err error) { - op.Contents, err = ioutil.ReadAll(r) - return -} - -// Serialize marshals the packet to a writer in its original form, including -// the packet header. -func (op *OpaquePacket) Serialize(w io.Writer) (err error) { - err = serializeHeader(w, packetType(op.Tag), len(op.Contents)) - if err == nil { - _, err = w.Write(op.Contents) - } - return -} - -// Parse attempts to parse the opaque contents into a structure supported by -// this package. If the packet is not known then the result will be another -// OpaquePacket. -func (op *OpaquePacket) Parse() (p Packet, err error) { - hdr := bytes.NewBuffer(nil) - err = serializeHeader(hdr, packetType(op.Tag), len(op.Contents)) - if err != nil { - op.Reason = err - return op, err - } - p, err = Read(io.MultiReader(hdr, bytes.NewBuffer(op.Contents))) - if err != nil { - op.Reason = err - p = op - } - return -} - -// OpaqueReader reads OpaquePackets from an io.Reader. -type OpaqueReader struct { - r io.Reader -} - -func NewOpaqueReader(r io.Reader) *OpaqueReader { - return &OpaqueReader{r: r} -} - -// Read the next OpaquePacket. -func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { - tag, _, contents, err := readHeader(or.r) - if err != nil { - return - } - op = &OpaquePacket{Tag: uint8(tag), Reason: err} - err = op.parse(contents) - if err != nil { - consumeAll(contents) - } - return -} - -// OpaqueSubpacket represents an unparsed OpenPGP subpacket, -// as found in signature and user attribute packets. -type OpaqueSubpacket struct { - SubType uint8 - Contents []byte -} - -// OpaqueSubpackets extracts opaque, unparsed OpenPGP subpackets from -// their byte representation. -func OpaqueSubpackets(contents []byte) (result []*OpaqueSubpacket, err error) { - var ( - subHeaderLen int - subPacket *OpaqueSubpacket - ) - for len(contents) > 0 { - subHeaderLen, subPacket, err = nextSubpacket(contents) - if err != nil { - break - } - result = append(result, subPacket) - contents = contents[subHeaderLen+len(subPacket.Contents):] - } - return -} - -func nextSubpacket(contents []byte) (subHeaderLen int, subPacket *OpaqueSubpacket, err error) { - // RFC 4880, section 5.2.3.1 - var subLen uint32 - if len(contents) < 1 { - goto Truncated - } - subPacket = &OpaqueSubpacket{} - switch { - case contents[0] < 192: - subHeaderLen = 2 // 1 length byte, 1 subtype byte - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[0]) - contents = contents[1:] - case contents[0] < 255: - subHeaderLen = 3 // 2 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[0]-192)<<8 + uint32(contents[1]) + 192 - contents = contents[2:] - default: - subHeaderLen = 6 // 5 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - subLen = uint32(contents[1])<<24 | - uint32(contents[2])<<16 | - uint32(contents[3])<<8 | - uint32(contents[4]) - contents = contents[5:] - } - if subLen > uint32(len(contents)) || subLen == 0 { - goto Truncated - } - subPacket.SubType = contents[0] - subPacket.Contents = contents[1:subLen] - return -Truncated: - err = errors.StructuralError("subpacket truncated") - return -} - -func (osp *OpaqueSubpacket) Serialize(w io.Writer) (err error) { - buf := make([]byte, 6) - n := serializeSubpacketLength(buf, len(osp.Contents)+1) - buf[n] = osp.SubType - if _, err = w.Write(buf[:n+1]); err != nil { - return - } - _, err = w.Write(osp.Contents) - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go deleted file mode 100644 index 13ff1a84b..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/packet.go +++ /dev/null @@ -1,576 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package packet implements parsing and serialization of OpenPGP packets, as -// specified in RFC 4880. -package packet // import "github.com/keybase/go-crypto/openpgp/packet" - -import ( - "bufio" - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/elliptic" - "crypto/rsa" - "io" - "math/big" - - "github.com/keybase/go-crypto/cast5" - "github.com/keybase/go-crypto/openpgp/errors" -) - -// readFull is the same as io.ReadFull except that reading zero bytes returns -// ErrUnexpectedEOF rather than EOF. -func readFull(r io.Reader, buf []byte) (n int, err error) { - n, err = io.ReadFull(r, buf) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. -func readLength(r io.Reader) (length int64, isPartial bool, err error) { - var buf [4]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - switch { - case buf[0] < 192: - length = int64(buf[0]) - case buf[0] < 224: - length = int64(buf[0]-192) << 8 - _, err = readFull(r, buf[0:1]) - if err != nil { - return - } - length += int64(buf[0]) + 192 - case buf[0] < 255: - length = int64(1) << (buf[0] & 0x1f) - isPartial = true - default: - _, err = readFull(r, buf[0:4]) - if err != nil { - return - } - length = int64(buf[0])<<24 | - int64(buf[1])<<16 | - int64(buf[2])<<8 | - int64(buf[3]) - } - return -} - -// partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths. -// The continuation lengths are parsed and removed from the stream and EOF is -// returned at the end of the packet. See RFC 4880, section 4.2.2.4. -type partialLengthReader struct { - r io.Reader - remaining int64 - isPartial bool -} - -func (r *partialLengthReader) Read(p []byte) (n int, err error) { - for r.remaining == 0 { - if !r.isPartial { - return 0, io.EOF - } - r.remaining, r.isPartial, err = readLength(r.r) - if err != nil { - return 0, err - } - } - - toRead := int64(len(p)) - if toRead > r.remaining { - toRead = r.remaining - } - - n, err = r.r.Read(p[:int(toRead)]) - r.remaining -= int64(n) - if n < int(toRead) && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// partialLengthWriter writes a stream of data using OpenPGP partial lengths. -// See RFC 4880, section 4.2.2.4. -type partialLengthWriter struct { - w io.WriteCloser - lengthByte [1]byte -} - -func (w *partialLengthWriter) Write(p []byte) (n int, err error) { - for len(p) > 0 { - for power := uint(14); power < 32; power-- { - l := 1 << power - if len(p) >= l { - w.lengthByte[0] = 224 + uint8(power) - _, err = w.w.Write(w.lengthByte[:]) - if err != nil { - return - } - var m int - m, err = w.w.Write(p[:l]) - n += m - if err != nil { - return - } - p = p[l:] - break - } - } - } - return -} - -func (w *partialLengthWriter) Close() error { - w.lengthByte[0] = 0 - _, err := w.w.Write(w.lengthByte[:]) - if err != nil { - return err - } - return w.w.Close() -} - -// A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the -// underlying Reader returns EOF before the limit has been reached. -type spanReader struct { - r io.Reader - n int64 -} - -func (l *spanReader) Read(p []byte) (n int, err error) { - if l.n <= 0 { - return 0, io.EOF - } - if int64(len(p)) > l.n { - p = p[0:l.n] - } - n, err = l.r.Read(p) - l.n -= int64(n) - if l.n > 0 && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readHeader parses a packet header and returns an io.Reader which will return -// the contents of the packet. See RFC 4880, section 4.2. -func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) { - var buf [4]byte - _, err = io.ReadFull(r, buf[:1]) - if err != nil { - return - } - if buf[0]&0x80 == 0 { - err = errors.StructuralError("tag byte does not have MSB set") - return - } - if buf[0]&0x40 == 0 { - // Old format packet - tag = packetType((buf[0] & 0x3f) >> 2) - lengthType := buf[0] & 3 - if lengthType == 3 { - length = -1 - contents = r - return - } - lengthBytes := 1 << lengthType - _, err = readFull(r, buf[0:lengthBytes]) - if err != nil { - return - } - for i := 0; i < lengthBytes; i++ { - length <<= 8 - length |= int64(buf[i]) - } - contents = &spanReader{r, length} - return - } - - // New format packet - tag = packetType(buf[0] & 0x3f) - length, isPartial, err := readLength(r) - if err != nil { - return - } - if isPartial { - contents = &partialLengthReader{ - remaining: length, - isPartial: true, - r: r, - } - length = -1 - } else { - contents = &spanReader{r, length} - } - return -} - -// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section -// 4.2. -func serializeHeader(w io.Writer, ptype packetType, length int) (err error) { - var buf [6]byte - var n int - - buf[0] = 0x80 | 0x40 | byte(ptype) - if length < 192 { - buf[1] = byte(length) - n = 2 - } else if length < 8384 { - length -= 192 - buf[1] = 192 + byte(length>>8) - buf[2] = byte(length) - n = 3 - } else { - buf[1] = 255 - buf[2] = byte(length >> 24) - buf[3] = byte(length >> 16) - buf[4] = byte(length >> 8) - buf[5] = byte(length) - n = 6 - } - - _, err = w.Write(buf[:n]) - return -} - -// serializeStreamHeader writes an OpenPGP packet header to w where the -// length of the packet is unknown. It returns a io.WriteCloser which can be -// used to write the contents of the packet. See RFC 4880, section 4.2. -func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) { - var buf [1]byte - buf[0] = 0x80 | 0x40 | byte(ptype) - _, err = w.Write(buf[:]) - if err != nil { - return - } - out = &partialLengthWriter{w: w} - return -} - -// Packet represents an OpenPGP packet. Users are expected to try casting -// instances of this interface to specific packet types. -type Packet interface { - parse(io.Reader) error -} - -// consumeAll reads from the given Reader until error, returning the number of -// bytes read. -func consumeAll(r io.Reader) (n int64, err error) { - var m int - var buf [1024]byte - - for { - m, err = r.Read(buf[:]) - n += int64(m) - if err == io.EOF { - err = nil - return - } - if err != nil { - return - } - } - - panic("unreachable") -} - -// packetType represents the numeric ids of the different OpenPGP packet types. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2 -type packetType uint8 - -const ( - packetTypeEncryptedKey packetType = 1 - packetTypeSignature packetType = 2 - packetTypeSymmetricKeyEncrypted packetType = 3 - packetTypeOnePassSignature packetType = 4 - packetTypePrivateKey packetType = 5 - packetTypePublicKey packetType = 6 - packetTypePrivateSubkey packetType = 7 - packetTypeCompressed packetType = 8 - packetTypeSymmetricallyEncrypted packetType = 9 - packetTypeLiteralData packetType = 11 - packetTypeUserId packetType = 13 - packetTypePublicSubkey packetType = 14 - packetTypeUserAttribute packetType = 17 - packetTypeSymmetricallyEncryptedMDC packetType = 18 -) - -// peekVersion detects the version of a public key packet about to -// be read. A bufio.Reader at the original position of the io.Reader -// is returned. -func peekVersion(r io.Reader) (bufr *bufio.Reader, ver byte, err error) { - bufr = bufio.NewReader(r) - var verBuf []byte - if verBuf, err = bufr.Peek(1); err != nil { - return - } - ver = verBuf[0] - return -} - -// Read reads a single OpenPGP packet from the given io.Reader. If there is an -// error parsing a packet, the whole packet is consumed from the input. -func Read(r io.Reader) (p Packet, err error) { - tag, _, contents, err := readHeader(r) - if err != nil { - return - } - - switch tag { - case packetTypeEncryptedKey: - p = new(EncryptedKey) - case packetTypeSignature: - var version byte - // Detect signature version - if contents, version, err = peekVersion(contents); err != nil { - return - } - if version < 4 { - p = new(SignatureV3) - } else { - p = new(Signature) - } - case packetTypeSymmetricKeyEncrypted: - p = new(SymmetricKeyEncrypted) - case packetTypeOnePassSignature: - p = new(OnePassSignature) - case packetTypePrivateKey, packetTypePrivateSubkey: - pk := new(PrivateKey) - if tag == packetTypePrivateSubkey { - pk.IsSubkey = true - } - p = pk - case packetTypePublicKey, packetTypePublicSubkey: - var version byte - if contents, version, err = peekVersion(contents); err != nil { - return - } - isSubkey := tag == packetTypePublicSubkey - if version < 4 { - p = &PublicKeyV3{IsSubkey: isSubkey} - } else { - p = &PublicKey{IsSubkey: isSubkey} - } - case packetTypeCompressed: - p = new(Compressed) - case packetTypeSymmetricallyEncrypted: - p = new(SymmetricallyEncrypted) - case packetTypeLiteralData: - p = new(LiteralData) - case packetTypeUserId: - p = new(UserId) - case packetTypeUserAttribute: - p = new(UserAttribute) - case packetTypeSymmetricallyEncryptedMDC: - se := new(SymmetricallyEncrypted) - se.MDC = true - p = se - default: - err = errors.UnknownPacketTypeError(tag) - } - if p != nil { - err = p.parse(contents) - } - if err != nil { - consumeAll(contents) - } - return -} - -// SignatureType represents the different semantic meanings of an OpenPGP -// signature. See RFC 4880, section 5.2.1. -type SignatureType uint8 - -const ( - SigTypeBinary SignatureType = 0 - SigTypeText = 1 - SigTypeGenericCert = 0x10 - SigTypePersonaCert = 0x11 - SigTypeCasualCert = 0x12 - SigTypePositiveCert = 0x13 - SigTypeSubkeyBinding = 0x18 - SigTypePrimaryKeyBinding = 0x19 - SigTypeDirectSignature = 0x1F - SigTypeKeyRevocation = 0x20 - SigTypeSubkeyRevocation = 0x28 - SigTypeIdentityRevocation = 0x30 -) - -// PublicKeyAlgorithm represents the different public key system specified for -// OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12 -type PublicKeyAlgorithm uint8 - -const ( - PubKeyAlgoRSA PublicKeyAlgorithm = 1 - PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 - PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 - PubKeyAlgoElGamal PublicKeyAlgorithm = 16 - PubKeyAlgoDSA PublicKeyAlgorithm = 17 - // RFC 6637, Section 5. - PubKeyAlgoECDH PublicKeyAlgorithm = 18 - PubKeyAlgoECDSA PublicKeyAlgorithm = 19 - - PubKeyAlgoBadElGamal PublicKeyAlgorithm = 20 // Reserved (deprecated, formerly ElGamal Encrypt or Sign) - // RFC -1 - PubKeyAlgoEdDSA PublicKeyAlgorithm = 22 -) - -// CanEncrypt returns true if it's possible to encrypt a message to a public -// key of the given type. -func (pka PublicKeyAlgorithm) CanEncrypt() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal, PubKeyAlgoECDH: - return true - } - return false -} - -// CanSign returns true if it's possible for a public key of the given type to -// sign a message. -func (pka PublicKeyAlgorithm) CanSign() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - return true - } - return false -} - -// CipherFunction represents the different block ciphers specified for OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 -type CipherFunction uint8 - -const ( - Cipher3DES CipherFunction = 2 - CipherCAST5 CipherFunction = 3 - CipherAES128 CipherFunction = 7 - CipherAES192 CipherFunction = 8 - CipherAES256 CipherFunction = 9 -) - -// KeySize returns the key size, in bytes, of cipher. -func (cipher CipherFunction) KeySize() int { - switch cipher { - case Cipher3DES: - return 24 - case CipherCAST5: - return cast5.KeySize - case CipherAES128: - return 16 - case CipherAES192: - return 24 - case CipherAES256: - return 32 - } - return 0 -} - -// blockSize returns the block size, in bytes, of cipher. -func (cipher CipherFunction) blockSize() int { - switch cipher { - case Cipher3DES: - return des.BlockSize - case CipherCAST5: - return 8 - case CipherAES128, CipherAES192, CipherAES256: - return 16 - } - return 0 -} - -// new returns a fresh instance of the given cipher. -func (cipher CipherFunction) new(key []byte) (block cipher.Block) { - switch cipher { - case Cipher3DES: - block, _ = des.NewTripleDESCipher(key) - case CipherCAST5: - block, _ = cast5.NewCipher(key) - case CipherAES128, CipherAES192, CipherAES256: - block, _ = aes.NewCipher(key) - } - return -} - -// readMPI reads a big integer from r. The bit length returned is the bit -// length that was specified in r. This is preserved so that the integer can be -// reserialized exactly. -func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) { - var buf [2]byte - _, err = readFull(r, buf[0:]) - if err != nil { - return - } - bitLength = uint16(buf[0])<<8 | uint16(buf[1]) - numBytes := (int(bitLength) + 7) / 8 - mpi = make([]byte, numBytes) - _, err = readFull(r, mpi) - // According to RFC 4880 3.2. we should check that the MPI has no leading - // zeroes (at least when not an encrypted MPI?), but this implementation - // does generate leading zeroes, so we keep accepting them. - return -} - -// writeMPI serializes a big integer to w. -func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) { - // Note that we can produce leading zeroes, in violation of RFC 4880 3.2. - // Implementations seem to be tolerant of them, and stripping them would - // make it complex to guarantee matching re-serialization. - _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) - if err == nil { - _, err = w.Write(mpiBytes) - } - return -} - -func WritePaddedBigInt(w io.Writer, length int, X *big.Int) (n int, err error) { - bytes := X.Bytes() - n1, err := w.Write(make([]byte, length-len(bytes))) - if err != nil { - return n1, err - } - n2, err := w.Write(bytes) - if err != nil { - return n2, err - } - return (n1 + n2), err -} - -// Minimum number of bytes to fit the curve coordinates. All -// coordinates have to be 0-padded to this length. -func mpiPointByteLength(curve elliptic.Curve) int { - return (curve.Params().P.BitLen() + 7) / 8 -} - -// writeBig serializes a *big.Int to w. -func writeBig(w io.Writer, i *big.Int) error { - return writeMPI(w, uint16(i.BitLen()), i.Bytes()) -} - -// padToKeySize left-pads a MPI with zeroes to match the length of the -// specified RSA public. -func padToKeySize(pub *rsa.PublicKey, b []byte) []byte { - k := (pub.N.BitLen() + 7) / 8 - if len(b) >= k { - return b - } - bb := make([]byte, k) - copy(bb[len(bb)-len(b):], b) - return bb -} - -// CompressionAlgo Represents the different compression algorithms -// supported by OpenPGP (except for BZIP2, which is not currently -// supported). See Section 9.3 of RFC 4880. -type CompressionAlgo uint8 - -const ( - CompressionNone CompressionAlgo = 0 - CompressionZIP CompressionAlgo = 1 - CompressionZLIB CompressionAlgo = 2 -) diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go deleted file mode 100644 index 9dca6fc9b..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/private_key.go +++ /dev/null @@ -1,557 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "crypto/cipher" - "crypto/dsa" - "crypto/ecdsa" - "crypto/rsa" - "crypto/sha1" - "fmt" - "io" - "io/ioutil" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/ed25519" - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// PrivateKey represents a possibly encrypted private key. See RFC 4880, -// section 5.5.3. -type PrivateKey struct { - PublicKey - Encrypted bool // if true then the private key is unavailable until Decrypt has been called. - encryptedData []byte - cipher CipherFunction - s2k func(out, in []byte) - PrivateKey interface{} // An *rsa.PrivateKey or *dsa.PrivateKey. - sha1Checksum bool - iv []byte - s2kHeader []byte -} - -type EdDSAPrivateKey struct { - PrivateKey - seed parsedMPI -} - -func (e *EdDSAPrivateKey) Sign(digest []byte) (R, S []byte, err error) { - r := bytes.NewReader(e.seed.bytes) - publicKey, privateKey, err := ed25519.GenerateKey(r) - if err != nil { - return nil, nil, err - } - - if !bytes.Equal(publicKey, e.PublicKey.edk.p.bytes[1:]) { // [1:] because [0] is 0x40 mpi header - return nil, nil, errors.UnsupportedError("EdDSA: Private key does not match public key.") - } - - sig := ed25519.Sign(privateKey, digest) - - sigLen := ed25519.SignatureSize / 2 - return sig[:sigLen], sig[sigLen:], nil -} - -func NewRSAPrivateKey(currentTime time.Time, priv *rsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewRSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewDSAPrivateKey(currentTime time.Time, priv *dsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewDSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewElGamalPrivateKey(currentTime time.Time, priv *elgamal.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewElGamalPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDSAPrivateKey(currentTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDSAPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDHPrivateKey(currentTime time.Time, priv *ecdh.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDHPublicKey(currentTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func (pk *PrivateKey) parse(r io.Reader) (err error) { - err = (&pk.PublicKey).parse(r) - if err != nil { - return - } - var buf [1]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - - s2kType := buf[0] - - switch s2kType { - case 0: - pk.s2k = nil - pk.Encrypted = false - case 254, 255: - _, err = readFull(r, buf[:]) - if err != nil { - return - } - pk.cipher = CipherFunction(buf[0]) - pk.Encrypted = true - pk.s2k, err = s2k.Parse(r) - if err != nil { - return - } - if s2kType == 254 { - pk.sha1Checksum = true - } - // S2K == nil implies that we got a "GNU Dummy" S2K. For instance, - // because our master secret key is on a USB key in a vault somewhere. - // In that case, there is no further data to consume here. - if pk.s2k == nil { - pk.Encrypted = false - return - } - default: - return errors.UnsupportedError("deprecated s2k function in private key") - } - if pk.Encrypted { - blockSize := pk.cipher.blockSize() - if blockSize == 0 { - return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) - } - pk.iv = make([]byte, blockSize) - _, err = readFull(r, pk.iv) - if err != nil { - return - } - } - - pk.encryptedData, err = ioutil.ReadAll(r) - if err != nil { - return - } - - if !pk.Encrypted { - return pk.parsePrivateKey(pk.encryptedData) - } - - return -} - -func mod64kHash(d []byte) uint16 { - var h uint16 - for _, b := range d { - h += uint16(b) - } - return h -} - -// Encrypt is the counterpart to the Decrypt() method below. It encrypts -// the private key with the provided passphrase. If config is nil, then -// the standard, and sensible, defaults apply. -// -// A key will be derived from the given passphrase using S2K Specifier -// Type 3 (Iterated + Salted, see RFC-4880 Sec. 3.7.1.3). This choice -// is hardcoded in s2k.Serialize(). S2KCount is hardcoded to 0, which is -// equivalent to 65536. And the hash algorithm for key-derivation can be -// set with config. The encrypted PrivateKey, using the algorithm specified -// in config (if provided), is written out to the encryptedData member. -// When Serialize() is called, this encryptedData member will be -// serialized, using S2K Usage value of 254, and thus SHA1 checksum. -func (pk *PrivateKey) Encrypt(passphrase []byte, config *Config) (err error) { - if pk.PrivateKey == nil { - return errors.InvalidArgumentError("there is no private key to encrypt") - } - - pk.sha1Checksum = true - pk.cipher = config.Cipher() - s2kConfig := s2k.Config{ - Hash: config.Hash(), - S2KCount: 0, - } - s2kBuf := bytes.NewBuffer(nil) - derivedKey := make([]byte, pk.cipher.KeySize()) - err = s2k.Serialize(s2kBuf, derivedKey, config.Random(), passphrase, &s2kConfig) - if err != nil { - return err - } - - pk.s2kHeader = s2kBuf.Bytes() - // No good way to set pk.s2k but to call s2k.Parse(), - // even though we have all the information here, but - // most of the functions needed are private to s2k. - pk.s2k, err = s2k.Parse(s2kBuf) - pk.iv = make([]byte, pk.cipher.blockSize()) - if _, err = config.Random().Read(pk.iv); err != nil { - return err - } - - privateKeyBuf := bytes.NewBuffer(nil) - if err = pk.serializePrivateKey(privateKeyBuf); err != nil { - return err - } - - checksum := sha1.Sum(privateKeyBuf.Bytes()) - if _, err = privateKeyBuf.Write(checksum[:]); err != nil { - return err - } - - pkData := privateKeyBuf.Bytes() - block := pk.cipher.new(derivedKey) - pk.encryptedData = make([]byte, len(pkData)) - cfb := cipher.NewCFBEncrypter(block, pk.iv) - cfb.XORKeyStream(pk.encryptedData, pkData) - pk.Encrypted = true - return nil -} - -func (pk *PrivateKey) Serialize(w io.Writer) (err error) { - buf := bytes.NewBuffer(nil) - err = pk.PublicKey.serializeWithoutHeaders(buf) - if err != nil { - return - } - - privateKeyBuf := bytes.NewBuffer(nil) - - if pk.PrivateKey == nil { - _, err = buf.Write([]byte{ - 254, // SHA-1 Convention - 9, // Encryption scheme (AES256) - 101, // GNU Extensions - 2, // Hash value (SHA1) - 'G', 'N', 'U', // "GNU" as a string - 1, // Extension type 1001 (minus 1000) - }) - } else if pk.Encrypted { - _, err = buf.Write([]byte{ - 254, // SHA-1 Convention - byte(pk.cipher), // Encryption scheme - }) - if err != nil { - return err - } - if _, err = buf.Write(pk.s2kHeader); err != nil { - return err - } - if _, err = buf.Write(pk.iv); err != nil { - return err - } - if _, err = privateKeyBuf.Write(pk.encryptedData); err != nil { - return err - } - } else { - buf.WriteByte(0 /* no encryption */) - if err = pk.serializePrivateKey(privateKeyBuf); err != nil { - return err - } - } - - ptype := packetTypePrivateKey - contents := buf.Bytes() - privateKeyBytes := privateKeyBuf.Bytes() - if pk.IsSubkey { - ptype = packetTypePrivateSubkey - } - totalLen := len(contents) + len(privateKeyBytes) - if !pk.Encrypted { - totalLen += 2 - } - err = serializeHeader(w, ptype, totalLen) - if err != nil { - return - } - _, err = w.Write(contents) - if err != nil { - return - } - _, err = w.Write(privateKeyBytes) - if err != nil { - return - } - - if len(privateKeyBytes) > 0 && !pk.Encrypted { - checksum := mod64kHash(privateKeyBytes) - var checksumBytes [2]byte - checksumBytes[0] = byte(checksum >> 8) - checksumBytes[1] = byte(checksum) - _, err = w.Write(checksumBytes[:]) - } - - return -} - -func (pk *PrivateKey) serializePrivateKey(w io.Writer) (err error) { - switch priv := pk.PrivateKey.(type) { - case *rsa.PrivateKey: - err = serializeRSAPrivateKey(w, priv) - case *dsa.PrivateKey: - err = serializeDSAPrivateKey(w, priv) - case *elgamal.PrivateKey: - err = serializeElGamalPrivateKey(w, priv) - case *ecdsa.PrivateKey: - err = serializeECDSAPrivateKey(w, priv) - case *ecdh.PrivateKey: - err = serializeECDHPrivateKey(w, priv) - case *EdDSAPrivateKey: - err = serializeEdDSAPrivateKey(w, priv) - default: - err = errors.InvalidArgumentError("unknown private key type") - } - - return err -} - -func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error { - err := writeBig(w, priv.D) - if err != nil { - return err - } - err = writeBig(w, priv.Primes[1]) - if err != nil { - return err - } - err = writeBig(w, priv.Primes[0]) - if err != nil { - return err - } - return writeBig(w, priv.Precomputed.Qinv) -} - -func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error { - return writeBig(w, priv.D) -} - -func serializeECDHPrivateKey(w io.Writer, priv *ecdh.PrivateKey) error { - return writeBig(w, priv.X) -} - -func serializeEdDSAPrivateKey(w io.Writer, priv *EdDSAPrivateKey) error { - return writeMPI(w, priv.seed.bitLength, priv.seed.bytes) -} - -// Decrypt decrypts an encrypted private key using a passphrase. -func (pk *PrivateKey) Decrypt(passphrase []byte) error { - if !pk.Encrypted { - return nil - } - // For GNU Dummy S2K, there's no key here, so don't do anything. - if pk.s2k == nil { - return nil - } - - key := make([]byte, pk.cipher.KeySize()) - pk.s2k(key, passphrase) - block := pk.cipher.new(key) - cfb := cipher.NewCFBDecrypter(block, pk.iv) - - data := make([]byte, len(pk.encryptedData)) - cfb.XORKeyStream(data, pk.encryptedData) - - if pk.sha1Checksum { - if len(data) < sha1.Size { - return errors.StructuralError("truncated private key data") - } - h := sha1.New() - h.Write(data[:len(data)-sha1.Size]) - sum := h.Sum(nil) - if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-sha1.Size] - } else { - if len(data) < 2 { - return errors.StructuralError("truncated private key data") - } - var sum uint16 - for i := 0; i < len(data)-2; i++ { - sum += uint16(data[i]) - } - if data[len(data)-2] != uint8(sum>>8) || - data[len(data)-1] != uint8(sum) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-2] - } - - return pk.parsePrivateKey(data) -} - -func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) { - switch pk.PublicKey.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: - return pk.parseRSAPrivateKey(data) - case PubKeyAlgoDSA: - return pk.parseDSAPrivateKey(data) - case PubKeyAlgoElGamal: - return pk.parseElGamalPrivateKey(data) - case PubKeyAlgoECDSA: - return pk.parseECDSAPrivateKey(data) - case PubKeyAlgoECDH: - return pk.parseECDHPrivateKey(data) - case PubKeyAlgoEdDSA: - return pk.parseEdDSAPrivateKey(data) - } - panic("impossible") -} - -func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) { - rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) - rsaPriv := new(rsa.PrivateKey) - rsaPriv.PublicKey = *rsaPub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - p, _, err := readMPI(buf) - if err != nil { - return - } - q, _, err := readMPI(buf) - if err != nil { - return - } - - rsaPriv.D = new(big.Int).SetBytes(d) - rsaPriv.Primes = make([]*big.Int, 2) - rsaPriv.Primes[0] = new(big.Int).SetBytes(p) - rsaPriv.Primes[1] = new(big.Int).SetBytes(q) - if err := rsaPriv.Validate(); err != nil { - return err - } - rsaPriv.Precompute() - pk.PrivateKey = rsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) { - dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) - dsaPriv := new(dsa.PrivateKey) - dsaPriv.PublicKey = *dsaPub - - buf := bytes.NewBuffer(data) - x, _, err := readMPI(buf) - if err != nil { - return - } - - dsaPriv.X = new(big.Int).SetBytes(x) - pk.PrivateKey = dsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) { - pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) - priv := new(elgamal.PrivateKey) - priv.PublicKey = *pub - - buf := bytes.NewBuffer(data) - x, _, err := readMPI(buf) - if err != nil { - return - } - - priv.X = new(big.Int).SetBytes(x) - pk.PrivateKey = priv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseECDHPrivateKey(data []byte) (err error) { - pub := pk.PublicKey.PublicKey.(*ecdh.PublicKey) - priv := new(ecdh.PrivateKey) - priv.PublicKey = *pub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - - priv.X = new(big.Int).SetBytes(d) - pk.PrivateKey = priv - pk.Encrypted = false - pk.encryptedData = nil - return nil -} - -func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) { - ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey) - ecdsaPriv := new(ecdsa.PrivateKey) - ecdsaPriv.PublicKey = *ecdsaPub - - buf := bytes.NewBuffer(data) - d, _, err := readMPI(buf) - if err != nil { - return - } - - ecdsaPriv.D = new(big.Int).SetBytes(d) - pk.PrivateKey = ecdsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -func (pk *PrivateKey) parseEdDSAPrivateKey(data []byte) (err error) { - eddsaPriv := new(EdDSAPrivateKey) - eddsaPriv.PublicKey = pk.PublicKey - - buf := bytes.NewBuffer(data) - eddsaPriv.seed.bytes, eddsaPriv.seed.bitLength, err = readMPI(buf) - if err != nil { - return err - } - - if bLen := len(eddsaPriv.seed.bytes); bLen != 32 { // 32 bytes private part of ed25519 key. - return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA private key length: %d", bLen)) - } - - pk.PrivateKey = eddsaPriv - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go deleted file mode 100644 index 59bf47193..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key.go +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" - "encoding/binary" - "fmt" - "hash" - "io" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/brainpool" - "github.com/keybase/go-crypto/curve25519" - "github.com/keybase/go-crypto/ed25519" - "github.com/keybase/go-crypto/openpgp/ecdh" - "github.com/keybase/go-crypto/openpgp/elgamal" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -var ( - // NIST curve P-256 - oidCurveP256 []byte = []byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07} - // NIST curve P-384 - oidCurveP384 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x22} - // NIST curve P-521 - oidCurveP521 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x23} - // Brainpool curve P-256r1 - oidCurveP256r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07} - // Brainpool curve P-384r1 - oidCurveP384r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B} - // Brainpool curve P-512r1 - oidCurveP512r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D} - // EdDSA - oidEdDSA []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01} - // cv25519 - oidCurve25519 []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01} -) - -const maxOIDLength = 10 - -// ecdsaKey stores the algorithm-specific fields for ECDSA keys. -// as defined in RFC 6637, Section 9. -type ecdsaKey struct { - // oid contains the OID byte sequence identifying the elliptic curve used - oid []byte - // p contains the elliptic curve point that represents the public key - p parsedMPI -} - -type edDSAkey struct { - ecdsaKey -} - -func copyFrontFill(dst, src []byte, length int) int { - if srcLen := len(src); srcLen < length { - return copy(dst[length-srcLen:], src[:]) - } else { - return copy(dst[:], src[:]) - } -} - -func (e *edDSAkey) Verify(payload []byte, r parsedMPI, s parsedMPI) bool { - const halfSigSize = ed25519.SignatureSize / 2 - var sig [ed25519.SignatureSize]byte - - // NOTE: The first byte is 0x40 - MPI header - // TODO: Maybe clean the code up and use 0x40 as a header when - // reading and keep only actual number in p field. Find out how - // other MPIs are stored. - key := e.p.bytes[1:] - - // Note: it may happen that R + S do not form 64-byte signature buffer that - // ed25519 expects, but because we copy it over to an array of exact size, - // we will always pass correctly sized slice to Verify. Slice too short - // would make ed25519 panic(). - copyFrontFill(sig[:halfSigSize], r.bytes, halfSigSize) - copyFrontFill(sig[halfSigSize:], s.bytes, halfSigSize) - - return ed25519.Verify(key, payload, sig[:]) -} - -// parseOID reads the OID for the curve as defined in RFC 6637, Section 9. -func parseOID(r io.Reader) (oid []byte, err error) { - buf := make([]byte, maxOIDLength) - if _, err = readFull(r, buf[:1]); err != nil { - return - } - oidLen := buf[0] - if int(oidLen) > len(buf) { - err = errors.UnsupportedError("invalid oid length: " + strconv.Itoa(int(oidLen))) - return - } - oid = buf[:oidLen] - _, err = readFull(r, oid) - return -} - -func (f *ecdsaKey) parse(r io.Reader) (err error) { - if f.oid, err = parseOID(r); err != nil { - return err - } - f.p.bytes, f.p.bitLength, err = readMPI(r) - return err -} - -func (f *ecdsaKey) serialize(w io.Writer) (err error) { - buf := make([]byte, maxOIDLength+1) - buf[0] = byte(len(f.oid)) - copy(buf[1:], f.oid) - if _, err = w.Write(buf[:len(f.oid)+1]); err != nil { - return - } - return writeMPIs(w, f.p) -} - -func getCurveByOid(oid []byte) elliptic.Curve { - switch { - case bytes.Equal(oid, oidCurveP256): - return elliptic.P256() - case bytes.Equal(oid, oidCurveP384): - return elliptic.P384() - case bytes.Equal(oid, oidCurveP521): - return elliptic.P521() - case bytes.Equal(oid, oidCurveP256r1): - return brainpool.P256r1() - case bytes.Equal(oid, oidCurveP384r1): - return brainpool.P384r1() - case bytes.Equal(oid, oidCurveP512r1): - return brainpool.P512r1() - case bytes.Equal(oid, oidCurve25519): - return curve25519.Cv25519() - default: - return nil - } -} - -func (f *ecdsaKey) newECDSA() (*ecdsa.PublicKey, error) { - var c = getCurveByOid(f.oid) - // Curve25519 should not be used in ECDSA. - if c == nil || bytes.Equal(f.oid, oidCurve25519) { - return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid)) - } - // Note: Unmarshal already checks if point is on curve. - x, y := elliptic.Unmarshal(c, f.p.bytes) - if x == nil { - return nil, errors.UnsupportedError("failed to parse EC point") - } - return &ecdsa.PublicKey{Curve: c, X: x, Y: y}, nil -} - -func (f *ecdsaKey) newECDH() (*ecdh.PublicKey, error) { - var c = getCurveByOid(f.oid) - if c == nil { - return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid)) - } - // ecdh.Unmarshal handles unmarshaling for all curve types. It - // also checks if point is on curve. - x, y := ecdh.Unmarshal(c, f.p.bytes) - if x == nil { - return nil, errors.UnsupportedError("failed to parse EC point") - } - return &ecdh.PublicKey{Curve: c, X: x, Y: y}, nil -} - -func (f *ecdsaKey) byteLen() int { - return 1 + len(f.oid) + 2 + len(f.p.bytes) -} - -type kdfHashFunction byte -type kdfAlgorithm byte - -// ecdhKdf stores key derivation function parameters -// used for ECDH encryption. See RFC 6637, Section 9. -type ecdhKdf struct { - KdfHash kdfHashFunction - KdfAlgo kdfAlgorithm -} - -func (f *ecdhKdf) parse(r io.Reader) (err error) { - buf := make([]byte, 1) - if _, err = readFull(r, buf); err != nil { - return - } - kdfLen := int(buf[0]) - if kdfLen < 3 { - return errors.UnsupportedError("Unsupported ECDH KDF length: " + strconv.Itoa(kdfLen)) - } - buf = make([]byte, kdfLen) - if _, err = readFull(r, buf); err != nil { - return - } - reserved := int(buf[0]) - f.KdfHash = kdfHashFunction(buf[1]) - f.KdfAlgo = kdfAlgorithm(buf[2]) - if reserved != 0x01 { - return errors.UnsupportedError("Unsupported KDF reserved field: " + strconv.Itoa(reserved)) - } - return -} - -func (f *ecdhKdf) serialize(w io.Writer) (err error) { - buf := make([]byte, 4) - // See RFC 6637, Section 9, Algorithm-Specific Fields for ECDH keys. - buf[0] = byte(0x03) // Length of the following fields - buf[1] = byte(0x01) // Reserved for future extensions, must be 1 for now - buf[2] = byte(f.KdfHash) - buf[3] = byte(f.KdfAlgo) - _, err = w.Write(buf[:]) - return -} - -func (f *ecdhKdf) byteLen() int { - return 4 -} - -// PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2. -type PublicKey struct { - CreationTime time.Time - PubKeyAlgo PublicKeyAlgorithm - PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey or *ecdsa.PublicKey - Fingerprint [20]byte - KeyId uint64 - IsSubkey bool - - n, e, p, q, g, y parsedMPI - - // RFC 6637 fields - ec *ecdsaKey - ecdh *ecdhKdf - - // EdDSA fields (no RFC available), uses ecdsa scaffolding - edk *edDSAkey -} - -// signingKey provides a convenient abstraction over signature verification -// for v3 and v4 public keys. -type signingKey interface { - SerializeSignaturePrefix(io.Writer) - serializeWithoutHeaders(io.Writer) error -} - -func FromBig(n *big.Int) parsedMPI { - return parsedMPI{ - bytes: n.Bytes(), - bitLength: uint16(n.BitLen()), - } -} - -func FromBytes(bytes []byte) parsedMPI { - return parsedMPI{ - bytes: bytes, - bitLength: uint16(8 * len(bytes)), - } -} - -// NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey. -func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoRSA, - PublicKey: pub, - n: FromBig(pub.N), - e: FromBig(big.NewInt(int64(pub.E))), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -// NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey. -func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoDSA, - PublicKey: pub, - p: FromBig(pub.P), - q: FromBig(pub.Q), - g: FromBig(pub.G), - y: FromBig(pub.Y), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -// check EdDSA public key material. -// There is currently no RFC for it, but it doesn't mean it's not -// implemented or in use. -func (e *edDSAkey) check() error { - if !bytes.Equal(e.oid, oidEdDSA) { - return errors.UnsupportedError(fmt.Sprintf("Bad OID for EdDSA key: %v", e.oid)) - } - if bLen := len(e.p.bytes); bLen != 33 { // 32 bytes for ed25519 key and 1 byte for 0x40 header - return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA public key length: %d", bLen)) - } - return nil -} - -// NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey. -func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoElGamal, - PublicKey: pub, - p: FromBig(pub.P), - g: FromBig(pub.G), - y: FromBig(pub.Y), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func getCurveOid(curve elliptic.Curve) (res []byte, err error) { - switch curve { - case elliptic.P256(): - res = oidCurveP256 - case elliptic.P384(): - res = oidCurveP384 - case elliptic.P521(): - res = oidCurveP521 - case brainpool.P256r1(): - res = oidCurveP256r1 - case brainpool.P384r1(): - res = oidCurveP384r1 - case brainpool.P512r1(): - res = oidCurveP512r1 - case curve25519.Cv25519(): - res = oidCurve25519 - default: - err = errors.UnsupportedError("unknown curve") - } - return -} - -func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDSA, - PublicKey: pub, - ec: new(ecdsaKey), - } - oid, _ := getCurveOid(pub.Curve) - pk.ec.oid = oid - bs, bitLen := ecdh.Marshal(pub.Curve, pub.X, pub.Y) - pk.ec.p.bytes = bs - pk.ec.p.bitLength = uint16(bitLen) - - pk.setFingerPrintAndKeyId() - return pk -} - -func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { - pk := &PublicKey{ - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDH, - PublicKey: pub, - ec: new(ecdsaKey), - } - oid, _ := getCurveOid(pub.Curve) - pk.ec.oid = oid - bs, bitLen := ecdh.Marshal(pub.Curve, pub.X, pub.Y) - pk.ec.p.bytes = bs - pk.ec.p.bitLength = uint16(bitLen) - - hashbyte, _ := s2k.HashToHashId(crypto.SHA512) - pk.ecdh = &ecdhKdf{ - KdfHash: kdfHashFunction(hashbyte), - KdfAlgo: kdfAlgorithm(CipherAES256), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func (pk *PublicKey) parse(r io.Reader) (err error) { - // RFC 4880, section 5.5.2 - var buf [6]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != 4 { - return errors.UnsupportedError("public key version") - } - pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) - pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5]) - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - err = pk.parseRSA(r) - case PubKeyAlgoDSA: - err = pk.parseDSA(r) - case PubKeyAlgoElGamal: - err = pk.parseElGamal(r) - case PubKeyAlgoEdDSA: - pk.edk = new(edDSAkey) - if err = pk.edk.parse(r); err != nil { - return err - } - err = pk.edk.check() - case PubKeyAlgoECDSA: - pk.ec = new(ecdsaKey) - if err = pk.ec.parse(r); err != nil { - return err - } - pk.PublicKey, err = pk.ec.newECDSA() - case PubKeyAlgoECDH: - pk.ec = new(ecdsaKey) - if err = pk.ec.parse(r); err != nil { - return - } - pk.ecdh = new(ecdhKdf) - if err = pk.ecdh.parse(r); err != nil { - return - } - pk.PublicKey, err = pk.ec.newECDH() - case PubKeyAlgoBadElGamal: - // Key has ElGamal format but nil-implementation - it will - // load but it's not possible to do any operations using this - // key. - err = pk.parseElGamal(r) - if err != nil { - pk.PublicKey = nil - } - default: - err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) - } - if err != nil { - return - } - - pk.setFingerPrintAndKeyId() - return -} - -func (pk *PublicKey) setFingerPrintAndKeyId() { - // RFC 4880, section 12.2 - fingerPrint := sha1.New() - pk.SerializeSignaturePrefix(fingerPrint) - pk.serializeWithoutHeaders(fingerPrint) - copy(pk.Fingerprint[:], fingerPrint.Sum(nil)) - pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20]) -} - -// parseRSA parses RSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseRSA(r io.Reader) (err error) { - pk.n.bytes, pk.n.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.e.bytes, pk.e.bitLength, err = readMPI(r) - if err != nil { - return - } - - if len(pk.e.bytes) > 7 { - err = errors.UnsupportedError("large public exponent") - return - } - rsa := &rsa.PublicKey{ - N: new(big.Int).SetBytes(pk.n.bytes), - E: 0, - } - for i := 0; i < len(pk.e.bytes); i++ { - rsa.E <<= 8 - rsa.E |= int(pk.e.bytes[i]) - } - pk.PublicKey = rsa - return -} - -// parseDSA parses DSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseDSA(r io.Reader) (err error) { - pk.p.bytes, pk.p.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.q.bytes, pk.q.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.g.bytes, pk.g.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.y.bytes, pk.y.bitLength, err = readMPI(r) - if err != nil { - return - } - - dsa := new(dsa.PublicKey) - dsa.P = new(big.Int).SetBytes(pk.p.bytes) - dsa.Q = new(big.Int).SetBytes(pk.q.bytes) - dsa.G = new(big.Int).SetBytes(pk.g.bytes) - dsa.Y = new(big.Int).SetBytes(pk.y.bytes) - pk.PublicKey = dsa - return -} - -// parseElGamal parses ElGamal public key material from the given Reader. See -// RFC 4880, section 5.5.2. -func (pk *PublicKey) parseElGamal(r io.Reader) (err error) { - pk.p.bytes, pk.p.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.g.bytes, pk.g.bitLength, err = readMPI(r) - if err != nil { - return - } - pk.y.bytes, pk.y.bitLength, err = readMPI(r) - if err != nil { - return - } - - elgamal := new(elgamal.PublicKey) - elgamal.P = new(big.Int).SetBytes(pk.p.bytes) - elgamal.G = new(big.Int).SetBytes(pk.g.bytes) - elgamal.Y = new(big.Int).SetBytes(pk.y.bytes) - pk.PublicKey = elgamal - return -} - -// SerializeSignaturePrefix writes the prefix for this public key to the given Writer. -// The prefix is used when calculating a signature over this public key. See -// RFC 4880, section 5.2.4. -func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) { - var pLength uint16 - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - pLength += 2 + uint16(len(pk.n.bytes)) - pLength += 2 + uint16(len(pk.e.bytes)) - case PubKeyAlgoDSA: - pLength += 2 + uint16(len(pk.p.bytes)) - pLength += 2 + uint16(len(pk.q.bytes)) - pLength += 2 + uint16(len(pk.g.bytes)) - pLength += 2 + uint16(len(pk.y.bytes)) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - pLength += 2 + uint16(len(pk.p.bytes)) - pLength += 2 + uint16(len(pk.g.bytes)) - pLength += 2 + uint16(len(pk.y.bytes)) - case PubKeyAlgoECDSA: - pLength += uint16(pk.ec.byteLen()) - case PubKeyAlgoECDH: - pLength += uint16(pk.ec.byteLen()) - pLength += uint16(pk.ecdh.byteLen()) - case PubKeyAlgoEdDSA: - pLength += uint16(pk.edk.byteLen()) - default: - panic("unknown public key algorithm") - } - pLength += 6 - h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) - return -} - -func (pk *PublicKey) Serialize(w io.Writer) (err error) { - length := 6 // 6 byte header - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - length += 2 + len(pk.n.bytes) - length += 2 + len(pk.e.bytes) - case PubKeyAlgoDSA: - length += 2 + len(pk.p.bytes) - length += 2 + len(pk.q.bytes) - length += 2 + len(pk.g.bytes) - length += 2 + len(pk.y.bytes) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - length += 2 + len(pk.p.bytes) - length += 2 + len(pk.g.bytes) - length += 2 + len(pk.y.bytes) - case PubKeyAlgoECDSA: - length += pk.ec.byteLen() - case PubKeyAlgoECDH: - length += pk.ec.byteLen() - length += pk.ecdh.byteLen() - case PubKeyAlgoEdDSA: - length += pk.edk.byteLen() - default: - panic("unknown public key algorithm") - } - - packetType := packetTypePublicKey - if pk.IsSubkey { - packetType = packetTypePublicSubkey - } - err = serializeHeader(w, packetType, length) - if err != nil { - return - } - return pk.serializeWithoutHeaders(w) -} - -// serializeWithoutHeaders marshals the PublicKey to w in the form of an -// OpenPGP public key packet, not including the packet header. -func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) { - var buf [6]byte - buf[0] = 4 - t := uint32(pk.CreationTime.Unix()) - buf[1] = byte(t >> 24) - buf[2] = byte(t >> 16) - buf[3] = byte(t >> 8) - buf[4] = byte(t) - buf[5] = byte(pk.PubKeyAlgo) - - _, err = w.Write(buf[:]) - if err != nil { - return - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - return writeMPIs(w, pk.n, pk.e) - case PubKeyAlgoDSA: - return writeMPIs(w, pk.p, pk.q, pk.g, pk.y) - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - return writeMPIs(w, pk.p, pk.g, pk.y) - case PubKeyAlgoECDSA: - return pk.ec.serialize(w) - case PubKeyAlgoEdDSA: - return pk.edk.serialize(w) - case PubKeyAlgoECDH: - if err = pk.ec.serialize(w); err != nil { - return - } - return pk.ecdh.serialize(w) - } - return errors.InvalidArgumentError("bad public-key algorithm") -} - -// CanSign returns true iff this public key can generate signatures -func (pk *PublicKey) CanSign() bool { - return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal -} - -// VerifySignature returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - signed.Write(sig.HashSuffix) - hashBytes := signed.Sum(nil) - - // NOTE(maxtaco) 2016-08-22 - // - // We used to do this: - // - // if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - // return errors.SignatureError("hash tag doesn't match") - // } - // - // But don't do anything in this case. Some GPGs generate bad - // 2-byte hash prefixes, but GPG also doesn't seem to care on - // import. See BrentMaxwell's key. I think it's safe to disable - // this check! - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) - err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)) - if err != nil { - return errors.SignatureError("RSA verification failure") - } - return nil - case PubKeyAlgoDSA: - dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey) - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 - if len(hashBytes) > subgroupSize { - hashBytes = hashBytes[:subgroupSize] - } - if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { - return errors.SignatureError("DSA verification failure") - } - return nil - case PubKeyAlgoECDSA: - ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) - if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) { - return errors.SignatureError("ECDSA verification failure") - } - return nil - case PubKeyAlgoEdDSA: - if !pk.edk.Verify(hashBytes, sig.EdDSASigR, sig.EdDSASigS) { - return errors.SignatureError("EdDSA verification failure") - } - return nil - default: - return errors.SignatureError("Unsupported public key algorithm used in signature") - } - panic("unreachable") -} - -// VerifySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - suffix := make([]byte, 5) - suffix[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) - signed.Write(suffix) - hashBytes := signed.Sum(nil) - - if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - return errors.SignatureError("hash tag doesn't match") - } - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - rsaPublicKey := pk.PublicKey.(*rsa.PublicKey) - if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)); err != nil { - return errors.SignatureError("RSA verification failure") - } - return - case PubKeyAlgoDSA: - dsaPublicKey := pk.PublicKey.(*dsa.PublicKey) - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 - if len(hashBytes) > subgroupSize { - hashBytes = hashBytes[:subgroupSize] - } - if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { - return errors.SignatureError("DSA verification failure") - } - return nil - default: - panic("shouldn't happen") - } - panic("unreachable") -} - -// keySignatureHash returns a Hash of the message that needs to be signed for -// pk to assert a subkey relationship to signed. -func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - updateKeySignatureHash(pk, signed, h) - - return -} - -// updateKeySignatureHash does the actual hash updates for keySignatureHash. -func updateKeySignatureHash(pk, signed signingKey, h hash.Hash) { - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - signed.SerializeSignaturePrefix(h) - signed.serializeWithoutHeaders(h) -} - -// VerifyKeySignature returns nil iff sig is a valid signature, made by this -// public key, of signed. -func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - if err = pk.VerifySignature(h, sig); err != nil { - return err - } - - if sig.FlagSign { - - // BUG(maxtaco) - // - // We should check for more than FlagsSign here, because if - // you read keys.go, we can sometimes use signing subkeys even if they're - // not explicitly flagged as such. However, so doing fails lots of currently - // working tests, so I'm not going to do much here. - // - // In other words, we should have this disjunction in the condition above: - // - // || (!sig.FlagsValid && pk.PubKeyAlgo.CanSign()) { - // - - // Signing subkeys must be cross-signed. See - // https://www.gnupg.org/faq/subkey-cross-certify.html. - if sig.EmbeddedSignature == nil { - return errors.StructuralError("signing subkey is missing cross-signature") - } - // Verify the cross-signature. This is calculated over the same - // data as the main signature, so we cannot just recursively - // call signed.VerifyKeySignature(...) - if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil { - return errors.StructuralError("error while hashing for cross-signature: " + err.Error()) - } - if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil { - return errors.StructuralError("error while verifying cross-signature: " + err.Error()) - } - } - - return nil -} - -func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - return -} - -// VerifyRevocationSignature returns nil iff sig is a valid signature, made by this -// public key. -func (pk *PublicKey) VerifyRevocationSignature(revokedKey *PublicKey, sig *Signature) (err error) { - h, err := keyRevocationHash(revokedKey, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -type teeHash struct { - h hash.Hash -} - -func (t teeHash) Write(b []byte) (n int, err error) { - fmt.Printf("hash -> %s %+v\n", string(b), b) - return t.h.Write(b) -} -func (t teeHash) Sum(b []byte) []byte { return t.h.Sum(b) } -func (t teeHash) Reset() { t.h.Reset() } -func (t teeHash) Size() int { return t.h.Size() } -func (t teeHash) BlockSize() int { return t.h.BlockSize() } - -// userIdSignatureHash returns a Hash of the message that needs to be signed -// to assert that pk is a valid key for id. -func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - updateUserIdSignatureHash(id, pk, h) - - return -} - -// updateUserIdSignatureHash does the actual hash updates for -// userIdSignatureHash. -func updateUserIdSignatureHash(id string, pk *PublicKey, h hash.Hash) { - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - var buf [5]byte - buf[0] = 0xb4 - buf[1] = byte(len(id) >> 24) - buf[2] = byte(len(id) >> 16) - buf[3] = byte(len(id) >> 8) - buf[4] = byte(len(id)) - h.Write(buf[:]) - h.Write([]byte(id)) - - return -} - -// VerifyUserIdSignature returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) { - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -// VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pub, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// KeyIdString returns the public key's fingerprint in capital hex -// (e.g. "6C7EE1B8621CC013"). -func (pk *PublicKey) KeyIdString() string { - return fmt.Sprintf("%X", pk.Fingerprint[12:20]) -} - -// KeyIdShortString returns the short form of public key's fingerprint -// in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). -func (pk *PublicKey) KeyIdShortString() string { - return fmt.Sprintf("%X", pk.Fingerprint[16:20]) -} - -// A parsedMPI is used to store the contents of a big integer, along with the -// bit length that was specified in the original input. This allows the MPI to -// be reserialized exactly. -type parsedMPI struct { - bytes []byte - bitLength uint16 -} - -// writeMPIs is a utility function for serializing several big integers to the -// given Writer. -func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) { - for _, mpi := range mpis { - err = writeMPI(w, mpi.bitLength, mpi.bytes) - if err != nil { - return - } - } - return -} - -// BitLength returns the bit length for the given public key. Used for -// displaying key information, actual buffers and BigInts inside may -// have non-matching different size if the key is invalid. -func (pk *PublicKey) BitLength() (bitLength uint16, err error) { - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - bitLength = pk.n.bitLength - case PubKeyAlgoDSA: - bitLength = pk.p.bitLength - case PubKeyAlgoElGamal, PubKeyAlgoBadElGamal: - bitLength = pk.p.bitLength - case PubKeyAlgoECDH: - ecdhPublicKey := pk.PublicKey.(*ecdh.PublicKey) - bitLength = uint16(ecdhPublicKey.Curve.Params().BitSize) - case PubKeyAlgoECDSA: - ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) - bitLength = uint16(ecdsaPublicKey.Curve.Params().BitSize) - case PubKeyAlgoEdDSA: - // EdDSA only support ed25519 curves right now, just return - // the length. Also, we don't have any PublicKey.Curve object - // to look the size up from. - bitLength = 256 - default: - err = errors.InvalidArgumentError("bad public-key algorithm") - } - return -} - -func (pk *PublicKey) ErrorIfDeprecated() error { - switch pk.PubKeyAlgo { - case PubKeyAlgoBadElGamal: - return errors.DeprecatedKeyError("ElGamal Encrypt or Sign (algo 20) is deprecated") - default: - return nil - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go deleted file mode 100644 index ee22426c0..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/public_key_v3.go +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto" - "crypto/md5" - "crypto/rsa" - "encoding/binary" - "fmt" - "hash" - "io" - "math/big" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// PublicKeyV3 represents older, version 3 public keys. These keys are less secure and -// should not be used for signing or encrypting. They are supported here only for -// parsing version 3 key material and validating signatures. -// See RFC 4880, section 5.5.2. -type PublicKeyV3 struct { - CreationTime time.Time - DaysToExpire uint16 - PubKeyAlgo PublicKeyAlgorithm - PublicKey *rsa.PublicKey - Fingerprint [16]byte - KeyId uint64 - IsSubkey bool - - n, e parsedMPI -} - -// newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey. -// Included here for testing purposes only. RFC 4880, section 5.5.2: -// "an implementation MUST NOT generate a V3 key, but MAY accept it." -func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 { - pk := &PublicKeyV3{ - CreationTime: creationTime, - PublicKey: pub, - n: FromBig(pub.N), - e: FromBig(big.NewInt(int64(pub.E))), - } - - pk.setFingerPrintAndKeyId() - return pk -} - -func (pk *PublicKeyV3) parse(r io.Reader) (err error) { - // RFC 4880, section 5.5.2 - var buf [8]byte - if _, err = readFull(r, buf[:]); err != nil { - return - } - if buf[0] < 2 || buf[0] > 3 { - return errors.UnsupportedError("public key version") - } - pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) - pk.DaysToExpire = binary.BigEndian.Uint16(buf[5:7]) - pk.PubKeyAlgo = PublicKeyAlgorithm(buf[7]) - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - err = pk.parseRSA(r) - default: - err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) - } - if err != nil { - return - } - - pk.setFingerPrintAndKeyId() - return -} - -func (pk *PublicKeyV3) setFingerPrintAndKeyId() { - // RFC 4880, section 12.2 - fingerPrint := md5.New() - fingerPrint.Write(pk.n.bytes) - fingerPrint.Write(pk.e.bytes) - fingerPrint.Sum(pk.Fingerprint[:0]) - pk.KeyId = binary.BigEndian.Uint64(pk.n.bytes[len(pk.n.bytes)-8:]) -} - -// parseRSA parses RSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKeyV3) parseRSA(r io.Reader) (err error) { - if pk.n.bytes, pk.n.bitLength, err = readMPI(r); err != nil { - return - } - if pk.e.bytes, pk.e.bitLength, err = readMPI(r); err != nil { - return - } - - // RFC 4880 Section 12.2 requires the low 8 bytes of the - // modulus to form the key id. - if len(pk.n.bytes) < 8 { - return errors.StructuralError("v3 public key modulus is too short") - } - if len(pk.e.bytes) > 7 { - err = errors.UnsupportedError("large public exponent") - return - } - rsa := &rsa.PublicKey{N: new(big.Int).SetBytes(pk.n.bytes)} - for i := 0; i < len(pk.e.bytes); i++ { - rsa.E <<= 8 - rsa.E |= int(pk.e.bytes[i]) - } - pk.PublicKey = rsa - return -} - -// SerializeSignaturePrefix writes the prefix for this public key to the given Writer. -// The prefix is used when calculating a signature over this public key. See -// RFC 4880, section 5.2.4. -func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { - var pLength uint16 - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - pLength += 2 + uint16(len(pk.n.bytes)) - pLength += 2 + uint16(len(pk.e.bytes)) - default: - panic("unknown public key algorithm") - } - pLength += 6 - w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) - return -} - -func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) { - length := 8 // 8 byte header - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - length += 2 + len(pk.n.bytes) - length += 2 + len(pk.e.bytes) - default: - panic("unknown public key algorithm") - } - - packetType := packetTypePublicKey - if pk.IsSubkey { - packetType = packetTypePublicSubkey - } - if err = serializeHeader(w, packetType, length); err != nil { - return - } - return pk.serializeWithoutHeaders(w) -} - -// serializeWithoutHeaders marshals the PublicKey to w in the form of an -// OpenPGP public key packet, not including the packet header. -func (pk *PublicKeyV3) serializeWithoutHeaders(w io.Writer) (err error) { - var buf [8]byte - // Version 3 - buf[0] = 3 - // Creation time - t := uint32(pk.CreationTime.Unix()) - buf[1] = byte(t >> 24) - buf[2] = byte(t >> 16) - buf[3] = byte(t >> 8) - buf[4] = byte(t) - // Days to expire - buf[5] = byte(pk.DaysToExpire >> 8) - buf[6] = byte(pk.DaysToExpire) - // Public key algorithm - buf[7] = byte(pk.PubKeyAlgo) - - if _, err = w.Write(buf[:]); err != nil { - return - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - return writeMPIs(w, pk.n, pk.e) - } - return errors.InvalidArgumentError("bad public-key algorithm") -} - -// CanSign returns true iff this public key can generate signatures -func (pk *PublicKeyV3) CanSign() bool { - return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly -} - -// VerifySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - - suffix := make([]byte, 5) - suffix[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix())) - signed.Write(suffix) - hashBytes := signed.Sum(nil) - - if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - return errors.SignatureError("hash tag doesn't match") - } - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - if err = rsa.VerifyPKCS1v15(pk.PublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { - return errors.SignatureError("RSA verification failure") - } - return - default: - // V3 public keys only support RSA. - panic("shouldn't happen") - } - panic("unreachable") -} - -// VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, pub *PublicKeyV3, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pk, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// VerifyKeySignatureV3 returns nil iff sig is a valid signature, made by this -// public key, of signed. -func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV3) (err error) { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignatureV3(h, sig) -} - -// userIdSignatureV3Hash returns a Hash of the message that needs to be signed -// to assert that pk is a valid key for id. -func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { - if !hfn.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hfn.New() - - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - h.Write([]byte(id)) - - return -} - -// KeyIdString returns the public key's fingerprint in capital hex -// (e.g. "6C7EE1B8621CC013"). -func (pk *PublicKeyV3) KeyIdString() string { - return fmt.Sprintf("%X", pk.KeyId) -} - -// KeyIdShortString returns the short form of public key's fingerprint -// in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). -func (pk *PublicKeyV3) KeyIdShortString() string { - return fmt.Sprintf("%X", pk.KeyId&0xFFFFFFFF) -} - -// BitLength returns the bit length for the given public key. -func (pk *PublicKeyV3) BitLength() (bitLength uint16, err error) { - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - bitLength = pk.n.bitLength - default: - err = errors.InvalidArgumentError("bad public-key algorithm") - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go deleted file mode 100644 index 957b3b897..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/reader.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "io" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// Reader reads packets from an io.Reader and allows packets to be 'unread' so -// that they result from the next call to Next. -type Reader struct { - q []Packet - readers []io.Reader -} - -// New io.Readers are pushed when a compressed or encrypted packet is processed -// and recursively treated as a new source of packets. However, a carefully -// crafted packet can trigger an infinite recursive sequence of packets. See -// http://mumble.net/~campbell/misc/pgp-quine -// https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-4402 -// This constant limits the number of recursive packets that may be pushed. -const maxReaders = 32 - -// Next returns the most recently unread Packet, or reads another packet from -// the top-most io.Reader. Unknown packet types are skipped. -func (r *Reader) Next() (p Packet, err error) { - if len(r.q) > 0 { - p = r.q[len(r.q)-1] - r.q = r.q[:len(r.q)-1] - return - } - - for len(r.readers) > 0 { - p, err = Read(r.readers[len(r.readers)-1]) - if err == nil { - return - } - if err == io.EOF { - r.readers = r.readers[:len(r.readers)-1] - continue - } - if _, ok := err.(errors.UnknownPacketTypeError); !ok { - return nil, err - } - } - return nil, io.EOF -} - -// Push causes the Reader to start reading from a new io.Reader. When an EOF -// error is seen from the new io.Reader, it is popped and the Reader continues -// to read from the next most recent io.Reader. Push returns a StructuralError -// if pushing the reader would exceed the maximum recursion level, otherwise it -// returns nil. -func (r *Reader) Push(reader io.Reader) (err error) { - if len(r.readers) >= maxReaders { - return errors.StructuralError("too many layers of packets") - } - r.readers = append(r.readers, reader) - return nil -} - -// Unread causes the given Packet to be returned from the next call to Next. -func (r *Reader) Unread(p Packet) { - r.q = append(r.q, p) -} - -func NewReader(r io.Reader) *Reader { - return &Reader{ - q: nil, - readers: []io.Reader{r}, - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go deleted file mode 100644 index e56ab7947..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature.go +++ /dev/null @@ -1,892 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/rsa" - "encoding/binary" - "hash" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -const ( - // See RFC 4880, section 5.2.3.21 for details. - KeyFlagCertify = 1 << iota - KeyFlagSign - KeyFlagEncryptCommunications - KeyFlagEncryptStorage -) - -// Signer can be implemented by application code to do actual signing. -type Signer interface { - hash.Hash - Sign(sig *Signature) error - KeyId() uint64 - PublicKeyAlgo() PublicKeyAlgorithm -} - -// RevocationKey represents designated revoker packet. See RFC 4880 -// section 5.2.3.15 for details. -type RevocationKey struct { - Class byte - PublicKeyAlgo PublicKeyAlgorithm - Fingerprint []byte -} - -// KeyFlagBits holds boolean whether any usage flags were provided in -// the signature and BitField with KeyFlag* flags. -type KeyFlagBits struct { - Valid bool - BitField byte -} - -// Signature represents a signature. See RFC 4880, section 5.2. -type Signature struct { - SigType SignatureType - PubKeyAlgo PublicKeyAlgorithm - Hash crypto.Hash - - // HashSuffix is extra data that is hashed in after the signed data. - HashSuffix []byte - // HashTag contains the first two bytes of the hash for fast rejection - // of bad signed data. - HashTag [2]byte - CreationTime time.Time - - RSASignature parsedMPI - DSASigR, DSASigS parsedMPI - ECDSASigR, ECDSASigS parsedMPI - EdDSASigR, EdDSASigS parsedMPI - - // rawSubpackets contains the unparsed subpackets, in order. - rawSubpackets []outputSubpacket - - // The following are optional so are nil when not included in the - // signature. - - SigLifetimeSecs, KeyLifetimeSecs *uint32 - PreferredSymmetric, PreferredHash, PreferredCompression []uint8 - PreferredKeyServer string - IssuerKeyId *uint64 - IsPrimaryId *bool - IssuerFingerprint []byte - - // FlagsValid is set if any flags were given. See RFC 4880, section - // 5.2.3.21 for details. - FlagsValid bool - FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool - - // RevocationReason is set if this signature has been revoked. - // See RFC 4880, section 5.2.3.23 for details. - RevocationReason *uint8 - RevocationReasonText string - - // PolicyURI is optional. See RFC 4880, Section 5.2.3.20 for details - PolicyURI string - - // Regex is a regex that can match a PGP UID. See RFC 4880, 5.2.3.14 for details - Regex string - - // MDC is set if this signature has a feature packet that indicates - // support for MDC subpackets. - MDC bool - - // EmbeddedSignature, if non-nil, is a signature of the parent key, by - // this key. This prevents an attacker from claiming another's signing - // subkey as their own. - EmbeddedSignature *Signature - - // StubbedOutCriticalError is not fail-stop, since it shouldn't break key parsing - // when appearing in WoT-style cross signatures. But it should prevent a signature - // from being applied to a primary or subkey. - StubbedOutCriticalError error - - // DesignaterRevoker will be present if this signature certifies a - // designated revoking key id (3rd party key that can sign - // revocation for this key). - DesignatedRevoker *RevocationKey - - outSubpackets []outputSubpacket -} - -func (sig *Signature) parse(r io.Reader) (err error) { - // RFC 4880, section 5.2.3 - var buf [5]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - if buf[0] != 4 { - err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) - return - } - - _, err = readFull(r, buf[:5]) - if err != nil { - return - } - sig.SigType = SignatureType(buf[0]) - sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1]) - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - default: - err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) - return - } - - var ok bool - sig.Hash, ok = s2k.HashIdToHash(buf[2]) - if !ok { - return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) - } - - hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4]) - l := 6 + hashedSubpacketsLength - sig.HashSuffix = make([]byte, l+6) - sig.HashSuffix[0] = 4 - copy(sig.HashSuffix[1:], buf[:5]) - hashedSubpackets := sig.HashSuffix[6:l] - _, err = readFull(r, hashedSubpackets) - if err != nil { - return - } - // See RFC 4880, section 5.2.4 - trailer := sig.HashSuffix[l:] - trailer[0] = 4 - trailer[1] = 0xff - trailer[2] = uint8(l >> 24) - trailer[3] = uint8(l >> 16) - trailer[4] = uint8(l >> 8) - trailer[5] = uint8(l) - - err = parseSignatureSubpackets(sig, hashedSubpackets, true) - if err != nil { - return - } - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1]) - unhashedSubpackets := make([]byte, unhashedSubpacketsLength) - _, err = readFull(r, unhashedSubpackets) - if err != nil { - return - } - err = parseSignatureSubpackets(sig, unhashedSubpackets, false) - if err != nil { - return - } - - _, err = readFull(r, sig.HashTag[:2]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) - case PubKeyAlgoDSA: - sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) - } - case PubKeyAlgoEdDSA: - sig.EdDSASigR.bytes, sig.EdDSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.EdDSASigS.bytes, sig.EdDSASigS.bitLength, err = readMPI(r) - } - case PubKeyAlgoECDSA: - sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r) - if err == nil { - sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r) - } - default: - panic("unreachable") - } - return -} - -// parseSignatureSubpackets parses subpackets of the main signature packet. See -// RFC 4880, section 5.2.3.1. -func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) { - for len(subpackets) > 0 { - subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed) - if err != nil { - return - } - } - - if sig.CreationTime.IsZero() { - err = errors.StructuralError("no creation time in signature") - } - - return -} - -type signatureSubpacketType uint8 - -const ( - creationTimeSubpacket signatureSubpacketType = 2 - signatureExpirationSubpacket signatureSubpacketType = 3 - regularExpressionSubpacket signatureSubpacketType = 6 - keyExpirationSubpacket signatureSubpacketType = 9 - prefSymmetricAlgosSubpacket signatureSubpacketType = 11 - revocationKey signatureSubpacketType = 12 - issuerSubpacket signatureSubpacketType = 16 - prefHashAlgosSubpacket signatureSubpacketType = 21 - prefCompressionSubpacket signatureSubpacketType = 22 - prefKeyServerSubpacket signatureSubpacketType = 24 - primaryUserIdSubpacket signatureSubpacketType = 25 - policyURISubpacket signatureSubpacketType = 26 - keyFlagsSubpacket signatureSubpacketType = 27 - reasonForRevocationSubpacket signatureSubpacketType = 29 - featuresSubpacket signatureSubpacketType = 30 - embeddedSignatureSubpacket signatureSubpacketType = 32 - issuerFingerprint signatureSubpacketType = 33 -) - -// parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1. -func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) { - // RFC 4880, section 5.2.3.1 - var ( - length uint32 - packetType signatureSubpacketType - isCritical bool - ) - switch { - case subpacket[0] < 192: - length = uint32(subpacket[0]) - subpacket = subpacket[1:] - case subpacket[0] < 255: - if len(subpacket) < 2 { - goto Truncated - } - length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192 - subpacket = subpacket[2:] - default: - if len(subpacket) < 5 { - goto Truncated - } - length = uint32(subpacket[1])<<24 | - uint32(subpacket[2])<<16 | - uint32(subpacket[3])<<8 | - uint32(subpacket[4]) - subpacket = subpacket[5:] - } - if length > uint32(len(subpacket)) { - goto Truncated - } - rest = subpacket[length:] - subpacket = subpacket[:length] - if len(subpacket) == 0 { - err = errors.StructuralError("zero length signature subpacket") - return - } - packetType = signatureSubpacketType(subpacket[0] & 0x7f) - isCritical = subpacket[0]&0x80 == 0x80 - subpacket = subpacket[1:] - sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket}) - switch packetType { - case creationTimeSubpacket: - if !isHashed { - err = errors.StructuralError("signature creation time in non-hashed area") - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("signature creation time not four bytes") - return - } - t := binary.BigEndian.Uint32(subpacket) - sig.CreationTime = time.Unix(int64(t), 0) - case signatureExpirationSubpacket: - // Signature expiration time, section 5.2.3.10 - if !isHashed { - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("expiration subpacket with bad length") - return - } - sig.SigLifetimeSecs = new(uint32) - *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case keyExpirationSubpacket: - // Key expiration time, section 5.2.3.6 - if !isHashed { - return - } - if len(subpacket) != 4 { - err = errors.StructuralError("key expiration subpacket with bad length") - return - } - sig.KeyLifetimeSecs = new(uint32) - *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case prefSymmetricAlgosSubpacket: - // Preferred symmetric algorithms, section 5.2.3.7 - if !isHashed { - return - } - sig.PreferredSymmetric = make([]byte, len(subpacket)) - copy(sig.PreferredSymmetric, subpacket) - case issuerSubpacket: - // Issuer, section 5.2.3.5 - if len(subpacket) != 8 { - err = errors.StructuralError("issuer subpacket with bad length") - return - } - sig.IssuerKeyId = new(uint64) - *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket) - case prefHashAlgosSubpacket: - // Preferred hash algorithms, section 5.2.3.8 - if !isHashed { - return - } - sig.PreferredHash = make([]byte, len(subpacket)) - copy(sig.PreferredHash, subpacket) - case prefCompressionSubpacket: - // Preferred compression algorithms, section 5.2.3.9 - if !isHashed { - return - } - sig.PreferredCompression = make([]byte, len(subpacket)) - copy(sig.PreferredCompression, subpacket) - case primaryUserIdSubpacket: - // Primary User ID, section 5.2.3.19 - if !isHashed { - return - } - if len(subpacket) != 1 { - err = errors.StructuralError("primary user id subpacket with bad length") - return - } - sig.IsPrimaryId = new(bool) - if subpacket[0] > 0 { - *sig.IsPrimaryId = true - } - case keyFlagsSubpacket: - // Key flags, section 5.2.3.21 - if !isHashed { - return - } - if len(subpacket) == 0 { - err = errors.StructuralError("empty key flags subpacket") - return - } - if subpacket[0] != 0 { - sig.FlagsValid = true - if subpacket[0]&KeyFlagCertify != 0 { - sig.FlagCertify = true - } - if subpacket[0]&KeyFlagSign != 0 { - sig.FlagSign = true - } - if subpacket[0]&KeyFlagEncryptCommunications != 0 { - sig.FlagEncryptCommunications = true - } - if subpacket[0]&KeyFlagEncryptStorage != 0 { - sig.FlagEncryptStorage = true - } - } - case reasonForRevocationSubpacket: - // Reason For Revocation, section 5.2.3.23 - if !isHashed { - return - } - if len(subpacket) == 0 { - err = errors.StructuralError("empty revocation reason subpacket") - return - } - sig.RevocationReason = new(uint8) - *sig.RevocationReason = subpacket[0] - sig.RevocationReasonText = string(subpacket[1:]) - case featuresSubpacket: - // Features subpacket, section 5.2.3.24 specifies a very general - // mechanism for OpenPGP implementations to signal support for new - // features. In practice, the subpacket is used exclusively to - // indicate support for MDC-protected encryption. - sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1 - case embeddedSignatureSubpacket: - // Only usage is in signatures that cross-certify - // signing subkeys. section 5.2.3.26 describes the - // format, with its usage described in section 11.1 - if sig.EmbeddedSignature != nil { - err = errors.StructuralError("Cannot have multiple embedded signatures") - return - } - sig.EmbeddedSignature = new(Signature) - // Embedded signatures are required to be v4 signatures see - // section 12.1. However, we only parse v4 signatures in this - // file anyway. - if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil { - return nil, err - } - if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding { - return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType))) - } - case policyURISubpacket: - // See RFC 4880, Section 5.2.3.20 - sig.PolicyURI = string(subpacket[:]) - case regularExpressionSubpacket: - sig.Regex = string(subpacket[:]) - if isCritical { - sig.StubbedOutCriticalError = errors.UnsupportedError("regex support is stubbed out") - } - case prefKeyServerSubpacket: - sig.PreferredKeyServer = string(subpacket[:]) - case issuerFingerprint: - // The first byte is how many bytes the fingerprint is, but we'll just - // read until the end of the subpacket, so we'll ignore it. - sig.IssuerFingerprint = append([]byte{}, subpacket[1:]...) - case revocationKey: - // Authorizes the specified key to issue revocation signatures - // for a key. - - // TODO: Class octet must have bit 0x80 set. If the bit 0x40 - // is set, then this means that the revocation information is - // sensitive. - sig.DesignatedRevoker = &RevocationKey{ - Class: subpacket[0], - PublicKeyAlgo: PublicKeyAlgorithm(subpacket[1]), - Fingerprint: append([]byte{}, subpacket[2:]...), - } - default: - if isCritical { - err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType))) - return - } - } - return - -Truncated: - err = errors.StructuralError("signature subpacket truncated") - return -} - -// subpacketLengthLength returns the length, in bytes, of an encoded length value. -func subpacketLengthLength(length int) int { - if length < 192 { - return 1 - } - if length < 16320 { - return 2 - } - return 5 -} - -// serializeSubpacketLength marshals the given length into to. -func serializeSubpacketLength(to []byte, length int) int { - // RFC 4880, Section 4.2.2. - if length < 192 { - to[0] = byte(length) - return 1 - } - if length < 16320 { - length -= 192 - to[0] = byte((length >> 8) + 192) - to[1] = byte(length) - return 2 - } - to[0] = 255 - to[1] = byte(length >> 24) - to[2] = byte(length >> 16) - to[3] = byte(length >> 8) - to[4] = byte(length) - return 5 -} - -// subpacketsLength returns the serialized length, in bytes, of the given -// subpackets. -func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - length += subpacketLengthLength(len(subpacket.contents) + 1) - length += 1 // type byte - length += len(subpacket.contents) - } - } - return -} - -// serializeSubpackets marshals the given subpackets into to. -func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - n := serializeSubpacketLength(to, len(subpacket.contents)+1) - to[n] = byte(subpacket.subpacketType) - to = to[1+n:] - n = copy(to, subpacket.contents) - to = to[n:] - } - } - return -} - -// KeyExpired returns whether sig is a self-signature of a key that has -// expired. -func (sig *Signature) KeyExpired(currentTime time.Time) bool { - if sig.KeyLifetimeSecs == nil { - return false - } - expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second) - return currentTime.After(expiry) -} - -// ExpiresBeforeOther checks if other signature has expiration at -// later date than sig. -func (sig *Signature) ExpiresBeforeOther(other *Signature) bool { - if sig.KeyLifetimeSecs == nil { - // This sig never expires, or has infinitely long expiration - // time. - return false - } else if other.KeyLifetimeSecs == nil { - // This sig expires at some non-infinite point, but the other - // sig never expires. - return true - } - - getExpiryDate := func(s *Signature) time.Time { - return s.CreationTime.Add(time.Duration(*s.KeyLifetimeSecs) * time.Second) - } - - return getExpiryDate(other).After(getExpiryDate(sig)) -} - -// buildHashSuffix constructs the HashSuffix member of sig in preparation for signing. -func (sig *Signature) buildHashSuffix() (err error) { - hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true) - - var ok bool - l := 6 + hashedSubpacketsLen - sig.HashSuffix = make([]byte, l+6) - sig.HashSuffix[0] = 4 - sig.HashSuffix[1] = uint8(sig.SigType) - sig.HashSuffix[2] = uint8(sig.PubKeyAlgo) - sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash) - if !ok { - sig.HashSuffix = nil - return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash))) - } - sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8) - sig.HashSuffix[5] = byte(hashedSubpacketsLen) - serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true) - trailer := sig.HashSuffix[l:] - trailer[0] = 4 - trailer[1] = 0xff - trailer[2] = byte(l >> 24) - trailer[3] = byte(l >> 16) - trailer[4] = byte(l >> 8) - trailer[5] = byte(l) - return -} - -func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) { - err = sig.buildHashSuffix() - if err != nil { - return - } - - h.Write(sig.HashSuffix) - digest = h.Sum(nil) - copy(sig.HashTag[:], digest) - return -} - -// Sign signs a message with a private key. The hash, h, must contain -// the hash of the message to be signed and will be mutated by this function. -// On success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) { - signer, hashIsSigner := h.(Signer) - - if !hashIsSigner && (priv == nil || priv.PrivateKey == nil) { - err = errors.InvalidArgumentError("attempting to sign with nil PrivateKey") - return - } - - sig.outSubpackets = sig.buildSubpackets() - digest, err := sig.signPrepareHash(h) - if err != nil { - return - } - - if hashIsSigner { - err = signer.Sign(sig) - return - } - - // Parameter check, if this is wrong we will make a signature but - // not serialize it later. - if sig.PubKeyAlgo != priv.PubKeyAlgo { - err = errors.InvalidArgumentError("signature pub key algo does not match priv key") - return - } - - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest) - sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes)) - case PubKeyAlgoDSA: - dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) - - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8 - if len(digest) > subgroupSize { - digest = digest[:subgroupSize] - } - r, s, err := dsa.Sign(config.Random(), dsaPriv, digest) - if err != nil { - return err - } - sig.DSASigR.bytes = r.Bytes() - sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes)) - sig.DSASigS.bytes = s.Bytes() - sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) - case PubKeyAlgoECDSA: - r, s, err := ecdsa.Sign(config.Random(), priv.PrivateKey.(*ecdsa.PrivateKey), digest) - if err != nil { - return err - } - sig.ECDSASigR = FromBig(r) - sig.ECDSASigS = FromBig(s) - case PubKeyAlgoEdDSA: - r, s, err := priv.PrivateKey.(*EdDSAPrivateKey).Sign(digest) - if err != nil { - return err - } - sig.EdDSASigR = FromBytes(r) - sig.EdDSASigS = FromBytes(s) - default: - err = errors.UnsupportedError("public key algorithm for signing: " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - - return -} - -// SignUserId computes a signature from priv, asserting that pub is a valid -// key for the identity id. On success, the signature is stored in sig. Call -// Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// SignUserIdWithSigner computes a signature from priv, asserting that pub is a -// valid key for the identity id. On success, the signature is stored in sig. -// Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignUserIdWithSigner(id string, pub *PublicKey, s Signer, config *Config) error { - updateUserIdSignatureHash(id, pub, s) - - return sig.Sign(s, nil, config) -} - -// SignKey computes a signature from priv, asserting that pub is a subkey. On -// success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// SignKeyWithSigner computes a signature using s, asserting that -// signeePubKey is a subkey. On success, the signature is stored in sig. Call -// Serialize to write it out. If config is nil, sensible defaults will be used. -func (sig *Signature) SignKeyWithSigner(signeePubKey *PublicKey, signerPubKey *PublicKey, s Signer, config *Config) error { - updateKeySignatureHash(signerPubKey, signeePubKey, s) - - return sig.Sign(s, nil, config) -} - -// Serialize marshals sig to w. Sign, SignUserId or SignKey must have been -// called first. -func (sig *Signature) Serialize(w io.Writer) (err error) { - if len(sig.outSubpackets) == 0 { - sig.outSubpackets = sig.rawSubpackets - } - if sig.RSASignature.bytes == nil && - sig.DSASigR.bytes == nil && - sig.ECDSASigR.bytes == nil && - sig.EdDSASigR.bytes == nil { - return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") - } - - sigLength := 0 - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sigLength = 2 + len(sig.RSASignature.bytes) - case PubKeyAlgoDSA: - sigLength = 2 + len(sig.DSASigR.bytes) - sigLength += 2 + len(sig.DSASigS.bytes) - case PubKeyAlgoEdDSA: - sigLength = 2 + len(sig.EdDSASigR.bytes) - sigLength += 2 + len(sig.EdDSASigS.bytes) - case PubKeyAlgoECDSA: - sigLength = 2 + len(sig.ECDSASigR.bytes) - sigLength += 2 + len(sig.ECDSASigS.bytes) - default: - panic("impossible") - } - - unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false) - length := len(sig.HashSuffix) - 6 /* trailer not included */ + - 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen + - 2 /* hash tag */ + sigLength - err = serializeHeader(w, packetTypeSignature, length) - if err != nil { - return - } - - _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6]) - if err != nil { - return - } - - unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen) - unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8) - unhashedSubpackets[1] = byte(unhashedSubpacketsLen) - serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false) - - _, err = w.Write(unhashedSubpackets) - if err != nil { - return - } - _, err = w.Write(sig.HashTag[:]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - err = writeMPIs(w, sig.RSASignature) - case PubKeyAlgoDSA: - err = writeMPIs(w, sig.DSASigR, sig.DSASigS) - case PubKeyAlgoEdDSA: - err = writeMPIs(w, sig.EdDSASigR, sig.EdDSASigS) - case PubKeyAlgoECDSA: - err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS) - default: - panic("impossible") - } - return -} - -// outputSubpacket represents a subpacket to be marshaled. -type outputSubpacket struct { - hashed bool // true if this subpacket is in the hashed area. - subpacketType signatureSubpacketType - isCritical bool - contents []byte -} - -func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { - creationTime := make([]byte, 4) - binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix())) - subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime}) - - if sig.IssuerKeyId != nil { - keyId := make([]byte, 8) - binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId) - subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId}) - } - - if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 { - sigLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime}) - } - - // Key flags may only appear in self-signatures or certification signatures. - - if sig.FlagsValid { - subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{sig.GetKeyFlags().BitField}}) - } - - // The following subpackets may only appear in self-signatures - - if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 { - keyLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime}) - } - - if sig.IsPrimaryId != nil && *sig.IsPrimaryId { - subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}}) - } - - if len(sig.PreferredSymmetric) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric}) - } - - if len(sig.PreferredHash) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash}) - } - - if len(sig.PreferredCompression) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression}) - } - - return -} - -func (sig *Signature) GetKeyFlags() (ret KeyFlagBits) { - if !sig.FlagsValid { - return ret - } - - ret.Valid = true - if sig.FlagCertify { - ret.BitField |= KeyFlagCertify - } - if sig.FlagSign { - ret.BitField |= KeyFlagSign - } - if sig.FlagEncryptCommunications { - ret.BitField |= KeyFlagEncryptCommunications - } - if sig.FlagEncryptStorage { - ret.BitField |= KeyFlagEncryptStorage - } - return ret -} - -func (f *KeyFlagBits) HasFlagCertify() bool { - return f.BitField&KeyFlagCertify != 0 -} - -func (f *KeyFlagBits) HasFlagSign() bool { - return f.BitField&KeyFlagSign != 0 -} - -func (f *KeyFlagBits) HasFlagEncryptCommunications() bool { - return f.BitField&KeyFlagEncryptCommunications != 0 -} - -func (f *KeyFlagBits) HasFlagEncryptStorage() bool { - return f.BitField&KeyFlagEncryptStorage != 0 -} - -func (f *KeyFlagBits) Merge(other KeyFlagBits) { - if other.Valid { - f.Valid = true - f.BitField |= other.BitField - } -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go deleted file mode 100644 index dfca651be..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/signature_v3.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto" - "encoding/binary" - "fmt" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// SignatureV3 represents older version 3 signatures. These signatures are less secure -// than version 4 and should not be used to create new signatures. They are included -// here for backwards compatibility to read and validate with older key material. -// See RFC 4880, section 5.2.2. -type SignatureV3 struct { - SigType SignatureType - CreationTime time.Time - IssuerKeyId uint64 - PubKeyAlgo PublicKeyAlgorithm - Hash crypto.Hash - HashTag [2]byte - - RSASignature parsedMPI - DSASigR, DSASigS parsedMPI -} - -func (sig *SignatureV3) parse(r io.Reader) (err error) { - // RFC 4880, section 5.2.2 - var buf [8]byte - if _, err = readFull(r, buf[:1]); err != nil { - return - } - if buf[0] < 2 || buf[0] > 3 { - err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) - return - } - if _, err = readFull(r, buf[:1]); err != nil { - return - } - if buf[0] != 5 { - err = errors.UnsupportedError( - "invalid hashed material length " + strconv.Itoa(int(buf[0]))) - return - } - - // Read hashed material: signature type + creation time - if _, err = readFull(r, buf[:5]); err != nil { - return - } - sig.SigType = SignatureType(buf[0]) - t := binary.BigEndian.Uint32(buf[1:5]) - sig.CreationTime = time.Unix(int64(t), 0) - - // Eight-octet Key ID of signer. - if _, err = readFull(r, buf[:8]); err != nil { - return - } - sig.IssuerKeyId = binary.BigEndian.Uint64(buf[:]) - - // Public-key and hash algorithm - if _, err = readFull(r, buf[:2]); err != nil { - return - } - sig.PubKeyAlgo = PublicKeyAlgorithm(buf[0]) - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA: - default: - err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) - return - } - var ok bool - if sig.Hash, ok = s2k.HashIdToHash(buf[1]); !ok { - return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) - } - - // Two-octet field holding left 16 bits of signed hash value. - if _, err = readFull(r, sig.HashTag[:2]); err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r) - case PubKeyAlgoDSA: - if sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r); err != nil { - return - } - sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r) - default: - panic("unreachable") - } - return -} - -// Serialize marshals sig to w. Sign, SignUserId or SignKey must have been -// called first. -func (sig *SignatureV3) Serialize(w io.Writer) (err error) { - buf := make([]byte, 8) - - // Write the sig type and creation time - buf[0] = byte(sig.SigType) - binary.BigEndian.PutUint32(buf[1:5], uint32(sig.CreationTime.Unix())) - if _, err = w.Write(buf[:5]); err != nil { - return - } - - // Write the issuer long key ID - binary.BigEndian.PutUint64(buf[:8], sig.IssuerKeyId) - if _, err = w.Write(buf[:8]); err != nil { - return - } - - // Write public key algorithm, hash ID, and hash value - buf[0] = byte(sig.PubKeyAlgo) - hashId, ok := s2k.HashToHashId(sig.Hash) - if !ok { - return errors.UnsupportedError(fmt.Sprintf("hash function %v", sig.Hash)) - } - buf[1] = hashId - copy(buf[2:4], sig.HashTag[:]) - if _, err = w.Write(buf[:4]); err != nil { - return - } - - if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil { - return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - err = writeMPIs(w, sig.RSASignature) - case PubKeyAlgoDSA: - err = writeMPIs(w, sig.DSASigR, sig.DSASigS) - default: - panic("impossible") - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go deleted file mode 100644 index b92c1d778..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetric_key_encrypted.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "crypto/cipher" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// This is the largest session key that we'll support. Since no 512-bit cipher -// has even been seriously used, this is comfortably large. -const maxSessionKeySizeInBytes = 64 - -// SymmetricKeyEncrypted represents a passphrase protected session key. See RFC -// 4880, section 5.3. -type SymmetricKeyEncrypted struct { - CipherFunc CipherFunction - s2k func(out, in []byte) - encryptedKey []byte -} - -const symmetricKeyEncryptedVersion = 4 - -func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error { - // RFC 4880, section 5.3. - var buf [2]byte - if _, err := readFull(r, buf[:]); err != nil { - return err - } - if buf[0] != symmetricKeyEncryptedVersion { - return errors.UnsupportedError("SymmetricKeyEncrypted version") - } - ske.CipherFunc = CipherFunction(buf[1]) - - if ske.CipherFunc.KeySize() == 0 { - return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1]))) - } - - var err error - ske.s2k, err = s2k.Parse(r) - if err != nil { - return err - } - if ske.s2k == nil { - return errors.UnsupportedError("can't use dummy S2K for symmetric key encryption") - } - - encryptedKey := make([]byte, maxSessionKeySizeInBytes) - // The session key may follow. We just have to try and read to find - // out. If it exists then we limit it to maxSessionKeySizeInBytes. - n, err := readFull(r, encryptedKey) - if err != nil && err != io.ErrUnexpectedEOF { - return err - } - - if n != 0 { - if n == maxSessionKeySizeInBytes { - return errors.UnsupportedError("oversized encrypted session key") - } - ske.encryptedKey = encryptedKey[:n] - } - - return nil -} - -// Decrypt attempts to decrypt an encrypted session key and returns the key and -// the cipher to use when decrypting a subsequent Symmetrically Encrypted Data -// packet. -func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) { - key := make([]byte, ske.CipherFunc.KeySize()) - ske.s2k(key, passphrase) - - if len(ske.encryptedKey) == 0 { - return key, ske.CipherFunc, nil - } - - // the IV is all zeros - iv := make([]byte, ske.CipherFunc.blockSize()) - c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv) - plaintextKey := make([]byte, len(ske.encryptedKey)) - c.XORKeyStream(plaintextKey, ske.encryptedKey) - cipherFunc := CipherFunction(plaintextKey[0]) - if cipherFunc.blockSize() == 0 { - return nil, ske.CipherFunc, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) - } - plaintextKey = plaintextKey[1:] - if l, cipherKeySize := len(plaintextKey), cipherFunc.KeySize(); l != cipherFunc.KeySize() { - return nil, cipherFunc, errors.StructuralError("length of decrypted key (" + strconv.Itoa(l) + ") " + - "not equal to cipher keysize (" + strconv.Itoa(cipherKeySize) + ")") - } - return plaintextKey, cipherFunc, nil -} - -// SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The -// packet contains a random session key, encrypted by a key derived from the -// given passphrase. The session key is returned and must be passed to -// SerializeSymmetricallyEncrypted. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) { - cipherFunc := config.Cipher() - keySize := cipherFunc.KeySize() - if keySize == 0 { - return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) - } - - s2kBuf := new(bytes.Buffer) - keyEncryptingKey := make([]byte, keySize) - // s2k.Serialize salts and stretches the passphrase, and writes the - // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf. - err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()}) - if err != nil { - return - } - s2kBytes := s2kBuf.Bytes() - - packetLength := 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize - err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength) - if err != nil { - return - } - - var buf [2]byte - buf[0] = symmetricKeyEncryptedVersion - buf[1] = byte(cipherFunc) - _, err = w.Write(buf[:]) - if err != nil { - return - } - _, err = w.Write(s2kBytes) - if err != nil { - return - } - - sessionKey := make([]byte, keySize) - _, err = io.ReadFull(config.Random(), sessionKey) - if err != nil { - return - } - iv := make([]byte, cipherFunc.blockSize()) - c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv) - encryptedCipherAndKey := make([]byte, keySize+1) - c.XORKeyStream(encryptedCipherAndKey, buf[1:]) - c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey) - _, err = w.Write(encryptedCipherAndKey) - if err != nil { - return - } - - key = sessionKey - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go deleted file mode 100644 index fd4f8f015..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/symmetrically_encrypted.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto/cipher" - "crypto/sha1" - "crypto/subtle" - "hash" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/errors" -) - -// SymmetricallyEncrypted represents a symmetrically encrypted byte string. The -// encrypted contents will consist of more OpenPGP packets. See RFC 4880, -// sections 5.7 and 5.13. -type SymmetricallyEncrypted struct { - MDC bool // true iff this is a type 18 packet and thus has an embedded MAC. - contents io.Reader - prefix []byte -} - -const symmetricallyEncryptedVersion = 1 - -func (se *SymmetricallyEncrypted) parse(r io.Reader) error { - if se.MDC { - // See RFC 4880, section 5.13. - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - if buf[0] != symmetricallyEncryptedVersion { - return errors.UnsupportedError("unknown SymmetricallyEncrypted version") - } - } - se.contents = r - return nil -} - -// Decrypt returns a ReadCloser, from which the decrypted contents of the -// packet can be read. An incorrect key can, with high probability, be detected -// immediately and this will result in a KeyIncorrect error being returned. -func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) { - keySize := c.KeySize() - if keySize == 0 { - return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c))) - } - if len(key) != keySize { - return nil, errors.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length") - } - - if se.prefix == nil { - se.prefix = make([]byte, c.blockSize()+2) - _, err := readFull(se.contents, se.prefix) - if err != nil { - return nil, err - } - } else if len(se.prefix) != c.blockSize()+2 { - return nil, errors.InvalidArgumentError("can't try ciphers with different block lengths") - } - - ocfbResync := OCFBResync - if se.MDC { - // MDC packets use a different form of OCFB mode. - ocfbResync = OCFBNoResync - } - - s := NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync) - if s == nil { - return nil, errors.ErrKeyIncorrect - } - - plaintext := cipher.StreamReader{S: s, R: se.contents} - - if se.MDC { - // MDC packets have an embedded hash that we need to check. - h := sha1.New() - h.Write(se.prefix) - return &seMDCReader{in: plaintext, h: h}, nil - } - - // Otherwise, we just need to wrap plaintext so that it's a valid ReadCloser. - return seReader{plaintext}, nil -} - -// seReader wraps an io.Reader with a no-op Close method. -type seReader struct { - in io.Reader -} - -func (ser seReader) Read(buf []byte) (int, error) { - return ser.in.Read(buf) -} - -func (ser seReader) Close() error { - return nil -} - -const mdcTrailerSize = 1 /* tag byte */ + 1 /* length byte */ + sha1.Size - -// An seMDCReader wraps an io.Reader, maintains a running hash and keeps hold -// of the most recent 22 bytes (mdcTrailerSize). Upon EOF, those bytes form an -// MDC packet containing a hash of the previous contents which is checked -// against the running hash. See RFC 4880, section 5.13. -type seMDCReader struct { - in io.Reader - h hash.Hash - trailer [mdcTrailerSize]byte - scratch [mdcTrailerSize]byte - trailerUsed int - error bool - eof bool -} - -func (ser *seMDCReader) Read(buf []byte) (n int, err error) { - if ser.error { - err = io.ErrUnexpectedEOF - return - } - if ser.eof { - err = io.EOF - return - } - - // If we haven't yet filled the trailer buffer then we must do that - // first. - for ser.trailerUsed < mdcTrailerSize { - n, err = ser.in.Read(ser.trailer[ser.trailerUsed:]) - ser.trailerUsed += n - if err == io.EOF { - if ser.trailerUsed != mdcTrailerSize { - n = 0 - err = io.ErrUnexpectedEOF - ser.error = true - return - } - ser.eof = true - n = 0 - return - } - - if err != nil { - n = 0 - return - } - } - - // If it's a short read then we read into a temporary buffer and shift - // the data into the caller's buffer. - if len(buf) <= mdcTrailerSize { - n, err = readFull(ser.in, ser.scratch[:len(buf)]) - copy(buf, ser.trailer[:n]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], ser.trailer[n:]) - copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:]) - if n < len(buf) { - ser.eof = true - err = io.EOF - } - return - } - - n, err = ser.in.Read(buf[mdcTrailerSize:]) - copy(buf, ser.trailer[:]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], buf[n:]) - - if err == io.EOF { - ser.eof = true - } - return -} - -// This is a new-format packet tag byte for a type 19 (MDC) packet. -const mdcPacketTagByte = byte(0x80) | 0x40 | 19 - -func (ser *seMDCReader) Close() error { - if ser.error { - return errors.SignatureError("error during reading") - } - - for !ser.eof { - // We haven't seen EOF so we need to read to the end - var buf [1024]byte - _, err := ser.Read(buf[:]) - if err == io.EOF { - break - } - if err != nil { - return errors.SignatureError("error during reading") - } - } - - if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size { - return errors.SignatureError("MDC packet not found") - } - ser.h.Write(ser.trailer[:2]) - - final := ser.h.Sum(nil) - if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 { - return errors.SignatureError("hash mismatch") - } - return nil -} - -// An seMDCWriter writes through to an io.WriteCloser while maintains a running -// hash of the data written. On close, it emits an MDC packet containing the -// running hash. -type seMDCWriter struct { - w io.WriteCloser - h hash.Hash -} - -func (w *seMDCWriter) Write(buf []byte) (n int, err error) { - w.h.Write(buf) - return w.w.Write(buf) -} - -func (w *seMDCWriter) Close() (err error) { - var buf [mdcTrailerSize]byte - - buf[0] = mdcPacketTagByte - buf[1] = sha1.Size - w.h.Write(buf[:2]) - digest := w.h.Sum(nil) - copy(buf[2:], digest) - - _, err = w.w.Write(buf[:]) - if err != nil { - return - } - return w.w.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -// SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet -// to w and returns a WriteCloser to which the to-be-encrypted packets can be -// written. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte, config *Config) (contents io.WriteCloser, err error) { - if c.KeySize() != len(key) { - return nil, errors.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length") - } - writeCloser := noOpCloser{w} - ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC) - if err != nil { - return - } - - _, err = ciphertext.Write([]byte{symmetricallyEncryptedVersion}) - if err != nil { - return - } - - block := c.new(key) - blockSize := block.BlockSize() - iv := make([]byte, blockSize) - _, err = config.Random().Read(iv) - if err != nil { - return - } - s, prefix := NewOCFBEncrypter(block, iv, OCFBNoResync) - _, err = ciphertext.Write(prefix) - if err != nil { - return - } - plaintext := cipher.StreamWriter{S: s, W: ciphertext} - - h := sha1.New() - h.Write(iv) - h.Write(iv[blockSize-2:]) - contents = &seMDCWriter{w: plaintext, h: h} - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go deleted file mode 100644 index 96a2b382a..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/userattribute.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "bytes" - "image" - "image/jpeg" - "io" - "io/ioutil" -) - -const UserAttrImageSubpacket = 1 - -// UserAttribute is capable of storing other types of data about a user -// beyond name, email and a text comment. In practice, user attributes are typically used -// to store a signed thumbnail photo JPEG image of the user. -// See RFC 4880, section 5.12. -type UserAttribute struct { - Contents []*OpaqueSubpacket -} - -// NewUserAttributePhoto creates a user attribute packet -// containing the given images. -func NewUserAttributePhoto(photos ...image.Image) (uat *UserAttribute, err error) { - uat = new(UserAttribute) - for _, photo := range photos { - var buf bytes.Buffer - // RFC 4880, Section 5.12.1. - data := []byte{ - 0x10, 0x00, // Little-endian image header length (16 bytes) - 0x01, // Image header version 1 - 0x01, // JPEG - 0, 0, 0, 0, // 12 reserved octets, must be all zero. - 0, 0, 0, 0, - 0, 0, 0, 0} - if _, err = buf.Write(data); err != nil { - return - } - if err = jpeg.Encode(&buf, photo, nil); err != nil { - return - } - uat.Contents = append(uat.Contents, &OpaqueSubpacket{ - SubType: UserAttrImageSubpacket, - Contents: buf.Bytes()}) - } - return -} - -// NewUserAttribute creates a new user attribute packet containing the given subpackets. -func NewUserAttribute(contents ...*OpaqueSubpacket) *UserAttribute { - return &UserAttribute{Contents: contents} -} - -func (uat *UserAttribute) parse(r io.Reader) (err error) { - // RFC 4880, section 5.13 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uat.Contents, err = OpaqueSubpackets(b) - return -} - -// Serialize marshals the user attribute to w in the form of an OpenPGP packet, including -// header. -func (uat *UserAttribute) Serialize(w io.Writer) (err error) { - var buf bytes.Buffer - for _, sp := range uat.Contents { - sp.Serialize(&buf) - } - if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { - return err - } - _, err = w.Write(buf.Bytes()) - return -} - -// ImageData returns zero or more byte slices, each containing -// JPEG File Interchange Format (JFIF), for each photo in the -// the user attribute packet. -func (uat *UserAttribute) ImageData() (imageData [][]byte) { - for _, sp := range uat.Contents { - if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { - imageData = append(imageData, sp.Contents[16:]) - } - } - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go b/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go deleted file mode 100644 index d6bea7d4a..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/packet/userid.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "io" - "io/ioutil" - "strings" -) - -// UserId contains text that is intended to represent the name and email -// address of the key holder. See RFC 4880, section 5.11. By convention, this -// takes the form "Full Name (Comment) " -type UserId struct { - Id string // By convention, this takes the form "Full Name (Comment) " which is split out in the fields below. - - Name, Comment, Email string -} - -func hasInvalidCharacters(s string) bool { - for _, c := range s { - switch c { - case '(', ')', '<', '>', 0: - return true - } - } - return false -} - -// NewUserId returns a UserId or nil if any of the arguments contain invalid -// characters. The invalid characters are '\x00', '(', ')', '<' and '>' -func NewUserId(name, comment, email string) *UserId { - // RFC 4880 doesn't deal with the structure of userid strings; the - // name, comment and email form is just a convention. However, there's - // no convention about escaping the metacharacters and GPG just refuses - // to create user ids where, say, the name contains a '('. We mirror - // this behaviour. - - if hasInvalidCharacters(name) || hasInvalidCharacters(comment) || hasInvalidCharacters(email) { - return nil - } - - uid := new(UserId) - uid.Name, uid.Comment, uid.Email = name, comment, email - uid.Id = name - if len(comment) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "(" - uid.Id += comment - uid.Id += ")" - } - if len(email) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "<" - uid.Id += email - uid.Id += ">" - } - return uid -} - -func (uid *UserId) parse(r io.Reader) (err error) { - // RFC 4880, section 5.11 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uid.Id = string(b) - uid.Name, uid.Comment, uid.Email = parseUserId(uid.Id) - return -} - -// Serialize marshals uid to w in the form of an OpenPGP packet, including -// header. -func (uid *UserId) Serialize(w io.Writer) error { - err := serializeHeader(w, packetTypeUserId, len(uid.Id)) - if err != nil { - return err - } - _, err = w.Write([]byte(uid.Id)) - return err -} - -// parseUserId extracts the name, comment and email from a user id string that -// is formatted as "Full Name (Comment) ". -func parseUserId(id string) (name, comment, email string) { - var n, c, e struct { - start, end int - } - var state int - - for offset, rune := range id { - switch state { - case 0: - // Entering name - n.start = offset - state = 1 - fallthrough - case 1: - // In name - if rune == '(' { - state = 2 - n.end = offset - } else if rune == '<' { - state = 5 - n.end = offset - } - case 2: - // Entering comment - c.start = offset - state = 3 - fallthrough - case 3: - // In comment - if rune == ')' { - state = 4 - c.end = offset - } - case 4: - // Between comment and email - if rune == '<' { - state = 5 - } - case 5: - // Entering email - e.start = offset - state = 6 - fallthrough - case 6: - // In email - if rune == '>' { - state = 7 - e.end = offset - } - default: - // After email - } - } - switch state { - case 1: - // ended in the name - n.end = len(id) - case 3: - // ended in comment - c.end = len(id) - case 6: - // ended in email - e.end = len(id) - } - - name = strings.TrimSpace(id[n.start:n.end]) - comment = strings.TrimSpace(id[c.start:c.end]) - email = strings.TrimSpace(id[e.start:e.end]) - return -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/patch.sh b/vendor/github.com/keybase/go-crypto/openpgp/patch.sh deleted file mode 100644 index 23cacc83d..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/patch.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -patch < sig-v3.patch -patch < s2k-gnu-dummy.patch -find . -type f -name '*.go' -exec sed -i'' -e 's/golang.org\/x\/crypto\/openpgp/github.com\/keybase\/go-crypto\/openpgp/' {} \; -find . -type f -name '*.go-e' -exec rm {} \; -go test ./... diff --git a/vendor/github.com/keybase/go-crypto/openpgp/read.go b/vendor/github.com/keybase/go-crypto/openpgp/read.go deleted file mode 100644 index 790630e55..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/read.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package openpgp implements high level operations on OpenPGP messages. -package openpgp // import "github.com/keybase/go-crypto/openpgp" - -import ( - "crypto" - "crypto/hmac" - _ "crypto/sha256" - "hash" - "io" - "strconv" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// SignatureType is the armor type for a PGP signature. -var SignatureType = "PGP SIGNATURE" - -// readArmored reads an armored block with the given type. -func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { - block, err := armor.Decode(r) - if err != nil { - return - } - - if block.Type != expectedType { - return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) - } - - return block.Body, nil -} - -// MessageDetails contains the result of parsing an OpenPGP encrypted and/or -// signed message. -type MessageDetails struct { - IsEncrypted bool // true if the message was encrypted. - EncryptedToKeyIds []uint64 // the list of recipient key ids. - IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. - DecryptedWith Key // the private key used to decrypt the message, if any. - IsSigned bool // true if the message is signed. - SignedByKeyId uint64 // the key id of the signer, if any. - SignedBy *Key // the key of the signer, if available. - LiteralData *packet.LiteralData // the metadata of the contents - UnverifiedBody io.Reader // the contents of the message. - - // If IsSigned is true and SignedBy is non-zero then the signature will - // be verified as UnverifiedBody is read. The signature cannot be - // checked until the whole of UnverifiedBody is read so UnverifiedBody - // must be consumed until EOF before the data can trusted. Even if a - // message isn't signed (or the signer is unknown) the data may contain - // an authentication code that is only checked once UnverifiedBody has - // been consumed. Once EOF has been seen, the following fields are - // valid. (An authentication code failure is reported as a - // SignatureError error when reading from UnverifiedBody.) - SignatureError error // nil if the signature is good. - Signature *packet.Signature // the signature packet itself, if v4 (default) - SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature - - // Does the Message include multiple signatures? Also called "nested signatures". - MultiSig bool - - decrypted io.ReadCloser -} - -// A PromptFunction is used as a callback by functions that may need to decrypt -// a private key, or prompt for a passphrase. It is called with a list of -// acceptable, encrypted private keys and a boolean that indicates whether a -// passphrase is usable. It should either decrypt a private key or return a -// passphrase to try. If the decrypted private key or given passphrase isn't -// correct, the function will be called again, forever. Any error returned will -// be passed up. -type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) - -// A keyEnvelopePair is used to store a private key with the envelope that -// contains a symmetric key, encrypted with that key. -type keyEnvelopePair struct { - key Key - encryptedKey *packet.EncryptedKey -} - -// ReadMessage parses an OpenPGP message that may be signed and/or encrypted. -// The given KeyRing should contain both public keys (for signature -// verification) and, possibly encrypted, private keys for decrypting. -// If config is nil, sensible defaults will be used. -func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { - var p packet.Packet - - var symKeys []*packet.SymmetricKeyEncrypted - var pubKeys []keyEnvelopePair - var se *packet.SymmetricallyEncrypted - - packets := packet.NewReader(r) - md = new(MessageDetails) - md.IsEncrypted = true - - // The message, if encrypted, starts with a number of packets - // containing an encrypted decryption key. The decryption key is either - // encrypted to a public key, or with a passphrase. This loop - // collects these packets. -ParsePackets: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.SymmetricKeyEncrypted: - // This packet contains the decryption key encrypted with a passphrase. - md.IsSymmetricallyEncrypted = true - symKeys = append(symKeys, p) - case *packet.EncryptedKey: - // This packet contains the decryption key encrypted to a public key. - md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) - switch p.Algo { - case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH: - break - default: - continue - } - var keys []Key - if p.KeyId == 0 { - keys = keyring.DecryptionKeys() - } else { - keys = keyring.KeysById(p.KeyId, nil) - } - for _, k := range keys { - pubKeys = append(pubKeys, keyEnvelopePair{k, p}) - } - case *packet.SymmetricallyEncrypted: - se = p - break ParsePackets - case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: - // This message isn't encrypted. - if len(symKeys) != 0 || len(pubKeys) != 0 { - return nil, errors.StructuralError("key material not followed by encrypted message") - } - packets.Unread(p) - return readSignedMessage(packets, nil, keyring) - } - } - - var candidates []Key - var decrypted io.ReadCloser - - // Now that we have the list of encrypted keys we need to decrypt at - // least one of them or, if we cannot, we need to call the prompt - // function so that it can decrypt a key or give us a passphrase. -FindKey: - for { - // See if any of the keys already have a private key available - candidates = candidates[:0] - candidateFingerprints := make(map[string]bool) - - for _, pk := range pubKeys { - if pk.key.PrivateKey == nil { - continue - } - if !pk.key.PrivateKey.Encrypted { - if len(pk.encryptedKey.Key) == 0 { - pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) - } - if len(pk.encryptedKey.Key) == 0 { - continue - } - decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) - if err != nil && err != errors.ErrKeyIncorrect { - return nil, err - } - if decrypted != nil { - md.DecryptedWith = pk.key - break FindKey - } - } else { - fpr := string(pk.key.PublicKey.Fingerprint[:]) - if v := candidateFingerprints[fpr]; v { - continue - } - candidates = append(candidates, pk.key) - candidateFingerprints[fpr] = true - } - } - - if len(candidates) == 0 && len(symKeys) == 0 { - return nil, errors.ErrKeyIncorrect - } - - if prompt == nil { - return nil, errors.ErrKeyIncorrect - } - - passphrase, err := prompt(candidates, len(symKeys) != 0) - if err != nil { - return nil, err - } - - // Try the symmetric passphrase first - if len(symKeys) != 0 && passphrase != nil { - for _, s := range symKeys { - key, cipherFunc, err := s.Decrypt(passphrase) - if err == nil { - decrypted, err = se.Decrypt(cipherFunc, key) - if err != nil && err != errors.ErrKeyIncorrect { - return nil, err - } - if decrypted != nil { - break FindKey - } - } - - } - } - } - - md.decrypted = decrypted - if err := packets.Push(decrypted); err != nil { - return nil, err - } - return readSignedMessage(packets, md, keyring) -} - -// readSignedMessage reads a possibly signed message if mdin is non-zero then -// that structure is updated and returned. Otherwise a fresh MessageDetails is -// used. -func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) { - if mdin == nil { - mdin = new(MessageDetails) - } - md = mdin - - var p packet.Packet - var h hash.Hash - var wrappedHash hash.Hash -FindLiteralData: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.Compressed: - if err := packets.Push(p.Body); err != nil { - return nil, err - } - case *packet.OnePassSignature: - if md.IsSigned { - // If IsSigned is set, it means we have multiple - // OnePassSignature packets. - md.MultiSig = true - if md.SignedBy != nil { - // We've already found the signature we were looking - // for, made by key that we had in keyring and can - // check signature against. Continue with that instead - // of trying to find another. - continue FindLiteralData - } - } - - h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) - if err != nil { - md = nil - return - } - - md.IsSigned = true - md.SignedByKeyId = p.KeyId - keys := keyring.KeysByIdUsage(p.KeyId, nil, packet.KeyFlagSign) - if len(keys) > 0 { - md.SignedBy = &keys[0] - } - case *packet.LiteralData: - md.LiteralData = p - break FindLiteralData - } - } - - if md.SignedBy != nil { - md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md} - } else if md.decrypted != nil { - md.UnverifiedBody = checkReader{md} - } else { - md.UnverifiedBody = md.LiteralData.Body - } - - return md, nil -} - -// hashForSignature returns a pair of hashes that can be used to verify a -// signature. The signature may specify that the contents of the signed message -// should be preprocessed (i.e. to normalize line endings). Thus this function -// returns two hashes. The second should be used to hash the message itself and -// performs any needed preprocessing. -func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { - if !hashId.Available() { - return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) - } - h := hashId.New() - - switch sigType { - case packet.SigTypeBinary: - return h, h, nil - case packet.SigTypeText: - return h, NewCanonicalTextHash(h), nil - } - - return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) -} - -// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF -// it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger -// MDC checks. -type checkReader struct { - md *MessageDetails -} - -func (cr checkReader) Read(buf []byte) (n int, err error) { - n, err = cr.md.LiteralData.Body.Read(buf) - if err == io.EOF { - mdcErr := cr.md.decrypted.Close() - if mdcErr != nil { - err = mdcErr - } - } - return -} - -// signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes -// the data as it is read. When it sees an EOF from the underlying io.Reader -// it parses and checks a trailing Signature packet and triggers any MDC checks. -type signatureCheckReader struct { - packets *packet.Reader - h, wrappedHash hash.Hash - md *MessageDetails -} - -func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { - n, err = scr.md.LiteralData.Body.Read(buf) - scr.wrappedHash.Write(buf[:n]) - if err == io.EOF { - for { - var p packet.Packet - p, scr.md.SignatureError = scr.packets.Next() - if scr.md.SignatureError != nil { - if scr.md.MultiSig { - // If we are in MultiSig, we might have found other - // signature that cannot be verified using our key. - // Clear Signature field so it's clear for consumers - // that this message failed to verify. - scr.md.Signature = nil - } - return - } - - var ok bool - if scr.md.Signature, ok = p.(*packet.Signature); ok { - var err error - if keyID := scr.md.Signature.IssuerKeyId; keyID != nil { - if *keyID != scr.md.SignedBy.PublicKey.KeyId { - if scr.md.MultiSig { - continue // try again to find a sig we can verify - } - err = errors.StructuralError("bad key id") - } - } - if fingerprint := scr.md.Signature.IssuerFingerprint; fingerprint != nil { - if !hmac.Equal(fingerprint, scr.md.SignedBy.PublicKey.Fingerprint[:]) { - if scr.md.MultiSig { - continue // try again to find a sig we can verify - } - err = errors.StructuralError("bad key fingerprint") - } - } - if err == nil { - err = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) - } - scr.md.SignatureError = err - } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { - scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) - } else { - scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") - return - } - - // Parse only one packet by default, unless message is MultiSig. Then - // we ask for more packets after discovering non-matching signature, - // until we find one that we can verify. - break - } - - // The SymmetricallyEncrypted packet, if any, might have an - // unsigned hash of its own. In order to check this we need to - // close that Reader. - if scr.md.decrypted != nil { - mdcErr := scr.md.decrypted.Close() - if mdcErr != nil { - err = mdcErr - } - } - } - return -} - -// CheckDetachedSignature takes a signed file and a detached signature and -// returns the signer if the signature is valid. If the signer isn't known, -// ErrUnknownIssuer is returned. -func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { - signer, _, err = checkDetachedSignature(keyring, signed, signature) - return signer, err -} - -func checkDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) { - var issuerKeyId uint64 - var issuerFingerprint []byte - var hashFunc crypto.Hash - var sigType packet.SignatureType - var keys []Key - var p packet.Packet - - packets := packet.NewReader(signature) - for { - p, err = packets.Next() - if err == io.EOF { - return nil, nil, errors.ErrUnknownIssuer - } - if err != nil { - return nil, nil, err - } - - switch sig := p.(type) { - case *packet.Signature: - if sig.IssuerKeyId == nil { - return nil, nil, errors.StructuralError("signature doesn't have an issuer") - } - issuerKeyId = *sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - issuerFingerprint = sig.IssuerFingerprint - case *packet.SignatureV3: - issuerKeyId = sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - default: - return nil, nil, errors.StructuralError("non signature packet found") - } - - keys = keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign) - if len(keys) > 0 { - break - } - } - - if len(keys) == 0 { - panic("unreachable") - } - - h, wrappedHash, err := hashForSignature(hashFunc, sigType) - if err != nil { - return nil, nil, err - } - - if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { - return nil, nil, err - } - - for _, key := range keys { - switch sig := p.(type) { - case *packet.Signature: - err = key.PublicKey.VerifySignature(h, sig) - case *packet.SignatureV3: - err = key.PublicKey.VerifySignatureV3(h, sig) - default: - panic("unreachable") - } - - if err == nil { - return key.Entity, &issuerKeyId, nil - } - } - - return nil, nil, err -} - -// CheckArmoredDetachedSignature performs the same actions as -// CheckDetachedSignature but expects the signature to be armored. -func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { - signer, _, err = checkArmoredDetachedSignature(keyring, signed, signature) - return signer, err -} - -func checkArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) { - body, err := readArmored(signature, SignatureType) - if err != nil { - return - } - return checkDetachedSignature(keyring, signed, body) -} diff --git a/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch b/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch deleted file mode 100644 index bfd764afe..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/sig-v3.patch +++ /dev/null @@ -1,135 +0,0 @@ -diff --git a/openpgp/read.go b/openpgp/read.go -index a6cecc5..0c9397b 100644 ---- a/openpgp/read.go -+++ b/openpgp/read.go -@@ -56,8 +56,9 @@ type MessageDetails struct { - // been consumed. Once EOF has been seen, the following fields are - // valid. (An authentication code failure is reported as a - // SignatureError error when reading from UnverifiedBody.) -- SignatureError error // nil if the signature is good. -- Signature *packet.Signature // the signature packet itself. -+ SignatureError error // nil if the signature is good. -+ Signature *packet.Signature // the signature packet itself, if v4 (default) -+ SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature - - decrypted io.ReadCloser - } -@@ -334,13 +335,15 @@ func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { - } - - var ok bool -- if scr.md.Signature, ok = p.(*packet.Signature); !ok { -+ if scr.md.Signature, ok = p.(*packet.Signature); ok { -+ scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) -+ } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { -+ scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) -+ } else { - scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") - return - } - -- scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) -- - // The SymmetricallyEncrypted packet, if any, might have an - // unsigned hash of its own. In order to check this we need to - // close that Reader. -diff --git a/openpgp/read_test.go b/openpgp/read_test.go -index 52f942c..abe8d7b 100644 ---- a/openpgp/read_test.go -+++ b/openpgp/read_test.go -@@ -13,6 +13,7 @@ import ( - "strings" - "testing" - -+ "golang.org/x/crypto/openpgp/armor" - "golang.org/x/crypto/openpgp/errors" - ) - -@@ -411,6 +412,50 @@ func TestIssue11504(t *testing.T) { - testReadMessageError(t, "9303000130303030303030303030983002303030303030030000000130") - } - -+// TestSignatureV3Message tests the verification of V3 signature, generated -+// with a modern V4-style key. Some people have their clients set to generate -+// V3 signatures, so it's useful to be able to verify them. -+func TestSignatureV3Message(t *testing.T) { -+ sig, err := armor.Decode(strings.NewReader(signedMessageV3)) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ key, err := ReadArmoredKeyRing(strings.NewReader(keyV4forVerifyingSignedMessageV3)) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ md, err := ReadMessage(sig.Body, key, nil, nil) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ -+ _, err = ioutil.ReadAll(md.UnverifiedBody) -+ if err != nil { -+ t.Error(err) -+ return -+ } -+ -+ // We'll see a sig error here after reading in the UnverifiedBody above, -+ // if there was one to see. -+ if err = md.SignatureError; err != nil { -+ t.Error(err) -+ return -+ } -+ -+ if md.SignatureV3 == nil { -+ t.Errorf("No available signature after checking signature") -+ return -+ } -+ if md.Signature != nil { -+ t.Errorf("Did not expect a signature V4 back") -+ return -+ } -+ return -+} -+ - const testKey1KeyId = 0xA34D7E18C20C31BB - const testKey3KeyId = 0x338934250CCC0360 - -@@ -504,3 +549,36 @@ const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6 - const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` - - const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` -+ -+const keyV4forVerifyingSignedMessageV3 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -+Comment: GPGTools - https://gpgtools.org -+ -+mI0EVfxoFQEEAMBIqmbDfYygcvP6Phr1wr1XI41IF7Qixqybs/foBF8qqblD9gIY -+BKpXjnBOtbkcVOJ0nljd3/sQIfH4E0vQwK5/4YRQSI59eKOqd6Fx+fWQOLG+uu6z -+tewpeCj9LLHvibx/Sc7VWRnrznia6ftrXxJ/wHMezSab3tnGC0YPVdGNABEBAAG0 -+JEdvY3J5cHRvIFRlc3QgS2V5IDx0aGVtYXhAZ21haWwuY29tPoi5BBMBCgAjBQJV -+/GgVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQeXnQmhdGW9PFVAP+ -+K7TU0qX5ArvIONIxh/WAweyOk884c5cE8f+3NOPOOCRGyVy0FId5A7MmD5GOQh4H -+JseOZVEVCqlmngEvtHZb3U1VYtVGE5WZ+6rQhGsMcWP5qaT4soYwMBlSYxgYwQcx -+YhN9qOr292f9j2Y//TTIJmZT4Oa+lMxhWdqTfX+qMgG4jQRV/GgVAQQArhFSiij1 -+b+hT3dnapbEU+23Z1yTu1DfF6zsxQ4XQWEV3eR8v+8mEDDNcz8oyyF56k6UQ3rXi -+UMTIwRDg4V6SbZmaFbZYCOwp/EmXJ3rfhm7z7yzXj2OFN22luuqbyVhuL7LRdB0M -+pxgmjXb4tTvfgKd26x34S+QqUJ7W6uprY4sAEQEAAYifBBgBCgAJBQJV/GgVAhsM -+AAoJEHl50JoXRlvT7y8D/02ckx4OMkKBZo7viyrBw0MLG92i+DC2bs35PooHR6zz -+786mitjOp5z2QWNLBvxC70S0qVfCIz8jKupO1J6rq6Z8CcbLF3qjm6h1omUBf8Nd -+EfXKD2/2HV6zMKVknnKzIEzauh+eCKS2CeJUSSSryap/QLVAjRnckaES/OsEWhNB -+=RZia -+-----END PGP PUBLIC KEY BLOCK----- -+` -+ -+const signedMessageV3 = `-----BEGIN PGP MESSAGE----- -+Comment: GPGTools - https://gpgtools.org -+ -+owGbwMvMwMVYWXlhlrhb9GXG03JJDKF/MtxDMjKLFYAoUaEktbhEITe1uDgxPVWP -+q5NhKjMrWAVcC9evD8z/bF/uWNjqtk/X3y5/38XGRQHm/57rrDRYuGnTw597Xqka -+uM3137/hH3Os+Jf2dc0fXOITKwJvXJvecPVs0ta+Vg7ZO1MLn8w58Xx+6L58mbka -+DGHyU9yTueZE8D+QF/Tz28Y78dqtF56R1VPn9Xw4uJqrWYdd7b3vIZ1V6R4Nh05d -+iT57d/OhWwA= -+=hG7R -+-----END PGP MESSAGE----- -+` diff --git a/vendor/github.com/keybase/go-crypto/openpgp/write.go b/vendor/github.com/keybase/go-crypto/openpgp/write.go deleted file mode 100644 index 89ef132b5..000000000 --- a/vendor/github.com/keybase/go-crypto/openpgp/write.go +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package openpgp - -import ( - "crypto" - "hash" - "io" - "strconv" - "time" - - "github.com/keybase/go-crypto/openpgp/armor" - "github.com/keybase/go-crypto/openpgp/errors" - "github.com/keybase/go-crypto/openpgp/packet" - "github.com/keybase/go-crypto/openpgp/s2k" -) - -// DetachSign signs message with the private key from signer (which must -// already have been decrypted) and writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// ArmoredDetachSign signs message with the private key from signer (which -// must already have been decrypted) and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { - return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// DetachSignText signs message (after canonicalising the line endings) with -// the private key from signer (which must already have been decrypted) and -// writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeText, config) -} - -// ArmoredDetachSignText signs message (after canonicalising the line endings) -// with the private key from signer (which must already have been decrypted) -// and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return armoredDetachSign(w, signer, message, packet.SigTypeText, config) -} - -func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - out, err := armor.Encode(w, SignatureType, nil) - if err != nil { - return - } - err = detachSign(out, signer, message, sigType, config) - if err != nil { - return - } - return out.Close() -} - -// SignWithSigner signs the message of type sigType with s and writes the -// signature to w. -// If config is nil, sensible defaults will be used. -func SignWithSigner(s packet.Signer, w io.Writer, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - keyId := s.KeyId() - sig := new(packet.Signature) - sig.SigType = sigType - sig.PubKeyAlgo = s.PublicKeyAlgo() - sig.Hash = config.Hash() - sig.CreationTime = config.Now() - sig.IssuerKeyId = &keyId - - s.Reset() - - wrapped := s.(hash.Hash) - - if sigType == packet.SigTypeText { - wrapped = NewCanonicalTextHash(s) - } - - io.Copy(wrapped, message) - - err = sig.Sign(s, nil, config) - if err != nil { - return - } - - err = sig.Serialize(w) - - return -} - -func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - signerSubkey, ok := signer.signingKey(config.Now()) - if !ok { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - if signerSubkey.PrivateKey == nil { - return errors.InvalidArgumentError("signing key doesn't have a private key") - } - if signerSubkey.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing key is encrypted") - } - - sig := new(packet.Signature) - sig.SigType = sigType - sig.PubKeyAlgo = signerSubkey.PrivateKey.PubKeyAlgo - sig.Hash = config.Hash() - sig.CreationTime = config.Now() - sig.IssuerKeyId = &signerSubkey.PrivateKey.KeyId - - h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) - if err != nil { - return - } - io.Copy(wrappedHash, message) - - err = sig.Sign(h, signerSubkey.PrivateKey, config) - if err != nil { - return - } - - return sig.Serialize(w) -} - -// FileHints contains metadata about encrypted files. This metadata is, itself, -// encrypted. -type FileHints struct { - // IsBinary can be set to hint that the contents are binary data. - IsBinary bool - // FileName hints at the name of the file that should be written. It's - // truncated to 255 bytes if longer. It may be empty to suggest that the - // file should not be written to disk. It may be equal to "_CONSOLE" to - // suggest the data should not be written to disk. - FileName string - // ModTime contains the modification time of the file, or the zero time if not applicable. - ModTime time.Time -} - -// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. -// The resulting WriteCloser must be closed after the contents of the file have -// been written. -// If config is nil, sensible defaults will be used. -func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - if hints == nil { - hints = &FileHints{} - } - - key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) - if err != nil { - return - } - w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config) - if err != nil { - return - } - - literaldata := w - if algo := config.Compression(); algo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - literaldata, err = packet.SerializeCompressed(w, algo, compConfig) - if err != nil { - return - } - } - - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - return packet.SerializeLiteral(literaldata, hints.IsBinary, hints.FileName, epochSeconds) -} - -// intersectPreferences mutates and returns a prefix of a that contains only -// the values in the intersection of a and b. The order of a is preserved. -func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { - var j int - for _, v := range a { - for _, v2 := range b { - if v == v2 { - a[j] = v - j++ - break - } - } - } - - return a[:j] -} - -func hashToHashId(h crypto.Hash) uint8 { - v, ok := s2k.HashToHashId(h) - if !ok { - panic("tried to convert unknown hash") - } - return v -} - -// Encrypt encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - var signer *packet.PrivateKey - if signed != nil { - signKey, ok := signed.signingKey(config.Now()) - if !ok { - return nil, errors.InvalidArgumentError("no valid signing keys") - } - signer = signKey.PrivateKey - if signer == nil { - return nil, errors.InvalidArgumentError("no private key in signing key") - } - if signer.Encrypted { - return nil, errors.InvalidArgumentError("signing key must be decrypted") - } - } - - // These are the possible ciphers that we'll use for the message. - candidateCiphers := []uint8{ - uint8(packet.CipherAES128), - uint8(packet.CipherAES256), - uint8(packet.CipherCAST5), - } - // These are the possible hash functions that we'll use for the signature. - candidateHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.SHA1), - hashToHashId(crypto.RIPEMD160), - } - - // If no preferences were specified, assume something safe and reasonable. - defaultCiphers := []uint8{ - uint8(packet.CipherAES128), - uint8(packet.CipherAES192), - uint8(packet.CipherAES256), - uint8(packet.CipherCAST5), - } - - defaultHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.RIPEMD160), - } - - encryptKeys := make([]Key, len(to)) - for i := range to { - var ok bool - encryptKeys[i], ok = to[i].encryptionKey(config.Now()) - if !ok { - return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys") - } - - sig := to[i].primaryIdentity().SelfSignature - - preferredSymmetric := sig.PreferredSymmetric - if len(preferredSymmetric) == 0 { - preferredSymmetric = defaultCiphers - } - preferredHashes := sig.PreferredHash - if len(preferredHashes) == 0 { - preferredHashes = defaultHashes - } - candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric) - candidateHashes = intersectPreferences(candidateHashes, preferredHashes) - } - - if len(candidateCiphers) == 0 { - return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common ciphers") - } - if len(candidateHashes) == 0 { - return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common hashes") - } - - cipher := packet.CipherFunction(candidateCiphers[0]) - // If the cipher specifed by config is a candidate, we'll use that. - configuredCipher := config.Cipher() - for _, c := range candidateCiphers { - cipherFunc := packet.CipherFunction(c) - if cipherFunc == configuredCipher { - cipher = cipherFunc - break - } - } - - var hash crypto.Hash - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { - hash = h - break - } - } - - // If the hash specified by config is a candidate, we'll use that. - if configuredHash := config.Hash(); configuredHash.Available() { - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { - hash = h - break - } - } - } - - if hash == 0 { - hashId := candidateHashes[0] - name, ok := s2k.HashIdToString(hashId) - if !ok { - name = "#" + strconv.Itoa(int(hashId)) - } - return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") - } - - symKey := make([]byte, cipher.KeySize()) - if _, err := io.ReadFull(config.Random(), symKey); err != nil { - return nil, err - } - - for _, key := range encryptKeys { - if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil { - return nil, err - } - } - - encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config) - if err != nil { - return - } - - if signer != nil { - ops := &packet.OnePassSignature{ - SigType: packet.SigTypeBinary, - Hash: hash, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - if err := ops.Serialize(encryptedData); err != nil { - return nil, err - } - } - - if hints == nil { - hints = &FileHints{} - } - - w := encryptedData - if signer != nil { - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - w = noOpCloser{encryptedData} - - } - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) - if err != nil { - return nil, err - } - - if signer != nil { - return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil - } - return literalData, nil -} - -// signatureWriter hashes the contents of a message while passing it along to -// literalData. When closed, it closes literalData, writes a signature packet -// to encryptedData and then also closes encryptedData. -type signatureWriter struct { - encryptedData io.WriteCloser - literalData io.WriteCloser - hashType crypto.Hash - h hash.Hash - signer *packet.PrivateKey - config *packet.Config -} - -func (s signatureWriter) Write(data []byte) (int, error) { - s.h.Write(data) - return s.literalData.Write(data) -} - -func (s signatureWriter) Close() error { - sig := &packet.Signature{ - SigType: packet.SigTypeBinary, - PubKeyAlgo: s.signer.PubKeyAlgo, - Hash: s.hashType, - CreationTime: s.config.Now(), - IssuerKeyId: &s.signer.KeyId, - } - - if err := sig.Sign(s.h, s.signer, s.config); err != nil { - return err - } - if err := s.literalData.Close(); err != nil { - return err - } - if err := sig.Serialize(s.encryptedData); err != nil { - return err - } - return s.encryptedData.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -// TODO: we have two of these in OpenPGP packages alone. This probably needs -// to be promoted somewhere more common. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -// AttachedSign is like openpgp.Encrypt (as in p.crypto/openpgp/write.go), but -// don't encrypt at all, just sign the literal unencrypted data. -// Unfortunately we need to duplicate some code here that's already -// in write.go -func AttachedSign(out io.WriteCloser, signed Entity, hints *FileHints, - config *packet.Config) (in io.WriteCloser, err error) { - - if hints == nil { - hints = &FileHints{} - } - - if config == nil { - config = &packet.Config{} - } - - var signer *packet.PrivateKey - - signKey, ok := signed.signingKey(config.Now()) - if !ok { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - signer = signKey.PrivateKey - if signer == nil { - err = errors.InvalidArgumentError("no valid signing keys") - return - } - if signer.Encrypted { - err = errors.InvalidArgumentError("signing key must be decrypted") - return - } - - if algo := config.Compression(); algo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - out, err = packet.SerializeCompressed(out, algo, compConfig) - if err != nil { - return - } - } - - hasher := crypto.SHA512 - - ops := &packet.OnePassSignature{ - SigType: packet.SigTypeBinary, - Hash: hasher, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - - if err = ops.Serialize(out); err != nil { - return - } - - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - - // We don't want the literal serializer to closer the output stream - // since we're going to need to write to it when we finish up the - // signature stuff. - in, err = packet.SerializeLiteral(noOpCloser{out}, hints.IsBinary, hints.FileName, epochSeconds) - - if err != nil { - return - } - - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - in = signatureWriter{out, in, hasher, hasher.New(), signer, config} - - return -} diff --git a/vendor/github.com/kr/pretty/License b/vendor/github.com/kr/pretty/License deleted file mode 100644 index 05c783ccf..000000000 --- a/vendor/github.com/kr/pretty/License +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright 2012 Keith Rarick - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/kr/pretty/Readme b/vendor/github.com/kr/pretty/Readme deleted file mode 100644 index c589fc622..000000000 --- a/vendor/github.com/kr/pretty/Readme +++ /dev/null @@ -1,9 +0,0 @@ -package pretty - - import "github.com/kr/pretty" - - Package pretty provides pretty-printing for Go values. - -Documentation - - http://godoc.org/github.com/kr/pretty diff --git a/vendor/github.com/kr/pretty/diff.go b/vendor/github.com/kr/pretty/diff.go deleted file mode 100644 index 6aa7f743a..000000000 --- a/vendor/github.com/kr/pretty/diff.go +++ /dev/null @@ -1,265 +0,0 @@ -package pretty - -import ( - "fmt" - "io" - "reflect" -) - -type sbuf []string - -func (p *sbuf) Printf(format string, a ...interface{}) { - s := fmt.Sprintf(format, a...) - *p = append(*p, s) -} - -// Diff returns a slice where each element describes -// a difference between a and b. -func Diff(a, b interface{}) (desc []string) { - Pdiff((*sbuf)(&desc), a, b) - return desc -} - -// wprintfer calls Fprintf on w for each Printf call -// with a trailing newline. -type wprintfer struct{ w io.Writer } - -func (p *wprintfer) Printf(format string, a ...interface{}) { - fmt.Fprintf(p.w, format+"\n", a...) -} - -// Fdiff writes to w a description of the differences between a and b. -func Fdiff(w io.Writer, a, b interface{}) { - Pdiff(&wprintfer{w}, a, b) -} - -type Printfer interface { - Printf(format string, a ...interface{}) -} - -// Pdiff prints to p a description of the differences between a and b. -// It calls Printf once for each difference, with no trailing newline. -// The standard library log.Logger is a Printfer. -func Pdiff(p Printfer, a, b interface{}) { - diffPrinter{w: p}.diff(reflect.ValueOf(a), reflect.ValueOf(b)) -} - -type Logfer interface { - Logf(format string, a ...interface{}) -} - -// logprintfer calls Fprintf on w for each Printf call -// with a trailing newline. -type logprintfer struct{ l Logfer } - -func (p *logprintfer) Printf(format string, a ...interface{}) { - p.l.Logf(format, a...) -} - -// Ldiff prints to l a description of the differences between a and b. -// It calls Logf once for each difference, with no trailing newline. -// The standard library testing.T and testing.B are Logfers. -func Ldiff(l Logfer, a, b interface{}) { - Pdiff(&logprintfer{l}, a, b) -} - -type diffPrinter struct { - w Printfer - l string // label -} - -func (w diffPrinter) printf(f string, a ...interface{}) { - var l string - if w.l != "" { - l = w.l + ": " - } - w.w.Printf(l+f, a...) -} - -func (w diffPrinter) diff(av, bv reflect.Value) { - if !av.IsValid() && bv.IsValid() { - w.printf("nil != %# v", formatter{v: bv, quote: true}) - return - } - if av.IsValid() && !bv.IsValid() { - w.printf("%# v != nil", formatter{v: av, quote: true}) - return - } - if !av.IsValid() && !bv.IsValid() { - return - } - - at := av.Type() - bt := bv.Type() - if at != bt { - w.printf("%v != %v", at, bt) - return - } - - switch kind := at.Kind(); kind { - case reflect.Bool: - if a, b := av.Bool(), bv.Bool(); a != b { - w.printf("%v != %v", a, b) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if a, b := av.Int(), bv.Int(); a != b { - w.printf("%d != %d", a, b) - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - if a, b := av.Uint(), bv.Uint(); a != b { - w.printf("%d != %d", a, b) - } - case reflect.Float32, reflect.Float64: - if a, b := av.Float(), bv.Float(); a != b { - w.printf("%v != %v", a, b) - } - case reflect.Complex64, reflect.Complex128: - if a, b := av.Complex(), bv.Complex(); a != b { - w.printf("%v != %v", a, b) - } - case reflect.Array: - n := av.Len() - for i := 0; i < n; i++ { - w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) - } - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - if a, b := av.Pointer(), bv.Pointer(); a != b { - w.printf("%#x != %#x", a, b) - } - case reflect.Interface: - w.diff(av.Elem(), bv.Elem()) - case reflect.Map: - ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys()) - for _, k := range ak { - w := w.relabel(fmt.Sprintf("[%#v]", k)) - w.printf("%q != (missing)", av.MapIndex(k)) - } - for _, k := range both { - w := w.relabel(fmt.Sprintf("[%#v]", k)) - w.diff(av.MapIndex(k), bv.MapIndex(k)) - } - for _, k := range bk { - w := w.relabel(fmt.Sprintf("[%#v]", k)) - w.printf("(missing) != %q", bv.MapIndex(k)) - } - case reflect.Ptr: - switch { - case av.IsNil() && !bv.IsNil(): - w.printf("nil != %# v", formatter{v: bv, quote: true}) - case !av.IsNil() && bv.IsNil(): - w.printf("%# v != nil", formatter{v: av, quote: true}) - case !av.IsNil() && !bv.IsNil(): - w.diff(av.Elem(), bv.Elem()) - } - case reflect.Slice: - lenA := av.Len() - lenB := bv.Len() - if lenA != lenB { - w.printf("%s[%d] != %s[%d]", av.Type(), lenA, bv.Type(), lenB) - break - } - for i := 0; i < lenA; i++ { - w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) - } - case reflect.String: - if a, b := av.String(), bv.String(); a != b { - w.printf("%q != %q", a, b) - } - case reflect.Struct: - for i := 0; i < av.NumField(); i++ { - w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i)) - } - default: - panic("unknown reflect Kind: " + kind.String()) - } -} - -func (d diffPrinter) relabel(name string) (d1 diffPrinter) { - d1 = d - if d.l != "" && name[0] != '[' { - d1.l += "." - } - d1.l += name - return d1 -} - -// keyEqual compares a and b for equality. -// Both a and b must be valid map keys. -func keyEqual(av, bv reflect.Value) bool { - if !av.IsValid() && !bv.IsValid() { - return true - } - if !av.IsValid() || !bv.IsValid() || av.Type() != bv.Type() { - return false - } - switch kind := av.Kind(); kind { - case reflect.Bool: - a, b := av.Bool(), bv.Bool() - return a == b - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - a, b := av.Int(), bv.Int() - return a == b - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - a, b := av.Uint(), bv.Uint() - return a == b - case reflect.Float32, reflect.Float64: - a, b := av.Float(), bv.Float() - return a == b - case reflect.Complex64, reflect.Complex128: - a, b := av.Complex(), bv.Complex() - return a == b - case reflect.Array: - for i := 0; i < av.Len(); i++ { - if !keyEqual(av.Index(i), bv.Index(i)) { - return false - } - } - return true - case reflect.Chan, reflect.UnsafePointer, reflect.Ptr: - a, b := av.Pointer(), bv.Pointer() - return a == b - case reflect.Interface: - return keyEqual(av.Elem(), bv.Elem()) - case reflect.String: - a, b := av.String(), bv.String() - return a == b - case reflect.Struct: - for i := 0; i < av.NumField(); i++ { - if !keyEqual(av.Field(i), bv.Field(i)) { - return false - } - } - return true - default: - panic("invalid map key type " + av.Type().String()) - } -} - -func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) { - for _, av := range a { - inBoth := false - for _, bv := range b { - if keyEqual(av, bv) { - inBoth = true - both = append(both, av) - break - } - } - if !inBoth { - ak = append(ak, av) - } - } - for _, bv := range b { - inBoth := false - for _, av := range a { - if keyEqual(av, bv) { - inBoth = true - break - } - } - if !inBoth { - bk = append(bk, bv) - } - } - return -} diff --git a/vendor/github.com/kr/pretty/formatter.go b/vendor/github.com/kr/pretty/formatter.go deleted file mode 100644 index a317d7b8e..000000000 --- a/vendor/github.com/kr/pretty/formatter.go +++ /dev/null @@ -1,328 +0,0 @@ -package pretty - -import ( - "fmt" - "io" - "reflect" - "strconv" - "text/tabwriter" - - "github.com/kr/text" -) - -type formatter struct { - v reflect.Value - force bool - quote bool -} - -// Formatter makes a wrapper, f, that will format x as go source with line -// breaks and tabs. Object f responds to the "%v" formatting verb when both the -// "#" and " " (space) flags are set, for example: -// -// fmt.Sprintf("%# v", Formatter(x)) -// -// If one of these two flags is not set, or any other verb is used, f will -// format x according to the usual rules of package fmt. -// In particular, if x satisfies fmt.Formatter, then x.Format will be called. -func Formatter(x interface{}) (f fmt.Formatter) { - return formatter{v: reflect.ValueOf(x), quote: true} -} - -func (fo formatter) String() string { - return fmt.Sprint(fo.v.Interface()) // unwrap it -} - -func (fo formatter) passThrough(f fmt.State, c rune) { - s := "%" - for i := 0; i < 128; i++ { - if f.Flag(i) { - s += string(i) - } - } - if w, ok := f.Width(); ok { - s += fmt.Sprintf("%d", w) - } - if p, ok := f.Precision(); ok { - s += fmt.Sprintf(".%d", p) - } - s += string(c) - fmt.Fprintf(f, s, fo.v.Interface()) -} - -func (fo formatter) Format(f fmt.State, c rune) { - if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') { - w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0) - p := &printer{tw: w, Writer: w, visited: make(map[visit]int)} - p.printValue(fo.v, true, fo.quote) - w.Flush() - return - } - fo.passThrough(f, c) -} - -type printer struct { - io.Writer - tw *tabwriter.Writer - visited map[visit]int - depth int -} - -func (p *printer) indent() *printer { - q := *p - q.tw = tabwriter.NewWriter(p.Writer, 4, 4, 1, ' ', 0) - q.Writer = text.NewIndentWriter(q.tw, []byte{'\t'}) - return &q -} - -func (p *printer) printInline(v reflect.Value, x interface{}, showType bool) { - if showType { - io.WriteString(p, v.Type().String()) - fmt.Fprintf(p, "(%#v)", x) - } else { - fmt.Fprintf(p, "%#v", x) - } -} - -// printValue must keep track of already-printed pointer values to avoid -// infinite recursion. -type visit struct { - v uintptr - typ reflect.Type -} - -func (p *printer) printValue(v reflect.Value, showType, quote bool) { - if p.depth > 10 { - io.WriteString(p, "!%v(DEPTH EXCEEDED)") - return - } - - switch v.Kind() { - case reflect.Bool: - p.printInline(v, v.Bool(), showType) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p.printInline(v, v.Int(), showType) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p.printInline(v, v.Uint(), showType) - case reflect.Float32, reflect.Float64: - p.printInline(v, v.Float(), showType) - case reflect.Complex64, reflect.Complex128: - fmt.Fprintf(p, "%#v", v.Complex()) - case reflect.String: - p.fmtString(v.String(), quote) - case reflect.Map: - t := v.Type() - if showType { - io.WriteString(p, t.String()) - } - writeByte(p, '{') - if nonzero(v) { - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - keys := v.MapKeys() - for i := 0; i < v.Len(); i++ { - showTypeInStruct := true - k := keys[i] - mv := v.MapIndex(k) - pp.printValue(k, false, true) - writeByte(pp, ':') - if expand { - writeByte(pp, '\t') - } - showTypeInStruct = t.Elem().Kind() == reflect.Interface - pp.printValue(mv, showTypeInStruct, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.Len()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - } - writeByte(p, '}') - case reflect.Struct: - t := v.Type() - if v.CanAddr() { - addr := v.UnsafeAddr() - vis := visit{addr, t} - if vd, ok := p.visited[vis]; ok && vd < p.depth { - p.fmtString(t.String()+"{(CYCLIC REFERENCE)}", false) - break // don't print v again - } - p.visited[vis] = p.depth - } - - if showType { - io.WriteString(p, t.String()) - } - writeByte(p, '{') - if nonzero(v) { - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - for i := 0; i < v.NumField(); i++ { - showTypeInStruct := true - if f := t.Field(i); f.Name != "" { - io.WriteString(pp, f.Name) - writeByte(pp, ':') - if expand { - writeByte(pp, '\t') - } - showTypeInStruct = labelType(f.Type) - } - pp.printValue(getField(v, i), showTypeInStruct, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.NumField()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - } - writeByte(p, '}') - case reflect.Interface: - switch e := v.Elem(); { - case e.Kind() == reflect.Invalid: - io.WriteString(p, "nil") - case e.IsValid(): - pp := *p - pp.depth++ - pp.printValue(e, showType, true) - default: - io.WriteString(p, v.Type().String()) - io.WriteString(p, "(nil)") - } - case reflect.Array, reflect.Slice: - t := v.Type() - if showType { - io.WriteString(p, t.String()) - } - if v.Kind() == reflect.Slice && v.IsNil() && showType { - io.WriteString(p, "(nil)") - break - } - if v.Kind() == reflect.Slice && v.IsNil() { - io.WriteString(p, "nil") - break - } - writeByte(p, '{') - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - for i := 0; i < v.Len(); i++ { - showTypeInSlice := t.Elem().Kind() == reflect.Interface - pp.printValue(v.Index(i), showTypeInSlice, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.Len()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - writeByte(p, '}') - case reflect.Ptr: - e := v.Elem() - if !e.IsValid() { - writeByte(p, '(') - io.WriteString(p, v.Type().String()) - io.WriteString(p, ")(nil)") - } else { - pp := *p - pp.depth++ - writeByte(pp, '&') - pp.printValue(e, true, true) - } - case reflect.Chan: - x := v.Pointer() - if showType { - writeByte(p, '(') - io.WriteString(p, v.Type().String()) - fmt.Fprintf(p, ")(%#v)", x) - } else { - fmt.Fprintf(p, "%#v", x) - } - case reflect.Func: - io.WriteString(p, v.Type().String()) - io.WriteString(p, " {...}") - case reflect.UnsafePointer: - p.printInline(v, v.Pointer(), showType) - case reflect.Invalid: - io.WriteString(p, "nil") - } -} - -func canInline(t reflect.Type) bool { - switch t.Kind() { - case reflect.Map: - return !canExpand(t.Elem()) - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if canExpand(t.Field(i).Type) { - return false - } - } - return true - case reflect.Interface: - return false - case reflect.Array, reflect.Slice: - return !canExpand(t.Elem()) - case reflect.Ptr: - return false - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - return false - } - return true -} - -func canExpand(t reflect.Type) bool { - switch t.Kind() { - case reflect.Map, reflect.Struct, - reflect.Interface, reflect.Array, reflect.Slice, - reflect.Ptr: - return true - } - return false -} - -func labelType(t reflect.Type) bool { - switch t.Kind() { - case reflect.Interface, reflect.Struct: - return true - } - return false -} - -func (p *printer) fmtString(s string, quote bool) { - if quote { - s = strconv.Quote(s) - } - io.WriteString(p, s) -} - -func writeByte(w io.Writer, b byte) { - w.Write([]byte{b}) -} - -func getField(v reflect.Value, i int) reflect.Value { - val := v.Field(i) - if val.Kind() == reflect.Interface && !val.IsNil() { - val = val.Elem() - } - return val -} diff --git a/vendor/github.com/kr/pretty/go.mod b/vendor/github.com/kr/pretty/go.mod deleted file mode 100644 index 1e2953314..000000000 --- a/vendor/github.com/kr/pretty/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module "github.com/kr/pretty" - -require "github.com/kr/text" v0.1.0 diff --git a/vendor/github.com/kr/pretty/pretty.go b/vendor/github.com/kr/pretty/pretty.go deleted file mode 100644 index 49423ec7f..000000000 --- a/vendor/github.com/kr/pretty/pretty.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package pretty provides pretty-printing for Go values. This is -// useful during debugging, to avoid wrapping long output lines in -// the terminal. -// -// It provides a function, Formatter, that can be used with any -// function that accepts a format string. It also provides -// convenience wrappers for functions in packages fmt and log. -package pretty - -import ( - "fmt" - "io" - "log" - "reflect" -) - -// Errorf is a convenience wrapper for fmt.Errorf. -// -// Calling Errorf(f, x, y) is equivalent to -// fmt.Errorf(f, Formatter(x), Formatter(y)). -func Errorf(format string, a ...interface{}) error { - return fmt.Errorf(format, wrap(a, false)...) -} - -// Fprintf is a convenience wrapper for fmt.Fprintf. -// -// Calling Fprintf(w, f, x, y) is equivalent to -// fmt.Fprintf(w, f, Formatter(x), Formatter(y)). -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error error) { - return fmt.Fprintf(w, format, wrap(a, false)...) -} - -// Log is a convenience wrapper for log.Printf. -// -// Calling Log(x, y) is equivalent to -// log.Print(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Log(a ...interface{}) { - log.Print(wrap(a, true)...) -} - -// Logf is a convenience wrapper for log.Printf. -// -// Calling Logf(f, x, y) is equivalent to -// log.Printf(f, Formatter(x), Formatter(y)). -func Logf(format string, a ...interface{}) { - log.Printf(format, wrap(a, false)...) -} - -// Logln is a convenience wrapper for log.Printf. -// -// Calling Logln(x, y) is equivalent to -// log.Println(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Logln(a ...interface{}) { - log.Println(wrap(a, true)...) -} - -// Print pretty-prints its operands and writes to standard output. -// -// Calling Print(x, y) is equivalent to -// fmt.Print(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Print(a ...interface{}) (n int, errno error) { - return fmt.Print(wrap(a, true)...) -} - -// Printf is a convenience wrapper for fmt.Printf. -// -// Calling Printf(f, x, y) is equivalent to -// fmt.Printf(f, Formatter(x), Formatter(y)). -func Printf(format string, a ...interface{}) (n int, errno error) { - return fmt.Printf(format, wrap(a, false)...) -} - -// Println pretty-prints its operands and writes to standard output. -// -// Calling Print(x, y) is equivalent to -// fmt.Println(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Println(a ...interface{}) (n int, errno error) { - return fmt.Println(wrap(a, true)...) -} - -// Sprint is a convenience wrapper for fmt.Sprintf. -// -// Calling Sprint(x, y) is equivalent to -// fmt.Sprint(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Sprint(a ...interface{}) string { - return fmt.Sprint(wrap(a, true)...) -} - -// Sprintf is a convenience wrapper for fmt.Sprintf. -// -// Calling Sprintf(f, x, y) is equivalent to -// fmt.Sprintf(f, Formatter(x), Formatter(y)). -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, wrap(a, false)...) -} - -func wrap(a []interface{}, force bool) []interface{} { - w := make([]interface{}, len(a)) - for i, x := range a { - w[i] = formatter{v: reflect.ValueOf(x), force: force} - } - return w -} diff --git a/vendor/github.com/kr/pretty/zero.go b/vendor/github.com/kr/pretty/zero.go deleted file mode 100644 index abb5b6fc1..000000000 --- a/vendor/github.com/kr/pretty/zero.go +++ /dev/null @@ -1,41 +0,0 @@ -package pretty - -import ( - "reflect" -) - -func nonzero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() != 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() != 0 - case reflect.Float32, reflect.Float64: - return v.Float() != 0 - case reflect.Complex64, reflect.Complex128: - return v.Complex() != complex(0, 0) - case reflect.String: - return v.String() != "" - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - if nonzero(getField(v, i)) { - return true - } - } - return false - case reflect.Array: - for i := 0; i < v.Len(); i++ { - if nonzero(v.Index(i)) { - return true - } - } - return false - case reflect.Map, reflect.Interface, reflect.Slice, reflect.Ptr, reflect.Chan, reflect.Func: - return !v.IsNil() - case reflect.UnsafePointer: - return v.Pointer() != 0 - } - return true -} diff --git a/vendor/github.com/kr/text/License b/vendor/github.com/kr/text/License deleted file mode 100644 index 480a32805..000000000 --- a/vendor/github.com/kr/text/License +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2012 Keith Rarick - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/kr/text/Readme b/vendor/github.com/kr/text/Readme deleted file mode 100644 index 7e6e7c068..000000000 --- a/vendor/github.com/kr/text/Readme +++ /dev/null @@ -1,3 +0,0 @@ -This is a Go package for manipulating paragraphs of text. - -See http://go.pkgdoc.org/github.com/kr/text for full documentation. diff --git a/vendor/github.com/kr/text/doc.go b/vendor/github.com/kr/text/doc.go deleted file mode 100644 index cf4c198f9..000000000 --- a/vendor/github.com/kr/text/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package text provides rudimentary functions for manipulating text in -// paragraphs. -package text diff --git a/vendor/github.com/kr/text/go.mod b/vendor/github.com/kr/text/go.mod deleted file mode 100644 index fa0528b9a..000000000 --- a/vendor/github.com/kr/text/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module "github.com/kr/text" - -require "github.com/kr/pty" v1.1.1 diff --git a/vendor/github.com/kr/text/indent.go b/vendor/github.com/kr/text/indent.go deleted file mode 100644 index 4ebac45c0..000000000 --- a/vendor/github.com/kr/text/indent.go +++ /dev/null @@ -1,74 +0,0 @@ -package text - -import ( - "io" -) - -// Indent inserts prefix at the beginning of each non-empty line of s. The -// end-of-line marker is NL. -func Indent(s, prefix string) string { - return string(IndentBytes([]byte(s), []byte(prefix))) -} - -// IndentBytes inserts prefix at the beginning of each non-empty line of b. -// The end-of-line marker is NL. -func IndentBytes(b, prefix []byte) []byte { - var res []byte - bol := true - for _, c := range b { - if bol && c != '\n' { - res = append(res, prefix...) - } - res = append(res, c) - bol = c == '\n' - } - return res -} - -// Writer indents each line of its input. -type indentWriter struct { - w io.Writer - bol bool - pre [][]byte - sel int - off int -} - -// NewIndentWriter makes a new write filter that indents the input -// lines. Each line is prefixed in order with the corresponding -// element of pre. If there are more lines than elements, the last -// element of pre is repeated for each subsequent line. -func NewIndentWriter(w io.Writer, pre ...[]byte) io.Writer { - return &indentWriter{ - w: w, - pre: pre, - bol: true, - } -} - -// The only errors returned are from the underlying indentWriter. -func (w *indentWriter) Write(p []byte) (n int, err error) { - for _, c := range p { - if w.bol { - var i int - i, err = w.w.Write(w.pre[w.sel][w.off:]) - w.off += i - if err != nil { - return n, err - } - } - _, err = w.w.Write([]byte{c}) - if err != nil { - return n, err - } - n++ - w.bol = c == '\n' - if w.bol { - w.off = 0 - if w.sel < len(w.pre)-1 { - w.sel++ - } - } - } - return n, nil -} diff --git a/vendor/github.com/kr/text/wrap.go b/vendor/github.com/kr/text/wrap.go deleted file mode 100644 index b09bb0373..000000000 --- a/vendor/github.com/kr/text/wrap.go +++ /dev/null @@ -1,86 +0,0 @@ -package text - -import ( - "bytes" - "math" -) - -var ( - nl = []byte{'\n'} - sp = []byte{' '} -) - -const defaultPenalty = 1e5 - -// Wrap wraps s into a paragraph of lines of length lim, with minimal -// raggedness. -func Wrap(s string, lim int) string { - return string(WrapBytes([]byte(s), lim)) -} - -// WrapBytes wraps b into a paragraph of lines of length lim, with minimal -// raggedness. -func WrapBytes(b []byte, lim int) []byte { - words := bytes.Split(bytes.Replace(bytes.TrimSpace(b), nl, sp, -1), sp) - var lines [][]byte - for _, line := range WrapWords(words, 1, lim, defaultPenalty) { - lines = append(lines, bytes.Join(line, sp)) - } - return bytes.Join(lines, nl) -} - -// WrapWords is the low-level line-breaking algorithm, useful if you need more -// control over the details of the text wrapping process. For most uses, either -// Wrap or WrapBytes will be sufficient and more convenient. -// -// WrapWords splits a list of words into lines with minimal "raggedness", -// treating each byte as one unit, accounting for spc units between adjacent -// words on each line, and attempting to limit lines to lim units. Raggedness -// is the total error over all lines, where error is the square of the -// difference of the length of the line and lim. Too-long lines (which only -// happen when a single word is longer than lim units) have pen penalty units -// added to the error. -func WrapWords(words [][]byte, spc, lim, pen int) [][][]byte { - n := len(words) - - length := make([][]int, n) - for i := 0; i < n; i++ { - length[i] = make([]int, n) - length[i][i] = len(words[i]) - for j := i + 1; j < n; j++ { - length[i][j] = length[i][j-1] + spc + len(words[j]) - } - } - - nbrk := make([]int, n) - cost := make([]int, n) - for i := range cost { - cost[i] = math.MaxInt32 - } - for i := n - 1; i >= 0; i-- { - if length[i][n-1] <= lim || i == n-1 { - cost[i] = 0 - nbrk[i] = n - } else { - for j := i + 1; j < n; j++ { - d := lim - length[i][j-1] - c := d*d + cost[j] - if length[i][j-1] > lim { - c += pen // too-long lines get a worse penalty - } - if c < cost[i] { - cost[i] = c - nbrk[i] = j - } - } - } - } - - var lines [][][]byte - i := 0 - for i < n { - lines = append(lines, words[i:nbrk[i]]) - i = nbrk[i] - } - return lines -} diff --git a/vendor/github.com/lib/pq/CONTRIBUTING.md b/vendor/github.com/lib/pq/CONTRIBUTING.md deleted file mode 100644 index 84c937f15..000000000 --- a/vendor/github.com/lib/pq/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -## Contributing to pq - -`pq` has a backlog of pull requests, but contributions are still very -much welcome. You can help with patch review, submitting bug reports, -or adding new functionality. There is no formal style guide, but -please conform to the style of existing code and general Go formatting -conventions when submitting patches. - -### Patch review - -Help review existing open pull requests by commenting on the code or -proposed functionality. - -### Bug reports - -We appreciate any bug reports, but especially ones with self-contained -(doesn't depend on code outside of pq), minimal (can't be simplified -further) test cases. It's especially helpful if you can submit a pull -request with just the failing test case (you'll probably want to -pattern it after the tests in -[conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go). - -### New functionality - -There are a number of pending patches for new functionality, so -additional feature patches will take a while to merge. Still, patches -are generally reviewed based on usefulness and complexity in addition -to time-in-queue, so if you have a knockout idea, take a shot. Feel -free to open an issue discussion your proposed patch beforehand. diff --git a/vendor/github.com/lib/pq/LICENSE.md b/vendor/github.com/lib/pq/LICENSE.md deleted file mode 100644 index 5773904a3..000000000 --- a/vendor/github.com/lib/pq/LICENSE.md +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2011-2013, 'pq' Contributors -Portions Copyright (C) 2011 Blake Mizerany - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/lib/pq/README.md b/vendor/github.com/lib/pq/README.md deleted file mode 100644 index d71f3c2c3..000000000 --- a/vendor/github.com/lib/pq/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# pq - A pure Go postgres driver for Go's database/sql package - -[![GoDoc](https://godoc.org/github.com/lib/pq?status.svg)](https://godoc.org/github.com/lib/pq) -[![Build Status](https://travis-ci.org/lib/pq.svg?branch=master)](https://travis-ci.org/lib/pq) - -## Install - - go get github.com/lib/pq - -## Docs - -For detailed documentation and basic usage examples, please see the package -documentation at . - -## Tests - -`go test` is used for testing. See [TESTS.md](TESTS.md) for more details. - -## Features - -* SSL -* Handles bad connections for `database/sql` -* Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`) -* Scan binary blobs correctly (i.e. `bytea`) -* Package for `hstore` support -* COPY FROM support -* pq.ParseURL for converting urls to connection strings for sql.Open. -* Many libpq compatible environment variables -* Unix socket support -* Notifications: `LISTEN`/`NOTIFY` -* pgpass support - -## Future / Things you can help with - -* Better COPY FROM / COPY TO (see discussion in #181) - -## Thank you (alphabetical) - -Some of these contributors are from the original library `bmizerany/pq.go` whose -code still exists in here. - -* Andy Balholm (andybalholm) -* Ben Berkert (benburkert) -* Benjamin Heatwole (bheatwole) -* Bill Mill (llimllib) -* Bjørn Madsen (aeons) -* Blake Gentry (bgentry) -* Brad Fitzpatrick (bradfitz) -* Charlie Melbye (cmelbye) -* Chris Bandy (cbandy) -* Chris Gilling (cgilling) -* Chris Walsh (cwds) -* Dan Sosedoff (sosedoff) -* Daniel Farina (fdr) -* Eric Chlebek (echlebek) -* Eric Garrido (minusnine) -* Eric Urban (hydrogen18) -* Everyone at The Go Team -* Evan Shaw (edsrzf) -* Ewan Chou (coocood) -* Fazal Majid (fazalmajid) -* Federico Romero (federomero) -* Fumin (fumin) -* Gary Burd (garyburd) -* Heroku (heroku) -* James Pozdena (jpoz) -* Jason McVetta (jmcvetta) -* Jeremy Jay (pbnjay) -* Joakim Sernbrant (serbaut) -* John Gallagher (jgallagher) -* Jonathan Rudenberg (titanous) -* Joël Stemmer (jstemmer) -* Kamil Kisiel (kisielk) -* Kelly Dunn (kellydunn) -* Keith Rarick (kr) -* Kir Shatrov (kirs) -* Lann Martin (lann) -* Maciek Sakrejda (uhoh-itsmaciek) -* Marc Brinkmann (mbr) -* Marko Tiikkaja (johto) -* Matt Newberry (MattNewberry) -* Matt Robenolt (mattrobenolt) -* Martin Olsen (martinolsen) -* Mike Lewis (mikelikespie) -* Nicolas Patry (Narsil) -* Oliver Tonnhofer (olt) -* Patrick Hayes (phayes) -* Paul Hammond (paulhammond) -* Ryan Smith (ryandotsmith) -* Samuel Stauffer (samuel) -* Timothée Peignier (cyberdelia) -* Travis Cline (tmc) -* TruongSinh Tran-Nguyen (truongsinh) -* Yaismel Miranda (ympons) -* notedit (notedit) diff --git a/vendor/github.com/lib/pq/TESTS.md b/vendor/github.com/lib/pq/TESTS.md deleted file mode 100644 index f05021115..000000000 --- a/vendor/github.com/lib/pq/TESTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# Tests - -## Running Tests - -`go test` is used for testing. A running PostgreSQL -server is required, with the ability to log in. The -database to connect to test with is "pqgotest," on -"localhost" but these can be overridden using [environment -variables](https://www.postgresql.org/docs/9.3/static/libpq-envars.html). - -Example: - - PGHOST=/run/postgresql go test - -## Benchmarks - -A benchmark suite can be run as part of the tests: - - go test -bench . - -## Example setup (Docker) - -Run a postgres container: - -``` -docker run --expose 5432:5432 postgres -``` - -Run tests: - -``` -PGHOST=localhost PGPORT=5432 PGUSER=postgres PGSSLMODE=disable PGDATABASE=postgres go test -``` diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go deleted file mode 100644 index e4933e227..000000000 --- a/vendor/github.com/lib/pq/array.go +++ /dev/null @@ -1,756 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql" - "database/sql/driver" - "encoding/hex" - "fmt" - "reflect" - "strconv" - "strings" -) - -var typeByteSlice = reflect.TypeOf([]byte{}) -var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() -var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() - -// Array returns the optimal driver.Valuer and sql.Scanner for an array or -// slice of any dimension. -// -// For example: -// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401})) -// -// var x []sql.NullInt64 -// db.QueryRow('SELECT ARRAY[235, 401]').Scan(pq.Array(&x)) -// -// Scanning multi-dimensional arrays is not supported. Arrays where the lower -// bound is not one (such as `[0:0]={1}') are not supported. -func Array(a interface{}) interface { - driver.Valuer - sql.Scanner -} { - switch a := a.(type) { - case []bool: - return (*BoolArray)(&a) - case []float64: - return (*Float64Array)(&a) - case []int64: - return (*Int64Array)(&a) - case []string: - return (*StringArray)(&a) - - case *[]bool: - return (*BoolArray)(a) - case *[]float64: - return (*Float64Array)(a) - case *[]int64: - return (*Int64Array)(a) - case *[]string: - return (*StringArray)(a) - } - - return GenericArray{a} -} - -// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner -// to override the array delimiter used by GenericArray. -type ArrayDelimiter interface { - // ArrayDelimiter returns the delimiter character(s) for this element's type. - ArrayDelimiter() string -} - -// BoolArray represents a one-dimensional array of the PostgreSQL boolean type. -type BoolArray []bool - -// Scan implements the sql.Scanner interface. -func (a *BoolArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to BoolArray", src) -} - -func (a *BoolArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "BoolArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(BoolArray, len(elems)) - for i, v := range elems { - if len(v) != 1 { - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - switch v[0] { - case 't': - b[i] = true - case 'f': - b[i] = false - default: - return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a BoolArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be exactly two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1+2*n) - - for i := 0; i < n; i++ { - b[2*i] = ',' - if a[i] { - b[1+2*i] = 't' - } else { - b[1+2*i] = 'f' - } - } - - b[0] = '{' - b[2*n] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type. -type ByteaArray [][]byte - -// Scan implements the sql.Scanner interface. -func (a *ByteaArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to ByteaArray", src) -} - -func (a *ByteaArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "ByteaArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(ByteaArray, len(elems)) - for i, v := range elems { - b[i], err = parseBytea(v) - if err != nil { - return fmt.Errorf("could not parse bytea array index %d: %s", i, err.Error()) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. It uses the "hex" format which -// is only supported on PostgreSQL 9.0 or newer. -func (a ByteaArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // 3*N bytes of hex formatting, and N-1 bytes of delimiters. - size := 1 + 6*n - for _, x := range a { - size += hex.EncodedLen(len(x)) - } - - b := make([]byte, size) - - for i, s := 0, b; i < n; i++ { - o := copy(s, `,"\\x`) - o += hex.Encode(s[o:], a[i]) - s[o] = '"' - s = s[o+1:] - } - - b[0] = '{' - b[size-1] = '}' - - return string(b), nil - } - - return "{}", nil -} - -// Float64Array represents a one-dimensional array of the PostgreSQL double -// precision type. -type Float64Array []float64 - -// Scan implements the sql.Scanner interface. -func (a *Float64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Float64Array", src) -} - -func (a *Float64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Float64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Float64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseFloat(string(v), 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Float64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendFloat(b, a[0], 'f', -1, 64) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendFloat(b, a[i], 'f', -1, 64) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// GenericArray implements the driver.Valuer and sql.Scanner interfaces for -// an array or slice of any dimension. -type GenericArray struct{ A interface{} } - -func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { - var assign func([]byte, reflect.Value) error - var del = "," - - // TODO calculate the assign function for other types - // TODO repeat this section on the element type of arrays or slices (multidimensional) - { - if reflect.PtrTo(rt).Implements(typeSQLScanner) { - // dest is always addressable because it is an element of a slice. - assign = func(src []byte, dest reflect.Value) (err error) { - ss := dest.Addr().Interface().(sql.Scanner) - if src == nil { - err = ss.Scan(nil) - } else { - err = ss.Scan(src) - } - return - } - goto FoundType - } - - assign = func([]byte, reflect.Value) error { - return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt) - } - } - -FoundType: - - if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - return rt, assign, del -} - -// Scan implements the sql.Scanner interface. -func (a GenericArray) Scan(src interface{}) error { - dpv := reflect.ValueOf(a.A) - switch { - case dpv.Kind() != reflect.Ptr: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - case dpv.IsNil(): - return fmt.Errorf("pq: destination %T is nil", a.A) - } - - dv := dpv.Elem() - switch dv.Kind() { - case reflect.Slice: - case reflect.Array: - default: - return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) - } - - switch src := src.(type) { - case []byte: - return a.scanBytes(src, dv) - case string: - return a.scanBytes([]byte(src), dv) - case nil: - if dv.Kind() == reflect.Slice { - dv.Set(reflect.Zero(dv.Type())) - return nil - } - } - - return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type()) -} - -func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error { - dtype, assign, del := a.evaluateDestination(dv.Type().Elem()) - dims, elems, err := parseArray(src, []byte(del)) - if err != nil { - return err - } - - // TODO allow multidimensional - - if len(dims) > 1 { - return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented", - strings.Replace(fmt.Sprint(dims), " ", "][", -1)) - } - - // Treat a zero-dimensional array like an array with a single dimension of zero. - if len(dims) == 0 { - dims = append(dims, 0) - } - - for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() { - switch rt.Kind() { - case reflect.Slice: - case reflect.Array: - if rt.Len() != dims[i] { - return fmt.Errorf("pq: cannot convert ARRAY%s to %s", - strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type()) - } - default: - // TODO handle multidimensional - } - } - - values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems)) - for i, e := range elems { - if err := assign(e, values.Index(i)); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - - // TODO handle multidimensional - - switch dv.Kind() { - case reflect.Slice: - dv.Set(values.Slice(0, dims[0])) - case reflect.Array: - for i := 0; i < dims[0]; i++ { - dv.Index(i).Set(values.Index(i)) - } - } - - return nil -} - -// Value implements the driver.Valuer interface. -func (a GenericArray) Value() (driver.Value, error) { - if a.A == nil { - return nil, nil - } - - rv := reflect.ValueOf(a.A) - - switch rv.Kind() { - case reflect.Slice: - if rv.IsNil() { - return nil, nil - } - case reflect.Array: - default: - return nil, fmt.Errorf("pq: Unable to convert %T to array", a.A) - } - - if n := rv.Len(); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 0, 1+2*n) - - b, _, err := appendArray(b, rv, n) - return string(b), err - } - - return "{}", nil -} - -// Int64Array represents a one-dimensional array of the PostgreSQL integer types. -type Int64Array []int64 - -// Scan implements the sql.Scanner interface. -func (a *Int64Array) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to Int64Array", src) -} - -func (a *Int64Array) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "Int64Array") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(Int64Array, len(elems)) - for i, v := range elems { - if b[i], err = strconv.ParseInt(string(v), 10, 64); err != nil { - return fmt.Errorf("pq: parsing array element index %d: %v", i, err) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a Int64Array) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, N bytes of values, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+2*n) - b[0] = '{' - - b = strconv.AppendInt(b, a[0], 10) - for i := 1; i < n; i++ { - b = append(b, ',') - b = strconv.AppendInt(b, a[i], 10) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// StringArray represents a one-dimensional array of the PostgreSQL character types. -type StringArray []string - -// Scan implements the sql.Scanner interface. -func (a *StringArray) Scan(src interface{}) error { - switch src := src.(type) { - case []byte: - return a.scanBytes(src) - case string: - return a.scanBytes([]byte(src)) - case nil: - *a = nil - return nil - } - - return fmt.Errorf("pq: cannot convert %T to StringArray", src) -} - -func (a *StringArray) scanBytes(src []byte) error { - elems, err := scanLinearArray(src, []byte{','}, "StringArray") - if err != nil { - return err - } - if *a != nil && len(elems) == 0 { - *a = (*a)[:0] - } else { - b := make(StringArray, len(elems)) - for i, v := range elems { - if b[i] = string(v); v == nil { - return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i) - } - } - *a = b - } - return nil -} - -// Value implements the driver.Valuer interface. -func (a StringArray) Value() (driver.Value, error) { - if a == nil { - return nil, nil - } - - if n := len(a); n > 0 { - // There will be at least two curly brackets, 2*N bytes of quotes, - // and N-1 bytes of delimiters. - b := make([]byte, 1, 1+3*n) - b[0] = '{' - - b = appendArrayQuotedBytes(b, []byte(a[0])) - for i := 1; i < n; i++ { - b = append(b, ',') - b = appendArrayQuotedBytes(b, []byte(a[i])) - } - - return string(append(b, '}')), nil - } - - return "{}", nil -} - -// appendArray appends rv to the buffer, returning the extended buffer and -// the delimiter used between elements. -// -// It panics when n <= 0 or rv's Kind is not reflect.Array nor reflect.Slice. -func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) { - var del string - var err error - - b = append(b, '{') - - if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil { - return b, del, err - } - - for i := 1; i < n; i++ { - b = append(b, del...) - if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil { - return b, del, err - } - } - - return append(b, '}'), del, nil -} - -// appendArrayElement appends rv to the buffer, returning the extended buffer -// and the delimiter to use before the next element. -// -// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted -// using driver.DefaultParameterConverter and the resulting []byte or string -// is double-quoted. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { - if k := rv.Kind(); k == reflect.Array || k == reflect.Slice { - if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) { - if n := rv.Len(); n > 0 { - return appendArray(b, rv, n) - } - - return b, "", nil - } - } - - var del = "," - var err error - var iv interface{} = rv.Interface() - - if ad, ok := iv.(ArrayDelimiter); ok { - del = ad.ArrayDelimiter() - } - - if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil { - return b, del, err - } - - switch v := iv.(type) { - case nil: - return append(b, "NULL"...), del, nil - case []byte: - return appendArrayQuotedBytes(b, v), del, nil - case string: - return appendArrayQuotedBytes(b, []byte(v)), del, nil - } - - b, err = appendValue(b, iv) - return b, del, err -} - -func appendArrayQuotedBytes(b, v []byte) []byte { - b = append(b, '"') - for { - i := bytes.IndexAny(v, `"\`) - if i < 0 { - b = append(b, v...) - break - } - if i > 0 { - b = append(b, v[:i]...) - } - b = append(b, '\\', v[i]) - v = v[i+1:] - } - return append(b, '"') -} - -func appendValue(b []byte, v driver.Value) ([]byte, error) { - return append(b, encode(nil, v, 0)...), nil -} - -// parseArray extracts the dimensions and elements of an array represented in -// text format. Only representations emitted by the backend are supported. -// Notably, whitespace around brackets and delimiters is significant, and NULL -// is case-sensitive. -// -// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO -func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) { - var depth, i int - - if len(src) < 1 || src[0] != '{' { - return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0) - } - -Open: - for i < len(src) { - switch src[i] { - case '{': - depth++ - i++ - case '}': - elems = make([][]byte, 0) - goto Close - default: - break Open - } - } - dims = make([]int, i) - -Element: - for i < len(src) { - switch src[i] { - case '{': - if depth == len(dims) { - break Element - } - depth++ - dims[depth-1] = 0 - i++ - case '"': - var elem = []byte{} - var escape bool - for i++; i < len(src); i++ { - if escape { - elem = append(elem, src[i]) - escape = false - } else { - switch src[i] { - default: - elem = append(elem, src[i]) - case '\\': - escape = true - case '"': - elems = append(elems, elem) - i++ - break Element - } - } - } - default: - for start := i; i < len(src); i++ { - if bytes.HasPrefix(src[i:], del) || src[i] == '}' { - elem := src[start:i] - if len(elem) == 0 { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - if bytes.Equal(elem, []byte("NULL")) { - elem = nil - } - elems = append(elems, elem) - break Element - } - } - } - } - - for i < len(src) { - if bytes.HasPrefix(src[i:], del) && depth > 0 { - dims[depth-1]++ - i += len(del) - goto Element - } else if src[i] == '}' && depth > 0 { - dims[depth-1]++ - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - -Close: - for i < len(src) { - if src[i] == '}' && depth > 0 { - depth-- - i++ - } else { - return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) - } - } - if depth > 0 { - err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i) - } - if err == nil { - for _, d := range dims { - if (len(elems) % d) != 0 { - err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions") - } - } - } - return -} - -func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) { - dims, elems, err := parseArray(src, del) - if err != nil { - return nil, err - } - if len(dims) > 1 { - return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ) - } - return elems, err -} diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go deleted file mode 100644 index 666b0012a..000000000 --- a/vendor/github.com/lib/pq/buf.go +++ /dev/null @@ -1,91 +0,0 @@ -package pq - -import ( - "bytes" - "encoding/binary" - - "github.com/lib/pq/oid" -) - -type readBuf []byte - -func (b *readBuf) int32() (n int) { - n = int(int32(binary.BigEndian.Uint32(*b))) - *b = (*b)[4:] - return -} - -func (b *readBuf) oid() (n oid.Oid) { - n = oid.Oid(binary.BigEndian.Uint32(*b)) - *b = (*b)[4:] - return -} - -// N.B: this is actually an unsigned 16-bit integer, unlike int32 -func (b *readBuf) int16() (n int) { - n = int(binary.BigEndian.Uint16(*b)) - *b = (*b)[2:] - return -} - -func (b *readBuf) string() string { - i := bytes.IndexByte(*b, 0) - if i < 0 { - errorf("invalid message format; expected string terminator") - } - s := (*b)[:i] - *b = (*b)[i+1:] - return string(s) -} - -func (b *readBuf) next(n int) (v []byte) { - v = (*b)[:n] - *b = (*b)[n:] - return -} - -func (b *readBuf) byte() byte { - return b.next(1)[0] -} - -type writeBuf struct { - buf []byte - pos int -} - -func (b *writeBuf) int32(n int) { - x := make([]byte, 4) - binary.BigEndian.PutUint32(x, uint32(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) int16(n int) { - x := make([]byte, 2) - binary.BigEndian.PutUint16(x, uint16(n)) - b.buf = append(b.buf, x...) -} - -func (b *writeBuf) string(s string) { - b.buf = append(b.buf, (s + "\000")...) -} - -func (b *writeBuf) byte(c byte) { - b.buf = append(b.buf, c) -} - -func (b *writeBuf) bytes(v []byte) { - b.buf = append(b.buf, v...) -} - -func (b *writeBuf) wrap() []byte { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - return b.buf -} - -func (b *writeBuf) next(c byte) { - p := b.buf[b.pos:] - binary.BigEndian.PutUint32(p, uint32(len(p))) - b.pos = len(b.buf) + 1 - b.buf = append(b.buf, c, 0, 0, 0, 0) -} diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go deleted file mode 100644 index 43c8df29f..000000000 --- a/vendor/github.com/lib/pq/conn.go +++ /dev/null @@ -1,1854 +0,0 @@ -package pq - -import ( - "bufio" - "crypto/md5" - "database/sql" - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "io" - "net" - "os" - "os/user" - "path" - "path/filepath" - "strconv" - "strings" - "time" - "unicode" - - "github.com/lib/pq/oid" -) - -// Common error types -var ( - ErrNotSupported = errors.New("pq: Unsupported command") - ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") - ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") - ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less") - ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly") - - errUnexpectedReady = errors.New("unexpected ReadyForQuery") - errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") - errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") -) - -// Driver is the Postgres database driver. -type Driver struct{} - -// Open opens a new connection to the database. name is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func (d *Driver) Open(name string) (driver.Conn, error) { - return Open(name) -} - -func init() { - sql.Register("postgres", &Driver{}) -} - -type parameterStatus struct { - // server version in the same format as server_version_num, or 0 if - // unavailable - serverVersion int - - // the current location based on the TimeZone value of the session, if - // available - currentLocation *time.Location -} - -type transactionStatus byte - -const ( - txnStatusIdle transactionStatus = 'I' - txnStatusIdleInTransaction transactionStatus = 'T' - txnStatusInFailedTransaction transactionStatus = 'E' -) - -func (s transactionStatus) String() string { - switch s { - case txnStatusIdle: - return "idle" - case txnStatusIdleInTransaction: - return "idle in transaction" - case txnStatusInFailedTransaction: - return "in a failed transaction" - default: - errorf("unknown transactionStatus %d", s) - } - - panic("not reached") -} - -// Dialer is the dialer interface. It can be used to obtain more control over -// how pq creates network connections. -type Dialer interface { - Dial(network, address string) (net.Conn, error) - DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) -} - -type defaultDialer struct{} - -func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) { - return net.Dial(ntw, addr) -} -func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) { - return net.DialTimeout(ntw, addr, timeout) -} - -type conn struct { - c net.Conn - buf *bufio.Reader - namei int - scratch [512]byte - txnStatus transactionStatus - txnFinish func() - - // Save connection arguments to use during CancelRequest. - dialer Dialer - opts values - - // Cancellation key data for use with CancelRequest messages. - processID int - secretKey int - - parameterStatus parameterStatus - - saveMessageType byte - saveMessageBuffer []byte - - // If true, this connection is bad and all public-facing functions should - // return ErrBadConn. - bad bool - - // If set, this connection should never use the binary format when - // receiving query results from prepared statements. Only provided for - // debugging. - disablePreparedBinaryResult bool - - // Whether to always send []byte parameters over as binary. Enables single - // round-trip mode for non-prepared Query calls. - binaryParameters bool - - // If true this connection is in the middle of a COPY - inCopy bool -} - -// Handle driver-side settings in parsed connection string. -func (cn *conn) handleDriverSettings(o values) (err error) { - boolSetting := func(key string, val *bool) error { - if value, ok := o[key]; ok { - if value == "yes" { - *val = true - } else if value == "no" { - *val = false - } else { - return fmt.Errorf("unrecognized value %q for %s", value, key) - } - } - return nil - } - - err = boolSetting("disable_prepared_binary_result", &cn.disablePreparedBinaryResult) - if err != nil { - return err - } - return boolSetting("binary_parameters", &cn.binaryParameters) -} - -func (cn *conn) handlePgpass(o values) { - // if a password was supplied, do not process .pgpass - if _, ok := o["password"]; ok { - return - } - filename := os.Getenv("PGPASSFILE") - if filename == "" { - // XXX this code doesn't work on Windows where the default filename is - // XXX %APPDATA%\postgresql\pgpass.conf - // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 - userHome := os.Getenv("HOME") - if userHome == "" { - user, err := user.Current() - if err != nil { - return - } - userHome = user.HomeDir - } - filename = filepath.Join(userHome, ".pgpass") - } - fileinfo, err := os.Stat(filename) - if err != nil { - return - } - mode := fileinfo.Mode() - if mode&(0x77) != 0 { - // XXX should warn about incorrect .pgpass permissions as psql does - return - } - file, err := os.Open(filename) - if err != nil { - return - } - defer file.Close() - scanner := bufio.NewScanner(io.Reader(file)) - hostname := o["host"] - ntw, _ := network(o) - port := o["port"] - db := o["dbname"] - username := o["user"] - // From: https://github.com/tg/pgpass/blob/master/reader.go - getFields := func(s string) []string { - fs := make([]string, 0, 5) - f := make([]rune, 0, len(s)) - - var esc bool - for _, c := range s { - switch { - case esc: - f = append(f, c) - esc = false - case c == '\\': - esc = true - case c == ':': - fs = append(fs, string(f)) - f = f[:0] - default: - f = append(f, c) - } - } - return append(fs, string(f)) - } - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 || line[0] == '#' { - continue - } - split := getFields(line) - if len(split) != 5 { - continue - } - if (split[0] == "*" || split[0] == hostname || (split[0] == "localhost" && (hostname == "" || ntw == "unix"))) && (split[1] == "*" || split[1] == port) && (split[2] == "*" || split[2] == db) && (split[3] == "*" || split[3] == username) { - o["password"] = split[4] - return - } - } -} - -func (cn *conn) writeBuf(b byte) *writeBuf { - cn.scratch[0] = b - return &writeBuf{ - buf: cn.scratch[:5], - pos: 1, - } -} - -// Open opens a new connection to the database. name is a connection string. -// Most users should only use it through database/sql package from the standard -// library. -func Open(name string) (_ driver.Conn, err error) { - return DialOpen(defaultDialer{}, name) -} - -// DialOpen opens a new connection to the database using a dialer. -func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { - // Handle any panics during connection initialization. Note that we - // specifically do *not* want to use errRecover(), as that would turn any - // connection errors into ErrBadConns, hiding the real error message from - // the user. - defer errRecoverNoErrBadConn(&err) - - o := make(values) - - // A number of defaults are applied here, in this order: - // - // * Very low precedence defaults applied in every situation - // * Environment variables - // * Explicitly passed connection information - o["host"] = "localhost" - o["port"] = "5432" - // N.B.: Extra float digits should be set to 3, but that breaks - // Postgres 8.4 and older, where the max is 2. - o["extra_float_digits"] = "2" - for k, v := range parseEnviron(os.Environ()) { - o[k] = v - } - - if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") { - name, err = ParseURL(name) - if err != nil { - return nil, err - } - } - - if err := parseOpts(name, o); err != nil { - return nil, err - } - - // Use the "fallback" application name if necessary - if fallback, ok := o["fallback_application_name"]; ok { - if _, ok := o["application_name"]; !ok { - o["application_name"] = fallback - } - } - - // We can't work with any client_encoding other than UTF-8 currently. - // However, we have historically allowed the user to set it to UTF-8 - // explicitly, and there's no reason to break such programs, so allow that. - // Note that the "options" setting could also set client_encoding, but - // parsing its value is not worth it. Instead, we always explicitly send - // client_encoding as a separate run-time parameter, which should override - // anything set in options. - if enc, ok := o["client_encoding"]; ok && !isUTF8(enc) { - return nil, errors.New("client_encoding must be absent or 'UTF8'") - } - o["client_encoding"] = "UTF8" - // DateStyle needs a similar treatment. - if datestyle, ok := o["datestyle"]; ok { - if datestyle != "ISO, MDY" { - panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v", - "ISO, MDY", datestyle)) - } - } else { - o["datestyle"] = "ISO, MDY" - } - - // If a user is not provided by any other means, the last - // resort is to use the current operating system provided user - // name. - if _, ok := o["user"]; !ok { - u, err := userCurrent() - if err != nil { - return nil, err - } - o["user"] = u - } - - cn := &conn{ - opts: o, - dialer: d, - } - err = cn.handleDriverSettings(o) - if err != nil { - return nil, err - } - cn.handlePgpass(o) - - cn.c, err = dial(d, o) - if err != nil { - return nil, err - } - - err = cn.ssl(o) - if err != nil { - return nil, err - } - - // cn.startup panics on error. Make sure we don't leak cn.c. - panicking := true - defer func() { - if panicking { - cn.c.Close() - } - }() - - cn.buf = bufio.NewReader(cn.c) - cn.startup(o) - - // reset the deadline, in case one was set (see dial) - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - err = cn.c.SetDeadline(time.Time{}) - } - panicking = false - return cn, err -} - -func dial(d Dialer, o values) (net.Conn, error) { - ntw, addr := network(o) - // SSL is not necessary or supported over UNIX domain sockets - if ntw == "unix" { - o["sslmode"] = "disable" - } - - // Zero or not specified means wait indefinitely. - if timeout, ok := o["connect_timeout"]; ok && timeout != "0" { - seconds, err := strconv.ParseInt(timeout, 10, 0) - if err != nil { - return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) - } - duration := time.Duration(seconds) * time.Second - // connect_timeout should apply to the entire connection establishment - // procedure, so we both use a timeout for the TCP connection - // establishment and set a deadline for doing the initial handshake. - // The deadline is then reset after startup() is done. - deadline := time.Now().Add(duration) - conn, err := d.DialTimeout(ntw, addr, duration) - if err != nil { - return nil, err - } - err = conn.SetDeadline(deadline) - return conn, err - } - return d.Dial(ntw, addr) -} - -func network(o values) (string, string) { - host := o["host"] - - if strings.HasPrefix(host, "/") { - sockPath := path.Join(host, ".s.PGSQL."+o["port"]) - return "unix", sockPath - } - - return "tcp", net.JoinHostPort(host, o["port"]) -} - -type values map[string]string - -// scanner implements a tokenizer for libpq-style option strings. -type scanner struct { - s []rune - i int -} - -// newScanner returns a new scanner initialized with the option string s. -func newScanner(s string) *scanner { - return &scanner{[]rune(s), 0} -} - -// Next returns the next rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) Next() (rune, bool) { - if s.i >= len(s.s) { - return 0, false - } - r := s.s[s.i] - s.i++ - return r, true -} - -// SkipSpaces returns the next non-whitespace rune. -// It returns 0, false if the end of the text has been reached. -func (s *scanner) SkipSpaces() (rune, bool) { - r, ok := s.Next() - for unicode.IsSpace(r) && ok { - r, ok = s.Next() - } - return r, ok -} - -// parseOpts parses the options from name and adds them to the values. -// -// The parsing code is based on conninfo_parse from libpq's fe-connect.c -func parseOpts(name string, o values) error { - s := newScanner(name) - - for { - var ( - keyRunes, valRunes []rune - r rune - ok bool - ) - - if r, ok = s.SkipSpaces(); !ok { - break - } - - // Scan the key - for !unicode.IsSpace(r) && r != '=' { - keyRunes = append(keyRunes, r) - if r, ok = s.Next(); !ok { - break - } - } - - // Skip any whitespace if we're not at the = yet - if r != '=' { - r, ok = s.SkipSpaces() - } - - // The current character should be = - if r != '=' || !ok { - return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) - } - - // Skip any whitespace after the = - if r, ok = s.SkipSpaces(); !ok { - // If we reach the end here, the last value is just an empty string as per libpq. - o[string(keyRunes)] = "" - break - } - - if r != '\'' { - for !unicode.IsSpace(r) { - if r == '\\' { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`missing character after backslash`) - } - } - valRunes = append(valRunes, r) - - if r, ok = s.Next(); !ok { - break - } - } - } else { - quote: - for { - if r, ok = s.Next(); !ok { - return fmt.Errorf(`unterminated quoted string literal in connection string`) - } - switch r { - case '\'': - break quote - case '\\': - r, _ = s.Next() - fallthrough - default: - valRunes = append(valRunes, r) - } - } - } - - o[string(keyRunes)] = string(valRunes) - } - - return nil -} - -func (cn *conn) isInTransaction() bool { - return cn.txnStatus == txnStatusIdleInTransaction || - cn.txnStatus == txnStatusInFailedTransaction -} - -func (cn *conn) checkIsInTransaction(intxn bool) { - if cn.isInTransaction() != intxn { - cn.bad = true - errorf("unexpected transaction status %v", cn.txnStatus) - } -} - -func (cn *conn) Begin() (_ driver.Tx, err error) { - return cn.begin("") -} - -func (cn *conn) begin(mode string) (_ driver.Tx, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(false) - _, commandTag, err := cn.simpleExec("BEGIN" + mode) - if err != nil { - return nil, err - } - if commandTag != "BEGIN" { - cn.bad = true - return nil, fmt.Errorf("unexpected command tag %s", commandTag) - } - if cn.txnStatus != txnStatusIdleInTransaction { - cn.bad = true - return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) - } - return cn, nil -} - -func (cn *conn) closeTxn() { - if finish := cn.txnFinish; finish != nil { - finish() - } -} - -func (cn *conn) Commit() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(true) - // We don't want the client to think that everything is okay if it tries - // to commit a failed transaction. However, no matter what we return, - // database/sql will release this connection back into the free connection - // pool so we have to abort the current transaction here. Note that you - // would get the same behaviour if you issued a COMMIT in a failed - // transaction, so it's also the least surprising thing to do here. - if cn.txnStatus == txnStatusInFailedTransaction { - if err := cn.Rollback(); err != nil { - return err - } - return ErrInFailedTransaction - } - - _, commandTag, err := cn.simpleExec("COMMIT") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "COMMIT" { - cn.bad = true - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) Rollback() (err error) { - defer cn.closeTxn() - if cn.bad { - return driver.ErrBadConn - } - defer cn.errRecover(&err) - - cn.checkIsInTransaction(true) - _, commandTag, err := cn.simpleExec("ROLLBACK") - if err != nil { - if cn.isInTransaction() { - cn.bad = true - } - return err - } - if commandTag != "ROLLBACK" { - return fmt.Errorf("unexpected command tag %s", commandTag) - } - cn.checkIsInTransaction(false) - return nil -} - -func (cn *conn) gname() string { - cn.namei++ - return strconv.FormatInt(int64(cn.namei), 10) -} - -func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C': - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - // done - return - case 'E': - err = parseError(r) - case 'I': - res = emptyRows - case 'T', 'D': - // ignore any results - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -func (cn *conn) simpleQuery(q string) (res *rows, err error) { - defer cn.errRecover(&err) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'C', 'I': - // We allow queries which don't return any results through Query as - // well as Exec. We still have to give database/sql a rows object - // the user can close, though, to avoid connections from being - // leaked. A "rows" with done=true works fine for that purpose. - if err != nil { - cn.bad = true - errorf("unexpected message %q in simple query execution", t) - } - if res == nil { - res = &rows{ - cn: cn, - } - } - // Set the result and tag to the last command complete if there wasn't a - // query already run. Although queries usually return from here and cede - // control to Next, a query with zero results does not. - if t == 'C' && res.colNames == nil { - res.result, res.tag = cn.parseComplete(r.string()) - } - res.done = true - case 'Z': - cn.processReadyForQuery(r) - // done - return - case 'E': - res = nil - err = parseError(r) - case 'D': - if res == nil { - cn.bad = true - errorf("unexpected DataRow in simple query execution") - } - // the query didn't fail; kick off to Next - cn.saveMessage(t, r) - return - case 'T': - // res might be non-nil here if we received a previous - // CommandComplete, but that's fine; just overwrite it - res = &rows{cn: cn} - res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r) - - // To work around a bug in QueryRow in Go 1.2 and earlier, wait - // until the first DataRow has been received. - default: - cn.bad = true - errorf("unknown response for simple query: %q", t) - } - } -} - -type noRows struct{} - -var emptyRows noRows - -var _ driver.Result = noRows{} - -func (noRows) LastInsertId() (int64, error) { - return 0, errNoLastInsertID -} - -func (noRows) RowsAffected() (int64, error) { - return 0, errNoRowsAffected -} - -// Decides which column formats to use for a prepared statement. The input is -// an array of type oids, one element per result column. -func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte) { - if len(colTyps) == 0 { - return nil, colFmtDataAllText - } - - colFmts = make([]format, len(colTyps)) - if forceText { - return colFmts, colFmtDataAllText - } - - allBinary := true - allText := true - for i, t := range colTyps { - switch t.OID { - // This is the list of types to use binary mode for when receiving them - // through a prepared statement. If a type appears in this list, it - // must also be implemented in binaryDecode in encode.go. - case oid.T_bytea: - fallthrough - case oid.T_int8: - fallthrough - case oid.T_int4: - fallthrough - case oid.T_int2: - fallthrough - case oid.T_uuid: - colFmts[i] = formatBinary - allText = false - - default: - allBinary = false - } - } - - if allBinary { - return colFmts, colFmtDataAllBinary - } else if allText { - return colFmts, colFmtDataAllText - } else { - colFmtData = make([]byte, 2+len(colFmts)*2) - binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) - for i, v := range colFmts { - binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) - } - return colFmts, colFmtData - } -} - -func (cn *conn) prepareTo(q, stmtName string) *stmt { - st := &stmt{cn: cn, name: stmtName} - - b := cn.writeBuf('P') - b.string(st.name) - b.string(q) - b.int16(0) - - b.next('D') - b.byte('S') - b.string(st.name) - - b.next('S') - cn.send(b) - - cn.readParseResponse() - st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() - st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) - cn.readReadyForQuery() - return st -} - -func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { - s, err := cn.prepareCopyIn(q) - if err == nil { - cn.inCopy = true - } - return s, err - } - return cn.prepareTo(q, cn.gname()), nil -} - -func (cn *conn) Close() (err error) { - // Skip cn.bad return here because we always want to close a connection. - defer cn.errRecover(&err) - - // Ensure that cn.c.Close is always run. Since error handling is done with - // panics and cn.errRecover, the Close must be in a defer. - defer func() { - cerr := cn.c.Close() - if err == nil { - err = cerr - } - }() - - // Don't go through send(); ListenerConn relies on us not scribbling on the - // scratch buffer of this connection. - return cn.sendSimpleMessage('X') -} - -// Implement the "Queryer" interface -func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { - return cn.query(query, args) -} - -func (cn *conn) query(query string, args []driver.Value) (_ *rows, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - if cn.inCopy { - return nil, errCopyInProgress - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleQuery" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - return cn.simpleQuery(query) - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - rows := &rows{cn: cn} - rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - return rows, nil - } - st := cn.prepareTo(query, "") - st.exec(args) - return &rows{ - cn: cn, - colNames: st.colNames, - colTyps: st.colTyps, - colFmts: st.colFmts, - }, nil -} - -// Implement the optional "Execer" interface for one-shot queries -func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { - if cn.bad { - return nil, driver.ErrBadConn - } - defer cn.errRecover(&err) - - // Check to see if we can use the "simpleExec" interface, which is - // *much* faster than going through prepare/exec - if len(args) == 0 { - // ignore commandTag, our caller doesn't care - r, _, err := cn.simpleExec(query) - return r, err - } - - if cn.binaryParameters { - cn.sendBinaryModeQuery(query, args) - - cn.readParseResponse() - cn.readBindResponse() - cn.readPortalDescribeResponse() - cn.postExecuteWorkaround() - res, _, err = cn.readExecuteResponse("Execute") - return res, err - } - // Use the unnamed statement to defer planning until bind - // time, or else value-based selectivity estimates cannot be - // used. - st := cn.prepareTo(query, "") - r, err := st.Exec(args) - if err != nil { - panic(err) - } - return r, err -} - -func (cn *conn) send(m *writeBuf) { - _, err := cn.c.Write(m.wrap()) - if err != nil { - panic(err) - } -} - -func (cn *conn) sendStartupPacket(m *writeBuf) error { - _, err := cn.c.Write((m.wrap())[1:]) - return err -} - -// Send a message of type typ to the server on the other end of cn. The -// message should have no payload. This method does not use the scratch -// buffer. -func (cn *conn) sendSimpleMessage(typ byte) (err error) { - _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) - return err -} - -// saveMessage memorizes a message and its buffer in the conn struct. -// recvMessage will then return these values on the next call to it. This -// method is useful in cases where you have to see what the next message is -// going to be (e.g. to see whether it's an error or not) but you can't handle -// the message yourself. -func (cn *conn) saveMessage(typ byte, buf *readBuf) { - if cn.saveMessageType != 0 { - cn.bad = true - errorf("unexpected saveMessageType %d", cn.saveMessageType) - } - cn.saveMessageType = typ - cn.saveMessageBuffer = *buf -} - -// recvMessage receives any message from the backend, or returns an error if -// a problem occurred while reading the message. -func (cn *conn) recvMessage(r *readBuf) (byte, error) { - // workaround for a QueryRow bug, see exec - if cn.saveMessageType != 0 { - t := cn.saveMessageType - *r = cn.saveMessageBuffer - cn.saveMessageType = 0 - cn.saveMessageBuffer = nil - return t, nil - } - - x := cn.scratch[:5] - _, err := io.ReadFull(cn.buf, x) - if err != nil { - return 0, err - } - - // read the type and length of the message that follows - t := x[0] - n := int(binary.BigEndian.Uint32(x[1:])) - 4 - var y []byte - if n <= len(cn.scratch) { - y = cn.scratch[:n] - } else { - y = make([]byte, n) - } - _, err = io.ReadFull(cn.buf, y) - if err != nil { - return 0, err - } - *r = y - return t, nil -} - -// recv receives a message from the backend, but if an error happened while -// reading the message or the received message was an ErrorResponse, it panics. -// NoticeResponses are ignored. This function should generally be used only -// during the startup sequence. -func (cn *conn) recv() (t byte, r *readBuf) { - for { - var err error - r = &readBuf{} - t, err = cn.recvMessage(r) - if err != nil { - panic(err) - } - - switch t { - case 'E': - panic(parseError(r)) - case 'N': - // ignore - default: - return - } - } -} - -// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by -// the caller to avoid an allocation. -func (cn *conn) recv1Buf(r *readBuf) byte { - for { - t, err := cn.recvMessage(r) - if err != nil { - panic(err) - } - - switch t { - case 'A', 'N': - // ignore - case 'S': - cn.processParameterStatus(r) - default: - return t - } - } -} - -// recv1 receives a message from the backend, panicking if an error occurs -// while attempting to read it. All asynchronous messages are ignored, with -// the exception of ErrorResponse. -func (cn *conn) recv1() (t byte, r *readBuf) { - r = &readBuf{} - t = cn.recv1Buf(r) - return t, r -} - -func (cn *conn) ssl(o values) error { - upgrade, err := ssl(o) - if err != nil { - return err - } - - if upgrade == nil { - // Nothing to do - return nil - } - - w := cn.writeBuf(0) - w.int32(80877103) - if err = cn.sendStartupPacket(w); err != nil { - return err - } - - b := cn.scratch[:1] - _, err = io.ReadFull(cn.c, b) - if err != nil { - return err - } - - if b[0] != 'S' { - return ErrSSLNotSupported - } - - cn.c, err = upgrade(cn.c) - return err -} - -// isDriverSetting returns true iff a setting is purely for configuring the -// driver's options and should not be sent to the server in the connection -// startup packet. -func isDriverSetting(key string) bool { - switch key { - case "host", "port": - return true - case "password": - return true - case "sslmode", "sslcert", "sslkey", "sslrootcert": - return true - case "fallback_application_name": - return true - case "connect_timeout": - return true - case "disable_prepared_binary_result": - return true - case "binary_parameters": - return true - - default: - return false - } -} - -func (cn *conn) startup(o values) { - w := cn.writeBuf(0) - w.int32(196608) - // Send the backend the name of the database we want to connect to, and the - // user we want to connect as. Additionally, we send over any run-time - // parameters potentially included in the connection string. If the server - // doesn't recognize any of them, it will reply with an error. - for k, v := range o { - if isDriverSetting(k) { - // skip options which can't be run-time parameters - continue - } - // The protocol requires us to supply the database name as "database" - // instead of "dbname". - if k == "dbname" { - k = "database" - } - w.string(k) - w.string(v) - } - w.string("") - if err := cn.sendStartupPacket(w); err != nil { - panic(err) - } - - for { - t, r := cn.recv() - switch t { - case 'K': - cn.processBackendKeyData(r) - case 'S': - cn.processParameterStatus(r) - case 'R': - cn.auth(r, o) - case 'Z': - cn.processReadyForQuery(r) - return - default: - errorf("unknown response for startup: %q", t) - } - } -} - -func (cn *conn) auth(r *readBuf, o values) { - switch code := r.int32(); code { - case 0: - // OK - case 3: - w := cn.writeBuf('p') - w.string(o["password"]) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - case 5: - s := string(r.next(4)) - w := cn.writeBuf('p') - w.string("md5" + md5s(md5s(o["password"]+o["user"])+s)) - cn.send(w) - - t, r := cn.recv() - if t != 'R' { - errorf("unexpected password response: %q", t) - } - - if r.int32() != 0 { - errorf("unexpected authentication response: %q", t) - } - default: - errorf("unknown authentication response: %d", code) - } -} - -type format int - -const formatText format = 0 -const formatBinary format = 1 - -// One result-column format code with the value 1 (i.e. all binary). -var colFmtDataAllBinary = []byte{0, 1, 0, 1} - -// No result-column format codes (i.e. all text). -var colFmtDataAllText = []byte{0, 0} - -type stmt struct { - cn *conn - name string - colNames []string - colFmts []format - colFmtData []byte - colTyps []fieldDesc - paramTyps []oid.Oid - closed bool -} - -func (st *stmt) Close() (err error) { - if st.closed { - return nil - } - if st.cn.bad { - return driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - w := st.cn.writeBuf('C') - w.byte('S') - w.string(st.name) - st.cn.send(w) - - st.cn.send(st.cn.writeBuf('S')) - - t, _ := st.cn.recv1() - if t != '3' { - st.cn.bad = true - errorf("unexpected close response: %q", t) - } - st.closed = true - - t, r := st.cn.recv1() - if t != 'Z' { - st.cn.bad = true - errorf("expected ready for query, but got: %q", t) - } - st.cn.processReadyForQuery(r) - - return nil -} - -func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - return &rows{ - cn: st.cn, - colNames: st.colNames, - colTyps: st.colTyps, - colFmts: st.colFmts, - }, nil -} - -func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { - if st.cn.bad { - return nil, driver.ErrBadConn - } - defer st.cn.errRecover(&err) - - st.exec(v) - res, _, err = st.cn.readExecuteResponse("simple query") - return res, err -} - -func (st *stmt) exec(v []driver.Value) { - if len(v) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) - } - if len(v) != len(st.paramTyps) { - errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) - } - - cn := st.cn - w := cn.writeBuf('B') - w.byte(0) // unnamed portal - w.string(st.name) - - if cn.binaryParameters { - cn.sendBinaryParameters(w, v) - } else { - w.int16(0) - w.int16(len(v)) - for i, x := range v { - if x == nil { - w.int32(-1) - } else { - b := encode(&cn.parameterStatus, x, st.paramTyps[i]) - w.int32(len(b)) - w.bytes(b) - } - } - } - w.bytes(st.colFmtData) - - w.next('E') - w.byte(0) - w.int32(0) - - w.next('S') - cn.send(w) - - cn.readBindResponse() - cn.postExecuteWorkaround() - -} - -func (st *stmt) NumInput() int { - return len(st.paramTyps) -} - -// parseComplete parses the "command tag" from a CommandComplete message, and -// returns the number of rows affected (if applicable) and a string -// identifying only the command that was executed, e.g. "ALTER TABLE". If the -// command tag could not be parsed, parseComplete panics. -func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { - commandsWithAffectedRows := []string{ - "SELECT ", - // INSERT is handled below - "UPDATE ", - "DELETE ", - "FETCH ", - "MOVE ", - "COPY ", - } - - var affectedRows *string - for _, tag := range commandsWithAffectedRows { - if strings.HasPrefix(commandTag, tag) { - t := commandTag[len(tag):] - affectedRows = &t - commandTag = tag[:len(tag)-1] - break - } - } - // INSERT also includes the oid of the inserted row in its command tag. - // Oids in user tables are deprecated, and the oid is only returned when - // exactly one row is inserted, so it's unlikely to be of value to any - // real-world application and we can ignore it. - if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { - parts := strings.Split(commandTag, " ") - if len(parts) != 3 { - cn.bad = true - errorf("unexpected INSERT command tag %s", commandTag) - } - affectedRows = &parts[len(parts)-1] - commandTag = "INSERT" - } - // There should be no affected rows attached to the tag, just return it - if affectedRows == nil { - return driver.RowsAffected(0), commandTag - } - n, err := strconv.ParseInt(*affectedRows, 10, 64) - if err != nil { - cn.bad = true - errorf("could not parse commandTag: %s", err) - } - return driver.RowsAffected(n), commandTag -} - -type rows struct { - cn *conn - finish func() - colNames []string - colTyps []fieldDesc - colFmts []format - done bool - rb readBuf - result driver.Result - tag string -} - -func (rs *rows) Close() error { - if finish := rs.finish; finish != nil { - defer finish() - } - // no need to look at cn.bad as Next() will - for { - err := rs.Next(nil) - switch err { - case nil: - case io.EOF: - // rs.Next can return io.EOF on both 'Z' (ready for query) and 'T' (row - // description, used with HasNextResultSet). We need to fetch messages until - // we hit a 'Z', which is done by waiting for done to be set. - if rs.done { - return nil - } - default: - return err - } - } -} - -func (rs *rows) Columns() []string { - return rs.colNames -} - -func (rs *rows) Result() driver.Result { - if rs.result == nil { - return emptyRows - } - return rs.result -} - -func (rs *rows) Tag() string { - return rs.tag -} - -func (rs *rows) Next(dest []driver.Value) (err error) { - if rs.done { - return io.EOF - } - - conn := rs.cn - if conn.bad { - return driver.ErrBadConn - } - defer conn.errRecover(&err) - - for { - t := conn.recv1Buf(&rs.rb) - switch t { - case 'E': - err = parseError(&rs.rb) - case 'C', 'I': - if t == 'C' { - rs.result, rs.tag = conn.parseComplete(rs.rb.string()) - } - continue - case 'Z': - conn.processReadyForQuery(&rs.rb) - rs.done = true - if err != nil { - return err - } - return io.EOF - case 'D': - n := rs.rb.int16() - if err != nil { - conn.bad = true - errorf("unexpected DataRow after error %s", err) - } - if n < len(dest) { - dest = dest[:n] - } - for i := range dest { - l := rs.rb.int32() - if l == -1 { - dest[i] = nil - continue - } - dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) - } - return - case 'T': - rs.colNames, rs.colFmts, rs.colTyps = parsePortalRowDescribe(&rs.rb) - return io.EOF - default: - errorf("unexpected message after execute: %q", t) - } - } -} - -func (rs *rows) HasNextResultSet() bool { - return !rs.done -} - -func (rs *rows) NextResultSet() error { - return nil -} - -// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be -// used as part of an SQL statement. For example: -// -// tblname := "my_table" -// data := "my_data" -// quoted := pq.QuoteIdentifier(tblname) -// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) -// -// Any double quotes in name will be escaped. The quoted identifier will be -// case sensitive when used in a query. If the input string contains a zero -// byte, the result will be truncated immediately before it. -func QuoteIdentifier(name string) string { - end := strings.IndexRune(name, 0) - if end > -1 { - name = name[:end] - } - return `"` + strings.Replace(name, `"`, `""`, -1) + `"` -} - -func md5s(s string) string { - h := md5.New() - h.Write([]byte(s)) - return fmt.Sprintf("%x", h.Sum(nil)) -} - -func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { - // Do one pass over the parameters to see if we're going to send any of - // them over in binary. If we are, create a paramFormats array at the - // same time. - var paramFormats []int - for i, x := range args { - _, ok := x.([]byte) - if ok { - if paramFormats == nil { - paramFormats = make([]int, len(args)) - } - paramFormats[i] = 1 - } - } - if paramFormats == nil { - b.int16(0) - } else { - b.int16(len(paramFormats)) - for _, x := range paramFormats { - b.int16(x) - } - } - - b.int16(len(args)) - for _, x := range args { - if x == nil { - b.int32(-1) - } else { - datum := binaryEncode(&cn.parameterStatus, x) - b.int32(len(datum)) - b.bytes(datum) - } - } -} - -func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { - if len(args) >= 65536 { - errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) - } - - b := cn.writeBuf('P') - b.byte(0) // unnamed statement - b.string(query) - b.int16(0) - - b.next('B') - b.int16(0) // unnamed portal and statement - cn.sendBinaryParameters(b, args) - b.bytes(colFmtDataAllText) - - b.next('D') - b.byte('P') - b.byte(0) // unnamed portal - - b.next('E') - b.byte(0) - b.int32(0) - - b.next('S') - cn.send(b) -} - -func (cn *conn) processParameterStatus(r *readBuf) { - var err error - - param := r.string() - switch param { - case "server_version": - var major1 int - var major2 int - var minor int - _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) - if err == nil { - cn.parameterStatus.serverVersion = major1*10000 + major2*100 + minor - } - - case "TimeZone": - cn.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) - if err != nil { - cn.parameterStatus.currentLocation = nil - } - - default: - // ignore - } -} - -func (cn *conn) processReadyForQuery(r *readBuf) { - cn.txnStatus = transactionStatus(r.byte()) -} - -func (cn *conn) readReadyForQuery() { - t, r := cn.recv1() - switch t { - case 'Z': - cn.processReadyForQuery(r) - return - default: - cn.bad = true - errorf("unexpected message %q; expected ReadyForQuery", t) - } -} - -func (cn *conn) processBackendKeyData(r *readBuf) { - cn.processID = r.int32() - cn.secretKey = r.int32() -} - -func (cn *conn) readParseResponse() { - t, r := cn.recv1() - switch t { - case '1': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Parse response %q", t) - } -} - -func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc) { - for { - t, r := cn.recv1() - switch t { - case 't': - nparams := r.int16() - paramTyps = make([]oid.Oid, nparams) - for i := range paramTyps { - paramTyps[i] = r.oid() - } - case 'n': - return paramTyps, nil, nil - case 'T': - colNames, colTyps = parseStatementRowDescribe(r) - return paramTyps, colNames, colTyps - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe statement response %q", t) - } - } -} - -func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []fieldDesc) { - t, r := cn.recv1() - switch t { - case 'T': - return parsePortalRowDescribe(r) - case 'n': - return nil, nil, nil - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Describe response %q", t) - } - panic("not reached") -} - -func (cn *conn) readBindResponse() { - t, r := cn.recv1() - switch t { - case '2': - return - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - default: - cn.bad = true - errorf("unexpected Bind response %q", t) - } -} - -func (cn *conn) postExecuteWorkaround() { - // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores - // any errors from rows.Next, which masks errors that happened during the - // execution of the query. To avoid the problem in common cases, we wait - // here for one more message from the database. If it's not an error the - // query will likely succeed (or perhaps has already, if it's a - // CommandComplete), so we push the message into the conn struct; recv1 - // will return it as the next message for rows.Next or rows.Close. - // However, if it's an error, we wait until ReadyForQuery and then return - // the error to our caller. - for { - t, r := cn.recv1() - switch t { - case 'E': - err := parseError(r) - cn.readReadyForQuery() - panic(err) - case 'C', 'D', 'I': - // the query didn't fail, but we can't process this message - cn.saveMessage(t, r) - return - default: - cn.bad = true - errorf("unexpected message during extended query execution: %q", t) - } - } -} - -// Only for Exec(), since we ignore the returned data -func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { - for { - t, r := cn.recv1() - switch t { - case 'C': - if err != nil { - cn.bad = true - errorf("unexpected CommandComplete after error %s", err) - } - res, commandTag = cn.parseComplete(r.string()) - case 'Z': - cn.processReadyForQuery(r) - if res == nil && err == nil { - err = errUnexpectedReady - } - return res, commandTag, err - case 'E': - err = parseError(r) - case 'T', 'D', 'I': - if err != nil { - cn.bad = true - errorf("unexpected %q after error %s", t, err) - } - if t == 'I' { - res = emptyRows - } - // ignore any results - default: - cn.bad = true - errorf("unknown %s response: %q", protocolState, t) - } - } -} - -func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { - n := r.int16() - colNames = make([]string, n) - colTyps = make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - // format code not known when describing a statement; always 0 - r.next(2) - } - return -} - -func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []fieldDesc) { - n := r.int16() - colNames = make([]string, n) - colFmts = make([]format, n) - colTyps = make([]fieldDesc, n) - for i := range colNames { - colNames[i] = r.string() - r.next(6) - colTyps[i].OID = r.oid() - colTyps[i].Len = r.int16() - colTyps[i].Mod = r.int32() - colFmts[i] = format(r.int16()) - } - return -} - -// parseEnviron tries to mimic some of libpq's environment handling -// -// To ease testing, it does not directly reference os.Environ, but is -// designed to accept its output. -// -// Environment-set connection information is intended to have a higher -// precedence than a library default but lower than any explicitly -// passed information (such as in the URL or connection string). -func parseEnviron(env []string) (out map[string]string) { - out = make(map[string]string) - - for _, v := range env { - parts := strings.SplitN(v, "=", 2) - - accrue := func(keyname string) { - out[keyname] = parts[1] - } - unsupported := func() { - panic(fmt.Sprintf("setting %v not supported", parts[0])) - } - - // The order of these is the same as is seen in the - // PostgreSQL 9.1 manual. Unsupported but well-defined - // keys cause a panic; these should be unset prior to - // execution. Options which pq expects to be set to a - // certain value are allowed, but must be set to that - // value if present (they can, of course, be absent). - switch parts[0] { - case "PGHOST": - accrue("host") - case "PGHOSTADDR": - unsupported() - case "PGPORT": - accrue("port") - case "PGDATABASE": - accrue("dbname") - case "PGUSER": - accrue("user") - case "PGPASSWORD": - accrue("password") - case "PGSERVICE", "PGSERVICEFILE", "PGREALM": - unsupported() - case "PGOPTIONS": - accrue("options") - case "PGAPPNAME": - accrue("application_name") - case "PGSSLMODE": - accrue("sslmode") - case "PGSSLCERT": - accrue("sslcert") - case "PGSSLKEY": - accrue("sslkey") - case "PGSSLROOTCERT": - accrue("sslrootcert") - case "PGREQUIRESSL", "PGSSLCRL": - unsupported() - case "PGREQUIREPEER": - unsupported() - case "PGKRBSRVNAME", "PGGSSLIB": - unsupported() - case "PGCONNECT_TIMEOUT": - accrue("connect_timeout") - case "PGCLIENTENCODING": - accrue("client_encoding") - case "PGDATESTYLE": - accrue("datestyle") - case "PGTZ": - accrue("timezone") - case "PGGEQO": - accrue("geqo") - case "PGSYSCONFDIR", "PGLOCALEDIR": - unsupported() - } - } - - return out -} - -// isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". -func isUTF8(name string) bool { - // Recognize all sorts of silly things as "UTF-8", like Postgres does - s := strings.Map(alnumLowerASCII, name) - return s == "utf8" || s == "unicode" -} - -func alnumLowerASCII(ch rune) rune { - if 'A' <= ch && ch <= 'Z' { - return ch + ('a' - 'A') - } - if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { - return ch - } - return -1 // discard -} diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go deleted file mode 100644 index a5254f2b4..000000000 --- a/vendor/github.com/lib/pq/conn_go18.go +++ /dev/null @@ -1,131 +0,0 @@ -// +build go1.8 - -package pq - -import ( - "context" - "database/sql" - "database/sql/driver" - "fmt" - "io" - "io/ioutil" -) - -// Implement the "QueryerContext" interface -func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - finish := cn.watchCancel(ctx) - r, err := cn.query(query, list) - if err != nil { - if finish != nil { - finish() - } - return nil, err - } - r.finish = finish - return r, nil -} - -// Implement the "ExecerContext" interface -func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { - list := make([]driver.Value, len(args)) - for i, nv := range args { - list[i] = nv.Value - } - - if finish := cn.watchCancel(ctx); finish != nil { - defer finish() - } - - return cn.Exec(query, list) -} - -// Implement the "ConnBeginTx" interface -func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - var mode string - - switch sql.IsolationLevel(opts.Isolation) { - case sql.LevelDefault: - // Don't touch mode: use the server's default - case sql.LevelReadUncommitted: - mode = " ISOLATION LEVEL READ UNCOMMITTED" - case sql.LevelReadCommitted: - mode = " ISOLATION LEVEL READ COMMITTED" - case sql.LevelRepeatableRead: - mode = " ISOLATION LEVEL REPEATABLE READ" - case sql.LevelSerializable: - mode = " ISOLATION LEVEL SERIALIZABLE" - default: - return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation) - } - - if opts.ReadOnly { - mode += " READ ONLY" - } else { - mode += " READ WRITE" - } - - tx, err := cn.begin(mode) - if err != nil { - return nil, err - } - cn.txnFinish = cn.watchCancel(ctx) - return tx, nil -} - -func (cn *conn) watchCancel(ctx context.Context) func() { - if done := ctx.Done(); done != nil { - finished := make(chan struct{}) - go func() { - select { - case <-done: - _ = cn.cancel() - finished <- struct{}{} - case <-finished: - } - }() - return func() { - select { - case <-finished: - case finished <- struct{}{}: - } - } - } - return nil -} - -func (cn *conn) cancel() error { - c, err := dial(cn.dialer, cn.opts) - if err != nil { - return err - } - defer c.Close() - - { - can := conn{ - c: c, - } - err = can.ssl(cn.opts) - if err != nil { - return err - } - - w := can.writeBuf(0) - w.int32(80877102) // cancel request code - w.int32(cn.processID) - w.int32(cn.secretKey) - - if err := can.sendStartupPacket(w); err != nil { - return err - } - } - - // Read until EOF to ensure that the server received the cancel. - { - _, err := io.Copy(ioutil.Discard, c) - return err - } -} diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go deleted file mode 100644 index 9e66eb5df..000000000 --- a/vendor/github.com/lib/pq/connector.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build go1.10 - -package pq - -import ( - "context" - "database/sql/driver" -) - -// Connector represents a fixed configuration for the pq driver with a given -// name. Connector satisfies the database/sql/driver Connector interface and -// can be used to create any number of DB Conn's via the database/sql OpenDB -// function. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -type connector struct { - name string -} - -// Connect returns a connection to the database using the fixed configuration -// of this Connector. Context is not used. -func (c *connector) Connect(_ context.Context) (driver.Conn, error) { - return (&Driver{}).Open(c.name) -} - -// Driver returnst the underlying driver of this Connector. -func (c *connector) Driver() driver.Driver { - return &Driver{} -} - -var _ driver.Connector = &connector{} - -// NewConnector returns a connector for the pq driver in a fixed configuration -// with the given name. The returned connector can be used to create any number -// of equivalent Conn's. The returned connector is intended to be used with -// database/sql.OpenDB. -// -// See https://golang.org/pkg/database/sql/driver/#Connector. -// See https://golang.org/pkg/database/sql/#OpenDB. -func NewConnector(name string) (driver.Connector, error) { - return &connector{name: name}, nil -} diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go deleted file mode 100644 index 345c2398f..000000000 --- a/vendor/github.com/lib/pq/copy.go +++ /dev/null @@ -1,282 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "sync" -) - -var ( - errCopyInClosed = errors.New("pq: copyin statement has already been closed") - errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") - errCopyToNotSupported = errors.New("pq: COPY TO is not supported") - errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") - errCopyInProgress = errors.New("pq: COPY in progress") -) - -// CopyIn creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). The target table should be visible in search_path. -func CopyIn(table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -// CopyInSchema creates a COPY FROM statement which can be prepared with -// Tx.Prepare(). -func CopyInSchema(schema, table string, columns ...string) string { - stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " (" - for i, col := range columns { - if i != 0 { - stmt += ", " - } - stmt += QuoteIdentifier(col) - } - stmt += ") FROM STDIN" - return stmt -} - -type copyin struct { - cn *conn - buffer []byte - rowData chan []byte - done chan bool - - closed bool - - sync.Mutex // guards err - err error -} - -const ciBufferSize = 64 * 1024 - -// flush buffer before the buffer is filled up and needs reallocation -const ciBufferFlushSize = 63 * 1024 - -func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) { - if !cn.isInTransaction() { - return nil, errCopyNotSupportedOutsideTxn - } - - ci := ©in{ - cn: cn, - buffer: make([]byte, 0, ciBufferSize), - rowData: make(chan []byte), - done: make(chan bool, 1), - } - // add CopyData identifier + 4 bytes for message length - ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0) - - b := cn.writeBuf('Q') - b.string(q) - cn.send(b) - -awaitCopyInResponse: - for { - t, r := cn.recv1() - switch t { - case 'G': - if r.byte() != 0 { - err = errBinaryCopyNotSupported - break awaitCopyInResponse - } - go ci.resploop() - return ci, nil - case 'H': - err = errCopyToNotSupported - break awaitCopyInResponse - case 'E': - err = parseError(r) - case 'Z': - if err == nil { - ci.setBad() - errorf("unexpected ReadyForQuery in response to COPY") - } - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for copy query: %q", t) - } - } - - // something went wrong, abort COPY before we return - b = cn.writeBuf('f') - b.string(err.Error()) - cn.send(b) - - for { - t, r := cn.recv1() - switch t { - case 'c', 'C', 'E': - case 'Z': - // correctly aborted, we're done - cn.processReadyForQuery(r) - return nil, err - default: - ci.setBad() - errorf("unknown response for CopyFail: %q", t) - } - } -} - -func (ci *copyin) flush(buf []byte) { - // set message length (without message identifier) - binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) - - _, err := ci.cn.c.Write(buf) - if err != nil { - panic(err) - } -} - -func (ci *copyin) resploop() { - for { - var r readBuf - t, err := ci.cn.recvMessage(&r) - if err != nil { - ci.setBad() - ci.setError(err) - ci.done <- true - return - } - switch t { - case 'C': - // complete - case 'N': - // NoticeResponse - case 'Z': - ci.cn.processReadyForQuery(&r) - ci.done <- true - return - case 'E': - err := parseError(&r) - ci.setError(err) - default: - ci.setBad() - ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) - ci.done <- true - return - } - } -} - -func (ci *copyin) setBad() { - ci.Lock() - ci.cn.bad = true - ci.Unlock() -} - -func (ci *copyin) isBad() bool { - ci.Lock() - b := ci.cn.bad - ci.Unlock() - return b -} - -func (ci *copyin) isErrorSet() bool { - ci.Lock() - isSet := (ci.err != nil) - ci.Unlock() - return isSet -} - -// setError() sets ci.err if one has not been set already. Caller must not be -// holding ci.Mutex. -func (ci *copyin) setError(err error) { - ci.Lock() - if ci.err == nil { - ci.err = err - } - ci.Unlock() -} - -func (ci *copyin) NumInput() int { - return -1 -} - -func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { - return nil, ErrNotSupported -} - -// Exec inserts values into the COPY stream. The insert is asynchronous -// and Exec can return errors from previous Exec calls to the same -// COPY stmt. -// -// You need to call Exec(nil) to sync the COPY stream and to get any -// errors from pending data, since Stmt.Close() doesn't return errors -// to the user. -func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { - if ci.closed { - return nil, errCopyInClosed - } - - if ci.isBad() { - return nil, driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if ci.isErrorSet() { - return nil, ci.err - } - - if len(v) == 0 { - return nil, ci.Close() - } - - numValues := len(v) - for i, value := range v { - ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value) - if i < numValues-1 { - ci.buffer = append(ci.buffer, '\t') - } - } - - ci.buffer = append(ci.buffer, '\n') - - if len(ci.buffer) > ciBufferFlushSize { - ci.flush(ci.buffer) - // reset buffer, keep bytes for message identifier and length - ci.buffer = ci.buffer[:5] - } - - return driver.RowsAffected(0), nil -} - -func (ci *copyin) Close() (err error) { - if ci.closed { // Don't do anything, we're already closed - return nil - } - ci.closed = true - - if ci.isBad() { - return driver.ErrBadConn - } - defer ci.cn.errRecover(&err) - - if len(ci.buffer) > 0 { - ci.flush(ci.buffer) - } - // Avoid touching the scratch buffer as resploop could be using it. - err = ci.cn.sendSimpleMessage('c') - if err != nil { - return err - } - - <-ci.done - ci.cn.inCopy = false - - if ci.isErrorSet() { - err = ci.err - return err - } - return nil -} diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go deleted file mode 100644 index a1b029713..000000000 --- a/vendor/github.com/lib/pq/doc.go +++ /dev/null @@ -1,245 +0,0 @@ -/* -Package pq is a pure Go Postgres driver for the database/sql package. - -In most cases clients will use the database/sql package instead of -using this package directly. For example: - - import ( - "database/sql" - - _ "github.com/lib/pq" - ) - - func main() { - connStr := "user=pqgotest dbname=pqgotest sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - if err != nil { - log.Fatal(err) - } - - age := 21 - rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) - … - } - -You can also connect to a database using a URL. For example: - - connStr := "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full" - db, err := sql.Open("postgres", connStr) - - -Connection String Parameters - - -Similarly to libpq, when establishing a connection using pq you are expected to -supply a connection string containing zero or more parameters. -A subset of the connection parameters supported by libpq are also supported by pq. -Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem) -directly in the connection string. This is different from libpq, which does not allow -run-time parameters in the connection string, instead requiring you to supply -them in the options parameter. - -For compatibility with libpq, the following special connection parameters are -supported: - - * dbname - The name of the database to connect to - * user - The user to sign in as - * password - The user's password - * host - The host to connect to. Values that start with / are for unix - domain sockets. (default is localhost) - * port - The port to bind to. (default is 5432) - * sslmode - Whether or not to use SSL (default is require, this is not - the default for libpq) - * fallback_application_name - An application_name to fall back to if one isn't provided. - * connect_timeout - Maximum wait for connection, in seconds. Zero or - not specified means wait indefinitely. - * sslcert - Cert file location. The file must contain PEM encoded data. - * sslkey - Key file location. The file must contain PEM encoded data. - * sslrootcert - The location of the root certificate file. The file - must contain PEM encoded data. - -Valid values for sslmode are: - - * disable - No SSL - * require - Always SSL (skip verification) - * verify-ca - Always SSL (verify that the certificate presented by the - server was signed by a trusted CA) - * verify-full - Always SSL (verify that the certification presented by - the server was signed by a trusted CA and the server host name - matches the one in the certificate) - -See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING -for more information about connection string parameters. - -Use single quotes for values that contain whitespace: - - "user=pqgotest password='with spaces'" - -A backslash will escape the next character in values: - - "user=space\ man password='it\'s valid'" - -Note that the connection parameter client_encoding (which sets the -text encoding for the connection) may be set but must be "UTF8", -matching with the same rules as Postgres. It is an error to provide -any other value. - -In addition to the parameters listed above, any run-time parameter that can be -set at backend start time can be set in the connection string. For more -information, see -http://www.postgresql.org/docs/current/static/runtime-config.html. - -Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html -supported by libpq are also supported by pq. If any of the environment -variables not supported by pq are set, pq will panic during connection -establishment. Environment variables have a lower precedence than explicitly -provided connection parameters. - -The pgpass mechanism as described in http://www.postgresql.org/docs/current/static/libpq-pgpass.html -is supported, but on Windows PGPASSFILE must be specified explicitly. - - -Queries - - -database/sql does not dictate any specific format for parameter -markers in query strings, and pq uses the Postgres-native ordinal markers, -as shown above. The same marker can be reused for the same parameter: - - rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1 - OR age BETWEEN $2 AND $2 + 3`, "orange", 64) - -pq does not support the LastInsertId() method of the Result type in database/sql. -To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres -RETURNING clause with a standard Query or QueryRow call: - - var userid int - err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age) - VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid) - -For more details on RETURNING, see the Postgres documentation: - - http://www.postgresql.org/docs/current/static/sql-insert.html - http://www.postgresql.org/docs/current/static/sql-update.html - http://www.postgresql.org/docs/current/static/sql-delete.html - -For additional instructions on querying see the documentation for the database/sql package. - - -Data Types - - -Parameters pass through driver.DefaultParameterConverter before they are handled -by this package. When the binary_parameters connection option is enabled, -[]byte values are sent directly to the backend as data in binary format. - -This package returns the following types for values from the PostgreSQL backend: - - - integer types smallint, integer, and bigint are returned as int64 - - floating-point types real and double precision are returned as float64 - - character types char, varchar, and text are returned as string - - temporal types date, time, timetz, timestamp, and timestamptz are - returned as time.Time - - the boolean type is returned as bool - - the bytea type is returned as []byte - -All other types are returned directly from the backend as []byte values in text format. - - -Errors - - -pq may return errors of type *pq.Error which can be interrogated for error details: - - if err, ok := err.(*pq.Error); ok { - fmt.Println("pq error:", err.Code.Name()) - } - -See the pq.Error type for details. - - -Bulk imports - -You can perform bulk imports by preparing a statement returned by pq.CopyIn (or -pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement -handle can then be repeatedly "executed" to copy data into the target table. -After all data has been processed you should call Exec() once with no arguments -to flush all buffered data. Any call to Exec() might return an error which -should be handled appropriately, but because of the internal buffering an error -returned by Exec() might not be related to the data passed in the call that -failed. - -CopyIn uses COPY FROM internally. It is not possible to COPY outside of an -explicit transaction in pq. - -Usage example: - - txn, err := db.Begin() - if err != nil { - log.Fatal(err) - } - - stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age")) - if err != nil { - log.Fatal(err) - } - - for _, user := range users { - _, err = stmt.Exec(user.Name, int64(user.Age)) - if err != nil { - log.Fatal(err) - } - } - - _, err = stmt.Exec() - if err != nil { - log.Fatal(err) - } - - err = stmt.Close() - if err != nil { - log.Fatal(err) - } - - err = txn.Commit() - if err != nil { - log.Fatal(err) - } - - -Notifications - - -PostgreSQL supports a simple publish/subscribe model over database -connections. See http://www.postgresql.org/docs/current/static/sql-notify.html -for more information about the general mechanism. - -To start listening for notifications, you first have to open a new connection -to the database by calling NewListener. This connection can not be used for -anything other than LISTEN / NOTIFY. Calling Listen will open a "notification -channel"; once a notification channel is open, a notification generated on that -channel will effect a send on the Listener.Notify channel. A notification -channel will remain open until Unlisten is called, though connection loss might -result in some notifications being lost. To solve this problem, Listener sends -a nil pointer over the Notify channel any time the connection is re-established -following a connection loss. The application can get information about the -state of the underlying connection by setting an event callback in the call to -NewListener. - -A single Listener can safely be used from concurrent goroutines, which means -that there is often no need to create more than one Listener in your -application. However, a Listener is always connected to a single database, so -you will need to create a new Listener instance for every database you want to -receive notifications in. - -The channel name in both Listen and Unlisten is case sensitive, and can contain -any characters legal in an identifier (see -http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS -for more information). Note that the channel name will be truncated to 63 -bytes by the PostgreSQL server. - -You can find a complete, working example of Listener usage at -http://godoc.org/github.com/lib/pq/example/listen. - -*/ -package pq diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go deleted file mode 100644 index 3b0d365f2..000000000 --- a/vendor/github.com/lib/pq/encode.go +++ /dev/null @@ -1,603 +0,0 @@ -package pq - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "math" - "strconv" - "strings" - "sync" - "time" - - "github.com/lib/pq/oid" -) - -func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte { - switch v := x.(type) { - case []byte: - return v - default: - return encode(parameterStatus, x, oid.T_unknown) - } -} - -func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(nil, v, 10) - case float64: - return strconv.AppendFloat(nil, v, 'f', -1, 64) - case []byte: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, v) - } - - return v - case string: - if pgtypOid == oid.T_bytea { - return encodeBytea(parameterStatus.serverVersion, []byte(v)) - } - - return []byte(v) - case bool: - return strconv.AppendBool(nil, v) - case time.Time: - return formatTs(v) - - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { - switch f { - case formatBinary: - return binaryDecode(parameterStatus, s, typ) - case formatText: - return textDecode(parameterStatus, s, typ) - default: - panic("not reached") - } -} - -func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_bytea: - return s - case oid.T_int8: - return int64(binary.BigEndian.Uint64(s)) - case oid.T_int4: - return int64(int32(binary.BigEndian.Uint32(s))) - case oid.T_int2: - return int64(int16(binary.BigEndian.Uint16(s))) - case oid.T_uuid: - b, err := decodeUUIDBinary(s) - if err != nil { - panic(err) - } - return b - - default: - errorf("don't know how to decode binary parameter of type %d", uint32(typ)) - } - - panic("not reached") -} - -func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { - switch typ { - case oid.T_char, oid.T_varchar, oid.T_text: - return string(s) - case oid.T_bytea: - b, err := parseBytea(s) - if err != nil { - errorf("%s", err) - } - return b - case oid.T_timestamptz: - return parseTs(parameterStatus.currentLocation, string(s)) - case oid.T_timestamp, oid.T_date: - return parseTs(nil, string(s)) - case oid.T_time: - return mustParse("15:04:05", typ, s) - case oid.T_timetz: - return mustParse("15:04:05-07", typ, s) - case oid.T_bool: - return s[0] == 't' - case oid.T_int8, oid.T_int4, oid.T_int2: - i, err := strconv.ParseInt(string(s), 10, 64) - if err != nil { - errorf("%s", err) - } - return i - case oid.T_float4, oid.T_float8: - bits := 64 - if typ == oid.T_float4 { - bits = 32 - } - f, err := strconv.ParseFloat(string(s), bits) - if err != nil { - errorf("%s", err) - } - return f - } - - return s -} - -// appendEncodedText encodes item in text format as required by COPY -// and appends to buf -func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { - switch v := x.(type) { - case int64: - return strconv.AppendInt(buf, v, 10) - case float64: - return strconv.AppendFloat(buf, v, 'f', -1, 64) - case []byte: - encodedBytea := encodeBytea(parameterStatus.serverVersion, v) - return appendEscapedText(buf, string(encodedBytea)) - case string: - return appendEscapedText(buf, v) - case bool: - return strconv.AppendBool(buf, v) - case time.Time: - return append(buf, formatTs(v)...) - case nil: - return append(buf, "\\N"...) - default: - errorf("encode: unknown type for %T", v) - } - - panic("not reached") -} - -func appendEscapedText(buf []byte, text string) []byte { - escapeNeeded := false - startPos := 0 - var c byte - - // check if we need to escape - for i := 0; i < len(text); i++ { - c = text[i] - if c == '\\' || c == '\n' || c == '\r' || c == '\t' { - escapeNeeded = true - startPos = i - break - } - } - if !escapeNeeded { - return append(buf, text...) - } - - // copy till first char to escape, iterate the rest - result := append(buf, text[:startPos]...) - for i := startPos; i < len(text); i++ { - c = text[i] - switch c { - case '\\': - result = append(result, '\\', '\\') - case '\n': - result = append(result, '\\', 'n') - case '\r': - result = append(result, '\\', 'r') - case '\t': - result = append(result, '\\', 't') - default: - result = append(result, c) - } - } - return result -} - -func mustParse(f string, typ oid.Oid, s []byte) time.Time { - str := string(s) - - // check for a 30-minute-offset timezone - if (typ == oid.T_timestamptz || typ == oid.T_timetz) && - str[len(str)-3] == ':' { - f += ":00" - } - t, err := time.Parse(f, str) - if err != nil { - errorf("decode: %s", err) - } - return t -} - -var errInvalidTimestamp = errors.New("invalid timestamp") - -type timestampParser struct { - err error -} - -func (p *timestampParser) expect(str string, char byte, pos int) { - if p.err != nil { - return - } - if pos+1 > len(str) { - p.err = errInvalidTimestamp - return - } - if c := str[pos]; c != char && p.err == nil { - p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c) - } -} - -func (p *timestampParser) mustAtoi(str string, begin int, end int) int { - if p.err != nil { - return 0 - } - if begin < 0 || end < 0 || begin > end || end > len(str) { - p.err = errInvalidTimestamp - return 0 - } - result, err := strconv.Atoi(str[begin:end]) - if err != nil { - if p.err == nil { - p.err = fmt.Errorf("expected number; got '%v'", str) - } - return 0 - } - return result -} - -// The location cache caches the time zones typically used by the client. -type locationCache struct { - cache map[int]*time.Location - lock sync.Mutex -} - -// All connections share the same list of timezones. Benchmarking shows that -// about 5% speed could be gained by putting the cache in the connection and -// losing the mutex, at the cost of a small amount of memory and a somewhat -// significant increase in code complexity. -var globalLocationCache = newLocationCache() - -func newLocationCache() *locationCache { - return &locationCache{cache: make(map[int]*time.Location)} -} - -// Returns the cached timezone for the specified offset, creating and caching -// it if necessary. -func (c *locationCache) getLocation(offset int) *time.Location { - c.lock.Lock() - defer c.lock.Unlock() - - location, ok := c.cache[offset] - if !ok { - location = time.FixedZone("", offset) - c.cache[offset] = location - } - - return location -} - -var infinityTsEnabled = false -var infinityTsNegative time.Time -var infinityTsPositive time.Time - -const ( - infinityTsEnabledAlready = "pq: infinity timestamp enabled already" - infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive" -) - -// EnableInfinityTs controls the handling of Postgres' "-infinity" and -// "infinity" "timestamp"s. -// -// If EnableInfinityTs is not called, "-infinity" and "infinity" will return -// []byte("-infinity") and []byte("infinity") respectively, and potentially -// cause error "sql: Scan error on column index 0: unsupported driver -> Scan -// pair: []uint8 -> *time.Time", when scanning into a time.Time value. -// -// Once EnableInfinityTs has been called, all connections created using this -// driver will decode Postgres' "-infinity" and "infinity" for "timestamp", -// "timestamp with time zone" and "date" types to the predefined minimum and -// maximum times, respectively. When encoding time.Time values, any time which -// equals or precedes the predefined minimum time will be encoded to -// "-infinity". Any values at or past the maximum time will similarly be -// encoded to "infinity". -// -// If EnableInfinityTs is called with negative >= positive, it will panic. -// Calling EnableInfinityTs after a connection has been established results in -// undefined behavior. If EnableInfinityTs is called more than once, it will -// panic. -func EnableInfinityTs(negative time.Time, positive time.Time) { - if infinityTsEnabled { - panic(infinityTsEnabledAlready) - } - if !negative.Before(positive) { - panic(infinityTsNegativeMustBeSmaller) - } - infinityTsEnabled = true - infinityTsNegative = negative - infinityTsPositive = positive -} - -/* - * Testing might want to toggle infinityTsEnabled - */ -func disableInfinityTs() { - infinityTsEnabled = false -} - -// This is a time function specific to the Postgres default DateStyle -// setting ("ISO, MDY"), the only one we currently support. This -// accounts for the discrepancies between the parsing available with -// time.Parse and the Postgres date formatting quirks. -func parseTs(currentLocation *time.Location, str string) interface{} { - switch str { - case "-infinity": - if infinityTsEnabled { - return infinityTsNegative - } - return []byte(str) - case "infinity": - if infinityTsEnabled { - return infinityTsPositive - } - return []byte(str) - } - t, err := ParseTimestamp(currentLocation, str) - if err != nil { - panic(err) - } - return t -} - -// ParseTimestamp parses Postgres' text format. It returns a time.Time in -// currentLocation iff that time's offset agrees with the offset sent from the -// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the -// fixed offset offset provided by the Postgres server. -func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) { - p := timestampParser{} - - monSep := strings.IndexRune(str, '-') - // this is Gregorian year, not ISO Year - // In Gregorian system, the year 1 BC is followed by AD 1 - year := p.mustAtoi(str, 0, monSep) - daySep := monSep + 3 - month := p.mustAtoi(str, monSep+1, daySep) - p.expect(str, '-', daySep) - timeSep := daySep + 3 - day := p.mustAtoi(str, daySep+1, timeSep) - - minLen := monSep + len("01-01") + 1 - - isBC := strings.HasSuffix(str, " BC") - if isBC { - minLen += 3 - } - - var hour, minute, second int - if len(str) > minLen { - p.expect(str, ' ', timeSep) - minSep := timeSep + 3 - p.expect(str, ':', minSep) - hour = p.mustAtoi(str, timeSep+1, minSep) - secSep := minSep + 3 - p.expect(str, ':', secSep) - minute = p.mustAtoi(str, minSep+1, secSep) - secEnd := secSep + 3 - second = p.mustAtoi(str, secSep+1, secEnd) - } - remainderIdx := monSep + len("01-01 00:00:00") + 1 - // Three optional (but ordered) sections follow: the - // fractional seconds, the time zone offset, and the BC - // designation. We set them up here and adjust the other - // offsets if the preceding sections exist. - - nanoSec := 0 - tzOff := 0 - - if remainderIdx < len(str) && str[remainderIdx] == '.' { - fracStart := remainderIdx + 1 - fracOff := strings.IndexAny(str[fracStart:], "-+ ") - if fracOff < 0 { - fracOff = len(str) - fracStart - } - fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff) - nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) - - remainderIdx += fracOff + 1 - } - if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') { - // time zone separator is always '-' or '+' (UTC is +00) - var tzSign int - switch c := str[tzStart]; c { - case '-': - tzSign = -1 - case '+': - tzSign = +1 - default: - return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c) - } - tzHours := p.mustAtoi(str, tzStart+1, tzStart+3) - remainderIdx += 3 - var tzMin, tzSec int - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - if remainderIdx < len(str) && str[remainderIdx] == ':' { - tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) - remainderIdx += 3 - } - tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) - } - var isoYear int - - if isBC { - isoYear = 1 - year - remainderIdx += 3 - } else { - isoYear = year - } - if remainderIdx < len(str) { - return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:]) - } - t := time.Date(isoYear, time.Month(month), day, - hour, minute, second, nanoSec, - globalLocationCache.getLocation(tzOff)) - - if currentLocation != nil { - // Set the location of the returned Time based on the session's - // TimeZone value, but only if the local time zone database agrees with - // the remote database on the offset. - lt := t.In(currentLocation) - _, newOff := lt.Zone() - if newOff == tzOff { - t = lt - } - } - - return t, p.err -} - -// formatTs formats t into a format postgres understands. -func formatTs(t time.Time) []byte { - if infinityTsEnabled { - // t <= -infinity : ! (t > -infinity) - if !t.After(infinityTsNegative) { - return []byte("-infinity") - } - // t >= infinity : ! (!t < infinity) - if !t.Before(infinityTsPositive) { - return []byte("infinity") - } - } - return FormatTimestamp(t) -} - -// FormatTimestamp formats t into Postgres' text format for timestamps. -func FormatTimestamp(t time.Time) []byte { - // Need to send dates before 0001 A.D. with " BC" suffix, instead of the - // minus sign preferred by Go. - // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on - bc := false - if t.Year() <= 0 { - // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" - t = t.AddDate((-t.Year())*2+1, 0, 0) - bc = true - } - b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) - - _, offset := t.Zone() - offset = offset % 60 - if offset != 0 { - // RFC3339Nano already printed the minus sign - if offset < 0 { - offset = -offset - } - - b = append(b, ':') - if offset < 10 { - b = append(b, '0') - } - b = strconv.AppendInt(b, int64(offset), 10) - } - - if bc { - b = append(b, " BC"...) - } - return b -} - -// Parse a bytea value received from the server. Both "hex" and the legacy -// "escape" format are supported. -func parseBytea(s []byte) (result []byte, err error) { - if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { - // bytea_output = hex - s = s[2:] // trim off leading "\\x" - result = make([]byte, hex.DecodedLen(len(s))) - _, err := hex.Decode(result, s) - if err != nil { - return nil, err - } - } else { - // bytea_output = escape - for len(s) > 0 { - if s[0] == '\\' { - // escaped '\\' - if len(s) >= 2 && s[1] == '\\' { - result = append(result, '\\') - s = s[2:] - continue - } - - // '\\' followed by an octal number - if len(s) < 4 { - return nil, fmt.Errorf("invalid bytea sequence %v", s) - } - r, err := strconv.ParseInt(string(s[1:4]), 8, 9) - if err != nil { - return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) - } - result = append(result, byte(r)) - s = s[4:] - } else { - // We hit an unescaped, raw byte. Try to read in as many as - // possible in one go. - i := bytes.IndexByte(s, '\\') - if i == -1 { - result = append(result, s...) - break - } - result = append(result, s[:i]...) - s = s[i:] - } - } - } - - return result, nil -} - -func encodeBytea(serverVersion int, v []byte) (result []byte) { - if serverVersion >= 90000 { - // Use the hex format if we know that the server supports it - result = make([]byte, 2+hex.EncodedLen(len(v))) - result[0] = '\\' - result[1] = 'x' - hex.Encode(result[2:], v) - } else { - // .. or resort to "escape" - for _, b := range v { - if b == '\\' { - result = append(result, '\\', '\\') - } else if b < 0x20 || b > 0x7e { - result = append(result, []byte(fmt.Sprintf("\\%03o", b))...) - } else { - result = append(result, b) - } - } - } - - return result -} - -// NullTime represents a time.Time that may be null. NullTime implements the -// sql.Scanner interface so it can be used as a scan destination, similar to -// sql.NullString. -type NullTime struct { - Time time.Time - Valid bool // Valid is true if Time is not NULL -} - -// Scan implements the Scanner interface. -func (nt *NullTime) Scan(value interface{}) error { - nt.Time, nt.Valid = value.(time.Time) - return nil -} - -// Value implements the driver Valuer interface. -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go deleted file mode 100644 index 96aae29c6..000000000 --- a/vendor/github.com/lib/pq/error.go +++ /dev/null @@ -1,515 +0,0 @@ -package pq - -import ( - "database/sql/driver" - "fmt" - "io" - "net" - "runtime" -) - -// Error severities -const ( - Efatal = "FATAL" - Epanic = "PANIC" - Ewarning = "WARNING" - Enotice = "NOTICE" - Edebug = "DEBUG" - Einfo = "INFO" - Elog = "LOG" -) - -// Error represents an error communicating with the server. -// -// See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields -type Error struct { - Severity string - Code ErrorCode - Message string - Detail string - Hint string - Position string - InternalPosition string - InternalQuery string - Where string - Schema string - Table string - Column string - DataTypeName string - Constraint string - File string - Line string - Routine string -} - -// ErrorCode is a five-character error code. -type ErrorCode string - -// Name returns a more human friendly rendering of the error code, namely the -// "condition name". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Name() string { - return errorCodeNames[ec] -} - -// ErrorClass is only the class part of an error code. -type ErrorClass string - -// Name returns the condition name of an error class. It is equivalent to the -// condition name of the "standard" error code (i.e. the one having the last -// three characters "000"). -func (ec ErrorClass) Name() string { - return errorCodeNames[ErrorCode(ec+"000")] -} - -// Class returns the error class, e.g. "28". -// -// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for -// details. -func (ec ErrorCode) Class() ErrorClass { - return ErrorClass(ec[0:2]) -} - -// errorCodeNames is a mapping between the five-character error codes and the -// human readable "condition names". It is derived from the list at -// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html -var errorCodeNames = map[ErrorCode]string{ - // Class 00 - Successful Completion - "00000": "successful_completion", - // Class 01 - Warning - "01000": "warning", - "0100C": "dynamic_result_sets_returned", - "01008": "implicit_zero_bit_padding", - "01003": "null_value_eliminated_in_set_function", - "01007": "privilege_not_granted", - "01006": "privilege_not_revoked", - "01004": "string_data_right_truncation", - "01P01": "deprecated_feature", - // Class 02 - No Data (this is also a warning class per the SQL standard) - "02000": "no_data", - "02001": "no_additional_dynamic_result_sets_returned", - // Class 03 - SQL Statement Not Yet Complete - "03000": "sql_statement_not_yet_complete", - // Class 08 - Connection Exception - "08000": "connection_exception", - "08003": "connection_does_not_exist", - "08006": "connection_failure", - "08001": "sqlclient_unable_to_establish_sqlconnection", - "08004": "sqlserver_rejected_establishment_of_sqlconnection", - "08007": "transaction_resolution_unknown", - "08P01": "protocol_violation", - // Class 09 - Triggered Action Exception - "09000": "triggered_action_exception", - // Class 0A - Feature Not Supported - "0A000": "feature_not_supported", - // Class 0B - Invalid Transaction Initiation - "0B000": "invalid_transaction_initiation", - // Class 0F - Locator Exception - "0F000": "locator_exception", - "0F001": "invalid_locator_specification", - // Class 0L - Invalid Grantor - "0L000": "invalid_grantor", - "0LP01": "invalid_grant_operation", - // Class 0P - Invalid Role Specification - "0P000": "invalid_role_specification", - // Class 0Z - Diagnostics Exception - "0Z000": "diagnostics_exception", - "0Z002": "stacked_diagnostics_accessed_without_active_handler", - // Class 20 - Case Not Found - "20000": "case_not_found", - // Class 21 - Cardinality Violation - "21000": "cardinality_violation", - // Class 22 - Data Exception - "22000": "data_exception", - "2202E": "array_subscript_error", - "22021": "character_not_in_repertoire", - "22008": "datetime_field_overflow", - "22012": "division_by_zero", - "22005": "error_in_assignment", - "2200B": "escape_character_conflict", - "22022": "indicator_overflow", - "22015": "interval_field_overflow", - "2201E": "invalid_argument_for_logarithm", - "22014": "invalid_argument_for_ntile_function", - "22016": "invalid_argument_for_nth_value_function", - "2201F": "invalid_argument_for_power_function", - "2201G": "invalid_argument_for_width_bucket_function", - "22018": "invalid_character_value_for_cast", - "22007": "invalid_datetime_format", - "22019": "invalid_escape_character", - "2200D": "invalid_escape_octet", - "22025": "invalid_escape_sequence", - "22P06": "nonstandard_use_of_escape_character", - "22010": "invalid_indicator_parameter_value", - "22023": "invalid_parameter_value", - "2201B": "invalid_regular_expression", - "2201W": "invalid_row_count_in_limit_clause", - "2201X": "invalid_row_count_in_result_offset_clause", - "22009": "invalid_time_zone_displacement_value", - "2200C": "invalid_use_of_escape_character", - "2200G": "most_specific_type_mismatch", - "22004": "null_value_not_allowed", - "22002": "null_value_no_indicator_parameter", - "22003": "numeric_value_out_of_range", - "2200H": "sequence_generator_limit_exceeded", - "22026": "string_data_length_mismatch", - "22001": "string_data_right_truncation", - "22011": "substring_error", - "22027": "trim_error", - "22024": "unterminated_c_string", - "2200F": "zero_length_character_string", - "22P01": "floating_point_exception", - "22P02": "invalid_text_representation", - "22P03": "invalid_binary_representation", - "22P04": "bad_copy_file_format", - "22P05": "untranslatable_character", - "2200L": "not_an_xml_document", - "2200M": "invalid_xml_document", - "2200N": "invalid_xml_content", - "2200S": "invalid_xml_comment", - "2200T": "invalid_xml_processing_instruction", - // Class 23 - Integrity Constraint Violation - "23000": "integrity_constraint_violation", - "23001": "restrict_violation", - "23502": "not_null_violation", - "23503": "foreign_key_violation", - "23505": "unique_violation", - "23514": "check_violation", - "23P01": "exclusion_violation", - // Class 24 - Invalid Cursor State - "24000": "invalid_cursor_state", - // Class 25 - Invalid Transaction State - "25000": "invalid_transaction_state", - "25001": "active_sql_transaction", - "25002": "branch_transaction_already_active", - "25008": "held_cursor_requires_same_isolation_level", - "25003": "inappropriate_access_mode_for_branch_transaction", - "25004": "inappropriate_isolation_level_for_branch_transaction", - "25005": "no_active_sql_transaction_for_branch_transaction", - "25006": "read_only_sql_transaction", - "25007": "schema_and_data_statement_mixing_not_supported", - "25P01": "no_active_sql_transaction", - "25P02": "in_failed_sql_transaction", - // Class 26 - Invalid SQL Statement Name - "26000": "invalid_sql_statement_name", - // Class 27 - Triggered Data Change Violation - "27000": "triggered_data_change_violation", - // Class 28 - Invalid Authorization Specification - "28000": "invalid_authorization_specification", - "28P01": "invalid_password", - // Class 2B - Dependent Privilege Descriptors Still Exist - "2B000": "dependent_privilege_descriptors_still_exist", - "2BP01": "dependent_objects_still_exist", - // Class 2D - Invalid Transaction Termination - "2D000": "invalid_transaction_termination", - // Class 2F - SQL Routine Exception - "2F000": "sql_routine_exception", - "2F005": "function_executed_no_return_statement", - "2F002": "modifying_sql_data_not_permitted", - "2F003": "prohibited_sql_statement_attempted", - "2F004": "reading_sql_data_not_permitted", - // Class 34 - Invalid Cursor Name - "34000": "invalid_cursor_name", - // Class 38 - External Routine Exception - "38000": "external_routine_exception", - "38001": "containing_sql_not_permitted", - "38002": "modifying_sql_data_not_permitted", - "38003": "prohibited_sql_statement_attempted", - "38004": "reading_sql_data_not_permitted", - // Class 39 - External Routine Invocation Exception - "39000": "external_routine_invocation_exception", - "39001": "invalid_sqlstate_returned", - "39004": "null_value_not_allowed", - "39P01": "trigger_protocol_violated", - "39P02": "srf_protocol_violated", - // Class 3B - Savepoint Exception - "3B000": "savepoint_exception", - "3B001": "invalid_savepoint_specification", - // Class 3D - Invalid Catalog Name - "3D000": "invalid_catalog_name", - // Class 3F - Invalid Schema Name - "3F000": "invalid_schema_name", - // Class 40 - Transaction Rollback - "40000": "transaction_rollback", - "40002": "transaction_integrity_constraint_violation", - "40001": "serialization_failure", - "40003": "statement_completion_unknown", - "40P01": "deadlock_detected", - // Class 42 - Syntax Error or Access Rule Violation - "42000": "syntax_error_or_access_rule_violation", - "42601": "syntax_error", - "42501": "insufficient_privilege", - "42846": "cannot_coerce", - "42803": "grouping_error", - "42P20": "windowing_error", - "42P19": "invalid_recursion", - "42830": "invalid_foreign_key", - "42602": "invalid_name", - "42622": "name_too_long", - "42939": "reserved_name", - "42804": "datatype_mismatch", - "42P18": "indeterminate_datatype", - "42P21": "collation_mismatch", - "42P22": "indeterminate_collation", - "42809": "wrong_object_type", - "42703": "undefined_column", - "42883": "undefined_function", - "42P01": "undefined_table", - "42P02": "undefined_parameter", - "42704": "undefined_object", - "42701": "duplicate_column", - "42P03": "duplicate_cursor", - "42P04": "duplicate_database", - "42723": "duplicate_function", - "42P05": "duplicate_prepared_statement", - "42P06": "duplicate_schema", - "42P07": "duplicate_table", - "42712": "duplicate_alias", - "42710": "duplicate_object", - "42702": "ambiguous_column", - "42725": "ambiguous_function", - "42P08": "ambiguous_parameter", - "42P09": "ambiguous_alias", - "42P10": "invalid_column_reference", - "42611": "invalid_column_definition", - "42P11": "invalid_cursor_definition", - "42P12": "invalid_database_definition", - "42P13": "invalid_function_definition", - "42P14": "invalid_prepared_statement_definition", - "42P15": "invalid_schema_definition", - "42P16": "invalid_table_definition", - "42P17": "invalid_object_definition", - // Class 44 - WITH CHECK OPTION Violation - "44000": "with_check_option_violation", - // Class 53 - Insufficient Resources - "53000": "insufficient_resources", - "53100": "disk_full", - "53200": "out_of_memory", - "53300": "too_many_connections", - "53400": "configuration_limit_exceeded", - // Class 54 - Program Limit Exceeded - "54000": "program_limit_exceeded", - "54001": "statement_too_complex", - "54011": "too_many_columns", - "54023": "too_many_arguments", - // Class 55 - Object Not In Prerequisite State - "55000": "object_not_in_prerequisite_state", - "55006": "object_in_use", - "55P02": "cant_change_runtime_param", - "55P03": "lock_not_available", - // Class 57 - Operator Intervention - "57000": "operator_intervention", - "57014": "query_canceled", - "57P01": "admin_shutdown", - "57P02": "crash_shutdown", - "57P03": "cannot_connect_now", - "57P04": "database_dropped", - // Class 58 - System Error (errors external to PostgreSQL itself) - "58000": "system_error", - "58030": "io_error", - "58P01": "undefined_file", - "58P02": "duplicate_file", - // Class F0 - Configuration File Error - "F0000": "config_file_error", - "F0001": "lock_file_exists", - // Class HV - Foreign Data Wrapper Error (SQL/MED) - "HV000": "fdw_error", - "HV005": "fdw_column_name_not_found", - "HV002": "fdw_dynamic_parameter_value_needed", - "HV010": "fdw_function_sequence_error", - "HV021": "fdw_inconsistent_descriptor_information", - "HV024": "fdw_invalid_attribute_value", - "HV007": "fdw_invalid_column_name", - "HV008": "fdw_invalid_column_number", - "HV004": "fdw_invalid_data_type", - "HV006": "fdw_invalid_data_type_descriptors", - "HV091": "fdw_invalid_descriptor_field_identifier", - "HV00B": "fdw_invalid_handle", - "HV00C": "fdw_invalid_option_index", - "HV00D": "fdw_invalid_option_name", - "HV090": "fdw_invalid_string_length_or_buffer_length", - "HV00A": "fdw_invalid_string_format", - "HV009": "fdw_invalid_use_of_null_pointer", - "HV014": "fdw_too_many_handles", - "HV001": "fdw_out_of_memory", - "HV00P": "fdw_no_schemas", - "HV00J": "fdw_option_name_not_found", - "HV00K": "fdw_reply_handle", - "HV00Q": "fdw_schema_not_found", - "HV00R": "fdw_table_not_found", - "HV00L": "fdw_unable_to_create_execution", - "HV00M": "fdw_unable_to_create_reply", - "HV00N": "fdw_unable_to_establish_connection", - // Class P0 - PL/pgSQL Error - "P0000": "plpgsql_error", - "P0001": "raise_exception", - "P0002": "no_data_found", - "P0003": "too_many_rows", - // Class XX - Internal Error - "XX000": "internal_error", - "XX001": "data_corrupted", - "XX002": "index_corrupted", -} - -func parseError(r *readBuf) *Error { - err := new(Error) - for t := r.byte(); t != 0; t = r.byte() { - msg := r.string() - switch t { - case 'S': - err.Severity = msg - case 'C': - err.Code = ErrorCode(msg) - case 'M': - err.Message = msg - case 'D': - err.Detail = msg - case 'H': - err.Hint = msg - case 'P': - err.Position = msg - case 'p': - err.InternalPosition = msg - case 'q': - err.InternalQuery = msg - case 'W': - err.Where = msg - case 's': - err.Schema = msg - case 't': - err.Table = msg - case 'c': - err.Column = msg - case 'd': - err.DataTypeName = msg - case 'n': - err.Constraint = msg - case 'F': - err.File = msg - case 'L': - err.Line = msg - case 'R': - err.Routine = msg - } - } - return err -} - -// Fatal returns true if the Error Severity is fatal. -func (err *Error) Fatal() bool { - return err.Severity == Efatal -} - -// Get implements the legacy PGError interface. New code should use the fields -// of the Error struct directly. -func (err *Error) Get(k byte) (v string) { - switch k { - case 'S': - return err.Severity - case 'C': - return string(err.Code) - case 'M': - return err.Message - case 'D': - return err.Detail - case 'H': - return err.Hint - case 'P': - return err.Position - case 'p': - return err.InternalPosition - case 'q': - return err.InternalQuery - case 'W': - return err.Where - case 's': - return err.Schema - case 't': - return err.Table - case 'c': - return err.Column - case 'd': - return err.DataTypeName - case 'n': - return err.Constraint - case 'F': - return err.File - case 'L': - return err.Line - case 'R': - return err.Routine - } - return "" -} - -func (err Error) Error() string { - return "pq: " + err.Message -} - -// PGError is an interface used by previous versions of pq. It is provided -// only to support legacy code. New code should use the Error type. -type PGError interface { - Error() string - Fatal() bool - Get(k byte) (v string) -} - -func errorf(s string, args ...interface{}) { - panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) -} - -// TODO(ainar-g) Rename to errorf after removing panics. -func fmterrorf(s string, args ...interface{}) error { - return fmt.Errorf("pq: %s", fmt.Sprintf(s, args...)) -} - -func errRecoverNoErrBadConn(err *error) { - e := recover() - if e == nil { - // Do nothing - return - } - var ok bool - *err, ok = e.(error) - if !ok { - *err = fmt.Errorf("pq: unexpected error: %#v", e) - } -} - -func (c *conn) errRecover(err *error) { - e := recover() - switch v := e.(type) { - case nil: - // Do nothing - case runtime.Error: - c.bad = true - panic(v) - case *Error: - if v.Fatal() { - *err = driver.ErrBadConn - } else { - *err = v - } - case *net.OpError: - c.bad = true - *err = v - case error: - if v == io.EOF || v.(error).Error() == "remote error: handshake failure" { - *err = driver.ErrBadConn - } else { - *err = v - } - - default: - c.bad = true - panic(fmt.Sprintf("unknown error: %#v", e)) - } - - // Any time we return ErrBadConn, we need to remember it since *Tx doesn't - // mark the connection bad in database/sql. - if *err == driver.ErrBadConn { - c.bad = true - } -} diff --git a/vendor/github.com/lib/pq/go.mod b/vendor/github.com/lib/pq/go.mod deleted file mode 100644 index edf0b343f..000000000 --- a/vendor/github.com/lib/pq/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/lib/pq diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go deleted file mode 100644 index 850bb9040..000000000 --- a/vendor/github.com/lib/pq/notify.go +++ /dev/null @@ -1,797 +0,0 @@ -package pq - -// Package pq is a pure Go Postgres driver for the database/sql package. -// This module contains support for Postgres LISTEN/NOTIFY. - -import ( - "errors" - "fmt" - "sync" - "sync/atomic" - "time" -) - -// Notification represents a single notification from the database. -type Notification struct { - // Process ID (PID) of the notifying postgres backend. - BePid int - // Name of the channel the notification was sent on. - Channel string - // Payload, or the empty string if unspecified. - Extra string -} - -func recvNotification(r *readBuf) *Notification { - bePid := r.int32() - channel := r.string() - extra := r.string() - - return &Notification{bePid, channel, extra} -} - -const ( - connStateIdle int32 = iota - connStateExpectResponse - connStateExpectReadyForQuery -) - -type message struct { - typ byte - err error -} - -var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") - -// ListenerConn is a low-level interface for waiting for notifications. You -// should use Listener instead. -type ListenerConn struct { - // guards cn and err - connectionLock sync.Mutex - cn *conn - err error - - connState int32 - - // the sending goroutine will be holding this lock - senderLock sync.Mutex - - notificationChan chan<- *Notification - - replyChan chan message -} - -// NewListenerConn creates a new ListenerConn. Use NewListener instead. -func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { - return newDialListenerConn(defaultDialer{}, name, notificationChan) -} - -func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) { - cn, err := DialOpen(d, name) - if err != nil { - return nil, err - } - - l := &ListenerConn{ - cn: cn.(*conn), - notificationChan: c, - connState: connStateIdle, - replyChan: make(chan message, 2), - } - - go l.listenerConnMain() - - return l, nil -} - -// We can only allow one goroutine at a time to be running a query on the -// connection for various reasons, so the goroutine sending on the connection -// must be holding senderLock. -// -// Returns an error if an unrecoverable error has occurred and the ListenerConn -// should be abandoned. -func (l *ListenerConn) acquireSenderLock() error { - // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery - l.senderLock.Lock() - - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - if err != nil { - l.senderLock.Unlock() - return err - } - return nil -} - -func (l *ListenerConn) releaseSenderLock() { - l.senderLock.Unlock() -} - -// setState advances the protocol state to newState. Returns false if moving -// to that state from the current state is not allowed. -func (l *ListenerConn) setState(newState int32) bool { - var expectedState int32 - - switch newState { - case connStateIdle: - expectedState = connStateExpectReadyForQuery - case connStateExpectResponse: - expectedState = connStateIdle - case connStateExpectReadyForQuery: - expectedState = connStateExpectResponse - default: - panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) - } - - return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) -} - -// Main logic is here: receive messages from the postgres backend, forward -// notifications and query replies and keep the internal state in sync with the -// protocol state. Returns when the connection has been lost, is about to go -// away or should be discarded because we couldn't agree on the state with the -// server backend. -func (l *ListenerConn) listenerConnLoop() (err error) { - defer errRecoverNoErrBadConn(&err) - - r := &readBuf{} - for { - t, err := l.cn.recvMessage(r) - if err != nil { - return err - } - - switch t { - case 'A': - // recvNotification copies all the data so we don't need to worry - // about the scratch buffer being overwritten. - l.notificationChan <- recvNotification(r) - - case 'T', 'D': - // only used by tests; ignore - - case 'E': - // We might receive an ErrorResponse even when not in a query; it - // is expected that the server will close the connection after - // that, but we should make sure that the error we display is the - // one from the stray ErrorResponse, not io.ErrUnexpectedEOF. - if !l.setState(connStateExpectReadyForQuery) { - return parseError(r) - } - l.replyChan <- message{t, parseError(r)} - - case 'C', 'I': - if !l.setState(connStateExpectReadyForQuery) { - // protocol out of sync - return fmt.Errorf("unexpected CommandComplete") - } - // ExecSimpleQuery doesn't need to know about this message - - case 'Z': - if !l.setState(connStateIdle) { - // protocol out of sync - return fmt.Errorf("unexpected ReadyForQuery") - } - l.replyChan <- message{t, nil} - - case 'N', 'S': - // ignore - default: - return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) - } - } -} - -// This is the main routine for the goroutine receiving on the database -// connection. Most of the main logic is in listenerConnLoop. -func (l *ListenerConn) listenerConnMain() { - err := l.listenerConnLoop() - - // listenerConnLoop terminated; we're done, but we still have to clean up. - // Make sure nobody tries to start any new queries by making sure the err - // pointer is set. It is important that we do not overwrite its value; a - // connection could be closed by either this goroutine or one sending on - // the connection -- whoever closes the connection is assumed to have the - // more meaningful error message (as the other one will probably get - // net.errClosed), so that goroutine sets the error we expose while the - // other error is discarded. If the connection is lost while two - // goroutines are operating on the socket, it probably doesn't matter which - // error we expose so we don't try to do anything more complex. - l.connectionLock.Lock() - if l.err == nil { - l.err = err - } - l.cn.Close() - l.connectionLock.Unlock() - - // There might be a query in-flight; make sure nobody's waiting for a - // response to it, since there's not going to be one. - close(l.replyChan) - - // let the listener know we're done - close(l.notificationChan) - - // this ListenerConn is done -} - -// Listen sends a LISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Listen(channel string) (bool, error) { - return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) -} - -// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery. -func (l *ListenerConn) Unlisten(channel string) (bool, error) { - return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) -} - -// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery. -func (l *ListenerConn) UnlistenAll() (bool, error) { - return l.ExecSimpleQuery("UNLISTEN *") -} - -// Ping the remote server to make sure it's alive. Non-nil error means the -// connection has failed and should be abandoned. -func (l *ListenerConn) Ping() error { - sent, err := l.ExecSimpleQuery("") - if !sent { - return err - } - if err != nil { - // shouldn't happen - panic(err) - } - return nil -} - -// Attempt to send a query on the connection. Returns an error if sending the -// query failed, and the caller should initiate closure of this connection. -// The caller must be holding senderLock (see acquireSenderLock and -// releaseSenderLock). -func (l *ListenerConn) sendSimpleQuery(q string) (err error) { - defer errRecoverNoErrBadConn(&err) - - // must set connection state before sending the query - if !l.setState(connStateExpectResponse) { - panic("two queries running at the same time") - } - - // Can't use l.cn.writeBuf here because it uses the scratch buffer which - // might get overwritten by listenerConnLoop. - b := &writeBuf{ - buf: []byte("Q\x00\x00\x00\x00"), - pos: 1, - } - b.string(q) - l.cn.send(b) - - return nil -} - -// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable -// parameters) on the connection. The possible return values are: -// 1) "executed" is true; the query was executed to completion on the -// database server. If the query failed, err will be set to the error -// returned by the database, otherwise err will be nil. -// 2) If "executed" is false, the query could not be executed on the remote -// server. err will be non-nil. -// -// After a call to ExecSimpleQuery has returned an executed=false value, the -// connection has either been closed or will be closed shortly thereafter, and -// all subsequently executed queries will return an error. -func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { - if err = l.acquireSenderLock(); err != nil { - return false, err - } - defer l.releaseSenderLock() - - err = l.sendSimpleQuery(q) - if err != nil { - // We can't know what state the protocol is in, so we need to abandon - // this connection. - l.connectionLock.Lock() - // Set the error pointer if it hasn't been set already; see - // listenerConnMain. - if l.err == nil { - l.err = err - } - l.connectionLock.Unlock() - l.cn.c.Close() - return false, err - } - - // now we just wait for a reply.. - for { - m, ok := <-l.replyChan - if !ok { - // We lost the connection to server, don't bother waiting for a - // a response. err should have been set already. - l.connectionLock.Lock() - err := l.err - l.connectionLock.Unlock() - return false, err - } - switch m.typ { - case 'Z': - // sanity check - if m.err != nil { - panic("m.err != nil") - } - // done; err might or might not be set - return true, err - - case 'E': - // sanity check - if m.err == nil { - panic("m.err == nil") - } - // server responded with an error; ReadyForQuery to follow - err = m.err - - default: - return false, fmt.Errorf("unknown response for simple query: %q", m.typ) - } - } -} - -// Close closes the connection. -func (l *ListenerConn) Close() error { - l.connectionLock.Lock() - if l.err != nil { - l.connectionLock.Unlock() - return errListenerConnClosed - } - l.err = errListenerConnClosed - l.connectionLock.Unlock() - // We can't send anything on the connection without holding senderLock. - // Simply close the net.Conn to wake up everyone operating on it. - return l.cn.c.Close() -} - -// Err returns the reason the connection was closed. It is not safe to call -// this function until l.Notify has been closed. -func (l *ListenerConn) Err() error { - return l.err -} - -var errListenerClosed = errors.New("pq: Listener has been closed") - -// ErrChannelAlreadyOpen is returned from Listen when a channel is already -// open. -var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") - -// ErrChannelNotOpen is returned from Unlisten when a channel is not open. -var ErrChannelNotOpen = errors.New("pq: channel is not open") - -// ListenerEventType is an enumeration of listener event types. -type ListenerEventType int - -const ( - // ListenerEventConnected is emitted only when the database connection - // has been initially initialized. The err argument of the callback - // will always be nil. - ListenerEventConnected ListenerEventType = iota - - // ListenerEventDisconnected is emitted after a database connection has - // been lost, either because of an error or because Close has been - // called. The err argument will be set to the reason the database - // connection was lost. - ListenerEventDisconnected - - // ListenerEventReconnected is emitted after a database connection has - // been re-established after connection loss. The err argument of the - // callback will always be nil. After this event has been emitted, a - // nil pq.Notification is sent on the Listener.Notify channel. - ListenerEventReconnected - - // ListenerEventConnectionAttemptFailed is emitted after a connection - // to the database was attempted, but failed. The err argument will be - // set to an error describing why the connection attempt did not - // succeed. - ListenerEventConnectionAttemptFailed -) - -// EventCallbackType is the event callback type. See also ListenerEventType -// constants' documentation. -type EventCallbackType func(event ListenerEventType, err error) - -// Listener provides an interface for listening to notifications from a -// PostgreSQL database. For general usage information, see section -// "Notifications". -// -// Listener can safely be used from concurrently running goroutines. -type Listener struct { - // Channel for receiving notifications from the database. In some cases a - // nil value will be sent. See section "Notifications" above. - Notify chan *Notification - - name string - minReconnectInterval time.Duration - maxReconnectInterval time.Duration - dialer Dialer - eventCallback EventCallbackType - - lock sync.Mutex - isClosed bool - reconnectCond *sync.Cond - cn *ListenerConn - connNotificationChan <-chan *Notification - channels map[string]struct{} -} - -// NewListener creates a new database connection dedicated to LISTEN / NOTIFY. -// -// name should be set to a connection string to be used to establish the -// database connection (see section "Connection String Parameters" above). -// -// minReconnectInterval controls the duration to wait before trying to -// re-establish the database connection after connection loss. After each -// consecutive failure this interval is doubled, until maxReconnectInterval is -// reached. Successfully completing the connection establishment procedure -// resets the interval back to minReconnectInterval. -// -// The last parameter eventCallback can be set to a function which will be -// called by the Listener when the state of the underlying database connection -// changes. This callback will be called by the goroutine which dispatches the -// notifications over the Notify channel, so you should try to avoid doing -// potentially time-consuming operations from the callback. -func NewListener(name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - return NewDialListener(defaultDialer{}, name, minReconnectInterval, maxReconnectInterval, eventCallback) -} - -// NewDialListener is like NewListener but it takes a Dialer. -func NewDialListener(d Dialer, - name string, - minReconnectInterval time.Duration, - maxReconnectInterval time.Duration, - eventCallback EventCallbackType) *Listener { - - l := &Listener{ - name: name, - minReconnectInterval: minReconnectInterval, - maxReconnectInterval: maxReconnectInterval, - dialer: d, - eventCallback: eventCallback, - - channels: make(map[string]struct{}), - - Notify: make(chan *Notification, 32), - } - l.reconnectCond = sync.NewCond(&l.lock) - - go l.listenerMain() - - return l -} - -// NotificationChannel returns the notification channel for this listener. -// This is the same channel as Notify, and will not be recreated during the -// life time of the Listener. -func (l *Listener) NotificationChannel() <-chan *Notification { - return l.Notify -} - -// Listen starts listening for notifications on a channel. Calls to this -// function will block until an acknowledgement has been received from the -// server. Note that Listener automatically re-establishes the connection -// after connection loss, so this function may block indefinitely if the -// connection can not be re-established. -// -// Listen will only fail in three conditions: -// 1) The channel is already open. The returned error will be -// ErrChannelAlreadyOpen. -// 2) The query was executed on the remote server, but PostgreSQL returned an -// error message in response to the query. The returned error will be a -// pq.Error containing the information the server supplied. -// 3) Close is called on the Listener before the request could be completed. -// -// The channel name is case-sensitive. -func (l *Listener) Listen(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // The server allows you to issue a LISTEN on a channel which is already - // open, but it seems useful to be able to detect this case to spot for - // mistakes in application logic. If the application genuinely does't - // care, it can check the exported error and ignore it. - _, exists := l.channels[channel] - if exists { - return ErrChannelAlreadyOpen - } - - if l.cn != nil { - // If gotResponse is true but error is set, the query was executed on - // the remote server, but resulted in an error. This should be - // relatively rare, so it's fine if we just pass the error to our - // caller. However, if gotResponse is false, we could not complete the - // query on the remote server and our underlying connection is about - // to go away, so we only add relname to l.channels, and wait for - // resync() to take care of the rest. - gotResponse, err := l.cn.Listen(channel) - if gotResponse && err != nil { - return err - } - } - - l.channels[channel] = struct{}{} - for l.cn == nil { - l.reconnectCond.Wait() - // we let go of the mutex for a while - if l.isClosed { - return errListenerClosed - } - } - - return nil -} - -// Unlisten removes a channel from the Listener's channel list. Returns -// ErrChannelNotOpen if the Listener is not listening on the specified channel. -// Returns immediately with no error if there is no connection. Note that you -// might still get notifications for this channel even after Unlisten has -// returned. -// -// The channel name is case-sensitive. -func (l *Listener) Unlisten(channel string) error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - // Similarly to LISTEN, this is not an error in Postgres, but it seems - // useful to distinguish from the normal conditions. - _, exists := l.channels[channel] - if !exists { - return ErrChannelNotOpen - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.Unlisten(channel) - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - delete(l.channels, channel) - return nil -} - -// UnlistenAll removes all channels from the Listener's channel list. Returns -// immediately with no error if there is no connection. Note that you might -// still get notifications for any of the deleted channels even after -// UnlistenAll has returned. -func (l *Listener) UnlistenAll() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - // Similarly to Listen (see comment in that function), the caller - // should only be bothered with an error if it came from the backend as - // a response to our query. - gotResponse, err := l.cn.UnlistenAll() - if gotResponse && err != nil { - return err - } - } - - // Don't bother waiting for resync if there's no connection. - l.channels = make(map[string]struct{}) - return nil -} - -// Ping the remote server to make sure it's alive. Non-nil return value means -// that there is no active connection. -func (l *Listener) Ping() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - if l.cn == nil { - return errors.New("no connection") - } - - return l.cn.Ping() -} - -// Clean up after losing the server connection. Returns l.cn.Err(), which -// should have the reason the connection was lost. -func (l *Listener) disconnectCleanup() error { - l.lock.Lock() - defer l.lock.Unlock() - - // sanity check; can't look at Err() until the channel has been closed - select { - case _, ok := <-l.connNotificationChan: - if ok { - panic("connNotificationChan not closed") - } - default: - panic("connNotificationChan not closed") - } - - err := l.cn.Err() - l.cn.Close() - l.cn = nil - return err -} - -// Synchronize the list of channels we want to be listening on with the server -// after the connection has been established. -func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { - doneChan := make(chan error) - go func(notificationChan <-chan *Notification) { - for channel := range l.channels { - // If we got a response, return that error to our caller as it's - // going to be more descriptive than cn.Err(). - gotResponse, err := cn.Listen(channel) - if gotResponse && err != nil { - doneChan <- err - return - } - - // If we couldn't reach the server, wait for notificationChan to - // close and then return the error message from the connection, as - // per ListenerConn's interface. - if err != nil { - for range notificationChan { - } - doneChan <- cn.Err() - return - } - } - doneChan <- nil - }(notificationChan) - - // Ignore notifications while synchronization is going on to avoid - // deadlocks. We have to send a nil notification over Notify anyway as - // we can't possibly know which notifications (if any) were lost while - // the connection was down, so there's no reason to try and process - // these messages at all. - for { - select { - case _, ok := <-notificationChan: - if !ok { - notificationChan = nil - } - - case err := <-doneChan: - return err - } - } -} - -// caller should NOT be holding l.lock -func (l *Listener) closed() bool { - l.lock.Lock() - defer l.lock.Unlock() - - return l.isClosed -} - -func (l *Listener) connect() error { - notificationChan := make(chan *Notification, 32) - cn, err := newDialListenerConn(l.dialer, l.name, notificationChan) - if err != nil { - return err - } - - l.lock.Lock() - defer l.lock.Unlock() - - err = l.resync(cn, notificationChan) - if err != nil { - cn.Close() - return err - } - - l.cn = cn - l.connNotificationChan = notificationChan - l.reconnectCond.Broadcast() - - return nil -} - -// Close disconnects the Listener from the database and shuts it down. -// Subsequent calls to its methods will return an error. Close returns an -// error if the connection has already been closed. -func (l *Listener) Close() error { - l.lock.Lock() - defer l.lock.Unlock() - - if l.isClosed { - return errListenerClosed - } - - if l.cn != nil { - l.cn.Close() - } - l.isClosed = true - - // Unblock calls to Listen() - l.reconnectCond.Broadcast() - - return nil -} - -func (l *Listener) emitEvent(event ListenerEventType, err error) { - if l.eventCallback != nil { - l.eventCallback(event, err) - } -} - -// Main logic here: maintain a connection to the server when possible, wait -// for notifications and emit events. -func (l *Listener) listenerConnLoop() { - var nextReconnect time.Time - - reconnectInterval := l.minReconnectInterval - for { - for { - err := l.connect() - if err == nil { - break - } - - if l.closed() { - return - } - l.emitEvent(ListenerEventConnectionAttemptFailed, err) - - time.Sleep(reconnectInterval) - reconnectInterval *= 2 - if reconnectInterval > l.maxReconnectInterval { - reconnectInterval = l.maxReconnectInterval - } - } - - if nextReconnect.IsZero() { - l.emitEvent(ListenerEventConnected, nil) - } else { - l.emitEvent(ListenerEventReconnected, nil) - l.Notify <- nil - } - - reconnectInterval = l.minReconnectInterval - nextReconnect = time.Now().Add(reconnectInterval) - - for { - notification, ok := <-l.connNotificationChan - if !ok { - // lost connection, loop again - break - } - l.Notify <- notification - } - - err := l.disconnectCleanup() - if l.closed() { - return - } - l.emitEvent(ListenerEventDisconnected, err) - - time.Sleep(time.Until(nextReconnect)) - } -} - -func (l *Listener) listenerMain() { - l.listenerConnLoop() - close(l.Notify) -} diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go deleted file mode 100644 index c6aa5b9a3..000000000 --- a/vendor/github.com/lib/pq/rows.go +++ /dev/null @@ -1,93 +0,0 @@ -package pq - -import ( - "math" - "reflect" - "time" - - "github.com/lib/pq/oid" -) - -const headerSize = 4 - -type fieldDesc struct { - // The object ID of the data type. - OID oid.Oid - // The data type size (see pg_type.typlen). - // Note that negative values denote variable-width types. - Len int - // The type modifier (see pg_attribute.atttypmod). - // The meaning of the modifier is type-specific. - Mod int -} - -func (fd fieldDesc) Type() reflect.Type { - switch fd.OID { - case oid.T_int8: - return reflect.TypeOf(int64(0)) - case oid.T_int4: - return reflect.TypeOf(int32(0)) - case oid.T_int2: - return reflect.TypeOf(int16(0)) - case oid.T_varchar, oid.T_text: - return reflect.TypeOf("") - case oid.T_bool: - return reflect.TypeOf(false) - case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz: - return reflect.TypeOf(time.Time{}) - case oid.T_bytea: - return reflect.TypeOf([]byte(nil)) - default: - return reflect.TypeOf(new(interface{})).Elem() - } -} - -func (fd fieldDesc) Name() string { - return oid.TypeName[fd.OID] -} - -func (fd fieldDesc) Length() (length int64, ok bool) { - switch fd.OID { - case oid.T_text, oid.T_bytea: - return math.MaxInt64, true - case oid.T_varchar, oid.T_bpchar: - return int64(fd.Mod - headerSize), true - default: - return 0, false - } -} - -func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) { - switch fd.OID { - case oid.T_numeric, oid.T__numeric: - mod := fd.Mod - headerSize - precision = int64((mod >> 16) & 0xffff) - scale = int64(mod & 0xffff) - return precision, scale, true - default: - return 0, 0, false - } -} - -// ColumnTypeScanType returns the value type that can be used to scan types into. -func (rs *rows) ColumnTypeScanType(index int) reflect.Type { - return rs.colTyps[index].Type() -} - -// ColumnTypeDatabaseTypeName return the database system type name. -func (rs *rows) ColumnTypeDatabaseTypeName(index int) string { - return rs.colTyps[index].Name() -} - -// ColumnTypeLength returns the length of the column type if the column is a -// variable length type. If the column is not a variable length type ok -// should return false. -func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) { - return rs.colTyps[index].Length() -} - -// ColumnTypePrecisionScale should return the precision and scale for decimal -// types. If not applicable, ok should be false. -func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { - return rs.colTyps[index].PrecisionScale() -} diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go deleted file mode 100644 index e1a326a0d..000000000 --- a/vendor/github.com/lib/pq/ssl.go +++ /dev/null @@ -1,169 +0,0 @@ -package pq - -import ( - "crypto/tls" - "crypto/x509" - "io/ioutil" - "net" - "os" - "os/user" - "path/filepath" -) - -// ssl generates a function to upgrade a net.Conn based on the "sslmode" and -// related settings. The function is nil when no upgrade should take place. -func ssl(o values) (func(net.Conn) (net.Conn, error), error) { - verifyCaOnly := false - tlsConf := tls.Config{} - switch mode := o["sslmode"]; mode { - // "require" is the default. - case "", "require": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - - // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: - // - // Note: For backwards compatibility with earlier versions of - // PostgreSQL, if a root CA file exists, the behavior of - // sslmode=require will be the same as that of verify-ca, meaning the - // server certificate is validated against the CA. Relying on this - // behavior is discouraged, and applications that need certificate - // validation should always use verify-ca or verify-full. - if sslrootcert, ok := o["sslrootcert"]; ok { - if _, err := os.Stat(sslrootcert); err == nil { - verifyCaOnly = true - } else { - delete(o, "sslrootcert") - } - } - case "verify-ca": - // We must skip TLS's own verification since it requires full - // verification since Go 1.3. - tlsConf.InsecureSkipVerify = true - verifyCaOnly = true - case "verify-full": - tlsConf.ServerName = o["host"] - case "disable": - return nil, nil - default: - return nil, fmterrorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) - } - - err := sslClientCertificates(&tlsConf, o) - if err != nil { - return nil, err - } - err = sslCertificateAuthority(&tlsConf, o) - if err != nil { - return nil, err - } - sslRenegotiation(&tlsConf) - - return func(conn net.Conn) (net.Conn, error) { - client := tls.Client(conn, &tlsConf) - if verifyCaOnly { - err := sslVerifyCertificateAuthority(client, &tlsConf) - if err != nil { - return nil, err - } - } - return client, nil - }, nil -} - -// sslClientCertificates adds the certificate specified in the "sslcert" and -// "sslkey" settings, or if they aren't set, from the .postgresql directory -// in the user's home directory. The configured files must exist and have -// the correct permissions. -func sslClientCertificates(tlsConf *tls.Config, o values) error { - // user.Current() might fail when cross-compiling. We have to ignore the - // error and continue without home directory defaults, since we wouldn't - // know from where to load them. - user, _ := user.Current() - - // In libpq, the client certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1036-L1037 - sslcert := o["sslcert"] - if len(sslcert) == 0 && user != nil { - sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1045 - if len(sslcert) == 0 { - return nil - } - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1050:L1054 - if _, err := os.Stat(sslcert); os.IsNotExist(err) { - return nil - } else if err != nil { - return err - } - - // In libpq, the ssl key is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L1123-L1222 - sslkey := o["sslkey"] - if len(sslkey) == 0 && user != nil { - sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") - } - - if len(sslkey) > 0 { - if err := sslKeyPermissions(sslkey); err != nil { - return err - } - } - - cert, err := tls.LoadX509KeyPair(sslcert, sslkey) - if err != nil { - return err - } - - tlsConf.Certificates = []tls.Certificate{cert} - return nil -} - -// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting. -func sslCertificateAuthority(tlsConf *tls.Config, o values) error { - // In libpq, the root certificate is only loaded if the setting is not blank. - // - // https://github.com/postgres/postgres/blob/REL9_6_2/src/interfaces/libpq/fe-secure-openssl.c#L950-L951 - if sslrootcert := o["sslrootcert"]; len(sslrootcert) > 0 { - tlsConf.RootCAs = x509.NewCertPool() - - cert, err := ioutil.ReadFile(sslrootcert) - if err != nil { - return err - } - - if !tlsConf.RootCAs.AppendCertsFromPEM(cert) { - return fmterrorf("couldn't parse pem in sslrootcert") - } - } - - return nil -} - -// sslVerifyCertificateAuthority carries out a TLS handshake to the server and -// verifies the presented certificate against the CA, i.e. the one specified in -// sslrootcert or the system CA if sslrootcert was not specified. -func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) error { - err := client.Handshake() - if err != nil { - return err - } - certs := client.ConnectionState().PeerCertificates - opts := x509.VerifyOptions{ - DNSName: client.ConnectionState().ServerName, - Intermediates: x509.NewCertPool(), - Roots: tlsConf.RootCAs, - } - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - _, err = certs[0].Verify(opts) - return err -} diff --git a/vendor/github.com/lib/pq/ssl_go1.7.go b/vendor/github.com/lib/pq/ssl_go1.7.go deleted file mode 100644 index d7ba43b32..000000000 --- a/vendor/github.com/lib/pq/ssl_go1.7.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build go1.7 - -package pq - -import "crypto/tls" - -// Accept renegotiation requests initiated by the backend. -// -// Renegotiation was deprecated then removed from PostgreSQL 9.5, but -// the default configuration of older versions has it enabled. Redshift -// also initiates renegotiations and cannot be reconfigured. -func sslRenegotiation(conf *tls.Config) { - conf.Renegotiation = tls.RenegotiateFreelyAsClient -} diff --git a/vendor/github.com/lib/pq/ssl_permissions.go b/vendor/github.com/lib/pq/ssl_permissions.go deleted file mode 100644 index 3b7c3a2a3..000000000 --- a/vendor/github.com/lib/pq/ssl_permissions.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package pq - -import "os" - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(sslkey string) error { - info, err := os.Stat(sslkey) - if err != nil { - return err - } - if info.Mode().Perm()&0077 != 0 { - return ErrSSLKeyHasWorldPermissions - } - return nil -} diff --git a/vendor/github.com/lib/pq/ssl_renegotiation.go b/vendor/github.com/lib/pq/ssl_renegotiation.go deleted file mode 100644 index 85ed5e437..000000000 --- a/vendor/github.com/lib/pq/ssl_renegotiation.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !go1.7 - -package pq - -import "crypto/tls" - -// Renegotiation is not supported by crypto/tls until Go 1.7. -func sslRenegotiation(*tls.Config) {} diff --git a/vendor/github.com/lib/pq/ssl_windows.go b/vendor/github.com/lib/pq/ssl_windows.go deleted file mode 100644 index 5d2c763ce..000000000 --- a/vendor/github.com/lib/pq/ssl_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package pq - -// sslKeyPermissions checks the permissions on user-supplied ssl key files. -// The key file should have very little access. -// -// libpq does not check key file permissions on Windows. -func sslKeyPermissions(string) error { return nil } diff --git a/vendor/github.com/lib/pq/url.go b/vendor/github.com/lib/pq/url.go deleted file mode 100644 index f4d8a7c20..000000000 --- a/vendor/github.com/lib/pq/url.go +++ /dev/null @@ -1,76 +0,0 @@ -package pq - -import ( - "fmt" - "net" - nurl "net/url" - "sort" - "strings" -) - -// ParseURL no longer needs to be used by clients of this library since supplying a URL as a -// connection string to sql.Open() is now supported: -// -// sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full") -// -// It remains exported here for backwards-compatibility. -// -// ParseURL converts a url to a connection string for driver.Open. -// Example: -// -// "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full" -// -// converts to: -// -// "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full" -// -// A minimal example: -// -// "postgres://" -// -// This will be blank, causing driver.Open to use all of the defaults -func ParseURL(url string) (string, error) { - u, err := nurl.Parse(url) - if err != nil { - return "", err - } - - if u.Scheme != "postgres" && u.Scheme != "postgresql" { - return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) - } - - var kvs []string - escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) - accrue := func(k, v string) { - if v != "" { - kvs = append(kvs, k+"="+escaper.Replace(v)) - } - } - - if u.User != nil { - v := u.User.Username() - accrue("user", v) - - v, _ = u.User.Password() - accrue("password", v) - } - - if host, port, err := net.SplitHostPort(u.Host); err != nil { - accrue("host", u.Host) - } else { - accrue("host", host) - accrue("port", port) - } - - if u.Path != "" { - accrue("dbname", u.Path[1:]) - } - - q := u.Query() - for k := range q { - accrue(k, q.Get(k)) - } - - sort.Strings(kvs) // Makes testing easier (not a performance concern) - return strings.Join(kvs, " "), nil -} diff --git a/vendor/github.com/lib/pq/user_posix.go b/vendor/github.com/lib/pq/user_posix.go deleted file mode 100644 index bf982524f..000000000 --- a/vendor/github.com/lib/pq/user_posix.go +++ /dev/null @@ -1,24 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. - -// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun - -package pq - -import ( - "os" - "os/user" -) - -func userCurrent() (string, error) { - u, err := user.Current() - if err == nil { - return u.Username, nil - } - - name := os.Getenv("USER") - if name != "" { - return name, nil - } - - return "", ErrCouldNotDetectUsername -} diff --git a/vendor/github.com/lib/pq/user_windows.go b/vendor/github.com/lib/pq/user_windows.go deleted file mode 100644 index 2b691267b..000000000 --- a/vendor/github.com/lib/pq/user_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package pq is a pure Go Postgres driver for the database/sql package. -package pq - -import ( - "path/filepath" - "syscall" -) - -// Perform Windows user name lookup identically to libpq. -// -// The PostgreSQL code makes use of the legacy Win32 function -// GetUserName, and that function has not been imported into stock Go. -// GetUserNameEx is available though, the difference being that a -// wider range of names are available. To get the output to be the -// same as GetUserName, only the base (or last) component of the -// result is returned. -func userCurrent() (string, error) { - pw_name := make([]uint16, 128) - pwname_size := uint32(len(pw_name)) - 1 - err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size) - if err != nil { - return "", ErrCouldNotDetectUsername - } - s := syscall.UTF16ToString(pw_name) - u := filepath.Base(s) - return u, nil -} diff --git a/vendor/github.com/lib/pq/uuid.go b/vendor/github.com/lib/pq/uuid.go deleted file mode 100644 index 9a1b9e074..000000000 --- a/vendor/github.com/lib/pq/uuid.go +++ /dev/null @@ -1,23 +0,0 @@ -package pq - -import ( - "encoding/hex" - "fmt" -) - -// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format. -func decodeUUIDBinary(src []byte) ([]byte, error) { - if len(src) != 16 { - return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src)) - } - - dst := make([]byte, 36) - dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-' - hex.Encode(dst[0:], src[0:4]) - hex.Encode(dst[9:], src[4:6]) - hex.Encode(dst[14:], src[6:8]) - hex.Encode(dst[19:], src[8:10]) - hex.Encode(dst[24:], src[10:16]) - - return dst, nil -} diff --git a/vendor/github.com/mattn/go-colorable/.travis.yml b/vendor/github.com/mattn/go-colorable/.travis.yml new file mode 100644 index 000000000..98db8f060 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/.travis.yml @@ -0,0 +1,9 @@ +language: go +go: + - tip + +before_install: + - go get github.com/mattn/goveralls + - go get golang.org/x/tools/cmd/cover +script: + - $HOME/gopath/bin/goveralls -repotoken xnXqRGwgW3SXIguzxf90ZSK1GPYZPaGrw diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go new file mode 100644 index 000000000..1f28d773d --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -0,0 +1,29 @@ +// +build appengine + +package colorable + +import ( + "io" + "os" + + _ "github.com/mattn/go-isatty" +) + +// NewColorable return new instance of Writer which handle escape sequence. +func NewColorable(file *os.File) io.Writer { + if file == nil { + panic("nil passed instead of *os.File to NewColorable()") + } + + return file +} + +// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. +func NewColorableStdout() io.Writer { + return os.Stdout +} + +// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. +func NewColorableStderr() io.Writer { + return os.Stderr +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 404e10ca0..e17a5474e 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -29,15 +29,6 @@ const ( backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) ) -const ( - genericRead = 0x80000000 - genericWrite = 0x40000000 -) - -const ( - consoleTextmodeBuffer = 0x1 -) - type wchar uint16 type short int16 type dword uint32 @@ -78,17 +69,14 @@ var ( procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") - procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) // Writer provide colorable Writer to the console type Writer struct { - out io.Writer - handle syscall.Handle - althandle syscall.Handle - oldattr word - oldpos coord - rest bytes.Buffer + out io.Writer + handle syscall.Handle + oldattr word + oldpos coord } // NewColorable return new instance of Writer which handle escape sequence from File. @@ -419,18 +407,7 @@ func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - handle := w.handle - - var er *bytes.Reader - if w.rest.Len() > 0 { - var rest bytes.Buffer - w.rest.WriteTo(&rest) - w.rest.Reset() - rest.Write(data) - er = bytes.NewReader(rest.Bytes()) - } else { - er = bytes.NewReader(data) - } + er := bytes.NewReader(data) var bw [1]byte loop: for { @@ -448,55 +425,29 @@ loop: break loop } - switch c2 { - case '>': - continue - case ']': - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) - if bytes.IndexByte(w.rest.Bytes(), 0x07) == -1 { + if c2 == ']' { + if err := doTitleSequence(er); err != nil { break loop } - er = bytes.NewReader(w.rest.Bytes()[2:]) - err := doTitleSequence(er) - if err != nil { - break loop - } - w.rest.Reset() continue - // https://github.com/mattn/go-colorable/issues/27 - case '7': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - continue - case '8': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - continue - case 0x5b: - // execute part after switch - default: + } + if c2 != 0x5b { continue } - w.rest.WriteByte(c1) - w.rest.WriteByte(c2) - er.WriteTo(&w.rest) - var buf bytes.Buffer var m byte - for i, c := range w.rest.Bytes()[2:] { + for { + c, err := er.ReadByte() + if err != nil { + break loop + } if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { m = c - er = bytes.NewReader(w.rest.Bytes()[2+i+1:]) - w.rest.Reset() break } buf.Write([]byte(string(c))) } - if m == 0 { - break loop - } switch m { case 'A': @@ -504,64 +455,61 @@ loop: if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x -= short(n) - if csbi.cursorPosition.x < 0 { - csbi.cursorPosition.x = 0 - } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'E': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'F': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'G': n, err = strconv.Atoi(buf.String()) if err != nil { continue } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n - 1) - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'H', 'f': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) if buf.Len() > 0 { token := strings.Split(buf.String(), ";") switch len(token) { @@ -586,7 +534,7 @@ loop: } else { csbi.cursorPosition.y = 0 } - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'J': n := 0 if buf.Len() > 0 { @@ -597,20 +545,20 @@ loop: } var count, written dword var cursor coord - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.window.top-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.window.top-csbi.cursorPosition.y)*csbi.size.x) case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x) - dword(csbi.cursorPosition.x) + dword(csbi.size.y-csbi.cursorPosition.y)*dword(csbi.size.x) + count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'K': n := 0 if buf.Len() > 0 { @@ -619,28 +567,28 @@ loop: continue } } - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) var cursor coord var count, written dword switch n { case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x) + cursor = coord{x: csbi.cursorPosition.x + 1, y: csbi.cursorPosition.y} + count = dword(csbi.size.x - csbi.cursorPosition.x - 1) case 1: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x - csbi.cursorPosition.x) case 2: - cursor = coord{x: csbi.window.left, y: csbi.cursorPosition.y} + cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} count = dword(csbi.size.x) } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) + procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) attr := csbi.attributes cs := buf.String() if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(w.oldattr)) + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) continue } token := strings.Split(cs, ";") @@ -679,21 +627,6 @@ loop: attr |= n256foreAttr[n256] i += 2 } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= foregroundRed - } - if g > 127 { - attr |= foregroundGreen - } - if b > 127 { - attr |= foregroundBlue - } } else { attr = attr & (w.oldattr & backgroundMask) } @@ -721,21 +654,6 @@ loop: attr |= n256backAttr[n256] i += 2 } - } else if len(token) == 5 && token[i+1] == "2" { - var r, g, b int - r, _ = strconv.Atoi(token[i+2]) - g, _ = strconv.Atoi(token[i+3]) - b, _ = strconv.Atoi(token[i+4]) - i += 4 - if r > 127 { - attr |= backgroundRed - } - if g > 127 { - attr |= backgroundGreen - } - if b > 127 { - attr |= backgroundBlue - } } else { attr = attr & (w.oldattr & foregroundMask) } @@ -767,52 +685,38 @@ loop: attr |= backgroundBlue } } - procSetConsoleTextAttribute.Call(uintptr(handle), uintptr(attr)) + procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) } } case 'h': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle == 0 { - h, _, _ := procCreateConsoleScreenBuffer.Call(uintptr(genericRead|genericWrite), 0, 0, uintptr(consoleTextmodeBuffer), 0, 0) - w.althandle = syscall.Handle(h) - if w.althandle != 0 { - handle = w.althandle - } - } + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } case 'l': var ci consoleCursorInfo cs := buf.String() if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) + procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?1049" { - if w.althandle != 0 { - syscall.CloseHandle(w.althandle) - w.althandle = 0 - handle = w.handle - } + procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) } case 's': - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) + procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) w.oldpos = csbi.cursorPosition case 'u': - procSetConsoleCursorPosition.Call(uintptr(handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) + procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) } } diff --git a/vendor/github.com/mattn/go-isatty/.travis.yml b/vendor/github.com/mattn/go-isatty/.travis.yml new file mode 100644 index 000000000..5597e026d --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/.travis.yml @@ -0,0 +1,13 @@ +language: go +go: + - tip + +os: + - linux + - osx + +before_install: + - go get github.com/mattn/goveralls + - go get golang.org/x/tools/cmd/cover +script: + - $HOME/gopath/bin/goveralls -repotoken 3gHdORO5k5ziZcWMBxnd9LrMZaJs8m9x5 diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go new file mode 100644 index 000000000..9584a9884 --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/isatty_appengine.go @@ -0,0 +1,15 @@ +// +build appengine + +package isatty + +// IsTerminal returns true if the file descriptor is terminal which +// is always false on on appengine classic which is a sandboxed PaaS. +func IsTerminal(fd uintptr) bool { + return false +} + +// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 +// terminal. This is also always false on this environment. +func IsCygwinTerminal(fd uintptr) bool { + return false +} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/CONTRIBUTING.md b/vendor/github.com/michaelklishin/rabbit-hole/CONTRIBUTING.md deleted file mode 100644 index 789a3d373..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ -## Contributing - -The workflow is pretty standard: - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Run integration tests (see below) -4. Commit your changes (`git commit -am 'Add some feature'`) -5. Push to the branch (`git push -u origin my-new-feature`) -6. Submit a pull request - -## Running Tests - -### Required Plugins - -The test suite assumes you have a RabbitMQ node running on localhost with `rabbitmq_management` and -`rabbitmq_shovel_management` plugins enabled and that -`rabbitmqctl` is available in `PATH` (or `RABBITHOLE_RABBITMQCTL` points to it). - -To enable the plugins: - - rabbitmq-plugins enable rabbitmq_management rabbitmq_shovel_management - -That will enable `rabbitmq_shovel` as a dependency. - -### Setting Up Virtual Hosts and Permissions - -Before running the tests, make sure to run `bin/ci/before_build.sh` that will create a vhost and user(s) needed -by the test suite. - -### Running Tests - -The project uses [Ginkgo](http://onsi.github.io/ginkgo/) and [Gomega](https://github.com/onsi/gomega). - -To clone dependencies and run tests, use `make`. It is also possible -to use the brilliant [Ginkgo CLI runner](http://onsi.github.io/ginkgo/#the-ginkgo-cli) e.g. -to only run a subset of tests. diff --git a/vendor/github.com/michaelklishin/rabbit-hole/ChangeLog.md b/vendor/github.com/michaelklishin/rabbit-hole/ChangeLog.md deleted file mode 100644 index b5252ffd7..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/ChangeLog.md +++ /dev/null @@ -1,32 +0,0 @@ -## Changes Between 1.0.0 and 1.1.0 (unreleased) - -### More Complete Message Stats Information - -Message stats now include fields such as `deliver_get` and `redeliver`. - -GH issue: [#73](https://github.com/michaelklishin/rabbit-hole/pull/73). - -Contributed by Edward Wilde. - - -## 1.0 (first tagged release, Dec 25th, 2015) - -### TLS Support - -`rabbithole.NewTLSClient` is a new function which works -much like `NewClient` but additionally accepts a transport. - -Contributed by @[GrimTheReaper](https://github.com/GrimTheReaper). - -### Federation Support - -It is now possible to create federation links -over HTTP API. - -Contributed by [Ryan Grenz](https://github.com/grenzr-bskyb). - -### Core Operations Support - -Most common HTTP API operations (listing and management of -vhosts, users, permissions, queues, exchanges, and bindings) -are supported by the client. diff --git a/vendor/github.com/michaelklishin/rabbit-hole/LICENSE b/vendor/github.com/michaelklishin/rabbit-hole/LICENSE deleted file mode 100644 index c3ab91024..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2013-2017, Michael Klishin -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/michaelklishin/rabbit-hole/Makefile b/vendor/github.com/michaelklishin/rabbit-hole/Makefile deleted file mode 100644 index 048ce87fd..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -export GOPATH := $(CURDIR) - -COVER_FILE := coverage - -all: test - -.PHONY: test - -test: install-dependencies - go test -race -v - -cover: install-dependencies install-cover - go test -v -test.coverprofile="$(COVER_FILE).prof" - sed -i.bak 's|_'$(GOPATH)'|.|g' $(COVER_FILE).prof - go tool cover -html=$(COVER_FILE).prof -o $(COVER_FILE).html - rm $(COVER_FILE).prof* - -install-cover: - go get code.google.com/p/go.tools/cmd/cover - -install-dependencies: - go get github.com/onsi/ginkgo - go get github.com/onsi/gomega - go get github.com/streadway/amqp - # to get Ginkgo CLI - go install github.com/onsi/ginkgo/ginkgo diff --git a/vendor/github.com/michaelklishin/rabbit-hole/README.md b/vendor/github.com/michaelklishin/rabbit-hole/README.md deleted file mode 100644 index 29bfd5261..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/README.md +++ /dev/null @@ -1,338 +0,0 @@ -# Rabbit Hole, a RabbitMQ HTTP API Client for Go - -This library is a [RabbitMQ HTTP API](https://raw.githack.com/rabbitmq/rabbitmq-management/rabbitmq_v3_6_0/priv/www/api/index.html) client for the Go language. - -## Supported Go Versions - -Rabbit Hole requires Go 1.6+. - - -## Supported RabbitMQ Versions - - * RabbitMQ 3.x - -All versions require [RabbitMQ Management UI plugin](http://www.rabbitmq.com/management.html) to be installed and enabled. - - -## Project Maturity - -Rabbit Hole is a fairly mature library (started in October 2013) -designed after a couple of other RabbitMQ HTTP API clients with stable -APIs. Breaking API changes are not out of the question but not without -a reasonable version bump. - -It is largely (80-90%) feature complete and decently documented. - - -## Installation - -``` -go get github.com/michaelklishin/rabbit-hole -``` - - -## Documentation - -### Overview - -To import the package: - -``` go -import ( - "github.com/michaelklishin/rabbit-hole" -) -``` - -All HTTP API operations are accessible via `rabbithole.Client`, which -should be instantiated with `rabbithole.NewClient`: - -``` go -// URI, username, password -rmqc, _ = NewClient("http://127.0.0.1:15672", "guest", "guest") -``` - -TLS (HTTPS) can be enabled by adding an HTTP transport to the parameters -of `rabbithole.NewTLSClient`: - -``` go -transport := &http.Transport{TLSClientConfig: tlsConfig} -rmqc, _ := NewTLSClient("https://127.0.0.1:15672", "guest", "guest", transport) -``` - -RabbitMQ HTTP API has to be [configured to use TLS](http://www.rabbitmq.com/management.html#web-dispatch-config). - -[API reference](http://godoc.org/github.com/michaelklishin/rabbit-hole) is available on [godoc.org](http://godoc.org). - - -### Getting Overview - -``` go -res, err := rmqc.Overview() -``` - -### Node and Cluster Status - -``` go -xs, err := rmqc.ListNodes() -// => []NodeInfo, err - -node, err := rmqc.GetNode("rabbit@mercurio") -// => NodeInfo, err -``` - - -### Operations on Connections - -``` go -xs, err := rmqc.ListConnections() -// => []ConnectionInfo, err - -conn, err := rmqc.GetConnection("127.0.0.1:50545 -> 127.0.0.1:5672") -// => ConnectionInfo, err - -// Forcefully close connection -_, err := rmqc.CloseConnection("127.0.0.1:50545 -> 127.0.0.1:5672") -// => *http.Response, err -``` - - -### Operations on Channels - -``` go -xs, err := rmqc.ListChannels() -// => []ChannelInfo, err - -ch, err := rmqc.GetChannel("127.0.0.1:50545 -> 127.0.0.1:5672 (1)") -// => ChannelInfo, err -``` - - -### Operations on Vhosts - -``` go -xs, err := rmqc.ListVhosts() -// => []VhostInfo, err - -// information about individual vhost -x, err := rmqc.GetVhost("/") -// => VhostInfo, err - -// creates or updates individual vhost -resp, err := rmqc.PutVhost("/", VhostSettings{Tracing: false}) -// => *http.Response, err - -// deletes individual vhost -resp, err := rmqc.DeleteVhost("/") -// => *http.Response, err -``` - - -### Managing Users - -``` go -xs, err := rmqc.ListUsers() -// => []UserInfo, err - -// information about individual user -x, err := rmqc.GetUser("my.user") -// => UserInfo, err - -// creates or updates individual user -resp, err := rmqc.PutUser("my.user", UserSettings{Password: "s3krE7", Tags: "management,policymaker"}) -// => *http.Response, err - -// creates or updates individual user with no password -resp, err := rmqc.PutUserWithoutPassword("my.user", UserSettings{Tags: "management,policymaker"}) -// => *http.Response, err - -// deletes individual user -resp, err := rmqc.DeleteUser("my.user") -// => *http.Response, err -``` - - -### Managing Permissions - -``` go -xs, err := rmqc.ListPermissions() -// => []PermissionInfo, err - -// permissions of individual user -x, err := rmqc.ListPermissionsOf("my.user") -// => []PermissionInfo, err - -// permissions of individual user in vhost -x, err := rmqc.GetPermissionsIn("/", "my.user") -// => PermissionInfo, err - -// updates permissions of user in vhost -resp, err := rmqc.UpdatePermissionsIn("/", "my.user", Permissions{Configure: ".*", Write: ".*", Read: ".*"}) -// => *http.Response, err - -// revokes permissions in vhost -resp, err := rmqc.ClearPermissionsIn("/", "my.user") -// => *http.Response, err -``` - - -### Operations on Exchanges - -``` go -xs, err := rmqc.ListExchanges() -// => []ExchangeInfo, err - -// list exchanges in a vhost -xs, err := rmqc.ListExchangesIn("/") -// => []ExchangeInfo, err - -// information about individual exchange -x, err := rmqc.GetExchange("/", "amq.fanout") -// => ExchangeInfo, err - -// declares an exchange -resp, err := rmqc.DeclareExchange("/", "an.exchange", ExchangeSettings{Type: "fanout", Durable: false}) -// => *http.Response, err - -// deletes individual exchange -resp, err := rmqc.DeleteExchange("/", "an.exchange") -// => *http.Response, err -``` - - -### Operations on Queues - -``` go -qs, err := rmqc.ListQueues() -// => []QueueInfo, err - -// list queues in a vhost -qs, err := rmqc.ListQueuesIn("/") -// => []QueueInfo, err - -// information about individual queue -q, err := rmqc.GetQueue("/", "a.queue") -// => QueueInfo, err - -// declares a queue -resp, err := rmqc.DeclareQueue("/", "a.queue", QueueSettings{Durable: false}) -// => *http.Response, err - -// deletes individual queue -resp, err := rmqc.DeleteQueue("/", "a.queue") -// => *http.Response, err - -// purges all messages in queue -resp, err := rmqc.PurgeQueue("/", "a.queue") -// => *http.Response, err -``` - - -### Operations on Bindings - -``` go -bs, err := rmqc.ListBindings() -// => []BindingInfo, err - -// list bindings in a vhost -bs, err := rmqc.ListBindingsIn("/") -// => []BindingInfo, err - -// list bindings of a queue -bs, err := rmqc.ListQueueBindings("/", "a.queue") -// => []BindingInfo, err - -// declare a binding -resp, err := rmqc.DeclareBinding("/", BindingInfo{ - Source: "an.exchange", - Destination: "a.queue", - DestinationType: "queue", - RoutingKey: "#", -}) -// => *http.Response, err - -// deletes individual binding -resp, err := rmqc.DeleteBinding("/", BindingInfo{ - Source: "an.exchange", - Destination: "a.queue", - DestinationType: "queue", - RoutingKey: "#", - PropertiesKey: "%23", -}) -// => *http.Response, err -``` - -### Operations on Shovels - -``` go -qs, err := rmqc.ListShovels() -// => []ShovelInfo, err - -// list shovels in a vhost -qs, err := rmqc.ListShovelsIn("/") -// => []ShovelInfo, err - -// information about an individual shovel -q, err := rmqc.GetShovel("/", "a.shovel") -// => ShovelInfo, err - -// declares a shovel -shovelDetails := rabbithole.ShovelDefinition{SourceURI: "amqp://sourceURI", SourceQueue: "mySourceQueue", DestinationURI: "amqp://destinationURI", DestinationQueue: "myDestQueue", AddForwardHeaders: true, AckMode: "on-confirm", DeleteAfter: "never"} -resp, err := rmqc.DeclareShovel("/", "a.shovel", shovelDetails) -// => *http.Response, err - -// deletes an individual shovel -resp, err := rmqc.DeleteShovel("/", "a.shovel") -// => *http.Response, err - -``` - -### Operations on cluster name -``` go -// Get cluster name -cn, err := rmqc.GetClusterName() -// => ClusterName, err - -// Rename cluster -resp, err := rmqc.SetClusterName(ClusterName{Name: "rabbitmq@rabbit-hole"}) -// => *http.Response, err - -``` - -### HTTPS Connections - -``` go -var tlsConfig *tls.Config - -... - -transport := &http.Transport{TLSClientConfig: tlsConfig} - -rmqc, err := NewTLSClient("https://127.0.0.1:15672", "guest", "guest", transport) -``` - -### Changing Transport Layer - -``` go -var transport *http.Transport - -... - -rmqc.SetTransport(transport) -``` - - -## CI Status - -[![Build Status](https://travis-ci.org/michaelklishin/rabbit-hole.svg?branch=master)](https://travis-ci.org/michaelklishin/rabbit-hole) - - -## Contributing - -See [CONTRIBUTING.md](https://github.com/michaelklishin/rabbit-hole/blob/master/CONTRIBUTING.md) - - -## License & Copyright - -2-clause BSD license. - -(c) Michael S. Klishin, 2013-2018. diff --git a/vendor/github.com/michaelklishin/rabbit-hole/bindings.go b/vendor/github.com/michaelklishin/rabbit-hole/bindings.go deleted file mode 100644 index d868faa47..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/bindings.go +++ /dev/null @@ -1,160 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// -// GET /api/bindings -// - -// Example response: -// -// [ -// { -// "source": "", -// "vhost": "\/", -// "destination": "amq.gen-Dzw36tPTm_VsmILY9oTG9w", -// "destination_type": "queue", -// "routing_key": "amq.gen-Dzw36tPTm_VsmILY9oTG9w", -// "arguments": { -// -// }, -// "properties_key": "amq.gen-Dzw36tPTm_VsmILY9oTG9w" -// } -// ] - -type BindingInfo struct { - // Binding source (exchange name) - Source string `json:"source"` - Vhost string `json:"vhost"` - // Binding destination (queue or exchange name) - Destination string `json:"destination"` - // Destination type, either "queue" or "exchange" - DestinationType string `json:"destination_type"` - RoutingKey string `json:"routing_key"` - Arguments map[string]interface{} `json:"arguments"` - PropertiesKey string `json:"properties_key"` -} - -// Returns all bindings -func (c *Client) ListBindings() (rec []BindingInfo, err error) { - req, err := newGETRequest(c, "bindings/") - if err != nil { - return []BindingInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []BindingInfo{}, err - } - - return rec, nil -} - -// -// GET /api/bindings/{vhost} -// - -// Returns all bindings in a virtual host. -func (c *Client) ListBindingsIn(vhost string) (rec []BindingInfo, err error) { - req, err := newGETRequest(c, "bindings/"+PathEscape(vhost)) - if err != nil { - return []BindingInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []BindingInfo{}, err - } - - return rec, nil -} - -// -// GET /api/queues/{vhost}/{queue}/bindings -// - -// Example response: -// [ -// {"source":"", -// "vhost":"/", -// "destination":"amq.gen-H0tnavWatL7g7uU2q5cAPA", -// "destination_type":"queue", -// "routing_key":"amq.gen-H0tnavWatL7g7uU2q5cAPA", -// "arguments":{}, -// "properties_key":"amq.gen-H0tnavWatL7g7uU2q5cAPA"}, -// {"source":"temp", -// "vhost":"/", -// "destination":"amq.gen-H0tnavWatL7g7uU2q5cAPA", -// "destination_type":"queue", -// "routing_key":"", -// "arguments":{}, -// "properties_key":"~"} -// ] - -// Returns all bindings of individual queue. -func (c *Client) ListQueueBindings(vhost, queue string) (rec []BindingInfo, err error) { - req, err := newGETRequest(c, "queues/"+PathEscape(vhost)+"/"+PathEscape(queue)+"/bindings") - if err != nil { - return []BindingInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []BindingInfo{}, err - } - - return rec, nil -} - -// -// POST /api/bindings/{vhost}/e/{source}/{destination_type}/{destination} -// - -// DeclareBinding updates information about a binding between a source and a target -func (c *Client) DeclareBinding(vhost string, info BindingInfo) (res *http.Response, err error) { - info.Vhost = vhost - - if info.Arguments == nil { - info.Arguments = make(map[string]interface{}) - } - body, err := json.Marshal(info) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "POST", "bindings/"+PathEscape(vhost)+ - "/e/"+PathEscape(info.Source)+"/"+PathEscape(string(info.DestinationType[0]))+ - "/"+PathEscape(info.Destination), body) - - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/bindings/{vhost}/e/{source}/{destination_type}/{destination}/{props} -// - -// DeleteBinding delets an individual binding -func (c *Client) DeleteBinding(vhost string, info BindingInfo) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "bindings/"+PathEscape(vhost)+ - "/e/"+PathEscape(info.Source)+"/"+PathEscape(string(info.DestinationType[0]))+ - "/"+PathEscape(info.Destination)+"/"+PathEscape(info.PropertiesKey), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/channels.go b/vendor/github.com/michaelklishin/rabbit-hole/channels.go deleted file mode 100644 index 0654dcf39..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/channels.go +++ /dev/null @@ -1,84 +0,0 @@ -package rabbithole - -// Brief (very incomplete) connection information. -type BriefConnectionDetails struct { - // Connection name - Name string `json:"name"` - // Client port - PeerPort Port `json:"peer_port"` - // Client host - PeerHost string `json:"peer_host"` -} - -type ChannelInfo struct { - // Channel number - Number int `json:"number"` - // Channel name - Name string `json:"name"` - - // basic.qos (prefetch count) value used - PrefetchCount int `json:"prefetch_count"` - // How many consumers does this channel have - ConsumerCount int `json:"consumer_count"` - - // Number of unacknowledged messages on this channel - UnacknowledgedMessageCount int `json:"messages_unacknowledged"` - // Number of messages on this channel unconfirmed to publishers - UnconfirmedMessageCount int `json:"messages_unconfirmed"` - // Number of messages on this channel uncommited to message store - UncommittedMessageCount int `json:"messages_uncommitted"` - // Number of acks on this channel uncommited to message store - UncommittedAckCount int `json:"acks_uncommitted"` - - // TODO(mk): custom deserializer to date/time? - IdleSince string `json:"idle_since"` - - // True if this channel uses publisher confirms - UsesPublisherConfirms bool `json:"confirm"` - // True if this channel uses transactions - Transactional bool `json:"transactional"` - // True if this channel is blocked via channel.flow - ClientFlowBlocked bool `json:"client_flow_blocked"` - - User string `json:"user"` - Vhost string `json:"vhost"` - Node string `json:"node"` - - ConnectionDetails BriefConnectionDetails `json:"connection_details"` -} - -// -// GET /api/channels -// - -// Returns information about all open channels. -func (c *Client) ListChannels() (rec []ChannelInfo, err error) { - req, err := newGETRequest(c, "channels") - if err != nil { - return []ChannelInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ChannelInfo{}, err - } - - return rec, nil -} - -// -// GET /api/channels/{name} -// - -// Returns channel information. -func (c *Client) GetChannel(name string) (rec *ChannelInfo, err error) { - req, err := newGETRequest(c, "channels/"+PathEscape(name)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/client.go b/vendor/github.com/michaelklishin/rabbit-hole/client.go deleted file mode 100644 index f4bf37096..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/client.go +++ /dev/null @@ -1,273 +0,0 @@ -package rabbithole - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "net/url" - "time" -) - -type Client struct { - // URI of a RabbitMQ node to use, not including the path, e.g. http://127.0.0.1:15672. - Endpoint string - // Username to use. This RabbitMQ user must have the "management" tag. - Username string - // Password to use. - Password string - host string - transport *http.Transport - timeout time.Duration -} - -func NewClient(uri string, username string, password string) (me *Client, err error) { - u, err := url.Parse(uri) - if err != nil { - return nil, err - } - - me = &Client{ - Endpoint: uri, - host: u.Host, - Username: username, - Password: password, - } - - return me, nil -} - -// Creates a client with a transport; it is up to the developer to make that layer secure. -func NewTLSClient(uri string, username string, password string, transport *http.Transport) (me *Client, err error) { - u, err := url.Parse(uri) - if err != nil { - return nil, err - } - - me = &Client{ - Endpoint: uri, - host: u.Host, - Username: username, - Password: password, - transport: transport, - } - - return me, nil -} - -//SetTransport changes the Transport Layer that the Client will use. -func (c *Client) SetTransport(transport *http.Transport) { - c.transport = transport -} - -// SetTimeout changes the HTTP timeout that the Client will use. -// By default there is no timeout. -func (c *Client) SetTimeout(timeout time.Duration) { - c.timeout = timeout -} - -func newGETRequest(client *Client, path string) (*http.Request, error) { - s := client.Endpoint + "/api/" + path - req, err := http.NewRequest("GET", s, nil) - - req.Close = true - req.SetBasicAuth(client.Username, client.Password) - - // set Opaque to preserve the percent-encoded path. MK. - req.URL.Opaque = "//" + client.host + "/api/" + path - - return req, err -} - -func newGETRequestWithParameters(client *Client, path string, qs url.Values) (*http.Request, error) { - s := client.Endpoint + "/api/" + path + "?" + qs.Encode() - - req, err := http.NewRequest("GET", s, nil) - req.Close = true - req.SetBasicAuth(client.Username, client.Password) - - return req, err -} - -func newRequestWithBody(client *Client, method string, path string, body []byte) (*http.Request, error) { - s := client.Endpoint + "/api/" + path - - req, err := http.NewRequest(method, s, bytes.NewReader(body)) - - req.Close = true - req.SetBasicAuth(client.Username, client.Password) - // set Opaque to preserve the percent-encoded path. - req.URL.Opaque = "//" + client.host + "/api/" + path - - req.Header.Add("Content-Type", "application/json") - - return req, err -} - -func executeRequest(client *Client, req *http.Request) (res *http.Response, err error) { - httpc := &http.Client{ - Timeout: client.timeout, - } - if client.transport != nil { - httpc.Transport = client.transport - } - return httpc.Do(req) -} - -func executeAndParseRequest(client *Client, req *http.Request, rec interface{}) (err error) { - res, err := executeRequest(client, req) - if err != nil { - return err - } - defer res.Body.Close() // always close body - - if res.StatusCode >= http.StatusBadRequest { - rme := ErrorResponse{} - err = json.NewDecoder(res.Body).Decode(&rme) - if err != nil { - return fmt.Errorf("Error %d from RabbitMQ: %s", res.StatusCode, err) - } - rme.StatusCode = res.StatusCode - return rme - } - - err = json.NewDecoder(res.Body).Decode(&rec) - if err != nil { - return err - } - - return nil -} - -// This is an ugly hack: we copy relevant bits from -// https://github.com/golang/go/blob/7e2bf952a905f16a17099970392ea17545cdd193/src/net/url/url.go -// because up to Go 1.8 there is no built-in method -// (and url.QueryEscape isn't suitable since it encodes -// spaces as + and not %20). -// -// See https://github.com/golang/go/issues/13737, -// https://github.com/golang/go/commit/7e2bf952a905f16a17099970392ea17545cdd193 - -// PathEscape escapes the string so it can be safely placed -// inside a URL path segment. -func PathEscape(s string) string { - return escape(s, encodePathSegment) -} - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodePathSegment - encodeHost - encodeZone - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - t := make([]byte, len(s)+2*hexCount) - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = "0123456789ABCDEF"[c>>4] - t[j+2] = "0123456789ABCDEF"[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -// -// Please be informed that for now shouldEscape does not check all -// reserved characters correctly. See golang.org/issue/5684. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { - return false - } - - if mode == encodeHost || mode == encodeZone { - // §3.2.2 Host allows - // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - // as part of reg-name. - // We add : because we include :port as part of host. - // We add [ ] because we include [ipv6]:port as part of host. - // We add < > because they're the only characters left that - // we could possibly allow, and Parse will reject them if we - // escape them (because hosts can't use %-encoding for - // ASCII bytes). - switch c { - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"': - return false - } - } - - switch c { - case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) - return false - - case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. This package - // only manipulates the path as a whole, so we allow those - // last three as well. That leaves only ? to escape. - return c == '?' - - case encodePathSegment: // §3.3 - // The RFC allows : @ & = + $ but saves / ; , for assigning - // meaning to individual path segments. - return c == '/' || c == ';' || c == ',' || c == '?' - - case encodeUserPassword: // §3.2.1 - // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in - // userinfo, so we must escape only '@', '/', and '?'. - // The parsing of userinfo treats ':' as special so we must escape - // that too. - return c == '@' || c == '/' || c == '?' || c == ':' - - case encodeQueryComponent: // §3.4 - // The RFC reserves (so we must escape) everything. - return true - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing. - return false - } - } - - // Everything else must be escaped. - return true -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/cluster.go b/vendor/github.com/michaelklishin/rabbit-hole/cluster.go deleted file mode 100644 index f655bdb79..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/cluster.go +++ /dev/null @@ -1,38 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -type ClusterName struct { - Name string `json:"name"` -} - -func (c *Client) GetClusterName() (rec *ClusterName, err error) { - req, err := newGETRequest(c, "cluster-name/") - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -func (c *Client) SetClusterName(cn ClusterName) (res *http.Response, err error) { - body, err := json.Marshal(cn) - if err != nil { - return nil, err - } - req, err := newRequestWithBody(c, "PUT", "cluster-name", body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/common.go b/vendor/github.com/michaelklishin/rabbit-hole/common.go deleted file mode 100644 index 504b34ca9..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/common.go +++ /dev/null @@ -1,66 +0,0 @@ -package rabbithole - -import "strconv" - -// Extra arguments as a map (on queues, bindings, etc) -type Properties map[string]interface{} - -// Port used by RabbitMQ or clients -type Port int - -func (p *Port) UnmarshalJSON(b []byte) error { - stringValue := string(b) - var parsed int64 - var err error - if stringValue[0] == '"' && stringValue[len(stringValue)-1] == '"' { - parsed, err = strconv.ParseInt(stringValue[1:len(stringValue)-1], 10, 32) - } else { - parsed, err = strconv.ParseInt(stringValue, 10, 32) - } - if err == nil { - *p = Port(int(parsed)) - } - return err -} - -// RateDetailSample single touple -type RateDetailSample struct { - Sample int64 `json:"sample"` - Timestamp int64 `json:"timestamp"` -} - -// Rate of change of a numerical value -type RateDetails struct { - Rate float32 `json:"rate"` - Samples []RateDetailSample `json:"samples"` -} - -// RabbitMQ context (Erlang app) running on -// a node -type BrokerContext struct { - Node string `json:"node"` - Description string `json:"description"` - Path string `json:"path"` - Port Port `json:"port"` - Ignore bool `json:"ignore_in_use"` -} - -// Basic published messages statistics -type MessageStats struct { - Publish int64 `json:"publish"` - PublishDetails RateDetails `json:"publish_details"` - Deliver int64 `json:"deliver"` - DeliverDetails RateDetails `json:"deliver_details"` - DeliverNoAck int64 `json:"deliver_noack"` - DeliverNoAckDetails RateDetails `json:"deliver_noack_details"` - DeliverGet int64 `json:"deliver_get"` - DeliverGetDetails RateDetails `json:"deliver_get_details"` - Redeliver int64 `json:"redeliver"` - RedeliverDetails RateDetails `json:"redeliver_details"` - Get int64 `json:"get"` - GetDetails RateDetails `json:"get_details"` - GetNoAck int64 `json:"get_no_ack"` - GetNoAckDetails RateDetails `json:"get_no_ack_details"` - Ack int64 `json:"ack"` - AckDetails RateDetails `json:"ack_details"` -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/connections.go b/vendor/github.com/michaelklishin/rabbit-hole/connections.go deleted file mode 100644 index bc0f77e59..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/connections.go +++ /dev/null @@ -1,130 +0,0 @@ -package rabbithole - -import ( - "net/http" -) - -// Provides information about connection to a RabbitMQ node. -type ConnectionInfo struct { - // Connection name - Name string `json:"name"` - // Node the client is connected to - Node string `json:"node"` - // Number of open channels - Channels int `json:"channels"` - // Connection state - State string `json:"state"` - // Connection type, network (via AMQP client) or direct (via direct Erlang client) - Type string `json:"type"` - - // Server port - Port Port `json:"port"` - // Client port - PeerPort Port `json:"peer_port"` - - // Server host - Host string `json:"host"` - // Client host - PeerHost string `json:"peer_host"` - - // Last connection blocking reason, if any - LastBlockedBy string `json:"last_blocked_by"` - // When connection was last blocked - LastBlockedAge string `json:"last_blocked_age"` - - // True if connection uses TLS/SSL - UsesTLS bool `json:"ssl"` - // Client certificate subject - PeerCertSubject string `json:"peer_cert_subject"` - // Client certificate validity - PeerCertValidity string `json:"peer_cert_validity"` - // Client certificate issuer - PeerCertIssuer string `json:"peer_cert_issuer"` - - // TLS/SSL protocol and version - SSLProtocol string `json:"ssl_protocol"` - // Key exchange mechanism - SSLKeyExchange string `json:"ssl_key_exchange"` - // SSL cipher suite used - SSLCipher string `json:"ssl_cipher"` - // SSL hash - SSLHash string `json:"ssl_hash"` - - // Protocol, e.g. AMQP 0-9-1 or MQTT 3-1 - Protocol string `json:"protocol"` - User string `json:"user"` - // Virtual host - Vhost string `json:"vhost"` - - // Heartbeat timeout - Timeout int `json:"timeout"` - // Maximum frame size (AMQP 0-9-1) - FrameMax int `json:"frame_max"` - - // A map of client properties (name, version, capabilities, etc) - ClientProperties Properties `json:"client_properties"` - - // Octets received - RecvOct uint64 `json:"recv_oct"` - // Octets sent - SendOct uint64 `json:"send_oct"` - RecvCount uint64 `json:"recv_cnt"` - SendCount uint64 `json:"send_cnt"` - SendPending uint64 `json:"send_pend"` - // Ingress data rate - RecvOctDetails RateDetails `json:"recv_oct_details"` - // Egress data rate - SendOctDetails RateDetails `json:"send_oct_details"` -} - -// -// GET /api/connections -// - -func (c *Client) ListConnections() (rec []ConnectionInfo, err error) { - req, err := newGETRequest(c, "connections") - if err != nil { - return []ConnectionInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ConnectionInfo{}, err - } - - return rec, nil -} - -// -// GET /api/connections/{name} -// - -func (c *Client) GetConnection(name string) (rec *ConnectionInfo, err error) { - req, err := newGETRequest(c, "connections/"+PathEscape(name)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// DELETE /api/connections/{name} -// - -func (c *Client) CloseConnection(name string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "connections/"+PathEscape(name), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/doc.go b/vendor/github.com/michaelklishin/rabbit-hole/doc.go deleted file mode 100644 index 4abb7dbff..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/doc.go +++ /dev/null @@ -1,186 +0,0 @@ -/* -Rabbit Hole is a Go client for the RabbitMQ HTTP API. - -All HTTP API operations are accessible via `rabbithole.Client`, which -should be instantiated with `rabbithole.NewClient`. - - // URI, username, password - rmqc, _ = NewClient("http://127.0.0.1:15672", "guest", "guest") - -Getting Overview - - res, err := rmqc.Overview() - -Node and Cluster Status - - var err error - - // => []NodeInfo, err - xs, err := rmqc.ListNodes() - - node, err := rmqc.GetNode("rabbit@mercurio") - // => NodeInfo, err - -Operations on Connections - - xs, err := rmqc.ListConnections() - // => []ConnectionInfo, err - - conn, err := rmqc.GetConnection("127.0.0.1:50545 -> 127.0.0.1:5672") - // => ConnectionInfo, err - - // Forcefully close connection - _, err := rmqc.CloseConnection("127.0.0.1:50545 -> 127.0.0.1:5672") - // => *http.Response, err - -Operations on Channels - - xs, err := rmqc.ListChannels() - // => []ChannelInfo, err - - ch, err := rmqc.GetChannel("127.0.0.1:50545 -> 127.0.0.1:5672 (1)") - // => ChannelInfo, err - -Operations on Exchanges - - xs, err := rmqc.ListExchanges() - // => []ExchangeInfo, err - - // list exchanges in a vhost - xs, err := rmqc.ListExchangesIn("/") - // => []ExchangeInfo, err - - // information about individual exchange - x, err := rmqc.GetExchange("/", "amq.fanout") - // => ExchangeInfo, err - - // declares an exchange - resp, err := rmqc.DeclareExchange("/", "an.exchange", ExchangeSettings{Type: "fanout", Durable: false}) - // => *http.Response, err - - // deletes individual exchange - resp, err := rmqc.DeleteExchange("/", "an.exchange") - // => *http.Response, err - -Operations on Queues - - xs, err := rmqc.ListQueues() - // => []QueueInfo, err - - // list queues in a vhost - xs, err := rmqc.ListQueuesIn("/") - // => []QueueInfo, err - - // information about individual queue - x, err := rmqc.GetQueue("/", "a.queue") - // => QueueInfo, err - - // declares a queue - resp, err := rmqc.DeclareQueue("/", "a.queue", QueueSettings{Durable: false}) - // => *http.Response, err - - // deletes individual queue - resp, err := rmqc.DeleteQueue("/", "a.queue") - // => *http.Response, err - - // purges all messages in queue - resp, err := rmqc.PurgeQueue("/", "a.queue") - // => *http.Response, err - -Operations on Bindings - - bs, err := rmqc.ListBindings() - // => []BindingInfo, err - - // list bindings in a vhost - bs, err := rmqc.ListBindingsIn("/") - // => []BindingInfo, err - - // list bindings of a queue - bs, err := rmqc.ListQueueBindings("/", "a.queue") - // => []BindingInfo, err - - // declare a binding - resp, err := rmqc.DeclareBinding("/", BindingInfo{ - Source: "an.exchange", - Destination: "a.queue", - DestinationType: "queue", - RoutingKey: "#", - }) - // => *http.Response, err - - // deletes individual binding - resp, err := rmqc.DeleteBinding("/", BindingInfo{ - Source: "an.exchange", - Destination: "a.queue", - DestinationType: "queue", - RoutingKey: "#", - PropertiesKey: "%23", - }) - // => *http.Response, err - -Operations on Vhosts - - xs, err := rmqc.ListVhosts() - // => []VhostInfo, err - - // information about individual vhost - x, err := rmqc.GetVhost("/") - // => VhostInfo, err - - // creates or updates individual vhost - resp, err := rmqc.PutVhost("/", VhostSettings{Tracing: false}) - // => *http.Response, err - - // deletes individual vhost - resp, err := rmqc.DeleteVhost("/") - // => *http.Response, err - -Managing Users - - xs, err := rmqc.ListUsers() - // => []UserInfo, err - - // information about individual user - x, err := rmqc.GetUser("my.user") - // => UserInfo, err - - // creates or updates individual user - resp, err := rmqc.PutUser("my.user", UserSettings{Password: "s3krE7", Tags: "management policymaker"}) - // => *http.Response, err - - // deletes individual user - resp, err := rmqc.DeleteUser("my.user") - // => *http.Response, err - -Managing Permissions - - xs, err := rmqc.ListPermissions() - // => []PermissionInfo, err - - // permissions of individual user - x, err := rmqc.ListPermissionsOf("my.user") - // => []PermissionInfo, err - - // permissions of individual user in vhost - x, err := rmqc.GetPermissionsIn("/", "my.user") - // => PermissionInfo, err - - // updates permissions of user in vhost - resp, err := rmqc.UpdatePermissionsIn("/", "my.user", Permissions{Configure: ".*", Write: ".*", Read: ".*"}) - // => *http.Response, err - - // revokes permissions in vhost - resp, err := rmqc.ClearPermissionsIn("/", "my.user") - // => *http.Response, err - -Operations on cluster name - // Get cluster name - cn, err := rmqc.GetClusterName() - // => ClusterName, err - - // Rename cluster - resp, err := rmqc.SetClusterName(ClusterName{Name: "rabbitmq@rabbit-hole"}) - // => *http.Response, err -*/ -package rabbithole diff --git a/vendor/github.com/michaelklishin/rabbit-hole/error.go b/vendor/github.com/michaelklishin/rabbit-hole/error.go deleted file mode 100644 index 9618e2f6b..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/error.go +++ /dev/null @@ -1,13 +0,0 @@ -package rabbithole - -import "fmt" - -type ErrorResponse struct { - StatusCode int - Message string `json:"error"` - Reason string `json:"reason"` -} - -func (rme ErrorResponse) Error() string { - return fmt.Sprintf("Error %d (%s): %s", rme.StatusCode, rme.Message, rme.Reason) -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/exchanges.go b/vendor/github.com/michaelklishin/rabbit-hole/exchanges.go deleted file mode 100644 index 1191ade70..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/exchanges.go +++ /dev/null @@ -1,218 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// -// GET /api/exchanges -// - -type IngressEgressStats struct { - PublishIn int `json:"publish_in"` - PublishInDetails RateDetails `json:"publish_in_details"` - - PublishOut int `json:"publish_out"` - PublishOutDetails RateDetails `json:"publish_out_details"` -} - -type ExchangeInfo struct { - Name string `json:"name"` - Vhost string `json:"vhost"` - Type string `json:"type"` - Durable bool `json:"durable"` - AutoDelete bool `json:"auto_delete"` - Internal bool `json:"internal"` - Arguments map[string]interface{} `json:"arguments"` - - MessageStats IngressEgressStats `json:"message_stats"` -} - -type ExchangeSettings struct { - Type string `json:"type"` - Durable bool `json:"durable"` - AutoDelete bool `json:"auto_delete,omitempty"` - Arguments map[string]interface{} `json:"arguments,omitempty"` -} - -func (c *Client) ListExchanges() (rec []ExchangeInfo, err error) { - req, err := newGETRequest(c, "exchanges") - if err != nil { - return []ExchangeInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ExchangeInfo{}, err - } - - return rec, nil -} - -// -// GET /api/exchanges/{vhost} -// - -func (c *Client) ListExchangesIn(vhost string) (rec []ExchangeInfo, err error) { - req, err := newGETRequest(c, "exchanges/"+PathEscape(vhost)) - if err != nil { - return []ExchangeInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ExchangeInfo{}, err - } - - return rec, nil -} - -// -// GET /api/exchanges/{vhost}/{name} -// - -// Example response: -// -// { -// "incoming": [ -// { -// "stats": { -// "publish": 2760, -// "publish_details": { -// "rate": 20 -// } -// }, -// "channel_details": { -// "name": "127.0.0.1:46928 -> 127.0.0.1:5672 (2)", -// "number": 2, -// "connection_name": "127.0.0.1:46928 -> 127.0.0.1:5672", -// "peer_port": 46928, -// "peer_host": "127.0.0.1" -// } -// } -// ], -// "outgoing": [ -// { -// "stats": { -// "publish": 1280, -// "publish_details": { -// "rate": 20 -// } -// }, -// "queue": { -// "name": "amq.gen-7NhO_yRr4lDdp-8hdnvfuw", -// "vhost": "rabbit\/hole" -// } -// } -// ], -// "message_stats": { -// "publish_in": 2760, -// "publish_in_details": { -// "rate": 20 -// }, -// "publish_out": 1280, -// "publish_out_details": { -// "rate": 20 -// } -// }, -// "name": "amq.fanout", -// "vhost": "rabbit\/hole", -// "type": "fanout", -// "durable": true, -// "auto_delete": false, -// "internal": false, -// "arguments": { -// } -// } - -type ExchangeIngressDetails struct { - Stats MessageStats `json:"stats"` - ChannelDetails PublishingChannel `json:"channel_details"` -} - -type PublishingChannel struct { - Number int `json:"number"` - Name string `json:"name"` - ConnectionName string `json:"connection_name"` - PeerPort Port `json:"peer_port"` - PeerHost string `json:"peer_host"` -} - -type NameAndVhost struct { - Name string `json:"name"` - Vhost string `json:"vhost"` -} - -type ExchangeEgressDetails struct { - Stats MessageStats `json:"stats"` - Queue NameAndVhost `json:"queue"` -} - -type DetailedExchangeInfo struct { - Name string `json:"name"` - Vhost string `json:"vhost"` - Type string `json:"type"` - Durable bool `json:"durable"` - AutoDelete bool `json:"auto_delete"` - Internal bool `json:"internal"` - Arguments map[string]interface{} `json:"arguments"` - - Incoming []ExchangeIngressDetails `json:"incoming"` - Outgoing []ExchangeEgressDetails `json:"outgoing"` -} - -func (c *Client) GetExchange(vhost, exchange string) (rec *DetailedExchangeInfo, err error) { - req, err := newGETRequest(c, "exchanges/"+PathEscape(vhost)+"/"+PathEscape(exchange)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/exchanges/{vhost}/{exchange} -// - -func (c *Client) DeclareExchange(vhost, exchange string, info ExchangeSettings) (res *http.Response, err error) { - if info.Arguments == nil { - info.Arguments = make(map[string]interface{}) - } - body, err := json.Marshal(info) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "exchanges/"+PathEscape(vhost)+"/"+PathEscape(exchange), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/exchanges/{vhost}/{name} -// - -func (c *Client) DeleteExchange(vhost, exchange string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "exchanges/"+PathEscape(vhost)+"/"+PathEscape(exchange), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/federation.go b/vendor/github.com/michaelklishin/rabbit-hole/federation.go deleted file mode 100644 index 7e854ea35..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/federation.go +++ /dev/null @@ -1,73 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// Federation definition: additional arguments -// added to the entities (queues, exchanges or both) -// that match a policy. -type FederationDefinition struct { - Uri string `json:"uri"` - Expires int `json:"expires"` - MessageTTL int32 `json:"message-ttl"` - MaxHops int `json:"max-hops"` - PrefetchCount int `json:"prefetch-count"` - ReconnectDelay int `json:"reconnect-delay"` - AckMode string `json:"ack-mode,omitempty"` - TrustUserId bool `json:"trust-user-id"` - Exchange string `json:"exchange"` - Queue string `json:"queue"` -} - -// Represents a configured Federation upstream. -type FederationUpstream struct { - Definition FederationDefinition `json:"value"` -} - -// -// PUT /api/parameters/federation-upstream/{vhost}/{upstream} -// - -// Updates a federation upstream -func (c *Client) PutFederationUpstream(vhost string, upstreamName string, fDef FederationDefinition) (res *http.Response, err error) { - fedUp := FederationUpstream{ - Definition: fDef, - } - body, err := json.Marshal(fedUp) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "parameters/federation-upstream/"+PathEscape(vhost)+"/"+PathEscape(upstreamName), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/parameters/federation-upstream/{vhost}/{name} -// - -// Deletes a federation upstream. -func (c *Client) DeleteFederationUpstream(vhost, upstreamName string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "parameters/federation-upstream/"+PathEscape(vhost)+"/"+PathEscape(upstreamName), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/misc.go b/vendor/github.com/michaelklishin/rabbit-hole/misc.go deleted file mode 100644 index 9fbd9887c..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/misc.go +++ /dev/null @@ -1,83 +0,0 @@ -package rabbithole - -// -// GET /api/overview -// - -type QueueTotals struct { - Messages int `json:"messages"` - MessagesDetails RateDetails `json:"messages_details"` - - MessagesReady int `json:"messages_ready"` - MessagesReadyDetails RateDetails `json:"messages_ready_details"` - - MessagesUnacknowledged int `json:"messages_unacknowledged"` - MessagesUnacknowledgedDetails RateDetails `json:"messages_unacknowledged_details"` -} - -type ObjectTotals struct { - Consumers int `json:"consumers"` - Queues int `json:"queues"` - Exchanges int `json:"exchanges"` - Connections int `json:"connections"` - Channels int `json:"channels"` -} - -type Listener struct { - Node string `json:"node"` - Protocol string `json:"protocol"` - IpAddress string `json:"ip_address"` - Port Port `json:"port"` -} - -type Overview struct { - ManagementVersion string `json:"management_version"` - StatisticsLevel string `json:"statistics_level"` - RabbitMQVersion string `json:"rabbitmq_version"` - ErlangVersion string `json:"erlang_version"` - FullErlangVersion string `json:"erlang_full_version"` - ExchangeTypes []ExchangeType `json:"exchange_types"` - MessageStats MessageStats `json:"message_stats"` - QueueTotals QueueTotals `json:"queue_totals"` - ObjectTotals ObjectTotals `json:"object_totals"` - Node string `json:"node"` - StatisticsDBNode string `json:"statistics_db_node"` - Listeners []Listener `json:"listeners"` - Contexts []BrokerContext `json:"contexts"` -} - -func (c *Client) Overview() (rec *Overview, err error) { - req, err := newGETRequest(c, "overview") - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// GET /api/whoami -// - -type WhoamiInfo struct { - Name string `json:"name"` - Tags string `json:"tags"` - AuthBackend string `json:"auth_backend"` -} - -func (c *Client) Whoami() (rec *WhoamiInfo, err error) { - req, err := newGETRequest(c, "whoami") - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/nodes.go b/vendor/github.com/michaelklishin/rabbit-hole/nodes.go deleted file mode 100644 index 4669641da..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/nodes.go +++ /dev/null @@ -1,300 +0,0 @@ -package rabbithole - -type OsPid string - -type NameDescriptionEnabled struct { - Name string `json:"name"` - Description string `json:"description"` - Enabled bool `json:"enabled"` -} - -type AuthMechanism NameDescriptionEnabled - -type ExchangeType NameDescriptionEnabled - -type NameDescriptionVersion struct { - Name string `json:"name"` - Description string `json:"description"` - Version string `json:"version"` -} - -type ErlangApp NameDescriptionVersion - -type NodeInfo struct { - Name string `json:"name"` - NodeType string `json:"type"` - IsRunning bool `json:"running"` - OsPid OsPid `json:"os_pid"` - - FdUsed int `json:"fd_used"` - FdTotal int `json:"fd_total"` - ProcUsed int `json:"proc_used"` - ProcTotal int `json:"proc_total"` - SocketsUsed int `json:"sockets_used"` - SocketsTotal int `json:"sockets_total"` - MemUsed int `json:"mem_used"` - MemLimit int `json:"mem_limit"` - MemAlarm bool `json:"mem_alarm"` - DiskFree int `json:"disk_free"` - DiskFreeLimit int `json:"disk_free_limit"` - DiskFreeAlarm bool `json:"disk_free_alarm"` - - // Erlang scheduler run queue length - RunQueueLength uint32 `json:"run_queue"` - Processors uint32 `json:"processors"` - Uptime uint64 `json:"uptime"` - - ExchangeTypes []ExchangeType `json:"exchange_types"` - AuthMechanisms []AuthMechanism `json:"auth_mechanisms"` - ErlangApps []ErlangApp `json:"applications"` - Contexts []BrokerContext `json:"contexts"` - - Partitions []string `json:"partitions"` -} - -// -// GET /api/nodes -// - -func (c *Client) ListNodes() (rec []NodeInfo, err error) { - req, err := newGETRequest(c, "nodes") - if err != nil { - return []NodeInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// GET /api/nodes/{name} -// - -// { -// "partitions": [], -// "os_pid": "39292", -// "fd_used": 35, -// "fd_total": 256, -// "sockets_used": 4, -// "sockets_total": 138, -// "mem_used": 69964432, -// "mem_limit": 2960660889, -// "mem_alarm": false, -// "disk_free_limit": 50000000, -// "disk_free": 188362731520, -// "disk_free_alarm": false, -// "proc_used": 370, -// "proc_total": 1048576, -// "statistics_level": "fine", -// "uptime": 98355255, -// "run_queue": 0, -// "processors": 8, -// "exchange_types": [ -// { -// "name": "topic", -// "description": "AMQP topic exchange, as per the AMQP specification", -// "enabled": true -// }, -// { -// "name": "x-consistent-hash", -// "description": "Consistent Hashing Exchange", -// "enabled": true -// }, -// { -// "name": "fanout", -// "description": "AMQP fanout exchange, as per the AMQP specification", -// "enabled": true -// }, -// { -// "name": "direct", -// "description": "AMQP direct exchange, as per the AMQP specification", -// "enabled": true -// }, -// { -// "name": "headers", -// "description": "AMQP headers exchange, as per the AMQP specification", -// "enabled": true -// } -// ], -// "auth_mechanisms": [ -// { -// "name": "AMQPLAIN", -// "description": "QPid AMQPLAIN mechanism", -// "enabled": true -// }, -// { -// "name": "PLAIN", -// "description": "SASL PLAIN authentication mechanism", -// "enabled": true -// }, -// { -// "name": "RABBIT-CR-DEMO", -// "description": "RabbitMQ Demo challenge-response authentication mechanism", -// "enabled": false -// } -// ], -// "applications": [ -// { -// "name": "amqp_client", -// "description": "RabbitMQ AMQP Client", -// "version": "3.2.0" -// }, -// { -// "name": "asn1", -// "description": "The Erlang ASN1 compiler version 2.0.3", -// "version": "2.0.3" -// }, -// { -// "name": "cowboy", -// "description": "Small, fast, modular HTTP server.", -// "version": "0.5.0-rmq3.2.0-git4b93c2d" -// }, -// { -// "name": "crypto", -// "description": "CRYPTO version 2", -// "version": "3.1" -// }, -// { -// "name": "inets", -// "description": "INETS CXC 138 49", -// "version": "5.9.6" -// }, -// { -// "name": "kernel", -// "description": "ERTS CXC 138 10", -// "version": "2.16.3" -// }, -// { -// "name": "mnesia", -// "description": "MNESIA CXC 138 12", -// "version": "4.10" -// }, -// { -// "name": "mochiweb", -// "description": "MochiMedia Web Server", -// "version": "2.7.0-rmq3.2.0-git680dba8" -// }, -// { -// "name": "os_mon", -// "description": "CPO CXC 138 46", -// "version": "2.2.13" -// }, -// { -// "name": "public_key", -// "description": "Public key infrastructure", -// "version": "0.20" -// }, -// { -// "name": "rabbit", -// "description": "RabbitMQ", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_consistent_hash_exchange", -// "description": "Consistent Hash Exchange Type", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_management", -// "description": "RabbitMQ Management Console", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_management_agent", -// "description": "RabbitMQ Management Agent", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_mqtt", -// "description": "RabbitMQ MQTT Adapter", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_shovel", -// "description": "Data Shovel for RabbitMQ", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_shovel_management", -// "description": "Shovel Status", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_stomp", -// "description": "Embedded Rabbit Stomp Adapter", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_web_dispatch", -// "description": "RabbitMQ Web Dispatcher", -// "version": "3.2.0" -// }, -// { -// "name": "rabbitmq_web_stomp", -// "description": "Rabbit WEB-STOMP - WebSockets to Stomp adapter", -// "version": "3.2.0" -// }, -// { -// "name": "sasl", -// "description": "SASL CXC 138 11", -// "version": "2.3.3" -// }, -// { -// "name": "sockjs", -// "description": "SockJS", -// "version": "0.3.4-rmq3.2.0-git3132eb9" -// }, -// { -// "name": "ssl", -// "description": "Erlang\/OTP SSL application", -// "version": "5.3.1" -// }, -// { -// "name": "stdlib", -// "description": "ERTS CXC 138 10", -// "version": "1.19.3" -// }, -// { -// "name": "webmachine", -// "description": "webmachine", -// "version": "1.10.3-rmq3.2.0-gite9359c7" -// }, -// { -// "name": "xmerl", -// "description": "XML parser", -// "version": "1.3.4" -// } -// ], -// "contexts": [ -// { -// "description": "Redirect to port 15672", -// "path": "\/", -// "port": 55672, -// "ignore_in_use": true -// }, -// { -// "description": "RabbitMQ Management", -// "path": "\/", -// "port": 15672 -// } -// ], -// "name": "rabbit@mercurio", -// "type": "disc", -// "running": true -// } - -func (c *Client) GetNode(name string) (rec *NodeInfo, err error) { - req, err := newGETRequest(c, "nodes/"+PathEscape(name)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/permissions.go b/vendor/github.com/michaelklishin/rabbit-hole/permissions.go deleted file mode 100644 index a6260a156..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/permissions.go +++ /dev/null @@ -1,125 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// -// GET /api/permissions -// - -// Example response: -// -// [{"user":"guest","vhost":"/","configure":".*","write":".*","read":".*"}] - -type PermissionInfo struct { - User string `json:"user"` - Vhost string `json:"vhost"` - - // Configuration permissions - Configure string `json:"configure"` - // Write permissions - Write string `json:"write"` - // Read permissions - Read string `json:"read"` -} - -// Returns permissions for all users and virtual hosts. -func (c *Client) ListPermissions() (rec []PermissionInfo, err error) { - req, err := newGETRequest(c, "permissions/") - if err != nil { - return []PermissionInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []PermissionInfo{}, err - } - - return rec, nil -} - -// -// GET /api/users/{user}/permissions -// - -// Returns permissions of a specific user. -func (c *Client) ListPermissionsOf(username string) (rec []PermissionInfo, err error) { - req, err := newGETRequest(c, "users/"+PathEscape(username)+"/permissions") - if err != nil { - return []PermissionInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []PermissionInfo{}, err - } - - return rec, nil -} - -// -// GET /api/permissions/{vhost}/{user} -// - -// Returns permissions of user in virtual host. -func (c *Client) GetPermissionsIn(vhost, username string) (rec PermissionInfo, err error) { - req, err := newGETRequest(c, "permissions/"+PathEscape(vhost)+"/"+PathEscape(username)) - if err != nil { - return PermissionInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return PermissionInfo{}, err - } - - return rec, nil -} - -// -// PUT /api/permissions/{vhost}/{user} -// - -type Permissions struct { - Configure string `json:"configure"` - Write string `json:"write"` - Read string `json:"read"` -} - -// Updates permissions of user in virtual host. -func (c *Client) UpdatePermissionsIn(vhost, username string, permissions Permissions) (res *http.Response, err error) { - body, err := json.Marshal(permissions) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "permissions/"+PathEscape(vhost)+"/"+PathEscape(username), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/permissions/{vhost}/{user} -// - -// Clears (deletes) permissions of user in virtual host. -func (c *Client) ClearPermissionsIn(vhost, username string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "permissions/"+PathEscape(vhost)+"/"+PathEscape(username), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/plugins.go b/vendor/github.com/michaelklishin/rabbit-hole/plugins.go deleted file mode 100644 index b2b9b266b..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/plugins.go +++ /dev/null @@ -1,31 +0,0 @@ -package rabbithole - -func (c *Client) EnabledProtocols() (xs []string, err error) { - overview, err := c.Overview() - if err != nil { - return []string{}, err - } - - // we really need to implement Map/Filter/etc. MK. - xs = make([]string, len(overview.Listeners)) - for i, lnr := range overview.Listeners { - xs[i] = lnr.Protocol - } - - return xs, nil -} - -func (c *Client) ProtocolPorts() (res map[string]Port, err error) { - res = map[string]Port{} - - overview, err := c.Overview() - if err != nil { - return res, err - } - - for _, lnr := range overview.Listeners { - res[lnr.Protocol] = lnr.Port - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/policies.go b/vendor/github.com/michaelklishin/rabbit-hole/policies.go deleted file mode 100644 index 765000878..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/policies.go +++ /dev/null @@ -1,126 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// Policy definition: additional arguments -// added to the entities (queues, exchanges or both) -// that match a policy. -type PolicyDefinition map[string]interface{} - -type NodeNames []string - -// Represents a configured policy. -type Policy struct { - // Virtual host this policy is in. - Vhost string `json:"vhost"` - // Regular expression pattern used to match queues and exchanges, - // , e.g. "^ha\..+" - Pattern string `json:"pattern"` - // What this policy applies to: "queues", "exchanges", etc. - ApplyTo string `json:"apply-to"` - Name string `json:"name"` - Priority int `json:"priority"` - // Additional arguments added to the entities (queues, - // exchanges or both) that match a policy - Definition PolicyDefinition `json:"definition"` -} - -// -// GET /api/policies -// - -// Return all policies (across all virtual hosts). -func (c *Client) ListPolicies() (rec []Policy, err error) { - req, err := newGETRequest(c, "policies") - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// GET /api/policies/{vhost} -// - -// Returns policies in a specific virtual host. -func (c *Client) ListPoliciesIn(vhost string) (rec []Policy, err error) { - req, err := newGETRequest(c, "policies/"+PathEscape(vhost)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// GET /api/policies/{vhost}/{name} -// - -// Returns individual policy in virtual host. -func (c *Client) GetPolicy(vhost, name string) (rec *Policy, err error) { - req, err := newGETRequest(c, "policies/"+PathEscape(vhost)+"/"+PathEscape(name)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/policies/{vhost}/{name} -// - -// Updates a policy. -func (c *Client) PutPolicy(vhost string, name string, policy Policy) (res *http.Response, err error) { - body, err := json.Marshal(policy) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "policies/"+PathEscape(vhost)+"/"+PathEscape(name), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/policies/{vhost}/{name} -// - -// Deletes a policy. -func (c *Client) DeletePolicy(vhost, name string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "policies/"+PathEscape(vhost)+"/"+PathEscape(name), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/queues.go b/vendor/github.com/michaelklishin/rabbit-hole/queues.go deleted file mode 100644 index 507551574..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/queues.go +++ /dev/null @@ -1,316 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" - "net/url" -) - -// Information about backing queue (queue storage engine). -type BackingQueueStatus struct { - Q1 int `json:"q1"` - Q2 int `json:"q2"` - Q3 int `json:"q3"` - Q4 int `json:"q4"` - // Total queue length - Length int64 `json:"len"` - // Number of pending acks from consumers - PendingAcks int64 `json:"pending_acks"` - // Number of messages held in RAM - RAMMessageCount int64 `json:"ram_msg_count"` - // Number of outstanding acks held in RAM - RAMAckCount int64 `json:"ram_ack_count"` - // Number of persistent messages in the store - PersistentCount int64 `json:"persistent_count"` - // Average ingress (inbound) rate, not including messages - // that straight through to auto-acking consumers. - AverageIngressRate float64 `json:"avg_ingress_rate"` - // Average egress (outbound) rate, not including messages - // that straight through to auto-acking consumers. - AverageEgressRate float64 `json:"avg_egress_rate"` - // rate at which unacknowledged message records enter RAM, - // e.g. because messages are delivered requiring acknowledgement - AverageAckIngressRate float32 `json:"avg_ack_ingress_rate"` - // rate at which unacknowledged message records leave RAM, - // e.g. because acks arrive or unacked messages are paged out - AverageAckEgressRate float32 `json:"avg_ack_egress_rate"` -} - -type OwnerPidDetails struct { - Name string `json:"name"` - PeerPort Port `json:"peer_port"` - PeerHost string `json:"peer_host"` -} - -type QueueInfo struct { - // Queue name - Name string `json:"name"` - // Virtual host this queue belongs to - Vhost string `json:"vhost"` - // Is this queue durable? - Durable bool `json:"durable"` - // Is this queue auto-delted? - AutoDelete bool `json:"auto_delete"` - // Extra queue arguments - Arguments map[string]interface{} `json:"arguments"` - - // RabbitMQ node that hosts master for this queue - Node string `json:"node"` - // Queue status - Status string `json:"status"` - - // Total amount of RAM used by this queue - Memory int64 `json:"memory"` - // How many consumers this queue has - Consumers int `json:"consumers"` - // Utilisation of all the consumers - ConsumerUtilisation float64 `json:"consumer_utilisation"` - // If there is an exclusive consumer, its consumer tag - ExclusiveConsumerTag string `json:"exclusive_consumer_tag"` - - // Policy applied to this queue, if any - Policy string `json:"policy"` - - // Total bytes of messages in this queues - MessagesBytes int64 `json:"message_bytes"` - MessagesBytesPersistent int64 `json:"message_bytes_persistent"` - MessagesBytesRAM int64 `json:"message_bytes_ram"` - - // Total number of messages in this queue - Messages int `json:"messages"` - MessagesDetails RateDetails `json:"messages_details"` - MessagesPersistent int `json:"messages_persistent"` - MessagesRAM int `json:"messages_ram"` - - // Number of messages ready to be delivered - MessagesReady int `json:"messages_ready"` - MessagesReadyDetails RateDetails `json:"messages_ready_details"` - - // Number of messages delivered and pending acknowledgements from consumers - MessagesUnacknowledged int `json:"messages_unacknowledged"` - MessagesUnacknowledgedDetails RateDetails `json:"messages_unacknowledged_details"` - - MessageStats MessageStats `json:"message_stats"` - - OwnerPidDetails OwnerPidDetails `json:"owner_pid_details"` - - BackingQueueStatus BackingQueueStatus `json:"backing_queue_status"` - - ActiveConsumers int64 `json:"active_consumers"` -} - -type DetailedQueueInfo QueueInfo - -// -// GET /api/queues -// - -// [ -// { -// "owner_pid_details": { -// "name": "127.0.0.1:46928 -> 127.0.0.1:5672", -// "peer_port": 46928, -// "peer_host": "127.0.0.1" -// }, -// "message_stats": { -// "publish": 19830, -// "publish_details": { -// "rate": 5 -// } -// }, -// "messages": 15, -// "messages_details": { -// "rate": 0 -// }, -// "messages_ready": 15, -// "messages_ready_details": { -// "rate": 0 -// }, -// "messages_unacknowledged": 0, -// "messages_unacknowledged_details": { -// "rate": 0 -// }, -// "policy": "", -// "exclusive_consumer_tag": "", -// "consumers": 0, -// "memory": 143112, -// "backing_queue_status": { -// "q1": 0, -// "q2": 0, -// "delta": [ -// "delta", -// "undefined", -// 0, -// "undefined" -// ], -// "q3": 0, -// "q4": 15, -// "len": 15, -// "pending_acks": 0, -// "target_ram_count": "infinity", -// "ram_msg_count": 15, -// "ram_ack_count": 0, -// "next_seq_id": 19830, -// "persistent_count": 0, -// "avg_ingress_rate": 4.9920127795527, -// "avg_egress_rate": 4.9920127795527, -// "avg_ack_ingress_rate": 0, -// "avg_ack_egress_rate": 0 -// }, -// "status": "running", -// "name": "amq.gen-QLEaT5Rn_ogbN3O8ZOQt3Q", -// "vhost": "rabbit\/hole", -// "durable": false, -// "auto_delete": false, -// "arguments": { -// "x-message-ttl": 5000 -// }, -// "node": "rabbit@marzo" -// } -// ] - -func (c *Client) ListQueues() (rec []QueueInfo, err error) { - req, err := newGETRequest(c, "queues") - if err != nil { - return []QueueInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []QueueInfo{}, err - } - - return rec, nil -} - -func (c *Client) ListQueuesWithParameters(params url.Values) (rec []QueueInfo, err error) { - req, err := newGETRequestWithParameters(c, "queues", params) - if err != nil { - return []QueueInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []QueueInfo{}, err - } - - return rec, nil -} - -// -// GET /api/queues/{vhost} -// - -func (c *Client) ListQueuesIn(vhost string) (rec []QueueInfo, err error) { - req, err := newGETRequest(c, "queues/"+PathEscape(vhost)) - if err != nil { - return []QueueInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []QueueInfo{}, err - } - - return rec, nil -} - -// -// GET /api/queues/{vhost}/{name} -// - -func (c *Client) GetQueue(vhost, queue string) (rec *DetailedQueueInfo, err error) { - req, err := newGETRequest(c, "queues/"+PathEscape(vhost)+"/"+PathEscape(queue)) - - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// GET /api/queues/{vhost}/{name}?{query} - -func (c *Client) GetQueueWithParameters(vhost, queue string, qs url.Values) (rec *DetailedQueueInfo, err error) { - req, err := newGETRequestWithParameters(c, "queues/"+PathEscape(vhost)+"/"+PathEscape(queue), qs) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/exchanges/{vhost}/{exchange} -// - -type QueueSettings struct { - Type string `json:"type"` - Durable bool `json:"durable"` - AutoDelete bool `json:"auto_delete,omitempty"` - Arguments map[string]interface{} `json:"arguments,omitempty"` -} - -func (c *Client) DeclareQueue(vhost, queue string, info QueueSettings) (res *http.Response, err error) { - if info.Arguments == nil { - info.Arguments = make(map[string]interface{}) - } - body, err := json.Marshal(info) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "queues/"+PathEscape(vhost)+"/"+PathEscape(queue), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/queues/{vhost}/{name} -// - -func (c *Client) DeleteQueue(vhost, queue string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "queues/"+PathEscape(vhost)+"/"+PathEscape(queue), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/queues/{vhost}/{name}/contents -// - -func (c *Client) PurgeQueue(vhost, queue string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "queues/"+PathEscape(vhost)+"/"+PathEscape(queue)+"/contents", nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/shovels.go b/vendor/github.com/michaelklishin/rabbit-hole/shovels.go deleted file mode 100644 index 36a5766e7..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/shovels.go +++ /dev/null @@ -1,140 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// ShovelInfo contains the configuration of a shovel -type ShovelInfo struct { - // Shovel name - Name string `json:"name"` - // Virtual host this shovel belongs to - Vhost string `json:"vhost"` - // Component shovels belong to - Component string `json:"component"` - // Details the configuration values of the shovel - Definition ShovelDefinition `json:"value"` -} - -// ShovelDefinition contains the details of the shovel configuration -type ShovelDefinition struct { - SourceURI string `json:"src-uri"` - SourceExchange string `json:"src-exchange,omitempty"` - SourceExchangeKey string `json:"src-exchange-key,omitempty"` - SourceQueue string `json:"src-queue,omitempty"` - DestinationURI string `json:"dest-uri"` - DestinationExchange string `json:"dest-exchange,omitempty"` - DestinationExchangeKey string `json:"dest-exchange-key,omitempty"` - DestinationQueue string `json:"dest-queue,omitempty"` - PrefetchCount int `json:"prefetch-count,omitempty"` - ReconnectDelay int `json:"reconnect-delay,omitempty"` - AddForwardHeaders bool `json:"add-forward-headers"` - AckMode string `json:"ack-mode"` - DeleteAfter string `json:"delete-after"` -} - -// ShovelDefinitionDTO provides a data transfer object -type ShovelDefinitionDTO struct { - Definition ShovelDefinition `json:"value"` -} - -// -// GET /api/parameters/shovel -// - -// ListShovels returns all shovels -func (c *Client) ListShovels() (rec []ShovelInfo, err error) { - req, err := newGETRequest(c, "parameters/shovel") - if err != nil { - return []ShovelInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ShovelInfo{}, err - } - - return rec, nil -} - -// -// GET /api/parameters/shovel/{vhost} -// - -// ListShovelsIn returns all shovels in a vhost -func (c *Client) ListShovelsIn(vhost string) (rec []ShovelInfo, err error) { - req, err := newGETRequest(c, "parameters/shovel/"+PathEscape(vhost)) - if err != nil { - return []ShovelInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []ShovelInfo{}, err - } - - return rec, nil -} - -// -// GET /api/parameters/shovel/{vhost}/{name} -// - -// GetShovel returns a shovel configuration -func (c *Client) GetShovel(vhost, shovel string) (rec *ShovelInfo, err error) { - req, err := newGETRequest(c, "parameters/shovel/"+PathEscape(vhost)+"/"+PathEscape(shovel)) - - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/parameters/shovel/{vhost}/{name} -// - -// DeclareShovel creates a shovel -func (c *Client) DeclareShovel(vhost, shovel string, info ShovelDefinition) (res *http.Response, err error) { - shovelDTO := ShovelDefinitionDTO{Definition: info} - - body, err := json.Marshal(shovelDTO) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "parameters/shovel/"+PathEscape(vhost)+"/"+PathEscape(shovel), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/parameters/shovel/{vhost}/{name} -// - -// DeleteShovel a shovel -func (c *Client) DeleteShovel(vhost, shovel string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "parameters/shovel/"+PathEscape(vhost)+"/"+PathEscape(shovel), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/users.go b/vendor/github.com/michaelklishin/rabbit-hole/users.go deleted file mode 100644 index a20960bff..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/users.go +++ /dev/null @@ -1,128 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -type UserInfo struct { - Name string `json:"name"` - PasswordHash string `json:"password_hash"` - // Tags control permissions. Built-in tags: administrator, management, policymaker. - Tags string `json:"tags"` -} - -// Settings used to create users. Tags must be comma-separated. -type UserSettings struct { - Name string `json:"name"` - // Tags control permissions. Administrator grants full - // permissions, management grants management UI and HTTP API - // access, policymaker grants policy management permissions. - Tags string `json:"tags"` - - // *never* returned by RabbitMQ. Set by the client - // to create/update a user. MK. - Password string `json:"password,omitempty"` - PasswordHash string `json:"password_hash,omitempty"` -} - -// -// GET /api/users -// - -// Example response: -// [{"name":"guest","password_hash":"8LYTIFbVUwi8HuV/dGlp2BYsD1I=","tags":"administrator"}] - -// Returns a list of all users in a cluster. -func (c *Client) ListUsers() (rec []UserInfo, err error) { - req, err := newGETRequest(c, "users/") - if err != nil { - return []UserInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []UserInfo{}, err - } - - return rec, nil -} - -// -// GET /api/users/{name} -// - -// Returns information about individual user. -func (c *Client) GetUser(username string) (rec *UserInfo, err error) { - req, err := newGETRequest(c, "users/"+PathEscape(username)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/users/{name} -// - -// Updates information about individual user. -func (c *Client) PutUser(username string, info UserSettings) (res *http.Response, err error) { - body, err := json.Marshal(info) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "users/"+PathEscape(username), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *Client) PutUserWithoutPassword(username string, info UserSettings) (res *http.Response, err error) { - body, err := json.Marshal(UserInfo{Tags: info.Tags}) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "users/"+PathEscape(username), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/users/{name} -// - -// Deletes user. -func (c *Client) DeleteUser(username string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "users/"+PathEscape(username), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/michaelklishin/rabbit-hole/vhosts.go b/vendor/github.com/michaelklishin/rabbit-hole/vhosts.go deleted file mode 100644 index 226d7a49a..000000000 --- a/vendor/github.com/michaelklishin/rabbit-hole/vhosts.go +++ /dev/null @@ -1,159 +0,0 @@ -package rabbithole - -import ( - "encoding/json" - "net/http" -) - -// -// GET /api/vhosts -// - -// Example response: - -// [ -// { -// "message_stats": { -// "publish": 78, -// "publish_details": { -// "rate": 0 -// } -// }, -// "messages": 0, -// "messages_details": { -// "rate": 0 -// }, -// "messages_ready": 0, -// "messages_ready_details": { -// "rate": 0 -// }, -// "messages_unacknowledged": 0, -// "messages_unacknowledged_details": { -// "rate": 0 -// }, -// "recv_oct": 16653, -// "recv_oct_details": { -// "rate": 0 -// }, -// "send_oct": 40495, -// "send_oct_details": { -// "rate": 0 -// }, -// "name": "\/", -// "tracing": false -// }, -// { -// "name": "29dd51888b834698a8b5bc3e7f8623aa1c9671f5", -// "tracing": false -// } -// ] - -type VhostInfo struct { - // Virtual host name - Name string `json:"name"` - // True if tracing is enabled for this virtual host - Tracing bool `json:"tracing"` - - // Total number of messages in queues of this virtual host - Messages int `json:"messages"` - MessagesDetails RateDetails `json:"messages_details"` - - // Total number of messages ready to be delivered in queues of this virtual host - MessagesReady int `json:"messages_ready"` - MessagesReadyDetails RateDetails `json:"messages_ready_details"` - - // Total number of messages pending acknowledgement from consumers in this virtual host - MessagesUnacknowledged int `json:"messages_unacknowledged"` - MessagesUnacknowledgedDetails RateDetails `json:"messages_unacknowledged_details"` - - // Octets received - RecvOct uint64 `json:"recv_oct"` - // Octets sent - SendOct uint64 `json:"send_oct"` - RecvCount uint64 `json:"recv_cnt"` - SendCount uint64 `json:"send_cnt"` - SendPending uint64 `json:"send_pend"` - RecvOctDetails RateDetails `json:"recv_oct_details"` - SendOctDetails RateDetails `json:"send_oct_details"` -} - -// Returns a list of virtual hosts. -func (c *Client) ListVhosts() (rec []VhostInfo, err error) { - req, err := newGETRequest(c, "vhosts") - if err != nil { - return []VhostInfo{}, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return []VhostInfo{}, err - } - - return rec, nil -} - -// -// GET /api/vhosts/{name} -// - -// Returns information about a specific virtual host. -func (c *Client) GetVhost(vhostname string) (rec *VhostInfo, err error) { - req, err := newGETRequest(c, "vhosts/"+PathEscape(vhostname)) - if err != nil { - return nil, err - } - - if err = executeAndParseRequest(c, req, &rec); err != nil { - return nil, err - } - - return rec, nil -} - -// -// PUT /api/vhosts/{name} -// - -// Settings used to create or modify virtual hosts. -type VhostSettings struct { - // True if tracing should be enabled. - Tracing bool `json:"tracing"` -} - -// Creates or updates a virtual host. -func (c *Client) PutVhost(vhostname string, settings VhostSettings) (res *http.Response, err error) { - body, err := json.Marshal(settings) - if err != nil { - return nil, err - } - - req, err := newRequestWithBody(c, "PUT", "vhosts/"+PathEscape(vhostname), body) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} - -// -// DELETE /api/vhosts/{name} -// - -// Deletes a virtual host. -func (c *Client) DeleteVhost(vhostname string) (res *http.Response, err error) { - req, err := newRequestWithBody(c, "DELETE", "vhosts/"+PathEscape(vhostname), nil) - if err != nil { - return nil, err - } - - res, err = executeRequest(c, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/vendor/github.com/mitchellh/cli/.travis.yml b/vendor/github.com/mitchellh/cli/.travis.yml new file mode 100644 index 000000000..b8599b3ac --- /dev/null +++ b/vendor/github.com/mitchellh/cli/.travis.yml @@ -0,0 +1,14 @@ +sudo: false + +language: go + +go: + - "1.8" + - "1.9" + - "1.10" + +branches: + only: + - master + +script: make updatedeps test testrace diff --git a/vendor/github.com/mitchellh/cli/cli.go b/vendor/github.com/mitchellh/cli/cli.go index 61206d6aa..c2dbe55aa 100644 --- a/vendor/github.com/mitchellh/cli/cli.go +++ b/vendor/github.com/mitchellh/cli/cli.go @@ -87,7 +87,7 @@ type CLI struct { // should be set exactly to the binary name that is autocompleted. // // Autocompletion is supported via the github.com/posener/complete - // library. This library supports both bash and zsh. To add support + // library. This library supports bash, zsh and fish. To add support // for other shells, please see that library. // // AutocompleteInstall and AutocompleteUninstall are the global flag @@ -419,6 +419,11 @@ func (c *CLI) initAutocomplete() { func (c *CLI) initAutocompleteSub(prefix string) complete.Command { var cmd complete.Command walkFn := func(k string, raw interface{}) bool { + // Ignore the empty key which can be present for default commands. + if k == "" { + return false + } + // Keep track of the full key so that we can nest further if necessary fullKey := k @@ -646,9 +651,29 @@ func (c *CLI) processArgs() { if c.subcommand == "" && arg != "" && arg[0] != '-' { c.subcommand = arg if c.commandNested { + // If the command has a space in it, then it is invalid. + // Set a blank command so that it fails. + if strings.ContainsRune(arg, ' ') { + c.subcommand = "" + return + } + + // Determine the argument we look to to end subcommands. + // We look at all arguments until one has a space. This + // disallows commands like: ./cli foo "bar baz". An argument + // with a space is always an argument. + j := 0 + for k, v := range c.Args[i:] { + if strings.ContainsRune(v, ' ') { + break + } + + j = i + k + 1 + } + // Nested CLI, the subcommand is actually the entire // arg list up to a flag that is still a valid subcommand. - searchKey := strings.Join(c.Args[i:], " ") + searchKey := strings.Join(c.Args[i:j], " ") k, _, ok := c.commandTree.LongestPrefix(searchKey) if ok { // k could be a prefix that doesn't contain the full diff --git a/vendor/github.com/mitchellh/cli/go.mod b/vendor/github.com/mitchellh/cli/go.mod new file mode 100644 index 000000000..675325ffa --- /dev/null +++ b/vendor/github.com/mitchellh/cli/go.mod @@ -0,0 +1,12 @@ +module github.com/mitchellh/cli + +require ( + github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 + github.com/bgentry/speakeasy v0.1.0 + github.com/fatih/color v1.7.0 + github.com/hashicorp/go-multierror v1.0.0 // indirect + github.com/mattn/go-colorable v0.0.9 // indirect + github.com/mattn/go-isatty v0.0.3 + github.com/posener/complete v1.1.1 + golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc // indirect +) diff --git a/vendor/github.com/mitchellh/cli/go.sum b/vendor/github.com/mitchellh/cli/go.sum new file mode 100644 index 000000000..037087523 --- /dev/null +++ b/vendor/github.com/mitchellh/cli/go.sum @@ -0,0 +1,22 @@ +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357 h1:Rem2+U35z1QtPQc6r+WolF7yXiefXqDKyk+lN2pE164= +github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0 h1:j30noezaCfvNLcdMYSvHLv81DxYRSt1grlpseG67vhU= +github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= +github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc h1:MeuS1UDyZyFH++6vVy44PuufTeFF0d0nfI6XB87YGSk= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/vendor/github.com/mitchellh/cli/ui_colored.go b/vendor/github.com/mitchellh/cli/ui_colored.go index e3d5131d1..b0ec44840 100644 --- a/vendor/github.com/mitchellh/cli/ui_colored.go +++ b/vendor/github.com/mitchellh/cli/ui_colored.go @@ -1,7 +1,11 @@ package cli import ( - "fmt" + "github.com/fatih/color" +) + +const ( + noColor = -1 ) // UiColor is a posix shell color code to use. @@ -12,13 +16,13 @@ type UiColor struct { // A list of colors that are useful. These are all non-bolded by default. var ( - UiColorNone UiColor = UiColor{-1, false} - UiColorRed = UiColor{31, false} - UiColorGreen = UiColor{32, false} - UiColorYellow = UiColor{33, false} - UiColorBlue = UiColor{34, false} - UiColorMagenta = UiColor{35, false} - UiColorCyan = UiColor{36, false} + UiColorNone UiColor = UiColor{noColor, false} + UiColorRed = UiColor{int(color.FgHiRed), false} + UiColorGreen = UiColor{int(color.FgHiGreen), false} + UiColorYellow = UiColor{int(color.FgHiYellow), false} + UiColorBlue = UiColor{int(color.FgHiBlue), false} + UiColorMagenta = UiColor{int(color.FgHiMagenta), false} + UiColorCyan = UiColor{int(color.FgHiCyan), false} ) // ColoredUi is a Ui implementation that colors its output according @@ -55,15 +59,15 @@ func (u *ColoredUi) Warn(message string) { u.Ui.Warn(u.colorize(message, u.WarnColor)) } -func (u *ColoredUi) colorize(message string, color UiColor) string { - if color.Code == -1 { +func (u *ColoredUi) colorize(message string, uc UiColor) string { + if uc.Code == noColor { return message } - attr := 0 - if color.Bold { - attr = 1 + attr := []color.Attribute{color.Attribute(uc.Code)} + if uc.Bold { + attr = append(attr, color.Bold) } - return fmt.Sprintf("\033[%d;%dm%s\033[0m", attr, color.Code, message) + return color.New(attr...).SprintFunc()(message) } diff --git a/vendor/github.com/mitchellh/copystructure/.travis.yml b/vendor/github.com/mitchellh/copystructure/.travis.yml new file mode 100644 index 000000000..d7b9589ab --- /dev/null +++ b/vendor/github.com/mitchellh/copystructure/.travis.yml @@ -0,0 +1,12 @@ +language: go + +go: + - 1.7 + - tip + +script: + - go test + +matrix: + allow_failures: + - go: tip diff --git a/vendor/github.com/mitchellh/copystructure/copystructure.go b/vendor/github.com/mitchellh/copystructure/copystructure.go index 0e725ea72..140435255 100644 --- a/vendor/github.com/mitchellh/copystructure/copystructure.go +++ b/vendor/github.com/mitchellh/copystructure/copystructure.go @@ -156,9 +156,13 @@ func (w *walker) Exit(l reflectwalk.Location) error { } switch l { + case reflectwalk.Array: + fallthrough case reflectwalk.Map: fallthrough case reflectwalk.Slice: + w.replacePointerMaybe() + // Pop map off our container w.cs = w.cs[:len(w.cs)-1] case reflectwalk.MapValue: @@ -171,16 +175,27 @@ func (w *walker) Exit(l reflectwalk.Location) error { // or in this case never adds it. We need to create a properly typed // zero value so that this key can be set. if !mv.IsValid() { - mv = reflect.Zero(m.Type().Elem()) + mv = reflect.Zero(m.Elem().Type().Elem()) + } + m.Elem().SetMapIndex(mk, mv) + case reflectwalk.ArrayElem: + // Pop off the value and the index and set it on the array + v := w.valPop() + i := w.valPop().Interface().(int) + if v.IsValid() { + a := w.cs[len(w.cs)-1] + ae := a.Elem().Index(i) // storing array as pointer on stack - so need Elem() call + if ae.CanSet() { + ae.Set(v) + } } - m.SetMapIndex(mk, mv) case reflectwalk.SliceElem: // Pop off the value and the index and set it on the slice v := w.valPop() i := w.valPop().Interface().(int) if v.IsValid() { s := w.cs[len(w.cs)-1] - se := s.Index(i) + se := s.Elem().Index(i) if se.CanSet() { se.Set(v) } @@ -220,9 +235,9 @@ func (w *walker) Map(m reflect.Value) error { // Create the map. If the map itself is nil, then just make a nil map var newMap reflect.Value if m.IsNil() { - newMap = reflect.Indirect(reflect.New(m.Type())) + newMap = reflect.New(m.Type()) } else { - newMap = reflect.MakeMap(m.Type()) + newMap = wrapPtr(reflect.MakeMap(m.Type())) } w.cs = append(w.cs, newMap) @@ -287,9 +302,9 @@ func (w *walker) Slice(s reflect.Value) error { var newS reflect.Value if s.IsNil() { - newS = reflect.Indirect(reflect.New(s.Type())) + newS = reflect.New(s.Type()) } else { - newS = reflect.MakeSlice(s.Type(), s.Len(), s.Cap()) + newS = wrapPtr(reflect.MakeSlice(s.Type(), s.Len(), s.Cap())) } w.cs = append(w.cs, newS) @@ -309,6 +324,31 @@ func (w *walker) SliceElem(i int, elem reflect.Value) error { return nil } +func (w *walker) Array(a reflect.Value) error { + if w.ignoring() { + return nil + } + w.lock(a) + + newA := reflect.New(a.Type()) + + w.cs = append(w.cs, newA) + w.valPush(newA) + return nil +} + +func (w *walker) ArrayElem(i int, elem reflect.Value) error { + if w.ignoring() { + return nil + } + + // We don't write the array here because elem might still be + // arbitrarily complex. Just record the index and continue on. + w.valPush(reflect.ValueOf(i)) + + return nil +} + func (w *walker) Struct(s reflect.Value) error { if w.ignoring() { return nil @@ -326,7 +366,10 @@ func (w *walker) Struct(s reflect.Value) error { return err } - v = reflect.ValueOf(dup) + // We need to put a pointer to the value on the value stack, + // so allocate a new pointer and set it. + v = reflect.New(s.Type()) + reflect.Indirect(v).Set(reflect.ValueOf(dup)) } else { // No copier, we copy ourselves and allow reflectwalk to guide // us deeper into the structure for copying. @@ -405,6 +448,23 @@ func (w *walker) replacePointerMaybe() { } v := w.valPop() + + // If the expected type is a pointer to an interface of any depth, + // such as *interface{}, **interface{}, etc., then we need to convert + // the value "v" from *CONCRETE to *interface{} so types match for + // Set. + // + // Example if v is type *Foo where Foo is a struct, v would become + // *interface{} instead. This only happens if we have an interface expectation + // at this depth. + // + // For more info, see GH-16 + if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)]; ok && iType.Kind() == reflect.Interface { + y := reflect.New(iType) // Create *interface{} + y.Elem().Set(reflect.Indirect(v)) // Assign "Foo" to interface{} (dereferenced) + v = y // v is now typed *interface{} (where *v = Foo) + } + for i := 1; i < w.ps[w.depth]; i++ { if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth]-i, w.depth)]; ok { iface := reflect.New(iType).Elem() @@ -475,3 +535,14 @@ func (w *walker) lock(v reflect.Value) { locker.Lock() w.locks[w.depth] = locker } + +// wrapPtr is a helper that takes v and always make it *v. copystructure +// stores things internally as pointers until the last moment before unwrapping +func wrapPtr(v reflect.Value) reflect.Value { + if !v.IsValid() { + return v + } + vPtr := reflect.New(v.Type()) + vPtr.Elem().Set(v) + return vPtr +} diff --git a/vendor/github.com/mitchellh/copystructure/go.mod b/vendor/github.com/mitchellh/copystructure/go.mod new file mode 100644 index 000000000..d01864309 --- /dev/null +++ b/vendor/github.com/mitchellh/copystructure/go.mod @@ -0,0 +1,3 @@ +module github.com/mitchellh/copystructure + +require github.com/mitchellh/reflectwalk v1.0.0 diff --git a/vendor/github.com/mitchellh/copystructure/go.sum b/vendor/github.com/mitchellh/copystructure/go.sum new file mode 100644 index 000000000..be5724561 --- /dev/null +++ b/vendor/github.com/mitchellh/copystructure/go.sum @@ -0,0 +1,2 @@ +github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= diff --git a/vendor/github.com/mitchellh/go-homedir/go.mod b/vendor/github.com/mitchellh/go-homedir/go.mod new file mode 100644 index 000000000..7efa09a04 --- /dev/null +++ b/vendor/github.com/mitchellh/go-homedir/go.mod @@ -0,0 +1 @@ +module github.com/mitchellh/go-homedir diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go index 47e1f9ef8..fb87bef94 100644 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ b/vendor/github.com/mitchellh/go-homedir/homedir.go @@ -77,33 +77,51 @@ func Expand(path string) (string, error) { } func dirUnix() (string, error) { + homeEnv := "HOME" + if runtime.GOOS == "plan9" { + // On plan9, env vars are lowercase. + homeEnv = "home" + } + // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { + if home := os.Getenv(homeEnv); home != "" { return home, nil } - // If that fails, try getent var stdout bytes.Buffer - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err + + // If that fails, try OS specific commands + if runtime.GOOS == "darwin" { + cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) + cmd.Stdout = &stdout + if err := cmd.Run(); err == nil { + result := strings.TrimSpace(stdout.String()) + if result != "" { + return result, nil + } } } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil + cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) + cmd.Stdout = &stdout + if err := cmd.Run(); err != nil { + // If the error is ErrNotFound, we ignore it. Otherwise, return it. + if err != exec.ErrNotFound { + return "", err + } + } else { + if passwd := strings.TrimSpace(stdout.String()); passwd != "" { + // username:password:uid:gid:gecos:home:shell + passwdParts := strings.SplitN(passwd, ":", 7) + if len(passwdParts) > 5 { + return passwdParts[5], nil + } } } } // If all else fails, try the shell stdout.Reset() - cmd = exec.Command("sh", "-c", "cd && pwd") + cmd := exec.Command("sh", "-c", "cd && pwd") cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return "", err @@ -123,14 +141,16 @@ func dirWindows() (string, error) { return home, nil } + // Prefer standard environment variable USERPROFILE + if home := os.Getenv("USERPROFILE"); home != "" { + return home, nil + } + drive := os.Getenv("HOMEDRIVE") path := os.Getenv("HOMEPATH") home := drive + path if drive == "" || path == "" { - home = os.Getenv("USERPROFILE") - } - if home == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") + return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") } return home, nil diff --git a/vendor/github.com/mitchellh/go-testing-interface/.travis.yml b/vendor/github.com/mitchellh/go-testing-interface/.travis.yml new file mode 100644 index 000000000..928d000ec --- /dev/null +++ b/vendor/github.com/mitchellh/go-testing-interface/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - 1.8 + - 1.x + - tip + +script: + - go test + +matrix: + allow_failures: + - go: tip diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml new file mode 100644 index 000000000..1689c7d73 --- /dev/null +++ b/vendor/github.com/mitchellh/mapstructure/.travis.yml @@ -0,0 +1,8 @@ +language: go + +go: + - "1.11.x" + - tip + +script: + - go test diff --git a/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md new file mode 100644 index 000000000..3b3cb723f --- /dev/null +++ b/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md @@ -0,0 +1,21 @@ +## 1.1.2 + +* Fix error when decode hook decodes interface implementation into interface + type. [GH-140] + +## 1.1.1 + +* Fix panic that can happen in `decodePtr` + +## 1.1.0 + +* Added `StringToIPHookFunc` to convert `string` to `net.IP` and `net.IPNet` [GH-133] +* Support struct to struct decoding [GH-137] +* If source map value is nil, then destination map value is nil (instead of empty) +* If source slice value is nil, then destination slice value is nil (instead of empty) +* If source pointer is nil, then destination pointer is set to nil (instead of + allocated zero value of type) + +## 1.0.0 + +* Initial tagged stable release. diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md index 659d6885f..0018dc7d9 100644 --- a/vendor/github.com/mitchellh/mapstructure/README.md +++ b/vendor/github.com/mitchellh/mapstructure/README.md @@ -1,4 +1,4 @@ -# mapstructure +# mapstructure [![Godoc](https://godoc.org/github.com/mitchellh/mapstructure?status.svg)](https://godoc.org/github.com/mitchellh/mapstructure) mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index 115ae67c1..1f0abc65a 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -2,6 +2,8 @@ package mapstructure import ( "errors" + "fmt" + "net" "reflect" "strconv" "strings" @@ -38,12 +40,6 @@ func DecodeHookExec( raw DecodeHookFunc, from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) { - // Build our arguments that reflect expects - argVals := make([]reflect.Value, 3) - argVals[0] = reflect.ValueOf(from) - argVals[1] = reflect.ValueOf(to) - argVals[2] = reflect.ValueOf(data) - switch f := typedDecodeHook(raw).(type) { case DecodeHookFuncType: return f(from, to, data) @@ -121,6 +117,74 @@ func StringToTimeDurationHookFunc() DecodeHookFunc { } } +// StringToIPHookFunc returns a DecodeHookFunc that converts +// strings to net.IP +func StringToIPHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IP{}) { + return data, nil + } + + // Convert it by parsing + ip := net.ParseIP(data.(string)) + if ip == nil { + return net.IP{}, fmt.Errorf("failed parsing ip %v", data) + } + + return ip, nil + } +} + +// StringToIPNetHookFunc returns a DecodeHookFunc that converts +// strings to net.IPNet +func StringToIPNetHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IPNet{}) { + return data, nil + } + + // Convert it by parsing + _, net, err := net.ParseCIDR(data.(string)) + return net, err + } +} + +// StringToTimeHookFunc returns a DecodeHookFunc that converts +// strings to time.Time. +func StringToTimeHookFunc(layout string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Time{}) { + return data, nil + } + + // Convert it by parsing + return time.Parse(layout, data.(string)) + } +} + +// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to +// the decoder. +// +// Note that this is significantly different from the WeaklyTypedInput option +// of the DecoderConfig. func WeaklyTypedHook( f reflect.Kind, t reflect.Kind, @@ -132,9 +196,8 @@ func WeaklyTypedHook( case reflect.Bool: if dataVal.Bool() { return "1", nil - } else { - return "0", nil } + return "0", nil case reflect.Float32: return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil case reflect.Int: diff --git a/vendor/github.com/mitchellh/mapstructure/go.mod b/vendor/github.com/mitchellh/mapstructure/go.mod new file mode 100644 index 000000000..d2a712562 --- /dev/null +++ b/vendor/github.com/mitchellh/mapstructure/go.mod @@ -0,0 +1 @@ +module github.com/mitchellh/mapstructure diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 6dee0ef0a..256ee63fb 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -1,5 +1,5 @@ -// The mapstructure package exposes functionality to convert an -// arbitrary map[string]interface{} into a native Go structure. +// Package mapstructure exposes functionality to convert an arbitrary +// map[string]interface{} into a native Go structure. // // The Go structure can be arbitrarily complex, containing slices, // other structs, etc. and the decoder will properly decode nested @@ -32,7 +32,12 @@ import ( // both. type DecodeHookFunc interface{} +// DecodeHookFuncType is a DecodeHookFunc which has complete information about +// the source and target types. type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) + +// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the +// source and target types. type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) // DecoderConfig is the configuration that is used to create a new decoder @@ -109,12 +114,12 @@ type Metadata struct { Unused []string } -// Decode takes a map and uses reflection to convert it into the -// given Go native structure. val must be a pointer to a struct. -func Decode(m interface{}, rawVal interface{}) error { +// Decode takes an input structure and uses reflection to translate it to +// the output structure. output must be a pointer to a map or struct. +func Decode(input interface{}, output interface{}) error { config := &DecoderConfig{ Metadata: nil, - Result: rawVal, + Result: output, } decoder, err := NewDecoder(config) @@ -122,7 +127,7 @@ func Decode(m interface{}, rawVal interface{}) error { return err } - return decoder.Decode(m) + return decoder.Decode(input) } // WeakDecode is the same as Decode but is shorthand to enable @@ -142,6 +147,40 @@ func WeakDecode(input, output interface{}) error { return decoder.Decode(input) } +// DecodeMetadata is the same as Decode, but is shorthand to +// enable metadata collection. See DecoderConfig for more info. +func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecodeMetadata is the same as Decode, but is shorthand to +// enable both WeaklyTypedInput and metadata collection. See +// DecoderConfig for more info. +func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + // NewDecoder returns a new decoder for the given configuration. Once // a decoder has been returned, the same configuration must not be used // again. @@ -179,68 +218,91 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) { // Decode decodes the given raw interface to the target pointer specified // by the configuration. -func (d *Decoder) Decode(raw interface{}) error { - return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem()) +func (d *Decoder) Decode(input interface{}) error { + return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) } // Decodes an unknown data type into a specific reflection value. -func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { - if data == nil { - // If the data is nil, then we don't set anything. +func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { + var inputVal reflect.Value + if input != nil { + inputVal = reflect.ValueOf(input) + + // We need to check here if input is a typed nil. Typed nils won't + // match the "input == nil" below so we check that here. + if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { + input = nil + } + } + + if input == nil { + // If the data is nil, then we don't set anything, unless ZeroFields is set + // to true. + if d.config.ZeroFields { + outVal.Set(reflect.Zero(outVal.Type())) + + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + } return nil } - dataVal := reflect.ValueOf(data) - if !dataVal.IsValid() { - // If the data value is invalid, then we just set the value + if !inputVal.IsValid() { + // If the input value is invalid, then we just set the value // to be the zero value. - val.Set(reflect.Zero(val.Type())) + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } return nil } if d.config.DecodeHook != nil { - // We have a DecodeHook, so let's pre-process the data. + // We have a DecodeHook, so let's pre-process the input. var err error - data, err = DecodeHookExec( + input, err = DecodeHookExec( d.config.DecodeHook, - dataVal.Type(), val.Type(), data) + inputVal.Type(), outVal.Type(), input) if err != nil { return fmt.Errorf("error decoding '%s': %s", name, err) } } var err error - dataKind := getKind(val) - switch dataKind { + outputKind := getKind(outVal) + switch outputKind { case reflect.Bool: - err = d.decodeBool(name, data, val) + err = d.decodeBool(name, input, outVal) case reflect.Interface: - err = d.decodeBasic(name, data, val) + err = d.decodeBasic(name, input, outVal) case reflect.String: - err = d.decodeString(name, data, val) + err = d.decodeString(name, input, outVal) case reflect.Int: - err = d.decodeInt(name, data, val) + err = d.decodeInt(name, input, outVal) case reflect.Uint: - err = d.decodeUint(name, data, val) + err = d.decodeUint(name, input, outVal) case reflect.Float32: - err = d.decodeFloat(name, data, val) + err = d.decodeFloat(name, input, outVal) case reflect.Struct: - err = d.decodeStruct(name, data, val) + err = d.decodeStruct(name, input, outVal) case reflect.Map: - err = d.decodeMap(name, data, val) + err = d.decodeMap(name, input, outVal) case reflect.Ptr: - err = d.decodePtr(name, data, val) + err = d.decodePtr(name, input, outVal) case reflect.Slice: - err = d.decodeSlice(name, data, val) + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) case reflect.Func: - err = d.decodeFunc(name, data, val) + err = d.decodeFunc(name, input, outVal) default: // If we reached this point then we weren't able to decode it - return fmt.Errorf("%s: unsupported type: %s", name, dataKind) + return fmt.Errorf("%s: unsupported type: %s", name, outputKind) } // If we reached here, then we successfully decoded SOMETHING, so - // mark the key as used if we're tracking metadata. + // mark the key as used if we're tracking metainput. if d.config.Metadata != nil && name != "" { d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } @@ -251,7 +313,19 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error // This decodes a basic type (bool, int, string, etc.) and sets the // value to "data" of that type. func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { + if val.IsValid() && val.Elem().IsValid() { + return d.decode(name, data, val.Elem()) + } + dataVal := reflect.ValueOf(data) + + // If the input data is a pointer, and the assigned type is the dereference + // of that exact pointer, then indirect it so that we can assign it. + // Example: *string to string + if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { + dataVal = reflect.Indirect(dataVal) + } + if !dataVal.IsValid() { dataVal = reflect.Zero(val.Type()) } @@ -268,7 +342,7 @@ func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) } func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) + dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) converted := true @@ -287,12 +361,22 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) - case dataKind == reflect.Slice && d.config.WeaklyTypedInput: + case dataKind == reflect.Slice && d.config.WeaklyTypedInput, + dataKind == reflect.Array && d.config.WeaklyTypedInput: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() - switch { - case elemKind == reflect.Uint8: - val.SetString(string(dataVal.Interface().([]uint8))) + switch elemKind { + case reflect.Uint8: + var uints []uint8 + if dataKind == reflect.Array { + uints = make([]uint8, dataVal.Len(), dataVal.Len()) + for i := range uints { + uints[i] = dataVal.Index(i).Interface().(uint8) + } + } else { + uints = dataVal.Interface().([]uint8) + } + val.SetString(string(uints)) default: converted = false } @@ -310,7 +394,7 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) } func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) + dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) dataType := dataVal.Type() @@ -352,7 +436,7 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) er } func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) + dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) switch { @@ -395,7 +479,7 @@ func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) e } func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) + dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) switch { @@ -426,7 +510,7 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) e } func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) + dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) dataType := dataVal.Type() @@ -436,7 +520,7 @@ func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) case dataKind == reflect.Uint: val.SetFloat(float64(dataVal.Uint())) case dataKind == reflect.Float32: - val.SetFloat(float64(dataVal.Float())) + val.SetFloat(dataVal.Float()) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetFloat(1) @@ -482,38 +566,68 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er valMap = reflect.MakeMap(mapType) } - // Check input type + // Check input type and based on the input type jump to the proper func dataVal := reflect.Indirect(reflect.ValueOf(data)) - if dataVal.Kind() != reflect.Map { - // In weak mode, we accept a slice of maps as an input... - if d.config.WeaklyTypedInput { - switch dataVal.Kind() { - case reflect.Array, reflect.Slice: - // Special case for BC reasons (covered by tests) - if dataVal.Len() == 0 { - val.Set(valMap) - return nil - } + switch dataVal.Kind() { + case reflect.Map: + return d.decodeMapFromMap(name, dataVal, val, valMap) - for i := 0; i < dataVal.Len(); i++ { - err := d.decode( - fmt.Sprintf("%s[%d]", name, i), - dataVal.Index(i).Interface(), val) - if err != nil { - return err - } - } + case reflect.Struct: + return d.decodeMapFromStruct(name, dataVal, val, valMap) - return nil - } + case reflect.Array, reflect.Slice: + if d.config.WeaklyTypedInput { + return d.decodeMapFromSlice(name, dataVal, val, valMap) } + fallthrough + + default: return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } +} + +func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } + + for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + fmt.Sprintf("%s[%d]", name, i), + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() // Accumulate errors errors := make([]string, 0) + // If the input data is empty, then we just match what the input data is. + if dataVal.Len() == 0 { + if dataVal.IsNil() { + if !val.IsNil() { + val.Set(dataVal) + } + } else { + // Set to empty allocated value + val.Set(valMap) + } + + return nil + } + for _, k := range dataVal.MapKeys() { fieldName := fmt.Sprintf("%s[%s]", name, k) @@ -546,22 +660,128 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er return nil } +func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + typ := dataVal.Type() + for i := 0; i < typ.NumField(); i++ { + // Get the StructField first since this is a cheap operation. If the + // field is unexported, then ignore it. + f := typ.Field(i) + if f.PkgPath != "" { + continue + } + + // Next get the actual value of this field and verify it is assignable + // to the map value. + v := dataVal.Field(i) + if !v.Type().AssignableTo(valMap.Type().Elem()) { + return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) + } + + tagValue := f.Tag.Get(d.config.TagName) + tagParts := strings.Split(tagValue, ",") + + // Determine the name of the key in the map + keyName := f.Name + if tagParts[0] != "" { + if tagParts[0] == "-" { + continue + } + keyName = tagParts[0] + } + + // If "squash" is specified in the tag, we squash the field down. + squash := false + for _, tag := range tagParts[1:] { + if tag == "squash" { + squash = true + break + } + } + if squash && v.Kind() != reflect.Struct { + return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) + } + + switch v.Kind() { + // this is an embedded struct, so handle it differently + case reflect.Struct: + x := reflect.New(v.Type()) + x.Elem().Set(v) + + vType := valMap.Type() + vKeyType := vType.Key() + vElemType := vType.Elem() + mType := reflect.MapOf(vKeyType, vElemType) + vMap := reflect.MakeMap(mType) + + err := d.decode(keyName, x.Interface(), vMap) + if err != nil { + return err + } + + if squash { + for _, k := range vMap.MapKeys() { + valMap.SetMapIndex(k, vMap.MapIndex(k)) + } + } else { + valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) + } + + default: + valMap.SetMapIndex(reflect.ValueOf(keyName), v) + } + } + + if val.CanAddr() { + val.Set(valMap) + } + + return nil +} + func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error { + // If the input data is nil, then we want to just set the output + // pointer to be nil as well. + isNil := data == nil + if !isNil { + switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { + case reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Ptr, + reflect.Slice: + isNil = v.IsNil() + } + } + if isNil { + if !val.IsNil() && val.CanSet() { + nilValue := reflect.New(val.Type()).Elem() + val.Set(nilValue) + } + + return nil + } + // Create an element of the concrete (non pointer) type and decode // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() + if val.CanSet() { + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { + return err + } - if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { - return err + val.Set(realVal) + } else { + if err := d.decode(name, data, reflect.Indirect(val)); err != nil { + return err + } } - - val.Set(realVal) return nil } @@ -587,22 +807,101 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) valSlice := val if valSlice.IsNil() || d.config.ZeroFields { + if d.config.WeaklyTypedInput { + switch { + // Slice and array we use the normal logic + case dataValKind == reflect.Slice, dataValKind == reflect.Array: + break + + // Empty maps turn into empty slices + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } + // Create slice of maps of other sizes + return d.decodeSlice(name, []interface{}{data}, val) + + case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: + return d.decodeSlice(name, []byte(dataVal.String()), val) + + // All other types we try to convert to the slice type + // and "lift" it into it. i.e. a string becomes a string slice. + default: + // Just re-try this function with data as a slice. + return d.decodeSlice(name, []interface{}{data}, val) + } + } + + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + + } + + // If the input value is empty, then don't allocate since non-nil != nil + if dataVal.Len() == 0 { + return nil + } + + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } + + // Accumulate any errors + errors := make([]string, 0) + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + for valSlice.Len() <= i { + valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) + } + currentField := valSlice.Index(i) + + fieldName := fmt.Sprintf("%s[%d]", name, i) + if err := d.decode(fieldName, currentData, currentField); err != nil { + errors = appendErrors(errors, err) + } + } + + // Finally, set the value to the slice we built up + val.Set(valSlice) + + // If there were errors, we return those + if len(errors) > 0 { + return &Error{errors} + } + + return nil +} + +func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + arrayType := reflect.ArrayOf(valType.Len(), valElemType) + + valArray := val + + if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { // Check input type if dataValKind != reflect.Array && dataValKind != reflect.Slice { if d.config.WeaklyTypedInput { switch { - // Empty maps turn into empty slices + // Empty maps turn into empty arrays case dataValKind == reflect.Map: if dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) + val.Set(reflect.Zero(arrayType)) return nil } - // All other types we try to convert to the slice type - // and "lift" it into it. i.e. a string becomes a string slice. + // All other types we try to convert to the array type + // and "lift" it into it. i.e. a string becomes a string array. default: // Just re-try this function with data as a slice. - return d.decodeSlice(name, []interface{}{data}, val) + return d.decodeArray(name, []interface{}{data}, val) } } @@ -610,9 +909,14 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) "'%s': source data must be an array or slice, got %s", name, dataValKind) } + if dataVal.Len() > arrayType.Len() { + return fmt.Errorf( + "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) - // Make a new slice to hold our result, same size as the original data. - valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } + + // Make a new array to hold our result, same size as the original data. + valArray = reflect.New(arrayType).Elem() } // Accumulate any errors @@ -620,10 +924,7 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) for i := 0; i < dataVal.Len(); i++ { currentData := dataVal.Index(i).Interface() - for valSlice.Len() <= i { - valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) - } - currentField := valSlice.Index(i) + currentField := valArray.Index(i) fieldName := fmt.Sprintf("%s[%d]", name, i) if err := d.decode(fieldName, currentData, currentField); err != nil { @@ -631,8 +932,8 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) } } - // Finally, set the value to the slice we built up - val.Set(valSlice) + // Finally, set the value to the array we built up + val.Set(valArray) // If there were errors, we return those if len(errors) > 0 { @@ -653,10 +954,29 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) } dataValKind := dataVal.Kind() - if dataValKind != reflect.Map { - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind) + switch dataValKind { + case reflect.Map: + return d.decodeStructFromMap(name, dataVal, val) + + case reflect.Struct: + // Not the most efficient way to do this but we can optimize later if + // we want to. To convert from struct to struct we go to map first + // as an intermediary. + m := make(map[string]interface{}) + mval := reflect.Indirect(reflect.ValueOf(&m)) + if err := d.decodeMapFromStruct(name, dataVal, mval, mval); err != nil { + return err + } + + result := d.decodeStructFromMap(name, mval, val) + return result + + default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } +} +func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error { dataValType := dataVal.Type() if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { return fmt.Errorf( @@ -681,7 +1001,11 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) // Compile the list of all the fields that we're going to be decoding // from all the structs. - fields := make(map[*reflect.StructField]reflect.Value) + type field struct { + field reflect.StructField + val reflect.Value + } + fields := []field{} for len(structs) > 0 { structVal := structs[0] structs = structs[1:] @@ -707,20 +1031,22 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) errors = appendErrors(errors, fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) } else { - structs = append(structs, val.FieldByName(fieldType.Name)) + structs = append(structs, structVal.FieldByName(fieldType.Name)) } continue } // Normal struct field, store it away - fields[&fieldType] = structVal.Field(i) + fields = append(fields, field{fieldType, structVal.Field(i)}) } } - for fieldType, field := range fields { - fieldName := fieldType.Name + // for fieldType, field := range fields { + for _, f := range fields { + field, fieldValue := f.field, f.val + fieldName := field.Name - tagValue := fieldType.Tag.Get(d.config.TagName) + tagValue := field.Tag.Get(d.config.TagName) tagValue = strings.SplitN(tagValue, ",", 2)[0] if tagValue != "" { fieldName = tagValue @@ -755,14 +1081,14 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) // Delete the key we're using from the unused map so we stop tracking delete(dataValKeysUnused, rawMapKey.Interface()) - if !field.IsValid() { + if !fieldValue.IsValid() { // This should never happen panic("field is not valid") } // If we can't set the field, then it is unexported or something, // and we just continue onwards. - if !field.CanSet() { + if !fieldValue.CanSet() { continue } @@ -772,7 +1098,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) fieldName = fmt.Sprintf("%s.%s", name, fieldName) } - if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil { + if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { errors = appendErrors(errors, err) } } diff --git a/vendor/github.com/mitchellh/reflectwalk/.travis.yml b/vendor/github.com/mitchellh/reflectwalk/.travis.yml new file mode 100644 index 000000000..4f2ee4d97 --- /dev/null +++ b/vendor/github.com/mitchellh/reflectwalk/.travis.yml @@ -0,0 +1 @@ +language: go diff --git a/vendor/github.com/mitchellh/reflectwalk/go.mod b/vendor/github.com/mitchellh/reflectwalk/go.mod new file mode 100644 index 000000000..52bb7c469 --- /dev/null +++ b/vendor/github.com/mitchellh/reflectwalk/go.mod @@ -0,0 +1 @@ +module github.com/mitchellh/reflectwalk diff --git a/vendor/github.com/mitchellh/reflectwalk/location.go b/vendor/github.com/mitchellh/reflectwalk/location.go index 7c59d764c..6a7f17611 100644 --- a/vendor/github.com/mitchellh/reflectwalk/location.go +++ b/vendor/github.com/mitchellh/reflectwalk/location.go @@ -11,6 +11,8 @@ const ( MapValue Slice SliceElem + Array + ArrayElem Struct StructField WalkLoc diff --git a/vendor/github.com/mitchellh/reflectwalk/location_string.go b/vendor/github.com/mitchellh/reflectwalk/location_string.go index d3cfe8545..70760cf4c 100644 --- a/vendor/github.com/mitchellh/reflectwalk/location_string.go +++ b/vendor/github.com/mitchellh/reflectwalk/location_string.go @@ -1,15 +1,15 @@ -// generated by stringer -type=Location location.go; DO NOT EDIT +// Code generated by "stringer -type=Location location.go"; DO NOT EDIT. package reflectwalk import "fmt" -const _Location_name = "NoneMapMapKeyMapValueSliceSliceElemStructStructFieldWalkLoc" +const _Location_name = "NoneMapMapKeyMapValueSliceSliceElemArrayArrayElemStructStructFieldWalkLoc" -var _Location_index = [...]uint8{0, 4, 7, 13, 21, 26, 35, 41, 52, 59} +var _Location_index = [...]uint8{0, 4, 7, 13, 21, 26, 35, 40, 49, 55, 66, 73} func (i Location) String() string { - if i+1 >= Location(len(_Location_index)) { + if i >= Location(len(_Location_index)-1) { return fmt.Sprintf("Location(%d)", i) } return _Location_name[_Location_index[i]:_Location_index[i+1]] diff --git a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go b/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go index ec0a62337..d7ab7b6d7 100644 --- a/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go +++ b/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go @@ -39,6 +39,13 @@ type SliceWalker interface { SliceElem(int, reflect.Value) error } +// ArrayWalker implementations are able to handle array elements found +// within complex structures. +type ArrayWalker interface { + Array(reflect.Value) error + ArrayElem(int, reflect.Value) error +} + // StructWalker is an interface that has methods that are called for // structs when a Walk is done. type StructWalker interface { @@ -65,6 +72,7 @@ type PointerWalker interface { // SkipEntry can be returned from walk functions to skip walking // the value of this field. This is only valid in the following functions: // +// - Struct: skips all fields from being walked // - StructField: skips walking the struct value // var SkipEntry = errors.New("skip this entry") @@ -179,6 +187,9 @@ func walk(v reflect.Value, w interface{}) (err error) { case reflect.Struct: err = walkStruct(v, w) return + case reflect.Array: + err = walkArray(v, w) + return default: panic("unsupported type: " + k.String()) } @@ -286,48 +297,99 @@ func walkSlice(v reflect.Value, w interface{}) (err error) { return nil } +func walkArray(v reflect.Value, w interface{}) (err error) { + ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(Array) + } + + if aw, ok := w.(ArrayWalker); ok { + if err := aw.Array(v); err != nil { + return err + } + } + + for i := 0; i < v.Len(); i++ { + elem := v.Index(i) + + if aw, ok := w.(ArrayWalker); ok { + if err := aw.ArrayElem(i, elem); err != nil { + return err + } + } + + ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(ArrayElem) + } + + if err := walk(elem, w); err != nil { + return err + } + + if ok { + ew.Exit(ArrayElem) + } + } + + ew, ok = w.(EnterExitWalker) + if ok { + ew.Exit(Array) + } + + return nil +} + func walkStruct(v reflect.Value, w interface{}) (err error) { ew, ewok := w.(EnterExitWalker) if ewok { ew.Enter(Struct) } + skip := false if sw, ok := w.(StructWalker); ok { - if err = sw.Struct(v); err != nil { + err = sw.Struct(v) + if err == SkipEntry { + skip = true + err = nil + } + if err != nil { return } } - vt := v.Type() - for i := 0; i < vt.NumField(); i++ { - sf := vt.Field(i) - f := v.FieldByIndex([]int{i}) + if !skip { + vt := v.Type() + for i := 0; i < vt.NumField(); i++ { + sf := vt.Field(i) + f := v.FieldByIndex([]int{i}) - if sw, ok := w.(StructWalker); ok { - err = sw.StructField(sf, f) + if sw, ok := w.(StructWalker); ok { + err = sw.StructField(sf, f) - // SkipEntry just pretends this field doesn't even exist - if err == SkipEntry { - continue + // SkipEntry just pretends this field doesn't even exist + if err == SkipEntry { + continue + } + + if err != nil { + return + } + } + + ew, ok := w.(EnterExitWalker) + if ok { + ew.Enter(StructField) } + err = walk(f, w) if err != nil { return } - } - - ew, ok := w.(EnterExitWalker) - if ok { - ew.Enter(StructField) - } - err = walk(f, w) - if err != nil { - return - } - - if ok { - ew.Exit(StructField) + if ok { + ew.Exit(StructField) + } } } diff --git a/vendor/github.com/oklog/run/.gitignore b/vendor/github.com/oklog/run/.gitignore new file mode 100644 index 000000000..a1338d685 --- /dev/null +++ b/vendor/github.com/oklog/run/.gitignore @@ -0,0 +1,14 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ diff --git a/vendor/github.com/oklog/run/.travis.yml b/vendor/github.com/oklog/run/.travis.yml new file mode 100644 index 000000000..362bdd41c --- /dev/null +++ b/vendor/github.com/oklog/run/.travis.yml @@ -0,0 +1,12 @@ +language: go +sudo: false +go: + - 1.x + - tip +install: + - go get -v github.com/golang/lint/golint + - go build ./... +script: + - go vet ./... + - $HOME/gopath/bin/golint . + - go test -v -race ./... diff --git a/vendor/github.com/oklog/run/README.md b/vendor/github.com/oklog/run/README.md index 1b32d8263..a7228cd9a 100644 --- a/vendor/github.com/oklog/run/README.md +++ b/vendor/github.com/oklog/run/README.md @@ -10,11 +10,9 @@ run.Group is a universal mechanism to manage goroutine lifecycles. Create a zero-value run.Group, and then add actors to it. Actors are defined as a pair of functions: an **execute** function, which should run synchronously; and an **interrupt** function, which, when invoked, should cause the execute -function to return. Finally, invoke Run, which concurrently runs all of the -actors, waits until the first actor exits, invokes the interrupt functions, and -finally returns control to the caller only once all actors have returned. This -general-purpose API allows callers to model pretty much any runnable task, and -achieve well-defined lifecycle semantics for the group. +function to return. Finally, invoke Run, which blocks until the first actor +returns. This general-purpose API allows callers to model pretty much any +runnable task, and achieve well-defined lifecycle semantics for the group. run.Group was written to manage component lifecycles in func main for [OK Log](https://github.com/oklog/oklog). diff --git a/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS b/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS deleted file mode 100644 index 2b16e9974..000000000 --- a/vendor/github.com/patrickmn/go-cache/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -This is a list of people who have contributed code to go-cache. They, or their -employers, are the copyright holders of the contributed code. Contributed code -is subject to the license restrictions listed in LICENSE (as they were when the -code was contributed.) - -Dustin Sallings -Jason Mooberry -Sergey Shepelev -Alex Edwards diff --git a/vendor/github.com/patrickmn/go-cache/LICENSE b/vendor/github.com/patrickmn/go-cache/LICENSE deleted file mode 100644 index 30b9cade0..000000000 --- a/vendor/github.com/patrickmn/go-cache/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012-2018 Patrick Mylund Nielsen and the go-cache contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/patrickmn/go-cache/README.md b/vendor/github.com/patrickmn/go-cache/README.md deleted file mode 100644 index c5789cc66..000000000 --- a/vendor/github.com/patrickmn/go-cache/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# go-cache - -go-cache is an in-memory key:value store/cache similar to memcached that is -suitable for applications running on a single machine. Its major advantage is -that, being essentially a thread-safe `map[string]interface{}` with expiration -times, it doesn't need to serialize or transmit its contents over the network. - -Any object can be stored, for a given duration or forever, and the cache can be -safely used by multiple goroutines. - -Although go-cache isn't meant to be used as a persistent datastore, the entire -cache can be saved to and loaded from a file (using `c.Items()` to retrieve the -items map to serialize, and `NewFrom()` to create a cache from a deserialized -one) to recover from downtime quickly. (See the docs for `NewFrom()` for caveats.) - -### Installation - -`go get github.com/patrickmn/go-cache` - -### Usage - -```go -import ( - "fmt" - "github.com/patrickmn/go-cache" - "time" -) - -func main() { - // Create a cache with a default expiration time of 5 minutes, and which - // purges expired items every 10 minutes - c := cache.New(5*time.Minute, 10*time.Minute) - - // Set the value of the key "foo" to "bar", with the default expiration time - c.Set("foo", "bar", cache.DefaultExpiration) - - // Set the value of the key "baz" to 42, with no expiration time - // (the item won't be removed until it is re-set, or removed using - // c.Delete("baz") - c.Set("baz", 42, cache.NoExpiration) - - // Get the string associated with the key "foo" from the cache - foo, found := c.Get("foo") - if found { - fmt.Println(foo) - } - - // Since Go is statically typed, and cache values can be anything, type - // assertion is needed when values are being passed to functions that don't - // take arbitrary types, (i.e. interface{}). The simplest way to do this for - // values which will only be used once--e.g. for passing to another - // function--is: - foo, found := c.Get("foo") - if found { - MyFunction(foo.(string)) - } - - // This gets tedious if the value is used several times in the same function. - // You might do either of the following instead: - if x, found := c.Get("foo"); found { - foo := x.(string) - // ... - } - // or - var foo string - if x, found := c.Get("foo"); found { - foo = x.(string) - } - // ... - // foo can then be passed around freely as a string - - // Want performance? Store pointers! - c.Set("foo", &MyStruct, cache.DefaultExpiration) - if x, found := c.Get("foo"); found { - foo := x.(*MyStruct) - // ... - } -} -``` - -### Reference - -`godoc` or [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache) diff --git a/vendor/github.com/patrickmn/go-cache/cache.go b/vendor/github.com/patrickmn/go-cache/cache.go deleted file mode 100644 index db88d2f2c..000000000 --- a/vendor/github.com/patrickmn/go-cache/cache.go +++ /dev/null @@ -1,1161 +0,0 @@ -package cache - -import ( - "encoding/gob" - "fmt" - "io" - "os" - "runtime" - "sync" - "time" -) - -type Item struct { - Object interface{} - Expiration int64 -} - -// Returns true if the item has expired. -func (item Item) Expired() bool { - if item.Expiration == 0 { - return false - } - return time.Now().UnixNano() > item.Expiration -} - -const ( - // For use with functions that take an expiration time. - NoExpiration time.Duration = -1 - // For use with functions that take an expiration time. Equivalent to - // passing in the same expiration duration as was given to New() or - // NewFrom() when the cache was created (e.g. 5 minutes.) - DefaultExpiration time.Duration = 0 -) - -type Cache struct { - *cache - // If this is confusing, see the comment at the bottom of New() -} - -type cache struct { - defaultExpiration time.Duration - items map[string]Item - mu sync.RWMutex - onEvicted func(string, interface{}) - janitor *janitor -} - -// Add an item to the cache, replacing any existing item. If the duration is 0 -// (DefaultExpiration), the cache's default expiration time is used. If it is -1 -// (NoExpiration), the item never expires. -func (c *cache) Set(k string, x interface{}, d time.Duration) { - // "Inlining" of set - var e int64 - if d == DefaultExpiration { - d = c.defaultExpiration - } - if d > 0 { - e = time.Now().Add(d).UnixNano() - } - c.mu.Lock() - c.items[k] = Item{ - Object: x, - Expiration: e, - } - // TODO: Calls to mu.Unlock are currently not deferred because defer - // adds ~200 ns (as of go1.) - c.mu.Unlock() -} - -func (c *cache) set(k string, x interface{}, d time.Duration) { - var e int64 - if d == DefaultExpiration { - d = c.defaultExpiration - } - if d > 0 { - e = time.Now().Add(d).UnixNano() - } - c.items[k] = Item{ - Object: x, - Expiration: e, - } -} - -// Add an item to the cache, replacing any existing item, using the default -// expiration. -func (c *cache) SetDefault(k string, x interface{}) { - c.Set(k, x, DefaultExpiration) -} - -// Add an item to the cache only if an item doesn't already exist for the given -// key, or if the existing item has expired. Returns an error otherwise. -func (c *cache) Add(k string, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if found { - c.mu.Unlock() - return fmt.Errorf("Item %s already exists", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - -// Set a new value for the cache key only if it already exists, and the existing -// item hasn't expired. Returns an error otherwise. -func (c *cache) Replace(k string, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if !found { - c.mu.Unlock() - return fmt.Errorf("Item %s doesn't exist", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - -// Get an item from the cache. Returns the item or nil, and a bool indicating -// whether the key was found. -func (c *cache) Get(k string) (interface{}, bool) { - c.mu.RLock() - // "Inlining" of get and Expired - item, found := c.items[k] - if !found { - c.mu.RUnlock() - return nil, false - } - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - c.mu.RUnlock() - return nil, false - } - } - c.mu.RUnlock() - return item.Object, true -} - -// GetWithExpiration returns an item and its expiration time from the cache. -// It returns the item or nil, the expiration time if one is set (if the item -// never expires a zero value for time.Time is returned), and a bool indicating -// whether the key was found. -func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) { - c.mu.RLock() - // "Inlining" of get and Expired - item, found := c.items[k] - if !found { - c.mu.RUnlock() - return nil, time.Time{}, false - } - - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - c.mu.RUnlock() - return nil, time.Time{}, false - } - - // Return the item and the expiration time - c.mu.RUnlock() - return item.Object, time.Unix(0, item.Expiration), true - } - - // If expiration <= 0 (i.e. no expiration time set) then return the item - // and a zeroed time.Time - c.mu.RUnlock() - return item.Object, time.Time{}, true -} - -func (c *cache) get(k string) (interface{}, bool) { - item, found := c.items[k] - if !found { - return nil, false - } - // "Inlining" of Expired - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - return nil, false - } - } - return item.Object, true -} - -// Increment an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to increment it by n. To retrieve the incremented value, use one -// of the specialized methods, e.g. IncrementInt64. -func (c *cache) Increment(k string, n int64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) + int(n) - case int8: - v.Object = v.Object.(int8) + int8(n) - case int16: - v.Object = v.Object.(int16) + int16(n) - case int32: - v.Object = v.Object.(int32) + int32(n) - case int64: - v.Object = v.Object.(int64) + n - case uint: - v.Object = v.Object.(uint) + uint(n) - case uintptr: - v.Object = v.Object.(uintptr) + uintptr(n) - case uint8: - v.Object = v.Object.(uint8) + uint8(n) - case uint16: - v.Object = v.Object.(uint16) + uint16(n) - case uint32: - v.Object = v.Object.(uint32) + uint32(n) - case uint64: - v.Object = v.Object.(uint64) + uint64(n) - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to increment it by n. Pass a negative number to decrement the -// value. To retrieve the incremented value, use one of the specialized methods, -// e.g. IncrementFloat64. -func (c *cache) IncrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint8 by n. Returns an error if the item's value -// is not an uint8, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to decrement it by n. To retrieve the decremented value, use one -// of the specialized methods, e.g. DecrementInt64. -func (c *cache) Decrement(k string, n int64) error { - // TODO: Implement Increment and Decrement more cleanly. - // (Cannot do Increment(k, n*-1) for uints.) - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item not found") - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) - int(n) - case int8: - v.Object = v.Object.(int8) - int8(n) - case int16: - v.Object = v.Object.(int16) - int16(n) - case int32: - v.Object = v.Object.(int32) - int32(n) - case int64: - v.Object = v.Object.(int64) - n - case uint: - v.Object = v.Object.(uint) - uint(n) - case uintptr: - v.Object = v.Object.(uintptr) - uintptr(n) - case uint8: - v.Object = v.Object.(uint8) - uint8(n) - case uint16: - v.Object = v.Object.(uint16) - uint16(n) - case uint32: - v.Object = v.Object.(uint32) - uint32(n) - case uint64: - v.Object = v.Object.(uint64) - uint64(n) - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to decrement it by n. Pass a negative number to decrement the -// value. To retrieve the decremented value, use one of the specialized methods, -// e.g. DecrementFloat64. -func (c *cache) DecrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint8 by n. Returns an error if the item's value is -// not an uint8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Delete an item from the cache. Does nothing if the key is not in the cache. -func (c *cache) Delete(k string) { - c.mu.Lock() - v, evicted := c.delete(k) - c.mu.Unlock() - if evicted { - c.onEvicted(k, v) - } -} - -func (c *cache) delete(k string) (interface{}, bool) { - if c.onEvicted != nil { - if v, found := c.items[k]; found { - delete(c.items, k) - return v.Object, true - } - } - delete(c.items, k) - return nil, false -} - -type keyAndValue struct { - key string - value interface{} -} - -// Delete all expired items from the cache. -func (c *cache) DeleteExpired() { - var evictedItems []keyAndValue - now := time.Now().UnixNano() - c.mu.Lock() - for k, v := range c.items { - // "Inlining" of expired - if v.Expiration > 0 && now > v.Expiration { - ov, evicted := c.delete(k) - if evicted { - evictedItems = append(evictedItems, keyAndValue{k, ov}) - } - } - } - c.mu.Unlock() - for _, v := range evictedItems { - c.onEvicted(v.key, v.value) - } -} - -// Sets an (optional) function that is called with the key and value when an -// item is evicted from the cache. (Including when it is deleted manually, but -// not when it is overwritten.) Set to nil to disable. -func (c *cache) OnEvicted(f func(string, interface{})) { - c.mu.Lock() - c.onEvicted = f - c.mu.Unlock() -} - -// Write the cache's items (using Gob) to an io.Writer. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) Save(w io.Writer) (err error) { - enc := gob.NewEncoder(w) - defer func() { - if x := recover(); x != nil { - err = fmt.Errorf("Error registering item types with Gob library") - } - }() - c.mu.RLock() - defer c.mu.RUnlock() - for _, v := range c.items { - gob.Register(v.Object) - } - err = enc.Encode(&c.items) - return -} - -// Save the cache's items to the given filename, creating the file if it -// doesn't exist, and overwriting it if it does. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) SaveFile(fname string) error { - fp, err := os.Create(fname) - if err != nil { - return err - } - err = c.Save(fp) - if err != nil { - fp.Close() - return err - } - return fp.Close() -} - -// Add (Gob-serialized) cache items from an io.Reader, excluding any items with -// keys that already exist (and haven't expired) in the current cache. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) Load(r io.Reader) error { - dec := gob.NewDecoder(r) - items := map[string]Item{} - err := dec.Decode(&items) - if err == nil { - c.mu.Lock() - defer c.mu.Unlock() - for k, v := range items { - ov, found := c.items[k] - if !found || ov.Expired() { - c.items[k] = v - } - } - } - return err -} - -// Load and add cache items from the given filename, excluding any items with -// keys that already exist in the current cache. -// -// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the -// documentation for NewFrom().) -func (c *cache) LoadFile(fname string) error { - fp, err := os.Open(fname) - if err != nil { - return err - } - err = c.Load(fp) - if err != nil { - fp.Close() - return err - } - return fp.Close() -} - -// Copies all unexpired items in the cache into a new map and returns it. -func (c *cache) Items() map[string]Item { - c.mu.RLock() - defer c.mu.RUnlock() - m := make(map[string]Item, len(c.items)) - now := time.Now().UnixNano() - for k, v := range c.items { - // "Inlining" of Expired - if v.Expiration > 0 { - if now > v.Expiration { - continue - } - } - m[k] = v - } - return m -} - -// Returns the number of items in the cache. This may include items that have -// expired, but have not yet been cleaned up. -func (c *cache) ItemCount() int { - c.mu.RLock() - n := len(c.items) - c.mu.RUnlock() - return n -} - -// Delete all items from the cache. -func (c *cache) Flush() { - c.mu.Lock() - c.items = map[string]Item{} - c.mu.Unlock() -} - -type janitor struct { - Interval time.Duration - stop chan bool -} - -func (j *janitor) Run(c *cache) { - ticker := time.NewTicker(j.Interval) - for { - select { - case <-ticker.C: - c.DeleteExpired() - case <-j.stop: - ticker.Stop() - return - } - } -} - -func stopJanitor(c *Cache) { - c.janitor.stop <- true -} - -func runJanitor(c *cache, ci time.Duration) { - j := &janitor{ - Interval: ci, - stop: make(chan bool), - } - c.janitor = j - go j.Run(c) -} - -func newCache(de time.Duration, m map[string]Item) *cache { - if de == 0 { - de = -1 - } - c := &cache{ - defaultExpiration: de, - items: m, - } - return c -} - -func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) *Cache { - c := newCache(de, m) - // This trick ensures that the janitor goroutine (which--granted it - // was enabled--is running DeleteExpired on c forever) does not keep - // the returned C object from being garbage collected. When it is - // garbage collected, the finalizer stops the janitor goroutine, after - // which c can be collected. - C := &Cache{c} - if ci > 0 { - runJanitor(c, ci) - runtime.SetFinalizer(C, stopJanitor) - } - return C -} - -// Return a new cache with a given default expiration duration and cleanup -// interval. If the expiration duration is less than one (or NoExpiration), -// the items in the cache never expire (by default), and must be deleted -// manually. If the cleanup interval is less than one, expired items are not -// deleted from the cache before calling c.DeleteExpired(). -func New(defaultExpiration, cleanupInterval time.Duration) *Cache { - items := make(map[string]Item) - return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) -} - -// Return a new cache with a given default expiration duration and cleanup -// interval. If the expiration duration is less than one (or NoExpiration), -// the items in the cache never expire (by default), and must be deleted -// manually. If the cleanup interval is less than one, expired items are not -// deleted from the cache before calling c.DeleteExpired(). -// -// NewFrom() also accepts an items map which will serve as the underlying map -// for the cache. This is useful for starting from a deserialized cache -// (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. -// make(map[string]Item, 500) to improve startup performance when the cache -// is expected to reach a certain minimum size. -// -// Only the cache's methods synchronize access to this map, so it is not -// recommended to keep any references to the map around after creating a cache. -// If need be, the map can be accessed at a later point using c.Items() (subject -// to the same caveat.) -// -// Note regarding serialization: When using e.g. gob, make sure to -// gob.Register() the individual types stored in the cache before encoding a -// map retrieved with c.Items(), and to register those same types before -// decoding a blob containing an items map. -func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache { - return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) -} diff --git a/vendor/github.com/patrickmn/go-cache/sharded.go b/vendor/github.com/patrickmn/go-cache/sharded.go deleted file mode 100644 index bcc0538bc..000000000 --- a/vendor/github.com/patrickmn/go-cache/sharded.go +++ /dev/null @@ -1,192 +0,0 @@ -package cache - -import ( - "crypto/rand" - "math" - "math/big" - insecurerand "math/rand" - "os" - "runtime" - "time" -) - -// This is an experimental and unexported (for now) attempt at making a cache -// with better algorithmic complexity than the standard one, namely by -// preventing write locks of the entire cache when an item is added. As of the -// time of writing, the overhead of selecting buckets results in cache -// operations being about twice as slow as for the standard cache with small -// total cache sizes, and faster for larger ones. -// -// See cache_test.go for a few benchmarks. - -type unexportedShardedCache struct { - *shardedCache -} - -type shardedCache struct { - seed uint32 - m uint32 - cs []*cache - janitor *shardedJanitor -} - -// djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead. -func djb33(seed uint32, k string) uint32 { - var ( - l = uint32(len(k)) - d = 5381 + seed + l - i = uint32(0) - ) - // Why is all this 5x faster than a for loop? - if l >= 4 { - for i < l-4 { - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - d = (d * 33) ^ uint32(k[i+2]) - d = (d * 33) ^ uint32(k[i+3]) - i += 4 - } - } - switch l - i { - case 1: - case 2: - d = (d * 33) ^ uint32(k[i]) - case 3: - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - case 4: - d = (d * 33) ^ uint32(k[i]) - d = (d * 33) ^ uint32(k[i+1]) - d = (d * 33) ^ uint32(k[i+2]) - } - return d ^ (d >> 16) -} - -func (sc *shardedCache) bucket(k string) *cache { - return sc.cs[djb33(sc.seed, k)%sc.m] -} - -func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) { - sc.bucket(k).Set(k, x, d) -} - -func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error { - return sc.bucket(k).Add(k, x, d) -} - -func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error { - return sc.bucket(k).Replace(k, x, d) -} - -func (sc *shardedCache) Get(k string) (interface{}, bool) { - return sc.bucket(k).Get(k) -} - -func (sc *shardedCache) Increment(k string, n int64) error { - return sc.bucket(k).Increment(k, n) -} - -func (sc *shardedCache) IncrementFloat(k string, n float64) error { - return sc.bucket(k).IncrementFloat(k, n) -} - -func (sc *shardedCache) Decrement(k string, n int64) error { - return sc.bucket(k).Decrement(k, n) -} - -func (sc *shardedCache) Delete(k string) { - sc.bucket(k).Delete(k) -} - -func (sc *shardedCache) DeleteExpired() { - for _, v := range sc.cs { - v.DeleteExpired() - } -} - -// Returns the items in the cache. This may include items that have expired, -// but have not yet been cleaned up. If this is significant, the Expiration -// fields of the items should be checked. Note that explicit synchronization -// is needed to use a cache and its corresponding Items() return values at -// the same time, as the maps are shared. -func (sc *shardedCache) Items() []map[string]Item { - res := make([]map[string]Item, len(sc.cs)) - for i, v := range sc.cs { - res[i] = v.Items() - } - return res -} - -func (sc *shardedCache) Flush() { - for _, v := range sc.cs { - v.Flush() - } -} - -type shardedJanitor struct { - Interval time.Duration - stop chan bool -} - -func (j *shardedJanitor) Run(sc *shardedCache) { - j.stop = make(chan bool) - tick := time.Tick(j.Interval) - for { - select { - case <-tick: - sc.DeleteExpired() - case <-j.stop: - return - } - } -} - -func stopShardedJanitor(sc *unexportedShardedCache) { - sc.janitor.stop <- true -} - -func runShardedJanitor(sc *shardedCache, ci time.Duration) { - j := &shardedJanitor{ - Interval: ci, - } - sc.janitor = j - go j.Run(sc) -} - -func newShardedCache(n int, de time.Duration) *shardedCache { - max := big.NewInt(0).SetUint64(uint64(math.MaxUint32)) - rnd, err := rand.Int(rand.Reader, max) - var seed uint32 - if err != nil { - os.Stderr.Write([]byte("WARNING: go-cache's newShardedCache failed to read from the system CSPRNG (/dev/urandom or equivalent.) Your system's security may be compromised. Continuing with an insecure seed.\n")) - seed = insecurerand.Uint32() - } else { - seed = uint32(rnd.Uint64()) - } - sc := &shardedCache{ - seed: seed, - m: uint32(n), - cs: make([]*cache, n), - } - for i := 0; i < n; i++ { - c := &cache{ - defaultExpiration: de, - items: map[string]Item{}, - } - sc.cs[i] = c - } - return sc -} - -func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache { - if defaultExpiration == 0 { - defaultExpiration = -1 - } - sc := newShardedCache(shards, defaultExpiration) - SC := &unexportedShardedCache{sc} - if cleanupInterval > 0 { - runShardedJanitor(sc, cleanupInterval) - runtime.SetFinalizer(SC, stopShardedJanitor) - } - return SC -} diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e75..000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 6483ba2af..000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0..000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index dae1a0cb7..000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 2874a048c..000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,147 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/vendor/github.com/posener/complete/.gitignore b/vendor/github.com/posener/complete/.gitignore new file mode 100644 index 000000000..136372081 --- /dev/null +++ b/vendor/github.com/posener/complete/.gitignore @@ -0,0 +1,2 @@ +.idea +coverage.txt diff --git a/vendor/github.com/posener/complete/.travis.yml b/vendor/github.com/posener/complete/.travis.yml new file mode 100644 index 000000000..c2798f8f3 --- /dev/null +++ b/vendor/github.com/posener/complete/.travis.yml @@ -0,0 +1,17 @@ +language: go +sudo: false +go: + - 1.9 + - 1.8 + +before_install: + - go get -u -t ./... + - go get -u gopkg.in/alecthomas/gometalinter.v1 + - gometalinter.v1 --install + +script: + - gometalinter.v1 --config metalinter.json ./... + - ./test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/posener/complete/cmd/install/fish.go b/vendor/github.com/posener/complete/cmd/install/fish.go new file mode 100644 index 000000000..f04e7c3ac --- /dev/null +++ b/vendor/github.com/posener/complete/cmd/install/fish.go @@ -0,0 +1,50 @@ +package install + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "text/template" +) + +// (un)install in fish + +type fish struct { + configDir string +} + +func (f fish) Install(cmd, bin string) error { + completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd)) + completeCmd := f.cmd(cmd, bin) + if _, err := os.Stat(completionFile); err == nil { + return fmt.Errorf("already installed at %s", completionFile) + } + + return createFile(completionFile, completeCmd) +} + +func (f fish) Uninstall(cmd, bin string) error { + completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd)) + if _, err := os.Stat(completionFile); err != nil { + return fmt.Errorf("does not installed in %s", f.configDir) + } + + return os.Remove(completionFile) +} + +func (f fish) cmd(cmd, bin string) string { + var buf bytes.Buffer + params := struct{ Cmd, Bin string }{cmd, bin} + template.Must(template.New("cmd").Parse(` +function __complete_{{.Cmd}} + set -lx COMP_LINE (string join ' ' (commandline -o)) + test (commandline -ct) = "" + and set COMP_LINE "$COMP_LINE " + {{.Bin}} +end +complete -c {{.Cmd}} -a "(__complete_{{.Cmd}})" +`)).Execute(&buf, params) + + return string(buf.Bytes()) +} diff --git a/vendor/github.com/posener/complete/cmd/install/install.go b/vendor/github.com/posener/complete/cmd/install/install.go index 644b40576..4a706242f 100644 --- a/vendor/github.com/posener/complete/cmd/install/install.go +++ b/vendor/github.com/posener/complete/cmd/install/install.go @@ -59,7 +59,7 @@ func Uninstall(cmd string) error { } func installers() (i []installer) { - for _, rc := range [...]string{".bashrc", ".bash_profile"} { + for _, rc := range [...]string{".bashrc", ".bash_profile", ".bash_login", ".profile"} { if f := rcFile(rc); f != "" { i = append(i, bash{f}) break @@ -68,9 +68,36 @@ func installers() (i []installer) { if f := rcFile(".zshrc"); f != "" { i = append(i, zsh{f}) } + if d := fishConfigDir(); d != "" { + i = append(i, fish{d}) + } return } +func fishConfigDir() string { + configDir := filepath.Join(getConfigHomePath(), "fish") + if configDir == "" { + return "" + } + if info, err := os.Stat(configDir); err != nil || !info.IsDir() { + return "" + } + return configDir +} + +func getConfigHomePath() string { + u, err := user.Current() + if err != nil { + return "" + } + + configHome := os.Getenv("XDG_CONFIG_HOME") + if configHome == "" { + return filepath.Join(u.HomeDir, ".config") + } + return configHome +} + func getBinaryPath() (string, error) { bin, err := os.Executable() if err != nil { diff --git a/vendor/github.com/posener/complete/cmd/install/utils.go b/vendor/github.com/posener/complete/cmd/install/utils.go index 2c8b44cab..bb709bc6c 100644 --- a/vendor/github.com/posener/complete/cmd/install/utils.go +++ b/vendor/github.com/posener/complete/cmd/install/utils.go @@ -6,6 +6,7 @@ import ( "io" "io/ioutil" "os" + "path/filepath" ) func lineInFile(name string, lookFor string) bool { @@ -36,6 +37,24 @@ func lineInFile(name string, lookFor string) bool { } } +func createFile(name string, content string) error { + // make sure file directory exists + if err := os.MkdirAll(filepath.Dir(name), 0775); err != nil { + return err + } + + // create the file + f, err := os.Create(name) + if err != nil { + return err + } + defer f.Close() + + // write file content + _, err = f.WriteString(fmt.Sprintf("%s\n", content)) + return err +} + func appendToFile(name string, content string) error { f, err := os.OpenFile(name, os.O_RDWR|os.O_APPEND, 0) if err != nil { diff --git a/vendor/github.com/posener/complete/readme.md b/vendor/github.com/posener/complete/readme.md index 74077e357..2a999ba76 100644 --- a/vendor/github.com/posener/complete/readme.md +++ b/vendor/github.com/posener/complete/readme.md @@ -1,12 +1,12 @@ # complete +A tool for bash writing bash completion in go, and bash completion for the go command line. + [![Build Status](https://travis-ci.org/posener/complete.svg?branch=master)](https://travis-ci.org/posener/complete) [![codecov](https://codecov.io/gh/posener/complete/branch/master/graph/badge.svg)](https://codecov.io/gh/posener/complete) [![GoDoc](https://godoc.org/github.com/posener/complete?status.svg)](http://godoc.org/github.com/posener/complete) [![Go Report Card](https://goreportcard.com/badge/github.com/posener/complete)](https://goreportcard.com/report/github.com/posener/complete) -A tool for bash writing bash completion in go. - Writing bash completion scripts is a hard work. This package provides an easy way to create bash completion scripts for any command, and also an easy way to install/uninstall the completion of the command. @@ -42,6 +42,7 @@ Supported shells: - [x] bash - [x] zsh +- [x] fish ### Usage diff --git a/vendor/github.com/posener/complete/test.sh b/vendor/github.com/posener/complete/test.sh old mode 100755 new mode 100644 diff --git a/vendor/github.com/rainycape/unidecode/.gitignore b/vendor/github.com/rainycape/unidecode/.gitignore new file mode 100644 index 000000000..836562412 --- /dev/null +++ b/vendor/github.com/rainycape/unidecode/.gitignore @@ -0,0 +1,23 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test diff --git a/vendor/github.com/rancher/go-rancher/Dockerfile.dapper b/vendor/github.com/rancher/go-rancher/Dockerfile.dapper deleted file mode 100644 index d5bfad7a7..000000000 --- a/vendor/github.com/rancher/go-rancher/Dockerfile.dapper +++ /dev/null @@ -1,30 +0,0 @@ -FROM ubuntu:16.04 -# FROM arm=armhf/ubuntu:16.04 - -ARG DAPPER_HOST_ARCH=amd64 -ENV HOST_ARCH=${DAPPER_HOST_ARCH} ARCH=${DAPPER_HOST_ARCH} - -RUN apt-get update && \ - apt-get install -y gcc ca-certificates git wget curl vim less file && \ - rm -f /bin/sh && ln -s /bin/bash /bin/sh - -ENV GOLANG_ARCH_amd64=amd64 GOLANG_ARCH_arm=armv6l GOLANG_ARCH=GOLANG_ARCH_${ARCH} \ - GOPATH=/go PATH=/go/bin:/usr/local/go/bin:${PATH} SHELL=/bin/bash - -ENV DOCKER_URL_amd64=https://get.docker.com/builds/Linux/x86_64/docker-1.10.3 \ - DOCKER_URL_arm=https://github.com/rancher/docker/releases/download/v1.10.3-ros1/docker-1.10.3_arm \ - DOCKER_URL=DOCKER_URL_${ARCH} -RUN wget -O - ${!DOCKER_URL} > /usr/bin/docker && chmod +x /usr/bin/docker - -RUN wget -O - https://storage.googleapis.com/golang/go1.7.1.linux-${!GOLANG_ARCH}.tar.gz | tar -xzf - -C /usr/local && \ - go get github.com/rancher/trash && go get github.com/golang/lint/golint - -ENV DAPPER_SOURCE /go/src/github.com/rancher/go-rancher/ -ENV DAPPER_OUTPUT ./bin -ENV DAPPER_DOCKER_SOCKET true -ENV TRASH_CACHE ${DAPPER_SOURCE}/.trash-cache -ENV HOME ${DAPPER_SOURCE} -WORKDIR ${DAPPER_SOURCE} - -ENTRYPOINT ["./scripts/entry"] -CMD ["ci"] diff --git a/vendor/github.com/rancher/go-rancher/LICENSE b/vendor/github.com/rancher/go-rancher/LICENSE deleted file mode 100644 index f433b1a53..000000000 --- a/vendor/github.com/rancher/go-rancher/LICENSE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/vendor/github.com/rancher/go-rancher/Makefile b/vendor/github.com/rancher/go-rancher/Makefile deleted file mode 100644 index d7d72a16d..000000000 --- a/vendor/github.com/rancher/go-rancher/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -TARGETS := $(shell ls scripts) - -.dapper: - @echo Downloading dapper - @curl -sL https://releases.rancher.com/dapper/latest/dapper-`uname -s`-`uname -m` > .dapper.tmp - @@chmod +x .dapper.tmp - @./.dapper.tmp -v - @mv .dapper.tmp .dapper - -$(TARGETS): .dapper - ./.dapper $@ - -trash: .dapper - ./.dapper -m bind trash - -trash-keep: .dapper - ./.dapper -m bind trash -k - -deps: trash - -.DEFAULT_GOAL := ci - -.PHONY: $(TARGETS) diff --git a/vendor/github.com/rancher/go-rancher/README.md b/vendor/github.com/rancher/go-rancher/README.md deleted file mode 100644 index 58e479a9d..000000000 --- a/vendor/github.com/rancher/go-rancher/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# Go Bindings for Rancher API - -# Generating Code -First, you must have a master version of Rancher running. The best way to do this is: -```sh -docker run -p 8080:8080 -d rancher/server:master -``` - -Once Rancher is running, you can run the gen-schema.sh script: -```sh -./scripts/gen-schema.sh http://:8080 - -# The default url is http://localhost:8080, so if rancher/server is listening on localhost, you can omit the url: -./scripts/gen-schema.sh -``` - -This will add, remove, and modify go files appropriately. Submit a PR that includes *all* these changes. - -## Important caveats -1. If you are running on macOS, you must have gnu-sed installed as sed for this to work properly. -2. If you are running against cattle that is running out of an IDE and you don't have go-machine-service running (you probably don't), you'll see a number of unexpected removed or modified files like `generated_host.go` `generated_machine.go` and `generated_*config.go`. - -# Building - -```sh -godep go build ./client -``` - -# Tests - -```sh -godep go test ./client -``` -# Contact -For bugs, questions, comments, corrections, suggestions, etc., open an issue in - [rancher/rancher](//github.com/rancher/rancher/issues) with a title starting with `[go-rancher] `. - -Or just [click here](//github.com/rancher/rancher/issues/new?title=%5Bgo-rancher%5D%20) to create a new issue. - - -# License -Copyright (c) 2014-2015 [Rancher Labs, Inc.](http://rancher.com) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - diff --git a/vendor/github.com/rancher/go-rancher/main.go b/vendor/github.com/rancher/go-rancher/main.go deleted file mode 100644 index e8274c8a1..000000000 --- a/vendor/github.com/rancher/go-rancher/main.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "fmt" - _ "github.com/rancher/go-rancher/client" -) - -func main() { - fmt.Println("I have nothing to do...") -} diff --git a/vendor/github.com/rancher/go-rancher/trash.conf b/vendor/github.com/rancher/go-rancher/trash.conf deleted file mode 100644 index 30cb3a959..000000000 --- a/vendor/github.com/rancher/go-rancher/trash.conf +++ /dev/null @@ -1,6 +0,0 @@ -github.com/pkg/errors 1d2e60385a13aaa66134984235061c2f9302520e -github.com/gorilla/context 215affda49addc4c8ef7e2534915df2c8c35c6cd -github.com/gorilla/mux f15e0c49460fd49eebe2bcc8486b05d1bef68d3a -github.com/gorilla/websocket 1551221275a7bd42978745a376b2531f791d88f3 -github.com/Sirupsen/logrus 26709e2714106fb8ad40b773b711ebce25b78914 -gopkg.in/yaml.v2 a83829b6f1293c91addabc89d0571c246397bbf4 diff --git a/vendor/github.com/ryanuber/columnize/LICENSE b/vendor/github.com/ryanuber/columnize/LICENSE deleted file mode 100644 index b9c0e2b68..000000000 --- a/vendor/github.com/ryanuber/columnize/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2016 Ryan Uber - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/ryanuber/columnize/README.md b/vendor/github.com/ryanuber/columnize/README.md deleted file mode 100644 index 9a583db8d..000000000 --- a/vendor/github.com/ryanuber/columnize/README.md +++ /dev/null @@ -1,71 +0,0 @@ -Columnize -========= - -Easy column-formatted output for golang - -[![Build Status](https://travis-ci.org/ryanuber/columnize.svg)](https://travis-ci.org/ryanuber/columnize) -[![GoDoc](https://godoc.org/github.com/ryanuber/columnize?status.svg)](https://godoc.org/github.com/ryanuber/columnize) - -Columnize is a really small Go package that makes building CLI's a little bit -easier. In some CLI designs, you want to output a number similar items in a -human-readable way with nicely aligned columns. However, figuring out how wide -to make each column is a boring problem to solve and eats your valuable time. - -Here is an example: - -```go -package main - -import ( - "fmt" - "github.com/ryanuber/columnize" -) - -func main() { - output := []string{ - "Name | Gender | Age", - "Bob | Male | 38", - "Sally | Female | 26", - } - result := columnize.SimpleFormat(output) - fmt.Println(result) -} -``` - -As you can see, you just pass in a list of strings. And the result: - -``` -Name Gender Age -Bob Male 38 -Sally Female 26 -``` - -Columnize is tolerant of missing or empty fields, or even empty lines, so -passing in extra lines for spacing should show up as you would expect. - -Configuration -============= - -Columnize is configured using a `Config`, which can be obtained by calling the -`DefaultConfig()` method. You can then tweak the settings in the resulting -`Config`: - -``` -config := columnize.DefaultConfig() -config.Delim = "|" -config.Glue = " " -config.Prefix = "" -config.Empty = "" -config.NoTrim = false -``` - -* `Delim` is the string by which columns of **input** are delimited -* `Glue` is the string by which columns of **output** are delimited -* `Prefix` is a string by which each line of **output** is prefixed -* `Empty` is a string used to replace blank values found in output -* `NoTrim` is a boolean used to disable the automatic trimming of input values - -You can then pass the `Config` in using the `Format` method (signature below) to -have text formatted to your liking. - -See the [godoc](https://godoc.org/github.com/ryanuber/columnize) page for usage. diff --git a/vendor/github.com/ryanuber/columnize/columnize.go b/vendor/github.com/ryanuber/columnize/columnize.go deleted file mode 100644 index 527c1d1b3..000000000 --- a/vendor/github.com/ryanuber/columnize/columnize.go +++ /dev/null @@ -1,191 +0,0 @@ -package columnize - -import ( - "bytes" - "fmt" - "strings" -) - -// Config can be used to tune certain parameters which affect the way -// in which Columnize will format output text. -type Config struct { - // The string by which the lines of input will be split. - Delim string - - // The string by which columns of output will be separated. - Glue string - - // The string by which columns of output will be prefixed. - Prefix string - - // A replacement string to replace empty fields. - Empty string - - // NoTrim disables automatic trimming of inputs. - NoTrim bool -} - -// DefaultConfig returns a *Config with default values. -func DefaultConfig() *Config { - return &Config{ - Delim: "|", - Glue: " ", - Prefix: "", - Empty: "", - NoTrim: false, - } -} - -// MergeConfig merges two config objects together and returns the resulting -// configuration. Values from the right take precedence over the left side. -func MergeConfig(a, b *Config) *Config { - // Return quickly if either side was nil - if a == nil { - return b - } - if b == nil { - return a - } - - var result Config = *a - - if b.Delim != "" { - result.Delim = b.Delim - } - if b.Glue != "" { - result.Glue = b.Glue - } - if b.Prefix != "" { - result.Prefix = b.Prefix - } - if b.Empty != "" { - result.Empty = b.Empty - } - if b.NoTrim { - result.NoTrim = true - } - - return &result -} - -// stringFormat, given a set of column widths and the number of columns in -// the current line, returns a sprintf-style format string which can be used -// to print output aligned properly with other lines using the same widths set. -func stringFormat(c *Config, widths []int, columns int) string { - // Create the buffer with an estimate of the length - buf := bytes.NewBuffer(make([]byte, 0, (6+len(c.Glue))*columns)) - - // Start with the prefix, if any was given. The buffer will not return an - // error so it does not need to be handled - buf.WriteString(c.Prefix) - - // Create the format string from the discovered widths - for i := 0; i < columns && i < len(widths); i++ { - if i == columns-1 { - buf.WriteString("%s\n") - } else { - fmt.Fprintf(buf, "%%-%ds%s", widths[i], c.Glue) - } - } - return buf.String() -} - -// elementsFromLine returns a list of elements, each representing a single -// item which will belong to a column of output. -func elementsFromLine(config *Config, line string) []interface{} { - separated := strings.Split(line, config.Delim) - elements := make([]interface{}, len(separated)) - for i, field := range separated { - value := field - if !config.NoTrim { - value = strings.TrimSpace(field) - } - - // Apply the empty value, if configured. - if value == "" && config.Empty != "" { - value = config.Empty - } - elements[i] = value - } - return elements -} - -// runeLen calculates the number of visible "characters" in a string -func runeLen(s string) int { - l := 0 - for _ = range s { - l++ - } - return l -} - -// widthsFromLines examines a list of strings and determines how wide each -// column should be considering all of the elements that need to be printed -// within it. -func widthsFromLines(config *Config, lines []string) []int { - widths := make([]int, 0, 8) - - for _, line := range lines { - elems := elementsFromLine(config, line) - for i := 0; i < len(elems); i++ { - l := runeLen(elems[i].(string)) - if len(widths) <= i { - widths = append(widths, l) - } else if widths[i] < l { - widths[i] = l - } - } - } - return widths -} - -// Format is the public-facing interface that takes a list of strings and -// returns nicely aligned column-formatted text. -func Format(lines []string, config *Config) string { - conf := MergeConfig(DefaultConfig(), config) - widths := widthsFromLines(conf, lines) - - // Estimate the buffer size - glueSize := len(conf.Glue) - var size int - for _, w := range widths { - size += w + glueSize - } - size *= len(lines) - - // Create the buffer - buf := bytes.NewBuffer(make([]byte, 0, size)) - - // Create a cache for the string formats - fmtCache := make(map[int]string, 16) - - // Create the formatted output using the format string - for _, line := range lines { - elems := elementsFromLine(conf, line) - - // Get the string format using cache - numElems := len(elems) - stringfmt, ok := fmtCache[numElems] - if !ok { - stringfmt = stringFormat(conf, widths, numElems) - fmtCache[numElems] = stringfmt - } - - fmt.Fprintf(buf, stringfmt, elems...) - } - - // Get the string result - result := buf.String() - - // Remove trailing newline without removing leading/trailing space - if n := len(result); n > 0 && result[n-1] == '\n' { - result = result[:n-1] - } - - return result -} - -// SimpleFormat is a convenience function to format text with the defaults. -func SimpleFormat(lines []string) string { - return Format(lines, nil) -} diff --git a/vendor/github.com/ryanuber/go-glob/.travis.yml b/vendor/github.com/ryanuber/go-glob/.travis.yml new file mode 100644 index 000000000..9d1ca3c37 --- /dev/null +++ b/vendor/github.com/ryanuber/go-glob/.travis.yml @@ -0,0 +1,5 @@ +language: go +go: + - tip +script: + - go test -v ./... diff --git a/vendor/github.com/ryanuber/go-glob/go.mod b/vendor/github.com/ryanuber/go-glob/go.mod new file mode 100644 index 000000000..f38203593 --- /dev/null +++ b/vendor/github.com/ryanuber/go-glob/go.mod @@ -0,0 +1 @@ +module github.com/ryanuber/go-glob diff --git a/vendor/github.com/ulikunitz/xz/.gitignore b/vendor/github.com/ulikunitz/xz/.gitignore new file mode 100644 index 000000000..e3c2fc2f1 --- /dev/null +++ b/vendor/github.com/ulikunitz/xz/.gitignore @@ -0,0 +1,25 @@ +# .gitignore + +TODO.html +README.html + +lzma/writer.txt +lzma/reader.txt + +cmd/gxz/gxz +cmd/xb/xb + +# test executables +*.test + +# profile files +*.out + +# vim swap file +.*.swp + +# executables on windows +*.exe + +# default compression test file +enwik8* diff --git a/vendor/github.com/ulikunitz/xz/example.go b/vendor/github.com/ulikunitz/xz/example.go new file mode 100644 index 000000000..855e60aee --- /dev/null +++ b/vendor/github.com/ulikunitz/xz/example.go @@ -0,0 +1,40 @@ +// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build ignore + +package main + +import ( + "bytes" + "io" + "log" + "os" + + "github.com/ulikunitz/xz" +) + +func main() { + const text = "The quick brown fox jumps over the lazy dog.\n" + var buf bytes.Buffer + // compress text + w, err := xz.NewWriter(&buf) + if err != nil { + log.Fatalf("xz.NewWriter error %s", err) + } + if _, err := io.WriteString(w, text); err != nil { + log.Fatalf("WriteString error %s", err) + } + if err := w.Close(); err != nil { + log.Fatalf("w.Close error %s", err) + } + // decompress buffer and write output to stdout + r, err := xz.NewReader(&buf) + if err != nil { + log.Fatalf("NewReader error %s", err) + } + if _, err = io.Copy(os.Stdout, r); err != nil { + log.Fatalf("io.Copy error %s", err) + } +} diff --git a/vendor/github.com/ulikunitz/xz/make-docs b/vendor/github.com/ulikunitz/xz/make-docs old mode 100755 new mode 100644 diff --git a/vendor/go.opencensus.io/.gitignore b/vendor/go.opencensus.io/.gitignore new file mode 100644 index 000000000..74a6db472 --- /dev/null +++ b/vendor/go.opencensus.io/.gitignore @@ -0,0 +1,9 @@ +/.idea/ + +# go.opencensus.io/exporter/aws +/exporter/aws/ + +# Exclude vendor, use dep ensure after checkout: +/vendor/github.com/ +/vendor/golang.org/ +/vendor/google.golang.org/ diff --git a/vendor/go.opencensus.io/.travis.yml b/vendor/go.opencensus.io/.travis.yml new file mode 100644 index 000000000..bd6b66ee8 --- /dev/null +++ b/vendor/go.opencensus.io/.travis.yml @@ -0,0 +1,17 @@ +language: go + +go_import_path: go.opencensus.io + +go: + - 1.11.x + +env: + global: + GO111MODULE=on + +before_script: + - make install-tools + +script: + - make travis-ci + - go run internal/check/version.go # TODO move this to makefile diff --git a/vendor/go.opencensus.io/go.mod b/vendor/go.opencensus.io/go.mod index b59bf6c13..cc9febc02 100644 --- a/vendor/go.opencensus.io/go.mod +++ b/vendor/go.opencensus.io/go.mod @@ -8,6 +8,6 @@ require ( github.com/openzipkin/zipkin-go v0.1.6 github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829 golang.org/x/net v0.0.0-20190311183353-d8887717615a - google.golang.org/api v0.2.0 + google.golang.org/api v0.3.1 google.golang.org/grpc v1.19.0 ) diff --git a/vendor/go.opencensus.io/opencensus.go b/vendor/go.opencensus.io/opencensus.go index a52dcd8c6..d2565f1e2 100644 --- a/vendor/go.opencensus.io/opencensus.go +++ b/vendor/go.opencensus.io/opencensus.go @@ -17,5 +17,5 @@ package opencensus // import "go.opencensus.io" // Version is the current release version of OpenCensus in use. func Version() string { - return "0.20.0" + return "0.21.0" } diff --git a/vendor/golang.org/x/crypto/AUTHORS b/vendor/golang.org/x/crypto/AUTHORS new file mode 100644 index 000000000..2b00ddba0 --- /dev/null +++ b/vendor/golang.org/x/crypto/AUTHORS @@ -0,0 +1,3 @@ +# This source code refers to The Go Authors for copyright purposes. +# The master list of authors is in the main Go distribution, +# visible at https://tip.golang.org/AUTHORS. diff --git a/vendor/golang.org/x/crypto/CONTRIBUTORS b/vendor/golang.org/x/crypto/CONTRIBUTORS new file mode 100644 index 000000000..1fbd3e976 --- /dev/null +++ b/vendor/golang.org/x/crypto/CONTRIBUTORS @@ -0,0 +1,3 @@ +# This source code was written by the Go contributors. +# The master list of contributors is in the main Go distribution, +# visible at https://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go b/vendor/golang.org/x/crypto/bcrypt/bcrypt.go index f8b807f9c..aeb73f81a 100644 --- a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go +++ b/vendor/golang.org/x/crypto/bcrypt/bcrypt.go @@ -12,9 +12,10 @@ import ( "crypto/subtle" "errors" "fmt" - "golang.org/x/crypto/blowfish" "io" "strconv" + + "golang.org/x/crypto/blowfish" ) const ( @@ -205,7 +206,6 @@ func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) { } func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) { - csalt, err := base64Decode(salt) if err != nil { return nil, err @@ -213,7 +213,8 @@ func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cip // Bug compatibility with C bcrypt implementations. They use the trailing // NULL in the key string during expansion. - ckey := append(key, 0) + // We copy the key to prevent changing the underlying array. + ckey := append(key[:len(key):len(key)], 0) c, err := blowfish.NewSaltedCipher(ckey, csalt) if err != nil { @@ -240,11 +241,11 @@ func (p *hashed) Hash() []byte { n = 3 } arr[n] = '$' - n += 1 + n++ copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost))) n += 2 arr[n] = '$' - n += 1 + n++ copy(arr[n:], p.salt) n += encodedSaltSize copy(arr[n:], p.hash) diff --git a/vendor/golang.org/x/crypto/blowfish/cipher.go b/vendor/golang.org/x/crypto/blowfish/cipher.go index a73954f39..213bf204a 100644 --- a/vendor/golang.org/x/crypto/blowfish/cipher.go +++ b/vendor/golang.org/x/crypto/blowfish/cipher.go @@ -3,10 +3,18 @@ // license that can be found in the LICENSE file. // Package blowfish implements Bruce Schneier's Blowfish encryption algorithm. +// +// Blowfish is a legacy cipher and its short block size makes it vulnerable to +// birthday bound attacks (see https://sweet32.info). It should only be used +// where compatibility with legacy systems, not security, is the goal. +// +// Deprecated: any new system should use AES (from crypto/aes, if necessary in +// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from +// golang.org/x/crypto/chacha20poly1305). package blowfish // import "golang.org/x/crypto/blowfish" // The code is a port of Bruce Schneier's C implementation. -// See http://www.schneier.com/blowfish.html. +// See https://www.schneier.com/blowfish.html. import "strconv" diff --git a/vendor/golang.org/x/crypto/blowfish/const.go b/vendor/golang.org/x/crypto/blowfish/const.go index 8c5ee4cb0..d04077595 100644 --- a/vendor/golang.org/x/crypto/blowfish/const.go +++ b/vendor/golang.org/x/crypto/blowfish/const.go @@ -4,7 +4,7 @@ // The startup permutation array and substitution boxes. // They are the hexadecimal digits of PI; see: -// http://www.schneier.com/code/constants.txt. +// https://www.schneier.com/code/constants.txt. package blowfish diff --git a/vendor/golang.org/x/crypto/cast5/cast5.go b/vendor/golang.org/x/crypto/cast5/cast5.go index 0b4af37bd..ddcbeb6f2 100644 --- a/vendor/golang.org/x/crypto/cast5/cast5.go +++ b/vendor/golang.org/x/crypto/cast5/cast5.go @@ -2,8 +2,15 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package cast5 implements CAST5, as defined in RFC 2144. CAST5 is a common -// OpenPGP cipher. +// Package cast5 implements CAST5, as defined in RFC 2144. +// +// CAST5 is a legacy cipher and its short block size makes it vulnerable to +// birthday bound attacks (see https://sweet32.info). It should only be used +// where compatibility with legacy systems, not security, is the goal. +// +// Deprecated: any new system should use AES (from crypto/aes, if necessary in +// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from +// golang.org/x/crypto/chacha20poly1305). package cast5 // import "golang.org/x/crypto/cast5" import "errors" diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.h b/vendor/golang.org/x/crypto/curve25519/const_amd64.h index 80ad2220f..b3f74162f 100644 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.h +++ b/vendor/golang.org/x/crypto/curve25519/const_amd64.h @@ -3,6 +3,6 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html #define REDMASK51 0x0007FFFFFFFFFFFF diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.s b/vendor/golang.org/x/crypto/curve25519/const_amd64.s index 0ad539885..ee7b4bd5f 100644 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/const_amd64.s @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine diff --git a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s index 45484d1b5..cd793a5b5 100644 --- a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s @@ -2,87 +2,64 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html - // +build amd64,!gccgo,!appengine -// func cswap(inout *[5]uint64, v uint64) +// func cswap(inout *[4][5]uint64, v uint64) TEXT ·cswap(SB),7,$0 MOVQ inout+0(FP),DI MOVQ v+8(FP),SI - CMPQ SI,$1 - MOVQ 0(DI),SI - MOVQ 80(DI),DX - MOVQ 8(DI),CX - MOVQ 88(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,0(DI) - MOVQ DX,80(DI) - MOVQ CX,8(DI) - MOVQ R8,88(DI) - MOVQ 16(DI),SI - MOVQ 96(DI),DX - MOVQ 24(DI),CX - MOVQ 104(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,16(DI) - MOVQ DX,96(DI) - MOVQ CX,24(DI) - MOVQ R8,104(DI) - MOVQ 32(DI),SI - MOVQ 112(DI),DX - MOVQ 40(DI),CX - MOVQ 120(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,32(DI) - MOVQ DX,112(DI) - MOVQ CX,40(DI) - MOVQ R8,120(DI) - MOVQ 48(DI),SI - MOVQ 128(DI),DX - MOVQ 56(DI),CX - MOVQ 136(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,48(DI) - MOVQ DX,128(DI) - MOVQ CX,56(DI) - MOVQ R8,136(DI) - MOVQ 64(DI),SI - MOVQ 144(DI),DX - MOVQ 72(DI),CX - MOVQ 152(DI),R8 - MOVQ SI,R9 - CMOVQEQ DX,SI - CMOVQEQ R9,DX - MOVQ CX,R9 - CMOVQEQ R8,CX - CMOVQEQ R9,R8 - MOVQ SI,64(DI) - MOVQ DX,144(DI) - MOVQ CX,72(DI) - MOVQ R8,152(DI) - MOVQ DI,AX - MOVQ SI,DX + SUBQ $1, SI + NOTQ SI + MOVQ SI, X15 + PSHUFD $0x44, X15, X15 + + MOVOU 0(DI), X0 + MOVOU 16(DI), X2 + MOVOU 32(DI), X4 + MOVOU 48(DI), X6 + MOVOU 64(DI), X8 + MOVOU 80(DI), X1 + MOVOU 96(DI), X3 + MOVOU 112(DI), X5 + MOVOU 128(DI), X7 + MOVOU 144(DI), X9 + + MOVO X1, X10 + MOVO X3, X11 + MOVO X5, X12 + MOVO X7, X13 + MOVO X9, X14 + + PXOR X0, X10 + PXOR X2, X11 + PXOR X4, X12 + PXOR X6, X13 + PXOR X8, X14 + PAND X15, X10 + PAND X15, X11 + PAND X15, X12 + PAND X15, X13 + PAND X15, X14 + PXOR X10, X0 + PXOR X10, X1 + PXOR X11, X2 + PXOR X11, X3 + PXOR X12, X4 + PXOR X12, X5 + PXOR X13, X6 + PXOR X13, X7 + PXOR X14, X8 + PXOR X14, X9 + + MOVOU X0, 0(DI) + MOVOU X2, 16(DI) + MOVOU X4, 32(DI) + MOVOU X6, 48(DI) + MOVOU X8, 64(DI) + MOVOU X1, 80(DI) + MOVOU X3, 96(DI) + MOVOU X5, 112(DI) + MOVOU X7, 128(DI) + MOVOU X9, 144(DI) RET diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go new file mode 100644 index 000000000..75f24babb --- /dev/null +++ b/vendor/golang.org/x/crypto/curve25519/curve25519.go @@ -0,0 +1,834 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// We have an implementation in amd64 assembly so this code is only run on +// non-amd64 platforms. The amd64 assembly does not support gccgo. +// +build !amd64 gccgo appengine + +package curve25519 + +import ( + "encoding/binary" +) + +// This code is a port of the public domain, "ref10" implementation of +// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. + +// fieldElement represents an element of the field GF(2^255 - 19). An element +// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 +// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on +// context. +type fieldElement [10]int32 + +func feZero(fe *fieldElement) { + for i := range fe { + fe[i] = 0 + } +} + +func feOne(fe *fieldElement) { + feZero(fe) + fe[0] = 1 +} + +func feAdd(dst, a, b *fieldElement) { + for i := range dst { + dst[i] = a[i] + b[i] + } +} + +func feSub(dst, a, b *fieldElement) { + for i := range dst { + dst[i] = a[i] - b[i] + } +} + +func feCopy(dst, src *fieldElement) { + for i := range dst { + dst[i] = src[i] + } +} + +// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. +// +// Preconditions: b in {0,1}. +func feCSwap(f, g *fieldElement, b int32) { + b = -b + for i := range f { + t := b & (f[i] ^ g[i]) + f[i] ^= t + g[i] ^= t + } +} + +// load3 reads a 24-bit, little-endian value from in. +func load3(in []byte) int64 { + var r int64 + r = int64(in[0]) + r |= int64(in[1]) << 8 + r |= int64(in[2]) << 16 + return r +} + +// load4 reads a 32-bit, little-endian value from in. +func load4(in []byte) int64 { + return int64(binary.LittleEndian.Uint32(in)) +} + +func feFromBytes(dst *fieldElement, src *[32]byte) { + h0 := load4(src[:]) + h1 := load3(src[4:]) << 6 + h2 := load3(src[7:]) << 5 + h3 := load3(src[10:]) << 3 + h4 := load3(src[13:]) << 2 + h5 := load4(src[16:]) + h6 := load3(src[20:]) << 7 + h7 := load3(src[23:]) << 5 + h8 := load3(src[26:]) << 4 + h9 := (load3(src[29:]) & 0x7fffff) << 2 + + var carry [10]int64 + carry[9] = (h9 + 1<<24) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + carry[1] = (h1 + 1<<24) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[3] = (h3 + 1<<24) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[5] = (h5 + 1<<24) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + carry[7] = (h7 + 1<<24) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[0] = (h0 + 1<<25) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[2] = (h2 + 1<<25) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[4] = (h4 + 1<<25) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[6] = (h6 + 1<<25) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + carry[8] = (h8 + 1<<25) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + dst[0] = int32(h0) + dst[1] = int32(h1) + dst[2] = int32(h2) + dst[3] = int32(h3) + dst[4] = int32(h4) + dst[5] = int32(h5) + dst[6] = int32(h6) + dst[7] = int32(h7) + dst[8] = int32(h8) + dst[9] = int32(h9) +} + +// feToBytes marshals h to s. +// Preconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +// +// Write p=2^255-19; q=floor(h/p). +// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). +// +// Proof: +// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. +// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. +// +// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). +// Then 0> 25 + q = (h[0] + q) >> 26 + q = (h[1] + q) >> 25 + q = (h[2] + q) >> 26 + q = (h[3] + q) >> 25 + q = (h[4] + q) >> 26 + q = (h[5] + q) >> 25 + q = (h[6] + q) >> 26 + q = (h[7] + q) >> 25 + q = (h[8] + q) >> 26 + q = (h[9] + q) >> 25 + + // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. + h[0] += 19 * q + // Goal: Output h-2^255 q, which is between 0 and 2^255-20. + + carry[0] = h[0] >> 26 + h[1] += carry[0] + h[0] -= carry[0] << 26 + carry[1] = h[1] >> 25 + h[2] += carry[1] + h[1] -= carry[1] << 25 + carry[2] = h[2] >> 26 + h[3] += carry[2] + h[2] -= carry[2] << 26 + carry[3] = h[3] >> 25 + h[4] += carry[3] + h[3] -= carry[3] << 25 + carry[4] = h[4] >> 26 + h[5] += carry[4] + h[4] -= carry[4] << 26 + carry[5] = h[5] >> 25 + h[6] += carry[5] + h[5] -= carry[5] << 25 + carry[6] = h[6] >> 26 + h[7] += carry[6] + h[6] -= carry[6] << 26 + carry[7] = h[7] >> 25 + h[8] += carry[7] + h[7] -= carry[7] << 25 + carry[8] = h[8] >> 26 + h[9] += carry[8] + h[8] -= carry[8] << 26 + carry[9] = h[9] >> 25 + h[9] -= carry[9] << 25 + // h10 = carry9 + + // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. + // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; + // evidently 2^255 h10-2^255 q = 0. + // Goal: Output h[0]+...+2^230 h[9]. + + s[0] = byte(h[0] >> 0) + s[1] = byte(h[0] >> 8) + s[2] = byte(h[0] >> 16) + s[3] = byte((h[0] >> 24) | (h[1] << 2)) + s[4] = byte(h[1] >> 6) + s[5] = byte(h[1] >> 14) + s[6] = byte((h[1] >> 22) | (h[2] << 3)) + s[7] = byte(h[2] >> 5) + s[8] = byte(h[2] >> 13) + s[9] = byte((h[2] >> 21) | (h[3] << 5)) + s[10] = byte(h[3] >> 3) + s[11] = byte(h[3] >> 11) + s[12] = byte((h[3] >> 19) | (h[4] << 6)) + s[13] = byte(h[4] >> 2) + s[14] = byte(h[4] >> 10) + s[15] = byte(h[4] >> 18) + s[16] = byte(h[5] >> 0) + s[17] = byte(h[5] >> 8) + s[18] = byte(h[5] >> 16) + s[19] = byte((h[5] >> 24) | (h[6] << 1)) + s[20] = byte(h[6] >> 7) + s[21] = byte(h[6] >> 15) + s[22] = byte((h[6] >> 23) | (h[7] << 3)) + s[23] = byte(h[7] >> 5) + s[24] = byte(h[7] >> 13) + s[25] = byte((h[7] >> 21) | (h[8] << 4)) + s[26] = byte(h[8] >> 4) + s[27] = byte(h[8] >> 12) + s[28] = byte((h[8] >> 20) | (h[9] << 6)) + s[29] = byte(h[9] >> 2) + s[30] = byte(h[9] >> 10) + s[31] = byte(h[9] >> 18) +} + +// feMul calculates h = f * g +// Can overlap h with f or g. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +// +// Notes on implementation strategy: +// +// Using schoolbook multiplication. +// Karatsuba would save a little in some cost models. +// +// Most multiplications by 2 and 19 are 32-bit precomputations; +// cheaper than 64-bit postcomputations. +// +// There is one remaining multiplication by 19 in the carry chain; +// one *19 precomputation can be merged into this, +// but the resulting data flow is considerably less clean. +// +// There are 12 carries below. +// 10 of them are 2-way parallelizable and vectorizable. +// Can get away with 11 carries, but then data flow is much deeper. +// +// With tighter constraints on inputs can squeeze carries into int32. +func feMul(h, f, g *fieldElement) { + f0 := f[0] + f1 := f[1] + f2 := f[2] + f3 := f[3] + f4 := f[4] + f5 := f[5] + f6 := f[6] + f7 := f[7] + f8 := f[8] + f9 := f[9] + g0 := g[0] + g1 := g[1] + g2 := g[2] + g3 := g[3] + g4 := g[4] + g5 := g[5] + g6 := g[6] + g7 := g[7] + g8 := g[8] + g9 := g[9] + g1_19 := 19 * g1 // 1.4*2^29 + g2_19 := 19 * g2 // 1.4*2^30; still ok + g3_19 := 19 * g3 + g4_19 := 19 * g4 + g5_19 := 19 * g5 + g6_19 := 19 * g6 + g7_19 := 19 * g7 + g8_19 := 19 * g8 + g9_19 := 19 * g9 + f1_2 := 2 * f1 + f3_2 := 2 * f3 + f5_2 := 2 * f5 + f7_2 := 2 * f7 + f9_2 := 2 * f9 + f0g0 := int64(f0) * int64(g0) + f0g1 := int64(f0) * int64(g1) + f0g2 := int64(f0) * int64(g2) + f0g3 := int64(f0) * int64(g3) + f0g4 := int64(f0) * int64(g4) + f0g5 := int64(f0) * int64(g5) + f0g6 := int64(f0) * int64(g6) + f0g7 := int64(f0) * int64(g7) + f0g8 := int64(f0) * int64(g8) + f0g9 := int64(f0) * int64(g9) + f1g0 := int64(f1) * int64(g0) + f1g1_2 := int64(f1_2) * int64(g1) + f1g2 := int64(f1) * int64(g2) + f1g3_2 := int64(f1_2) * int64(g3) + f1g4 := int64(f1) * int64(g4) + f1g5_2 := int64(f1_2) * int64(g5) + f1g6 := int64(f1) * int64(g6) + f1g7_2 := int64(f1_2) * int64(g7) + f1g8 := int64(f1) * int64(g8) + f1g9_38 := int64(f1_2) * int64(g9_19) + f2g0 := int64(f2) * int64(g0) + f2g1 := int64(f2) * int64(g1) + f2g2 := int64(f2) * int64(g2) + f2g3 := int64(f2) * int64(g3) + f2g4 := int64(f2) * int64(g4) + f2g5 := int64(f2) * int64(g5) + f2g6 := int64(f2) * int64(g6) + f2g7 := int64(f2) * int64(g7) + f2g8_19 := int64(f2) * int64(g8_19) + f2g9_19 := int64(f2) * int64(g9_19) + f3g0 := int64(f3) * int64(g0) + f3g1_2 := int64(f3_2) * int64(g1) + f3g2 := int64(f3) * int64(g2) + f3g3_2 := int64(f3_2) * int64(g3) + f3g4 := int64(f3) * int64(g4) + f3g5_2 := int64(f3_2) * int64(g5) + f3g6 := int64(f3) * int64(g6) + f3g7_38 := int64(f3_2) * int64(g7_19) + f3g8_19 := int64(f3) * int64(g8_19) + f3g9_38 := int64(f3_2) * int64(g9_19) + f4g0 := int64(f4) * int64(g0) + f4g1 := int64(f4) * int64(g1) + f4g2 := int64(f4) * int64(g2) + f4g3 := int64(f4) * int64(g3) + f4g4 := int64(f4) * int64(g4) + f4g5 := int64(f4) * int64(g5) + f4g6_19 := int64(f4) * int64(g6_19) + f4g7_19 := int64(f4) * int64(g7_19) + f4g8_19 := int64(f4) * int64(g8_19) + f4g9_19 := int64(f4) * int64(g9_19) + f5g0 := int64(f5) * int64(g0) + f5g1_2 := int64(f5_2) * int64(g1) + f5g2 := int64(f5) * int64(g2) + f5g3_2 := int64(f5_2) * int64(g3) + f5g4 := int64(f5) * int64(g4) + f5g5_38 := int64(f5_2) * int64(g5_19) + f5g6_19 := int64(f5) * int64(g6_19) + f5g7_38 := int64(f5_2) * int64(g7_19) + f5g8_19 := int64(f5) * int64(g8_19) + f5g9_38 := int64(f5_2) * int64(g9_19) + f6g0 := int64(f6) * int64(g0) + f6g1 := int64(f6) * int64(g1) + f6g2 := int64(f6) * int64(g2) + f6g3 := int64(f6) * int64(g3) + f6g4_19 := int64(f6) * int64(g4_19) + f6g5_19 := int64(f6) * int64(g5_19) + f6g6_19 := int64(f6) * int64(g6_19) + f6g7_19 := int64(f6) * int64(g7_19) + f6g8_19 := int64(f6) * int64(g8_19) + f6g9_19 := int64(f6) * int64(g9_19) + f7g0 := int64(f7) * int64(g0) + f7g1_2 := int64(f7_2) * int64(g1) + f7g2 := int64(f7) * int64(g2) + f7g3_38 := int64(f7_2) * int64(g3_19) + f7g4_19 := int64(f7) * int64(g4_19) + f7g5_38 := int64(f7_2) * int64(g5_19) + f7g6_19 := int64(f7) * int64(g6_19) + f7g7_38 := int64(f7_2) * int64(g7_19) + f7g8_19 := int64(f7) * int64(g8_19) + f7g9_38 := int64(f7_2) * int64(g9_19) + f8g0 := int64(f8) * int64(g0) + f8g1 := int64(f8) * int64(g1) + f8g2_19 := int64(f8) * int64(g2_19) + f8g3_19 := int64(f8) * int64(g3_19) + f8g4_19 := int64(f8) * int64(g4_19) + f8g5_19 := int64(f8) * int64(g5_19) + f8g6_19 := int64(f8) * int64(g6_19) + f8g7_19 := int64(f8) * int64(g7_19) + f8g8_19 := int64(f8) * int64(g8_19) + f8g9_19 := int64(f8) * int64(g9_19) + f9g0 := int64(f9) * int64(g0) + f9g1_38 := int64(f9_2) * int64(g1_19) + f9g2_19 := int64(f9) * int64(g2_19) + f9g3_38 := int64(f9_2) * int64(g3_19) + f9g4_19 := int64(f9) * int64(g4_19) + f9g5_38 := int64(f9_2) * int64(g5_19) + f9g6_19 := int64(f9) * int64(g6_19) + f9g7_38 := int64(f9_2) * int64(g7_19) + f9g8_19 := int64(f9) * int64(g8_19) + f9g9_38 := int64(f9_2) * int64(g9_19) + h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 + h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 + h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 + h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 + h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 + h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 + h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 + h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 + h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 + h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 + var carry [10]int64 + + // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) + // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 + // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) + // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + // |h0| <= 2^25 + // |h4| <= 2^25 + // |h1| <= 1.51*2^58 + // |h5| <= 1.51*2^58 + + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + // |h1| <= 2^24; from now on fits into int32 + // |h5| <= 2^24; from now on fits into int32 + // |h2| <= 1.21*2^59 + // |h6| <= 1.21*2^59 + + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + // |h2| <= 2^25; from now on fits into int32 unchanged + // |h6| <= 2^25; from now on fits into int32 unchanged + // |h3| <= 1.51*2^58 + // |h7| <= 1.51*2^58 + + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + // |h3| <= 2^24; from now on fits into int32 unchanged + // |h7| <= 2^24; from now on fits into int32 unchanged + // |h4| <= 1.52*2^33 + // |h8| <= 1.52*2^33 + + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + // |h4| <= 2^25; from now on fits into int32 unchanged + // |h8| <= 2^25; from now on fits into int32 unchanged + // |h5| <= 1.01*2^24 + // |h9| <= 1.51*2^58 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + // |h9| <= 2^24; from now on fits into int32 unchanged + // |h0| <= 1.8*2^37 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + // |h0| <= 2^25; from now on fits into int32 unchanged + // |h1| <= 1.01*2^24 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feSquare calculates h = f*f. Can overlap h with f. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +func feSquare(h, f *fieldElement) { + f0 := f[0] + f1 := f[1] + f2 := f[2] + f3 := f[3] + f4 := f[4] + f5 := f[5] + f6 := f[6] + f7 := f[7] + f8 := f[8] + f9 := f[9] + f0_2 := 2 * f0 + f1_2 := 2 * f1 + f2_2 := 2 * f2 + f3_2 := 2 * f3 + f4_2 := 2 * f4 + f5_2 := 2 * f5 + f6_2 := 2 * f6 + f7_2 := 2 * f7 + f5_38 := 38 * f5 // 1.31*2^30 + f6_19 := 19 * f6 // 1.31*2^30 + f7_38 := 38 * f7 // 1.31*2^30 + f8_19 := 19 * f8 // 1.31*2^30 + f9_38 := 38 * f9 // 1.31*2^30 + f0f0 := int64(f0) * int64(f0) + f0f1_2 := int64(f0_2) * int64(f1) + f0f2_2 := int64(f0_2) * int64(f2) + f0f3_2 := int64(f0_2) * int64(f3) + f0f4_2 := int64(f0_2) * int64(f4) + f0f5_2 := int64(f0_2) * int64(f5) + f0f6_2 := int64(f0_2) * int64(f6) + f0f7_2 := int64(f0_2) * int64(f7) + f0f8_2 := int64(f0_2) * int64(f8) + f0f9_2 := int64(f0_2) * int64(f9) + f1f1_2 := int64(f1_2) * int64(f1) + f1f2_2 := int64(f1_2) * int64(f2) + f1f3_4 := int64(f1_2) * int64(f3_2) + f1f4_2 := int64(f1_2) * int64(f4) + f1f5_4 := int64(f1_2) * int64(f5_2) + f1f6_2 := int64(f1_2) * int64(f6) + f1f7_4 := int64(f1_2) * int64(f7_2) + f1f8_2 := int64(f1_2) * int64(f8) + f1f9_76 := int64(f1_2) * int64(f9_38) + f2f2 := int64(f2) * int64(f2) + f2f3_2 := int64(f2_2) * int64(f3) + f2f4_2 := int64(f2_2) * int64(f4) + f2f5_2 := int64(f2_2) * int64(f5) + f2f6_2 := int64(f2_2) * int64(f6) + f2f7_2 := int64(f2_2) * int64(f7) + f2f8_38 := int64(f2_2) * int64(f8_19) + f2f9_38 := int64(f2) * int64(f9_38) + f3f3_2 := int64(f3_2) * int64(f3) + f3f4_2 := int64(f3_2) * int64(f4) + f3f5_4 := int64(f3_2) * int64(f5_2) + f3f6_2 := int64(f3_2) * int64(f6) + f3f7_76 := int64(f3_2) * int64(f7_38) + f3f8_38 := int64(f3_2) * int64(f8_19) + f3f9_76 := int64(f3_2) * int64(f9_38) + f4f4 := int64(f4) * int64(f4) + f4f5_2 := int64(f4_2) * int64(f5) + f4f6_38 := int64(f4_2) * int64(f6_19) + f4f7_38 := int64(f4) * int64(f7_38) + f4f8_38 := int64(f4_2) * int64(f8_19) + f4f9_38 := int64(f4) * int64(f9_38) + f5f5_38 := int64(f5) * int64(f5_38) + f5f6_38 := int64(f5_2) * int64(f6_19) + f5f7_76 := int64(f5_2) * int64(f7_38) + f5f8_38 := int64(f5_2) * int64(f8_19) + f5f9_76 := int64(f5_2) * int64(f9_38) + f6f6_19 := int64(f6) * int64(f6_19) + f6f7_38 := int64(f6) * int64(f7_38) + f6f8_38 := int64(f6_2) * int64(f8_19) + f6f9_38 := int64(f6) * int64(f9_38) + f7f7_38 := int64(f7) * int64(f7_38) + f7f8_38 := int64(f7_2) * int64(f8_19) + f7f9_76 := int64(f7_2) * int64(f9_38) + f8f8_19 := int64(f8) * int64(f8_19) + f8f9_38 := int64(f8) * int64(f9_38) + f9f9_38 := int64(f9) * int64(f9_38) + h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 + h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 + h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 + h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 + h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 + h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 + h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 + h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 + h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 + h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 + var carry [10]int64 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feMul121666 calculates h = f * 121666. Can overlap h with f. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +func feMul121666(h, f *fieldElement) { + h0 := int64(f[0]) * 121666 + h1 := int64(f[1]) * 121666 + h2 := int64(f[2]) * 121666 + h3 := int64(f[3]) * 121666 + h4 := int64(f[4]) * 121666 + h5 := int64(f[5]) * 121666 + h6 := int64(f[6]) * 121666 + h7 := int64(f[7]) * 121666 + h8 := int64(f[8]) * 121666 + h9 := int64(f[9]) * 121666 + var carry [10]int64 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feInvert sets out = z^-1. +func feInvert(out, z *fieldElement) { + var t0, t1, t2, t3 fieldElement + var i int + + feSquare(&t0, z) + for i = 1; i < 1; i++ { + feSquare(&t0, &t0) + } + feSquare(&t1, &t0) + for i = 1; i < 2; i++ { + feSquare(&t1, &t1) + } + feMul(&t1, z, &t1) + feMul(&t0, &t0, &t1) + feSquare(&t2, &t0) + for i = 1; i < 1; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t1, &t2) + feSquare(&t2, &t1) + for i = 1; i < 5; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t2, &t1) + for i = 1; i < 10; i++ { + feSquare(&t2, &t2) + } + feMul(&t2, &t2, &t1) + feSquare(&t3, &t2) + for i = 1; i < 20; i++ { + feSquare(&t3, &t3) + } + feMul(&t2, &t3, &t2) + feSquare(&t2, &t2) + for i = 1; i < 10; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t2, &t1) + for i = 1; i < 50; i++ { + feSquare(&t2, &t2) + } + feMul(&t2, &t2, &t1) + feSquare(&t3, &t2) + for i = 1; i < 100; i++ { + feSquare(&t3, &t3) + } + feMul(&t2, &t3, &t2) + feSquare(&t2, &t2) + for i = 1; i < 50; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t1, &t1) + for i = 1; i < 5; i++ { + feSquare(&t1, &t1) + } + feMul(out, &t1, &t0) +} + +func scalarMult(out, in, base *[32]byte) { + var e [32]byte + + copy(e[:], in[:]) + e[0] &= 248 + e[31] &= 127 + e[31] |= 64 + + var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement + feFromBytes(&x1, base) + feOne(&x2) + feCopy(&x3, &x1) + feOne(&z3) + + swap := int32(0) + for pos := 254; pos >= 0; pos-- { + b := e[pos/8] >> uint(pos&7) + b &= 1 + swap ^= int32(b) + feCSwap(&x2, &x3, swap) + feCSwap(&z2, &z3, swap) + swap = int32(b) + + feSub(&tmp0, &x3, &z3) + feSub(&tmp1, &x2, &z2) + feAdd(&x2, &x2, &z2) + feAdd(&z2, &x3, &z3) + feMul(&z3, &tmp0, &x2) + feMul(&z2, &z2, &tmp1) + feSquare(&tmp0, &tmp1) + feSquare(&tmp1, &x2) + feAdd(&x3, &z3, &z2) + feSub(&z2, &z3, &z2) + feMul(&x2, &tmp1, &tmp0) + feSub(&tmp1, &tmp1, &tmp0) + feSquare(&z2, &z2) + feMul121666(&z3, &tmp1) + feSquare(&x3, &x3) + feAdd(&tmp0, &tmp0, &z3) + feMul(&z3, &x1, &z2) + feMul(&z2, &tmp1, &tmp0) + } + + feCSwap(&x2, &x3, swap) + feCSwap(&z2, &z3, swap) + + feInvert(&z2, &z2) + feMul(&x2, &x2, &z2) + feToBytes(out, &x2) +} diff --git a/vendor/golang.org/x/crypto/curve25519/doc.go b/vendor/golang.org/x/crypto/curve25519/doc.go index ebeea3c2d..da9b10d9c 100644 --- a/vendor/golang.org/x/crypto/curve25519/doc.go +++ b/vendor/golang.org/x/crypto/curve25519/doc.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package curve25519 provides an implementation of scalar multiplication on -// the elliptic curve known as curve25519. See http://cr.yp.to/ecdh.html +// the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html package curve25519 // import "golang.org/x/crypto/curve25519" // basePoint is the x coordinate of the generator of the curve. diff --git a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s index 536479bf6..390816106 100644 --- a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine diff --git a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s index 7074e5cd9..9e9040b25 100644 --- a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine diff --git a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s index b162e6515..5ce80a2e5 100644 --- a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine diff --git a/vendor/golang.org/x/crypto/curve25519/square_amd64.s b/vendor/golang.org/x/crypto/curve25519/square_amd64.s index 4e864a83e..12f73734f 100644 --- a/vendor/golang.org/x/crypto/curve25519/square_amd64.s +++ b/vendor/golang.org/x/crypto/curve25519/square_amd64.s @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: http://bench.cr.yp.to/supercop.html +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html // +build amd64,!gccgo,!appengine diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go index f1d95674a..d6f683ba3 100644 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ b/vendor/golang.org/x/crypto/ed25519/ed25519.go @@ -3,20 +3,23 @@ // license that can be found in the LICENSE file. // Package ed25519 implements the Ed25519 signature algorithm. See -// http://ed25519.cr.yp.to/. +// https://ed25519.cr.yp.to/. // // These functions are also compatible with the “Ed25519” function defined in -// https://tools.ietf.org/html/draft-irtf-cfrg-eddsa-05. +// RFC 8032. However, unlike RFC 8032's formulation, this package's private key +// representation includes a public key suffix to make multiple signing +// operations with the same key more efficient. This package refers to the RFC +// 8032 private key as the “seed”. package ed25519 // This code is a port of the public domain, “ref10” implementation of ed25519 // from SUPERCOP. import ( + "bytes" "crypto" cryptorand "crypto/rand" "crypto/sha512" - "crypto/subtle" "errors" "io" "strconv" @@ -31,6 +34,8 @@ const ( PrivateKeySize = 64 // SignatureSize is the size, in bytes, of signatures generated and verified by this package. SignatureSize = 64 + // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. + SeedSize = 32 ) // PublicKey is the type of Ed25519 public keys. @@ -46,6 +51,15 @@ func (priv PrivateKey) Public() crypto.PublicKey { return PublicKey(publicKey) } +// Seed returns the private key seed corresponding to priv. It is provided for +// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds +// in this package. +func (priv PrivateKey) Seed() []byte { + seed := make([]byte, SeedSize) + copy(seed, priv[:32]) + return seed +} + // Sign signs the given message with priv. // Ed25519 performs two passes over messages to be signed and therefore cannot // handle pre-hashed messages. Thus opts.HashFunc() must return zero to @@ -61,19 +75,33 @@ func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOp // GenerateKey generates a public/private key pair using entropy from rand. // If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) { +func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { if rand == nil { rand = cryptorand.Reader } - privateKey = make([]byte, PrivateKeySize) - publicKey = make([]byte, PublicKeySize) - _, err = io.ReadFull(rand, privateKey[:32]) - if err != nil { + seed := make([]byte, SeedSize) + if _, err := io.ReadFull(rand, seed); err != nil { return nil, nil, err } - digest := sha512.Sum512(privateKey[:32]) + privateKey := NewKeyFromSeed(seed) + publicKey := make([]byte, PublicKeySize) + copy(publicKey, privateKey[32:]) + + return publicKey, privateKey, nil +} + +// NewKeyFromSeed calculates a private key from a seed. It will panic if +// len(seed) is not SeedSize. This function is provided for interoperability +// with RFC 8032. RFC 8032's private keys correspond to seeds in this +// package. +func NewKeyFromSeed(seed []byte) PrivateKey { + if l := len(seed); l != SeedSize { + panic("ed25519: bad seed length: " + strconv.Itoa(l)) + } + + digest := sha512.Sum512(seed) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 @@ -85,10 +113,11 @@ func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, er var publicKeyBytes [32]byte A.ToBytes(&publicKeyBytes) + privateKey := make([]byte, PrivateKeySize) + copy(privateKey, seed) copy(privateKey[32:], publicKeyBytes[:]) - copy(publicKey, publicKeyBytes[:]) - return publicKey, privateKey, nil + return privateKey } // Sign signs the message with privateKey and returns a signature. It will @@ -171,11 +200,18 @@ func Verify(publicKey PublicKey, message, sig []byte) bool { edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement - var b [32]byte - copy(b[:], sig[32:]) - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) + var s [32]byte + copy(s[:], sig[32:]) + + // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in + // the range [0, order) in order to prevent signature malleability. + if !edwards25519.ScMinimal(&s) { + return false + } + + edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) var checkR [32]byte R.ToBytes(&checkR) - return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 + return bytes.Equal(sig[:32], checkR[:]) } diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go index 5f8b99478..fd03c252a 100644 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go +++ b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go @@ -4,6 +4,8 @@ package edwards25519 +import "encoding/binary" + // This code is a port of the public domain, “ref10” implementation of ed25519 // from SUPERCOP. @@ -1769,3 +1771,23 @@ func ScReduce(out *[32]byte, s *[64]byte) { out[30] = byte(s11 >> 9) out[31] = byte(s11 >> 17) } + +// order is the order of Curve25519 in little-endian form. +var order = [4]uint64{0x5812631a5cf5d3ed, 0x14def9dea2f79cd6, 0, 0x1000000000000000} + +// ScMinimal returns true if the given scalar is less than the order of the +// curve. +func ScMinimal(scalar *[32]byte) bool { + for i := 3; ; i-- { + v := binary.LittleEndian.Uint64(scalar[i*8:]) + if v > order[i] { + return false + } else if v < order[i] { + break + } else if i == 0 { + return false + } + } + + return true +} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s b/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s new file mode 100644 index 000000000..b3a16ef75 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s @@ -0,0 +1,308 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11 +// +build !gccgo,!appengine + +#include "textflag.h" + +#define NUM_ROUNDS 10 + +// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) +TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 + MOVD dst+0(FP), R1 + MOVD src+24(FP), R2 + MOVD src_len+32(FP), R3 + MOVD key+48(FP), R4 + MOVD nonce+56(FP), R6 + MOVD counter+64(FP), R7 + + MOVD $·constants(SB), R10 + MOVD $·incRotMatrix(SB), R11 + + MOVW (R7), R20 + + AND $~255, R3, R13 + ADD R2, R13, R12 // R12 for block end + AND $255, R3, R13 +loop: + MOVD $NUM_ROUNDS, R21 + VLD1 (R11), [V30.S4, V31.S4] + + // load contants + // VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4] + WORD $0x4D60E940 + + // load keys + // VLD4R 16(R4), [V4.S4, V5.S4, V6.S4, V7.S4] + WORD $0x4DFFE884 + // VLD4R 16(R4), [V8.S4, V9.S4, V10.S4, V11.S4] + WORD $0x4DFFE888 + SUB $32, R4 + + // load counter + nonce + // VLD1R (R7), [V12.S4] + WORD $0x4D40C8EC + + // VLD3R (R6), [V13.S4, V14.S4, V15.S4] + WORD $0x4D40E8CD + + // update counter + VADD V30.S4, V12.S4, V12.S4 + +chacha: + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) + VADD V0.S4, V4.S4, V0.S4 + VADD V1.S4, V5.S4, V1.S4 + VADD V2.S4, V6.S4, V2.S4 + VADD V3.S4, V7.S4, V3.S4 + VEOR V12.B16, V0.B16, V12.B16 + VEOR V13.B16, V1.B16, V13.B16 + VEOR V14.B16, V2.B16, V14.B16 + VEOR V15.B16, V3.B16, V15.B16 + VREV32 V12.H8, V12.H8 + VREV32 V13.H8, V13.H8 + VREV32 V14.H8, V14.H8 + VREV32 V15.H8, V15.H8 + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) + VADD V8.S4, V12.S4, V8.S4 + VADD V9.S4, V13.S4, V9.S4 + VADD V10.S4, V14.S4, V10.S4 + VADD V11.S4, V15.S4, V11.S4 + VEOR V8.B16, V4.B16, V16.B16 + VEOR V9.B16, V5.B16, V17.B16 + VEOR V10.B16, V6.B16, V18.B16 + VEOR V11.B16, V7.B16, V19.B16 + VSHL $12, V16.S4, V4.S4 + VSHL $12, V17.S4, V5.S4 + VSHL $12, V18.S4, V6.S4 + VSHL $12, V19.S4, V7.S4 + VSRI $20, V16.S4, V4.S4 + VSRI $20, V17.S4, V5.S4 + VSRI $20, V18.S4, V6.S4 + VSRI $20, V19.S4, V7.S4 + + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) + VADD V0.S4, V4.S4, V0.S4 + VADD V1.S4, V5.S4, V1.S4 + VADD V2.S4, V6.S4, V2.S4 + VADD V3.S4, V7.S4, V3.S4 + VEOR V12.B16, V0.B16, V12.B16 + VEOR V13.B16, V1.B16, V13.B16 + VEOR V14.B16, V2.B16, V14.B16 + VEOR V15.B16, V3.B16, V15.B16 + VTBL V31.B16, [V12.B16], V12.B16 + VTBL V31.B16, [V13.B16], V13.B16 + VTBL V31.B16, [V14.B16], V14.B16 + VTBL V31.B16, [V15.B16], V15.B16 + + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) + VADD V12.S4, V8.S4, V8.S4 + VADD V13.S4, V9.S4, V9.S4 + VADD V14.S4, V10.S4, V10.S4 + VADD V15.S4, V11.S4, V11.S4 + VEOR V8.B16, V4.B16, V16.B16 + VEOR V9.B16, V5.B16, V17.B16 + VEOR V10.B16, V6.B16, V18.B16 + VEOR V11.B16, V7.B16, V19.B16 + VSHL $7, V16.S4, V4.S4 + VSHL $7, V17.S4, V5.S4 + VSHL $7, V18.S4, V6.S4 + VSHL $7, V19.S4, V7.S4 + VSRI $25, V16.S4, V4.S4 + VSRI $25, V17.S4, V5.S4 + VSRI $25, V18.S4, V6.S4 + VSRI $25, V19.S4, V7.S4 + + // V0..V3 += V5..V7, V4 + // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) + VADD V0.S4, V5.S4, V0.S4 + VADD V1.S4, V6.S4, V1.S4 + VADD V2.S4, V7.S4, V2.S4 + VADD V3.S4, V4.S4, V3.S4 + VEOR V15.B16, V0.B16, V15.B16 + VEOR V12.B16, V1.B16, V12.B16 + VEOR V13.B16, V2.B16, V13.B16 + VEOR V14.B16, V3.B16, V14.B16 + VREV32 V12.H8, V12.H8 + VREV32 V13.H8, V13.H8 + VREV32 V14.H8, V14.H8 + VREV32 V15.H8, V15.H8 + + // V10 += V15; V5 <<<= ((V10 XOR V5), 12) + // ... + VADD V15.S4, V10.S4, V10.S4 + VADD V12.S4, V11.S4, V11.S4 + VADD V13.S4, V8.S4, V8.S4 + VADD V14.S4, V9.S4, V9.S4 + VEOR V10.B16, V5.B16, V16.B16 + VEOR V11.B16, V6.B16, V17.B16 + VEOR V8.B16, V7.B16, V18.B16 + VEOR V9.B16, V4.B16, V19.B16 + VSHL $12, V16.S4, V5.S4 + VSHL $12, V17.S4, V6.S4 + VSHL $12, V18.S4, V7.S4 + VSHL $12, V19.S4, V4.S4 + VSRI $20, V16.S4, V5.S4 + VSRI $20, V17.S4, V6.S4 + VSRI $20, V18.S4, V7.S4 + VSRI $20, V19.S4, V4.S4 + + // V0 += V5; V15 <<<= ((V0 XOR V15), 8) + // ... + VADD V5.S4, V0.S4, V0.S4 + VADD V6.S4, V1.S4, V1.S4 + VADD V7.S4, V2.S4, V2.S4 + VADD V4.S4, V3.S4, V3.S4 + VEOR V0.B16, V15.B16, V15.B16 + VEOR V1.B16, V12.B16, V12.B16 + VEOR V2.B16, V13.B16, V13.B16 + VEOR V3.B16, V14.B16, V14.B16 + VTBL V31.B16, [V12.B16], V12.B16 + VTBL V31.B16, [V13.B16], V13.B16 + VTBL V31.B16, [V14.B16], V14.B16 + VTBL V31.B16, [V15.B16], V15.B16 + + // V10 += V15; V5 <<<= ((V10 XOR V5), 7) + // ... + VADD V15.S4, V10.S4, V10.S4 + VADD V12.S4, V11.S4, V11.S4 + VADD V13.S4, V8.S4, V8.S4 + VADD V14.S4, V9.S4, V9.S4 + VEOR V10.B16, V5.B16, V16.B16 + VEOR V11.B16, V6.B16, V17.B16 + VEOR V8.B16, V7.B16, V18.B16 + VEOR V9.B16, V4.B16, V19.B16 + VSHL $7, V16.S4, V5.S4 + VSHL $7, V17.S4, V6.S4 + VSHL $7, V18.S4, V7.S4 + VSHL $7, V19.S4, V4.S4 + VSRI $25, V16.S4, V5.S4 + VSRI $25, V17.S4, V6.S4 + VSRI $25, V18.S4, V7.S4 + VSRI $25, V19.S4, V4.S4 + + SUB $1, R21 + CBNZ R21, chacha + + // VLD4R (R10), [V16.S4, V17.S4, V18.S4, V19.S4] + WORD $0x4D60E950 + + // VLD4R 16(R4), [V20.S4, V21.S4, V22.S4, V23.S4] + WORD $0x4DFFE894 + VADD V30.S4, V12.S4, V12.S4 + VADD V16.S4, V0.S4, V0.S4 + VADD V17.S4, V1.S4, V1.S4 + VADD V18.S4, V2.S4, V2.S4 + VADD V19.S4, V3.S4, V3.S4 + // VLD4R 16(R4), [V24.S4, V25.S4, V26.S4, V27.S4] + WORD $0x4DFFE898 + // restore R4 + SUB $32, R4 + + // load counter + nonce + // VLD1R (R7), [V28.S4] + WORD $0x4D40C8FC + // VLD3R (R6), [V29.S4, V30.S4, V31.S4] + WORD $0x4D40E8DD + + VADD V20.S4, V4.S4, V4.S4 + VADD V21.S4, V5.S4, V5.S4 + VADD V22.S4, V6.S4, V6.S4 + VADD V23.S4, V7.S4, V7.S4 + VADD V24.S4, V8.S4, V8.S4 + VADD V25.S4, V9.S4, V9.S4 + VADD V26.S4, V10.S4, V10.S4 + VADD V27.S4, V11.S4, V11.S4 + VADD V28.S4, V12.S4, V12.S4 + VADD V29.S4, V13.S4, V13.S4 + VADD V30.S4, V14.S4, V14.S4 + VADD V31.S4, V15.S4, V15.S4 + + VZIP1 V1.S4, V0.S4, V16.S4 + VZIP2 V1.S4, V0.S4, V17.S4 + VZIP1 V3.S4, V2.S4, V18.S4 + VZIP2 V3.S4, V2.S4, V19.S4 + VZIP1 V5.S4, V4.S4, V20.S4 + VZIP2 V5.S4, V4.S4, V21.S4 + VZIP1 V7.S4, V6.S4, V22.S4 + VZIP2 V7.S4, V6.S4, V23.S4 + VZIP1 V9.S4, V8.S4, V24.S4 + VZIP2 V9.S4, V8.S4, V25.S4 + VZIP1 V11.S4, V10.S4, V26.S4 + VZIP2 V11.S4, V10.S4, V27.S4 + VZIP1 V13.S4, V12.S4, V28.S4 + VZIP2 V13.S4, V12.S4, V29.S4 + VZIP1 V15.S4, V14.S4, V30.S4 + VZIP2 V15.S4, V14.S4, V31.S4 + VZIP1 V18.D2, V16.D2, V0.D2 + VZIP2 V18.D2, V16.D2, V4.D2 + VZIP1 V19.D2, V17.D2, V8.D2 + VZIP2 V19.D2, V17.D2, V12.D2 + VLD1.P 64(R2), [V16.B16, V17.B16, V18.B16, V19.B16] + + VZIP1 V22.D2, V20.D2, V1.D2 + VZIP2 V22.D2, V20.D2, V5.D2 + VZIP1 V23.D2, V21.D2, V9.D2 + VZIP2 V23.D2, V21.D2, V13.D2 + VLD1.P 64(R2), [V20.B16, V21.B16, V22.B16, V23.B16] + VZIP1 V26.D2, V24.D2, V2.D2 + VZIP2 V26.D2, V24.D2, V6.D2 + VZIP1 V27.D2, V25.D2, V10.D2 + VZIP2 V27.D2, V25.D2, V14.D2 + VLD1.P 64(R2), [V24.B16, V25.B16, V26.B16, V27.B16] + VZIP1 V30.D2, V28.D2, V3.D2 + VZIP2 V30.D2, V28.D2, V7.D2 + VZIP1 V31.D2, V29.D2, V11.D2 + VZIP2 V31.D2, V29.D2, V15.D2 + VLD1.P 64(R2), [V28.B16, V29.B16, V30.B16, V31.B16] + VEOR V0.B16, V16.B16, V16.B16 + VEOR V1.B16, V17.B16, V17.B16 + VEOR V2.B16, V18.B16, V18.B16 + VEOR V3.B16, V19.B16, V19.B16 + VST1.P [V16.B16, V17.B16, V18.B16, V19.B16], 64(R1) + VEOR V4.B16, V20.B16, V20.B16 + VEOR V5.B16, V21.B16, V21.B16 + VEOR V6.B16, V22.B16, V22.B16 + VEOR V7.B16, V23.B16, V23.B16 + VST1.P [V20.B16, V21.B16, V22.B16, V23.B16], 64(R1) + VEOR V8.B16, V24.B16, V24.B16 + VEOR V9.B16, V25.B16, V25.B16 + VEOR V10.B16, V26.B16, V26.B16 + VEOR V11.B16, V27.B16, V27.B16 + VST1.P [V24.B16, V25.B16, V26.B16, V27.B16], 64(R1) + VEOR V12.B16, V28.B16, V28.B16 + VEOR V13.B16, V29.B16, V29.B16 + VEOR V14.B16, V30.B16, V30.B16 + VEOR V15.B16, V31.B16, V31.B16 + VST1.P [V28.B16, V29.B16, V30.B16, V31.B16], 64(R1) + + ADD $4, R20 + MOVW R20, (R7) // update counter + + CMP R2, R12 + BGT loop + + RET + + +DATA ·constants+0x00(SB)/4, $0x61707865 +DATA ·constants+0x04(SB)/4, $0x3320646e +DATA ·constants+0x08(SB)/4, $0x79622d32 +DATA ·constants+0x0c(SB)/4, $0x6b206574 +GLOBL ·constants(SB), NOPTR|RODATA, $32 + +DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 +DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 +DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 +DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 +DATA ·incRotMatrix+0x10(SB)/4, $0x02010003 +DATA ·incRotMatrix+0x14(SB)/4, $0x06050407 +DATA ·incRotMatrix+0x18(SB)/4, $0x0A09080B +DATA ·incRotMatrix+0x1c(SB)/4, $0x0E0D0C0F +GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go new file mode 100644 index 000000000..ad74e23ae --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go @@ -0,0 +1,31 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11 +// +build !gccgo + +package chacha20 + +const ( + haveAsm = true + bufSize = 256 +) + +//go:noescape +func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) + +func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { + + if len(src) >= bufSize { + xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) + } + + if len(src)%bufSize != 0 { + i := len(src) - len(src)%bufSize + c.buf = [bufSize]byte{} + copy(c.buf[:], src[i:]) + xorKeyStreamVX(c.buf[:], c.buf[:], &c.key, &c.nonce, &c.counter) + c.len = bufSize - copy(dst[i:], c.buf[:len(src)%bufSize]) + } +} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go new file mode 100644 index 000000000..6570847f5 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go @@ -0,0 +1,264 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package ChaCha20 implements the core ChaCha20 function as specified +// in https://tools.ietf.org/html/rfc7539#section-2.3. +package chacha20 + +import ( + "crypto/cipher" + "encoding/binary" + + "golang.org/x/crypto/internal/subtle" +) + +// assert that *Cipher implements cipher.Stream +var _ cipher.Stream = (*Cipher)(nil) + +// Cipher is a stateful instance of ChaCha20 using a particular key +// and nonce. A *Cipher implements the cipher.Stream interface. +type Cipher struct { + key [8]uint32 + counter uint32 // incremented after each block + nonce [3]uint32 + buf [bufSize]byte // buffer for unused keystream bytes + len int // number of unused keystream bytes at end of buf +} + +// New creates a new ChaCha20 stream cipher with the given key and nonce. +// The initial counter value is set to 0. +func New(key [8]uint32, nonce [3]uint32) *Cipher { + return &Cipher{key: key, nonce: nonce} +} + +// ChaCha20 constants spelling "expand 32-byte k" +const ( + j0 uint32 = 0x61707865 + j1 uint32 = 0x3320646e + j2 uint32 = 0x79622d32 + j3 uint32 = 0x6b206574 +) + +func quarterRound(a, b, c, d uint32) (uint32, uint32, uint32, uint32) { + a += b + d ^= a + d = (d << 16) | (d >> 16) + c += d + b ^= c + b = (b << 12) | (b >> 20) + a += b + d ^= a + d = (d << 8) | (d >> 24) + c += d + b ^= c + b = (b << 7) | (b >> 25) + return a, b, c, d +} + +// XORKeyStream XORs each byte in the given slice with a byte from the +// cipher's key stream. Dst and src must overlap entirely or not at all. +// +// If len(dst) < len(src), XORKeyStream will panic. It is acceptable +// to pass a dst bigger than src, and in that case, XORKeyStream will +// only update dst[:len(src)] and will not touch the rest of dst. +// +// Multiple calls to XORKeyStream behave as if the concatenation of +// the src buffers was passed in a single run. That is, Cipher +// maintains state and does not reset at each XORKeyStream call. +func (s *Cipher) XORKeyStream(dst, src []byte) { + if len(dst) < len(src) { + panic("chacha20: output smaller than input") + } + if subtle.InexactOverlap(dst[:len(src)], src) { + panic("chacha20: invalid buffer overlap") + } + + // xor src with buffered keystream first + if s.len != 0 { + buf := s.buf[len(s.buf)-s.len:] + if len(src) < len(buf) { + buf = buf[:len(src)] + } + td, ts := dst[:len(buf)], src[:len(buf)] // BCE hint + for i, b := range buf { + td[i] = ts[i] ^ b + } + s.len -= len(buf) + if s.len != 0 { + return + } + s.buf = [len(s.buf)]byte{} // zero the empty buffer + src = src[len(buf):] + dst = dst[len(buf):] + } + + if len(src) == 0 { + return + } + if haveAsm { + if uint64(len(src))+uint64(s.counter)*64 > (1<<38)-64 { + panic("chacha20: counter overflow") + } + s.xorKeyStreamAsm(dst, src) + return + } + + // set up a 64-byte buffer to pad out the final block if needed + // (hoisted out of the main loop to avoid spills) + rem := len(src) % 64 // length of final block + fin := len(src) - rem // index of final block + if rem > 0 { + copy(s.buf[len(s.buf)-64:], src[fin:]) + } + + // pre-calculate most of the first round + s1, s5, s9, s13 := quarterRound(j1, s.key[1], s.key[5], s.nonce[0]) + s2, s6, s10, s14 := quarterRound(j2, s.key[2], s.key[6], s.nonce[1]) + s3, s7, s11, s15 := quarterRound(j3, s.key[3], s.key[7], s.nonce[2]) + + n := len(src) + src, dst = src[:n:n], dst[:n:n] // BCE hint + for i := 0; i < n; i += 64 { + // calculate the remainder of the first round + s0, s4, s8, s12 := quarterRound(j0, s.key[0], s.key[4], s.counter) + + // execute the second round + x0, x5, x10, x15 := quarterRound(s0, s5, s10, s15) + x1, x6, x11, x12 := quarterRound(s1, s6, s11, s12) + x2, x7, x8, x13 := quarterRound(s2, s7, s8, s13) + x3, x4, x9, x14 := quarterRound(s3, s4, s9, s14) + + // execute the remaining 18 rounds + for i := 0; i < 9; i++ { + x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) + x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) + x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) + x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) + + x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) + x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) + x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) + x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) + } + + x0 += j0 + x1 += j1 + x2 += j2 + x3 += j3 + + x4 += s.key[0] + x5 += s.key[1] + x6 += s.key[2] + x7 += s.key[3] + x8 += s.key[4] + x9 += s.key[5] + x10 += s.key[6] + x11 += s.key[7] + + x12 += s.counter + x13 += s.nonce[0] + x14 += s.nonce[1] + x15 += s.nonce[2] + + // increment the counter + s.counter += 1 + if s.counter == 0 { + panic("chacha20: counter overflow") + } + + // pad to 64 bytes if needed + in, out := src[i:], dst[i:] + if i == fin { + // src[fin:] has already been copied into s.buf before + // the main loop + in, out = s.buf[len(s.buf)-64:], s.buf[len(s.buf)-64:] + } + in, out = in[:64], out[:64] // BCE hint + + // XOR the key stream with the source and write out the result + xor(out[0:], in[0:], x0) + xor(out[4:], in[4:], x1) + xor(out[8:], in[8:], x2) + xor(out[12:], in[12:], x3) + xor(out[16:], in[16:], x4) + xor(out[20:], in[20:], x5) + xor(out[24:], in[24:], x6) + xor(out[28:], in[28:], x7) + xor(out[32:], in[32:], x8) + xor(out[36:], in[36:], x9) + xor(out[40:], in[40:], x10) + xor(out[44:], in[44:], x11) + xor(out[48:], in[48:], x12) + xor(out[52:], in[52:], x13) + xor(out[56:], in[56:], x14) + xor(out[60:], in[60:], x15) + } + // copy any trailing bytes out of the buffer and into dst + if rem != 0 { + s.len = 64 - rem + copy(dst[fin:], s.buf[len(s.buf)-64:]) + } +} + +// Advance discards bytes in the key stream until the next 64 byte block +// boundary is reached and updates the counter accordingly. If the key +// stream is already at a block boundary no bytes will be discarded and +// the counter will be unchanged. +func (s *Cipher) Advance() { + s.len -= s.len % 64 + if s.len == 0 { + s.buf = [len(s.buf)]byte{} + } +} + +// XORKeyStream crypts bytes from in to out using the given key and counters. +// In and out must overlap entirely or not at all. Counter contains the raw +// ChaCha20 counter bytes (i.e. block counter followed by nonce). +func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { + s := Cipher{ + key: [8]uint32{ + binary.LittleEndian.Uint32(key[0:4]), + binary.LittleEndian.Uint32(key[4:8]), + binary.LittleEndian.Uint32(key[8:12]), + binary.LittleEndian.Uint32(key[12:16]), + binary.LittleEndian.Uint32(key[16:20]), + binary.LittleEndian.Uint32(key[20:24]), + binary.LittleEndian.Uint32(key[24:28]), + binary.LittleEndian.Uint32(key[28:32]), + }, + nonce: [3]uint32{ + binary.LittleEndian.Uint32(counter[4:8]), + binary.LittleEndian.Uint32(counter[8:12]), + binary.LittleEndian.Uint32(counter[12:16]), + }, + counter: binary.LittleEndian.Uint32(counter[0:4]), + } + s.XORKeyStream(out, in) +} + +// HChaCha20 uses the ChaCha20 core to generate a derived key from a key and a +// nonce. It should only be used as part of the XChaCha20 construction. +func HChaCha20(key *[8]uint32, nonce *[4]uint32) [8]uint32 { + x0, x1, x2, x3 := j0, j1, j2, j3 + x4, x5, x6, x7 := key[0], key[1], key[2], key[3] + x8, x9, x10, x11 := key[4], key[5], key[6], key[7] + x12, x13, x14, x15 := nonce[0], nonce[1], nonce[2], nonce[3] + + for i := 0; i < 10; i++ { + x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) + x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) + x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) + x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) + + x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) + x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) + x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) + x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) + } + + var out [8]uint32 + out[0], out[1], out[2], out[3] = x0, x1, x2, x3 + out[4], out[5], out[6], out[7] = x12, x13, x14, x15 + return out +} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go new file mode 100644 index 000000000..47eac0314 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !arm64,!s390x arm64,!go1.11 gccgo appengine + +package chacha20 + +const ( + bufSize = 64 + haveAsm = false +) + +func (*Cipher) xorKeyStreamAsm(dst, src []byte) { + panic("not implemented") +} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go new file mode 100644 index 000000000..aad645b44 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go @@ -0,0 +1,29 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,!gccgo,!appengine + +package chacha20 + +import ( + "golang.org/x/sys/cpu" +) + +var haveAsm = cpu.S390X.HasVX + +const bufSize = 256 + +// xorKeyStreamVX is an assembly implementation of XORKeyStream. It must only +// be called when the vector facility is available. +// Implementation in asm_s390x.s. +//go:noescape +func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) + +func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { + xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter, &c.buf, &c.len) +} + +// EXRL targets, DO NOT CALL! +func mvcSrcToBuf() +func mvcBufToDst() diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s new file mode 100644 index 000000000..57df40446 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s @@ -0,0 +1,260 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,!gccgo,!appengine + +#include "go_asm.h" +#include "textflag.h" + +// This is an implementation of the ChaCha20 encryption algorithm as +// specified in RFC 7539. It uses vector instructions to compute +// 4 keystream blocks in parallel (256 bytes) which are then XORed +// with the bytes in the input slice. + +GLOBL ·constants<>(SB), RODATA|NOPTR, $32 +// BSWAP: swap bytes in each 4-byte element +DATA ·constants<>+0x00(SB)/4, $0x03020100 +DATA ·constants<>+0x04(SB)/4, $0x07060504 +DATA ·constants<>+0x08(SB)/4, $0x0b0a0908 +DATA ·constants<>+0x0c(SB)/4, $0x0f0e0d0c +// J0: [j0, j1, j2, j3] +DATA ·constants<>+0x10(SB)/4, $0x61707865 +DATA ·constants<>+0x14(SB)/4, $0x3320646e +DATA ·constants<>+0x18(SB)/4, $0x79622d32 +DATA ·constants<>+0x1c(SB)/4, $0x6b206574 + +// EXRL targets: +TEXT ·mvcSrcToBuf(SB), NOFRAME|NOSPLIT, $0 + MVC $1, (R1), (R8) + RET + +TEXT ·mvcBufToDst(SB), NOFRAME|NOSPLIT, $0 + MVC $1, (R8), (R9) + RET + +#define BSWAP V5 +#define J0 V6 +#define KEY0 V7 +#define KEY1 V8 +#define NONCE V9 +#define CTR V10 +#define M0 V11 +#define M1 V12 +#define M2 V13 +#define M3 V14 +#define INC V15 +#define X0 V16 +#define X1 V17 +#define X2 V18 +#define X3 V19 +#define X4 V20 +#define X5 V21 +#define X6 V22 +#define X7 V23 +#define X8 V24 +#define X9 V25 +#define X10 V26 +#define X11 V27 +#define X12 V28 +#define X13 V29 +#define X14 V30 +#define X15 V31 + +#define NUM_ROUNDS 20 + +#define ROUND4(a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3, d0, d1, d2, d3) \ + VAF a1, a0, a0 \ + VAF b1, b0, b0 \ + VAF c1, c0, c0 \ + VAF d1, d0, d0 \ + VX a0, a2, a2 \ + VX b0, b2, b2 \ + VX c0, c2, c2 \ + VX d0, d2, d2 \ + VERLLF $16, a2, a2 \ + VERLLF $16, b2, b2 \ + VERLLF $16, c2, c2 \ + VERLLF $16, d2, d2 \ + VAF a2, a3, a3 \ + VAF b2, b3, b3 \ + VAF c2, c3, c3 \ + VAF d2, d3, d3 \ + VX a3, a1, a1 \ + VX b3, b1, b1 \ + VX c3, c1, c1 \ + VX d3, d1, d1 \ + VERLLF $12, a1, a1 \ + VERLLF $12, b1, b1 \ + VERLLF $12, c1, c1 \ + VERLLF $12, d1, d1 \ + VAF a1, a0, a0 \ + VAF b1, b0, b0 \ + VAF c1, c0, c0 \ + VAF d1, d0, d0 \ + VX a0, a2, a2 \ + VX b0, b2, b2 \ + VX c0, c2, c2 \ + VX d0, d2, d2 \ + VERLLF $8, a2, a2 \ + VERLLF $8, b2, b2 \ + VERLLF $8, c2, c2 \ + VERLLF $8, d2, d2 \ + VAF a2, a3, a3 \ + VAF b2, b3, b3 \ + VAF c2, c3, c3 \ + VAF d2, d3, d3 \ + VX a3, a1, a1 \ + VX b3, b1, b1 \ + VX c3, c1, c1 \ + VX d3, d1, d1 \ + VERLLF $7, a1, a1 \ + VERLLF $7, b1, b1 \ + VERLLF $7, c1, c1 \ + VERLLF $7, d1, d1 + +#define PERMUTE(mask, v0, v1, v2, v3) \ + VPERM v0, v0, mask, v0 \ + VPERM v1, v1, mask, v1 \ + VPERM v2, v2, mask, v2 \ + VPERM v3, v3, mask, v3 + +#define ADDV(x, v0, v1, v2, v3) \ + VAF x, v0, v0 \ + VAF x, v1, v1 \ + VAF x, v2, v2 \ + VAF x, v3, v3 + +#define XORV(off, dst, src, v0, v1, v2, v3) \ + VLM off(src), M0, M3 \ + PERMUTE(BSWAP, v0, v1, v2, v3) \ + VX v0, M0, M0 \ + VX v1, M1, M1 \ + VX v2, M2, M2 \ + VX v3, M3, M3 \ + VSTM M0, M3, off(dst) + +#define SHUFFLE(a, b, c, d, t, u, v, w) \ + VMRHF a, c, t \ // t = {a[0], c[0], a[1], c[1]} + VMRHF b, d, u \ // u = {b[0], d[0], b[1], d[1]} + VMRLF a, c, v \ // v = {a[2], c[2], a[3], c[3]} + VMRLF b, d, w \ // w = {b[2], d[2], b[3], d[3]} + VMRHF t, u, a \ // a = {a[0], b[0], c[0], d[0]} + VMRLF t, u, b \ // b = {a[1], b[1], c[1], d[1]} + VMRHF v, w, c \ // c = {a[2], b[2], c[2], d[2]} + VMRLF v, w, d // d = {a[3], b[3], c[3], d[3]} + +// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) +TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 + MOVD $·constants<>(SB), R1 + MOVD dst+0(FP), R2 // R2=&dst[0] + LMG src+24(FP), R3, R4 // R3=&src[0] R4=len(src) + MOVD key+48(FP), R5 // R5=key + MOVD nonce+56(FP), R6 // R6=nonce + MOVD counter+64(FP), R7 // R7=counter + MOVD buf+72(FP), R8 // R8=buf + MOVD len+80(FP), R9 // R9=len + + // load BSWAP and J0 + VLM (R1), BSWAP, J0 + + // set up tail buffer + ADD $-1, R4, R12 + MOVBZ R12, R12 + CMPUBEQ R12, $255, aligned + MOVD R4, R1 + AND $~255, R1 + MOVD $(R3)(R1*1), R1 + EXRL $·mvcSrcToBuf(SB), R12 + MOVD $255, R0 + SUB R12, R0 + MOVD R0, (R9) // update len + +aligned: + // setup + MOVD $95, R0 + VLM (R5), KEY0, KEY1 + VLL R0, (R6), NONCE + VZERO M0 + VLEIB $7, $32, M0 + VSRLB M0, NONCE, NONCE + + // initialize counter values + VLREPF (R7), CTR + VZERO INC + VLEIF $1, $1, INC + VLEIF $2, $2, INC + VLEIF $3, $3, INC + VAF INC, CTR, CTR + VREPIF $4, INC + +chacha: + VREPF $0, J0, X0 + VREPF $1, J0, X1 + VREPF $2, J0, X2 + VREPF $3, J0, X3 + VREPF $0, KEY0, X4 + VREPF $1, KEY0, X5 + VREPF $2, KEY0, X6 + VREPF $3, KEY0, X7 + VREPF $0, KEY1, X8 + VREPF $1, KEY1, X9 + VREPF $2, KEY1, X10 + VREPF $3, KEY1, X11 + VLR CTR, X12 + VREPF $1, NONCE, X13 + VREPF $2, NONCE, X14 + VREPF $3, NONCE, X15 + + MOVD $(NUM_ROUNDS/2), R1 + +loop: + ROUND4(X0, X4, X12, X8, X1, X5, X13, X9, X2, X6, X14, X10, X3, X7, X15, X11) + ROUND4(X0, X5, X15, X10, X1, X6, X12, X11, X2, X7, X13, X8, X3, X4, X14, X9) + + ADD $-1, R1 + BNE loop + + // decrement length + ADD $-256, R4 + BLT tail + +continue: + // rearrange vectors + SHUFFLE(X0, X1, X2, X3, M0, M1, M2, M3) + ADDV(J0, X0, X1, X2, X3) + SHUFFLE(X4, X5, X6, X7, M0, M1, M2, M3) + ADDV(KEY0, X4, X5, X6, X7) + SHUFFLE(X8, X9, X10, X11, M0, M1, M2, M3) + ADDV(KEY1, X8, X9, X10, X11) + VAF CTR, X12, X12 + SHUFFLE(X12, X13, X14, X15, M0, M1, M2, M3) + ADDV(NONCE, X12, X13, X14, X15) + + // increment counters + VAF INC, CTR, CTR + + // xor keystream with plaintext + XORV(0*64, R2, R3, X0, X4, X8, X12) + XORV(1*64, R2, R3, X1, X5, X9, X13) + XORV(2*64, R2, R3, X2, X6, X10, X14) + XORV(3*64, R2, R3, X3, X7, X11, X15) + + // increment pointers + MOVD $256(R2), R2 + MOVD $256(R3), R3 + + CMPBNE R4, $0, chacha + CMPUBEQ R12, $255, return + EXRL $·mvcBufToDst(SB), R12 // len was updated during setup + +return: + VSTEF $0, CTR, (R7) + RET + +tail: + MOVD R2, R9 + MOVD R8, R2 + MOVD R8, R3 + MOVD $0, R4 + JMP continue diff --git a/vendor/golang.org/x/crypto/internal/chacha20/xor.go b/vendor/golang.org/x/crypto/internal/chacha20/xor.go new file mode 100644 index 000000000..9c5ba0b33 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/chacha20/xor.go @@ -0,0 +1,43 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found src the LICENSE file. + +package chacha20 + +import ( + "runtime" +) + +// Platforms that have fast unaligned 32-bit little endian accesses. +const unaligned = runtime.GOARCH == "386" || + runtime.GOARCH == "amd64" || + runtime.GOARCH == "arm64" || + runtime.GOARCH == "ppc64le" || + runtime.GOARCH == "s390x" + +// xor reads a little endian uint32 from src, XORs it with u and +// places the result in little endian byte order in dst. +func xor(dst, src []byte, u uint32) { + _, _ = src[3], dst[3] // eliminate bounds checks + if unaligned { + // The compiler should optimize this code into + // 32-bit unaligned little endian loads and stores. + // TODO: delete once the compiler does a reliably + // good job with the generic code below. + // See issue #25111 for more details. + v := uint32(src[0]) + v |= uint32(src[1]) << 8 + v |= uint32(src[2]) << 16 + v |= uint32(src[3]) << 24 + v ^= u + dst[0] = byte(v) + dst[1] = byte(v >> 8) + dst[2] = byte(v >> 16) + dst[3] = byte(v >> 24) + } else { + dst[0] = src[0] ^ byte(u) + dst[1] = src[1] ^ byte(u>>8) + dst[2] = src[2] ^ byte(u>>16) + dst[3] = src[3] ^ byte(u>>24) + } +} diff --git a/vendor/golang.org/x/crypto/internal/subtle/aliasing.go b/vendor/golang.org/x/crypto/internal/subtle/aliasing.go new file mode 100644 index 000000000..f38797bfa --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/subtle/aliasing.go @@ -0,0 +1,32 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !appengine + +// Package subtle implements functions that are often useful in cryptographic +// code but require careful thought to use correctly. +package subtle // import "golang.org/x/crypto/internal/subtle" + +import "unsafe" + +// AnyOverlap reports whether x and y share memory at any (not necessarily +// corresponding) index. The memory beyond the slice length is ignored. +func AnyOverlap(x, y []byte) bool { + return len(x) > 0 && len(y) > 0 && + uintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) && + uintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1])) +} + +// InexactOverlap reports whether x and y share memory at any non-corresponding +// index. The memory beyond the slice length is ignored. Note that x and y can +// have different lengths and still not have any inexact overlap. +// +// InexactOverlap can be used to implement the requirements of the crypto/cipher +// AEAD, Block, BlockMode and Stream interfaces. +func InexactOverlap(x, y []byte) bool { + if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] { + return false + } + return AnyOverlap(x, y) +} diff --git a/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go b/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go new file mode 100644 index 000000000..0cc4a8a64 --- /dev/null +++ b/vendor/golang.org/x/crypto/internal/subtle/aliasing_appengine.go @@ -0,0 +1,35 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build appengine + +// Package subtle implements functions that are often useful in cryptographic +// code but require careful thought to use correctly. +package subtle // import "golang.org/x/crypto/internal/subtle" + +// This is the Google App Engine standard variant based on reflect +// because the unsafe package and cgo are disallowed. + +import "reflect" + +// AnyOverlap reports whether x and y share memory at any (not necessarily +// corresponding) index. The memory beyond the slice length is ignored. +func AnyOverlap(x, y []byte) bool { + return len(x) > 0 && len(y) > 0 && + reflect.ValueOf(&x[0]).Pointer() <= reflect.ValueOf(&y[len(y)-1]).Pointer() && + reflect.ValueOf(&y[0]).Pointer() <= reflect.ValueOf(&x[len(x)-1]).Pointer() +} + +// InexactOverlap reports whether x and y share memory at any non-corresponding +// index. The memory beyond the slice length is ignored. Note that x and y can +// have different lengths and still not have any inexact overlap. +// +// InexactOverlap can be used to implement the requirements of the crypto/cipher +// AEAD, Block, BlockMode and Stream interfaces. +func InexactOverlap(x, y []byte) bool { + if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] { + return false + } + return AnyOverlap(x, y) +} diff --git a/vendor/golang.org/x/crypto/openpgp/keys.go b/vendor/golang.org/x/crypto/openpgp/keys.go index 68b14c6ae..3e2518600 100644 --- a/vendor/golang.org/x/crypto/openpgp/keys.go +++ b/vendor/golang.org/x/crypto/openpgp/keys.go @@ -325,16 +325,14 @@ func ReadEntity(packets *packet.Reader) (*Entity, error) { if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { packets.Unread(p) return nil, errors.StructuralError("first packet was not a public/private key") - } else { - e.PrimaryKey = &e.PrivateKey.PublicKey } + e.PrimaryKey = &e.PrivateKey.PublicKey } if !e.PrimaryKey.PubKeyAlgo.CanSign() { return nil, errors.StructuralError("primary key cannot be used for signatures") } - var current *Identity var revocations []*packet.Signature EachPacket: for { @@ -347,32 +345,8 @@ EachPacket: switch pkt := p.(type) { case *packet.UserId: - current = new(Identity) - current.Name = pkt.Id - current.UserId = pkt - e.Identities[pkt.Id] = current - - for { - p, err = packets.Next() - if err == io.EOF { - return nil, io.ErrUnexpectedEOF - } else if err != nil { - return nil, err - } - - sig, ok := p.(*packet.Signature) - if !ok { - return nil, errors.StructuralError("user ID packet not followed by self-signature") - } - - if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { - if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil { - return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error()) - } - current.SelfSignature = sig - break - } - current.Signatures = append(current.Signatures, sig) + if err := addUserID(e, packets, pkt); err != nil { + return nil, err } case *packet.Signature: if pkt.SigType == packet.SigTypeKeyRevocation { @@ -381,11 +355,9 @@ EachPacket: // TODO: RFC4880 5.2.1 permits signatures // directly on keys (eg. to bind additional // revocation keys). - } else if current == nil { - return nil, errors.StructuralError("signature packet found before user id packet") - } else { - current.Signatures = append(current.Signatures, pkt) } + // Else, ignoring the signature as it does not follow anything + // we would know to attach it to. case *packet.PrivateKey: if pkt.IsSubkey == false { packets.Unread(p) @@ -426,33 +398,105 @@ EachPacket: return e, nil } +func addUserID(e *Entity, packets *packet.Reader, pkt *packet.UserId) error { + // Make a new Identity object, that we might wind up throwing away. + // We'll only add it if we get a valid self-signature over this + // userID. + identity := new(Identity) + identity.Name = pkt.Id + identity.UserId = pkt + + for { + p, err := packets.Next() + if err == io.EOF { + break + } else if err != nil { + return err + } + + sig, ok := p.(*packet.Signature) + if !ok { + packets.Unread(p) + break + } + + if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { + if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil { + return errors.StructuralError("user ID self-signature invalid: " + err.Error()) + } + identity.SelfSignature = sig + e.Identities[pkt.Id] = identity + } else { + identity.Signatures = append(identity.Signatures, sig) + } + } + + return nil +} + func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { var subKey Subkey subKey.PublicKey = pub subKey.PrivateKey = priv - p, err := packets.Next() - if err == io.EOF { - return io.ErrUnexpectedEOF - } - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) + + for { + p, err := packets.Next() + if err == io.EOF { + break + } else if err != nil { + return errors.StructuralError("subkey signature invalid: " + err.Error()) + } + + sig, ok := p.(*packet.Signature) + if !ok { + packets.Unread(p) + break + } + + if sig.SigType != packet.SigTypeSubkeyBinding && sig.SigType != packet.SigTypeSubkeyRevocation { + return errors.StructuralError("subkey signature with wrong type") + } + + if err := e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig); err != nil { + return errors.StructuralError("subkey signature invalid: " + err.Error()) + } + + switch sig.SigType { + case packet.SigTypeSubkeyRevocation: + subKey.Sig = sig + case packet.SigTypeSubkeyBinding: + + if shouldReplaceSubkeySig(subKey.Sig, sig) { + subKey.Sig = sig + } + } } - var ok bool - subKey.Sig, ok = p.(*packet.Signature) - if !ok { + + if subKey.Sig == nil { return errors.StructuralError("subkey packet not followed by signature") } - if subKey.Sig.SigType != packet.SigTypeSubkeyBinding && subKey.Sig.SigType != packet.SigTypeSubkeyRevocation { - return errors.StructuralError("subkey signature with wrong type") - } - err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } + e.Subkeys = append(e.Subkeys, subKey) + return nil } +func shouldReplaceSubkeySig(existingSig, potentialNewSig *packet.Signature) bool { + if potentialNewSig == nil { + return false + } + + if existingSig == nil { + return true + } + + if existingSig.SigType == packet.SigTypeSubkeyRevocation { + return false // never override a revocation signature + } + + return potentialNewSig.CreationTime.After(existingSig.CreationTime) +} + const defaultRSAKeyBits = 2048 // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a @@ -487,7 +531,7 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err } isPrimaryId := true e.Identities[uid.Id] = &Identity{ - Name: uid.Name, + Name: uid.Id, UserId: uid, SelfSignature: &packet.Signature{ CreationTime: currentTime, @@ -501,6 +545,10 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err IssuerKeyId: &e.PrimaryKey.KeyId, }, } + err = e.Identities[uid.Id].SelfSignature.SignUserId(uid.Id, e.PrimaryKey, e.PrivateKey, config) + if err != nil { + return nil, err + } // If the user passes in a DefaultHash via packet.Config, // set the PreferredHash for the SelfSignature. @@ -508,6 +556,11 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err e.Identities[uid.Id].SelfSignature.PreferredHash = []uint8{hashToHashId(config.DefaultHash)} } + // Likewise for DefaultCipher. + if config != nil && config.DefaultCipher != 0 { + e.Identities[uid.Id].SelfSignature.PreferredSymmetric = []uint8{uint8(config.DefaultCipher)} + } + e.Subkeys = make([]Subkey, 1) e.Subkeys[0] = Subkey{ PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), @@ -525,13 +578,16 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err } e.Subkeys[0].PublicKey.IsSubkey = true e.Subkeys[0].PrivateKey.IsSubkey = true - + err = e.Subkeys[0].Sig.SignKey(e.Subkeys[0].PublicKey, e.PrivateKey, config) + if err != nil { + return nil, err + } return e, nil } -// SerializePrivate serializes an Entity, including private key material, to -// the given Writer. For now, it must only be used on an Entity returned from -// NewEntity. +// SerializePrivate serializes an Entity, including private key material, but +// excluding signatures from other entities, to the given Writer. +// Identities and subkeys are re-signed in case they changed since NewEntry. // If config is nil, sensible defaults will be used. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { err = e.PrivateKey.Serialize(w) @@ -569,8 +625,8 @@ func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error return nil } -// Serialize writes the public part of the given Entity to w. (No private -// key material will be output). +// Serialize writes the public part of the given Entity to w, including +// signatures from other entities. No private key material will be output. func (e *Entity) Serialize(w io.Writer) error { err := e.PrimaryKey.Serialize(w) if err != nil { diff --git a/vendor/golang.org/x/crypto/openpgp/packet/encrypted_key.go b/vendor/golang.org/x/crypto/openpgp/packet/encrypted_key.go index 266840d05..02b372cf3 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/encrypted_key.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/encrypted_key.go @@ -42,12 +42,18 @@ func (e *EncryptedKey) parse(r io.Reader) (err error) { switch e.Algo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) + if err != nil { + return + } case PubKeyAlgoElGamal: e.encryptedMPI1.bytes, e.encryptedMPI1.bitLength, err = readMPI(r) if err != nil { return } e.encryptedMPI2.bytes, e.encryptedMPI2.bitLength, err = readMPI(r) + if err != nil { + return + } } _, err = consumeAll(r) return @@ -72,7 +78,8 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error { // padding oracle attacks. switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - b, err = rsa.DecryptPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), e.encryptedMPI1.bytes) + k := priv.PrivateKey.(*rsa.PrivateKey) + b, err = rsa.DecryptPKCS1v15(config.Random(), k, padToKeySize(&k.PublicKey, e.encryptedMPI1.bytes)) case PubKeyAlgoElGamal: c1 := new(big.Int).SetBytes(e.encryptedMPI1.bytes) c2 := new(big.Int).SetBytes(e.encryptedMPI2.bytes) diff --git a/vendor/golang.org/x/crypto/openpgp/packet/packet.go b/vendor/golang.org/x/crypto/openpgp/packet/packet.go index 3eded93f0..5af64c542 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/packet.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/packet.go @@ -11,10 +11,12 @@ import ( "crypto/aes" "crypto/cipher" "crypto/des" - "golang.org/x/crypto/cast5" - "golang.org/x/crypto/openpgp/errors" + "crypto/rsa" "io" "math/big" + + "golang.org/x/crypto/cast5" + "golang.org/x/crypto/openpgp/errors" ) // readFull is the same as io.ReadFull except that reading zero bytes returns @@ -402,14 +404,16 @@ const ( type PublicKeyAlgorithm uint8 const ( - PubKeyAlgoRSA PublicKeyAlgorithm = 1 - PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 - PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 - PubKeyAlgoElGamal PublicKeyAlgorithm = 16 - PubKeyAlgoDSA PublicKeyAlgorithm = 17 + PubKeyAlgoRSA PublicKeyAlgorithm = 1 + PubKeyAlgoElGamal PublicKeyAlgorithm = 16 + PubKeyAlgoDSA PublicKeyAlgorithm = 17 // RFC 6637, Section 5. PubKeyAlgoECDH PublicKeyAlgorithm = 18 PubKeyAlgoECDSA PublicKeyAlgorithm = 19 + + // Deprecated in RFC 4880, Section 13.5. Use key flags instead. + PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 + PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 ) // CanEncrypt returns true if it's possible to encrypt a message to a public @@ -500,19 +504,17 @@ func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) { numBytes := (int(bitLength) + 7) / 8 mpi = make([]byte, numBytes) _, err = readFull(r, mpi) - return -} - -// mpiLength returns the length of the given *big.Int when serialized as an -// MPI. -func mpiLength(n *big.Int) (mpiLengthInBytes int) { - mpiLengthInBytes = 2 /* MPI length */ - mpiLengthInBytes += (n.BitLen() + 7) / 8 + // According to RFC 4880 3.2. we should check that the MPI has no leading + // zeroes (at least when not an encrypted MPI?), but this implementation + // does generate leading zeroes, so we keep accepting them. return } // writeMPI serializes a big integer to w. func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) { + // Note that we can produce leading zeroes, in violation of RFC 4880 3.2. + // Implementations seem to be tolerant of them, and stripping them would + // make it complex to guarantee matching re-serialization. _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) if err == nil { _, err = w.Write(mpiBytes) @@ -525,6 +527,18 @@ func writeBig(w io.Writer, i *big.Int) error { return writeMPI(w, uint16(i.BitLen()), i.Bytes()) } +// padToKeySize left-pads a MPI with zeroes to match the length of the +// specified RSA public. +func padToKeySize(pub *rsa.PublicKey, b []byte) []byte { + k := (pub.N.BitLen() + 7) / 8 + if len(b) >= k { + return b + } + bb := make([]byte, k) + copy(bb[len(bb)-len(b):], b) + return bb +} + // CompressionAlgo Represents the different compression algorithms // supported by OpenPGP (except for BZIP2, which is not currently // supported). See Section 9.3 of RFC 4880. diff --git a/vendor/golang.org/x/crypto/openpgp/packet/private_key.go b/vendor/golang.org/x/crypto/openpgp/packet/private_key.go index 34734cc63..bd31cceac 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/private_key.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/private_key.go @@ -64,14 +64,19 @@ func NewECDSAPrivateKey(currentTime time.Time, priv *ecdsa.PrivateKey) *PrivateK return pk } -// NewSignerPrivateKey creates a sign-only PrivateKey from a crypto.Signer that +// NewSignerPrivateKey creates a PrivateKey from a crypto.Signer that // implements RSA or ECDSA. func NewSignerPrivateKey(currentTime time.Time, signer crypto.Signer) *PrivateKey { pk := new(PrivateKey) + // In general, the public Keys should be used as pointers. We still + // type-switch on the values, for backwards-compatibility. switch pubkey := signer.Public().(type) { + case *rsa.PublicKey: + pk.PublicKey = *NewRSAPublicKey(currentTime, pubkey) case rsa.PublicKey: pk.PublicKey = *NewRSAPublicKey(currentTime, &pubkey) - pk.PubKeyAlgo = PubKeyAlgoRSASignOnly + case *ecdsa.PublicKey: + pk.PublicKey = *NewECDSAPublicKey(currentTime, pubkey) case ecdsa.PublicKey: pk.PublicKey = *NewECDSAPublicKey(currentTime, &pubkey) default: diff --git a/vendor/golang.org/x/crypto/openpgp/packet/public_key.go b/vendor/golang.org/x/crypto/openpgp/packet/public_key.go index ead26233d..fcd5f5251 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/public_key.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/public_key.go @@ -244,7 +244,12 @@ func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey } pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) - pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes)) + + // The bit length is 3 (for the 0x04 specifying an uncompressed key) + // plus two field elements (for x and y), which are rounded up to the + // nearest byte. See https://tools.ietf.org/html/rfc6637#section-6 + fieldBytes := (pub.Curve.Params().BitSize + 7) & ^7 + pk.ec.p.bitLength = uint16(3 + fieldBytes + fieldBytes) pk.setFingerPrintAndKeyId() return pk @@ -515,7 +520,7 @@ func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err erro switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) - err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes) + err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)) if err != nil { return errors.SignatureError("RSA verification failure") } @@ -566,7 +571,7 @@ func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err switch pk.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: rsaPublicKey := pk.PublicKey.(*rsa.PublicKey) - if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil { + if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.bytes)); err != nil { return errors.SignatureError("RSA verification failure") } return diff --git a/vendor/golang.org/x/crypto/openpgp/packet/signature.go b/vendor/golang.org/x/crypto/openpgp/packet/signature.go index 6ce0cbedb..b2a24a532 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/signature.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/signature.go @@ -542,7 +542,7 @@ func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err e r, s, err = ecdsa.Sign(config.Random(), pk, digest) } else { var b []byte - b, err = priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, nil) + b, err = priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash) if err == nil { r, s, err = unwrapECDSASig(b) } diff --git a/vendor/golang.org/x/crypto/openpgp/packet/userattribute.go b/vendor/golang.org/x/crypto/openpgp/packet/userattribute.go index 96a2b382a..d19ffbc78 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/userattribute.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/userattribute.go @@ -80,7 +80,7 @@ func (uat *UserAttribute) Serialize(w io.Writer) (err error) { // ImageData returns zero or more byte slices, each containing // JPEG File Interchange Format (JFIF), for each photo in the -// the user attribute packet. +// user attribute packet. func (uat *UserAttribute) ImageData() (imageData [][]byte) { for _, sp := range uat.Contents { if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { diff --git a/vendor/golang.org/x/crypto/openpgp/write.go b/vendor/golang.org/x/crypto/openpgp/write.go index 65a304cc8..4ee71784e 100644 --- a/vendor/golang.org/x/crypto/openpgp/write.go +++ b/vendor/golang.org/x/crypto/openpgp/write.go @@ -164,12 +164,12 @@ func hashToHashId(h crypto.Hash) uint8 { return v } -// Encrypt encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { +// writeAndSign writes the data as a payload package and, optionally, signs +// it. hints contains optional information, that is also encrypted, +// that aids the recipients in processing the message. The resulting +// WriteCloser must be closed after the contents of the file have been +// written. If config is nil, sensible defaults will be used. +func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { var signer *packet.PrivateKey if signed != nil { signKey, ok := signed.signingKey(config.Now()) @@ -185,6 +185,83 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint } } + var hash crypto.Hash + for _, hashId := range candidateHashes { + if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { + hash = h + break + } + } + + // If the hash specified by config is a candidate, we'll use that. + if configuredHash := config.Hash(); configuredHash.Available() { + for _, hashId := range candidateHashes { + if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { + hash = h + break + } + } + } + + if hash == 0 { + hashId := candidateHashes[0] + name, ok := s2k.HashIdToString(hashId) + if !ok { + name = "#" + strconv.Itoa(int(hashId)) + } + return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") + } + + if signer != nil { + ops := &packet.OnePassSignature{ + SigType: packet.SigTypeBinary, + Hash: hash, + PubKeyAlgo: signer.PubKeyAlgo, + KeyId: signer.KeyId, + IsLast: true, + } + if err := ops.Serialize(payload); err != nil { + return nil, err + } + } + + if hints == nil { + hints = &FileHints{} + } + + w := payload + if signer != nil { + // If we need to write a signature packet after the literal + // data then we need to stop literalData from closing + // encryptedData. + w = noOpCloser{w} + + } + var epochSeconds uint32 + if !hints.ModTime.IsZero() { + epochSeconds = uint32(hints.ModTime.Unix()) + } + literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) + if err != nil { + return nil, err + } + + if signer != nil { + return signatureWriter{payload, literalData, hash, hash.New(), signer, config}, nil + } + return literalData, nil +} + +// Encrypt encrypts a message to a number of recipients and, optionally, signs +// it. hints contains optional information, that is also encrypted, that aids +// the recipients in processing the message. The resulting WriteCloser must +// be closed after the contents of the file have been written. +// If config is nil, sensible defaults will be used. +func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { + if len(to) == 0 { + return nil, errors.InvalidArgumentError("no encryption recipient provided") + } + // These are the possible ciphers that we'll use for the message. candidateCiphers := []uint8{ uint8(packet.CipherAES128), @@ -194,6 +271,7 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint // These are the possible hash functions that we'll use for the signature. candidateHashes := []uint8{ hashToHashId(crypto.SHA256), + hashToHashId(crypto.SHA384), hashToHashId(crypto.SHA512), hashToHashId(crypto.SHA1), hashToHashId(crypto.RIPEMD160), @@ -241,33 +319,6 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint } } - var hash crypto.Hash - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { - hash = h - break - } - } - - // If the hash specified by config is a candidate, we'll use that. - if configuredHash := config.Hash(); configuredHash.Available() { - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { - hash = h - break - } - } - } - - if hash == 0 { - hashId := candidateHashes[0] - name, ok := s2k.HashIdToString(hashId) - if !ok { - name = "#" + strconv.Itoa(int(hashId)) - } - return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") - } - symKey := make([]byte, cipher.KeySize()) if _, err := io.ReadFull(config.Random(), symKey); err != nil { return nil, err @@ -279,49 +330,38 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint } } - encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config) + payload, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config) if err != nil { return } - if signer != nil { - ops := &packet.OnePassSignature{ - SigType: packet.SigTypeBinary, - Hash: hash, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - if err := ops.Serialize(encryptedData); err != nil { - return nil, err - } - } + return writeAndSign(payload, candidateHashes, signed, hints, config) +} - if hints == nil { - hints = &FileHints{} +// Sign signs a message. The resulting WriteCloser must be closed after the +// contents of the file have been written. hints contains optional information +// that aids the recipients in processing the message. +// If config is nil, sensible defaults will be used. +func Sign(output io.Writer, signed *Entity, hints *FileHints, config *packet.Config) (input io.WriteCloser, err error) { + if signed == nil { + return nil, errors.InvalidArgumentError("no signer provided") } - w := encryptedData - if signer != nil { - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - w = noOpCloser{encryptedData} - - } - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) - if err != nil { - return nil, err + // These are the possible hash functions that we'll use for the signature. + candidateHashes := []uint8{ + hashToHashId(crypto.SHA256), + hashToHashId(crypto.SHA384), + hashToHashId(crypto.SHA512), + hashToHashId(crypto.SHA1), + hashToHashId(crypto.RIPEMD160), } - - if signer != nil { - return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil + defaultHashes := candidateHashes[len(candidateHashes)-1:] + preferredHashes := signed.primaryIdentity().SelfSignature.PreferredHash + if len(preferredHashes) == 0 { + preferredHashes = defaultHashes } - return literalData, nil + candidateHashes = intersectPreferences(candidateHashes, preferredHashes) + return writeAndSign(noOpCloser{output}, candidateHashes, signed, hints, config) } // signatureWriter hashes the contents of a message while passing it along to diff --git a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go new file mode 100644 index 000000000..8387d2999 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go @@ -0,0 +1,11 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !amd64 gccgo appengine + +package poly1305 + +type mac struct{ macGeneric } + +func newMAC(key *[32]byte) mac { return mac{newMACGeneric(key)} } diff --git a/vendor/golang.org/x/crypto/poly1305/poly1305.go b/vendor/golang.org/x/crypto/poly1305/poly1305.go new file mode 100644 index 000000000..d076a5623 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/poly1305.go @@ -0,0 +1,83 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package poly1305 implements Poly1305 one-time message authentication code as +// specified in https://cr.yp.to/mac/poly1305-20050329.pdf. +// +// Poly1305 is a fast, one-time authentication function. It is infeasible for an +// attacker to generate an authenticator for a message without the key. However, a +// key must only be used for a single message. Authenticating two different +// messages with the same key allows an attacker to forge authenticators for other +// messages with the same key. +// +// Poly1305 was originally coupled with AES in order to make Poly1305-AES. AES was +// used with a fixed key in order to generate one-time keys from an nonce. +// However, in this package AES isn't used and the one-time key is specified +// directly. +package poly1305 // import "golang.org/x/crypto/poly1305" + +import "crypto/subtle" + +// TagSize is the size, in bytes, of a poly1305 authenticator. +const TagSize = 16 + +// Verify returns true if mac is a valid authenticator for m with the given +// key. +func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { + var tmp [16]byte + Sum(&tmp, m, key) + return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1 +} + +// New returns a new MAC computing an authentication +// tag of all data written to it with the given key. +// This allows writing the message progressively instead +// of passing it as a single slice. Common users should use +// the Sum function instead. +// +// The key must be unique for each message, as authenticating +// two different messages with the same key allows an attacker +// to forge messages at will. +func New(key *[32]byte) *MAC { + return &MAC{ + mac: newMAC(key), + finalized: false, + } +} + +// MAC is an io.Writer computing an authentication tag +// of the data written to it. +// +// MAC cannot be used like common hash.Hash implementations, +// because using a poly1305 key twice breaks its security. +// Therefore writing data to a running MAC after calling +// Sum causes it to panic. +type MAC struct { + mac // platform-dependent implementation + + finalized bool +} + +// Size returns the number of bytes Sum will return. +func (h *MAC) Size() int { return TagSize } + +// Write adds more data to the running message authentication code. +// It never returns an error. +// +// It must not be called after the first call of Sum. +func (h *MAC) Write(p []byte) (n int, err error) { + if h.finalized { + panic("poly1305: write to MAC after Sum") + } + return h.mac.Write(p) +} + +// Sum computes the authenticator of all data written to the +// message authentication code. +func (h *MAC) Sum(b []byte) []byte { + var mac [TagSize]byte + h.mac.Sum(&mac) + h.finalized = true + return append(b, mac[:]...) +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go new file mode 100644 index 000000000..2dbf42aa5 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go @@ -0,0 +1,68 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build amd64,!gccgo,!appengine + +package poly1305 + +//go:noescape +func initialize(state *[7]uint64, key *[32]byte) + +//go:noescape +func update(state *[7]uint64, msg []byte) + +//go:noescape +func finalize(tag *[TagSize]byte, state *[7]uint64) + +// Sum generates an authenticator for m using a one-time key and puts the +// 16-byte result into out. Authenticating two different messages with the same +// key allows an attacker to forge messages at will. +func Sum(out *[16]byte, m []byte, key *[32]byte) { + h := newMAC(key) + h.Write(m) + h.Sum(out) +} + +func newMAC(key *[32]byte) (h mac) { + initialize(&h.state, key) + return +} + +type mac struct { + state [7]uint64 // := uint64{ h0, h1, h2, r0, r1, pad0, pad1 } + + buffer [TagSize]byte + offset int +} + +func (h *mac) Write(p []byte) (n int, err error) { + n = len(p) + if h.offset > 0 { + remaining := TagSize - h.offset + if n < remaining { + h.offset += copy(h.buffer[h.offset:], p) + return n, nil + } + copy(h.buffer[h.offset:], p[:remaining]) + p = p[remaining:] + h.offset = 0 + update(&h.state, h.buffer[:]) + } + if nn := len(p) - (len(p) % TagSize); nn > 0 { + update(&h.state, p[:nn]) + p = p[nn:] + } + if len(p) > 0 { + h.offset += copy(h.buffer[h.offset:], p) + } + return n, nil +} + +func (h *mac) Sum(out *[16]byte) { + state := h.state + if h.offset > 0 { + update(&state, h.buffer[:h.offset]) + } + finalize(out, &state) +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s new file mode 100644 index 000000000..7d600f13c --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s @@ -0,0 +1,148 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build amd64,!gccgo,!appengine + +#include "textflag.h" + +#define POLY1305_ADD(msg, h0, h1, h2) \ + ADDQ 0(msg), h0; \ + ADCQ 8(msg), h1; \ + ADCQ $1, h2; \ + LEAQ 16(msg), msg + +#define POLY1305_MUL(h0, h1, h2, r0, r1, t0, t1, t2, t3) \ + MOVQ r0, AX; \ + MULQ h0; \ + MOVQ AX, t0; \ + MOVQ DX, t1; \ + MOVQ r0, AX; \ + MULQ h1; \ + ADDQ AX, t1; \ + ADCQ $0, DX; \ + MOVQ r0, t2; \ + IMULQ h2, t2; \ + ADDQ DX, t2; \ + \ + MOVQ r1, AX; \ + MULQ h0; \ + ADDQ AX, t1; \ + ADCQ $0, DX; \ + MOVQ DX, h0; \ + MOVQ r1, t3; \ + IMULQ h2, t3; \ + MOVQ r1, AX; \ + MULQ h1; \ + ADDQ AX, t2; \ + ADCQ DX, t3; \ + ADDQ h0, t2; \ + ADCQ $0, t3; \ + \ + MOVQ t0, h0; \ + MOVQ t1, h1; \ + MOVQ t2, h2; \ + ANDQ $3, h2; \ + MOVQ t2, t0; \ + ANDQ $0xFFFFFFFFFFFFFFFC, t0; \ + ADDQ t0, h0; \ + ADCQ t3, h1; \ + ADCQ $0, h2; \ + SHRQ $2, t3, t2; \ + SHRQ $2, t3; \ + ADDQ t2, h0; \ + ADCQ t3, h1; \ + ADCQ $0, h2 + +DATA ·poly1305Mask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF +DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC +GLOBL ·poly1305Mask<>(SB), RODATA, $16 + +// func update(state *[7]uint64, msg []byte) +TEXT ·update(SB), $0-32 + MOVQ state+0(FP), DI + MOVQ msg_base+8(FP), SI + MOVQ msg_len+16(FP), R15 + + MOVQ 0(DI), R8 // h0 + MOVQ 8(DI), R9 // h1 + MOVQ 16(DI), R10 // h2 + MOVQ 24(DI), R11 // r0 + MOVQ 32(DI), R12 // r1 + + CMPQ R15, $16 + JB bytes_between_0_and_15 + +loop: + POLY1305_ADD(SI, R8, R9, R10) + +multiply: + POLY1305_MUL(R8, R9, R10, R11, R12, BX, CX, R13, R14) + SUBQ $16, R15 + CMPQ R15, $16 + JAE loop + +bytes_between_0_and_15: + TESTQ R15, R15 + JZ done + MOVQ $1, BX + XORQ CX, CX + XORQ R13, R13 + ADDQ R15, SI + +flush_buffer: + SHLQ $8, BX, CX + SHLQ $8, BX + MOVB -1(SI), R13 + XORQ R13, BX + DECQ SI + DECQ R15 + JNZ flush_buffer + + ADDQ BX, R8 + ADCQ CX, R9 + ADCQ $0, R10 + MOVQ $16, R15 + JMP multiply + +done: + MOVQ R8, 0(DI) + MOVQ R9, 8(DI) + MOVQ R10, 16(DI) + RET + +// func initialize(state *[7]uint64, key *[32]byte) +TEXT ·initialize(SB), $0-16 + MOVQ state+0(FP), DI + MOVQ key+8(FP), SI + + // state[0...7] is initialized with zero + MOVOU 0(SI), X0 + MOVOU 16(SI), X1 + MOVOU ·poly1305Mask<>(SB), X2 + PAND X2, X0 + MOVOU X0, 24(DI) + MOVOU X1, 40(DI) + RET + +// func finalize(tag *[TagSize]byte, state *[7]uint64) +TEXT ·finalize(SB), $0-16 + MOVQ tag+0(FP), DI + MOVQ state+8(FP), SI + + MOVQ 0(SI), AX + MOVQ 8(SI), BX + MOVQ 16(SI), CX + MOVQ AX, R8 + MOVQ BX, R9 + SUBQ $0xFFFFFFFFFFFFFFFB, AX + SBBQ $0xFFFFFFFFFFFFFFFF, BX + SBBQ $3, CX + CMOVQCS R8, AX + CMOVQCS R9, BX + ADDQ 40(SI), AX + ADCQ 48(SI), BX + + MOVQ AX, 0(DI) + MOVQ BX, 8(DI) + RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.go b/vendor/golang.org/x/crypto/poly1305/sum_arm.go new file mode 100644 index 000000000..5dc321c2f --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_arm.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build arm,!gccgo,!appengine,!nacl + +package poly1305 + +// This function is implemented in sum_arm.s +//go:noescape +func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte) + +// Sum generates an authenticator for m using a one-time key and puts the +// 16-byte result into out. Authenticating two different messages with the same +// key allows an attacker to forge messages at will. +func Sum(out *[16]byte, m []byte, key *[32]byte) { + var mPtr *byte + if len(m) > 0 { + mPtr = &m[0] + } + poly1305_auth_armv6(out, mPtr, uint32(len(m)), key) +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.s b/vendor/golang.org/x/crypto/poly1305/sum_arm.s new file mode 100644 index 000000000..f70b4ac48 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_arm.s @@ -0,0 +1,427 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build arm,!gccgo,!appengine,!nacl + +#include "textflag.h" + +// This code was translated into a form compatible with 5a from the public +// domain source by Andrew Moon: github.com/floodyberry/poly1305-opt/blob/master/app/extensions/poly1305. + +DATA ·poly1305_init_constants_armv6<>+0x00(SB)/4, $0x3ffffff +DATA ·poly1305_init_constants_armv6<>+0x04(SB)/4, $0x3ffff03 +DATA ·poly1305_init_constants_armv6<>+0x08(SB)/4, $0x3ffc0ff +DATA ·poly1305_init_constants_armv6<>+0x0c(SB)/4, $0x3f03fff +DATA ·poly1305_init_constants_armv6<>+0x10(SB)/4, $0x00fffff +GLOBL ·poly1305_init_constants_armv6<>(SB), 8, $20 + +// Warning: the linker may use R11 to synthesize certain instructions. Please +// take care and verify that no synthetic instructions use it. + +TEXT poly1305_init_ext_armv6<>(SB), NOSPLIT, $0 + // Needs 16 bytes of stack and 64 bytes of space pointed to by R0. (It + // might look like it's only 60 bytes of space but the final four bytes + // will be written by another function.) We need to skip over four + // bytes of stack because that's saving the value of 'g'. + ADD $4, R13, R8 + MOVM.IB [R4-R7], (R8) + MOVM.IA.W (R1), [R2-R5] + MOVW $·poly1305_init_constants_armv6<>(SB), R7 + MOVW R2, R8 + MOVW R2>>26, R9 + MOVW R3>>20, g + MOVW R4>>14, R11 + MOVW R5>>8, R12 + ORR R3<<6, R9, R9 + ORR R4<<12, g, g + ORR R5<<18, R11, R11 + MOVM.IA (R7), [R2-R6] + AND R8, R2, R2 + AND R9, R3, R3 + AND g, R4, R4 + AND R11, R5, R5 + AND R12, R6, R6 + MOVM.IA.W [R2-R6], (R0) + EOR R2, R2, R2 + EOR R3, R3, R3 + EOR R4, R4, R4 + EOR R5, R5, R5 + EOR R6, R6, R6 + MOVM.IA.W [R2-R6], (R0) + MOVM.IA.W (R1), [R2-R5] + MOVM.IA [R2-R6], (R0) + ADD $20, R13, R0 + MOVM.DA (R0), [R4-R7] + RET + +#define MOVW_UNALIGNED(Rsrc, Rdst, Rtmp, offset) \ + MOVBU (offset+0)(Rsrc), Rtmp; \ + MOVBU Rtmp, (offset+0)(Rdst); \ + MOVBU (offset+1)(Rsrc), Rtmp; \ + MOVBU Rtmp, (offset+1)(Rdst); \ + MOVBU (offset+2)(Rsrc), Rtmp; \ + MOVBU Rtmp, (offset+2)(Rdst); \ + MOVBU (offset+3)(Rsrc), Rtmp; \ + MOVBU Rtmp, (offset+3)(Rdst) + +TEXT poly1305_blocks_armv6<>(SB), NOSPLIT, $0 + // Needs 24 bytes of stack for saved registers and then 88 bytes of + // scratch space after that. We assume that 24 bytes at (R13) have + // already been used: four bytes for the link register saved in the + // prelude of poly1305_auth_armv6, four bytes for saving the value of g + // in that function and 16 bytes of scratch space used around + // poly1305_finish_ext_armv6_skip1. + ADD $24, R13, R12 + MOVM.IB [R4-R8, R14], (R12) + MOVW R0, 88(R13) + MOVW R1, 92(R13) + MOVW R2, 96(R13) + MOVW R1, R14 + MOVW R2, R12 + MOVW 56(R0), R8 + WORD $0xe1180008 // TST R8, R8 not working see issue 5921 + EOR R6, R6, R6 + MOVW.EQ $(1<<24), R6 + MOVW R6, 84(R13) + ADD $116, R13, g + MOVM.IA (R0), [R0-R9] + MOVM.IA [R0-R4], (g) + CMP $16, R12 + BLO poly1305_blocks_armv6_done + +poly1305_blocks_armv6_mainloop: + WORD $0xe31e0003 // TST R14, #3 not working see issue 5921 + BEQ poly1305_blocks_armv6_mainloop_aligned + ADD $100, R13, g + MOVW_UNALIGNED(R14, g, R0, 0) + MOVW_UNALIGNED(R14, g, R0, 4) + MOVW_UNALIGNED(R14, g, R0, 8) + MOVW_UNALIGNED(R14, g, R0, 12) + MOVM.IA (g), [R0-R3] + ADD $16, R14 + B poly1305_blocks_armv6_mainloop_loaded + +poly1305_blocks_armv6_mainloop_aligned: + MOVM.IA.W (R14), [R0-R3] + +poly1305_blocks_armv6_mainloop_loaded: + MOVW R0>>26, g + MOVW R1>>20, R11 + MOVW R2>>14, R12 + MOVW R14, 92(R13) + MOVW R3>>8, R4 + ORR R1<<6, g, g + ORR R2<<12, R11, R11 + ORR R3<<18, R12, R12 + BIC $0xfc000000, R0, R0 + BIC $0xfc000000, g, g + MOVW 84(R13), R3 + BIC $0xfc000000, R11, R11 + BIC $0xfc000000, R12, R12 + ADD R0, R5, R5 + ADD g, R6, R6 + ORR R3, R4, R4 + ADD R11, R7, R7 + ADD $116, R13, R14 + ADD R12, R8, R8 + ADD R4, R9, R9 + MOVM.IA (R14), [R0-R4] + MULLU R4, R5, (R11, g) + MULLU R3, R5, (R14, R12) + MULALU R3, R6, (R11, g) + MULALU R2, R6, (R14, R12) + MULALU R2, R7, (R11, g) + MULALU R1, R7, (R14, R12) + ADD R4<<2, R4, R4 + ADD R3<<2, R3, R3 + MULALU R1, R8, (R11, g) + MULALU R0, R8, (R14, R12) + MULALU R0, R9, (R11, g) + MULALU R4, R9, (R14, R12) + MOVW g, 76(R13) + MOVW R11, 80(R13) + MOVW R12, 68(R13) + MOVW R14, 72(R13) + MULLU R2, R5, (R11, g) + MULLU R1, R5, (R14, R12) + MULALU R1, R6, (R11, g) + MULALU R0, R6, (R14, R12) + MULALU R0, R7, (R11, g) + MULALU R4, R7, (R14, R12) + ADD R2<<2, R2, R2 + ADD R1<<2, R1, R1 + MULALU R4, R8, (R11, g) + MULALU R3, R8, (R14, R12) + MULALU R3, R9, (R11, g) + MULALU R2, R9, (R14, R12) + MOVW g, 60(R13) + MOVW R11, 64(R13) + MOVW R12, 52(R13) + MOVW R14, 56(R13) + MULLU R0, R5, (R11, g) + MULALU R4, R6, (R11, g) + MULALU R3, R7, (R11, g) + MULALU R2, R8, (R11, g) + MULALU R1, R9, (R11, g) + ADD $52, R13, R0 + MOVM.IA (R0), [R0-R7] + MOVW g>>26, R12 + MOVW R4>>26, R14 + ORR R11<<6, R12, R12 + ORR R5<<6, R14, R14 + BIC $0xfc000000, g, g + BIC $0xfc000000, R4, R4 + ADD.S R12, R0, R0 + ADC $0, R1, R1 + ADD.S R14, R6, R6 + ADC $0, R7, R7 + MOVW R0>>26, R12 + MOVW R6>>26, R14 + ORR R1<<6, R12, R12 + ORR R7<<6, R14, R14 + BIC $0xfc000000, R0, R0 + BIC $0xfc000000, R6, R6 + ADD R14<<2, R14, R14 + ADD.S R12, R2, R2 + ADC $0, R3, R3 + ADD R14, g, g + MOVW R2>>26, R12 + MOVW g>>26, R14 + ORR R3<<6, R12, R12 + BIC $0xfc000000, g, R5 + BIC $0xfc000000, R2, R7 + ADD R12, R4, R4 + ADD R14, R0, R0 + MOVW R4>>26, R12 + BIC $0xfc000000, R4, R8 + ADD R12, R6, R9 + MOVW 96(R13), R12 + MOVW 92(R13), R14 + MOVW R0, R6 + CMP $32, R12 + SUB $16, R12, R12 + MOVW R12, 96(R13) + BHS poly1305_blocks_armv6_mainloop + +poly1305_blocks_armv6_done: + MOVW 88(R13), R12 + MOVW R5, 20(R12) + MOVW R6, 24(R12) + MOVW R7, 28(R12) + MOVW R8, 32(R12) + MOVW R9, 36(R12) + ADD $48, R13, R0 + MOVM.DA (R0), [R4-R8, R14] + RET + +#define MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) \ + MOVBU.P 1(Rsrc), Rtmp; \ + MOVBU.P Rtmp, 1(Rdst); \ + MOVBU.P 1(Rsrc), Rtmp; \ + MOVBU.P Rtmp, 1(Rdst) + +#define MOVWP_UNALIGNED(Rsrc, Rdst, Rtmp) \ + MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp); \ + MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) + +// func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]key) +TEXT ·poly1305_auth_armv6(SB), $196-16 + // The value 196, just above, is the sum of 64 (the size of the context + // structure) and 132 (the amount of stack needed). + // + // At this point, the stack pointer (R13) has been moved down. It + // points to the saved link register and there's 196 bytes of free + // space above it. + // + // The stack for this function looks like: + // + // +--------------------- + // | + // | 64 bytes of context structure + // | + // +--------------------- + // | + // | 112 bytes for poly1305_blocks_armv6 + // | + // +--------------------- + // | 16 bytes of final block, constructed at + // | poly1305_finish_ext_armv6_skip8 + // +--------------------- + // | four bytes of saved 'g' + // +--------------------- + // | lr, saved by prelude <- R13 points here + // +--------------------- + MOVW g, 4(R13) + + MOVW out+0(FP), R4 + MOVW m+4(FP), R5 + MOVW mlen+8(FP), R6 + MOVW key+12(FP), R7 + + ADD $136, R13, R0 // 136 = 4 + 4 + 16 + 112 + MOVW R7, R1 + + // poly1305_init_ext_armv6 will write to the stack from R13+4, but + // that's ok because none of the other values have been written yet. + BL poly1305_init_ext_armv6<>(SB) + BIC.S $15, R6, R2 + BEQ poly1305_auth_armv6_noblocks + ADD $136, R13, R0 + MOVW R5, R1 + ADD R2, R5, R5 + SUB R2, R6, R6 + BL poly1305_blocks_armv6<>(SB) + +poly1305_auth_armv6_noblocks: + ADD $136, R13, R0 + MOVW R5, R1 + MOVW R6, R2 + MOVW R4, R3 + + MOVW R0, R5 + MOVW R1, R6 + MOVW R2, R7 + MOVW R3, R8 + AND.S R2, R2, R2 + BEQ poly1305_finish_ext_armv6_noremaining + EOR R0, R0 + ADD $8, R13, R9 // 8 = offset to 16 byte scratch space + MOVW R0, (R9) + MOVW R0, 4(R9) + MOVW R0, 8(R9) + MOVW R0, 12(R9) + WORD $0xe3110003 // TST R1, #3 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_aligned + WORD $0xe3120008 // TST R2, #8 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip8 + MOVWP_UNALIGNED(R1, R9, g) + MOVWP_UNALIGNED(R1, R9, g) + +poly1305_finish_ext_armv6_skip8: + WORD $0xe3120004 // TST $4, R2 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip4 + MOVWP_UNALIGNED(R1, R9, g) + +poly1305_finish_ext_armv6_skip4: + WORD $0xe3120002 // TST $2, R2 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip2 + MOVHUP_UNALIGNED(R1, R9, g) + B poly1305_finish_ext_armv6_skip2 + +poly1305_finish_ext_armv6_aligned: + WORD $0xe3120008 // TST R2, #8 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip8_aligned + MOVM.IA.W (R1), [g-R11] + MOVM.IA.W [g-R11], (R9) + +poly1305_finish_ext_armv6_skip8_aligned: + WORD $0xe3120004 // TST $4, R2 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip4_aligned + MOVW.P 4(R1), g + MOVW.P g, 4(R9) + +poly1305_finish_ext_armv6_skip4_aligned: + WORD $0xe3120002 // TST $2, R2 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip2 + MOVHU.P 2(R1), g + MOVH.P g, 2(R9) + +poly1305_finish_ext_armv6_skip2: + WORD $0xe3120001 // TST $1, R2 not working see issue 5921 + BEQ poly1305_finish_ext_armv6_skip1 + MOVBU.P 1(R1), g + MOVBU.P g, 1(R9) + +poly1305_finish_ext_armv6_skip1: + MOVW $1, R11 + MOVBU R11, 0(R9) + MOVW R11, 56(R5) + MOVW R5, R0 + ADD $8, R13, R1 + MOVW $16, R2 + BL poly1305_blocks_armv6<>(SB) + +poly1305_finish_ext_armv6_noremaining: + MOVW 20(R5), R0 + MOVW 24(R5), R1 + MOVW 28(R5), R2 + MOVW 32(R5), R3 + MOVW 36(R5), R4 + MOVW R4>>26, R12 + BIC $0xfc000000, R4, R4 + ADD R12<<2, R12, R12 + ADD R12, R0, R0 + MOVW R0>>26, R12 + BIC $0xfc000000, R0, R0 + ADD R12, R1, R1 + MOVW R1>>26, R12 + BIC $0xfc000000, R1, R1 + ADD R12, R2, R2 + MOVW R2>>26, R12 + BIC $0xfc000000, R2, R2 + ADD R12, R3, R3 + MOVW R3>>26, R12 + BIC $0xfc000000, R3, R3 + ADD R12, R4, R4 + ADD $5, R0, R6 + MOVW R6>>26, R12 + BIC $0xfc000000, R6, R6 + ADD R12, R1, R7 + MOVW R7>>26, R12 + BIC $0xfc000000, R7, R7 + ADD R12, R2, g + MOVW g>>26, R12 + BIC $0xfc000000, g, g + ADD R12, R3, R11 + MOVW $-(1<<26), R12 + ADD R11>>26, R12, R12 + BIC $0xfc000000, R11, R11 + ADD R12, R4, R9 + MOVW R9>>31, R12 + SUB $1, R12 + AND R12, R6, R6 + AND R12, R7, R7 + AND R12, g, g + AND R12, R11, R11 + AND R12, R9, R9 + MVN R12, R12 + AND R12, R0, R0 + AND R12, R1, R1 + AND R12, R2, R2 + AND R12, R3, R3 + AND R12, R4, R4 + ORR R6, R0, R0 + ORR R7, R1, R1 + ORR g, R2, R2 + ORR R11, R3, R3 + ORR R9, R4, R4 + ORR R1<<26, R0, R0 + MOVW R1>>6, R1 + ORR R2<<20, R1, R1 + MOVW R2>>12, R2 + ORR R3<<14, R2, R2 + MOVW R3>>18, R3 + ORR R4<<8, R3, R3 + MOVW 40(R5), R6 + MOVW 44(R5), R7 + MOVW 48(R5), g + MOVW 52(R5), R11 + ADD.S R6, R0, R0 + ADC.S R7, R1, R1 + ADC.S g, R2, R2 + ADC.S R11, R3, R3 + MOVM.IA [R0-R3], (R8) + MOVW R5, R12 + EOR R0, R0, R0 + EOR R1, R1, R1 + EOR R2, R2, R2 + EOR R3, R3, R3 + EOR R4, R4, R4 + EOR R5, R5, R5 + EOR R6, R6, R6 + EOR R7, R7, R7 + MOVM.IA.W [R0-R7], (R12) + MOVM.IA [R0-R7], (R12) + MOVW 4(R13), g + RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_generic.go b/vendor/golang.org/x/crypto/poly1305/sum_generic.go new file mode 100644 index 000000000..bab76ef0d --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_generic.go @@ -0,0 +1,172 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package poly1305 + +import "encoding/binary" + +const ( + msgBlock = uint32(1 << 24) + finalBlock = uint32(0) +) + +// sumGeneric generates an authenticator for msg using a one-time key and +// puts the 16-byte result into out. This is the generic implementation of +// Sum and should be called if no assembly implementation is available. +func sumGeneric(out *[TagSize]byte, msg []byte, key *[32]byte) { + h := newMACGeneric(key) + h.Write(msg) + h.Sum(out) +} + +func newMACGeneric(key *[32]byte) (h macGeneric) { + h.r[0] = binary.LittleEndian.Uint32(key[0:]) & 0x3ffffff + h.r[1] = (binary.LittleEndian.Uint32(key[3:]) >> 2) & 0x3ffff03 + h.r[2] = (binary.LittleEndian.Uint32(key[6:]) >> 4) & 0x3ffc0ff + h.r[3] = (binary.LittleEndian.Uint32(key[9:]) >> 6) & 0x3f03fff + h.r[4] = (binary.LittleEndian.Uint32(key[12:]) >> 8) & 0x00fffff + + h.s[0] = binary.LittleEndian.Uint32(key[16:]) + h.s[1] = binary.LittleEndian.Uint32(key[20:]) + h.s[2] = binary.LittleEndian.Uint32(key[24:]) + h.s[3] = binary.LittleEndian.Uint32(key[28:]) + return +} + +type macGeneric struct { + h, r [5]uint32 + s [4]uint32 + + buffer [TagSize]byte + offset int +} + +func (h *macGeneric) Write(p []byte) (n int, err error) { + n = len(p) + if h.offset > 0 { + remaining := TagSize - h.offset + if n < remaining { + h.offset += copy(h.buffer[h.offset:], p) + return n, nil + } + copy(h.buffer[h.offset:], p[:remaining]) + p = p[remaining:] + h.offset = 0 + updateGeneric(h.buffer[:], msgBlock, &(h.h), &(h.r)) + } + if nn := len(p) - (len(p) % TagSize); nn > 0 { + updateGeneric(p, msgBlock, &(h.h), &(h.r)) + p = p[nn:] + } + if len(p) > 0 { + h.offset += copy(h.buffer[h.offset:], p) + } + return n, nil +} + +func (h *macGeneric) Sum(out *[16]byte) { + H, R := h.h, h.r + if h.offset > 0 { + var buffer [TagSize]byte + copy(buffer[:], h.buffer[:h.offset]) + buffer[h.offset] = 1 // invariant: h.offset < TagSize + updateGeneric(buffer[:], finalBlock, &H, &R) + } + finalizeGeneric(out, &H, &(h.s)) +} + +func updateGeneric(msg []byte, flag uint32, h, r *[5]uint32) { + h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] + r0, r1, r2, r3, r4 := uint64(r[0]), uint64(r[1]), uint64(r[2]), uint64(r[3]), uint64(r[4]) + R1, R2, R3, R4 := r1*5, r2*5, r3*5, r4*5 + + for len(msg) >= TagSize { + // h += msg + h0 += binary.LittleEndian.Uint32(msg[0:]) & 0x3ffffff + h1 += (binary.LittleEndian.Uint32(msg[3:]) >> 2) & 0x3ffffff + h2 += (binary.LittleEndian.Uint32(msg[6:]) >> 4) & 0x3ffffff + h3 += (binary.LittleEndian.Uint32(msg[9:]) >> 6) & 0x3ffffff + h4 += (binary.LittleEndian.Uint32(msg[12:]) >> 8) | flag + + // h *= r + d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1) + d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2) + d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3) + d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4) + d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0) + + // h %= p + h0 = uint32(d0) & 0x3ffffff + h1 = uint32(d1) & 0x3ffffff + h2 = uint32(d2) & 0x3ffffff + h3 = uint32(d3) & 0x3ffffff + h4 = uint32(d4) & 0x3ffffff + + h0 += uint32(d4>>26) * 5 + h1 += h0 >> 26 + h0 = h0 & 0x3ffffff + + msg = msg[TagSize:] + } + + h[0], h[1], h[2], h[3], h[4] = h0, h1, h2, h3, h4 +} + +func finalizeGeneric(out *[TagSize]byte, h *[5]uint32, s *[4]uint32) { + h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] + + // h %= p reduction + h2 += h1 >> 26 + h1 &= 0x3ffffff + h3 += h2 >> 26 + h2 &= 0x3ffffff + h4 += h3 >> 26 + h3 &= 0x3ffffff + h0 += 5 * (h4 >> 26) + h4 &= 0x3ffffff + h1 += h0 >> 26 + h0 &= 0x3ffffff + + // h - p + t0 := h0 + 5 + t1 := h1 + (t0 >> 26) + t2 := h2 + (t1 >> 26) + t3 := h3 + (t2 >> 26) + t4 := h4 + (t3 >> 26) - (1 << 26) + t0 &= 0x3ffffff + t1 &= 0x3ffffff + t2 &= 0x3ffffff + t3 &= 0x3ffffff + + // select h if h < p else h - p + t_mask := (t4 >> 31) - 1 + h_mask := ^t_mask + h0 = (h0 & h_mask) | (t0 & t_mask) + h1 = (h1 & h_mask) | (t1 & t_mask) + h2 = (h2 & h_mask) | (t2 & t_mask) + h3 = (h3 & h_mask) | (t3 & t_mask) + h4 = (h4 & h_mask) | (t4 & t_mask) + + // h %= 2^128 + h0 |= h1 << 26 + h1 = ((h1 >> 6) | (h2 << 20)) + h2 = ((h2 >> 12) | (h3 << 14)) + h3 = ((h3 >> 18) | (h4 << 8)) + + // s: the s part of the key + // tag = (h + s) % (2^128) + t := uint64(h0) + uint64(s[0]) + h0 = uint32(t) + t = uint64(h1) + uint64(s[1]) + (t >> 32) + h1 = uint32(t) + t = uint64(h2) + uint64(s[2]) + (t >> 32) + h2 = uint32(t) + t = uint64(h3) + uint64(s[3]) + (t >> 32) + h3 = uint32(t) + + binary.LittleEndian.PutUint32(out[0:], h0) + binary.LittleEndian.PutUint32(out[4:], h1) + binary.LittleEndian.PutUint32(out[8:], h2) + binary.LittleEndian.PutUint32(out[12:], h3) +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go new file mode 100644 index 000000000..fcdef46ab --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,!go1.11 !arm,!amd64,!s390x gccgo appengine nacl + +package poly1305 + +// Sum generates an authenticator for msg using a one-time key and puts the +// 16-byte result into out. Authenticating two different messages with the same +// key allows an attacker to forge messages at will. +func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) { + h := newMAC(key) + h.Write(msg) + h.Sum(out) +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.go b/vendor/golang.org/x/crypto/poly1305/sum_s390x.go new file mode 100644 index 000000000..ec99e07e9 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_s390x.go @@ -0,0 +1,42 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,go1.11,!gccgo,!appengine + +package poly1305 + +import ( + "golang.org/x/sys/cpu" +) + +// poly1305vx is an assembly implementation of Poly1305 that uses vector +// instructions. It must only be called if the vector facility (vx) is +// available. +//go:noescape +func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]byte) + +// poly1305vmsl is an assembly implementation of Poly1305 that uses vector +// instructions, including VMSL. It must only be called if the vector facility (vx) is +// available and if VMSL is supported. +//go:noescape +func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]byte) + +// Sum generates an authenticator for m using a one-time key and puts the +// 16-byte result into out. Authenticating two different messages with the same +// key allows an attacker to forge messages at will. +func Sum(out *[16]byte, m []byte, key *[32]byte) { + if cpu.S390X.HasVX { + var mPtr *byte + if len(m) > 0 { + mPtr = &m[0] + } + if cpu.S390X.HasVXE && len(m) > 256 { + poly1305vmsl(out, mPtr, uint64(len(m)), key) + } else { + poly1305vx(out, mPtr, uint64(len(m)), key) + } + } else { + sumGeneric(out, m, key) + } +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_s390x.s new file mode 100644 index 000000000..ca5a309d8 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_s390x.s @@ -0,0 +1,378 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,go1.11,!gccgo,!appengine + +#include "textflag.h" + +// Implementation of Poly1305 using the vector facility (vx). + +// constants +#define MOD26 V0 +#define EX0 V1 +#define EX1 V2 +#define EX2 V3 + +// temporaries +#define T_0 V4 +#define T_1 V5 +#define T_2 V6 +#define T_3 V7 +#define T_4 V8 + +// key (r) +#define R_0 V9 +#define R_1 V10 +#define R_2 V11 +#define R_3 V12 +#define R_4 V13 +#define R5_1 V14 +#define R5_2 V15 +#define R5_3 V16 +#define R5_4 V17 +#define RSAVE_0 R5 +#define RSAVE_1 R6 +#define RSAVE_2 R7 +#define RSAVE_3 R8 +#define RSAVE_4 R9 +#define R5SAVE_1 V28 +#define R5SAVE_2 V29 +#define R5SAVE_3 V30 +#define R5SAVE_4 V31 + +// message block +#define F_0 V18 +#define F_1 V19 +#define F_2 V20 +#define F_3 V21 +#define F_4 V22 + +// accumulator +#define H_0 V23 +#define H_1 V24 +#define H_2 V25 +#define H_3 V26 +#define H_4 V27 + +GLOBL ·keyMask<>(SB), RODATA, $16 +DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f +DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f + +GLOBL ·bswapMask<>(SB), RODATA, $16 +DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 +DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 + +GLOBL ·constants<>(SB), RODATA, $64 +// MOD26 +DATA ·constants<>+0(SB)/8, $0x3ffffff +DATA ·constants<>+8(SB)/8, $0x3ffffff +// EX0 +DATA ·constants<>+16(SB)/8, $0x0006050403020100 +DATA ·constants<>+24(SB)/8, $0x1016151413121110 +// EX1 +DATA ·constants<>+32(SB)/8, $0x060c0b0a09080706 +DATA ·constants<>+40(SB)/8, $0x161c1b1a19181716 +// EX2 +DATA ·constants<>+48(SB)/8, $0x0d0d0d0d0d0f0e0d +DATA ·constants<>+56(SB)/8, $0x1d1d1d1d1d1f1e1d + +// h = (f*g) % (2**130-5) [partial reduction] +#define MULTIPLY(f0, f1, f2, f3, f4, g0, g1, g2, g3, g4, g51, g52, g53, g54, h0, h1, h2, h3, h4) \ + VMLOF f0, g0, h0 \ + VMLOF f0, g1, h1 \ + VMLOF f0, g2, h2 \ + VMLOF f0, g3, h3 \ + VMLOF f0, g4, h4 \ + VMLOF f1, g54, T_0 \ + VMLOF f1, g0, T_1 \ + VMLOF f1, g1, T_2 \ + VMLOF f1, g2, T_3 \ + VMLOF f1, g3, T_4 \ + VMALOF f2, g53, h0, h0 \ + VMALOF f2, g54, h1, h1 \ + VMALOF f2, g0, h2, h2 \ + VMALOF f2, g1, h3, h3 \ + VMALOF f2, g2, h4, h4 \ + VMALOF f3, g52, T_0, T_0 \ + VMALOF f3, g53, T_1, T_1 \ + VMALOF f3, g54, T_2, T_2 \ + VMALOF f3, g0, T_3, T_3 \ + VMALOF f3, g1, T_4, T_4 \ + VMALOF f4, g51, h0, h0 \ + VMALOF f4, g52, h1, h1 \ + VMALOF f4, g53, h2, h2 \ + VMALOF f4, g54, h3, h3 \ + VMALOF f4, g0, h4, h4 \ + VAG T_0, h0, h0 \ + VAG T_1, h1, h1 \ + VAG T_2, h2, h2 \ + VAG T_3, h3, h3 \ + VAG T_4, h4, h4 + +// carry h0->h1 h3->h4, h1->h2 h4->h0, h0->h1 h2->h3, h3->h4 +#define REDUCE(h0, h1, h2, h3, h4) \ + VESRLG $26, h0, T_0 \ + VESRLG $26, h3, T_1 \ + VN MOD26, h0, h0 \ + VN MOD26, h3, h3 \ + VAG T_0, h1, h1 \ + VAG T_1, h4, h4 \ + VESRLG $26, h1, T_2 \ + VESRLG $26, h4, T_3 \ + VN MOD26, h1, h1 \ + VN MOD26, h4, h4 \ + VESLG $2, T_3, T_4 \ + VAG T_3, T_4, T_4 \ + VAG T_2, h2, h2 \ + VAG T_4, h0, h0 \ + VESRLG $26, h2, T_0 \ + VESRLG $26, h0, T_1 \ + VN MOD26, h2, h2 \ + VN MOD26, h0, h0 \ + VAG T_0, h3, h3 \ + VAG T_1, h1, h1 \ + VESRLG $26, h3, T_2 \ + VN MOD26, h3, h3 \ + VAG T_2, h4, h4 + +// expand in0 into d[0] and in1 into d[1] +#define EXPAND(in0, in1, d0, d1, d2, d3, d4) \ + VGBM $0x0707, d1 \ // d1=tmp + VPERM in0, in1, EX2, d4 \ + VPERM in0, in1, EX0, d0 \ + VPERM in0, in1, EX1, d2 \ + VN d1, d4, d4 \ + VESRLG $26, d0, d1 \ + VESRLG $30, d2, d3 \ + VESRLG $4, d2, d2 \ + VN MOD26, d0, d0 \ + VN MOD26, d1, d1 \ + VN MOD26, d2, d2 \ + VN MOD26, d3, d3 + +// pack h4:h0 into h1:h0 (no carry) +#define PACK(h0, h1, h2, h3, h4) \ + VESLG $26, h1, h1 \ + VESLG $26, h3, h3 \ + VO h0, h1, h0 \ + VO h2, h3, h2 \ + VESLG $4, h2, h2 \ + VLEIB $7, $48, h1 \ + VSLB h1, h2, h2 \ + VO h0, h2, h0 \ + VLEIB $7, $104, h1 \ + VSLB h1, h4, h3 \ + VO h3, h0, h0 \ + VLEIB $7, $24, h1 \ + VSRLB h1, h4, h1 + +// if h > 2**130-5 then h -= 2**130-5 +#define MOD(h0, h1, t0, t1, t2) \ + VZERO t0 \ + VLEIG $1, $5, t0 \ + VACCQ h0, t0, t1 \ + VAQ h0, t0, t0 \ + VONE t2 \ + VLEIG $1, $-4, t2 \ + VAQ t2, t1, t1 \ + VACCQ h1, t1, t1 \ + VONE t2 \ + VAQ t2, t1, t1 \ + VN h0, t1, t2 \ + VNC t0, t1, t1 \ + VO t1, t2, h0 + +// func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]key) +TEXT ·poly1305vx(SB), $0-32 + // This code processes up to 2 blocks (32 bytes) per iteration + // using the algorithm described in: + // NEON crypto, Daniel J. Bernstein & Peter Schwabe + // https://cryptojedi.org/papers/neoncrypto-20120320.pdf + LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key + + // load MOD26, EX0, EX1 and EX2 + MOVD $·constants<>(SB), R5 + VLM (R5), MOD26, EX2 + + // setup r + VL (R4), T_0 + MOVD $·keyMask<>(SB), R6 + VL (R6), T_1 + VN T_0, T_1, T_0 + EXPAND(T_0, T_0, R_0, R_1, R_2, R_3, R_4) + + // setup r*5 + VLEIG $0, $5, T_0 + VLEIG $1, $5, T_0 + + // store r (for final block) + VMLOF T_0, R_1, R5SAVE_1 + VMLOF T_0, R_2, R5SAVE_2 + VMLOF T_0, R_3, R5SAVE_3 + VMLOF T_0, R_4, R5SAVE_4 + VLGVG $0, R_0, RSAVE_0 + VLGVG $0, R_1, RSAVE_1 + VLGVG $0, R_2, RSAVE_2 + VLGVG $0, R_3, RSAVE_3 + VLGVG $0, R_4, RSAVE_4 + + // skip r**2 calculation + CMPBLE R3, $16, skip + + // calculate r**2 + MULTIPLY(R_0, R_1, R_2, R_3, R_4, R_0, R_1, R_2, R_3, R_4, R5SAVE_1, R5SAVE_2, R5SAVE_3, R5SAVE_4, H_0, H_1, H_2, H_3, H_4) + REDUCE(H_0, H_1, H_2, H_3, H_4) + VLEIG $0, $5, T_0 + VLEIG $1, $5, T_0 + VMLOF T_0, H_1, R5_1 + VMLOF T_0, H_2, R5_2 + VMLOF T_0, H_3, R5_3 + VMLOF T_0, H_4, R5_4 + VLR H_0, R_0 + VLR H_1, R_1 + VLR H_2, R_2 + VLR H_3, R_3 + VLR H_4, R_4 + + // initialize h + VZERO H_0 + VZERO H_1 + VZERO H_2 + VZERO H_3 + VZERO H_4 + +loop: + CMPBLE R3, $32, b2 + VLM (R2), T_0, T_1 + SUB $32, R3 + MOVD $32(R2), R2 + EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) + VLEIB $4, $1, F_4 + VLEIB $12, $1, F_4 + +multiply: + VAG H_0, F_0, F_0 + VAG H_1, F_1, F_1 + VAG H_2, F_2, F_2 + VAG H_3, F_3, F_3 + VAG H_4, F_4, F_4 + MULTIPLY(F_0, F_1, F_2, F_3, F_4, R_0, R_1, R_2, R_3, R_4, R5_1, R5_2, R5_3, R5_4, H_0, H_1, H_2, H_3, H_4) + REDUCE(H_0, H_1, H_2, H_3, H_4) + CMPBNE R3, $0, loop + +finish: + // sum vectors + VZERO T_0 + VSUMQG H_0, T_0, H_0 + VSUMQG H_1, T_0, H_1 + VSUMQG H_2, T_0, H_2 + VSUMQG H_3, T_0, H_3 + VSUMQG H_4, T_0, H_4 + + // h may be >= 2*(2**130-5) so we need to reduce it again + REDUCE(H_0, H_1, H_2, H_3, H_4) + + // carry h1->h4 + VESRLG $26, H_1, T_1 + VN MOD26, H_1, H_1 + VAQ T_1, H_2, H_2 + VESRLG $26, H_2, T_2 + VN MOD26, H_2, H_2 + VAQ T_2, H_3, H_3 + VESRLG $26, H_3, T_3 + VN MOD26, H_3, H_3 + VAQ T_3, H_4, H_4 + + // h is now < 2*(2**130-5) + // pack h into h1 (hi) and h0 (lo) + PACK(H_0, H_1, H_2, H_3, H_4) + + // if h > 2**130-5 then h -= 2**130-5 + MOD(H_0, H_1, T_0, T_1, T_2) + + // h += s + MOVD $·bswapMask<>(SB), R5 + VL (R5), T_1 + VL 16(R4), T_0 + VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) + VAQ T_0, H_0, H_0 + VPERM H_0, H_0, T_1, H_0 // reverse bytes (to little) + VST H_0, (R1) + + RET + +b2: + CMPBLE R3, $16, b1 + + // 2 blocks remaining + SUB $17, R3 + VL (R2), T_0 + VLL R3, 16(R2), T_1 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, T_1 + EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) + CMPBNE R3, $16, 2(PC) + VLEIB $12, $1, F_4 + VLEIB $4, $1, F_4 + + // setup [r²,r] + VLVGG $1, RSAVE_0, R_0 + VLVGG $1, RSAVE_1, R_1 + VLVGG $1, RSAVE_2, R_2 + VLVGG $1, RSAVE_3, R_3 + VLVGG $1, RSAVE_4, R_4 + VPDI $0, R5_1, R5SAVE_1, R5_1 + VPDI $0, R5_2, R5SAVE_2, R5_2 + VPDI $0, R5_3, R5SAVE_3, R5_3 + VPDI $0, R5_4, R5SAVE_4, R5_4 + + MOVD $0, R3 + BR multiply + +skip: + VZERO H_0 + VZERO H_1 + VZERO H_2 + VZERO H_3 + VZERO H_4 + + CMPBEQ R3, $0, finish + +b1: + // 1 block remaining + SUB $1, R3 + VLL R3, (R2), T_0 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, T_0 + VZERO T_1 + EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) + CMPBNE R3, $16, 2(PC) + VLEIB $4, $1, F_4 + VLEIG $1, $1, R_0 + VZERO R_1 + VZERO R_2 + VZERO R_3 + VZERO R_4 + VZERO R5_1 + VZERO R5_2 + VZERO R5_3 + VZERO R5_4 + + // setup [r, 1] + VLVGG $0, RSAVE_0, R_0 + VLVGG $0, RSAVE_1, R_1 + VLVGG $0, RSAVE_2, R_2 + VLVGG $0, RSAVE_3, R_3 + VLVGG $0, RSAVE_4, R_4 + VPDI $0, R5SAVE_1, R5_1, R5_1 + VPDI $0, R5SAVE_2, R5_2, R5_2 + VPDI $0, R5SAVE_3, R5_3, R5_3 + VPDI $0, R5SAVE_4, R5_4, R5_4 + + MOVD $0, R3 + BR multiply diff --git a/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s new file mode 100644 index 000000000..e60bbc1d7 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s @@ -0,0 +1,909 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build s390x,go1.11,!gccgo,!appengine + +#include "textflag.h" + +// Implementation of Poly1305 using the vector facility (vx) and the VMSL instruction. + +// constants +#define EX0 V1 +#define EX1 V2 +#define EX2 V3 + +// temporaries +#define T_0 V4 +#define T_1 V5 +#define T_2 V6 +#define T_3 V7 +#define T_4 V8 +#define T_5 V9 +#define T_6 V10 +#define T_7 V11 +#define T_8 V12 +#define T_9 V13 +#define T_10 V14 + +// r**2 & r**4 +#define R_0 V15 +#define R_1 V16 +#define R_2 V17 +#define R5_1 V18 +#define R5_2 V19 +// key (r) +#define RSAVE_0 R7 +#define RSAVE_1 R8 +#define RSAVE_2 R9 +#define R5SAVE_1 R10 +#define R5SAVE_2 R11 + +// message block +#define M0 V20 +#define M1 V21 +#define M2 V22 +#define M3 V23 +#define M4 V24 +#define M5 V25 + +// accumulator +#define H0_0 V26 +#define H1_0 V27 +#define H2_0 V28 +#define H0_1 V29 +#define H1_1 V30 +#define H2_1 V31 + +GLOBL ·keyMask<>(SB), RODATA, $16 +DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f +DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f + +GLOBL ·bswapMask<>(SB), RODATA, $16 +DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 +DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 + +GLOBL ·constants<>(SB), RODATA, $48 +// EX0 +DATA ·constants<>+0(SB)/8, $0x18191a1b1c1d1e1f +DATA ·constants<>+8(SB)/8, $0x0000050403020100 +// EX1 +DATA ·constants<>+16(SB)/8, $0x18191a1b1c1d1e1f +DATA ·constants<>+24(SB)/8, $0x00000a0908070605 +// EX2 +DATA ·constants<>+32(SB)/8, $0x18191a1b1c1d1e1f +DATA ·constants<>+40(SB)/8, $0x0000000f0e0d0c0b + +GLOBL ·c<>(SB), RODATA, $48 +// EX0 +DATA ·c<>+0(SB)/8, $0x0000050403020100 +DATA ·c<>+8(SB)/8, $0x0000151413121110 +// EX1 +DATA ·c<>+16(SB)/8, $0x00000a0908070605 +DATA ·c<>+24(SB)/8, $0x00001a1918171615 +// EX2 +DATA ·c<>+32(SB)/8, $0x0000000f0e0d0c0b +DATA ·c<>+40(SB)/8, $0x0000001f1e1d1c1b + +GLOBL ·reduce<>(SB), RODATA, $32 +// 44 bit +DATA ·reduce<>+0(SB)/8, $0x0 +DATA ·reduce<>+8(SB)/8, $0xfffffffffff +// 42 bit +DATA ·reduce<>+16(SB)/8, $0x0 +DATA ·reduce<>+24(SB)/8, $0x3ffffffffff + +// h = (f*g) % (2**130-5) [partial reduction] +// uses T_0...T_9 temporary registers +// input: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2 +// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9 +// output: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2 +#define MULTIPLY(m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9) \ + \ // Eliminate the dependency for the last 2 VMSLs + VMSLG m02_0, r_2, m4_2, m4_2 \ + VMSLG m13_0, r_2, m5_2, m5_2 \ // 8 VMSLs pipelined + VMSLG m02_0, r_0, m4_0, m4_0 \ + VMSLG m02_1, r5_2, V0, T_0 \ + VMSLG m02_0, r_1, m4_1, m4_1 \ + VMSLG m02_1, r_0, V0, T_1 \ + VMSLG m02_1, r_1, V0, T_2 \ + VMSLG m02_2, r5_1, V0, T_3 \ + VMSLG m02_2, r5_2, V0, T_4 \ + VMSLG m13_0, r_0, m5_0, m5_0 \ + VMSLG m13_1, r5_2, V0, T_5 \ + VMSLG m13_0, r_1, m5_1, m5_1 \ + VMSLG m13_1, r_0, V0, T_6 \ + VMSLG m13_1, r_1, V0, T_7 \ + VMSLG m13_2, r5_1, V0, T_8 \ + VMSLG m13_2, r5_2, V0, T_9 \ + VMSLG m02_2, r_0, m4_2, m4_2 \ + VMSLG m13_2, r_0, m5_2, m5_2 \ + VAQ m4_0, T_0, m02_0 \ + VAQ m4_1, T_1, m02_1 \ + VAQ m5_0, T_5, m13_0 \ + VAQ m5_1, T_6, m13_1 \ + VAQ m02_0, T_3, m02_0 \ + VAQ m02_1, T_4, m02_1 \ + VAQ m13_0, T_8, m13_0 \ + VAQ m13_1, T_9, m13_1 \ + VAQ m4_2, T_2, m02_2 \ + VAQ m5_2, T_7, m13_2 \ + +// SQUARE uses three limbs of r and r_2*5 to output square of r +// uses T_1, T_5 and T_7 temporary registers +// input: r_0, r_1, r_2, r5_2 +// temp: TEMP0, TEMP1, TEMP2 +// output: p0, p1, p2 +#define SQUARE(r_0, r_1, r_2, r5_2, p0, p1, p2, TEMP0, TEMP1, TEMP2) \ + VMSLG r_0, r_0, p0, p0 \ + VMSLG r_1, r5_2, V0, TEMP0 \ + VMSLG r_2, r5_2, p1, p1 \ + VMSLG r_0, r_1, V0, TEMP1 \ + VMSLG r_1, r_1, p2, p2 \ + VMSLG r_0, r_2, V0, TEMP2 \ + VAQ TEMP0, p0, p0 \ + VAQ TEMP1, p1, p1 \ + VAQ TEMP2, p2, p2 \ + VAQ TEMP0, p0, p0 \ + VAQ TEMP1, p1, p1 \ + VAQ TEMP2, p2, p2 \ + +// carry h0->h1->h2->h0 || h3->h4->h5->h3 +// uses T_2, T_4, T_5, T_7, T_8, T_9 +// t6, t7, t8, t9, t10, t11 +// input: h0, h1, h2, h3, h4, h5 +// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11 +// output: h0, h1, h2, h3, h4, h5 +#define REDUCE(h0, h1, h2, h3, h4, h5, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) \ + VLM (R12), t6, t7 \ // 44 and 42 bit clear mask + VLEIB $7, $0x28, t10 \ // 5 byte shift mask + VREPIB $4, t8 \ // 4 bit shift mask + VREPIB $2, t11 \ // 2 bit shift mask + VSRLB t10, h0, t0 \ // h0 byte shift + VSRLB t10, h1, t1 \ // h1 byte shift + VSRLB t10, h2, t2 \ // h2 byte shift + VSRLB t10, h3, t3 \ // h3 byte shift + VSRLB t10, h4, t4 \ // h4 byte shift + VSRLB t10, h5, t5 \ // h5 byte shift + VSRL t8, t0, t0 \ // h0 bit shift + VSRL t8, t1, t1 \ // h2 bit shift + VSRL t11, t2, t2 \ // h2 bit shift + VSRL t8, t3, t3 \ // h3 bit shift + VSRL t8, t4, t4 \ // h4 bit shift + VESLG $2, t2, t9 \ // h2 carry x5 + VSRL t11, t5, t5 \ // h5 bit shift + VN t6, h0, h0 \ // h0 clear carry + VAQ t2, t9, t2 \ // h2 carry x5 + VESLG $2, t5, t9 \ // h5 carry x5 + VN t6, h1, h1 \ // h1 clear carry + VN t7, h2, h2 \ // h2 clear carry + VAQ t5, t9, t5 \ // h5 carry x5 + VN t6, h3, h3 \ // h3 clear carry + VN t6, h4, h4 \ // h4 clear carry + VN t7, h5, h5 \ // h5 clear carry + VAQ t0, h1, h1 \ // h0->h1 + VAQ t3, h4, h4 \ // h3->h4 + VAQ t1, h2, h2 \ // h1->h2 + VAQ t4, h5, h5 \ // h4->h5 + VAQ t2, h0, h0 \ // h2->h0 + VAQ t5, h3, h3 \ // h5->h3 + VREPG $1, t6, t6 \ // 44 and 42 bit masks across both halves + VREPG $1, t7, t7 \ + VSLDB $8, h0, h0, h0 \ // set up [h0/1/2, h3/4/5] + VSLDB $8, h1, h1, h1 \ + VSLDB $8, h2, h2, h2 \ + VO h0, h3, h3 \ + VO h1, h4, h4 \ + VO h2, h5, h5 \ + VESRLG $44, h3, t0 \ // 44 bit shift right + VESRLG $44, h4, t1 \ + VESRLG $42, h5, t2 \ + VN t6, h3, h3 \ // clear carry bits + VN t6, h4, h4 \ + VN t7, h5, h5 \ + VESLG $2, t2, t9 \ // multiply carry by 5 + VAQ t9, t2, t2 \ + VAQ t0, h4, h4 \ + VAQ t1, h5, h5 \ + VAQ t2, h3, h3 \ + +// carry h0->h1->h2->h0 +// input: h0, h1, h2 +// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8 +// output: h0, h1, h2 +#define REDUCE2(h0, h1, h2, t0, t1, t2, t3, t4, t5, t6, t7, t8) \ + VLEIB $7, $0x28, t3 \ // 5 byte shift mask + VREPIB $4, t4 \ // 4 bit shift mask + VREPIB $2, t7 \ // 2 bit shift mask + VGBM $0x003F, t5 \ // mask to clear carry bits + VSRLB t3, h0, t0 \ + VSRLB t3, h1, t1 \ + VSRLB t3, h2, t2 \ + VESRLG $4, t5, t5 \ // 44 bit clear mask + VSRL t4, t0, t0 \ + VSRL t4, t1, t1 \ + VSRL t7, t2, t2 \ + VESRLG $2, t5, t6 \ // 42 bit clear mask + VESLG $2, t2, t8 \ + VAQ t8, t2, t2 \ + VN t5, h0, h0 \ + VN t5, h1, h1 \ + VN t6, h2, h2 \ + VAQ t0, h1, h1 \ + VAQ t1, h2, h2 \ + VAQ t2, h0, h0 \ + VSRLB t3, h0, t0 \ + VSRLB t3, h1, t1 \ + VSRLB t3, h2, t2 \ + VSRL t4, t0, t0 \ + VSRL t4, t1, t1 \ + VSRL t7, t2, t2 \ + VN t5, h0, h0 \ + VN t5, h1, h1 \ + VESLG $2, t2, t8 \ + VN t6, h2, h2 \ + VAQ t0, h1, h1 \ + VAQ t8, t2, t2 \ + VAQ t1, h2, h2 \ + VAQ t2, h0, h0 \ + +// expands two message blocks into the lower halfs of the d registers +// moves the contents of the d registers into upper halfs +// input: in1, in2, d0, d1, d2, d3, d4, d5 +// temp: TEMP0, TEMP1, TEMP2, TEMP3 +// output: d0, d1, d2, d3, d4, d5 +#define EXPACC(in1, in2, d0, d1, d2, d3, d4, d5, TEMP0, TEMP1, TEMP2, TEMP3) \ + VGBM $0xff3f, TEMP0 \ + VGBM $0xff1f, TEMP1 \ + VESLG $4, d1, TEMP2 \ + VESLG $4, d4, TEMP3 \ + VESRLG $4, TEMP0, TEMP0 \ + VPERM in1, d0, EX0, d0 \ + VPERM in2, d3, EX0, d3 \ + VPERM in1, d2, EX2, d2 \ + VPERM in2, d5, EX2, d5 \ + VPERM in1, TEMP2, EX1, d1 \ + VPERM in2, TEMP3, EX1, d4 \ + VN TEMP0, d0, d0 \ + VN TEMP0, d3, d3 \ + VESRLG $4, d1, d1 \ + VESRLG $4, d4, d4 \ + VN TEMP1, d2, d2 \ + VN TEMP1, d5, d5 \ + VN TEMP0, d1, d1 \ + VN TEMP0, d4, d4 \ + +// expands one message block into the lower halfs of the d registers +// moves the contents of the d registers into upper halfs +// input: in, d0, d1, d2 +// temp: TEMP0, TEMP1, TEMP2 +// output: d0, d1, d2 +#define EXPACC2(in, d0, d1, d2, TEMP0, TEMP1, TEMP2) \ + VGBM $0xff3f, TEMP0 \ + VESLG $4, d1, TEMP2 \ + VGBM $0xff1f, TEMP1 \ + VPERM in, d0, EX0, d0 \ + VESRLG $4, TEMP0, TEMP0 \ + VPERM in, d2, EX2, d2 \ + VPERM in, TEMP2, EX1, d1 \ + VN TEMP0, d0, d0 \ + VN TEMP1, d2, d2 \ + VESRLG $4, d1, d1 \ + VN TEMP0, d1, d1 \ + +// pack h2:h0 into h1:h0 (no carry) +// input: h0, h1, h2 +// output: h0, h1, h2 +#define PACK(h0, h1, h2) \ + VMRLG h1, h2, h2 \ // copy h1 to upper half h2 + VESLG $44, h1, h1 \ // shift limb 1 44 bits, leaving 20 + VO h0, h1, h0 \ // combine h0 with 20 bits from limb 1 + VESRLG $20, h2, h1 \ // put top 24 bits of limb 1 into h1 + VLEIG $1, $0, h1 \ // clear h2 stuff from lower half of h1 + VO h0, h1, h0 \ // h0 now has 88 bits (limb 0 and 1) + VLEIG $0, $0, h2 \ // clear upper half of h2 + VESRLG $40, h2, h1 \ // h1 now has upper two bits of result + VLEIB $7, $88, h1 \ // for byte shift (11 bytes) + VSLB h1, h2, h2 \ // shift h2 11 bytes to the left + VO h0, h2, h0 \ // combine h0 with 20 bits from limb 1 + VLEIG $0, $0, h1 \ // clear upper half of h1 + +// if h > 2**130-5 then h -= 2**130-5 +// input: h0, h1 +// temp: t0, t1, t2 +// output: h0 +#define MOD(h0, h1, t0, t1, t2) \ + VZERO t0 \ + VLEIG $1, $5, t0 \ + VACCQ h0, t0, t1 \ + VAQ h0, t0, t0 \ + VONE t2 \ + VLEIG $1, $-4, t2 \ + VAQ t2, t1, t1 \ + VACCQ h1, t1, t1 \ + VONE t2 \ + VAQ t2, t1, t1 \ + VN h0, t1, t2 \ + VNC t0, t1, t1 \ + VO t1, t2, h0 \ + +// func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]key) +TEXT ·poly1305vmsl(SB), $0-32 + // This code processes 6 + up to 4 blocks (32 bytes) per iteration + // using the algorithm described in: + // NEON crypto, Daniel J. Bernstein & Peter Schwabe + // https://cryptojedi.org/papers/neoncrypto-20120320.pdf + // And as moddified for VMSL as described in + // Accelerating Poly1305 Cryptographic Message Authentication on the z14 + // O'Farrell et al, CASCON 2017, p48-55 + // https://ibm.ent.box.com/s/jf9gedj0e9d2vjctfyh186shaztavnht + + LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key + VZERO V0 // c + + // load EX0, EX1 and EX2 + MOVD $·constants<>(SB), R5 + VLM (R5), EX0, EX2 // c + + // setup r + VL (R4), T_0 + MOVD $·keyMask<>(SB), R6 + VL (R6), T_1 + VN T_0, T_1, T_0 + VZERO T_2 // limbs for r + VZERO T_3 + VZERO T_4 + EXPACC2(T_0, T_2, T_3, T_4, T_1, T_5, T_7) + + // T_2, T_3, T_4: [0, r] + + // setup r*20 + VLEIG $0, $0, T_0 + VLEIG $1, $20, T_0 // T_0: [0, 20] + VZERO T_5 + VZERO T_6 + VMSLG T_0, T_3, T_5, T_5 + VMSLG T_0, T_4, T_6, T_6 + + // store r for final block in GR + VLGVG $1, T_2, RSAVE_0 // c + VLGVG $1, T_3, RSAVE_1 // c + VLGVG $1, T_4, RSAVE_2 // c + VLGVG $1, T_5, R5SAVE_1 // c + VLGVG $1, T_6, R5SAVE_2 // c + + // initialize h + VZERO H0_0 + VZERO H1_0 + VZERO H2_0 + VZERO H0_1 + VZERO H1_1 + VZERO H2_1 + + // initialize pointer for reduce constants + MOVD $·reduce<>(SB), R12 + + // calculate r**2 and 20*(r**2) + VZERO R_0 + VZERO R_1 + VZERO R_2 + SQUARE(T_2, T_3, T_4, T_6, R_0, R_1, R_2, T_1, T_5, T_7) + REDUCE2(R_0, R_1, R_2, M0, M1, M2, M3, M4, R5_1, R5_2, M5, T_1) + VZERO R5_1 + VZERO R5_2 + VMSLG T_0, R_1, R5_1, R5_1 + VMSLG T_0, R_2, R5_2, R5_2 + + // skip r**4 calculation if 3 blocks or less + CMPBLE R3, $48, b4 + + // calculate r**4 and 20*(r**4) + VZERO T_8 + VZERO T_9 + VZERO T_10 + SQUARE(R_0, R_1, R_2, R5_2, T_8, T_9, T_10, T_1, T_5, T_7) + REDUCE2(T_8, T_9, T_10, M0, M1, M2, M3, M4, T_2, T_3, M5, T_1) + VZERO T_2 + VZERO T_3 + VMSLG T_0, T_9, T_2, T_2 + VMSLG T_0, T_10, T_3, T_3 + + // put r**2 to the right and r**4 to the left of R_0, R_1, R_2 + VSLDB $8, T_8, T_8, T_8 + VSLDB $8, T_9, T_9, T_9 + VSLDB $8, T_10, T_10, T_10 + VSLDB $8, T_2, T_2, T_2 + VSLDB $8, T_3, T_3, T_3 + + VO T_8, R_0, R_0 + VO T_9, R_1, R_1 + VO T_10, R_2, R_2 + VO T_2, R5_1, R5_1 + VO T_3, R5_2, R5_2 + + CMPBLE R3, $80, load // less than or equal to 5 blocks in message + + // 6(or 5+1) blocks + SUB $81, R3 + VLM (R2), M0, M4 + VLL R3, 80(R2), M5 + ADD $1, R3 + MOVBZ $1, R0 + CMPBGE R3, $16, 2(PC) + VLVGB R3, R0, M5 + MOVD $96(R2), R2 + EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) + EXPACC(M2, M3, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) + VLEIB $2, $1, H2_0 + VLEIB $2, $1, H2_1 + VLEIB $10, $1, H2_0 + VLEIB $10, $1, H2_1 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO T_4 + VZERO T_10 + EXPACC(M4, M5, M0, M1, M2, M3, T_4, T_10, T_0, T_1, T_2, T_3) + VLR T_4, M4 + VLEIB $10, $1, M2 + CMPBLT R3, $16, 2(PC) + VLEIB $10, $1, T_10 + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) + VMRHG V0, H0_1, H0_0 + VMRHG V0, H1_1, H1_0 + VMRHG V0, H2_1, H2_0 + VMRLG V0, H0_1, H0_1 + VMRLG V0, H1_1, H1_1 + VMRLG V0, H2_1, H2_1 + + SUB $16, R3 + CMPBLE R3, $0, square + +load: + // load EX0, EX1 and EX2 + MOVD $·c<>(SB), R5 + VLM (R5), EX0, EX2 + +loop: + CMPBLE R3, $64, add // b4 // last 4 or less blocks left + + // next 4 full blocks + VLM (R2), M2, M5 + SUB $64, R3 + MOVD $64(R2), R2 + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, T_0, T_1, T_3, T_4, T_5, T_2, T_7, T_8, T_9) + + // expacc in-lined to create [m2, m3] limbs + VGBM $0x3f3f, T_0 // 44 bit clear mask + VGBM $0x1f1f, T_1 // 40 bit clear mask + VPERM M2, M3, EX0, T_3 + VESRLG $4, T_0, T_0 // 44 bit clear mask ready + VPERM M2, M3, EX1, T_4 + VPERM M2, M3, EX2, T_5 + VN T_0, T_3, T_3 + VESRLG $4, T_4, T_4 + VN T_1, T_5, T_5 + VN T_0, T_4, T_4 + VMRHG H0_1, T_3, H0_0 + VMRHG H1_1, T_4, H1_0 + VMRHG H2_1, T_5, H2_0 + VMRLG H0_1, T_3, H0_1 + VMRLG H1_1, T_4, H1_1 + VMRLG H2_1, T_5, H2_1 + VLEIB $10, $1, H2_0 + VLEIB $10, $1, H2_1 + VPERM M4, M5, EX0, T_3 + VPERM M4, M5, EX1, T_4 + VPERM M4, M5, EX2, T_5 + VN T_0, T_3, T_3 + VESRLG $4, T_4, T_4 + VN T_1, T_5, T_5 + VN T_0, T_4, T_4 + VMRHG V0, T_3, M0 + VMRHG V0, T_4, M1 + VMRHG V0, T_5, M2 + VMRLG V0, T_3, M3 + VMRLG V0, T_4, M4 + VMRLG V0, T_5, M5 + VLEIB $10, $1, M2 + VLEIB $10, $1, M5 + + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + CMPBNE R3, $0, loop + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) + VMRHG V0, H0_1, H0_0 + VMRHG V0, H1_1, H1_0 + VMRHG V0, H2_1, H2_0 + VMRLG V0, H0_1, H0_1 + VMRLG V0, H1_1, H1_1 + VMRLG V0, H2_1, H2_1 + + // load EX0, EX1, EX2 + MOVD $·constants<>(SB), R5 + VLM (R5), EX0, EX2 + + // sum vectors + VAQ H0_0, H0_1, H0_0 + VAQ H1_0, H1_1, H1_0 + VAQ H2_0, H2_1, H2_0 + + // h may be >= 2*(2**130-5) so we need to reduce it again + // M0...M4 are used as temps here + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) + +next: // carry h1->h2 + VLEIB $7, $0x28, T_1 + VREPIB $4, T_2 + VGBM $0x003F, T_3 + VESRLG $4, T_3 + + // byte shift + VSRLB T_1, H1_0, T_4 + + // bit shift + VSRL T_2, T_4, T_4 + + // clear h1 carry bits + VN T_3, H1_0, H1_0 + + // add carry + VAQ T_4, H2_0, H2_0 + + // h is now < 2*(2**130-5) + // pack h into h1 (hi) and h0 (lo) + PACK(H0_0, H1_0, H2_0) + + // if h > 2**130-5 then h -= 2**130-5 + MOD(H0_0, H1_0, T_0, T_1, T_2) + + // h += s + MOVD $·bswapMask<>(SB), R5 + VL (R5), T_1 + VL 16(R4), T_0 + VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) + VAQ T_0, H0_0, H0_0 + VPERM H0_0, H0_0, T_1, H0_0 // reverse bytes (to little) + VST H0_0, (R1) + RET + +add: + // load EX0, EX1, EX2 + MOVD $·constants<>(SB), R5 + VLM (R5), EX0, EX2 + + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) + VMRHG V0, H0_1, H0_0 + VMRHG V0, H1_1, H1_0 + VMRHG V0, H2_1, H2_0 + VMRLG V0, H0_1, H0_1 + VMRLG V0, H1_1, H1_1 + VMRLG V0, H2_1, H2_1 + CMPBLE R3, $64, b4 + +b4: + CMPBLE R3, $48, b3 // 3 blocks or less + + // 4(3+1) blocks remaining + SUB $49, R3 + VLM (R2), M0, M2 + VLL R3, 48(R2), M3 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, M3 + MOVD $64(R2), R2 + EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) + VLEIB $10, $1, H2_0 + VLEIB $10, $1, H2_1 + VZERO M0 + VZERO M1 + VZERO M4 + VZERO M5 + VZERO T_4 + VZERO T_10 + EXPACC(M2, M3, M0, M1, M4, M5, T_4, T_10, T_0, T_1, T_2, T_3) + VLR T_4, M2 + VLEIB $10, $1, M4 + CMPBNE R3, $16, 2(PC) + VLEIB $10, $1, T_10 + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M4, M5, M2, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) + VMRHG V0, H0_1, H0_0 + VMRHG V0, H1_1, H1_0 + VMRHG V0, H2_1, H2_0 + VMRLG V0, H0_1, H0_1 + VMRLG V0, H1_1, H1_1 + VMRLG V0, H2_1, H2_1 + SUB $16, R3 + CMPBLE R3, $0, square // this condition must always hold true! + +b3: + CMPBLE R3, $32, b2 + + // 3 blocks remaining + + // setup [r²,r] + VSLDB $8, R_0, R_0, R_0 + VSLDB $8, R_1, R_1, R_1 + VSLDB $8, R_2, R_2, R_2 + VSLDB $8, R5_1, R5_1, R5_1 + VSLDB $8, R5_2, R5_2, R5_2 + + VLVGG $1, RSAVE_0, R_0 + VLVGG $1, RSAVE_1, R_1 + VLVGG $1, RSAVE_2, R_2 + VLVGG $1, R5SAVE_1, R5_1 + VLVGG $1, R5SAVE_2, R5_2 + + // setup [h0, h1] + VSLDB $8, H0_0, H0_0, H0_0 + VSLDB $8, H1_0, H1_0, H1_0 + VSLDB $8, H2_0, H2_0, H2_0 + VO H0_1, H0_0, H0_0 + VO H1_1, H1_0, H1_0 + VO H2_1, H2_0, H2_0 + VZERO H0_1 + VZERO H1_1 + VZERO H2_1 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + + // H*[r**2, r] + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, T_10, M5) + + SUB $33, R3 + VLM (R2), M0, M1 + VLL R3, 32(R2), M2 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, M2 + + // H += m0 + VZERO T_1 + VZERO T_2 + VZERO T_3 + EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6) + VLEIB $10, $1, T_3 + VAG H0_0, T_1, H0_0 + VAG H1_0, T_2, H1_0 + VAG H2_0, T_3, H2_0 + + VZERO M0 + VZERO M3 + VZERO M4 + VZERO M5 + VZERO T_10 + + // (H+m0)*r + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M3, M4, M5, V0, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_10, H0_1, H1_1, H2_1, T_9) + + // H += m1 + VZERO V0 + VZERO T_1 + VZERO T_2 + VZERO T_3 + EXPACC2(M1, T_1, T_2, T_3, T_4, T_5, T_6) + VLEIB $10, $1, T_3 + VAQ H0_0, T_1, H0_0 + VAQ H1_0, T_2, H1_0 + VAQ H2_0, T_3, H2_0 + REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) + + // [H, m2] * [r**2, r] + EXPACC2(M2, H0_0, H1_0, H2_0, T_1, T_2, T_3) + CMPBNE R3, $16, 2(PC) + VLEIB $10, $1, H2_0 + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, M5, T_10) + SUB $16, R3 + CMPBLE R3, $0, next // this condition must always hold true! + +b2: + CMPBLE R3, $16, b1 + + // 2 blocks remaining + + // setup [r²,r] + VSLDB $8, R_0, R_0, R_0 + VSLDB $8, R_1, R_1, R_1 + VSLDB $8, R_2, R_2, R_2 + VSLDB $8, R5_1, R5_1, R5_1 + VSLDB $8, R5_2, R5_2, R5_2 + + VLVGG $1, RSAVE_0, R_0 + VLVGG $1, RSAVE_1, R_1 + VLVGG $1, RSAVE_2, R_2 + VLVGG $1, R5SAVE_1, R5_1 + VLVGG $1, R5SAVE_2, R5_2 + + // setup [h0, h1] + VSLDB $8, H0_0, H0_0, H0_0 + VSLDB $8, H1_0, H1_0, H1_0 + VSLDB $8, H2_0, H2_0, H2_0 + VO H0_1, H0_0, H0_0 + VO H1_1, H1_0, H1_0 + VO H2_1, H2_0, H2_0 + VZERO H0_1 + VZERO H1_1 + VZERO H2_1 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + + // H*[r**2, r] + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) + VMRHG V0, H0_1, H0_0 + VMRHG V0, H1_1, H1_0 + VMRHG V0, H2_1, H2_0 + VMRLG V0, H0_1, H0_1 + VMRLG V0, H1_1, H1_1 + VMRLG V0, H2_1, H2_1 + + // move h to the left and 0s at the right + VSLDB $8, H0_0, H0_0, H0_0 + VSLDB $8, H1_0, H1_0, H1_0 + VSLDB $8, H2_0, H2_0, H2_0 + + // get message blocks and append 1 to start + SUB $17, R3 + VL (R2), M0 + VLL R3, 16(R2), M1 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, M1 + VZERO T_6 + VZERO T_7 + VZERO T_8 + EXPACC2(M0, T_6, T_7, T_8, T_1, T_2, T_3) + EXPACC2(M1, T_6, T_7, T_8, T_1, T_2, T_3) + VLEIB $2, $1, T_8 + CMPBNE R3, $16, 2(PC) + VLEIB $10, $1, T_8 + + // add [m0, m1] to h + VAG H0_0, T_6, H0_0 + VAG H1_0, T_7, H1_0 + VAG H2_0, T_8, H2_0 + + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + VZERO T_10 + VZERO M0 + + // at this point R_0 .. R5_2 look like [r**2, r] + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M2, M3, M4, M5, T_10, M0, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M2, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) + SUB $16, R3, R3 + CMPBLE R3, $0, next + +b1: + CMPBLE R3, $0, next + + // 1 block remaining + + // setup [r²,r] + VSLDB $8, R_0, R_0, R_0 + VSLDB $8, R_1, R_1, R_1 + VSLDB $8, R_2, R_2, R_2 + VSLDB $8, R5_1, R5_1, R5_1 + VSLDB $8, R5_2, R5_2, R5_2 + + VLVGG $1, RSAVE_0, R_0 + VLVGG $1, RSAVE_1, R_1 + VLVGG $1, RSAVE_2, R_2 + VLVGG $1, R5SAVE_1, R5_1 + VLVGG $1, R5SAVE_2, R5_2 + + // setup [h0, h1] + VSLDB $8, H0_0, H0_0, H0_0 + VSLDB $8, H1_0, H1_0, H1_0 + VSLDB $8, H2_0, H2_0, H2_0 + VO H0_1, H0_0, H0_0 + VO H1_1, H1_0, H1_0 + VO H2_1, H2_0, H2_0 + VZERO H0_1 + VZERO H1_1 + VZERO H2_1 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + + // H*[r**2, r] + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) + + // set up [0, m0] limbs + SUB $1, R3 + VLL R3, (R2), M0 + ADD $1, R3 + MOVBZ $1, R0 + CMPBEQ R3, $16, 2(PC) + VLVGB R3, R0, M0 + VZERO T_1 + VZERO T_2 + VZERO T_3 + EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6)// limbs: [0, m] + CMPBNE R3, $16, 2(PC) + VLEIB $10, $1, T_3 + + // h+m0 + VAQ H0_0, T_1, H0_0 + VAQ H1_0, T_2, H1_0 + VAQ H2_0, T_3, H2_0 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) + + BR next + +square: + // setup [r²,r] + VSLDB $8, R_0, R_0, R_0 + VSLDB $8, R_1, R_1, R_1 + VSLDB $8, R_2, R_2, R_2 + VSLDB $8, R5_1, R5_1, R5_1 + VSLDB $8, R5_2, R5_2, R5_2 + + VLVGG $1, RSAVE_0, R_0 + VLVGG $1, RSAVE_1, R_1 + VLVGG $1, RSAVE_2, R_2 + VLVGG $1, R5SAVE_1, R5_1 + VLVGG $1, R5SAVE_2, R5_2 + + // setup [h0, h1] + VSLDB $8, H0_0, H0_0, H0_0 + VSLDB $8, H1_0, H1_0, H1_0 + VSLDB $8, H2_0, H2_0, H2_0 + VO H0_1, H0_0, H0_0 + VO H1_1, H1_0, H1_0 + VO H2_1, H2_0, H2_0 + VZERO H0_1 + VZERO H1_1 + VZERO H2_1 + + VZERO M0 + VZERO M1 + VZERO M2 + VZERO M3 + VZERO M4 + VZERO M5 + + // (h0*r**2) + (h1*r) + MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) + REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) + BR next diff --git a/vendor/golang.org/x/crypto/ssh/agent/client.go b/vendor/golang.org/x/crypto/ssh/agent/client.go deleted file mode 100644 index acb5ad80e..000000000 --- a/vendor/golang.org/x/crypto/ssh/agent/client.go +++ /dev/null @@ -1,683 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package agent implements the ssh-agent protocol, and provides both -// a client and a server. The client can talk to a standard ssh-agent -// that uses UNIX sockets, and one could implement an alternative -// ssh-agent process using the sample server. -// -// References: -// [PROTOCOL.agent]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent?rev=HEAD -package agent // import "golang.org/x/crypto/ssh/agent" - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/base64" - "encoding/binary" - "errors" - "fmt" - "io" - "math/big" - "sync" - - "golang.org/x/crypto/ed25519" - "golang.org/x/crypto/ssh" -) - -// Agent represents the capabilities of an ssh-agent. -type Agent interface { - // List returns the identities known to the agent. - List() ([]*Key, error) - - // Sign has the agent sign the data using a protocol 2 key as defined - // in [PROTOCOL.agent] section 2.6.2. - Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) - - // Add adds a private key to the agent. - Add(key AddedKey) error - - // Remove removes all identities with the given public key. - Remove(key ssh.PublicKey) error - - // RemoveAll removes all identities. - RemoveAll() error - - // Lock locks the agent. Sign and Remove will fail, and List will empty an empty list. - Lock(passphrase []byte) error - - // Unlock undoes the effect of Lock - Unlock(passphrase []byte) error - - // Signers returns signers for all the known keys. - Signers() ([]ssh.Signer, error) -} - -// ConstraintExtension describes an optional constraint defined by users. -type ConstraintExtension struct { - // ExtensionName consist of a UTF-8 string suffixed by the - // implementation domain following the naming scheme defined - // in Section 4.2 of [RFC4251], e.g. "foo@example.com". - ExtensionName string - // ExtensionDetails contains the actual content of the extended - // constraint. - ExtensionDetails []byte -} - -// AddedKey describes an SSH key to be added to an Agent. -type AddedKey struct { - // PrivateKey must be a *rsa.PrivateKey, *dsa.PrivateKey or - // *ecdsa.PrivateKey, which will be inserted into the agent. - PrivateKey interface{} - // Certificate, if not nil, is communicated to the agent and will be - // stored with the key. - Certificate *ssh.Certificate - // Comment is an optional, free-form string. - Comment string - // LifetimeSecs, if not zero, is the number of seconds that the - // agent will store the key for. - LifetimeSecs uint32 - // ConfirmBeforeUse, if true, requests that the agent confirm with the - // user before each use of this key. - ConfirmBeforeUse bool - // ConstraintExtensions are the experimental or private-use constraints - // defined by users. - ConstraintExtensions []ConstraintExtension -} - -// See [PROTOCOL.agent], section 3. -const ( - agentRequestV1Identities = 1 - agentRemoveAllV1Identities = 9 - - // 3.2 Requests from client to agent for protocol 2 key operations - agentAddIdentity = 17 - agentRemoveIdentity = 18 - agentRemoveAllIdentities = 19 - agentAddIDConstrained = 25 - - // 3.3 Key-type independent requests from client to agent - agentAddSmartcardKey = 20 - agentRemoveSmartcardKey = 21 - agentLock = 22 - agentUnlock = 23 - agentAddSmartcardKeyConstrained = 26 - - // 3.7 Key constraint identifiers - agentConstrainLifetime = 1 - agentConstrainConfirm = 2 - agentConstrainExtension = 3 -) - -// maxAgentResponseBytes is the maximum agent reply size that is accepted. This -// is a sanity check, not a limit in the spec. -const maxAgentResponseBytes = 16 << 20 - -// Agent messages: -// These structures mirror the wire format of the corresponding ssh agent -// messages found in [PROTOCOL.agent]. - -// 3.4 Generic replies from agent to client -const agentFailure = 5 - -type failureAgentMsg struct{} - -const agentSuccess = 6 - -type successAgentMsg struct{} - -// See [PROTOCOL.agent], section 2.5.2. -const agentRequestIdentities = 11 - -type requestIdentitiesAgentMsg struct{} - -// See [PROTOCOL.agent], section 2.5.2. -const agentIdentitiesAnswer = 12 - -type identitiesAnswerAgentMsg struct { - NumKeys uint32 `sshtype:"12"` - Keys []byte `ssh:"rest"` -} - -// See [PROTOCOL.agent], section 2.6.2. -const agentSignRequest = 13 - -type signRequestAgentMsg struct { - KeyBlob []byte `sshtype:"13"` - Data []byte - Flags uint32 -} - -// See [PROTOCOL.agent], section 2.6.2. - -// 3.6 Replies from agent to client for protocol 2 key operations -const agentSignResponse = 14 - -type signResponseAgentMsg struct { - SigBlob []byte `sshtype:"14"` -} - -type publicKey struct { - Format string - Rest []byte `ssh:"rest"` -} - -// 3.7 Key constraint identifiers -type constrainLifetimeAgentMsg struct { - LifetimeSecs uint32 `sshtype:"1"` -} - -type constrainExtensionAgentMsg struct { - ExtensionName string `sshtype:"3"` - ExtensionDetails []byte - - // Rest is a field used for parsing, not part of message - Rest []byte `ssh:"rest"` -} - -// Key represents a protocol 2 public key as defined in -// [PROTOCOL.agent], section 2.5.2. -type Key struct { - Format string - Blob []byte - Comment string -} - -func clientErr(err error) error { - return fmt.Errorf("agent: client error: %v", err) -} - -// String returns the storage form of an agent key with the format, base64 -// encoded serialized key, and the comment if it is not empty. -func (k *Key) String() string { - s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob) - - if k.Comment != "" { - s += " " + k.Comment - } - - return s -} - -// Type returns the public key type. -func (k *Key) Type() string { - return k.Format -} - -// Marshal returns key blob to satisfy the ssh.PublicKey interface. -func (k *Key) Marshal() []byte { - return k.Blob -} - -// Verify satisfies the ssh.PublicKey interface. -func (k *Key) Verify(data []byte, sig *ssh.Signature) error { - pubKey, err := ssh.ParsePublicKey(k.Blob) - if err != nil { - return fmt.Errorf("agent: bad public key: %v", err) - } - return pubKey.Verify(data, sig) -} - -type wireKey struct { - Format string - Rest []byte `ssh:"rest"` -} - -func parseKey(in []byte) (out *Key, rest []byte, err error) { - var record struct { - Blob []byte - Comment string - Rest []byte `ssh:"rest"` - } - - if err := ssh.Unmarshal(in, &record); err != nil { - return nil, nil, err - } - - var wk wireKey - if err := ssh.Unmarshal(record.Blob, &wk); err != nil { - return nil, nil, err - } - - return &Key{ - Format: wk.Format, - Blob: record.Blob, - Comment: record.Comment, - }, record.Rest, nil -} - -// client is a client for an ssh-agent process. -type client struct { - // conn is typically a *net.UnixConn - conn io.ReadWriter - // mu is used to prevent concurrent access to the agent - mu sync.Mutex -} - -// NewClient returns an Agent that talks to an ssh-agent process over -// the given connection. -func NewClient(rw io.ReadWriter) Agent { - return &client{conn: rw} -} - -// call sends an RPC to the agent. On success, the reply is -// unmarshaled into reply and replyType is set to the first byte of -// the reply, which contains the type of the message. -func (c *client) call(req []byte) (reply interface{}, err error) { - c.mu.Lock() - defer c.mu.Unlock() - - msg := make([]byte, 4+len(req)) - binary.BigEndian.PutUint32(msg, uint32(len(req))) - copy(msg[4:], req) - if _, err = c.conn.Write(msg); err != nil { - return nil, clientErr(err) - } - - var respSizeBuf [4]byte - if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil { - return nil, clientErr(err) - } - respSize := binary.BigEndian.Uint32(respSizeBuf[:]) - if respSize > maxAgentResponseBytes { - return nil, clientErr(err) - } - - buf := make([]byte, respSize) - if _, err = io.ReadFull(c.conn, buf); err != nil { - return nil, clientErr(err) - } - reply, err = unmarshal(buf) - if err != nil { - return nil, clientErr(err) - } - return reply, err -} - -func (c *client) simpleCall(req []byte) error { - resp, err := c.call(req) - if err != nil { - return err - } - if _, ok := resp.(*successAgentMsg); ok { - return nil - } - return errors.New("agent: failure") -} - -func (c *client) RemoveAll() error { - return c.simpleCall([]byte{agentRemoveAllIdentities}) -} - -func (c *client) Remove(key ssh.PublicKey) error { - req := ssh.Marshal(&agentRemoveIdentityMsg{ - KeyBlob: key.Marshal(), - }) - return c.simpleCall(req) -} - -func (c *client) Lock(passphrase []byte) error { - req := ssh.Marshal(&agentLockMsg{ - Passphrase: passphrase, - }) - return c.simpleCall(req) -} - -func (c *client) Unlock(passphrase []byte) error { - req := ssh.Marshal(&agentUnlockMsg{ - Passphrase: passphrase, - }) - return c.simpleCall(req) -} - -// List returns the identities known to the agent. -func (c *client) List() ([]*Key, error) { - // see [PROTOCOL.agent] section 2.5.2. - req := []byte{agentRequestIdentities} - - msg, err := c.call(req) - if err != nil { - return nil, err - } - - switch msg := msg.(type) { - case *identitiesAnswerAgentMsg: - if msg.NumKeys > maxAgentResponseBytes/8 { - return nil, errors.New("agent: too many keys in agent reply") - } - keys := make([]*Key, msg.NumKeys) - data := msg.Keys - for i := uint32(0); i < msg.NumKeys; i++ { - var key *Key - var err error - if key, data, err = parseKey(data); err != nil { - return nil, err - } - keys[i] = key - } - return keys, nil - case *failureAgentMsg: - return nil, errors.New("agent: failed to list keys") - } - panic("unreachable") -} - -// Sign has the agent sign the data using a protocol 2 key as defined -// in [PROTOCOL.agent] section 2.6.2. -func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) { - req := ssh.Marshal(signRequestAgentMsg{ - KeyBlob: key.Marshal(), - Data: data, - }) - - msg, err := c.call(req) - if err != nil { - return nil, err - } - - switch msg := msg.(type) { - case *signResponseAgentMsg: - var sig ssh.Signature - if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil { - return nil, err - } - - return &sig, nil - case *failureAgentMsg: - return nil, errors.New("agent: failed to sign challenge") - } - panic("unreachable") -} - -// unmarshal parses an agent message in packet, returning the parsed -// form and the message type of packet. -func unmarshal(packet []byte) (interface{}, error) { - if len(packet) < 1 { - return nil, errors.New("agent: empty packet") - } - var msg interface{} - switch packet[0] { - case agentFailure: - return new(failureAgentMsg), nil - case agentSuccess: - return new(successAgentMsg), nil - case agentIdentitiesAnswer: - msg = new(identitiesAnswerAgentMsg) - case agentSignResponse: - msg = new(signResponseAgentMsg) - case agentV1IdentitiesAnswer: - msg = new(agentV1IdentityMsg) - default: - return nil, fmt.Errorf("agent: unknown type tag %d", packet[0]) - } - if err := ssh.Unmarshal(packet, msg); err != nil { - return nil, err - } - return msg, nil -} - -type rsaKeyMsg struct { - Type string `sshtype:"17|25"` - N *big.Int - E *big.Int - D *big.Int - Iqmp *big.Int // IQMP = Inverse Q Mod P - P *big.Int - Q *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type dsaKeyMsg struct { - Type string `sshtype:"17|25"` - P *big.Int - Q *big.Int - G *big.Int - Y *big.Int - X *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type ecdsaKeyMsg struct { - Type string `sshtype:"17|25"` - Curve string - KeyBytes []byte - D *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type ed25519KeyMsg struct { - Type string `sshtype:"17|25"` - Pub []byte - Priv []byte - Comments string - Constraints []byte `ssh:"rest"` -} - -// Insert adds a private key to the agent. -func (c *client) insertKey(s interface{}, comment string, constraints []byte) error { - var req []byte - switch k := s.(type) { - case *rsa.PrivateKey: - if len(k.Primes) != 2 { - return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes)) - } - k.Precompute() - req = ssh.Marshal(rsaKeyMsg{ - Type: ssh.KeyAlgoRSA, - N: k.N, - E: big.NewInt(int64(k.E)), - D: k.D, - Iqmp: k.Precomputed.Qinv, - P: k.Primes[0], - Q: k.Primes[1], - Comments: comment, - Constraints: constraints, - }) - case *dsa.PrivateKey: - req = ssh.Marshal(dsaKeyMsg{ - Type: ssh.KeyAlgoDSA, - P: k.P, - Q: k.Q, - G: k.G, - Y: k.Y, - X: k.X, - Comments: comment, - Constraints: constraints, - }) - case *ecdsa.PrivateKey: - nistID := fmt.Sprintf("nistp%d", k.Params().BitSize) - req = ssh.Marshal(ecdsaKeyMsg{ - Type: "ecdsa-sha2-" + nistID, - Curve: nistID, - KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y), - D: k.D, - Comments: comment, - Constraints: constraints, - }) - case *ed25519.PrivateKey: - req = ssh.Marshal(ed25519KeyMsg{ - Type: ssh.KeyAlgoED25519, - Pub: []byte(*k)[32:], - Priv: []byte(*k), - Comments: comment, - Constraints: constraints, - }) - default: - return fmt.Errorf("agent: unsupported key type %T", s) - } - - // if constraints are present then the message type needs to be changed. - if len(constraints) != 0 { - req[0] = agentAddIDConstrained - } - - resp, err := c.call(req) - if err != nil { - return err - } - if _, ok := resp.(*successAgentMsg); ok { - return nil - } - return errors.New("agent: failure") -} - -type rsaCertMsg struct { - Type string `sshtype:"17|25"` - CertBytes []byte - D *big.Int - Iqmp *big.Int // IQMP = Inverse Q Mod P - P *big.Int - Q *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type dsaCertMsg struct { - Type string `sshtype:"17|25"` - CertBytes []byte - X *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type ecdsaCertMsg struct { - Type string `sshtype:"17|25"` - CertBytes []byte - D *big.Int - Comments string - Constraints []byte `ssh:"rest"` -} - -type ed25519CertMsg struct { - Type string `sshtype:"17|25"` - CertBytes []byte - Pub []byte - Priv []byte - Comments string - Constraints []byte `ssh:"rest"` -} - -// Add adds a private key to the agent. If a certificate is given, -// that certificate is added instead as public key. -func (c *client) Add(key AddedKey) error { - var constraints []byte - - if secs := key.LifetimeSecs; secs != 0 { - constraints = append(constraints, ssh.Marshal(constrainLifetimeAgentMsg{secs})...) - } - - if key.ConfirmBeforeUse { - constraints = append(constraints, agentConstrainConfirm) - } - - cert := key.Certificate - if cert == nil { - return c.insertKey(key.PrivateKey, key.Comment, constraints) - } - return c.insertCert(key.PrivateKey, cert, key.Comment, constraints) -} - -func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string, constraints []byte) error { - var req []byte - switch k := s.(type) { - case *rsa.PrivateKey: - if len(k.Primes) != 2 { - return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes)) - } - k.Precompute() - req = ssh.Marshal(rsaCertMsg{ - Type: cert.Type(), - CertBytes: cert.Marshal(), - D: k.D, - Iqmp: k.Precomputed.Qinv, - P: k.Primes[0], - Q: k.Primes[1], - Comments: comment, - Constraints: constraints, - }) - case *dsa.PrivateKey: - req = ssh.Marshal(dsaCertMsg{ - Type: cert.Type(), - CertBytes: cert.Marshal(), - X: k.X, - Comments: comment, - Constraints: constraints, - }) - case *ecdsa.PrivateKey: - req = ssh.Marshal(ecdsaCertMsg{ - Type: cert.Type(), - CertBytes: cert.Marshal(), - D: k.D, - Comments: comment, - Constraints: constraints, - }) - case *ed25519.PrivateKey: - req = ssh.Marshal(ed25519CertMsg{ - Type: cert.Type(), - CertBytes: cert.Marshal(), - Pub: []byte(*k)[32:], - Priv: []byte(*k), - Comments: comment, - Constraints: constraints, - }) - default: - return fmt.Errorf("agent: unsupported key type %T", s) - } - - // if constraints are present then the message type needs to be changed. - if len(constraints) != 0 { - req[0] = agentAddIDConstrained - } - - signer, err := ssh.NewSignerFromKey(s) - if err != nil { - return err - } - if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 { - return errors.New("agent: signer and cert have different public key") - } - - resp, err := c.call(req) - if err != nil { - return err - } - if _, ok := resp.(*successAgentMsg); ok { - return nil - } - return errors.New("agent: failure") -} - -// Signers provides a callback for client authentication. -func (c *client) Signers() ([]ssh.Signer, error) { - keys, err := c.List() - if err != nil { - return nil, err - } - - var result []ssh.Signer - for _, k := range keys { - result = append(result, &agentKeyringSigner{c, k}) - } - return result, nil -} - -type agentKeyringSigner struct { - agent *client - pub ssh.PublicKey -} - -func (s *agentKeyringSigner) PublicKey() ssh.PublicKey { - return s.pub -} - -func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) { - // The agent has its own entropy source, so the rand argument is ignored. - return s.agent.Sign(s.pub, data) -} diff --git a/vendor/golang.org/x/crypto/ssh/agent/forward.go b/vendor/golang.org/x/crypto/ssh/agent/forward.go deleted file mode 100644 index fd24ba900..000000000 --- a/vendor/golang.org/x/crypto/ssh/agent/forward.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package agent - -import ( - "errors" - "io" - "net" - "sync" - - "golang.org/x/crypto/ssh" -) - -// RequestAgentForwarding sets up agent forwarding for the session. -// ForwardToAgent or ForwardToRemote should be called to route -// the authentication requests. -func RequestAgentForwarding(session *ssh.Session) error { - ok, err := session.SendRequest("auth-agent-req@openssh.com", true, nil) - if err != nil { - return err - } - if !ok { - return errors.New("forwarding request denied") - } - return nil -} - -// ForwardToAgent routes authentication requests to the given keyring. -func ForwardToAgent(client *ssh.Client, keyring Agent) error { - channels := client.HandleChannelOpen(channelType) - if channels == nil { - return errors.New("agent: already have handler for " + channelType) - } - - go func() { - for ch := range channels { - channel, reqs, err := ch.Accept() - if err != nil { - continue - } - go ssh.DiscardRequests(reqs) - go func() { - ServeAgent(keyring, channel) - channel.Close() - }() - } - }() - return nil -} - -const channelType = "auth-agent@openssh.com" - -// ForwardToRemote routes authentication requests to the ssh-agent -// process serving on the given unix socket. -func ForwardToRemote(client *ssh.Client, addr string) error { - channels := client.HandleChannelOpen(channelType) - if channels == nil { - return errors.New("agent: already have handler for " + channelType) - } - conn, err := net.Dial("unix", addr) - if err != nil { - return err - } - conn.Close() - - go func() { - for ch := range channels { - channel, reqs, err := ch.Accept() - if err != nil { - continue - } - go ssh.DiscardRequests(reqs) - go forwardUnixSocket(channel, addr) - } - }() - return nil -} - -func forwardUnixSocket(channel ssh.Channel, addr string) { - conn, err := net.Dial("unix", addr) - if err != nil { - return - } - - var wg sync.WaitGroup - wg.Add(2) - go func() { - io.Copy(conn, channel) - conn.(*net.UnixConn).CloseWrite() - wg.Done() - }() - go func() { - io.Copy(channel, conn) - channel.CloseWrite() - wg.Done() - }() - - wg.Wait() - conn.Close() - channel.Close() -} diff --git a/vendor/golang.org/x/crypto/ssh/agent/keyring.go b/vendor/golang.org/x/crypto/ssh/agent/keyring.go deleted file mode 100644 index a6ba06ab3..000000000 --- a/vendor/golang.org/x/crypto/ssh/agent/keyring.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package agent - -import ( - "bytes" - "crypto/rand" - "crypto/subtle" - "errors" - "fmt" - "sync" - "time" - - "golang.org/x/crypto/ssh" -) - -type privKey struct { - signer ssh.Signer - comment string - expire *time.Time -} - -type keyring struct { - mu sync.Mutex - keys []privKey - - locked bool - passphrase []byte -} - -var errLocked = errors.New("agent: locked") - -// NewKeyring returns an Agent that holds keys in memory. It is safe -// for concurrent use by multiple goroutines. -func NewKeyring() Agent { - return &keyring{} -} - -// RemoveAll removes all identities. -func (r *keyring) RemoveAll() error { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return errLocked - } - - r.keys = nil - return nil -} - -// removeLocked does the actual key removal. The caller must already be holding the -// keyring mutex. -func (r *keyring) removeLocked(want []byte) error { - found := false - for i := 0; i < len(r.keys); { - if bytes.Equal(r.keys[i].signer.PublicKey().Marshal(), want) { - found = true - r.keys[i] = r.keys[len(r.keys)-1] - r.keys = r.keys[:len(r.keys)-1] - continue - } else { - i++ - } - } - - if !found { - return errors.New("agent: key not found") - } - return nil -} - -// Remove removes all identities with the given public key. -func (r *keyring) Remove(key ssh.PublicKey) error { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return errLocked - } - - return r.removeLocked(key.Marshal()) -} - -// Lock locks the agent. Sign and Remove will fail, and List will return an empty list. -func (r *keyring) Lock(passphrase []byte) error { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return errLocked - } - - r.locked = true - r.passphrase = passphrase - return nil -} - -// Unlock undoes the effect of Lock -func (r *keyring) Unlock(passphrase []byte) error { - r.mu.Lock() - defer r.mu.Unlock() - if !r.locked { - return errors.New("agent: not locked") - } - if len(passphrase) != len(r.passphrase) || 1 != subtle.ConstantTimeCompare(passphrase, r.passphrase) { - return fmt.Errorf("agent: incorrect passphrase") - } - - r.locked = false - r.passphrase = nil - return nil -} - -// expireKeysLocked removes expired keys from the keyring. If a key was added -// with a lifetimesecs contraint and seconds >= lifetimesecs seconds have -// ellapsed, it is removed. The caller *must* be holding the keyring mutex. -func (r *keyring) expireKeysLocked() { - for _, k := range r.keys { - if k.expire != nil && time.Now().After(*k.expire) { - r.removeLocked(k.signer.PublicKey().Marshal()) - } - } -} - -// List returns the identities known to the agent. -func (r *keyring) List() ([]*Key, error) { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - // section 2.7: locked agents return empty. - return nil, nil - } - - r.expireKeysLocked() - var ids []*Key - for _, k := range r.keys { - pub := k.signer.PublicKey() - ids = append(ids, &Key{ - Format: pub.Type(), - Blob: pub.Marshal(), - Comment: k.comment}) - } - return ids, nil -} - -// Insert adds a private key to the keyring. If a certificate -// is given, that certificate is added as public key. Note that -// any constraints given are ignored. -func (r *keyring) Add(key AddedKey) error { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return errLocked - } - signer, err := ssh.NewSignerFromKey(key.PrivateKey) - - if err != nil { - return err - } - - if cert := key.Certificate; cert != nil { - signer, err = ssh.NewCertSigner(cert, signer) - if err != nil { - return err - } - } - - p := privKey{ - signer: signer, - comment: key.Comment, - } - - if key.LifetimeSecs > 0 { - t := time.Now().Add(time.Duration(key.LifetimeSecs) * time.Second) - p.expire = &t - } - - r.keys = append(r.keys, p) - - return nil -} - -// Sign returns a signature for the data. -func (r *keyring) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return nil, errLocked - } - - r.expireKeysLocked() - wanted := key.Marshal() - for _, k := range r.keys { - if bytes.Equal(k.signer.PublicKey().Marshal(), wanted) { - return k.signer.Sign(rand.Reader, data) - } - } - return nil, errors.New("not found") -} - -// Signers returns signers for all the known keys. -func (r *keyring) Signers() ([]ssh.Signer, error) { - r.mu.Lock() - defer r.mu.Unlock() - if r.locked { - return nil, errLocked - } - - r.expireKeysLocked() - s := make([]ssh.Signer, 0, len(r.keys)) - for _, k := range r.keys { - s = append(s, k.signer) - } - return s, nil -} diff --git a/vendor/golang.org/x/crypto/ssh/agent/server.go b/vendor/golang.org/x/crypto/ssh/agent/server.go deleted file mode 100644 index 2e4692cbd..000000000 --- a/vendor/golang.org/x/crypto/ssh/agent/server.go +++ /dev/null @@ -1,523 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package agent - -import ( - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/binary" - "errors" - "fmt" - "io" - "log" - "math/big" - - "golang.org/x/crypto/ed25519" - "golang.org/x/crypto/ssh" -) - -// Server wraps an Agent and uses it to implement the agent side of -// the SSH-agent, wire protocol. -type server struct { - agent Agent -} - -func (s *server) processRequestBytes(reqData []byte) []byte { - rep, err := s.processRequest(reqData) - if err != nil { - if err != errLocked { - // TODO(hanwen): provide better logging interface? - log.Printf("agent %d: %v", reqData[0], err) - } - return []byte{agentFailure} - } - - if err == nil && rep == nil { - return []byte{agentSuccess} - } - - return ssh.Marshal(rep) -} - -func marshalKey(k *Key) []byte { - var record struct { - Blob []byte - Comment string - } - record.Blob = k.Marshal() - record.Comment = k.Comment - - return ssh.Marshal(&record) -} - -// See [PROTOCOL.agent], section 2.5.1. -const agentV1IdentitiesAnswer = 2 - -type agentV1IdentityMsg struct { - Numkeys uint32 `sshtype:"2"` -} - -type agentRemoveIdentityMsg struct { - KeyBlob []byte `sshtype:"18"` -} - -type agentLockMsg struct { - Passphrase []byte `sshtype:"22"` -} - -type agentUnlockMsg struct { - Passphrase []byte `sshtype:"23"` -} - -func (s *server) processRequest(data []byte) (interface{}, error) { - switch data[0] { - case agentRequestV1Identities: - return &agentV1IdentityMsg{0}, nil - - case agentRemoveAllV1Identities: - return nil, nil - - case agentRemoveIdentity: - var req agentRemoveIdentityMsg - if err := ssh.Unmarshal(data, &req); err != nil { - return nil, err - } - - var wk wireKey - if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { - return nil, err - } - - return nil, s.agent.Remove(&Key{Format: wk.Format, Blob: req.KeyBlob}) - - case agentRemoveAllIdentities: - return nil, s.agent.RemoveAll() - - case agentLock: - var req agentLockMsg - if err := ssh.Unmarshal(data, &req); err != nil { - return nil, err - } - - return nil, s.agent.Lock(req.Passphrase) - - case agentUnlock: - var req agentUnlockMsg - if err := ssh.Unmarshal(data, &req); err != nil { - return nil, err - } - return nil, s.agent.Unlock(req.Passphrase) - - case agentSignRequest: - var req signRequestAgentMsg - if err := ssh.Unmarshal(data, &req); err != nil { - return nil, err - } - - var wk wireKey - if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil { - return nil, err - } - - k := &Key{ - Format: wk.Format, - Blob: req.KeyBlob, - } - - sig, err := s.agent.Sign(k, req.Data) // TODO(hanwen): flags. - if err != nil { - return nil, err - } - return &signResponseAgentMsg{SigBlob: ssh.Marshal(sig)}, nil - - case agentRequestIdentities: - keys, err := s.agent.List() - if err != nil { - return nil, err - } - - rep := identitiesAnswerAgentMsg{ - NumKeys: uint32(len(keys)), - } - for _, k := range keys { - rep.Keys = append(rep.Keys, marshalKey(k)...) - } - return rep, nil - - case agentAddIDConstrained, agentAddIdentity: - return nil, s.insertIdentity(data) - } - - return nil, fmt.Errorf("unknown opcode %d", data[0]) -} - -func parseConstraints(constraints []byte) (lifetimeSecs uint32, confirmBeforeUse bool, extensions []ConstraintExtension, err error) { - for len(constraints) != 0 { - switch constraints[0] { - case agentConstrainLifetime: - lifetimeSecs = binary.BigEndian.Uint32(constraints[1:5]) - constraints = constraints[5:] - case agentConstrainConfirm: - confirmBeforeUse = true - constraints = constraints[1:] - case agentConstrainExtension: - var msg constrainExtensionAgentMsg - if err = ssh.Unmarshal(constraints, &msg); err != nil { - return 0, false, nil, err - } - extensions = append(extensions, ConstraintExtension{ - ExtensionName: msg.ExtensionName, - ExtensionDetails: msg.ExtensionDetails, - }) - constraints = msg.Rest - default: - return 0, false, nil, fmt.Errorf("unknown constraint type: %d", constraints[0]) - } - } - return -} - -func setConstraints(key *AddedKey, constraintBytes []byte) error { - lifetimeSecs, confirmBeforeUse, constraintExtensions, err := parseConstraints(constraintBytes) - if err != nil { - return err - } - - key.LifetimeSecs = lifetimeSecs - key.ConfirmBeforeUse = confirmBeforeUse - key.ConstraintExtensions = constraintExtensions - return nil -} - -func parseRSAKey(req []byte) (*AddedKey, error) { - var k rsaKeyMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - if k.E.BitLen() > 30 { - return nil, errors.New("agent: RSA public exponent too large") - } - priv := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - E: int(k.E.Int64()), - N: k.N, - }, - D: k.D, - Primes: []*big.Int{k.P, k.Q}, - } - priv.Precompute() - - addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseEd25519Key(req []byte) (*AddedKey, error) { - var k ed25519KeyMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - priv := ed25519.PrivateKey(k.Priv) - - addedKey := &AddedKey{PrivateKey: &priv, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseDSAKey(req []byte) (*AddedKey, error) { - var k dsaKeyMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - priv := &dsa.PrivateKey{ - PublicKey: dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: k.P, - Q: k.Q, - G: k.G, - }, - Y: k.Y, - }, - X: k.X, - } - - addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func unmarshalECDSA(curveName string, keyBytes []byte, privScalar *big.Int) (priv *ecdsa.PrivateKey, err error) { - priv = &ecdsa.PrivateKey{ - D: privScalar, - } - - switch curveName { - case "nistp256": - priv.Curve = elliptic.P256() - case "nistp384": - priv.Curve = elliptic.P384() - case "nistp521": - priv.Curve = elliptic.P521() - default: - return nil, fmt.Errorf("agent: unknown curve %q", curveName) - } - - priv.X, priv.Y = elliptic.Unmarshal(priv.Curve, keyBytes) - if priv.X == nil || priv.Y == nil { - return nil, errors.New("agent: point not on curve") - } - - return priv, nil -} - -func parseEd25519Cert(req []byte) (*AddedKey, error) { - var k ed25519CertMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - pubKey, err := ssh.ParsePublicKey(k.CertBytes) - if err != nil { - return nil, err - } - priv := ed25519.PrivateKey(k.Priv) - cert, ok := pubKey.(*ssh.Certificate) - if !ok { - return nil, errors.New("agent: bad ED25519 certificate") - } - - addedKey := &AddedKey{PrivateKey: &priv, Certificate: cert, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseECDSAKey(req []byte) (*AddedKey, error) { - var k ecdsaKeyMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - - priv, err := unmarshalECDSA(k.Curve, k.KeyBytes, k.D) - if err != nil { - return nil, err - } - - addedKey := &AddedKey{PrivateKey: priv, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseRSACert(req []byte) (*AddedKey, error) { - var k rsaCertMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - - pubKey, err := ssh.ParsePublicKey(k.CertBytes) - if err != nil { - return nil, err - } - - cert, ok := pubKey.(*ssh.Certificate) - if !ok { - return nil, errors.New("agent: bad RSA certificate") - } - - // An RSA publickey as marshaled by rsaPublicKey.Marshal() in keys.go - var rsaPub struct { - Name string - E *big.Int - N *big.Int - } - if err := ssh.Unmarshal(cert.Key.Marshal(), &rsaPub); err != nil { - return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err) - } - - if rsaPub.E.BitLen() > 30 { - return nil, errors.New("agent: RSA public exponent too large") - } - - priv := rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - E: int(rsaPub.E.Int64()), - N: rsaPub.N, - }, - D: k.D, - Primes: []*big.Int{k.Q, k.P}, - } - priv.Precompute() - - addedKey := &AddedKey{PrivateKey: &priv, Certificate: cert, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseDSACert(req []byte) (*AddedKey, error) { - var k dsaCertMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - pubKey, err := ssh.ParsePublicKey(k.CertBytes) - if err != nil { - return nil, err - } - cert, ok := pubKey.(*ssh.Certificate) - if !ok { - return nil, errors.New("agent: bad DSA certificate") - } - - // A DSA publickey as marshaled by dsaPublicKey.Marshal() in keys.go - var w struct { - Name string - P, Q, G, Y *big.Int - } - if err := ssh.Unmarshal(cert.Key.Marshal(), &w); err != nil { - return nil, fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err) - } - - priv := &dsa.PrivateKey{ - PublicKey: dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: w.P, - Q: w.Q, - G: w.G, - }, - Y: w.Y, - }, - X: k.X, - } - - addedKey := &AddedKey{PrivateKey: priv, Certificate: cert, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func parseECDSACert(req []byte) (*AddedKey, error) { - var k ecdsaCertMsg - if err := ssh.Unmarshal(req, &k); err != nil { - return nil, err - } - - pubKey, err := ssh.ParsePublicKey(k.CertBytes) - if err != nil { - return nil, err - } - cert, ok := pubKey.(*ssh.Certificate) - if !ok { - return nil, errors.New("agent: bad ECDSA certificate") - } - - // An ECDSA publickey as marshaled by ecdsaPublicKey.Marshal() in keys.go - var ecdsaPub struct { - Name string - ID string - Key []byte - } - if err := ssh.Unmarshal(cert.Key.Marshal(), &ecdsaPub); err != nil { - return nil, err - } - - priv, err := unmarshalECDSA(ecdsaPub.ID, ecdsaPub.Key, k.D) - if err != nil { - return nil, err - } - - addedKey := &AddedKey{PrivateKey: priv, Certificate: cert, Comment: k.Comments} - if err := setConstraints(addedKey, k.Constraints); err != nil { - return nil, err - } - return addedKey, nil -} - -func (s *server) insertIdentity(req []byte) error { - var record struct { - Type string `sshtype:"17|25"` - Rest []byte `ssh:"rest"` - } - - if err := ssh.Unmarshal(req, &record); err != nil { - return err - } - - var addedKey *AddedKey - var err error - - switch record.Type { - case ssh.KeyAlgoRSA: - addedKey, err = parseRSAKey(req) - case ssh.KeyAlgoDSA: - addedKey, err = parseDSAKey(req) - case ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521: - addedKey, err = parseECDSAKey(req) - case ssh.KeyAlgoED25519: - addedKey, err = parseEd25519Key(req) - case ssh.CertAlgoRSAv01: - addedKey, err = parseRSACert(req) - case ssh.CertAlgoDSAv01: - addedKey, err = parseDSACert(req) - case ssh.CertAlgoECDSA256v01, ssh.CertAlgoECDSA384v01, ssh.CertAlgoECDSA521v01: - addedKey, err = parseECDSACert(req) - case ssh.CertAlgoED25519v01: - addedKey, err = parseEd25519Cert(req) - default: - return fmt.Errorf("agent: not implemented: %q", record.Type) - } - - if err != nil { - return err - } - return s.agent.Add(*addedKey) -} - -// ServeAgent serves the agent protocol on the given connection. It -// returns when an I/O error occurs. -func ServeAgent(agent Agent, c io.ReadWriter) error { - s := &server{agent} - - var length [4]byte - for { - if _, err := io.ReadFull(c, length[:]); err != nil { - return err - } - l := binary.BigEndian.Uint32(length[:]) - if l > maxAgentResponseBytes { - // We also cap requests. - return fmt.Errorf("agent: request too large: %d", l) - } - - req := make([]byte, l) - if _, err := io.ReadFull(c, req); err != nil { - return err - } - - repData := s.processRequestBytes(req) - if len(repData) > maxAgentResponseBytes { - return fmt.Errorf("agent: reply too large: %d bytes", len(repData)) - } - - binary.BigEndian.PutUint32(length[:], uint32(len(repData))) - if _, err := c.Write(length[:]); err != nil { - return err - } - if _, err := c.Write(repData); err != nil { - return err - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/buffer.go b/vendor/golang.org/x/crypto/ssh/buffer.go index 6931b5114..1ab07d078 100644 --- a/vendor/golang.org/x/crypto/ssh/buffer.go +++ b/vendor/golang.org/x/crypto/ssh/buffer.go @@ -51,13 +51,12 @@ func (b *buffer) write(buf []byte) { } // eof closes the buffer. Reads from the buffer once all -// the data has been consumed will receive os.EOF. -func (b *buffer) eof() error { +// the data has been consumed will receive io.EOF. +func (b *buffer) eof() { b.Cond.L.Lock() b.closed = true b.Cond.Signal() b.Cond.L.Unlock() - return nil } // Read reads data from the internal buffer in buf. Reads will block diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index 6331c94d5..00ed9923e 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -44,7 +44,9 @@ type Signature struct { const CertTimeInfinity = 1<<64 - 1 // An Certificate represents an OpenSSH certificate as defined in -// [PROTOCOL.certkeys]?rev=1.8. +// [PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the +// PublicKey interface, so it can be unmarshaled using +// ParsePublicKey. type Certificate struct { Nonce []byte Key PublicKey @@ -220,6 +222,11 @@ type openSSHCertSigner struct { signer Signer } +type algorithmOpenSSHCertSigner struct { + *openSSHCertSigner + algorithmSigner AlgorithmSigner +} + // NewCertSigner returns a Signer that signs with the given Certificate, whose // private key is held by signer. It returns an error if the public key in cert // doesn't match the key used by signer. @@ -228,7 +235,12 @@ func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) { return nil, errors.New("ssh: signer and cert have different public key") } - return &openSSHCertSigner{cert, signer}, nil + if algorithmSigner, ok := signer.(AlgorithmSigner); ok { + return &algorithmOpenSSHCertSigner{ + &openSSHCertSigner{cert, signer}, algorithmSigner}, nil + } else { + return &openSSHCertSigner{cert, signer}, nil + } } func (s *openSSHCertSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { @@ -239,6 +251,10 @@ func (s *openSSHCertSigner) PublicKey() PublicKey { return s.pub } +func (s *algorithmOpenSSHCertSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { + return s.algorithmSigner.SignWithAlgorithm(rand, data, algorithm) +} + const sourceAddressCriticalOption = "source-address" // CertChecker does the work of verifying a certificate. Its methods @@ -251,10 +267,18 @@ type CertChecker struct { // for user certificates. SupportedCriticalOptions []string - // IsAuthority should return true if the key is recognized as - // an authority. This allows for certificates to be signed by other - // certificates. - IsAuthority func(auth PublicKey) bool + // IsUserAuthority should return true if the key is recognized as an + // authority for the given user certificate. This allows for + // certificates to be signed by other certificates. This must be set + // if this CertChecker will be checking user certificates. + IsUserAuthority func(auth PublicKey) bool + + // IsHostAuthority should report whether the key is recognized as + // an authority for this host. This allows for certificates to be + // signed by other keys, and for those other keys to only be valid + // signers for particular hostnames. This must be set if this + // CertChecker will be checking host certificates. + IsHostAuthority func(auth PublicKey, address string) bool // Clock is used for verifying time stamps. If nil, time.Now // is used. @@ -268,7 +292,7 @@ type CertChecker struct { // HostKeyFallback is called when CertChecker.CheckHostKey encounters a // public key that is not a certificate. It must implement host key // validation or else, if nil, all such keys are rejected. - HostKeyFallback func(addr string, remote net.Addr, key PublicKey) error + HostKeyFallback HostKeyCallback // IsRevoked is called for each certificate so that revocation checking // can be implemented. It should return true if the given certificate @@ -290,8 +314,17 @@ func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) if cert.CertType != HostCert { return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType) } + if !c.IsHostAuthority(cert.SignatureKey, addr) { + return fmt.Errorf("ssh: no authorities for hostname: %v", addr) + } - return c.CheckCert(addr, cert) + hostname, _, err := net.SplitHostPort(addr) + if err != nil { + return err + } + + // Pass hostname only as principal for host certificates (consistent with OpenSSH) + return c.CheckCert(hostname, cert) } // Authenticate checks a user certificate. Authenticate can be used as @@ -308,6 +341,9 @@ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permis if cert.CertType != UserCert { return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType) } + if !c.IsUserAuthority(cert.SignatureKey) { + return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority") + } if err := c.CheckCert(conn.User(), cert); err != nil { return nil, err @@ -320,10 +356,10 @@ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permis // the signature of the certificate. func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { if c.IsRevoked != nil && c.IsRevoked(cert) { - return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial) + return fmt.Errorf("ssh: certificate serial %d revoked", cert.Serial) } - for opt, _ := range cert.CriticalOptions { + for opt := range cert.CriticalOptions { // sourceAddressCriticalOption will be enforced by // serverAuthenticate if opt == sourceAddressCriticalOption { @@ -356,10 +392,6 @@ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { } } - if !c.IsAuthority(cert.SignatureKey) { - return fmt.Errorf("ssh: certificate signed by unrecognized authority") - } - clock := c.Clock if clock == nil { clock = time.Now diff --git a/vendor/golang.org/x/crypto/ssh/channel.go b/vendor/golang.org/x/crypto/ssh/channel.go index 195530ea0..c0834c00d 100644 --- a/vendor/golang.org/x/crypto/ssh/channel.go +++ b/vendor/golang.org/x/crypto/ssh/channel.go @@ -205,32 +205,32 @@ type channel struct { // writePacket sends a packet. If the packet is a channel close, it updates // sentClose. This method takes the lock c.writeMu. -func (c *channel) writePacket(packet []byte) error { - c.writeMu.Lock() - if c.sentClose { - c.writeMu.Unlock() +func (ch *channel) writePacket(packet []byte) error { + ch.writeMu.Lock() + if ch.sentClose { + ch.writeMu.Unlock() return io.EOF } - c.sentClose = (packet[0] == msgChannelClose) - err := c.mux.conn.writePacket(packet) - c.writeMu.Unlock() + ch.sentClose = (packet[0] == msgChannelClose) + err := ch.mux.conn.writePacket(packet) + ch.writeMu.Unlock() return err } -func (c *channel) sendMessage(msg interface{}) error { +func (ch *channel) sendMessage(msg interface{}) error { if debugMux { - log.Printf("send(%d): %#v", c.mux.chanList.offset, msg) + log.Printf("send(%d): %#v", ch.mux.chanList.offset, msg) } p := Marshal(msg) - binary.BigEndian.PutUint32(p[1:], c.remoteId) - return c.writePacket(p) + binary.BigEndian.PutUint32(p[1:], ch.remoteId) + return ch.writePacket(p) } // WriteExtended writes data to a specific extended stream. These streams are // used, for example, for stderr. -func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { - if c.sentEOF { +func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { + if ch.sentEOF { return 0, io.EOF } // 1 byte message type, 4 bytes remoteId, 4 bytes data length @@ -241,16 +241,16 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er opCode = msgChannelExtendedData } - c.writeMu.Lock() - packet := c.packetPool[extendedCode] + ch.writeMu.Lock() + packet := ch.packetPool[extendedCode] // We don't remove the buffer from packetPool, so // WriteExtended calls from different goroutines will be // flagged as errors by the race detector. - c.writeMu.Unlock() + ch.writeMu.Unlock() for len(data) > 0 { - space := min(c.maxRemotePayload, len(data)) - if space, err = c.remoteWin.reserve(space); err != nil { + space := min(ch.maxRemotePayload, len(data)) + if space, err = ch.remoteWin.reserve(space); err != nil { return n, err } if want := headerLength + space; uint32(cap(packet)) < want { @@ -262,13 +262,13 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er todo := data[:space] packet[0] = opCode - binary.BigEndian.PutUint32(packet[1:], c.remoteId) + binary.BigEndian.PutUint32(packet[1:], ch.remoteId) if extendedCode > 0 { binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode)) } binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo))) copy(packet[headerLength:], todo) - if err = c.writePacket(packet); err != nil { + if err = ch.writePacket(packet); err != nil { return n, err } @@ -276,14 +276,14 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er data = data[len(todo):] } - c.writeMu.Lock() - c.packetPool[extendedCode] = packet - c.writeMu.Unlock() + ch.writeMu.Lock() + ch.packetPool[extendedCode] = packet + ch.writeMu.Unlock() return n, err } -func (c *channel) handleData(packet []byte) error { +func (ch *channel) handleData(packet []byte) error { headerLen := 9 isExtendedData := packet[0] == msgChannelExtendedData if isExtendedData { @@ -303,7 +303,7 @@ func (c *channel) handleData(packet []byte) error { if length == 0 { return nil } - if length > c.maxIncomingPayload { + if length > ch.maxIncomingPayload { // TODO(hanwen): should send Disconnect? return errors.New("ssh: incoming packet exceeds maximum payload size") } @@ -313,21 +313,21 @@ func (c *channel) handleData(packet []byte) error { return errors.New("ssh: wrong packet length") } - c.windowMu.Lock() - if c.myWindow < length { - c.windowMu.Unlock() + ch.windowMu.Lock() + if ch.myWindow < length { + ch.windowMu.Unlock() // TODO(hanwen): should send Disconnect with reason? return errors.New("ssh: remote side wrote too much") } - c.myWindow -= length - c.windowMu.Unlock() + ch.myWindow -= length + ch.windowMu.Unlock() if extended == 1 { - c.extPending.write(data) + ch.extPending.write(data) } else if extended > 0 { // discard other extended data. } else { - c.pending.write(data) + ch.pending.write(data) } return nil } @@ -384,31 +384,31 @@ func (c *channel) close() { // responseMessageReceived is called when a success or failure message is // received on a channel to check that such a message is reasonable for the // given channel. -func (c *channel) responseMessageReceived() error { - if c.direction == channelInbound { +func (ch *channel) responseMessageReceived() error { + if ch.direction == channelInbound { return errors.New("ssh: channel response message received on inbound channel") } - if c.decided { + if ch.decided { return errors.New("ssh: duplicate response received for channel") } - c.decided = true + ch.decided = true return nil } -func (c *channel) handlePacket(packet []byte) error { +func (ch *channel) handlePacket(packet []byte) error { switch packet[0] { case msgChannelData, msgChannelExtendedData: - return c.handleData(packet) + return ch.handleData(packet) case msgChannelClose: - c.sendMessage(channelCloseMsg{PeersId: c.remoteId}) - c.mux.chanList.remove(c.localId) - c.close() + ch.sendMessage(channelCloseMsg{PeersID: ch.remoteId}) + ch.mux.chanList.remove(ch.localId) + ch.close() return nil case msgChannelEOF: // RFC 4254 is mute on how EOF affects dataExt messages but // it is logical to signal EOF at the same time. - c.extPending.eof() - c.pending.eof() + ch.extPending.eof() + ch.pending.eof() return nil } @@ -419,24 +419,24 @@ func (c *channel) handlePacket(packet []byte) error { switch msg := decoded.(type) { case *channelOpenFailureMsg: - if err := c.responseMessageReceived(); err != nil { + if err := ch.responseMessageReceived(); err != nil { return err } - c.mux.chanList.remove(msg.PeersId) - c.msg <- msg + ch.mux.chanList.remove(msg.PeersID) + ch.msg <- msg case *channelOpenConfirmMsg: - if err := c.responseMessageReceived(); err != nil { + if err := ch.responseMessageReceived(); err != nil { return err } if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { return fmt.Errorf("ssh: invalid MaxPacketSize %d from peer", msg.MaxPacketSize) } - c.remoteId = msg.MyId - c.maxRemotePayload = msg.MaxPacketSize - c.remoteWin.add(msg.MyWindow) - c.msg <- msg + ch.remoteId = msg.MyID + ch.maxRemotePayload = msg.MaxPacketSize + ch.remoteWin.add(msg.MyWindow) + ch.msg <- msg case *windowAdjustMsg: - if !c.remoteWin.add(msg.AdditionalBytes) { + if !ch.remoteWin.add(msg.AdditionalBytes) { return fmt.Errorf("ssh: invalid window update for %d bytes", msg.AdditionalBytes) } case *channelRequestMsg: @@ -444,12 +444,12 @@ func (c *channel) handlePacket(packet []byte) error { Type: msg.Request, WantReply: msg.WantReply, Payload: msg.RequestSpecificData, - ch: c, + ch: ch, } - c.incomingRequests <- &req + ch.incomingRequests <- &req default: - c.msg <- msg + ch.msg <- msg } return nil } @@ -488,23 +488,23 @@ func (e *extChannel) Read(data []byte) (n int, err error) { return e.ch.ReadExtended(data, e.code) } -func (c *channel) Accept() (Channel, <-chan *Request, error) { - if c.decided { +func (ch *channel) Accept() (Channel, <-chan *Request, error) { + if ch.decided { return nil, nil, errDecidedAlready } - c.maxIncomingPayload = channelMaxPacket + ch.maxIncomingPayload = channelMaxPacket confirm := channelOpenConfirmMsg{ - PeersId: c.remoteId, - MyId: c.localId, - MyWindow: c.myWindow, - MaxPacketSize: c.maxIncomingPayload, + PeersID: ch.remoteId, + MyID: ch.localId, + MyWindow: ch.myWindow, + MaxPacketSize: ch.maxIncomingPayload, } - c.decided = true - if err := c.sendMessage(confirm); err != nil { + ch.decided = true + if err := ch.sendMessage(confirm); err != nil { return nil, nil, err } - return c, c.incomingRequests, nil + return ch, ch.incomingRequests, nil } func (ch *channel) Reject(reason RejectionReason, message string) error { @@ -512,7 +512,7 @@ func (ch *channel) Reject(reason RejectionReason, message string) error { return errDecidedAlready } reject := channelOpenFailureMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, Reason: reason, Message: message, Language: "en", @@ -541,7 +541,7 @@ func (ch *channel) CloseWrite() error { } ch.sentEOF = true return ch.sendMessage(channelEOFMsg{ - PeersId: ch.remoteId}) + PeersID: ch.remoteId}) } func (ch *channel) Close() error { @@ -550,7 +550,7 @@ func (ch *channel) Close() error { } return ch.sendMessage(channelCloseMsg{ - PeersId: ch.remoteId}) + PeersID: ch.remoteId}) } // Extended returns an io.ReadWriter that sends and receives data on the given, @@ -577,7 +577,7 @@ func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (boo } msg := channelRequestMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, Request: name, WantReply: wantReply, RequestSpecificData: payload, @@ -614,11 +614,11 @@ func (ch *channel) ackRequest(ok bool) error { var msg interface{} if !ok { msg = channelRequestFailureMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, } } else { msg = channelRequestSuccessMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, } } return ch.sendMessage(msg) diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go index 13484ab4b..67b012610 100644 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ b/vendor/golang.org/x/crypto/ssh/cipher.go @@ -16,6 +16,10 @@ import ( "hash" "io" "io/ioutil" + "math/bits" + + "golang.org/x/crypto/internal/chacha20" + "golang.org/x/crypto/poly1305" ) const ( @@ -53,78 +57,78 @@ func newRC4(key, iv []byte) (cipher.Stream, error) { return rc4.NewCipher(key) } -type streamCipherMode struct { - keySize int - ivSize int - skip int - createFunc func(key, iv []byte) (cipher.Stream, error) +type cipherMode struct { + keySize int + ivSize int + create func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) } -func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) { - if len(key) < c.keySize { - panic("ssh: key length too small for cipher") - } - if len(iv) < c.ivSize { - panic("ssh: iv too small for cipher") - } - - stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize]) - if err != nil { - return nil, err - } +func streamCipherMode(skip int, createFunc func(key, iv []byte) (cipher.Stream, error)) func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) { + return func(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { + stream, err := createFunc(key, iv) + if err != nil { + return nil, err + } - var streamDump []byte - if c.skip > 0 { - streamDump = make([]byte, 512) - } + var streamDump []byte + if skip > 0 { + streamDump = make([]byte, 512) + } - for remainingToDump := c.skip; remainingToDump > 0; { - dumpThisTime := remainingToDump - if dumpThisTime > len(streamDump) { - dumpThisTime = len(streamDump) + for remainingToDump := skip; remainingToDump > 0; { + dumpThisTime := remainingToDump + if dumpThisTime > len(streamDump) { + dumpThisTime = len(streamDump) + } + stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) + remainingToDump -= dumpThisTime } - stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) - remainingToDump -= dumpThisTime - } - return stream, nil + mac := macModes[algs.MAC].new(macKey) + return &streamPacketCipher{ + mac: mac, + etm: macModes[algs.MAC].etm, + macResult: make([]byte, mac.Size()), + cipher: stream, + }, nil + } } // cipherModes documents properties of supported ciphers. Ciphers not included // are not supported and will not be negotiated, even if explicitly requested in // ClientConfig.Crypto.Ciphers. -var cipherModes = map[string]*streamCipherMode{ +var cipherModes = map[string]*cipherMode{ // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms // are defined in the order specified in the RFC. - "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR}, - "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR}, - "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR}, + "aes128-ctr": {16, aes.BlockSize, streamCipherMode(0, newAESCTR)}, + "aes192-ctr": {24, aes.BlockSize, streamCipherMode(0, newAESCTR)}, + "aes256-ctr": {32, aes.BlockSize, streamCipherMode(0, newAESCTR)}, // Ciphers from RFC4345, which introduces security-improved arcfour ciphers. // They are defined in the order specified in the RFC. - "arcfour128": {16, 0, 1536, newRC4}, - "arcfour256": {32, 0, 1536, newRC4}, + "arcfour128": {16, 0, streamCipherMode(1536, newRC4)}, + "arcfour256": {32, 0, streamCipherMode(1536, newRC4)}, // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and // RC4) has problems with weak keys, and should be used with caution." // RFC4345 introduces improved versions of Arcfour. - "arcfour": {16, 0, 0, newRC4}, + "arcfour": {16, 0, streamCipherMode(0, newRC4)}, - // AES-GCM is not a stream cipher, so it is constructed with a - // special case. If we add any more non-stream ciphers, we - // should invest a cleaner way to do this. - gcmCipherID: {16, 12, 0, nil}, + // AEAD ciphers + gcmCipherID: {16, 12, newGCMCipher}, + chacha20Poly1305ID: {64, 0, newChaCha20Cipher}, // CBC mode is insecure and so is not included in the default config. // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely // needed, it's possible to specify a custom Config to enable it. // You should expect that an active attacker can recover plaintext if // you do. - aes128cbcID: {16, aes.BlockSize, 0, nil}, + aes128cbcID: {16, aes.BlockSize, newAESCBCCipher}, - // 3des-cbc is insecure and is disabled by default. - tripledescbcID: {24, des.BlockSize, 0, nil}, + // 3des-cbc is insecure and is not included in the default + // config. + tripledescbcID: {24, des.BlockSize, newTripleDESCBCCipher}, } // prefixLen is the length of the packet prefix that contains the packet length @@ -304,7 +308,7 @@ type gcmCipher struct { buf []byte } -func newGCMCipher(iv, key, macKey []byte) (packetCipher, error) { +func newGCMCipher(key, iv, unusedMacKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err @@ -372,7 +376,7 @@ func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { } length := binary.BigEndian.Uint32(c.prefix[:]) if length > maxPacket { - return nil, errors.New("ssh: max packet length exceeded.") + return nil, errors.New("ssh: max packet length exceeded") } if cap(c.buf) < int(length+gcmTagSize) { @@ -392,7 +396,9 @@ func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { c.incIV() padding := plain[0] - if padding < 4 || padding >= 20 { + if padding < 4 { + // padding is a byte, so it automatically satisfies + // the maximum size, which is 255. return nil, fmt.Errorf("ssh: illegal padding %d", padding) } @@ -420,7 +426,7 @@ type cbcCipher struct { oracleCamouflage uint32 } -func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { cbc := &cbcCipher{ mac: macModes[algs.MAC].new(macKey), decrypter: cipher.NewCBCDecrypter(c, iv), @@ -434,13 +440,13 @@ func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorith return cbc, nil } -func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newAESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } - cbc, err := newCBCCipher(c, iv, key, macKey, algs) + cbc, err := newCBCCipher(c, key, iv, macKey, algs) if err != nil { return nil, err } @@ -448,13 +454,13 @@ func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCi return cbc, nil } -func newTripleDESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newTripleDESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := des.NewTripleDESCipher(key) if err != nil { return nil, err } - cbc, err := newCBCCipher(c, iv, key, macKey, algs) + cbc, err := newCBCCipher(c, key, iv, macKey, algs) if err != nil { return nil, err } @@ -546,11 +552,11 @@ func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) c.packetData = c.packetData[:entirePacketSize] } - if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { + n, err := io.ReadFull(r, c.packetData[firstBlockLength:]) + if err != nil { return nil, err - } else { - c.oracleCamouflage -= uint32(n) } + c.oracleCamouflage -= uint32(n) remainingCrypted := c.packetData[firstBlockLength:macStart] c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) @@ -625,3 +631,140 @@ func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, pack return nil } + +const chacha20Poly1305ID = "chacha20-poly1305@openssh.com" + +// chacha20Poly1305Cipher implements the chacha20-poly1305@openssh.com +// AEAD, which is described here: +// +// https://tools.ietf.org/html/draft-josefsson-ssh-chacha20-poly1305-openssh-00 +// +// the methods here also implement padding, which RFC4253 Section 6 +// also requires of stream ciphers. +type chacha20Poly1305Cipher struct { + lengthKey [8]uint32 + contentKey [8]uint32 + buf []byte +} + +func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { + if len(key) != 64 { + panic(len(key)) + } + + c := &chacha20Poly1305Cipher{ + buf: make([]byte, 256), + } + + for i := range c.contentKey { + c.contentKey[i] = binary.LittleEndian.Uint32(key[i*4 : (i+1)*4]) + } + for i := range c.lengthKey { + c.lengthKey[i] = binary.LittleEndian.Uint32(key[(i+8)*4 : (i+9)*4]) + } + return c, nil +} + +func (c *chacha20Poly1305Cipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { + nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} + s := chacha20.New(c.contentKey, nonce) + var polyKey [32]byte + s.XORKeyStream(polyKey[:], polyKey[:]) + s.Advance() // skip next 32 bytes + + encryptedLength := c.buf[:4] + if _, err := io.ReadFull(r, encryptedLength); err != nil { + return nil, err + } + + var lenBytes [4]byte + chacha20.New(c.lengthKey, nonce).XORKeyStream(lenBytes[:], encryptedLength) + + length := binary.BigEndian.Uint32(lenBytes[:]) + if length > maxPacket { + return nil, errors.New("ssh: invalid packet length, packet too large") + } + + contentEnd := 4 + length + packetEnd := contentEnd + poly1305.TagSize + if uint32(cap(c.buf)) < packetEnd { + c.buf = make([]byte, packetEnd) + copy(c.buf[:], encryptedLength) + } else { + c.buf = c.buf[:packetEnd] + } + + if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil { + return nil, err + } + + var mac [poly1305.TagSize]byte + copy(mac[:], c.buf[contentEnd:packetEnd]) + if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) { + return nil, errors.New("ssh: MAC failure") + } + + plain := c.buf[4:contentEnd] + s.XORKeyStream(plain, plain) + + padding := plain[0] + if padding < 4 { + // padding is a byte, so it automatically satisfies + // the maximum size, which is 255. + return nil, fmt.Errorf("ssh: illegal padding %d", padding) + } + + if int(padding)+1 >= len(plain) { + return nil, fmt.Errorf("ssh: padding %d too large", padding) + } + + plain = plain[1 : len(plain)-int(padding)] + + return plain, nil +} + +func (c *chacha20Poly1305Cipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error { + nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} + s := chacha20.New(c.contentKey, nonce) + var polyKey [32]byte + s.XORKeyStream(polyKey[:], polyKey[:]) + s.Advance() // skip next 32 bytes + + // There is no blocksize, so fall back to multiple of 8 byte + // padding, as described in RFC 4253, Sec 6. + const packetSizeMultiple = 8 + + padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple + if padding < 4 { + padding += packetSizeMultiple + } + + // size (4 bytes), padding (1), payload, padding, tag. + totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize + if cap(c.buf) < totalLength { + c.buf = make([]byte, totalLength) + } else { + c.buf = c.buf[:totalLength] + } + + binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding)) + chacha20.New(c.lengthKey, nonce).XORKeyStream(c.buf, c.buf[:4]) + c.buf[4] = byte(padding) + copy(c.buf[5:], payload) + packetEnd := 5 + len(payload) + padding + if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil { + return err + } + + s.XORKeyStream(c.buf[4:], c.buf[4:packetEnd]) + + var mac [poly1305.TagSize]byte + poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey) + + copy(c.buf[packetEnd:], mac[:]) + + if _, err := w.Write(c.buf); err != nil { + return err + } + return nil +} diff --git a/vendor/golang.org/x/crypto/ssh/client.go b/vendor/golang.org/x/crypto/ssh/client.go index c97f2978e..7b00bff1c 100644 --- a/vendor/golang.org/x/crypto/ssh/client.go +++ b/vendor/golang.org/x/crypto/ssh/client.go @@ -5,18 +5,22 @@ package ssh import ( + "bytes" "errors" "fmt" "net" + "os" "sync" "time" ) // Client implements a traditional SSH client that supports shells, -// subprocesses, port forwarding and tunneled dialing. +// subprocesses, TCP port/streamlocal forwarding and tunneled dialing. type Client struct { Conn + handleForwardsOnce sync.Once // guards calling (*Client).handleForwards + forwards forwardList // forwarded tcpip connections from the remote side mu sync.Mutex channelHandlers map[string]chan NewChannel @@ -58,7 +62,6 @@ func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { conn.Wait() conn.forwards.closeAll() }() - go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip")) return conn } @@ -68,6 +71,11 @@ func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { func NewClientConn(c net.Conn, addr string, config *ClientConfig) (Conn, <-chan NewChannel, <-chan *Request, error) { fullConf := *config fullConf.SetDefaults() + if fullConf.HostKeyCallback == nil { + c.Close() + return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback") + } + conn := &connection{ sshConn: sshConn{conn: c}, } @@ -173,6 +181,17 @@ func Dial(network, addr string, config *ClientConfig) (*Client, error) { return NewClient(c, chans, reqs), nil } +// HostKeyCallback is the function type used for verifying server +// keys. A HostKeyCallback must return nil if the host key is OK, or +// an error to reject it. It receives the hostname as passed to Dial +// or NewClientConn. The remote address is the RemoteAddr of the +// net.Conn underlying the SSH connection. +type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error + +// BannerCallback is the function type used for treat the banner sent by +// the server. A BannerCallback receives the message sent by the remote server. +type BannerCallback func(message string) error + // A ClientConfig structure is used to configure a Client. It must not be // modified after having been passed to an SSH function. type ClientConfig struct { @@ -188,10 +207,18 @@ type ClientConfig struct { // be used during authentication. Auth []AuthMethod - // HostKeyCallback, if not nil, is called during the cryptographic - // handshake to validate the server's host key. A nil HostKeyCallback - // implies that all host keys are accepted. - HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error + // HostKeyCallback is called during the cryptographic + // handshake to validate the server's host key. The client + // configuration must supply this callback for the connection + // to succeed. The functions InsecureIgnoreHostKey or + // FixedHostKey can be used for simplistic host key checks. + HostKeyCallback HostKeyCallback + + // BannerCallback is called during the SSH dance to display a custom + // server's message. The client configuration can supply this callback to + // handle it as wished. The function BannerDisplayStderr can be used for + // simplistic display on Stderr. + BannerCallback BannerCallback // ClientVersion contains the version identification string that will // be used for the connection. If empty, a reasonable default is used. @@ -209,3 +236,43 @@ type ClientConfig struct { // A Timeout of zero means no timeout. Timeout time.Duration } + +// InsecureIgnoreHostKey returns a function that can be used for +// ClientConfig.HostKeyCallback to accept any host key. It should +// not be used for production code. +func InsecureIgnoreHostKey() HostKeyCallback { + return func(hostname string, remote net.Addr, key PublicKey) error { + return nil + } +} + +type fixedHostKey struct { + key PublicKey +} + +func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error { + if f.key == nil { + return fmt.Errorf("ssh: required host key was nil") + } + if !bytes.Equal(key.Marshal(), f.key.Marshal()) { + return fmt.Errorf("ssh: host key mismatch") + } + return nil +} + +// FixedHostKey returns a function for use in +// ClientConfig.HostKeyCallback to accept only a specific host key. +func FixedHostKey(key PublicKey) HostKeyCallback { + hk := &fixedHostKey{key} + return hk.check +} + +// BannerDisplayStderr returns a function that can be used for +// ClientConfig.BannerCallback to display banners on os.Stderr. +func BannerDisplayStderr() BannerCallback { + return func(banner string) error { + _, err := os.Stderr.WriteString(banner) + + return err + } +} diff --git a/vendor/golang.org/x/crypto/ssh/client_auth.go b/vendor/golang.org/x/crypto/ssh/client_auth.go index fd1ec5dda..5f44b7740 100644 --- a/vendor/golang.org/x/crypto/ssh/client_auth.go +++ b/vendor/golang.org/x/crypto/ssh/client_auth.go @@ -11,6 +11,14 @@ import ( "io" ) +type authResult int + +const ( + authFailure authResult = iota + authPartialSuccess + authSuccess +) + // clientAuthenticate authenticates with the remote server. See RFC 4252. func (c *connection) clientAuthenticate(config *ClientConfig) error { // initiate user auth session @@ -37,11 +45,12 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { if err != nil { return err } - if ok { + if ok == authSuccess { // success return nil + } else if ok == authFailure { + tried[auth.method()] = true } - tried[auth.method()] = true if methods == nil { methods = lastMethods } @@ -82,7 +91,7 @@ type AuthMethod interface { // If authentication is not successful, a []string of alternative // method names is returned. If the slice is nil, it will be ignored // and the previous set of possible methods will be reused. - auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error) + auth(session []byte, user string, p packetConn, rand io.Reader) (authResult, []string, error) // method returns the RFC 4252 method name. method() string @@ -91,13 +100,13 @@ type AuthMethod interface { // "none" authentication, RFC 4252 section 5.2. type noneAuth int -func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { if err := c.writePacket(Marshal(&userAuthRequestMsg{ User: user, Service: serviceSSH, Method: "none", })); err != nil { - return false, nil, err + return authFailure, nil, err } return handleAuthResponse(c) @@ -111,7 +120,7 @@ func (n *noneAuth) method() string { // a function call, e.g. by prompting the user. type passwordCallback func() (password string, err error) -func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { type passwordAuthMsg struct { User string `sshtype:"50"` Service string @@ -125,7 +134,7 @@ func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand // The program may only find out that the user doesn't have a password // when prompting. if err != nil { - return false, nil, err + return authFailure, nil, err } if err := c.writePacket(Marshal(&passwordAuthMsg{ @@ -135,7 +144,7 @@ func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand Reply: false, Password: pw, })); err != nil { - return false, nil, err + return authFailure, nil, err } return handleAuthResponse(c) @@ -178,32 +187,27 @@ func (cb publicKeyCallback) method() string { return "publickey" } -func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { - // Authentication is performed in two stages. The first stage sends an - // enquiry to test if each key is acceptable to the remote. The second - // stage attempts to authenticate with the valid keys obtained in the - // first stage. +func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { + // Authentication is performed by sending an enquiry to test if a key is + // acceptable to the remote. If the key is acceptable, the client will + // attempt to authenticate with the valid key. If not the client will repeat + // the process with the remaining keys. signers, err := cb() if err != nil { - return false, nil, err + return authFailure, nil, err } - var validKeys []Signer + var methods []string for _, signer := range signers { - if ok, err := validateKey(signer.PublicKey(), user, c); ok { - validKeys = append(validKeys, signer) - } else { - if err != nil { - return false, nil, err - } + ok, err := validateKey(signer.PublicKey(), user, c) + if err != nil { + return authFailure, nil, err + } + if !ok { + continue } - } - // methods that may continue if this auth is not successful. - var methods []string - for _, signer := range validKeys { pub := signer.PublicKey() - pubKey := pub.Marshal() sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{ User: user, @@ -211,7 +215,7 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand Method: cb.method(), }, []byte(pub.Type()), pubKey)) if err != nil { - return false, nil, err + return authFailure, nil, err } // manually wrap the serialized signature in a string @@ -229,18 +233,34 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand } p := Marshal(&msg) if err := c.writePacket(p); err != nil { - return false, nil, err + return authFailure, nil, err } - var success bool + var success authResult success, methods, err = handleAuthResponse(c) if err != nil { - return false, nil, err + return authFailure, nil, err } - if success { + + // If authentication succeeds or the list of available methods does not + // contain the "publickey" method, do not attempt to authenticate with any + // other keys. According to RFC 4252 Section 7, the latter can occur when + // additional authentication methods are required. + if success == authSuccess || !containsMethod(methods, cb.method()) { return success, methods, err } } - return false, methods, nil + + return authFailure, methods, nil +} + +func containsMethod(methods []string, method string) bool { + for _, m := range methods { + if m == method { + return true + } + } + + return false } // validateKey validates the key provided is acceptable to the server. @@ -272,7 +292,9 @@ func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { } switch packet[0] { case msgUserAuthBanner: - // TODO(gpaul): add callback to present the banner to the user + if err := handleBannerResponse(c, packet); err != nil { + return false, err + } case msgUserAuthPubKeyOk: var msg userAuthPubKeyOkMsg if err := Unmarshal(packet, &msg); err != nil { @@ -305,30 +327,53 @@ func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMet // handleAuthResponse returns whether the preceding authentication request succeeded // along with a list of remaining authentication methods to try next and // an error if an unexpected response was received. -func handleAuthResponse(c packetConn) (bool, []string, error) { +func handleAuthResponse(c packetConn) (authResult, []string, error) { for { packet, err := c.readPacket() if err != nil { - return false, nil, err + return authFailure, nil, err } switch packet[0] { case msgUserAuthBanner: - // TODO: add callback to present the banner to the user + if err := handleBannerResponse(c, packet); err != nil { + return authFailure, nil, err + } case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err } - return false, msg.Methods, nil + if msg.PartialSuccess { + return authPartialSuccess, msg.Methods, nil + } + return authFailure, msg.Methods, nil case msgUserAuthSuccess: - return true, nil, nil + return authSuccess, nil, nil default: - return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) + return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } +func handleBannerResponse(c packetConn, packet []byte) error { + var msg userAuthBannerMsg + if err := Unmarshal(packet, &msg); err != nil { + return err + } + + transport, ok := c.(*handshakeTransport) + if !ok { + return nil + } + + if transport.bannerCallback != nil { + return transport.bannerCallback(msg.Message) + } + + return nil +} + // KeyboardInteractiveChallenge should print questions, optionally // disabling echoing (e.g. for passwords), and return all the answers. // Challenge may be called multiple times in a single session. After @@ -338,7 +383,7 @@ func handleAuthResponse(c packetConn) (bool, []string, error) { // both CLI and GUI environments. type KeyboardInteractiveChallenge func(user, instruction string, questions []string, echos []bool) (answers []string, err error) -// KeyboardInteractive returns a AuthMethod using a prompt/response +// KeyboardInteractive returns an AuthMethod using a prompt/response // sequence controlled by the server. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { return challenge @@ -348,7 +393,7 @@ func (cb KeyboardInteractiveChallenge) method() string { return "keyboard-interactive" } -func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { type initiateMsg struct { User string `sshtype:"50"` Service string @@ -362,37 +407,42 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe Service: serviceSSH, Method: "keyboard-interactive", })); err != nil { - return false, nil, err + return authFailure, nil, err } for { packet, err := c.readPacket() if err != nil { - return false, nil, err + return authFailure, nil, err } // like handleAuthResponse, but with less options. switch packet[0] { case msgUserAuthBanner: - // TODO: Print banners during userauth. + if err := handleBannerResponse(c, packet); err != nil { + return authFailure, nil, err + } continue case msgUserAuthInfoRequest: // OK case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err + } + if msg.PartialSuccess { + return authPartialSuccess, msg.Methods, nil } - return false, msg.Methods, nil + return authFailure, msg.Methods, nil case msgUserAuthSuccess: - return true, nil, nil + return authSuccess, nil, nil default: - return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) + return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } var msg userAuthInfoRequestMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err } // Manually unpack the prompt/echo pairs. @@ -402,7 +452,7 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe for i := 0; i < int(msg.NumPrompts); i++ { prompt, r, ok := parseString(rest) if !ok || len(r) == 0 { - return false, nil, errors.New("ssh: prompt format error") + return authFailure, nil, errors.New("ssh: prompt format error") } prompts = append(prompts, string(prompt)) echos = append(echos, r[0] != 0) @@ -410,16 +460,16 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe } if len(rest) != 0 { - return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs") + return authFailure, nil, errors.New("ssh: extra data following keyboard-interactive pairs") } answers, err := cb(msg.User, msg.Instruction, prompts, echos) if err != nil { - return false, nil, err + return authFailure, nil, err } if len(answers) != len(prompts) { - return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") + return authFailure, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") } responseLength := 1 + 4 for _, a := range answers { @@ -435,7 +485,7 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe } if err := c.writePacket(serialized); err != nil { - return false, nil, err + return authFailure, nil, err } } } @@ -445,10 +495,10 @@ type retryableAuthMethod struct { maxTries int } -func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) { +func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok authResult, methods []string, err error) { for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { ok, methods, err = r.authMethod.auth(session, user, c, rand) - if ok || err != nil { // either success or error terminate + if ok != authFailure || err != nil { // either success, partial success or error terminate return ok, methods, err } } diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index 8656d0f85..04f3620b3 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -9,6 +9,7 @@ import ( "crypto/rand" "fmt" "io" + "math" "sync" _ "crypto/sha1" @@ -23,11 +24,21 @@ const ( serviceSSH = "ssh-connection" ) -// supportedCiphers specifies the supported ciphers in preference order. +// supportedCiphers lists ciphers we support but might not recommend. var supportedCiphers = []string{ "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", - "arcfour256", "arcfour128", + chacha20Poly1305ID, + "arcfour256", "arcfour128", "arcfour", + aes128cbcID, + tripledescbcID, +} + +// preferredCiphers specifies the default preference for ciphers. +var preferredCiphers = []string{ + "aes128-gcm@openssh.com", + chacha20Poly1305ID, + "aes128-ctr", "aes192-ctr", "aes256-ctr", } // supportedKexAlgos specifies the supported key-exchange algorithms in @@ -40,7 +51,7 @@ var supportedKexAlgos = []string{ kexAlgoDH14SHA1, kexAlgoDH1SHA1, } -// supportedKexAlgos specifies the supported host-key algorithms (i.e. methods +// supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods // of authenticating servers) in preference order. var supportedHostKeyAlgos = []string{ CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, @@ -186,7 +197,7 @@ type Config struct { // The maximum number of bytes sent or received after which a // new key is negotiated. It must be at least 256. If - // unspecified, 1 gigabyte is used. + // unspecified, a size suitable for the chosen cipher is used. RekeyThreshold uint64 // The allowed key exchanges algorithms. If unspecified then a @@ -210,7 +221,7 @@ func (c *Config) SetDefaults() { c.Rand = rand.Reader } if c.Ciphers == nil { - c.Ciphers = supportedCiphers + c.Ciphers = preferredCiphers } var ciphers []string for _, c := range c.Ciphers { @@ -230,17 +241,18 @@ func (c *Config) SetDefaults() { } if c.RekeyThreshold == 0 { - // RFC 4253, section 9 suggests rekeying after 1G. - c.RekeyThreshold = 1 << 30 - } - if c.RekeyThreshold < minRekeyThreshold { + // cipher specific default + } else if c.RekeyThreshold < minRekeyThreshold { c.RekeyThreshold = minRekeyThreshold + } else if c.RekeyThreshold >= math.MaxInt64 { + // Avoid weirdness if somebody uses -1 as a threshold. + c.RekeyThreshold = math.MaxInt64 } } // buildDataSignedForAuth returns the data that is signed in order to prove // possession of a private key. See RFC 4252, section 7. -func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { +func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { data := struct { Session []byte Type byte @@ -251,7 +263,7 @@ func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubK Algo []byte PubKey []byte }{ - sessionId, + sessionID, msgUserAuthRequest, req.User, req.Service, diff --git a/vendor/golang.org/x/crypto/ssh/connection.go b/vendor/golang.org/x/crypto/ssh/connection.go index e786f2f9a..fd6b0681b 100644 --- a/vendor/golang.org/x/crypto/ssh/connection.go +++ b/vendor/golang.org/x/crypto/ssh/connection.go @@ -25,7 +25,7 @@ type ConnMetadata interface { // User returns the user ID for this connection. User() string - // SessionID returns the sesson hash, also denoted by H. + // SessionID returns the session hash, also denoted by H. SessionID() []byte // ClientVersion returns the client's version string as hashed diff --git a/vendor/golang.org/x/crypto/ssh/doc.go b/vendor/golang.org/x/crypto/ssh/doc.go index d6be89466..67b7322c0 100644 --- a/vendor/golang.org/x/crypto/ssh/doc.go +++ b/vendor/golang.org/x/crypto/ssh/doc.go @@ -14,5 +14,8 @@ others. References: [PROTOCOL.certkeys]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?rev=HEAD [SSH-PARAMETERS]: http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1 + +This package does not fall under the stability promise of the Go language itself, +so its API may be changed when pressing needs arise. */ package ssh // import "golang.org/x/crypto/ssh" diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go index 8de650644..4f7912ecd 100644 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ b/vendor/golang.org/x/crypto/ssh/handshake.go @@ -74,10 +74,15 @@ type handshakeTransport struct { startKex chan *pendingKex // data for host key checking - hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error + hostKeyCallback HostKeyCallback dialAddress string remoteAddr net.Addr + // bannerCallback is non-empty if we are the client and it has been set in + // ClientConfig. In that case it is called during the user authentication + // dance to handle a custom server's message. + bannerCallback BannerCallback + // Algorithms agreed in the last key exchange. algorithms *algorithms @@ -107,6 +112,8 @@ func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, config: config, } + t.resetReadThresholds() + t.resetWriteThresholds() // We always start with a mandatory key exchange. t.requestKex <- struct{}{} @@ -118,6 +125,7 @@ func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byt t.dialAddress = dialAddr t.remoteAddr = addr t.hostKeyCallback = config.HostKeyCallback + t.bannerCallback = config.BannerCallback if config.HostKeyAlgorithms != nil { t.hostKeyAlgorithms = config.HostKeyAlgorithms } else { @@ -237,6 +245,17 @@ func (t *handshakeTransport) requestKeyExchange() { } } +func (t *handshakeTransport) resetWriteThresholds() { + t.writePacketsLeft = packetRekeyThreshold + if t.config.RekeyThreshold > 0 { + t.writeBytesLeft = int64(t.config.RekeyThreshold) + } else if t.algorithms != nil { + t.writeBytesLeft = t.algorithms.w.rekeyBytes() + } else { + t.writeBytesLeft = 1 << 30 + } +} + func (t *handshakeTransport) kexLoop() { write: @@ -285,12 +304,8 @@ write: t.writeError = err t.sentInitPacket = nil t.sentInitMsg = nil - t.writePacketsLeft = packetRekeyThreshold - if t.config.RekeyThreshold > 0 { - t.writeBytesLeft = int64(t.config.RekeyThreshold) - } else if t.algorithms != nil { - t.writeBytesLeft = t.algorithms.w.rekeyBytes() - } + + t.resetWriteThresholds() // we have completed the key exchange. Since the // reader is still blocked, it is safe to clear out @@ -344,6 +359,17 @@ write: // key exchange itself. const packetRekeyThreshold = (1 << 31) +func (t *handshakeTransport) resetReadThresholds() { + t.readPacketsLeft = packetRekeyThreshold + if t.config.RekeyThreshold > 0 { + t.readBytesLeft = int64(t.config.RekeyThreshold) + } else if t.algorithms != nil { + t.readBytesLeft = t.algorithms.r.rekeyBytes() + } else { + t.readBytesLeft = 1 << 30 + } +} + func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) { p, err := t.conn.readPacket() if err != nil { @@ -391,12 +417,7 @@ func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) { return nil, err } - t.readPacketsLeft = packetRekeyThreshold - if t.config.RekeyThreshold > 0 { - t.readBytesLeft = int64(t.config.RekeyThreshold) - } else { - t.readBytesLeft = t.algorithms.r.rekeyBytes() - } + t.resetReadThresholds() // By default, a key exchange is hidden from higher layers by // translating it into msgIgnore. @@ -574,7 +595,9 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error { } result.SessionID = t.sessionID - t.conn.prepareKeyChange(t.algorithms, result) + if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil { + return err + } if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil { return err } @@ -614,11 +637,9 @@ func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics * return nil, err } - if t.hostKeyCallback != nil { - err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) - if err != nil { - return nil, err - } + err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey) + if err != nil { + return nil, err } return result, nil diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go index c87fbebfd..f34bcc013 100644 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ b/vendor/golang.org/x/crypto/ssh/kex.go @@ -119,7 +119,7 @@ func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handsha return nil, err } - kInt, err := group.diffieHellman(kexDHReply.Y, x) + ki, err := group.diffieHellman(kexDHReply.Y, x) if err != nil { return nil, err } @@ -129,8 +129,8 @@ func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handsha writeString(h, kexDHReply.HostKey) writeInt(h, X) writeInt(h, kexDHReply.Y) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) return &kexResult{ @@ -164,7 +164,7 @@ func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handsha } Y := new(big.Int).Exp(group.g, y, group.p) - kInt, err := group.diffieHellman(kexDHInit.X, y) + ki, err := group.diffieHellman(kexDHInit.X, y) if err != nil { return nil, err } @@ -177,8 +177,8 @@ func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handsha writeInt(h, kexDHInit.X) writeInt(h, Y) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) H := h.Sum(nil) @@ -383,8 +383,8 @@ func init() { // 4253 and Oakley Group 2 in RFC 2409. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, + g: new(big.Int).SetInt64(2), + p: p, pMinus1: new(big.Int).Sub(p, bigOne), } @@ -393,8 +393,8 @@ func init() { p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16) kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{ - g: new(big.Int).SetInt64(2), - p: p, + g: new(big.Int).SetInt64(2), + p: p, pMinus1: new(big.Int).Sub(p, bigOne), } @@ -462,9 +462,9 @@ func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handsh writeString(h, kp.pub[:]) writeString(h, reply.EphemeralPubKey) - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + ki := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) return &kexResult{ @@ -510,9 +510,9 @@ func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handsh writeString(h, kexInit.ClientPubKey) writeString(h, kp.pub[:]) - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + ki := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) H := h.Sum(nil) diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index f38de9898..969804794 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -38,6 +38,16 @@ const ( KeyAlgoED25519 = "ssh-ed25519" ) +// These constants represent non-default signature algorithms that are supported +// as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See +// [PROTOCOL.agent] section 4.5.1 and +// https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10 +const ( + SigAlgoRSA = "ssh-rsa" + SigAlgoRSASHA2256 = "rsa-sha2-256" + SigAlgoRSASHA2512 = "rsa-sha2-512" +) + // parsePubKey parses a public key of the given algorithm. // Use ParsePublicKey for keys with prepended algorithm. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) { @@ -276,7 +286,8 @@ type PublicKey interface { Type() string // Marshal returns the serialized key data in SSH wire format, - // with the name prefix. + // with the name prefix. To unmarshal the returned data, use + // the ParsePublicKey function. Marshal() []byte // Verify that sig is a signature on the given data using this @@ -300,6 +311,19 @@ type Signer interface { Sign(rand io.Reader, data []byte) (*Signature, error) } +// A AlgorithmSigner is a Signer that also supports specifying a specific +// algorithm to use for signing. +type AlgorithmSigner interface { + Signer + + // SignWithAlgorithm is like Signer.Sign, but allows specification of a + // non-default signing algorithm. See the SigAlgo* constants in this + // package for signature algorithms supported by this package. Callers may + // pass an empty string for the algorithm in which case the AlgorithmSigner + // will use its default algorithm. + SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) +} + type rsaPublicKey rsa.PublicKey func (r *rsaPublicKey) Type() string { @@ -348,13 +372,21 @@ func (r *rsaPublicKey) Marshal() []byte { } func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != r.Type() { + var hash crypto.Hash + switch sig.Format { + case SigAlgoRSA: + hash = crypto.SHA1 + case SigAlgoRSASHA2256: + hash = crypto.SHA256 + case SigAlgoRSASHA2512: + hash = crypto.SHA512 + default: return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type()) } - h := crypto.SHA1.New() + h := hash.New() h.Write(data) digest := h.Sum(nil) - return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob) + return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, sig.Blob) } func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { @@ -363,10 +395,21 @@ func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { type dsaPublicKey dsa.PublicKey -func (r *dsaPublicKey) Type() string { +func (k *dsaPublicKey) Type() string { return "ssh-dss" } +func checkDSAParams(param *dsa.Parameters) error { + // SSH specifies FIPS 186-2, which only provided a single size + // (1024 bits) DSA key. FIPS 186-3 allows for larger key + // sizes, which would confuse SSH. + if l := param.P.BitLen(); l != 1024 { + return fmt.Errorf("ssh: unsupported DSA key size %d", l) + } + + return nil +} + // parseDSA parses an DSA key according to RFC 4253, section 6.6. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) { var w struct { @@ -377,13 +420,18 @@ func parseDSA(in []byte) (out PublicKey, rest []byte, err error) { return nil, nil, err } + param := dsa.Parameters{ + P: w.P, + Q: w.Q, + G: w.G, + } + if err := checkDSAParams(¶m); err != nil { + return nil, nil, err + } + key := &dsaPublicKey{ - Parameters: dsa.Parameters{ - P: w.P, - Q: w.Q, - G: w.G, - }, - Y: w.Y, + Parameters: param, + Y: w.Y, } return key, w.Rest, nil } @@ -442,6 +490,14 @@ func (k *dsaPrivateKey) PublicKey() PublicKey { } func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { + return k.SignWithAlgorithm(rand, data, "") +} + +func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { + if algorithm != "" && algorithm != k.PublicKey().Type() { + return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) + } + h := crypto.SHA1.New() h.Write(data) digest := h.Sum(nil) @@ -465,12 +521,12 @@ func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { type ecdsaPublicKey ecdsa.PublicKey -func (key *ecdsaPublicKey) Type() string { - return "ecdsa-sha2-" + key.nistID() +func (k *ecdsaPublicKey) Type() string { + return "ecdsa-sha2-" + k.nistID() } -func (key *ecdsaPublicKey) nistID() string { - switch key.Params().BitSize { +func (k *ecdsaPublicKey) nistID() string { + switch k.Params().BitSize { case 256: return "nistp256" case 384: @@ -483,7 +539,7 @@ func (key *ecdsaPublicKey) nistID() string { type ed25519PublicKey ed25519.PublicKey -func (key ed25519PublicKey) Type() string { +func (k ed25519PublicKey) Type() string { return KeyAlgoED25519 } @@ -502,23 +558,23 @@ func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { return (ed25519PublicKey)(key), w.Rest, nil } -func (key ed25519PublicKey) Marshal() []byte { +func (k ed25519PublicKey) Marshal() []byte { w := struct { Name string KeyBytes []byte }{ KeyAlgoED25519, - []byte(key), + []byte(k), } return Marshal(&w) } -func (key ed25519PublicKey) Verify(b []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) +func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } - edKey := (ed25519.PublicKey)(key) + edKey := (ed25519.PublicKey)(k) if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { return errors.New("ssh: signature did not verify") } @@ -579,9 +635,9 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { return (*ecdsaPublicKey)(key), w.Rest, nil } -func (key *ecdsaPublicKey) Marshal() []byte { +func (k *ecdsaPublicKey) Marshal() []byte { // See RFC 5656, section 3.1. - keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y) + keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y) // ECDSA publickey struct layout should match the struct used by // parseECDSACert in the x/crypto/ssh/agent package. w := struct { @@ -589,20 +645,20 @@ func (key *ecdsaPublicKey) Marshal() []byte { ID string Key []byte }{ - key.Type(), - key.nistID(), + k.Type(), + k.nistID(), keyBytes, } return Marshal(&w) } -func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) +func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } - h := ecHash(key.Curve).New() + h := ecHash(k.Curve).New() h.Write(data) digest := h.Sum(nil) @@ -619,7 +675,7 @@ func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { return err } - if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) { + if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) { return nil } return errors.New("ssh: signature did not verify") @@ -630,19 +686,28 @@ func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey { } // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, -// *ecdsa.PrivateKey or any other crypto.Signer and returns a corresponding -// Signer instance. ECDSA keys must use P-256, P-384 or P-521. +// *ecdsa.PrivateKey or any other crypto.Signer and returns a +// corresponding Signer instance. ECDSA keys must use P-256, P-384 or +// P-521. DSA keys must use parameter size L1024N160. func NewSignerFromKey(key interface{}) (Signer, error) { switch key := key.(type) { case crypto.Signer: return NewSignerFromSigner(key) case *dsa.PrivateKey: - return &dsaPrivateKey{key}, nil + return newDSAPrivateKey(key) default: return nil, fmt.Errorf("ssh: unsupported key type %T", key) } } +func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) { + if err := checkDSAParams(&key.PublicKey.Parameters); err != nil { + return nil, err + } + + return &dsaPrivateKey{key}, nil +} + type wrappedSigner struct { signer crypto.Signer pubKey PublicKey @@ -665,16 +730,42 @@ func (s *wrappedSigner) PublicKey() PublicKey { } func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { + return s.SignWithAlgorithm(rand, data, "") +} + +func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) { var hashFunc crypto.Hash - switch key := s.pubKey.(type) { - case *rsaPublicKey, *dsaPublicKey: - hashFunc = crypto.SHA1 - case *ecdsaPublicKey: - hashFunc = ecHash(key.Curve) - case ed25519PublicKey: - default: - return nil, fmt.Errorf("ssh: unsupported key type %T", key) + if _, ok := s.pubKey.(*rsaPublicKey); ok { + // RSA keys support a few hash functions determined by the requested signature algorithm + switch algorithm { + case "", SigAlgoRSA: + algorithm = SigAlgoRSA + hashFunc = crypto.SHA1 + case SigAlgoRSASHA2256: + hashFunc = crypto.SHA256 + case SigAlgoRSASHA2512: + hashFunc = crypto.SHA512 + default: + return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) + } + } else { + // The only supported algorithm for all other key types is the same as the type of the key + if algorithm == "" { + algorithm = s.pubKey.Type() + } else if algorithm != s.pubKey.Type() { + return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm) + } + + switch key := s.pubKey.(type) { + case *dsaPublicKey: + hashFunc = crypto.SHA1 + case *ecdsaPublicKey: + hashFunc = ecHash(key.Curve) + case ed25519PublicKey: + default: + return nil, fmt.Errorf("ssh: unsupported key type %T", key) + } } var digest []byte @@ -719,7 +810,7 @@ func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) { } return &Signature{ - Format: s.pubKey.Type(), + Format: algorithm, Blob: signature, }, nil } @@ -733,7 +824,7 @@ func NewPublicKey(key interface{}) (PublicKey, error) { return (*rsaPublicKey)(key), nil case *ecdsa.PublicKey: if !supportedEllipticCurve(key.Curve) { - return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.") + return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported") } return (*ecdsaPublicKey)(key), nil case *dsa.PublicKey: @@ -756,6 +847,18 @@ func ParsePrivateKey(pemBytes []byte) (Signer, error) { return NewSignerFromKey(key) } +// ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private +// key and passphrase. It supports the same keys as +// ParseRawPrivateKeyWithPassphrase. +func ParsePrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (Signer, error) { + key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase) + if err != nil { + return nil, err + } + + return NewSignerFromKey(key) +} + // encryptedBlock tells whether a private key is // encrypted by examining its Proc-Type header // for a mention of ENCRYPTED @@ -765,7 +868,7 @@ func encryptedBlock(block *pem.Block) bool { } // ParseRawPrivateKey returns a private key from a PEM encoded private key. It -// supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys. +// supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { block, _ := pem.Decode(pemBytes) if block == nil { @@ -779,6 +882,9 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { switch block.Type { case "RSA PRIVATE KEY": return x509.ParsePKCS1PrivateKey(block.Bytes) + // RFC5208 - https://tools.ietf.org/html/rfc5208 + case "PRIVATE KEY": + return x509.ParsePKCS8PrivateKey(block.Bytes) case "EC PRIVATE KEY": return x509.ParseECPrivateKey(block.Bytes) case "DSA PRIVATE KEY": @@ -790,6 +896,43 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { } } +// ParseRawPrivateKeyWithPassphrase returns a private key decrypted with +// passphrase from a PEM encoded private key. If wrong passphrase, return +// x509.IncorrectPasswordError. +func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) { + block, _ := pem.Decode(pemBytes) + if block == nil { + return nil, errors.New("ssh: no key found") + } + buf := block.Bytes + + if encryptedBlock(block) { + if x509.IsEncryptedPEMBlock(block) { + var err error + buf, err = x509.DecryptPEMBlock(block, passPhrase) + if err != nil { + if err == x509.IncorrectPasswordError { + return nil, err + } + return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) + } + } + } + + switch block.Type { + case "RSA PRIVATE KEY": + return x509.ParsePKCS1PrivateKey(buf) + case "EC PRIVATE KEY": + return x509.ParseECPrivateKey(buf) + case "DSA PRIVATE KEY": + return ParseDSAPrivateKey(buf) + case "OPENSSH PRIVATE KEY": + return parseOpenSSHPrivateKey(buf) + default: + return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) + } +} + // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as // specified by the OpenSSL DSA man page. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { @@ -824,9 +967,9 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { // Implemented based on the documentation at // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key -func parseOpenSSHPrivateKey(key []byte) (*ed25519.PrivateKey, error) { - magic := append([]byte("openssh-key-v1"), 0) - if !bytes.Equal(magic, key[0:len(magic)]) { +func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { + const magic = "openssh-key-v1\x00" + if len(key) < len(magic) || string(key[:len(magic)]) != magic { return nil, errors.New("ssh: invalid openssh private key format") } remaining := key[len(magic):] @@ -844,14 +987,15 @@ func parseOpenSSHPrivateKey(key []byte) (*ed25519.PrivateKey, error) { return nil, err } + if w.KdfName != "none" || w.CipherName != "none" { + return nil, errors.New("ssh: cannot decode encrypted private keys") + } + pk1 := struct { Check1 uint32 Check2 uint32 Keytype string - Pub []byte - Priv []byte - Comment string - Pad []byte `ssh:"rest"` + Rest []byte `ssh:"rest"` }{} if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil { @@ -862,24 +1006,75 @@ func parseOpenSSHPrivateKey(key []byte) (*ed25519.PrivateKey, error) { return nil, errors.New("ssh: checkint mismatch") } - // we only handle ed25519 keys currently - if pk1.Keytype != KeyAlgoED25519 { - return nil, errors.New("ssh: unhandled key type") - } + // we only handle ed25519 and rsa keys currently + switch pk1.Keytype { + case KeyAlgoRSA: + // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773 + key := struct { + N *big.Int + E *big.Int + D *big.Int + Iqmp *big.Int + P *big.Int + Q *big.Int + Comment string + Pad []byte `ssh:"rest"` + }{} + + if err := Unmarshal(pk1.Rest, &key); err != nil { + return nil, err + } - for i, b := range pk1.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") + for i, b := range key.Pad { + if int(b) != i+1 { + return nil, errors.New("ssh: padding not as expected") + } } - } - if len(pk1.Priv) != ed25519.PrivateKeySize { - return nil, errors.New("ssh: private key unexpected length") - } + pk := &rsa.PrivateKey{ + PublicKey: rsa.PublicKey{ + N: key.N, + E: int(key.E.Int64()), + }, + D: key.D, + Primes: []*big.Int{key.P, key.Q}, + } + + if err := pk.Validate(); err != nil { + return nil, err + } + + pk.Precompute() - pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) - copy(pk, pk1.Priv) - return &pk, nil + return pk, nil + case KeyAlgoED25519: + key := struct { + Pub []byte + Priv []byte + Comment string + Pad []byte `ssh:"rest"` + }{} + + if err := Unmarshal(pk1.Rest, &key); err != nil { + return nil, err + } + + if len(key.Priv) != ed25519.PrivateKeySize { + return nil, errors.New("ssh: private key unexpected length") + } + + for i, b := range key.Pad { + if int(b) != i+1 { + return nil, errors.New("ssh: padding not as expected") + } + } + + pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) + copy(pk, key.Priv) + return &pk, nil + default: + return nil, errors.New("ssh: unhandled key type") + } } // FingerprintLegacyMD5 returns the user presentation of the key's diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go index e6ecd3afa..08d281173 100644 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ b/vendor/golang.org/x/crypto/ssh/messages.go @@ -23,10 +23,6 @@ const ( msgUnimplemented = 3 msgDebug = 4 msgNewKeys = 21 - - // Standard authentication messages - msgUserAuthSuccess = 52 - msgUserAuthBanner = 53 ) // SSH messages: @@ -137,6 +133,18 @@ type userAuthFailureMsg struct { PartialSuccess bool } +// See RFC 4252, section 5.1 +const msgUserAuthSuccess = 52 + +// See RFC 4252, section 5.4 +const msgUserAuthBanner = 53 + +type userAuthBannerMsg struct { + Message string `sshtype:"53"` + // unused, but required to allow message parsing + Language string +} + // See RFC 4256, section 3.2 const msgUserAuthInfoRequest = 60 const msgUserAuthInfoResponse = 61 @@ -154,7 +162,7 @@ const msgChannelOpen = 90 type channelOpenMsg struct { ChanType string `sshtype:"90"` - PeersId uint32 + PeersID uint32 PeersWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` @@ -165,7 +173,7 @@ const msgChannelData = 94 // Used for debug print outs of packets. type channelDataMsg struct { - PeersId uint32 `sshtype:"94"` + PeersID uint32 `sshtype:"94"` Length uint32 Rest []byte `ssh:"rest"` } @@ -174,8 +182,8 @@ type channelDataMsg struct { const msgChannelOpenConfirm = 91 type channelOpenConfirmMsg struct { - PeersId uint32 `sshtype:"91"` - MyId uint32 + PeersID uint32 `sshtype:"91"` + MyID uint32 MyWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` @@ -185,7 +193,7 @@ type channelOpenConfirmMsg struct { const msgChannelOpenFailure = 92 type channelOpenFailureMsg struct { - PeersId uint32 `sshtype:"92"` + PeersID uint32 `sshtype:"92"` Reason RejectionReason Message string Language string @@ -194,7 +202,7 @@ type channelOpenFailureMsg struct { const msgChannelRequest = 98 type channelRequestMsg struct { - PeersId uint32 `sshtype:"98"` + PeersID uint32 `sshtype:"98"` Request string WantReply bool RequestSpecificData []byte `ssh:"rest"` @@ -204,28 +212,28 @@ type channelRequestMsg struct { const msgChannelSuccess = 99 type channelRequestSuccessMsg struct { - PeersId uint32 `sshtype:"99"` + PeersID uint32 `sshtype:"99"` } // See RFC 4254, section 5.4. const msgChannelFailure = 100 type channelRequestFailureMsg struct { - PeersId uint32 `sshtype:"100"` + PeersID uint32 `sshtype:"100"` } // See RFC 4254, section 5.3 const msgChannelClose = 97 type channelCloseMsg struct { - PeersId uint32 `sshtype:"97"` + PeersID uint32 `sshtype:"97"` } // See RFC 4254, section 5.3 const msgChannelEOF = 96 type channelEOFMsg struct { - PeersId uint32 `sshtype:"96"` + PeersID uint32 `sshtype:"96"` } // See RFC 4254, section 4 @@ -255,7 +263,7 @@ type globalRequestFailureMsg struct { const msgChannelWindowAdjust = 93 type windowAdjustMsg struct { - PeersId uint32 `sshtype:"93"` + PeersID uint32 `sshtype:"93"` AdditionalBytes uint32 } diff --git a/vendor/golang.org/x/crypto/ssh/mux.go b/vendor/golang.org/x/crypto/ssh/mux.go index 27a527c10..f19016270 100644 --- a/vendor/golang.org/x/crypto/ssh/mux.go +++ b/vendor/golang.org/x/crypto/ssh/mux.go @@ -278,7 +278,7 @@ func (m *mux) handleChannelOpen(packet []byte) error { if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { failMsg := channelOpenFailureMsg{ - PeersId: msg.PeersId, + PeersID: msg.PeersID, Reason: ConnectionFailed, Message: "invalid request", Language: "en_US.UTF-8", @@ -287,7 +287,7 @@ func (m *mux) handleChannelOpen(packet []byte) error { } c := m.newChannel(msg.ChanType, channelInbound, msg.TypeSpecificData) - c.remoteId = msg.PeersId + c.remoteId = msg.PeersID c.maxRemotePayload = msg.MaxPacketSize c.remoteWin.add(msg.PeersWindow) m.incomingChannels <- c @@ -313,7 +313,7 @@ func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { PeersWindow: ch.myWindow, MaxPacketSize: ch.maxIncomingPayload, TypeSpecificData: extra, - PeersId: ch.localId, + PeersID: ch.localId, } if err := m.sendMessage(open); err != nil { return nil, err diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go index 77c84d165..e86e89661 100644 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ b/vendor/golang.org/x/crypto/ssh/server.go @@ -14,23 +14,34 @@ import ( ) // The Permissions type holds fine-grained permissions that are -// specific to a user or a specific authentication method for a -// user. Permissions, except for "source-address", must be enforced in -// the server application layer, after successful authentication. The -// Permissions are passed on in ServerConn so a server implementation -// can honor them. +// specific to a user or a specific authentication method for a user. +// The Permissions value for a successful authentication attempt is +// available in ServerConn, so it can be used to pass information from +// the user-authentication phase to the application layer. type Permissions struct { - // Critical options restrict default permissions. Common - // restrictions are "source-address" and "force-command". If - // the server cannot enforce the restriction, or does not - // recognize it, the user should not authenticate. + // CriticalOptions indicate restrictions to the default + // permissions, and are typically used in conjunction with + // user certificates. The standard for SSH certificates + // defines "force-command" (only allow the given command to + // execute) and "source-address" (only allow connections from + // the given address). The SSH package currently only enforces + // the "source-address" critical option. It is up to server + // implementations to enforce other critical options, such as + // "force-command", by checking them after the SSH handshake + // is successful. In general, SSH servers should reject + // connections that specify critical options that are unknown + // or not supported. CriticalOptions map[string]string // Extensions are extra functionality that the server may - // offer on authenticated connections. Common extensions are - // "permit-agent-forwarding", "permit-X11-forwarding". Lack of - // support for an extension does not preclude authenticating a - // user. + // offer on authenticated connections. Lack of support for an + // extension does not preclude authenticating a user. Common + // extensions are "permit-agent-forwarding", + // "permit-X11-forwarding". The Go SSH library currently does + // not act on any extension, and it is up to server + // implementations to honor them. Extensions can be used to + // pass data from the authentication callbacks to the server + // application layer. Extensions map[string]string } @@ -45,13 +56,24 @@ type ServerConfig struct { // authenticating. NoClientAuth bool + // MaxAuthTries specifies the maximum number of authentication attempts + // permitted per connection. If set to a negative number, the number of + // attempts are unlimited. If set to zero, the number of attempts are limited + // to 6. + MaxAuthTries int + // PasswordCallback, if non-nil, is called when a user // attempts to authenticate using a password. PasswordCallback func(conn ConnMetadata, password []byte) (*Permissions, error) - // PublicKeyCallback, if non-nil, is called when a client attempts public - // key authentication. It must return true if the given public key is - // valid for the given user. For example, see CertChecker.Authenticate. + // PublicKeyCallback, if non-nil, is called when a client + // offers a public key for authentication. It must return a nil error + // if the given public key can be used to authenticate the + // given user. For example, see CertChecker.Authenticate. A + // call to this function does not guarantee that the key + // offered is in fact used to authenticate. To record any data + // depending on the public key, store it inside a + // Permissions.Extensions entry. PublicKeyCallback func(conn ConnMetadata, key PublicKey) (*Permissions, error) // KeyboardInteractiveCallback, if non-nil, is called when @@ -73,6 +95,10 @@ type ServerConfig struct { // Note that RFC 4253 section 4.2 requires that this string start with // "SSH-2.0-". ServerVersion string + + // BannerCallback, if present, is called and the return string is sent to + // the client after key exchange completed but before authentication. + BannerCallback func(conn ConnMetadata) string } // AddHostKey adds a private key as a host key. If an existing host @@ -140,9 +166,16 @@ type ServerConn struct { // unsuccessful, it closes the connection and returns an error. The // Request and NewChannel channels must be serviced, or the connection // will hang. +// +// The returned error may be of type *ServerAuthError for +// authentication errors. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) { fullConf := *config fullConf.SetDefaults() + if fullConf.MaxAuthTries == 0 { + fullConf.MaxAuthTries = 6 + } + s := &connection{ sshConn: sshConn{conn: c}, } @@ -226,7 +259,7 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) func isAcceptableAlgo(algo string) bool { switch algo { case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01: + CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: return true } return false @@ -262,15 +295,60 @@ func checkSourceAddress(addr net.Addr, sourceAddrs string) error { return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr) } +// ServerAuthError represents server authentication errors and is +// sometimes returned by NewServerConn. It appends any authentication +// errors that may occur, and is returned if all of the authentication +// methods provided by the user failed to authenticate. +type ServerAuthError struct { + // Errors contains authentication errors returned by the authentication + // callback methods. The first entry is typically ErrNoAuth. + Errors []error +} + +func (l ServerAuthError) Error() string { + var errs []string + for _, err := range l.Errors { + errs = append(errs, err.Error()) + } + return "[" + strings.Join(errs, ", ") + "]" +} + +// ErrNoAuth is the error value returned if no +// authentication method has been passed yet. This happens as a normal +// part of the authentication loop, since the client first tries +// 'none' authentication to discover available methods. +// It is returned in ServerAuthError.Errors from NewServerConn. +var ErrNoAuth = errors.New("ssh: no auth passed yet") + func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) { sessionID := s.transport.getSessionID() var cache pubKeyCache var perms *Permissions + authFailures := 0 + var authErrs []error + var displayedBanner bool + userAuthLoop: for { + if authFailures >= config.MaxAuthTries && config.MaxAuthTries > 0 { + discMsg := &disconnectMsg{ + Reason: 2, + Message: "too many authentication failures", + } + + if err := s.transport.writePacket(Marshal(discMsg)); err != nil { + return nil, err + } + + return nil, discMsg + } + var userAuthReq userAuthRequestMsg if packet, err := s.transport.readPacket(); err != nil { + if err == io.EOF { + return nil, &ServerAuthError{Errors: authErrs} + } return nil, err } else if err = Unmarshal(packet, &userAuthReq); err != nil { return nil, err @@ -281,14 +359,33 @@ userAuthLoop: } s.user = userAuthReq.User + + if !displayedBanner && config.BannerCallback != nil { + displayedBanner = true + msg := config.BannerCallback(s) + if msg != "" { + bannerMsg := &userAuthBannerMsg{ + Message: msg, + } + if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil { + return nil, err + } + } + } + perms = nil - authErr := errors.New("no auth passed yet") + authErr := ErrNoAuth switch userAuthReq.Method { case "none": if config.NoClientAuth { authErr = nil } + + // allow initial attempt of 'none' without penalty + if authFailures == 0 { + authFailures-- + } case "password": if config.PasswordCallback == nil { authErr = errors.New("ssh: password auth not configured") @@ -307,7 +404,7 @@ userAuthLoop: perms, authErr = config.PasswordCallback(s, password) case "keyboard-interactive": if config.KeyboardInteractiveCallback == nil { - authErr = errors.New("ssh: keyboard-interactive auth not configubred") + authErr = errors.New("ssh: keyboard-interactive auth not configured") break } @@ -360,6 +457,7 @@ userAuthLoop: if isQuery { // The client can query if the given public key // would be okay. + if len(payload) > 0 { return nil, parseError(msgUserAuthRequest) } @@ -386,6 +484,7 @@ userAuthLoop: // sig.Format. This is usually the same, but // for certs, the names differ. if !isAcceptableAlgo(sig.Format) { + authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format) break } signedData := buildDataSignedForAuth(sessionID, userAuthReq, algoBytes, pubKeyData) @@ -401,6 +500,8 @@ userAuthLoop: authErr = fmt.Errorf("ssh: unknown method %q", userAuthReq.Method) } + authErrs = append(authErrs, authErr) + if config.AuthLogCallback != nil { config.AuthLogCallback(s, userAuthReq.Method, authErr) } @@ -409,6 +510,8 @@ userAuthLoop: break userAuthLoop } + authFailures++ + var failureMsg userAuthFailureMsg if config.PasswordCallback != nil { failureMsg.Methods = append(failureMsg.Methods, "password") diff --git a/vendor/golang.org/x/crypto/ssh/session.go b/vendor/golang.org/x/crypto/ssh/session.go index 17e2aa85c..d3321f6b7 100644 --- a/vendor/golang.org/x/crypto/ssh/session.go +++ b/vendor/golang.org/x/crypto/ssh/session.go @@ -231,6 +231,26 @@ func (s *Session) RequestSubsystem(subsystem string) error { return err } +// RFC 4254 Section 6.7. +type ptyWindowChangeMsg struct { + Columns uint32 + Rows uint32 + Width uint32 + Height uint32 +} + +// WindowChange informs the remote host about a terminal window dimension change to h rows and w columns. +func (s *Session) WindowChange(h, w int) error { + req := ptyWindowChangeMsg{ + Columns: uint32(w), + Rows: uint32(h), + Width: uint32(w * 8), + Height: uint32(h * 8), + } + _, err := s.ch.SendRequest("window-change", false, Marshal(&req)) + return err +} + // RFC 4254 Section 6.9. type signalMsg struct { Signal string @@ -386,7 +406,7 @@ func (s *Session) Wait() error { s.stdinPipeWriter.Close() } var copyError error - for _ = range s.copyFuncs { + for range s.copyFuncs { if err := <-s.errors; err != nil && copyError == nil { copyError = err } diff --git a/vendor/golang.org/x/crypto/ssh/streamlocal.go b/vendor/golang.org/x/crypto/ssh/streamlocal.go new file mode 100644 index 000000000..b171b330b --- /dev/null +++ b/vendor/golang.org/x/crypto/ssh/streamlocal.go @@ -0,0 +1,116 @@ +package ssh + +import ( + "errors" + "io" + "net" +) + +// streamLocalChannelOpenDirectMsg is a struct used for SSH_MSG_CHANNEL_OPEN message +// with "direct-streamlocal@openssh.com" string. +// +// See openssh-portable/PROTOCOL, section 2.4. connection: Unix domain socket forwarding +// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL#L235 +type streamLocalChannelOpenDirectMsg struct { + socketPath string + reserved0 string + reserved1 uint32 +} + +// forwardedStreamLocalPayload is a struct used for SSH_MSG_CHANNEL_OPEN message +// with "forwarded-streamlocal@openssh.com" string. +type forwardedStreamLocalPayload struct { + SocketPath string + Reserved0 string +} + +// streamLocalChannelForwardMsg is a struct used for SSH2_MSG_GLOBAL_REQUEST message +// with "streamlocal-forward@openssh.com"/"cancel-streamlocal-forward@openssh.com" string. +type streamLocalChannelForwardMsg struct { + socketPath string +} + +// ListenUnix is similar to ListenTCP but uses a Unix domain socket. +func (c *Client) ListenUnix(socketPath string) (net.Listener, error) { + c.handleForwardsOnce.Do(c.handleForwards) + m := streamLocalChannelForwardMsg{ + socketPath, + } + // send message + ok, _, err := c.SendRequest("streamlocal-forward@openssh.com", true, Marshal(&m)) + if err != nil { + return nil, err + } + if !ok { + return nil, errors.New("ssh: streamlocal-forward@openssh.com request denied by peer") + } + ch := c.forwards.add(&net.UnixAddr{Name: socketPath, Net: "unix"}) + + return &unixListener{socketPath, c, ch}, nil +} + +func (c *Client) dialStreamLocal(socketPath string) (Channel, error) { + msg := streamLocalChannelOpenDirectMsg{ + socketPath: socketPath, + } + ch, in, err := c.OpenChannel("direct-streamlocal@openssh.com", Marshal(&msg)) + if err != nil { + return nil, err + } + go DiscardRequests(in) + return ch, err +} + +type unixListener struct { + socketPath string + + conn *Client + in <-chan forward +} + +// Accept waits for and returns the next connection to the listener. +func (l *unixListener) Accept() (net.Conn, error) { + s, ok := <-l.in + if !ok { + return nil, io.EOF + } + ch, incoming, err := s.newCh.Accept() + if err != nil { + return nil, err + } + go DiscardRequests(incoming) + + return &chanConn{ + Channel: ch, + laddr: &net.UnixAddr{ + Name: l.socketPath, + Net: "unix", + }, + raddr: &net.UnixAddr{ + Name: "@", + Net: "unix", + }, + }, nil +} + +// Close closes the listener. +func (l *unixListener) Close() error { + // this also closes the listener. + l.conn.forwards.remove(&net.UnixAddr{Name: l.socketPath, Net: "unix"}) + m := streamLocalChannelForwardMsg{ + l.socketPath, + } + ok, _, err := l.conn.SendRequest("cancel-streamlocal-forward@openssh.com", true, Marshal(&m)) + if err == nil && !ok { + err = errors.New("ssh: cancel-streamlocal-forward@openssh.com failed") + } + return err +} + +// Addr returns the listener's network address. +func (l *unixListener) Addr() net.Addr { + return &net.UnixAddr{ + Name: l.socketPath, + Net: "unix", + } +} diff --git a/vendor/golang.org/x/crypto/ssh/tcpip.go b/vendor/golang.org/x/crypto/ssh/tcpip.go index 6151241ff..80d35f5ec 100644 --- a/vendor/golang.org/x/crypto/ssh/tcpip.go +++ b/vendor/golang.org/x/crypto/ssh/tcpip.go @@ -20,12 +20,20 @@ import ( // addr. Incoming connections will be available by calling Accept on // the returned net.Listener. The listener must be serviced, or the // SSH connection may hang. +// N must be "tcp", "tcp4", "tcp6", or "unix". func (c *Client) Listen(n, addr string) (net.Listener, error) { - laddr, err := net.ResolveTCPAddr(n, addr) - if err != nil { - return nil, err + switch n { + case "tcp", "tcp4", "tcp6": + laddr, err := net.ResolveTCPAddr(n, addr) + if err != nil { + return nil, err + } + return c.ListenTCP(laddr) + case "unix": + return c.ListenUnix(addr) + default: + return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } - return c.ListenTCP(laddr) } // Automatic port allocation is broken with OpenSSH before 6.0. See @@ -82,10 +90,19 @@ type channelForwardMsg struct { rport uint32 } +// handleForwards starts goroutines handling forwarded connections. +// It's called on first use by (*Client).ListenTCP to not launch +// goroutines until needed. +func (c *Client) handleForwards() { + go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-tcpip")) + go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-streamlocal@openssh.com")) +} + // ListenTCP requests the remote peer open a listening socket // on laddr. Incoming connections will be available by calling // Accept on the returned net.Listener. func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { + c.handleForwardsOnce.Do(c.handleForwards) if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { return c.autoPortListenWorkaround(laddr) } @@ -116,7 +133,7 @@ func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { } // Register this forward, using the port number we obtained. - ch := c.forwards.add(*laddr) + ch := c.forwards.add(laddr) return &tcpListener{laddr, c, ch}, nil } @@ -131,7 +148,7 @@ type forwardList struct { // forwardEntry represents an established mapping of a laddr on a // remote ssh server to a channel connected to a tcpListener. type forwardEntry struct { - laddr net.TCPAddr + laddr net.Addr c chan forward } @@ -139,16 +156,16 @@ type forwardEntry struct { // arguments to add/remove/lookup should be address as specified in // the original forward-request. type forward struct { - newCh NewChannel // the ssh client channel underlying this forward - raddr *net.TCPAddr // the raddr of the incoming connection + newCh NewChannel // the ssh client channel underlying this forward + raddr net.Addr // the raddr of the incoming connection } -func (l *forwardList) add(addr net.TCPAddr) chan forward { +func (l *forwardList) add(addr net.Addr) chan forward { l.Lock() defer l.Unlock() f := forwardEntry{ - addr, - make(chan forward, 1), + laddr: addr, + c: make(chan forward, 1), } l.entries = append(l.entries, f) return f.c @@ -176,44 +193,69 @@ func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) { func (l *forwardList) handleChannels(in <-chan NewChannel) { for ch := range in { - var payload forwardedTCPPayload - if err := Unmarshal(ch.ExtraData(), &payload); err != nil { - ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) - continue - } - - // RFC 4254 section 7.2 specifies that incoming - // addresses should list the address, in string - // format. It is implied that this should be an IP - // address, as it would be impossible to connect to it - // otherwise. - laddr, err := parseTCPAddr(payload.Addr, payload.Port) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue - } - raddr, err := parseTCPAddr(payload.OriginAddr, payload.OriginPort) - if err != nil { - ch.Reject(ConnectionFailed, err.Error()) - continue + var ( + laddr net.Addr + raddr net.Addr + err error + ) + switch channelType := ch.ChannelType(); channelType { + case "forwarded-tcpip": + var payload forwardedTCPPayload + if err = Unmarshal(ch.ExtraData(), &payload); err != nil { + ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) + continue + } + + // RFC 4254 section 7.2 specifies that incoming + // addresses should list the address, in string + // format. It is implied that this should be an IP + // address, as it would be impossible to connect to it + // otherwise. + laddr, err = parseTCPAddr(payload.Addr, payload.Port) + if err != nil { + ch.Reject(ConnectionFailed, err.Error()) + continue + } + raddr, err = parseTCPAddr(payload.OriginAddr, payload.OriginPort) + if err != nil { + ch.Reject(ConnectionFailed, err.Error()) + continue + } + + case "forwarded-streamlocal@openssh.com": + var payload forwardedStreamLocalPayload + if err = Unmarshal(ch.ExtraData(), &payload); err != nil { + ch.Reject(ConnectionFailed, "could not parse forwarded-streamlocal@openssh.com payload: "+err.Error()) + continue + } + laddr = &net.UnixAddr{ + Name: payload.SocketPath, + Net: "unix", + } + raddr = &net.UnixAddr{ + Name: "@", + Net: "unix", + } + default: + panic(fmt.Errorf("ssh: unknown channel type %s", channelType)) } - - if ok := l.forward(*laddr, *raddr, ch); !ok { + if ok := l.forward(laddr, raddr, ch); !ok { // Section 7.2, implementations MUST reject spurious incoming // connections. ch.Reject(Prohibited, "no forward for address") continue } + } } // remove removes the forward entry, and the channel feeding its // listener. -func (l *forwardList) remove(addr net.TCPAddr) { +func (l *forwardList) remove(addr net.Addr) { l.Lock() defer l.Unlock() for i, f := range l.entries { - if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port { + if addr.Network() == f.laddr.Network() && addr.String() == f.laddr.String() { l.entries = append(l.entries[:i], l.entries[i+1:]...) close(f.c) return @@ -231,12 +273,12 @@ func (l *forwardList) closeAll() { l.entries = nil } -func (l *forwardList) forward(laddr, raddr net.TCPAddr, ch NewChannel) bool { +func (l *forwardList) forward(laddr, raddr net.Addr, ch NewChannel) bool { l.Lock() defer l.Unlock() for _, f := range l.entries { - if laddr.IP.Equal(f.laddr.IP) && laddr.Port == f.laddr.Port { - f.c <- forward{ch, &raddr} + if laddr.Network() == f.laddr.Network() && laddr.String() == f.laddr.String() { + f.c <- forward{newCh: ch, raddr: raddr} return true } } @@ -262,7 +304,7 @@ func (l *tcpListener) Accept() (net.Conn, error) { } go DiscardRequests(incoming) - return &tcpChanConn{ + return &chanConn{ Channel: ch, laddr: l.laddr, raddr: s.raddr, @@ -277,7 +319,7 @@ func (l *tcpListener) Close() error { } // this also closes the listener. - l.conn.forwards.remove(*l.laddr) + l.conn.forwards.remove(l.laddr) ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m)) if err == nil && !ok { err = errors.New("ssh: cancel-tcpip-forward failed") @@ -293,29 +335,52 @@ func (l *tcpListener) Addr() net.Addr { // Dial initiates a connection to the addr from the remote host. // The resulting connection has a zero LocalAddr() and RemoteAddr(). func (c *Client) Dial(n, addr string) (net.Conn, error) { - // Parse the address into host and numeric port. - host, portString, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - port, err := strconv.ParseUint(portString, 10, 16) - if err != nil { - return nil, err - } - // Use a zero address for local and remote address. - zeroAddr := &net.TCPAddr{ - IP: net.IPv4zero, - Port: 0, - } - ch, err := c.dial(net.IPv4zero.String(), 0, host, int(port)) - if err != nil { - return nil, err + var ch Channel + switch n { + case "tcp", "tcp4", "tcp6": + // Parse the address into host and numeric port. + host, portString, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + port, err := strconv.ParseUint(portString, 10, 16) + if err != nil { + return nil, err + } + ch, err = c.dial(net.IPv4zero.String(), 0, host, int(port)) + if err != nil { + return nil, err + } + // Use a zero address for local and remote address. + zeroAddr := &net.TCPAddr{ + IP: net.IPv4zero, + Port: 0, + } + return &chanConn{ + Channel: ch, + laddr: zeroAddr, + raddr: zeroAddr, + }, nil + case "unix": + var err error + ch, err = c.dialStreamLocal(addr) + if err != nil { + return nil, err + } + return &chanConn{ + Channel: ch, + laddr: &net.UnixAddr{ + Name: "@", + Net: "unix", + }, + raddr: &net.UnixAddr{ + Name: addr, + Net: "unix", + }, + }, nil + default: + return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } - return &tcpChanConn{ - Channel: ch, - laddr: zeroAddr, - raddr: zeroAddr, - }, nil } // DialTCP connects to the remote address raddr on the network net, @@ -332,7 +397,7 @@ func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) if err != nil { return nil, err } - return &tcpChanConn{ + return &chanConn{ Channel: ch, laddr: laddr, raddr: raddr, @@ -366,26 +431,26 @@ type tcpChan struct { Channel // the backing channel } -// tcpChanConn fulfills the net.Conn interface without +// chanConn fulfills the net.Conn interface without // the tcpChan having to hold laddr or raddr directly. -type tcpChanConn struct { +type chanConn struct { Channel laddr, raddr net.Addr } // LocalAddr returns the local network address. -func (t *tcpChanConn) LocalAddr() net.Addr { +func (t *chanConn) LocalAddr() net.Addr { return t.laddr } // RemoteAddr returns the remote network address. -func (t *tcpChanConn) RemoteAddr() net.Addr { +func (t *chanConn) RemoteAddr() net.Addr { return t.raddr } // SetDeadline sets the read and write deadlines associated // with the connection. -func (t *tcpChanConn) SetDeadline(deadline time.Time) error { +func (t *chanConn) SetDeadline(deadline time.Time) error { if err := t.SetReadDeadline(deadline); err != nil { return err } @@ -396,12 +461,14 @@ func (t *tcpChanConn) SetDeadline(deadline time.Time) error { // A zero value for t means Read will not time out. // After the deadline, the error from Read will implement net.Error // with Timeout() == true. -func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error { +func (t *chanConn) SetReadDeadline(deadline time.Time) error { + // for compatibility with previous version, + // the error message contains "tcpChan" return errors.New("ssh: tcpChan: deadline not supported") } // SetWriteDeadline exists to satisfy the net.Conn interface // but is not implemented by this type. It always returns an error. -func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error { +func (t *chanConn) SetWriteDeadline(deadline time.Time) error { return errors.New("ssh: tcpChan: deadline not supported") } diff --git a/vendor/golang.org/x/crypto/ssh/transport.go b/vendor/golang.org/x/crypto/ssh/transport.go index f9780e0ae..f6fae1db4 100644 --- a/vendor/golang.org/x/crypto/ssh/transport.go +++ b/vendor/golang.org/x/crypto/ssh/transport.go @@ -6,6 +6,7 @@ package ssh import ( "bufio" + "bytes" "errors" "io" "log" @@ -76,17 +77,17 @@ type connectionState struct { // both directions are triggered by reading and writing a msgNewKey packet // respectively. func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error { - if ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult); err != nil { + ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult) + if err != nil { return err - } else { - t.reader.pendingKeyChange <- ciph } + t.reader.pendingKeyChange <- ciph - if ciph, err := newPacketCipher(t.writer.dir, algs.w, kexResult); err != nil { + ciph, err = newPacketCipher(t.writer.dir, algs.w, kexResult) + if err != nil { return err - } else { - t.writer.pendingKeyChange <- ciph } + t.writer.pendingKeyChange <- ciph return nil } @@ -139,7 +140,7 @@ func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) { case cipher := <-s.pendingKeyChange: s.packetCipher = cipher default: - return nil, errors.New("ssh: got bogus newkeys message.") + return nil, errors.New("ssh: got bogus newkeys message") } case msgDisconnect: @@ -232,52 +233,22 @@ var ( clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}} ) -// generateKeys generates key material for IV, MAC and encryption. -func generateKeys(d direction, algs directionAlgorithms, kex *kexResult) (iv, key, macKey []byte) { +// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as +// described in RFC 4253, section 6.4. direction should either be serverKeys +// (to setup server->client keys) or clientKeys (for client->server keys). +func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { cipherMode := cipherModes[algs.Cipher] macMode := macModes[algs.MAC] - iv = make([]byte, cipherMode.ivSize) - key = make([]byte, cipherMode.keySize) - macKey = make([]byte, macMode.keySize) + iv := make([]byte, cipherMode.ivSize) + key := make([]byte, cipherMode.keySize) + macKey := make([]byte, macMode.keySize) generateKeyMaterial(iv, d.ivTag, kex) generateKeyMaterial(key, d.keyTag, kex) generateKeyMaterial(macKey, d.macKeyTag, kex) - return -} - -// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as -// described in RFC 4253, section 6.4. direction should either be serverKeys -// (to setup server->client keys) or clientKeys (for client->server keys). -func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { - iv, key, macKey := generateKeys(d, algs, kex) - - if algs.Cipher == gcmCipherID { - return newGCMCipher(iv, key, macKey) - } - - if algs.Cipher == aes128cbcID { - return newAESCBCCipher(iv, key, macKey, algs) - } - - if algs.Cipher == tripledescbcID { - return newTripleDESCBCCipher(iv, key, macKey, algs) - } - c := &streamPacketCipher{ - mac: macModes[algs.MAC].new(macKey), - etm: macModes[algs.MAC].etm, - } - c.macResult = make([]byte, c.mac.Size()) - - var err error - c.cipher, err = cipherModes[algs.Cipher].createStream(key, iv) - if err != nil { - return nil, err - } - - return c, nil + return cipherModes[algs.Cipher].create(key, iv, macKey, algs) } // generateKeyMaterial fills out with key material generated from tag, K, H @@ -342,7 +313,7 @@ func readVersion(r io.Reader) ([]byte, error) { var ok bool var buf [1]byte - for len(versionString) < maxVersionStringBytes { + for length := 0; length < maxVersionStringBytes; length++ { _, err := io.ReadFull(r, buf[:]) if err != nil { return nil, err @@ -350,6 +321,13 @@ func readVersion(r io.Reader) ([]byte, error) { // The RFC says that the version should be terminated with \r\n // but several SSH servers actually only send a \n. if buf[0] == '\n' { + if !bytes.HasPrefix(versionString, []byte("SSH-")) { + // RFC 4253 says we need to ignore all version string lines + // except the one containing the SSH version (provided that + // all the lines do not exceed 255 bytes in total). + versionString = versionString[:0] + continue + } ok = true break } diff --git a/vendor/golang.org/x/net/AUTHORS b/vendor/golang.org/x/net/AUTHORS new file mode 100644 index 000000000..15167cd74 --- /dev/null +++ b/vendor/golang.org/x/net/AUTHORS @@ -0,0 +1,3 @@ +# This source code refers to The Go Authors for copyright purposes. +# The master list of authors is in the main Go distribution, +# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/golang.org/x/net/CONTRIBUTORS b/vendor/golang.org/x/net/CONTRIBUTORS new file mode 100644 index 000000000..1c4577e96 --- /dev/null +++ b/vendor/golang.org/x/net/CONTRIBUTORS @@ -0,0 +1,3 @@ +# This source code was written by the Go contributors. +# The master list of contributors is in the main Go distribution, +# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/golang.org/x/net/html/atom/gen.go b/vendor/golang.org/x/net/html/atom/gen.go new file mode 100644 index 000000000..5d052781b --- /dev/null +++ b/vendor/golang.org/x/net/html/atom/gen.go @@ -0,0 +1,712 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build ignore + +//go:generate go run gen.go +//go:generate go run gen.go -test + +package main + +import ( + "bytes" + "flag" + "fmt" + "go/format" + "io/ioutil" + "math/rand" + "os" + "sort" + "strings" +) + +// identifier converts s to a Go exported identifier. +// It converts "div" to "Div" and "accept-charset" to "AcceptCharset". +func identifier(s string) string { + b := make([]byte, 0, len(s)) + cap := true + for _, c := range s { + if c == '-' { + cap = true + continue + } + if cap && 'a' <= c && c <= 'z' { + c -= 'a' - 'A' + } + cap = false + b = append(b, byte(c)) + } + return string(b) +} + +var test = flag.Bool("test", false, "generate table_test.go") + +func genFile(name string, buf *bytes.Buffer) { + b, err := format.Source(buf.Bytes()) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + if err := ioutil.WriteFile(name, b, 0644); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func main() { + flag.Parse() + + var all []string + all = append(all, elements...) + all = append(all, attributes...) + all = append(all, eventHandlers...) + all = append(all, extra...) + sort.Strings(all) + + // uniq - lists have dups + w := 0 + for _, s := range all { + if w == 0 || all[w-1] != s { + all[w] = s + w++ + } + } + all = all[:w] + + if *test { + var buf bytes.Buffer + fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") + fmt.Fprintln(&buf, "//go:generate go run gen.go -test\n") + fmt.Fprintln(&buf, "package atom\n") + fmt.Fprintln(&buf, "var testAtomList = []string{") + for _, s := range all { + fmt.Fprintf(&buf, "\t%q,\n", s) + } + fmt.Fprintln(&buf, "}") + + genFile("table_test.go", &buf) + return + } + + // Find hash that minimizes table size. + var best *table + for i := 0; i < 1000000; i++ { + if best != nil && 1<<(best.k-1) < len(all) { + break + } + h := rand.Uint32() + for k := uint(0); k <= 16; k++ { + if best != nil && k >= best.k { + break + } + var t table + if t.init(h, k, all) { + best = &t + break + } + } + } + if best == nil { + fmt.Fprintf(os.Stderr, "failed to construct string table\n") + os.Exit(1) + } + + // Lay out strings, using overlaps when possible. + layout := append([]string{}, all...) + + // Remove strings that are substrings of other strings + for changed := true; changed; { + changed = false + for i, s := range layout { + if s == "" { + continue + } + for j, t := range layout { + if i != j && t != "" && strings.Contains(s, t) { + changed = true + layout[j] = "" + } + } + } + } + + // Join strings where one suffix matches another prefix. + for { + // Find best i, j, k such that layout[i][len-k:] == layout[j][:k], + // maximizing overlap length k. + besti := -1 + bestj := -1 + bestk := 0 + for i, s := range layout { + if s == "" { + continue + } + for j, t := range layout { + if i == j { + continue + } + for k := bestk + 1; k <= len(s) && k <= len(t); k++ { + if s[len(s)-k:] == t[:k] { + besti = i + bestj = j + bestk = k + } + } + } + } + if bestk > 0 { + layout[besti] += layout[bestj][bestk:] + layout[bestj] = "" + continue + } + break + } + + text := strings.Join(layout, "") + + atom := map[string]uint32{} + for _, s := range all { + off := strings.Index(text, s) + if off < 0 { + panic("lost string " + s) + } + atom[s] = uint32(off<<8 | len(s)) + } + + var buf bytes.Buffer + // Generate the Go code. + fmt.Fprintln(&buf, "// Code generated by go generate gen.go; DO NOT EDIT.\n") + fmt.Fprintln(&buf, "//go:generate go run gen.go\n") + fmt.Fprintln(&buf, "package atom\n\nconst (") + + // compute max len + maxLen := 0 + for _, s := range all { + if maxLen < len(s) { + maxLen = len(s) + } + fmt.Fprintf(&buf, "\t%s Atom = %#x\n", identifier(s), atom[s]) + } + fmt.Fprintln(&buf, ")\n") + + fmt.Fprintf(&buf, "const hash0 = %#x\n\n", best.h0) + fmt.Fprintf(&buf, "const maxAtomLen = %d\n\n", maxLen) + + fmt.Fprintf(&buf, "var table = [1<<%d]Atom{\n", best.k) + for i, s := range best.tab { + if s == "" { + continue + } + fmt.Fprintf(&buf, "\t%#x: %#x, // %s\n", i, atom[s], s) + } + fmt.Fprintf(&buf, "}\n") + datasize := (1 << best.k) * 4 + + fmt.Fprintln(&buf, "const atomText =") + textsize := len(text) + for len(text) > 60 { + fmt.Fprintf(&buf, "\t%q +\n", text[:60]) + text = text[60:] + } + fmt.Fprintf(&buf, "\t%q\n\n", text) + + genFile("table.go", &buf) + + fmt.Fprintf(os.Stdout, "%d atoms; %d string bytes + %d tables = %d total data\n", len(all), textsize, datasize, textsize+datasize) +} + +type byLen []string + +func (x byLen) Less(i, j int) bool { return len(x[i]) > len(x[j]) } +func (x byLen) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x byLen) Len() int { return len(x) } + +// fnv computes the FNV hash with an arbitrary starting value h. +func fnv(h uint32, s string) uint32 { + for i := 0; i < len(s); i++ { + h ^= uint32(s[i]) + h *= 16777619 + } + return h +} + +// A table represents an attempt at constructing the lookup table. +// The lookup table uses cuckoo hashing, meaning that each string +// can be found in one of two positions. +type table struct { + h0 uint32 + k uint + mask uint32 + tab []string +} + +// hash returns the two hashes for s. +func (t *table) hash(s string) (h1, h2 uint32) { + h := fnv(t.h0, s) + h1 = h & t.mask + h2 = (h >> 16) & t.mask + return +} + +// init initializes the table with the given parameters. +// h0 is the initial hash value, +// k is the number of bits of hash value to use, and +// x is the list of strings to store in the table. +// init returns false if the table cannot be constructed. +func (t *table) init(h0 uint32, k uint, x []string) bool { + t.h0 = h0 + t.k = k + t.tab = make([]string, 1< len(t.tab) { + return false + } + s := t.tab[i] + h1, h2 := t.hash(s) + j := h1 + h2 - i + if t.tab[j] != "" && !t.push(j, depth+1) { + return false + } + t.tab[j] = s + return true +} + +// The lists of element names and attribute keys were taken from +// https://html.spec.whatwg.org/multipage/indices.html#index +// as of the "HTML Living Standard - Last Updated 16 April 2018" version. + +// "command", "keygen" and "menuitem" have been removed from the spec, +// but are kept here for backwards compatibility. +var elements = []string{ + "a", + "abbr", + "address", + "area", + "article", + "aside", + "audio", + "b", + "base", + "bdi", + "bdo", + "blockquote", + "body", + "br", + "button", + "canvas", + "caption", + "cite", + "code", + "col", + "colgroup", + "command", + "data", + "datalist", + "dd", + "del", + "details", + "dfn", + "dialog", + "div", + "dl", + "dt", + "em", + "embed", + "fieldset", + "figcaption", + "figure", + "footer", + "form", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hgroup", + "hr", + "html", + "i", + "iframe", + "img", + "input", + "ins", + "kbd", + "keygen", + "label", + "legend", + "li", + "link", + "main", + "map", + "mark", + "menu", + "menuitem", + "meta", + "meter", + "nav", + "noscript", + "object", + "ol", + "optgroup", + "option", + "output", + "p", + "param", + "picture", + "pre", + "progress", + "q", + "rp", + "rt", + "ruby", + "s", + "samp", + "script", + "section", + "select", + "slot", + "small", + "source", + "span", + "strong", + "style", + "sub", + "summary", + "sup", + "table", + "tbody", + "td", + "template", + "textarea", + "tfoot", + "th", + "thead", + "time", + "title", + "tr", + "track", + "u", + "ul", + "var", + "video", + "wbr", +} + +// https://html.spec.whatwg.org/multipage/indices.html#attributes-3 +// +// "challenge", "command", "contextmenu", "dropzone", "icon", "keytype", "mediagroup", +// "radiogroup", "spellcheck", "scoped", "seamless", "sortable" and "sorted" have been removed from the spec, +// but are kept here for backwards compatibility. +var attributes = []string{ + "abbr", + "accept", + "accept-charset", + "accesskey", + "action", + "allowfullscreen", + "allowpaymentrequest", + "allowusermedia", + "alt", + "as", + "async", + "autocomplete", + "autofocus", + "autoplay", + "challenge", + "charset", + "checked", + "cite", + "class", + "color", + "cols", + "colspan", + "command", + "content", + "contenteditable", + "contextmenu", + "controls", + "coords", + "crossorigin", + "data", + "datetime", + "default", + "defer", + "dir", + "dirname", + "disabled", + "download", + "draggable", + "dropzone", + "enctype", + "for", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "headers", + "height", + "hidden", + "high", + "href", + "hreflang", + "http-equiv", + "icon", + "id", + "inputmode", + "integrity", + "is", + "ismap", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "keytype", + "kind", + "label", + "lang", + "list", + "loop", + "low", + "manifest", + "max", + "maxlength", + "media", + "mediagroup", + "method", + "min", + "minlength", + "multiple", + "muted", + "name", + "nomodule", + "nonce", + "novalidate", + "open", + "optimum", + "pattern", + "ping", + "placeholder", + "playsinline", + "poster", + "preload", + "radiogroup", + "readonly", + "referrerpolicy", + "rel", + "required", + "reversed", + "rows", + "rowspan", + "sandbox", + "spellcheck", + "scope", + "scoped", + "seamless", + "selected", + "shape", + "size", + "sizes", + "sortable", + "sorted", + "slot", + "span", + "spellcheck", + "src", + "srcdoc", + "srclang", + "srcset", + "start", + "step", + "style", + "tabindex", + "target", + "title", + "translate", + "type", + "typemustmatch", + "updateviacache", + "usemap", + "value", + "width", + "workertype", + "wrap", +} + +// "onautocomplete", "onautocompleteerror", "onmousewheel", +// "onshow" and "onsort" have been removed from the spec, +// but are kept here for backwards compatibility. +var eventHandlers = []string{ + "onabort", + "onautocomplete", + "onautocompleteerror", + "onauxclick", + "onafterprint", + "onbeforeprint", + "onbeforeunload", + "onblur", + "oncancel", + "oncanplay", + "oncanplaythrough", + "onchange", + "onclick", + "onclose", + "oncontextmenu", + "oncopy", + "oncuechange", + "oncut", + "ondblclick", + "ondrag", + "ondragend", + "ondragenter", + "ondragexit", + "ondragleave", + "ondragover", + "ondragstart", + "ondrop", + "ondurationchange", + "onemptied", + "onended", + "onerror", + "onfocus", + "onhashchange", + "oninput", + "oninvalid", + "onkeydown", + "onkeypress", + "onkeyup", + "onlanguagechange", + "onload", + "onloadeddata", + "onloadedmetadata", + "onloadend", + "onloadstart", + "onmessage", + "onmessageerror", + "onmousedown", + "onmouseenter", + "onmouseleave", + "onmousemove", + "onmouseout", + "onmouseover", + "onmouseup", + "onmousewheel", + "onwheel", + "onoffline", + "ononline", + "onpagehide", + "onpageshow", + "onpaste", + "onpause", + "onplay", + "onplaying", + "onpopstate", + "onprogress", + "onratechange", + "onreset", + "onresize", + "onrejectionhandled", + "onscroll", + "onsecuritypolicyviolation", + "onseeked", + "onseeking", + "onselect", + "onshow", + "onsort", + "onstalled", + "onstorage", + "onsubmit", + "onsuspend", + "ontimeupdate", + "ontoggle", + "onunhandledrejection", + "onunload", + "onvolumechange", + "onwaiting", +} + +// extra are ad-hoc values not covered by any of the lists above. +var extra = []string{ + "acronym", + "align", + "annotation", + "annotation-xml", + "applet", + "basefont", + "bgsound", + "big", + "blink", + "center", + "color", + "desc", + "face", + "font", + "foreignObject", // HTML is case-insensitive, but SVG-embedded-in-HTML is case-sensitive. + "foreignobject", + "frame", + "frameset", + "image", + "isindex", + "listing", + "malignmark", + "marquee", + "math", + "mglyph", + "mi", + "mn", + "mo", + "ms", + "mtext", + "nobr", + "noembed", + "noframes", + "plaintext", + "prompt", + "public", + "rb", + "rtc", + "spacer", + "strike", + "svg", + "system", + "tt", + "xmp", +} diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go index 2605ba310..2a938864c 100644 --- a/vendor/golang.org/x/net/html/atom/table.go +++ b/vendor/golang.org/x/net/html/atom/table.go @@ -1,713 +1,783 @@ -// generated by go run gen.go; DO NOT EDIT +// Code generated by go generate gen.go; DO NOT EDIT. + +//go:generate go run gen.go package atom const ( - A Atom = 0x1 - Abbr Atom = 0x4 - Accept Atom = 0x2106 - AcceptCharset Atom = 0x210e - Accesskey Atom = 0x3309 - Action Atom = 0x1f606 - Address Atom = 0x4f307 - Align Atom = 0x1105 - Alt Atom = 0x4503 - Annotation Atom = 0x1670a - AnnotationXml Atom = 0x1670e - Applet Atom = 0x2b306 - Area Atom = 0x2fa04 - Article Atom = 0x38807 - Aside Atom = 0x8305 - Async Atom = 0x7b05 - Audio Atom = 0xa605 - Autocomplete Atom = 0x1fc0c - Autofocus Atom = 0xb309 - Autoplay Atom = 0xce08 - B Atom = 0x101 - Base Atom = 0xd604 - Basefont Atom = 0xd608 - Bdi Atom = 0x1a03 - Bdo Atom = 0xe703 - Bgsound Atom = 0x11807 - Big Atom = 0x12403 - Blink Atom = 0x12705 - Blockquote Atom = 0x12c0a - Body Atom = 0x2f04 - Br Atom = 0x202 - Button Atom = 0x13606 - Canvas Atom = 0x7f06 - Caption Atom = 0x1bb07 - Center Atom = 0x5b506 - Challenge Atom = 0x21f09 - Charset Atom = 0x2807 - Checked Atom = 0x32807 - Cite Atom = 0x3c804 - Class Atom = 0x4de05 - Code Atom = 0x14904 - Col Atom = 0x15003 - Colgroup Atom = 0x15008 - Color Atom = 0x15d05 - Cols Atom = 0x16204 - Colspan Atom = 0x16207 - Command Atom = 0x17507 - Content Atom = 0x42307 - Contenteditable Atom = 0x4230f - Contextmenu Atom = 0x3310b - Controls Atom = 0x18808 - Coords Atom = 0x19406 - Crossorigin Atom = 0x19f0b - Data Atom = 0x44a04 - Datalist Atom = 0x44a08 - Datetime Atom = 0x23c08 - Dd Atom = 0x26702 - Default Atom = 0x8607 - Defer Atom = 0x14b05 - Del Atom = 0x3ef03 - Desc Atom = 0x4db04 - Details Atom = 0x4807 - Dfn Atom = 0x6103 - Dialog Atom = 0x1b06 - Dir Atom = 0x6903 - Dirname Atom = 0x6907 - Disabled Atom = 0x10c08 - Div Atom = 0x11303 - Dl Atom = 0x11e02 - Download Atom = 0x40008 - Draggable Atom = 0x17b09 - Dropzone Atom = 0x39108 - Dt Atom = 0x50902 - Em Atom = 0x6502 - Embed Atom = 0x6505 - Enctype Atom = 0x21107 - Face Atom = 0x5b304 - Fieldset Atom = 0x1b008 - Figcaption Atom = 0x1b80a - Figure Atom = 0x1cc06 - Font Atom = 0xda04 - Footer Atom = 0x8d06 - For Atom = 0x1d803 - ForeignObject Atom = 0x1d80d - Foreignobject Atom = 0x1e50d - Form Atom = 0x1f204 - Formaction Atom = 0x1f20a - Formenctype Atom = 0x20d0b - Formmethod Atom = 0x2280a - Formnovalidate Atom = 0x2320e - Formtarget Atom = 0x2470a - Frame Atom = 0x9a05 - Frameset Atom = 0x9a08 - H1 Atom = 0x26e02 - H2 Atom = 0x29402 - H3 Atom = 0x2a702 - H4 Atom = 0x2e902 - H5 Atom = 0x2f302 - H6 Atom = 0x50b02 - Head Atom = 0x2d504 - Header Atom = 0x2d506 - Headers Atom = 0x2d507 - Height Atom = 0x25106 - Hgroup Atom = 0x25906 - Hidden Atom = 0x26506 - High Atom = 0x26b04 - Hr Atom = 0x27002 - Href Atom = 0x27004 - Hreflang Atom = 0x27008 - Html Atom = 0x25504 - HttpEquiv Atom = 0x2780a - I Atom = 0x601 - Icon Atom = 0x42204 - Id Atom = 0x8502 - Iframe Atom = 0x29606 - Image Atom = 0x29c05 - Img Atom = 0x2a103 - Input Atom = 0x3e805 - Inputmode Atom = 0x3e809 - Ins Atom = 0x1a803 - Isindex Atom = 0x2a907 - Ismap Atom = 0x2b005 - Itemid Atom = 0x33c06 - Itemprop Atom = 0x3c908 - Itemref Atom = 0x5ad07 - Itemscope Atom = 0x2b909 - Itemtype Atom = 0x2c308 - Kbd Atom = 0x1903 - Keygen Atom = 0x3906 - Keytype Atom = 0x53707 - Kind Atom = 0x10904 - Label Atom = 0xf005 - Lang Atom = 0x27404 - Legend Atom = 0x18206 - Li Atom = 0x1202 - Link Atom = 0x12804 - List Atom = 0x44e04 - Listing Atom = 0x44e07 - Loop Atom = 0xf404 - Low Atom = 0x11f03 - Malignmark Atom = 0x100a - Manifest Atom = 0x5f108 - Map Atom = 0x2b203 - Mark Atom = 0x1604 - Marquee Atom = 0x2cb07 - Math Atom = 0x2d204 - Max Atom = 0x2e103 - Maxlength Atom = 0x2e109 - Media Atom = 0x6e05 - Mediagroup Atom = 0x6e0a - Menu Atom = 0x33804 - Menuitem Atom = 0x33808 - Meta Atom = 0x45d04 - Meter Atom = 0x24205 - Method Atom = 0x22c06 - Mglyph Atom = 0x2a206 - Mi Atom = 0x2eb02 - Min Atom = 0x2eb03 - Minlength Atom = 0x2eb09 - Mn Atom = 0x23502 - Mo Atom = 0x3ed02 - Ms Atom = 0x2bc02 - Mtext Atom = 0x2f505 - Multiple Atom = 0x30308 - Muted Atom = 0x30b05 - Name Atom = 0x6c04 - Nav Atom = 0x3e03 - Nobr Atom = 0x5704 - Noembed Atom = 0x6307 - Noframes Atom = 0x9808 - Noscript Atom = 0x3d208 - Novalidate Atom = 0x2360a - Object Atom = 0x1ec06 - Ol Atom = 0xc902 - Onabort Atom = 0x13a07 - Onafterprint Atom = 0x1c00c - Onautocomplete Atom = 0x1fa0e - Onautocompleteerror Atom = 0x1fa13 - Onbeforeprint Atom = 0x6040d - Onbeforeunload Atom = 0x4e70e - Onblur Atom = 0xaa06 - Oncancel Atom = 0xe908 - Oncanplay Atom = 0x28509 - Oncanplaythrough Atom = 0x28510 - Onchange Atom = 0x3a708 - Onclick Atom = 0x31007 - Onclose Atom = 0x31707 - Oncontextmenu Atom = 0x32f0d - Oncuechange Atom = 0x3420b - Ondblclick Atom = 0x34d0a - Ondrag Atom = 0x35706 - Ondragend Atom = 0x35709 - Ondragenter Atom = 0x3600b - Ondragleave Atom = 0x36b0b - Ondragover Atom = 0x3760a - Ondragstart Atom = 0x3800b - Ondrop Atom = 0x38f06 - Ondurationchange Atom = 0x39f10 - Onemptied Atom = 0x39609 - Onended Atom = 0x3af07 - Onerror Atom = 0x3b607 - Onfocus Atom = 0x3bd07 - Onhashchange Atom = 0x3da0c - Oninput Atom = 0x3e607 - Oninvalid Atom = 0x3f209 - Onkeydown Atom = 0x3fb09 - Onkeypress Atom = 0x4080a - Onkeyup Atom = 0x41807 - Onlanguagechange Atom = 0x43210 - Onload Atom = 0x44206 - Onloadeddata Atom = 0x4420c - Onloadedmetadata Atom = 0x45510 - Onloadstart Atom = 0x46b0b - Onmessage Atom = 0x47609 - Onmousedown Atom = 0x47f0b - Onmousemove Atom = 0x48a0b - Onmouseout Atom = 0x4950a - Onmouseover Atom = 0x4a20b - Onmouseup Atom = 0x4ad09 - Onmousewheel Atom = 0x4b60c - Onoffline Atom = 0x4c209 - Ononline Atom = 0x4cb08 - Onpagehide Atom = 0x4d30a - Onpageshow Atom = 0x4fe0a - Onpause Atom = 0x50d07 - Onplay Atom = 0x51706 - Onplaying Atom = 0x51709 - Onpopstate Atom = 0x5200a - Onprogress Atom = 0x52a0a - Onratechange Atom = 0x53e0c - Onreset Atom = 0x54a07 - Onresize Atom = 0x55108 - Onscroll Atom = 0x55f08 - Onseeked Atom = 0x56708 - Onseeking Atom = 0x56f09 - Onselect Atom = 0x57808 - Onshow Atom = 0x58206 - Onsort Atom = 0x58b06 - Onstalled Atom = 0x59509 - Onstorage Atom = 0x59e09 - Onsubmit Atom = 0x5a708 - Onsuspend Atom = 0x5bb09 - Ontimeupdate Atom = 0xdb0c - Ontoggle Atom = 0x5c408 - Onunload Atom = 0x5cc08 - Onvolumechange Atom = 0x5d40e - Onwaiting Atom = 0x5e209 - Open Atom = 0x3cf04 - Optgroup Atom = 0xf608 - Optimum Atom = 0x5eb07 - Option Atom = 0x60006 - Output Atom = 0x49c06 - P Atom = 0xc01 - Param Atom = 0xc05 - Pattern Atom = 0x5107 - Ping Atom = 0x7704 - Placeholder Atom = 0xc30b - Plaintext Atom = 0xfd09 - Poster Atom = 0x15706 - Pre Atom = 0x25e03 - Preload Atom = 0x25e07 - Progress Atom = 0x52c08 - Prompt Atom = 0x5fa06 - Public Atom = 0x41e06 - Q Atom = 0x13101 - Radiogroup Atom = 0x30a - Readonly Atom = 0x2fb08 - Rel Atom = 0x25f03 - Required Atom = 0x1d008 - Reversed Atom = 0x5a08 - Rows Atom = 0x9204 - Rowspan Atom = 0x9207 - Rp Atom = 0x1c602 - Rt Atom = 0x13f02 - Ruby Atom = 0xaf04 - S Atom = 0x2c01 - Samp Atom = 0x4e04 - Sandbox Atom = 0xbb07 - Scope Atom = 0x2bd05 - Scoped Atom = 0x2bd06 - Script Atom = 0x3d406 - Seamless Atom = 0x31c08 - Section Atom = 0x4e207 - Select Atom = 0x57a06 - Selected Atom = 0x57a08 - Shape Atom = 0x4f905 - Size Atom = 0x55504 - Sizes Atom = 0x55505 - Small Atom = 0x18f05 - Sortable Atom = 0x58d08 - Sorted Atom = 0x19906 - Source Atom = 0x1aa06 - Spacer Atom = 0x2db06 - Span Atom = 0x9504 - Spellcheck Atom = 0x3230a - Src Atom = 0x3c303 - Srcdoc Atom = 0x3c306 - Srclang Atom = 0x41107 - Start Atom = 0x38605 - Step Atom = 0x5f704 - Strike Atom = 0x53306 - Strong Atom = 0x55906 - Style Atom = 0x61105 - Sub Atom = 0x5a903 - Summary Atom = 0x61607 - Sup Atom = 0x61d03 - Svg Atom = 0x62003 - System Atom = 0x62306 - Tabindex Atom = 0x46308 - Table Atom = 0x42d05 - Target Atom = 0x24b06 - Tbody Atom = 0x2e05 - Td Atom = 0x4702 - Template Atom = 0x62608 - Textarea Atom = 0x2f608 - Tfoot Atom = 0x8c05 - Th Atom = 0x22e02 - Thead Atom = 0x2d405 - Time Atom = 0xdd04 - Title Atom = 0xa105 - Tr Atom = 0x10502 - Track Atom = 0x10505 - Translate Atom = 0x14009 - Tt Atom = 0x5302 - Type Atom = 0x21404 - Typemustmatch Atom = 0x2140d - U Atom = 0xb01 - Ul Atom = 0x8a02 - Usemap Atom = 0x51106 - Value Atom = 0x4005 - Var Atom = 0x11503 - Video Atom = 0x28105 - Wbr Atom = 0x12103 - Width Atom = 0x50705 - Wrap Atom = 0x58704 - Xmp Atom = 0xc103 + A Atom = 0x1 + Abbr Atom = 0x4 + Accept Atom = 0x1a06 + AcceptCharset Atom = 0x1a0e + Accesskey Atom = 0x2c09 + Acronym Atom = 0xaa07 + Action Atom = 0x27206 + Address Atom = 0x6f307 + Align Atom = 0xb105 + Allowfullscreen Atom = 0x2080f + Allowpaymentrequest Atom = 0xc113 + Allowusermedia Atom = 0xdd0e + Alt Atom = 0xf303 + Annotation Atom = 0x1c90a + AnnotationXml Atom = 0x1c90e + Applet Atom = 0x31906 + Area Atom = 0x35604 + Article Atom = 0x3fc07 + As Atom = 0x3c02 + Aside Atom = 0x10705 + Async Atom = 0xff05 + Audio Atom = 0x11505 + Autocomplete Atom = 0x2780c + Autofocus Atom = 0x12109 + Autoplay Atom = 0x13c08 + B Atom = 0x101 + Base Atom = 0x3b04 + Basefont Atom = 0x3b08 + Bdi Atom = 0xba03 + Bdo Atom = 0x14b03 + Bgsound Atom = 0x15e07 + Big Atom = 0x17003 + Blink Atom = 0x17305 + Blockquote Atom = 0x1870a + Body Atom = 0x2804 + Br Atom = 0x202 + Button Atom = 0x19106 + Canvas Atom = 0x10306 + Caption Atom = 0x23107 + Center Atom = 0x22006 + Challenge Atom = 0x29b09 + Charset Atom = 0x2107 + Checked Atom = 0x47907 + Cite Atom = 0x19c04 + Class Atom = 0x56405 + Code Atom = 0x5c504 + Col Atom = 0x1ab03 + Colgroup Atom = 0x1ab08 + Color Atom = 0x1bf05 + Cols Atom = 0x1c404 + Colspan Atom = 0x1c407 + Command Atom = 0x1d707 + Content Atom = 0x58b07 + Contenteditable Atom = 0x58b0f + Contextmenu Atom = 0x3800b + Controls Atom = 0x1de08 + Coords Atom = 0x1ea06 + Crossorigin Atom = 0x1fb0b + Data Atom = 0x4a504 + Datalist Atom = 0x4a508 + Datetime Atom = 0x2b808 + Dd Atom = 0x2d702 + Default Atom = 0x10a07 + Defer Atom = 0x5c705 + Del Atom = 0x45203 + Desc Atom = 0x56104 + Details Atom = 0x7207 + Dfn Atom = 0x8703 + Dialog Atom = 0xbb06 + Dir Atom = 0x9303 + Dirname Atom = 0x9307 + Disabled Atom = 0x16408 + Div Atom = 0x16b03 + Dl Atom = 0x5e602 + Download Atom = 0x46308 + Draggable Atom = 0x17a09 + Dropzone Atom = 0x40508 + Dt Atom = 0x64b02 + Em Atom = 0x6e02 + Embed Atom = 0x6e05 + Enctype Atom = 0x28d07 + Face Atom = 0x21e04 + Fieldset Atom = 0x22608 + Figcaption Atom = 0x22e0a + Figure Atom = 0x24806 + Font Atom = 0x3f04 + Footer Atom = 0xf606 + For Atom = 0x25403 + ForeignObject Atom = 0x2540d + Foreignobject Atom = 0x2610d + Form Atom = 0x26e04 + Formaction Atom = 0x26e0a + Formenctype Atom = 0x2890b + Formmethod Atom = 0x2a40a + Formnovalidate Atom = 0x2ae0e + Formtarget Atom = 0x2c00a + Frame Atom = 0x8b05 + Frameset Atom = 0x8b08 + H1 Atom = 0x15c02 + H2 Atom = 0x2de02 + H3 Atom = 0x30d02 + H4 Atom = 0x34502 + H5 Atom = 0x34f02 + H6 Atom = 0x64d02 + Head Atom = 0x33104 + Header Atom = 0x33106 + Headers Atom = 0x33107 + Height Atom = 0x5206 + Hgroup Atom = 0x2ca06 + Hidden Atom = 0x2d506 + High Atom = 0x2db04 + Hr Atom = 0x15702 + Href Atom = 0x2e004 + Hreflang Atom = 0x2e008 + Html Atom = 0x5604 + HttpEquiv Atom = 0x2e80a + I Atom = 0x601 + Icon Atom = 0x58a04 + Id Atom = 0x10902 + Iframe Atom = 0x2fc06 + Image Atom = 0x30205 + Img Atom = 0x30703 + Input Atom = 0x44b05 + Inputmode Atom = 0x44b09 + Ins Atom = 0x20403 + Integrity Atom = 0x23f09 + Is Atom = 0x16502 + Isindex Atom = 0x30f07 + Ismap Atom = 0x31605 + Itemid Atom = 0x38b06 + Itemprop Atom = 0x19d08 + Itemref Atom = 0x3cd07 + Itemscope Atom = 0x67109 + Itemtype Atom = 0x31f08 + Kbd Atom = 0xb903 + Keygen Atom = 0x3206 + Keytype Atom = 0xd607 + Kind Atom = 0x17704 + Label Atom = 0x5905 + Lang Atom = 0x2e404 + Legend Atom = 0x18106 + Li Atom = 0xb202 + Link Atom = 0x17404 + List Atom = 0x4a904 + Listing Atom = 0x4a907 + Loop Atom = 0x5d04 + Low Atom = 0xc303 + Main Atom = 0x1004 + Malignmark Atom = 0xb00a + Manifest Atom = 0x6d708 + Map Atom = 0x31803 + Mark Atom = 0xb604 + Marquee Atom = 0x32707 + Math Atom = 0x32e04 + Max Atom = 0x33d03 + Maxlength Atom = 0x33d09 + Media Atom = 0xe605 + Mediagroup Atom = 0xe60a + Menu Atom = 0x38704 + Menuitem Atom = 0x38708 + Meta Atom = 0x4b804 + Meter Atom = 0x9805 + Method Atom = 0x2a806 + Mglyph Atom = 0x30806 + Mi Atom = 0x34702 + Min Atom = 0x34703 + Minlength Atom = 0x34709 + Mn Atom = 0x2b102 + Mo Atom = 0xa402 + Ms Atom = 0x67402 + Mtext Atom = 0x35105 + Multiple Atom = 0x35f08 + Muted Atom = 0x36705 + Name Atom = 0x9604 + Nav Atom = 0x1303 + Nobr Atom = 0x3704 + Noembed Atom = 0x6c07 + Noframes Atom = 0x8908 + Nomodule Atom = 0xa208 + Nonce Atom = 0x1a605 + Noscript Atom = 0x21608 + Novalidate Atom = 0x2b20a + Object Atom = 0x26806 + Ol Atom = 0x13702 + Onabort Atom = 0x19507 + Onafterprint Atom = 0x2360c + Onautocomplete Atom = 0x2760e + Onautocompleteerror Atom = 0x27613 + Onauxclick Atom = 0x61f0a + Onbeforeprint Atom = 0x69e0d + Onbeforeunload Atom = 0x6e70e + Onblur Atom = 0x56d06 + Oncancel Atom = 0x11908 + Oncanplay Atom = 0x14d09 + Oncanplaythrough Atom = 0x14d10 + Onchange Atom = 0x41b08 + Onclick Atom = 0x2f507 + Onclose Atom = 0x36c07 + Oncontextmenu Atom = 0x37e0d + Oncopy Atom = 0x39106 + Oncuechange Atom = 0x3970b + Oncut Atom = 0x3a205 + Ondblclick Atom = 0x3a70a + Ondrag Atom = 0x3b106 + Ondragend Atom = 0x3b109 + Ondragenter Atom = 0x3ba0b + Ondragexit Atom = 0x3c50a + Ondragleave Atom = 0x3df0b + Ondragover Atom = 0x3ea0a + Ondragstart Atom = 0x3f40b + Ondrop Atom = 0x40306 + Ondurationchange Atom = 0x41310 + Onemptied Atom = 0x40a09 + Onended Atom = 0x42307 + Onerror Atom = 0x42a07 + Onfocus Atom = 0x43107 + Onhashchange Atom = 0x43d0c + Oninput Atom = 0x44907 + Oninvalid Atom = 0x45509 + Onkeydown Atom = 0x45e09 + Onkeypress Atom = 0x46b0a + Onkeyup Atom = 0x48007 + Onlanguagechange Atom = 0x48d10 + Onload Atom = 0x49d06 + Onloadeddata Atom = 0x49d0c + Onloadedmetadata Atom = 0x4b010 + Onloadend Atom = 0x4c609 + Onloadstart Atom = 0x4cf0b + Onmessage Atom = 0x4da09 + Onmessageerror Atom = 0x4da0e + Onmousedown Atom = 0x4e80b + Onmouseenter Atom = 0x4f30c + Onmouseleave Atom = 0x4ff0c + Onmousemove Atom = 0x50b0b + Onmouseout Atom = 0x5160a + Onmouseover Atom = 0x5230b + Onmouseup Atom = 0x52e09 + Onmousewheel Atom = 0x53c0c + Onoffline Atom = 0x54809 + Ononline Atom = 0x55108 + Onpagehide Atom = 0x5590a + Onpageshow Atom = 0x5730a + Onpaste Atom = 0x57f07 + Onpause Atom = 0x59a07 + Onplay Atom = 0x5a406 + Onplaying Atom = 0x5a409 + Onpopstate Atom = 0x5ad0a + Onprogress Atom = 0x5b70a + Onratechange Atom = 0x5cc0c + Onrejectionhandled Atom = 0x5d812 + Onreset Atom = 0x5ea07 + Onresize Atom = 0x5f108 + Onscroll Atom = 0x60008 + Onsecuritypolicyviolation Atom = 0x60819 + Onseeked Atom = 0x62908 + Onseeking Atom = 0x63109 + Onselect Atom = 0x63a08 + Onshow Atom = 0x64406 + Onsort Atom = 0x64f06 + Onstalled Atom = 0x65909 + Onstorage Atom = 0x66209 + Onsubmit Atom = 0x66b08 + Onsuspend Atom = 0x67b09 + Ontimeupdate Atom = 0x400c + Ontoggle Atom = 0x68408 + Onunhandledrejection Atom = 0x68c14 + Onunload Atom = 0x6ab08 + Onvolumechange Atom = 0x6b30e + Onwaiting Atom = 0x6c109 + Onwheel Atom = 0x6ca07 + Open Atom = 0x1a304 + Optgroup Atom = 0x5f08 + Optimum Atom = 0x6d107 + Option Atom = 0x6e306 + Output Atom = 0x51d06 + P Atom = 0xc01 + Param Atom = 0xc05 + Pattern Atom = 0x6607 + Picture Atom = 0x7b07 + Ping Atom = 0xef04 + Placeholder Atom = 0x1310b + Plaintext Atom = 0x1b209 + Playsinline Atom = 0x1400b + Poster Atom = 0x2cf06 + Pre Atom = 0x47003 + Preload Atom = 0x48607 + Progress Atom = 0x5b908 + Prompt Atom = 0x53606 + Public Atom = 0x58606 + Q Atom = 0xcf01 + Radiogroup Atom = 0x30a + Rb Atom = 0x3a02 + Readonly Atom = 0x35708 + Referrerpolicy Atom = 0x3d10e + Rel Atom = 0x48703 + Required Atom = 0x24c08 + Reversed Atom = 0x8008 + Rows Atom = 0x9c04 + Rowspan Atom = 0x9c07 + Rp Atom = 0x23c02 + Rt Atom = 0x19a02 + Rtc Atom = 0x19a03 + Ruby Atom = 0xfb04 + S Atom = 0x2501 + Samp Atom = 0x7804 + Sandbox Atom = 0x12907 + Scope Atom = 0x67505 + Scoped Atom = 0x67506 + Script Atom = 0x21806 + Seamless Atom = 0x37108 + Section Atom = 0x56807 + Select Atom = 0x63c06 + Selected Atom = 0x63c08 + Shape Atom = 0x1e505 + Size Atom = 0x5f504 + Sizes Atom = 0x5f505 + Slot Atom = 0x1ef04 + Small Atom = 0x20605 + Sortable Atom = 0x65108 + Sorted Atom = 0x33706 + Source Atom = 0x37806 + Spacer Atom = 0x43706 + Span Atom = 0x9f04 + Spellcheck Atom = 0x4740a + Src Atom = 0x5c003 + Srcdoc Atom = 0x5c006 + Srclang Atom = 0x5f907 + Srcset Atom = 0x6f906 + Start Atom = 0x3fa05 + Step Atom = 0x58304 + Strike Atom = 0xd206 + Strong Atom = 0x6dd06 + Style Atom = 0x6ff05 + Sub Atom = 0x66d03 + Summary Atom = 0x70407 + Sup Atom = 0x70b03 + Svg Atom = 0x70e03 + System Atom = 0x71106 + Tabindex Atom = 0x4be08 + Table Atom = 0x59505 + Target Atom = 0x2c406 + Tbody Atom = 0x2705 + Td Atom = 0x9202 + Template Atom = 0x71408 + Textarea Atom = 0x35208 + Tfoot Atom = 0xf505 + Th Atom = 0x15602 + Thead Atom = 0x33005 + Time Atom = 0x4204 + Title Atom = 0x11005 + Tr Atom = 0xcc02 + Track Atom = 0x1ba05 + Translate Atom = 0x1f209 + Tt Atom = 0x6802 + Type Atom = 0xd904 + Typemustmatch Atom = 0x2900d + U Atom = 0xb01 + Ul Atom = 0xa702 + Updateviacache Atom = 0x460e + Usemap Atom = 0x59e06 + Value Atom = 0x1505 + Var Atom = 0x16d03 + Video Atom = 0x2f105 + Wbr Atom = 0x57c03 + Width Atom = 0x64905 + Workertype Atom = 0x71c0a + Wrap Atom = 0x72604 + Xmp Atom = 0x12f03 ) -const hash0 = 0xc17da63e +const hash0 = 0x81cdf10e -const maxAtomLen = 19 +const maxAtomLen = 25 var table = [1 << 9]Atom{ - 0x1: 0x48a0b, // onmousemove - 0x2: 0x5e209, // onwaiting - 0x3: 0x1fa13, // onautocompleteerror - 0x4: 0x5fa06, // prompt - 0x7: 0x5eb07, // optimum - 0x8: 0x1604, // mark - 0xa: 0x5ad07, // itemref - 0xb: 0x4fe0a, // onpageshow - 0xc: 0x57a06, // select - 0xd: 0x17b09, // draggable - 0xe: 0x3e03, // nav - 0xf: 0x17507, // command - 0x11: 0xb01, // u - 0x14: 0x2d507, // headers - 0x15: 0x44a08, // datalist - 0x17: 0x4e04, // samp - 0x1a: 0x3fb09, // onkeydown - 0x1b: 0x55f08, // onscroll - 0x1c: 0x15003, // col - 0x20: 0x3c908, // itemprop - 0x21: 0x2780a, // http-equiv - 0x22: 0x61d03, // sup - 0x24: 0x1d008, // required - 0x2b: 0x25e07, // preload - 0x2c: 0x6040d, // onbeforeprint - 0x2d: 0x3600b, // ondragenter - 0x2e: 0x50902, // dt - 0x2f: 0x5a708, // onsubmit - 0x30: 0x27002, // hr - 0x31: 0x32f0d, // oncontextmenu - 0x33: 0x29c05, // image - 0x34: 0x50d07, // onpause - 0x35: 0x25906, // hgroup - 0x36: 0x7704, // ping - 0x37: 0x57808, // onselect - 0x3a: 0x11303, // div - 0x3b: 0x1fa0e, // onautocomplete - 0x40: 0x2eb02, // mi - 0x41: 0x31c08, // seamless - 0x42: 0x2807, // charset - 0x43: 0x8502, // id - 0x44: 0x5200a, // onpopstate - 0x45: 0x3ef03, // del - 0x46: 0x2cb07, // marquee - 0x47: 0x3309, // accesskey - 0x49: 0x8d06, // footer - 0x4a: 0x44e04, // list - 0x4b: 0x2b005, // ismap - 0x51: 0x33804, // menu - 0x52: 0x2f04, // body - 0x55: 0x9a08, // frameset - 0x56: 0x54a07, // onreset - 0x57: 0x12705, // blink - 0x58: 0xa105, // title - 0x59: 0x38807, // article - 0x5b: 0x22e02, // th - 0x5d: 0x13101, // q - 0x5e: 0x3cf04, // open - 0x5f: 0x2fa04, // area - 0x61: 0x44206, // onload - 0x62: 0xda04, // font - 0x63: 0xd604, // base - 0x64: 0x16207, // colspan - 0x65: 0x53707, // keytype - 0x66: 0x11e02, // dl - 0x68: 0x1b008, // fieldset - 0x6a: 0x2eb03, // min - 0x6b: 0x11503, // var - 0x6f: 0x2d506, // header - 0x70: 0x13f02, // rt - 0x71: 0x15008, // colgroup - 0x72: 0x23502, // mn - 0x74: 0x13a07, // onabort - 0x75: 0x3906, // keygen - 0x76: 0x4c209, // onoffline - 0x77: 0x21f09, // challenge - 0x78: 0x2b203, // map - 0x7a: 0x2e902, // h4 - 0x7b: 0x3b607, // onerror - 0x7c: 0x2e109, // maxlength - 0x7d: 0x2f505, // mtext - 0x7e: 0xbb07, // sandbox - 0x7f: 0x58b06, // onsort - 0x80: 0x100a, // malignmark - 0x81: 0x45d04, // meta - 0x82: 0x7b05, // async - 0x83: 0x2a702, // h3 - 0x84: 0x26702, // dd - 0x85: 0x27004, // href - 0x86: 0x6e0a, // mediagroup - 0x87: 0x19406, // coords - 0x88: 0x41107, // srclang - 0x89: 0x34d0a, // ondblclick - 0x8a: 0x4005, // value - 0x8c: 0xe908, // oncancel - 0x8e: 0x3230a, // spellcheck - 0x8f: 0x9a05, // frame - 0x91: 0x12403, // big - 0x94: 0x1f606, // action - 0x95: 0x6903, // dir - 0x97: 0x2fb08, // readonly - 0x99: 0x42d05, // table - 0x9a: 0x61607, // summary - 0x9b: 0x12103, // wbr - 0x9c: 0x30a, // radiogroup - 0x9d: 0x6c04, // name - 0x9f: 0x62306, // system - 0xa1: 0x15d05, // color - 0xa2: 0x7f06, // canvas - 0xa3: 0x25504, // html - 0xa5: 0x56f09, // onseeking - 0xac: 0x4f905, // shape - 0xad: 0x25f03, // rel - 0xae: 0x28510, // oncanplaythrough - 0xaf: 0x3760a, // ondragover - 0xb0: 0x62608, // template - 0xb1: 0x1d80d, // foreignObject - 0xb3: 0x9204, // rows - 0xb6: 0x44e07, // listing - 0xb7: 0x49c06, // output - 0xb9: 0x3310b, // contextmenu - 0xbb: 0x11f03, // low - 0xbc: 0x1c602, // rp - 0xbd: 0x5bb09, // onsuspend - 0xbe: 0x13606, // button - 0xbf: 0x4db04, // desc - 0xc1: 0x4e207, // section - 0xc2: 0x52a0a, // onprogress - 0xc3: 0x59e09, // onstorage - 0xc4: 0x2d204, // math - 0xc5: 0x4503, // alt - 0xc7: 0x8a02, // ul - 0xc8: 0x5107, // pattern - 0xc9: 0x4b60c, // onmousewheel - 0xca: 0x35709, // ondragend - 0xcb: 0xaf04, // ruby - 0xcc: 0xc01, // p - 0xcd: 0x31707, // onclose - 0xce: 0x24205, // meter - 0xcf: 0x11807, // bgsound - 0xd2: 0x25106, // height - 0xd4: 0x101, // b - 0xd5: 0x2c308, // itemtype - 0xd8: 0x1bb07, // caption - 0xd9: 0x10c08, // disabled - 0xdb: 0x33808, // menuitem - 0xdc: 0x62003, // svg - 0xdd: 0x18f05, // small - 0xde: 0x44a04, // data - 0xe0: 0x4cb08, // ononline - 0xe1: 0x2a206, // mglyph - 0xe3: 0x6505, // embed - 0xe4: 0x10502, // tr - 0xe5: 0x46b0b, // onloadstart - 0xe7: 0x3c306, // srcdoc - 0xeb: 0x5c408, // ontoggle - 0xed: 0xe703, // bdo - 0xee: 0x4702, // td - 0xef: 0x8305, // aside - 0xf0: 0x29402, // h2 - 0xf1: 0x52c08, // progress - 0xf2: 0x12c0a, // blockquote - 0xf4: 0xf005, // label - 0xf5: 0x601, // i - 0xf7: 0x9207, // rowspan - 0xfb: 0x51709, // onplaying - 0xfd: 0x2a103, // img - 0xfe: 0xf608, // optgroup - 0xff: 0x42307, // content - 0x101: 0x53e0c, // onratechange - 0x103: 0x3da0c, // onhashchange - 0x104: 0x4807, // details - 0x106: 0x40008, // download - 0x109: 0x14009, // translate - 0x10b: 0x4230f, // contenteditable - 0x10d: 0x36b0b, // ondragleave - 0x10e: 0x2106, // accept - 0x10f: 0x57a08, // selected - 0x112: 0x1f20a, // formaction - 0x113: 0x5b506, // center - 0x115: 0x45510, // onloadedmetadata - 0x116: 0x12804, // link - 0x117: 0xdd04, // time - 0x118: 0x19f0b, // crossorigin - 0x119: 0x3bd07, // onfocus - 0x11a: 0x58704, // wrap - 0x11b: 0x42204, // icon - 0x11d: 0x28105, // video - 0x11e: 0x4de05, // class - 0x121: 0x5d40e, // onvolumechange - 0x122: 0xaa06, // onblur - 0x123: 0x2b909, // itemscope - 0x124: 0x61105, // style - 0x127: 0x41e06, // public - 0x129: 0x2320e, // formnovalidate - 0x12a: 0x58206, // onshow - 0x12c: 0x51706, // onplay - 0x12d: 0x3c804, // cite - 0x12e: 0x2bc02, // ms - 0x12f: 0xdb0c, // ontimeupdate - 0x130: 0x10904, // kind - 0x131: 0x2470a, // formtarget - 0x135: 0x3af07, // onended - 0x136: 0x26506, // hidden - 0x137: 0x2c01, // s - 0x139: 0x2280a, // formmethod - 0x13a: 0x3e805, // input - 0x13c: 0x50b02, // h6 - 0x13d: 0xc902, // ol - 0x13e: 0x3420b, // oncuechange - 0x13f: 0x1e50d, // foreignobject - 0x143: 0x4e70e, // onbeforeunload - 0x144: 0x2bd05, // scope - 0x145: 0x39609, // onemptied - 0x146: 0x14b05, // defer - 0x147: 0xc103, // xmp - 0x148: 0x39f10, // ondurationchange - 0x149: 0x1903, // kbd - 0x14c: 0x47609, // onmessage - 0x14d: 0x60006, // option - 0x14e: 0x2eb09, // minlength - 0x14f: 0x32807, // checked - 0x150: 0xce08, // autoplay - 0x152: 0x202, // br - 0x153: 0x2360a, // novalidate - 0x156: 0x6307, // noembed - 0x159: 0x31007, // onclick - 0x15a: 0x47f0b, // onmousedown - 0x15b: 0x3a708, // onchange - 0x15e: 0x3f209, // oninvalid - 0x15f: 0x2bd06, // scoped - 0x160: 0x18808, // controls - 0x161: 0x30b05, // muted - 0x162: 0x58d08, // sortable - 0x163: 0x51106, // usemap - 0x164: 0x1b80a, // figcaption - 0x165: 0x35706, // ondrag - 0x166: 0x26b04, // high - 0x168: 0x3c303, // src - 0x169: 0x15706, // poster - 0x16b: 0x1670e, // annotation-xml - 0x16c: 0x5f704, // step - 0x16d: 0x4, // abbr - 0x16e: 0x1b06, // dialog - 0x170: 0x1202, // li - 0x172: 0x3ed02, // mo - 0x175: 0x1d803, // for - 0x176: 0x1a803, // ins - 0x178: 0x55504, // size - 0x179: 0x43210, // onlanguagechange - 0x17a: 0x8607, // default - 0x17b: 0x1a03, // bdi - 0x17c: 0x4d30a, // onpagehide - 0x17d: 0x6907, // dirname - 0x17e: 0x21404, // type - 0x17f: 0x1f204, // form - 0x181: 0x28509, // oncanplay - 0x182: 0x6103, // dfn - 0x183: 0x46308, // tabindex - 0x186: 0x6502, // em - 0x187: 0x27404, // lang - 0x189: 0x39108, // dropzone - 0x18a: 0x4080a, // onkeypress - 0x18b: 0x23c08, // datetime - 0x18c: 0x16204, // cols - 0x18d: 0x1, // a - 0x18e: 0x4420c, // onloadeddata - 0x190: 0xa605, // audio - 0x192: 0x2e05, // tbody - 0x193: 0x22c06, // method - 0x195: 0xf404, // loop - 0x196: 0x29606, // iframe - 0x198: 0x2d504, // head - 0x19e: 0x5f108, // manifest - 0x19f: 0xb309, // autofocus - 0x1a0: 0x14904, // code - 0x1a1: 0x55906, // strong - 0x1a2: 0x30308, // multiple - 0x1a3: 0xc05, // param - 0x1a6: 0x21107, // enctype - 0x1a7: 0x5b304, // face - 0x1a8: 0xfd09, // plaintext - 0x1a9: 0x26e02, // h1 - 0x1aa: 0x59509, // onstalled - 0x1ad: 0x3d406, // script - 0x1ae: 0x2db06, // spacer - 0x1af: 0x55108, // onresize - 0x1b0: 0x4a20b, // onmouseover - 0x1b1: 0x5cc08, // onunload - 0x1b2: 0x56708, // onseeked - 0x1b4: 0x2140d, // typemustmatch - 0x1b5: 0x1cc06, // figure - 0x1b6: 0x4950a, // onmouseout - 0x1b7: 0x25e03, // pre - 0x1b8: 0x50705, // width - 0x1b9: 0x19906, // sorted - 0x1bb: 0x5704, // nobr - 0x1be: 0x5302, // tt - 0x1bf: 0x1105, // align - 0x1c0: 0x3e607, // oninput - 0x1c3: 0x41807, // onkeyup - 0x1c6: 0x1c00c, // onafterprint - 0x1c7: 0x210e, // accept-charset - 0x1c8: 0x33c06, // itemid - 0x1c9: 0x3e809, // inputmode - 0x1cb: 0x53306, // strike - 0x1cc: 0x5a903, // sub - 0x1cd: 0x10505, // track - 0x1ce: 0x38605, // start - 0x1d0: 0xd608, // basefont - 0x1d6: 0x1aa06, // source - 0x1d7: 0x18206, // legend - 0x1d8: 0x2d405, // thead - 0x1da: 0x8c05, // tfoot - 0x1dd: 0x1ec06, // object - 0x1de: 0x6e05, // media - 0x1df: 0x1670a, // annotation - 0x1e0: 0x20d0b, // formenctype - 0x1e2: 0x3d208, // noscript - 0x1e4: 0x55505, // sizes - 0x1e5: 0x1fc0c, // autocomplete - 0x1e6: 0x9504, // span - 0x1e7: 0x9808, // noframes - 0x1e8: 0x24b06, // target - 0x1e9: 0x38f06, // ondrop - 0x1ea: 0x2b306, // applet - 0x1ec: 0x5a08, // reversed - 0x1f0: 0x2a907, // isindex - 0x1f3: 0x27008, // hreflang - 0x1f5: 0x2f302, // h5 - 0x1f6: 0x4f307, // address - 0x1fa: 0x2e103, // max - 0x1fb: 0xc30b, // placeholder - 0x1fc: 0x2f608, // textarea - 0x1fe: 0x4ad09, // onmouseup - 0x1ff: 0x3800b, // ondragstart + 0x1: 0xe60a, // mediagroup + 0x2: 0x2e404, // lang + 0x4: 0x2c09, // accesskey + 0x5: 0x8b08, // frameset + 0x7: 0x63a08, // onselect + 0x8: 0x71106, // system + 0xa: 0x64905, // width + 0xc: 0x2890b, // formenctype + 0xd: 0x13702, // ol + 0xe: 0x3970b, // oncuechange + 0x10: 0x14b03, // bdo + 0x11: 0x11505, // audio + 0x12: 0x17a09, // draggable + 0x14: 0x2f105, // video + 0x15: 0x2b102, // mn + 0x16: 0x38704, // menu + 0x17: 0x2cf06, // poster + 0x19: 0xf606, // footer + 0x1a: 0x2a806, // method + 0x1b: 0x2b808, // datetime + 0x1c: 0x19507, // onabort + 0x1d: 0x460e, // updateviacache + 0x1e: 0xff05, // async + 0x1f: 0x49d06, // onload + 0x21: 0x11908, // oncancel + 0x22: 0x62908, // onseeked + 0x23: 0x30205, // image + 0x24: 0x5d812, // onrejectionhandled + 0x26: 0x17404, // link + 0x27: 0x51d06, // output + 0x28: 0x33104, // head + 0x29: 0x4ff0c, // onmouseleave + 0x2a: 0x57f07, // onpaste + 0x2b: 0x5a409, // onplaying + 0x2c: 0x1c407, // colspan + 0x2f: 0x1bf05, // color + 0x30: 0x5f504, // size + 0x31: 0x2e80a, // http-equiv + 0x33: 0x601, // i + 0x34: 0x5590a, // onpagehide + 0x35: 0x68c14, // onunhandledrejection + 0x37: 0x42a07, // onerror + 0x3a: 0x3b08, // basefont + 0x3f: 0x1303, // nav + 0x40: 0x17704, // kind + 0x41: 0x35708, // readonly + 0x42: 0x30806, // mglyph + 0x44: 0xb202, // li + 0x46: 0x2d506, // hidden + 0x47: 0x70e03, // svg + 0x48: 0x58304, // step + 0x49: 0x23f09, // integrity + 0x4a: 0x58606, // public + 0x4c: 0x1ab03, // col + 0x4d: 0x1870a, // blockquote + 0x4e: 0x34f02, // h5 + 0x50: 0x5b908, // progress + 0x51: 0x5f505, // sizes + 0x52: 0x34502, // h4 + 0x56: 0x33005, // thead + 0x57: 0xd607, // keytype + 0x58: 0x5b70a, // onprogress + 0x59: 0x44b09, // inputmode + 0x5a: 0x3b109, // ondragend + 0x5d: 0x3a205, // oncut + 0x5e: 0x43706, // spacer + 0x5f: 0x1ab08, // colgroup + 0x62: 0x16502, // is + 0x65: 0x3c02, // as + 0x66: 0x54809, // onoffline + 0x67: 0x33706, // sorted + 0x69: 0x48d10, // onlanguagechange + 0x6c: 0x43d0c, // onhashchange + 0x6d: 0x9604, // name + 0x6e: 0xf505, // tfoot + 0x6f: 0x56104, // desc + 0x70: 0x33d03, // max + 0x72: 0x1ea06, // coords + 0x73: 0x30d02, // h3 + 0x74: 0x6e70e, // onbeforeunload + 0x75: 0x9c04, // rows + 0x76: 0x63c06, // select + 0x77: 0x9805, // meter + 0x78: 0x38b06, // itemid + 0x79: 0x53c0c, // onmousewheel + 0x7a: 0x5c006, // srcdoc + 0x7d: 0x1ba05, // track + 0x7f: 0x31f08, // itemtype + 0x82: 0xa402, // mo + 0x83: 0x41b08, // onchange + 0x84: 0x33107, // headers + 0x85: 0x5cc0c, // onratechange + 0x86: 0x60819, // onsecuritypolicyviolation + 0x88: 0x4a508, // datalist + 0x89: 0x4e80b, // onmousedown + 0x8a: 0x1ef04, // slot + 0x8b: 0x4b010, // onloadedmetadata + 0x8c: 0x1a06, // accept + 0x8d: 0x26806, // object + 0x91: 0x6b30e, // onvolumechange + 0x92: 0x2107, // charset + 0x93: 0x27613, // onautocompleteerror + 0x94: 0xc113, // allowpaymentrequest + 0x95: 0x2804, // body + 0x96: 0x10a07, // default + 0x97: 0x63c08, // selected + 0x98: 0x21e04, // face + 0x99: 0x1e505, // shape + 0x9b: 0x68408, // ontoggle + 0x9e: 0x64b02, // dt + 0x9f: 0xb604, // mark + 0xa1: 0xb01, // u + 0xa4: 0x6ab08, // onunload + 0xa5: 0x5d04, // loop + 0xa6: 0x16408, // disabled + 0xaa: 0x42307, // onended + 0xab: 0xb00a, // malignmark + 0xad: 0x67b09, // onsuspend + 0xae: 0x35105, // mtext + 0xaf: 0x64f06, // onsort + 0xb0: 0x19d08, // itemprop + 0xb3: 0x67109, // itemscope + 0xb4: 0x17305, // blink + 0xb6: 0x3b106, // ondrag + 0xb7: 0xa702, // ul + 0xb8: 0x26e04, // form + 0xb9: 0x12907, // sandbox + 0xba: 0x8b05, // frame + 0xbb: 0x1505, // value + 0xbc: 0x66209, // onstorage + 0xbf: 0xaa07, // acronym + 0xc0: 0x19a02, // rt + 0xc2: 0x202, // br + 0xc3: 0x22608, // fieldset + 0xc4: 0x2900d, // typemustmatch + 0xc5: 0xa208, // nomodule + 0xc6: 0x6c07, // noembed + 0xc7: 0x69e0d, // onbeforeprint + 0xc8: 0x19106, // button + 0xc9: 0x2f507, // onclick + 0xca: 0x70407, // summary + 0xcd: 0xfb04, // ruby + 0xce: 0x56405, // class + 0xcf: 0x3f40b, // ondragstart + 0xd0: 0x23107, // caption + 0xd4: 0xdd0e, // allowusermedia + 0xd5: 0x4cf0b, // onloadstart + 0xd9: 0x16b03, // div + 0xda: 0x4a904, // list + 0xdb: 0x32e04, // math + 0xdc: 0x44b05, // input + 0xdf: 0x3ea0a, // ondragover + 0xe0: 0x2de02, // h2 + 0xe2: 0x1b209, // plaintext + 0xe4: 0x4f30c, // onmouseenter + 0xe7: 0x47907, // checked + 0xe8: 0x47003, // pre + 0xea: 0x35f08, // multiple + 0xeb: 0xba03, // bdi + 0xec: 0x33d09, // maxlength + 0xed: 0xcf01, // q + 0xee: 0x61f0a, // onauxclick + 0xf0: 0x57c03, // wbr + 0xf2: 0x3b04, // base + 0xf3: 0x6e306, // option + 0xf5: 0x41310, // ondurationchange + 0xf7: 0x8908, // noframes + 0xf9: 0x40508, // dropzone + 0xfb: 0x67505, // scope + 0xfc: 0x8008, // reversed + 0xfd: 0x3ba0b, // ondragenter + 0xfe: 0x3fa05, // start + 0xff: 0x12f03, // xmp + 0x100: 0x5f907, // srclang + 0x101: 0x30703, // img + 0x104: 0x101, // b + 0x105: 0x25403, // for + 0x106: 0x10705, // aside + 0x107: 0x44907, // oninput + 0x108: 0x35604, // area + 0x109: 0x2a40a, // formmethod + 0x10a: 0x72604, // wrap + 0x10c: 0x23c02, // rp + 0x10d: 0x46b0a, // onkeypress + 0x10e: 0x6802, // tt + 0x110: 0x34702, // mi + 0x111: 0x36705, // muted + 0x112: 0xf303, // alt + 0x113: 0x5c504, // code + 0x114: 0x6e02, // em + 0x115: 0x3c50a, // ondragexit + 0x117: 0x9f04, // span + 0x119: 0x6d708, // manifest + 0x11a: 0x38708, // menuitem + 0x11b: 0x58b07, // content + 0x11d: 0x6c109, // onwaiting + 0x11f: 0x4c609, // onloadend + 0x121: 0x37e0d, // oncontextmenu + 0x123: 0x56d06, // onblur + 0x124: 0x3fc07, // article + 0x125: 0x9303, // dir + 0x126: 0xef04, // ping + 0x127: 0x24c08, // required + 0x128: 0x45509, // oninvalid + 0x129: 0xb105, // align + 0x12b: 0x58a04, // icon + 0x12c: 0x64d02, // h6 + 0x12d: 0x1c404, // cols + 0x12e: 0x22e0a, // figcaption + 0x12f: 0x45e09, // onkeydown + 0x130: 0x66b08, // onsubmit + 0x131: 0x14d09, // oncanplay + 0x132: 0x70b03, // sup + 0x133: 0xc01, // p + 0x135: 0x40a09, // onemptied + 0x136: 0x39106, // oncopy + 0x137: 0x19c04, // cite + 0x138: 0x3a70a, // ondblclick + 0x13a: 0x50b0b, // onmousemove + 0x13c: 0x66d03, // sub + 0x13d: 0x48703, // rel + 0x13e: 0x5f08, // optgroup + 0x142: 0x9c07, // rowspan + 0x143: 0x37806, // source + 0x144: 0x21608, // noscript + 0x145: 0x1a304, // open + 0x146: 0x20403, // ins + 0x147: 0x2540d, // foreignObject + 0x148: 0x5ad0a, // onpopstate + 0x14a: 0x28d07, // enctype + 0x14b: 0x2760e, // onautocomplete + 0x14c: 0x35208, // textarea + 0x14e: 0x2780c, // autocomplete + 0x14f: 0x15702, // hr + 0x150: 0x1de08, // controls + 0x151: 0x10902, // id + 0x153: 0x2360c, // onafterprint + 0x155: 0x2610d, // foreignobject + 0x156: 0x32707, // marquee + 0x157: 0x59a07, // onpause + 0x158: 0x5e602, // dl + 0x159: 0x5206, // height + 0x15a: 0x34703, // min + 0x15b: 0x9307, // dirname + 0x15c: 0x1f209, // translate + 0x15d: 0x5604, // html + 0x15e: 0x34709, // minlength + 0x15f: 0x48607, // preload + 0x160: 0x71408, // template + 0x161: 0x3df0b, // ondragleave + 0x162: 0x3a02, // rb + 0x164: 0x5c003, // src + 0x165: 0x6dd06, // strong + 0x167: 0x7804, // samp + 0x168: 0x6f307, // address + 0x169: 0x55108, // ononline + 0x16b: 0x1310b, // placeholder + 0x16c: 0x2c406, // target + 0x16d: 0x20605, // small + 0x16e: 0x6ca07, // onwheel + 0x16f: 0x1c90a, // annotation + 0x170: 0x4740a, // spellcheck + 0x171: 0x7207, // details + 0x172: 0x10306, // canvas + 0x173: 0x12109, // autofocus + 0x174: 0xc05, // param + 0x176: 0x46308, // download + 0x177: 0x45203, // del + 0x178: 0x36c07, // onclose + 0x179: 0xb903, // kbd + 0x17a: 0x31906, // applet + 0x17b: 0x2e004, // href + 0x17c: 0x5f108, // onresize + 0x17e: 0x49d0c, // onloadeddata + 0x180: 0xcc02, // tr + 0x181: 0x2c00a, // formtarget + 0x182: 0x11005, // title + 0x183: 0x6ff05, // style + 0x184: 0xd206, // strike + 0x185: 0x59e06, // usemap + 0x186: 0x2fc06, // iframe + 0x187: 0x1004, // main + 0x189: 0x7b07, // picture + 0x18c: 0x31605, // ismap + 0x18e: 0x4a504, // data + 0x18f: 0x5905, // label + 0x191: 0x3d10e, // referrerpolicy + 0x192: 0x15602, // th + 0x194: 0x53606, // prompt + 0x195: 0x56807, // section + 0x197: 0x6d107, // optimum + 0x198: 0x2db04, // high + 0x199: 0x15c02, // h1 + 0x19a: 0x65909, // onstalled + 0x19b: 0x16d03, // var + 0x19c: 0x4204, // time + 0x19e: 0x67402, // ms + 0x19f: 0x33106, // header + 0x1a0: 0x4da09, // onmessage + 0x1a1: 0x1a605, // nonce + 0x1a2: 0x26e0a, // formaction + 0x1a3: 0x22006, // center + 0x1a4: 0x3704, // nobr + 0x1a5: 0x59505, // table + 0x1a6: 0x4a907, // listing + 0x1a7: 0x18106, // legend + 0x1a9: 0x29b09, // challenge + 0x1aa: 0x24806, // figure + 0x1ab: 0xe605, // media + 0x1ae: 0xd904, // type + 0x1af: 0x3f04, // font + 0x1b0: 0x4da0e, // onmessageerror + 0x1b1: 0x37108, // seamless + 0x1b2: 0x8703, // dfn + 0x1b3: 0x5c705, // defer + 0x1b4: 0xc303, // low + 0x1b5: 0x19a03, // rtc + 0x1b6: 0x5230b, // onmouseover + 0x1b7: 0x2b20a, // novalidate + 0x1b8: 0x71c0a, // workertype + 0x1ba: 0x3cd07, // itemref + 0x1bd: 0x1, // a + 0x1be: 0x31803, // map + 0x1bf: 0x400c, // ontimeupdate + 0x1c0: 0x15e07, // bgsound + 0x1c1: 0x3206, // keygen + 0x1c2: 0x2705, // tbody + 0x1c5: 0x64406, // onshow + 0x1c7: 0x2501, // s + 0x1c8: 0x6607, // pattern + 0x1cc: 0x14d10, // oncanplaythrough + 0x1ce: 0x2d702, // dd + 0x1cf: 0x6f906, // srcset + 0x1d0: 0x17003, // big + 0x1d2: 0x65108, // sortable + 0x1d3: 0x48007, // onkeyup + 0x1d5: 0x5a406, // onplay + 0x1d7: 0x4b804, // meta + 0x1d8: 0x40306, // ondrop + 0x1da: 0x60008, // onscroll + 0x1db: 0x1fb0b, // crossorigin + 0x1dc: 0x5730a, // onpageshow + 0x1dd: 0x4, // abbr + 0x1de: 0x9202, // td + 0x1df: 0x58b0f, // contenteditable + 0x1e0: 0x27206, // action + 0x1e1: 0x1400b, // playsinline + 0x1e2: 0x43107, // onfocus + 0x1e3: 0x2e008, // hreflang + 0x1e5: 0x5160a, // onmouseout + 0x1e6: 0x5ea07, // onreset + 0x1e7: 0x13c08, // autoplay + 0x1e8: 0x63109, // onseeking + 0x1ea: 0x67506, // scoped + 0x1ec: 0x30a, // radiogroup + 0x1ee: 0x3800b, // contextmenu + 0x1ef: 0x52e09, // onmouseup + 0x1f1: 0x2ca06, // hgroup + 0x1f2: 0x2080f, // allowfullscreen + 0x1f3: 0x4be08, // tabindex + 0x1f6: 0x30f07, // isindex + 0x1f7: 0x1a0e, // accept-charset + 0x1f8: 0x2ae0e, // formnovalidate + 0x1fb: 0x1c90e, // annotation-xml + 0x1fc: 0x6e05, // embed + 0x1fd: 0x21806, // script + 0x1fe: 0xbb06, // dialog + 0x1ff: 0x1d707, // command } -const atomText = "abbradiogrouparamalignmarkbdialogaccept-charsetbodyaccesskey" + - "genavaluealtdetailsampatternobreversedfnoembedirnamediagroup" + - "ingasyncanvasidefaultfooterowspanoframesetitleaudionblurubya" + - "utofocusandboxmplaceholderautoplaybasefontimeupdatebdoncance" + - "labelooptgrouplaintextrackindisabledivarbgsoundlowbrbigblink" + - "blockquotebuttonabortranslatecodefercolgroupostercolorcolspa" + - "nnotation-xmlcommandraggablegendcontrolsmallcoordsortedcross" + - "originsourcefieldsetfigcaptionafterprintfigurequiredforeignO" + - "bjectforeignobjectformactionautocompleteerrorformenctypemust" + - "matchallengeformmethodformnovalidatetimeterformtargetheightm" + - "lhgroupreloadhiddenhigh1hreflanghttp-equivideoncanplaythroug" + - "h2iframeimageimglyph3isindexismappletitemscopeditemtypemarqu" + - "eematheaderspacermaxlength4minlength5mtextareadonlymultiplem" + - "utedonclickoncloseamlesspellcheckedoncontextmenuitemidoncuec" + - "hangeondblclickondragendondragenterondragleaveondragoverondr" + - "agstarticleondropzonemptiedondurationchangeonendedonerroronf" + - "ocusrcdocitempropenoscriptonhashchangeoninputmodeloninvalido" + - "nkeydownloadonkeypressrclangonkeyupublicontenteditableonlang" + - "uagechangeonloadeddatalistingonloadedmetadatabindexonloadsta" + - "rtonmessageonmousedownonmousemoveonmouseoutputonmouseoveronm" + - "ouseuponmousewheelonofflineononlineonpagehidesclassectionbef" + - "oreunloaddresshapeonpageshowidth6onpausemaponplayingonpopsta" + - "teonprogresstrikeytypeonratechangeonresetonresizestrongonscr" + - "ollonseekedonseekingonselectedonshowraponsortableonstalledon" + - "storageonsubmitemrefacenteronsuspendontoggleonunloadonvolume" + - "changeonwaitingoptimumanifestepromptoptionbeforeprintstylesu" + - "mmarysupsvgsystemplate" +const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + + "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + + "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + + "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + + "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + + "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + + "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + + "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + + "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" + + "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" + + "ignObjectforeignobjectformactionautocompleteerrorformenctype" + + "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" + + "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" + + "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" + + "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" + + "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" + + "enterondragexitemreferrerpolicyondragleaveondragoverondragst" + + "articleondropzonemptiedondurationchangeonendedonerroronfocus" + + "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" + + "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" + + "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" + + "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" + + "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" + + "classectionbluronpageshowbronpastepublicontenteditableonpaus" + + "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" + + "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" + + "violationauxclickonseekedonseekingonselectedonshowidth6onsor" + + "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" + + "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" + + "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" + + "arysupsvgsystemplateworkertypewrap" diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go index 52f651ff6..a3a918f0b 100644 --- a/vendor/golang.org/x/net/html/const.go +++ b/vendor/golang.org/x/net/html/const.go @@ -4,7 +4,7 @@ package html -// Section 12.2.3.2 of the HTML5 specification says "The following elements +// Section 12.2.4.2 of the HTML5 specification says "The following elements // have varying levels of special parsing rules". // https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements var isSpecialElementMap = map[string]bool{ @@ -52,10 +52,12 @@ var isSpecialElementMap = map[string]bool{ "iframe": true, "img": true, "input": true, - "isindex": true, + "isindex": true, // The 'isindex' element has been removed, but keep it for backwards compatibility. + "keygen": true, "li": true, "link": true, "listing": true, + "main": true, "marquee": true, "menu": true, "meta": true, @@ -95,8 +97,16 @@ func isSpecialElement(element *Node) bool { switch element.Namespace { case "", "html": return isSpecialElementMap[element.Data] + case "math": + switch element.Data { + case "mi", "mo", "mn", "ms", "mtext", "annotation-xml": + return true + } case "svg": - return element.Data == "foreignObject" + switch element.Data { + case "foreignObject", "desc", "title": + return true + } } return false } diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go index 94f496874..822ed42a0 100644 --- a/vendor/golang.org/x/net/html/doc.go +++ b/vendor/golang.org/x/net/html/doc.go @@ -49,18 +49,18 @@ call to Next. For example, to extract an HTML page's anchor text: for { tt := z.Next() switch tt { - case ErrorToken: + case html.ErrorToken: return z.Err() - case TextToken: + case html.TextToken: if depth > 0 { // emitBytes should copy the []byte it receives, // if it doesn't process it immediately. emitBytes(z.Text()) } - case StartTagToken, EndTagToken: + case html.StartTagToken, html.EndTagToken: tn, _ := z.TagName() if len(tn) == 1 && tn[0] == 'a' { - if tt == StartTagToken { + if tt == html.StartTagToken { depth++ } else { depth-- diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go index a50c04c60..b628880a0 100644 --- a/vendor/golang.org/x/net/html/entity.go +++ b/vendor/golang.org/x/net/html/entity.go @@ -75,2083 +75,2083 @@ var entity = map[string]rune{ "Copf;": '\U00002102', "Coproduct;": '\U00002210', "CounterClockwiseContourIntegral;": '\U00002233', - "Cross;": '\U00002A2F', - "Cscr;": '\U0001D49E', - "Cup;": '\U000022D3', - "CupCap;": '\U0000224D', - "DD;": '\U00002145', - "DDotrahd;": '\U00002911', - "DJcy;": '\U00000402', - "DScy;": '\U00000405', - "DZcy;": '\U0000040F', - "Dagger;": '\U00002021', - "Darr;": '\U000021A1', - "Dashv;": '\U00002AE4', - "Dcaron;": '\U0000010E', - "Dcy;": '\U00000414', - "Del;": '\U00002207', - "Delta;": '\U00000394', - "Dfr;": '\U0001D507', - "DiacriticalAcute;": '\U000000B4', - "DiacriticalDot;": '\U000002D9', - "DiacriticalDoubleAcute;": '\U000002DD', - "DiacriticalGrave;": '\U00000060', - "DiacriticalTilde;": '\U000002DC', - "Diamond;": '\U000022C4', - "DifferentialD;": '\U00002146', - "Dopf;": '\U0001D53B', - "Dot;": '\U000000A8', - "DotDot;": '\U000020DC', - "DotEqual;": '\U00002250', - "DoubleContourIntegral;": '\U0000222F', - "DoubleDot;": '\U000000A8', - "DoubleDownArrow;": '\U000021D3', - "DoubleLeftArrow;": '\U000021D0', - "DoubleLeftRightArrow;": '\U000021D4', - "DoubleLeftTee;": '\U00002AE4', - "DoubleLongLeftArrow;": '\U000027F8', - "DoubleLongLeftRightArrow;": '\U000027FA', - "DoubleLongRightArrow;": '\U000027F9', - "DoubleRightArrow;": '\U000021D2', - "DoubleRightTee;": '\U000022A8', - "DoubleUpArrow;": '\U000021D1', - "DoubleUpDownArrow;": '\U000021D5', - "DoubleVerticalBar;": '\U00002225', - "DownArrow;": '\U00002193', - "DownArrowBar;": '\U00002913', - "DownArrowUpArrow;": '\U000021F5', - "DownBreve;": '\U00000311', - "DownLeftRightVector;": '\U00002950', - "DownLeftTeeVector;": '\U0000295E', - "DownLeftVector;": '\U000021BD', - "DownLeftVectorBar;": '\U00002956', - "DownRightTeeVector;": '\U0000295F', - "DownRightVector;": '\U000021C1', - "DownRightVectorBar;": '\U00002957', - "DownTee;": '\U000022A4', - "DownTeeArrow;": '\U000021A7', - "Downarrow;": '\U000021D3', - "Dscr;": '\U0001D49F', - "Dstrok;": '\U00000110', - "ENG;": '\U0000014A', - "ETH;": '\U000000D0', - "Eacute;": '\U000000C9', - "Ecaron;": '\U0000011A', - "Ecirc;": '\U000000CA', - "Ecy;": '\U0000042D', - "Edot;": '\U00000116', - "Efr;": '\U0001D508', - "Egrave;": '\U000000C8', - "Element;": '\U00002208', - "Emacr;": '\U00000112', - "EmptySmallSquare;": '\U000025FB', - "EmptyVerySmallSquare;": '\U000025AB', - "Eogon;": '\U00000118', - "Eopf;": '\U0001D53C', - "Epsilon;": '\U00000395', - "Equal;": '\U00002A75', - "EqualTilde;": '\U00002242', - "Equilibrium;": '\U000021CC', - "Escr;": '\U00002130', - "Esim;": '\U00002A73', - "Eta;": '\U00000397', - "Euml;": '\U000000CB', - "Exists;": '\U00002203', - "ExponentialE;": '\U00002147', - "Fcy;": '\U00000424', - "Ffr;": '\U0001D509', - "FilledSmallSquare;": '\U000025FC', - "FilledVerySmallSquare;": '\U000025AA', - "Fopf;": '\U0001D53D', - "ForAll;": '\U00002200', - "Fouriertrf;": '\U00002131', - "Fscr;": '\U00002131', - "GJcy;": '\U00000403', - "GT;": '\U0000003E', - "Gamma;": '\U00000393', - "Gammad;": '\U000003DC', - "Gbreve;": '\U0000011E', - "Gcedil;": '\U00000122', - "Gcirc;": '\U0000011C', - "Gcy;": '\U00000413', - "Gdot;": '\U00000120', - "Gfr;": '\U0001D50A', - "Gg;": '\U000022D9', - "Gopf;": '\U0001D53E', - "GreaterEqual;": '\U00002265', - "GreaterEqualLess;": '\U000022DB', - "GreaterFullEqual;": '\U00002267', - "GreaterGreater;": '\U00002AA2', - "GreaterLess;": '\U00002277', - "GreaterSlantEqual;": '\U00002A7E', - "GreaterTilde;": '\U00002273', - "Gscr;": '\U0001D4A2', - "Gt;": '\U0000226B', - "HARDcy;": '\U0000042A', - "Hacek;": '\U000002C7', - "Hat;": '\U0000005E', - "Hcirc;": '\U00000124', - "Hfr;": '\U0000210C', - "HilbertSpace;": '\U0000210B', - "Hopf;": '\U0000210D', - "HorizontalLine;": '\U00002500', - "Hscr;": '\U0000210B', - "Hstrok;": '\U00000126', - "HumpDownHump;": '\U0000224E', - "HumpEqual;": '\U0000224F', - "IEcy;": '\U00000415', - "IJlig;": '\U00000132', - "IOcy;": '\U00000401', - "Iacute;": '\U000000CD', - "Icirc;": '\U000000CE', - "Icy;": '\U00000418', - "Idot;": '\U00000130', - "Ifr;": '\U00002111', - "Igrave;": '\U000000CC', - "Im;": '\U00002111', - "Imacr;": '\U0000012A', - "ImaginaryI;": '\U00002148', - "Implies;": '\U000021D2', - "Int;": '\U0000222C', - "Integral;": '\U0000222B', - "Intersection;": '\U000022C2', - "InvisibleComma;": '\U00002063', - "InvisibleTimes;": '\U00002062', - "Iogon;": '\U0000012E', - "Iopf;": '\U0001D540', - "Iota;": '\U00000399', - "Iscr;": '\U00002110', - "Itilde;": '\U00000128', - "Iukcy;": '\U00000406', - "Iuml;": '\U000000CF', - "Jcirc;": '\U00000134', - "Jcy;": '\U00000419', - "Jfr;": '\U0001D50D', - "Jopf;": '\U0001D541', - "Jscr;": '\U0001D4A5', - "Jsercy;": '\U00000408', - "Jukcy;": '\U00000404', - "KHcy;": '\U00000425', - "KJcy;": '\U0000040C', - "Kappa;": '\U0000039A', - "Kcedil;": '\U00000136', - "Kcy;": '\U0000041A', - "Kfr;": '\U0001D50E', - "Kopf;": '\U0001D542', - "Kscr;": '\U0001D4A6', - "LJcy;": '\U00000409', - "LT;": '\U0000003C', - "Lacute;": '\U00000139', - "Lambda;": '\U0000039B', - "Lang;": '\U000027EA', - "Laplacetrf;": '\U00002112', - "Larr;": '\U0000219E', - "Lcaron;": '\U0000013D', - "Lcedil;": '\U0000013B', - "Lcy;": '\U0000041B', - "LeftAngleBracket;": '\U000027E8', - "LeftArrow;": '\U00002190', - "LeftArrowBar;": '\U000021E4', - "LeftArrowRightArrow;": '\U000021C6', - "LeftCeiling;": '\U00002308', - "LeftDoubleBracket;": '\U000027E6', - "LeftDownTeeVector;": '\U00002961', - "LeftDownVector;": '\U000021C3', - "LeftDownVectorBar;": '\U00002959', - "LeftFloor;": '\U0000230A', - "LeftRightArrow;": '\U00002194', - "LeftRightVector;": '\U0000294E', - "LeftTee;": '\U000022A3', - "LeftTeeArrow;": '\U000021A4', - "LeftTeeVector;": '\U0000295A', - "LeftTriangle;": '\U000022B2', - "LeftTriangleBar;": '\U000029CF', - "LeftTriangleEqual;": '\U000022B4', - "LeftUpDownVector;": '\U00002951', - "LeftUpTeeVector;": '\U00002960', - "LeftUpVector;": '\U000021BF', - "LeftUpVectorBar;": '\U00002958', - "LeftVector;": '\U000021BC', - "LeftVectorBar;": '\U00002952', - "Leftarrow;": '\U000021D0', - "Leftrightarrow;": '\U000021D4', - "LessEqualGreater;": '\U000022DA', - "LessFullEqual;": '\U00002266', - "LessGreater;": '\U00002276', - "LessLess;": '\U00002AA1', - "LessSlantEqual;": '\U00002A7D', - "LessTilde;": '\U00002272', - "Lfr;": '\U0001D50F', - "Ll;": '\U000022D8', - "Lleftarrow;": '\U000021DA', - "Lmidot;": '\U0000013F', - "LongLeftArrow;": '\U000027F5', - "LongLeftRightArrow;": '\U000027F7', - "LongRightArrow;": '\U000027F6', - "Longleftarrow;": '\U000027F8', - "Longleftrightarrow;": '\U000027FA', - "Longrightarrow;": '\U000027F9', - "Lopf;": '\U0001D543', - "LowerLeftArrow;": '\U00002199', - "LowerRightArrow;": '\U00002198', - "Lscr;": '\U00002112', - "Lsh;": '\U000021B0', - "Lstrok;": '\U00000141', - "Lt;": '\U0000226A', - "Map;": '\U00002905', - "Mcy;": '\U0000041C', - "MediumSpace;": '\U0000205F', - "Mellintrf;": '\U00002133', - "Mfr;": '\U0001D510', - "MinusPlus;": '\U00002213', - "Mopf;": '\U0001D544', - "Mscr;": '\U00002133', - "Mu;": '\U0000039C', - "NJcy;": '\U0000040A', - "Nacute;": '\U00000143', - "Ncaron;": '\U00000147', - "Ncedil;": '\U00000145', - "Ncy;": '\U0000041D', - "NegativeMediumSpace;": '\U0000200B', - "NegativeThickSpace;": '\U0000200B', - "NegativeThinSpace;": '\U0000200B', - "NegativeVeryThinSpace;": '\U0000200B', - "NestedGreaterGreater;": '\U0000226B', - "NestedLessLess;": '\U0000226A', - "NewLine;": '\U0000000A', - "Nfr;": '\U0001D511', - "NoBreak;": '\U00002060', - "NonBreakingSpace;": '\U000000A0', - "Nopf;": '\U00002115', - "Not;": '\U00002AEC', - "NotCongruent;": '\U00002262', - "NotCupCap;": '\U0000226D', - "NotDoubleVerticalBar;": '\U00002226', - "NotElement;": '\U00002209', - "NotEqual;": '\U00002260', - "NotExists;": '\U00002204', - "NotGreater;": '\U0000226F', - "NotGreaterEqual;": '\U00002271', - "NotGreaterLess;": '\U00002279', - "NotGreaterTilde;": '\U00002275', - "NotLeftTriangle;": '\U000022EA', - "NotLeftTriangleEqual;": '\U000022EC', - "NotLess;": '\U0000226E', - "NotLessEqual;": '\U00002270', - "NotLessGreater;": '\U00002278', - "NotLessTilde;": '\U00002274', - "NotPrecedes;": '\U00002280', - "NotPrecedesSlantEqual;": '\U000022E0', - "NotReverseElement;": '\U0000220C', - "NotRightTriangle;": '\U000022EB', - "NotRightTriangleEqual;": '\U000022ED', - "NotSquareSubsetEqual;": '\U000022E2', - "NotSquareSupersetEqual;": '\U000022E3', - "NotSubsetEqual;": '\U00002288', - "NotSucceeds;": '\U00002281', - "NotSucceedsSlantEqual;": '\U000022E1', - "NotSupersetEqual;": '\U00002289', - "NotTilde;": '\U00002241', - "NotTildeEqual;": '\U00002244', - "NotTildeFullEqual;": '\U00002247', - "NotTildeTilde;": '\U00002249', - "NotVerticalBar;": '\U00002224', - "Nscr;": '\U0001D4A9', - "Ntilde;": '\U000000D1', - "Nu;": '\U0000039D', - "OElig;": '\U00000152', - "Oacute;": '\U000000D3', - "Ocirc;": '\U000000D4', - "Ocy;": '\U0000041E', - "Odblac;": '\U00000150', - "Ofr;": '\U0001D512', - "Ograve;": '\U000000D2', - "Omacr;": '\U0000014C', - "Omega;": '\U000003A9', - "Omicron;": '\U0000039F', - "Oopf;": '\U0001D546', - "OpenCurlyDoubleQuote;": '\U0000201C', - "OpenCurlyQuote;": '\U00002018', - "Or;": '\U00002A54', - "Oscr;": '\U0001D4AA', - "Oslash;": '\U000000D8', - "Otilde;": '\U000000D5', - "Otimes;": '\U00002A37', - "Ouml;": '\U000000D6', - "OverBar;": '\U0000203E', - "OverBrace;": '\U000023DE', - "OverBracket;": '\U000023B4', - "OverParenthesis;": '\U000023DC', - "PartialD;": '\U00002202', - "Pcy;": '\U0000041F', - "Pfr;": '\U0001D513', - "Phi;": '\U000003A6', - "Pi;": '\U000003A0', - "PlusMinus;": '\U000000B1', - "Poincareplane;": '\U0000210C', - "Popf;": '\U00002119', - "Pr;": '\U00002ABB', - "Precedes;": '\U0000227A', - "PrecedesEqual;": '\U00002AAF', - "PrecedesSlantEqual;": '\U0000227C', - "PrecedesTilde;": '\U0000227E', - "Prime;": '\U00002033', - "Product;": '\U0000220F', - "Proportion;": '\U00002237', - "Proportional;": '\U0000221D', - "Pscr;": '\U0001D4AB', - "Psi;": '\U000003A8', - "QUOT;": '\U00000022', - "Qfr;": '\U0001D514', - "Qopf;": '\U0000211A', - "Qscr;": '\U0001D4AC', - "RBarr;": '\U00002910', - "REG;": '\U000000AE', - "Racute;": '\U00000154', - "Rang;": '\U000027EB', - "Rarr;": '\U000021A0', - "Rarrtl;": '\U00002916', - "Rcaron;": '\U00000158', - "Rcedil;": '\U00000156', - "Rcy;": '\U00000420', - "Re;": '\U0000211C', - "ReverseElement;": '\U0000220B', - "ReverseEquilibrium;": '\U000021CB', - "ReverseUpEquilibrium;": '\U0000296F', - "Rfr;": '\U0000211C', - "Rho;": '\U000003A1', - "RightAngleBracket;": '\U000027E9', - "RightArrow;": '\U00002192', - "RightArrowBar;": '\U000021E5', - "RightArrowLeftArrow;": '\U000021C4', - "RightCeiling;": '\U00002309', - "RightDoubleBracket;": '\U000027E7', - "RightDownTeeVector;": '\U0000295D', - "RightDownVector;": '\U000021C2', - "RightDownVectorBar;": '\U00002955', - "RightFloor;": '\U0000230B', - "RightTee;": '\U000022A2', - "RightTeeArrow;": '\U000021A6', - "RightTeeVector;": '\U0000295B', - "RightTriangle;": '\U000022B3', - "RightTriangleBar;": '\U000029D0', - "RightTriangleEqual;": '\U000022B5', - "RightUpDownVector;": '\U0000294F', - "RightUpTeeVector;": '\U0000295C', - "RightUpVector;": '\U000021BE', - "RightUpVectorBar;": '\U00002954', - "RightVector;": '\U000021C0', - "RightVectorBar;": '\U00002953', - "Rightarrow;": '\U000021D2', - "Ropf;": '\U0000211D', - "RoundImplies;": '\U00002970', - "Rrightarrow;": '\U000021DB', - "Rscr;": '\U0000211B', - "Rsh;": '\U000021B1', - "RuleDelayed;": '\U000029F4', - "SHCHcy;": '\U00000429', - "SHcy;": '\U00000428', - "SOFTcy;": '\U0000042C', - "Sacute;": '\U0000015A', - "Sc;": '\U00002ABC', - "Scaron;": '\U00000160', - "Scedil;": '\U0000015E', - "Scirc;": '\U0000015C', - "Scy;": '\U00000421', - "Sfr;": '\U0001D516', - "ShortDownArrow;": '\U00002193', - "ShortLeftArrow;": '\U00002190', - "ShortRightArrow;": '\U00002192', - "ShortUpArrow;": '\U00002191', - "Sigma;": '\U000003A3', - "SmallCircle;": '\U00002218', - "Sopf;": '\U0001D54A', - "Sqrt;": '\U0000221A', - "Square;": '\U000025A1', - "SquareIntersection;": '\U00002293', - "SquareSubset;": '\U0000228F', - "SquareSubsetEqual;": '\U00002291', - "SquareSuperset;": '\U00002290', - "SquareSupersetEqual;": '\U00002292', - "SquareUnion;": '\U00002294', - "Sscr;": '\U0001D4AE', - "Star;": '\U000022C6', - "Sub;": '\U000022D0', - "Subset;": '\U000022D0', - "SubsetEqual;": '\U00002286', - "Succeeds;": '\U0000227B', - "SucceedsEqual;": '\U00002AB0', - "SucceedsSlantEqual;": '\U0000227D', - "SucceedsTilde;": '\U0000227F', - "SuchThat;": '\U0000220B', - "Sum;": '\U00002211', - "Sup;": '\U000022D1', - "Superset;": '\U00002283', - "SupersetEqual;": '\U00002287', - "Supset;": '\U000022D1', - "THORN;": '\U000000DE', - "TRADE;": '\U00002122', - "TSHcy;": '\U0000040B', - "TScy;": '\U00000426', - "Tab;": '\U00000009', - "Tau;": '\U000003A4', - "Tcaron;": '\U00000164', - "Tcedil;": '\U00000162', - "Tcy;": '\U00000422', - "Tfr;": '\U0001D517', - "Therefore;": '\U00002234', - "Theta;": '\U00000398', - "ThinSpace;": '\U00002009', - "Tilde;": '\U0000223C', - "TildeEqual;": '\U00002243', - "TildeFullEqual;": '\U00002245', - "TildeTilde;": '\U00002248', - "Topf;": '\U0001D54B', - "TripleDot;": '\U000020DB', - "Tscr;": '\U0001D4AF', - "Tstrok;": '\U00000166', - "Uacute;": '\U000000DA', - "Uarr;": '\U0000219F', - "Uarrocir;": '\U00002949', - "Ubrcy;": '\U0000040E', - "Ubreve;": '\U0000016C', - "Ucirc;": '\U000000DB', - "Ucy;": '\U00000423', - "Udblac;": '\U00000170', - "Ufr;": '\U0001D518', - "Ugrave;": '\U000000D9', - "Umacr;": '\U0000016A', - "UnderBar;": '\U0000005F', - "UnderBrace;": '\U000023DF', - "UnderBracket;": '\U000023B5', - "UnderParenthesis;": '\U000023DD', - "Union;": '\U000022C3', - "UnionPlus;": '\U0000228E', - "Uogon;": '\U00000172', - "Uopf;": '\U0001D54C', - "UpArrow;": '\U00002191', - "UpArrowBar;": '\U00002912', - "UpArrowDownArrow;": '\U000021C5', - "UpDownArrow;": '\U00002195', - "UpEquilibrium;": '\U0000296E', - "UpTee;": '\U000022A5', - "UpTeeArrow;": '\U000021A5', - "Uparrow;": '\U000021D1', - "Updownarrow;": '\U000021D5', - "UpperLeftArrow;": '\U00002196', - "UpperRightArrow;": '\U00002197', - "Upsi;": '\U000003D2', - "Upsilon;": '\U000003A5', - "Uring;": '\U0000016E', - "Uscr;": '\U0001D4B0', - "Utilde;": '\U00000168', - "Uuml;": '\U000000DC', - "VDash;": '\U000022AB', - "Vbar;": '\U00002AEB', - "Vcy;": '\U00000412', - "Vdash;": '\U000022A9', - "Vdashl;": '\U00002AE6', - "Vee;": '\U000022C1', - "Verbar;": '\U00002016', - "Vert;": '\U00002016', - "VerticalBar;": '\U00002223', - "VerticalLine;": '\U0000007C', - "VerticalSeparator;": '\U00002758', - "VerticalTilde;": '\U00002240', - "VeryThinSpace;": '\U0000200A', - "Vfr;": '\U0001D519', - "Vopf;": '\U0001D54D', - "Vscr;": '\U0001D4B1', - "Vvdash;": '\U000022AA', - "Wcirc;": '\U00000174', - "Wedge;": '\U000022C0', - "Wfr;": '\U0001D51A', - "Wopf;": '\U0001D54E', - "Wscr;": '\U0001D4B2', - "Xfr;": '\U0001D51B', - "Xi;": '\U0000039E', - "Xopf;": '\U0001D54F', - "Xscr;": '\U0001D4B3', - "YAcy;": '\U0000042F', - "YIcy;": '\U00000407', - "YUcy;": '\U0000042E', - "Yacute;": '\U000000DD', - "Ycirc;": '\U00000176', - "Ycy;": '\U0000042B', - "Yfr;": '\U0001D51C', - "Yopf;": '\U0001D550', - "Yscr;": '\U0001D4B4', - "Yuml;": '\U00000178', - "ZHcy;": '\U00000416', - "Zacute;": '\U00000179', - "Zcaron;": '\U0000017D', - "Zcy;": '\U00000417', - "Zdot;": '\U0000017B', - "ZeroWidthSpace;": '\U0000200B', - "Zeta;": '\U00000396', - "Zfr;": '\U00002128', - "Zopf;": '\U00002124', - "Zscr;": '\U0001D4B5', - "aacute;": '\U000000E1', - "abreve;": '\U00000103', - "ac;": '\U0000223E', - "acd;": '\U0000223F', - "acirc;": '\U000000E2', - "acute;": '\U000000B4', - "acy;": '\U00000430', - "aelig;": '\U000000E6', - "af;": '\U00002061', - "afr;": '\U0001D51E', - "agrave;": '\U000000E0', - "alefsym;": '\U00002135', - "aleph;": '\U00002135', - "alpha;": '\U000003B1', - "amacr;": '\U00000101', - "amalg;": '\U00002A3F', - "amp;": '\U00000026', - "and;": '\U00002227', - "andand;": '\U00002A55', - "andd;": '\U00002A5C', - "andslope;": '\U00002A58', - "andv;": '\U00002A5A', - "ang;": '\U00002220', - "ange;": '\U000029A4', - "angle;": '\U00002220', - "angmsd;": '\U00002221', - "angmsdaa;": '\U000029A8', - "angmsdab;": '\U000029A9', - "angmsdac;": '\U000029AA', - "angmsdad;": '\U000029AB', - "angmsdae;": '\U000029AC', - "angmsdaf;": '\U000029AD', - "angmsdag;": '\U000029AE', - "angmsdah;": '\U000029AF', - "angrt;": '\U0000221F', - "angrtvb;": '\U000022BE', - "angrtvbd;": '\U0000299D', - "angsph;": '\U00002222', - "angst;": '\U000000C5', - "angzarr;": '\U0000237C', - "aogon;": '\U00000105', - "aopf;": '\U0001D552', - "ap;": '\U00002248', - "apE;": '\U00002A70', - "apacir;": '\U00002A6F', - "ape;": '\U0000224A', - "apid;": '\U0000224B', - "apos;": '\U00000027', - "approx;": '\U00002248', - "approxeq;": '\U0000224A', - "aring;": '\U000000E5', - "ascr;": '\U0001D4B6', - "ast;": '\U0000002A', - "asymp;": '\U00002248', - "asympeq;": '\U0000224D', - "atilde;": '\U000000E3', - "auml;": '\U000000E4', - "awconint;": '\U00002233', - "awint;": '\U00002A11', - "bNot;": '\U00002AED', - "backcong;": '\U0000224C', - "backepsilon;": '\U000003F6', - "backprime;": '\U00002035', - "backsim;": '\U0000223D', - "backsimeq;": '\U000022CD', - "barvee;": '\U000022BD', - "barwed;": '\U00002305', - "barwedge;": '\U00002305', - "bbrk;": '\U000023B5', - "bbrktbrk;": '\U000023B6', - "bcong;": '\U0000224C', - "bcy;": '\U00000431', - "bdquo;": '\U0000201E', - "becaus;": '\U00002235', - "because;": '\U00002235', - "bemptyv;": '\U000029B0', - "bepsi;": '\U000003F6', - "bernou;": '\U0000212C', - "beta;": '\U000003B2', - "beth;": '\U00002136', - "between;": '\U0000226C', - "bfr;": '\U0001D51F', - "bigcap;": '\U000022C2', - "bigcirc;": '\U000025EF', - "bigcup;": '\U000022C3', - "bigodot;": '\U00002A00', - "bigoplus;": '\U00002A01', - "bigotimes;": '\U00002A02', - "bigsqcup;": '\U00002A06', - "bigstar;": '\U00002605', - "bigtriangledown;": '\U000025BD', - "bigtriangleup;": '\U000025B3', - "biguplus;": '\U00002A04', - "bigvee;": '\U000022C1', - "bigwedge;": '\U000022C0', - "bkarow;": '\U0000290D', - "blacklozenge;": '\U000029EB', - "blacksquare;": '\U000025AA', - "blacktriangle;": '\U000025B4', - "blacktriangledown;": '\U000025BE', - "blacktriangleleft;": '\U000025C2', - "blacktriangleright;": '\U000025B8', - "blank;": '\U00002423', - "blk12;": '\U00002592', - "blk14;": '\U00002591', - "blk34;": '\U00002593', - "block;": '\U00002588', - "bnot;": '\U00002310', - "bopf;": '\U0001D553', - "bot;": '\U000022A5', - "bottom;": '\U000022A5', - "bowtie;": '\U000022C8', - "boxDL;": '\U00002557', - "boxDR;": '\U00002554', - "boxDl;": '\U00002556', - "boxDr;": '\U00002553', - "boxH;": '\U00002550', - "boxHD;": '\U00002566', - "boxHU;": '\U00002569', - "boxHd;": '\U00002564', - "boxHu;": '\U00002567', - "boxUL;": '\U0000255D', - "boxUR;": '\U0000255A', - "boxUl;": '\U0000255C', - "boxUr;": '\U00002559', - "boxV;": '\U00002551', - "boxVH;": '\U0000256C', - "boxVL;": '\U00002563', - "boxVR;": '\U00002560', - "boxVh;": '\U0000256B', - "boxVl;": '\U00002562', - "boxVr;": '\U0000255F', - "boxbox;": '\U000029C9', - "boxdL;": '\U00002555', - "boxdR;": '\U00002552', - "boxdl;": '\U00002510', - "boxdr;": '\U0000250C', - "boxh;": '\U00002500', - "boxhD;": '\U00002565', - "boxhU;": '\U00002568', - "boxhd;": '\U0000252C', - "boxhu;": '\U00002534', - "boxminus;": '\U0000229F', - "boxplus;": '\U0000229E', - "boxtimes;": '\U000022A0', - "boxuL;": '\U0000255B', - "boxuR;": '\U00002558', - "boxul;": '\U00002518', - "boxur;": '\U00002514', - "boxv;": '\U00002502', - "boxvH;": '\U0000256A', - "boxvL;": '\U00002561', - "boxvR;": '\U0000255E', - "boxvh;": '\U0000253C', - "boxvl;": '\U00002524', - "boxvr;": '\U0000251C', - "bprime;": '\U00002035', - "breve;": '\U000002D8', - "brvbar;": '\U000000A6', - "bscr;": '\U0001D4B7', - "bsemi;": '\U0000204F', - "bsim;": '\U0000223D', - "bsime;": '\U000022CD', - "bsol;": '\U0000005C', - "bsolb;": '\U000029C5', - "bsolhsub;": '\U000027C8', - "bull;": '\U00002022', - "bullet;": '\U00002022', - "bump;": '\U0000224E', - "bumpE;": '\U00002AAE', - "bumpe;": '\U0000224F', - "bumpeq;": '\U0000224F', - "cacute;": '\U00000107', - "cap;": '\U00002229', - "capand;": '\U00002A44', - "capbrcup;": '\U00002A49', - "capcap;": '\U00002A4B', - "capcup;": '\U00002A47', - "capdot;": '\U00002A40', - "caret;": '\U00002041', - "caron;": '\U000002C7', - "ccaps;": '\U00002A4D', - "ccaron;": '\U0000010D', - "ccedil;": '\U000000E7', - "ccirc;": '\U00000109', - "ccups;": '\U00002A4C', - "ccupssm;": '\U00002A50', - "cdot;": '\U0000010B', - "cedil;": '\U000000B8', - "cemptyv;": '\U000029B2', - "cent;": '\U000000A2', - "centerdot;": '\U000000B7', - "cfr;": '\U0001D520', - "chcy;": '\U00000447', - "check;": '\U00002713', - "checkmark;": '\U00002713', - "chi;": '\U000003C7', - "cir;": '\U000025CB', - "cirE;": '\U000029C3', - "circ;": '\U000002C6', - "circeq;": '\U00002257', - "circlearrowleft;": '\U000021BA', - "circlearrowright;": '\U000021BB', - "circledR;": '\U000000AE', - "circledS;": '\U000024C8', - "circledast;": '\U0000229B', - "circledcirc;": '\U0000229A', - "circleddash;": '\U0000229D', - "cire;": '\U00002257', - "cirfnint;": '\U00002A10', - "cirmid;": '\U00002AEF', - "cirscir;": '\U000029C2', - "clubs;": '\U00002663', - "clubsuit;": '\U00002663', - "colon;": '\U0000003A', - "colone;": '\U00002254', - "coloneq;": '\U00002254', - "comma;": '\U0000002C', - "commat;": '\U00000040', - "comp;": '\U00002201', - "compfn;": '\U00002218', - "complement;": '\U00002201', - "complexes;": '\U00002102', - "cong;": '\U00002245', - "congdot;": '\U00002A6D', - "conint;": '\U0000222E', - "copf;": '\U0001D554', - "coprod;": '\U00002210', - "copy;": '\U000000A9', - "copysr;": '\U00002117', - "crarr;": '\U000021B5', - "cross;": '\U00002717', - "cscr;": '\U0001D4B8', - "csub;": '\U00002ACF', - "csube;": '\U00002AD1', - "csup;": '\U00002AD0', - "csupe;": '\U00002AD2', - "ctdot;": '\U000022EF', - "cudarrl;": '\U00002938', - "cudarrr;": '\U00002935', - "cuepr;": '\U000022DE', - "cuesc;": '\U000022DF', - "cularr;": '\U000021B6', - "cularrp;": '\U0000293D', - "cup;": '\U0000222A', - "cupbrcap;": '\U00002A48', - "cupcap;": '\U00002A46', - "cupcup;": '\U00002A4A', - "cupdot;": '\U0000228D', - "cupor;": '\U00002A45', - "curarr;": '\U000021B7', - "curarrm;": '\U0000293C', - "curlyeqprec;": '\U000022DE', - "curlyeqsucc;": '\U000022DF', - "curlyvee;": '\U000022CE', - "curlywedge;": '\U000022CF', - "curren;": '\U000000A4', - "curvearrowleft;": '\U000021B6', - "curvearrowright;": '\U000021B7', - "cuvee;": '\U000022CE', - "cuwed;": '\U000022CF', - "cwconint;": '\U00002232', - "cwint;": '\U00002231', - "cylcty;": '\U0000232D', - "dArr;": '\U000021D3', - "dHar;": '\U00002965', - "dagger;": '\U00002020', - "daleth;": '\U00002138', - "darr;": '\U00002193', - "dash;": '\U00002010', - "dashv;": '\U000022A3', - "dbkarow;": '\U0000290F', - "dblac;": '\U000002DD', - "dcaron;": '\U0000010F', - "dcy;": '\U00000434', - "dd;": '\U00002146', - "ddagger;": '\U00002021', - "ddarr;": '\U000021CA', - "ddotseq;": '\U00002A77', - "deg;": '\U000000B0', - "delta;": '\U000003B4', - "demptyv;": '\U000029B1', - "dfisht;": '\U0000297F', - "dfr;": '\U0001D521', - "dharl;": '\U000021C3', - "dharr;": '\U000021C2', - "diam;": '\U000022C4', - "diamond;": '\U000022C4', - "diamondsuit;": '\U00002666', - "diams;": '\U00002666', - "die;": '\U000000A8', - "digamma;": '\U000003DD', - "disin;": '\U000022F2', - "div;": '\U000000F7', - "divide;": '\U000000F7', - "divideontimes;": '\U000022C7', - "divonx;": '\U000022C7', - "djcy;": '\U00000452', - "dlcorn;": '\U0000231E', - "dlcrop;": '\U0000230D', - "dollar;": '\U00000024', - "dopf;": '\U0001D555', - "dot;": '\U000002D9', - "doteq;": '\U00002250', - "doteqdot;": '\U00002251', - "dotminus;": '\U00002238', - "dotplus;": '\U00002214', - "dotsquare;": '\U000022A1', - "doublebarwedge;": '\U00002306', - "downarrow;": '\U00002193', - "downdownarrows;": '\U000021CA', - "downharpoonleft;": '\U000021C3', - "downharpoonright;": '\U000021C2', - "drbkarow;": '\U00002910', - "drcorn;": '\U0000231F', - "drcrop;": '\U0000230C', - "dscr;": '\U0001D4B9', - "dscy;": '\U00000455', - "dsol;": '\U000029F6', - "dstrok;": '\U00000111', - "dtdot;": '\U000022F1', - "dtri;": '\U000025BF', - "dtrif;": '\U000025BE', - "duarr;": '\U000021F5', - "duhar;": '\U0000296F', - "dwangle;": '\U000029A6', - "dzcy;": '\U0000045F', - "dzigrarr;": '\U000027FF', - "eDDot;": '\U00002A77', - "eDot;": '\U00002251', - "eacute;": '\U000000E9', - "easter;": '\U00002A6E', - "ecaron;": '\U0000011B', - "ecir;": '\U00002256', - "ecirc;": '\U000000EA', - "ecolon;": '\U00002255', - "ecy;": '\U0000044D', - "edot;": '\U00000117', - "ee;": '\U00002147', - "efDot;": '\U00002252', - "efr;": '\U0001D522', - "eg;": '\U00002A9A', - "egrave;": '\U000000E8', - "egs;": '\U00002A96', - "egsdot;": '\U00002A98', - "el;": '\U00002A99', - "elinters;": '\U000023E7', - "ell;": '\U00002113', - "els;": '\U00002A95', - "elsdot;": '\U00002A97', - "emacr;": '\U00000113', - "empty;": '\U00002205', - "emptyset;": '\U00002205', - "emptyv;": '\U00002205', - "emsp;": '\U00002003', - "emsp13;": '\U00002004', - "emsp14;": '\U00002005', - "eng;": '\U0000014B', - "ensp;": '\U00002002', - "eogon;": '\U00000119', - "eopf;": '\U0001D556', - "epar;": '\U000022D5', - "eparsl;": '\U000029E3', - "eplus;": '\U00002A71', - "epsi;": '\U000003B5', - "epsilon;": '\U000003B5', - "epsiv;": '\U000003F5', - "eqcirc;": '\U00002256', - "eqcolon;": '\U00002255', - "eqsim;": '\U00002242', - "eqslantgtr;": '\U00002A96', - "eqslantless;": '\U00002A95', - "equals;": '\U0000003D', - "equest;": '\U0000225F', - "equiv;": '\U00002261', - "equivDD;": '\U00002A78', - "eqvparsl;": '\U000029E5', - "erDot;": '\U00002253', - "erarr;": '\U00002971', - "escr;": '\U0000212F', - "esdot;": '\U00002250', - "esim;": '\U00002242', - "eta;": '\U000003B7', - "eth;": '\U000000F0', - "euml;": '\U000000EB', - "euro;": '\U000020AC', - "excl;": '\U00000021', - "exist;": '\U00002203', - "expectation;": '\U00002130', - "exponentiale;": '\U00002147', - "fallingdotseq;": '\U00002252', - "fcy;": '\U00000444', - "female;": '\U00002640', - "ffilig;": '\U0000FB03', - "fflig;": '\U0000FB00', - "ffllig;": '\U0000FB04', - "ffr;": '\U0001D523', - "filig;": '\U0000FB01', - "flat;": '\U0000266D', - "fllig;": '\U0000FB02', - "fltns;": '\U000025B1', - "fnof;": '\U00000192', - "fopf;": '\U0001D557', - "forall;": '\U00002200', - "fork;": '\U000022D4', - "forkv;": '\U00002AD9', - "fpartint;": '\U00002A0D', - "frac12;": '\U000000BD', - "frac13;": '\U00002153', - "frac14;": '\U000000BC', - "frac15;": '\U00002155', - "frac16;": '\U00002159', - "frac18;": '\U0000215B', - "frac23;": '\U00002154', - "frac25;": '\U00002156', - "frac34;": '\U000000BE', - "frac35;": '\U00002157', - "frac38;": '\U0000215C', - "frac45;": '\U00002158', - "frac56;": '\U0000215A', - "frac58;": '\U0000215D', - "frac78;": '\U0000215E', - "frasl;": '\U00002044', - "frown;": '\U00002322', - "fscr;": '\U0001D4BB', - "gE;": '\U00002267', - "gEl;": '\U00002A8C', - "gacute;": '\U000001F5', - "gamma;": '\U000003B3', - "gammad;": '\U000003DD', - "gap;": '\U00002A86', - "gbreve;": '\U0000011F', - "gcirc;": '\U0000011D', - "gcy;": '\U00000433', - "gdot;": '\U00000121', - "ge;": '\U00002265', - "gel;": '\U000022DB', - "geq;": '\U00002265', - "geqq;": '\U00002267', - "geqslant;": '\U00002A7E', - "ges;": '\U00002A7E', - "gescc;": '\U00002AA9', - "gesdot;": '\U00002A80', - "gesdoto;": '\U00002A82', - "gesdotol;": '\U00002A84', - "gesles;": '\U00002A94', - "gfr;": '\U0001D524', - "gg;": '\U0000226B', - "ggg;": '\U000022D9', - "gimel;": '\U00002137', - "gjcy;": '\U00000453', - "gl;": '\U00002277', - "glE;": '\U00002A92', - "gla;": '\U00002AA5', - "glj;": '\U00002AA4', - "gnE;": '\U00002269', - "gnap;": '\U00002A8A', - "gnapprox;": '\U00002A8A', - "gne;": '\U00002A88', - "gneq;": '\U00002A88', - "gneqq;": '\U00002269', - "gnsim;": '\U000022E7', - "gopf;": '\U0001D558', - "grave;": '\U00000060', - "gscr;": '\U0000210A', - "gsim;": '\U00002273', - "gsime;": '\U00002A8E', - "gsiml;": '\U00002A90', - "gt;": '\U0000003E', - "gtcc;": '\U00002AA7', - "gtcir;": '\U00002A7A', - "gtdot;": '\U000022D7', - "gtlPar;": '\U00002995', - "gtquest;": '\U00002A7C', - "gtrapprox;": '\U00002A86', - "gtrarr;": '\U00002978', - "gtrdot;": '\U000022D7', - "gtreqless;": '\U000022DB', - "gtreqqless;": '\U00002A8C', - "gtrless;": '\U00002277', - "gtrsim;": '\U00002273', - "hArr;": '\U000021D4', - "hairsp;": '\U0000200A', - "half;": '\U000000BD', - "hamilt;": '\U0000210B', - "hardcy;": '\U0000044A', - "harr;": '\U00002194', - "harrcir;": '\U00002948', - "harrw;": '\U000021AD', - "hbar;": '\U0000210F', - "hcirc;": '\U00000125', - "hearts;": '\U00002665', - "heartsuit;": '\U00002665', - "hellip;": '\U00002026', - "hercon;": '\U000022B9', - "hfr;": '\U0001D525', - "hksearow;": '\U00002925', - "hkswarow;": '\U00002926', - "hoarr;": '\U000021FF', - "homtht;": '\U0000223B', - "hookleftarrow;": '\U000021A9', - "hookrightarrow;": '\U000021AA', - "hopf;": '\U0001D559', - "horbar;": '\U00002015', - "hscr;": '\U0001D4BD', - "hslash;": '\U0000210F', - "hstrok;": '\U00000127', - "hybull;": '\U00002043', - "hyphen;": '\U00002010', - "iacute;": '\U000000ED', - "ic;": '\U00002063', - "icirc;": '\U000000EE', - "icy;": '\U00000438', - "iecy;": '\U00000435', - "iexcl;": '\U000000A1', - "iff;": '\U000021D4', - "ifr;": '\U0001D526', - "igrave;": '\U000000EC', - "ii;": '\U00002148', - "iiiint;": '\U00002A0C', - "iiint;": '\U0000222D', - "iinfin;": '\U000029DC', - "iiota;": '\U00002129', - "ijlig;": '\U00000133', - "imacr;": '\U0000012B', - "image;": '\U00002111', - "imagline;": '\U00002110', - "imagpart;": '\U00002111', - "imath;": '\U00000131', - "imof;": '\U000022B7', - "imped;": '\U000001B5', - "in;": '\U00002208', - "incare;": '\U00002105', - "infin;": '\U0000221E', - "infintie;": '\U000029DD', - "inodot;": '\U00000131', - "int;": '\U0000222B', - "intcal;": '\U000022BA', - "integers;": '\U00002124', - "intercal;": '\U000022BA', - "intlarhk;": '\U00002A17', - "intprod;": '\U00002A3C', - "iocy;": '\U00000451', - "iogon;": '\U0000012F', - "iopf;": '\U0001D55A', - "iota;": '\U000003B9', - "iprod;": '\U00002A3C', - "iquest;": '\U000000BF', - "iscr;": '\U0001D4BE', - "isin;": '\U00002208', - "isinE;": '\U000022F9', - "isindot;": '\U000022F5', - "isins;": '\U000022F4', - "isinsv;": '\U000022F3', - "isinv;": '\U00002208', - "it;": '\U00002062', - "itilde;": '\U00000129', - "iukcy;": '\U00000456', - "iuml;": '\U000000EF', - "jcirc;": '\U00000135', - "jcy;": '\U00000439', - "jfr;": '\U0001D527', - "jmath;": '\U00000237', - "jopf;": '\U0001D55B', - "jscr;": '\U0001D4BF', - "jsercy;": '\U00000458', - "jukcy;": '\U00000454', - "kappa;": '\U000003BA', - "kappav;": '\U000003F0', - "kcedil;": '\U00000137', - "kcy;": '\U0000043A', - "kfr;": '\U0001D528', - "kgreen;": '\U00000138', - "khcy;": '\U00000445', - "kjcy;": '\U0000045C', - "kopf;": '\U0001D55C', - "kscr;": '\U0001D4C0', - "lAarr;": '\U000021DA', - "lArr;": '\U000021D0', - "lAtail;": '\U0000291B', - "lBarr;": '\U0000290E', - "lE;": '\U00002266', - "lEg;": '\U00002A8B', - "lHar;": '\U00002962', - "lacute;": '\U0000013A', - "laemptyv;": '\U000029B4', - "lagran;": '\U00002112', - "lambda;": '\U000003BB', - "lang;": '\U000027E8', - "langd;": '\U00002991', - "langle;": '\U000027E8', - "lap;": '\U00002A85', - "laquo;": '\U000000AB', - "larr;": '\U00002190', - "larrb;": '\U000021E4', - "larrbfs;": '\U0000291F', - "larrfs;": '\U0000291D', - "larrhk;": '\U000021A9', - "larrlp;": '\U000021AB', - "larrpl;": '\U00002939', - "larrsim;": '\U00002973', - "larrtl;": '\U000021A2', - "lat;": '\U00002AAB', - "latail;": '\U00002919', - "late;": '\U00002AAD', - "lbarr;": '\U0000290C', - "lbbrk;": '\U00002772', - "lbrace;": '\U0000007B', - "lbrack;": '\U0000005B', - "lbrke;": '\U0000298B', - "lbrksld;": '\U0000298F', - "lbrkslu;": '\U0000298D', - "lcaron;": '\U0000013E', - "lcedil;": '\U0000013C', - "lceil;": '\U00002308', - "lcub;": '\U0000007B', - "lcy;": '\U0000043B', - "ldca;": '\U00002936', - "ldquo;": '\U0000201C', - "ldquor;": '\U0000201E', - "ldrdhar;": '\U00002967', - "ldrushar;": '\U0000294B', - "ldsh;": '\U000021B2', - "le;": '\U00002264', - "leftarrow;": '\U00002190', - "leftarrowtail;": '\U000021A2', - "leftharpoondown;": '\U000021BD', - "leftharpoonup;": '\U000021BC', - "leftleftarrows;": '\U000021C7', - "leftrightarrow;": '\U00002194', - "leftrightarrows;": '\U000021C6', - "leftrightharpoons;": '\U000021CB', - "leftrightsquigarrow;": '\U000021AD', - "leftthreetimes;": '\U000022CB', - "leg;": '\U000022DA', - "leq;": '\U00002264', - "leqq;": '\U00002266', - "leqslant;": '\U00002A7D', - "les;": '\U00002A7D', - "lescc;": '\U00002AA8', - "lesdot;": '\U00002A7F', - "lesdoto;": '\U00002A81', - "lesdotor;": '\U00002A83', - "lesges;": '\U00002A93', - "lessapprox;": '\U00002A85', - "lessdot;": '\U000022D6', - "lesseqgtr;": '\U000022DA', - "lesseqqgtr;": '\U00002A8B', - "lessgtr;": '\U00002276', - "lesssim;": '\U00002272', - "lfisht;": '\U0000297C', - "lfloor;": '\U0000230A', - "lfr;": '\U0001D529', - "lg;": '\U00002276', - "lgE;": '\U00002A91', - "lhard;": '\U000021BD', - "lharu;": '\U000021BC', - "lharul;": '\U0000296A', - "lhblk;": '\U00002584', - "ljcy;": '\U00000459', - "ll;": '\U0000226A', - "llarr;": '\U000021C7', - "llcorner;": '\U0000231E', - "llhard;": '\U0000296B', - "lltri;": '\U000025FA', - "lmidot;": '\U00000140', - "lmoust;": '\U000023B0', - "lmoustache;": '\U000023B0', - "lnE;": '\U00002268', - "lnap;": '\U00002A89', - "lnapprox;": '\U00002A89', - "lne;": '\U00002A87', - "lneq;": '\U00002A87', - "lneqq;": '\U00002268', - "lnsim;": '\U000022E6', - "loang;": '\U000027EC', - "loarr;": '\U000021FD', - "lobrk;": '\U000027E6', - "longleftarrow;": '\U000027F5', - "longleftrightarrow;": '\U000027F7', - "longmapsto;": '\U000027FC', - "longrightarrow;": '\U000027F6', - "looparrowleft;": '\U000021AB', - "looparrowright;": '\U000021AC', - "lopar;": '\U00002985', - "lopf;": '\U0001D55D', - "loplus;": '\U00002A2D', - "lotimes;": '\U00002A34', - "lowast;": '\U00002217', - "lowbar;": '\U0000005F', - "loz;": '\U000025CA', - "lozenge;": '\U000025CA', - "lozf;": '\U000029EB', - "lpar;": '\U00000028', - "lparlt;": '\U00002993', - "lrarr;": '\U000021C6', - "lrcorner;": '\U0000231F', - "lrhar;": '\U000021CB', - "lrhard;": '\U0000296D', - "lrm;": '\U0000200E', - "lrtri;": '\U000022BF', - "lsaquo;": '\U00002039', - "lscr;": '\U0001D4C1', - "lsh;": '\U000021B0', - "lsim;": '\U00002272', - "lsime;": '\U00002A8D', - "lsimg;": '\U00002A8F', - "lsqb;": '\U0000005B', - "lsquo;": '\U00002018', - "lsquor;": '\U0000201A', - "lstrok;": '\U00000142', - "lt;": '\U0000003C', - "ltcc;": '\U00002AA6', - "ltcir;": '\U00002A79', - "ltdot;": '\U000022D6', - "lthree;": '\U000022CB', - "ltimes;": '\U000022C9', - "ltlarr;": '\U00002976', - "ltquest;": '\U00002A7B', - "ltrPar;": '\U00002996', - "ltri;": '\U000025C3', - "ltrie;": '\U000022B4', - "ltrif;": '\U000025C2', - "lurdshar;": '\U0000294A', - "luruhar;": '\U00002966', - "mDDot;": '\U0000223A', - "macr;": '\U000000AF', - "male;": '\U00002642', - "malt;": '\U00002720', - "maltese;": '\U00002720', - "map;": '\U000021A6', - "mapsto;": '\U000021A6', - "mapstodown;": '\U000021A7', - "mapstoleft;": '\U000021A4', - "mapstoup;": '\U000021A5', - "marker;": '\U000025AE', - "mcomma;": '\U00002A29', - "mcy;": '\U0000043C', - "mdash;": '\U00002014', - "measuredangle;": '\U00002221', - "mfr;": '\U0001D52A', - "mho;": '\U00002127', - "micro;": '\U000000B5', - "mid;": '\U00002223', - "midast;": '\U0000002A', - "midcir;": '\U00002AF0', - "middot;": '\U000000B7', - "minus;": '\U00002212', - "minusb;": '\U0000229F', - "minusd;": '\U00002238', - "minusdu;": '\U00002A2A', - "mlcp;": '\U00002ADB', - "mldr;": '\U00002026', - "mnplus;": '\U00002213', - "models;": '\U000022A7', - "mopf;": '\U0001D55E', - "mp;": '\U00002213', - "mscr;": '\U0001D4C2', - "mstpos;": '\U0000223E', - "mu;": '\U000003BC', - "multimap;": '\U000022B8', - "mumap;": '\U000022B8', - "nLeftarrow;": '\U000021CD', - "nLeftrightarrow;": '\U000021CE', - "nRightarrow;": '\U000021CF', - "nVDash;": '\U000022AF', - "nVdash;": '\U000022AE', - "nabla;": '\U00002207', - "nacute;": '\U00000144', - "nap;": '\U00002249', - "napos;": '\U00000149', - "napprox;": '\U00002249', - "natur;": '\U0000266E', - "natural;": '\U0000266E', - "naturals;": '\U00002115', - "nbsp;": '\U000000A0', - "ncap;": '\U00002A43', - "ncaron;": '\U00000148', - "ncedil;": '\U00000146', - "ncong;": '\U00002247', - "ncup;": '\U00002A42', - "ncy;": '\U0000043D', - "ndash;": '\U00002013', - "ne;": '\U00002260', - "neArr;": '\U000021D7', - "nearhk;": '\U00002924', - "nearr;": '\U00002197', - "nearrow;": '\U00002197', - "nequiv;": '\U00002262', - "nesear;": '\U00002928', - "nexist;": '\U00002204', - "nexists;": '\U00002204', - "nfr;": '\U0001D52B', - "nge;": '\U00002271', - "ngeq;": '\U00002271', - "ngsim;": '\U00002275', - "ngt;": '\U0000226F', - "ngtr;": '\U0000226F', - "nhArr;": '\U000021CE', - "nharr;": '\U000021AE', - "nhpar;": '\U00002AF2', - "ni;": '\U0000220B', - "nis;": '\U000022FC', - "nisd;": '\U000022FA', - "niv;": '\U0000220B', - "njcy;": '\U0000045A', - "nlArr;": '\U000021CD', - "nlarr;": '\U0000219A', - "nldr;": '\U00002025', - "nle;": '\U00002270', - "nleftarrow;": '\U0000219A', - "nleftrightarrow;": '\U000021AE', - "nleq;": '\U00002270', - "nless;": '\U0000226E', - "nlsim;": '\U00002274', - "nlt;": '\U0000226E', - "nltri;": '\U000022EA', - "nltrie;": '\U000022EC', - "nmid;": '\U00002224', - "nopf;": '\U0001D55F', - "not;": '\U000000AC', - "notin;": '\U00002209', - "notinva;": '\U00002209', - "notinvb;": '\U000022F7', - "notinvc;": '\U000022F6', - "notni;": '\U0000220C', - "notniva;": '\U0000220C', - "notnivb;": '\U000022FE', - "notnivc;": '\U000022FD', - "npar;": '\U00002226', - "nparallel;": '\U00002226', - "npolint;": '\U00002A14', - "npr;": '\U00002280', - "nprcue;": '\U000022E0', - "nprec;": '\U00002280', - "nrArr;": '\U000021CF', - "nrarr;": '\U0000219B', - "nrightarrow;": '\U0000219B', - "nrtri;": '\U000022EB', - "nrtrie;": '\U000022ED', - "nsc;": '\U00002281', - "nsccue;": '\U000022E1', - "nscr;": '\U0001D4C3', - "nshortmid;": '\U00002224', - "nshortparallel;": '\U00002226', - "nsim;": '\U00002241', - "nsime;": '\U00002244', - "nsimeq;": '\U00002244', - "nsmid;": '\U00002224', - "nspar;": '\U00002226', - "nsqsube;": '\U000022E2', - "nsqsupe;": '\U000022E3', - "nsub;": '\U00002284', - "nsube;": '\U00002288', - "nsubseteq;": '\U00002288', - "nsucc;": '\U00002281', - "nsup;": '\U00002285', - "nsupe;": '\U00002289', - "nsupseteq;": '\U00002289', - "ntgl;": '\U00002279', - "ntilde;": '\U000000F1', - "ntlg;": '\U00002278', - "ntriangleleft;": '\U000022EA', - "ntrianglelefteq;": '\U000022EC', - "ntriangleright;": '\U000022EB', - "ntrianglerighteq;": '\U000022ED', - "nu;": '\U000003BD', - "num;": '\U00000023', - "numero;": '\U00002116', - "numsp;": '\U00002007', - "nvDash;": '\U000022AD', - "nvHarr;": '\U00002904', - "nvdash;": '\U000022AC', - "nvinfin;": '\U000029DE', - "nvlArr;": '\U00002902', - "nvrArr;": '\U00002903', - "nwArr;": '\U000021D6', - "nwarhk;": '\U00002923', - "nwarr;": '\U00002196', - "nwarrow;": '\U00002196', - "nwnear;": '\U00002927', - "oS;": '\U000024C8', - "oacute;": '\U000000F3', - "oast;": '\U0000229B', - "ocir;": '\U0000229A', - "ocirc;": '\U000000F4', - "ocy;": '\U0000043E', - "odash;": '\U0000229D', - "odblac;": '\U00000151', - "odiv;": '\U00002A38', - "odot;": '\U00002299', - "odsold;": '\U000029BC', - "oelig;": '\U00000153', - "ofcir;": '\U000029BF', - "ofr;": '\U0001D52C', - "ogon;": '\U000002DB', - "ograve;": '\U000000F2', - "ogt;": '\U000029C1', - "ohbar;": '\U000029B5', - "ohm;": '\U000003A9', - "oint;": '\U0000222E', - "olarr;": '\U000021BA', - "olcir;": '\U000029BE', - "olcross;": '\U000029BB', - "oline;": '\U0000203E', - "olt;": '\U000029C0', - "omacr;": '\U0000014D', - "omega;": '\U000003C9', - "omicron;": '\U000003BF', - "omid;": '\U000029B6', - "ominus;": '\U00002296', - "oopf;": '\U0001D560', - "opar;": '\U000029B7', - "operp;": '\U000029B9', - "oplus;": '\U00002295', - "or;": '\U00002228', - "orarr;": '\U000021BB', - "ord;": '\U00002A5D', - "order;": '\U00002134', - "orderof;": '\U00002134', - "ordf;": '\U000000AA', - "ordm;": '\U000000BA', - "origof;": '\U000022B6', - "oror;": '\U00002A56', - "orslope;": '\U00002A57', - "orv;": '\U00002A5B', - "oscr;": '\U00002134', - "oslash;": '\U000000F8', - "osol;": '\U00002298', - "otilde;": '\U000000F5', - "otimes;": '\U00002297', - "otimesas;": '\U00002A36', - "ouml;": '\U000000F6', - "ovbar;": '\U0000233D', - "par;": '\U00002225', - "para;": '\U000000B6', - "parallel;": '\U00002225', - "parsim;": '\U00002AF3', - "parsl;": '\U00002AFD', - "part;": '\U00002202', - "pcy;": '\U0000043F', - "percnt;": '\U00000025', - "period;": '\U0000002E', - "permil;": '\U00002030', - "perp;": '\U000022A5', - "pertenk;": '\U00002031', - "pfr;": '\U0001D52D', - "phi;": '\U000003C6', - "phiv;": '\U000003D5', - "phmmat;": '\U00002133', - "phone;": '\U0000260E', - "pi;": '\U000003C0', - "pitchfork;": '\U000022D4', - "piv;": '\U000003D6', - "planck;": '\U0000210F', - "planckh;": '\U0000210E', - "plankv;": '\U0000210F', - "plus;": '\U0000002B', - "plusacir;": '\U00002A23', - "plusb;": '\U0000229E', - "pluscir;": '\U00002A22', - "plusdo;": '\U00002214', - "plusdu;": '\U00002A25', - "pluse;": '\U00002A72', - "plusmn;": '\U000000B1', - "plussim;": '\U00002A26', - "plustwo;": '\U00002A27', - "pm;": '\U000000B1', - "pointint;": '\U00002A15', - "popf;": '\U0001D561', - "pound;": '\U000000A3', - "pr;": '\U0000227A', - "prE;": '\U00002AB3', - "prap;": '\U00002AB7', - "prcue;": '\U0000227C', - "pre;": '\U00002AAF', - "prec;": '\U0000227A', - "precapprox;": '\U00002AB7', - "preccurlyeq;": '\U0000227C', - "preceq;": '\U00002AAF', - "precnapprox;": '\U00002AB9', - "precneqq;": '\U00002AB5', - "precnsim;": '\U000022E8', - "precsim;": '\U0000227E', - "prime;": '\U00002032', - "primes;": '\U00002119', - "prnE;": '\U00002AB5', - "prnap;": '\U00002AB9', - "prnsim;": '\U000022E8', - "prod;": '\U0000220F', - "profalar;": '\U0000232E', - "profline;": '\U00002312', - "profsurf;": '\U00002313', - "prop;": '\U0000221D', - "propto;": '\U0000221D', - "prsim;": '\U0000227E', - "prurel;": '\U000022B0', - "pscr;": '\U0001D4C5', - "psi;": '\U000003C8', - "puncsp;": '\U00002008', - "qfr;": '\U0001D52E', - "qint;": '\U00002A0C', - "qopf;": '\U0001D562', - "qprime;": '\U00002057', - "qscr;": '\U0001D4C6', - "quaternions;": '\U0000210D', - "quatint;": '\U00002A16', - "quest;": '\U0000003F', - "questeq;": '\U0000225F', - "quot;": '\U00000022', - "rAarr;": '\U000021DB', - "rArr;": '\U000021D2', - "rAtail;": '\U0000291C', - "rBarr;": '\U0000290F', - "rHar;": '\U00002964', - "racute;": '\U00000155', - "radic;": '\U0000221A', - "raemptyv;": '\U000029B3', - "rang;": '\U000027E9', - "rangd;": '\U00002992', - "range;": '\U000029A5', - "rangle;": '\U000027E9', - "raquo;": '\U000000BB', - "rarr;": '\U00002192', - "rarrap;": '\U00002975', - "rarrb;": '\U000021E5', - "rarrbfs;": '\U00002920', - "rarrc;": '\U00002933', - "rarrfs;": '\U0000291E', - "rarrhk;": '\U000021AA', - "rarrlp;": '\U000021AC', - "rarrpl;": '\U00002945', - "rarrsim;": '\U00002974', - "rarrtl;": '\U000021A3', - "rarrw;": '\U0000219D', - "ratail;": '\U0000291A', - "ratio;": '\U00002236', - "rationals;": '\U0000211A', - "rbarr;": '\U0000290D', - "rbbrk;": '\U00002773', - "rbrace;": '\U0000007D', - "rbrack;": '\U0000005D', - "rbrke;": '\U0000298C', - "rbrksld;": '\U0000298E', - "rbrkslu;": '\U00002990', - "rcaron;": '\U00000159', - "rcedil;": '\U00000157', - "rceil;": '\U00002309', - "rcub;": '\U0000007D', - "rcy;": '\U00000440', - "rdca;": '\U00002937', - "rdldhar;": '\U00002969', - "rdquo;": '\U0000201D', - "rdquor;": '\U0000201D', - "rdsh;": '\U000021B3', - "real;": '\U0000211C', - "realine;": '\U0000211B', - "realpart;": '\U0000211C', - "reals;": '\U0000211D', - "rect;": '\U000025AD', - "reg;": '\U000000AE', - "rfisht;": '\U0000297D', - "rfloor;": '\U0000230B', - "rfr;": '\U0001D52F', - "rhard;": '\U000021C1', - "rharu;": '\U000021C0', - "rharul;": '\U0000296C', - "rho;": '\U000003C1', - "rhov;": '\U000003F1', - "rightarrow;": '\U00002192', - "rightarrowtail;": '\U000021A3', - "rightharpoondown;": '\U000021C1', - "rightharpoonup;": '\U000021C0', - "rightleftarrows;": '\U000021C4', - "rightleftharpoons;": '\U000021CC', - "rightrightarrows;": '\U000021C9', - "rightsquigarrow;": '\U0000219D', - "rightthreetimes;": '\U000022CC', - "ring;": '\U000002DA', - "risingdotseq;": '\U00002253', - "rlarr;": '\U000021C4', - "rlhar;": '\U000021CC', - "rlm;": '\U0000200F', - "rmoust;": '\U000023B1', - "rmoustache;": '\U000023B1', - "rnmid;": '\U00002AEE', - "roang;": '\U000027ED', - "roarr;": '\U000021FE', - "robrk;": '\U000027E7', - "ropar;": '\U00002986', - "ropf;": '\U0001D563', - "roplus;": '\U00002A2E', - "rotimes;": '\U00002A35', - "rpar;": '\U00000029', - "rpargt;": '\U00002994', - "rppolint;": '\U00002A12', - "rrarr;": '\U000021C9', - "rsaquo;": '\U0000203A', - "rscr;": '\U0001D4C7', - "rsh;": '\U000021B1', - "rsqb;": '\U0000005D', - "rsquo;": '\U00002019', - "rsquor;": '\U00002019', - "rthree;": '\U000022CC', - "rtimes;": '\U000022CA', - "rtri;": '\U000025B9', - "rtrie;": '\U000022B5', - "rtrif;": '\U000025B8', - "rtriltri;": '\U000029CE', - "ruluhar;": '\U00002968', - "rx;": '\U0000211E', - "sacute;": '\U0000015B', - "sbquo;": '\U0000201A', - "sc;": '\U0000227B', - "scE;": '\U00002AB4', - "scap;": '\U00002AB8', - "scaron;": '\U00000161', - "sccue;": '\U0000227D', - "sce;": '\U00002AB0', - "scedil;": '\U0000015F', - "scirc;": '\U0000015D', - "scnE;": '\U00002AB6', - "scnap;": '\U00002ABA', - "scnsim;": '\U000022E9', - "scpolint;": '\U00002A13', - "scsim;": '\U0000227F', - "scy;": '\U00000441', - "sdot;": '\U000022C5', - "sdotb;": '\U000022A1', - "sdote;": '\U00002A66', - "seArr;": '\U000021D8', - "searhk;": '\U00002925', - "searr;": '\U00002198', - "searrow;": '\U00002198', - "sect;": '\U000000A7', - "semi;": '\U0000003B', - "seswar;": '\U00002929', - "setminus;": '\U00002216', - "setmn;": '\U00002216', - "sext;": '\U00002736', - "sfr;": '\U0001D530', - "sfrown;": '\U00002322', - "sharp;": '\U0000266F', - "shchcy;": '\U00000449', - "shcy;": '\U00000448', - "shortmid;": '\U00002223', - "shortparallel;": '\U00002225', - "shy;": '\U000000AD', - "sigma;": '\U000003C3', - "sigmaf;": '\U000003C2', - "sigmav;": '\U000003C2', - "sim;": '\U0000223C', - "simdot;": '\U00002A6A', - "sime;": '\U00002243', - "simeq;": '\U00002243', - "simg;": '\U00002A9E', - "simgE;": '\U00002AA0', - "siml;": '\U00002A9D', - "simlE;": '\U00002A9F', - "simne;": '\U00002246', - "simplus;": '\U00002A24', - "simrarr;": '\U00002972', - "slarr;": '\U00002190', - "smallsetminus;": '\U00002216', - "smashp;": '\U00002A33', - "smeparsl;": '\U000029E4', - "smid;": '\U00002223', - "smile;": '\U00002323', - "smt;": '\U00002AAA', - "smte;": '\U00002AAC', - "softcy;": '\U0000044C', - "sol;": '\U0000002F', - "solb;": '\U000029C4', - "solbar;": '\U0000233F', - "sopf;": '\U0001D564', - "spades;": '\U00002660', - "spadesuit;": '\U00002660', - "spar;": '\U00002225', - "sqcap;": '\U00002293', - "sqcup;": '\U00002294', - "sqsub;": '\U0000228F', - "sqsube;": '\U00002291', - "sqsubset;": '\U0000228F', - "sqsubseteq;": '\U00002291', - "sqsup;": '\U00002290', - "sqsupe;": '\U00002292', - "sqsupset;": '\U00002290', - "sqsupseteq;": '\U00002292', - "squ;": '\U000025A1', - "square;": '\U000025A1', - "squarf;": '\U000025AA', - "squf;": '\U000025AA', - "srarr;": '\U00002192', - "sscr;": '\U0001D4C8', - "ssetmn;": '\U00002216', - "ssmile;": '\U00002323', - "sstarf;": '\U000022C6', - "star;": '\U00002606', - "starf;": '\U00002605', - "straightepsilon;": '\U000003F5', - "straightphi;": '\U000003D5', - "strns;": '\U000000AF', - "sub;": '\U00002282', - "subE;": '\U00002AC5', - "subdot;": '\U00002ABD', - "sube;": '\U00002286', - "subedot;": '\U00002AC3', - "submult;": '\U00002AC1', - "subnE;": '\U00002ACB', - "subne;": '\U0000228A', - "subplus;": '\U00002ABF', - "subrarr;": '\U00002979', - "subset;": '\U00002282', - "subseteq;": '\U00002286', - "subseteqq;": '\U00002AC5', - "subsetneq;": '\U0000228A', - "subsetneqq;": '\U00002ACB', - "subsim;": '\U00002AC7', - "subsub;": '\U00002AD5', - "subsup;": '\U00002AD3', - "succ;": '\U0000227B', - "succapprox;": '\U00002AB8', - "succcurlyeq;": '\U0000227D', - "succeq;": '\U00002AB0', - "succnapprox;": '\U00002ABA', - "succneqq;": '\U00002AB6', - "succnsim;": '\U000022E9', - "succsim;": '\U0000227F', - "sum;": '\U00002211', - "sung;": '\U0000266A', - "sup;": '\U00002283', - "sup1;": '\U000000B9', - "sup2;": '\U000000B2', - "sup3;": '\U000000B3', - "supE;": '\U00002AC6', - "supdot;": '\U00002ABE', - "supdsub;": '\U00002AD8', - "supe;": '\U00002287', - "supedot;": '\U00002AC4', - "suphsol;": '\U000027C9', - "suphsub;": '\U00002AD7', - "suplarr;": '\U0000297B', - "supmult;": '\U00002AC2', - "supnE;": '\U00002ACC', - "supne;": '\U0000228B', - "supplus;": '\U00002AC0', - "supset;": '\U00002283', - "supseteq;": '\U00002287', - "supseteqq;": '\U00002AC6', - "supsetneq;": '\U0000228B', - "supsetneqq;": '\U00002ACC', - "supsim;": '\U00002AC8', - "supsub;": '\U00002AD4', - "supsup;": '\U00002AD6', - "swArr;": '\U000021D9', - "swarhk;": '\U00002926', - "swarr;": '\U00002199', - "swarrow;": '\U00002199', - "swnwar;": '\U0000292A', - "szlig;": '\U000000DF', - "target;": '\U00002316', - "tau;": '\U000003C4', - "tbrk;": '\U000023B4', - "tcaron;": '\U00000165', - "tcedil;": '\U00000163', - "tcy;": '\U00000442', - "tdot;": '\U000020DB', - "telrec;": '\U00002315', - "tfr;": '\U0001D531', - "there4;": '\U00002234', - "therefore;": '\U00002234', - "theta;": '\U000003B8', - "thetasym;": '\U000003D1', - "thetav;": '\U000003D1', - "thickapprox;": '\U00002248', - "thicksim;": '\U0000223C', - "thinsp;": '\U00002009', - "thkap;": '\U00002248', - "thksim;": '\U0000223C', - "thorn;": '\U000000FE', - "tilde;": '\U000002DC', - "times;": '\U000000D7', - "timesb;": '\U000022A0', - "timesbar;": '\U00002A31', - "timesd;": '\U00002A30', - "tint;": '\U0000222D', - "toea;": '\U00002928', - "top;": '\U000022A4', - "topbot;": '\U00002336', - "topcir;": '\U00002AF1', - "topf;": '\U0001D565', - "topfork;": '\U00002ADA', - "tosa;": '\U00002929', - "tprime;": '\U00002034', - "trade;": '\U00002122', - "triangle;": '\U000025B5', - "triangledown;": '\U000025BF', - "triangleleft;": '\U000025C3', - "trianglelefteq;": '\U000022B4', - "triangleq;": '\U0000225C', - "triangleright;": '\U000025B9', - "trianglerighteq;": '\U000022B5', - "tridot;": '\U000025EC', - "trie;": '\U0000225C', - "triminus;": '\U00002A3A', - "triplus;": '\U00002A39', - "trisb;": '\U000029CD', - "tritime;": '\U00002A3B', - "trpezium;": '\U000023E2', - "tscr;": '\U0001D4C9', - "tscy;": '\U00000446', - "tshcy;": '\U0000045B', - "tstrok;": '\U00000167', - "twixt;": '\U0000226C', - "twoheadleftarrow;": '\U0000219E', - "twoheadrightarrow;": '\U000021A0', - "uArr;": '\U000021D1', - "uHar;": '\U00002963', - "uacute;": '\U000000FA', - "uarr;": '\U00002191', - "ubrcy;": '\U0000045E', - "ubreve;": '\U0000016D', - "ucirc;": '\U000000FB', - "ucy;": '\U00000443', - "udarr;": '\U000021C5', - "udblac;": '\U00000171', - "udhar;": '\U0000296E', - "ufisht;": '\U0000297E', - "ufr;": '\U0001D532', - "ugrave;": '\U000000F9', - "uharl;": '\U000021BF', - "uharr;": '\U000021BE', - "uhblk;": '\U00002580', - "ulcorn;": '\U0000231C', - "ulcorner;": '\U0000231C', - "ulcrop;": '\U0000230F', - "ultri;": '\U000025F8', - "umacr;": '\U0000016B', - "uml;": '\U000000A8', - "uogon;": '\U00000173', - "uopf;": '\U0001D566', - "uparrow;": '\U00002191', - "updownarrow;": '\U00002195', - "upharpoonleft;": '\U000021BF', - "upharpoonright;": '\U000021BE', - "uplus;": '\U0000228E', - "upsi;": '\U000003C5', - "upsih;": '\U000003D2', - "upsilon;": '\U000003C5', - "upuparrows;": '\U000021C8', - "urcorn;": '\U0000231D', - "urcorner;": '\U0000231D', - "urcrop;": '\U0000230E', - "uring;": '\U0000016F', - "urtri;": '\U000025F9', - "uscr;": '\U0001D4CA', - "utdot;": '\U000022F0', - "utilde;": '\U00000169', - "utri;": '\U000025B5', - "utrif;": '\U000025B4', - "uuarr;": '\U000021C8', - "uuml;": '\U000000FC', - "uwangle;": '\U000029A7', - "vArr;": '\U000021D5', - "vBar;": '\U00002AE8', - "vBarv;": '\U00002AE9', - "vDash;": '\U000022A8', - "vangrt;": '\U0000299C', - "varepsilon;": '\U000003F5', - "varkappa;": '\U000003F0', - "varnothing;": '\U00002205', - "varphi;": '\U000003D5', - "varpi;": '\U000003D6', - "varpropto;": '\U0000221D', - "varr;": '\U00002195', - "varrho;": '\U000003F1', - "varsigma;": '\U000003C2', - "vartheta;": '\U000003D1', - "vartriangleleft;": '\U000022B2', - "vartriangleright;": '\U000022B3', - "vcy;": '\U00000432', - "vdash;": '\U000022A2', - "vee;": '\U00002228', - "veebar;": '\U000022BB', - "veeeq;": '\U0000225A', - "vellip;": '\U000022EE', - "verbar;": '\U0000007C', - "vert;": '\U0000007C', - "vfr;": '\U0001D533', - "vltri;": '\U000022B2', - "vopf;": '\U0001D567', - "vprop;": '\U0000221D', - "vrtri;": '\U000022B3', - "vscr;": '\U0001D4CB', - "vzigzag;": '\U0000299A', - "wcirc;": '\U00000175', - "wedbar;": '\U00002A5F', - "wedge;": '\U00002227', - "wedgeq;": '\U00002259', - "weierp;": '\U00002118', - "wfr;": '\U0001D534', - "wopf;": '\U0001D568', - "wp;": '\U00002118', - "wr;": '\U00002240', - "wreath;": '\U00002240', - "wscr;": '\U0001D4CC', - "xcap;": '\U000022C2', - "xcirc;": '\U000025EF', - "xcup;": '\U000022C3', - "xdtri;": '\U000025BD', - "xfr;": '\U0001D535', - "xhArr;": '\U000027FA', - "xharr;": '\U000027F7', - "xi;": '\U000003BE', - "xlArr;": '\U000027F8', - "xlarr;": '\U000027F5', - "xmap;": '\U000027FC', - "xnis;": '\U000022FB', - "xodot;": '\U00002A00', - "xopf;": '\U0001D569', - "xoplus;": '\U00002A01', - "xotime;": '\U00002A02', - "xrArr;": '\U000027F9', - "xrarr;": '\U000027F6', - "xscr;": '\U0001D4CD', - "xsqcup;": '\U00002A06', - "xuplus;": '\U00002A04', - "xutri;": '\U000025B3', - "xvee;": '\U000022C1', - "xwedge;": '\U000022C0', - "yacute;": '\U000000FD', - "yacy;": '\U0000044F', - "ycirc;": '\U00000177', - "ycy;": '\U0000044B', - "yen;": '\U000000A5', - "yfr;": '\U0001D536', - "yicy;": '\U00000457', - "yopf;": '\U0001D56A', - "yscr;": '\U0001D4CE', - "yucy;": '\U0000044E', - "yuml;": '\U000000FF', - "zacute;": '\U0000017A', - "zcaron;": '\U0000017E', - "zcy;": '\U00000437', - "zdot;": '\U0000017C', - "zeetrf;": '\U00002128', - "zeta;": '\U000003B6', - "zfr;": '\U0001D537', - "zhcy;": '\U00000436', - "zigrarr;": '\U000021DD', - "zopf;": '\U0001D56B', - "zscr;": '\U0001D4CF', - "zwj;": '\U0000200D', - "zwnj;": '\U0000200C', - "AElig": '\U000000C6', - "AMP": '\U00000026', - "Aacute": '\U000000C1', - "Acirc": '\U000000C2', - "Agrave": '\U000000C0', - "Aring": '\U000000C5', - "Atilde": '\U000000C3', - "Auml": '\U000000C4', - "COPY": '\U000000A9', - "Ccedil": '\U000000C7', - "ETH": '\U000000D0', - "Eacute": '\U000000C9', - "Ecirc": '\U000000CA', - "Egrave": '\U000000C8', - "Euml": '\U000000CB', - "GT": '\U0000003E', - "Iacute": '\U000000CD', - "Icirc": '\U000000CE', - "Igrave": '\U000000CC', - "Iuml": '\U000000CF', - "LT": '\U0000003C', - "Ntilde": '\U000000D1', - "Oacute": '\U000000D3', - "Ocirc": '\U000000D4', - "Ograve": '\U000000D2', - "Oslash": '\U000000D8', - "Otilde": '\U000000D5', - "Ouml": '\U000000D6', - "QUOT": '\U00000022', - "REG": '\U000000AE', - "THORN": '\U000000DE', - "Uacute": '\U000000DA', - "Ucirc": '\U000000DB', - "Ugrave": '\U000000D9', - "Uuml": '\U000000DC', - "Yacute": '\U000000DD', - "aacute": '\U000000E1', - "acirc": '\U000000E2', - "acute": '\U000000B4', - "aelig": '\U000000E6', - "agrave": '\U000000E0', - "amp": '\U00000026', - "aring": '\U000000E5', - "atilde": '\U000000E3', - "auml": '\U000000E4', - "brvbar": '\U000000A6', - "ccedil": '\U000000E7', - "cedil": '\U000000B8', - "cent": '\U000000A2', - "copy": '\U000000A9', - "curren": '\U000000A4', - "deg": '\U000000B0', - "divide": '\U000000F7', - "eacute": '\U000000E9', - "ecirc": '\U000000EA', - "egrave": '\U000000E8', - "eth": '\U000000F0', - "euml": '\U000000EB', - "frac12": '\U000000BD', - "frac14": '\U000000BC', - "frac34": '\U000000BE', - "gt": '\U0000003E', - "iacute": '\U000000ED', - "icirc": '\U000000EE', - "iexcl": '\U000000A1', - "igrave": '\U000000EC', - "iquest": '\U000000BF', - "iuml": '\U000000EF', - "laquo": '\U000000AB', - "lt": '\U0000003C', - "macr": '\U000000AF', - "micro": '\U000000B5', - "middot": '\U000000B7', - "nbsp": '\U000000A0', - "not": '\U000000AC', - "ntilde": '\U000000F1', - "oacute": '\U000000F3', - "ocirc": '\U000000F4', - "ograve": '\U000000F2', - "ordf": '\U000000AA', - "ordm": '\U000000BA', - "oslash": '\U000000F8', - "otilde": '\U000000F5', - "ouml": '\U000000F6', - "para": '\U000000B6', - "plusmn": '\U000000B1', - "pound": '\U000000A3', - "quot": '\U00000022', - "raquo": '\U000000BB', - "reg": '\U000000AE', - "sect": '\U000000A7', - "shy": '\U000000AD', - "sup1": '\U000000B9', - "sup2": '\U000000B2', - "sup3": '\U000000B3', - "szlig": '\U000000DF', - "thorn": '\U000000FE', - "times": '\U000000D7', - "uacute": '\U000000FA', - "ucirc": '\U000000FB', - "ugrave": '\U000000F9', - "uml": '\U000000A8', - "uuml": '\U000000FC', - "yacute": '\U000000FD', - "yen": '\U000000A5', - "yuml": '\U000000FF', + "Cross;": '\U00002A2F', + "Cscr;": '\U0001D49E', + "Cup;": '\U000022D3', + "CupCap;": '\U0000224D', + "DD;": '\U00002145', + "DDotrahd;": '\U00002911', + "DJcy;": '\U00000402', + "DScy;": '\U00000405', + "DZcy;": '\U0000040F', + "Dagger;": '\U00002021', + "Darr;": '\U000021A1', + "Dashv;": '\U00002AE4', + "Dcaron;": '\U0000010E', + "Dcy;": '\U00000414', + "Del;": '\U00002207', + "Delta;": '\U00000394', + "Dfr;": '\U0001D507', + "DiacriticalAcute;": '\U000000B4', + "DiacriticalDot;": '\U000002D9', + "DiacriticalDoubleAcute;": '\U000002DD', + "DiacriticalGrave;": '\U00000060', + "DiacriticalTilde;": '\U000002DC', + "Diamond;": '\U000022C4', + "DifferentialD;": '\U00002146', + "Dopf;": '\U0001D53B', + "Dot;": '\U000000A8', + "DotDot;": '\U000020DC', + "DotEqual;": '\U00002250', + "DoubleContourIntegral;": '\U0000222F', + "DoubleDot;": '\U000000A8', + "DoubleDownArrow;": '\U000021D3', + "DoubleLeftArrow;": '\U000021D0', + "DoubleLeftRightArrow;": '\U000021D4', + "DoubleLeftTee;": '\U00002AE4', + "DoubleLongLeftArrow;": '\U000027F8', + "DoubleLongLeftRightArrow;": '\U000027FA', + "DoubleLongRightArrow;": '\U000027F9', + "DoubleRightArrow;": '\U000021D2', + "DoubleRightTee;": '\U000022A8', + "DoubleUpArrow;": '\U000021D1', + "DoubleUpDownArrow;": '\U000021D5', + "DoubleVerticalBar;": '\U00002225', + "DownArrow;": '\U00002193', + "DownArrowBar;": '\U00002913', + "DownArrowUpArrow;": '\U000021F5', + "DownBreve;": '\U00000311', + "DownLeftRightVector;": '\U00002950', + "DownLeftTeeVector;": '\U0000295E', + "DownLeftVector;": '\U000021BD', + "DownLeftVectorBar;": '\U00002956', + "DownRightTeeVector;": '\U0000295F', + "DownRightVector;": '\U000021C1', + "DownRightVectorBar;": '\U00002957', + "DownTee;": '\U000022A4', + "DownTeeArrow;": '\U000021A7', + "Downarrow;": '\U000021D3', + "Dscr;": '\U0001D49F', + "Dstrok;": '\U00000110', + "ENG;": '\U0000014A', + "ETH;": '\U000000D0', + "Eacute;": '\U000000C9', + "Ecaron;": '\U0000011A', + "Ecirc;": '\U000000CA', + "Ecy;": '\U0000042D', + "Edot;": '\U00000116', + "Efr;": '\U0001D508', + "Egrave;": '\U000000C8', + "Element;": '\U00002208', + "Emacr;": '\U00000112', + "EmptySmallSquare;": '\U000025FB', + "EmptyVerySmallSquare;": '\U000025AB', + "Eogon;": '\U00000118', + "Eopf;": '\U0001D53C', + "Epsilon;": '\U00000395', + "Equal;": '\U00002A75', + "EqualTilde;": '\U00002242', + "Equilibrium;": '\U000021CC', + "Escr;": '\U00002130', + "Esim;": '\U00002A73', + "Eta;": '\U00000397', + "Euml;": '\U000000CB', + "Exists;": '\U00002203', + "ExponentialE;": '\U00002147', + "Fcy;": '\U00000424', + "Ffr;": '\U0001D509', + "FilledSmallSquare;": '\U000025FC', + "FilledVerySmallSquare;": '\U000025AA', + "Fopf;": '\U0001D53D', + "ForAll;": '\U00002200', + "Fouriertrf;": '\U00002131', + "Fscr;": '\U00002131', + "GJcy;": '\U00000403', + "GT;": '\U0000003E', + "Gamma;": '\U00000393', + "Gammad;": '\U000003DC', + "Gbreve;": '\U0000011E', + "Gcedil;": '\U00000122', + "Gcirc;": '\U0000011C', + "Gcy;": '\U00000413', + "Gdot;": '\U00000120', + "Gfr;": '\U0001D50A', + "Gg;": '\U000022D9', + "Gopf;": '\U0001D53E', + "GreaterEqual;": '\U00002265', + "GreaterEqualLess;": '\U000022DB', + "GreaterFullEqual;": '\U00002267', + "GreaterGreater;": '\U00002AA2', + "GreaterLess;": '\U00002277', + "GreaterSlantEqual;": '\U00002A7E', + "GreaterTilde;": '\U00002273', + "Gscr;": '\U0001D4A2', + "Gt;": '\U0000226B', + "HARDcy;": '\U0000042A', + "Hacek;": '\U000002C7', + "Hat;": '\U0000005E', + "Hcirc;": '\U00000124', + "Hfr;": '\U0000210C', + "HilbertSpace;": '\U0000210B', + "Hopf;": '\U0000210D', + "HorizontalLine;": '\U00002500', + "Hscr;": '\U0000210B', + "Hstrok;": '\U00000126', + "HumpDownHump;": '\U0000224E', + "HumpEqual;": '\U0000224F', + "IEcy;": '\U00000415', + "IJlig;": '\U00000132', + "IOcy;": '\U00000401', + "Iacute;": '\U000000CD', + "Icirc;": '\U000000CE', + "Icy;": '\U00000418', + "Idot;": '\U00000130', + "Ifr;": '\U00002111', + "Igrave;": '\U000000CC', + "Im;": '\U00002111', + "Imacr;": '\U0000012A', + "ImaginaryI;": '\U00002148', + "Implies;": '\U000021D2', + "Int;": '\U0000222C', + "Integral;": '\U0000222B', + "Intersection;": '\U000022C2', + "InvisibleComma;": '\U00002063', + "InvisibleTimes;": '\U00002062', + "Iogon;": '\U0000012E', + "Iopf;": '\U0001D540', + "Iota;": '\U00000399', + "Iscr;": '\U00002110', + "Itilde;": '\U00000128', + "Iukcy;": '\U00000406', + "Iuml;": '\U000000CF', + "Jcirc;": '\U00000134', + "Jcy;": '\U00000419', + "Jfr;": '\U0001D50D', + "Jopf;": '\U0001D541', + "Jscr;": '\U0001D4A5', + "Jsercy;": '\U00000408', + "Jukcy;": '\U00000404', + "KHcy;": '\U00000425', + "KJcy;": '\U0000040C', + "Kappa;": '\U0000039A', + "Kcedil;": '\U00000136', + "Kcy;": '\U0000041A', + "Kfr;": '\U0001D50E', + "Kopf;": '\U0001D542', + "Kscr;": '\U0001D4A6', + "LJcy;": '\U00000409', + "LT;": '\U0000003C', + "Lacute;": '\U00000139', + "Lambda;": '\U0000039B', + "Lang;": '\U000027EA', + "Laplacetrf;": '\U00002112', + "Larr;": '\U0000219E', + "Lcaron;": '\U0000013D', + "Lcedil;": '\U0000013B', + "Lcy;": '\U0000041B', + "LeftAngleBracket;": '\U000027E8', + "LeftArrow;": '\U00002190', + "LeftArrowBar;": '\U000021E4', + "LeftArrowRightArrow;": '\U000021C6', + "LeftCeiling;": '\U00002308', + "LeftDoubleBracket;": '\U000027E6', + "LeftDownTeeVector;": '\U00002961', + "LeftDownVector;": '\U000021C3', + "LeftDownVectorBar;": '\U00002959', + "LeftFloor;": '\U0000230A', + "LeftRightArrow;": '\U00002194', + "LeftRightVector;": '\U0000294E', + "LeftTee;": '\U000022A3', + "LeftTeeArrow;": '\U000021A4', + "LeftTeeVector;": '\U0000295A', + "LeftTriangle;": '\U000022B2', + "LeftTriangleBar;": '\U000029CF', + "LeftTriangleEqual;": '\U000022B4', + "LeftUpDownVector;": '\U00002951', + "LeftUpTeeVector;": '\U00002960', + "LeftUpVector;": '\U000021BF', + "LeftUpVectorBar;": '\U00002958', + "LeftVector;": '\U000021BC', + "LeftVectorBar;": '\U00002952', + "Leftarrow;": '\U000021D0', + "Leftrightarrow;": '\U000021D4', + "LessEqualGreater;": '\U000022DA', + "LessFullEqual;": '\U00002266', + "LessGreater;": '\U00002276', + "LessLess;": '\U00002AA1', + "LessSlantEqual;": '\U00002A7D', + "LessTilde;": '\U00002272', + "Lfr;": '\U0001D50F', + "Ll;": '\U000022D8', + "Lleftarrow;": '\U000021DA', + "Lmidot;": '\U0000013F', + "LongLeftArrow;": '\U000027F5', + "LongLeftRightArrow;": '\U000027F7', + "LongRightArrow;": '\U000027F6', + "Longleftarrow;": '\U000027F8', + "Longleftrightarrow;": '\U000027FA', + "Longrightarrow;": '\U000027F9', + "Lopf;": '\U0001D543', + "LowerLeftArrow;": '\U00002199', + "LowerRightArrow;": '\U00002198', + "Lscr;": '\U00002112', + "Lsh;": '\U000021B0', + "Lstrok;": '\U00000141', + "Lt;": '\U0000226A', + "Map;": '\U00002905', + "Mcy;": '\U0000041C', + "MediumSpace;": '\U0000205F', + "Mellintrf;": '\U00002133', + "Mfr;": '\U0001D510', + "MinusPlus;": '\U00002213', + "Mopf;": '\U0001D544', + "Mscr;": '\U00002133', + "Mu;": '\U0000039C', + "NJcy;": '\U0000040A', + "Nacute;": '\U00000143', + "Ncaron;": '\U00000147', + "Ncedil;": '\U00000145', + "Ncy;": '\U0000041D', + "NegativeMediumSpace;": '\U0000200B', + "NegativeThickSpace;": '\U0000200B', + "NegativeThinSpace;": '\U0000200B', + "NegativeVeryThinSpace;": '\U0000200B', + "NestedGreaterGreater;": '\U0000226B', + "NestedLessLess;": '\U0000226A', + "NewLine;": '\U0000000A', + "Nfr;": '\U0001D511', + "NoBreak;": '\U00002060', + "NonBreakingSpace;": '\U000000A0', + "Nopf;": '\U00002115', + "Not;": '\U00002AEC', + "NotCongruent;": '\U00002262', + "NotCupCap;": '\U0000226D', + "NotDoubleVerticalBar;": '\U00002226', + "NotElement;": '\U00002209', + "NotEqual;": '\U00002260', + "NotExists;": '\U00002204', + "NotGreater;": '\U0000226F', + "NotGreaterEqual;": '\U00002271', + "NotGreaterLess;": '\U00002279', + "NotGreaterTilde;": '\U00002275', + "NotLeftTriangle;": '\U000022EA', + "NotLeftTriangleEqual;": '\U000022EC', + "NotLess;": '\U0000226E', + "NotLessEqual;": '\U00002270', + "NotLessGreater;": '\U00002278', + "NotLessTilde;": '\U00002274', + "NotPrecedes;": '\U00002280', + "NotPrecedesSlantEqual;": '\U000022E0', + "NotReverseElement;": '\U0000220C', + "NotRightTriangle;": '\U000022EB', + "NotRightTriangleEqual;": '\U000022ED', + "NotSquareSubsetEqual;": '\U000022E2', + "NotSquareSupersetEqual;": '\U000022E3', + "NotSubsetEqual;": '\U00002288', + "NotSucceeds;": '\U00002281', + "NotSucceedsSlantEqual;": '\U000022E1', + "NotSupersetEqual;": '\U00002289', + "NotTilde;": '\U00002241', + "NotTildeEqual;": '\U00002244', + "NotTildeFullEqual;": '\U00002247', + "NotTildeTilde;": '\U00002249', + "NotVerticalBar;": '\U00002224', + "Nscr;": '\U0001D4A9', + "Ntilde;": '\U000000D1', + "Nu;": '\U0000039D', + "OElig;": '\U00000152', + "Oacute;": '\U000000D3', + "Ocirc;": '\U000000D4', + "Ocy;": '\U0000041E', + "Odblac;": '\U00000150', + "Ofr;": '\U0001D512', + "Ograve;": '\U000000D2', + "Omacr;": '\U0000014C', + "Omega;": '\U000003A9', + "Omicron;": '\U0000039F', + "Oopf;": '\U0001D546', + "OpenCurlyDoubleQuote;": '\U0000201C', + "OpenCurlyQuote;": '\U00002018', + "Or;": '\U00002A54', + "Oscr;": '\U0001D4AA', + "Oslash;": '\U000000D8', + "Otilde;": '\U000000D5', + "Otimes;": '\U00002A37', + "Ouml;": '\U000000D6', + "OverBar;": '\U0000203E', + "OverBrace;": '\U000023DE', + "OverBracket;": '\U000023B4', + "OverParenthesis;": '\U000023DC', + "PartialD;": '\U00002202', + "Pcy;": '\U0000041F', + "Pfr;": '\U0001D513', + "Phi;": '\U000003A6', + "Pi;": '\U000003A0', + "PlusMinus;": '\U000000B1', + "Poincareplane;": '\U0000210C', + "Popf;": '\U00002119', + "Pr;": '\U00002ABB', + "Precedes;": '\U0000227A', + "PrecedesEqual;": '\U00002AAF', + "PrecedesSlantEqual;": '\U0000227C', + "PrecedesTilde;": '\U0000227E', + "Prime;": '\U00002033', + "Product;": '\U0000220F', + "Proportion;": '\U00002237', + "Proportional;": '\U0000221D', + "Pscr;": '\U0001D4AB', + "Psi;": '\U000003A8', + "QUOT;": '\U00000022', + "Qfr;": '\U0001D514', + "Qopf;": '\U0000211A', + "Qscr;": '\U0001D4AC', + "RBarr;": '\U00002910', + "REG;": '\U000000AE', + "Racute;": '\U00000154', + "Rang;": '\U000027EB', + "Rarr;": '\U000021A0', + "Rarrtl;": '\U00002916', + "Rcaron;": '\U00000158', + "Rcedil;": '\U00000156', + "Rcy;": '\U00000420', + "Re;": '\U0000211C', + "ReverseElement;": '\U0000220B', + "ReverseEquilibrium;": '\U000021CB', + "ReverseUpEquilibrium;": '\U0000296F', + "Rfr;": '\U0000211C', + "Rho;": '\U000003A1', + "RightAngleBracket;": '\U000027E9', + "RightArrow;": '\U00002192', + "RightArrowBar;": '\U000021E5', + "RightArrowLeftArrow;": '\U000021C4', + "RightCeiling;": '\U00002309', + "RightDoubleBracket;": '\U000027E7', + "RightDownTeeVector;": '\U0000295D', + "RightDownVector;": '\U000021C2', + "RightDownVectorBar;": '\U00002955', + "RightFloor;": '\U0000230B', + "RightTee;": '\U000022A2', + "RightTeeArrow;": '\U000021A6', + "RightTeeVector;": '\U0000295B', + "RightTriangle;": '\U000022B3', + "RightTriangleBar;": '\U000029D0', + "RightTriangleEqual;": '\U000022B5', + "RightUpDownVector;": '\U0000294F', + "RightUpTeeVector;": '\U0000295C', + "RightUpVector;": '\U000021BE', + "RightUpVectorBar;": '\U00002954', + "RightVector;": '\U000021C0', + "RightVectorBar;": '\U00002953', + "Rightarrow;": '\U000021D2', + "Ropf;": '\U0000211D', + "RoundImplies;": '\U00002970', + "Rrightarrow;": '\U000021DB', + "Rscr;": '\U0000211B', + "Rsh;": '\U000021B1', + "RuleDelayed;": '\U000029F4', + "SHCHcy;": '\U00000429', + "SHcy;": '\U00000428', + "SOFTcy;": '\U0000042C', + "Sacute;": '\U0000015A', + "Sc;": '\U00002ABC', + "Scaron;": '\U00000160', + "Scedil;": '\U0000015E', + "Scirc;": '\U0000015C', + "Scy;": '\U00000421', + "Sfr;": '\U0001D516', + "ShortDownArrow;": '\U00002193', + "ShortLeftArrow;": '\U00002190', + "ShortRightArrow;": '\U00002192', + "ShortUpArrow;": '\U00002191', + "Sigma;": '\U000003A3', + "SmallCircle;": '\U00002218', + "Sopf;": '\U0001D54A', + "Sqrt;": '\U0000221A', + "Square;": '\U000025A1', + "SquareIntersection;": '\U00002293', + "SquareSubset;": '\U0000228F', + "SquareSubsetEqual;": '\U00002291', + "SquareSuperset;": '\U00002290', + "SquareSupersetEqual;": '\U00002292', + "SquareUnion;": '\U00002294', + "Sscr;": '\U0001D4AE', + "Star;": '\U000022C6', + "Sub;": '\U000022D0', + "Subset;": '\U000022D0', + "SubsetEqual;": '\U00002286', + "Succeeds;": '\U0000227B', + "SucceedsEqual;": '\U00002AB0', + "SucceedsSlantEqual;": '\U0000227D', + "SucceedsTilde;": '\U0000227F', + "SuchThat;": '\U0000220B', + "Sum;": '\U00002211', + "Sup;": '\U000022D1', + "Superset;": '\U00002283', + "SupersetEqual;": '\U00002287', + "Supset;": '\U000022D1', + "THORN;": '\U000000DE', + "TRADE;": '\U00002122', + "TSHcy;": '\U0000040B', + "TScy;": '\U00000426', + "Tab;": '\U00000009', + "Tau;": '\U000003A4', + "Tcaron;": '\U00000164', + "Tcedil;": '\U00000162', + "Tcy;": '\U00000422', + "Tfr;": '\U0001D517', + "Therefore;": '\U00002234', + "Theta;": '\U00000398', + "ThinSpace;": '\U00002009', + "Tilde;": '\U0000223C', + "TildeEqual;": '\U00002243', + "TildeFullEqual;": '\U00002245', + "TildeTilde;": '\U00002248', + "Topf;": '\U0001D54B', + "TripleDot;": '\U000020DB', + "Tscr;": '\U0001D4AF', + "Tstrok;": '\U00000166', + "Uacute;": '\U000000DA', + "Uarr;": '\U0000219F', + "Uarrocir;": '\U00002949', + "Ubrcy;": '\U0000040E', + "Ubreve;": '\U0000016C', + "Ucirc;": '\U000000DB', + "Ucy;": '\U00000423', + "Udblac;": '\U00000170', + "Ufr;": '\U0001D518', + "Ugrave;": '\U000000D9', + "Umacr;": '\U0000016A', + "UnderBar;": '\U0000005F', + "UnderBrace;": '\U000023DF', + "UnderBracket;": '\U000023B5', + "UnderParenthesis;": '\U000023DD', + "Union;": '\U000022C3', + "UnionPlus;": '\U0000228E', + "Uogon;": '\U00000172', + "Uopf;": '\U0001D54C', + "UpArrow;": '\U00002191', + "UpArrowBar;": '\U00002912', + "UpArrowDownArrow;": '\U000021C5', + "UpDownArrow;": '\U00002195', + "UpEquilibrium;": '\U0000296E', + "UpTee;": '\U000022A5', + "UpTeeArrow;": '\U000021A5', + "Uparrow;": '\U000021D1', + "Updownarrow;": '\U000021D5', + "UpperLeftArrow;": '\U00002196', + "UpperRightArrow;": '\U00002197', + "Upsi;": '\U000003D2', + "Upsilon;": '\U000003A5', + "Uring;": '\U0000016E', + "Uscr;": '\U0001D4B0', + "Utilde;": '\U00000168', + "Uuml;": '\U000000DC', + "VDash;": '\U000022AB', + "Vbar;": '\U00002AEB', + "Vcy;": '\U00000412', + "Vdash;": '\U000022A9', + "Vdashl;": '\U00002AE6', + "Vee;": '\U000022C1', + "Verbar;": '\U00002016', + "Vert;": '\U00002016', + "VerticalBar;": '\U00002223', + "VerticalLine;": '\U0000007C', + "VerticalSeparator;": '\U00002758', + "VerticalTilde;": '\U00002240', + "VeryThinSpace;": '\U0000200A', + "Vfr;": '\U0001D519', + "Vopf;": '\U0001D54D', + "Vscr;": '\U0001D4B1', + "Vvdash;": '\U000022AA', + "Wcirc;": '\U00000174', + "Wedge;": '\U000022C0', + "Wfr;": '\U0001D51A', + "Wopf;": '\U0001D54E', + "Wscr;": '\U0001D4B2', + "Xfr;": '\U0001D51B', + "Xi;": '\U0000039E', + "Xopf;": '\U0001D54F', + "Xscr;": '\U0001D4B3', + "YAcy;": '\U0000042F', + "YIcy;": '\U00000407', + "YUcy;": '\U0000042E', + "Yacute;": '\U000000DD', + "Ycirc;": '\U00000176', + "Ycy;": '\U0000042B', + "Yfr;": '\U0001D51C', + "Yopf;": '\U0001D550', + "Yscr;": '\U0001D4B4', + "Yuml;": '\U00000178', + "ZHcy;": '\U00000416', + "Zacute;": '\U00000179', + "Zcaron;": '\U0000017D', + "Zcy;": '\U00000417', + "Zdot;": '\U0000017B', + "ZeroWidthSpace;": '\U0000200B', + "Zeta;": '\U00000396', + "Zfr;": '\U00002128', + "Zopf;": '\U00002124', + "Zscr;": '\U0001D4B5', + "aacute;": '\U000000E1', + "abreve;": '\U00000103', + "ac;": '\U0000223E', + "acd;": '\U0000223F', + "acirc;": '\U000000E2', + "acute;": '\U000000B4', + "acy;": '\U00000430', + "aelig;": '\U000000E6', + "af;": '\U00002061', + "afr;": '\U0001D51E', + "agrave;": '\U000000E0', + "alefsym;": '\U00002135', + "aleph;": '\U00002135', + "alpha;": '\U000003B1', + "amacr;": '\U00000101', + "amalg;": '\U00002A3F', + "amp;": '\U00000026', + "and;": '\U00002227', + "andand;": '\U00002A55', + "andd;": '\U00002A5C', + "andslope;": '\U00002A58', + "andv;": '\U00002A5A', + "ang;": '\U00002220', + "ange;": '\U000029A4', + "angle;": '\U00002220', + "angmsd;": '\U00002221', + "angmsdaa;": '\U000029A8', + "angmsdab;": '\U000029A9', + "angmsdac;": '\U000029AA', + "angmsdad;": '\U000029AB', + "angmsdae;": '\U000029AC', + "angmsdaf;": '\U000029AD', + "angmsdag;": '\U000029AE', + "angmsdah;": '\U000029AF', + "angrt;": '\U0000221F', + "angrtvb;": '\U000022BE', + "angrtvbd;": '\U0000299D', + "angsph;": '\U00002222', + "angst;": '\U000000C5', + "angzarr;": '\U0000237C', + "aogon;": '\U00000105', + "aopf;": '\U0001D552', + "ap;": '\U00002248', + "apE;": '\U00002A70', + "apacir;": '\U00002A6F', + "ape;": '\U0000224A', + "apid;": '\U0000224B', + "apos;": '\U00000027', + "approx;": '\U00002248', + "approxeq;": '\U0000224A', + "aring;": '\U000000E5', + "ascr;": '\U0001D4B6', + "ast;": '\U0000002A', + "asymp;": '\U00002248', + "asympeq;": '\U0000224D', + "atilde;": '\U000000E3', + "auml;": '\U000000E4', + "awconint;": '\U00002233', + "awint;": '\U00002A11', + "bNot;": '\U00002AED', + "backcong;": '\U0000224C', + "backepsilon;": '\U000003F6', + "backprime;": '\U00002035', + "backsim;": '\U0000223D', + "backsimeq;": '\U000022CD', + "barvee;": '\U000022BD', + "barwed;": '\U00002305', + "barwedge;": '\U00002305', + "bbrk;": '\U000023B5', + "bbrktbrk;": '\U000023B6', + "bcong;": '\U0000224C', + "bcy;": '\U00000431', + "bdquo;": '\U0000201E', + "becaus;": '\U00002235', + "because;": '\U00002235', + "bemptyv;": '\U000029B0', + "bepsi;": '\U000003F6', + "bernou;": '\U0000212C', + "beta;": '\U000003B2', + "beth;": '\U00002136', + "between;": '\U0000226C', + "bfr;": '\U0001D51F', + "bigcap;": '\U000022C2', + "bigcirc;": '\U000025EF', + "bigcup;": '\U000022C3', + "bigodot;": '\U00002A00', + "bigoplus;": '\U00002A01', + "bigotimes;": '\U00002A02', + "bigsqcup;": '\U00002A06', + "bigstar;": '\U00002605', + "bigtriangledown;": '\U000025BD', + "bigtriangleup;": '\U000025B3', + "biguplus;": '\U00002A04', + "bigvee;": '\U000022C1', + "bigwedge;": '\U000022C0', + "bkarow;": '\U0000290D', + "blacklozenge;": '\U000029EB', + "blacksquare;": '\U000025AA', + "blacktriangle;": '\U000025B4', + "blacktriangledown;": '\U000025BE', + "blacktriangleleft;": '\U000025C2', + "blacktriangleright;": '\U000025B8', + "blank;": '\U00002423', + "blk12;": '\U00002592', + "blk14;": '\U00002591', + "blk34;": '\U00002593', + "block;": '\U00002588', + "bnot;": '\U00002310', + "bopf;": '\U0001D553', + "bot;": '\U000022A5', + "bottom;": '\U000022A5', + "bowtie;": '\U000022C8', + "boxDL;": '\U00002557', + "boxDR;": '\U00002554', + "boxDl;": '\U00002556', + "boxDr;": '\U00002553', + "boxH;": '\U00002550', + "boxHD;": '\U00002566', + "boxHU;": '\U00002569', + "boxHd;": '\U00002564', + "boxHu;": '\U00002567', + "boxUL;": '\U0000255D', + "boxUR;": '\U0000255A', + "boxUl;": '\U0000255C', + "boxUr;": '\U00002559', + "boxV;": '\U00002551', + "boxVH;": '\U0000256C', + "boxVL;": '\U00002563', + "boxVR;": '\U00002560', + "boxVh;": '\U0000256B', + "boxVl;": '\U00002562', + "boxVr;": '\U0000255F', + "boxbox;": '\U000029C9', + "boxdL;": '\U00002555', + "boxdR;": '\U00002552', + "boxdl;": '\U00002510', + "boxdr;": '\U0000250C', + "boxh;": '\U00002500', + "boxhD;": '\U00002565', + "boxhU;": '\U00002568', + "boxhd;": '\U0000252C', + "boxhu;": '\U00002534', + "boxminus;": '\U0000229F', + "boxplus;": '\U0000229E', + "boxtimes;": '\U000022A0', + "boxuL;": '\U0000255B', + "boxuR;": '\U00002558', + "boxul;": '\U00002518', + "boxur;": '\U00002514', + "boxv;": '\U00002502', + "boxvH;": '\U0000256A', + "boxvL;": '\U00002561', + "boxvR;": '\U0000255E', + "boxvh;": '\U0000253C', + "boxvl;": '\U00002524', + "boxvr;": '\U0000251C', + "bprime;": '\U00002035', + "breve;": '\U000002D8', + "brvbar;": '\U000000A6', + "bscr;": '\U0001D4B7', + "bsemi;": '\U0000204F', + "bsim;": '\U0000223D', + "bsime;": '\U000022CD', + "bsol;": '\U0000005C', + "bsolb;": '\U000029C5', + "bsolhsub;": '\U000027C8', + "bull;": '\U00002022', + "bullet;": '\U00002022', + "bump;": '\U0000224E', + "bumpE;": '\U00002AAE', + "bumpe;": '\U0000224F', + "bumpeq;": '\U0000224F', + "cacute;": '\U00000107', + "cap;": '\U00002229', + "capand;": '\U00002A44', + "capbrcup;": '\U00002A49', + "capcap;": '\U00002A4B', + "capcup;": '\U00002A47', + "capdot;": '\U00002A40', + "caret;": '\U00002041', + "caron;": '\U000002C7', + "ccaps;": '\U00002A4D', + "ccaron;": '\U0000010D', + "ccedil;": '\U000000E7', + "ccirc;": '\U00000109', + "ccups;": '\U00002A4C', + "ccupssm;": '\U00002A50', + "cdot;": '\U0000010B', + "cedil;": '\U000000B8', + "cemptyv;": '\U000029B2', + "cent;": '\U000000A2', + "centerdot;": '\U000000B7', + "cfr;": '\U0001D520', + "chcy;": '\U00000447', + "check;": '\U00002713', + "checkmark;": '\U00002713', + "chi;": '\U000003C7', + "cir;": '\U000025CB', + "cirE;": '\U000029C3', + "circ;": '\U000002C6', + "circeq;": '\U00002257', + "circlearrowleft;": '\U000021BA', + "circlearrowright;": '\U000021BB', + "circledR;": '\U000000AE', + "circledS;": '\U000024C8', + "circledast;": '\U0000229B', + "circledcirc;": '\U0000229A', + "circleddash;": '\U0000229D', + "cire;": '\U00002257', + "cirfnint;": '\U00002A10', + "cirmid;": '\U00002AEF', + "cirscir;": '\U000029C2', + "clubs;": '\U00002663', + "clubsuit;": '\U00002663', + "colon;": '\U0000003A', + "colone;": '\U00002254', + "coloneq;": '\U00002254', + "comma;": '\U0000002C', + "commat;": '\U00000040', + "comp;": '\U00002201', + "compfn;": '\U00002218', + "complement;": '\U00002201', + "complexes;": '\U00002102', + "cong;": '\U00002245', + "congdot;": '\U00002A6D', + "conint;": '\U0000222E', + "copf;": '\U0001D554', + "coprod;": '\U00002210', + "copy;": '\U000000A9', + "copysr;": '\U00002117', + "crarr;": '\U000021B5', + "cross;": '\U00002717', + "cscr;": '\U0001D4B8', + "csub;": '\U00002ACF', + "csube;": '\U00002AD1', + "csup;": '\U00002AD0', + "csupe;": '\U00002AD2', + "ctdot;": '\U000022EF', + "cudarrl;": '\U00002938', + "cudarrr;": '\U00002935', + "cuepr;": '\U000022DE', + "cuesc;": '\U000022DF', + "cularr;": '\U000021B6', + "cularrp;": '\U0000293D', + "cup;": '\U0000222A', + "cupbrcap;": '\U00002A48', + "cupcap;": '\U00002A46', + "cupcup;": '\U00002A4A', + "cupdot;": '\U0000228D', + "cupor;": '\U00002A45', + "curarr;": '\U000021B7', + "curarrm;": '\U0000293C', + "curlyeqprec;": '\U000022DE', + "curlyeqsucc;": '\U000022DF', + "curlyvee;": '\U000022CE', + "curlywedge;": '\U000022CF', + "curren;": '\U000000A4', + "curvearrowleft;": '\U000021B6', + "curvearrowright;": '\U000021B7', + "cuvee;": '\U000022CE', + "cuwed;": '\U000022CF', + "cwconint;": '\U00002232', + "cwint;": '\U00002231', + "cylcty;": '\U0000232D', + "dArr;": '\U000021D3', + "dHar;": '\U00002965', + "dagger;": '\U00002020', + "daleth;": '\U00002138', + "darr;": '\U00002193', + "dash;": '\U00002010', + "dashv;": '\U000022A3', + "dbkarow;": '\U0000290F', + "dblac;": '\U000002DD', + "dcaron;": '\U0000010F', + "dcy;": '\U00000434', + "dd;": '\U00002146', + "ddagger;": '\U00002021', + "ddarr;": '\U000021CA', + "ddotseq;": '\U00002A77', + "deg;": '\U000000B0', + "delta;": '\U000003B4', + "demptyv;": '\U000029B1', + "dfisht;": '\U0000297F', + "dfr;": '\U0001D521', + "dharl;": '\U000021C3', + "dharr;": '\U000021C2', + "diam;": '\U000022C4', + "diamond;": '\U000022C4', + "diamondsuit;": '\U00002666', + "diams;": '\U00002666', + "die;": '\U000000A8', + "digamma;": '\U000003DD', + "disin;": '\U000022F2', + "div;": '\U000000F7', + "divide;": '\U000000F7', + "divideontimes;": '\U000022C7', + "divonx;": '\U000022C7', + "djcy;": '\U00000452', + "dlcorn;": '\U0000231E', + "dlcrop;": '\U0000230D', + "dollar;": '\U00000024', + "dopf;": '\U0001D555', + "dot;": '\U000002D9', + "doteq;": '\U00002250', + "doteqdot;": '\U00002251', + "dotminus;": '\U00002238', + "dotplus;": '\U00002214', + "dotsquare;": '\U000022A1', + "doublebarwedge;": '\U00002306', + "downarrow;": '\U00002193', + "downdownarrows;": '\U000021CA', + "downharpoonleft;": '\U000021C3', + "downharpoonright;": '\U000021C2', + "drbkarow;": '\U00002910', + "drcorn;": '\U0000231F', + "drcrop;": '\U0000230C', + "dscr;": '\U0001D4B9', + "dscy;": '\U00000455', + "dsol;": '\U000029F6', + "dstrok;": '\U00000111', + "dtdot;": '\U000022F1', + "dtri;": '\U000025BF', + "dtrif;": '\U000025BE', + "duarr;": '\U000021F5', + "duhar;": '\U0000296F', + "dwangle;": '\U000029A6', + "dzcy;": '\U0000045F', + "dzigrarr;": '\U000027FF', + "eDDot;": '\U00002A77', + "eDot;": '\U00002251', + "eacute;": '\U000000E9', + "easter;": '\U00002A6E', + "ecaron;": '\U0000011B', + "ecir;": '\U00002256', + "ecirc;": '\U000000EA', + "ecolon;": '\U00002255', + "ecy;": '\U0000044D', + "edot;": '\U00000117', + "ee;": '\U00002147', + "efDot;": '\U00002252', + "efr;": '\U0001D522', + "eg;": '\U00002A9A', + "egrave;": '\U000000E8', + "egs;": '\U00002A96', + "egsdot;": '\U00002A98', + "el;": '\U00002A99', + "elinters;": '\U000023E7', + "ell;": '\U00002113', + "els;": '\U00002A95', + "elsdot;": '\U00002A97', + "emacr;": '\U00000113', + "empty;": '\U00002205', + "emptyset;": '\U00002205', + "emptyv;": '\U00002205', + "emsp;": '\U00002003', + "emsp13;": '\U00002004', + "emsp14;": '\U00002005', + "eng;": '\U0000014B', + "ensp;": '\U00002002', + "eogon;": '\U00000119', + "eopf;": '\U0001D556', + "epar;": '\U000022D5', + "eparsl;": '\U000029E3', + "eplus;": '\U00002A71', + "epsi;": '\U000003B5', + "epsilon;": '\U000003B5', + "epsiv;": '\U000003F5', + "eqcirc;": '\U00002256', + "eqcolon;": '\U00002255', + "eqsim;": '\U00002242', + "eqslantgtr;": '\U00002A96', + "eqslantless;": '\U00002A95', + "equals;": '\U0000003D', + "equest;": '\U0000225F', + "equiv;": '\U00002261', + "equivDD;": '\U00002A78', + "eqvparsl;": '\U000029E5', + "erDot;": '\U00002253', + "erarr;": '\U00002971', + "escr;": '\U0000212F', + "esdot;": '\U00002250', + "esim;": '\U00002242', + "eta;": '\U000003B7', + "eth;": '\U000000F0', + "euml;": '\U000000EB', + "euro;": '\U000020AC', + "excl;": '\U00000021', + "exist;": '\U00002203', + "expectation;": '\U00002130', + "exponentiale;": '\U00002147', + "fallingdotseq;": '\U00002252', + "fcy;": '\U00000444', + "female;": '\U00002640', + "ffilig;": '\U0000FB03', + "fflig;": '\U0000FB00', + "ffllig;": '\U0000FB04', + "ffr;": '\U0001D523', + "filig;": '\U0000FB01', + "flat;": '\U0000266D', + "fllig;": '\U0000FB02', + "fltns;": '\U000025B1', + "fnof;": '\U00000192', + "fopf;": '\U0001D557', + "forall;": '\U00002200', + "fork;": '\U000022D4', + "forkv;": '\U00002AD9', + "fpartint;": '\U00002A0D', + "frac12;": '\U000000BD', + "frac13;": '\U00002153', + "frac14;": '\U000000BC', + "frac15;": '\U00002155', + "frac16;": '\U00002159', + "frac18;": '\U0000215B', + "frac23;": '\U00002154', + "frac25;": '\U00002156', + "frac34;": '\U000000BE', + "frac35;": '\U00002157', + "frac38;": '\U0000215C', + "frac45;": '\U00002158', + "frac56;": '\U0000215A', + "frac58;": '\U0000215D', + "frac78;": '\U0000215E', + "frasl;": '\U00002044', + "frown;": '\U00002322', + "fscr;": '\U0001D4BB', + "gE;": '\U00002267', + "gEl;": '\U00002A8C', + "gacute;": '\U000001F5', + "gamma;": '\U000003B3', + "gammad;": '\U000003DD', + "gap;": '\U00002A86', + "gbreve;": '\U0000011F', + "gcirc;": '\U0000011D', + "gcy;": '\U00000433', + "gdot;": '\U00000121', + "ge;": '\U00002265', + "gel;": '\U000022DB', + "geq;": '\U00002265', + "geqq;": '\U00002267', + "geqslant;": '\U00002A7E', + "ges;": '\U00002A7E', + "gescc;": '\U00002AA9', + "gesdot;": '\U00002A80', + "gesdoto;": '\U00002A82', + "gesdotol;": '\U00002A84', + "gesles;": '\U00002A94', + "gfr;": '\U0001D524', + "gg;": '\U0000226B', + "ggg;": '\U000022D9', + "gimel;": '\U00002137', + "gjcy;": '\U00000453', + "gl;": '\U00002277', + "glE;": '\U00002A92', + "gla;": '\U00002AA5', + "glj;": '\U00002AA4', + "gnE;": '\U00002269', + "gnap;": '\U00002A8A', + "gnapprox;": '\U00002A8A', + "gne;": '\U00002A88', + "gneq;": '\U00002A88', + "gneqq;": '\U00002269', + "gnsim;": '\U000022E7', + "gopf;": '\U0001D558', + "grave;": '\U00000060', + "gscr;": '\U0000210A', + "gsim;": '\U00002273', + "gsime;": '\U00002A8E', + "gsiml;": '\U00002A90', + "gt;": '\U0000003E', + "gtcc;": '\U00002AA7', + "gtcir;": '\U00002A7A', + "gtdot;": '\U000022D7', + "gtlPar;": '\U00002995', + "gtquest;": '\U00002A7C', + "gtrapprox;": '\U00002A86', + "gtrarr;": '\U00002978', + "gtrdot;": '\U000022D7', + "gtreqless;": '\U000022DB', + "gtreqqless;": '\U00002A8C', + "gtrless;": '\U00002277', + "gtrsim;": '\U00002273', + "hArr;": '\U000021D4', + "hairsp;": '\U0000200A', + "half;": '\U000000BD', + "hamilt;": '\U0000210B', + "hardcy;": '\U0000044A', + "harr;": '\U00002194', + "harrcir;": '\U00002948', + "harrw;": '\U000021AD', + "hbar;": '\U0000210F', + "hcirc;": '\U00000125', + "hearts;": '\U00002665', + "heartsuit;": '\U00002665', + "hellip;": '\U00002026', + "hercon;": '\U000022B9', + "hfr;": '\U0001D525', + "hksearow;": '\U00002925', + "hkswarow;": '\U00002926', + "hoarr;": '\U000021FF', + "homtht;": '\U0000223B', + "hookleftarrow;": '\U000021A9', + "hookrightarrow;": '\U000021AA', + "hopf;": '\U0001D559', + "horbar;": '\U00002015', + "hscr;": '\U0001D4BD', + "hslash;": '\U0000210F', + "hstrok;": '\U00000127', + "hybull;": '\U00002043', + "hyphen;": '\U00002010', + "iacute;": '\U000000ED', + "ic;": '\U00002063', + "icirc;": '\U000000EE', + "icy;": '\U00000438', + "iecy;": '\U00000435', + "iexcl;": '\U000000A1', + "iff;": '\U000021D4', + "ifr;": '\U0001D526', + "igrave;": '\U000000EC', + "ii;": '\U00002148', + "iiiint;": '\U00002A0C', + "iiint;": '\U0000222D', + "iinfin;": '\U000029DC', + "iiota;": '\U00002129', + "ijlig;": '\U00000133', + "imacr;": '\U0000012B', + "image;": '\U00002111', + "imagline;": '\U00002110', + "imagpart;": '\U00002111', + "imath;": '\U00000131', + "imof;": '\U000022B7', + "imped;": '\U000001B5', + "in;": '\U00002208', + "incare;": '\U00002105', + "infin;": '\U0000221E', + "infintie;": '\U000029DD', + "inodot;": '\U00000131', + "int;": '\U0000222B', + "intcal;": '\U000022BA', + "integers;": '\U00002124', + "intercal;": '\U000022BA', + "intlarhk;": '\U00002A17', + "intprod;": '\U00002A3C', + "iocy;": '\U00000451', + "iogon;": '\U0000012F', + "iopf;": '\U0001D55A', + "iota;": '\U000003B9', + "iprod;": '\U00002A3C', + "iquest;": '\U000000BF', + "iscr;": '\U0001D4BE', + "isin;": '\U00002208', + "isinE;": '\U000022F9', + "isindot;": '\U000022F5', + "isins;": '\U000022F4', + "isinsv;": '\U000022F3', + "isinv;": '\U00002208', + "it;": '\U00002062', + "itilde;": '\U00000129', + "iukcy;": '\U00000456', + "iuml;": '\U000000EF', + "jcirc;": '\U00000135', + "jcy;": '\U00000439', + "jfr;": '\U0001D527', + "jmath;": '\U00000237', + "jopf;": '\U0001D55B', + "jscr;": '\U0001D4BF', + "jsercy;": '\U00000458', + "jukcy;": '\U00000454', + "kappa;": '\U000003BA', + "kappav;": '\U000003F0', + "kcedil;": '\U00000137', + "kcy;": '\U0000043A', + "kfr;": '\U0001D528', + "kgreen;": '\U00000138', + "khcy;": '\U00000445', + "kjcy;": '\U0000045C', + "kopf;": '\U0001D55C', + "kscr;": '\U0001D4C0', + "lAarr;": '\U000021DA', + "lArr;": '\U000021D0', + "lAtail;": '\U0000291B', + "lBarr;": '\U0000290E', + "lE;": '\U00002266', + "lEg;": '\U00002A8B', + "lHar;": '\U00002962', + "lacute;": '\U0000013A', + "laemptyv;": '\U000029B4', + "lagran;": '\U00002112', + "lambda;": '\U000003BB', + "lang;": '\U000027E8', + "langd;": '\U00002991', + "langle;": '\U000027E8', + "lap;": '\U00002A85', + "laquo;": '\U000000AB', + "larr;": '\U00002190', + "larrb;": '\U000021E4', + "larrbfs;": '\U0000291F', + "larrfs;": '\U0000291D', + "larrhk;": '\U000021A9', + "larrlp;": '\U000021AB', + "larrpl;": '\U00002939', + "larrsim;": '\U00002973', + "larrtl;": '\U000021A2', + "lat;": '\U00002AAB', + "latail;": '\U00002919', + "late;": '\U00002AAD', + "lbarr;": '\U0000290C', + "lbbrk;": '\U00002772', + "lbrace;": '\U0000007B', + "lbrack;": '\U0000005B', + "lbrke;": '\U0000298B', + "lbrksld;": '\U0000298F', + "lbrkslu;": '\U0000298D', + "lcaron;": '\U0000013E', + "lcedil;": '\U0000013C', + "lceil;": '\U00002308', + "lcub;": '\U0000007B', + "lcy;": '\U0000043B', + "ldca;": '\U00002936', + "ldquo;": '\U0000201C', + "ldquor;": '\U0000201E', + "ldrdhar;": '\U00002967', + "ldrushar;": '\U0000294B', + "ldsh;": '\U000021B2', + "le;": '\U00002264', + "leftarrow;": '\U00002190', + "leftarrowtail;": '\U000021A2', + "leftharpoondown;": '\U000021BD', + "leftharpoonup;": '\U000021BC', + "leftleftarrows;": '\U000021C7', + "leftrightarrow;": '\U00002194', + "leftrightarrows;": '\U000021C6', + "leftrightharpoons;": '\U000021CB', + "leftrightsquigarrow;": '\U000021AD', + "leftthreetimes;": '\U000022CB', + "leg;": '\U000022DA', + "leq;": '\U00002264', + "leqq;": '\U00002266', + "leqslant;": '\U00002A7D', + "les;": '\U00002A7D', + "lescc;": '\U00002AA8', + "lesdot;": '\U00002A7F', + "lesdoto;": '\U00002A81', + "lesdotor;": '\U00002A83', + "lesges;": '\U00002A93', + "lessapprox;": '\U00002A85', + "lessdot;": '\U000022D6', + "lesseqgtr;": '\U000022DA', + "lesseqqgtr;": '\U00002A8B', + "lessgtr;": '\U00002276', + "lesssim;": '\U00002272', + "lfisht;": '\U0000297C', + "lfloor;": '\U0000230A', + "lfr;": '\U0001D529', + "lg;": '\U00002276', + "lgE;": '\U00002A91', + "lhard;": '\U000021BD', + "lharu;": '\U000021BC', + "lharul;": '\U0000296A', + "lhblk;": '\U00002584', + "ljcy;": '\U00000459', + "ll;": '\U0000226A', + "llarr;": '\U000021C7', + "llcorner;": '\U0000231E', + "llhard;": '\U0000296B', + "lltri;": '\U000025FA', + "lmidot;": '\U00000140', + "lmoust;": '\U000023B0', + "lmoustache;": '\U000023B0', + "lnE;": '\U00002268', + "lnap;": '\U00002A89', + "lnapprox;": '\U00002A89', + "lne;": '\U00002A87', + "lneq;": '\U00002A87', + "lneqq;": '\U00002268', + "lnsim;": '\U000022E6', + "loang;": '\U000027EC', + "loarr;": '\U000021FD', + "lobrk;": '\U000027E6', + "longleftarrow;": '\U000027F5', + "longleftrightarrow;": '\U000027F7', + "longmapsto;": '\U000027FC', + "longrightarrow;": '\U000027F6', + "looparrowleft;": '\U000021AB', + "looparrowright;": '\U000021AC', + "lopar;": '\U00002985', + "lopf;": '\U0001D55D', + "loplus;": '\U00002A2D', + "lotimes;": '\U00002A34', + "lowast;": '\U00002217', + "lowbar;": '\U0000005F', + "loz;": '\U000025CA', + "lozenge;": '\U000025CA', + "lozf;": '\U000029EB', + "lpar;": '\U00000028', + "lparlt;": '\U00002993', + "lrarr;": '\U000021C6', + "lrcorner;": '\U0000231F', + "lrhar;": '\U000021CB', + "lrhard;": '\U0000296D', + "lrm;": '\U0000200E', + "lrtri;": '\U000022BF', + "lsaquo;": '\U00002039', + "lscr;": '\U0001D4C1', + "lsh;": '\U000021B0', + "lsim;": '\U00002272', + "lsime;": '\U00002A8D', + "lsimg;": '\U00002A8F', + "lsqb;": '\U0000005B', + "lsquo;": '\U00002018', + "lsquor;": '\U0000201A', + "lstrok;": '\U00000142', + "lt;": '\U0000003C', + "ltcc;": '\U00002AA6', + "ltcir;": '\U00002A79', + "ltdot;": '\U000022D6', + "lthree;": '\U000022CB', + "ltimes;": '\U000022C9', + "ltlarr;": '\U00002976', + "ltquest;": '\U00002A7B', + "ltrPar;": '\U00002996', + "ltri;": '\U000025C3', + "ltrie;": '\U000022B4', + "ltrif;": '\U000025C2', + "lurdshar;": '\U0000294A', + "luruhar;": '\U00002966', + "mDDot;": '\U0000223A', + "macr;": '\U000000AF', + "male;": '\U00002642', + "malt;": '\U00002720', + "maltese;": '\U00002720', + "map;": '\U000021A6', + "mapsto;": '\U000021A6', + "mapstodown;": '\U000021A7', + "mapstoleft;": '\U000021A4', + "mapstoup;": '\U000021A5', + "marker;": '\U000025AE', + "mcomma;": '\U00002A29', + "mcy;": '\U0000043C', + "mdash;": '\U00002014', + "measuredangle;": '\U00002221', + "mfr;": '\U0001D52A', + "mho;": '\U00002127', + "micro;": '\U000000B5', + "mid;": '\U00002223', + "midast;": '\U0000002A', + "midcir;": '\U00002AF0', + "middot;": '\U000000B7', + "minus;": '\U00002212', + "minusb;": '\U0000229F', + "minusd;": '\U00002238', + "minusdu;": '\U00002A2A', + "mlcp;": '\U00002ADB', + "mldr;": '\U00002026', + "mnplus;": '\U00002213', + "models;": '\U000022A7', + "mopf;": '\U0001D55E', + "mp;": '\U00002213', + "mscr;": '\U0001D4C2', + "mstpos;": '\U0000223E', + "mu;": '\U000003BC', + "multimap;": '\U000022B8', + "mumap;": '\U000022B8', + "nLeftarrow;": '\U000021CD', + "nLeftrightarrow;": '\U000021CE', + "nRightarrow;": '\U000021CF', + "nVDash;": '\U000022AF', + "nVdash;": '\U000022AE', + "nabla;": '\U00002207', + "nacute;": '\U00000144', + "nap;": '\U00002249', + "napos;": '\U00000149', + "napprox;": '\U00002249', + "natur;": '\U0000266E', + "natural;": '\U0000266E', + "naturals;": '\U00002115', + "nbsp;": '\U000000A0', + "ncap;": '\U00002A43', + "ncaron;": '\U00000148', + "ncedil;": '\U00000146', + "ncong;": '\U00002247', + "ncup;": '\U00002A42', + "ncy;": '\U0000043D', + "ndash;": '\U00002013', + "ne;": '\U00002260', + "neArr;": '\U000021D7', + "nearhk;": '\U00002924', + "nearr;": '\U00002197', + "nearrow;": '\U00002197', + "nequiv;": '\U00002262', + "nesear;": '\U00002928', + "nexist;": '\U00002204', + "nexists;": '\U00002204', + "nfr;": '\U0001D52B', + "nge;": '\U00002271', + "ngeq;": '\U00002271', + "ngsim;": '\U00002275', + "ngt;": '\U0000226F', + "ngtr;": '\U0000226F', + "nhArr;": '\U000021CE', + "nharr;": '\U000021AE', + "nhpar;": '\U00002AF2', + "ni;": '\U0000220B', + "nis;": '\U000022FC', + "nisd;": '\U000022FA', + "niv;": '\U0000220B', + "njcy;": '\U0000045A', + "nlArr;": '\U000021CD', + "nlarr;": '\U0000219A', + "nldr;": '\U00002025', + "nle;": '\U00002270', + "nleftarrow;": '\U0000219A', + "nleftrightarrow;": '\U000021AE', + "nleq;": '\U00002270', + "nless;": '\U0000226E', + "nlsim;": '\U00002274', + "nlt;": '\U0000226E', + "nltri;": '\U000022EA', + "nltrie;": '\U000022EC', + "nmid;": '\U00002224', + "nopf;": '\U0001D55F', + "not;": '\U000000AC', + "notin;": '\U00002209', + "notinva;": '\U00002209', + "notinvb;": '\U000022F7', + "notinvc;": '\U000022F6', + "notni;": '\U0000220C', + "notniva;": '\U0000220C', + "notnivb;": '\U000022FE', + "notnivc;": '\U000022FD', + "npar;": '\U00002226', + "nparallel;": '\U00002226', + "npolint;": '\U00002A14', + "npr;": '\U00002280', + "nprcue;": '\U000022E0', + "nprec;": '\U00002280', + "nrArr;": '\U000021CF', + "nrarr;": '\U0000219B', + "nrightarrow;": '\U0000219B', + "nrtri;": '\U000022EB', + "nrtrie;": '\U000022ED', + "nsc;": '\U00002281', + "nsccue;": '\U000022E1', + "nscr;": '\U0001D4C3', + "nshortmid;": '\U00002224', + "nshortparallel;": '\U00002226', + "nsim;": '\U00002241', + "nsime;": '\U00002244', + "nsimeq;": '\U00002244', + "nsmid;": '\U00002224', + "nspar;": '\U00002226', + "nsqsube;": '\U000022E2', + "nsqsupe;": '\U000022E3', + "nsub;": '\U00002284', + "nsube;": '\U00002288', + "nsubseteq;": '\U00002288', + "nsucc;": '\U00002281', + "nsup;": '\U00002285', + "nsupe;": '\U00002289', + "nsupseteq;": '\U00002289', + "ntgl;": '\U00002279', + "ntilde;": '\U000000F1', + "ntlg;": '\U00002278', + "ntriangleleft;": '\U000022EA', + "ntrianglelefteq;": '\U000022EC', + "ntriangleright;": '\U000022EB', + "ntrianglerighteq;": '\U000022ED', + "nu;": '\U000003BD', + "num;": '\U00000023', + "numero;": '\U00002116', + "numsp;": '\U00002007', + "nvDash;": '\U000022AD', + "nvHarr;": '\U00002904', + "nvdash;": '\U000022AC', + "nvinfin;": '\U000029DE', + "nvlArr;": '\U00002902', + "nvrArr;": '\U00002903', + "nwArr;": '\U000021D6', + "nwarhk;": '\U00002923', + "nwarr;": '\U00002196', + "nwarrow;": '\U00002196', + "nwnear;": '\U00002927', + "oS;": '\U000024C8', + "oacute;": '\U000000F3', + "oast;": '\U0000229B', + "ocir;": '\U0000229A', + "ocirc;": '\U000000F4', + "ocy;": '\U0000043E', + "odash;": '\U0000229D', + "odblac;": '\U00000151', + "odiv;": '\U00002A38', + "odot;": '\U00002299', + "odsold;": '\U000029BC', + "oelig;": '\U00000153', + "ofcir;": '\U000029BF', + "ofr;": '\U0001D52C', + "ogon;": '\U000002DB', + "ograve;": '\U000000F2', + "ogt;": '\U000029C1', + "ohbar;": '\U000029B5', + "ohm;": '\U000003A9', + "oint;": '\U0000222E', + "olarr;": '\U000021BA', + "olcir;": '\U000029BE', + "olcross;": '\U000029BB', + "oline;": '\U0000203E', + "olt;": '\U000029C0', + "omacr;": '\U0000014D', + "omega;": '\U000003C9', + "omicron;": '\U000003BF', + "omid;": '\U000029B6', + "ominus;": '\U00002296', + "oopf;": '\U0001D560', + "opar;": '\U000029B7', + "operp;": '\U000029B9', + "oplus;": '\U00002295', + "or;": '\U00002228', + "orarr;": '\U000021BB', + "ord;": '\U00002A5D', + "order;": '\U00002134', + "orderof;": '\U00002134', + "ordf;": '\U000000AA', + "ordm;": '\U000000BA', + "origof;": '\U000022B6', + "oror;": '\U00002A56', + "orslope;": '\U00002A57', + "orv;": '\U00002A5B', + "oscr;": '\U00002134', + "oslash;": '\U000000F8', + "osol;": '\U00002298', + "otilde;": '\U000000F5', + "otimes;": '\U00002297', + "otimesas;": '\U00002A36', + "ouml;": '\U000000F6', + "ovbar;": '\U0000233D', + "par;": '\U00002225', + "para;": '\U000000B6', + "parallel;": '\U00002225', + "parsim;": '\U00002AF3', + "parsl;": '\U00002AFD', + "part;": '\U00002202', + "pcy;": '\U0000043F', + "percnt;": '\U00000025', + "period;": '\U0000002E', + "permil;": '\U00002030', + "perp;": '\U000022A5', + "pertenk;": '\U00002031', + "pfr;": '\U0001D52D', + "phi;": '\U000003C6', + "phiv;": '\U000003D5', + "phmmat;": '\U00002133', + "phone;": '\U0000260E', + "pi;": '\U000003C0', + "pitchfork;": '\U000022D4', + "piv;": '\U000003D6', + "planck;": '\U0000210F', + "planckh;": '\U0000210E', + "plankv;": '\U0000210F', + "plus;": '\U0000002B', + "plusacir;": '\U00002A23', + "plusb;": '\U0000229E', + "pluscir;": '\U00002A22', + "plusdo;": '\U00002214', + "plusdu;": '\U00002A25', + "pluse;": '\U00002A72', + "plusmn;": '\U000000B1', + "plussim;": '\U00002A26', + "plustwo;": '\U00002A27', + "pm;": '\U000000B1', + "pointint;": '\U00002A15', + "popf;": '\U0001D561', + "pound;": '\U000000A3', + "pr;": '\U0000227A', + "prE;": '\U00002AB3', + "prap;": '\U00002AB7', + "prcue;": '\U0000227C', + "pre;": '\U00002AAF', + "prec;": '\U0000227A', + "precapprox;": '\U00002AB7', + "preccurlyeq;": '\U0000227C', + "preceq;": '\U00002AAF', + "precnapprox;": '\U00002AB9', + "precneqq;": '\U00002AB5', + "precnsim;": '\U000022E8', + "precsim;": '\U0000227E', + "prime;": '\U00002032', + "primes;": '\U00002119', + "prnE;": '\U00002AB5', + "prnap;": '\U00002AB9', + "prnsim;": '\U000022E8', + "prod;": '\U0000220F', + "profalar;": '\U0000232E', + "profline;": '\U00002312', + "profsurf;": '\U00002313', + "prop;": '\U0000221D', + "propto;": '\U0000221D', + "prsim;": '\U0000227E', + "prurel;": '\U000022B0', + "pscr;": '\U0001D4C5', + "psi;": '\U000003C8', + "puncsp;": '\U00002008', + "qfr;": '\U0001D52E', + "qint;": '\U00002A0C', + "qopf;": '\U0001D562', + "qprime;": '\U00002057', + "qscr;": '\U0001D4C6', + "quaternions;": '\U0000210D', + "quatint;": '\U00002A16', + "quest;": '\U0000003F', + "questeq;": '\U0000225F', + "quot;": '\U00000022', + "rAarr;": '\U000021DB', + "rArr;": '\U000021D2', + "rAtail;": '\U0000291C', + "rBarr;": '\U0000290F', + "rHar;": '\U00002964', + "racute;": '\U00000155', + "radic;": '\U0000221A', + "raemptyv;": '\U000029B3', + "rang;": '\U000027E9', + "rangd;": '\U00002992', + "range;": '\U000029A5', + "rangle;": '\U000027E9', + "raquo;": '\U000000BB', + "rarr;": '\U00002192', + "rarrap;": '\U00002975', + "rarrb;": '\U000021E5', + "rarrbfs;": '\U00002920', + "rarrc;": '\U00002933', + "rarrfs;": '\U0000291E', + "rarrhk;": '\U000021AA', + "rarrlp;": '\U000021AC', + "rarrpl;": '\U00002945', + "rarrsim;": '\U00002974', + "rarrtl;": '\U000021A3', + "rarrw;": '\U0000219D', + "ratail;": '\U0000291A', + "ratio;": '\U00002236', + "rationals;": '\U0000211A', + "rbarr;": '\U0000290D', + "rbbrk;": '\U00002773', + "rbrace;": '\U0000007D', + "rbrack;": '\U0000005D', + "rbrke;": '\U0000298C', + "rbrksld;": '\U0000298E', + "rbrkslu;": '\U00002990', + "rcaron;": '\U00000159', + "rcedil;": '\U00000157', + "rceil;": '\U00002309', + "rcub;": '\U0000007D', + "rcy;": '\U00000440', + "rdca;": '\U00002937', + "rdldhar;": '\U00002969', + "rdquo;": '\U0000201D', + "rdquor;": '\U0000201D', + "rdsh;": '\U000021B3', + "real;": '\U0000211C', + "realine;": '\U0000211B', + "realpart;": '\U0000211C', + "reals;": '\U0000211D', + "rect;": '\U000025AD', + "reg;": '\U000000AE', + "rfisht;": '\U0000297D', + "rfloor;": '\U0000230B', + "rfr;": '\U0001D52F', + "rhard;": '\U000021C1', + "rharu;": '\U000021C0', + "rharul;": '\U0000296C', + "rho;": '\U000003C1', + "rhov;": '\U000003F1', + "rightarrow;": '\U00002192', + "rightarrowtail;": '\U000021A3', + "rightharpoondown;": '\U000021C1', + "rightharpoonup;": '\U000021C0', + "rightleftarrows;": '\U000021C4', + "rightleftharpoons;": '\U000021CC', + "rightrightarrows;": '\U000021C9', + "rightsquigarrow;": '\U0000219D', + "rightthreetimes;": '\U000022CC', + "ring;": '\U000002DA', + "risingdotseq;": '\U00002253', + "rlarr;": '\U000021C4', + "rlhar;": '\U000021CC', + "rlm;": '\U0000200F', + "rmoust;": '\U000023B1', + "rmoustache;": '\U000023B1', + "rnmid;": '\U00002AEE', + "roang;": '\U000027ED', + "roarr;": '\U000021FE', + "robrk;": '\U000027E7', + "ropar;": '\U00002986', + "ropf;": '\U0001D563', + "roplus;": '\U00002A2E', + "rotimes;": '\U00002A35', + "rpar;": '\U00000029', + "rpargt;": '\U00002994', + "rppolint;": '\U00002A12', + "rrarr;": '\U000021C9', + "rsaquo;": '\U0000203A', + "rscr;": '\U0001D4C7', + "rsh;": '\U000021B1', + "rsqb;": '\U0000005D', + "rsquo;": '\U00002019', + "rsquor;": '\U00002019', + "rthree;": '\U000022CC', + "rtimes;": '\U000022CA', + "rtri;": '\U000025B9', + "rtrie;": '\U000022B5', + "rtrif;": '\U000025B8', + "rtriltri;": '\U000029CE', + "ruluhar;": '\U00002968', + "rx;": '\U0000211E', + "sacute;": '\U0000015B', + "sbquo;": '\U0000201A', + "sc;": '\U0000227B', + "scE;": '\U00002AB4', + "scap;": '\U00002AB8', + "scaron;": '\U00000161', + "sccue;": '\U0000227D', + "sce;": '\U00002AB0', + "scedil;": '\U0000015F', + "scirc;": '\U0000015D', + "scnE;": '\U00002AB6', + "scnap;": '\U00002ABA', + "scnsim;": '\U000022E9', + "scpolint;": '\U00002A13', + "scsim;": '\U0000227F', + "scy;": '\U00000441', + "sdot;": '\U000022C5', + "sdotb;": '\U000022A1', + "sdote;": '\U00002A66', + "seArr;": '\U000021D8', + "searhk;": '\U00002925', + "searr;": '\U00002198', + "searrow;": '\U00002198', + "sect;": '\U000000A7', + "semi;": '\U0000003B', + "seswar;": '\U00002929', + "setminus;": '\U00002216', + "setmn;": '\U00002216', + "sext;": '\U00002736', + "sfr;": '\U0001D530', + "sfrown;": '\U00002322', + "sharp;": '\U0000266F', + "shchcy;": '\U00000449', + "shcy;": '\U00000448', + "shortmid;": '\U00002223', + "shortparallel;": '\U00002225', + "shy;": '\U000000AD', + "sigma;": '\U000003C3', + "sigmaf;": '\U000003C2', + "sigmav;": '\U000003C2', + "sim;": '\U0000223C', + "simdot;": '\U00002A6A', + "sime;": '\U00002243', + "simeq;": '\U00002243', + "simg;": '\U00002A9E', + "simgE;": '\U00002AA0', + "siml;": '\U00002A9D', + "simlE;": '\U00002A9F', + "simne;": '\U00002246', + "simplus;": '\U00002A24', + "simrarr;": '\U00002972', + "slarr;": '\U00002190', + "smallsetminus;": '\U00002216', + "smashp;": '\U00002A33', + "smeparsl;": '\U000029E4', + "smid;": '\U00002223', + "smile;": '\U00002323', + "smt;": '\U00002AAA', + "smte;": '\U00002AAC', + "softcy;": '\U0000044C', + "sol;": '\U0000002F', + "solb;": '\U000029C4', + "solbar;": '\U0000233F', + "sopf;": '\U0001D564', + "spades;": '\U00002660', + "spadesuit;": '\U00002660', + "spar;": '\U00002225', + "sqcap;": '\U00002293', + "sqcup;": '\U00002294', + "sqsub;": '\U0000228F', + "sqsube;": '\U00002291', + "sqsubset;": '\U0000228F', + "sqsubseteq;": '\U00002291', + "sqsup;": '\U00002290', + "sqsupe;": '\U00002292', + "sqsupset;": '\U00002290', + "sqsupseteq;": '\U00002292', + "squ;": '\U000025A1', + "square;": '\U000025A1', + "squarf;": '\U000025AA', + "squf;": '\U000025AA', + "srarr;": '\U00002192', + "sscr;": '\U0001D4C8', + "ssetmn;": '\U00002216', + "ssmile;": '\U00002323', + "sstarf;": '\U000022C6', + "star;": '\U00002606', + "starf;": '\U00002605', + "straightepsilon;": '\U000003F5', + "straightphi;": '\U000003D5', + "strns;": '\U000000AF', + "sub;": '\U00002282', + "subE;": '\U00002AC5', + "subdot;": '\U00002ABD', + "sube;": '\U00002286', + "subedot;": '\U00002AC3', + "submult;": '\U00002AC1', + "subnE;": '\U00002ACB', + "subne;": '\U0000228A', + "subplus;": '\U00002ABF', + "subrarr;": '\U00002979', + "subset;": '\U00002282', + "subseteq;": '\U00002286', + "subseteqq;": '\U00002AC5', + "subsetneq;": '\U0000228A', + "subsetneqq;": '\U00002ACB', + "subsim;": '\U00002AC7', + "subsub;": '\U00002AD5', + "subsup;": '\U00002AD3', + "succ;": '\U0000227B', + "succapprox;": '\U00002AB8', + "succcurlyeq;": '\U0000227D', + "succeq;": '\U00002AB0', + "succnapprox;": '\U00002ABA', + "succneqq;": '\U00002AB6', + "succnsim;": '\U000022E9', + "succsim;": '\U0000227F', + "sum;": '\U00002211', + "sung;": '\U0000266A', + "sup;": '\U00002283', + "sup1;": '\U000000B9', + "sup2;": '\U000000B2', + "sup3;": '\U000000B3', + "supE;": '\U00002AC6', + "supdot;": '\U00002ABE', + "supdsub;": '\U00002AD8', + "supe;": '\U00002287', + "supedot;": '\U00002AC4', + "suphsol;": '\U000027C9', + "suphsub;": '\U00002AD7', + "suplarr;": '\U0000297B', + "supmult;": '\U00002AC2', + "supnE;": '\U00002ACC', + "supne;": '\U0000228B', + "supplus;": '\U00002AC0', + "supset;": '\U00002283', + "supseteq;": '\U00002287', + "supseteqq;": '\U00002AC6', + "supsetneq;": '\U0000228B', + "supsetneqq;": '\U00002ACC', + "supsim;": '\U00002AC8', + "supsub;": '\U00002AD4', + "supsup;": '\U00002AD6', + "swArr;": '\U000021D9', + "swarhk;": '\U00002926', + "swarr;": '\U00002199', + "swarrow;": '\U00002199', + "swnwar;": '\U0000292A', + "szlig;": '\U000000DF', + "target;": '\U00002316', + "tau;": '\U000003C4', + "tbrk;": '\U000023B4', + "tcaron;": '\U00000165', + "tcedil;": '\U00000163', + "tcy;": '\U00000442', + "tdot;": '\U000020DB', + "telrec;": '\U00002315', + "tfr;": '\U0001D531', + "there4;": '\U00002234', + "therefore;": '\U00002234', + "theta;": '\U000003B8', + "thetasym;": '\U000003D1', + "thetav;": '\U000003D1', + "thickapprox;": '\U00002248', + "thicksim;": '\U0000223C', + "thinsp;": '\U00002009', + "thkap;": '\U00002248', + "thksim;": '\U0000223C', + "thorn;": '\U000000FE', + "tilde;": '\U000002DC', + "times;": '\U000000D7', + "timesb;": '\U000022A0', + "timesbar;": '\U00002A31', + "timesd;": '\U00002A30', + "tint;": '\U0000222D', + "toea;": '\U00002928', + "top;": '\U000022A4', + "topbot;": '\U00002336', + "topcir;": '\U00002AF1', + "topf;": '\U0001D565', + "topfork;": '\U00002ADA', + "tosa;": '\U00002929', + "tprime;": '\U00002034', + "trade;": '\U00002122', + "triangle;": '\U000025B5', + "triangledown;": '\U000025BF', + "triangleleft;": '\U000025C3', + "trianglelefteq;": '\U000022B4', + "triangleq;": '\U0000225C', + "triangleright;": '\U000025B9', + "trianglerighteq;": '\U000022B5', + "tridot;": '\U000025EC', + "trie;": '\U0000225C', + "triminus;": '\U00002A3A', + "triplus;": '\U00002A39', + "trisb;": '\U000029CD', + "tritime;": '\U00002A3B', + "trpezium;": '\U000023E2', + "tscr;": '\U0001D4C9', + "tscy;": '\U00000446', + "tshcy;": '\U0000045B', + "tstrok;": '\U00000167', + "twixt;": '\U0000226C', + "twoheadleftarrow;": '\U0000219E', + "twoheadrightarrow;": '\U000021A0', + "uArr;": '\U000021D1', + "uHar;": '\U00002963', + "uacute;": '\U000000FA', + "uarr;": '\U00002191', + "ubrcy;": '\U0000045E', + "ubreve;": '\U0000016D', + "ucirc;": '\U000000FB', + "ucy;": '\U00000443', + "udarr;": '\U000021C5', + "udblac;": '\U00000171', + "udhar;": '\U0000296E', + "ufisht;": '\U0000297E', + "ufr;": '\U0001D532', + "ugrave;": '\U000000F9', + "uharl;": '\U000021BF', + "uharr;": '\U000021BE', + "uhblk;": '\U00002580', + "ulcorn;": '\U0000231C', + "ulcorner;": '\U0000231C', + "ulcrop;": '\U0000230F', + "ultri;": '\U000025F8', + "umacr;": '\U0000016B', + "uml;": '\U000000A8', + "uogon;": '\U00000173', + "uopf;": '\U0001D566', + "uparrow;": '\U00002191', + "updownarrow;": '\U00002195', + "upharpoonleft;": '\U000021BF', + "upharpoonright;": '\U000021BE', + "uplus;": '\U0000228E', + "upsi;": '\U000003C5', + "upsih;": '\U000003D2', + "upsilon;": '\U000003C5', + "upuparrows;": '\U000021C8', + "urcorn;": '\U0000231D', + "urcorner;": '\U0000231D', + "urcrop;": '\U0000230E', + "uring;": '\U0000016F', + "urtri;": '\U000025F9', + "uscr;": '\U0001D4CA', + "utdot;": '\U000022F0', + "utilde;": '\U00000169', + "utri;": '\U000025B5', + "utrif;": '\U000025B4', + "uuarr;": '\U000021C8', + "uuml;": '\U000000FC', + "uwangle;": '\U000029A7', + "vArr;": '\U000021D5', + "vBar;": '\U00002AE8', + "vBarv;": '\U00002AE9', + "vDash;": '\U000022A8', + "vangrt;": '\U0000299C', + "varepsilon;": '\U000003F5', + "varkappa;": '\U000003F0', + "varnothing;": '\U00002205', + "varphi;": '\U000003D5', + "varpi;": '\U000003D6', + "varpropto;": '\U0000221D', + "varr;": '\U00002195', + "varrho;": '\U000003F1', + "varsigma;": '\U000003C2', + "vartheta;": '\U000003D1', + "vartriangleleft;": '\U000022B2', + "vartriangleright;": '\U000022B3', + "vcy;": '\U00000432', + "vdash;": '\U000022A2', + "vee;": '\U00002228', + "veebar;": '\U000022BB', + "veeeq;": '\U0000225A', + "vellip;": '\U000022EE', + "verbar;": '\U0000007C', + "vert;": '\U0000007C', + "vfr;": '\U0001D533', + "vltri;": '\U000022B2', + "vopf;": '\U0001D567', + "vprop;": '\U0000221D', + "vrtri;": '\U000022B3', + "vscr;": '\U0001D4CB', + "vzigzag;": '\U0000299A', + "wcirc;": '\U00000175', + "wedbar;": '\U00002A5F', + "wedge;": '\U00002227', + "wedgeq;": '\U00002259', + "weierp;": '\U00002118', + "wfr;": '\U0001D534', + "wopf;": '\U0001D568', + "wp;": '\U00002118', + "wr;": '\U00002240', + "wreath;": '\U00002240', + "wscr;": '\U0001D4CC', + "xcap;": '\U000022C2', + "xcirc;": '\U000025EF', + "xcup;": '\U000022C3', + "xdtri;": '\U000025BD', + "xfr;": '\U0001D535', + "xhArr;": '\U000027FA', + "xharr;": '\U000027F7', + "xi;": '\U000003BE', + "xlArr;": '\U000027F8', + "xlarr;": '\U000027F5', + "xmap;": '\U000027FC', + "xnis;": '\U000022FB', + "xodot;": '\U00002A00', + "xopf;": '\U0001D569', + "xoplus;": '\U00002A01', + "xotime;": '\U00002A02', + "xrArr;": '\U000027F9', + "xrarr;": '\U000027F6', + "xscr;": '\U0001D4CD', + "xsqcup;": '\U00002A06', + "xuplus;": '\U00002A04', + "xutri;": '\U000025B3', + "xvee;": '\U000022C1', + "xwedge;": '\U000022C0', + "yacute;": '\U000000FD', + "yacy;": '\U0000044F', + "ycirc;": '\U00000177', + "ycy;": '\U0000044B', + "yen;": '\U000000A5', + "yfr;": '\U0001D536', + "yicy;": '\U00000457', + "yopf;": '\U0001D56A', + "yscr;": '\U0001D4CE', + "yucy;": '\U0000044E', + "yuml;": '\U000000FF', + "zacute;": '\U0000017A', + "zcaron;": '\U0000017E', + "zcy;": '\U00000437', + "zdot;": '\U0000017C', + "zeetrf;": '\U00002128', + "zeta;": '\U000003B6', + "zfr;": '\U0001D537', + "zhcy;": '\U00000436', + "zigrarr;": '\U000021DD', + "zopf;": '\U0001D56B', + "zscr;": '\U0001D4CF', + "zwj;": '\U0000200D', + "zwnj;": '\U0000200C', + "AElig": '\U000000C6', + "AMP": '\U00000026', + "Aacute": '\U000000C1', + "Acirc": '\U000000C2', + "Agrave": '\U000000C0', + "Aring": '\U000000C5', + "Atilde": '\U000000C3', + "Auml": '\U000000C4', + "COPY": '\U000000A9', + "Ccedil": '\U000000C7', + "ETH": '\U000000D0', + "Eacute": '\U000000C9', + "Ecirc": '\U000000CA', + "Egrave": '\U000000C8', + "Euml": '\U000000CB', + "GT": '\U0000003E', + "Iacute": '\U000000CD', + "Icirc": '\U000000CE', + "Igrave": '\U000000CC', + "Iuml": '\U000000CF', + "LT": '\U0000003C', + "Ntilde": '\U000000D1', + "Oacute": '\U000000D3', + "Ocirc": '\U000000D4', + "Ograve": '\U000000D2', + "Oslash": '\U000000D8', + "Otilde": '\U000000D5', + "Ouml": '\U000000D6', + "QUOT": '\U00000022', + "REG": '\U000000AE', + "THORN": '\U000000DE', + "Uacute": '\U000000DA', + "Ucirc": '\U000000DB', + "Ugrave": '\U000000D9', + "Uuml": '\U000000DC', + "Yacute": '\U000000DD', + "aacute": '\U000000E1', + "acirc": '\U000000E2', + "acute": '\U000000B4', + "aelig": '\U000000E6', + "agrave": '\U000000E0', + "amp": '\U00000026', + "aring": '\U000000E5', + "atilde": '\U000000E3', + "auml": '\U000000E4', + "brvbar": '\U000000A6', + "ccedil": '\U000000E7', + "cedil": '\U000000B8', + "cent": '\U000000A2', + "copy": '\U000000A9', + "curren": '\U000000A4', + "deg": '\U000000B0', + "divide": '\U000000F7', + "eacute": '\U000000E9', + "ecirc": '\U000000EA', + "egrave": '\U000000E8', + "eth": '\U000000F0', + "euml": '\U000000EB', + "frac12": '\U000000BD', + "frac14": '\U000000BC', + "frac34": '\U000000BE', + "gt": '\U0000003E', + "iacute": '\U000000ED', + "icirc": '\U000000EE', + "iexcl": '\U000000A1', + "igrave": '\U000000EC', + "iquest": '\U000000BF', + "iuml": '\U000000EF', + "laquo": '\U000000AB', + "lt": '\U0000003C', + "macr": '\U000000AF', + "micro": '\U000000B5', + "middot": '\U000000B7', + "nbsp": '\U000000A0', + "not": '\U000000AC', + "ntilde": '\U000000F1', + "oacute": '\U000000F3', + "ocirc": '\U000000F4', + "ograve": '\U000000F2', + "ordf": '\U000000AA', + "ordm": '\U000000BA', + "oslash": '\U000000F8', + "otilde": '\U000000F5', + "ouml": '\U000000F6', + "para": '\U000000B6', + "plusmn": '\U000000B1', + "pound": '\U000000A3', + "quot": '\U00000022', + "raquo": '\U000000BB', + "reg": '\U000000AE', + "sect": '\U000000A7', + "shy": '\U000000AD', + "sup1": '\U000000B9', + "sup2": '\U000000B2', + "sup3": '\U000000B3', + "szlig": '\U000000DF', + "thorn": '\U000000FE', + "times": '\U000000D7', + "uacute": '\U000000FA', + "ucirc": '\U000000FB', + "ugrave": '\U000000F9', + "uml": '\U000000A8', + "uuml": '\U000000FC', + "yacute": '\U000000FD', + "yen": '\U000000A5', + "yuml": '\U000000FF', } // HTML entities that are two unicode codepoints. diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go index d3b384409..01477a963 100644 --- a/vendor/golang.org/x/net/html/foreign.go +++ b/vendor/golang.org/x/net/html/foreign.go @@ -67,7 +67,7 @@ func mathMLTextIntegrationPoint(n *Node) bool { return false } -// Section 12.2.5.5. +// Section 12.2.6.5. var breakout = map[string]bool{ "b": true, "big": true, @@ -115,7 +115,7 @@ var breakout = map[string]bool{ "var": true, } -// Section 12.2.5.5. +// Section 12.2.6.5. var svgTagNameAdjustments = map[string]string{ "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", @@ -155,7 +155,7 @@ var svgTagNameAdjustments = map[string]string{ "textpath": "textPath", } -// Section 12.2.5.1 +// Section 12.2.6.1 var mathMLAttributeAdjustments = map[string]string{ "definitionurl": "definitionURL", } diff --git a/vendor/golang.org/x/net/html/node.go b/vendor/golang.org/x/net/html/node.go index 26b657aec..633ee15dc 100644 --- a/vendor/golang.org/x/net/html/node.go +++ b/vendor/golang.org/x/net/html/node.go @@ -21,9 +21,10 @@ const ( scopeMarkerNode ) -// Section 12.2.3.3 says "scope markers are inserted when entering applet -// elements, buttons, object elements, marquees, table cells, and table -// captions, and are used to prevent formatting from 'leaking'". +// Section 12.2.4.3 says "The markers are inserted when entering applet, +// object, marquee, template, td, th, and caption elements, and are used +// to prevent formatting from "leaking" into applet, object, marquee, +// template, td, th, and caption elements". var scopeMarker = Node{Type: scopeMarkerNode} // A Node consists of a NodeType and some Data (tag name for element nodes, @@ -173,6 +174,16 @@ func (s *nodeStack) index(n *Node) int { return -1 } +// contains returns whether a is within s. +func (s *nodeStack) contains(a atom.Atom) bool { + for _, n := range *s { + if n.DataAtom == a && n.Namespace == "" { + return true + } + } + return false +} + // insert inserts a node at the given index. func (s *nodeStack) insert(i int, n *Node) { (*s) = append(*s, nil) @@ -191,3 +202,19 @@ func (s *nodeStack) remove(n *Node) { (*s)[j] = nil *s = (*s)[:j] } + +type insertionModeStack []insertionMode + +func (s *insertionModeStack) pop() (im insertionMode) { + i := len(*s) + im = (*s)[i-1] + *s = (*s)[:i-1] + return im +} + +func (s *insertionModeStack) top() insertionMode { + if i := len(*s); i > 0 { + return (*s)[i-1] + } + return nil +} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go index be4b2bf5a..1d3c198ae 100644 --- a/vendor/golang.org/x/net/html/parse.go +++ b/vendor/golang.org/x/net/html/parse.go @@ -25,20 +25,22 @@ type parser struct { hasSelfClosingToken bool // doc is the document root element. doc *Node - // The stack of open elements (section 12.2.3.2) and active formatting - // elements (section 12.2.3.3). + // The stack of open elements (section 12.2.4.2) and active formatting + // elements (section 12.2.4.3). oe, afe nodeStack - // Element pointers (section 12.2.3.4). + // Element pointers (section 12.2.4.4). head, form *Node - // Other parsing state flags (section 12.2.3.5). + // Other parsing state flags (section 12.2.4.5). scripting, framesetOK bool + // The stack of template insertion modes + templateStack insertionModeStack // im is the current insertion mode. im insertionMode // originalIM is the insertion mode to go back to after completing a text // or inTableText insertion mode. originalIM insertionMode // fosterParenting is whether new elements should be inserted according to - // the foster parenting rules (section 12.2.5.3). + // the foster parenting rules (section 12.2.6.1). fosterParenting bool // quirks is whether the parser is operating in "quirks mode." quirks bool @@ -56,7 +58,7 @@ func (p *parser) top() *Node { return p.doc } -// Stop tags for use in popUntil. These come from section 12.2.3.2. +// Stop tags for use in popUntil. These come from section 12.2.4.2. var ( defaultScopeStopTags = map[string][]a.Atom{ "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, @@ -79,7 +81,7 @@ const ( // popUntil pops the stack of open elements at the highest element whose tag // is in matchTags, provided there is no higher element in the scope's stop -// tags (as defined in section 12.2.3.2). It returns whether or not there was +// tags (as defined in section 12.2.4.2). It returns whether or not there was // such an element. If there was not, popUntil leaves the stack unchanged. // // For example, the set of stop tags for table scope is: "html", "table". If @@ -126,7 +128,7 @@ func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { return -1 } case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { return -1 } case selectScope: @@ -162,17 +164,17 @@ func (p *parser) clearStackToContext(s scope) { tagAtom := p.oe[i].DataAtom switch s { case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { p.oe = p.oe[:i+1] return } case tableRowScope: - if tagAtom == a.Html || tagAtom == a.Tr { + if tagAtom == a.Html || tagAtom == a.Tr || tagAtom == a.Template { p.oe = p.oe[:i+1] return } case tableBodyScope: - if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { + if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead || tagAtom == a.Template { p.oe = p.oe[:i+1] return } @@ -183,7 +185,7 @@ func (p *parser) clearStackToContext(s scope) { } // generateImpliedEndTags pops nodes off the stack of open elements as long as -// the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. +// the top node has a tag name of dd, dt, li, optgroup, option, p, rb, rp, rt or rtc. // If exceptions are specified, nodes with that name will not be popped off. func (p *parser) generateImpliedEndTags(exceptions ...string) { var i int @@ -192,7 +194,7 @@ loop: n := p.oe[i] if n.Type == ElementNode { switch n.DataAtom { - case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: + case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc: for _, except := range exceptions { if n.Data == except { break loop @@ -234,9 +236,9 @@ func (p *parser) shouldFosterParent() bool { } // fosterParent adds a child node according to the foster parenting rules. -// Section 12.2.5.3, "foster parenting". +// Section 12.2.6.1, "foster parenting". func (p *parser) fosterParent(n *Node) { - var table, parent, prev *Node + var table, parent, prev, template *Node var i int for i = len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == a.Table { @@ -245,6 +247,19 @@ func (p *parser) fosterParent(n *Node) { } } + var j int + for j = len(p.oe) - 1; j >= 0; j-- { + if p.oe[j].DataAtom == a.Template { + template = p.oe[j] + break + } + } + + if template != nil && (table == nil || j > i) { + template.AppendChild(n) + return + } + if table == nil { // The foster parent is the html element. parent = p.oe[0] @@ -304,7 +319,7 @@ func (p *parser) addElement() { }) } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) addFormattingElement() { tagAtom, attr := p.tok.DataAtom, p.tok.Attr p.addElement() @@ -351,7 +366,7 @@ findIdenticalElements: p.afe = append(p.afe, p.top()) } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) clearActiveFormattingElements() { for { n := p.afe.pop() @@ -361,7 +376,7 @@ func (p *parser) clearActiveFormattingElements() { } } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) reconstructActiveFormattingElements() { n := p.afe.top() if n == nil { @@ -390,12 +405,12 @@ func (p *parser) reconstructActiveFormattingElements() { } } -// Section 12.2.4. +// Section 12.2.5. func (p *parser) acknowledgeSelfClosingTag() { p.hasSelfClosingToken = false } -// An insertion mode (section 12.2.3.1) is the state transition function from +// An insertion mode (section 12.2.4.1) is the state transition function from // a particular state in the HTML5 parser's state machine. It updates the // parser's fields depending on parser.tok (where ErrorToken means EOF). // It returns whether the token was consumed. @@ -403,7 +418,7 @@ type insertionMode func(*parser) bool // setOriginalIM sets the insertion mode to return to after completing a text or // inTableText insertion mode. -// Section 12.2.3.1, "using the rules for". +// Section 12.2.4.1, "using the rules for". func (p *parser) setOriginalIM() { if p.originalIM != nil { panic("html: bad parser state: originalIM was set twice") @@ -411,18 +426,35 @@ func (p *parser) setOriginalIM() { p.originalIM = p.im } -// Section 12.2.3.1, "reset the insertion mode". +// Section 12.2.4.1, "reset the insertion mode". func (p *parser) resetInsertionMode() { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] - if i == 0 && p.context != nil { + last := i == 0 + if last && p.context != nil { n = p.context } switch n.DataAtom { case a.Select: + if !last { + for ancestor, first := n, p.oe[0]; ancestor != first; { + ancestor = p.oe[p.oe.index(ancestor)-1] + switch ancestor.DataAtom { + case a.Template: + p.im = inSelectIM + return + case a.Table: + p.im = inSelectInTableIM + return + } + } + } p.im = inSelectIM case a.Td, a.Th: + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 p.im = inCellIM case a.Tr: p.im = inRowIM @@ -434,25 +466,41 @@ func (p *parser) resetInsertionMode() { p.im = inColumnGroupIM case a.Table: p.im = inTableIM + case a.Template: + // TODO: remove this divergence from the HTML5 spec. + if n.Namespace != "" { + continue + } + p.im = p.templateStack.top() case a.Head: - p.im = inBodyIM + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.im = inHeadIM case a.Body: p.im = inBodyIM case a.Frameset: p.im = inFramesetIM case a.Html: - p.im = beforeHeadIM + if p.head == nil { + p.im = beforeHeadIM + } else { + p.im = afterHeadIM + } default: + if last { + p.im = inBodyIM + return + } continue } return } - p.im = inBodyIM } const whitespace = " \t\r\n\f" -// Section 12.2.5.4.1. +// Section 12.2.6.4.1. func initialIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -479,7 +527,7 @@ func initialIM(p *parser) bool { return false } -// Section 12.2.5.4.2. +// Section 12.2.6.4.2. func beforeHTMLIM(p *parser) bool { switch p.tok.Type { case DoctypeToken: @@ -517,7 +565,7 @@ func beforeHTMLIM(p *parser) bool { return false } -// Section 12.2.5.4.3. +// Section 12.2.6.4.3. func beforeHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -560,7 +608,7 @@ func beforeHeadIM(p *parser) bool { return false } -// Section 12.2.5.4.4. +// Section 12.2.6.4.4. func inHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -590,19 +638,41 @@ func inHeadIM(p *parser) bool { case a.Head: // Ignore the token. return true + case a.Template: + p.addElement() + p.afe = append(p.afe, &scopeMarker) + p.framesetOK = false + p.im = inTemplateIM + p.templateStack = append(p.templateStack, inTemplateIM) + return true } case EndTagToken: switch p.tok.DataAtom { case a.Head: - n := p.oe.pop() - if n.DataAtom != a.Head { - panic("html: bad parser state: element not found, in the in-head insertion mode") - } + p.oe.pop() p.im = afterHeadIM return true case a.Body, a.Html, a.Br: p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false + case a.Template: + if !p.oe.contains(a.Template) { + return true + } + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.generateImpliedEndTags() + for i := len(p.oe) - 1; i >= 0; i-- { + if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template { + p.oe = p.oe[:i] + break + } + } + p.clearActiveFormattingElements() + p.templateStack.pop() + p.resetInsertionMode() + return true default: // Ignore the token. return true @@ -622,7 +692,7 @@ func inHeadIM(p *parser) bool { return false } -// Section 12.2.5.4.6. +// Section 12.2.6.4.6. func afterHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -648,7 +718,7 @@ func afterHeadIM(p *parser) bool { p.addElement() p.im = inFramesetIM return true - case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: + case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: p.oe = append(p.oe, p.head) defer p.oe.remove(p.head) return inHeadIM(p) @@ -660,6 +730,8 @@ func afterHeadIM(p *parser) bool { switch p.tok.DataAtom { case a.Body, a.Html, a.Br: // Drop down to creating an implied tag. + case a.Template: + return inHeadIM(p) default: // Ignore the token. return true @@ -697,7 +769,7 @@ func copyAttributes(dst *Node, src Token) { } } -// Section 12.2.5.4.7. +// Section 12.2.6.4.7. func inBodyIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -727,10 +799,16 @@ func inBodyIM(p *parser) bool { case StartTagToken: switch p.tok.DataAtom { case a.Html: + if p.oe.contains(a.Template) { + return true + } copyAttributes(p.oe[0], p.tok) - case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: + case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: return inHeadIM(p) case a.Body: + if p.oe.contains(a.Template) { + return true + } if len(p.oe) >= 2 { body := p.oe[1] if body.Type == ElementNode && body.DataAtom == a.Body { @@ -767,9 +845,13 @@ func inBodyIM(p *parser) bool { // The newline, if any, will be dealt with by the TextToken case. p.framesetOK = false case a.Form: - if p.form == nil { - p.popUntil(buttonScope, a.P) - p.addElement() + if p.form != nil && !p.oe.contains(a.Template) { + // Ignore the token + return true + } + p.popUntil(buttonScope, a.P) + p.addElement() + if !p.oe.contains(a.Template) { p.form = p.top() } case a.Li: @@ -819,7 +901,7 @@ func inBodyIM(p *parser) bool { case a.A: for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- { if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A { - p.inBodyEndTagFormatting(a.A) + p.inBodyEndTagFormatting(a.A, "a") p.oe.remove(n) p.afe.remove(n) break @@ -833,7 +915,7 @@ func inBodyIM(p *parser) bool { case a.Nobr: p.reconstructActiveFormattingElements() if p.elementInScope(defaultScope, a.Nobr) { - p.inBodyEndTagFormatting(a.Nobr) + p.inBodyEndTagFormatting(a.Nobr, "nobr") p.reconstructActiveFormattingElements() } p.addFormattingElement() @@ -903,6 +985,14 @@ func inBodyIM(p *parser) bool { p.acknowledgeSelfClosingTag() p.popUntil(buttonScope, a.P) p.parseImpliedToken(StartTagToken, a.Form, a.Form.String()) + if p.form == nil { + // NOTE: The 'isindex' element has been removed, + // and the 'template' element has not been designed to be + // collaborative with the index element. + // + // Ignore the token. + return true + } if action != "" { p.form.Attr = []Attribute{{Key: "action", Val: action}} } @@ -952,11 +1042,16 @@ func inBodyIM(p *parser) bool { } p.reconstructActiveFormattingElements() p.addElement() - case a.Rp, a.Rt: + case a.Rb, a.Rtc: if p.elementInScope(defaultScope, a.Ruby) { p.generateImpliedEndTags() } p.addElement() + case a.Rp, a.Rt: + if p.elementInScope(defaultScope, a.Ruby) { + p.generateImpliedEndTags("rtc") + } + p.addElement() case a.Math, a.Svg: p.reconstructActiveFormattingElements() if p.tok.DataAtom == a.Math { @@ -993,15 +1088,29 @@ func inBodyIM(p *parser) bool { case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul: p.popUntil(defaultScope, p.tok.DataAtom) case a.Form: - node := p.form - p.form = nil - i := p.indexOfElementInScope(defaultScope, a.Form) - if node == nil || i == -1 || p.oe[i] != node { - // Ignore the token. - return true + if p.oe.contains(a.Template) { + i := p.indexOfElementInScope(defaultScope, a.Form) + if i == -1 { + // Ignore the token. + return true + } + p.generateImpliedEndTags() + if p.oe[i].DataAtom != a.Form { + // Ignore the token. + return true + } + p.popUntil(defaultScope, a.Form) + } else { + node := p.form + p.form = nil + i := p.indexOfElementInScope(defaultScope, a.Form) + if node == nil || i == -1 || p.oe[i] != node { + // Ignore the token. + return true + } + p.generateImpliedEndTags() + p.oe.remove(node) } - p.generateImpliedEndTags() - p.oe.remove(node) case a.P: if !p.elementInScope(buttonScope, a.P) { p.parseImpliedToken(StartTagToken, a.P, a.P.String()) @@ -1014,7 +1123,7 @@ func inBodyIM(p *parser) bool { case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6: p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6) case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U: - p.inBodyEndTagFormatting(p.tok.DataAtom) + p.inBodyEndTagFormatting(p.tok.DataAtom, p.tok.Data) case a.Applet, a.Marquee, a.Object: if p.popUntil(defaultScope, p.tok.DataAtom) { p.clearActiveFormattingElements() @@ -1022,20 +1131,37 @@ func inBodyIM(p *parser) bool { case a.Br: p.tok.Type = StartTagToken return false + case a.Template: + return inHeadIM(p) default: - p.inBodyEndTagOther(p.tok.DataAtom) + p.inBodyEndTagOther(p.tok.DataAtom, p.tok.Data) } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) + case ErrorToken: + // TODO: remove this divergence from the HTML5 spec. + if len(p.templateStack) > 0 { + p.im = inTemplateIM + return false + } else { + for _, e := range p.oe { + switch e.DataAtom { + case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc, a.Tbody, a.Td, a.Tfoot, a.Th, + a.Thead, a.Tr, a.Body, a.Html: + default: + return true + } + } + } } return true } -func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { +func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom, tagName string) { // This is the "adoption agency" algorithm, described at // https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency @@ -1057,7 +1183,7 @@ func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { } } if formattingElement == nil { - p.inBodyEndTagOther(tagAtom) + p.inBodyEndTagOther(tagAtom, tagName) return } feIndex := p.oe.index(formattingElement) @@ -1160,11 +1286,19 @@ func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { } // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM. -// "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content +// "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign -func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { +func (p *parser) inBodyEndTagOther(tagAtom a.Atom, tagName string) { for i := len(p.oe) - 1; i >= 0; i-- { - if p.oe[i].DataAtom == tagAtom { + // Two element nodes have the same tag if they have the same Data (a + // string-typed field). As an optimization, for common HTML tags, each + // Data string is assigned a unique, non-zero DataAtom (a uint32-typed + // field), since integer comparison is faster than string comparison. + // Uncommon (custom) tags get a zero DataAtom. + // + // The if condition here is equivalent to (p.oe[i].Data == tagName). + if (p.oe[i].DataAtom == tagAtom) && + ((tagAtom != 0) || (p.oe[i].Data == tagName)) { p.oe = p.oe[:i] break } @@ -1174,7 +1308,7 @@ func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { } } -// Section 12.2.5.4.8. +// Section 12.2.6.4.8. func textIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1203,12 +1337,9 @@ func textIM(p *parser) bool { return p.tok.Type == EndTagToken } -// Section 12.2.5.4.9. +// Section 12.2.6.4.9. func inTableIM(p *parser) bool { switch p.tok.Type { - case ErrorToken: - // Stop parsing. - return true case TextToken: p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1) switch p.oe.top().DataAtom { @@ -1249,7 +1380,7 @@ func inTableIM(p *parser) bool { } // Ignore the token. return true - case a.Style, a.Script: + case a.Style, a.Script, a.Template: return inHeadIM(p) case a.Input: for _, t := range p.tok.Attr { @@ -1261,7 +1392,7 @@ func inTableIM(p *parser) bool { } // Otherwise drop down to the default action. case a.Form: - if p.form != nil { + if p.oe.contains(a.Template) || p.form != nil { // Ignore the token. return true } @@ -1291,6 +1422,8 @@ func inTableIM(p *parser) bool { case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. return true + case a.Template: + return inHeadIM(p) } case CommentToken: p.addChild(&Node{ @@ -1301,6 +1434,8 @@ func inTableIM(p *parser) bool { case DoctypeToken: // Ignore the token. return true + case ErrorToken: + return inBodyIM(p) } p.fosterParenting = true @@ -1309,7 +1444,7 @@ func inTableIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.11. +// Section 12.2.6.4.11. func inCaptionIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1355,7 +1490,7 @@ func inCaptionIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.12. +// Section 12.2.6.4.12. func inColumnGroupIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -1386,11 +1521,13 @@ func inColumnGroupIM(p *parser) bool { p.oe.pop() p.acknowledgeSelfClosingTag() return true + case a.Template: + return inHeadIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Colgroup: - if p.oe.top().DataAtom != a.Html { + if p.oe.top().DataAtom == a.Colgroup { p.oe.pop() p.im = inTableIM } @@ -1398,17 +1535,21 @@ func inColumnGroupIM(p *parser) bool { case a.Col: // Ignore the token. return true + case a.Template: + return inHeadIM(p) } + case ErrorToken: + return inBodyIM(p) } - if p.oe.top().DataAtom != a.Html { - p.oe.pop() - p.im = inTableIM - return false + if p.oe.top().DataAtom != a.Colgroup { + return true } - return true + p.oe.pop() + p.im = inTableIM + return false } -// Section 12.2.5.4.13. +// Section 12.2.6.4.13. func inTableBodyIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1460,7 +1601,7 @@ func inTableBodyIM(p *parser) bool { return inTableIM(p) } -// Section 12.2.5.4.14. +// Section 12.2.6.4.14. func inRowIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1511,7 +1652,7 @@ func inRowIM(p *parser) bool { return inTableIM(p) } -// Section 12.2.5.4.15. +// Section 12.2.6.4.15. func inCellIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1560,12 +1701,9 @@ func inCellIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.16. +// Section 12.2.6.4.16. func inSelectIM(p *parser) bool { switch p.tok.Type { - case ErrorToken: - // Stop parsing. - return true case TextToken: p.addText(strings.Replace(p.tok.Data, "\x00", "", -1)) case StartTagToken: @@ -1586,8 +1724,12 @@ func inSelectIM(p *parser) bool { } p.addElement() case a.Select: - p.tok.Type = EndTagToken - return false + if p.popUntil(selectScope, a.Select) { + p.resetInsertionMode() + } else { + // Ignore the token. + return true + } case a.Input, a.Keygen, a.Textarea: if p.elementInScope(selectScope, a.Select) { p.parseImpliedToken(EndTagToken, a.Select, a.Select.String()) @@ -1597,7 +1739,7 @@ func inSelectIM(p *parser) bool { p.tokenizer.NextIsNotRawText() // Ignore the token. return true - case a.Script: + case a.Script, a.Template: return inHeadIM(p) } case EndTagToken: @@ -1617,7 +1759,12 @@ func inSelectIM(p *parser) bool { case a.Select: if p.popUntil(selectScope, a.Select) { p.resetInsertionMode() + } else { + // Ignore the token. + return true } + case a.Template: + return inHeadIM(p) } case CommentToken: p.addChild(&Node{ @@ -1627,30 +1774,107 @@ func inSelectIM(p *parser) bool { case DoctypeToken: // Ignore the token. return true + case ErrorToken: + return inBodyIM(p) } return true } -// Section 12.2.5.4.17. +// Section 12.2.6.4.17. func inSelectInTableIM(p *parser) bool { switch p.tok.Type { case StartTagToken, EndTagToken: switch p.tok.DataAtom { case a.Caption, a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr, a.Td, a.Th: - if p.tok.Type == StartTagToken || p.elementInScope(tableScope, p.tok.DataAtom) { - p.parseImpliedToken(EndTagToken, a.Select, a.Select.String()) - return false - } else { + if p.tok.Type == EndTagToken && !p.elementInScope(tableScope, p.tok.DataAtom) { // Ignore the token. return true } + // This is like p.popUntil(selectScope, a.Select), but it also + // matches , not just